Search code examples
pythonmatplotlibcolorbar

Same colormap and range for two different pcolormesh plots


I have a pcolormesh plot (plot 1) and a corresponding colorbar showing the data range (0 to 100). Now for illustration of my problem I divide the data by 2 and show for them a second pcolormesh plot (plot 2) with data between 0 to 50.

What I want:

plot 2 should use the same colorbar and range as plot 1. It should not scale the full colorbar values between 0 and 50, but should use the colors acoording the data of the first plot (50 should be at the half of the colorbar in plot 2). So all the colors in plot 2 should be between black and green!

Here is my code:

import numpy as np
import matplotlib.pyplot as plt

nx, ny = 10, 20
nz = nx*ny

minx, maxx = -5, 5
miny, maxy = -10, 10
minz, maxz = 0, 100

np.random.seed(1)

x = np.linspace(minx, maxx, nx)
y = np.linspace(miny, maxy, ny)
z1 = np.linspace(minz, maxz, nz)

np.random.shuffle(z1)
z2 = z1/2

z1=z1.reshape(ny,nx)
z2=z2.reshape(ny,nx)
PLOT 1
fig1, ax1 = plt.subplots(1,figsize=(5,5))

plot1=ax1.pcolormesh(x,y,z1,cmap='nipy_spectral',shading='auto')

ax1.set_xlabel('x')
ax1.set_ylabel('y')

cb1=fig1.colorbar(plot1,ax=ax1)

enter image description here

PLOT 2 (colorbar should go from 0 to 100, the maximum should be green)
fig2, ax2 = plt.subplots(1,figsize=(5,5))

plot2=ax2.pcolormesh(x,y,z2,cmap='nipy_spectral',shading='auto')

ax2.set_xlabel('x')
ax2.set_ylabel('y')

cb2=fig2.colorbar(plot2,ax=ax2)

enter image description here


Solution

  • You can change the colorbar limits to those from the first colorbar.

    cb2.mappable.set_clim(*cb1.mappable.get_clim())
    

    enter image description here