Skip to main content
 首页 » 编程设计

python之为树状图中的特定链接着色

2024年11月01日9tuyile006

在 scipy 的层次聚类的树状图中,我想突出显示连接特定两个标签的链接,比方说 0 和 1。

import scipy.cluster.hierarchy as hac 
from matplotlib import pyplot as plt 
 
clustering = hac.linkage(points, method='single', metric='cosine') 
link_colors = ["black"] * (2 * len(points) - 1) 
hac.dendrogram(clustering, link_color_func=lambda k: link_colors[k]) 
plt.show() 

聚类具有以下格式: clustering[i] 对应于节点号 len(points) + i ,它的前两个数字是链接节点的索引。索引小于 len(points) 的节点对应于原始 points,更高索引对应于簇。

绘制树状图时,使用不同的链接索引,这些索引用于选择颜色。链接的索引(在 link_colors 中索引)如何对应于 clustering 中的索引?

请您参考如下方法:

您已经非常接近解决方案了。 clustering 中的索引按 clustering 数组第 3 列的大小排序。 link_color_func 的颜色列表的索引是聚类 的索引 + 点 的长度。

import scipy.cluster.hierarchy as hac 
from matplotlib import pyplot as plt 
import numpy as np 
 
# Sample data 
points = np.array([[8, 7, 7, 1],  
            [8, 4, 7, 0],  
            [4, 0, 6, 4],  
            [2, 4, 6, 3],  
            [3, 7, 8, 5]]) 
 
clustering = hac.linkage(points, method='single', metric='cosine') 

聚类看起来像这样

array([[3.        , 4.        , 0.00766939, 2.        ], 
       [0.        , 1.        , 0.02763245, 2.        ], 
       [5.        , 6.        , 0.13433008, 4.        ], 
       [2.        , 7.        , 0.15768043, 5.        ]]) 

如您所见,聚类的排序(以及行索引)结果按第三列排序。

现在要突出显示特定链接(例如,[0,1],如您所建议的),您必须在 clustering 中找到 [0,1] 对的行索引并添加 len (点)。生成的数字是为 link_color_func 提供的颜色列表的索引。

# Initialize the link_colors list with 'black' (as you did already) 
link_colors = ['black'] * (2 * len(points) - 1) 
# Specify link you want to have highlighted 
link_highlight = (0, 1) 
# Find index in clustering where first two columns are equal to link_highlight. This will cause an exception if you look for a link, which is not in clustering (e.g. [0,4]) 
index_highlight = np.where((clustering[:,0] == link_highlight[0]) *  
                           (clustering[:,1] == link_highlight[1]))[0][0] 
# Index in color_list of desired link is index from clustering + length of points 
link_colors[index_highlight + len(points)] = 'red' 
 
hac.dendrogram(clustering, link_color_func=lambda k: link_colors[k]) 
plt.show() 

像这样,您可以突出显示所需的链接:

它也适用于原始元素和集群之间或两个集群之间的链接(例如 link_highlight = (5, 6))