[英]How to add a line on a pandas bar plot in matplotlib?
嗨我已設法在條形圖中添加一條線,但位置不對。 我想在每個欄的正中間做點。 有人可以幫忙嗎?
>>> df
price cost net
0 22.5 -20.737486 1.364360
1 35.5 -19.285862 16.695847
2 13.5 -20.456378 -9.016052
3 5.0 -19.643776 -17.539636
4 13.5 -27.015138 -15.964597
5 5.0 -24.267836 -22.618819
6 18.0 -21.096404 -7.357684
7 5.0 -24.691966 -24.116106
8 5.0 -25.755958 -22.080329
9 25.0 -26.352161 -2.781588
fig = plt.figure()
df[['price','cost']].plot(kind = 'bar',stacked = True,color = ['grey','navy'])
df['net'].plot('o',color = 'orange',linewidth=2.0,use_index = True)
更新:這將在即將發布的0.14版本中修復(上面的代碼將正常工作),對於較舊的pandas版本,我的答案可以用作解決方法。
您遇到的問題是您在條形圖上看到的xaxis標簽與matplotlib使用的實際底層坐標不完全對應。
例如,使用matplotlib中的默認bar
,第一個矩形(標簽為0的第一個條形)將繪制在0到0.8的x坐標上(條形寬度為0.8)。 因此,如果你想在這個中間繪制一個點或線,那么x坐標應該是0.4,而不是 0!
為了解決這個問題,您可以:
In [3]: ax = df[['price','cost']].plot(kind = 'bar',stacked = True,color = ['grey','navy'])
In [4]: ax.get_children()[3]
Out[4]: <matplotlib.patches.Rectangle at 0x16f2aba8>
In [5]: ax.get_children()[3].get_width()
Out[5]: 0.5
In [6]: ax.get_children()[3].get_bbox()
Out[6]: Bbox('array([[ 0.25, 0. ],\n [ 0.75, 22.5 ]])')
In [7]: plt.plot(df.index+0.5, df['net'],color = 'orange',linewidth=2.0)
我執行ax.get_children()[3].get_width()
和.get_bbox()
來檢查繪圖中條形圖的實際寬度和坐標,因為pandas似乎沒有使用matplotlib的默認值(值0.5實際上來自0.25(從y軸偏移到開始第一個條)+ 0.5 / 2(寬度的一半))。
所以我實際上做的是將df['net'].plot(use_index = True)
更改為plt.plot(df.index + 0.5, df['net'])
。
這給了我:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.