繁体   English   中英

是否有用于临时更改matplotlib设置的上下文管理器?

[英]Is there a context manager for temporarily changing matplotlib settings?

pandasseaborn ,可以使用with关键字临时更改显示/绘图选项,该关键字仅将指定设置应用于缩进代码,而未更改全局设置:

print(pd.get_option("display.max_rows"))

with pd.option_context("display.max_rows",10):
    print(pd.get_option("display.max_rows"))

print(pd.get_option("display.max_rows"))

出:

60
10
60

当我类似地尝试with mpl.rcdefaults():with mpl.rc('lines', linewidth=2, color='r'): ,我收到AttributeError: __exit__

有没有一种方法可以临时更改matplotlib中的rcParam,以便仅将其应用于代码的选定子集,还是我必须手动保持来回切换?

是的,使用样式表。

请参阅: http : //matplotlib.org/users/style_sheets.html

例如:

# The default parameters in Matplotlib
with plt.style.context('classic'):
    plt.plot([1, 2, 3, 4])

# Similar to ggplot from R
with plt.style.context('ggplot'):
    plt.plot([1, 2, 3, 4])

您可以轻松定义自己的样式表并使用

with plt.style.context('/path/to/stylesheet'):
    plt.plot([1, 2, 3, 4])

对于单个选项,还有plt.rc_context

with plt.rc_context({'lines.linewidth': 5}):
    plt.plot([1, 2, 3, 4])

是的, matplotlib.rc_context函数将执行您想要的操作:

import matplotlib as mpl
import matplotlib.pyplot as plt
with mpl.rc_context({"lines.linewidth": 2, "lines.color": "r"}):
    plt.plot([0, 1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM