11.8 Saving plots to a file with pdf(), jpeg() and png()

Once you’ve created a plot in R, you may wish to save it to a file so you can use it in another document. To do this, you’ll use either the pdf(), png() or jpeg() functions. These functions will save your plot to either a .pdf, .jpg, or .png file.

Table 11.13: Arguments to pdf(), jpeg() and png()
Argument Outcome
file The directory and name of the final plot entered as a string. For example, to put a plot on my desktop, I’d write file = "/Users/nphillips/Desktop/plot.pdf" when creating a pdf, and file = "/Users/nphillips/Desktop/plot.jpg" when creating a jpeg.
width, height The width and height of the final plot in inches.
dev.off() This is not an argument to pdf() and jpeg(). You just need to execute this code after creating the plot to finish creating the image file (see examples).

To use these functions to save files, you need to follow 3 steps:

  1. Execute the pdf() or jpeg() functions with file, width, height arguments.
  2. Execute all your plotting code (e.g.; plot(x = 1:10, y = 1:10))
  3. Complete the file by executing the command dev.off(). This tells R that you’re done creating the file.

The chunk below shows an example of the three steps in creating a pdf:

# Step 1: Call the pdf command to start the plot
pdf(file = "/Users/ndphillips/Desktop/My Plot.pdf",   # The directory you want to save the file in
    width = 4, # The width of the plot in inches
    height = 4) # The height of the plot in inches

# Step 2: Create the plot with R code
plot(x = 1:10, 
     y = 1:10)
abline(v = 0) # Additional low-level plotting commands
text(x = 0, y = 1, labels = "Random text")

# Step 3: Run dev.off() to create the file!

You’ll notice that after you close the plot with dev.off(), you’ll see a message in the prompt like “null device”. That’s just R telling you that you can now create plots in the main R plotting window again.

The functions pdf(), jpeg(), and png() all work the same way, they just return different file types. If you can, use pdf() it saves the plot in a high quality format.