How to Save a GGPlot

How to Save a GGPlot

In this article, you will learn how to save a ggplot to different file formats, including: PDF, SVG vector files, PNG, TIFF, JPEG, etc.

You can either print directly a ggplot into PNG/PDF files or use the convenient function ggsave() for saving a ggplot.

The default of ggsave() is to export the last plot that you displayed, using the size of the current graphics device. It also guesses the type of graphics device from the extension.


Related Book

GGPlot2 Essentials for Great Data Visualization in R


The standard procedure to save any graphics from R is as follow:

  1. Open a graphic device using one of the following functions:
  • pdf(“r-graphics.pdf”),
  • svg(“r-graphics.svg”),
  • png(“r-graphics.png”),
  • tiff(“r-graphics.tiff”),
  • jpeg(“r-graphics.jpg”),
  • and so on.

Additional arguments indicating the width and the height (in inches) of the graphics region can be also specified in the mentioned function.

  1. Create and print a plot
  2. Close the graphic device using the function

Save ggplot into a PDF file

For example, to export ggplot2 graphs to a pdf file, the R code looks like this:

# Create some plots
myplot1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + 
myplot2 <- ggplot(iris, aes(Species, Sepal.Length)) + 

# Print plots to a pdf file
print(myplot1)     # Plot 1 --> in the first page of PDF
print(myplot2)     # Plot 2 ---> in the second page of the PDF 


It’s also possible to make a ggplot and to save it from the screen using the function ggsave():

# 1. Create a plot: displayed on the screen (by default)
ggplot(mtcars, aes(wt, mpg)) + geom_point()
# 2.1. Save the plot to a pdf
# 2.2 OR save it to png file

Specify the name of the plot to export:

p1 <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
ggsave("myplot.png", plot = p1)

Version: Français

No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments