thanks for @ali_m 's idea, a few days later I think I get an idea of defining a custom Normalization
subclass with any normalisation function y=func(x)
. basically replace the private member self._normed
with the normalised values given by any func(self._levels)
. and when initialising the subclass, one must give the function hook to the normalisation function func
. But be sure the func
must be a truly normalisation.
the code below is inspired by @ali_m 's answer:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
class CustomNorm(Normalize):
def __init__(self, levels, func, clip=None):
# input levels
self._levels = np.linspace(min(levels), max(levels), 10)
# corresponding normalized values between 0 and 1
self._normed = func(self._levels)
Normalize.__init__(self, None, None, clip)
def __call__(self, value, clip=None):
# linearly interpolate to get the normalized value
return np.ma.masked_array(np.interp(value, self._levels, self._normed))
def inverse(self, value):
return 1.0 - self.__call__(value)
def func(x):
# whatever function, just normalise x into a sub-field of [0,1],
# it can be even [0,0.5]
return x/50.0/2.0
y, x = np.mgrid[0.0:3.0:100j, 0.0:5.0:100j]
H = 50.0 * np.exp( -(x**2 + y**2) / 4.0 )
levels = [0, 1, 2, 3, 6, 9, 20, 50]
# levels = [0, 50]
# H1 = -50.0 * np.exp( -(x**2 + y**2) / 4.0 )
# levels1 = [-50, -20, -9, -6, -3, -2, -1, 0]
# levels1 = [-50, 0]
fig, ax = plt.subplots(2, 2, gridspec_kw={'width_ratios':(20, 1), 'wspace':0.05})
im0 = ax[0, 0].contourf(x, y, H, cmap='jet', norm=CustomNorm(levels, func))
cb0 = fig.colorbar(im0, cax=ax[0, 1])
# im1 = ax[1, 0].contourf(x, y, H1, levels1, cmap='jet', norm=CustomNorm(levels1, func))
# cb1 = fig.colorbar(im1, cax=ax[1, 1])
plt.show()