Dendrogram and Hierarchical Clustering
What is a dendrogram?
A dendrogram is a tree diagram that shows how hierarchical clustering grouped a set of items. Each item is a leaf along the bottom. Each join, drawn as an upside-down U, merges two groups, and its height is the distance between them. Cutting the tree with a horizontal line splits the items into clusters.

Four groups of points clustered with Ward's method, and the dendrogram cut into four clusters (sample data). Try the interactive version.
- Hierarchical clustering builds a whole tree of nested clusters, so you choose the number of clusters afterwards by cutting the tree.
- The height of a join is the distance at which two clusters merged. Leaf order along the bottom says little about similarity.
- The linkage method decides what "distance between clusters" means, and it can change the result more than anything else.
- Scale the features first: clustering works on distances, and an unscaled feature with a large range takes over.
- DBSCAN groups points by density instead. It finds curved clusters, labels outliers as noise, and needs no cluster count.
What is hierarchical clustering?
Hierarchical clustering is a family of unsupervised learning methods that group items into a hierarchy of nested clusters. "Unsupervised" means there are no labels to learn from: the method only looks at how far apart the items are. The output is not one set of clusters but a tree containing every possible number of clusters, from one cluster holding everything down to one cluster per item.
There are two ways to build the tree:
- Agglomerative (bottom-up) clustering starts with each item as its own cluster and repeatedly merges the two closest clusters until one is left. It is by far the more common approach, and the one this page uses.
- Divisive (top-down) clustering starts with one cluster and repeatedly splits it. It needs a rule for the best split, which is expensive to search, so it is used less often.
Two choices define an agglomerative clustering: a distance measure between items (most often the Euclidean, straight-line distance, but correlation and others are common) and a linkage method, the rule for the distance between two clusters once they contain more than one item.
How agglomerative clustering works: a worked example
Take five points on a plane: A (0, 0), B (0, 2), C (6, 0), D (6, 3) and E (10, 3). The first step is the distance matrix, the straight-line distance between every pair:
| A | B | C | D | E | |
|---|---|---|---|---|---|
| A | 0 | 2.00 | 6.00 | 6.71 | 10.44 |
| B | 2.00 | 0 | 6.32 | 6.08 | 10.05 |
| C | 6.00 | 6.32 | 0 | 3.00 | 5.00 |
| D | 6.71 | 6.08 | 3.00 | 0 | 4.00 |
| E | 10.44 | 10.05 | 5.00 | 4.00 | 0 |
Then the algorithm repeats two steps until one cluster is left: merge the closest pair, and work out the distance from the new cluster to every other cluster. With complete linkage, where the distance between clusters is that of their farthest pair of points:
- The smallest distance is A–B, 2.00. Merge them into AB at height 2. Its distance to C is the larger of A–C and B–C: 6.32.
- The smallest is now C–D, 3.00. Merge them into CD at height 3.
- The candidates are AB–CD (the farthest pair is A–D, 6.71), AB–E (A–E, 10.44) and CD–E (C–E, 5.00). Merge E into CDE at height 5.
- Only AB and CDE are left. Their farthest pair is A–E, so the last merge is at 10.44.
Five points take four merges, and n items always take n − 1. The other linkage methods agree on the first two steps here but give different heights after that, and step 3 shows why. Single linkage, which uses the closest pair, measures CD–E as D–E = 4.00 rather than 5.00:
| Merge | Single | Complete | Average | Ward |
|---|---|---|---|---|
| A + B | 2.00 | 2.00 | 2.00 | 2.00 |
| C + D | 3.00 | 3.00 | 3.00 | 3.00 |
| CD + E | 4.00 | 5.00 | 4.50 | 4.93 |
| AB + CDE | 6.00 | 10.44 | 7.60 | 11.47 |
A horizontal cut at height 4.5 gives three clusters (AB, CD and E) on the complete-linkage tree, but two (AB and CDE) on the single-linkage tree, so heights can only be compared within one linkage method.
How to read a dendrogram
Read a dendrogram from the bottom up: the height where two branches join is how far apart the tree says those groups are, and a horizontal cut splits it into clusters.
- Leaves. Each leaf at the bottom (or the left, if the tree is drawn sideways) is one item: a data point, a gene, a document, a customer.
- Joins. Each upside-down U merges two clusters. The two legs lead down to the clusters it merged, and the bar is drawn at the merge height.
- Height. The vertical axis is the distance between the two clusters at the moment they merged, measured by the linkage method. A low join means similar items; a high join means the groups were far apart.
- Similarity of two items. Follow both leaves up until their branches meet. The height of that join, called the cophenetic distance, is how far apart the tree says they are. In the worked example, B and D meet at 10.44 even though they are 6.08 apart.
- Leaf order. Any join can be flipped left to right without changing the tree, so a tree with n leaves can be drawn in 2ⁿ⁻¹ orders. Two neighbouring leaves are not necessarily similar: the last leaf of one cluster sits next to the first leaf of another.
- The cut. A horizontal line at any height splits the tree into clusters: every vertical branch it crosses is one cluster, holding all the leaves below it.
- Long branches. A cluster whose vertical branch runs a long way up without any joins is well separated from the rest. A tree where all the joins sit at similar heights has no clear clusters.
How to choose the number of clusters
- Cut in the biggest gap. Look for the longest stretch of height with no joins, and cut through its middle. In the worked example, the jump from 5 to 10.44 suggests two clusters.
- Use what you know. A biologist may want clusters at a set level of similarity, or a marketing team a fixed number of segments.
- Check with a score. Compute a measure such as the silhouette score for several cuts and compare. The k-means clustering guide explains the silhouette score.
- Check the tree itself. The cophenetic correlation, the correlation between the original distances and the cophenetic distances (Sokal and Rohlf, 1962), shows how faithfully the tree represents the data. Values near 1 mean the tree distorts little.
Linkage methods: single, complete, average and Ward
The linkage method is the rule for the distance between two clusters, A and B, with and points. It decides the shape of the clusters you get.
| Linkage | Distance between clusters A and B | Tends to give | Watch out for |
|---|---|---|---|
| Single (nearest neighbour) | The closest pair of points, one from each | Long, thin or curved clusters | Chaining: one stray point or a thin trail joins two clusters |
| Complete (farthest neighbour) | The farthest pair of points | Compact clusters of similar diameter | Splitting large clusters; sensitive to outliers |
| Average (UPGMA) | The mean of all pair distances | A middle way between single and complete | Changes if the distances are transformed, for example squared; single and complete don't |
| Ward's method | The increase in the within-cluster sum of squares if A and B merge | Round clusters of similar size, like k-means | Assumes Euclidean distances; poor on curved shapes |
Ward's method (Ward, 1963) merges the pair of clusters whose merger adds least to the total squared distance of points from their cluster centroids. For two clusters with centroids and , the merge height reported by most software is
which equals the plain distance when both clusters are single points. All four methods can be computed with one update formula, published by Lance and Williams in 1967 (Wishart showed in 1969 that Ward's method fits it too), so the algorithm stays the same and only the update changes.
Two other linkages, centroid and median, measure the distance between cluster centres. They can produce inversions, where a later merge sits lower than an earlier one, which makes the tree impossible to cut cleanly. Single, complete, average and Ward never do.
What each linkage does to four datasets
The live demo on this page runs each linkage on four synthetic datasets and cuts the tree at the true number of groups. The adjusted Rand index (ARI) scores the result against the groups the points were drawn from: 1 is a perfect match and 0 is no better than chance.
| Dataset | Single | Complete | Average | Ward | DBSCAN (eps 0.35, minPts 5) |
|---|---|---|---|---|---|
| Four blobs | 1.00 | 1.00 | 1.00 | 1.00 | 0.98 |
| Blobs with a trail and outliers | 0.21 | 0.85 | 0.84 | 0.84 | 0.86 |
| Two moons | 1.00 | 0.31 | 0.29 | 0.14 | 1.00 |
| Two rings | 1.00 | 0.15 | −0.07 | −0.02 | 1.00 |
No method wins everywhere. Single linkage follows the moons and rings perfectly, but on the second dataset it chains three blobs into one cluster through the trail and the outliers, and spends two of its four clusters on stray points (cluster sizes 162, 35, 2 and 1). Ward's method finds the blobs but cuts the moons and rings straight across. The outliers count as their own group in the ARI, which is why no method reaches 1 on the second dataset.
Dendrograms beside heatmaps: the clustered heatmap
A clustered heatmap shows a table of values as a grid of colours, with its rows and columns reordered by hierarchical clustering and a dendrogram drawn along one or both edges. Eisen and colleagues (1998) made it the standard way to show gene expression: each row is a gene, each column a sample, and genes that rise and fall together end up next to each other, forming visible blocks of colour.
The same reordering helps any matrix:
- In a heatmap, sorting rows by a dendrogram turns a noisy grid into blocks you can read.
- In a correlation matrix, "reorder by similarity" usually means clustering the variables with 1 − correlation as the distance and average linkage, so strongly related variables sit together along the diagonal.
Because leaf order within a tree is not fixed, software usually picks the order that puts similar neighbours next to each other, for example with the optimal leaf ordering algorithm of Bar-Joseph and colleagues (2001). Reordering the leaves this way leaves every merge and height unchanged.
DBSCAN: density-based clustering
DBSCAN (density-based spatial clustering of applications with noise), published by Ester, Kriegel, Sander and Xu in 1996, treats a cluster as a region where points are packed densely, separated from other clusters by sparse space. It takes two settings:
- eps: the radius of the neighbourhood around each point;
- minPts: how many points, the point itself included, that neighbourhood must hold.
Every point then gets one of three roles:
- A core point has at least minPts points within eps.
- A border point is within eps of a core point but has too few neighbours to be core itself.
- A noise point is neither. DBSCAN leaves it out of every cluster.
The algorithm picks an unvisited core point, starts a cluster, and adds every point within eps of it. Each new core point adds its own neighbours in turn, until the cluster stops growing; then it moves on to the next unvisited core point. Border points join a cluster but don't extend it. A border point within reach of two clusters joins whichever reaches it first.
To choose eps, Ester and colleagues suggest sorting every point's distance to its k-th nearest neighbour and plotting the result: the curve is flat through the dense regions and rises steeply for the sparse points, and the bend is a good eps. They used minPts = 4 for two-dimensional data; Schubert and colleagues (2017) suggest twice the number of dimensions as a starting point. The live demo shows this k-distance plot in DBSCAN mode, with eps as a line you can drag.
DBSCAN and hierarchical clustering are related. DBSCAN with minPts = 2 gives the same clusters as single linkage cut at height eps, except that the single-linkage tree keeps each isolated point as a one-point cluster where DBSCAN calls it noise. HDBSCAN (Campello, Moulavi and Sander, 2013) builds a hierarchy over every eps and keeps the most stable clusters, so it needs no eps at all.
Hierarchical clustering vs k-means vs DBSCAN
Hierarchical clustering gives a whole tree and lets you pick the number of clusters afterwards, k-means needs that number up front but scales to millions of points, and DBSCAN finds clusters of any shape and labels outliers as noise.
| Hierarchical (agglomerative) | K-means | DBSCAN | |
|---|---|---|---|
| Number of clusters | Chosen afterwards, by cutting the tree | Set in advance (k) | Follows from eps and minPts |
| Cluster shapes | Depends on linkage: single follows any shape, Ward prefers round | Round, similar size | Any shape, as long as density is similar |
| Outliers | Kept in a cluster (or as tiny clusters) | Pull centres towards them | Labelled as noise |
| Output | A full tree of nested clusters | One flat partition and the centres | One flat partition plus noise |
| Scales to | Tens of thousands of points (memory for every pair) | Millions | Hundreds of thousands to millions, with a spatial index |
| Deterministic | Yes | No: depends on the starting centres | Yes, apart from border points between clusters |
| Best for | Small to medium data where the structure between clusters matters, ordering heatmaps | Large data, compact clusters, a known k | Spatial or sensor data with noise and odd shapes |
The k-means clustering guide covers the k-means algorithm, the elbow method and the silhouette score.
Where hierarchical clustering is used
Hierarchical clustering is used where the nesting of groups matters as much as the groups themselves.
- Biology. Phylogenetic trees of species and genes are dendrograms, and clustered heatmaps of gene expression are standard in genomics. See how SciChart is used for diagnostics and life sciences software.
- Document and text clustering. Grouping articles, support tickets or search results into topics and subtopics, where the hierarchy itself is useful.
- Customer segmentation. Grouping customers by behaviour, then cutting the tree at the level of detail a team can act on.
- Sensor and instrument data. Grouping similar machines, wafers or test runs, and spotting the odd one out on a tall branch of its own.
- Ecology and archaeology. Grouping sites by the species or artefacts found there, with distance measures made for presence and absence data.
Common hierarchical clustering mistakes
Most mistakes come from reading the tree the wrong way, from unscaled features, or from trusting one linkage and one cut without checking.
- Reading leaf order as similarity. Neighbouring leaves can be far apart. Judge two items by the height where their branches meet.
- Clustering unscaled features. With income in pounds and age in years, income decides every distance. Standardise each feature (subtract the mean, divide by the standard deviation) unless the units are already comparable.
- Using one linkage without checking. As the four-dataset table shows, linkage can turn a perfect result into a useless one. Try two or three and compare the trees.
- Comparing heights across linkages or datasets. A cut at height 4.5 means different things for single and Ward linkage.
- Pairing Ward's method with a non-Euclidean distance. Ward's method is defined for squared Euclidean distances. With correlation or Manhattan distances, use average or complete linkage.
- Ignoring the size limit. The distance matrix for n items holds n(n − 1)/2 values: about 40 GB for 100,000 points at 8 bytes each. Sample, cluster in two stages, or use k-means or DBSCAN.
- Trusting a cut with no gap. If the joins near the cut sit at similar heights, a slightly different cut gives different clusters. Check whether nearby cuts give the same clusters before reporting them.
- Setting DBSCAN's eps by guesswork. Use the k-distance plot, and remember eps is in the units of the scaled data.
How to make a dendrogram in JavaScript, React or Angular
The demo clusters 180 to 250 points in the browser, with no machine learning library, and recolours the dendrogram and the scatter plot together as you drag the cut line.
Drag the dashed cut line on the dendrogram, or move the Clusters slider, to cut the tree and recolour the points. Linkage switches between single, complete, average and Ward, and Dataset between four blobs, blobs with a trail and outliers, two moons and two rings; the readout shows the cluster sizes and the adjusted Rand index. Set Method to DBSCAN to replace the dendrogram with the k-distance plot: drag the line, or move the eps and minPts sliders, to see core points (filled), border points (rings) and noise (crosses). Zoom with the mouse wheel, pan the scatter plot by dragging, double-click to reset, and hover a point for its values.
Here is the code for this chart. The clustering, the tree layout and DBSCAN are plain JavaScript; SciChart.js draws the dendrogram as line segments, the points as a scatter series with a palette provider, and the cut line as a draggable annotation.
- JavaScript
- React
- Angular
// Hierarchical clustering with a dendrogram, and DBSCAN with a k-distance plot, charted with SciChart.js
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
FastLineRenderableSeries,
FastLineSegmentRenderableSeries,
XyScatterRenderableSeries,
EllipsePointMarker,
CrossPointMarker,
XyDataSeries,
XyxyDataSeries,
HorizontalLineAnnotation,
ELabelPlacement,
EStrokePaletteMode,
parseColorToUIntArgb,
LegendModifier,
ELegendPlacement,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
// --- Clustering maths (plain JavaScript, no library needed) ---
// Agglomerative clustering. Start with every point as its own cluster, then merge the closest pair of clusters
// n - 1 times. After each merge, the distance from the new cluster to every other cluster comes from the
// Lance-Williams update for the chosen linkage. Returns the merges in order: the two clusters joined (ids 0 to n-1
// are points, n + s is the cluster made at step s), the merge height (distance) and the new cluster's size.
function agglomerate(x, y, linkage) {
const n = x.length;
const d = new Float64Array(n * n); // distance matrix, kept symmetric
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) d[i * n + j] = d[j * n + i] = Math.hypot(x[i] - x[j], y[i] - y[j]);
}
const size = new Array(n).fill(1);
const id = Array.from({ length: n }, (_, i) => i); // which cluster each row of the matrix holds now
const active = new Array(n).fill(true);
const merges = [];
for (let step = 0; step < n - 1; step++) {
let best = Infinity;
let a = -1;
let b = -1;
for (let i = 0; i < n; i++) {
if (!active[i]) continue;
for (let j = i + 1; j < n; j++) {
if (active[j] && d[i * n + j] < best) {
best = d[i * n + j];
a = i;
b = j;
}
}
}
const na = size[a];
const nb = size[b];
for (let k = 0; k < n; k++) {
if (!active[k] || k === a || k === b) continue;
const dka = d[k * n + a];
const dkb = d[k * n + b];
let dist;
if (linkage === "single") dist = Math.min(dka, dkb); // nearest pair of points
else if (linkage === "complete") dist = Math.max(dka, dkb); // farthest pair of points
else if (linkage === "average") dist = (na * dka + nb * dkb) / (na + nb); // mean over all pairs
else {
// Ward: the increase in within-cluster sum of squares, on the same scale as a distance
const nk = size[k];
dist = Math.sqrt(((na + nk) * dka * dka + (nb + nk) * dkb * dkb - nk * best * best) / (na + nb + nk));
}
d[k * n + a] = d[a * n + k] = dist;
}
merges.push({ a: id[a], b: id[b], height: best, size: na + nb });
active[b] = false; // row a now holds the merged cluster
size[a] = na + nb;
id[a] = n + step;
}
return merges;
}
// Place the dendrogram: walk the tree from the top so each cluster's points sit side by side, give each point
// an x position in that order, and put each merge midway between its two children at its merge height
function dendrogramLayout(merges, n) {
const xPos = new Array(2 * n - 1);
const height = new Array(2 * n - 1).fill(0);
const order = [];
const visit = (node) => {
if (node < n) {
xPos[node] = order.length;
order.push(node);
return;
}
const m = merges[node - n];
visit(m.a);
visit(m.b);
xPos[node] = (xPos[m.a] + xPos[m.b]) / 2;
height[node] = m.height;
};
visit(2 * n - 2); // the root
return { xPos, height, order };
}
// Cut the tree into k clusters: undo the last k - 1 merges. Clusters are numbered left to right along the
// dendrogram. Returns a label for each point, and for each merge its cluster (or -1 if it is above the cut).
function cutTree(merges, n, k, order) {
const parent = Array.from({ length: n }, (_, i) => i);
const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
const leafOf = Array.from({ length: n }, (_, i) => i); // one point inside each cluster
merges.forEach((m, s) => {
leafOf[n + s] = leafOf[m.a];
if (s < n - k) parent[find(leafOf[m.b])] = find(leafOf[m.a]);
});
const number = new Map();
for (const leaf of order) if (!number.has(find(leaf))) number.set(find(leaf), number.size);
const labels = Array.from({ length: n }, (_, i) => number.get(find(i)));
const mergeLabels = merges.map((m, s) => (s < n - k ? labels[leafOf[n + s]] : -1));
return { labels, mergeLabels };
}
// The height to draw the cut line at for k clusters: halfway between the merges either side of the cut
function cutHeight(merges, k) {
const n = merges.length + 1;
const above = k > 1 ? merges[n - k].height : merges[n - 2].height * 1.1;
const below = k < n ? merges[n - k - 1].height : 0;
return k > 1 ? (above + below) / 2 : above;
}
// DBSCAN (Ester et al., 1996). A core point has at least minPts points (itself included) within eps.
// Clusters grow from core points through their neighbours; a border point is in reach of a core point but is
// not core itself; noise is everything else (label -1).
function dbscan(x, y, eps, minPts) {
const n = x.length;
const neighbours = [];
for (let i = 0; i < n; i++) {
const list = [];
for (let j = 0; j < n; j++) if (Math.hypot(x[i] - x[j], y[i] - y[j]) <= eps) list.push(j);
neighbours.push(list);
}
const core = neighbours.map((list) => list.length >= minPts);
const labels = new Array(n).fill(-1);
let clusters = 0;
for (let i = 0; i < n; i++) {
if (!core[i] || labels[i] !== -1) continue;
labels[i] = clusters;
const queue = [i];
while (queue.length > 0) {
const p = queue.shift();
if (!core[p]) continue; // border points join the cluster but don't extend it
for (const q of neighbours[p]) {
if (labels[q] === -1) {
labels[q] = clusters;
queue.push(q);
}
}
}
clusters++;
}
return { labels, core, clusters };
}
// The k-distance of each point: the distance to its (minPts - 1)th nearest other point, sorted. A point is a
// DBSCAN core point exactly when its k-distance is at most eps, and the bend in this curve suggests an eps.
function kDistances(x, y, minPts) {
const n = x.length;
const result = [];
for (let i = 0; i < n; i++) {
const dist = [];
for (let j = 0; j < n; j++) if (j !== i) dist.push(Math.hypot(x[i] - x[j], y[i] - y[j]));
dist.sort((p, q) => p - q);
result.push(dist[minPts - 2]);
}
return result.sort((p, q) => p - q);
}
// Adjusted Rand index: agreement between two labellings of the same points, 1 = identical groups, about 0 = chance
function adjustedRandIndex(a, b) {
const pairs = (m) => (m * (m - 1)) / 2;
const cells = new Map();
const rows = new Map();
const cols = new Map();
for (let i = 0; i < a.length; i++) {
const key = a[i] + "," + b[i];
cells.set(key, (cells.get(key) || 0) + 1);
rows.set(a[i], (rows.get(a[i]) || 0) + 1);
cols.set(b[i], (cols.get(b[i]) || 0) + 1);
}
const sum = (map) => [...map.values()].reduce((s, m) => s + pairs(m), 0);
const index = sum(cells);
const expected = (sum(rows) * sum(cols)) / pairs(a.length);
const max = (sum(rows) + sum(cols)) / 2;
return max === expected ? 1 : (index - expected) / (max - expected);
}
// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOURS = ["#50C7E0", "#F48420", "#3BD16F", "#E36FD4", "#F6E05E", "#9B8CFF", "#FF6B6B", "#2EC4B6", "#C9A227", "#7FB2FF", "#FF9FB2", "#A3E635"];
const ABOVE_CUT = "#8A9BB8";
const NOISE = "#C8D3E8";
const BACKGROUND = "#22365B";
// 1. The scatter plot, coloured by cluster. A palette provider gives each point its own colour, so one series
// draws every cluster. DBSCAN border points are drawn as rings and noise as crosses.
const scatter = await SciChartSurface.create(ui.scatterDiv, { theme });
const xAxis = new NumericAxis(scatter.wasmContext, { axisTitle: "Feature 1", labelPrecision: 1 });
const yAxis = new NumericAxis(scatter.wasmContext, { axisTitle: "Feature 2", labelPrecision: 1 });
scatter.sciChartSurface.xAxes.add(xAxis);
scatter.sciChartSurface.yAxes.add(yAxis);
function colouredScatter(name, size, hollow) {
const colours = []; // one colour per point, in the order the points are appended
const paletteProvider = {
strokePaletteMode: EStrokePaletteMode.SOLID,
onAttached: () => {},
onDetached: () => {},
overridePointMarkerArgb: (px, py, index) => {
const argb = parseColorToUIntArgb(colours[index] || NOISE);
return { stroke: argb, fill: hollow ? parseColorToUIntArgb(BACKGROUND) : argb };
}
};
const series = new XyScatterRenderableSeries(scatter.wasmContext, {
dataSeries: new XyDataSeries(scatter.wasmContext, { dataSeriesName: name }),
pointMarker: new EllipsePointMarker(scatter.wasmContext, { width: size, height: size, strokeThickness: hollow ? 2 : 1, fill: hollow ? BACKGROUND : "#50C7E0", stroke: "#50C7E0" }),
paletteProvider
});
scatter.sciChartSurface.renderableSeries.add(series);
return { series, colours };
}
const corePoints = colouredScatter("Points", 9, false);
const borderPoints = colouredScatter("Border points", 9, true);
const noisePoints = new XyScatterRenderableSeries(scatter.wasmContext, {
dataSeries: new XyDataSeries(scatter.wasmContext, { dataSeriesName: "Noise" }),
pointMarker: new CrossPointMarker(scatter.wasmContext, { width: 9, height: 9, stroke: NOISE, strokeThickness: 2 })
});
scatter.sciChartSurface.renderableSeries.add(noisePoints);
const scatterLegend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopLeft });
scatter.sciChartSurface.chartModifiers.add(
scatterLegend,
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// 2. The dendrogram. SciChart.js has no dendrogram series, so each merge is drawn as three line segments
// (up, across, down) in a FastLineSegmentRenderableSeries: one series per cluster colour, and one for the
// merges above the cut. The same chart shows the k-distance plot in DBSCAN mode.
const tree = await SciChartSurface.create(ui.treeDiv, { theme });
const treeXAxis = new NumericAxis(tree.wasmContext, { axisTitle: "Points, in dendrogram order", drawLabels: false, drawMajorTickLines: false, drawMinorTickLines: false });
const treeYAxis = new NumericAxis(tree.wasmContext, { axisTitle: "Merge height (distance)", autoRange: EAutoRange.Always, growBy: new NumberRange(0.1, 0.08), labelPrecision: 2 });
tree.sciChartSurface.xAxes.add(treeXAxis);
tree.sciChartSurface.yAxes.add(treeYAxis);
const linkSeries = [...COLOURS, ABOVE_CUT].map((colour) => {
const segments = new XyxyDataSeries(tree.wasmContext); // x1, y1, x2, y2 for each segment
const series = new FastLineSegmentRenderableSeries(tree.wasmContext, {
dataSeries: segments,
stroke: colour,
strokeThickness: colour === ABOVE_CUT ? 2 : 1.5
});
tree.sciChartSurface.renderableSeries.add(series);
return { series, segments };
});
const kDistanceLine = new FastLineRenderableSeries(tree.wasmContext, {
dataSeries: new XyDataSeries(tree.wasmContext, { dataSeriesName: "k-distance" }),
stroke: "#50C7E0",
strokeThickness: 2.5
});
tree.sciChartSurface.renderableSeries.add(kDistanceLine);
const cutLine = new HorizontalLineAnnotation({
y1: 1,
stroke: "#FFFFFF",
strokeThickness: 2,
strokeDashArray: [6, 4],
isEditable: true, // drag the line to cut the tree (or to set eps)
showLabel: true,
labelPlacement: ELabelPlacement.Axis,
axisLabelFill: "#FFFFFF",
axisLabelStroke: BACKGROUND
});
tree.sciChartSurface.annotations.add(cutLine);
// No ZoomPanModifier here, so a drag always moves the cut line
tree.sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier(), new ZoomExtentsModifier());
const setPoints = (series, x, y) => {
series.dataSeries.clear();
series.dataSeries.appendRange(x, y);
};
// --- The controls ---
let data;
let merges;
let layout;
// New dataset or linkage: recluster, redraw the points and fit the axes
function onDataChanged() {
data = makeDataset(ui.datasetSelect.value);
merges = agglomerate(data.x, data.y, ui.linkageSelect.value);
layout = dendrogramLayout(merges, data.x.length);
const pad = 0.3;
xAxis.visibleRange = new NumberRange(Math.min(...data.x) - pad, Math.max(...data.x) + pad);
yAxis.visibleRange = new NumberRange(Math.min(...data.y) - pad, Math.max(...data.y) + 3 * pad); // room for the legend
treeXAxis.visibleRange = new NumberRange(-0.08 * data.x.length, data.x.length + 1); // room for the watermark
onSettingsChanged();
}
// Method, cluster count, eps or minPts changed: recolour without reclustering
function onSettingsChanged(fromDrag = false) {
const isTree = ui.methodSelect.value === "tree";
ui.modeGroups.forEach((el) => el.toggleAttribute("hidden", (el.getAttribute("data-mode") === "tree") !== isTree));
for (const link of linkSeries) link.series.isVisible = isTree;
kDistanceLine.isVisible = !isTree;
borderPoints.series.isVisible = !isTree;
noisePoints.isVisible = !isTree;
corePoints.series.dataSeries.dataSeriesName = isTree ? "Points" : "Core points";
scatterLegend.sciChartLegend?.setRenderableSeriesArray(isTree ? [] : [corePoints.series, borderPoints.series, noisePoints]);
if (isTree) drawTree(fromDrag);
else drawDbscan(fromDrag);
}
function drawTree(fromDrag) {
const n = data.x.length;
const k = Number(ui.clustersInput.value);
ui.clustersOutput.textContent = String(k);
treeXAxis.axisTitle = "Points, in dendrogram order";
treeYAxis.axisTitle = "Merge height (distance)";
if (!fromDrag) cutLine.y1 = cutHeight(merges, k);
cutLine.labelValue = `${k} cluster${k > 1 ? "s" : ""}`;
const { labels, mergeLabels } = cutTree(merges, n, k, layout.order);
// Three segments per merge, into the series for its cluster's colour (or the grey one above the cut)
const segments = linkSeries.map(() => ({ x1: [], y1: [], x2: [], y2: [] }));
merges.forEach((m, s) => {
const into = segments[mergeLabels[s] === -1 ? COLOURS.length : mergeLabels[s] % COLOURS.length];
const xa = layout.xPos[m.a];
const xb = layout.xPos[m.b];
const ha = layout.height[m.a];
const hb = layout.height[m.b];
for (const [x1, y1, x2, y2] of [[xa, ha, xa, m.height], [xa, m.height, xb, m.height], [xb, m.height, xb, hb]]) {
into.x1.push(x1);
into.y1.push(y1);
into.x2.push(x2);
into.y2.push(y2);
}
});
linkSeries.forEach((link, i) => {
link.segments.clear();
link.segments.appendRange(segments[i].x1, segments[i].y1, segments[i].x2, segments[i].y2);
});
corePoints.colours.length = 0;
labels.forEach((label) => corePoints.colours.push(COLOURS[label % COLOURS.length]));
setPoints(corePoints.series, data.x, data.y);
corePoints.series.dataSeries.dataSeriesName = "Points";
setPoints(borderPoints.series, [], []);
setPoints(noisePoints, [], []);
const sizes = new Array(k).fill(0);
labels.forEach((label) => sizes[label]++);
const truth = data.group.map((g) => (g >= data.groups ? data.groups : g)); // outliers count as one group
ui.readout.textContent =
`${k} cluster${k > 1 ? "s" : ""}, cut between merge heights ${(k < n ? merges[n - k - 1].height : 0).toFixed(2)} ` +
`and ${(k > 1 ? merges[n - k].height : Infinity).toFixed(2)} · sizes ${sizes.join(", ")} · ` +
`agreement with the true groups (adjusted Rand index) ${adjustedRandIndex(labels, truth).toFixed(2)}`;
}
function drawDbscan(fromDrag) {
const eps = Number(ui.epsInput.value);
const minPts = Number(ui.minPtsInput.value);
ui.epsOutput.textContent = eps.toFixed(2);
ui.minPtsOutput.textContent = String(minPts);
treeXAxis.axisTitle = "Points, sorted by k-distance";
treeYAxis.axisTitle = `Distance to neighbour no. ${minPts - 1}`;
const kd = kDistances(data.x, data.y, minPts);
setPoints(kDistanceLine, kd.map((_, i) => i), kd);
if (!fromDrag) cutLine.y1 = eps;
cutLine.labelValue = `eps ${eps.toFixed(2)}`;
const { labels, core, clusters } = dbscan(data.x, data.y, eps, minPts);
const coreXy = { x: [], y: [] };
const borderXy = { x: [], y: [] };
const noiseXy = { x: [], y: [] };
corePoints.colours.length = 0;
borderPoints.colours.length = 0;
labels.forEach((label, i) => {
if (label === -1) {
noiseXy.x.push(data.x[i]);
noiseXy.y.push(data.y[i]);
} else if (core[i]) {
coreXy.x.push(data.x[i]);
coreXy.y.push(data.y[i]);
corePoints.colours.push(COLOURS[label % COLOURS.length]);
} else {
borderXy.x.push(data.x[i]);
borderXy.y.push(data.y[i]);
borderPoints.colours.push(COLOURS[label % COLOURS.length]);
}
});
setPoints(corePoints.series, coreXy.x, coreXy.y);
setPoints(borderPoints.series, borderXy.x, borderXy.y);
setPoints(noisePoints, noiseXy.x, noiseXy.y);
const truth = data.group.map((g) => (g >= data.groups ? data.groups : g));
ui.readout.textContent =
`${clusters} cluster${clusters === 1 ? "" : "s"} · ${coreXy.x.length} core, ${borderXy.x.length} border, ` +
`${noiseXy.x.length} noise points · adjusted Rand index ${adjustedRandIndex(labels, truth).toFixed(2)} ` +
`(noise counted as one group)`;
}
// Dragging the cut line sets the number of clusters (or eps); the line snaps to a clean cut when you let go
function onCutDragged() {
if (ui.methodSelect.value === "tree") {
const n = data.x.length;
const below = merges.filter((m) => m.height <= cutLine.y1).length;
ui.clustersInput.value = String(Math.max(1, Math.min(12, n - below)));
} else {
ui.epsInput.value = String(Math.max(0.05, Math.min(0.8, cutLine.y1)));
}
onSettingsChanged(true);
}
cutLine.dragDelta.subscribe(onCutDragged);
cutLine.dragEnded.subscribe(() => onSettingsChanged());
ui.datasetSelect.addEventListener("change", () => {
ui.clustersInput.value = String(makeDataset(ui.datasetSelect.value).groups);
onDataChanged();
});
ui.linkageSelect.addEventListener("change", onDataChanged);
ui.methodSelect.addEventListener("change", () => onSettingsChanged());
for (const input of [ui.clustersInput, ui.epsInput, ui.minPtsInput]) input.addEventListener("input", () => onSettingsChanged());
onDataChanged();
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
FastLineSegmentRenderableSeries,
XyxyDataSeries,
HorizontalLineAnnotation,
SciChartJsNavyTheme,
MouseWheelZoomModifier,
ZoomExtentsModifier
} from "scichart";
// Agglomerative clustering with average linkage: merge the closest pair of clusters n - 1 times
const agglomerate = (x: number[], y: number[]) => {
const n = x.length;
const d = x.map((_, i) => x.map((_, j) => Math.hypot(x[i] - x[j], y[i] - y[j])));
const size = new Array(n).fill(1), id = x.map((_, i) => i), active = new Array(n).fill(true);
const merges: { a: number; b: number; height: number }[] = [];
for (let step = 0; step < n - 1; step++) {
let best = Infinity, a = -1, b = -1;
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++)
if (active[i] && active[j] && d[i][j] < best) [best, a, b] = [d[i][j], i, j];
for (let k = 0; k < n; k++) if (active[k] && k !== a && k !== b)
d[k][a] = d[a][k] = (size[a] * d[k][a] + size[b] * d[k][b]) / (size[a] + size[b]);
merges.push({ a: id[a], b: id[b], height: best });
active[b] = false; size[a] += size[b]; id[a] = n + step;
}
return merges;
};
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { drawLabels: false }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Merge height" }));
const { x, y } = getYourPoints(); // one x and one y value per item (scale the features first)
const n = x.length;
const merges = agglomerate(x, y);
// Leaf x positions from a walk down the tree; each merge sits midway between its children
const xPos: number[] = [], height: number[] = new Array(2 * n - 1).fill(0);
let next = 0;
const visit = (node: number) => {
if (node < n) { xPos[node] = next++; return; }
const { a, b, height: h } = merges[node - n];
visit(a); visit(b);
xPos[node] = (xPos[a] + xPos[b]) / 2; height[node] = h;
};
visit(2 * n - 2);
// Each merge is three segments: up from child a, across at the merge height, down to child b
const segments = new XyxyDataSeries(wasmContext);
merges.forEach(({ a, b, height: h }) => {
segments.appendRange(
[xPos[a], xPos[a], xPos[b]], [height[a], h, h],
[xPos[a], xPos[b], xPos[b]], [h, h, height[b]]
);
});
sciChartSurface.renderableSeries.add(
new FastLineSegmentRenderableSeries(wasmContext, { dataSeries: segments, stroke: "#50C7E0", strokeThickness: 1.5 })
);
// A draggable line to cut the tree: every branch it crosses is one cluster
sciChartSurface.annotations.add(
new HorizontalLineAnnotation({ y1: merges[n - 2].height * 0.6, stroke: "#FFFFFF", strokeDashArray: [6, 4], isEditable: true })
);
sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier(), new ZoomExtentsModifier());
return { sciChartSurface };
};
export const DendrogramChart = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 450 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
FastLineSegmentRenderableSeries,
XyxyDataSeries,
HorizontalLineAnnotation,
SciChartJsNavyTheme,
MouseWheelZoomModifier,
ZoomExtentsModifier
} from "scichart";
// Agglomerative clustering with average linkage: merge the closest pair of clusters n - 1 times
const agglomerate = (x: number[], y: number[]) => {
const n = x.length;
const d = x.map((_, i) => x.map((_, j) => Math.hypot(x[i] - x[j], y[i] - y[j])));
const size = new Array(n).fill(1), id = x.map((_, i) => i), active = new Array(n).fill(true);
const merges: { a: number; b: number; height: number }[] = [];
for (let step = 0; step < n - 1; step++) {
let best = Infinity, a = -1, b = -1;
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++)
if (active[i] && active[j] && d[i][j] < best) [best, a, b] = [d[i][j], i, j];
for (let k = 0; k < n; k++) if (active[k] && k !== a && k !== b)
d[k][a] = d[a][k] = (size[a] * d[k][a] + size[b] * d[k][b]) / (size[a] + size[b]);
merges.push({ a: id[a], b: id[b], height: best });
active[b] = false; size[a] += size[b]; id[a] = n + step;
}
return merges;
};
@Component({
selector: "app-dendrogram-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 450px"></scichart-angular>`
})
export class DendrogramChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { drawLabels: false }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Merge height" }));
const { x, y } = getYourPoints(); // one x and one y value per item (scale the features first)
const n = x.length;
const merges = agglomerate(x, y);
// Leaf x positions from a walk down the tree; each merge sits midway between its children
const xPos: number[] = [], height: number[] = new Array(2 * n - 1).fill(0);
let next = 0;
const visit = (node: number) => {
if (node < n) { xPos[node] = next++; return; }
const { a, b, height: h } = merges[node - n];
visit(a); visit(b);
xPos[node] = (xPos[a] + xPos[b]) / 2; height[node] = h;
};
visit(2 * n - 2);
// Each merge is three segments: up from child a, across at the merge height, down to child b
const segments = new XyxyDataSeries(wasmContext);
merges.forEach(({ a, b, height: h }) => {
segments.appendRange(
[xPos[a], xPos[a], xPos[b]], [height[a], h, h],
[xPos[a], xPos[b], xPos[b]], [h, h, height[b]]
);
});
sciChartSurface.renderableSeries.add(
new FastLineSegmentRenderableSeries(wasmContext, { dataSeries: segments, stroke: "#50C7E0", strokeThickness: 1.5 })
);
// A draggable line to cut the tree: every branch it crosses is one cluster
sciChartSurface.annotations.add(
new HorizontalLineAnnotation({ y1: merges[n - 2].height * 0.6, stroke: "#FFFFFF", strokeDashArray: [6, 4], isEditable: true })
);
sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier(), new ZoomExtentsModifier());
return { sciChartSurface };
};
}
Key points:
- SciChart.js has no dendrogram series. Each merge is three segments in a
FastLineSegmentRenderableSeriesover anXyxyDataSeries, which holds a start and an end point per segment. The demo uses one series per cluster colour, plus a grey one for the joins above the cut. - The cut line is a
HorizontalLineAnnotationwithisEditable: true. ItsdragDeltaevent recounts the clusters as you drag, anddragEndedsnaps it to the middle of the gap. - The points are one
XyScatterRenderableSerieswith a palette provider:overridePointMarkerArgbreturns each point's cluster colour, so one series draws every cluster. - In DBSCAN mode, the k-distance curve is a
FastLineRenderableSerieson the same chart, and the same annotation sets eps.
See it in the demo app: JavaScript scatter chart · React scatter chart · Angular scatter chart, and for a clustered grid of values, JavaScript heatmap chart · React heatmap chart · Angular heatmap chart.
Go deeper: SciChart.js line segment series documentation, the scatter series documentation, and the scatter plot guide. For how laboratory and genomics software uses SciChart, see SciChart for diagnostics and life sciences.
Frequently asked questions
What is a dendrogram used for?
A dendrogram shows the result of hierarchical clustering: which items were grouped together, in what order, and how far apart the groups were when they joined. It is used to choose a number of clusters by cutting the tree, to order the rows and columns of a heatmap so similar items sit together, and to show relationships such as gene expression patterns, document topics, customer segments or the evolutionary tree of species.
How do you read a dendrogram?
Read a dendrogram from the bottom up. Each leaf is one item, and each join merges two clusters at a height equal to the distance between them under the chosen linkage. Two items are as similar as the height of the lowest join that connects them, not as close as their positions along the bottom. To get clusters, draw a horizontal line across the tree: every vertical branch it crosses is one cluster. Long vertical branches with no joins mean well separated clusters.
What is the difference between hierarchical clustering and k-means?
K-means needs the number of clusters in advance and finds that many groups by moving cluster centres, so it suits large datasets with round clusters of similar size. Hierarchical clustering builds a whole tree of nested clusters from a distance matrix, so you can choose the number of clusters afterwards by cutting the tree and can see how the clusters relate. It needs memory for every pair of points, which limits it to tens of thousands of items, and its merges can't be undone.
What is DBSCAN?
DBSCAN (density-based spatial clustering of applications with noise) groups points that sit in dense regions. A point with at least minPts points within a radius eps is a core point; clusters grow outwards from core points, points within reach of a core point join as border points, and everything else is labelled noise. It finds clusters of any shape without being told how many there are, but one eps value has to suit every cluster's density.
Which linkage method should I use?
Ward's method is a good default for numeric features when you expect compact, roughly equal clusters: it merges the pair that least increases the within-cluster sum of squares. Average linkage is a safer choice with other distance measures, such as correlation. Complete linkage gives tight clusters of similar diameter. Single linkage follows long, thin or curved shapes but chains clusters together through noise points. Try more than one and compare the trees.
How do I draw a dendrogram in JavaScript?
Run agglomerative clustering to get the list of merges, each with its two children and a height. Walk the tree from the top to give each leaf an x position, place each merge midway between its children, and draw every merge as three line segments: up from the left child, across at the merge height, and down to the right child. SciChart.js has no dendrogram series, so draw the segments with a FastLineSegmentRenderableSeries and an XyxyDataSeries, in plain JavaScript, React or Angular.
Sources
- Ester, M., Kriegel, H.-P., Sander, J. and Xu, X. (1996), A density-based algorithm for discovering clusters in large spatial databases with noise. Proceedings of the Second International Conference on Knowledge Discovery and Data Mining (KDD-96), 226–231. DBSCAN, core and border points, and the sorted k-distance plot.
- Schubert, E., Sander, J., Ester, M., Kriegel, H.-P. and Xu, X. (2017), DBSCAN revisited, revisited: why and how you should (still) use DBSCAN. ACM Transactions on Database Systems, 42(3), 19.
- Ward, J. H. (1963), Hierarchical grouping to optimize an objective function. Journal of the American Statistical Association, 58(301), 236–244.
- Lance, G. N. and Williams, W. T. (1967), A general theory of classificatory sorting strategies: 1. Hierarchical systems. The Computer Journal, 9(4), 373–380.
- Wishart, D. (1969), An algorithm for hierarchical classifications. Biometrics, 25(1), 165–170. Ward's method in the Lance–Williams formula.
- Bar-Joseph, Z., Gifford, D. K. and Jaakkola, T. S. (2001), Fast optimal leaf ordering for hierarchical clustering. Bioinformatics, 17(suppl 1), S22–S29.
- Campello, R. J. G. B., Moulavi, D. and Sander, J. (2013), Density-based clustering based on hierarchical density estimates. Advances in Knowledge Discovery and Data Mining (PAKDD 2013), Lecture Notes in Computer Science 7819, 160–172. HDBSCAN.
- Eisen, M. B., Spellman, P. T., Brown, P. O. and Botstein, D. (1998), Cluster analysis and display of genome-wide expression patterns. Proceedings of the National Academy of Sciences, 95(25), 14863–14868.
- Sokal, R. R. and Rohlf, F. J. (1962), The comparison of dendrograms by objective methods. Taxon, 11(2), 33–40. The cophenetic correlation.
- Hubert, L. and Arabie, P. (1985), Comparing partitions. Journal of Classification, 2, 193–218. The adjusted Rand index.
- Hastie, T., Tibshirani, R. and Friedman, J. (2009), The Elements of Statistical Learning, 2nd edition, Springer, section 14.3.12 (hierarchical clustering).