Suppose that I have a dataset with distinct positive and negative values (like a Digital Terrain Map containing topography above sea level and bathymetry below sea level). The positive values far exceed the negative values. If I want to plot the data with e.g. matplotlib.pcolormesh
, I can specify the range with vmin
and vmax
. In order to have the colourbar correctly centred at zero, I'd need to set vmin = -vmax
. However, this leaves a large part of the colourbar unused. See for instance the minimal example below:
import matplotlib.pyplot as plt
import numpy as np
# Independent variables
x = 2 * np.pi * np.linspace(0, 1, 1000)
y = x
X, Y = np.meshgrid(x, x)
# Dependent variable
Z = np.sin(X) + 0.25 * Y
# Draw canvas
fig, axes = plt.subplots(ncols=2, figsize=(9, 4), constrained_layout=True)
ax = axes[0]
ax.set_title("vmin at Z.min()")
CS = ax.pcolormesh(x, y, Z, cmap="RdBu_r", shading="auto", vmin=Z.min(), vmax=Z.max())
fig.colorbar(CS, ax=ax)
ax = axes[1]
ax.set_title("Correct colourbar midpoint")
CS = ax.pcolormesh(x, y, Z, cmap="RdBu_r", shading="auto", vmin=-Z.max(), vmax=Z.max())
fig.colorbar(CS, ax=ax)
plt.show()
As you can see in the right panel, when I fix the midpoint of the colourbar at zero the colourbar range from -1 to -2.5 is not used, and I'd like to discard this. How can I "clip" the colourbar between -1 and 2.5 such that it is correctly centred at zero?