5
$\begingroup$

Normally when I draw bar plot its simple as

import matplotlib.pyplot as plt
from pylab import rcParams
import seaborn as sb

%matplotlib inline
rcParams['figure.figsize'] = 5, 4
sb.set_style('whitegrid')

x = range(1, 10)
y = [1,2,3,4,0.5,4,3,2,1]

plt.bar(x, y)

When I aggregate data on basis of age feature with the following command

data_ag = data.groupby('age')['age'].count()

It returns the output that is the people belonging to a particular age e.g. 11 people with age 22 years.

age
22     11
23      8
27     28
28      1
29     70
30     13
31     45
Name: age, dtype: int64

How can I treat those as x and y points to draw a bar plot?

x = # what should I write here for age data
y = # what for count 

plt.bar(x, y)
$\endgroup$
0

2 Answers 2

5
$\begingroup$
import pandas as pd

df = pd.Series(data=[11, 8, 28, 1, 70, 13, 45],
               index=[22, 23, 27, 28, 29, 30, 31],
               name="age").rename_axis("age", axis=0)

x = df.index
y = df.values

plt.bar(x, y)

enter image description here

$\endgroup$
2
  • $\begingroup$ I had a different type of data (returned by aggregate function) not a Series data.. Thanks anyways. $\endgroup$
    – Mutafaf
    Apr 3, 2018 at 11:34
  • 3
    $\begingroup$ @MutafafWahhaj, what makes you think what you were working with was not a Series? $\endgroup$
    – Stephen Rauch
    Apr 3, 2018 at 12:20
2
$\begingroup$

I solved my issue using size() and reset_index() functions.

g1 = data.groupby( ["age"] ).size().reset_index(name='count')

x= g1['count']
y=g1['age']

plt.bar(x, y)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.