我有一個bizzare問題。我有一個看起來像下面的數據框。它已從csv文件中讀取。x軸標籤不按正確順序排列(matplotlib/pandas)
AgeGroups Factor Cancer Frequency
0 0_5 wo-statin Yes 0
1 6_10 wo-statin Yes 0
2 11_15 wo-statin Yes 1
3 16_20 wo-statin Yes 1
4 21_25 wo-statin Yes 23
5 26_30 wo-statin Yes 50
6 31_35 wo-statin Yes 70
7 36_40 wo-statin Yes 107
8 41_45 wo-statin Yes 168
9 46_50 wo-statin Yes 412
10 51_55 wo-statin Yes 503
11 56_60 wo-statin Yes 646
12 61_65 wo-statin Yes 635
13 66_70 wo-statin Yes 725
14 71_75 wo-statin Yes 771
15 76_80 wo-statin Yes 421
16 81_85 wo-statin Yes 181
17 86_90 wo-statin Yes 57
18 91_95 wo-statin Yes 4
19 96_100 wo-statin Yes 4
..
60 0_5 w-statin Yes 0
61 6_10 w-statin Yes 0
62 11_15 w-statin Yes 0
63 16_20 w-statin Yes 0
64 21_25 w-statin Yes 0
65 26_30 w-statin Yes 0
66 31_35 w-statin Yes 0
67 36_40 w-statin Yes 0
68 41_45 w-statin Yes 0
69 46_50 w-statin Yes 10
70 51_55 w-statin Yes 17
71 56_60 w-statin Yes 24
72 61_65 w-statin Yes 50
73 66_70 w-statin Yes 113
74 71_75 w-statin Yes 198
75 76_80 w-statin Yes 105
76 81_85 w-statin Yes 37
77 86_90 w-statin Yes 18
78 91_95 w-statin Yes 2
79 96_100 w-statin Yes 0
我想開展從我從下面的代碼得到了條形圖一些統計分析:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('file:///C:/Users/out.CSV')
ages= df.AgeGroups.unique()
grp = df.groupby(['AgeGroups','Factor','Cancer']).Frequency.sum()
counts = grp.unstack(level=[2])
by_factor = counts.groupby(level='Factor')
k = by_factor.ngroups
fig, axes = plt.subplots(1, k, sharex=True, sharey=True, figsize=(15, 8))
for i, (gname, grp) in enumerate(by_factor):
grp.xs(gname, level='Factor').plot.bar(
stacked=True, rot=45, ax=axes[i], title=gname)
_ = axes.set_xticklabels(grp['AgeGroups'])
#for ax in axes: ax.set_ylim([0,25000])
fig.tight_layout()
我幾乎很高興一切順利出去,直到我意識到年齡組我的情節上的6_10出現在情節的中間。
如果我手動更改實例0_5的表格爲00-05和6_10爲06-10等,則該圖表顯示正確的順序。然而,對我來說問題是,我有大約2k這樣的CSV,並且幾乎不可能手動編輯每個表的順序。 如果需要,我可以提供更多信息,非常感謝您的幫助。 :)
是它永遠只有兩個值' 「0_5」'和' 「6_10」'會引起問題的?還是還有其他價值觀,需要進行調整? – ImportanceOfBeingErnest
@ImportanceOfBeingErnest,非常感謝你的回覆。這個問題似乎只與他們在一起。如果我將它們排除在外,Plot看起來很好。 –