计算每色相堆积条的图

count plot with stacked bars per hue

我正在寻找一种根据 "hue" 绘制带堆叠条形计数图的有效方法。 标准色调行为是根据第二列的值将计数拆分为平行条,我正在寻找的是一种有效的方式来堆叠色调条以便快速比较总数。

让我用泰坦尼克号数据集中的一个例子来解释一下:

import pandas as pd
import numpy as np
import seaborn as sns
%matplotlib inline

df = sns.load_dataset('titanic')
sns.countplot(x='survived',hue='class',data=df)

使用计数图和色调给出标准的 Seaborn 行为

我正在寻找的是类似每个色调的堆叠条

为了得到最后一张图片我使用了下面的代码

def aggregate(rows,columns,df):
    column_keys = df[columns].unique()
    row_keys = df[rows].unique()

    agg = { key : [ len(df[(df[rows]==value) & (df[columns]==key)]) for value in row_keys]
               for key in column_keys }

    aggdf = pd.DataFrame(agg,index = row_keys)
    aggdf.index.rename(rows,inplace=True)

    return aggdf

aggregate('survived','class',df).plot(kind='bar',stacked=True)

我确信有一些更有效的方法。 我知道 seaborn 不是很友好的堆叠条...所以我尝试用我的函数重新排列数据集并使用 matplotlib,但我想还有一个更聪明的方法来做到这一点。

非常感谢!

你基本上完成了最后一部分,将 DataFrame.plot()barstacked=True 结合使用。

您可以使用 groupby + pivot 来完成您想要的,而不是您的 aggregate 函数。

df_plot = df.groupby(['class', 'survived']).size().reset_index().pivot(columns='class', index='survived', values=0)

class     First  Second  Third
survived                      
0            80      97    372
1           136      87    119

从这里您可以将其绘制为带有 stacked=True 参数的 bar

df_plot.plot(kind='bar', stacked=True)