Saving plots lets you keep your graphs as image files. This helps you share or use them later.
Saving plots (ggsave) in R Programming
ggsave(filename, plot = last_plot(), device = NULL, path = NULL, scale = 1, width = NA, height = NA, units = c("in", "cm", "mm"), dpi = 300, limitsize = TRUE, ...)
filename is the name of the file you want to save, including extension like .png or .pdf.
If you don't specify plot, ggsave saves the last plot you made.
ggsave("myplot.png")ggsave("plot.pdf", width = 5, height = 4, units = "in")
my_plot as a PNG with high resolution (600 dpi).ggsave("plot2.png", plot = my_plot, dpi = 600)
This program makes a scatter plot of car weight vs. miles per gallon. Then it saves the plot as a PNG file named 'car_plot.png' with size 6x4 inches and 300 dpi resolution.
library(ggplot2) # Create a simple plot p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() # Save the plot as a PNG file # This saves 'car_plot.png' in your working directory ggsave("car_plot.png", plot = p, width = 6, height = 4, units = "in", dpi = 300) print("Plot saved as car_plot.png")
Make sure your working directory is where you want to save the file, or provide a full path in filename.
You can save plots in many formats like PNG, PDF, JPEG, TIFF by changing the file extension.
If you get an error about size, try setting limitsize = FALSE to allow bigger images.
ggsave saves your ggplot graphs as image files.
You can control file name, format, size, and resolution easily.
It saves the last plot by default or a specific plot if you provide one.