How do I set the focal node in a D3.js Force Directed Graph?

d3.js, force-layout, javascript

Solution

If you only want a root node you can have a root property in your object and set it to true, than treat that node separately. You can also set this root to center. Here is how we did it (d3 + Prototype - at the time - now switching to d3+jQuery+underscore):

getCenter: function() {
    var center = {
        x : this.width / 2,
        y : this.height / 2
    };
    return center;
}

//later do something like this in your init method:
var first = {
                id : id,
                name : name,
                x : this.getCenter().x,
                y : this.getCenter().y,
                root : true,
                //other properties
            };

//later in your redraw() or other methods you might employ...
//try to find the root node later in the code using something like:
var rootNode = this.nodes.detect(function(node) {
    return node.root;
});

//do something to the root node after you have detected it...
if (rootNode) {
    rootNode.x = rootNode.px = this.getCenter().x;
    rootNode.y = rootNode.py = this.getCenter().y;
    //some other stuff...
}

This is how we have done it. However it's not clear to me what are the links in your example... A little bit puzzled. As you will notice, for a force directed layout or more complicated animations you almost always need to use D3+something else (Prototype, jQuery, underscore) for the simple methods like detect or include or other similar Ruby style methods.

Problem

I have a data set that defines a number of nodes to use in a Force Directed Graph. It looks like... ``` var nodeSet = [ {id: "N1", name: "Node 1", type: "Type 1", hlink: "http://www.if4it.com"}, {id: "N2", name: "Node 2", type: "Type 3", hlink: "http://www.if4it.com/glossary.html"}, {id: "N3", name: "Node 3", type: "Type 4", hlink: "http://www.if4it.com/resources.html"}, {id: "N4", name: "Node 4", type: "Type 5", hlink: "http://www.if4it.com/taxonomy.html"}, {id: "N5", name: "Node 5", type: "Type 1", hlink: "http://www.if4it.com/disciplines.html"} ]; ``` How do I specifically tell the force.layout in the d3.js library to use "Node 1" of id = "N1" as the primary root or focal node?

Original source

Related problems