2017-04-25 12 views
1

背景条件和有效的奶源图形设备:如何使用dev.off()中的R

我经常使用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%') 

回答

1

一种解决方案是为存储原始面值设置,如所要求的功能内改变它,以及使用功能退出代码(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 
它在函数的结束时恢复