Can anyone explain why a selectAll + data + enter + append works fine initially, but when I call it again it only appends a single element?
http://jsfiddle.net/scottieb/wQJen/
When I run
vis.selectAll("circle")
.data(datafiltered).enter().append("svg:circle")
.attr("cx", function(d) { return x(d.x)})
.attr("cy", function(d) { return y(d.y)})
.attr("fill", "red").attr("r", 15);
I get four points (corresponding to the four pairs of data in ‘datafiltered.’). But on button click, I run
vis.selectAll("circle")
.data(datafiltered2)
.enter().append("svg:circle")
.attr("cx", function(d) {
return x(d.x)
}).attr("cy", function(d) {
return y(d.y)
}).attr("fill", "black").attr("r", 5);
and only add the final element of ‘datafiltered2’ (five pairs in this one). So, the data are different and the second one occurs on button click, but not sure why I’m only getting the one point added!
The issue here is that there is no key function on the data you are binding, so D3 uses the index instead – hence the first four (pre-existing) elements are bound with new data, and the single 5th element gets added.
See this recent tutorial for details on key functions: http://bost.ocks.org/mike/constancy/
Possibly you really only wanted to add the single element, but also change the existing elements to represent their newly bound data, as in: http://jsfiddle.net/jsl6906/wQJen/2/