python - 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
解决方案
1) with_par
在withr包中可以临时设置那些par
在一个范围内可设置的经典图形参数,在范围外自动设置回去。
2)您也可以在完成后重新设置参数(不需要包):
opar <- par(...whatever...)
# plotting commands
par(opar)
要在函数中使用它,一种可能性是par(opar)
在on.exit
退出时自动重置参数。
f <- function() {
on.exit(par(opar))
opar <- par(...whatever...)
# plotting commands
}
推荐阅读
- java - 如何在 Java Swing 中的 while 循环迭代后等待
- powershell - 尝试在目录中查找以 4 个数字开头的所有文件,并将这 4 个数字插入到文本文件中
- c++ - 是否可以在不暴露派生密钥(使用 TPM)的情况下从共享密钥 (BCryptSecretAgreement) 派生密钥?
- python - Python:根据名称移动目录
- mysql - 如何在 python 中将数据添加到我的数据库中?
- ios - UIView 子类中的 UIButton 未触发
- cordova - Cordova:在模拟器上运行时未加载 CSS 字体
- c# - 如何使用 C# 和 DLL 制作可移植的 .EXE?
- java - Java / iText 多页 Tiff 到 PDF ByteArrayOutputStream VS 文件
- python - 如何使用 pandas 删除不需要的数据?