save_plot | R Documentation |
ggsave()
, with better support for multi-figure plots.This function replaces the standard ggsave()
function for saving a plot into a file. It
has several advantages over ggsave()
. First, it uses default sizes that work well with
the cowplot theme, so that frequently a plot size does not have to be explicitly specified. Second, it
acknowledges that one often first develops individual plots and then combines them into
multi-plot figures, and it makes it easy—in combination with plot_grid()
—to carry out
this workflow. Finally, it makes it easy to adjust the aspect ratio of the figure, which is
frequently necessary to accommodate plots with or without figure legend.
save_plot(
filename,
plot,
ncol = 1,
nrow = 1,
base_height = 3.71,
base_asp = 1.618,
base_width = NULL,
...,
cols,
rows,
base_aspect_ratio,
width,
height
)
filename |
Name of the plot file to generate. |
plot |
Plot to save. |
ncol |
Number of subplot columns. |
nrow |
Number of subplot rows. |
base_height |
The height (in inches) of the plot or of one sub-plot if |
base_asp |
The aspect ratio (width/height) of the plot or of one sub-plot if |
base_width |
The width (in inches) of the plot or of one sub-plot if |
... |
Other arguments to be handed to |
cols |
Deprecated. Use |
rows |
Deprecated. Use |
base_aspect_ratio |
Deprecated. Use |
width |
Deprecated. Don't use. |
height |
Deprecated. Don't use. |
The key idea for this function is that plots are often grids, with sup-plots at the individual grid locations. Therefore, for this function we specify a base width and aspect ratio that apply to one sup-plot, and we then specify how many rows and columns of subplots we have. This means that if we have code that can save a single figure, it is trivial to adapt this code to save a combination of multiple comparable figures. See examples for details.
library(ggplot2)
# save a single plot with a legend
p1 <- ggplot(mpg, aes(x = cty, y = hwy, color = factor(cyl))) +
geom_point(size = 2) +
theme_half_open()
file1 <- tempfile("file1", fileext = ".png")
file2 <- tempfile("file2", fileext = ".png")
save_plot(file1, p1)
# same as file1 but determine base_width given base_height
save_plot(file2, p1, base_height = NULL, base_width = 6)
# save a single plot without legend, adjust aspect ratio
x <- (1:100)/10
p3 <- ggplot(data.frame(x = x, y = x*sin(x)), aes(x, y)) +
geom_line() +
theme_minimal_hgrid()
file3 <- tempfile("file3", fileext = ".pdf")
save_plot(file3, p3, base_asp = 1.1)
# now combine with a second plot and save
p3b <- ggplot(data.frame(x = x, y = cos(x)+x), aes(x, y)) +
geom_line() +
theme_minimal_hgrid()
p4 <- plot_grid(p3, p3b, labels = "AUTO")
file4 <- tempfile("file4", fileext = ".pdf")
save_plot(file4, p4, ncol = 2, base_asp = 1.1)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.