Public
Edited
Feb 24, 2024
1 star
Insert cell
Insert cell
Insert cell
render(generateRandomData(range))
Insert cell
Insert cell
Insert cell
function generateRandomData(nodeCount) {
const nodes = Array.from({ length: nodeCount }, (_, i) => ({ id: `Node ${i}` }));
const links = Array.from({ length: nodeCount - 1 }).map((_, i) => ({
source: `Node ${Math.floor(Math.random() * nodeCount)}`,
target: `Node ${Math.floor(Math.random() * nodeCount)}`
})).filter(link => link.source !== link.target);
return { nodes, links };
}

Insert cell
Insert cell
render = (data) => {

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.style("border", "1px solid #ccc");

const { nodes, links } = data;

// Initialize the force simulation
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
// Update the simulation with new nodes and links
simulation.nodes(nodes);
simulation.force("link").links(links);
simulation.alpha(1).restart();
// Render links
const link = svg.append("g")
.attr("stroke", "#ebd3a2")
.selectAll("line")
.data(links)
.join("line");
// Render nodes
const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", () => _.random(4, 8))
.attr("fill", "#4e1d4c");

// Update positions on simulation "tick"
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});
return svg.node();
}

Insert cell
Insert cell
Insert cell
Insert cell
update = {
const nodeCount = nodesRange; // Starting number of nodes
while (true) {
yield Promises.tick(milliseconds, render(generateRandomData(nodeCount + Math.floor(Math.random() * 5)))); // Update node count randomly
}
}

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