Saving Plots in ggplot in R


Communicating your work is an important step in your work as an analyst. There are other methods for saving your plots, such as: Export and ggsave().

As an example, we can use the palmer penguins data in ggplot.

library(ggplot2)
library(palmerpenguins)

ggplot(data = penguins) +
  geom_point(mapping=aes(x=flipper_length_mm,y=body_mass_g,color=species))

In RStudio, in the Plots pane in the lower right corner, there is an Export button. After you run the above code you can export the plot to an image, PDF or copy to clipboard. When you save the plot as an image, a dialog box appears with six different options. The format can be PNG, JPEG, TIFF, BMP, SVG or EPS. Enter you file name. Choose a directory. Click the Save button. If you check the view plot after saving checkbox in the lower left corner, your image will appear using the default software program for your chosen file type. Currently for PNG, I have associated IrfanView.

ggsave() defaults to the last plot you created.

ggsave("Three Penguin Species.png")

Where does it save the file? Which folder?

In most cases, ggsave() is the simplest way to save your plot. But there are situations when it might be best to save your plot by writing it directly to a graphics device. When you make a plot in R, it has to be “sent” to a specific graphics device. To save images without using ggsave(), you can open an R graphics device like png() or pdf(); these will allow you to save your plot as a .png or .pdf file. You can also choose to print the plot and then close the device using dev.off(). Here are some instructions at the ggplot website. The article is called Save a ggplot (or other grid object) with sensible defaults.

Leave a Reply