This example demonstrates a force-directed graph computed using d3-force.
See also the draggable version.
forked from mbostock's block: Albany Graph
xxxxxxxxxx
<meta charset="utf-8">
<canvas width="960" height="500"></canvas>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script>
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter());
d3.json("albany04_formatting.json", function(error, graph) {
if (error) throw error;
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
context.clearRect(0, 0, width, height);
context.save();
context.translate(width / 2, height / 2 + 40);
context.beginPath();
graph.links.forEach(drawLink);
context.strokeStyle = "#aaa";
context.stroke();
context.beginPath();
graph.nodes.forEach(drawNode);
context.fill();
context.stroke();
context.restore();
}
});
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("g")
.on("mouseover", mouseover)
.on("mouseout", mouseout)
function mouseover() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 16);
}
function mouseout() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 8);
}
function drawLink(d) {
context.moveTo(d.source.x, d.source.y);
context.lineTo(d.target.x, d.target.y);
}
function drawNode(d) {
context.moveTo(d.x + 3, d.y);
context.strokeStyle = d3.interpolateRdYlGn(1 - d.hanguprate);
context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
}
</script>
https://d3js.org/d3.v4.js
https://d3js.org/d3-scale-chromatic.v1.min.js