Search code examples
rggplot2gridextraggpubrpatchwork

Arrange multiple plots per page, but # of plots is not multiple of # of pages


I have used wrap_plots(), ggarrange(), or grid.arrange() in the past. However, I have not found how to arrange several plots per page, using a for loop, when the number of plots is not a multiple number of the number of pages wanted.

Let us say I have six plot and I want four plots per page, for (quite a silly) instance. If I do the following, I get an error, obviously enough:

for (i in seq(1,6,4)) 
grid.arrange(plots[[i]] , plots[[i+1]] , plots[[i+2]] , plots[[i+3]], col = 2, row = 2)

I know I could create a loop up to the maximal multiple value of four in the list, and the create a second loop with the remaining plots, but I wonder if there is an easier and/or more elegant way to handle this.

Finally, using wrap_plots()or ggarrange() seems more complicated when I want to create multiple pages one after the other, even if they are complete 2*2: I do not get a viable pdf. I think I am missing something regarding those two.

Thanks you for your help.

Best,

David


Solution

  • One option would be to create an index vector which assigns plots to pages. Afterwards you can loop over the pages like so:

    library(ggplot2)
    library(ggpubr)
    library(patchwork)
    
    plots <- lapply(1:6, function(x) {
      ggplot(mtcars, aes(hp, mpg)) +
        geom_point() +
        labs(title = x)
    })
    
    pages <- (seq_along(plots) - 1) %/% 4
    
    lapply(unique(pages), function(page) {
      wrap_plots(plots[pages %in% page])
    })
    #> [[1]]
    

    #> 
    #> [[2]]
    

    Or using ggarrange:

    lapply(unique(pages), function(page) {
      ggarrange(plotlist = plots[pages %in% page])
    })