簡體   English   中英

如何臨時更改 matplotlib 設置?

[英]How to change matplotlib settings temporarily?

我通常在繪制任何設置fontsize, figuresize大小、圖形大小和其他設置以更好地滿足我的需要之前設置rcParams 但是對於某些axesfigure ,我想更改某些設置。 例如,假設我在默認值中設置了 fontsize = 20,並且對於我添加到軸的插圖,我想將所有字體大小更改為 12。實現它的最簡單方法是什么? 目前我正在手動調整不同文本的字體大小,即 label 字體大小,勾選 label 字體大小等! 是否可以做類似的事情

Some plotting here with fontsize=20

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

Resume plotting with fontsize=20

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

在此處輸入圖像描述

我不確定是否可以臨時更改設置,但您可以更改單個 plot 的設置,然后將它們更改回默認值:

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

或者,如果您想對多個繪圖使用相同的設置,您可以定義一個 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