Reset par () in functions

When writing a charting function in R, I would not want to change the global environment, so I include something like

op <- par() on.exit(par(op)) 

But this is less than satisfactory because it spills out warning messages (for example, "In par(op) : graphical parameter "cin" cannot be set" ), but more importantly, it is not compatible with multi-panel graphs. For example, if I had a simple function like

 pfun <- function(x) { op <- par() on.exit(par(op)) par(bg = "gray21", col = "deeppink", col.axis = "deeppink") plot(x, xaxt = "n", yaxt = "n", col = "deeppink", cex = 2, pch = 22, bg = "deeppink", col.lab = "deeppink") axis(1, col = "deeppink") axis(2, col = "deeppink") } 

it is perfect for a single plot (except for warnings), but is incompatible with multi-panel charts, for example

 par(mfrow = c(2, 2)) pfun(1:10) pfun(10:1) # overwrites the first plot rather than plotting in the second panel 

Is there a way to have the plot settings reset when exiting, as well as the ability to multi-line display?

+6
source share
1 answer

We can avoid interfering with multi-panel graphics by only saving / restoring the par elements that we change in the function. In this case, this only means saving bg , col and axis.col . It is important to avoid interfering with the graphic parameters (in particular, mfrow , mfcol and mfg ) that control the positions of the multi-positions.

 pfun <- function(x) { op <- par('bg', 'col', 'col.axis') on.exit(par(op)) par(bg = "gray21", col = "deeppink", col.axis = "deeppink") plot(x, xaxt = "n", yaxt = "n", col = "deeppink", cex = 2, pch = 22, bg = "deeppink", col.lab = "deeppink") axis(1, col = "deeppink") axis(2, col = "deeppink") } 

Or, it’s even a little more accurate to use the fact that when we set parameters with par , it invisibly returns a list of old parameter values ​​that we changed. So only the following will work beautifully:

  op <- par(bg = "gray21", col = "deeppink", col.axis = "deeppink") on.exit(par(op)) 
+4
source

Source: https://habr.com/ru/post/1015460/


All Articles