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

How to update bound data in d3.js?

本文关键字:更新 绑定 数据 js d3      更新时间:2023-09-26

我想在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)});

此代码有效。但是当我更新数据时,例如:

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);

不行。

如何更新绑定数据?

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

编辑2:假设我这样做:

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

我可以修改mydata吗?

没有像

角度那样的数据绑定魔法会触发"重绘"。 只需调用.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();

这里的例子。

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

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

我基于常规更新模式的更改,以及迈克关于联接的这篇文章

我已经在每个圆圈的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();

更新数据时,每次都会运行force.start();,因此它看起来像新数据。如果删除它,则更容易看到正在发生的事情,但会丢失动画。您可能想要的是仅对新节点(也许是现有节点)的条目进行动画处理,但这将是一个单独的问题