Update a ggplot using a for loop (R) [duplicate]

2020-02-13 01:31发布

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?

2条回答
唯我独甜
2楼-- · 2020-02-13 02:13

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))
}
查看更多
等我变得足够好
3楼-- · 2020-02-13 02:31

It has to do with how ggplot does lazy evaluation -- see here.

Since geom_vline is vectorized, this works:

library(ggplot2)

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

x + geom_vline(aes(xintercept = seq(5,30,5)))
查看更多
登录 后发表回答