如何根据定义的组为树状图的标签着色? (在 python 中)

How to color a dendrogram's labels according to defined groups? (in python)

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

简单示例测试:

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 索引。

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)之间的差异已突出显示以显示差异。