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

如何在Seaborn聚类图右侧纵轴添加直方图?

给Seaborn Clustermap右侧添加直方图替代行标签

嘿,我懂你要的效果——把Seaborn clustermap右侧默认的行标签替换成展示orange、yellow、brown列数据的直方图对吧?之前用jointplot走不通很正常,因为jointplot是用来做双变量关联图的,咱们换个思路,直接用Matplotlib的子图布局来搭配clustermap就能搞定,下面是具体的实现方案:

核心思路

  1. 用Matplotlib的GridSpec创建左右布局的子图,左边留给clustermap,右边放直方图
  2. 获取clustermap的行聚类顺序,让直方图的行顺序和聚类后的行完全对齐
  3. 隐藏clustermap原有的右侧行标签,用右侧的直方图替代

完整代码示例

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

# 1. 准备你的数据集(这里用模拟数据示例,替换成你真实的数据即可)
data = pd.DataFrame({
    'feature1': [1.2, 3.1, 2.5, 4.3, 0.8],
    'feature2': [5.4, 2.2, 3.7, 1.9, 4.1],
    'feature3': [2.8, 4.5, 1.3, 3.9, 0.5],
    'orange': [12, 24, 18, 28, 9],
    'yellow': [7, 19, 13, 23, 6],
    'brown': [10, 22, 16, 26, 8]
})

# 2. 分离聚类用的特征数据和要展示的直方图数据
cluster_features = data[['feature1', 'feature2', 'feature3']]
histogram_data = data[['orange', 'yellow', 'brown']]

# 3. 创建布局:左边80%空间放clustermap,右边20%放直方图
fig = plt.figure(figsize=(11, 6))
gs = GridSpec(1, 2, width_ratios=[4, 1])

# 4. 绘制Clustermap到左侧子图
ax_clust = fig.add_subplot(gs[0])
clustermap = sns.clustermap(cluster_features, ax=ax_clust, cbar=False)
# 隐藏原有的右侧行标签和刻度
clustermap.ax_heatmap.set_yticklabels([])
clustermap.ax_heatmap.tick_params(axis='y', left=False)

# 5. 在右侧子图绘制直方图
ax_hist = fig.add_subplot(gs[1])
# 获取Clustermap聚类后的行顺序,保证直方图和聚类行对齐
row_cluster_order = clustermap.dendrogram_row.reordered_ind
# 按聚类顺序重新排列直方图数据
ordered_hist_data = histogram_data.iloc[row_cluster_order]

# 绘制水平堆叠直方图(也可以改成并列直方图,把stacked=False即可)
ordered_hist_data.plot(kind='barh', stacked=True, ax=ax_hist, legend=False)
# 调整y轴,让直方图和Clustermap的行完全对齐
ax_hist.set_yticks(range(len(row_cluster_order)))
ax_hist.set_yticklabels([])
ax_hist.invert_yaxis()  # 反转y轴,和Clustermap的行方向保持一致

# 6. 添加图例(可以调整位置避免遮挡)
ax_hist.legend(loc='upper right', bbox_to_anchor=(1.4, 1))

plt.tight_layout()
plt.show()

关键细节说明

  • 行顺序对齐:通过clustermap.dendrogram_row.reordered_ind获取聚类后的行索引,这样直方图的每一行都对应clustermap里的聚类行,不会错位
  • 布局控制:用GridSpec的width_ratios参数可以灵活调整左右区域的宽度比例,根据你的需求修改即可
  • 样式自定义:如果不想用堆叠直方图,把stacked=True改成stacked=False就能得到并列直方图;也可以通过color参数自定义各列的颜色,比如color=['orange', 'yellow', 'brown']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:23:36