This example shows how to link nodes in a force-directed graph using a named identifier rather than a numeric index.
forked from mbostock's block: 29. Link Nodes by Name
xxxxxxxxxx
<meta charset="utf-8">
<style>
.node {
stroke: #000;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-width: 1.5px;
}
</style>
<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var simulation = d3.forceSimulation()
// ---- trial and error on .strength(value)
.force("charge", d3.forceManyBody().strength(-300))
// ---- trial and error on .distance(value)
.force("link", d3.forceLink().id(function(d) { return d.id; }).distance(90))
// ---central position
.force("x", d3.forceX(width / 4))
.force("y", d3.forceY(height / 2))
// .on("tick", ticked);
// ---- create empty nodeList
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");
d3.json("graph.json", function(error, graph) {
if (error) throw error;
// load graph.nodes and graph.links to simulation
simulation.nodes(graph.nodes);
simulation.force("link").links(graph.links);
// as a result, node and link's data contain x,y,vx,vy now
//---- replace empty NodeList with lines and circles
link = link
.data(graph.links)
.enter().append("line")
.attr("class", "link");
node = node
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 6)
.style("fill", function(d) { return d.id; });
// --- reveal node and link
simulation
.on("tick", ticked);
});
function ticked() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
</script>
https://d3js.org/d3.v4.min.js