pandas :如何绘制一个分别包含两个类别和四个系列的条形图? [英] Pandas: how to draw a bar plot with two categories and four series each?

查看:92
本文介绍了 pandas :如何绘制一个分别包含两个类别和四个系列的条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following dataframe, where pd.concat has been used to group the columns:

    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的颜色相同,依此类推.

Now I want to draw a bar plot where I only have two categories (a and b), and each category has four bars representing the average of each column. Columns C1 and C5 should have the same color, as should columns C2 and C6, and so forth.

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

How can I do it with df.plot.bar()?

该图应类似于下图.很抱歉,它是手绘的,但是我很难找到一个相关的例子:

The plot should resemble the following image. Sorry for it being hand-drawn but it was very hard for me to find a relevant example:

编辑

这是我实际的DataFrame的标题:

This is the header of my actual DataFrame:

    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

推荐答案

您可以在计算DFmean以呈现条形图之后,简单地执行unstack.

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

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

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)

这篇关于 pandas :如何绘制一个分别包含两个类别和四个系列的条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆