<p>这个问题并没有很好地定义矩阵:“值矩阵”,“数据矩阵”。我假设你是指距离矩阵。换言之,对称非负N乘N<em>距离矩阵</em>D中的元素D_ij表示两个特征向量x_i和x_j之间的距离,对吗?</p>
<p>如果是,那么试试这个(2010年6月13日编辑,以反映两个不同的树状图):</p>
<pre><code>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')
</code></pre>
<p><a href="https://i.stack.imgur.com/Z2tvi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Z2tvi.png" alt="Plot"/></a></p>
<p>祝你好运!如果你需要更多帮助,请告诉我。</p>
<hr/>
<p>编辑:对于不同的颜色,调整<code>imshow</code>中的<code>cmap</code>属性。有关示例,请参见<a href="http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps" rel="noreferrer">scipy/matplotlib docs</a>。该页还描述了如何创建自己的颜色映射。为了方便起见,我建议使用预先存在的颜色映射。在我的例子中,我使用了<code>YlGnBu</code>。</p>
<hr/>
<p>编辑:<code>add_axes</code>(<a href="http://matplotlib.sourceforge.net/api/figure_api.html?highlight=add_axes#matplotlib.figure.Figure.add_axes" rel="noreferrer">see documentation here</a>)接受列表或元组:<code>(left, bottom, width, height)</code>。例如,<code>(0.5,0,0.5,1)</code>在图的右半部分添加一个<code>Axes</code>。<code>(0,0.5,1,0.5)</code>在图的上半部分添加一个<code>Axes</code>。</p>
<p>大多数人使用<code>add_subplot</code>可能是为了方便。我喜欢<code>add_axes</code>来控制它。</p>
<p>要删除边框,请使用<code>add_axes([left,bottom,width,height], frame_on=False)</code>。<a href="http://matplotlib.sourceforge.net/examples/pylab_examples/manual_axis.html" rel="noreferrer">See example here.</a></p>