Text On each bar of a stacked bar chart d3.js

后端 未结 2 1344
悲哀的现实
悲哀的现实 2021-01-03 02:06

I would like to have some text in each bar of a stacked bar in stacked bar chart provided in d3.js library.

Thanks for your help.

I have customized the examp

2条回答
  •  情歌与酒
    2021-01-03 02:42

    Here is the 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 binds each data point to the colored rectangles. To add text, change it like this:

      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');
    

    This stores a pointer to the "enter" method that is called for each data point, then adds an additional element to the svg for each data point.

提交回复
热议问题