her*_*rfz 5 python hierarchical-clustering dendrogram scipy
是否可以为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)
Run Code Online (Sandbox Code Playgroud)
谢谢.
War*_*ser 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()
Run Code Online (Sandbox Code Playgroud)
这是示例生成的图:
