Create Polygon from Points
Last updated:
You can create a Shapely polygon from a list of points, either by providing the point's coordinates or extracting them from a list of Shapely points.
The most basic geometrical objects in Shapely are points and polygons. In case you want to create a polygon from a list of points, there are two cases: you can either provide the coordinates directly, or you might have stored the coordinates as Shapely points.
Create Polygon from a list of xy coordinates
In order to create a shapely polygon from a list of coordinates, they must be ordered as a list of 2-element lists or tuples. Shapely will automatically take care of closing the polygon:
from shapely.geometry import Polygon
poly1 = Polygon( [[0, 0], [1,0], [1,1], [0,1] ] )
poly2 = Polygon( [(0, 0), (1,0), (1,1), (0,1) ] )
print(poly1.wkt)
print(poly2.wkt)
POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))
POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))
Create Polygon from a list of shapely Points
Creating a polygon from a list of Shapely points is actually not much different than the previous option. Actually, we need to extract the coordinates manually and resort to list comprehensions to create a list of coordinates, sorted in the same way as before.
from shapely.geometry import Point, Polygon
p1 = Point(0,0)
p2 = Point(1,0)
p3 = Point(1,1)
p4 = Point(0,1)
points = [p1, p2, p3, p4, p1]
poly = Polygon([[p.x, p.y] for p in points])
print(poly.wkt)
POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))