How can I save multiple plots to a single PDF file in R?

Saving multiple plots to a single PDF file in R can be achieved by using the “pdf” function. This function allows you to specify the file name and location where you want to save the PDF file, as well as the dimensions of the resulting document. Once the PDF file is created, you can use the “par” function to divide the page into multiple sections and plot each graph in its designated section. This method is useful for organizing and presenting multiple plots in a single, easily shareable file. It is also a convenient way to compare and analyze different graphs in one document.

Save Multiple Plots to PDF in R


You can use the following basic syntax to save multiple plots to a PDF in R:

#specify path to save PDF to
destination = 'C:UsersBobDocumentsmy_plots.pdf'

#open PDF
pdf(file=destination)

#specify to save plots in 2x2 grid
par(mfrow = c(2,2))

#save plots to PDF
for (i in 1:4) {   
  x=rnorm(i)  
  y=rnorm(i)  
  plot(x, y)   
}

#turn off PDF plotting
dev.off() 

The following examples show how to use this syntax in practice.

Example 1: Save Multiple Plots to Same Page in PDF

The following code shows how to save several plots to the same page in a PDF:

#specify path to save PDF to
destination = 'C:UsersBobDocumentsmy_plots.pdf'

#open PDF
pdf(file=destination)

#specify to save plots in 2x2 grid
par(mfrow = c(2,2))

#save plots to PDF
for (i in 1:4) {   
  x=rnorm(i)  
  y=rnorm(i)  
  plot(x, y)   
}

#turn off PDF plotting
dev.off() 

Once I navigate to the PDF in the specified location on my computer, I find the following one-page PDF with four plots on it:

Example 2: Save Multiple Plots to Different Pages in PDF

To save multiple plots to different pages in a PDF, I can simply remove the par() function:

#specify path to save PDF to
destination = 'C:UsersBobDocumentsmy_plots.pdf'

#open PDF
pdf(file=destination)

#save plots to PDF
for (i in 1:4) {   
  x=rnorm(i)  
  y=rnorm(i)  
  plot(x, y)   
}

#turn off PDF plotting
dev.off() 

Once I navigate to the PDF in the specified location on my computer, I find the a four-page PDF with one plot on each page.

Additional Resources

x