htmltools (version 0.5.0)

capturePlot: Capture a plot as a saved file

Description

Easily generates a .png file (or other graphics file) from a plotting expression.

Usage

capturePlot(
  expr,
  filename = tempfile(fileext = ".png"),
  device = defaultPngDevice(),
  width = 400,
  height = 400,
  res = 72,
  ...
)

Arguments

expr

A plotting expression that generates a plot (or yields an object that generates a plot when printed, like a ggplot2). We evaluate this expression after activating the graphics device (device).

filename

The output filename. By default, a temp file with .png extension will be used; you should provide a filename with a different extension if you provide a non-PNG graphics device function.

device

A graphics device function; by default, this will be either grDevices::png(), ragg::agg_png(), or Cairo::CairoPNG(), depending on your system and configuration. See defaultPngDevice().

width, height, res, ...

Additional arguments to the device function.

See Also

plotTag() saves plots as a self-contained <img> tag.

Examples

Run this code
# NOT RUN {
# Default settings
res <- capturePlot(plot(cars))

if (interactive()) browseURL(res)

# Use custom width/height
pngpath <- tempfile(fileext = ".png")
capturePlot(plot(pressure), pngpath, width = 800, height = 375)

if (interactive()) browseURL(pngpath)

# Use SVG
svgpath <- capturePlot(
  plot(pressure),
  tempfile(fileext = ".svg"),
  grDevices::svg,
  width = 8, height = 3.75)

if (interactive()) browseURL(svgpath)

# Clean up
unlink(res)
unlink(pngpath)
unlink(svgpath)

# }

Run the code above in your browser using DataLab