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();
}
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:
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 toforce.start(): you can call it repeatedly and each call executes a step of the layout algorithm. However, there is an internalalphavariable used to control the simulated annealing used internally, and once the layout has “cooled”, this variable will be0and further calls toforce.tick()will have no effect. (Admittedly it might be nice ifforce.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.xandd.y, you should also setd.pxandd.pywith the same values if you want the node to remain in a certain position.