Polygons and holes
How Shapely stores a polygon, how its area is computed with the shoelace formula, and what a hole does to area and centroid.
- Build a Polygon from coordinates, with and without holes
- Compute a polygon's area with the shoelace formula
- Read exterior, interiors, bounds and centroid, and know what each means
A Polygon is a closed exterior ring plus any number of interior rings (holes). The notebook builds a triangle two ways — from coordinate tuples and from Point objects — and they are the same polygon:
poly = Polygon([(2.2, 4.2), (7.2, -25.1), (9.26, -2.456)])
poly2 = Polygon([[p.x, p.y] for p in [point1, point2, point3]])
poly.area # 86.789
The ring does not need to repeat its first point; Shapely closes it.
Area by the shoelace formula
For a ring of vertices \((x_0, y_0), \dots, (x_{n-1}, y_{n-1})\),
\[A = \frac{1}{2} \sum_{i=0}^{n-1} \left( x_i\,y_{i+1} - x_{i+1}\,y_i \right), \qquad (x_n, y_n) = (x_0, y_0)\]Each term is the signed area of the triangle between the origin and one edge. Edges that run anticlockwise around the origin add; the others subtract; everything outside the polygon cancels.
The sign of the sum tells the ring’s orientation: positive for anticlockwise. The notebook’s triangle comes out positive, and poly.exterior.is_ccw is True. Shapely reports area as an absolute value either way.
A world with a hole
world_exterior = [(-180, 90), (-180, -90), (180, -90), (180, 90)]
hole = [[(-170, 80), (-170, -80), (170, -80), (170, 80)]]
world = Polygon(shell=world_exterior)
world_has_a_hole = Polygon(shell=world_exterior, holes=hole)
| Attribute | world | world_has_a_hole |
|---|---|---|
area | 64,800 | 64,800 − 340 × 160 = 10,400 |
centroid | (0, 0) | (0, 0) |
bounds | (−180, −90, 180, 90) | the same |
exterior.length | 1,080 | the same |
The hole removes area but not bounds or exterior: those describe the outer ring only. The centroid stays at the origin because the hole is centred. In general a hole moves the centroid away from itself — or, as in the diagram above, the centroid can end up inside the hole.
The holes argument is a list of rings, which is why hole is wrapped in an extra pair of brackets.
Try it yourself. Implement the shoelace formula in five lines of Python and check it against world_has_a_hole.area. (Apply it to the exterior and to each ring in interiors, and subtract.) Then reverse the order of the triangle’s vertices and check what happens to your signed sum, poly.area, and poly.exterior.is_ccw.