matplotlib 如何使用iris快速绘图扩展colorbar

pw136qt2  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(86)

下面是我正在使用的代码块。我想扩展颜色条的两端。使用

extend='both'.

我找不到一个理想的地点。

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()

我尝试将其添加到情节线。如下面的代码所示:

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

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

t2a7ltrp1#

BoundaryNorm使用 extend 关键字,但from_labels_and_colors提供了一些便利:

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()

相关问题