Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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]) } 
like image 633
Michael Avatar asked Sep 02 '12 07:09

Michael


People also ask

How do I combine multiple Ggplots?

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.

How do I save multiple Ggplots?

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() .

How do I save multiple plots in R?

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.


1 Answers

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).

like image 165
Sven Hohenstein Avatar answered Oct 02 '22 12:10

Sven Hohenstein