如何在Python中按自定义分组为dendrogram(树状图)的标签着色?
树状图标签与分组颜色统一的实现方案
直接对生成的x轴标签对象设置颜色即可,你给出的示例调整后可运行代码如下:
import numpy as np from scipy.cluster.hierarchy import dendrogram, linkage import matplotlib.pyplot as plt mat = np.array([[1.0, 0.5, 0.0], [0.5, 1.0, -0.5], [1.0, -0.5, 0.5], [0.0, 0.5, -0.5]]) dist_mat = mat linkage_matrix = linkage(dist_mat, "single") plt.clf() ddata = dendrogram(linkage_matrix, color_threshold=0.8) # 自定义标签颜色映射 label_color = {0:'blue', 1:'red', 2:'blue', 3:'red'} ax = plt.gca() # 遍历修改所有x轴标签颜色 for lab in ax.get_xticklabels(): idx = int(lab.get_text()) lab.set_color(label_color[idx]) plt.show()
如果需要自动对齐树状图的分支颜色,不需要手动配置映射,可以用以下通用逻辑实现:
# 自动匹配分支与标签颜色的方案 link_color_map = {} n_leaves = len(mat) for i, (node1, node2) in enumerate(linkage_matrix[:, :2].astype(int)): color1 = link_color_map[node1] if node1 >= n_leaves else ddata['color_list'][i] color2 = link_color_map[node2] if node2 >= n_leaves else ddata['color_list'][i] link_color_map[i + n_leaves] = color1 if color1 == color2 else ddata['color_list'][i] for lab in ax.get_xticklabels(): idx = int(lab.get_text()) lab.set_color(link_color_map[idx])
该方案会自动识别每个叶节点所属分支的颜色,直接赋值给对应标签,适配任意分组数量的场景。
内容的提问来源于stack exchange,提问作者Federico Vega
相关产品推荐
相关产品推荐

