Printing multiple ggplots into a single pdf, multiple plots per page

Solution 1:

This solution is independent of whether the lengths of the lists in the list p are different.

library(gridExtra)

pdf("plots.pdf", onefile = TRUE)
for (i in seq(length(p))) {
  do.call("grid.arrange", p[[i]])  
}
dev.off()

Because of onefile = TRUE the function pdf saves all graphics appearing sequentially in the same file (one page for one graphic).

Solution 2:

Here is a simpler version of Sven's solution for the R beginners who would otherwise blindly use the do.call and nested lists that they neither need nor understand. I have empirical evidence. :)

library(ggplot2)
library(gridExtra)

pdf("plots.pdf", onefile = TRUE)
cuts <- unique(diamonds$cut)
for(i in 1:length(cuts)){
    dat <- subset(diamonds, cut==cuts[i])
    top.plot <- ggplot(dat, aes(price,table)) + geom_point() + 
        opts(title=cuts[i])
    bottom.plot <- ggplot(dat, aes(price,depth)) + geom_point() + 
        opts(title=cuts[i])
    grid.arrange(top.plot, bottom.plot)
}
dev.off()

Solution 3:

Here is the most elegant solution to exporting a list of ggplot objects into a single pdf file using ggplot2::ggsave() and gridExtra::marrangeGrob().

library(ggplot2)
library(gridExtra)

Let's say you create multiple plots using lapply()

p <- lapply(names(mtcars), function(x) {
  ggplot(mtcars, aes_string(x)) + 
    geom_histogram()
})

Save list of p plots:

ggsave(
   filename = "plots.pdf", 
   plot = marrangeGrob(p, nrow=1, ncol=1), 
   width = 15, height = 9
)