gpt4 book ai didi

python - 带有名称的 Scipy 树形图

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:43 26 4
gpt4 key购买 nike

我正在使用 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')

最佳答案

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

这是它生成的图: plot

(请注意,对于像 D 这样的对称数组,对两个轴进行聚类实际上没有意义。通过对称性,它们将生成相同的树状图。)

关于python - 带有名称的 Scipy 树形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999852/

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