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); }); });