修复 D3 力导向布局中的节点位置 [英] Fix Node Position in D3 Force Directed Layout

查看:55
本文介绍了修复 D3 力导向布局中的节点位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的力导向布局中的一些节点忽略所有力并根据节点的属性保持在固定位置,同时仍然能够被拖动并对其他节点施加排斥并保持它们的链接线.

I want some of the nodes in my force-directed layout to ignore all forces and stay in fixed positions based on an attribute of the node, while still being able to be dragged and exert repulsion on other nodes and maintain their link lines.

我以为就这么简单:

force.on("tick", function() {
    vis.selectAll("g.node")
        .attr("transform", function(d) {
            return (d.someAttribute == true) ?
               "translate(" + d.xcoordFromAttribute + "," + d.ycoordFromAttribute +")" :
               "translate(" + d.x + "," + d.y + ")"
        });
  });

我还尝试在每个刻度上手动设置节点的 x 和 y 属性,但是如果节点受到力的影响,链接会继续浮动到节点所在的位置.

I have also tried to manually set the node's x and y attributes each tick, but then the links continue to float out to where the node would be if it was affected by the force.

显然,我对这应该如何工作有一个基本的误解.如何将节点固定在某个位置,同时保持链接并仍然允许它们可拖动?

Obviously I have a basic misunderstanding of how this is supposed to work. How can I fix nodes in a position, while keeping links and still allowing for them to be draggable?

推荐答案

将所需节点上的 d.fixed 设置为 true,并初始化 dxdy 到所需的位置.这些节点仍然是模拟的一部分,您可以使用正常的显示代码(例如,设置转换属性);但是,因为它们被标记为固定的,所以它们只能通过拖动而不是通过模拟来移动.

Set d.fixed on the desired nodes to true, and initialize d.x and d.y to the desired position. These nodes will then still be part of the simulation, and you can use the normal display code (e.g., setting a transform attribute); however, because they are marked as fixed, they can only be moved by dragging and not by the simulation.

有关更多详细信息,请参阅强制布局文档(v3 文档当前文档),并查看根节点如何位于这个例子.

See the force layout documentation for more details (v3 docs, current docs), and also see how the root node is positioned in this example.

这篇关于修复 D3 力导向布局中的节点位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆