如何临时更改matplotlib设置?

2024-03-29 13:43:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我通常先设置rcParams,然后再绘制任何设置fontsize, figuresize和其他设置,以更好地满足我的需要。但是对于某些axesfigure我想更改一些设置。例如,假设我在默认设置中设置fontsize=20 一个插入我添加到一个轴,我想改变所有字体大小为12。最简单的方法是什么?目前我正在调整不同的文字字体大小,即标签字体大小,勾标签字体大小等手工! 有没有可能这样做

Some plotting here with fontsize=20

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

Resume plotting with fontsize=20

Tags: 方法herewith绘制some标签plottingfigure
2条回答

我不确定是否可以临时更改设置,但您可以只更改单个绘图的设置,然后将其更改回默认值:

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()

Matplotlib为rc参数提供了context manager。例如

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()

enter image description here

相关问题 更多 >