I have an image that I\'m showing with matplotlib.
The image is gener
There's more than one way to do this. In your case, it's easiest to use LinearSegmentedColormap.from_list and specify relative positions of colors as well as the colornames. (If you had evenly-spaced changes, you could skip the tuples and just do from_list('my cmap', ['blue', 'white', 'red']).) You'll then need to specify a manual min and max to the data (the vmin and vmax kwargs to imshow/pcolor/etc).
As an example:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
data = np.array(
[[ 0.000, 0.120, 0.043, 0.094, 0.037, 0.045],
[ 0.120, 0.000, 0.108, 0.107, 0.105, 0.108],
[ 0.043, 0.108, 0.000, 0.083, 0.043, 0.042],
[ 0.094, 0.107, 0.083, 0.000, 0.083, 0.089],
[ 0.037, 0.105, 0.043, 0.083, 0.000, 2.440],
[ 0.045, 0.108, 0.042, 0.089, 2.440, 0.000]])
mask = np.tri(data.shape[0], k=-1)
data = np.ma.masked_where(mask, data)
vmax = 3.0
cmap = LinearSegmentedColormap.from_list('mycmap', [(0 / vmax, 'blue'),
(1 / vmax, 'white'),
(3 / vmax, 'red')]
)
fig, ax = plt.subplots()
im = ax.pcolor(data, cmap=cmap, vmin=0, vmax=vmax, edgecolors='black')
cbar = fig.colorbar(im)
cbar.set_ticks(range(4)) # Integer colorbar tick locations
ax.set(frame_on=False, aspect=1, xticks=[], yticks=[])
ax.invert_yaxis()
plt.show()
