Published
Edited
Oct 22, 2020
1 fork
3 stars
Insert cell
Insert cell
chart = {
const context = DOM.context2d(width, height);
const nodes = data.map(Object.create);

const simulation = d3.forceSimulation(nodes)
.alphaTarget(0.3) // stay hot
.velocityDecay(0.1) // low friction
.force("x", d3.forceX().strength(0.01))
.force("y", d3.forceY().strength(0.01))
.force("collide", d3.forceCollide().radius(d => d.r + 1).iterations(3))
//.force("charge", d3.forceManyBody().strength((d, i) => i ? 0 : -width * 2 / 3))
.on("tick", ticked);

d3.select(context.canvas)
.on("touchmove", event => event.preventDefault())
.on("pointermove", pointed);

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

function pointed(event) {
const [x, y] = d3.pointer(event);
for (const d of nodes) {
const xPos = (x - width / 2);
const yPos = (y - width / 2);

// Distance from mouse position to node
const magnitude = Math.sqrt(Math.pow((d.x - xPos), 2) + Math.pow((d.y - yPos), 2));
const minSize = 5;
const r = d.startingSize + 1000 / magnitude;
const maxSize = 50;
d.r = r > maxSize ? maxSize : r;
}
simulation.force("collide").initialize(nodes);
}

function ticked() {
context.clearRect(0, 0, width, height);
context.save();
context.translate(width / 2, height / 2);
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();
}

return context.canvas;
}
Insert cell
data = {
const k = width / 200;
const r = d3.randomUniform(k, k * 4);
return Array.from({length: 200}, (_, i) => {
const radius = r();
return {r: radius, startingSize: radius, group: (i % (n + 1))}
});
}
Insert cell
n = 3
Insert cell
color = d3.scaleOrdinal(d3.range(n), d3.schemeTableau10)
Insert cell
height = width
Insert cell
d3 = require("d3@6")
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