163

I'm using a simple ggplot function which works fine outside a loop but not inside even if the iterative value does not interfere with the ggplot function. Why is it so ?

Here is my code

x=1:7
y=1:7
df = data.frame(x=x,y=y)
ggplot(df,aes(x,y))+geom_point()

It works ! But if the ggplot is inside a for loop ...

for (i in 1:5) {
   ggplot(df,aes(x,y))+geom_point()
}

it doesn't work anymore, what am I missing ?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Remi.b
  • 17,389
  • 28
  • 87
  • 168

1 Answers1

298

When in a for loop, you have to explicitly print your resulting ggplot object :

for (i in 1:5) { 
    print(ggplot(df,aes(x,y))+geom_point()) 
}
juba
  • 47,631
  • 14
  • 113
  • 118
  • 7
    Could you elaborate on why this is the case? – Syd Kerckhove Nov 14 '16 at 19:57
  • 3
    @SydKerckhove In case you are still interested, here is an excellent article about ggplot: http://www.data-imaginist.com/2017/Beneath-the-canvas/ – roarkz Aug 08 '17 at 18:36
  • 2
    How do you use this with ggsave? – John Oct 13 '17 at 20:29
  • 3
    @John `myPlot = ggplot()..... ` then `ggsave("filename", plot = myPlot)` – Glubbdrubb Jul 04 '19 at 12:05
  • 6
    This is probably off topic, but I'm not sure there is any value in posting about my confusion independently: The suggested `print(ggplot(df,aes(x,y))+geom_point())` works, but `ggplot(df,aes(x,y))+geom_point() %>% print()` does not. However, `(ggplot(df,aes(x,y))+geom_point()) %>% print()` does work. This is probably related to the "not a pipe" nature of the ggplot `+` described here https://stackoverflow.com/questions/38166708/plus-sign-between-ggplot2-and-other-function-r – Josh May 02 '21 at 21:39
  • Disclaimer, I am a total noob. Can you explain i in 1:5 please? – yaynikkiprograms Nov 05 '21 at 17:08
  • @yaynikkiprograms, perhaps too late, but ... type in [`?:`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Colon.html), and see that it is a shortcut for sequences. – r2evans Feb 10 '22 at 00:00
  • I have also found the need to use `print()` when exporting from within a `for` loop...e.g. `jpeg(...) print( ggplot(...) ) dev.off()` – Roasty247 Sep 06 '22 at 06:33
  • I found had to use print(ggdraw(...)) as well to get to work inside a loop – Markm0705 Jul 01 '23 at 09:52