Jump to the instructions and examples!
There are two main techniques for saving a plot in R/RStudio:
1: Saving a plot programmatically, the preferred method.
2: Using the RStudio export function in the Plot pane.
There are lots functions to save figures as raster-based graphics files such as png, tiff, jpeg, gif and vector-based files such as pdf, svg, and eps.
Two of the most helpful are the pdf()
and png()
I’ll illustrate the process with one of R’s built-in datasets: mtcars
.
data("mtcars")
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
To save a figure programatically:
png(filename = "mtcars_boxplot.png")
boxplot(
qsec ~ cyl,
data = mtcars,
xlab = "Number of cylinders",
ylab = "Time from stopped to 1/4 mile",
main = "Cylindars and Acceleration!")
dev.off()
## png
## 2
The graphics functions have lots of options to customize your output files. You can investigate the various arguments on your own.
require(here)
png(
filename = here("mtcars_boxplot_hi_res.png"),
width = 1200, height = 900,
res = 120, units = "px")
boxplot(
qsec ~ cyl,
data = mtcars,
xlab = "Number of cylinders",
ylab = "Time from stopped to 1/4 mile",
main = "Cylindars and Acceleration!")
dev.off()
## png
## 2
Vector formats are better for publications. PDF is a popular format.
The syntax for pdf() is very similar to png()
pdf(
file = here("mtcars_boxplot_hi_res.pdf"),
width = 7, height = 10, bg = rgb(0.9, 1, 1))
boxplot(
qsec ~ cyl,
data = mtcars,
xlab = "Number of cylinders",
ylab = "Time from stopped to 1/4 mile",
main = "Cylindars and Acceleration!")
dev.off()
## png
## 2
Now there will be a file called mtcars_boxplot.png in your working directory.
here
package to organize your file input/output. Check it out: https://here.r-lib.org/dev.off()
dev.off()
## Error in dev.off(): cannot shut down device 1 (the null device)
dev.off()
## Error in dev.off(): cannot shut down device 1 (the null device)
## null device
## 1