51

如何在 Python 中在值矩阵的顶部绘制树状图,并适当地重新排序以反映聚类?一个例子是下图:

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

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

对此的任何帮助将不胜感激。

4

2 回答 2

99

这个问题没有很好地定义矩阵:“值矩阵”,“数据矩阵”。我假设您的意思是距离矩阵。换言之,对称非负 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')

阴谋

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


编辑:对于不同的颜色,调整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). 请参见此处的示例。

于 2010-06-10T05:40:19.457 回答
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])

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

得到的结果是这样的:

于 2014-04-13T17:48:06.290 回答