Search code examples
pythoncoordinatespolygonarea

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


Solution

  • 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.