Shapely: Convert from a list of Points to a Polygon

Created on 24 Aug 2012  ·  3Comments  ·  Source: Toblerity/Shapely

Hi all,

I didn't find a mailing list of a forum, so I'm going to ask here. Is there a "canonical" form to convert from a list of Points to a Polygon? For example,

list_points = []
vertices = [Point(1,1), Point(2,2), Point(3,3)]
for i in xrange(len(vertices)):
    list_points.append(vertices[i])
polygon = Polygon(list_points)

This code doesn't work. I had to use convex_hull:

poly = MultiPoint(list_points).convex_hull

What is not exaclty what I'm looking for.

Thanks for the patience and the good work!

Most helpful comment

Ever so slightly faster again:

points = [Point(0,0), Point(2,2), Point(2,0)]
coords = [p.coords[:][0] for p in points]
poly = Polygon(coords)
poly.area

All 3 comments

Here's thing: polygon rings (instances of LinearRing) aren't defined by Points, they are defined by sequences of coordinate tuples. Points and coordinates are different things to Shapely. You need to pass the coordinates of the points to the Polygon constructor. Like this:

>>> points = [Point(0,0), Point(2,2), Point(2,0)]
>>> coords = sum(map(list, (p.coords for p in points)), [])
>>> poly = Polygon(coords)
>>> poly.area
2.0

As I keep googling for this every now and then, here is how I prefer to do it (I find it more readable like this):

>>> points = [Point(0,0), Point(2,2), Point(2,0)]
>>> coords = [(p.x, p.y) for p in points]
>>> poly = Polygon(coords)
>>> poly.area
2.0

timeit says things might be getting cached but @sgillies's approach seems consistently 2/3 faster (~65µs mine vs ~45µs his) so if you need super ultra hardcore performance for gazillions of points or polys, consider that.

Ever so slightly faster again:

points = [Point(0,0), Point(2,2), Point(2,0)]
coords = [p.coords[:][0] for p in points]
poly = Polygon(coords)
poly.area
Was this page helpful?
0 / 5 - 0 ratings

Related issues

kannes picture kannes  ·  4Comments

sgillies picture sgillies  ·  5Comments

LostFan123 picture LostFan123  ·  5Comments

pvalsecc picture pvalsecc  ·  4Comments

sgillies picture sgillies  ·  6Comments