Seaborn clustermap: Clustered Heatmaps with Dendrograms

Make a clustered heatmap with sns.clustermap: scale rows, add row colors and a legend, choose a distance metric, control the dendrograms, and extract the clusters.

sns.clustermap(df) draws a heatmap, reorders its rows and columns so that similar ones sit together, and adds dendrograms showing how they were grouped. It takes a wide table of numbers with no missing values.

Quick Example

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib.patches import Patch

# Sample data: average bike pickups by hour at 18 bike share stations
rng = np.random.default_rng(88)
hours = np.arange(5, 24)

def bump(center, width):
    return np.exp(-((hours - center) ** 2) / (2 * width ** 2))

shapes = {
    "Residential": bump(8, 1.3) + 0.3 * bump(18, 2),
    "Office": 0.25 * bump(8, 1.5) + bump(17, 1.4),
    "Nightlife": 0.3 * bump(13, 3) + bump(22, 2),
}
names = {
    "Residential": ["Elm St", "Birch Ave", "Oak Park", "Cedar Ct", "Maple Rd", "Willow Way"],
    "Office": ["City Hall", "Tech Park", "Exchange", "Union Sq", "Court St", "Plaza"],
    "Nightlife": ["Old Market", "Canal Walk", "Theatre Row", "Dock Yard", "Arts Quarter", "King St"],
}
data, kinds = {}, {}
for kind, stations in names.items():
    for station in stations:
        size = rng.uniform(5, 90)  # stations differ a lot in how busy they are
        noise = rng.normal(0, 0.07, len(hours))
        data[station] = np.clip(size * (shapes[kind] + 0.08 + noise), 0, None)
        kinds[station] = kind
trips = pd.DataFrame(data, index=hours).T.sample(frac=1, random_state=4)

palette = {"Residential": "#2563eb", "Office": "#f59e0b", "Nightlife": "#9333ea"}
station_colors = trips.index.to_series().map(kinds).map(palette).rename("Area")

g = sns.clustermap(trips, z_score=0, col_cluster=False, cmap="vlag", center=0,
                   row_colors=station_colors, figsize=(9, 7),
                   cbar_pos=(0.03, 0.83, 0.025, 0.14))
g.ax_heatmap.set(xlabel="Hour of day", ylabel="")
g.figure.suptitle("Bike pickups by station and hour (row z-scores)", y=0.93)
g.figure.legend(handles=[Patch(color=c, label=k) for k, c in palette.items()],
                loc="upper center", bbox_to_anchor=(0.55, 0.87), ncol=3, frameon=False)
plt.show()

Seaborn clustermap of 18 bike stations by hour, with the row dendrogram separating residential, office, and nightlife stations

Clustering used only the pickup numbers, and it put each of the three station types in its own block: morning peaks, evening commute peaks, and late-night peaks. The code targets Seaborn 0.13 and needs SciPy installed.

What the Default clustermap Does

With no options, clustermap() clusters both rows and columns on the raw values.

g = sns.clustermap(trips, figsize=(8, 7))
plt.show()

Default clustermap of unscaled pickups where busy and quiet stations of the same type are split apart and the hours are shuffled

Two things go wrong for this data. The residential and nightlife stations each split into a busy group and a quiet group, because on raw counts, how busy a station is can outweigh when it is busy. The hours are also shuffled, even though time has a natural order.

Scale the Data with z_score or standard_scale

Scaling puts rows (or columns) on a common footing before clustering and coloring.

Argument Result Colormap
z_score=0 Each row has mean 0 and standard deviation 1 Diverging, with center=0
z_score=1 Same, for each column Diverging, with center=0
standard_scale=0 Each row runs from 0 to 1 Sequential
standard_scale=1 Each column runs from 0 to 1 Sequential

0 means rows and 1 means columns. Passing both arguments raises an error. Here each station is scaled so that its busiest hour is 1:

g = sns.clustermap(trips, standard_scale=0, col_cluster=False, cmap="mako_r",
                   figsize=(8, 7), cbar_kws={"label": "Share of peak"},
                   cbar_pos=(0.03, 0.83, 0.025, 0.14))
plt.show()

Clustermap with each station scaled from 0 to 1, showing three bands of peak hours

Scale columns instead when each column is a different measurement in its own units, such as price, weight, and rating.

Choose the Linkage Method and Distance Metric

metric defines how far apart two rows are, and method defines how clusters are merged. The defaults are metric="euclidean" and method="average".

g = sns.clustermap(trips, metric="correlation", method="average", col_cluster=False,
                   standard_scale=0, cmap="rocket_r", figsize=(8, 7))
plt.show()

Clustermap of bike stations clustered with correlation distance

  • metric="correlation" compares the shape of each row and ignores its level, so it groups similar daily patterns even without scaling.
  • method="ward" tends to give compact, similar-sized clusters. It assumes Euclidean distance.
  • method="single" often produces long chains that are hard to read.

The dendrogram guide compares linkage methods on the same data and shows how to read the tree.

Turn Off Clustering or Hide a Dendrogram

col_cluster=False keeps the columns in their original order, and row_cluster=False does the same for rows. To cluster the rows but not show their tree, hide that Axes:

g = sns.clustermap(trips, z_score=0, col_cluster=False, cmap="vlag", center=0,
                   figsize=(8, 7), cbar_pos=(0.03, 0.83, 0.025, 0.14))
g.ax_row_dendrogram.set_visible(False)
plt.show()

Clustered station heatmap with the row dendrogram hidden

dendrogram_ratio sets how much of the figure the trees take, for example dendrogram_ratio=(0.1, 0.2) for rows and columns.

Add Several Row Color Strips

Pass row_colors a DataFrame to get one labeled strip per column. Its index must match the data's index, which is how Seaborn keeps the colors aligned after reordering. col_colors does the same above the heatmap.

volume = trips.sum(axis=1)
strips = pd.DataFrame({
    "Area": station_colors,
    "Busy": np.where(volume > volume.median(), "#111827", "#d1d5db"),
}, index=trips.index)

g = sns.clustermap(trips, z_score=0, col_cluster=False, cmap="vlag", center=0,
                   row_colors=strips, colors_ratio=0.025, figsize=(8, 7),
                   cbar_pos=(0.03, 0.83, 0.025, 0.14))
plt.show()

Clustermap with two color strips showing station area and whether the station is busier than the median

The area colors form solid blocks, while the busy and quiet shades are mixed within them. After row scaling, station size no longer drives the grouping. Seaborn does not add a legend for these colors, so build one with Patch handles as in the Quick Example.

Show Every Label and Rotate Them

Seaborn skips tick labels when they would overlap. yticklabels=True forces every row label, and a taller figure or smaller font makes room.

g = sns.clustermap(trips, z_score=0, col_cluster=False, cmap="vlag", center=0,
                   figsize=(8, 4.5), yticklabels=True, xticklabels=2)
g.ax_heatmap.tick_params(axis="y", labelsize=8, labelrotation=0)
g.ax_heatmap.tick_params(axis="x", labelrotation=0)
plt.show()

Short clustermap showing all 18 station names and every second hour

Get the Clustered Order and Cluster Labels

The returned ClusterGrid stores the new order and the linkage matrix. g.data2d is the table as drawn, after scaling and reordering.

from scipy.cluster.hierarchy import fcluster

g = sns.clustermap(trips, z_score=0, col_cluster=False)

order = g.dendrogram_row.reordered_ind          # row positions, top to bottom
ordered_trips = trips.iloc[order]               # original units, clustered order

labels = fcluster(g.dendrogram_row.linkage, t=3, criterion="maxclust")
clusters = pd.Series(labels, index=trips.index, name="cluster")
print(pd.crosstab(clusters, trips.index.to_series().map(kinds).rename("area")))
plt.close("all")

Each of the three clusters holds the six stations of one area type. labels follows the original row order of trips, not the plotted order.

Annotate a Small clustermap

Other keyword arguments go to sns.heatmap(), so annot, fmt, linewidths, vmin, and vmax work. Annotations are readable only on small tables.

blocks = trips.T.groupby(pd.cut(hours, [4, 10, 15, 19, 23],
                                labels=["Morning", "Midday", "Evening", "Night"]),
                         observed=True).mean().T
small = blocks.loc[["Elm St", "Oak Park", "Plaza", "Exchange", "King St", "Dock Yard"]]

g = sns.clustermap(small, annot=True, fmt=".0f", cmap="crest", linewidths=1,
                   figsize=(6.5, 5), cbar_pos=None)
g.ax_heatmap.tick_params(axis="y", labelrotation=0)
plt.show()

Small annotated clustermap of average pickups for six stations in four parts of the day

cbar_pos=None removes the colorbar, which the numbers make unnecessary.

Cluster Long-Format Data

If the data has one row per observation, pivot_kws reshapes it inside the call. The pivot needs exactly one value for each row and column pair, so aggregate duplicates first.

long = trips.rename_axis(index="station", columns="hour").stack().rename("pickups").reset_index()

g = sns.clustermap(long, pivot_kws={"index": "station", "columns": "hour", "values": "pickups"},
                   z_score=0, col_cluster=False, cmap="vlag", center=0)
plt.close("all")

Save the Figure

clustermap() is a figure-level function: it creates its own figure and does not accept ax=. Set the size with figsize and save through the grid, which keeps the dendrograms and outside labels in the image.

g = sns.clustermap(trips, z_score=0, col_cluster=False, figsize=(8, 7))
g.savefig("station-clusters.png", dpi=200)
plt.close("all")

Fix Common clustermap Errors

Error or symptom Cause and fix
ValueError: The condensed distance matrix must contain only finite values Missing or infinite values. Use df.dropna() or df.fillna(...). A row with a constant value also triggers this with z_score, so drop it
TypeError: ... multiple values for keyword argument 'ax' clustermap cannot draw into an existing subplot. Remove ax=
One huge value washes out the colors Scale the data, or pass robust=True to set color limits from percentiles
Row colors are all white The row_colors index does not match the data's index

clustermap or heatmap?

Use heatmap() when the row and column order already means something, such as months, ranked categories, or a confusion matrix. Use clustermap() when you want the data to suggest the order and the groups. Cluster results depend on the scaling, metric, and method, so check that a pattern survives a reasonable change to those before reporting it.

Similar Topics