您已经非常接近解决方案了。 clustering 中的索引按 clustering 数组的第 3 列的大小排序。 link_color_func 的颜色列表的索引是 clustering 的索引 + points 的长度。
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')
clustering 确实是这样的
array([[3. , 4. , 0.00766939, 2. ],
[0. , 1. , 0.02763245, 2. ],
[5. , 6. , 0.13433008, 4. ],
[2. , 7. , 0.15768043, 5. ]])
如您所见,clustering 按第三列排序后的排序(以及行索引)结果。
现在要突出显示特定链接(例如您建议的 [0,1]),您必须在 clustering 中找到对 [0,1] 的行索引并添加 len(points)。结果数字是为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))