Skip to content

Instantly share code, notes, and snippets.

@pnavarrc
Last active August 30, 2016 18:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pnavarrc/1ebc1704ee623c7c6f1d to your computer and use it in GitHub Desktop.
Save pnavarrc/1ebc1704ee623c7c6f1d to your computer and use it in GitHub Desktop.
Force Vertical Gravity

Force layout with vertical gravity.

<!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>
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