Skip to contents

Save a ggplot object to file using ragg for font-correct rendering when available, falling back to ggsave otherwise. Automatically matches the plot background to the active theme.

Usage

save_plot(
  filename,
  plot = NULL,
  width = 7,
  height = 5,
  dpi = 300,
  bg = NULL,
  device = NULL,
  ...
)

Arguments

filename

Character. Output file path. The file extension determines the device: .png, .pdf, .svg, .tiff, or .jpg/.jpeg.

plot

A ggplot2 plot object. If NULL (default), the last ggplot created with last_plot() is used.

width

Numeric. Plot width in inches. Default is 7.

height

Numeric. Plot height in inches. Default is 5.

dpi

Numeric. Resolution in dots per inch. Default is 300.

bg

Character. Background color. If NULL (default), automatically detects the current theme's plot.background fill ("#faf9f7" for solaris, "#ffffff" for t2m, or "white" as fallback).

device

Character. Override the output device. If NULL (default), the device is inferred from filename.

...

Additional arguments passed to ggsave or the ragg device function.

Value

Invisibly returns the filename.

Examples

if (FALSE) { # \dontrun{
library(ggplot2)
ggastrum::set_theme()

p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
save_plot("myplot.png", p, width = 8, height = 6)

# Auto-detect background from current theme
save_plot("myplot.pdf", p)
} # }