简体   繁体   中英

In D3 force-directed layout, how can I position fixed nodes programmatically, without dragging?

In the answer to this question , mbostock notes that "if a node is fixed, it can only be moved by dragging and not by the simulation."

What if I'd like to position the nodes programmatically, however, perhaps by setting the dx and dy values? My attempts thus far have failed. I have tried the obvious setting of dx and dy, but these values are ignored for fixed nodes. I've also attempted to temporarily "un-fix", redraw, then "re-fix" the nodes, but this also doesn't work -- the nodes are magically reset to their original positions on the next tick.

Here's a running example of this latter approach.

Here's the key bit of that code, executed on click:

function explicitlyPosition() {
  node.each(function(d) {
    d.x = 0;
    d.y = 0;
    d.fixed = false;
  });
  tick();
  node.each(function(d) {
    d.fixed = true;
  });
  force.resume();
}

Is there a way to do this using the approach I've tried or one similar? Or I could use a totally different graph layout in D3, but I would ideally like large portions of my graph to be laid out in a force-directed manner.

Thanks!

When you fire tick , the previous positions of nodes are used to determine the new positions, and are stored in the px and py attributes. If you change these attributes, running tick will update the x and y attributes to these values.

Fiddle.

Essentially, your nodes will magically fix to the new values when you redraw, rather than magically fix back to their old values.

The jsfiddles used in the 2014 answer and comments for this question are outdated for D3 version 4. In version 4, the process for making fixed nodes is greatly simplified. You can simply set an fx and fy value for each node you want to fix.

For example, like this:

var graph = {
    "nodes": [
        // unfixed
        {"id":0},
        // fixed
        {"id":1, "fx": 200, "fy": 200},
        {"id":2, "fx": 200, "fy": 300},
        {"id":3, "fx": 300, "fy": 250}
    ],
    "links": [
        {"source": 0, "target": 1},
        {"source": 0, "target": 2},
        {"source": 1, "target": 3},
        {"source": 2, "target": 3}
    ]
};

or this:

graph.nodes[3].fx = 500;
graph.nodes[3].fy = 250;

or this:

graph.nodes.each(function(d) {
    if(d.id == 2) {
        d.fx = 0;
        d.fy = 0;       
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM