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.


26 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 Anoop,

      Thank you for the comment.

      Please have a look at the following tutorials:

      https://statisticsglobe.com/name-variables-in-for-loop-dynamically-in-r
      https://statisticsglobe.com/assign-function-in-r

      They explain how to assign names dynamically. You can also use this logic to assign Y-axis labels dynamically.

      Regards,

      Joachim

      Reply
      • Hi Joachim
        This was an excellent description of how to create the for loop for ggplotting.

        I have a follow up question related to Anoop’s question that I hope you can help with, because I don’t seem to be able to work it out from the links you have shared.

        I would like to assign my column names to be the x labels (my y variable is always the same), but when I try with the code that I put together from the links you shared I only ever get the column number and not the column name. I have tried passing a character list of column names, however it only ever uses the first name in the list.

        Can you help clear this up a little for me please, as I am not sure where I am going wrong.

        Reply
        • Hey,

          Thanks a lot for the kind comment, it’s great to hear that you find this tutorial helpful!

          Regarding your question, could you share your code and illustrate how your data set looks like?

          Regards,
          Joachim

          Reply
          • Thank you.
            I have a dataframe of 36 observations of 17 variables, but in this iteration of what I am doing I only need to plot column 2 (Total_Erosion) against columns 8-17.

            Am using the code below at the moment:
            for (i in 8:ncol(Bank1Variables)) {
            print(ggplot(data = Bank1Variables, aes_string(x = Bank1Variables[ , i], y = Total_Erosion*-1)) +
            geom_point() +
            labs(x = assign(paste0(” “, i), value = i), y = names(Bank1Variables[2])) +
            geom_smooth(method = “lm”, se = FALSE))
            }

            Which produces my plots beautifully, and names my Y axis correctly but my X axes are only ever named based on their row number and not their name.

            I have also created a character vector of the column names that I am using

            w <- c("Mean_Stage", "Max_Stage", "Peaks_AboveQ10", "Peaks_AboveQ50", "Hours_AboveQ10", "Hours_AboveQ50")

            But when I include the vector in the code as follows:
            for (i in 8:ncol(Bank1Variables)) {
            print(ggplot(data = Bank1Variables, aes_string(x = Bank1Variables[ , i], y = Total_Erosion*-1)) +
            geom_point() +
            labs(x = assign(paste0(" ", w), value = w), y = names(Bank1Variables[2])) +
            geom_smooth(method = "lm", se = FALSE))
            }

            It only ever uses the first name of Mean_Stage and labels all plots the same and then if i replace the w with w[i] it labels them all as NA

            It's likely to be something extremely simply and silly, but I have been working on it for a while now and can't get it to work.

            Thank you for your time. I really appreciate it!

          • Thanks for the clarifications! You may simply add the xlab and ylab functions to your ggplot2 code.

            Have a look at the following example. It shows how to modify the yaxis label dynamically:

            for(i in 2:ncol(data)) {
              print(ggplot(data, aes(x = x, y = data[ , i])) +
                      geom_point()) +
                ylab(colnames(data)[i]) # Change ylab
              Sys.sleep(2)
            }

            Let me know in case you need further help! ๐Ÿ™‚

            Regards,
            Joachim

  • 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
    • Thanks a lot for this wonderful feedback Richard! I’m very glad to hear that my tutorials helped to improve your R programming skills ๐Ÿ™‚

      Regards

      Joachim

      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
    • Hey Joe,

      You mean you want to export these plots as PDF or PNG? I’m not certain if I get your question correctly.

      Regards

      Joachim

      Reply
      • I think thatโ€™s what the poster was asking, and itโ€™s what I really want to know as well.

        Reply
        • Hey Mike,

          You can export all plots as PDFs as shown below:

          for(i in 2:ncol(data)) {                              # Printing ggplot within for-loop
            pdf(paste0("plot_no_", i - 1, ".pdf"))
            print(ggplot(data, aes(x = x, y = data[ , i])) +
                    geom_point())
            dev.off()
          }

          I hope that helps!

          Joachim

          Reply
  • Hi Joachim, very useful script. How ever I have a question could you please answer this.

    for(i in 2:ncol(data))

    Can you please explain why you have put 2. Thanks

    Reply
    • Hey Sameer,

      Thank you, glad it is useful!

      The 2:ncol is used because the first column in our data frame is the x-variable, and we do only want to loop over the y-variables (i.e. positions 2:ncol(data)).

      Regards,
      Joachim

      Reply
  • Hi Joachim,

    I am using for-loops to produce multiple graphs in RMarkdown. I assign them to a list so that they are able to print or to be exported to html or word document. My problem is that i would like to use for-loops then export results of each single code chunk to a separate document i.e. 5 RMarkdown code chunks = 5 separate word documents. I can do this with officer package when the plots are not produced by for-loops or assigned to a list but if i do this for plots on a list produced by for-loop, i only get 1 plot only.

    Is there a way to do this in a simple way?

    Reply
    • Hey Joshua,

      Unfortunately, I’m not an expert on RMarkdown. However, could you share your code? I could have a look and try to fx it.

      Regards,
      Joachim

      Reply
  • Hi Joachim
    For some reason I couldn’t reply to your last message on our thread but I just wanted to say that your solution worked perfectly.

    I am so grateful for your help! Thank you for your time and effort.
    It is much appreciated!
    BB

    Reply

Leave a Reply

Your email address will not be published.

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

Menu
Top