簡體   English   中英

Matplotlib:中心 Y 軸在 0

[英]Matplotlib: center Y-axis on 0

我已經制作了 function 來繪制經濟性能圖表,但 output 通常在 y 軸上不平衡。

下圖顯示了問題。 y 值的范圍使圖表默認以最大值/最小值作為 y 軸的范圍。

在此處輸入圖像描述

有什么方法可以強制圖表以 0 為中心,還是我需要在 function 中導出最大值和最小值?

function 如下。 如果您希望我用值替換變量以重現圖表 lmk - 這是一項艱巨的任務。

def recession_comparison(key, variable, dimension):
    '''
    Creates the "scary chart"- proportional growth for a single area/industry. All recessions included in chart.

        Parameters: 
            key (str or int): area-fips or industry_code
            variable (str): determines what economic indicator will be used in the timeline. Must be one of ['month3_emplvl' (employment), 'avg_wkly_wage' (wages), 'qtrly_estabs_count'(firms)]
            dimension (str): dimension of data to chart.
            
        Returns: 
            fig (matplotlib plot)
    '''
    fig, ax = plt.subplots(figsize =(15, 10))
    if dimension == 'area':
        index = 'area_fips'
        title = 'Recession Comparison, ' + area_titles[key] + " (" + str(key) + ")" 
    elif dimension == 'industry':
        index = 'industry_code'
        title = 'Recession Comparison: ' + industry_titles[key] + " (" + str(key) + ")" 
    for recession in recessions_int.keys():
        if recession == 'full':
            break
        loadpath = filepath(variable = variable, dimension = dimension, charttype = 'proportional', recession = recession, filetype = 'json')
        df = pd.read_json(loadpath)
        df.set_index(index, inplace = True)
        ax.plot(df.loc[key][1:-1]*100, label = str(recession), linewidth = 1.5, alpha = 0.8)
    ax.axvline(x = 6, color = 'black', linewidth = 0.8, alpha = 0.5, ls = ':', label = 'Event Quarter')
    ax.axhline(y = 0, color = 'black', linewidth = 0.8, alpha = 0.5, ls = '--', label = 'Pre-Recession baseline')
    ax.set_xlabel('Quarters since start of recession')
    ax.set_ylabel('Growth: ' + var_display[variable])
    ax.set_title(title)
    ax.yaxis.set_major_formatter(mtick.PercentFormatter())
    plt.legend()
    plt.show()
    return fig

編輯:來自 DapperDuck 的完整代碼解決方案:

def recession_comparison(key, variable, dimension):
    fig, ax = plt.subplots(figsize =(15, 10))
    if dimension == 'area':
        index = 'area_fips'
        title = 'Recession Comparison, ' + area_titles[key] + " (" + str(key) + ")" 
    elif dimension == 'industry':
        index = 'industry_code'
        title = 'Recession Comparison: ' + industry_titles[key] + " (" + str(key) + ")" 
    for recession in recessions_int.keys():
        if recession == 'full':
            break
        loadpath = filepath(variable = variable, dimension = dimension, charttype = 'proportional', recession = recession, filetype = 'json')
        df = pd.read_json(loadpath)
        df.set_index(index, inplace = True)
        ax.plot(df.loc[key][1:-1]*100, label = str(recession), linewidth = 1.5, alpha = 0.8)
    ax.axvline(x = 6, color = 'black', linewidth = 0.8, alpha = 0.5, ls = ':', label = 'Event Quarter')
    ax.axhline(y = 0, color = 'black', linewidth = 0.8, alpha = 0.5, ls = '--', label = 'Pre-Recession baseline')
    yabs_max = abs(max(ax.get_ylim(), key=abs))
    ax.set_ylim(ymin=-yabs_max, ymax=yabs_max)
    ax.set_xlabel('Quarters since start of recession')
    ax.set_ylabel('Growth: ' + var_display[variable])
    ax.set_title(title)
    ax.yaxis.set_major_formatter(mtick.PercentFormatter())
    plt.legend()
    plt.show()
    return fig

修正后的圖像: 在此處輸入圖像描述

ax.axhline(y = 0, color = 'black', linewidth = 0.8, alpha = 0.5, ls = '--', label = 'Pre-Recession baseline')之后添加以下代碼:

yabs_max = abs(max(ax.get_ylim(), key=abs))
ax.set_ylim(ymin=-yabs_max, ymax=yabs_max)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM