ggsave() can change active graphics device #2363
Comments
A simple fix would be saving current device and restoring it. cur_dev <- dev.cur()
ggsave("plot.png", g)
dev.set(cur_dev) To fix it inside cur_dev <- dev.cur()
dev(file = filename, width = dim[1], height = dim[2], ...)
on.exit(utils::capture.output({
grDevices::dev.off()
dev.set(cur_dev)
}))
grid.draw(plot) |
On Ubuntu 17.10, when putting the below code in an Rscript and running it from the command line, the graphics device is still changed.
It also creates an empty
as an Rscript from the command line. I therefore believe this is also closely related to #2752 .
Running this from within Rstudio does give the expected behavior. |
I'm reopening this issue, since I think I know what's going on. And I agree #2752 is likely the same problem. This code tries to save the current graphics device and then restore it once the plot is saved: Lines 57 to 62 in 79e8b45 The problem is this doesn't work when no device is currently open. When no device is open, dev.cur() returns 1. However, when dev.set() is called with an argument of 1, it opens a new device (!):
library(grDevices)
dev.off()
#> null device
#> 1
dev.list()
#> NULL
dev.cur()
#> null device
#> 1
dev.set(1)
#> null device
#> 1
dev.list()
#> pdf
#> 2 (This is documented behavior: " The solution I think is to replace line 61 in the code quoted above with: if (old_dev > 1) grDevices::dev.set(old_dev) |
I made a pull request. It would be great if somebody could test it. Install from github via: devtools::install_github("clauswilke/ggplot2@issue-2363-ggsave") |
I can confirm that the pull request @clauswilke made works for me.
|
This comment was marked as off-topic.
This comment was marked as off-topic.
This comment was marked as off-topic.
This comment was marked as off-topic.
This old issue has been automatically locked. If you believe you have found a related problem, please file a new issue (with reprex) and link to this issue. https://reprex.tidyverse.org/ |
If there is more than one graphics device open, calling
ggsave()
can change which one is active.For example, in RStudio:
In R at the terminal:
The text was updated successfully, but these errors were encountered: