Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate area of polygon given (x,y) coordinates

I have a set of points and would like to know if there is a function (for the sake of convenience and probably speed) that can calculate the area enclosed by a set of points.

for example:

x = np.arange(0,1,0.001) y = np.sqrt(1-x**2)  points = zip(x,y) 

given points the area should be approximately equal to (pi-2)/4. Maybe there is something from scipy, matplotlib, numpy, shapely, etc. to do this? I won't be encountering any negative values for either the x or y coordinates... and they will be polygons without any defined function.

EDIT:

points will most likely not be in any specified order (clockwise or counterclockwise) and may be quite complex as they are a set of utm coordinates from a shapefile under a set of boundaries

like image 785
pbreach Avatar asked Jun 28 '14 14:06

pbreach


People also ask

How do you find area in coordinate geometry?

The formula of the area of triangle in coordinate geometry is: A = (1/2)|x1 1 (y2 2 − y3 3 ) + x2 2 (y3 3 − y1 1 ) + x3 3 (y1 1 − y2 2 )|, where (x1 1 ,y1 1 ), (x2 2 ,y2 2 ), and (x3 3 ,y3 3 ) are the vertices of triangle.

How do you calculate area of a shape using the coordinates of its vertices?

To find the area of a triangle where you know the x and y coordinates of the three vertices, you'll need to use the coordinate geometry formula: area = the absolute value of Ax(By - Cy) + Bx(Cy - Ay) + Cx(Ay - By) divided by 2. Ax and Ay are the x and y coordinates for the vertex of A.


1 Answers

Implementation of Shoelace formula could be done in Numpy. Assuming these vertices:

import numpy as np x = np.arange(0,1,0.001) y = np.sqrt(1-x**2) 

We can redefine the function in numpy to find the area:

def PolyArea(x,y):     return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) 

And getting results:

print PolyArea(x,y) # 0.26353377782163534 

Avoiding for loop makes this function ~50X faster than PolygonArea:

%timeit PolyArea(x,y) # 10000 loops, best of 3: 42 µs per loop %timeit PolygonArea(zip(x,y)) # 100 loops, best of 3: 2.09 ms per loop. 

Timing is done in Jupyter notebook.

like image 81
Mahdi Avatar answered Sep 23 '22 00:09

Mahdi