使用for循环(R)更新ggplot [英] Update a ggplot using a for loop (R)

查看:157
本文介绍了使用for循环(R)更新ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在更新ggplot对象时遇到了一些问题。我想要做的是在每个循环的特定位置放置一条垂直线,因此:多条线将显示在不同的位置。但是,当我使用for循环时,它只显示它创建的最后一行,但是当我手动执行时,它可以工作。我创建了一个可复制的例子,您可以检查:

  library(ggplot2)

x< - ggplot(mapping = aes(x = 1:100,y = 1:100))+
geom_line()

(i in 1:6){
x< (x = 1:100,y = 1:100)+ x +
geom_line()

y< - y + geom_vline(aes(xintercept = 5))
y< - y + geom_vline(aes(xintercept = 10))$ b $通过< -y + geom_vline(aes(xintercept = 15))
y< -y + geom_vline(aes(xintercept = 20))
y< -y + geom_vline(aes(xintercept = 25) )
y< - y + geom_vline(aes(xintercept = 30))

地块。为什么第一个情节与第二个情节看起来不一样,尽管对于我来说这两个过程都做了相同的事情?

解决方案

我正在看一些有些人离开我的贡献,有一个人非常有效地解决它,它是使用aes_()而不是aes()。不同之处在于aes_()强制评估和更新绘图,而aes()仅绘制绘图时评估索引。因此:当它在for循环中时,它永远不会更新。

  library(ggplot2)

x< ; - ggplot(mapping = aes(x = 1:100,y = 1:100))+
geom_line()

(i in 1:6){
x < - x + geom_vline(aes_(xintercept = i * 5))
}


I am having some problems updating a ggplot object. What I want to do is to put a vertical line in a specific location that I change on every loop, hence: multiple lines will be displayed in different locations. However, when I use a for loop it only shows me the last line that it's created but when I do it manually it works. I created a reproductible example that you guys can check:

library(ggplot2)

x <- ggplot(mapping = aes(x = 1:100, y = 1:100)) +
  geom_line()

for(i in 1:6){
  x <- x + geom_vline(aes(xintercept = i*5))
}

y <- ggplot(mapping = aes(x = 1:100, y = 1:100)) +
  geom_line()

y <- y + geom_vline(aes(xintercept = 5))
y <- y + geom_vline(aes(xintercept = 10))
y <- y + geom_vline(aes(xintercept = 15))
y <- y + geom_vline(aes(xintercept = 20))
y <- y + geom_vline(aes(xintercept = 25))
y <- y + geom_vline(aes(xintercept = 30))

Check both plots. Why is the first plot not looking the same as the second one, although for me both processes do the "same" thing?

解决方案

I was looking at some contributions that some people left me and there is one who solves it pretty efficiently and it is to use aes_() instead of aes(). The difference is that aes_() forces to evaluate and update the plot, while aes() only evaluates the indexes when the plot is drawn. Hence: it never updates while it is inside a for loop.

library(ggplot2)

x <- ggplot(mapping = aes(x = 1:100, y = 1:100)) +
  geom_line()

for(i in 1:6){
  x <- x + geom_vline(aes_(xintercept = i*5))
}

这篇关于使用for循环(R)更新ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆