How to update bound data in d3.js?
d3.js, javascript
Solution
There's no data-binding magic à la angular that's going to trigger a "redraw". Just call `.data` and then re-set the attributes:
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();
Example here.
Problem
I want to update a network graph dynamically in D3.js. Now my code is: ``` 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)}); ``` This code works. But when I update data like: ``` 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); ``` doesn't work. How can I update bound data? EDIT: What I want to do is replacing old data `my_nodes` with new data `new_nodes`. Is there any way to update the attribute `cluster` of each bound data? EDIT2: Suppose I do: `d3.select("body").select("svg").selectAll("circle").data(mydata).enter().append("svg:circle");` Can I modify `mydata`?