首页 > 解决方案 > 使用 `with` 恢复 Matplotlib 默认样式

问题描述

我希望能够使用成语为我的 Matplotlib 绘图临时使用任意订书钉

with my_styles(style):
    # plotting code ...

并定义了

def my_styles(style='mine'):
    if style == 'mine':
        return plt.rc_context({
            "font.family": "sans-serif", 
            "mathtext.fontset": "dejavusans", 
            "font.sans-serif": ["Nunito", "Open Sans"] + plt.rcParams["font.sans-serif"],
            "text.usetex": False })
    elif style == 'another': 
        # USE - Very slow (?)
        return plt.rc_context({
            'axes.linewidth': 1.5,
            'lines.linewidth': 2.0,
            'figure.facecolor': 'white',
            'grid.linewidth': 0.0,
            'axes.grid': False,
            'axes.unicode_minus': False,
            'axes.edgecolor': 'black',
            'text.usetex': True
        })
    else:
        return plt.rc_context(plt.rc_params())

但最后一个案例并没有恢复 Matplotlib 的默认样式,而是似乎继续使用以前使用的样式。如何完全恢复 Matplotlib 的默认值,使用rc_contextand这样做的正确习惯是什么with

标签: matplotlibwith-statement

解决方案


推荐阅读