Notebooks 2.0 is here.

Published
Edited
Oct 25, 2020
1 star
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 + 3).iterations(3))
.force("center", d3.forceCenter(width / 2, height / 2));
function pointed(event) {
const [x, y] = d3.pointer(event);
for (const d of nodes) {
const xPos = (x);
const yPos = (y);

// 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);
}
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
svg.on("touchmove", event => event.preventDefault())

svg.on("pointermove", event => pointed(event));

const node = svg.append("g")
//.attr("stroke", "#fff")
// .attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", d => d.r)
.attr("fill", d => color(d.group));
// .call(drag(simulation));

node.append("title")
.text(d => d.id);

simulation.on("tick", () => {
node
.attr("r", d => d.r)
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});

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

return svg.node();
}

Insert cell
data = {
const k = width / 200;
const r = d3.randomUniform(k, k * 4);
return Array.from({length: 15}, (_, 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