Skip to main content

K-Means Clustering

What is k-means clustering?​

K-means clustering is an unsupervised machine learning method that splits a set of unlabelled points into k groups, where you choose k. Each group is represented by its centre, or centroid, and every point belongs to the group whose centroid is nearest. The algorithm moves the centroids until the groups are as compact as it can make them.

A k-means clustering chart in a dark navy theme: about 300 points in four groups, each coloured by its cluster, with a large marker at each centroid and dashed lines tracing how the centroids moved, over shaded regions showing which centroid is nearest. Beside it, an elbow plot of inertia against the number of clusters, bending sharply at k = 4, and a silhouette plot peaking at k = 4

K-means on four simulated groups of points, with the elbow and silhouette plots used to choose k (sample data). Try the interactive version.

Key takeaways
  • K-means repeats two steps: assign each point to its nearest centroid, then move each centroid to the mean of its points.
  • It minimises inertia, the sum of squared distances from points to their centroids, and stops at a local minimum that depends on the start.
  • Choose k with the elbow plot and the silhouette score together, and with what the groups mean for your problem.
  • It assumes round clusters of similar size on comparable scales. Moons, rings and unscaled features break it.
  • K-means clusters unlabelled data. K-nearest neighbours (k-NN) classifies new points from labelled data.

What is clustering?​

Clustering is grouping items so that items in the same group are more alike than items in different groups, without being told what the groups are. It is the main kind of unsupervised learning: there are no labels to learn from, only the data.

Methods differ in what they mean by a group:

  • Centroid-based methods, such as k-means, describe each group by a centre and assign points to the nearest one.
  • Hierarchical methods build a tree of merges or splits, drawn as a dendrogram (see hierarchical clustering).
  • Density-based methods, such as DBSCAN, call a group any dense region separated by sparse space, and leave isolated points unassigned as noise.
  • Model-based methods, such as Gaussian mixture models, assume each group is drawn from a probability distribution and give each point a probability of belonging to each group.

K-means is the simplest of these to write, quick to run and easy to picture. Hugo Steinhaus described the idea in 1956. Stuart Lloyd wrote the standard algorithm at Bell Labs in 1957, though it was not published until 1982, and James MacQueen gave it the name "k-means" in 1967.

How the k-means algorithm works​

The standard version is Lloyd's algorithm. With the data and a chosen k:

  1. Start: place k centroids, for example on k data points picked at random.
  2. Assign: give each point to its nearest centroid, by straight-line (Euclidean) distance.
  3. Update: move each centroid to the mean of the points assigned to it.
  4. Repeat steps 2 and 3 until no point changes cluster.

Step 2 draws the boundaries and step 3 moves the centres they are drawn around. The two steps take turns until the centroids stop moving, usually after a handful of iterations on well-separated data. Each iteration costs about n × k × d distance calculations for n points with d features, which is why k-means scales to millions of points.

The objective: inertia​

K-means minimises the inertia, also called the within-cluster sum of squares (WCSS): the sum, over every point, of the squared distance to its cluster's centroid.

inertia=∑j=1k∑xi∈Cj∥xi−μj∥2\text{inertia} = \sum_{j=1}^{k} \sum_{x_i \in C_j} \lVert x_i - \mu_j \rVert^2

Here CjC_j is cluster j and μj\mu_j is its centroid. Neither step can raise this number. Assigning a point to a nearer centroid can only shorten its distance, and the mean is the position that minimises the sum of squared distances to a set of points. Since there are only finitely many ways to split n points into k groups, the algorithm must stop.

A worked example​

Take six points and k = 2: P1 (1, 2), P2 (2, 1), P3 (2, 3), P4 (5, 4), P5 (6, 6) and P6 (7, 5). Start with the centroids on P1 and P3, a deliberately poor start since both sit in the same group.

Three panels showing k-means on six points. In panel 1, the six points are grey and the two starting centroids sit on P1 and P3. In panel 2, P1 and P2 are coloured blue and P3 to P6 orange, split by a dashed boundary halfway between the centroids, and arrows move the centroids to (1.5, 1.5) and (5, 4.5); the inertia falls from 66 to 20. In panel 3, P3 has switched to blue, and the centroids move to (1.67, 2) and (6, 5), where the inertia is 6.67

StepCentroid ACentroid BCluster ACluster BInertia
Start, then assign(1, 2)(2, 3)P1, P2P3, P4, P5, P666.00
Update(1.5, 1.5)(5, 4.5)P1, P2P3, P4, P5, P620.00
Assign: P3 switches(1.5, 1.5)(5, 4.5)P1, P2, P3P4, P5, P611.25
Update(1.67, 2)(6, 5)P1, P2, P3P4, P5, P66.67
Assign: nothing changes(1.67, 2)(6, 5)P1, P2, P3P4, P5, P66.67, converged

P3 at (2, 3) moves because, after the first update, it is 1.58 from centroid A at (1.5, 1.5) and 3.35 from centroid B at (5, 4.5). The final inertia, 6.67, is the lowest possible for these six points: checking all 31 ways of splitting them into two non-empty groups gives the same answer.

Initialisation: random starts, k-means++ and local minima​

K-means always converges, but not always to the best answer. Where it ends depends on where the centroids start. Two centroids that start in the same natural group can leave another group with none, and the algorithm cannot climb out of that, because every single step makes the inertia smaller or leaves it the same. Finding the best possible clustering is NP-hard, even for points in a plane when k can be any number (for a fixed k it can be solved in polynomial time, though far too slowly to be practical), so every practical method settles for a good local minimum.

Two ways to start:

  • Random points (Forgy's method): pick k data points at random as the centroids.
  • K-means++ (Arthur and Vassilvitskii, 2007): pick the first centroid at random, then pick each next one from the data with probability proportional to its squared distance from the nearest centroid already chosen. This spreads the starts out. The authors proved the expected inertia right after seeding is within a factor of O(log k) of the optimum.

On the four-group dataset in the demo, with k = 4, 27 of 200 random-point starts ended more than 1% above the best inertia (the worst at 2,662 against the best 714), against 10 of 200 for k-means++. The standard fix is to run k-means several times from different starts and keep the lowest inertia. Libraries do this by default; the demo's side charts use the best of 10 k-means++ starts at each k.

How to choose k: the elbow method and silhouette score​

K-means needs k up front. Inertia can't choose it on its own: it always falls as k rises, down to zero when every point is its own cluster. The two most used checks look at how fast it falls and how well separated the clusters are.

The elbow method​

The elbow method plots the inertia against k. Adding clusters cuts the inertia quickly while each new centroid splits a real group, then slowly once the groups are already found and extra centroids only split them. The bend between the two, the elbow, suggests k.

For the demo's four-group data (best of 10 k-means++ starts):

k12345678
Inertia7,9884,2692,227714644576515462
Mean silhouette–0.4700.5640.6890.5960.5040.4080.339

Going from 3 to 4 clusters removes 1,513; going from 4 to 5 removes 70. The elbow is at k = 4. On real data the curve often bends gently with no clear corner, and two people can read different elbows from the same plot.

The silhouette score​

The silhouette of a point measures how much closer it is to its own cluster than to the next nearest one (Rousseeuw, 1987). For point i:

  • a(i) is the mean distance from i to the other points in its cluster;
  • b(i) is the smallest mean distance from i to the points of any other cluster.
s(i)=b(i)−a(i)max⁡(a(i), b(i))s(i) = \frac{b(i) - a(i)}{\max\big(a(i),\, b(i)\big)}

Three clusters of points. One blue point, labelled point i, has solid lines to the other points in its own blue cluster, with a mean length a = 1.36, and dashed lines to the orange cluster, the nearest other cluster, with a mean length b = 4.68. A green cluster further away has a mean distance of 5.68 and is ignored. The formula gives s = (4.68 - 1.36) / 4.68 = 0.71, marked on a scale from -1 to 1 labelled: below 0, closer to another cluster; near 0, on a boundary; near 1, well inside its own cluster

The silhouette score of a clustering is the mean of s(i) over all points, and the k with the highest score is the silhouette method's choice. It needs at least two clusters. A point alone in its cluster scores 0 by convention.

Mean silhouetteKaufman and Rousseeuw's reading
0.71 to 1.00Strong structure
0.51 to 0.70Reasonable structure
0.26 to 0.50Weak structure, possibly artificial
0.25 or lessNo substantial structure

In the six-point example, the final clusters have a mean silhouette of 0.65; P4 has the lowest, 0.44, because it is the closest of B's points to cluster A. In the four-group data, the score peaks at 0.689 for k = 4, agreeing with the elbow.

Elbow vs silhouette​

Elbow methodSilhouette score
MeasuresCompactness: inertiaCompactness against separation
Choice of kThe bend, read by eyeThe highest score
Works at k = 1YesNo, needs k ≥ 2
CostCheap: one pass per kAll pairwise distances: n² per k
Weak spotGentle curves with no clear bendFavours round, well-separated clusters, like k-means itself

Other indices, such as the gap statistic (Tibshirani, Walther and Hastie, 2001), Calinski–Harabasz and Davies–Bouldin, answer the same question in different ways. When they disagree, the data probably doesn't have one natural k, and the choice comes down to which grouping is most useful.

K-means and Voronoi cells​

When the algorithm stops, each centroid owns the region of space closer to it than to any other centroid. These regions are the Voronoi cells of the centroids, and their edges are the straight lines halfway between pairs of centroids. The dashed boundaries in the worked example are such edges, and the shaded regions in the demo are the Voronoi diagram of its centroids. See the Voronoi diagram guide for how the cells are built.

Because every boundary is a straight line, k-means can only cut space into convex pieces. A new point is classified by the cell it falls in, so a trained k-means model works as a simple classifier for new data, a property used in vector quantisation.

Limitations of k-means: when it fails​

K-means works best when the clusters are round, about the same size and spread, and measured on comparable scales. Each demo dataset breaks one of those assumptions:

Dataset in the demoWhat goes wrong (best of 10 starts)Why
Uneven sizes: one wide group of 220 points, two tight groups of 40At k = 3, 38 points from the wide group go to the small clustersThe boundary sits halfway between centroids, regardless of spread
Moons: two interleaved half-ringsAt k = 2, only 75% of points are grouped with their own moonThe clusters are not convex, and a straight cut can't follow a curve
Circles: a ring around a discAt k = 2, 59% agree with the true groups, little better than chanceBoth groups share a centre, so no centroid can describe either
Unscaled features: feature 1 in units 20 times largerAt k = 4, 53% correct; after standardising, 100%Distance is dominated by the feature with the largest numbers

On the unscaled data, the elbow and the silhouette score both point to k = 2, the two groups that feature 1 separates, so the checks for k are misled by the same scaling problem. After standardising, both point to k = 4.

Outliers cause a fifth problem. A mean is pulled by extreme values, so a few far-off points can drag a centroid away from its group, or claim a centroid of their own. K-medoids, which uses an actual data point as each centre, and trimmed variants are less sensitive.

For curved or nested shapes, DBSCAN, spectral clustering or kernel k-means do better; for elongated or differently sized groups, a Gaussian mixture model can fit an ellipse to each.

K-means vs k-NN​

K-means and k-nearest neighbours are often confused because both have a k and both measure distances. They solve different problems:

K-meansK-nearest neighbours (k-NN)
Type of learningUnsupervised: no labelsSupervised: needs labelled training data
TaskClustering: find groupsClassification or regression: predict a label or value
What k meansThe number of clustersThe number of neighbours that vote
TrainingIterates until the centroids settleNone: stores the training data
Prediction for a new pointThe nearest centroid's clusterThe majority label (or mean value) of its k nearest training points
OutputCluster numbers with no meaning until you name themClass labels from the training data
BoundariesStraight lines between centroids (Voronoi cells)Can be any shape, following the training points
Choosing kElbow method, silhouette scoreCross-validation on held-out labels

They can work together: k-means can shrink a large training set to a few hundred centroids, and k-NN can then classify against those.

K-means vs DBSCAN vs hierarchical clustering​

K-means suits compact, round groups of similar size; DBSCAN suits irregular shapes and noisy data; hierarchical clustering suits smaller datasets where the nesting of groups matters.

MethodYou chooseCluster shapesOutliersScales to large dataBest for
K-meanskRound, convex, similar sizePulled into clustersYes: linear in n per iterationQuick, compact groups; segmentation; quantisation
Hierarchical clusteringLinkage, then where to cut the treeDepends on linkage; single linkage follows chainsShow up as late mergesHard beyond tens of thousands: needs all pairwise distancesSmall data where the nested structure matters
DBSCANNeighbourhood radius and minimum pointsAny shape, if density is similarLabelled as noiseYes, with a spatial indexIrregular shapes, spatial data, noise
Gaussian mixture modelNumber of componentsEllipses of any size and tiltLow-probability pointsModerateOverlapping groups, soft membership

How to visualise clustering results​

With two features, a scatter plot coloured by cluster label, with the centroids marked, shows the whole result. Shading each centroid's region adds the boundaries a new point would be classified by. Most data has more than two features, so you need other views:

  • Project to two dimensions with PCA or a similar method, then draw the scatter plot. See dimensionality reduction.
  • Draw a parallel coordinates plot with one line per point, coloured by cluster, to compare clusters across every feature.
  • Plot the elbow and silhouette curves to show how k was chosen, as in the demo.
  • Draw a silhouette plot: each point's s(i) as a horizontal bar, sorted within each cluster. Thin clusters or bars below zero flag poor groups.
  • Show a heatmap of the centroids, one row per cluster and one column per feature, to describe what each cluster stands for.

Where k-means is used​

K-means is used wherever a large set of items needs a handful of representative groups or values.

  • Customer and market segmentation: grouping customers by spending, frequency and recency.
  • Colour quantisation and image compression: replacing millions of colours with the k centroid colours.
  • Vector quantisation in signal processing and speech coding, where Lloyd developed the method for pulse-code modulation.
  • Document and search-result grouping, on word or embedding vectors.
  • Manufacturing and test data: grouping similar measurements, test results or failure patterns, for example in semiconductor manufacturing.
  • As a building block: seeding Gaussian mixture models, building visual vocabularies for images, and picking representative samples from large datasets.

Common k-means clustering mistakes​

Most k-means mistakes come from unscaled features, a single unlucky start, or trusting the k groups it always returns.

  • Forgetting to scale the features. A feature measured in thousands swamps one measured in fractions. Standardise (z-scores) or normalise first, unless the units are already comparable.
  • Trusting a single run. One unlucky start can merge two real groups. Use k-means++ and keep the best of several runs.
  • Taking the elbow as proof. Inertia always falls with k, and on real data the bend is often vague. Back it up with the silhouette score and a look at the clusters.
  • Reading cluster numbers as meaningful. Cluster 1 in one run may be cluster 3 in the next. Name clusters by their centroids, not their numbers.
  • Using k-means on categorical data. Means and Euclidean distances make no sense for categories such as colour or country. Use k-modes, or a method with a suitable distance.
  • Clustering high-dimensional data directly. With hundreds of features, distances between points become similar and clusters blur. Reduce the dimensions first.
  • Expecting clusters to exist. K-means always returns k groups, even from uniform noise. A low silhouette score, below about 0.25, suggests there is no real structure to find.

How to make a k-means clustering chart in JavaScript, React or Angular​

The demo runs k-means, the elbow plot and the silhouette score in the browser, and redraws the points, the centroids and the shaded regions after every half-iteration, about three times a second while it runs.

Pick a Dataset and the number of clusters with k, and choose how the centroids Start: k-means++ or random points. Step runs one half of an iteration at a time (assign, then update), Run plays it to convergence, and New start tries different starting centroids; press it a few times on the four blobs and some runs settle at about three times the best inertia, with two centroids sharing one group. Standardise features rescales both features before clustering. Click on the chart to add a point; Reset points removes them. The side charts show the best of 10 starts at each k, with a ring for the current run. The main chart zooms with the wheel, pans when dragged and fits the data again on a double-click.

Here is the code for this chart. K-means, k-means++ and the silhouette score are plain JavaScript; SciChart.js draws the points and centroids as scatter series, the centroid paths as line series and the regions as a heatmap.

// K-means clustering, step by step: points coloured by cluster, centroids and their paths, and the Voronoi
// regions as a heatmap, with an elbow plot and a silhouette plot computed live. Charted with SciChart.js.
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
EAxisAlignment,
XyDataSeries,
XyScatterRenderableSeries,
FastLineRenderableSeries,
EllipsePointMarker,
MetadataPaletteProvider,
UniformHeatmapDataSeries,
UniformHeatmapRenderableSeries,
HeatmapColorMap,
CustomChartModifier2D,
translateFromCanvasToSeriesViewRect,
LegendModifier,
ELegendPlacement,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- K-means maths (plain JavaScript, no library needed). A point is [x, y]. ---

const squaredDistance = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2;

// Index of the centroid nearest to point p
function nearest(p, centroids) {
let best = 0;
let bestDistance = Infinity;
for (let c = 0; c < centroids.length; c++) {
const d = squaredDistance(p, centroids[c]);
if (d < bestDistance) {
bestDistance = d;
best = c;
}
}
return best;
}

// Starting centroids. "random": k distinct data points picked at random (Forgy's method).
// "plusplus": k-means++ (Arthur and Vassilvitskii, 2007): the first centre is a random point; each next one is a
// point picked with probability proportional to its squared distance from the nearest centre chosen so far.
function initialCentroids(points, k, method, random) {
if (method === "random") {
const chosen = [];
while (chosen.length < Math.min(k, points.length)) {
const i = Math.floor(random() * points.length);
if (!chosen.includes(i)) chosen.push(i);
}
return chosen.map((i) => [...points[i]]);
}
const centroids = [[...points[Math.floor(random() * points.length)]]];
const d2 = points.map((p) => squaredDistance(p, centroids[0]));
while (centroids.length < k) {
const total = d2.reduce((sum, d) => sum + d, 0);
let target = random() * total;
let pick = 0;
while (pick < points.length - 1 && target > d2[pick]) target -= d2[pick++];
centroids.push([...points[pick]]);
for (let i = 0; i < points.length; i++) d2[i] = Math.min(d2[i], squaredDistance(points[i], points[pick]));
}
return centroids;
}

// Step 1, assignment: give every point the label of its nearest centroid. Returns how many labels changed.
function assignPoints(points, centroids, labels) {
let changed = 0;
for (let i = 0; i < points.length; i++) {
const c = nearest(points[i], centroids);
if (labels[i] !== c) changed++;
labels[i] = c;
}
return changed;
}

// Step 2, update: move each centroid to the mean of its points. A centroid with no points stays where it is.
function updateCentroids(points, labels, centroids) {
const sums = centroids.map(() => [0, 0, 0]);
for (let i = 0; i < points.length; i++) {
const s = sums[labels[i]];
s[0] += points[i][0];
s[1] += points[i][1];
s[2]++;
}
return centroids.map((c, j) => (sums[j][2] > 0 ? [sums[j][0] / sums[j][2], sums[j][1] / sums[j][2]] : c));
}

// The objective k-means minimises: inertia, the within-cluster sum of squared distances to the centroids
function inertia(points, labels, centroids) {
let sum = 0;
for (let i = 0; i < points.length; i++) sum += squaredDistance(points[i], centroids[labels[i]]);
return sum;
}

// Lloyd's algorithm to convergence: assign, update, repeat until no label changes
function kMeans(points, k, method, random, maxIterations = 100) {
let centroids = initialCentroids(points, k, method, random);
const labels = new Array(points.length).fill(-1);
for (let it = 0; it < maxIterations; it++) {
if (assignPoints(points, centroids, labels) === 0) break;
centroids = updateCentroids(points, labels, centroids);
}
return { centroids, labels, inertia: inertia(points, labels, centroids) };
}

// Mean silhouette score. For point i: a = mean distance to the other points in its cluster, b = the smallest mean
// distance to the points of another cluster, s = (b - a) / max(a, b). A point alone in its cluster scores 0.
function meanSilhouette(points, labels, k) {
if (k < 2) return NaN;
const sizes = new Array(k).fill(0);
labels.forEach((c) => sizes[c]++);
let total = 0;
const sumTo = new Array(k);
for (let i = 0; i < points.length; i++) {
sumTo.fill(0);
for (let j = 0; j < points.length; j++) {
if (j !== i) sumTo[labels[j]] += Math.sqrt(squaredDistance(points[i], points[j]));
}
const own = labels[i];
if (sizes[own] < 2) continue; // s = 0
const a = sumTo[own] / (sizes[own] - 1);
let b = Infinity;
for (let c = 0; c < k; c++) if (c !== own && sizes[c] > 0) b = Math.min(b, sumTo[c] / sizes[c]);
if (Number.isFinite(b)) total += (b - a) / Math.max(a, b);
}
return total / points.length;
}

// Standardise each feature to mean 0 and standard deviation 1 (z-scores), so both count equally in distances
function scaler(points, on) {
const n = points.length;
const mean = [0, 1].map((d) => points.reduce((s, p) => s + p[d], 0) / n);
const sd = [0, 1].map((d) => Math.sqrt(points.reduce((s, p) => s + (p[d] - mean[d]) ** 2, 0) / n) || 1);
return {
forward: (p) => (on ? [(p[0] - mean[0]) / sd[0], (p[1] - mean[1]) / sd[1]] : p),
back: (p) => (on ? [p[0] * sd[0] + mean[0], p[1] * sd[1] + mean[1]] : p)
};
}

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOURS = ["#50C7E0", "#F48420", "#3BD16F", "#E36FD4", "#FFE066", "#9B8AFB", "#EF5350", "#C8D3E8"];
const zoom = () => [new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier()];

// 1. The main chart: Voronoi regions (heatmap), points coloured by cluster, centroid paths and centroids
const main = await SciChartSurface.create(ui.mainDiv, { theme });
const xAxis = new NumericAxis(main.wasmContext, { axisTitle: "Feature 1", autoRange: EAutoRange.Never, drawMinorGridLines: false });
const yAxis = new NumericAxis(main.wasmContext, {
axisTitle: "Feature 2",
axisAlignment: EAxisAlignment.Left,
autoRange: EAutoRange.Never,
drawMinorGridLines: false
});
main.sciChartSurface.xAxes.add(xAxis);
main.sciChartSurface.yAxes.add(yAxis);

// Each heatmap cell holds the index of its nearest centroid; the colour map gives cluster c the colour COLOURS[c]
const regionData = new UniformHeatmapDataSeries(main.wasmContext, {
zValues: Array.from({ length: GRID }, () => new Array(GRID).fill(NaN)),
xStart: 0,
xStep: 1,
yStart: 0,
yStep: 1
});
main.sciChartSurface.renderableSeries.add(
new UniformHeatmapRenderableSeries(main.wasmContext, {
dataSeries: regionData,
opacity: 0.3,
colorMap: new HeatmapColorMap({
minimum: 0,
maximum: MAX_K - 1,
gradientStops: COLOURS.map((color, c) => ({ offset: c / (MAX_K - 1), color }))
})
})
);
// All points in one scatter series; each point's colour comes from its metadata (MetadataPaletteProvider)
const pointData = new XyDataSeries(main.wasmContext, { dataSeriesName: "Points" });
main.sciChartSurface.renderableSeries.add(
new XyScatterRenderableSeries(main.wasmContext, {
dataSeries: pointData,
pointMarker: new EllipsePointMarker(main.wasmContext, { width: 7, height: 7, strokeThickness: 1, fill: "#FFFFFF", stroke: "#0B1A33" }),
paletteProvider: new MetadataPaletteProvider()
})
);
// One line per centroid, tracing where it has moved
const pathData = COLOURS.map(() => new XyDataSeries(main.wasmContext));
pathData.forEach((dataSeries, c) =>
main.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(main.wasmContext, { dataSeries, stroke: COLOURS[c], strokeThickness: 2, strokeDashArray: [4, 3] })
)
);
const centroidData = new XyDataSeries(main.wasmContext, { dataSeriesName: "Centroids" });
main.sciChartSurface.renderableSeries.add(
new XyScatterRenderableSeries(main.wasmContext, {
dataSeries: centroidData,
pointMarker: new EllipsePointMarker(main.wasmContext, { width: 20, height: 20, strokeThickness: 3, fill: "#FFFFFF", stroke: "#FFFFFF" }),
paletteProvider: new MetadataPaletteProvider()
})
);

// Click (without dragging) on the main chart to add a point there
class AddPointModifier extends CustomChartModifier2D {
downPoint = undefined;
modifierMouseDown(args) {
super.modifierMouseDown(args);
this.downPoint = args.mousePoint;
}
modifierMouseUp(args) {
super.modifierMouseUp(args);
const down = this.downPoint;
if (!down || Math.hypot(args.mousePoint.x - down.x, args.mousePoint.y - down.y) > 5) return;
const p = translateFromCanvasToSeriesViewRect(args.mousePoint, this.parentSurface.seriesViewRect);
if (!p) return;
addPoint([xAxis.getCurrentCoordinateCalculator().getDataValue(p.x), yAxis.getCurrentCoordinateCalculator().getDataValue(p.y)]);
}
}
main.sciChartSurface.chartModifiers.add(new AddPointModifier(), ...zoom());

// 2 and 3. Elbow plot (inertia against k) and silhouette plot (mean silhouette against k): a line for the best of
// several k-means++ starts at each k, and a large marker for the run on the main chart
async function scoreChart(div, yTitle, colour, labelPrecision) {
const { sciChartSurface, wasmContext } = await SciChartSurface.create(div, { theme });
sciChartSurface.xAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Number of clusters k",
visibleRange: new NumberRange(0.5, MAX_K + 0.5),
autoTicks: false,
majorDelta: 1,
minorDelta: 1,
labelPrecision: 0
})
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: yTitle,
axisAlignment: EAxisAlignment.Left,
autoRange: EAutoRange.Always,
growBy: new NumberRange(0.1, 0.6), // headroom for the legend
labelPrecision
})
);
const best = new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { dataSeriesName: "Best of 10 starts", dataIsSortedInX: true }),
stroke: colour,
strokeThickness: 2.5,
pointMarker: new EllipsePointMarker(wasmContext, { width: 8, height: 8, fill: colour, stroke: colour })
});
const run = new XyScatterRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { dataSeriesName: "This run" }),
pointMarker: new EllipsePointMarker(wasmContext, { width: 16, height: 16, fill: "#FFFFFF00", stroke: "#FFFFFF", strokeThickness: 2.5 })
});
sciChartSurface.renderableSeries.add(best, run);
const legend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopRight });
sciChartSurface.chartModifiers.add(
legend,
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
...zoom()
);
return { best, run, legend };
}
const elbow = await scoreChart(ui.elbowDiv, "Inertia", "#50C7E0", 0);
const silhouette = await scoreChart(ui.silhouetteDiv, "Mean silhouette", "#F48420", 2);

const setXy = (dataSeries, x, y, metadata = undefined) => {
dataSeries.clear();
dataSeries.appendRange(x, y, metadata);
};

// --- State and controls ---
let points = []; // the data, in chart units
let work = []; // the data the algorithm sees: standardised or not
let scale = scaler([[0, 0]], false);
let centroids = []; // in work units
let labels = [];
let iteration = 0;
let nextStep = "update"; // the algorithm alternates: assign points, then move centroids
let converged = false;
let lastChanged = 0;
let startSeed = 1;
let timer;
let scoresTimer;

const k = () => Number(ui.kInput.value);

// Shade the Voronoi cells: each grid cell gets the index of the centroid nearest to its centre
function drawRegions() {
const xr = xAxis.visibleRange;
const yr = yAxis.visibleRange;
const xStep = (xr.max - xr.min) / GRID;
const yStep = (yr.max - yr.min) / GRID;
const z = [];
for (let row = 0; row < GRID; row++) {
const line = new Array(GRID);
for (let col = 0; col < GRID; col++) {
line[col] = nearest(scale.forward([xr.min + (col + 0.5) * xStep, yr.min + (row + 0.5) * yStep]), centroids);
}
z.push(line);
}
regionData.xStart = xr.min;
regionData.xStep = xStep;
regionData.yStart = yr.min;
regionData.yStep = yStep;
regionData.setZValues(z);
}

function draw() {
const meta = labels.map((c) => {
const colour = c >= 0 ? COLOURS[c] : "#FFFFFF";
return { isSelected: false, fill: colour, stroke: "#0B1A33" };
});
setXy(pointData, points.map((p) => p[0]), points.map((p) => p[1]), meta);
const shown = centroids.map(scale.back);
setXy(
centroidData,
shown.map((c) => c[0]),
shown.map((c) => c[1]),
shown.map((_, c) => ({ isSelected: false, fill: COLOURS[c], stroke: "#FFFFFF" }))
);
shown.forEach((c, j) => pathData[j].append(c[0], c[1]));
drawRegions();
const currentInertia = inertia(work, labels, centroids);
const currentSilhouette = meanSilhouette(work, labels, k());
setXy(elbow.run.dataSeries, [k()], [currentInertia]);
setXy(silhouette.run.dataSeries, Number.isFinite(currentSilhouette) ? [k()] : [], Number.isFinite(currentSilhouette) ? [currentSilhouette] : []);
const phase = nextStep === "update" ? `points assigned to the nearest centroid (${lastChanged} changed)` : "centroids moved to the mean of their points";
ui.status.textContent =
`Iteration ${iteration}: ${converged ? "converged, no point changed cluster" : phase} · ` +
`inertia ${currentInertia.toFixed(1)} · silhouette ${Number.isFinite(currentSilhouette) ? currentSilhouette.toFixed(3) : "– (needs k ≥ 2)"} · ` +
`${points.length} points`;
}

// One half-step of Lloyd's algorithm
function step() {
if (converged) return;
if (nextStep === "update") {
centroids = updateCentroids(work, labels, centroids);
nextStep = "assign";
} else {
iteration++;
lastChanged = assignPoints(work, centroids, labels);
converged = lastChanged === 0;
nextStep = "update";
}
draw();
if (converged) stop();
}

function stop() {
clearInterval(timer);
timer = undefined;
ui.runButton.textContent = "Run";
}
function run() {
if (timer) return stop();
if (converged) restart();
ui.runButton.textContent = "Pause";
timer = setInterval(step, 350);
}

// Place new starting centroids (seeded, so "New start" gives a different but repeatable start) and assign
function restart() {
stop();
centroids = initialCentroids(work, k(), ui.initSelect.value, seededRandom(startSeed * 7919));
labels = new Array(work.length).fill(-1);
lastChanged = assignPoints(work, centroids, labels);
iteration = 0;
nextStep = "update";
converged = false;
pathData.forEach((d) => d.clear());
draw();
}

// Elbow and silhouette curves: best of 10 k-means++ starts for k = 1 to MAX_K (debounced while clicking points)
function updateScores() {
clearTimeout(scoresTimer);
scoresTimer = setTimeout(() => {
const ks = [];
const inertias = [];
const silhouettes = [];
for (let kk = 1; kk <= MAX_K; kk++) {
const random = seededRandom(kk * 101);
let best;
for (let s = 0; s < 10; s++) {
const result = kMeans(work, kk, "plusplus", random);
if (!best || result.inertia < best.inertia) best = result;
}
ks.push(kk);
inertias.push(best.inertia);
silhouettes.push(meanSilhouette(work, best.labels, kk));
}
setXy(elbow.best.dataSeries, ks, inertias);
setXy(silhouette.best.dataSeries, ks.slice(1), silhouettes.slice(1));
const bestK = ks.slice(1)[silhouettes.slice(1).indexOf(Math.max(...silhouettes.slice(1)))];
silhouette.best.dataSeries.dataSeriesName = `Best of 10 starts (peak at k = ${bestK})`;
silhouette.legend.sciChartLegend?.setRenderableSeriesArray([silhouette.best, silhouette.run]); // show the new name
}, 120);
}

// Work in the scaled or unscaled space, and fit the axes and the heatmap to the data
function prepareData() {
scale = scaler(points, ui.scaleCheckbox.checked);
work = points.map(scale.forward);
const xs = points.map((p) => p[0]);
const ys = points.map((p) => p[1]);
const pad = (min, max) => new NumberRange(min - 0.08 * (max - min), max + 0.08 * (max - min));
xAxis.visibleRange = pad(Math.min(...xs), Math.max(...xs));
yAxis.visibleRange = pad(Math.min(...ys), Math.max(...ys));
updateScores();
}

function loadDataset() {
points = makeDataset(ui.datasetSelect.value);
prepareData();
restart();
}

// A clicked point joins the nearest cluster; the algorithm carries on from the current centroids
function addPoint(p) {
points.push(p);
work.push(scale.forward(p));
labels.push(nearest(work[work.length - 1], centroids));
lastChanged = 1; // the new point
converged = false;
nextStep = "update";
updateScores();
draw();
}

ui.kOutput.textContent = String(k());
ui.kInput.addEventListener("input", () => {
ui.kOutput.textContent = String(k());
restart();
});
ui.datasetSelect.addEventListener("change", loadDataset);
ui.initSelect.addEventListener("change", restart);
ui.scaleCheckbox.addEventListener("change", () => {
prepareData();
restart();
});
ui.stepButton.addEventListener("click", () => {
stop();
if (converged) restart();
else step();
});
ui.runButton.addEventListener("click", run);
ui.restartButton.addEventListener("click", () => {
startSeed++;
restart();
});
ui.resetButton.addEventListener("click", loadDataset);
// Re-shade the regions after zooming or panning, so they always fill the view
xAxis.visibleRangeChanged.subscribe(() => centroids.length && drawRegions());
yAxis.visibleRangeChanged.subscribe(() => centroids.length && drawRegions());

loadDataset();
// Play the first run once the chart scrolls into view
const observer = new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) {
observer.disconnect();
run();
}
});
observer.observe(ui.root);

Key points:

  • All the points are one XyScatterRenderableSeries. Each point's metadata carries its cluster colour, and MetadataPaletteProvider applies it, so recolouring after an iteration is one appendRange call rather than one series per cluster.
  • The regions are a UniformHeatmapRenderableSeries whose cells hold the index of the nearest centroid. A HeatmapColorMap with one gradient stop per cluster colour, and opacity: 0.3, shades the Voronoi cells behind the points.
  • Clicking adds a point through a small CustomChartModifier2D: it converts the mouse position to data values with each axis's coordinate calculator, and ignores drags so panning still works.
  • The elbow and silhouette charts are FastLineRenderableSeries with point markers for the best runs, plus an XyScatterRenderableSeries ring for the current run.

See it in the demo app: JavaScript scatter chart · React scatter chart · Angular scatter chart, and for colour-mapped grids, JavaScript heatmap chart · React heatmap chart · Angular heatmap chart.

Go deeper: SciChart.js scatter chart documentation, the heatmap documentation for the region map, and the scatter plot guide. For clustering and charting large test datasets, see SciChart for semiconductors.

Frequently asked questions​

What is k-means clustering used for?​

K-means is used to split unlabelled data into a chosen number of groups of similar items. Common uses are customer segmentation, reducing the colours in an image (colour quantisation), grouping documents or sensor readings, building codebooks for compression, and as a quick first look at the structure of a dataset before a more careful analysis.

How do you choose the number of clusters k?​

Run k-means for a range of k and compare. The elbow method plots the inertia (within-cluster sum of squares) against k and looks for the bend after which adding clusters helps little. The silhouette method picks the k with the highest mean silhouette score. Use both, and check that the clusters at the chosen k make sense for the problem; a domain reason, such as the number of product lines, often decides.

What is a good silhouette score?​

The silhouette score runs from -1 to 1. Kaufman and Rousseeuw's rule of thumb reads a mean above 0.70 as strong structure, 0.51 to 0.70 as reasonable, 0.26 to 0.50 as weak and possibly artificial, and 0.25 or less as no real structure. A high score only means the clusters are compact and well separated in the distance k-means uses; it says nothing about whether they are useful.

What is the difference between k-means and k-NN?​

K-means is unsupervised clustering: it takes unlabelled data and splits it into k groups, where k is the number of clusters. K-nearest neighbours (k-NN) is supervised: it predicts the label of a new point from the labels of its k closest training points, where k is the number of neighbours. They share the letter k and a distance measure, but solve different problems.

Does k-means always find the best clusters?​

No. Each run of k-means always converges, because neither step can increase the within-cluster sum of squares, but it converges to a local minimum that depends on the starting centroids. Finding the true minimum is NP-hard, even for points in a plane when the number of clusters can be any number; for a fixed number of clusters it can be solved in polynomial time, but not quickly. In practice you run it several times from different starts, ideally with k-means++ seeding, and keep the run with the lowest inertia.

How do I visualise k-means clustering in JavaScript?​

Run k-means in plain JavaScript (assign each point to its nearest centroid, move each centroid to the mean of its points, repeat until nothing changes), then draw the points as a scatter series coloured by cluster label and the centroids as larger markers. Shading each centroid's region with a heatmap shows the decision boundaries. In SciChart.js that is an XyScatterRenderableSeries with a MetadataPaletteProvider for the colours and a UniformHeatmapRenderableSeries for the regions, whether you use plain JavaScript, React or Angular.

Sources​