簡體   English   中英

用次要y軸繪制熊貓圖的barplot:在x軸上未對齊

[英]pandas plotting barplot with secondary y-axis: misaligned on the x-axis

我正在嘗試使用pandas DataFrame繪制帶有輔助y軸的條形圖。 但是,返回的圖形在x軸上未對齊,如下所示

在此處輸入圖片說明

換句話說,黑色曲線的x = 1似乎與小節圖的x = 2相對應。 有一個簡單的解決辦法嗎? 數據框具有以下值:

在此處輸入圖片說明

生成圖的代碼如下所示:

values = np.array([[ 5.8,  3.5,  0.7, 32.2],
       [ 4.8,  4.7,  0.5, 23.5],
       [ 4.8,  4.7,  0.5, 23.1],
       [ 4.6,  5.1,  0.3, 23.6],
       [ 4.4,  5.2,  0.5, 22.1]])

pdata = pd.DataFrame(values,index=[1,2,3,4,5],columns=['a1', 'a2', 'a3', 'pie'])

fig,ax = plt.subplots(figsize=(5,3))
axp = ax.twinx()

pdata[['a1','a2','a3']].plot(ax=ax,kind='bar',stacked=True,rot=0)
pdata['pie'].plot(ax=axp,color='k',rot=0)
axp.set_ylim([0,100])
ax.set_ylim([0,10])

ax.legend(loc=2)  
axp.legend(loc=1)
ax.set_ylabel('value')
axp.set_ylabel('pie')

df.plot(kind='bar')對於range(len(df))繪制條形圖,並用df.index標記刻度df.index 由於您的索引為1,2,3,4,5 ,因此您會看到線圖已移動。

一種解決方法是手動繪制pie

fig,ax = plt.subplots(figsize=(5,3))
axp = ax.twinx()

pdata[['a1','a2','a3']].plot(ax=ax,kind='bar',stacked=True,rot=0)

# note the difference
axp.plot(range(len(pdata)), pdata['pie'], color='k')

axp.set_ylim([0,100])
ax.set_ylim([0,10])

ax.legend(loc=2)  
axp.legend(loc=1)
ax.set_ylabel('value')
axp.set_ylabel('pie')

輸出:

在此處輸入圖片說明

暫無
暫無

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

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