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

如何用自定义调色板绘制树状图?解决单颜色显示异常

热图自定义调色板仅显示单一颜色的排查与解决

核心问题分析

你遇到的问题是:自定义调色板color_list包含两种颜色(对应train_clusters["Cluster_Label"]的两个唯一值),但热图只渲染出一种颜色。大概率是颜色映射没有和聚类标签正确绑定,或者数据关联环节出现匹配偏差。

具体排查与修复步骤

1. 确认数据索引与聚类标签的匹配性

首先确保train_clusters["Sample"]和train_combined_df的索引完全匹配,没有缺失或错位:

# 检查匹配情况
mismatched_samples = set(train_clusters["Sample"]) - set(train_combined_df.index)
if mismatched_samples:
    print("存在不匹配的样本:", mismatched_samples)
else:
    print("样本索引完全匹配")

如果存在不匹配,先对齐数据:

# 过滤并对齐两个数据集的样本
train_combined_df = train_combined_df.loc[train_clusters["Sample"]]

2. 手动绑定聚类标签与调色板

默认热图的颜色映射不会自动关联你的Cluster_Label,需要创建颜色映射字典,在绘图时指定行/列的分组颜色:

import seaborn as sns
import matplotlib.pyplot as plt

# 创建聚类标签到颜色的映射字典
cluster_color_map = dict(zip(train_clusters["Cluster_Label"].unique(), color_list))

# 按热图样本顺序提取对应聚类颜色
row_colors = train_clusters.set_index("Sample").loc[train_combined_df.index, "Cluster_Label"].map(cluster_color_map)

# 绘制带聚类颜色分组的热图
plt.figure(figsize=(12,8))
sns.heatmap(train_combined_df, row_colors=row_colors, cmap="viridis")
plt.show()

这里的row_colors会在热图左侧显示对应聚类的颜色,确保两种颜色都能被正确调用。

3. 避免调色板被热图数值范围覆盖

如果直接用cmap指定调色板,可能因热图数值分布导致颜色显示单一。可先按聚类标签排序数据,再应用自定义调色板:

# 自定义离散调色板
custom_cmap = sns.color_palette(color_list, n_colors=len(train_clusters["Cluster_Label"].unique()))

# 按聚类标签排序热图数据
sorted_df = train_combined_df.join(train_clusters.set_index("Sample"), how="inner")\
                            .sort_values("Cluster_Label")\
                            .drop("Cluster_Label", axis=1)

# 绘制分组热图
sns.heatmap(sorted_df, cmap=custom_cmap)

验证要点

运行后检查:

  • 热图左侧的row_colors是否显示两种不同颜色
  • 排序后的热图是否按聚类分组形成明显的颜色区块

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 22:49:56