ame*_*ian 9 python plot matplotlib pandas seaborn
我有一个如下所示的数据集(假设 中有 4 个类别Clicked,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
Run Code Online (Sandbox Code Playgroud)
这是返回该图的代码:
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')
Run Code Online (Sandbox Code Playgroud)
有没有办法用seaborn(或matplotlib)而不是pandas绘图功能来实现这一点?我尝试了几种方法,包括运行seaborn代码和预处理数据集以使其格式正确,但没有成功。
例如
tips = sns.load_dataset("tips")
sns.histplot(
data=tips,
x="size", hue="day",
multiple="fill", stat="proportion",
discrete=True, shrink=.8
)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
输出:
最好,您还可以反转 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)
Run Code Online (Sandbox Code Playgroud)
输出: