4
votes

Is there a way to increase the reltive sizes of hexagons in pyplot.hexbin based on their frequency? I can only see binsize for the keyword arguments, which affects the number of hexes, but not their size.

But in this article (around 2/3 in under the heading 'Multivariate Hexagonal Binning'), it discusses drawing hexagons with size proportional to count in order to more clearly observe trends (see following image taken from that article)

enter image description here

Have I missed a keyword argument that allows this?

Thanks!

1
No, you did not miss any keyword argument. Matplotlib hexbin plots use a constant bin size throughout the plot. For the plot shown I also do not quite understand how that plot is consitently produced, other than using a normal scatterplot. - ImportanceOfBeingErnest
Possibly you can look at the source for hexbin, figure out how it works and adapt it for your use. You would need to include the modified function in your project. - wwii

1 Answers

9
votes

For the plot in question there is no advantage of using hexagonal binning since the hexagons have different sizes and hence would not allow a consistent binning throughout the plot. You may however use a constant binning and just shrink the cells, which do not have the maximal value.

import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import numpy as np; np.random.seed(42)

a = np.random.rand(200,2)
b = np.random.rand(200)
c = np.concatenate((a,np.c_[b,b]), axis=0)

fig, ax = plt.subplots()

hexbin = ax.hexbin(c[:,0],c[:,1],gridsize=20, linewidth=0 )

def sized_hexbin(ax,hc):
    offsets = hc.get_offsets()
    orgpath = hc.get_paths()[0]
    verts = orgpath.vertices
    values = hc.get_array()
    ma = values.max()
    patches = []
    for offset,val in zip(offsets,values):
        v1 = verts*val/ma+offset
        path = Path(v1, orgpath.codes)
        patch = PathPatch(path)
        patches.append(patch)

    pc = PatchCollection(patches)
    pc.set_array(values)
    ax.add_collection(pc)
    hc.remove()

sized_hexbin(ax,hexbin)
plt.show()

enter image description here


import matplotlib.pyplot as plt
import numpy as np; np.random.seed(42)

a = np.random.rand(200,2)
b = np.random.rand(200)
c = np.concatenate((a,np.c_[b,b]), axis=0)

fig, ax = plt.subplots()

h, ex, ey = np.histogram2d(c[:,0],c[:,1], bins=np.linspace(0,1,20))

X,Y = np.meshgrid(ex[:-1]+np.diff(ex)/2.,ey[:-1]+np.diff(ey)/2.)

ax.scatter(X.flatten(),Y.flatten(), 
           c=h.T.flatten(), s=h.T.flatten()**2,
           marker="h")

plt.show()

enter image description here