简体   繁体   中英

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?

You need cut for create range s 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))

图形

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))

图形

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM