2

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? Thanks in advance.

Shubham R
  • 7,382
  • 18
  • 53
  • 119
  • Why do you think your df2 should have an attribute `patches`? In your code you completely miss the part of plotting the data. There are some examples([here](http://matplotlib.org/examples/pylab_examples/barchart_demo.html) and [here](http://matplotlib.org/examples/pylab_examples/barchart_demo2.html)) how to draw barplots. Also [this question](http://stackoverflow.com/questions/28931224/adding-value-labels-on-a-matplotlib-bar-chart) has been asked before here. [Here](http://stackoverflow.com/questions/7423445/how-can-i-display-text-over-columns-in-a-bar-chart-in-matplotlib) is another solution. – ImportanceOfBeingErnest Nov 16 '16 at 17:21
  • in your code df2 doesn't have any column called patches, but your still trying to get column called `patches` from df2 – Mr. A Nov 17 '16 at 08:37

1 Answers1

0

Possible solution is the following:

# pip install pandas
# pip install matplotlib

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# set test data and create dataframe
data = {'Total_orders': [1,2,3,4,5,6,7,8,9,10], 'frequency': [2,3,4,5,6,7,8,10,11,12]}
df = pd.DataFrame(data)

# set plot fugure size
plt.rcParams["figure.figsize"] = [9,5]

fig, ax = plt.subplots()
rects = ax.bar(df['Total_orders'], df['frequency'], color='r', label='frequency')

ax.set_xlabel('Orders')
ax.set_ylabel('Frequency')
ax.set_title('Frequency per orders')
ax.set_xticks(df['Total_orders'])
ax.legend(loc=2)

# add values on top
ax.bar_label(rects, padding=3)

fig.tight_layout()
plt.show()

Returns

enter image description here

gremur
  • 1,645
  • 2
  • 7
  • 20