用python绘制数据矩阵的层次聚类ontop结果

2024-05-11 19:57:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,如何在值矩阵的正上方绘制树状图,并对其进行适当的重新排序以反映集群?例如下图:

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

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

在此方面的任何帮助都将不胜感激。


Tags: 数据httpsorg排序绘制集群矩阵cdn
2条回答

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

Plot

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


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


编辑:add_axessee 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.

如果除了矩阵和树形图之外,还需要显示元素的标签,则可以使用以下代码,显示旋转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])

结果如下(使用不同的颜色贴图):

The result obtained is this:

相关问题 更多 >