Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am creating a piechart with D3 using d3.layout.pie(). 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. Thanks.

Circle chart

like image 225
Sergei Basharov Avatar asked Jul 02 '13 13:07

Sergei Basharov


Video Answer


2 Answers

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?

like image 179
Justin Ethier Avatar answered Oct 15 '22 19:10

Justin Ethier


I know its been a year you asked this questions but just dropping in an answer which might help others. Try Using the arc.centriod() in the transform of the circles you want to display.

Something like this

enterMenu.append("circle")
            .attr("r", 5)
            .attr('transform',function(d){
              return "translate(" + arc.centriod(d) + ")";
            });

This should place the circle exactly in between the slice. In the above function d is the endAngle of the arc.

For you reference Check out this link http://bl.ocks.org/Guerino1/2295263

like image 26
Chait Avatar answered Oct 15 '22 18:10

Chait