Geographic Information Systems Asked by Sam Comber on August 10, 2021
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])
f,ax=plt.subplots(1)
im =ax.hexbin(x,y, gridsize=(3,3), edgecolor='black')
l.plot(ax=ax, color='black', markersize=55)
Which produces this…
But when trying to extract the hexagons it produces a hexagon with the same position..
array_of_hexes=[]
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)
array_of_hexes.append(Polygon(points))
gpd.GeoDataFrame({'geometry':array_of_hexes}).plot(edgecolor='black')
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})
Answered by Sam Comber on August 10, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP