我想控制我的节点,以便它们中的每一个都被链接并且没有孤立的节点。
我的脚本每 30 秒从 JSON 查询中添加一对新节点。如果任一新节点是现有节点的副本,则该图将仅使用唯一节点进行更新并将其链接到另一个现有节点。
在此过程中,我将移出最旧的节点以在图表上保留最多 10 个节点。在这里,我似乎遇到了麻烦。我怎样才能着手删除节点并检查并删除任何散乱的节点,即未链接到任何其他节点的节点?
脚本基于on knoren's post on adding new nodes .
this.checkLength = function () {
if (nodes.length > 10) {
var i = links.shift();
nodes.splice(findNodeIndex(i),1);
update();
}
}
最佳答案
正如 paxRoman 所建议的,为了删除一个节点,你可以这样做:
node.exit().remove();
现在,要查找空节点,您可以使用力节点的 weight
属性,如 documentation of the force layout 中所述。 :
weight - the node weight; the number of associated links.
所以,最后,为了获得所有为空的节点,您可以这样做:
force.nodes().filter(function(d){d.weight==0})
force
是你的强制布局。
另请注意,权重属性只会在 force.start()
调用时初始化,如文档中所述:
These attributes do not need to be set before passing the nodes to the layout; if they are not set, suitable defaults will be initialized by the layout when start is called
关于javascript - 如何检查没有链接的节点的 d3 js 力图并将其删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12924227/