Skip to content

Commit e1ad189

Browse files
committed
ggsave(): restore previous device. Fixes #2363
1 parent 7b5c185 commit e1ad189

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,9 @@ up correct aspect ratio, and draws a graticule.
253253
* `ggsave()`'s DPI argument now supports 3 string options: "retina" (320
254254
DPI), "print" (300 DPI), and "screen" (72 DPI) (@foo-bar-baz-qux, #2156).
255255

256+
* `ggsave()` now correctly restores the previous graphics device when several
257+
graphics devices are open. (#2363)
258+
256259
* `print.ggplot()` now returns the original ggplot object, instead of the
257260
output from `ggplot_build()`. Also, the object returned from
258261
`ggplot_build()` now has the class `"ggplot_built"`. (#2034)

R/save.r

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,12 @@ ggsave <- function(filename, plot = last_plot(),
5353
if (!is.null(path)) {
5454
filename <- file.path(path, filename)
5555
}
56+
old_dev <- dev.cur()
5657
dev(file = filename, width = dim[1], height = dim[2], ...)
57-
on.exit(utils::capture.output(grDevices::dev.off()))
58+
on.exit(utils::capture.output({
59+
grDevices::dev.off()
60+
dev.set(old_dev)
61+
}))
5862
grid.draw(plot)
5963

6064
invisible()

tests/testthat/test-ggsave.R

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,26 @@ test_that("ggsave creates file", {
1111
expect_true(file.exists(path))
1212
})
1313

14+
test_that("ggsave restores previous graphics device", {
15+
# When multiple devices are open, dev.off() restores the next one in the list,
16+
# not the previously-active one. (#2363)
17+
path <- tempfile()
18+
on.exit(unlink(path))
19+
20+
png()
21+
png()
22+
on.exit({
23+
dev.off()
24+
dev.off()
25+
}, add = TRUE)
26+
27+
old_dev <- dev.cur()
28+
p <- ggplot(mpg, aes(displ, hwy)) + geom_point()
29+
ggsave(path, p, device = "png", width = 5, height = 5)
30+
31+
expect_identical(old_dev, dev.cur())
32+
})
33+
1434

1535
# plot_dim ---------------------------------------------------------------
1636

0 commit comments

Comments
 (0)