Public
Edited
Dec 4, 2023
Insert cell
Insert cell
Insert cell
Insert cell
{
const nIter = 10;

for(let i = 0; i < nIter; i++) {
// Assign observations into clusters
data.forEach(d => {
d.cluster = d3.scan(centroids, (a, b) => distance(a, d) - distance(b, d));
});
// Calculate new centroids
d3.nest()
.key(d => d.cluster)
.sortKeys(d3.ascending)
.entries(data)
.forEach(n => {
let cx = n.values.map(v => v.petalWidth).reduce((a, b) => a + b) / n.values.length
let cy = n.values.map(v => v.petalLength).reduce((a, b) => a + b) / n.values.length
centroids[+n.key].petalWidth = cx;
centroids[+n.key].petalLength = cy;
});
// Update
update(svg);
yield md`Iteration: ${await Promises.delay(1000, i + 1)} / ${nIter}`;
}
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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