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

后端 未结 2 1358
悲哀的现实
悲哀的现实 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:50

    I plotted out with this code. Text will append into center of the stacked chart . We need to find out the x coordinate values for position the text. For that barWidth/2 is used.Demo Sorted Stacked Bar Chart

     var state= svg.selectAll(".state")
      .data(data)
    .enter().append("g")
      .attr("class", "state")
      .attr("transform", function(d) { return "translate(" + (x(d.state)) + ",0)"; });
    
      module.selectAll("rect")
      .data(function(d) { return d.ages; })
      .enter().append("rect")
      .attr("width", x.rangeBand())
      .attr("y", 200)
      .attr("height", 100) 
      .style("fill", function(d) { return color(d.name); })
      .transition()
       .delay(function(d, i) { return i * 200; })
       .duration(4000)
       .attr("y", function(d) { return y(d.y1); })
       .attr('height', function(d) { return y(d.y0) - y(d.y1); });
    
     module.append("text")
      .attr("y", 400)
      .attr("x",x.rangeBand()/2 )
      .style("text-anchor", "middle")
      .style("font-size", "20px")
      .style("color", "white")
      .text(function(d,i) { return i+1; }); 
    

提交回复
热议问题