Skip to contents

A wrapper around ggsave that facilitates saving ggplot objects within knitr documents. Automatically handles file naming and directory creation, with support for multiple output formats.

Usage

write_gg(
  gg_obj = NULL,
  file = NULL,
  target_dir = NULL,
  device = "pdf",
  theme = NULL,
  ...
)

Arguments

gg_obj

The ggplot to be written. If not specified, the last ggplot created will be written.

file

The name of the file to be written. If not specified, the label of the code block will be used.

target_dir

The directory where the file will be written. If not specified, the current working directory will be used.

device

The device to be used for saving the ggplot. Options include "pdf" (default), "png", "jpeg", "tiff", and "svg".

theme

The ggplot2 theme to be applied to the ggplot. Default is the theme specified in the ggplot2 options.

...

Additional arguments to be passed to the ggsave function from the ggplot2 package.

Value

The path of the written file.

Details

This function extends ggplot2::ggsave by:

  • Using knitr code block labels for automatic file naming

  • Creating target directories if they don't exist

  • Supporting multiple output formats (PDF, PNG, JPEG, TIFF, SVG)

  • Applying custom themes to plots before saving

Examples

if (FALSE) { # \dontrun{
library(ggplot2)

plot_dir <- file.path(tempdir(), "plot")

# Write a ggplot object as a PDF file
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point()

write_gg(
  gg_obj = p,
  file = "plot_file",
  target_dir = plot_dir,
  device = "pdf"
)

unlink(plot_dir)
} # }