3

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:

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.

Borbag
  • 597
  • 4
  • 21
  • 2
    May I offer alternative workflow? You can create hexagonal grid in QGIS, (Vector/Research Tools/Create Grid), keep only those cells within your polygon, make your points and do spatial join between points and grid. You don't even need to leave QGIS to do that and it is much easier than trying to convert Matplotlib patches into shapefile. – martinfleis Apr 27 '19 at 09:57
  • I actually did almost the same thing. I used ArcGis (21 trial days). Draw the polygon of the zone and used hexagonal tesselation. Then I switched to geojson.io to draw subpolygons with the desired property (numerical value) because I didn't know how to do it in ArcGis, it wouln't let me attribute a property. I then imported thos polygons in arcgis, did a spatial join and colored the hexagons according to the property of the intersecting polygons. I would have done it in Qgis if I knew it was possible. – Borbag Apr 27 '19 at 15:31
  • 1
    are you asking how to create a shapefile or how to extract the coordinates from the hexbins? – Paul H Apr 28 '19 at 14:19
  • How to create a shapefile – Borbag Apr 29 '19 at 14:18

0 Answers0