Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center force directed layout after tick using root node (return to center)

I am experimenting with force directed layout using D3.js. What I need is center the layout by root (or other selected node) and return this node to the svg (e.g. canvas) center after the tick function is done (the graph alpha is low). Is it possible? I found an example at

http://bl.ocks.org/1080941

but I am unable to make the root (when using aplha or other custom tick function calculation) return back to the center (center the layout by this particular node).

Any help would be appreciated.

like image 994
Bery Avatar asked Feb 20 '12 14:02

Bery


2 Answers

Actually I solved this like this(similar to previous but more sophisticated):

force.on("tick", function(e) {

     node.attr("transform", function(d) { 
         //TODO move these constants to the header section
        //center the center (root) node when graph is cooling down
        if(d.index==0){
            damper = 0.1;
            d.x = d.x + (w/2 - d.x) * (damper + 0.71) * e.alpha;
            d.y = d.y + (h/2 - d.y) * (damper + 0.71) * e.alpha;
        }
        //start is initiated when importing nodes from XML
        if(d.start === true){
            d.x = w/2;
            d.y = h/2;
            d.start = false;
        }

        r = d.name.length;
        //these setting are used for bounding box, see [http://blockses.appspot.com/1129492][1]
        d.x = Math.max(r, Math.min(w - r, d.x));
        d.y = Math.max(r, Math.min(h - r, d.y));

            return "translate("+d.x+","+d.y+")";            

     }
    );

     });   
like image 188
Bery Avatar answered Sep 30 '22 06:09

Bery


Try to change the force event handler like this:

force.on("tick", function(e) {
nodes[0].x = w / 2;
nodes[0].y = h / 2;

var k = 0.05 * e.alpha;
          nodes.forEach(function(o, i) {
            o.y += (nodes[0].y - o.y) * k;
            o.x += (nodes[0].x - o.x) * k;
          });

link.attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });

node.attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });
 });
like image 36
Shali Liu Avatar answered Sep 30 '22 05:09

Shali Liu