pythonmatplotlibcolormap

Defining the midpoint of a colormap in matplotlib


I want to set the middle point of a colormap, i.e., my data goes from -5 to 10 and I want zero to be the middle point. I think the way to do it is by subclassing normalize and using the norm, but I didn't find any example and it is not clear to me, what exactly have I to implement?


Solution

  • With matplotlib version 3.4 or later, the perhaps simplest solution is to use the new CenteredNorm.

    Example using CenteredNorm and one of the diverging colormaps:

    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    plt.pcolormesh(data_to_plot, norm=mpl.colors.CenteredNorm(), cmap='coolwarm')
    

    Being simple, CenteredNorm is symmetrical, so that if the data goes from -5 to 10, the colormap will be stretched from -10 to 10. If you want a different mapping on either side of the center, so that the colormap ranges from -5 to 10, use the TwoSlopeNorm as described in @macKaiver's answer.