Skip to main content

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.

Two charts in a dark navy theme: on the left, a scatter plot of 180 points in four groups, each coloured by its cluster; on the right, the dendrogram of the same points, with each cluster's branches in the matching colour, grey joins above them and a dashed horizontal cut line labelled 4 clusters

Four groups of points clustered with Ward's method, and the dendrogram cut into four clusters (sample data). Try the interactive version.

Key takeaways
  • 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:

ABCDE
A02.006.006.7110.44
B2.0006.326.0810.05
C6.006.3203.005.00
D6.716.083.0004.00
E10.4410.055.004.000

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:

  1. 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.
  2. The smallest is now C–D, 3.00. Merge them into CD at height 3.
  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.
  4. Only AB and CDE are left. Their farthest pair is A–E, so the last merge is at 10.44.

Left: the five points A to E on a grid, with A and B close together, C and D close together and E on its own to the right, each group circled. Right: their complete-linkage dendrogram, with A and B joining at height 2, C and D at 3, E joining them at 5 and the two groups joining at 10.44, and a dashed cut line at height 4 that crosses three branches, giving three clusters. Callout 1 marks the tallest join and callout 2 the leaves

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:

MergeSingleCompleteAverageWard
A + B2.002.002.002.00
C + D3.003.003.003.00
CD + E4.005.004.504.93
AB + CDE6.0010.447.6011.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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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 nAn_A and nBn_B points. It decides the shape of the clusters you get.

Four panels of the same two clusters, three points on the left and four on the right. Single linkage joins the closest pair with one line, complete linkage the farthest pair, average linkage draws all twelve lines between the clusters, and Ward's method marks each cluster's centroid with a cross and joins the two with a dashed line

LinkageDistance between clusters A and BTends to giveWatch out for
Single (nearest neighbour)The closest pair of points, one from eachLong, thin or curved clustersChaining: one stray point or a thin trail joins two clusters
Complete (farthest neighbour)The farthest pair of pointsCompact clusters of similar diameterSplitting large clusters; sensitive to outliers
Average (UPGMA)The mean of all nA×nBn_A \times n_B pair distancesA middle way between single and completeChanges if the distances are transformed, for example squared; single and complete don't
Ward's methodThe increase in the within-cluster sum of squares if A and B mergeRound clusters of similar size, like k-meansAssumes 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 aˉ\bar{a} and bˉ\bar{b}, the merge height reported by most software is

d(A,B)=2 nAnBnA+nB  ∥aˉ−bˉ∥d(A, B) = \sqrt{\frac{2\, n_A n_B}{n_A + n_B}}\; \lVert \bar{a} - \bar{b} \rVert

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.

DatasetSingleCompleteAverageWardDBSCAN (eps 0.35, minPts 5)
Four blobs1.001.001.001.000.98
Blobs with a trail and outliers0.210.850.840.840.86
Two moons1.000.310.290.141.00
Two rings1.000.15−0.07−0.021.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 dense group of eight filled points, each with at least four points within radius eps, marked as core points. A circle of radius eps around one of them reaches a ring-shaped point to its right, marked as a border point because its own circle holds only two points. A cross far away is marked as noise

  • 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-meansDBSCAN
Number of clustersChosen afterwards, by cutting the treeSet in advance (k)Follows from eps and minPts
Cluster shapesDepends on linkage: single follows any shape, Ward prefers roundRound, similar sizeAny shape, as long as density is similar
OutliersKept in a cluster (or as tiny clusters)Pull centres towards themLabelled as noise
OutputA full tree of nested clustersOne flat partition and the centresOne flat partition plus noise
Scales toTens of thousands of points (memory for every pair)MillionsHundreds of thousands to millions, with a spatial index
DeterministicYesNo: depends on the starting centresYes, apart from border points between clusters
Best forSmall to medium data where the structure between clusters matters, ordering heatmapsLarge data, compact clusters, a known kSpatial 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.

// 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();

Key points:

  • SciChart.js has no dendrogram series. Each merge is three segments in a FastLineSegmentRenderableSeries over an XyxyDataSeries, 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 HorizontalLineAnnotation with isEditable: true. Its dragDelta event recounts the clusters as you drag, and dragEnded snaps it to the middle of the gap.
  • The points are one XyScatterRenderableSeries with a palette provider: overridePointMarkerArgb returns each point's cluster colour, so one series draws every cluster.
  • In DBSCAN mode, the k-distance curve is a FastLineRenderableSeries on 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​