如何更新d3.js中的绑定数据?

kei*_*uke 7 javascript d3.js

我想在D3.js中动态更新网络图.现在我的代码是:

var color = d3.scale.category20();
var my_nodes = [{"cluster": 0, "x": 50,  "y": 50},
                {"cluster": 0, "x": 100, "y": 50},
                {"cluster": 1, "x": 100, "y":100}];
var vis = d3.select("body").append("svg").attr("width", 500).attr("height", 500);
var nodes = vis.selectAll("circle.node").data(my_nodes).enter().append("g")
               .attr("class", "node");
var circles = nodes.append("svg:circle")
                   .attr("cx", function(d) { return d.x; })
                   .attr("cy", function(d) { return d.y; })
                   .attr("r", 5)
                   .style("fill", function(d) {return color(d.cluster)});
Run Code Online (Sandbox Code Playgroud)

这段代码有效.但是当我更新数据时:

var new_nodes = [{"cluster": 0, "x": 50,  "y": 50},
                 {"cluster": 2, "x": 100, "y": 50},
                 {"cluster": 2, "x": 100, "y":100}];
nodes.data(new_nodes);
Run Code Online (Sandbox Code Playgroud)

不起作用.

如何更新绑定数据?

编辑:我想要做的是用my_nodes新数据替换旧数据new_nodes.有没有办法更新cluster每个绑定数据的属性?

编辑2:假设我这样做:

d3.select("body").select("svg").selectAll("circle").data(mydata).enter().append("svg:circle");

我可以修改mydata吗?

Mar*_*ark 10

没有数据绑定魔法角度会触发"重绘".只需调用.data然后重新设置属性:

function update(){
 nodes
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .attr("r", 5)
  .style("fill", function(d) {
    return color(d.cluster)
  });
}

var nodes = vis.selectAll("circle.node").data(my_nodes)
  .enter()
  .append("g")
  .attr("class", "node")
  .append("svg:circle");
update();

// some time later

nodes.data(new_nodes);
update();
Run Code Online (Sandbox Code Playgroud)

这里的例子.

  • 谢谢你。问题之一是您指出的“重绘”问题,另一个问题是“子节点继承父数据。但如果更新父数据,则不会自动更新子数据。” 所以我想做的是:[这里](http://plnkr.co/edit/ixWDtnbl1iDSi71nTiNv?p=preview) (2认同)

Hen*_*y S 5

不知道您希望它看起来如何,但是我在这里创建了一个小提琴:http : //jsfiddle.net/henbox/8ua144p4/4/

单击update按钮将更新为新数据。

我基于常规更新模式所做的更改以及Mike在Joins上的这篇文章

我在fill每个圆的属性上都添加了一个过渡,因此您可以希望看到在这种情况下正在更新节点,而不是添加新节点。我还展示了添加的第4个新节点,以演示差异。

最后,我通过删除nodeg)元素并仅使用来简化了一些事情circle。这是重要的代码:

// DATA JOIN
// Join new data with old elements, if any.
var circle = vis.selectAll("circle").data(data);

// ENTER
// Create new elements as needed.
circle.enter().append("svg:circle").attr("r", 5);

// UPDATE
// Update old elements as needed.
circle.attr("cx", function (d) {return d.x;})
    .attr("cy", function (d) {return d.y;})
    .transition().duration(750)
    .style("fill", function (d) {
    return color(d.cluster)
});
// EXIT
// Remove old elements as needed.
circle.exit().remove();
Run Code Online (Sandbox Code Playgroud)

数据更新后,force.start();每次都会运行,因此看起来像新数据。如果将其删除,则更容易看到正在发生的情况,但会丢失动画。您可能想要的只是为新节点(甚至可能是退出节点)设置动画,但这将是一个单独的问题