Skip to content

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.

Usage

figure(file, height = 480, width = 480, scale = 1, ...)

close_figure(file)

Arguments

file

Character. The path of the output file passed to png(), pdf(), or jpeg(). Plot type determined by file extension.

height

Double. The height of the plot in pixels.

width

Double. The width of the plot in pixels.

scale

A re-scaling of the output to resize window better.

...

Additional arguments passed to png(), pdf(), or jpeg().

Value

The file argument, invisibly.

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:

Functions

  • close_figure(): Closes the currently active plotting device with a dev.off() call if a file name is passed. If file = NULL, nothing happens. This function is typically used in conjunction with figure() 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

png(), pdf(), dev.off()

Other base R: plotPolygon()

Author

Stu Field

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")
}