Jojo Ceasar
Jojo Ceasar

Reputation: 13

How to calculate the center of pie slice with pie chart created with D3?

I created a pie chart with D3. I want to calculate the center of each pie slice, so I can draw a line/path from the center of each pie slice. At the end of the line, it'll have text.

Code Playground

I want something like this, but the line will be invisible when it's inside the pie chart.

Pie

Upvotes: 0

Views: 26

Answers (1)

Noleli
Noleli

Reputation: 662

As @Mark pointed out in a comment, arc.centroid will give you the center of the arc. But based on your drawing, that’s not quite what you want. For each line you’re looking for two points: the center of the pie (which is the same for all lines) and a point that’s at the center angle of each segment but with a radius somewhere outside.

You already know the center of the pie because it’s the center of your coordinate system. In Cartesian (x, y) coordinates it (0, 0), and in polar (radius, angle) coordinates it’s (0, doesn’t matter).

The angle of each line is the average of startAngle() and endAngle() in each element of Pie_Data.

You can generate the data like this:

const lineAngles = Pie_Data.map(d => (d.endAngle() - d.startAngle)/2);

The radius is the same for each line, and would be some arbitrary amount larger than outerRadius. I’ll call it lineRadius.

At this point use pointRadial() to draw a line from 0, 0 to pointRadial(angle, radius) we calculated above.

lineAngles.map(d => {
  const endPoint = pointRadial(d, lineRadius);
  return `<line x1="0" y1="0" x2=${endPoint[0]} y2=${endPoint[1]}></line>`;
}).join("\n");

Note that I’m not using JSX, so adjust accordingly :)

Upvotes: 0

Related Questions