如何使用Seaborn绘制分类数据的堆叠100%条形图

8

我有一个数据集,长这样(假设Clicked有4个类别,head(10)只显示了2个类别):

    Rank Clicked
0   2.0 Cat4
1   2.0 Cat4
2   2.0 Cat4
3   1.0 Cat1
4   1.0 Cat4
5   2.0 Cat4
6   2.0 Cat4
7   3.0 Cat4
8   5.0 Cat4
9   5.0 Cat4

这是一段返回此图的代码:

eee = (df.groupby(['Rank','Clicked'])['Clicked'].count()/df.groupby(['Rank'])['Clicked'].count())
eee.unstack().plot.bar(stacked=True)
plt.legend(['Cat1','Cat2','Cat3','Cat4'])
plt.xlabel('Rank')

enter image description here

有没有办法使用seaborn(或者matplotlib)实现这个,而不是使用pandas绘图能力?我尝试了几种方法,包括运行seaborn代码和预处理数据集使其格式正确,但都没有成功。

1
Seaborn只是matplotlib的一个API,而pandas则使用matplotlib。pandas可以做堆叠条形图,而seaborn则不行。在Python中使用ggplot样式,这就是它们之间的样式差异。 - Trenton McKinney
1
应该是 df.groupby(['Rank'])['Clicked'].value_counts(normalize=True).unstack().plot(kind='bar', stacked=True) - Trenton McKinney
Groupby应该使用value_counts进行规范化:如何创建一个没有多级索引的groupby数据框架 - Trenton McKinney
你可以使用每个seaborn参数列表末尾的**kwargs将任何内容传递给底层的matplotlib调用。但是!我经常不得不阅读seaborn代码才能确切地弄清楚如何做到这一点,并且找到matplotlib的样式选项可能更容易。 - cphlewis
2个回答

8

e.g.

tips = sns.load_dataset("tips")
sns.histplot(
    data=tips,
    x="size", hue="day",
    multiple="fill", stat="proportion",
    discrete=True, shrink=.8
)

enter image description here


4

Seaborn不支持堆叠条形图,因此您需要绘制累积和:

# calculate the distribution of `Clicked` per `Rank`
distribution = pd.crosstab(df.Rank, df.Clicked, normalize='index')

# plot the cumsum, with reverse hue order
sns.barplot(data=distribution.cumsum(axis=1).stack().reset_index(name='Dist'),
            x='Rank', y='Dist', hue='Clicked',
            hue_order = distribution.columns[::-1],   # reverse hue order so that the taller bars got plotted first
            dodge=False)

输出:

输入图像描述

更好的方法是反转cumsum方向,这样就不需要反转hue顺序:

sns.barplot(data=distribution.iloc[:,::-1].cumsum(axis=1)       # we reverse cumsum direction here
                       .stack().reset_index(name='Dist'),
            x='Rank', y='Dist', hue='Clicked',
            hue_order=distribution.columns,                     # forward order
            dodge=False)

输出:

在此输入图片描述


我不知道为什么有人踩了你的答案...它真的很好!我有一个问题:如何给出自定义的hue_order,例如:Cat2,Cat4,Cat1,Cat3?尝试将其作为列表传递,但它不接受。 - amestrian
@Quang,有没有办法在这个图表中添加标签(不是累积的)? - PriyankaJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接