从datafram在绘图中分组堆叠的条形图

2024-09-28 19:34:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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

我想绘制一个按(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


Tags: 数据truepandasdfplot绘制axsimulation
1条回答
网友
1楼 · 发布于 2024-09-28 19:34:51

让我们试试这个:

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

相关问题 更多 >