Search code examples
pythongeopandasvoronoi

Python: how to extend Voronoi cells to the boundary of the geometry?


I have two geopandas dataframes dfMd and centers. dfMd is made by polygons while centers by points. Here the link to the files.

f,ax=plt.subplots()
dfMd.plot(ax=ax, column='volume')
centers.plot(ax=ax, color='red')

enter image description here

I would like to generate the Voronoi tasselation of the points extended to the entire geometry. This is what I am doing:

from shapely.geometry import mapping
g = [i for i in centers.geometry]
coords = []
for i in range(0, len(g)):
    coords.append(mapping(g[i])["coordinates"]) # for first feature/row

from libpysal.cg.voronoi  import voronoi, voronoi_frames

regions, vertices = voronoi(coords)
region_df, point_df = voronoi_frames(coords)


fig, ax = plt.subplots()
region_df.plot(ax=ax, color='white',edgecolor='black', lw=3)
dfMd.plot(ax=ax, column='volume',alpha=0.1)
point_df.plot(ax=ax, color='red')

fig, ax = plt.subplots()
region_df.plot(ax=ax, color='white',edgecolor='black', lw=3)
dfMd.plot(ax=ax, column='volume',alpha=0.1)
point_df.plot(ax=ax, color='red')

enter image description here

How can I extend the Voronoi region to the external boundary of my dfMd?


Solution

  • You need an option clip=box() within voronoi_frames(). Relevant code follows.

    from shapely.geometry import box
    
    region_df, point_df = voronoi_frames(coords, clip=box(-4.2, 40.15, -3.0, 40.85))
    

    voronoi