5

是否可以为 Scipy 的树状图的叶子标签分配颜色?我无法从文档中弄清楚。这是我到目前为止所尝试的:

from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage, dendrogram

distanceMatrix = pdist(subj1.ix[:,:3])
dendrogram(linkage(distanceMatrix, method='complete'), 
           color_threshold=0.3, 
           leaf_label_func=lambda x: subj1['activity'][x],
           leaf_font_size=12)

谢谢。

4

2 回答 2

10

dendrogram使用 matplotlib 创建绘图,因此在调用 之后dendrogram,您可以随心所欲地操纵绘图。特别是,您可以修改 x 轴标签的属性,包括颜色。这是一个例子:

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=1,
                   labels=["a", "b", "c", "d"])

# Assignment of colors to labels: 'a' is red, 'b' is green, etc.
label_colors = {'a': 'r', 'b': 'g', 'c': 'b', 'd': 'm'}

ax = plt.gca()
xlbls = ax.get_xmajorticklabels()
for lbl in xlbls:
    lbl.set_color(label_colors[lbl.get_text()])

plt.show()

这是示例产生的情节:

示例图

于 2013-02-11T13:31:03.600 回答
1

是的!创建树状图后,您可以获取当前图形并进行修改。

dendrogram(
    Z, 
    leaf_rotation = 90.,  # rotates the x axis labels
    leaf_font_size = 10., # font size for the x axis labels)
    labels = y # list of labels to include 
    ) 

ax = plt.gca()
x_lables = ax.get_xmajorticklabels()
for x in x_labels:
        x.set_color(colorDict[x.get_text()])

希望这可以帮助!

于 2017-12-13T18:46:04.787 回答