Skip to content

ckmeans

Clusters one-dimensional numeric data into a specified number of groups using the Ckmeans dynamic programming algorithm, minimizing within-group sum-of-squared-deviations.

Splits a list of numbers into k groups so that values within a group are as close together as possible (the Ckmeans algorithm, an exact 1-D k-means). Three obvious clumps come back as three clusters. This is the “jenks” option of a chart’s colorScale.

import {ckmeans} from "@d3plus/math";

ckmeans([1, 2, 3, 10, 11, 12, 20, 21, 22], 3);

The number of clusters is yours to choose; the algorithm finds the best split for that count. Asking for two merges the nearest clumps, asking for four splits one of them. k cannot exceed the number of values.

import {ckmeans} from "@d3plus/math";

ckmeans([1, 2, 3, 10, 11, 12, 20, 21, 22], 2);
ckmeans([1, 2, 3, 10, 11, 12, 20, 21, 22], 4);

Because the criterion is within-cluster variance, a lone extreme value gets a cluster of its own rather than dragging a boundary toward it, which keeps color-scale breaks sensible on skewed data.

import {ckmeans} from "@d3plus/math";

ckmeans([1, 2, 3, 4, 5, 100], 2);

Parameters

import {ckmeans} from "@d3plus/math";
datarequiredArray.<number>

input data, as an array of number values

nClustersrequirednumber

number of desired classes. This cannot be greater than the number of values in the data array.