Skip to content Skip to sidebar Skip to footer

How To Obtain Transparency For Masked Values In Customised Colormap (matplotlib/python)

I have come across this useful class MidpointNormalize that allows you to choose a data value to correspond to the midpoint colour of your colour-scale. Effectively this means you

Solution 1:

The MidpointNormalize originates from this answer in which there is an explicit comment "I'm ignoring masked values and all kinds of edge cases to make a simple example".

In this case, you do not want to ignore masked values. Hence you need to propagate the mask through to the output of the __call__.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors

classMidpointNormalize(colors.Normalize):
    def__init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        colors.Normalize.__init__(self, vmin, vmax, clip)

    def__call__(self, value, clip=None):
        # Note that I'm ignoring clipping and other edge cases here.
        result, is_scalar = self.process_value(value)
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.array(np.interp(value, x, y), mask=result.mask, copy=False)

N = 100
non_masked_data = np.sort(np.random.rand(N,N)*4.0-2.0)
data = np.ma.masked_where(non_masked_data < -1.0, non_masked_data)

fig, ax = plt.subplots()
ax.set_facecolor('black')

norm_me = MidpointNormalize(midpoint=1.,vmin=data.min(),vmax=data.max())
plot = plt.imshow(data, origin='lower', interpolation='none', cmap="RdBu_r", norm=norm_me)
cb   = fig.colorbar(plot)
plt.show()

I added another note in the class, to warn that I'm ignoring clipping and other edge cases here. ;-)

The result is the following where masked values are transparent (hence the black background is shown).

enter image description here

Post a Comment for "How To Obtain Transparency For Masked Values In Customised Colormap (matplotlib/python)"