[英]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)
. 我想绘制一个按
(Q)
和(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)
I would like something like this: 我想要这样的东西:
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: 输出:
IIUC: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.