ggplot does not work if it is inside a for loop although it works outside of it

Remi.b picture Remi.b · Mar 28, 2013 · Viewed 79.8k times · Source

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 ?

Answer

juba picture juba · Mar 28, 2013

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()) 
}