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

joe*_*lom 13 python matplotlib pandas seaborn

pandas和中seaborn,可以使用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"))
Run Code Online (Sandbox Code Playgroud)

日期:

60
10
60
Run Code Online (Sandbox Code Playgroud)

当我同样尝试with mpl.rcdefaults():或者with mpl.rc('lines', linewidth=2, color='r'):,我收到AttributeError: __exit__.

有没有办法临时更改matplotlib中的rcParams,以便它们只适用于选定的代码子集,还是我必须手动来回切换?

Max*_*Noe 18

是的,使用样式表.

请参阅: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])
Run Code Online (Sandbox Code Playgroud)

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

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

对于单一选项,也有 plt.rc_context

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


mwa*_*kom 14

是的,该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])
Run Code Online (Sandbox Code Playgroud)