How may I calculate the centroid of a multipolygon in shapely (not a polygon)

1.7k views Asked by At

I understand that the centroid of a polygon may be calculated from

from shapely.geometry import Polygon
coordinate_list = [[1,2], [2,3], [5,5]]
output = Polygon(coordinate_list).centroid

However, my coordinate_list is a multiple polygons, e.g. my coordinate_list = [[[1,2], [2,3], [5,5]], [[0,0], [0,1], [1,0]]]

Is there way to do this. Shapely appears to have a multipolygon class but it does not operate the same as the Polygon class.

1

There are 1 answers

0
margusl On BEST ANSWER

You can use MultiPolygon().centroid, it's just that you can't pass that coordinate_list directly to MultiPolygon constructor as it:

/../ takes a sequence of exterior ring and hole list tuples /../
/../ also accepts an unordered sequence of Polygon instances /../ https://shapely.readthedocs.io/en/stable/manual.html#collections-of-polygons

# Based on Multipolygon sample,
# https://shapely.readthedocs.io/en/stable/code/multipolygon.py

from matplotlib import pyplot
from shapely.geometry import Polygon, MultiPolygon
from descartes.patch import PolygonPatch

# from https://github.com/shapely/shapely/blob/main/docs/code/figures.py
from figures import BLUE, BLACK, SIZE, set_limits, plot_coords, color_isvalid

fig = pyplot.figure(1, figsize=SIZE, dpi=90)
ax = fig.add_subplot(121)
set_limits(ax, -1, 6, -1, 6)

coordinate_list = [[[1,2], [2,3], [5,5]], [[0,0], [0,1], [1,0]]]

# "constructor takes a sequence of exterior ring and hole list tuples" - 
# https://shapely.readthedocs.io/en/stable/manual.html#collections-of-polygons
multi = MultiPolygon([(coordinate_list[0], []), (coordinate_list[1], [])])

# "the constructor also accepts an unordered sequence of Polygon instances"
#multi = MultiPolygon([Polygon(coordinate_list[0]),Polygon(coordinate_list[1])])

plot_coords(ax, multi.centroid, color=BLACK)

for polygon in multi.geoms:
    plot_coords(ax, polygon.exterior)
    patch = PolygonPatch(polygon, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2)
    ax.add_patch(patch) 

Multipolygon with centroid