Python 在自带colorbar的基础上自定义颜色

Python 在自带colorbar的基础上自定义颜色

python 拥有众多的色彩设置,但有时候并不能满足作者的需要,因此本文介绍了一种在原有的colorbar的基础上,设定自己颜色的方法。

主要代码

下面是一个具体的例子

# -*- coding: utf-8 -*-
import os
import gzip
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib import cm
from matplotlib.colors import LinearSegmentedColormap

#在自带的colorabar "jet" 的基础上修改,得到自己想要的颜色
def get_spectral():

    colormap_float = np.zeros( (256, 3), np.float ) #新建一个数组用于存储颜色的数值
 
    for i in range(0, 256, 1):
       colormap_float[i, 0] = cm.jet(i)[0] * 255.0
       colormap_float[i, 1] = cm.jet(i)[1] * 255.0
       colormap_float[i, 2] = cm.jet(i)[2] * 255.0 #将原有的 "jet"颜色赋值到colormap_float中
       colormap_float[255, :] = [130, 130, 130]    #自定义了一些颜色的数值,作者可以根据需要自己设置
       colormap_float[254, :] = [0, 0, 0]
       colormap_float[253, :] = [182, 251, 255]
       colormap_float[252, :] = [255, 255, 255]
       colormap_float[251, :] = [255, 84, 156]
    # np.savetxt("jet_float.txt", colormap_float, fmt = "%f", delimiter = ' ', newline = '\n')
    # np.savetxt("jet_int.txt", colormap_int, fmt = "%d", delimiter = ' ', newline = '\n')

    return( colormap_float )
############################################################################
def read_gz_file(path):
    contents = []
    if os.path.exists(path):
        with gzip.open(path, 'rb') as fp:
            contents = fp.read()
    else:
        print('File not exist! continue') 
    return contents
#############################################################################
def draw_sst(data, name_string, scale, offset, lon, lat, colormap_float):
    temp = data[0, :, :]
    index_valid = np.where(temp <= 250)
    # temp[index_valid] = temp[index_valid] * scale[0] + offset[0]
    min_value = np.round( np.min( temp[index_valid] ) * 
                         scale[0] + offset[0] )
    max_value = np.round( np.max( temp[index_valid] ) * 
                         scale[0] + offset[0] )
    
    rgb_table = LinearSegmentedColormap.from_list('sst cmap', colormap_float / 255.0) #这段是比较关键的代码,将获取的rgb数值转换成哈希表的格式,我将其命名为'sst cmap'
    fig = plt.figure( "数据显示" )
    # ax = fig.add_subplot()
    ax = plt.axes()
    # ax.foo = 'bar'
    m = Basemap(projection = 'cyl', llcrnrlon = 0,
                    llcrnrlat = -90, urcrnrlon = 360, urcrnrlat = 90,
                    lon_0 = 180., lat_0 = 0., resolution = 'l')
    X,Y = m(lon, lat)
    c = m.pcolor(X, Y, temp, cmap = rgb_table)
    ax.set(title = "GMI v8.2 Sea Surface Temperature 2019/08 "
          "- monthly average - Global")
    # ax.axhline(y=75, color='g', linestyle='--')
    # ax.axhline(y=90, color='r', linestyle='--')
    # rect = plt.Rectangle((10,10),10,10,linewidth=3,edgecolor='r',facecolor='red', alpha=1)
    # ax.add_patch(rect)
    m.drawmapboundary(fill_color = 'aqua')
    m.shadedrelief()
    # m.fillcontinents(color = 'grey', lake_color = 'w')
    m.drawlsmask(land_color='grey')
    m.drawcoastlines()
    parallels = np.arange(-90.,91.,30.)
    m.drawparallels(parallels,labels=[True,False,False,False])
    meridians = np.arange(-180.,181.,60.)
    m.drawmeridians(meridians,labels=[False,False,False,True])
    m.colorbar(c)



if __name__ == "__main__":
    Dir = r"H:\LNHCourse\6"
    file_path = Dir + r'\f35_201908v8.2.gz'
    row = int( 360/0.25) ; line = int( 180/0.25 )
    data = read_gz_file(file_path)
    data = np.array(bytearray(data)).reshape(6, line, row)

    scale = np.array( [0.15, 0.2, 0.2, 0.3, 0.01, 0.1] )
    offset = np.array( [-3, 0, 0, 0, -0.05, 0] )
    name_string = np.array( ['SST','wspd_lf','wspd_mf','vapor',
                               'cloud','rain'] )
    lon = (  np.linspace(1, 1, 720).reshape( (720, 1) ) @ 
       np.linspace(0., 360., 1440).reshape( (1, 1440) )  )
    lat = (  np.linspace(-90., 90., 720).reshape( (720, 1) ) @ 
       np.linspace(1, 1, 1440).reshape( (1, 1440) )  )

    colormap_float = get_spectral() #调用自定义的获取颜色大的函数,colormap_float是我们想要的数组
    sst = draw_sst(data, name_string, scale, offset, lon, lat, 
                   colormap_float)           

结果如图所示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值