r/learnpython • u/Dragoran21 • 7d ago
Calculations behind the Seaborn's clustermap? Or how to get just the pure matrix dataset.
I am looking for a way to produce a matrix dataset based on seaborn.clustermap(). I need to do some statistical comparisons, and just staring at a plot won't do it.
What I want is the raw numerical matrix that can be seen when annot=True. Grabbing that from a plot isn't the way, so I think I need to replicate the calculation behind the clustermap. I am not sure how to do that?
I understand that clustermap uses scipy.cluster.hierarchy.linkage and scipy.spatial.distance.pdist to calculate the hierarchical clustering, but I have not found examples of how to use them for something like this.
Can you help me find answers? Examples of someone doing this before? A name for right modules?
1
u/RyanDubois43 7d ago
clustermap just plots your original DataFrame reordered, so use sns.clustermap(data, return_cluster=True) in seaborn 0.13+ to get the reordered matrix as a DataFrame, no need to replicate linkage calculations yourself.
1
u/Sufficient-Tale6131 6d ago
You don't need to replicate anything, the clustermap object already holds it. Keep the return value, g = sns.clustermap(df), and then:
If you want to do it without seaborn, the defaults are method='average' and metric='euclidean', so leaves_list(linkage(df.values, method='average', metric='euclidean')) from scipy.cluster.hierarchy gives the same row order (use df.T for columns). That linkage matrix is also what you'd pass to fcluster if you want actual cluster labels for your statistics.
Small note: as far as I can tell there's no return_cluster argument in seaborn 0.13, so that won't work.