You can use the ggsave() function to quickly save plots created by ggplot2.
This function uses the following basic syntax:
ggsave( filename, plot = last_plot(), device = NULL, path = NULL, scale = 1, width = NA, height = NA, units = c("in", "cm", "mm", "px"),") ... )
where:
- filename: File name to use when saving plot (e.g. “my_plot.pdf”)
- plot: The plot to save. Default is to save last plot displayed.
- device: Device to use
- path: Path to save file to
- scale: Multiplicative scaling factor
- width: width of plot in units specified
- height: height of plot in units specified
- units: Units to use when specifying size of plot
The following examples show how to use the ggsave() function in practice to save the following scatter plot created in ggplot2:
library(ggplot2)
#create data frame
df <- data.frame(team=rep(c('A', 'B'), each=5),
assists=c(1, 3, 3, 4, 5, 7, 7, 9, 9, 10),
points=c(4, 8, 12, 10, 18, 25, 20, 28, 33, 35))
#create scatter plot
ggplot(df, aes(x=assists, y=points)) +
geom_point(aes(color=team), size=3)
Example 1: Use ggsave() to Save Plot with Default Settings
We can use the following syntax with ggsave() to save this scatter plot to a PDF file called my_plot.pdf with all of the default settings:
library(ggplot2)
#save scatter plot as PDF file
ggsave('my_plot.pdf')
Since we didn’t specify a path or a size for our plot, the scatter plot will simply be saved as a PDF in the current working directory with the size of the current graphics device.
If I navigate to my current working directory, I can view the PDF file:
I can see that the plot has been saved as a PDF file with the size of the current graphics device.
Example 2: Use ggsave() to Save Plot with Custom Settings
We can use the following syntax with ggsave() to save this scatter plot to a PDF file called my_plot2.pdf with a size of 3 inches wide by 6 inches tall:
library(ggplot2)
#save scatter plot as PDF file with specific dimensions
ggsave('my_plot2.pdf', width=3, height=6, units='in')
If I navigate to my current working directory, I can view the PDF file:
I can see that the plot has been saved as a PDF file with the dimensions that I specified.
Note: In these examples we chose to save the plots from ggplot2 as PDF files, but you can also specify jpeg, png, or other file formats.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Add Text to ggplot2 Plots
How to Change Title Position in ggplot2
How to Remove Axis Labels in ggplot2