1

I'm trying to save plots with one overall legend per page over multiple pages in a pdf using cowplot and marrangeGrob but I'm struggling to save the final step to a pdf. I can save plots on one page following this question.

Example:

library(ggplot2)
library(cowplot)
library(gridExtra)
plot_f <- function(df, xx) {
  df %>% 
    filter(carb == xx) %>% 
    ggplot() + 
    geom_line(aes(x = disp, y = hp, colour = "darkblue" )) +
    geom_line(aes(x = disp, y = qsec, colour = "red")) +
    scale_color_discrete(name = "Y series", labels = c("Y2", "Y1"))

}
dd <- unique(mtcars$carb)
list_plots <- map(dd, function(x) {
  plot_f(mtcars, x)
})


# -------------------------------------------------------------------------


#REMOVE LEGEND
p_no_legend <- lapply(list_plots, function(x) x + theme(legend.position = "none"))
p_no_legend[[1]]


legend <- cowplot::get_legend(list_plots[[1]] + theme(legend.position = "bottom"))
title <- cowplot::ggdraw() + cowplot::draw_label("test", fontface = "bold")

p_grid <- cowplot::plot_grid(plotlist = p_no_legend, nrow = 1, ncol = 2)
p_grid
test <- cowplot::plot_grid(title, p_grid, legend, ncol = 1, rel_heights = c(0.1, 1, 0.2))
#this plots the first 2 plots 
test

I can save test to a pdf but only save the first two plots:

save_plot("test.pdf", test, ncol = 1, nrow = 1, base_asp = 1.1)

What I want to do is something like this:

#or save_plot? 
#saving 1x1 here should save each plot as 1x2 plot with overall legend for the plot from above
ggsave("test.pdf", marrangeGrob(grobs = test, nrow = 1, ncol = 1, widths = c(6, 6)), width = 12, height = 7)

but test is not a list (only contains one 1x2 plot) so wont work. Is there a neat way to save the 1x2 plots with an overall legend in a list to use in marrangeGrob?

Thanks

user63230
  • 4,095
  • 21
  • 43
  • 1
    Relates to your previous question: [ggpubr::ggarrange save plots over multiple pages with one legend per page](https://stackoverflow.com/questions/62306026/ggpubrggarrange-save-plots-over-multiple-pages-with-one-legend-per-page) – markus Jun 11 '20 at 11:48
  • related but different! The previous question is focused on `ggpubr` but this is related to a different package, `cowplot` . Here I'm just trying to save plots in a list so I think its more straight forward? – user63230 Jun 11 '20 at 11:52

0 Answers0