如何为Scipy dendrogram(树状图)添加图例?
给Scipy树状图添加图例的方法
你可以通过dendrogram函数返回的结果获取分支颜色,再结合聚类标签来创建图例。下面是修改后的完整代码,关键步骤已标注:
import pandas as pd import numpy as np from sklearn.cluster import AgglomerativeClustering from sklearn.preprocessing import StandardScaler from sklearn.metrics import silhouette_score import matplotlib.pyplot as plt from scipy.cluster.hierarchy import dendrogram, linkage from matplotlib.patches import Patch # 用于创建图例元素 # 此处保留你原有的数据预处理逻辑,比如生成dfx_scaled的代码 # 层次聚类训练 agg_clustering = AgglomerativeClustering(n_clusters=4).fit(dfx_scaled) dfx['clusters'] = agg_clustering.labels_ # 生成链接矩阵并绘制树状图 linkage_matrix = linkage(dfx_scaled, 'ward') plt.figure(figsize=(10, 7)) # 仅调用一次dendrogram并保存返回结果,避免重复绘图 d = dendrogram(linkage_matrix, no_labels=True) plt.axhline(y=140, color='black', linestyle='--') # 构建聚类标签与树状图颜色的映射 # leaves是树状图叶子节点对应的原始数据索引,color_list是对应叶子的颜色 leaf_colors = d['color_list'] leaf_indices = d['leaves'] # 根据叶子索引匹配对应数据的聚类标签 cluster_labels = [dfx['clusters'][idx] for idx in leaf_indices] # 创建颜色-聚类的映射字典(去重,确保每个聚类只对应一种颜色) color_cluster_map = {} for color, label in zip(leaf_colors, cluster_labels): if label not in color_cluster_map: color_cluster_map[label] = color # 生成图例元素 legend_elements = [Patch(facecolor=color, label=f'Cluster {label+1}') for label, color in color_cluster_map.items()] # 添加图例到图中,位置可根据需求调整 plt.legend(handles=legend_elements, loc='upper right') plt.show()
关键说明
- 不要重复调用
dendrogram函数,你原代码中调用了两次,只需调用一次并保存返回的字典d即可。 d['leaves']对应树状图叶子节点的原始数据行索引,d['color_list']是每个叶子节点的颜色值。- 通过索引匹配将叶子颜色与聚类标签绑定,去重后得到每个聚类对应的唯一颜色。
- 用
Patch创建颜色块元素,再通过plt.legend添加到图中。
如果需要固定聚类的颜色(不受树状图自动配色影响),可以手动指定颜色映射:
# 手动定义聚类与十六进制颜色的映射 custom_color_map = {0: '#1f77b4', 1: '#ff7f0e', 2: '#2ca02c', 3: '#d62728'} # 生成图例元素 legend_elements = [Patch(facecolor=custom_color_map[label], label=f'Cluster {label+1}') for label in custom_color_map.keys()] plt.legend(handles=legend_elements, loc='upper right')
内容的提问来源于stack exchange,提问作者rerere L.
相关产品推荐
相关产品推荐

