D3网络(图形)可视化 - 单击删除节点(+链接)

4
我一直在尝试调整以下代码:https://bl.ocks.org/mbostock/4062045,使其能够通过鼠标单击删除节点及其相关连线。
我尝试添加了以下代码:
.on("click",function() {
            d3.select(this).remove();
            restart();
            })

以下是来自这里的代码片段:https://bl.ocks.org/mbostock/1095795

function restart() {

  // Apply the general update pattern to the nodes.
  node = node.data(nodes, function(d) { return d.id;});
  node.exit().remove();
  node = node.enter().append("circle").attr("fill", function(d) { return color(d.id); }).attr("r", 8).merge(node);

  // Apply the general update pattern to the links.
  link = link.data(links, function(d) { return d.source.id + "-" + d.target.id; });
  link.exit().remove();
  link = link.enter().append("line").merge(link);

  // Update and restart the simulation.
  simulation.nodes(nodes);
  simulation.force("link").links(links);
  simulation.alpha(1).restart();
}

如果我先以以下方式指定节点和链接:
  var nodes = [{id: "Simplice"},{id: "Valjean"}]
  var links = [{"source": "Simplice", "target": "Valjean", "value": 3}]

restart(); 会删除除指定节点和链接以外的所有节点和链接 - 我想要实现相反的效果。因此,我能够删除除指定元素以外的所有元素,并且图形重新绘制得很好,但我无法使其删除选定的节点。

d3.select(this).remove(); 可以删除节点,但不能删除链接,也不能重新绘制图形。

我的想法是:1. 将JSON数据存储在“nodes”变量中。 2. 在鼠标单击时从“nodes”变量中删除该元素及其链接。

然后图形应该能够重新绘制得很好。有什么好的想法吗?

1个回答

2
而不是使用修改文档,你需要修改数据本身(即nodes和links,而不是node和link)。我认为这基本上是你在问题结尾描述的内容。
例如,试试像这样的东西:
.on("click", function(d){
    nodes = nodes.filter(function(n){ return n.id !== d.id; });
    links = links.filter(function(e){
      return e.source.id !== d.id && e.target.id !== d.id;
    });
    restart();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接