1

I'm trying to stack multiple plots that are combined in a list and are coming from purrr::map.

The conditions are:

  • no use of facet_wrap or facet_grid - I understand this can be done with these function but I have another limiting factor which does not allow for their use
  • the number of plots in the list might vary - so it is not a constant

A reproducible example to recreate the problem:

library(dplyr)
library(tidyr)
library(purrr)

# a sample dataframe
df <- data.frame(gr = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3),
                 a = rnorm(10, 5, 3), 
                 b = rnorm(10, 5, 3)) %>% 
      group_by(gr) %>%
      nest()

# a plotting function
plotting <- function(x) {
  ggplot(x) + geom_point(aes(a,b))
}

# getting the list of the plots
lst <- map(df$data,plotting)

I can solve the problem manually by using the patchwork package:

library(patchwork)
lst[[1]] + lst[[2]] + lst[[3]] + patchwork::plot_layout(nrow = 1)

or the gridExtra package:

library(gridExtra)
grid.arrange(lst[[1]], lst[[2]], lst[[3]],nrow = 1)

but if the number of plots varies this would not work. Grateful for any ideas on how to automate this.

adl
  • 1,390
  • 16
  • 36
  • 2
    `cowplot::plot_grid(plotlist = lst, nrow = 1)` or `do.call(gridExtra::grid.arrange, c(lst, nrow = 1))`, or `patchwork::wrap_plots(lst, nrow = 1)`. – Axeman Jun 28 '18 at 12:10
  • I didn't realize there were so many options. Thank you – adl Jun 28 '18 at 12:20

1 Answers1

2

The plot_grid function in cowplot accepts a list of plots as input.

cowplot::plot_grid(plotlist=lst, nrow=1)

enter image description here

Simon Larsen
  • 712
  • 3
  • 9