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::ggsave
filename
File name to create on disk.
device
Device 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 thefilename
extension.path
Path of the directory to save plot to:
path
andfilename
are combined to create the fully qualified file name. Defaults to the working directory.scale
Multiplicative scaling factor.
limitsize
When
TRUE
(the default),ggsave()
will not save images larger than 50x50 inches, to prevent the common error of specifying dimensions in pixels.bg
Background colour. If
NULL
, uses theplot.background
fill value from the plot theme.create.dir
Whether to create new directories if a non-existing directory is specified in the
filename
orpath
(TRUE
) or return an error (FALSE
, default). IfFALSE
and 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
units
argument. 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
width
andheight
arguments 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)
#> Warning: The `panel.widths` theme element is not defined in the element hierarchy.
#> Warning: The `panel.heights` theme element is not defined in the element hierarchy.
#> Saving 7 x 7 in image
#> Warning: The `panel.widths` theme element is not defined in the element hierarchy.
#> Warning: The `panel.heights` theme element is not defined in the element hierarchy.
#> Warning: The `panel.widths` theme element is not defined in the element hierarchy.
#> Warning: The `panel.heights` theme element is not defined in the element hierarchy.
#> [1] "/tmp/RtmpmRPWAv/file1d80452bf1d1.png"
#> attr(,"width")
#> [1] NA
#> attr(,"height")
#> [1] NA
# Clean up temporary file
unlink(tmp)