Public
Edited
May 23
1 fork
Insert cell
Insert cell
graph = FileAttachment("graph@2.json").json()
Insert cell
viewof chart = {
const width = 900, height = 600;
const svg = d3.select(DOM.svg(width, height));

const color = d3.scaleOrdinal(d3.schemeCategory10);
graph.nodes.forEach(d => {
d.x = width / 2 + Math.random() * 50 - 25;
d.y = height / 2 + Math.random() * 50 - 25;
});
const simulation = d3.forceSimulation(graph.nodes)
.force("link", d3.forceLink(graph.links).id(d => d.id).distance(90))
.force("charge", d3.forceManyBody().strength(-25))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("collide", d3.forceCollide().radius(12));

const link = svg.append("g")
.attr("stroke", "#aaa")
.attr("stroke-width", 1.5)
.selectAll("line")
.data(graph.links)
.join("line");

const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(graph.nodes)
.join("circle")
.attr("r", 6)
.attr("fill", d => color(d.group))
.call(d3.drag()
.on("start", (event, d) => {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
})
.on("drag", (event, d) => {
d.fx = event.x;
d.fy = event.y;
})
.on("end", (event, d) => {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}));

const label = svg.append("g")
.selectAll("text")
.data(graph.nodes)
.join("text")
.text(d => d.id.split(" ")[0])
.attr("font-size", "10px")
.attr("dx", 8)
.attr("dy", 3);

simulation.on("tick", () => {
graph.nodes.forEach(d => {
d.x = Math.max(10, Math.min(width - 10, d.x));
d.y = Math.max(10, Math.min(height - 10, d.y));
});

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);

label
.attr("x", d => d.x)
.attr("y", d => d.y);
});

return svg.node();
}

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