2017-04-25 9 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 
を使用して関数の最後でそれを復元するかもしれません
関連する問題