I'm trying to extract all the vertices of hexagons that are returned from plt.hexbin. I then want to eventually convert them to shapely polygons, so I can use them with geopandas. At the moment I can only seem to extract one polygon from the PolyCollection returned by plt.hexbin

Does anybody have any advice as to how to return the full grid of hexbins?

This example will reproduce my problem,

import numpy as np
import geopandas as gpd
import matplotlib.pyplot as plt
from shapely.geometry import Point, Polygon
from matplotlib.patches import RegularPolygon

geoms = [Point(919.000, 533.500), Point(940.500, 528.500), 
 Point(937.000, 555.000), Point(889.000, 526.500), Point(898.000, 520.500)]

l = gpd.GeoDataFrame({'geometry':geoms})

y= np.array([ 533.500,  528.500,  555.000,  526.500,  520.500])
x= np.array([ 919.000,  940.500,  937.000,  889.000,  898.000])

im =ax.hexbin(x,y, gridsize=(3,3), edgecolor='black')
l.plot(ax=ax, color='black', markersize=55)

Which produces this...

enter image description here

But when trying to extract the hexagons it produces a hexagon with the same position..

for x,y in im.get_offsets():
    hexes = RegularPolygon((x, y), numVertices=6, radius= 5 )
    verts = hexes.get_path().vertices
    trans = im.get_transform()
    points = trans.transform(verts)


enter image description here


Incase anyone faces a similar issue, the resolution is:

collection = plt.hexbin(x,y, gridsize=(5,5)
hex_polys = collection.get_paths()[0].vertices
hex_array = []
for xs,ys in collection.get_offsets():
    hex_x = np.add(hex_polys[:,0],  xs)
    hex_y = np.add(hex_polys[:,1],  ys)
    hex_array.append(Polygon(np.vstack([hex_x, hex_y]).T))

hex_grid = gpd.GeoDataFrame({'geometry':hex_array})
  • Thanks, this was very helpful! – Calvin Brown Feb 18 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.