Back

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

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

In order 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
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...