从seaborn clustermap提取树状图

5

以下是来自 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)

问题:如何以非图形形式获得树状图?
背景信息: 从该树状图的根部开始,我想在最大长度处切断它。例如,我们有一条边从根部到左侧聚类(L),一条边到右侧聚类(R)...从这两条边中,我想获取它们的边长,并在最长的这两条边处切断整个树状图。
此致敬礼
1个回答

9

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]

链接矩阵是计算树状图所使用的输入,它也可能会有所帮助:
h.dendrogram_col.linkage
h.dendrogram_row.linkage

非常感谢您详细的阐述,这帮助我解决了问题! - Daniyal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接