I want to produce an hexagonal grid inside a polygon (representing a geographical aera) where I get to chose the color of each hexagon.
What I did:
- draw the polygon in Qgis over a map
- create a point grid inside the polygon
- add points where I want a higher density
- upload all those points in a geopandas dataframe
- plot a hexbin of those points
This is the grid I want !
Now I have to export it as a shapefile, but I can't find a way to get a shapefile from a plot?
The python code:
df = gpd.read_file("points.geojson")[['geometry']].to_crs(epsg=3857)
def get_coords(geom, i):
if type(geom) == MultiPoint:
geom = Point(geom[0])
coords = geom.x, geom.y
return coords[i]
df['X'] = df.apply((lambda x: get_coords(x.geometry, 0)), axis=1)
df['Y'] = df.apply((lambda x: get_coords(x.geometry, 1)), axis=1)
def add_basemap(ax, zoom, url='http://tile.stamen.com/terrain/tileZ/tileX/tileY.png'):
xmin, xmax, ymin, ymax = ax.axis()
basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax, zoom=zoom, url=url)
ax.imshow(basemap, extent=extent, interpolation='bilinear')
# restore original x/y limits
ax.axis((xmin, xmax, ymin, ymax))
f, ax = plt.subplots(1, figsize=(15, 15))
hexbin = ax.hexbin(df.X, df.Y, gridsize=30, alpha=0.5, cmap='RdYlGn', mincnt=1)
add_basemap(ax, zoom=15)
plt.colorbar(hexbin)
plt.axis('off')
plt.show()
And the resulting map:
Alternatively, if you have a better way to draw this kind of map without having to create a bunch of points, that would be great too.