Skip to content

Instantly share code, notes, and snippets.

@flunky
Created May 5, 2017 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flunky/ad46cc868850a563bc01050bdbb461f6 to your computer and use it in GitHub Desktop.
Save flunky/ad46cc868850a563bc01050bdbb461f6 to your computer and use it in GitHub Desktop.
D3 Force Directed Graph Layout
<!DOCTYPE html>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.link line {stroke: black;}
.node circle {stroke: black; fill: white;}
.node text {text-anchor: middle; font-size: 20px}
</style>
<svg width="300" height="300"></svg>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().distance(75)
.id(function(d) { return d.value;}))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
var nodes = [
{"value": 4},
{"value": 8},
{"value": 15},
{"value": 16},
{"value": 23},
{"value": 42}
];
simulation.nodes(nodes)
var links = [
{"source": 8, "target": 4},
{"source": 16, "target": 4},
{"source": 16, "target": 8},
{"source": 23, "target": 8},
{"source": 23, "target": 15},
{"source": 42, "target": 4},
{"source": 42, "target": 15},
{"source": 42, "target": 23}
];
simulation.force("link").links(links);
var linksel = svg.append("g")
.attr("class", "link")
.selectAll("line").data(links).enter().append("line")
var nodesel = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
nodesel.append("circle")
.attr("r",20);
nodesel.append("text")
.attr("transform","translate(0,6)")
.text(function (d) { return d.value; });
// replace "tick" with "end" for static layout
simulation.on("tick", ticked);
function ticked() {
linksel.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; });
nodesel.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
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;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment