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

RFor LoopGgplot2

R Problem Overview


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 ?

R Solutions


Solution 1 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRemi.bView Question on Stackoverflow
Solution 1 - RjubaView Answer on Stackoverflow