Saving plots

Once you have made your plot, you typically want to save it. This is easy with ggsave.


It has saved a plot, but where? What plot was saved?

Without further speficiation, ‘ggsave’ saves the lost ggplot that was made in the R-environment. Typically, we want a little bit more control, so we tell ggsave which ggplot-object to save:

density_plot <- ggplot(mpg, aes(x=cty, fill=drv)) + geom_density()  +
  scale_fill_manual(values = c("4" = "magenta4", "f" = "cornflowerblue", "r" = "hotpink4"))

ggsave("myplot.pdf", density_plot)

ggplot already tells us that is saving a 7 x 5 image. This means it’s saving a 7 inch by 5 inch pdf. We can easily adjust the size:

ggsave("myplot_bigger.pdf", density_plot, width = 10, height = 10)

If you meant 10 centimer instead of inch, you can either:

ggsave("myplot_bigger_cm.pdf", density_plot, width = 10/2.54, height = 10/2.54)
ggsave("myplot_bigger_cm2.pdf", density_plot, width = 10, height = 10, unit = "cm")

pdf is typically the preferred format of saving images/graphs because no matter how much you zoom in, you’ll never lose quality. This is much different with png or jpeg or bmp (other extensions are available too. Nonetheless, with ggplot we can easily save to those formats as well:

ggsave("myplot_png.png", density_plot)
ggsave("myplot_jpg.jpeg", density_plot)
ggsave("myplot_bmp.bmp", density_plot)

In those cases, you can also specify a resolution. Compare:

ggsave("myplot_lowres.png", density_plot, dpi = 100)
ggsave("myplot_highres.png", density_plot, dpi = 600)