zin*_*gsy 5 python plot matplotlib histogram pandas
我有一个数据框,其中有多列成对:如果一列是值,则相邻列是相应的计数。我想使用值作为x变量并计数作为频率来绘制直方图。
例如,我有以下列:
Age Counts
60 1204
45 700
21 400
. .
. .
34 56
10 150
Run Code Online (Sandbox Code Playgroud)
我希望我的代码将Age
最大值和最小值之间十年间隔的值进行分类,并从列中获取每个间隔的累积频率,Counts
然后绘制直方图。有没有办法使用 matplotlib 来做到这一点?
我尝试了以下方法但没有成功:
patient_dets.plot(x='PatientAge', y='PatientAgecounts', kind='hist')
Run Code Online (Sandbox Code Playgroud)
( Patient_dets 是以 'PatientAge' 和 'PatientAgecounts' 作为列的数据框)
我认为你需要Series.plot.bar
:
patient_dets.set_index('PatientAge')['PatientAgecounts'].plot.bar()
Run Code Online (Sandbox Code Playgroud)
如果需要垃圾箱,一种可能的解决方案是pd.cut
:
#helper df with min and max ages
df1 = pd.DataFrame({'G':['14 yo and younger','15-19','20-24','25-29','30-34',
'35-39','40-44','45-49','50-54','55-59','60-64','65+'],
'Min':[0, 15,20,25,30,35,40,45,50,55,60,65],
'Max':[14,19,24,29,34,39,44,49,54,59,64,120]})
print (df1)
G Max Min
0 14 yo and younger 14 0
1 15-19 19 15
2 20-24 24 20
3 25-29 29 25
4 30-34 34 30
5 35-39 39 35
6 40-44 44 40
7 45-49 49 45
8 50-54 54 50
9 55-59 59 55
10 60-64 64 60
11 65+ 120 65
cutoff = np.hstack([np.array(df1.Min[0]), df1.Max.values])
labels = df1.G.values
patient_dets['Groups'] = pd.cut(patient_dets.PatientAge, bins=cutoff, labels=labels, right=True, include_lowest=True)
print (patient_dets)
PatientAge PatientAgecounts Groups
0 60 1204 60-64
1 45 700 45-49
2 21 400 20-24
3 34 56 30-34
4 10 150 14 yo and younger
patient_dets.groupby(['PatientAge','Groups'])['PatientAgecounts'].sum().plot.bar()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11920 次 |
最近记录: |