Home > Blockchain >  Shading specific "pixels" a different color in matplotlib's pcolormesh
Shading specific "pixels" a different color in matplotlib's pcolormesh

Time:09-30

I have a heatmap that I plot with pcolormesh:

import numpy as np
import matplotlib.pyplot as plt

# generate random array
array = np.random.rand(10,10)
x = np.arange(0,10)
y = np.arange(0,10)

fig, ax = plt.subplots(nrows=1,ncols=1)
colormesh = ax.pcolormesh(x,y,array)
ax.set_xticks(x)
ax.set_yticks(y)
cb_ax = fig.add_axes([0.93, 0.1, 0.02, 0.8])
cbar = fig.colorbar(colormesh,cax=cb_ax)
colormesh.set_clim(0,1)
plt.show()

I want to select a few pixels and shade them another color that is different from those in the colorbar. Say I set the values of these pixels to -1:

# chose the pixels to shade
array[5,5] = -1
array[0,7] = -1

I don't want to set the colorbar limits from -1 to 1, as there is no value in the range (-1,0) and this only compresses the range of colors available for the range [0,1].

With this setup, is there a way for me to selectively color those pixels, say, red?

Notes:

  • I'm using pcolormesh and not imshow because in the original data x and y are not equally spaced.
  • I don't want to add a dot on top of the said pixels like coloring a few pixels in plt.colormesh()

  • Related