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/3] 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/3] 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) From ada4759aa970f33f09c625ff5ee92b6fff1da7ed Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 25 Mar 2025 09:52:14 +0100 Subject: [PATCH 3/3] add news bullet --- NEWS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NEWS.md b/NEWS.md index 67d35b9878..b9b3fa8b45 100644 --- a/NEWS.md +++ b/NEWS.md @@ -310,6 +310,8 @@ (@teunbrand, #3669). * Added `scale_{x/y}_time(date_breaks, date_minor_breaks, date_labels)` (@teunbrand, #4335). +* `ggsave()` can write a multi-page pdf file when provided with a list of plots + (@teunbrand, #5093). # ggplot2 3.5.1