Python pcolor and colorbar dont use the whole colormap

3.3k Views Asked by At

When I try to create a simple pcolor plot with values between -2 and 10 the default pcolor and colorbar use the colormap only from -2 to 2, thus showing wrong colors.

Here is a working example:

import numpy as np
from matplotlib import pyplot as plt

m = np.array([[ 0.9, 2., 2., 1.8],
              [ -0.8, 0.1, -0.6, -2],
              [ -0.1, -2, -2, -0.06],
              [ 3, 4, 7, 10]])

x = [0, 1, 2, 3]
y = [0, 1, 2, 3]
xv,yv = np.meshgrid(x,y)

fig = plt.figure()
ax = fig.add_subplot(111)
print m.min(),m.max()
cax = ax.pcolormesh(xv,yv,m, cmap='viridis')
cbar = fig.colorbar(cax)
plt.show()

I would include an image but dont have enough reputation on stackoverflow

2

There are 2 best solutions below

0
On BEST ANSWER

You need to add another value to your x and y, because it only plots values on the ranges in between your mesh values (plots image values from 0-1, 1-2, 2-3, 3-4), like so:

import numpy as np
from matplotlib import pyplot as plt

m = np.array([[ 0.9, 2., 2., 1.8],
              [ -0.8, 0.1, -0.6, -2],
              [ -0.1, -2, -2, -0.06],
              [ 3, 4, 7, 10]])

x = [0, 1, 2, 3, 4]  # added the 4
y = [0, 1, 2, 3, 4]  # added the 4
xv,yv = np.meshgrid(x,y)

fig = plt.figure()
ax = fig.add_subplot(111)
print m.min(),m.max()
cax = ax.pcolormesh(xv,yv,m, cmap='viridis')
cbar = fig.colorbar(cax)
plt.show()

Your example only uses the first 3 values of each dimension, so the full range is from -2 to 2. By adding one more value, you use the whole matrix.

0
On

Is this the outcome you were hoping for?

import numpy as np
from matplotlib import pyplot as plt

m = np.array([[ 0.9, 2., 2., 1.8],
              [ -0.8, 0.1, -0.6, -2],
              [ -0.1, -2, -2, -0.06],
              [ 3, 4, 7, 10]])

x = [0, 1, 2, 3]
y = [0, 1, 2, 3]
xv,yv = np.meshgrid(x,y)

fig = plt.figure()
ax = fig.add_subplot(111)
print m.min(),m.max()
cax = ax.pcolormesh(xv,yv,m, cmap='viridis', vmin=-2, vmax=10)
cbar = fig.colorbar(cax)
plt.show()