Search code examples
pythonmatplotlibhexbin

how to get vertices of hexagons from the polycollection output of hexbin() matplotlib method?


I am trying to get the vertices of hexagons drawn from hexbin() method using matplotlib and python. Got the no. of points in each hexagon using .get_arrays() and tried getting vertices co-ordinates with get_paths() but it gives me just 1 path (i.e vertices of just 1 hexagon).

How can I retrieve vertices of all the hexagons? The tried code is written below with the output.

x, y = np.random.normal(size=(2, 10000))
fig, ax = plt.subplots()
im = ax.hexbin(x, y, gridsize=20)
paths=im.get_paths()
print(paths)
fig.colorbar(im, ax=ax)

enter image description here

[the output map that is being generated has more than 1 hexagon. I can't upload it here due to account restrictions since I am new to this.][2]

 [Path(array([[ 0.18489907, -0.1102285 ],
   [ 0.18489907,  0.1102285 ],
   [ 0.        ,  0.22045701],
   [-0.18489907,  0.1102285 ],
   [-0.18489907, -0.1102285 ],
   [ 0.        , -0.22045701],
   [ 0.18489907, -0.1102285 ]]), array([ 1,  2,  2,  2,  2,  2, 79], dtype=uint8))]

Solution

  • I am answering it myself the way I solved it and it worked.

    Step 1: Get the sample hexagon co-ordinates with im.get_paths() as done above in the question.

    Step 2: Get offsets of all the hexagons created by hexbin() method using im.get_offsets(). It gives x and y offsets for all the hexagons.

    Step 3: Just add the offsets to the sample 'path' co-ordinates obtained in step 1 and this will give the actual co-ordinates of the hexagon collection.