这个问题没有定义矩阵很好:“矩阵的值”,“数据矩阵”。我假设你的意思是距离矩阵。换句话说,对称非负N×N距离矩阵D中的元素D_ij表示两个特征向量x_i和x_j之间的距离。那是对的吗?
如果是的话,那就试试这个(编辑2010年6月13日,以反映两个不同的树状图):
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])
# 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')
Dendrogram and distance matrix http://up.stevetjoa.com/dendrogram.png
祝你好运!让我知道你是否需要更多的帮助。
编辑:对于不同的颜色,调整cmap
属性中imshow
。示例请参阅scipy/matplotlib docs。该页面还介绍了如何创建自己的色彩映射。为了方便起见,我建议使用预先存在的色彩映射表。在我的例子中,我使用了YlGnBu
。
编辑:add_axes
(see documentation here)接受列表或元组:(left, bottom, width, height)
。例如,(0.5,0,0.5,1)
在图的右半部分添加Axes
。 (0,0.5,1,0.5)
在该图的上半部分添加Axes
。
为方便起见,大多数人可能使用add_subplot
。我喜欢add_axes
的控制权。请使用add_axes([left,bottom,width,height], frame_on=False)
删除边框。 See example here.
这更是一个matplotlib问题,我已经将它重新标记了。 – dwf 2010-06-06 08:06:52
可能的重复:http://stackoverflow.com/questions/2455761/reordering-matrix-elements-to-reflect-column-and-row-clustering-in-naiive-python – 2010-06-09 18:19:26
请更新链接到图片。 – 2015-07-27 13:58:37