javascript - 如何删除 d3.js 中的现有节点

标签 javascript d3.js visualization data-visualization


我已经访问了add and remove nodes in D3js但它不能解决我的问题。

第一次有一些节点,然后我想动态添加节点,如果节点已经存在,它会更新该节点并且不要重复。

现在它正在复制而不是更新现有的。
这是主要代码和完整代码,工作 fiddle 是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);

最佳答案

尝试一下:

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

节点的 Id 是唯一的。

你可以看到:jsfiddle.net/MoHSenMHS/5r62N/

关于javascript - 如何删除 d3.js 中的现有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17649385/

相关文章:

c++ - VTK:定位和缩放多架飞机

javascript - 使用 angularjs 提交表单后显示警报

javascript - Grails-检索i18n消息时阻止XSS

javascript - 在 Google map API 的 SVG 图标内添加文本

javascript - 使用多维数组/嵌套 json 文件创建 d3 水平条形图

javascript - 在 AngularJS 的数据可视化上下文中调用 D3 工具提示

python - Python中的树形图

python - 在 python 中使用 matplotlib 绘制相似度测量圆时出错

javascript - 如何选择和操作表 jQuery 中的列

javascript - Javascript 中异步任务的 for..in 循环