Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add text to ggplot in loop

Tags:

r

ggplot2

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?

like image 743
smoff Avatar asked Nov 17 '25 22:11

smoff


1 Answers

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]]
like image 117
Adela Avatar answered Nov 19 '25 11:11

Adela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!