I'm playing around with the "update" pattern in D3.js. I am just creating a simple bar graph that will update the data when you press the "Change" button.
My problem is that when you press the "Change" button, the first three rendered bars do not get re-rendered. I debugged and saw that the data was properly applied (__data__
was correct) but the re-application failed.
Here is my code and a link to it in CodePen:
var myData = [ 100, 200, 300 ];
d3.select('body').append('button').text("Change").on("click", function() {
myData = [200, 400, 600, 700, 800, 900, 1000];
update(myData);
});
var svg = d3.select('body').append('svg')
.attr("class", "chart")
.attr("y", 30);
var update = function(data) {
var bars = svg.selectAll('g')
.data(data);
var groups = bars.enter()
.append("g")
.attr("transform", function(d,i) {return "translate(0," + i*25 + ")"});
groups
.append("rect")
.attr("height", 25)
.attr("fill", "pink")
.attr("stroke", "white");
groups
.append("text")
.attr("x", 10)
.attr("y", 18)
.attr("fill", "red");
bars.selectAll("rect")
.attr("width", String);
bars.selectAll("text")
.text(String);
};
update(myData);