# How can I make a clustered heatmap from an unclustered matrix?

I have a similarity matrix and when I plot it as a heatmap, it looks like:

I have tried using 'Agglomerate' to cluster the underlying matrix but I cannot figure out how to get the clusters to show in a new heatmap. How can I do this?

You can use the package "HeatmapPlot.m". Below are given examples.

Import["https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/Misc/HeatmapPlot.m"]


Make a random symmetric matrix:

SeedRandom[23];
{m, n} = {80, 50};
mat = RandomReal[{0, 100}, {m, n}];
mat = SparseArray[RandomSample[Most@ArrayRules@SparseArray[mat], Floor[4*m]]];
mat = mat.Transpose[mat];
MatrixPlot[mat, MaxPlotPoints -> 300]


Heatmap plot with clustering for the random symmetric matrix:

HeatmapPlot[mat, Dendrogram -> True, ImageSize -> Large]


You can specify distance function and linkage:

Grid[Table[
HeatmapPlot[ mat,
Dendrogram -> True,
DistanceFunction -> dist,
HierarchicalClusteringLinkage -> link,
PlotLabel -> {dist, link}, ImageSize -> Medium],
{dist, {EuclideanDistance, CosineDistance}},
{link, {"Single", "Complete", "Ward"}}],
Dividers -> All, FrameStyle -> GrayLevel[0.8]]
`

• Maybe I don't understand something fundamentally, but the matrix is symmetric along one diagonal, but the dendrograms seem to set the symmetry along the other diagonal. Please, explain. Commented Oct 14, 2022 at 14:12
• The dendrograms are derived by the column- and row-similarities. They might "imply" order that is not immediately obvious from the matrix plot. Also, if the matrix plots are made with larger number of points the impressions they give might be different. Commented Oct 14, 2022 at 18:27
• Yes, ok.. Still. Take a look here researchgate.net/publication/… It seems that dendrogram at the right should be flipped along horizontal axis. Commented Oct 17, 2022 at 14:13
• @ФилиппЦветков Thanks, I will read the article later this week... Commented Oct 17, 2022 at 14:47