I am working through a tutorial in Scott Murray's amazing "Interactive Data Visualization For The Web" (my second attempt...I got too frustrated and gave up before) and got to an extra credit segment of an interactive bar chart tutorial. The on click trigger adds new bars from randomly generated data...but the labels don't update. He left in an initial code block to "create" the text labels leaving the challenge of updating based on the code. So I looked at the code used to update the bars...
var bars = svg.selectAll("rect")
.data(dataset);
bars.enter()
.append("rect")
.attr("x", w)
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.bandwidth())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", function(d) {
return "rgb(0, 0, " + Math.round(d * 10) + ")";
})
.merge(bars)
.transition()
.duration(500)
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.bandwidth())
.attr("height", function(d) {
return yScale(d);
});
...and interpolated that with the original code block used to create the initial labels...
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.bandwidth() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
so with that in mind this is what I came up with...
var labels = svg.selectAll("text")
.data(dataset);
labels.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", w)
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
})
.merge(labels)
.transition()
.duration(500)
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.bandwidth() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
});
At least to the point where it doesn't break the bar update code...but it gets stuck at the .merge(labels) line with an Uncaught ReferenceError: labels is not defined and the labels don't update. If I define a variable called "labels" (exactly the same way "bars" are) shouldn't that be all that's required to define?