简体   繁体   English

如何临时更改 matplotlib 设置?

[英]How to change matplotlib settings temporarily?

I usually set rcParams before plotting anything setting fontsize, figuresize and other settings to better suit my needs.我通常在绘制任何设置fontsize, figuresize大小、图形大小和其他设置以更好地满足我的需要之前设置rcParams However for a certain axes or figure I would like to change some part of the settings.但是对于某些axesfigure ,我想更改某些设置。 For example say I set fontsize = 20 in defaults, and for an inset I add to an axes I would like to change all fontsize to 12. What's the easiest way to achieve it?例如,假设我在默认值中设置了 fontsize = 20,并且对于我添加到轴的插图,我想将所有字体大小更改为 12。实现它的最简单方法是什么? Currently I am tweaking fontsize of different text ie label font size, tick label font size etc. by hand!目前我正在手动调整不同文本的字体大小,即 label 字体大小,勾选 label 字体大小等! Is it possible to do something like是否可以做类似的事情

Some plotting here with fontsize=20

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

Resume plotting with fontsize=20

Matplotlib provides a context manager for rc Parameters rc_context() . Matplotlib 为 rc 参数rc_context()提供了一个上下文管理器 Eg例如

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

在此处输入图像描述

I am not sure if it is possible to change the settings just temporarily, but you could just change the settings for a single plot and afterwards just change them back to the defaults:我不确定是否可以临时更改设置,但您可以更改单个 plot 的设置,然后将它们更改回默认值:

import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)

Or if you want to use the same settings for multiple plots you could just define a function to change them to your specific configuration and then just change them back:或者,如果您想对多个绘图使用相同的设置,您可以定义一个 function 将它们更改为您的特定配置,然后将它们改回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM