Question

I have nodes in a D3 force-directed layout that are set to .fixed = true. If I set the .x or .y values, the nodes themselves don't move to their new position.

Here's my function:

function fixNode(idArray, locationX, locationY) {
    for ( x = 0; x < idArray.length; x++ ) {
        for ( y = 0; y < nodes.length; y++ ) {
            if (nodes[y].id == idArray[x]) {
                nodes[y].fixed = true;
                nodes[y].x = 50;
                nodes[y].y = 50;
                break;
            }
        }
    }
}

UPDATE 1:

Here is the working function based on Jason's advice:

function fixNode(idArray, locationX, locationY) {
    for ( x = 0; x < idArray.length; x++ ) {
        for ( y = 0; y < nodes.length; y++ ) {
            if (nodes[y].id == idArray[x]) {
                nodes[y].fixed = true;
                nodes[y].x = 50;
                nodes[y].y = 50;
                nodes[y].px = 50;
                nodes[y].py = 50;
                break;
            }
        }
    }
    tick();
}
Was it helpful?

Solution

The force-directed layout is decoupled from the actual rendering. Normally you have a tick handler, which updates the attributes of your SVG elements for every "tick" of the layout algorithm (the nice thing about the decoupling is you render to a <canvas> instead, or something else).

So to answer your question, you simply need to call this handler directly in order to update the attributes of your SVG elements. For example, your code might look like this:

var node = …; // append circle elements

var force = d3.layout.force()
    .nodes(…)
    .links(…)
    .on("tick", tick)
    .start();

function tick() {
  // Update positions of circle elements.
  node.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
}

So you could simply call tick() at any point and update the element positions.

You might be tempted to call force.tick(), but this is meant to be used as a synchronous alternative to force.start(): you can call it repeatedly and each call executes a step of the layout algorithm. However, there is an internal alpha variable used to control the simulated annealing used internally, and once the layout has "cooled", this variable will be 0 and further calls to force.tick() will have no effect. (Admittedly it might be nice if force.tick() always fired a tick event regardless of cooling, but that is not the current behaviour).

As you correctly noted in the comments, if you manually set d.x and d.y, you should also set d.px and d.py with the same values if you want the node to remain in a certain position.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top