r/learnpython • • 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 Upvotes

7 comments sorted by

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/Dragoran21 6d ago

I tried that but got this error message:

AttributeError: QuadMesh.set() got an unexpected keyword argument 'return_cluster'

Are you sure that was the right term? Oh, and I use PyCharm Community Edition.

1

u/Dragoran21 6d ago

I see where you got it wrong. What I needed to do was:

X=sns.clustermap.(data)
y=X.data2a #data2a turns clustermap into normal dataframe. 

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:

  • g.data2d is the matrix in the exact order shown in the plot. It's the same DataFrame the heatmap draws, so it matches what annot=True shows (after any z_score/standard_scale you passed).
  • g.dendrogram_row.reordered_ind and g.dendrogram_col.reordered_ind are the row and column orders.
  • g.dendrogram_row.linkage is the scipy linkage matrix.

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.