Public
Edited
Apr 4
Insert cell
Insert cell
miserables = FileAttachment("miserables.json").json()
Insert cell
{
const width = 1040, height = 800;

const colorScale = d3.scaleOrdinal(d3.schemeCategory10);
const svg = d3.select(DOM.svg(width, height));

const links = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(miserables.links)
.enter().append("line")
.attr("stroke", "#576")
.attr("stroke-opacity", 0.6)
.attr("stroke-width", d => Math.sqrt(d.value));


const nodes = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(miserables.nodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", d => colorScale(d.group))
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.call(d3.drag()
.on("start", dragStart)
.on("drag", dragMove)
.on("end", dragEnd)
);


const linkForce = d3.forceLink(miserables.links).id(d => d.id);

const simulation = d3.forceSimulation(miserables.nodes)
.force("link", linkForce)
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2))
.on("tick", ticked);

function ticked() {
links
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);

nodes
.attr("cx", d => d.x)
.attr("cy", d => d.y);
}

function dragStart(event, node) {
if (!event.active) simulation.alphaTarget(0.3).restart();
node.fx = node.x;
node.fy = node.y;
}

function dragMove(event, node) {
node.fx = event.x;
node.fy = event.y;
}

function dragEnd(event, node) {
if (!event.active) simulation.alphaTarget(0);
node.fx = null;
node.fy = null;
}

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