如何在 d3.js 中更新绑定数据
How to update bound data in 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)});
此代码有效。但是当我更新数据时,例如:
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 个新节点,以演示差异。
最后,我通过删除node
(g
)元素并仅使用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();
,因此它看起来像新数据。如果删除它,则更容易看到正在发生的事情,但会丢失动画。您可能想要的是仅对新节点(也许是现有节点)的条目进行动画处理,但这将是一个单独的问题
相关文章:
- Angular:更新一次性绑定的数据
- AngularJS 1.5.x服务未正确绑定,并且未在控制器中更新
- AnguarJS 1.3使用一次性绑定手动更新绑定
- Angular$watch未更新绑定
- 是否可以在extjs5中动态更新绑定
- 如何在引导日期范围选取器日期更改时更新绑定
- 将更新绑定到链接中的指令元素,而不是内联
. - 表单提交不会更新绑定到单选按钮的模型
- 如何在 d3.js 中更新绑定数据
- 角度更新绑定配置
- 为什么我的 ko 计算的可观察量在其值更改时不更新绑定的 UI 元素
- KnockoutJS-一个计算可写的可观察对象;无法正确更新绑定
- 在AngularJS中,如何为多个控制器的共享服务属性的异步模型更改更新绑定[.]
- js:更新绑定
- 更新绑定与jQuery排序
- Angular.js:手动修改后更新绑定
- JqxGrid过滤器值在更新绑定数据时清除
- 如果以编程方式更改了模型,Ko不会更新绑定控件
- 为什么不't将通知更新绑定到变量
- 更新绑定到表单表的observableArray会导致焦点丢失