簡體   English   中英

如何使用 seaborn 為分類數據繪制堆疊的 100% 條形圖

[英]How to plot stacked 100% bar plot with seaborn for categorical data

我有一個看起來像這樣的數據集(假設它在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')

在此處輸入圖片說明

有沒有辦法用seaborn(或matplotlib)而不是pandas繪圖功能來實現這一點? 我嘗試了幾種方法,包括運行 seaborn 代碼和預處理數據集,使其格式正確,但沒有運氣。

Seaborn 不支持堆疊條形圖,因此您需要繪制 cumsum:

# 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 方向,那么您就不需要反轉色調順序:

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)

輸出:

在此處輸入圖片說明

例如

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM