Python Matplotlib 创建自定义色标

Python Matplotlib creating a custom colour scale

我根据 NetCDF 文件中的降水数据创建了一个区域的降水量地图。我想添加一个自定义比例,如果降水量小于 800 毫米,它将是一种颜色,800-1000 毫米是另一种颜色,等等。类似于此处找到的地图:http://www.metmalawi.com/climate/climate.php

目前我正在使用渐变比例,但它没有显示我需要的细节。这是目前绘图的代码(其中 'Average' 是我已经格式化的数据)。

    #load color palette
    colourA = mpl_cm.get_cmap('BuPu')
    
    #plot map with physical features 
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    ax.add_feature(cartopy.feature.COASTLINE)   
    ax.add_feature(cartopy.feature.BORDERS)
    ax.add_feature(cartopy.feature.LAKES, alpha=0.5)
    ax.add_feature(cartopy.feature.RIVERS)

    #set map boundary
    ax.set_extent([32.5, 36., -9, -17]) 
    
    #set axis tick marks
    ax.set_xticks([33, 34, 35]) 
    ax.set_yticks([-10, -12, -14, -16]) 
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    
    #plot data and set colour range
    plot = iplt.contourf(Average, cmap=colourA, levels=np.arange(0,15500,500), extend='both')

    #add colour bar index and a label
    plt.colorbar(plot, label='mm per year')

    #give map a title
    plt.title('Pr 1990-2008 - Average_ERAINT ', fontsize=10)

    #save the image of the graph and include full legend
    plt.savefig('ERAINT_Average_Pr_MAP_Annual', bbox_inches='tight')

    plt.show()

有人知道我该怎么做吗?

谢谢!

这是一个伪装成 Iris 问题的 matplotlib 问题,因为这个问题是通过 Iris 绘图例程出现的,但要回答这个问题,我们只需要几个 matplotlib 命令。因此,我的回答基于此 matplotlib gallery example。它们是 levels(包含每个轮廓上限的值)和 colors(指定颜色以遮蔽每个轮廓)。最好有相同数量的关卡和颜色。

为了证明这一点,我把下面的例子放在一起。鉴于没有提供示例数据,我制作了自己的三角数据。级别基于三角数据值,因此不反映问题中要求的级别,但可以更改为原始级别。使用的颜色是问题中 link 中图像指定级别的十六进制值。

代码:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-25, 25)
y = np.arange(-20, 20)
x2d, y2d = np.meshgrid(x, y)
vals = (3 * np.cos(x2d)) + (2 * np.sin(y2d))

colours = ['#bf8046', '#df9f24', '#e0de30', '#c1de2d', '#1ebf82',
           '#23de27', '#1dbe20', '#11807f', '#24607f', '#22427e']
levels = range(-5, 6)

plt.contourf(vals, levels=levels, colors=colours)
plt.colorbar()
plt.show()

生成的图像:

也可以从颜色图中选择颜色(显示了一种方法 in this Whosebug answer)。还有其他方法,包括上面的 matplotlib 画廊示例 linked。不过,考虑到问题中 linked 的样本地图具有特定颜色,我选择直接使用这些颜色。