Sometimes we make plotting functions that alter graphical parameters, par
. For instance if I want to combine base and grid I need to do some magic that alters par
. Now I want to allow users to plot with such a function and not have the side effects in the next call to the same function. For example the following function if pressed twice results in the following two images each time:
library(ggplot2); library(grid); library(gridBase)
plotter <- function(){
#invisible(try(dev.off()))
layout(matrix(c(1, 2), nrow = 1, byrow = TRUE))
#Draw base plot
plot.new()
graphics::par(mar=c(1, 1, 1, 1), new = TRUE)
plot(1:10)
#Draw ggplot
plot.new()
vps <- baseViewports()
print( ggplot(mtcars, aes(mpg, hp)) + geom_point(), vp = vpStack(vps$figure,vps$plot))
}
plotter()
plotter()
Notice the smushed ggplot the second go round. Now I could fix this by uncommenting out the line invisible(try(dev.off()))
. But...when I then want to plot to an external device the call to pdf
for example below, gets turned off. How can I restart the interactive device safely, or some other answer as I may be asking the wrong question.
pdf("test.pdf")
plotter()
dev.off()
I tried adding .pardefault <- par(no.readonly = T)
at the beginning of the function call and par(.pardefault)
at the end via: https://stackoverflow.com/a/9292673/1000343 but this does not work. This answer https://stackoverflow.com/a/5790430/1000343 does not work either.
Perhaps there's a way to use dev.cur
against a list of internal plot devices to recognize if the plot device is RStudio or windows or such and only restart in those cases.