如何在matplotlib中的pandas柱状图上添加一条线?

2024-05-15 23:06:12 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我设法在条形图中添加了一行,但是位置不对。我想在每个酒吧的正中画出点。有人能帮忙吗?

>>> 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)

enter image description here


Tags: truedfnetplotfigpltpricecolor
1条回答
网友
1楼 · 发布于 2024-05-15 23:06:12

更新:这将在即将发布的0.14版本中得到修复(上面的代码也将正常工作),对于较老的pandas版本,我下面的回答可以用作解决方法。


您遇到的问题是,您在条形图上看到的xaxis标签与matplotlib使用的实际底层坐标不完全对应。
例如,使用matplotlib中的默认bar绘图,第一个矩形(标签为0的第一个条形图)将在0到0.8(条形图宽度为0.8)的x坐标上绘制。所以如果你想在中间画一个点或线,它的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'])

这给了我:

enter image description here

相关问题 更多 >