我一直在尝试调整以下代码: 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}]
重启();删除除指定节点和链接之外的所有节点和链接 - 我正在努力实现相反的目标。因此,我能够删除除指定元素之外的所有元素,并且图形会很好地自行重绘,但我无法让它删除选定的节点。
d3.select(this).remove();删除节点但不删除链接并且不重绘图形。
我的想法是: 1. 将 json 数据存储在“nodes”变量中。 2. 单击鼠标从“nodes”变量中删除元素及其链接。
然后图形应该很好地重新绘制。有什么想法吗?
最佳答案
与其使用 d3.select(this).remove()
修改文档,不如修改数据本身(即 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();
});
关于javascript - d3 网络(图形)可视化 - 单击时删除节点(+链接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42270662/