Sergei Basharov Sergei Basharov - 1 year ago 63
HTML Question

How to get coordinates of slices along the edge of a pie chart?

I am creating a piechart with D3 using

It looks like this one, without black dots (I've put them manually in Photoshop to illustrate my issue). I wonder how I can calculate coordinates of these dots, that are in the middle of the surface to place some tooltips there. I am not asking for a finished solution but more about the principle how to do it.

Circle chart

Answer Source

You can use the following equations to calculate a point along the circumference of a circle:

x = cx + r * cos(a)
y = cy + r * sin(a)

Where (cx, cy) is the center of the circle, r is the radius, and a is the angle.

In order for this to work for you, you will need a way to computing the angle based upon the pie slices on your chart - see below.

According to the d3 documentation for pie layouts, the pie function returns a list of arcs, so you can process this data to calculate each of your points:

pie(values[, index])

Evaluates the pie function on the specified array of values. An optional index may be specified, which is passed along to the start and end angle functions. The return value is an array of arc descriptors

  • value - the data value, returned by the value accessor.
  • startAngle - the start angle of the arc in radians.
  • endAngle - the end angle of the arc in radians.
  • data - the original datum for this arc.

Presumably you could just take half the distance between endAngle and startAngle for each arc, and place your point there.

For what it's worth, here is the code from pie.js that is used to compute each arc:

// Compute the arcs!
// They are stored in the original data's order.
var arcs = [];
index.forEach(function(i) {
  var d;
  arcs[i] = {
    data: data[i],
    value: d = values[i],
    startAngle: a,
    endAngle: a += d * k
return arcs;

Does that help?