# How to set 0 as the middle point in a matplotlib diverging colormap ?

Published: February 18, 2023

Updated: February 18, 2023

Diverging colormaps are often used to visualize data that has a natural midpoint, such as temperature or depth. If the data does not have a natural midpoint, it is possible to use a diverging colormap by setting 0 as the middle point.

## Diverging colormap

Let's construct a straightforward example using matplotlib with a diverging colormap:

````    from pylab import figure, cm`

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

`    x1_min = -10.0`
`    x1_max = 5.0`
`    x2_min = -2.0`
`    x2_max = 2.0`

`    x1, x2 = np.meshgrid(np.arange(x1_min,x1_max, 0.1), np.arange(x2_min,x2_max, 0.1))`

`    plt.imshow(x1, origin='lower', cmap='seismic',extent=[x1_min,x1_max,x1_min,x1_max])`

`    plt.title("How to set 0 as the middle point \n in a matplotlib diverging colormap ?" , fontsize=12)`

`    plt.colorbar()`

`    plt.savefig("matplotlib_set_0_middle_point_matpotlib_diverging_colormap_01.png", bbox_inches='tight',dpi=200, facecolor='white')`

`    plt.show()`

`    plt.close()`
```

Evidently, zero is not the middle point of the colormap.

## Set 0 as the middle point

To set 0 as the middle point, a solution is to define a new norm:

````custom_norm=colors.TwoSlopeNorm(vmin=x1_min, vcenter=0., vmax=x1_max)`
```

Example:

````    from pylab import figure, cm`

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

`    from matplotlib import colors`
`    x1_min = -10.0`
`    x1_max = 5.0`
`    x2_min = -2.0`
`    x2_max = 2.0`

`    x1, x2 = np.meshgrid(np.arange(x1_min,x1_max, 0.1), np.arange(x2_min,x2_max, 0.1))`

`    custom_norm=colors.TwoSlopeNorm(vmin=x1_min, vcenter=0., vmax=x1_max)`

`    plt.imshow(x1, origin='lower', cmap='seismic',extent=[x1_min,x1_max,x1_min,x1_max], norm=custom_norm)`

`    plt.title("How to set 0 as the middle point \n in a matplotlib diverging colormap ?" , fontsize=12)`

`    plt.colorbar()`

`    plt.savefig("matplotlib_set_0_middle_point_matpotlib_diverging_colormap_02.png", bbox_inches='tight',dpi=200, facecolor='white')`

`    plt.show()`

`    plt.close()`
```