在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数组的第三列的大小排序。 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()


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

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

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

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

10-08 08:44