python画聚类图_python – 如何绘制和注释scipy/matplotlib中的层次聚类树形图

linkage()的输入是一个n×m的数组,代表n个点

m维空间或包含

condensed distance matrix的一维数组。在您的示例中,mat是3 x 3,所以你是聚类

三个3-d点。聚类基于这些点之间的距离。

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

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

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

也不是整个数据集的平移(垫偏移)改变相对值

点之间的距离。

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

在下面的代码中,我

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

段的图与相应的距离。相关的值

使用键icoord和dcoord给出每个的x和y坐标

三段倒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”时,树形图只显示“top”的树状图。下面显示了show_leaf_counts的效果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值