Plot multiple ggplot2 on same page

后端 未结 2 767
故里飘歌
故里飘歌 2021-01-03 09:36

I have a working loop which generates and can save individual plots from each file saved in a directory.

I want to plot all of the returned plots in a single file as

2条回答
  •  执笔经年
    2021-01-03 09:57

    Assuming you need a PDF output where every page has multiple plots plotted as one, e.g.: if there are 12 plots then 4 plots per page.

    Try this example:

    library(ggplot2)
    library(cowplot)
    
    # list of 12 dummy plots, only title is changing.
    pltList <- lapply(1:12, function(i){
      ggplot(mtcars,aes(mpg,cyl)) +
        geom_point() +
        ggtitle(paste("Title",i))})
    
    # outputs 3 jpeg files with 4 plots each.
    for(i in seq(1,12,4))
    ggsave(paste0("Temp",i,".jpeg"),
           plot_grid(pltList[[i]],
                     pltList[[i+1]],
                     pltList[[i+2]],
                     pltList[[i+3]],nrow = 2))
    
    # or we can output into 1 PDF with 3 pages using print
    pdf("TempPDF.pdf")
    for(i in seq(1,12,4))
      print(plot_grid(pltList[[i]],
                pltList[[i+1]],
                pltList[[i+2]],
                pltList[[i+3]],nrow = 2))
    dev.off()
    

    EDIT:

    Another way using gridExtra, as suggested by @user20650:

    library(gridExtra)
    
    #output as PDF
    pdf("multipage.pdf")
    
    #use gridExtra to put plots together
    marrangeGrob(pltList, nrow=2, ncol=2)
    
    dev.off()
    

提交回复
热议问题