voronoiCentroids = (options) =>
Plot.initializer(
options,
function (
data,
facets,
{ x: X0, y: Y0, x2: X2, y2: Y2 },
{ x, y },
{ width, height, marginLeft, marginRight, marginTop, marginBottom },
context
) {
const X = X2 ?? X0;
const Y = Y2 ?? Y0;
if (X.scale !== "x") x = (x) => x;
if (Y.scale !== "y") y = (y) => y;
for (const I of facets) {
const v = d3.Delaunay.from(
I,
(i) => x(X.value[i]),
(i) => y(Y.value[i])
).voronoi([
marginLeft,
marginTop,
width - marginRight,
height - marginBottom
]);
let cell;
for (const [i, k] of I.entries()) {
if ((cell = v.cellPolygon(k))) {
const [x, y] = d3.polygonCentroid(cell);
X.value[i] = x;
Y.value[i] = y;
}
}
}
delete X.scale;
delete Y.scale;
return { data, facets };
}
)