Dendrogram
A dendrogram is a tree-like diagram that records the sequence of merges (or splits) performed by a hierarchical clustering algorithm. It's one of the most intuitive ways to visualize how clusters form step by step.
How to Read a Dendrogram
- Each leaf at the bottom represents a single data point.
- Each merge point (called a "node") shows two clusters being combined.
- The height of a merge represents the distance (or dissimilarity) between the two clusters being joined.
Plotting a Dendrogram in Python
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt
Z = linkage(data, method="ward")
dendrogram(Z)
plt.title("Dendrogram")
plt.xlabel("Data Points")
plt.ylabel("Distance")
plt.show()
Choosing the Number of Clusters
One of the most useful things a dendrogram tells you is how many clusters to pick. By drawing a horizontal line across the tallest vertical lines that aren't crossed by any merge, you can count how many clusters that cut produces.
Coming Up Next
With clustering covered, the course now shifts to another major unsupervised learning theme - reducing the number of features in your data through Dimensionality Reduction.
What the Linkage Matrix Contains
The dendrogram() call draws a picture, but the real information lives in the matrix returned by linkage(). For n data points it has n − 1 rows, one per merge, and each row holds four numbers:
- Index of the first cluster being merged.
- Index of the second cluster.
- The distance at which they merged (this becomes the height in the plot).
- How many original points the new cluster contains.
Indices below n refer to original points. An index of n or higher refers to a cluster created in an earlier row, so row 0 creates cluster n, row 1 creates cluster n + 1, and so on.
A Small End-to-End Example
The code below clusters six 2-D points, cuts the tree into two groups and checks how faithfully the tree preserves the original distances.
import numpy as np
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster, cophenet
from scipy.spatial.distance import pdist
import matplotlib.pyplot as plt
X = np.array([[1, 2], [1.5, 1.8], [1, 0.6],
[5, 8], [8, 8], [9, 11]])
Z = linkage(X, method="ward")
print(Z) # one row per merge
labels = fcluster(Z, t=2, criterion="maxclust")
print(labels) # e.g. [1 1 1 2 2 2]
c, _ = cophenet(Z, pdist(X))
print("Cophenetic correlation:", round(c, 3))
dendrogram(Z, labels=["A", "B", "C", "D", "E", "F"])
plt.axhline(y=5, linestyle="--")
plt.show()
The three points near the origin join first at small heights. The other three join each other later, and the final merge between the two groups happens far higher up. That long vertical gap is the visual signal that two clusters is a sensible answer.
You can also cut by height instead of by cluster count with fcluster(Z, t=5, criterion="distance"), which returns the groups below that horizontal line.
How the Linkage Method Changes the Shape
| Method | Distance between clusters | Effect on the tree |
|---|---|---|
| single | Closest pair of points | Long chains, sensitive to noise |
| complete | Farthest pair of points | Compact, similar-sized groups |
| average | Mean of all pairwise distances | A middle ground |
| ward | Increase in within-cluster variance | Balanced groups, needs Euclidean distance |
If two methods give very different dendrograms on the same data, the cluster structure is probably weak, and you should treat any chosen cut with caution.
Practical Tips and Common Slip-Ups
- Scale first: a feature measured in thousands will dominate one measured in single digits. Use
StandardScalerbefore linkage. - Large datasets: hierarchical clustering compares all pairs, so memory and time grow quickly. Sample the data or use
truncate_mode="lastp"to show only the last merges. - Ward with the wrong metric: Ward assumes Euclidean distance; pairing it with cosine or Manhattan gives misleading heights.
- Reading leaf order as similarity: neighbouring leaves are not always close; only the merge height tells you how similar two branches are.
Checklist: scale features, try two or three linkage methods, look for the tallest uncrossed gap, confirm with fcluster, and check the cophenetic correlation is reasonably high.