Here is an important piece of code:
state.selectAll("rect") .data(function(d) { return d.ages; }) .enter().append("rect") .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.y1); }) .attr("height", function(d) { return y(d.y0) - y(d.y1); }) .style("fill", function(d) { return color(d.name); });
This attaches each data point to colored rectangles. To add text, change it as follows:
var ages_enter = state.selectAll("rect") .data(function(d) { return d.ages; }) .enter(); ages_enter.append("rect") .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.y1); }) .attr("height", function(d) { return y(d.y0) - y(d.y1); }) .style("fill", function(d) { return color(d.name); }); ages_enter.append("text") .text(function(d) { return d3.format(".2s")(d.y1); }) .attr("y", function(d) { return y(d.y1)+16; }) .style("stroke", '#ffffff');
A pointer to the "enter" method is stored here, which is called for each data point, and then adds an additional element to svg for each data point.
source share