Public
Edited
May 9
1 fork
Importers
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
data = Array.from({ length: 100 }, () => ({
x: width * Math.random(),
y: height * Math.random()
}))
Insert cell
voronoiGenerator = Voronoi()
.size([width, height])
.x(d => d.x)
.y(d => d.y)
Insert cell
// Don't do voronoiGenerator(data).polygons() anymore
polygons = voronoiGenerator(data)
Insert cell
color = d3.scaleSequential()
.domain([0, d3.max(polygons, d => Math.abs(d3.polygonArea(d)))])
.interpolator(d3.interpolateSpectral)
Insert cell
height = 500
Insert cell
graphic = () => {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

svg.selectAll()
.data(polygons)
.join("polygon")
.attr("stroke", "black")
.attr("fill", d => color(Math.abs(d3.polygonArea(d))))
.attr("points", d => d);

return svg.node();
}
Insert cell
Insert cell
Insert cell
function Voronoi() {
let x = d => d[0];
let y = d => d[1];
let size = [1, 1];

function voronoi(entries) {
const cloned = JSON.parse(JSON.stringify(entries));
const delaunay = d3.Delaunay.from(cloned, x, y);
const voronoi = delaunay.voronoi([0, 0, ...size]);
return cloned.map((d, i) => {
const polygon = voronoi.cellPolygon(i);
return polygon ? Object.assign(polygon, { data: d }) : null;
}).filter(Boolean); // Remove any nulls (for degenerate cells)
}

voronoi.x = function(fn) {
return arguments.length ? ((x = fn), voronoi) : x;
};
voronoi.y = function(fn) {
return arguments.length ? ((y = fn), voronoi) : y;
};
voronoi.size = function(arr) {
return arguments.length ? ((size = arr), voronoi) : size;
};

return voronoi;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more