如何在 Matplotlib 中调整树状图的分​​支长度?

matplotlibpythondata visualization更新于 2025/6/6 11:56:17

要在 Matplotlib 中调整树状图的分​​支长度,我们可以采取以下步骤 −

  • 设置图形大小并调整子图之间和周围的填充。

  • 从多元正态分布中绘制随机样本(a 和 b)。

  • 使用 concatenate() 方法沿现有轴连接一系列数组。

  • 执行分层/聚集聚类。

  • 使用 figure() 方法创建新图形或激活现有图形。

  • 将轴作为图形的一部分添加到图形中子图排列。

  • 使用 dendrogram() 方法将层次聚类绘制为树状图。

  • 要显示该图,请使用 show() 方法。

示例

from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
a = np.random.multivariate_normal([0, 10], [[3, 1], [1, 4]], size=[2, ])
b = np.random.multivariate_normal([0, 10], [[3, 1], [1, 4]], size=[3, ])
X = np.concatenate((a, b), )
Z = linkage(X)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
dendrogram(Z, ax=ax)
plt.show()

输出


相关文章


有用资源