You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Seaborn绘制聚类分组对应的消费占比堆叠条形图

聚类用户品类消费占比堆叠条形图实现方案

前置说明

数据集已包含以下字段:

  • 各品类消费占比字段:Wines%、Fruits%、Meat%、Fish%、Sweets%、Gold%,所有占比之和为1
  • 聚类分群字段:Clusters

已完成的数据预处理代码如下:

df_test = df[['Wines%', 'Fruits%', 'Meat%', 'Fish%', 'Sweets%','Gold%', 'Clusters']]
df_unpivoted = df_test.melt(id_vars=['Clusters'], var_name='Category', value_name='Spend%')
df_unpivoted.head()
df_new = pd.pivot_table(df_unpivoted, index=['Clusters','Category'])

绘图实现代码

Seaborn没有原生的堆叠条形图接口,我们可以配合Matplotlib、结合Pandas绘图能力实现,代码如下:

import seaborn as sns
import matplotlib.pyplot as plt

# 将多级索引的预处理结果转为聚类为行、品类为列的宽表
df_plot = df_new['Spend%'].unstack()

# 设置Seaborn绘图风格
sns.set_style("whitegrid")

# 绘制堆叠条形图,使用Seaborn配色
ax = df_plot.plot(
    kind='bar', 
    stacked=True, 
    colormap=sns.color_palette("husl", n_colors=len(df_plot.columns)),
    figsize=(10, 6)
)

# 配置图表标注
plt.xlabel('聚类分组', fontsize=12)
plt.ylabel('消费占比', fontsize=12)
plt.title('不同聚类用户的品类消费占比分布', fontsize=14)
plt.legend(title='消费品类', bbox_to_anchor=(1.02, 1), loc='upper left')

# 调整布局避免图例截断
plt.tight_layout()
plt.show()

效果说明

最终输出的堆叠条形图x轴为聚类分组,每个柱子的不同颜色分段对应各品类的消费占比,可直观对比不同聚类用户的消费结构差异。

内容的提问来源于stack exchange,提问作者ShridharK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:15:07