从 seaborn clustermap 中提取树状图

Dan*_*yal 3 python dendrogram scipy seaborn

鉴于以下示例来自:https : //python-graph-gallery.com/404-dendrogram-with-heat-map/

它生成一个树状图,我假设它是基于 scipy 的。

# Libraries
import seaborn as sns
import pandas as pd
from matplotlib import pyplot as plt

# Data set
url = 'https://python-graph-gallery.com/wp-content/uploads/mtcars.csv'
df = pd.read_csv(url)
df = df.set_index('model')
del df.index.name
df

# Default plot
sns.clustermap(df)
Run Code Online (Sandbox Code Playgroud)

问题:如何获得非图形形式的树状图?

背景信息:从该树状图的根部,我想以最大长度切割它。例如,我们有一条从根到左簇 (L) 的边和一条到右簇 (R) 的边……从这两个中我想得到它们的边长并以最长的时间切割整个树状图这两条边。

此致

Bon*_*fum 6

clustermap返回ClusterGrid对象的句柄,其中包括每个树状图的子对象,h.dendrogram_col 和 h.dendrogram_row。在这些内部是树状图本身,它根据 scipy.hierarchical.dendrogram 返回数据提供树状图几何结构,您可以从中计算特定分支的长度。

h = sns.clustermap(df)
dgram = h.dendrogram_col.dendrogram
D = np.array(dgram['dcoord'])
I = np.array(dgram['icoord'])

# then the root node will be the last entry, and the length of the L/R branches will be
yy = D[-1] 
lenL = yy[1]-yy[0]
lenR = yy[2]-yy[3]
Run Code Online (Sandbox Code Playgroud)

用于计算树状图的输入链接矩阵也可能有帮助:

h.dendrogram_col.linkage
h.dendrogram_row.linkage
Run Code Online (Sandbox Code Playgroud)