如何临时更改Matplotlib设置?

4

通常我会在绘图之前设置rcParams,设置fontsize、figuresize和其他参数以更好地满足我的需求。但是对于某个axesfigure,我想要更改一些设置的部分内容。例如,假设我在默认中设置了fontsize = 20,并且对于添加到axes中的插图,我想将所有fontsize更改为12。最简单的方法是什么?目前,我在手动调整不同文本的 fontsize,即标签字体大小、刻度标签字体大小等! 是否有可能做到像下面这样:

Some plotting here with fontsize=20

with fontsize=12 :
    inset.plot(x,y)
    Set various labels and stuff

Resume plotting with fontsize=20

2个回答

14

Matplotlib 提供了一个上下文管理器 context manager,用于 rc 参数 rc_context()。例如:

from matplotlib import pyplot as plt

rc1 = {"font.size" : 16}
rc2 = {"font.size" : 8}

plt.rcParams.update(rc1)

fig, ax = plt.subplots()

with plt.rc_context(rc2):
    axins = ax.inset_axes([0.6, 0.6, 0.37, 0.37])

plt.show()

在此输入图像描述


正是我所需要的!非常感谢。 - Navdeep Rana

1
我不确定是否可以临时更改设置,但您可以仅更改单个图的设置,然后将其更改回默认设置:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)

如果您想在多个图中使用相同的设置,可以定义一个函数将它们更改为特定配置,然后再将其更改回来:

def fancy_plot(ax, tick_formatter=mpl.ticker.ScalarFormatter()):
    """
    Some function to store your unique configuration
    """
    mpl.rcParams['figure.figsize'] = (16.0, 12.0)
    mpl.style.use('ggplot')
    mpl.rcParams.update({'font.size': fontsize})
    ax.spines['bottom'].set_color('black')
    ax.spines['top'].set_color('black') 
    ax.spines['right'].set_color('black')
    ax.spines['left'].set_color('black')
    ax.set_facecolor((1,1,1))
    ax.yaxis.set_major_formatter(tick_formatter)
    ax.xaxis.set_major_formatter(tick_formatter)

def mpl_default():
    """
    Some function to srestore default values
    """
    mpl.rcParams.update(mpl.rcParamsDefault)
    plt.style.use('default')

fig, ax = plt.subplots()
fancy_plot(ax)
fig.plot(x,y)
fig.show()

mpl_default()

fig, ax = plt.subplots()
fig.plot(some_other_x,some_other_y)
fig.show()

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