Matplotlib:以 0 为中心的 Y 轴

问题描述

我制作了一个函数来绘制经济表现,但输出通常在 y 轴上是不平衡的。

下图显示了问题。 y 值的范围使图表认为最大值/最小值作为 y 轴的范围。

enter image description here

有什么方法可以强制图表以 0 为中心,还是我需要在函数内导出最大和最小 y 值?

功能如下。如果您希望我用值替换变量以重现图表 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,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,dimension):
    fig,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

更正后的图像:

enter image description here

解决方法

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)