2

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()

enter image description here

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?

MPA
  • 1,878
  • 2
  • 26
  • 51
  • TwoSlopeNorm with vcenter=0 – JohanC Mar 06 '21 at 19:43
  • @JohanC doesn't that distort one side of the colourmap (i.e. compress the blues)? – MPA Mar 06 '21 at 20:30
  • 2
    If I understand correctly, you want to hide the dark blue part of the colorbar (and leave the right image as is)? [Asymmetric Color Bar with Fair Diverging Color Map](https://stackoverflow.com/questions/55665167/asymmetric-color-bar-with-fair-diverging-color-map) seems to tackle this. And also [Set limits on a matplotlib colorbar without changing the actual plot](https://stackoverflow.com/questions/16695275/set-limits-on-a-matplotlib-colorbar-without-changing-the-actual-plot) – JohanC Mar 06 '21 at 20:56
  • @JohanC this indeed addresses my issue – MPA Mar 07 '21 at 08:46

0 Answers0