首页 > 解决方案 > Python pandas 绘制移动secondary_yaxis(kind='line')

问题描述

我正在尝试解决以前报告过的绘图问题,在 pandas 绘图 (.plot()) 中使用辅助 y 轴。

这是我当前的代码:

根据所附图片,tfig 是 Pandas DataFrame: tfig 快照


Title = 'Transport Results'

xlabels = ['Period 1 (2023 - 2026)','Period 2 (2027 - 2032)','Period 3 (2033 - 2038)','Period 4 (2039 - 2044)','Period 5 (2045 - 2050)']

fig, ax = plt.subplots() 

ax1 = tfig[['Ship 6k', 'Ship 30k','Ship 40k','Pipe6','Pipe18','Pipe18']].plot(kind='bar',figsize=(10,6),stacked= False, color=['lightblue','deepskyblue','cyan','grey','k','darkblue'], ax=ax)

ax2 = tfig[['Trip - Ship 6k','Trip - Ship 30k','Trip - Ship 40k']].plot(stacked = True, color=['lightblue','deepskyblue','cyan'], ax=ax, secondary_y = True )

xlabels_new = [label.replace(' (', ' \n(') for label in xlabels]
ax.set_xticklabels(xlabels_new, rotation='horizontal')
ax1.set_ylim(0,12)
ax1.legend(ncol=3,loc='upper left')
ax2.legend()
ax2.set_ylim(0,1200)

plt.title(Title, fontsize=12)
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']
plt.rcParams['font.size'] = 10

plt.savefig('test2.png', format='png')

结果图如下。理想情况下,辅助 y 轴应从“周期 1”而不是“周期 2”开始。

关于如何修复此代码以相应地绘制它的任何想法?

谢谢你的帮助

Test2.png 绘图

标签: pythonpandasplot

解决方案


推荐阅读