Belkacem Thiziri
Belkacem Thiziri

Reputation: 665

Grouped stacked bars in a plot from pandas dataframe

I have the following dataframe created in Pandas:

                     living     simulation
(Q+A) ARCII         60.247557   39.752443
      CDSSM         49.431875   50.568125
      DUET          75.205311   24.794689
      MATCHPYRAMID  62.426825   37.573175
      MVLSTM        93.288528    6.711472
(Q)   ARCII         51.508421   48.491579
      CDSSM         57.308882   42.691118
      DUET          60.374999   39.625001
      MATCHPYRAMID  55.334333   44.665667
      MVLSTM        85.297333   14.702667

I would like to plot a stacked bars grouped by (Q) and (Q+A). The following instruction gives separated bars:

ax = df.plot.bar(stacked=True, grid=True, xticks=list(), colormap=cmap1, width=0.5, legend=True)

enter image description here

I would like something like this:

enter image description here

Upvotes: 1

Views: 117

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Let's try this:

plt.figure(figsize=(15,8))
df1 = df.unstack(0).swaplevel(0,1, axis=1).loc[:,'(Q)']
x=[i for i in range(len(df1.index))]


p1 = plt.bar([i - .4 for i in x], df1['living'], width=.4, edgecolor='lightgreen', color='#1f77b4')
p2 = plt.bar([i - .4  for i in x], df1['simulation'], bottom=df1['living'], width=.4, edgecolor='lightgreen', color='#ff7f0e')

df1 = df.unstack(0).swaplevel(0,1, axis=1).loc[:,'(Q+A)']
p3 = plt.bar([i  for i in x], df1['living'], width=.4, edgecolor='k')
p4 = plt.bar([i  for i in x], df1['simulation'], bottom=df1['living'], width=.4, edgecolor='k')

plt.legend((p1,p2,p3,p4),('(Q) Living','(Q) Simulation','(Q+A) Living','(Q+A) Simulation'))

plt.xticks([i - .2 for i in x], df1.index)
plt.gcf().gca().spines['right'].set_visible(False)
plt.gcf().gca().spines['top'].set_visible(False)

Output:

enter image description here

IIUC:

fig,ax = plt.subplots(1,2, figsize=(15,8))
ax = ax.flatten()
i=0
for n,g in df.groupby(level=0):
    g.xs(n).plot.bar(stacked=True, ax=ax[i], title=n)
    i+=1

Output: enter image description here

Upvotes: 2

Related Questions