4

I have a list of objects created with patchwork. I'd like to save each element of this list as a separate page within a single PDF.

If doing this for ordinary ggplot2 objects I would combine the plots using gridExtra::marrangeGrob(), as per the solution given here. I like this approach because it's tidy, and because the output includes page numbers.

However I cannot get this approach to work with patchwork. Instead of printing the entire plot 'composite' on each page, it only shows one of the plot elements. MWE given below.

library(ggplot2)
library(patchwork)
library(gridExtra)

# dummy plots
p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_point()
p2 <- ggplot(mtcars, aes(mpg, disp)) + geom_line()

# create plot 'composites' using `patchwork` and combine into list
# elements duplicated for simplicity
plot_list <- list(
  wrap_plots(p1, p2),
  wrap_plots(p1, p2)
)

# attempt to export with separate page for each list element
# expect to produce a PDF with two pages, both of which show p1 adjacent to p2
plot_list %>%
  marrangeGrob(nrow = 1, ncol = 1) %>% # no combination of nrow and ncol seems to work
  ggsave(filename = "plots.pdf")

What am I doing wrong here? Is combining patchwork with gridExtra a silly idea? If so, what's the better alternative?

pyg
  • 716
  • 6
  • 18
  • 1
    It seems to work with `cowplot::plot_grid` instead of `wrap_plots`, but I'm not sure if this is flexible enough for you. – slamballais May 13 '21 at 15:30
  • Does something like this work? `pdf("myplots.pdf") for (i in 1:2){ plot(plots_for_page[i]) } dev.off()` – Josh May 13 '21 at 18:38

0 Answers0