Text On each panel of the folded histogram d3.js

I would like to have some text in each column of the stacked row in the stacked histogram presented in the d3.js library.

Thank you for your help.

I set up an example link here, but I did not change anything in javascript code

and here is the result result

+4
source share
2 answers

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.

+3
source

I built this code. Text will be added to the center of the complex chart. We need to find out the x coordinate values ​​to place the text. For this, barWidth / 2 is used. Demo Sorted Pivot 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; }); 
0
source

Source: https://habr.com/ru/post/1490748/


All Articles