Home > Back-end >  Inserting a text on top of the rect component in a svg using d3
Inserting a text on top of the rect component in a svg using d3

Time:06-25

I've to put some text on top of the rectangles on a stacked bar chart in d3.js. I've to insert the text exactly as reported on the attached image below instead of the 'x' characters. How could I do?enter image description here

This is my code that creates the svg.

chartRealModel = {
  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height]);

  svg.append("g")
    .selectAll("g")
    .data(seriesRealModel)
    .join("g")
      .attr("fill", d => color(d.key))
    .selectAll("rect")
    .data(d => d)
    .join("rect")
      .attr("x", (d, i) => xRealModel(d.data.Week))
      .attr("y", d => yRealModel(d[1]))
      .attr("height", d => yRealModel(d[0]) - yRealModel(d[1]))
      .attr("width", xRealModel.bandwidth())
    .append("title")
      .text(d => `${d.key}
${formatValue(d.data[d.key])}`);

  svg.selectAll("rect")

  svg.append("g")
      .call(xAxisRealModel);

  svg.append("g")
      .call(yAxisRealModel);

  return svg.node();

CodePudding user response:

you pretty much do the same thing as you did to create the bars, but instead with the text

svg.append("g")
  .selectAll("label")
  .data(seriesRealModel)
   .join('text')
   .text( d => `${d.key}${formatValue(d.data[d.key])}`);
    // positioning the text in the middle of the bar
    .attr('x', d  => xRealModel(d.data.Week)   xRealModel.bandwidth() /2)
    // positioning on the top of the bar 
    .attr('y',d => yRealModel(d[1]) -5)
    .attr("fill", "black")
  • Related