How to modify the facecolors of hexbin plots?

Question:

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?

Asked By: Arnaud Antkowiak

||

Answers:

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

Answered By: JohanC
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.