背景:
我经常使用CentipedeBody
调用我的绘图函数。但是,因为每个绘图功能都有自己的source
设置,所以在运行第一个绘图功能后,为了在我的图形设备中正确显示下一个连续的绘图功能,我运行par(...)
。 下面,我展示了当我使用伪R代码在3个不同的R文件中编写3个绘图函数时我到底做了什么。
问题:
我想知道在运行第一个绘图功能后,如何避免多次运行dev.off()
来运行每个绘图功能?
dev.off()
答案 0 :(得分:1)
一种解决方案可能是存储原始par设置,根据需要在函数内更改它,并使用函数退出代码(on.exit()
)
#FUNCTIONS
myf1 = function(x = rnorm(20)){
original_par = par(no.readonly = TRUE) #store original par in original_par
on.exit(par(original_par)) #reset on exiting function
par(bg = "red") #Change par inside function as needed
plot(x)
}
myf2 = function(x = rnorm(20)){
original_par = par(no.readonly = TRUE)
on.exit(par(original_par))
plot(x, type = "l")
}
#USAGE
par(bg = "green") #Let's start by setting green background
myf1() #this has red background
myf2() #But this has green like in the start
par(bg = "pink") #Let's repeat with pink
myf1() #Red
myf2() #Pink
dev.off() #Let's reset par
myf1() #Red
myf2() #White