Concept Flow - Saving plots (ggsave)
Create plot object
Call ggsave() with filename
Check file extension
Save plot to file
File saved on disk
END
This flow shows how you create a plot, then use ggsave() to save it as a file on your computer.
library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
ggsave("myplot.png", plot = p)| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Load ggplot2 library | library(ggplot2) | ggplot2 functions ready |
| 2 | Create plot object p | p <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() | p stores scatter plot |
| 3 | Call ggsave() with filename and plot | ggsave("myplot.png", plot = p) | File 'myplot.png' saved |
| 4 | Check file saved | file.exists("myplot.png") | TRUE |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| p | NULL | Scatter plot object | Same plot object | Same plot object |
ggsave(filename, plot) saves a ggplot object to a file. Assign your plot to a variable first. File format depends on filename extension (.png, .pdf, .jpeg). If plot is not given, last plot is saved. Use ggsave to export plots for sharing or reports.