简体   繁体   中英

How to change matplotlib settings temporarily?

I usually set rcParams before plotting anything setting fontsize, figuresize and other settings to better suit my needs. However for a certain axes or figure I would like to change some part of the settings. 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? Currently I am tweaking fontsize of different text ie label font size, tick label font size etc. by hand! 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() . 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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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