如何在matplotlib中的pandas条形图上添加一行?
发布时间:2020-12-20 11:35:40 所属栏目:Python 来源:网络整理
导读:嗨我已设法在条形图中添加一条线,但位置不对.我想在每个栏的正中间做点.有人可以帮忙吗? df price cost net0 22.5 -20.737486 1.3643601 35.5 -19.285862 16.6958472 13.5 -20.456378 -9.0160523 5.0 -19.643776 -17.5396364 13.5 -27.015138 -15.9645975 5
嗨我已设法在条形图中添加一条线,但位置不对.我想在每个栏的正中间做点.有人可以帮忙吗?
>>> 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使用的实际底层坐标不完全对应. 为了解决这个问题,您可以: In [3]: ax = df[['price','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'],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’]). 这给了我: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |