【问题标题】:How to color a dendrogram's labels according to defined groups? (in python)如何根据定义的组为树状图的标签着色? (在蟒蛇中)
【发布时间】:2021-09-08 08:10:22
【问题描述】:

我想以组的相同颜色生成图的标签。我该怎么做?

简单示例测试:

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)

前面的代码生成了这个图:

但我想要蓝色的 0 和 2 索引以及红色的 1 和 3。

【问题讨论】:

    标签: matplotlib scikit-learn label dendrogram


    【解决方案1】:
    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)
    
    # We get the color of leaves from the scipy dendogram docs
    # The key is called "leaves_color_list". We iterate over the list of these colors and set colors for our leaves
    # Please note that this parameter ("leaves_color_list") is different from the "color_list" which is the color of links
    # (as shown in the picture)
    # For the latest names of these parameters, please refer to scipy docs
    # https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.dendrogram.html
    for leaf, leaf_color in zip(plt.gca().get_xticklabels(), ddata["leaves_color_list"]):
        leaf.set_color(leaf_color)
    plt.show()
    

    输出如下图所示。参数(color_listleaves_color_list)之间的差异已被突出显示以显示差异。

    【讨论】:

    • @JohanC 注意到对显式索引部分的关注!将尽快修复。但是如何注意早期版本,我应该注意一下还是将当前关键字“leaves_color_list”的来源放在scipy中,以便用户以后可以检查自己是否有变化?
    • @JohanC 刚刚检查了scipy doccolor_list 代表链接的颜色(此图像中的三个链接),而 leaves_color_list 代表叶子(此图像中的 4 个叶子)
    • 感谢您的检查。所以,这是一个全新的参数。提及当前的 scipy 版本很重要,因此使用旧版本进行测试并遇到“奇怪”错误的人知道他们应该升级。见 a.o. Codementor 的 Stop using indices! 关于索引。
    • @JohanC 相应地更新了答案(1)删除了显式索引,很好的阅读(停止阅读索引!)(2)添加了指向 scipy doc 的链接并解释了图像中的参数,谢谢你建议!
    猜你喜欢
    • 2015-09-16
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多