Search code examples
matplotlibcolorbarcolormap

Making sure 0 gets white in a RdBu colorbar


I create a heatmap with the following snippet:

import numpy as np
import matplotlib.pyplot as plt
d = np.random.normal(.4,2,(10,10))
plt.imshow(d,cmap=plt.cm.RdBu)
plt.colorbar()
plt.show()

The result is plot below: enter image description here

Now, since the middle point of the data is not 0, the cells in which the colormap has value 0 are not white, but rather a little reddish.

How do I force the colormap so that max=blue, min=red and 0=white?


Solution

  • Use a TwoSlopeNorm.

    Note: Prior to matplotlib 3.2, TwoSlopeNorm was known as DivergingNorm.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    
    d = np.random.normal(.4,2,(10,10))
    
    norm = mcolors.TwoSlopeNorm(vmin=d.min(), vcenter=0, vmax = d.max())
    plt.imshow(d, cmap=plt.cm.RdBu, norm=norm)
    
    plt.colorbar()
    plt.show()
    

    enter image description here