Acerace.py
Acerace.py

Reputation: 719

Two subplots Within a Single Plot in Pandas

After a count operation in Pandas, I have the following dataframe:

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

I am having a problem with my barchart. With the code:

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)

yielded me: enter image description here

My target is to achieve two different subplots with two different factors (w-statin/wo-statin) with agegroups as my x-axis. It should approximately look like this: enter image description here

I would appreciate any help provided. Thank you so much.

Upvotes: 1

Views: 111

Answers (1)

piRSquared
piRSquared

Reputation: 294218

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

Upvotes: 1

Related Questions