Sohail Ahmad
Sohail Ahmad

Reputation: 256

How to remove existing nodes in d3.js


I have already visit add and remove nodes in D3js but it don't solve my problem.

There are some nodes at first time, then I want to add nodes dynamically and want if node is already exists it update that nodes and don't do duplicate.

now it is making duplicate not updating existing ones.
Here is main code and full code and working fiddle is here

//handles node elements
var circles = svg.selectAll('g');


//update graph (called when needed)
function restart() {

/***************************************
    Draw circles (nodes)
****************************************/


circles = circles.data(data.nodes);

var g = circles.enter()
               .append("g")
               .attr("class", "gNode")
               .attr("cursor", "pointer")
               .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
               .call(force.drag);



g.append("circle")                      
.attr({
     "class": "node", 
     "cx": function(d) { return rScale(d.NumOccurrences); },
     "cy": function(d) { return rScale(d.NumOccurrences); },
     "r": function(d) { return rScale(d.NumOccurrences); }
 })             
 .style("fill", function(d, i) { return colors(i); })
 .style("stroke", "#000");



 g.append("text")
.attr({
    "x": function(d) { return rScale(d.NumOccurrences); },
    "y": function(d) { return rScale(d.NumOccurrences); },
    "font-family": "sans-serif",
    "font-size": "20px",
    "fill": "black",
    "text-anchor": "middle"
   })
   .text( function (d) { return d.name; });

   g.append("title")        
    .text(function(d) { return d.name; });

 // remove old nodes
 circles.exit().remove();

 // set the graph in motion
 force.start();
 }

// app starts here
restart();


 function dynamicAddNodes() {

var updatedata = {"name":"ios","NumOccurrences":"500","color":"green","x":0,"y":1}

data.nodes.push(updatedata);    

restart();
 }

 setInterval(dynamicAddNodes, 10000);

Upvotes: 6

Views: 5516

Answers (2)

MHS
MHS

Reputation: 931

try it:

circles = circles.data(data.nodes,function (d) {
     return d.id;
   });

that the node's Id is unique.

you can see : jsfiddle.net/MoHSenMHS/5r62N/

Upvotes: 3

ckersch
ckersch

Reputation: 7687

Your problem is not the update nodes process, but the data you are updating them to.

When restart() runs, it doesn't remove any nodes from the data, it just adds them. Since the data is never taken away, nodes are never taken away. Each time the function is called, a new data node is added, and a new circle is added corresponding to that data node.

I've updated your example here to show this behavior. Each time I change the data, I remove an entry from your data, and replace it with a new data point.

Upvotes: 1

Related Questions