A wrapper for png()
, pdf()
, or jpeg()
to save plots to
disk. If a file path is passed to figure()
, it
opens a plotting device based on the file extension,
passing the same file name to close_figure()
.
If file = NULL
, output is directed to the default plotting device.
Arguments
Details
The figure()
and close_figure()
functions
are most useful when used inside of another function that creates a plot.
By adding a file =
pass-through argument to a function that creates a plot,
the user can toggle between plotting to file or to a graphics device.
Supported plotting devices:
postscript()
(*.eps
)
Functions
close_figure()
: Closes the currently active plotting device with adev.off()
call if a file name is passed. Iffile = NULL
, nothing happens. This function is typically used in conjunction withfigure()
inside the enclosing function. See example.
Note
The fontsize
of the plots are constant. If you would like to
increase the font size relative to the plot, you can decrease the plot size.
Alternatively, you can pass pointsize
as an additional argument.
See also
Other base R:
plotPolygon()
Examples
# Create enclosing plotting function
createPlot <- function(file = NULL) {
figure(file = file)
on.exit(close_figure(file = file))
plot_data <- withr::with_seed(1, matrix(rnorm(30), ncol = 2))
plot(as.data.frame(plot_data), col = unlist(soma_colors), pch = 19, cex = 2)
}
# default; no file saved
createPlot()
if ( interactive() ) {
# Save as *.pdf
createPlot("example.pdf")
# Save as *.png
createPlot("example.png")
}