3

I'm looking for a way to fine tune the color of individual cells in a hexbin plot.

I have tried to use the method set_facecolors from PolyCollection to alter the color of an individual cell but this does not appear to work.

Example: this should result in a hexbin with a red cell in the center:

import numpy as np
import matplotlib.pyplot as plt

x = y = np.linspace(0.,1.,10)
pts=np.vstack(np.meshgrid(x,y,indexing='ij')).reshape(2,-1).T
z = np.zeros_like(pts[:,0])

fig, ax = plt.subplots(figsize=(3, 3))
hb = ax.hexbin(pts[:,0],pts[:,1], C=z, gridsize=(5,3), vmin=-1., edgecolors='white')
ax.set_xlim([0,1])
ax.set_ylim([0,1])

ax.figure.canvas.draw()
fcolors = hb.get_facecolors()
fcolors[31] = [1., 0., 0., 1.]
hb.set_facecolors(fcolors)

plt.show()

Hexbin plot should feature a red cell in its center

Any idea on how to set the facecolor of individual cells?

  • 1
    See also [Constructing a hexagonal heat-map with custom colors in each cell](https://stackoverflow.com/a/70443427/12046409) – JohanC Nov 11 '22 at 16:19

1 Answers1

1

Normally, the colors are set via a colormap (hence the C=z parameter in ax.hexbin()). To change individual colors, you need to disable that behavior. That can be achieved by setting the "array" of the PolyCollection to None (see also Joe Kington's answer here).

import matplotlib.pyplot as plt
import numpy as np;

x = y = np.linspace(0., 1., 10)
pts = np.vstack(np.meshgrid(x, y, indexing='ij')).reshape(2, -1).T
z = np.zeros_like(pts[:, 0])

fig, ax = plt.subplots(figsize=(3, 3))
hb = ax.hexbin(pts[:, 0], pts[:, 1], C=z, gridsize=(5, 3), vmin=-1., edgecolors='white')
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])

ax.figure.canvas.draw()

fcolors = hb.get_facecolors()
fcolors[31] = [1., 0., 0., 1.]
hb.set(array=None, facecolors=fcolors)

plt.show()

changing individual colors in a hexbin

JohanC
  • 71,591
  • 8
  • 33
  • 66