How can i fix arc labels overlapping in d3js?

Issue

I am drawing a doughnut chart using d3js.

I have few issues

1) the arc labels over lap over arc. Any idea how can i fix it?

enter image description here

2) the arc labels i am applying the style class pieChartOuterLabel , however it is not getting applied .

.pieChartOuterLabel {
  font-size: 1em;
  fill: black;
  font-weight: bold;
  font-family: 'Times New Roman, Times, serif';
}

3) How can i align the text in the center of the chart centrally aligned ?

the project is available on stack blitz.

https://angular-dbcqpg.stackblitz.io/

the code is also available at

https://stackblitz.com/edit/angular-dbcqpg

really appreciate any help.

Solution

Lets answer your questions one by one.

  1. To adjust the labels create a more creative function in the transform for the text like so.
  .attr("transform", function(d) { 
    let labelcoords = labelArc.centroid(d); // retrieve the label coords
    let offset = 6; // distance by which you want the labels to move out
    //now get the new label coords by running a function on them
    labelcoords[0] = adjustLabelCoords(labelcoords[0]);
    labelcoords[1] = adjustLabelCoords(labelcoords[1]);
    //This function checks if the coords are negative or positive and applies the offset
    function adjustLabelCoords(coord) {
      if (coord < 0) {
        coord = coord - offset; //if coord is negative, apply a negative offset to move more left or up
      } else if (coord > 0) {
        coord = coord + offset; //if coord is positive, apply a positive offset to move right or down
      }
      return coord;
    }
    return "translate(" + labelcoords + ")"; }
  )
  1. The class .pieChartOuterLabel is being applied see the screenshot below. So I am not able to understand your issue.

The css style is being applied

You can see that the class is being applied correctly to the text.

  1. Your text is already aligned in the center using the text-anchor="middle" attribute. I suppose you want it to be vertically also centered. To do that you can do the following:

Change your svgTextLabel to:

        svgTxtLabel
          .attr("text-anchor", "middle")
          .attr("font-size", (labelSize)+'em')
          .attr("transform", `translate(0,-10)`)
          //.attr("dy", '-1.5em')
          .attr("class","pieChartCenterTextLabel")
          .transition().delay(2000)
          .text("Total");

and your svgTxtValue to:

 let svgTxtValue =   svg.append("text");
      svgTxtValue
        .attr("text-anchor", "middle")
        .attr("font-size", (valueSize)+'em')
        .attr("transform", "translate(0,10)")
        .attr("class","pieChartCenterTextLabel")
        .transition().delay(2000)
        .text(total);

All of this produces:

Final result

Here is the final stackblitz.

Answered By – Coola

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.