如何在R中使用dev.off()有条件地高效管理图形设备
背景: 我经常使用如何在R中使用dev.off()有条件地高效管理图形设备,r,plot,R,Plot,背景: 我经常使用source调用绘图函数。但是,由于每个打印函数都有自己的par(…)设置,因此在运行第一个打印函数后,为了使下一个后续打印函数在图形设备中正确显示,我运行dev.off()下面,我将展示我使用伪R代码在3个不同的R文件中编写3个绘图函数时的具体操作。 问题: 我想知道如何避免在运行第一个绘图函数后多次运行dev.off()来运行每个绘图函数 ### source 3 R files each containing a plotting function that plots
source
调用绘图函数。但是,由于每个打印函数都有自己的par(…)
设置,因此在运行第一个打印函数后,为了使下一个后续打印函数在图形设备中正确显示,我运行dev.off()
下面,我将展示我使用伪R代码在3个不同的R文件中编写3个绘图函数时的具体操作。
问题:
我想知道如何避免在运行第一个绘图函数后多次运行dev.off()
来运行每个绘图函数
### source 3 R files each containing a plotting function that plots something:
#1 source("C:/file1.path/file1.name.R")
#2 source("C:/file2.path/file2.name.R")
#3 source("C:/file3.path/file3.name.R")
#1 Function in file 1: Beta (Low = '5%', High = '90%', cover = '95%')
## dev.off() # Now run this to reset the par(...) to default
#2 Function in file 2: Normal (Low = -5, High = 5, cover = '95%')
## dev.off() # Now run this to reset the par(...) to default
#3 Function in file 3: Cauchy (Low = -5, High = 5, cover = '90%')
一种解决方案可能是存储原始PAR设置,根据需要在函数中更改它,并使用函数退出代码(<代码> on(Ext)(< /代码>)< /P>”在函数的末尾恢复它。
#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