2017-04-05 112 views
1

一個圖在大熊貓計數操作之後,我有以下數據框:兩個次要情節在在熊貓

Cancer     No Yes 
AgeGroups Factor     
0-5  w-statin  108  0 
      wo-statin 6575 223 
11-15  w-statin  5  1 
      wo-statin 3669 143 
16-20  w-statin  28  1 
      wo-statin 6174 395 
21-25  w-statin  80  2 
      wo-statin 8173 624 
26-30  w-statin  110  2 
      wo-statin 9143 968 
30-35  w-statin  171  5 
      wo-statin 9046 1225 
35-40  w-statin  338 21 
      wo-statin 8883 1475 
41-45  w-statin  782 65 
      wo-statin 11155 2533 

我有我的條形圖的一個問題。隨着代碼:

ax = counts.plot(kind='bar',stacked=True,colormap='Paired',rot = 45) 

for p in ax.patches: 
     ax.annotate(np.round(p.get_height(),decimals=0).astype(np.int64), (p.get_x()+p.get_width()/2., p.get_y()), ha='center', va='center', xytext=(2, 10), textcoords='offset points', fontsize=10) 

得到我: enter image description here

我的目標是實現有兩個不同的因素(W-他汀/ WO-他汀類藥物)與agegroups作爲我的X軸的兩個不同的次要情節。它應該大致看起來像這樣: enter image description here

我希望提供任何幫助。非常感謝。所有的

回答

1
by_factor = counts.groupby(level='Factor') 

k = by_factor.ngroups 

fig, axes = plt.subplots(1, k, sharex=True, sharey=False, figsize=(15, 8)) 
for i, (gname, grp) in enumerate(by_factor): 
    grp.xs(gname, level='Factor').plot.bar(
     stacked=True, colormap='Paired', rot=45, ax=axes[i], title=gname) 
fig.tight_layout() 

enter image description here

+0

首先感謝您piRSquared的回答。乍一看,我想,我明白了。你能否向我解釋'k'和'by_factor'的參數?非常感謝你的時間和幫助。 –

+1

@Araceraceae很高興你問...我沒有粘貼所有的代碼...我真的應該睡一覺。將編輯帖子。 – piRSquared

+0

好的。慢慢來,謝謝你的回覆。 –