在python中绘制数据矩阵的层次聚类结果

48 python cluster-analysis machine-learning matplotlib scipy

如何在值矩阵之上绘制树形图,在Python中适当地重新排序以反映聚类?一个例子如下图:

https://publishing-cdn.elifesciences.org/07103/elife-07103-fig6-figsupp1-v2.jpg

我使用scipy.cluster.dendrogram来制作树形图并对数据矩阵执行层次聚类.然后,我如何将数据绘制为矩阵,其中行已重新排序以反映在特定阈值处切割树状图所引起的聚类,并将树状图绘制在矩阵旁边?我知道如何在scipy中绘制树形图,而不是如何在其旁边的右侧比例尺绘制数据的强度矩阵.

任何有关这方面的帮助将不胜感激.

Ste*_*joa 93

这个问题没有很好地定义矩阵:"价值矩阵","数据矩阵".我假设你的意思是距离矩阵.换句话说,对称非负N×N 距离矩阵 D 中的元素D_ij 表示两个特征向量x_i和x_j之间的距离.那是对的吗?

如果是这样,那么试试这个(2010年6月13日编辑,以反映两种不同的树形图):

import scipy
import pylab
import scipy.cluster.hierarchy as sch
from scipy.spatial.distance import squareform


# 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])

condensedD = squareform(D)

# 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(condensedD, method='centroid')
Z1 = sch.dendrogram(Y, orientation='left')
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(condensedD, 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')
Run Code Online (Sandbox Code Playgroud)

情节

祝好运!如果您需要更多帮助,请告诉我.


编辑:对于不同的颜色,请调整cmap属性imshow.有关示例,请参阅scipy/matplotlib文档.该页面还描述了如何创建自己的色彩映射表.为方便起见,我建议使用预先存在的色彩映射表.在我的例子中,我用过YlGnBu.


编辑:add_axes(见这里的文档)接受列表或元组:(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).见这里的例子.

  • 我认为你使用联动功能的方式是错误的.如果查看linkage()的源代码,如果第一个参数(这里使用D)是一个矩阵,它将被视为数据,而不是距离.要输入距离,您必须获取D的上三角形并将其转换为一维向量,然后将其传递给linkage(). (2认同)

Pic*_*rus 9

如果除了矩阵和树形图之外还需要显示元素的标签,可以使用以下代码,它显示旋转x标签的所有标签并更改字体大小以避免在x轴上重叠.它需要移动颜色条以为y标签留出空间:

axmatrix.set_xticks(range(40))
axmatrix.set_xticklabels(idx1, minor=False)
axmatrix.xaxis.set_label_position('bottom')
axmatrix.xaxis.tick_bottom()

pylab.xticks(rotation=-90, fontsize=8)

axmatrix.set_yticks(range(40))
axmatrix.set_yticklabels(idx2, minor=False)
axmatrix.yaxis.set_label_position('right')
axmatrix.yaxis.tick_right()

axcolor = fig.add_axes([0.94,0.1,0.02,0.6])
Run Code Online (Sandbox Code Playgroud)

获得的结果是这个(使用不同的颜色图):

得到的结果是这样的: