Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show multiple plots from ggplot on one page in r

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.

like image 340
zesla Avatar asked Sep 21 '18 04:09

zesla


People also ask

How do I display multiple plots in R?

We can put multiple graphs in a single plot by setting some graphical parameters with the help of par() function. R programming has a lot of graphical parameters which control the way our graphs are displayed. The par() function helps us in setting or inquiring about these parameters.

How do I show multiple Ggplots together?

The function ggarrange() [ggpubr] provides a convenient solution to arrange multiple ggplots over multiple pages. After specifying the arguments nrow and ncol, ggarrange()` computes automatically the number of pages required to hold the list of the plots. It returns a list of arranged ggplots.

Does par () work with ggplot?

The base R functions such as par() and layout() will not work with ggplot2 because it uses a different graphics system and this system does not recognize base R functionality for plotting. However, there are multiple ways you can combine plots from ggplot2 . One way is using the cowplot package.


1 Answers

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:

  • Creating arbitrary panes in ggplot2 (patchwork, multipanelfigure & egg packages)

  • Multiple plots in for loop

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)

like image 123
Tung Avatar answered Sep 21 '22 12:09

Tung