# How to Plot a Dendrogram in Python with SciPy

> Plot a dendrogram in Python with scipy linkage() and dendrogram(). Cut clusters with fcluster, compare linkage methods, truncate large trees, and use clustermap.

Source: https://www.pythoncharts.com/python/dendrogram-python/ | Published: 2026-11-26 | Author: Alex Scott | Category: Python | Tags: python, scipy, seaborn, dendrogram, clustering, clustermap

To plot a dendrogram in Python, compute a hierarchical clustering with `scipy.cluster.hierarchy.linkage()` and pass the result to `dendrogram()`. The tree shows which items are most similar and at what distance each group merges.

The examples use SciPy 1.18, and the clustermap uses Seaborn.

## Quick Example

This clusters coffee drinks by their typical recipe, in milliliters of each ingredient. The values are illustrative.

```python
import matplotlib.pyplot as plt
import pandas as pd
from scipy.cluster.hierarchy import dendrogram, linkage

drinks = pd.DataFrame(
    [  # espresso, hot water, steamed milk, foam, chocolate (ml)
        [30, 0, 0, 0, 0], [60, 0, 0, 0, 0], [20, 0, 0, 0, 0],
        [60, 150, 0, 0, 0], [60, 100, 0, 0, 0], [90, 0, 0, 0, 0],
        [30, 0, 220, 10, 0], [60, 0, 60, 60, 0], [60, 0, 110, 10, 0],
        [30, 0, 0, 15, 0], [60, 0, 60, 0, 0], [60, 0, 180, 10, 30],
    ],
    index=["Espresso", "Doppio", "Ristretto", "Americano", "Long black", "Lungo",
           "Latte", "Cappuccino", "Flat white", "Macchiato", "Cortado", "Mocha"],
    columns=["espresso", "water", "milk", "foam", "chocolate"],
)

scaled = (drinks - drinks.mean()) / drinks.std()
Z = linkage(scaled, method="ward")

fig, ax = plt.subplots(figsize=(9, 5.5))
dendrogram(Z, labels=drinks.index.to_list(), orientation="right",
           color_threshold=3, above_threshold_color="#8d99ae", ax=ax)
ax.set_title("Coffee drinks clustered by recipe")
ax.set_xlabel("Ward distance")
ax.spines[["top", "right", "left"]].set_visible(False)
fig.tight_layout()
plt.show()
```

![Horizontal dendrogram of twelve coffee drinks. Ristretto and Espresso merge first, and Mocha joins last](https://www.pythoncharts.com/python/dendrogram-python/images/dendrogram-python-quick-example.png)

`orientation="right"` puts the leaves on the left with horizontal labels, which are easier to read than rotated ones.

## How to Read a Dendrogram

- Each leaf is one item.
- Where two branches join, those groups were merged. The position of the join along the distance axis shows how different they were.
- Espresso and ristretto join first, at 0.50, so they are the most alike. Mocha joins last.
- The order of leaves is partly arbitrary. Two neighbors aren't necessarily similar unless they join at a low distance.

The `Z` array records the same information. Each of its rows lists the two clusters merged, the distance between them, and the number of items in the new cluster.

## Why Scale the Data First

Clustering works on distances, so columns with a larger spread dominate. Milk has a standard deviation of 78 ml and chocolate 9 ml. Without scaling, a three-cluster cut separates the latte and mocha (lots of milk), the americano and long black (lots of water), and puts the other eight together. Subtracting the mean and dividing by the standard deviation gives each ingredient equal weight. Skip it only when all columns share units and their differences in spread are meaningful.

## Cut the Tree into Clusters with fcluster

`fcluster()` turns the tree into one cluster number per item. Cut at a distance with `criterion="distance"`, or ask for a number of clusters with `criterion="maxclust"`.

```python
from scipy.cluster.hierarchy import fcluster, set_link_color_palette

cut = 3
clusters = pd.Series(fcluster(Z, t=cut, criterion="distance"), index=drinks.index)
for number, group in clusters.groupby(clusters):
    print(number, ", ".join(group.index))

set_link_color_palette(["#d62828", "#f77f00", "#2a9d8f", "#6a4c93", "#1d3557"])
fig, ax = plt.subplots(figsize=(10, 5))
dendrogram(Z, labels=drinks.index.to_list(), color_threshold=cut,
           above_threshold_color="#adb5bd", leaf_rotation=45, ax=ax)
ax.axhline(cut, color="black", linestyle="--", linewidth=1)
ax.annotate(f"cut at {cut}", (1, cut), xycoords=("axes fraction", "data"),
            ha="right", va="bottom")
for label in ax.get_xticklabels():
    label.set_horizontalalignment("right")
ax.set_ylabel("Ward distance")
ax.set_title(f"Cutting the tree gives {clusters.nunique()} clusters")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
set_link_color_palette(None)  # restore the default colors
```

```text
1 Americano, Long black
2 Doppio, Lungo, Flat white, Cortado
3 Espresso, Ristretto, Macchiato
4 Latte
5 Cappuccino
6 Mocha
```

![Dendrogram with a dashed cut line at distance 3, coloring three multi-drink clusters and leaving Mocha, Cappuccino and Latte on their own](https://www.pythoncharts.com/python/dendrogram-python/images/dendrogram-cut-clusters.png)

Use the same value for `color_threshold` and `t` so the colors match the clusters. Single-item clusters take the `above_threshold_color`. `set_link_color_palette()` changes a global setting, hence the reset at the end.

## Which Linkage Method Should I Use?

The method defines the distance between two clusters. The cophenetic correlation, from `cophenet()`, measures how closely the tree's merge distances match the original distances between items.

```python
from scipy.cluster.hierarchy import cophenet
from scipy.spatial.distance import pdist

distances = pdist(scaled)

fig, axes = plt.subplots(2, 2, figsize=(11, 8))
for ax, method in zip(axes.flat, ["single", "complete", "average", "ward"]):
    links = linkage(scaled, method=method)
    score, _ = cophenet(links, distances)
    dendrogram(links, labels=drinks.index.to_list(), leaf_rotation=90,
               color_threshold=0, above_threshold_color="#264653", ax=ax)
    ax.set_title(f"method='{method}' (cophenetic r = {score:.2f})")
    ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
```

![Four dendrograms of the coffee drinks using single, complete, average and ward linkage, with average scoring the highest cophenetic correlation of 0.89](https://www.pythoncharts.com/python/dendrogram-python/images/dendrogram-linkage-methods.png)

| `method=` | Distance between clusters | Tends to |
|---|---|---|
| `"single"` (SciPy default) | Closest pair of items | Chain items into long clusters |
| `"complete"` | Farthest pair | Make compact clusters |
| `"average"` | Mean of all pairs | Sit between the two |
| `"ward"` | Increase in within-cluster variance | Make clusters of low variance. Needs Euclidean distances |

Average linkage scores highest here (0.89), but that score doesn't tell you which clusters are most useful. Check that the groups make sense for your data. To use another distance, pass `metric="cosine"` or `metric="correlation"` with a method other than Ward.

If you already have a square distance matrix, convert it with `scipy.spatial.distance.squareform()` before calling `linkage()`. A square matrix is treated as raw observations, and SciPy warns with a `ClusterWarning`.

## Truncate a Large Dendrogram

With many items the labels become unreadable. `truncate_mode="lastp"` shows only the last `p` merged clusters, with their sizes in parentheses. This uses the wine dataset included with scikit-learn:

```python
from sklearn.datasets import load_wine

wine = load_wine(as_frame=True)
features = wine.data
wine_scaled = (features - features.mean()) / features.std()
wine_Z = linkage(wine_scaled, method="ward")

fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
dendrogram(wine_Z, no_labels=True, ax=axes[0])
axes[0].set_title(f"All {len(features)} wines")
dendrogram(wine_Z, truncate_mode="lastp", p=12, show_contracted=True,
           leaf_rotation=0, ax=axes[1])
axes[1].set_title("truncate_mode='lastp', p=12")
fig.tight_layout()
plt.show()
```

![A full dendrogram of 178 wines with three colored branches, beside a truncated version with twelve leaves labeled by size](https://www.pythoncharts.com/python/dendrogram-python/images/dendrogram-truncated.png)

`truncate_mode="level"` is the alternative: it limits the tree to `p` levels below the root.

## Dendrogram with a Heatmap: sns.clustermap

[Seaborn's `clustermap()`](https://seaborn.pydata.org/generated/seaborn.clustermap.html) clusters rows and columns and reorders a heatmap to match. `z_score=1` standardizes each column, and `row_colors` adds a strip for a known label, here the grape cultivar.

```python
import seaborn as sns

cols = ["alcohol", "malic_acid", "color_intensity", "hue", "flavanoids",
        "total_phenols", "proline", "alcalinity_of_ash"]
cultivar_colors = wine.target.map({0: "#e63946", 1: "#457b9d", 2: "#f4a261"})

grid = sns.clustermap(features[cols], method="ward", z_score=1, cmap="vlag",
                      center=0, vmin=-3, vmax=3, figsize=(8, 8),
                      row_colors=cultivar_colors.rename("cultivar"),
                      yticklabels=False, cbar_kws={"label": "z-score"})
grid.ax_heatmap.set_ylabel("178 wines")
plt.show()
```

![Clustermap of eight wine measurements. The row color strip shows the three cultivars falling into mostly separate blocks](https://www.pythoncharts.com/python/dendrogram-python/images/dendrogram-clustermap.png)

The cultivar was not used for clustering, yet the three colors form mostly separate blocks. For heatmaps without clustering, see [Seaborn heatmaps](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/).

## Similar Topics

- [K-means elbow and silhouette plots](https://www.pythoncharts.com/machine-learning/kmeans-elbow-silhouette-python/)
- [Heatmaps in Seaborn](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/)
- [Network graphs in Python with NetworkX](https://www.pythoncharts.com/python/network-graph-python/)
