This is a wrapper for ggsave() that attempts to make a
reasonable guess at the plot size, particularly if they have been set in
the theme(panel.widths, panel.heights) settings or when the
force_panelsizes() function has been used.
Usage
save_plot(
...,
plot = get_last_plot(),
width = NULL,
height = NULL,
units = c("in", "cm", "mm", "px"),
dpi = 300
)Arguments
- ...
Arguments passed on to
ggplot2::ggsavefilenameFile name to create on disk.
deviceDevice to use. Can either be a device function (e.g. png), or one of "eps", "ps", "tex" (pictex), "pdf", "jpeg", "tiff", "png", "bmp", "svg" or "wmf" (windows only). If
NULL(default), the device is guessed based on thefilenameextension.pathPath of the directory to save plot to:
pathandfilenameare combined to create the fully qualified file name. Defaults to the working directory.scaleMultiplicative scaling factor.
limitsizeWhen
TRUE(the default),ggsave()will not save images larger than 50x50 inches, to prevent the common error of specifying dimensions in pixels.bgBackground colour. If
NULL, uses theplot.backgroundfill value from the plot theme.create.dirWhether to create new directories if a non-existing directory is specified in the
filenameorpath(TRUE) or return an error (FALSE, default). IfFALSEand run in an interactive session, a prompt will appear asking to create a new directory when necessary.
- plot
Plot to save, defaults to last plot displayed.
- width, height
Plot size in units expressed by the
unitsargument. IfNULL(default), the plot size will be measured. When the plot does not have a fixed size, these becomeNA, meaning that the size of the current graphics device is used.- units
One of the following units in which the
widthandheightarguments are expressed:"in","cm","mm"or"px".- dpi
Plot resolution. Also accepts a string input: "retina" (320), "print" (300), or "screen" (72). Only applies when converting pixel units, as is typical for raster output types.
Examples
# A plot with fixed dimensions
p <- ggplot(mpg, aes(displ, hwy)) +
geom_point() +
theme(
panel.widths = unit(10, "cm"),
panel.heights = unit(2, "cm")
)
# Save plot to a temporary file
tmp <- tempfile(fileext = ".png")
save_plot(tmp, plot = p)
#> [1] "/tmp/RtmpMyC8ZT/file1e3d1812df7e.png"
#> attr(,"width")
#> [1] 4.490031
#> attr(,"height")
#> [1] 1.296193
# Clean up temporary file
unlink(tmp)
