Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basics of D3's Force-directed Layout

I'm plowing into the exciting world of force-directed layouts with d3.js. I've got a grasp of the fundamentals of d3, but I can't figure out the basic system for setting up a force-directed layout.

Right now, I'm trying to create a simple layout with a few unconnected bubbles that float to the center. Pretty simple right!? The circles with the correct are created, but nothing happens.

Edit: the problem seems to be that the force.nodes() returns the initial data array. On working scripts, force.nodes() returns an array of objects.

Here's my code:

<script>
  $(function(){

    var width = 600,
        height = 400;

    var data = [2,5,7,3,4,6,3,6];


    //create chart
    var chart = d3.select('body').append('svg')
        .attr('class','chart')
        .attr('width', width)
        .attr('height', height);

    //create force layout
    var force = d3.layout.force()
        .gravity(30)
        .alpha(.2)
        .size([width, height])
        .nodes(data)
        .links([])
        .charge(30)
        .start();

    //create visuals
    var circles = chart.selectAll('.circle')
        .data(force.nodes()) //what should I put here???
        .enter()
        .append('circle')
        .attr('class','circles')
        .attr('r', function(d) { return d; });

    //update locations
    force.on("tick", function(e) {
      circles.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
    });

  });


</script>
like image 952
Alex Avatar asked Aug 07 '12 22:08

Alex


1 Answers

Here was the problem. The array you feed into force.nodes(array) needs to be an array of objects.

So:

var data = [{number:1, value:20}, {number:2, value:30}...];

works. Or even just

var data=[{value:1},{value:2}];

makes the script work fine.

like image 167
Alex Avatar answered Sep 28 '22 17:09

Alex