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.
It has to do with how ggplot does lazy evaluation -- see here.
Since
geom_vline
is vectorized, this works: