Skip to content

Commit 5fe3c2a

Browse files
authored
Allow saving PDF pages (#6187)
* allow saving pages * helper to deal with background * add news bullet
1 parent a641f5d commit 5fe3c2a

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

NEWS.md

+2
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,8 @@
310310
(@teunbrand, #3669).
311311
* Added `scale_{x/y}_time(date_breaks, date_minor_breaks, date_labels)`
312312
(@teunbrand, #4335).
313+
* `ggsave()` can write a multi-page pdf file when provided with a list of plots
314+
(@teunbrand, #5093).
313315

314316
# ggplot2 3.5.1
315317

R/save.R

+16-4
Original file line numberDiff line numberDiff line change
@@ -101,17 +101,18 @@ ggsave <- function(filename, plot = get_last_plot(),
101101
dev <- validate_device(device, filename, dpi = dpi)
102102
dim <- plot_dim(c(width, height), scale = scale, units = units,
103103
limitsize = limitsize, dpi = dpi)
104+
bg <- get_plot_background(plot, bg)
104105

105-
if (is_null(bg)) {
106-
bg <- calc_element("plot.background", plot_theme(plot))$fill %||% "transparent"
107-
}
108106
old_dev <- grDevices::dev.cur()
109107
dev(filename = filename, width = dim[1], height = dim[2], bg = bg, ...)
110108
on.exit(utils::capture.output({
111109
grDevices::dev.off()
112110
if (old_dev > 1) grDevices::dev.set(old_dev) # restore old device unless null device
113111
}))
114-
grid.draw(plot)
112+
if (!is_bare_list(plot)) {
113+
plot <- list(plot)
114+
}
115+
lapply(plot, grid.draw)
115116

116117
invisible(filename)
117118
}
@@ -235,6 +236,17 @@ plot_dim <- function(dim = c(NA, NA), scale = 1, units = "in",
235236
dim
236237
}
237238

239+
get_plot_background <- function(plot, bg = NULL, default = "transparent") {
240+
if (!is.null(bg)) {
241+
return(bg)
242+
}
243+
plot <- if (is_bare_list(plot)) plot[[1]] else plot
244+
if (!is.ggplot(plot)) {
245+
return(default)
246+
}
247+
calc_element("plot.background", plot_theme(plot))$fill %||% default
248+
}
249+
238250
validate_device <- function(device, filename = NULL, dpi = 300, call = caller_env()) {
239251
force(filename)
240252
force(dpi)

0 commit comments

Comments
 (0)