D3 JS-力图-不;删除节点后无法重新启动布局

D3 JS - Force Graph - Doesn't restart layout after removing Node

本文关键字:重新启动 布局 节点 删除 力图 JS- D3      更新时间:2023-09-26

更新:移除节点后,图形现在可以正常工作。然而,当我有条件地移除非顺序节点(例如4、5、10)时,图不会显示正确的节点。

请查看下面更新的点击处理程序(大量调试)。我正在尝试删除所有带有"d.source"value=="news24"的节点,这些节点都是蓝色的大圆圈。尽管阵列在"删除"后是正确的,但显示的是不正确的节点。我怀疑这与node.exit()有关,但我不确定。

完整更新代码:http://www.darkness.co.za/code/graph_test_2.zip

$('#btnRemove').click(function(e) {
// These are the large blue circles  
var sourceToHide = "news24";
// DEBUG - Before Removal
for (i=0; i < nodes.length; i++) {
  console.log("node_object[" + i + "].source = " + nodes[i].source);
  console.log("-----------------------------------");
}
// Hold indices of items to remove  
var itemsToRemove = [];
// Find items with the source to remove
for (i=0; i < nodes.length; i++) {
    var nodeSource = nodes[i].source;
    console.log("Node source = " + nodeSource + " sourceToHide = " + sourceToHide);         
    if (nodeSource == sourceToHide) {
        itemsToRemove.push(i);
    }
}
// Reverse removal array - makes splice work as expected
itemsToRemove.reverse();
// Remove items
for (i=0; i < itemsToRemove.length; i++) {
    nodes.splice(itemsToRemove[i], 1);
}
// DEBUG - After Removal
for (i=0; i < nodes.length; i++) {
    console.log("node_object[" + i + "].source = " + nodes[i].source);
    console.log("-----------------------------------");
}   
// Rebind the nodes to the array
node = svg.selectAll("circle")
.data(nodes)
// Remove the exit'ed node
node.exit().remove();
// Tell the layout that this is the new set of nodes
// so that it doesn't include the old one in the computation
force
.nodes(nodes)
// That's it. No need to restart the force layout

});

我搜索了很多,孤立地尝试了很多例子,但对于我的特定设置和数据,无法解决这个问题。

代码:
很抱歉,我在JSFiddle(外部文件等)上设置它时遇到了问题,所以你可以在这里获得完整的代码:http://darkness.co.za/code/graph_test.zip

我想要实现的目标:
(对于这个测试)我想删除一个节点,然后重新绘制/重新启动图形

我尝试过的:
我试图从节点数组中删除最后一个元素,然后重新绘制图形(圆和线),然后调用force.start()

问题:
节点确实根据需要消失,但整个图形停止响应。

如何正确地删除节点,然后在具有正常拖动行为的情况下成功地重新启动图形?

注意:我在"drawGraph()"函数的末尾调用"force.start()"

感谢

在这种情况下,您不需要"重新启动"图形。您所要做的就是从DOM中移除节点,并告诉强制布局有一组新的节点(与之前的节点集相同)。因此,在按钮的点击处理程序中:

// Button Listeners
$('#btnRemove').click(function(e) {
  // Remove the node from the array
  nodes.splice((nodes.length - 1), 1);
  // Rebind the nodes to the array
  node = svg.selectAll(".node")
    .data(nodes)
  // Remove the exit'ed node
  node.exit().remove();
  // Tell the layout that this is the new set of nodes
  // so that it doesn't include the old one in the computation
  force
    .nodes(nodes)
  // That's it. No need to restart the force layout
});

这并没有解决删除节点的链接线的问题,但您可以使用相同的方法来执行此操作。