【问题标题】:Bar graph plot with values on top python条形图与顶部 python 上的值
【发布时间】:2016-11-16 16:39:25
【问题描述】:

我的 pandas df 中有一张桌子。

    Total_orders    frequency
      0.0           18679137
      1.0           360235
      2.0           68214
      3.0           20512
      4.0           7211
      ...           ...
      50.0          12

我想绘制一个总订单与频率的条形图,频率值显示在每个条形的顶部。

我正在运行这三个代码。

代码1:

plt.figure(figsize=(12,6))
df2 = df.groupby('Total_orders')['frequency'].plot(kind='bar')
plt.xlabel('Total_orders')
plt.ylabel('frequency')

for rect in df2.patches:
    height = rect.get_height()
    df2.text(rect.get_x() + rect.get_width()/2., 1.05*height+100,
'%d' % int(height),ha='center', va='bottom', rotation=90)

代码2:(for循环)

for ii,rect in enumerate(df2.patches):
    height = rect.get_height()
    df2.text(rect.get_x() + rect.get_width()/2., 1.14*height+100,'%d' % int(height),ha='center', va='bottom', rotation=90)

代码3

for p in df2.patches:
df2.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() *1.05),rotation=90)

但是当我运行代码时它显示错误,

AttributeError: 'Series' 对象没有属性 'patches'

知道为什么会发生这种情况,以及如何删除它吗?

【问题讨论】:

  • 看起来您正在访问 Series 对象 (df2?) 并尝试迭代其 patches,但 Series 对象没有 patches 属性。您必须找到一种方法来访问具有您想要迭代的patches 的任何对象。

标签: python python-3.x python-2.7 pandas matplotlib


【解决方案1】:

试试这个:

def autolabel(rects, height_factor=1.05):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., height_factor*height,
                '%d' % int(height),
                ha='center', va='bottom')


In [48]: df
Out[48]:
   Total_orders  frequency
0           0.0   18679137
1           1.0     360235
2           2.0      68214
3           3.0      20512
4           4.0       7211
5          50.0         12

In [49]: import matplotlib

In [50]: matplotlib.style.use('ggplot')

In [51]: ax = df.plot.bar(x='Total_orders', y='frequency', rot=0, width=0.85, alpha=0.6, figsize=(14,12))

In [52]: autolabel(ax.patches, 1.02)

【讨论】:

  • 我可以增加值的高度吗,我的意思是它非常接近 x 轴,如图所示。我希望它向上一点(大约 0.5 厘米),这样我的情节看起来不错。
  • @SRingne,确定只是将height_factor 参数设置得更高
  • 确实做到了,将其进一步增加到 5,也做到了 height_factor*height+100 但没有变化
猜你喜欢
  • 2017-03-25
  • 1970-01-01
  • 2014-09-21
  • 2022-01-23
  • 1970-01-01
  • 2019-04-03
  • 2021-12-05
  • 2017-06-04
  • 2022-07-06
相关资源
最近更新 更多