我已經訪問add and remove nodes in D3js但它不能解決我的問題。如何刪除d3.js中的現有節點
有一些節點在第一時間,然後我想要動態添加節點,並希望如果節點已經存在,它會更新節點,並且不會重複。
現在它正在複製而不更新現有的。
這是主要的代碼和完整的代碼和工作小提琴是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);
感謝您的回覆。讓我向你解釋我想做什麼。 **要更新現有節點的半徑並添加新節點** ** 1 **這些是存儲在數據庫中的關鍵字。 ** 2 **第一次顯示20個節點和半徑大小,基於該關鍵字在數據庫中存在的時間。 ** 3 **現在新的關鍵字進入數據庫或添加了一些重複的關鍵字。 ** 4 **現在10秒後我打電話到數據庫並檢索關鍵字並想更新現有節點的半徑並添加新節點 –
查看http://bl.ocks.org/mbostock/3808218。它顯示了d3中的一般更新模式,接下來的兩個示例顯示如何執行鍵控數據和轉換。 基本上,您要做的是指定數據進入,離開和更改時發生的情況。您需要一個定義這些行爲的函數,然後每次更新數據時調用該函數。 – ckersch