I'm trying to create a numpy meshgrid and convert it to Shapely polygons. I can likely solve this with a very brute force method but it feels like there has to be a good trick to accomplish this but I haven't come up with it, yet.
This gets me the grid of points (assumed running in Jupyter) -
import numpy as np
from matplotlib import pyplot
fig = pyplot.figure(figsize=(10, 10))
ax = fig.add_subplot(111, aspect='equal')
x,y = np.mgrid[-5:-1:8j, 1:5:8j]
ax.plot(x,y, 'o', color='#000000')
pyplot.show()
Now the need is to connect all of these points horizontally and vertically to form Shapely polygons. My first attempt at this was to generate a Shapely MultiLineString to draw vertical and horizontal lines and then perform a polygonize operation on it. This resulted in only the main outer polygon being created - this is due to the MultiLineString only containing vertices on the outer polygon.
I know this might be more reasonable using rasters and GDAL but my circumstances require the end result to be Shapely polygons.
Any help tracking down a solution is appreciated!
You basically have to define every line before you construct the MultiLineString.
import numpy as np
from shapely.geometry import MultiLineString
from shapely.ops import polygonize
x = np.linspace(-5, -1, 8)
y = np.linspace(1, 5, 8)
hlines = [((x1, yi), (x2, yi)) for x1, x2 in zip(x[:-1], x[1:]) for yi in y]
vlines = [((xi, y1), (xi, y2)) for y1, y2 in zip(y[:-1], y[1:]) for xi in x]
grids = list(polygonize(MultiLineString(hlines + vlines)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With