问题
I want to produce a single pdf with many pages of ggplots. Using gridExtra, I can also build a page of plots with a m x n layout (m rows of plots, n columns of plots).
The function ggsave allows me to write a page of plots, even those that are built with gridExtra having the m x n layout.
Using arrangeGrob it is even possible to ggsave many pages to a single pdf, as long as each page has the same m x n layout.
I'm wondering how I can ggsave a list of plots that have different page layouts? For example, I have a list, l, with length 3 representing 3 pages.
l[[1]] is a page with a 2 x 2 layout and has 4 plots
l[[2]] is 2 x 1 with 2 plots
l[[3]] is only 1 x 1
How could I hack ggsave so that I can write the list l into 1 pdf file with 3 pages having different layouts? The plots should be displayed in landscape, so typically the command would have the form
ggsave("multipage.pdf", do.call(arrangeGrob, myplots[[i]]), width=11, height=8.5)
回答1:
you can use the same class trick as marrangeGrob,
library(ggplot2)
library(gridExtra)
pl <- lapply(1:7, function(i) ggplot() + ggtitle(i))
ppl <- list(p1 = arrangeGrob(grobs=pl[1:4]),
p2 = arrangeGrob(grobs=pl[5:6]),
p3 = arrangeGrob(grobs=pl[7]))
class(ppl) <- c("arrangelist", class(pl))
ggsave("multipage.pdf", ppl)
来源:https://stackoverflow.com/questions/36049296/ggplot-list-of-plots-to-one-pdf-with-different-page-layouts