2017-04-05 327 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

好的。慢慢来,谢谢你的回复。 –