微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

R - 有没有办法像在 python 中使用“with”语句那样在 R 中临时设置上下文特定的绘图参数?

如何解决R - 有没有办法像在 python 中使用“with”语句那样在 R 中临时设置上下文特定的绘图参数?

在 Python 中,您可以使用 with 语句设置上下文特定(即临时更改)绘图参数,如下所示。
问题 2 :在 R 中也可以这样做吗?

我当前的代码

# save default parameters
defop = options()

# sunction to set plot parameters
plot_pars = function(w=7,h=7) {options(repr.plot.width=w,repr.plot.height=h)}

# set plot size
plot_pars(10,4)

# generate Boxplot
Boxplot(Outstate ~ Elite,data=college,horizontal=T,col=5:6,xlab="Elite",ylab="Outstate tuition (USD)")

# reset parameters
options(defop)

每次更改绘图参数时,我都必须重置它们。必须有办法避免这种情况。

enter image description here

问题 2: 是否有类似于 Python 中 with功能/设备?

Python 代码

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import requests

## import data
url = "https://statlearning.com/College.csv"  # ISLR repository
df = pd.read_csv(url)
## generate Boxplot with specified dimensions
with plt.rc_context():
    plt.figure(figsize=(10,3))
    sns.Boxplot(y='Private',x='Outstate',data=df);
# Boxplot generated with specified dimensions

enter image description here

## generate Boxplot normally
sns.Boxplot(y='Private',data=df);
# Boxplot generated with default dimensions
# defaults were not changed as the plt.figure() was
# within 'with' container

enter image description here

解决方法

1) withr包中的with_par可以临时设置那些在par中可设置的经典图形参数在范围内和范围外自动设置回来.

2) 您也可以在完成后重新设置参数(不需要任何软件包):

opar <- par(...whatever...)
# plotting commands
par(opar)

要在函数中使用它,一种可能性是将 par(opar) 放在 on.exit 中,以便在退出时自动重置参数。

f <- function() {
  on.exit(par(opar))

  opar <- par(...whatever...)
  # plotting commands
}
,

您可以为此编写一个基本的辅助函数。在这里,我们编写了一个通用包装函数,该函数将返回一个函数,该函数将使用您喜欢的任何选项评估您的代码,然后将它们重置。我们可以为宽度和高度值制作一个特殊的帮助器。

with_options <- function(...) {
  function(code) {
    orig <- options()
    on.exit(options(orig))
    options(...)
    force(code)
  }
}
with_repr_size <- function(w=7,h=8) 
  with_options(repr.plot.width=w,repr.plot.height=h)

然后你可以用它来做类似的事情

#sample data
set.seed(10)
college <- data.frame(
  Elite = runif(100) < .4,Outstate = rnorm(100,1200,200)
)

with_repr_size(w=10,h=4)({
  boxplot(Outstate ~ Elite,data=college,horizontal=T,col=5:6,xlab="Elite",ylab="Outstate tuition (USD)");
  print(options("repr.plot.height"))   # for testing
})
print(options("repr.plot.height"))     # for testing

这类似于 withr::with_options 之类的函数,如果您更喜欢使用包中的代码而不是编写自己的代码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。