How to Use ggsave to Quickly Save ggplot2 Plots

ggsave is a function from the ggplot2 package that allows you to quickly save an already-made ggplot2 plot as an image file, such as a PNG or JPEG. It takes in the plot name and file name as arguments and creates the image file automatically. It is a useful tool for quickly saving a plot without having to use a separate plotting application.


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.

The following tutorials explain how to perform other common tasks in R:

x