6

I want to make multiple ggplot in a loop and show them on one plot.

for ( i in 1:8) {
    g <- ggplot(data=mtcars, aes(x=hp, y=wt))+
        geom_point()
    print(g)
}

I want to arrange the plots above on one page, 4 rows and 2 columns. Does anyone know how to do that? Thanks.

Tung
  • 26,371
  • 7
  • 91
  • 115
zesla
  • 11,155
  • 16
  • 82
  • 147
  • 2
    Are you looking for `facet_grid` and/or `facet_wrap` functionality? Check this out https://ggplot2.tidyverse.org/reference/facet_grid.html – PKumar Sep 21 '18 at 04:15
  • 1
    Look at [cowplot](https://cran.r-project.org/web/packages/cowplot/vignettes/introduction.html) or [gridExtra](https://cran.r-project.org/web/packages/egg/vignettes/Ecosystem.html) or [patchwork](https://github.com/thomasp85/patchwork). If you're using a loop, you'll probably want to create a list with your plots. – neilfws Sep 21 '18 at 04:19

2 Answers2

9

You can save all the plot in a list then use either cowplot::plot_grid() or gridExtra::marrangeGrob() to put them in one or more pages

See also:

library(tidyverse)

# create a list with a specific length 
plot_lst <- vector("list", length = 8)

for (i in 1:8) {
  g <- ggplot(data = mtcars, aes(x = hp, y = wt)) +
    geom_point()
  plot_lst[[i]] <- g
}

# Combine all plots
cowplot::plot_grid(plotlist = plot_lst, nrow = 4)

library(gridExtra)
ml1 <- marrangeGrob(plot_lst, nrow = 2, ncol = 2)
ml1

Created on 2018-09-20 by the reprex package (v0.2.1.9000)

Tung
  • 26,371
  • 7
  • 91
  • 115
0

Note that, in the loop you provided, the counter i isn't referenced in the plot, so you'll end up printing the same plot eight times!

If you have a bunch of different subsets of a single dataset and want to lay them out, you can follow @PKumar's comment and check out facetting in ggplot2. It essentially splits your data up into groups according to one or more of your columns and then lays them out in a grid or a ribbon.

On the other hand, if you have a bunch of a different plots that you want to combine on one page, there're a couple of packages that can make this happen:

  • cowplot is a fairly mature package that can do this, and
  • patchwork is a newer package that lets you lay plots out using arithmetic.

Hope those help!

jimjamslam
  • 1,988
  • 1
  • 18
  • 32