This is a simple tutorial on how to save a plot as an image file in R/RStudio.
The data for this demo include various measurements of redbacked salamander (Plethodon cinereus) collected at several sites in Ithaca, NY.
You can download the data file here: mander.csv
These variables within the data set include:
Suppose I have loaded the salamander into a variable called mander
.
head(mander)
## Date Collector Year Season Site SVL Total_length Sex
## 1 5-Sep-14 Sutherland 2014 Fall A 36 72 female
## 2 4-Oct-14 Sutherland 2014 Fall A 46 83 female
## 3 4-Oct-14 Sutherland 2014 Fall A 42 89 female
## 4 4-Oct-14 Sutherland 2014 Fall A 34 75 female
## 5 4-Oct-14 Sutherland 2014 Fall A 37 80 female
## 6 18-Oct-14 Sutherland 2014 Fall A 40 79 female
Using ggplot, I’ll make a conditional boxplot of SVL by Site and Sex. Don’t worry if you don’t know what that means, the focus of this walkthrough is on saving the plot to a file.
ggplot(mander, aes(x = Sex, y = SVL, fill = Site)) +
geom_boxplot() +
ggtitle("Salamander Snout to Vent Length")
The Plots pane in my RStudio session now looks like this:
You can also save a figure directly using code in R. I prefer this method because you can more easily specify the options that you want to use for the image.
The image will be saved as the filename
that you provide. The image will be saved in your current working directory.
The syntax is slightly different than what you’re used to:
png()
on the line before your plotting code.dev.off()
on the line after your plotting code.# This tells R to create an empty image file:
png(filename = "salamander_boxplot.png")
# These lines create the plot.
# You won't see the plot in the RStudio plot window.
ggplot(mander, aes(x = Sex, y = SVL, fill = Site)) +
geom_boxplot() +
ggtitle("Salamander Snout to Vent Length")
# This tells R to write the graphical data to the image file and save it.
dev.off()
png()
has lots of options (see the help entry). For example, you can specify the height and width of the output image (in pixels).
I’ll now have a file called salamander_boxplot.png in my current working directory.
There are related functions for saving files to other raster and vector formats like jpg, tiff, pdf, and eps.
png()
The best way to learn is to try it out on one of your own plots!