3

In every cycle of a loop I create a ggplot object and I want to add text to the plot according to the cycle.

Here is my code:

gp <- list()

for(k in 1:3) {
 gp[[k]] <- ggplot() + 
  geom_text(aes(x = 2, y = 1, label=k), colour = "#1874CD")
 }
gp[[1]]
gp[[2]]
gp[[3]]

What I get is the number 3 in all plots. Why is that? And how can I manage to plot "1" in the first plot, "2" in the second and so forth?

smoff
  • 592
  • 5
  • 21
  • 3
    It's because the `k` isn't evaluated until you actually print the plot. So when you run `gp[[1]]` the current value of `k` is 3, because that's the value of `k` at the end of the loop. Use `aes_` instead of `aes` to force immediate evaluation of `k`, as described in [this SO answer](https://stackoverflow.com/a/39021087/496488). – eipi10 Nov 08 '17 at 06:42
  • Thank you very much! Did the trick! – smoff Nov 08 '17 at 06:53
  • [This answer](https://stackoverflow.com/a/26246791/2461552) has a nice explanation for how `aes` works. – aosmith Nov 08 '17 at 16:02

1 Answers1

3

Try aes_string instead of aes in geom_text:

gp <- list()

for(k in 1:3) {
  gp[[k]] <- ggplot() + 
    geom_text(aes_string(x = 2, y = 1, label = k), colour = "#1874CD")
}
gp[[1]]
gp[[2]]
gp[[3]]
Adela
  • 1,757
  • 19
  • 37