首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在R中使用dev.off()有条件、高效地管理图形设备

如何在R中使用dev.off()有条件、高效地管理图形设备
EN

Stack Overflow用户
提问于 2017-04-25 17:51:42
回答 1查看 120关注 0票数 1

背景:

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

问题:

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

代码语言:javascript
运行
复制
### 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%')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-25 18:09:42

一种解决方案可能是存储原始par设置,根据需要在函数中更改它,并使用函数退出代码(on.exit())在函数末尾恢复它。

代码语言:javascript
运行
复制
#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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43617721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档