带有名称的 Scipy 树状图
Posted
技术标签:
【中文标题】带有名称的 Scipy 树状图【英文标题】:Scipy dendrogram with names 【发布时间】:2016-10-26 06:34:13 【问题描述】:我在工作中使用来自this post 的示例树状图,但也想跟踪哪一行/哪列来自哪条数据。
我已将数据名称记录为names
的代码编辑如下,并希望在距离矩阵可视化的底部和右侧打印出名称。我尝试在对dendrogram
的调用中添加labels = names
,但这没有帮助。
有谁知道如何给这个添加标签?
import scipy
import pylab
import scipy.cluster.hierarchy as sch
# Generate random features and distance matrix.
x = scipy.rand(40)
D = scipy.zeros([40,40])
for i in range(40):
for j in range(40):
D[i,j] = abs(x[i] - x[j])
### new code
names = [ ]
for i in range(40):
names.append( 'str%i'%( i ) )
print names[-1]
### end new code
# Compute and plot first dendrogram.
fig = pylab.figure(figsize=(8,8))
ax1 = fig.add_axes([0.09,0.1,0.2,0.6])
Y = sch.linkage(D, method='centroid')
Z1 = sch.dendrogram(Y, orientation='right')
ax1.set_xticks([])
ax1.set_yticks([])
# Compute and plot second dendrogram.
ax2 = fig.add_axes([0.3,0.71,0.6,0.2])
Y = sch.linkage(D, method='single')
Z2 = sch.dendrogram(Y)
ax2.set_xticks([])
ax2.set_yticks([])
# Plot distance matrix.
axmatrix = fig.add_axes([0.3,0.1,0.6,0.6])
idx1 = Z1['leaves']
idx2 = Z2['leaves']
D = D[idx1,:]
D = D[:,idx2]
im = axmatrix.matshow(D, aspect='auto', origin='lower', cmap=pylab.cm.YlGnBu)
axmatrix.set_xticks([])
axmatrix.set_yticks([])
# Plot colorbar.
#axcolor = fig.add_axes([0.91,0.1,0.02,0.6])
#pylab.colorbar(im, cax=axcolor)
fig.show()
fig.savefig('dendrogram.png')
【问题讨论】:
【参考方案1】:我写的python包heatmapcluster
(可用on PyPI)接受(事实上,需要)标签。
这是使用heatmapcluster
的脚本的简化版本:
import numpy as np
import matplotlib.pyplot as plt
from heatmapcluster import heatmapcluster
# Generate random features and distance matrix.
x = np.random.rand(40)
D = np.abs(np.subtract.outer(x, x))
names = ['str%i' % i for i in range(len(x))]
h = heatmapcluster(D, names, names,
num_row_clusters=3, num_col_clusters=3,
label_fontsize=8,
xlabel_rotation=-75,
cmap=plt.cm.coolwarm,
show_colorbar=True,
top_dendrogram=True)
plt.show()
这是它生成的情节:
(请注意,对于像D
这样的对称数组,对两个轴进行聚类实际上没有任何意义。通过对称性,它们将生成相同的树状图。)
【讨论】:
以上是关于带有名称的 Scipy 树状图的主要内容,如果未能解决你的问题,请参考以下文章