有没有一个上下文管理器可以临时更改matplotlib设置?

23

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中的rcParams,以便它们仅适用于所选择的代码子集,还是我必须手动来回切换?

2个回答

29
是的,可以使用样式表。
请参考:https://matplotlib.org/stable/tutorials/introductory/customizing.html

e.g.:

# 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])

18

是的,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])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接