Published
Edited
Mar 31, 2021
2 stars
Insert cell
Insert cell
chart = {
const n = 4;
const k = Math.min(width / 200, height / 200);
const r = d3.randomUniform(k, k * 3);
const data = Array.from({length: bubblesNumber}, (_, i) => ({r: r() * 4, group: i && (i % n + 1)}));
const context = DOM.context2d(width, height);
const nodes = data.map(Object.create);
const color = d3.scaleOrdinal(d3.range(n), ["transparent"].concat(d3.schemeBlues[4]));
const simulation = d3.forceSimulation(nodes)
.alphaTarget(0.3) // stay hot
.velocityDecay(0.1) // low friction
.force("x", d3.forceX().strength(0.005))
.force("y", d3.forceY().strength(0.005))
.force("collide", d3.forceCollide().radius(d => d.r - 1).iterations(3))
.force("charge", d3.forceManyBody().strength((d, i) => i ? 0 : -width * 2 / 3))
.force("bounds", boxingForce)
.on("tick", ticked);

invalidation.then(() => simulation.stop());

function pointed(event) {
const [x, y] = [window.mouseX || width/2, window.mouseY || height/2]
nodes[0].fx = x - width / 2;
nodes[0].fy = y - height / 2;
}

function ticked() {
pointed();
context.clearRect(0, 0, width, height);
context.save();
context.translate(width / 2, height / 2);
context.globalAlpha = 0.7;
for (const d of nodes) {
context.beginPath();
context.moveTo(d.x + d.r, d.y);
context.arc(d.x, d.y, d.r, 0, 2 * Math.PI);
context.fillStyle = color(d.group);
context.fill();
}
context.restore();
}
function boxingForce() {
const radiusX = width/2 ;
const radiusY = height/2 ;

for (let node of nodes) {
let r = Math.ceil(node.r) * 2;
node.x = Math.max(-radiusX+r, Math.min(radiusX-r, node.x));
node.y = Math.max(-radiusY+r, Math.min(radiusY-r, node.y));
}
}

return context.canvas;
}

Insert cell
height = 500
Insert cell
width = 500

Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
bubblesNumber = 50
Insert cell
d3 = require("d3@6")
Insert cell
pointermoveEvent = {
function getMousePos(event) {
const [x, y] = d3.pointer(event);
window.mouseX = x;
window.mouseY = y;
}
d3.select("body")
.on("pointermove", getMousePos)
.on("touchstart", getMousePos);
}
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