How do you know if a dot (x, y) is within the filled percentage of a pie chart?

6

I came up with this code that shows whether a point (x, y) is inside or outside a circle on a Cartesian plane.

def dentro_fora(p, x = 0, y = 0):

    r = cx = cy = 50

    if (x - cx)**2 + (y - cy)**2 < r**2:
        return 'dentro'
    else:
        return 'fora'

But I needed to know if this point is in the filled part of the circle, for example if I have 33% of the circle filled (assuming it is a pie chart), how do I find out if the point (12, 55) of the filled area?

Considering that the center of the circle is the point (50, 50) and the radius is 50.

    
asked by anonymous 07.01.2017 / 16:55

1 answer

11

You are using a basic distance formula, which in practice simply tells you whether the point is in the circle or not.

Since it is enough to determine if it is on the graph, all you need to know is the angle of the point with respect to the center. It is from this angle that you will extract the percentage where the point is.

It has a mathematical function that gives you this ready, is the arc tangent with 2 parameters:

 angulo = math.atan2( x, y )

x, y are the coordinates of the point in relation to the center of the circle, in the case of the graph of your question, it would be ( x - 50, y - 50 ) .

It is important to consider that atan2 considers the rightmost point as the beginning, and usually the pie charts use the origin at the top, so you can make a move with symmetry:

 angulo = math.atan2( -y, -x )

And with the center setting:

 angulo = math.atan2( -(y - 50), -(x - 50) )

(adjust as needed, the key is to invert the coordinates and the negative on some or both sides depending on the source used)

To know in percent, in relation to pie chart, divide the angle by 2 PI (representing the 360º in Radians), and multiply by 100:

porcentagem = angulo / ( math.pi * 2 ) * 100

(I did not simplify the formula to make reading easier)

Of course, if you have several "slices" in the pizza, you will have to add up the percentage of each of them until you get past the "percentage" obtained in the above formula.

Example: if the point is at 62%, and you have pieces of 20%, 30% and 40%:

  Pedaço 1 - 20%  (20 >= 62, falso, vamos pro próximo )
  Pedaço 2 - 30%  (30 + 20 >= 62, falso, vamos pro próximo )
  Pedaço 3 - 40%  (40 + 30 + 20 >= 62, verdadeiro, achamos nosso pedaço )

This is probably the case with a simple loop .

    
07.01.2017 / 17:04