Python Scipy树状图叶子标签颜色
是否可以为Scipy树状图的叶子标签指定颜色?我从照片上看不出来。以下是我迄今为止所尝试的:Python Scipy树状图叶子标签颜色,python,scipy,hierarchical-clustering,dendrogram,Python,Scipy,Hierarchical Clustering,Dendrogram,是否可以为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'),
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)
谢谢。使用matplotlib创建绘图,因此在调用树状图之后,您可以随意操作绘图。特别是,可以修改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()
下面是示例生成的图:
是的!创建树状图后,可以抓取当前图形并进行修改
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()])
希望这有帮助 啊,好的,明白了。我试试看。谢谢不要给距离矩阵(Link Kar)作为输入,因为它会考虑它的观测向量:这已经修复了吗?我一直在使用平方距离矩阵。我们还能给它什么?pdist?如果标签包含unichar,如何处理?我得到一个错误,我想这与此有关。@Sigur,如果在搜索stackoverflow后找不到答案,请创建一个新问题。我不认为这些评论是处理你问题的地方。