How to Save ggplot2 Plot in R: Simple Guide
To save a
ggplot2 plot in R, use the ggsave() function which saves the last plot by default or a specified plot object. You can specify the filename, width, height, and file format like PNG or PDF in ggsave().Syntax
The basic syntax of ggsave() is:
filename: The name of the file to save the plot to, including extension like .png or .pdf.plot: The ggplot object to save. If omitted, it saves the last plot displayed.widthandheight: Size of the saved image in inches.units: Units for width and height, usually "in" (inches).dpi: Resolution of the image, higher means better quality.
r
ggsave(filename, plot = last_plot(), width = 7, height = 5, units = "in", dpi = 300)
Example
This example creates a simple scatter plot and saves it as a PNG file named "scatterplot.png" with specified size and resolution.
r
library(ggplot2) # Create a scatter plot p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + ggtitle("Car Weight vs. MPG") # Save the plot to a PNG file # This saves the plot 'p' as a 6x4 inch image with 300 dpi resolution ggsave("scatterplot.png", plot = p, width = 6, height = 4, dpi = 300)
Output
A file named 'scatterplot.png' is created in the working directory containing the scatter plot image.
Common Pitfalls
- Not specifying the
plotargument when you want to save a plot stored in a variable, which causesggsave()to save the last plot shown instead. - Forgetting to include the file extension in
filename, which can cause errors or unexpected file formats. - Using incorrect units or sizes that make the saved image too small or too large.
- Saving plots before they are created or displayed, resulting in empty or missing files.
r
library(ggplot2) p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() # Wrong: saves last plot, which might not be 'p' ggsave("wrong_plot.png") # Right: specify the plot object ggsave("correct_plot.png", plot = p)
Quick Reference
Remember these tips when saving ggplot2 plots:
- Always include the file extension in the filename (e.g., .png, .pdf).
- Use
plot = your_plotif your plot is saved in a variable. - Adjust
width,height, anddpifor better image quality. - Check your working directory to find the saved file or specify a full path.
Key Takeaways
Use ggsave() to save ggplot2 plots easily with control over file name and size.
Always specify the plot object in ggsave() if it is not the last displayed plot.
Include the file extension in the filename to set the output format correctly.
Adjust width, height, and dpi to control the image quality and dimensions.
Check your working directory or provide a full path to find the saved plot file.