Yash Singhvi
Yash Singhvi

Reputation: 61

How to plot pie chart using data frame group by different range?

My Code is:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style

df=pd.read_csv("patient1.csv")
a=df.loc[df.Age<18,['Age']]
print(a)
b=df.loc[(df.Age >= 18) & (df.Age < 60),['Age']]
print(b)
c=df.loc[df.Age>=60,['Age']]
print(c)
d=pd.concat([a,b,c],keys=["0-17","18-59","60+"])
e=d.loc[:,['Age']]
print(e)

The file patient1.csv contains data as:

Name    Surname Age
fdgf    bcbb    21
Yash    Singhvi 19
Yash    Singhvi 19
piyush  daga    20
cvcv    dfg     16
sdsd    sdsd    65
dsfef   fedf    12
rfef    fefe    70
fdgf    rgd     10

Actually, I want to plot pie chart of the patient of age 0-17,18-59,60+. From the code, you can see that I have separated the data frame in different ranges of age. What do I need to add to the code to plot the pie chart?

Upvotes: 6

Views: 33449

Answers (1)

jezrael
jezrael

Reputation: 862681

You need cut for create ranges first. Then groupby, aggregate size and reshape by unstack.

Last use DataFrame.plot.pie:

df['bins'] = pd.cut(df['Age'],bins=[0,17,59,120], labels=["0-17","18-59","60+"])
df = df.groupby(['Age', 'bins']).size().unstack(fill_value=0)
print (df)
bins  0-17  18-59  60+
Age                   
10       1      0    0
12       1      0    0
16       1      0    0
19       0      2    0
20       0      1    0
21       0      1    0
65       0      0    1
70       0      0    1

df.plot.pie(subplots=True,figsize=(8, 3))

graph

EDIT:

a = df.groupby('bins').size()
#a = df['bins'].value_counts()
print (a)
bins
0-17     3
18-59    4
60+      2
dtype: int64

a.plot.pie(figsize=(4,4))

graph

Upvotes: 14

Related Questions