Public
Edited
Aug 8, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function compactBeeswarm(data, { diameter = 1, x = d => d } = {}) {
const diameter2 = diameter ** 2;

// For placed circles, circle.y is the y position; for unplaced
// circles, circle.y is the lowest currently-permitted y position.
const circles = data
.map((d, i, data) => ({ x: +x(d, i, data), placed: false, y: 0, data: d }))
.sort((a, b) => a.x - b.x);

// next() returns the point that is to be placed next
function next() {
let best;
for (let c of circles) {
if (c.placed) continue;
if (!best || c.y < best.y) best = c;
}
return best;
}

// updateYValues(circle) updates the y values of unplaced points
// that horizontally overlap circle.
function updateYValues(circle) {
for (let c of circles) {
if (c.placed) continue;
let xDiff = Math.abs(circle.x - c.x);
if (xDiff >= diameter) continue;
let yDiff = Math.sqrt(diameter2 - xDiff ** 2);
c.y = Math.max(c.y, circle.y + yDiff);
}
}

let time = 0;

for (let i = 0; i < circles.length; i++) {
let c = next();
c.placed = true;
c.insertionTime = ++time;
updateYValues(c);
}

return circles;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more