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

前端 未结 3 2073
离开以前
离开以前 2020-12-19 05:10

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

相关标签:
3条回答
  • 2020-12-19 05:54

    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?

    0 讨论(0)
  • 2020-12-19 06:00

    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

    0 讨论(0)
  • 2020-12-19 06:05

    It may sound trivial but I was trying to find the x and y coordinates inside each slice, and when I saw the formula posted above,

    x = cx + r * cos(a)

    y = cy + r * sin(a)

    , it can be done by increasing r from (cx+1 or cy+1) to radius length, and repeating by increasing (a) from origin angle to destination angle, then adding (cx, cy). Hope it helps someone.

    0 讨论(0)
提交回复
热议问题