背景:
我经常使用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%')发布于 2017-04-25 18:09:42
一种解决方案可能是存储原始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() #Whitehttps://stackoverflow.com/questions/43617721
复制相似问题