问题
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?
回答1:
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.
回答2:
I'm not sure what you mean by focal or root node. If you want to fix a certain node in a specific place (e.g. the centre) you can set its 'fixed' attribute to true. For more info see Fix Node Position in D3 Force-Directed Layout, and also Moving fixed nodes in D3.
I dont think your force directed radial graph example does show that d3 implicitly uses the first node in the node list as the 'root' node. Node 1 in your example always gravitates towards the centre as a consequence of the network structure. If you place Node 1 later in the array of nodes its behaviour is the same.
来源:https://stackoverflow.com/questions/10887027/how-do-i-set-the-focal-node-in-a-d3-js-force-directed-graph