[英]how to plot specific columns of data frame with different range in one plot (Maybe using sub-plot?)
[英]How to plot pie chart using data frame group by different range?
我的代码是:
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)
文件patient1.csv包含以下数据:
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
实际上,我想绘制0-17,18-59,60 +年龄患者的饼图。 从代码中,您可以看到我已经在不同的年龄范围内分离了数据框。 我需要在代码中添加什么来绘制饼图?
首先需要cut
创建range
。 然后groupby
,聚合size
并重新unstack
。
上次使用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))
编辑:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.