[英]How to align the bar and line in matplotlib two y-axes chart?
我有一個熊貓df如下:
>>> df
sales net_pft sales_gr net_pft_gr
STK_ID RPT_Date
600809 20120331 22.1401 4.9253 0.1824 -0.0268
20120630 38.1565 7.8684 0.3181 0.1947
20120930 52.5098 12.4338 0.4735 0.7573
20121231 64.7876 13.2731 0.4435 0.7005
20130331 27.9517 7.5182 0.2625 0.5264
20130630 40.6460 9.8572 0.0652 0.2528
20130930 53.0501 11.8605 0.0103 -0.0461
然后df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)
創建條形圖。
並且df[['sales_gr','net_pft_gr']].plot(kind='line', use_index=True)
創建折線圖:
現在我想使用twinx()將它們放在兩個y軸的圖表中。
import matplotlib.pyplot as plt
fig = plt.figure()
ax = df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)
ax2 = ax.twinx()
ax2.plot(df[['sales_gr','net_pft_gr']].values, linestyle='-', marker='o', linewidth=2.0)
結果是這樣的:
我的問題是:
只需將最后一行更改為:
ax2.plot(ax.get_xticks(),
df[['sales_gr','net_pft_gr']].values,
linestyle='-',
marker='o', linewidth=2.0)
你將全力以赴。
我不太明白你的第二個問題。 第一和第二y軸具有不同的比例,將它們對齊到同一條線是什么意思? 它們不能與同一網格線對齊(是的,你可以,但右軸看起來很丑,有0.687等值)。 無論如何,你可以這樣做:
ax.set_ylim((-10, 80.))
對齊它們,情節現在看起來很難看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.