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

我们两清 提交于 2019-12-18 17:01:32

问题


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 example here link but I have not changed anything else in the javascript code

and here is the result


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/17574621/text-on-each-bar-of-a-stacked-bar-chart-d3-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!