【问题标题】:Coloring specific links in a dendrogram为树状图中的特定链接着色
【发布时间】:2019-09-10 10:55:54
【问题描述】:

在 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 中的索引相对应?

【问题讨论】:

    标签: python matplotlib scipy


    【解决方案1】:

    您已经非常接近解决方案了。 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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 2015-10-13
      • 2015-09-16
      • 2016-04-29
      相关资源
      最近更新 更多