Scipy树状图叶标颜色

2024-05-13 11:48:47 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以为Scipy树状图的叶标签指定颜色?我无法从documentation中找出答案。到目前为止,我一直在尝试:

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)

谢谢。


Tags: 答案fromimport颜色documentationscipy标签树状
2条回答

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

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()])

希望这有帮助!

^{}使用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()

下面是这个例子产生的情节:

example plot

相关问题 更多 >