# 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()``` 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) }``` 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. 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.

Subscribe to the Statistics Globe Newsletter

• Anoop
January 8, 2021 10:57 am

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

• Hi Anoop,

Thank you for the comment.

Please have a look at the following tutorials:

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

Regards,

Joachim

• Moh
June 9, 2021 5:54 am

Hi,
I am getting following error.

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

• Ale
June 17, 2021 8:16 am

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)

• 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?

• 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

• Richard Ngaya
September 17, 2021 6:10 am

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!!!!!!!!!!!!!!!!!!!!!!!!!

• 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

• Littleag
September 19, 2021 5:56 pm

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.

• Thanks a lot for the kind comment Littleag! Glad it helped! 🙂

Regards

Joachim

• JOE
September 30, 2021 8:54 am

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