Chapter 16 Exporting Graphics to a File

Welcome back to Quantitative Reasoning! Last time we learned how to make histograms. After playing with the bin sizes, we created this histogram.

sw_ver <- iris$Sepal.Width[iris$Species == "versicolor"]
hist(sw_ver,
     main = "Sepal Width of Iris Versicolor",
     col = "lightgreen",
     xlab = "Width (cm)",
     breaks = seq(2.0, 3.4, 0.1))

Suppose we want to save this histogram as an image that we can include in a report or presentation. We can save the image by clicking on the “Export” button at the top of the Plots tab. From the dropdown menu, we can choose either “Save as Image” or “Save as PDF”. “Save as Image” permits us to save the plot in various non-PDF graphics formats (e.g. PNG, JPEG or TIFF). I personally prefer to save R graphics as a PDF because the images tend to be crisp and there are plenty of good PDF viewers, so let’s choose “Save as PDF” from the Export menu. In the dialog window, we choose the PDF size to match the “Device Size” so that the exported image looks the same as the plot in the bottom right RStudio pane.

Let’s give the plot a telling name, for example iris_histogram. We don’t need to append the extension “.pdf”. RStudio will append it automatically. Finally click “Save”. We can see in the Files tab that RStudio has saved iris_histogram.pdf in our iris project folder. We can open the PDF by clicking on the file name. We can now also share the plot (e.g. by attaching it to an email).

In summary, we perform the following steps when we want to export R graphics.

  • First we adjust the size of the Plots tab so that the plot looks pleasant on our computer screen.
  • Then we click “Export” at the top of the Plots tab.
  • We choose the option “Save as PDF”.
  • We choose the PDF size to match the device size, and
  • we give the PDF file a meaningful name.
  • After we click “Save”, the PDF appears in the Files tab.

What if we want to share not only a diagram, but also data that we calculated with R? In the next tutorial, we learn how to export a data frame as a CSV file.

See you soon.