Skip to content

Handle filename better in ggsave() #5116

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 1 commit into from
Dec 25, 2022
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
@@ -1,5 +1,7 @@
# ggplot2 (development version)

* `ggsave()` warns when multiple `filename`s are given, and only writes to the
first file (@teunbrand, #5114).
* Fixed a regression in `geom_hex()` where aesthetics were replicated across
bins (@thomasp85, #5037 and #5044)
* Fixed spurious warning when `weight` aesthetic was used in `stat_smooth()`
Expand Down
11 changes: 11 additions & 0 deletions R/save.r
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,17 @@ ggsave <- function(filename, plot = last_plot(),
device = NULL, path = NULL, scale = 1,
width = NA, height = NA, units = c("in", "cm", "mm", "px"),
dpi = 300, limitsize = TRUE, bg = NULL, ...) {
if (length(filename) != 1) {
if (length(filename) == 0) {
cli::cli_abort("{.arg filename} cannot be empty.")
}
len <- length(filename)
filename <- filename[1]
cli::cli_warn(c(
"{.arg filename} must have length 1, not length {len}.",
"!" = "Only the first, {.file {filename}}, will be used."
))
}

dpi <- parse_dpi(dpi)
dev <- plot_dev(device, filename, dpi = dpi)
Expand Down
15 changes: 15 additions & 0 deletions tests/testthat/test-ggsave.R
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,21 @@ test_that("ggsave can handle blank background", {
expect_true(grepl("fill: none", bg))
})

test_that("ggsave warns about empty or multiple filenames", {
filenames <- c("plot1.png", "plot2.png")
plot <- ggplot(mtcars, aes(disp, mpg)) + geom_point()

withr::with_file(filenames, {
expect_warning(
suppressMessages(ggsave(filenames, plot)),
"`filename` must have length 1"
)
expect_error(
ggsave(character(), plot),
"`filename` cannot be empty."
)
})
})

# plot_dim ---------------------------------------------------------------

Expand Down