Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active Mar 29, 2017
Embed
What would you like to do?
Force Layout from Adjacency List
license: gpl-3.0
{
"1": [ 7, 2, 6],
"2": [ 8, 3, 1],
"3": [ 4, 2, 9],
"4": [10, 3, 5],
"5": [ 6, 4, 11],
"6": [ 1, 5, 12],
"7": [ 1, 20, 13],
"8": [ 2, 14, 21],
"9": [ 3, 22, 15],
"10": [ 4, 16, 23],
"11": [ 5, 17, 24],
"12": [ 6, 19, 18],
"13": [ 7, 19],
"14": [20, 8],
"15": [21, 9],
"16": [22, 10],
"17": [23, 11],
"18": [24, 12],
"19": [12, 13],
"20": [14, 7],
"21": [ 8, 15],
"22": [ 9, 16],
"23": [10, 17],
"24": [11, 18]
}
<!DOCTYPE html>
<meta charset="utf-8">
<style>
line {
stroke: #ccc;
stroke-width: 1.5px;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.size([width, height]);
d3.json("graph.json", function(error, graph) {
if (error) throw error;
var nodes = d3.values(graph),
links = d3.merge(nodes.map(function(source) {
return source.map(function(target) {
return {source: source, target: graph[target]};
});
}));
force
.nodes(nodes)
.links(links)
.start();
var link = svg.selectAll(".link")
.data(links)
.enter().append("line");
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("r", 5)
.call(force.drag);
force.on("tick", function() {
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment