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]) }
To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.
For this function, we simply specify the different ggplot objects in order, followed by the number of columns (ncol) and numebr of rows (nrow). This function is awesome at aligning axes and resizing figures. From here, we can simply save the arranged plot using ggsave() .
To save multiple plots to the same page in the PDF file, we use the par() function to create a grid and then add plots to the grid. In this way, all the plots are saved on the same page of the pdf file. We use the mfrow argument to the par() function to create the desired grid.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With