python - 如何在 matplotlib 中的 Pandas 条形图上添加一条线?

标签 python matplotlib plot pandas

您好,我已经设法在条形图中添加了一条线,但是位置不对。我想把点放在每个小节的中间。谁能帮忙?

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

最佳答案

更新:这将在即将发布的 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'] )

这给了我:

enter image description here

关于python - 如何在 matplotlib 中的 Pandas 条形图上添加一条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23909249/

相关文章:

r - R 中的标注文本

python - pandas 时间戳 - dateoffset 的错误结果

python - 如何让plotly python在打开html时不自动下载图表?

python - Matplotlib 箭袋绘图,箭头大小不变

r - 如何将 x 轴刻度设置为月末?

r - 在 R 中添加子图标签

python - 确保 aiohttp/asyncio 中递归函数的 future

java - 是否有与 Java 的 FixedThreadPool 等效的 Python 库?

python - 如何使最后一个标记在 matplotlib 轴子图中不可见?

python - 如何将绘制在不同图形上的图像保存到matplotlib中的不同位置?