Skip to content

Allow saving PDF pages #6187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 16 additions & 4 deletions R/save.R
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,18 @@
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)) {
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({
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)
}
Expand Down Expand Up @@ -235,6 +236,17 @@
dim
}

get_plot_background <- function(plot, bg = NULL, default = "transparent") {
if (!is.null(bg)) {
return(bg)

Check warning on line 241 in R/save.R

View check run for this annotation

Codecov / codecov/patch

R/save.R#L241

Added line #L241 was not covered by tests
}
plot <- if (is_bare_list(plot)) plot[[1]] else plot
if (!is.ggplot(plot)) {
return(default)

Check warning on line 245 in R/save.R

View check run for this annotation

Codecov / codecov/patch

R/save.R#L245

Added line #L245 was not covered by tests
}
calc_element("plot.background", plot_theme(plot))$fill %||% default
}

validate_device <- function(device, filename = NULL, dpi = 300, call = caller_env()) {
force(filename)
force(dpi)
Expand Down