Skip to contents

This function is a wrapper around ggsave from the ggplot2 package that allows you to write a ggplot object as part of a knitr document as an output for later use. It is designed to be used in a code block. The file name, if not specified, will be the label of the code block.

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.

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