Skip to content

Instantly share code, notes, and snippets.

@FrissAnalytics
Last active October 1, 2018 14:11
Show Gist options
  • Save FrissAnalytics/b09db2c701d6b163b5b3dcec6b2519fc to your computer and use it in GitHub Desktop.
Save FrissAnalytics/b09db2c701d6b163b5b3dcec6b2519fc to your computer and use it in GitHub Desktop.
Force-Directed Tree Layout weak tree
license: mit
{
"nodes": [
{"name": "d3"},
{"name": "d3.svg"},
{"name": "d3.svg.area"},
{"name": "d3.svg.line"},
{"name": "d3.scale"},
{"name": "d3.scale.linear"},
{"name": "d3.scale.ordinal"},
{"name": "n7"},
{"name": "n8"},
{"name": "n9"},
{"name": "n10"},
{"name": "n11"},
{"name": "n12"},
{"name": "n13"},
{"name": "n14"},
{"name": "n15"},
{"name": "n16"}
],
"links": [
{"source": 0, "target": 1},
{"source": 1, "target": 2},
{"source": 1, "target": 3},
{"source": 0, "target": 4},
{"source": 4, "target": 5},
{"source": 4, "target": 6},
{"source": 6, "target": 7},
{"source": 7, "target": 8},
{"source": 8, "target": 9}
]
}
<!DOCTYPE html>
<html>
<head>
<title>Force-Directed Layout</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.29.1"></script>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.geom.js?1.29.1"></script>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js?1.29.1"></script>
<style type="text/css">
circle {
stroke-width: 1.5px;
}
line {
stroke: #999;
}
</style>
</head>
<body>
<script type="text/javascript">
var w = 960,
h = 500,
r = 6,
fill = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([w, h]);
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
d3.json("graph.json", function(json) {
var link = svg.selectAll("line")
.data(json.links)
.enter().append("svg:line");
var node = svg.selectAll("circle")
.data(json.nodes)
.enter().append("svg:circle")
.attr("r", r - .75)
.style("fill", function(d) { return fill(d.group); })
.style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
.call(force.drag);
force
.nodes(json.nodes)
.links(json.links)
.on("tick", tick)
.start();
function tick(e) {
// Push sources up and targets down to form a weak tree.
var k = 6 * e.alpha;
json.links.forEach(function(d, i) {
d.source.y -= k;
d.target.y += k;
});
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
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; });
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment