如何使用R中的dev.off()有条不紊地管理图形设备

时间:2017-04-25 17:51:43

标签: r plot

背景:

我经常使用CentipedeBody调用我的绘图函数。但是,因为每个绘图功能都有自己的source设置,所以在运行第一个绘图功能后,为了在我的图形设备中正确显示下一个连续的绘图功能,我运行par(...) 下面,我展示了当我使用伪R代码在3个不同的R文件中编写3个绘图函数时我到底做了什么。

问题:

我想知道在运行第一个绘图功能后,如何避免多次运行dev.off() 来运行每个绘图功能?

dev.off()

1 个答案:

答案 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