Skip to content

Instantly share code, notes, and snippets.

@ChocopieKewpie
Last active February 22, 2024 21:26
Show Gist options
  • Save ChocopieKewpie/fb08254ee82834fc36c90d0cef7f259b to your computer and use it in GitHub Desktop.
Save ChocopieKewpie/fb08254ee82834fc36c90d0cef7f259b to your computer and use it in GitHub Desktop.
Generating Voronoi in a Polygon
import geopandas as gpd
from shapely.ops import voronoi_diagram
from shapely.ops import unary_union
from shapely.geometry import shape
import random
def generate_voronoi_plot(df, n_points):
# Read GeoDataFrame from file
# Extract geometry for clipping
clip_df = df.loc[0, 'geometry']
# Sample points and create Voronoi diagram
points = df['geometry'].sample_points(n_points)
points = [shape(geometry) for geometry in points]
mp = unary_union(points)
vor = gpd.GeoDataFrame(gpd.GeoSeries(voronoi_diagram(mp, envelope=clip_df))).set_geometry(0).explode()
# Clip Voronoi diagram
vor = gpd.clip(vor, clip_df, keep_geom_type=True).set_crs(df.crs.to_epsg())
# Generate random values
def generate_random():
return random.randint(0, 1)
# Use the assign method to create a new column filled with random values
vor = vor.assign(val=[generate_random() for _ in range(len(vor))])
vor=vor.dissolve('val')
return vor
# Plot the Voronoi diagram
# Call the function with the file path
df=gpd.read_file('input.gpkg') #Only tested with a geopackage that contains only 1 polygon
n_points=75
shapes=generate_voronoi_plot(df, n_points)
shapes.to_file('output.gpkg')
@ChocopieKewpie
Copy link
Author

Probably pass a .dissolve() at the end to make it easier for benchmarking later

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment