4.5 Exporting plots

Creating plots in R is all well and good but what if you want to use these plots in your thesis, report or publication? One option is to click on the ‘Export’ button in the ‘Plots’ tab in RStudio as we described previously. You can also export your plots from R to an external file by writing some code in your R script. The advantage of this approach is that you have a little more control over the output format and it also allows you to generate (or update) plots automatically whenever you run your script. You can export your plots in many different formats but the most common are, pdf, png, jpeg and tiff.

By default, R (and therefore RStudio) will direct any plot you create to the plot window. To save your plot to an external file you first need to redirect your plot to a different graphics device. You do this by using one of the many graphics device functions to start a new graphic device. For example, to save a plot in pdf format we will use the pdf() function. The first argument in the pdf() function is the filepath and filename of the file we want to save (don’t forget to include the .pdf extension). Once we’ve used the pdf() function we can then write all of the code we used to create our plot including any graphical parameters such as setting the margins and splitting up the plotting device. Once the code has run we need to close the pdf plotting device using the dev.off() function.

pdf(file = 'output/my_plot.pdf')
par(mar = c(4.1, 4.4, 4.1, 1.9), xaxs="i", yaxs="i")
plot(flowers$weight, flowers$shootarea, 
       xlab = "weight (g)",
       ylab = expression(paste("shoot area (cm"^"2",")")),
       xlim = c(0, 30), ylim = c(0, 200), bty = "l",
       las = 1, cex.axis = 0.8, tcl = -0.2,
       pch = 16, col = "dodgerblue1", cex = 0.9)
text(x = 28, y = 190, label = "A", cex = 2)
dev.off()

If we want to save this plot in png format we simply use the png() function in more or less the same way we used the pdf() function.

png('output/my_plot.png')
par(mar = c(4.1, 4.4, 4.1, 1.9), xaxs="i", yaxs="i")
plot(flowers$weight, flowers$shootarea, 
       xlab = "weight (g)",
       ylab = expression(paste("shoot area (cm"^"2",")")),
       xlim = c(0, 30), ylim = c(0, 200), bty = "l",
       las = 1, cex.axis = 0.8, tcl = -0.2,
       pch = 16, col = "dodgerblue1", cex = 0.9)
text(x = 28, y = 190, label = "A", cex = 2)
dev.off()

Other useful functions are; jpeg(), tiff() and bmp(). Additional arguments to these functions allow you to change the size, resolution and background colour of your saved images. See ?png for more details.