Search code examples
pythonmatplotlibmatplotlib-basemapcolorbar

matplotlib colorbar boundaries do not implemented


I am trying to create several plots all with the same colorbar limits in a loop.

I set the limits of the contour plot with map.contourf(x, y, U_10m, vmin=0, vmax=25) and this seems to give consistent colour scales for each plot. However, when I use cbar = plt.colorbar(boundaries=np.linspace(0,1,25), ticks=[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]) # sets all cbar to same limits each plot does not have the same colorbar limits (examples of two plots with different colorbars and code below).

fig1 fig2

 from netCDF4 import Dataset as NetCDFFile
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

def wrf_tseries_contour_plotter (
ncfile, time_ind, lowerllat, upperrlat, lowerllon, upperrlon, output_dir):
    '''
    EDITED FROM http://www.atmos.washington.edu/~ovens/wrfwinds.html 
    '''

    print 'timestep:', + time_ind 
    #which figure is being generated 0 = 00:00, 144 = 23:50
    nc     = NetCDFFile(ncfile, 'r')
    #
# get the actual longitudes, latitudes, and corners
lons = nc.variables['XLONG'][time_ind]
lats = nc.variables['XLAT'][time_ind]

#get the u10 to plot as a contour instead of t2m
U10_raw = nc.variables['U10'][time_ind] #61 is the index for 10:00am 
V10_raw = nc.variables['V10'][time_ind]

#bodge to calculate U from U and V (u10 = sqrt(u^2+v^2))
v2 = np.square(V10_raw)
u2 = np.square(U10_raw)
U_10m = np.sqrt(u2 + v2)

# Make map
map = Basemap(projection='cyl',llcrnrlat=lowerllat,urcrnrlat=upperrlat,
            llcrnrlon=lowerllon,urcrnrlon=upperrlon,
                resolution='h')
# lllat, urlat,lllon, urlon set outside of f(x) lower left and 
# upper right lat/lon for basemap axis limits

x, y = map(lons[:,:], lats[:,:])
    map.contourf(x, y, U_10m, vmin=0, vmax=25) 
    map.drawcoastlines(linewidth = 0.5, color = '0.15') 
    #thinner lines for larger scale map

    #plt.clim(0, 25) #added
    cbar = plt.colorbar(boundaries=np.linspace(0,1,25), ticks=[0, 2, 4, 6,
    8, 10, 12, 14, 16, 18, 20, 22, 24]) # sets all cbar to same limits
    cbar.set_label('10m U (m/s)', size=12)
    cbar.ax.set_yticklabels([0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24])
    #cbar.set_clim(0, 25)

    time_str = str(time_ind)
    plt.title('gust 20070724' + '_' + time_str)
    fig_name = '\gust20070724_'+  time_str + '.png'      
    plt.savefig(output_dir + fig_name)
    plt.close()
#set inputs for  wrf_tseries_contour_plotter(ncfile, time_ind, lllat, urlat,
                                             lllon, urlon, output_dir)

ncfile = 'E:\WRFout_UK2Fino\wrfout_d03_2007-07-24_00%3A00%3A00'
tlist = np.arange(0,145) 

#set the lower left/upper right lat/lon for axis limits on the maps
lowerllat=48
upperrlat=63
lowerllon=-10
upperrlon=25

#set output directory for figures 
output_dir = '''C:\cbar_test'''

for time_ind in tlist:
    wrf_tseries_contour_plotter(ncfile, time_ind, lowerllat, upperrlat, 
                                lowerllon, upperrlon, output_dir)

Solution

  • You have to use vmin and vmax values to set boundaries of a colorbar like in this example:

    import numpy as np
    import matplotlib.cm as cm
    import matplotlib.mlab as mlab
    import matplotlib.pyplot as plt
    
    # test data
    x = np.linspace(0,15,100)
    X,Y = np.meshgrid(x,x)
    SPD1 = np.sqrt(X*X + Y*Y)
    SPD2 = SPD1 * 1.3
    
    fig = plt.figure()  
    
    # implement boundaries of colorbar and it ticks
    vmin, vmax = 0, 26
    levels = np.linspace(vmin,vmax,14)
    
    # 1st subplot
    ax1 = fig.add_subplot(221)
    # Set contour levels and limits
    CF1 = ax1.contourf(X, Y, SPD1, levels=levels, vmax=vmax, vmin=vmin) 
    cbar = plt.colorbar(CF1)
    cbar.set_label('10m U (m/s)', size=12)
    
    #2nd subplot
    ax1 = fig.add_subplot(222)
    CF1 = ax1.contourf(X, Y, SPD2, levels=levels, vmax=vmax, vmin=vmin) 
    cbar = plt.colorbar(CF1)
    cbar.set_label('10m U (m/s)', size=12)
    
    plt.tight_layout()
    plt.show()
    

    enter image description here

    However you have to select vmin, vmax correctly because of if your values are outside boundaries of colorbar they will not shown (right upper corner of 2nd subplot).