How to save a ggplot chart to a file in R

· 2 min read · Updated March 15, 2026 · beginner
r ggplot2 visualization export graphics

Saving ggplot2 charts to files is essential for reports and publications.

With ggsave()

The ggsave() function is the simplest way to export plots:

library(ggplot2)

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  labs(title = "Car Weight vs MPG")

# Save as PNG
ggsave("plot.png", p, width = 6, height = 4, dpi = 300)

# Save as PDF
ggsave("plot.pdf", p, width = 6, height = 4)

Common file formats

PNG (raster)

Best for web and presentations:

ggsave("plot.png", p, width = 6, height = 4, dpi = 300, bg = "white")

Set bg = "white" to ensure a white background for transparent plots.

PDF (vector)

Best for publications and reports:

ggsave("plot.pdf", p, width = 6, height = 4)

PDF files scale without quality loss.

SVG (vector)

Best for web graphics that need scaling:

ggsave("plot.svg", p, width = 6, height = 4)

Controlling dimensions

Specify dimensions in different units:

# In inches (default)
ggsave("plot.png", p, width = 6, height = 4)

# In centimeters
ggsave("plot.png", p, width = 15, height = 10, units = "cm")

Saving the last plot

Omit the plot object to save the last created plot:

ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()

ggsave("last_plot.png")  # Saves the above plot

Using base graphics

Save base R plots with dedicated functions:

png("plot.png", width = 800, height = 600)
plot(mtcars$wt, mtcars$mpg)
dev.off()

pdf("plot.pdf")
plot(mtcars$wt, mtcars$mpg)
dev.off()

See Also