Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...