gpt4 book ai didi

python - Scipy 树状图叶标签颜色

转载 作者:太空狗 更新时间:2023-10-30 00:36:40 34 4
gpt4 key购买 nike

是否可以为 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)

谢谢。

最佳答案

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

这是示例生成的图:

example plot

关于python - Scipy 树状图叶标签颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14802048/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com