Print ggplot2 Plot within for-Loop in R (Example)

 

In this article you’ll learn how to draw ggplot2 plots within a for-loop in the R programming language.

The post looks as follows:

You’re here for the answer, so let’s get straight to the programming part…

 

Introducing Example Data

We will use the following data as basement for the example of this R programming tutorial:

set.seed(159159)                                      # Create example data
data <- data.frame(x = 1:100,
                   y1 = rnorm(100),
                   y2 = rnorm(100),
                   y3 = rnorm(100))

Our example data contains 100 rows and four columns. The variable x is ranging from 1 to 100 and the columns y1, y2, and y2 contain 100 random normally distributed numbers each.

We also need to install and load the ggplot2 add-on package to RStudio:

install.packages("ggplot2")                           # Install and load ggplot2
library("ggplot2")

Now, we can draw a basic ggplot2 graph as follows:

ggplot(data, aes(x = x, y = y1)) +                    # Basic ggplot2 plot of x & y1
  geom_point()

 

scatterplot created by ggplot2 package in r

Figure 1: Basic Scatterplot Created by ggplot2 Package.

 

In Figure 1, you can see the result of the previous R code: A scatterplot of x and y1.

Now, let’s assume we want to create a ggplot2 plot of each combination of x and y1, y2, and y3 respectively. In such a scenario, we may want to use a for-loop:

for(i in 2:ncol(data)) {                              # ggplot within for-loop
  ggplot(data, aes(x = x, y = data[ , i])) +
    geom_point()
  Sys.sleep(2)
}

Damn! No graphic was returned!

So why does ggplot2 not work if it is inside a for-loop although it works outside of it?!

That’s what I’m going to show you next…

 

Example: Plotting ggplot2 Plots within Loop

If we want to draw a plot within a for-loop, we need to wrap the print function around the R code creating the plot. Have a look at the following R syntax:

for(i in 2:ncol(data)) {                              # Printing ggplot within for-loop
  print(ggplot(data, aes(x = x, y = data[ , i])) +
          geom_point())
  Sys.sleep(2)
}

 

gif multiple scatterplots created by ggplot2 package in r

Figure 2: Showing ggplot2 Plots within for-Loop using print() Function.

 

After running the previous R code, you will see three ggplot2 graphs popping up at the bottom right of RStudio with a delay of 2 seconds.

Looks good!

 

Video, Further Resources & Summary

Would you like to know more about the ggplot2 package in R? Then you could watch the following video of my YouTube channel. In the video, I explain the R codes of this article in RStudio:

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Furthermore, you might have a look at the related articles of this website. A selection of articles can be found here.

 

This tutorial illustrated how to use the ggplot2 package within while- or for-loops in R. Don’t hesitate to let me know in the comments, in case you have additional questions. In addition, please subscribe to my email newsletter in order to receive updates on the newest articles.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


14 Comments. Leave new

  • Hi , Thanks for the tutorial on ggplot loop! Is there a way to dynamically assign the variable names as Y-Axis labels?

    Reply
  • Hi,
    I am getting following error.

    Error in data[, i] : object of type ‘closure’ is not subsettable.

    Any solution please? Thanks

    Reply
  • Hi and thanks for the tutorial! Is there a way to show all graphs at the same time? In R, without using a pdf (it’s only 9 graphs for me)

    Reply
  • Christer P. Volk
    August 12, 2021 8:37 am

    Hi Joachim

    This is great. Been having this issue a few times. But why does it work? What does print() do that is needed here?

    Reply
    • Hi Christer,

      Thank you for the nice comment, glad it helped!

      You can read more about the reasons in this article, specifically: “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.”

      Regards

      Joachim

      Reply
  • THis website was very helpful for me. I have always tried several times to learn creating loops in R and the books have not been good. But, your website made me like to go through all your examples and even try some other new options just to see how the outputs changes.

    Thank you very much!!!!!!!!!!!!!!!!!!!!!!!!!

    Reply
  • I spent days on this problem, but with your help it will be a big time-saver in the future! I especially like how you showed the initial lack of result (“Damn! No graphic…”), just as I experienced it (many times). I can’t thank you enough.

    Reply
  • HI !
    i fellowed your code ,and it work fine, when i try to save each plot of them,i meet so error.
    ———————————————————————————————————————————
    for (i in 2:ncol(data)) {
    p=( ggplot(data=data) + geom_bar(aes(x=tissue,y=data[,i]),stat=”identity”)+theme_classic())
    plot_list[[i]] = p}
    ———————————————————————————————————————————
    Rstudio did not repot error,but the plot was not the plot when i use code as you descripted
    ————————————————————————————————————————
    for (i in 2:ncol(data)) {

    print( ggplot(data=data) + geom_bar(aes(x=tissue,y=data[,i]),stat=”identity”)+theme_classic())
    Sys.sleep(2)}
    ——————————–
    thanks u

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top