I have a list, p
, where each element of p
is a list of ggplot2 plotting objects.
I would like to output a single pdf containing all the plots in p
such that the plots in p[[1]]
are on page 1, the plots in p[[2]]
are on page 2, etc. How might I do this?
Here's some example code to provide you with the data structure I'm working with--apologies for the boring plots, I picked variables at random.
require(ggplot2)
p <- list()
cuts <- unique(diamonds$cut)
for(i in 1:length(cuts)){
p[[i]] <- list()
dat <- subset(diamonds, cut==cuts[i])
p[[i]][[1]] <- ggplot(dat, aes(price,table)) + geom_point() +
opts(title=cuts[i])
p[[i]][[2]] <- ggplot(dat, aes(price,depth)) + geom_point() +
opts(title=cuts[i])
}
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. :)
Here's one solution, but I don't particularly like it:
ggsave("test.pdf", do.call("marrangeGrob", c(unlist(p,recursive=FALSE),nrow=2,ncol=1)))
The problem is that it relies on there being the same number of plots in each group. If
all(sapply(p, length) == 2)
were false, then it would break.I've tried some of these solutions but with no success. I researched a little more and found a solution that worked perfectly for me. It saves all my graphics in a single pdf file, each chart on one page.
Here's a function based on Sven's approach, including the roxygen2 documentation and an example.
A nice solution without the
gridExtra
package:This solution is independent of whether the lengths of the lists in the list
p
are different.Because of
onefile = TRUE
the functionpdf
saves all graphics appearing sequentially in the same file (one page for one graphic).