'How to add non-overlapping polylines and text labels to 3D pie chart using d3.js?

I have commented the extra code on the already existing code written by DavidB and created this example to extract only one 3d pie chart. I would like to add polylines(non-overlapping) and text labels to the pie chart. Any suggestions are highly appreciated. The expected results should look like this.enter image description here



Solution 1:[1]

How to prevent overlapping SVG text

Since the text is absolutely positioned, there isn't a great way of dealing with overlapping labels. SVGs have tspan elements which allow you to word-wrap, but that's about it.

In one of my data visualization projects, we had to deal with many labels that needed to resize when the graph would shrink. The way we handled this, was by calculating the available space. Then "simulating" the total size of a text label (at a given font size) using:

selection.node().getBBox().width
selection.node().getBBox().height

If the dimensions of the new label would have overlapped, then you would try again with a smaller font size, until the dimensions of the label were smaller than the available space. It wasn't a great solution...

One issue with generating SVG elements (in order to measure their size) is that it triggers a re-rendering, which is expensive, considering the number of iterations.

You can improve the performance of this "brute force" approach, by using a <canvas> to calculate the size of a given label, without rendering anything:

  let canvasEl = document.createElement('canvas');
  let canvas = canvasEl.getContext('2d').font('12px sans-serif');
  const getWidthHeightOfLabel = (label) => {
    return { 
      width: canvas.measureText(label).width, 
      height: canvas.measureText(label).height
    };
  } 

In certain situations, we avoided SVG labels altogether and opted for plain old HTML text, which we would dynamically position ontop of the SVG.

Please let me know if my suggestion is unclear or if you need additional information! Thanks.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1