Skip to content

Commit ef00be7

Browse files
authored
Handle filename better in ggsave() (#5116)
1 parent d9f179b commit ef00be7

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# ggplot2 (development version)
22

3+
* `ggsave()` warns when multiple `filename`s are given, and only writes to the
4+
first file (@teunbrand, #5114).
35
* Fixed a regression in `geom_hex()` where aesthetics were replicated across
46
bins (@thomasp85, #5037 and #5044)
57
* Fixed spurious warning when `weight` aesthetic was used in `stat_smooth()`

R/save.r

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,17 @@ ggsave <- function(filename, plot = last_plot(),
7777
device = NULL, path = NULL, scale = 1,
7878
width = NA, height = NA, units = c("in", "cm", "mm", "px"),
7979
dpi = 300, limitsize = TRUE, bg = NULL, ...) {
80+
if (length(filename) != 1) {
81+
if (length(filename) == 0) {
82+
cli::cli_abort("{.arg filename} cannot be empty.")
83+
}
84+
len <- length(filename)
85+
filename <- filename[1]
86+
cli::cli_warn(c(
87+
"{.arg filename} must have length 1, not length {len}.",
88+
"!" = "Only the first, {.file {filename}}, will be used."
89+
))
90+
}
8091

8192
dpi <- parse_dpi(dpi)
8293
dev <- plot_dev(device, filename, dpi = dpi)

tests/testthat/test-ggsave.R

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,21 @@ test_that("ggsave can handle blank background", {
5656
expect_true(grepl("fill: none", bg))
5757
})
5858

59+
test_that("ggsave warns about empty or multiple filenames", {
60+
filenames <- c("plot1.png", "plot2.png")
61+
plot <- ggplot(mtcars, aes(disp, mpg)) + geom_point()
62+
63+
withr::with_file(filenames, {
64+
expect_warning(
65+
suppressMessages(ggsave(filenames, plot)),
66+
"`filename` must have length 1"
67+
)
68+
expect_error(
69+
ggsave(character(), plot),
70+
"`filename` cannot be empty."
71+
)
72+
})
73+
})
5974

6075
# plot_dim ---------------------------------------------------------------
6176

0 commit comments

Comments
 (0)