Recharts Pie Chart - Calculate Max Width of Text Label in a Given Slice

70 Views Asked by At

I've been trying to find a react chart library that is flexible (feature-wise) as well as responsive, but it's been difficult, as most libraries I've come across don't handle responsiveness very well (for example, Nivo is over all an amazing chart library, but the responsiveness on the pie chart was almost non-existent - deal breaker).

So I think I've landed on Recharts, which seems both flexible and pretty decently responsive. But I'd like to improve the responsiveness of the pie chart, specifically when using custom labels that go directly on the pie slices. What I'm trying to accomplish is what React Google Charts does out of the box (see this example here) - specifically, as you're making the browser window smaller and the pie is getting smaller, hide the labels that don't fit in the pie slice, like this:

enter image description here

So I need a formula to calculate the max width of a label for a given pie slice.

Assumptions

  1. The label is horizontal in orientation.
  2. The label is centered somewhere along the mid angle of the slice (but can be closer to center of pie or closer to outside of pie), like this:

enter image description here

Account for the Following Data

  1. Where along the mid angle the label sits
  2. How wide the pie slice is (the angle of the slice itself)
  3. What orientation the slice is along the pie (it's mid angle)

Here's the formula I'm currently using that gets me close to what I want, but it doesn't account for the orientation of the slice on the pie (mid angle), which it should, because the text is horizontal so should generally be able to fit more in a slice that is also horizontally oriented:

const maxLabelWidth = 2 * radius * Math.sin(angleInRadians / 2);

...where radius is the radius at the point where the label sits - this could be the full radius (outer radius) or some fraction of that (* 0.5 would be the exact center of the pie slice, * 0.7 would be further towards the outer radius).

0

There are 0 best solutions below