From b682c8a24da37855584e390e1b0fe8168cc6d70d Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Fri, 15 Nov 2024 16:45:26 +0100 Subject: [PATCH 1/2] allow saving pages --- R/save.R | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/R/save.R b/R/save.R index b06c567b2e..177cb71fe0 100644 --- a/R/save.R +++ b/R/save.R @@ -102,7 +102,7 @@ ggsave <- function(filename, plot = get_last_plot(), dim <- plot_dim(c(width, height), scale = scale, units = units, limitsize = limitsize, dpi = dpi) - if (is_null(bg)) { + if (is_null(bg) && is.ggplot(plot)) { bg <- calc_element("plot.background", plot_theme(plot))$fill %||% "transparent" } old_dev <- grDevices::dev.cur() @@ -111,7 +111,10 @@ ggsave <- function(filename, plot = get_last_plot(), grDevices::dev.off() if (old_dev > 1) grDevices::dev.set(old_dev) # restore old device unless null device })) - grid.draw(plot) + if (!is_bare_list(plot)) { + plot <- list(plot) + } + lapply(plot, grid.draw) invisible(filename) } From 8aadf30280247d22f3ae3980f318cff27863fdd3 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Mon, 27 Jan 2025 16:51:29 +0100 Subject: [PATCH 2/2] helper to deal with background --- R/save.R | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/R/save.R b/R/save.R index 198fec660f..523f2ef29b 100644 --- a/R/save.R +++ b/R/save.R @@ -101,10 +101,8 @@ ggsave <- function(filename, plot = get_last_plot(), dev <- validate_device(device, filename, dpi = dpi) dim <- plot_dim(c(width, height), scale = scale, units = units, limitsize = limitsize, dpi = dpi) + bg <- get_plot_background(plot, bg) - if (is_null(bg) && is.ggplot(plot)) { - bg <- calc_element("plot.background", plot_theme(plot))$fill %||% "transparent" - } old_dev <- grDevices::dev.cur() dev(filename = filename, width = dim[1], height = dim[2], bg = bg, ...) on.exit(utils::capture.output({ @@ -238,6 +236,17 @@ plot_dim <- function(dim = c(NA, NA), scale = 1, units = "in", dim } +get_plot_background <- function(plot, bg = NULL, default = "transparent") { + if (!is.null(bg)) { + return(bg) + } + plot <- if (is_bare_list(plot)) plot[[1]] else plot + if (!is.ggplot(plot)) { + return(default) + } + calc_element("plot.background", plot_theme(plot))$fill %||% default +} + validate_device <- function(device, filename = NULL, dpi = 300, call = caller_env()) { force(filename) force(dpi)