3

I'm trying to workout a function (without any success) that will automatically assemble a list of ggplots plots with patchwork.

The function would take in the following inputs:

  • no_of_rows
  • no_of_cols
  • master_list_with_plots

With thee inputs the function should automatically structure the plots. I have provided an example below:

library(tidyverse)
library(patchwork)
  
p1 <- mtcars %>% ggplot() + geom_bar(aes(mpg))
p2 <- mtcars %>% ggplot() + geom_bar(aes(cyl))
p3 <- mtcars %>% ggplot() + geom_bar(aes(disp))
p4 <- mtcars %>% ggplot() + geom_bar(aes(hp))
p5 <- mtcars %>% ggplot() + geom_bar(aes(drat))                                   
p6 <- mtcars %>% ggplot() + geom_bar(aes(wt))

plot_list <- list(mpg  = p1,
                  cyl  = p2,
                  disp = p3,
                  hp   = p4,
                  drat = p5,
                  wt   = p6)

# Function inputs
no_of_rows = 2
no_of_col2 = 3
master_list_with_plots = org_plot
    
#Function output would be org_plot below
org_plot <- plot_list[["mpg"]] + plot_list[["cyl"]] + plot_list[["disp"]] + 
            plot_list[["hp"]]  + plot_list[["drat"]] + plot_list[["wt"]] 

Any ideas?

cephalopod
  • 1,826
  • 22
  • 31

2 Answers2

10

You can put patchwork::wrap_plots in a function :

plot_a_list <- function(master_list_with_plots, no_of_rows, no_of_cols) {

  patchwork::wrap_plots(master_list_with_plots, 
                        nrow = no_of_rows, ncol = no_of_cols)
}

plot_a_list(plot_list, 2, 3)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
5

If it is a simple grid of plots you are looking for, try have a look at the package gridExtra (functions like gridExtra::grid.arrange), or a more easy wrapper of this function for ggplots called ggpubr::ggarange. Given your plot_list object, you can try:

ggpubr::ggarrange(plotlist = plot_list, nrow = 2, ncol = 3, byrow = TRUE)

byrow = TRUE is the default. Setting this to FALSE will arrange your plot list by columns.

Ubiminor
  • 114
  • 1