将熊猫数据框中的图中的堆叠条形图分组

时间:2018-11-06 12:47:02

标签: python pandas matplotlib plot

我在熊猫中创建了以下数据框:

                     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

我想绘制按(Q)(Q+A)分组的堆叠条形图。 以下说明给出了分隔条:

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

enter image description here

我想要这样的东西:

enter image description here

1 个答案:

答案 0 :(得分:2)

让我们尝试一下:

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)

输出:

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

输出: enter image description here