0
0
R Programmingprogramming~5 mins

Saving plots (ggsave) in R Programming

Choose your learning style9 modes available
Introduction

Saving plots lets you keep your graphs as image files. This helps you share or use them later.

You want to save a graph to include in a report or presentation.
You need to keep a copy of your plot for future reference.
You want to save a plot in a specific format like PNG or PDF.
You want to save multiple plots automatically in a script.
You want to control the size and resolution of your saved plot.
Syntax
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.

Examples
Saves the last plot as a PNG file named 'myplot.png' in the current folder.
R Programming
ggsave("myplot.png")
Saves the last plot as a PDF with width 5 inches and height 4 inches.
R Programming
ggsave("plot.pdf", width = 5, height = 4, units = "in")
Saves a specific plot object my_plot as a PNG with high resolution (600 dpi).
R Programming
ggsave("plot2.png", plot = my_plot, dpi = 600)
Sample Program

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.

R Programming
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")
OutputSuccess
Important Notes

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.

Summary

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.