Table of Contents
In R, multiple plots can be saved to a single PDF file using the pdf() and dev.off() functions. The pdf() function opens a graphics device that allows multiple plots to be drawn on the same page, and the dev.off() function closes the device and saves the plots to a PDF file. To save a single plot to a PDF file, the pdf() function can be used with no arguments followed by the plot command and dev.off(). The arguments of the pdf() function can be used to customize the size and orientation of the output PDF file.
You can use the following basic syntax to save multiple plots to a PDF in R:
#specify path to save PDF to destination = 'C:\Users\Bob\Documents\my_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:\Users\Bob\Documents\my_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:\Users\Bob\Documents\my_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.