>>> 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.0 -24.267836 -22.6188196 18.0 -21.096404 -7.3576847 5.0 -24.691966 -24.1161068 5.0 -25.755958 -22.0803299 25.0 -26.352161 -2.781588fig = 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中的默认条形图,第一个矩形(标签为0的第一个条形)将绘制在0到0.8的x坐标上(条形宽度为0.8).因此,如果你想在这个中间绘制一个点或线,那么x坐标应该是0.4,而不是0!
为了解决这个问题,您可以:
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.5In [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’]).
这给了我:
总结以上是内存溢出为你收集整理的如何在matplotlib中的pandas条形图上添加一行?全部内容,希望文章能够帮你解决如何在matplotlib中的pandas条形图上添加一行?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)