How to extend colorbar using iris quick plot

88 views Asked by At

Below is the code block I'm using. I'd like to extend the ends of the color bar. With

extend='both'.

I can't find an ideal location that works.

import matplotlib.colors as mcolors
import iris.plot as iplt

def bnorm(min, max, nlevels):
    '''
    small function to set the boundary norm and colormap using 
    a min, max and number of colors
    '''
    # set up even bounds 
    bounds = np.linspace(min, max, nlevels)
    # get one more color than bounds from colormap
    colors = plt.get_cmap('BrBG')(np.linspace(0,1,len(bounds)-1))
    cmap = mcolors.ListedColormap(colors)
    # create norm from bounds
    norm = mcolors.BoundaryNorm(boundaries=bounds, ncolors=len(bounds)-1)

    return norm, cmap

plotno=0
plt.figure(figsize=(14, 12))
    
for row, models in enumerate(['GERICS', 'CLMcom']):
    for col, drivers in enumerate(['Nor','MPI','MOHC']):
        chan = os.path.join(CLIMDIR, 'pr_'+drivers+'_change_'+models+'_avg_max_day.nc')
        change = iris.load_cube(chan)
        
        plotno+=1

        # Future Change
        norm, cmap = bnorm(-80, 80, 9)
        
        plt.subplot(2, 3, plotno)
        qplt.pcolormesh(change, norm=norm, cmap=cmap)
        plt.title('Daily Precipitation(mm/day)\n2071-2100 - Relative to 1981-2010')
        ax = plt.gca()
        ax.coastlines()
        ax.add_feature(cf.BORDERS)  

plt.show()

I tried to add it to the plot line. As shown in the code below:

qplt.pcolormesh(change, norm=norm, cmap=cmap, extend='both')


AttributeError: 'QuadMesh' object has no property 'extend'
1

There are 1 answers

0
RuthC On BEST ANSWER

BoundaryNorm takes the extend keyword, but from_labels_and_colors provides some convenience:

import iris
import iris.quickplot as qplt
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np

fname = iris.sample_data_path("air_temp.pp")
cube = iris.load_cube(fname)

levels = np.linspace(250, 300, 11)
colors = plt.get_cmap("RdBu_r")(np.linspace(0,1,len(levels)+1))
cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend="both")

qplt.pcolormesh(cube, cmap=cmap, norm=norm)
plt.gca().coastlines()
plt.show()

enter image description here