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

自作多情 提交于 2019-12-01 18:14:59

You could simply perform unstack after calculating the mean of the DF to render the bar plot.

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)) 


Data: (As per the edited post)

df

Prepare the multiindex DF by creating an extra column by repeating the labels according to the selections of columns(Here, 4).

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)

Try 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])

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!