I've been trying to adjust the following code: https://bl.ocks.org/mbostock/4062045 in such a way to make it possible to remove the node + its links on mouse-click.
What I tried so far was adding the following code:
.on("click",function() {
d3.select(this).remove();
restart();
})
And this snippet from here: 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();
}
If I first specify nodes and links the following way:
var nodes = [{id: "Simplice"},{id: "Valjean"}]
var links = [{"source": "Simplice", "target": "Valjean", "value": 3}]
restart(); removes all nodes and links except the specified ones - I am trying to achieve the opposite. Therefore, I am able to remove all elements except ones specified and the graph redraws itself nicely, but I am not able to make it remove selected nodes.
d3.select(this).remove(); removes the node but not the links and does not redraw the graph.
My idea is to: 1. store the json data in "nodes" variable. 2. Remove the element and its links from "nodes" variable on mouse-click.
Then the graph should redraw itself nicely. Any ideas how to do it?
Rather than modifying the document with d3.select(this).remove(), you need to modify the data itself (i.e. nodes and links instead of node and link). I think this is basically what you are describing at the end of your question.
For example, try something like this:
.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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With