首页 > 解决方案 > R - 有没有办法使用“with”语句在 R 中临时设置特定于上下文的绘图参数,就像在 python 中所做的那样?

问题描述

with在 Python 中,您可以使用下面给出的语句设置特定于上下文(即临时更改)的绘图参数。
问题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)

每次更改绘图参数时,我都必须重置它们。必须有办法避免这种情况。 在此处输入图像描述

问题 2: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

在此处输入图像描述

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

在此处输入图像描述

标签: pythonrplotsizewith-statement

解决方案


1) with_parwithr包中可以临时设置那些par在一个范围内可设置的经典图形参数,在范围外自动设置回去。

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

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

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

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

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

推荐阅读