show multiple plots from ggplot on one page in r

后端 未结 2 1189
灰色年华
灰色年华 2020-12-07 02:18

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()
         


        
2条回答
  •  余生分开走
    2020-12-07 03:21

    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)

提交回复
热议问题