使用for循环(R)更新ggplot [英] Update a ggplot using a for loop (R)
问题描述
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屋!