ggpubr::ggarrange save plots over multiple pages with one legend per page

痴心易碎 提交于 2020-06-13 09:32:34

问题


I'm trying to save plots over multiple pdf plots with one overall legend per page. I'm wondering is there a neat way to use ggsave and ggpubr::ggarrange to do this? Changing nrow ncol within ggarrange only changes the setup for one page and forces all plots to be on the same page (not over a few pages).

library(ggplot2)
library(ggpubr)
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)
})

#WORKS this saves plots all on the same page
ggsave("test.pdf", ggpubr::ggarrange(plotlist =  list_plots, # list of plots
                                     labels = "AUTO", # labels
                                     common.legend = T, # COMMON LEGEND
                                     legend = "bottom", # legend position
                                     align = "hv", # Align them both, horizontal and vertical
                                     nrow = 6),
       height = 9,
       width = 12)

The following throws an error because 2x2 is less than the total number of plots:

ggsave("test.pdf", ggpubr::ggarrange(plotlist =  list_plots, # list of plots
                                     labels = "AUTO", # labels
                                     common.legend = T, # COMMON LEGEND
                                     legend = "bottom", # legend position
                                     align = "hv", # Align them both, horizontal and vertical
                                     nrow = 2, ncol = 2),
       height = 9, 
       width = 12)

Error in UseMethod("grid.draw") : 
  no applicable method for 'grid.draw' applied to an object of class "c('list', 'ggarrange')"

I would like a flexible approach to supply various nrow ncol values, similar to marrangeGrob function in the gridExtra package, e.g. nrow = 2 ncol = 2. I know cowplot does something similar but I like the ease that an overall legend can be added with ggpubr using common.legend = T.

Thanks

来源:https://stackoverflow.com/questions/62306026/ggpubrggarrange-save-plots-over-multiple-pages-with-one-legend-per-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!