Last active
February 23, 2017 16:16
-
-
Save bhurlow/7088478 to your computer and use it in GitHub Desktop.
d3 force layouts explained
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = [ | |
10, | |
32, | |
59, | |
21, | |
66, | |
32, | |
12, | |
92, | |
88 | |
] | |
var svg = d3.select("#world") | |
.append("svg") | |
.attr("width", 500) | |
.attr("height", 500) | |
var dots = svg.append("g").attr("id", "dots") | |
// Like other layouts, d3 expects objects that the layout can manipulate | |
data.forEach(function(item, index) { | |
data[index] = { | |
value: item | |
} | |
}) | |
var force = d3.layout.force() | |
.nodes(data) | |
// size affects center of gravity | |
.size([500, 500]) | |
// internally, the force layout ticks forward and updates the values of | |
// the connected data | |
// this is necessary for the animation to be reprensented | |
// otherwise, the layout is ticking forward the positions without visual | |
// representation | |
.on('tick', tick) | |
// defaults to .9 | |
// 1 = frictionless, 0 = frozen | |
.friction(0.9) | |
// defaults to -30 | |
// can be a function | |
// A negative value results in node repulsion, while a positive value results in node attraction. | |
// 0 charge disables the quadtree computation | |
.charge(-100) | |
// deftaults to 0.8 | |
// sets approximation | |
.theta(1) | |
// defaults to 0.1 | |
// 0 = disabled | |
.gravity(0.2) | |
// gets or sets the cooling param | |
.alpha(0.9) | |
// start ticking internally | |
.start() | |
// this returns extended objects | |
var nodes = force.nodes() | |
dots.selectAll() | |
.data(nodes) | |
.enter() | |
.append('circle') | |
// force layout doesn't change the r value like a pack layout does | |
.attr('r', function(d) { | |
return d.r || 10 | |
}) | |
.attr('cx', function(d, i) { | |
return d.x | |
}) | |
.attr('cy', function(d, i) { | |
return d.y | |
}) | |
.attr("class", "node") | |
.style("fill", "#1f77b4") | |
.style("stroke", "#0f3a58;") | |
// this applies a 'mousedown' event listener | |
.call(force.drag) | |
function tick() { | |
var node = d3.selectAll('.node') | |
// these values have already been updated by the force layout on each tick | |
node.attr("cx", function(d) { return d.x; }) | |
.attr("cy", function(d) { return d.y; }); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment