python画聚类树状图_如何在scipy/matplotlib中绘制和标注层次聚类树状图

本文介绍如何在Python中使用scipy和matplotlib绘制并标注层次聚类树状图。通过示例代码详细解释了linkage()函数的输入和聚类原理,并展示了如何在树状图上标注节点间距离。同时,探讨了show_leaf_counts参数的作用,展示了一个包含100个随机点的聚类树状图实例。
摘要由CSDN通过智能技术生成

linkage()的输入是一个n x m数组,表示

m维空间,或包含condensed distance matrix的一维数组。在您的示例中,mat是3x 3,因此您是集群

三个三维点。聚类是基于这些点之间的距离。

为什么mat和1-mat在这里给出相同的clustering?

数组mat和1-mat产生相同的聚类,因为

是基于点之间的距离,而不是反射(-mat)

整个数据集的转换(mat + offset)也不会改变相对

点之间的距离。

如何使用树状图标注沿着树的每个分支的距离,以便可以比较节点对之间的距离?

在下面的代码中,我

显示如何使用树状图返回的数据来标记水平

图中具有相应距离的段。关联的值

用键icoord和dcoord给出每个

图的三段倒U。在augmented_dendrogram这个数据中

用于添加每个水平面的距离(即y值)的标签

树状图中的线段。from scipy.cluster.hierarchy import dendrogram

import matplotlib.pyplot as plt

def augmented_dendrogram(*args, **kwargs):

ddata = dendrogram(*args, **kwargs)

if not kwargs.get('no_plot', False):

for i, d in zip(ddata['icoord'], ddata['dcoord']):

x = 0.5 * sum(i[1:3])

y = d[1]

plt.plot(x, y, 'ro')

plt.annotate("%.3g" % y, (x, y), xytext=(0, -8),

textcoords='offset points',

va='top', ha='center')

return ddata

对于您的mat数组,扩充的树状图是

所以点'a'和'c'相距1.01个单位,点'b'相距1.57个单位

集群['a','c']。

似乎忽略了show_leaf_counts标志,有没有办法打开它

以便显示每个类中的对象数?

标记show_leaf_counts仅在并非所有原始数据时适用

点显示为叶。例如,当trunc_mode = "lastp"时,

只显示最后的p节点。

下面是一个100分的例子:import numpy as np

from scipy.cluster.hierarchy import linkage

import matplotlib.pyplot as plt

from augmented_dendrogram import augmented_dendrogram

# Generate a random sample of `n` points in 2-d.

np.random.seed(12312)

n = 100

x = np.random.multivariate_normal([0, 0], np.array([[4.0, 2.5], [2.5, 1.4]]),

size=(n,))

plt.figure(1, figsize=(6, 5))

plt.clf()

plt.scatter(x[:, 0], x[:, 1])

plt.axis('equal')

plt.grid(True)

linkage_matrix = linkage(x, "single")

plt.figure(2, figsize=(10, 4))

plt.clf()

plt.subplot(1, 2, 1)

show_leaf_counts = False

ddata = augmented_dendrogram(linkage_matrix,

color_threshold=1,

p=6,

truncate_mode='lastp',

show_leaf_counts=show_leaf_counts,

)

plt.title("show_leaf_counts = %s" % show_leaf_counts)

plt.subplot(1, 2, 2)

show_leaf_counts = True

ddata = augmented_dendrogram(linkage_matrix,

color_threshold=1,

p=6,

truncate_mode='lastp',

show_leaf_counts=show_leaf_counts,

)

plt.title("show_leaf_counts = %s" % show_leaf_counts)

plt.show()

这些是数据集中的点:

使用p=6和trunc_mode="lastp",dendrogram只显示“top”

树状图的。下面显示show_leaf_counts的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值