Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (7.3k points)
edited by

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?

Thank you

1 Answer

0 votes
by
edited by

For ggplot to work inside a for loop you have to explicitly call the print() function. i.e.,

for (i in 1:5) { 

  print(ggplot(df,aes(x,y))+geom_point()) 

}

This happens because the print() method is called automatically by R, every time a variable is queried and, for a ggplot object, it draws the content of your object on your device. An interesting side-effect of this is that ggplots are only rendered when explicitly print()ed/plot()ed within a loop, as only the last return value in a sequence of calls gets its print method invoked.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...