Python Matplotlib:将Y轴居中于0
我做了一个函数来描绘经济表现,但产出在y轴上往往是不平衡的 下图显示了问题所在。y值的范围使图表默认为最大/最小值作为y轴的范围 有没有办法强制图表将其自身居中于0,或者我是否需要在函数中导出最大和最小y值 函数如下所示。如果你想让我用值替换变量来重新调整图表lmk,那就有点麻烦了Python Matplotlib:将Y轴居中于0,python,matplotlib,yaxis,Python,Matplotlib,Yaxis,我做了一个函数来描绘经济表现,但产出在y轴上往往是不平衡的 下图显示了问题所在。y值的范围使图表默认为最大/最小值作为y轴的范围 有没有办法强制图表将其自身居中于0,或者我是否需要在函数中导出最大和最小y值 函数如下所示。如果你想让我用值替换变量来重新调整图表lmk,那就有点麻烦了 def recession_comparison(key, variable, dimension): ''' Creates the "scary chart"- propor
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,颜色为“黑色”,线宽为0.8,alpha=0.5,ls='--',标签为“衰退前基线”)之后添加以下代码。:
请参见添加的图像。这并没有达到我们预期的效果。@CJH我更新了我的答案。试试看out@CJH更新后的解决方案有效吗?我只是想澄清一下,您是希望y轴以x轴“0”为中心,还是希望x轴以y轴“0”为中心,或者两者兼而有之,现在我明白您的意思了。我将编辑我的答案以备将来参考。这个问题对。。。看起来不像。我不想移动脊椎或刻度,我希望水平0线始终位于图表的中心。
yabs_max = abs(max(ax.get_ylim(), key=abs))
ax.set_ylim(ymin=-yabs_max, ymax=yabs_max)