[英]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." 在这个问题的答案中,mbostock指出“如果一个节点是固定的,它只能通过拖动而不是通过模拟来移动。”
What if I'd like to position the nodes programmatically, however, perhaps by setting the dx and dy values? 但是,如果我想以编程方式定位节点,或许可以通过设置dx和dy值,该怎么办? My attempts thus far have failed. 到目前为止,我的尝试失败了。 I have tried the obvious setting of dx and dy, but these values are ignored for fixed nodes. 我已经尝试了明显的dx和dy设置,但固定节点会忽略这些值。 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. 或者我可以在D3中使用完全不同的图形布局,但我理想地希望我的图形的大部分以力导向的方式布局。
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. 当您触发tick
,节点的先前位置用于确定新位置,并存储在px
和py
属性中。 If you change these attributes, running tick
will update the x
and y
attributes to these values. 如果更改这些属性,则运行tick
会将x
和y
属性更新为这些值。
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. 2014年答案中使用的jsfiddles和此问题的评论对于D3版本4已经过时。在版本4中,大大简化了制作固定节点的过程。 You can simply set an fx
and fy
value for each node you want to fix. 您只需为要修复的每个节点设置fx
和fy
值即可。
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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.