Clustered Heatmap Tutorial: pheatmap in R, seaborn in Python, SPSS and Online
Updated November 7, 2026 · StatFAS Tutorials · Beginner to intermediate
This tutorial shows how to create a clustered heatmap and run the statistics behind the clustered heatmap in four ways: SPSS, R, Python and the free Clustered Heatmap Maker on statfas.com. Every script is complete and can be copied into the software. For the concepts behind the clustered heatmap, read the guide Clustered Heatmap Explained: Hierarchical Clustering, Dendrograms and Interpretation.
Step 1: Prepare the data
A numeric matrix with feature names in the first column and one column per sample. Name sample columns by group plus a number (Control_1, Treated_1) to enable group annotation and one-way ANOVA for each feature.
Example layout:
Gene,Control_1,Control_2,Treated_1,Treated_2
Gene_01,5.1,5.3,6.9,7.2
Gene_02,7.8,7.6,6.1,5.9Step 2: SPSS
SPSS performs hierarchical cluster analysis and draws a dendrogram, but does not draw colour-coded heatmaps. Use SPSS for the clustering and tests, and a dedicated tool for the figure.
* Data: one row per sample, one column per feature (rows and columns can be swapped with Data > Transpose).
DESCRIPTIVES VARIABLES=Gene_01 TO Gene_60 /SAVE. * saves z-scores as ZGene_01 ... ZGene_60
CLUSTER ZGene_01 TO ZGene_60
/METHOD BAVERAGE
/MEASURE=SEUCLID
/PRINT SCHEDULE
/PLOT DENDROGRAM VICICLE.
* Menu path: Analyze > Classify > Hierarchical Cluster (cluster cases = samples; cluster variables = features).
* SPSS draws the dendrogram but not a colour-coded heatmap; export the ordered matrix to statfas.com for the figure.
ONEWAY Gene_01 TO Gene_60 BY Group. * ANOVA per feature; apply the Benjamini-Hochberg correction afterwardsStep 3: R
The pheatmap package clusters, scales and draws the clustered heatmap in one call; base R functions give the cophenetic correlation and the ANOVA tests.
library(pheatmap)
m <- read.csv("matrix.csv", row.names = 1) # features x samples
grp <- sub("[_.\\-\\s]*\\d+$", "", colnames(m))
ann <- data.frame(Group = grp, row.names = colnames(m))
top <- m[order(apply(m, 1, var), decreasing = TRUE)[1:60], ]
pheatmap(top, scale = "row", clustering_distance_rows = "euclidean",
clustering_method = "average", annotation_col = ann,
color = colorRampPalette(c("#2166ac", "white", "#b2182b"))(100),
breaks = seq(-2, 2, length.out = 101), filename = "heatmap.png",
width = 7, height = 9)
# Cophenetic correlation
z <- t(scale(t(top)))
hc <- hclust(dist(z), method = "average")
cor(dist(z), cophenetic(hc))
# One-way ANOVA per feature with BH correction
p <- apply(m, 1, function(x) summary(aov(x ~ factor(grp)))[[1]][["Pr(>F)"]][1])
q <- p.adjust(p, method = "BH")
head(sort(q), 10)Step 4: Python
The seaborn clustermap function draws the clustered heatmap; SciPy supplies the cophenetic correlation and ANOVA.
import pandas as pd, seaborn as sns
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import pdist
from scipy import stats
from statsmodels.stats.multitest import multipletests
df = pd.read_csv("matrix.csv", index_col=0) # features x samples
groups = df.columns.str.replace(r"[_\.\-\s]*\d+$", "", regex=True)
# Select the 60 most variable features and draw the clustered heatmap
top = df.loc[df.var(axis=1).sort_values(ascending=False).index[:60]]
g = sns.clustermap(top, z_score=0, method="average", metric="euclidean", cmap="RdBu_r",
vmin=-2, vmax=2, figsize=(7, 9),
col_colors=pd.Series(groups, index=df.columns).map(
dict(zip(sorted(set(groups)), ["#e41a1c", "#377eb8", "#4daf4a"]))))
g.savefig("heatmap.png", dpi=300)
# Cophenetic correlation: how faithfully the row dendrogram preserves distances
z = top.sub(top.mean(axis=1), axis=0).div(top.std(axis=1), axis=0)
c, _ = cophenet(linkage(z, "average", "euclidean"), pdist(z, "euclidean"))
print("Cophenetic correlation (features):", round(c, 3))
# One-way ANOVA for every feature, Benjamini-Hochberg corrected
cols = {k: df.columns[groups == k] for k in sorted(set(groups))}
res = df.apply(lambda r: stats.f_oneway(*[r[c] for c in cols.values()]), axis=1, result_type="expand")
res.columns = ["F", "p"]; res["q"] = multipletests(res["p"], method="fdr_bh")[1]
print(res.sort_values("p").head(10))Step 5: The easy way on statfas.com
The Clustered Heatmap Maker needs no installation and no code. Follow these steps:
- Open the tool. Go to the StatFAS Clustered Heatmap Maker.
- Add data. Click Load example data to see the layout, then paste or upload a matrix with features in rows and samples in columns.
- Choose settings. Set the number of features, how to select them, scaling, distance, linkage, whether to cluster rows and columns, and the colour scale.
- Read the results. The tool draws the clustered heatmap with dendrograms and group bars, calculates cophenetic correlations, sample-cluster purity and one-way ANOVA with FDR for each feature.
- Download. Download the PNG or SVG, or a Word file with the figure, the tables and the APA 7 interpretation.
Upload or paste data and get the clustered heatmap, the statistics and an APA 7 write-up in seconds.
Open the free Clustered Heatmap Maker
Step 6: Interpret and report in APA 7
Check these points before the clustered heatmap goes into a manuscript:
- Read colours relative to the scale. With row z-scores, red means higher than that row’s average and blue means lower; the colours do not compare different rows with each other.
- Judge the dendrograms by the height at which branches join: early joins at low height mean similar profiles, late joins at large height mean dissimilar profiles.
- Report the distance measure, the linkage method and the scaling, because each choice changes the clustering.
- The cophenetic correlation measures how faithfully a dendrogram preserves the original distances; higher values indicate a more faithful tree.
Example APA 7 results paragraph:
Avoid these mistakes with the clustered heatmap:
- Clustering without scaling, so that high-abundance features dominate the picture.
- Choosing the number of features by looking at which choice gives the prettiest picture.
- Reading the vertical order of rows as a ranking; only the branching structure carries meaning.
- Presenting clusters as proof of biological subtypes without validation.
Frequently asked questions
What does a clustered heatmap show?
A clustered heatmap shows a data matrix as colours, with rows and columns reordered by hierarchical clustering so that similar features and similar samples appear together.
Should data be scaled before clustering?
Usually yes. Row z-scores place all features on a common scale, so that clustering reflects patterns rather than absolute abundance.
Which linkage method is best?
Average linkage is a balanced default, complete linkage gives compact clusters. Report the choice and check that conclusions do not depend on the method.
What is the cophenetic correlation?
The cophenetic correlation is the correlation between the original pairwise distances and the distances implied by the dendrogram; higher values mean the tree represents the data more faithfully.
Related guides
How to cite this page: StatFAS. (2026, November 7). Clustered Heatmap Tutorial: pheatmap in R, seaborn in Python, SPSS and Online. https://statfas.com/tutorials/clustered-heatmap.html