Skip to content

Instantly share code, notes, and snippets.

@SchmidtPaul
Last active April 4, 2022 13:43
Show Gist options
  • Save SchmidtPaul/9c6302a3567687c06c871ca6ee4a00bf to your computer and use it in GitHub Desktop.
Save SchmidtPaul/9c6302a3567687c06c871ca6ee4a00bf to your computer and use it in GitHub Desktop.
It's basically ggsave() with some addons
# This function exports plots. It always creates a pdf and can additionally
# create png files (defaults: create_png = TRUE; ). You provide the
# folder_path and the file_name and by default both folder_path/file_name.pdf
# and folder_path/file_name.png will be created.
#
# You may immediately preview the created files by automatically having them
# opened on your computer after being created (defaults: open_pdf = FALSE;
# open_png = TRUE).
#
# The pdf is exported via ggplot2::ggsave(), but the png is not! Instead,
# the png is actually created by reimporting the exported pdf and exporting
# it via png::writePNG(). This hack is supposed to ensure having the same scales
# and (font) sizes in both files.
# if necessary: install necessary packages
if (!require("png")) install.packages("png")
if (!require("ggplot2")) install.packages("ggplot2")
if (!require("pdftools")) install.packages("pdftools")
if (!require("ggplotify")) install.packages("ggplotify")
gg_export <-
function(plot_obj = NULL,
folder_path = NULL,
file_name = NULL,
width_cm = 16,
height_cm = 10,
create_pdf = FALSE,
create_png = TRUE,
open_pdf = FALSE,
open_png = TRUE
) {
# for a manually curated list of non-ggplot2 plot types,
# the object is converted to make things work:
others <- c(
"trellis" # {desplot}
)
if (class(plot_obj)[1] %in% others) {
plot_obj <- ggplotify::as.ggplot(plot_obj)
}
# export pdf
pdf_path <- paste0(folder_path, "/", file_name, ".pdf")
ggplot2::ggsave(
filename = pdf_path,
plot = plot_obj,
width = width_cm,
height = height_cm,
units = "cm",
scale = 1,
device = cairo_pdf
)
# export png
if (create_png) {
png_path <- paste0(folder_path, "/", file_name, ".png")
bitmap <- pdftools::pdf_render_page(pdf_path, page = 1, dpi = 300)
png::writePNG(bitmap, png_path)
}
if (!create_pdf) {
file.remove(pdf_path)
}
# open pdf
if (open_pdf) {
system(paste0('open "', pdf_path, '"'))
}
# open png
if (open_png) {
system(paste0('open "', png_path, '"'))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment