Pandas中单个图中的两个子图

时间:2017-04-05 10:06:55

标签: python pandas

在Pandas进行计数操作后,我有以下数据框:

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-statin / wo-statin)实现两个不同的子图,其中年龄组为我的x轴。它应该看起来像这样: enter image description here

感谢您提供的任何帮助。非常感谢。

1 个答案:

答案 0 :(得分: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

相关问题