Force layout with vertical gravity.
Last active
August 30, 2016 18:07
-
-
Save pnavarrc/1ebc1704ee623c7c6f1d to your computer and use it in GitHub Desktop.
Force Vertical Gravity
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
</head> | |
<style> | |
svg { | |
overflow: visible; | |
border: solid 1px #666; | |
} | |
.node { | |
fill-opacity: 0.8; | |
stroke: #fff; | |
stroke-width: 2; | |
} | |
</style> | |
<body> | |
<svg class="gravity"></svg> | |
<script type="text/javascript" src="main.js"></script> | |
</body> | |
</html> |
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 numNodes = 50, | |
nodes = []; | |
var width = 800, | |
height = 400, | |
r = 20; | |
for (var k = 0; k < numNodes; k += 1) { | |
nodes.push({ | |
num: k | |
}); | |
} | |
var force = d3.layout.force() | |
.nodes(nodes) | |
.gravity(0) | |
.charge(-150) | |
.size([width, height]) | |
.start(); | |
var svg = d3.select('svg') | |
.attr('width', width) | |
.attr('height', height); | |
var colorScale = d3.scale.linear() | |
.domain([0, height]) | |
.range(['#F8CA00', '#BD1550']); | |
var circles = svg.selectAll('.node').data(nodes); | |
circles.enter().append('circle').classed('node', true); | |
circles.attr('r', r); | |
circles.exit().remove(); | |
force.on('tick', function(e) { | |
nodes.forEach(function(o) { | |
var dy = (height - r) - o.y; | |
o.y = (dy < 0) ? (height - r) : o.y + (dy / height); | |
}); | |
circles | |
.attr('cx', function(d) { return d.x; }) | |
.attr('cy', function(d) { return d.y; }) | |
.attr('fill', function(d) { return colorScale(d.y); }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment