Pandas: 如何绘制两个类别和四个系列的条形图?

Pandas: how to draw a bar plot with two categories and four series each?

我有以下数据框,其中 pd.concat 已用于对列进行分组:

    a               b            
   C1  C2  C3  C4  C5  C6  C7  C8
0  15  37  17  10   8  11  19  86
1  39  84  11   5   5  13   9  11
2  10  20  30  51  74  62  56  58
3  88   2   1   3   9   6   0  17
4  17  17  32  24  91  45  63  48

现在我想绘制一个条形图,其中我只有两个类别(ab),每个类别有四个条代表每列的平均值。 C1 和 C5 列应具有相同的颜色,C2 和 C6 列也应具有相同的颜色,依此类推。

如何使用 df.plot.bar()?

情节应该类似于下图。很抱歉它是 hand-drawn 但我很难找到相关的例子:

编辑

这是我实际 DataFrame 的 header:

    C1  C2  C3  C4  C5  C6  C7  C8
0   34  34  34  34  6   40  13  26
1   19  19  19  19  5   27  12  15
2   100 100 100 100 0   0   0   0
3   0   0   0   0   0   0   0   0
4   100 100 100 100 0   0   0   0

尝试seaborn

import seaborn as sns
import pandas as pd

def r(df):
    return df.loc[df.name].reset_index(drop=True)

data = df.mean().groupby(level=0).apply(r) \
         .rename_axis(['grp', 'cat']).reset_index(name='mu')

ax = sns.barplot(x='grp', y='mu', hue='cat', data=data)

ax.legend_.remove()
for i, p in enumerate(ax.patches):
    height = p.get_height()
    ax.text(p.get_x() + .05, height + 1, df.columns.levels[1][i])

您可以在计算 DFmean 后简单地执行 unstack 来渲染条形图。

import seaborn as sns
sns.set_style('white')

#color=0.75(grey)
df.mean().unstack().plot.bar(color=list('rbg')+['0.75'], rot=0, figsize=(8,8)) 


数据:(根据编辑的post)

df

通过根据列的选择(此处为 4)重复标签来创建额外的列,从而准备多索引 DF

df_multi_col = df.T.reset_index()
df_multi_col['labels'] = np.concatenate((np.repeat('A', 4), np.repeat('B', 4)))
df_multi_col.set_index(['labels', 'index'], inplace=True)
df_multi_col

df_multi_col.mean(1).unstack().plot.bar(color=list('rbg')+['0.75'], rot=0, figsize=(6,6), width=2)