rggplot2ggsave

ggsave() fails with Error in png_dev(..., res = dpi, units = "in") : unable to start png() device


When I try to save a ggplot to a new directory with ggsave(), I get an error.

library(ggplot2)
ggplot(mtcars, aes(x = cyl)) +
  geom_bar()
ggsave("current_folder/new_folder/new_plot.png")

Produces the error:

Saving 11.3 x 7.32 in image
Error in png_dev(..., res = dpi, units = "in") : 
  unable to start png() device
In addition: Warning messages:
1: In png_dev(..., res = dpi, units = "in") :
  unable to open file 'current_folder/new_folder/new_plot.png' for writing
2: In png_dev(..., res = dpi, units = "in") : opening device failed

Solution

  • If the target directory does not already exist, ggsave() will not create it as part of saving. It will instead throw this error.

    First create the directory, either in your operating system outside of R or with dir.create like in this answer: https://stackoverflow.com/a/29784923.

    Then save with ggsave().