Reputation:
I have a table in my pandas df.
Total_orders frequency
0.0 18679137
1.0 360235
2.0 68214
3.0 20512
4.0 7211
... ...
50.0 12
I want to plot a bar graph total orders vs frequency, with the values of frequency displayed on the top of each bars.
I am running these three codes.
Code1:
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)
but when I am running the code it's showing me error, that
AttributeError: 'Series' object has no attribute 'patches'
Any idea why this is happening, and how to remove it?
Upvotes: 0
Views: 934
Reputation: 210852
Try this:
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)
Upvotes: 2