我的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)
Code2 :( for loop)
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)
CODE3
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'
知道为什么会这样,以及如何删除它?
答案 0 :(得分: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)