157

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
  • 46,390
  • 10
  • 104
  • 180
Remi.b
  • 16,247
  • 25
  • 74
  • 153

1 Answers1

270

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
  • 45,570
  • 12
  • 106
  • 116
  • 6
    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
  • 2
    @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