Enriching a ggplot2 plot with multiple geom_segment in a loop?

ggplot2, r

Solution

It has to do with the lazy evaluation of the `aes()` values. You are binding to the variable `i` but not actually doing anything with it in the loop. The mappings aren't resolved till you actually `print(p)`. Essentially this means they are all being bound to `i` and after the loop exits, `i` will have the value it had during the final loop.

So the problem really is you shounld't be using `aes()` here as you don't really want active binding. Just set the `x` and `xend` values outside the `aes()`. (And since the `y`'s are constant they should be outside the `aes()` as well).

values <- c(1, 5)
for (i in values) {
   p <- p + geom_segment(x=i, y=103, xend=i, yend=107)
}

Problem

I successfully create a plot using the following: ``` # suppose I have a p <- ggplot(data=df, ...) then the following works # I get those two segments plotted correctly p <- p + geom_segment(aes(x=1,y=103,xend=1,yend=107)) p <- p + geom_segment(aes(x=5,y=103,xend=5,yend=107)) ``` However if I do: ``` values <- c(1, 5) for (i in values) { p <- p + geom_segment(aes(x=i,y=103,xend=i,yend=107)) } ``` It doesn't work, only the last segment is created. Can anyone advice what's wrong here?

Original source