Reputation: 583
Is there an equivalent to the very good st_make_grid method of the sf package from r-spatial in python? The method create rectangular grid geometry over the bounding box of a polygon.
I would like to do exactly the same as the solution proposed in this question, e.g. divide a polygon into several squares of the same area that I choose. Thanks for your help.
Alternatively, I could use rpy2 to run a script in r that executes the st_make_grid
method which takes a shapely polygon as input and outputs the square polygons, to be read with shapely. Would this be effective on many polygons to process?
Upvotes: 3
Views: 2112
Reputation: 7814
Would this be effective on many polygons to process?
Certainly not. There's no built-in Python version but the function below does the trick. If you need performance, make sure that you have pygeos
installed in your environment.
def make_grid(polygon, edge_size):
"""
polygon : shapely.geometry
edge_size : length of the grid cell
"""
from itertools import product
import numpy as np
import geopandas as gpd
bounds = polygon.bounds
x_coords = np.arange(bounds[0] + edge_size/2, bounds[2], edge_size)
y_coords = np.arange(bounds[1] + edge_size/2, bounds[3], edge_size)
combinations = np.array(list(product(x_coords, y_coords)))
squares = gpd.points_from_xy(combinations[:, 0], combinations[:, 1]).buffer(edge_size / 2, cap_style=3)
return gpd.GeoSeries(squares[squares.intersects(polygon)])
Upvotes: 4