Search code examples
pythonmatplotlibplotdata-visualizationcolorbar

matplotlib colorbar limits for contourf


How do you set hard limits on colorbar used with contourf? The code below works as expected with colorbar limits set to [-3, 3] when using plot_surface, but with contourf the limits are not at the tips of the colorbar. I need this to create a gif from multiple images with a constant colorbar.

import matplotlib.pyplot as plt 
import numpy as np

fig = plt.figure()

ax = fig.gca(projection='3d')
CHI = np.linspace(-45, 45, 35);
M = np.linspace(0, 1, 35) 
CHI, M = np.meshgrid(CHI, M)
R = 10*2*M*np.sin(  2 * np.deg2rad(CHI) )

cont = ax.contourf(CHI, M, R)
#cont = ax.plot_surface(CHI, M, R)
cont.set_clim(vmin=-3, vmax=3)

ax.set_xlim(-45,45)
cbar = plt.colorbar(cont, ticks=[-3,-2,-1,0,1,2,3])
plt.show()

enter image description here enter image description here


Solution

  • You could pass levels parameter to matplotlib.pyplot.contourf in order to specify the number and positions of the contour regions. Then you can set extend = 'both' in order to draw the countour regions outside levels range you used:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    
    ax = fig.gca(projection='3d')
    CHI = np.linspace(-45, 45, 35);
    M = np.linspace(0, 1, 35)
    CHI, M = np.meshgrid(CHI, M)
    R = 10*2*M*np.sin(  2 * np.deg2rad(CHI) )
    
    levels = [-3, -2, -1, 0, 1, 2, 3]
    
    cont = ax.contourf(CHI, M, R, levels = levels, extend = 'both')
    
    ax.set_xlim(-45,45)
    cbar = plt.colorbar(cont)
    plt.show()
    

    enter image description here