The previous example works with another input files where
all self intersected polygons have been separated.
wget -nc https://thredds-su.ipsl.fr/thredds/fileServer/ipsl_thredds/brocksce/tmp/polys_03.pickle
See details from answer given in
https://discourse.vtk.org/t/create-separated-regions-from-polydata
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import shapely
from shapely import geometry
import cartopy.crs as ccrs
import random
import pickle
#-----------------------------------------
! wget -nc https://thredds-su.ipsl.fr/thredds/fileServer/ipsl_thredds/brocksce/tmp/polys_03.pickle
with open('./polys_03.pickle', "rb") as poly_file:
polygons = pickle.load(poly_file)
#-----------------------------------------
def polygon2patch(poly, **kwargs):
path = Path.make_compound_path(
Path(poly.exterior.coords, closed=True),
*[Path(ring.coords) for ring in poly.interiors])
patch = PathPatch(path, **kwargs)
return patch
#-----------------------------------------
fig = plt.figure(figsize=(10,5))
map_proj = ccrs.Orthographic(-10, 80)
#map_proj = ccrs.Orthographic(-10, 60)
ax = fig.add_subplot(1, 1, 1, projection=map_proj)
transform = ccrs.Geodetic()
holesNumber = []
for n,polygonA in enumerate(polygons):
if n != 16: continue
holes = []
for m,polygonB in enumerate(polygons):
if (m == n): continue
if polygonA.contains(polygonB):
holes.append(polygonB.exterior.coords)
holesNumber.append(m)
if n in holesNumber: continue # n is a hole
polygonNew = geometry.Polygon(polygonA.exterior.coords, holes=holes)
polygonNew = shapely.geometry.polygon.orient(polygonNew) # Orient to be oriented counter-clockwise
random_color = "#"+''.join([random.choice('0123456789ABCDEF') for i in range(6)])
patch = polygon2patch(polygonNew, transform=transform, facecolor=random_color, lw=0.5, edgecolor="black")
ax.add_patch(patch)
ax.set_global()
ax.gridlines()
plt.show()