Published
Edited
May 23, 2019
6 stars
Insert cell
Insert cell
chart = {
const links = data.links.map(d => Object.create(d));
const nodes = data.nodes.map(d => Object.create(d));

const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id).distance(50))
.force("charge", d3.forceManyBody().strength(-1000))
.force('collision', d3.forceCollide().radius(10))
.force("center", d3.forceCenter(width / 2, height / 2));

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

const link = svg.append("g")
.attr("stroke-opacity", 0.2)
.selectAll("path")
.data(links)
.join("path")
.attr("stroke-width", 2)
.attr("stroke", color)
.attr("fill", "transparent");

const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 6)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 6)
.attr("fill", "#555")
.call(drag(simulation))
const textElements = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.id)
.attr('font-size', 10)
.attr("font-family", "Nunito")
.attr("fill", "#555")
.attr('dx', 10)
.attr('dy', 4)

simulation.on("tick", () => {
link
.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
textElements
.attr("x", node => node.x)
.attr("y", node => node.y)
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});

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

return svg.node();
}
Insert cell
data =
d3.json("https://gist.githubusercontent.com/namitamo/1caf4cdbc602d3faaa569b696a03d5a4/raw/2d325af92718fd6df6697c197a0fa29917930b07/sample-data.json")
Insert cell
height = 700
Insert cell
width = 800
Insert cell
color = {
const scale = d3.scaleOrdinal(d3.schemeCategory10);
return d => scale(d.group);
}
Insert cell
drag = simulation => {
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
Insert cell
d3 = require("d3@5")
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