Exemplo n.º 1
0
def Horizontal_Pallete(figsize=(16, 9),
                       plotcrs=ccrs.PlateCarree(),
                       datacrs=ccrs.PlateCarree(),
                       map_extent=(60, 145, 15, 55),
                       title='',
                       forcast_info='',
                       add_china=True,
                       add_city=False,
                       add_background=True,
                       south_China_sea=True,
                       info_zorder=10,
                       title_fontsize=30):

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')

    fig = plt.figure(figsize=figsize)
    if (plotcrs is None):
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)
    #ax.set_extent(map_extent, crs=crs)
    map_extent = adjust_map_ratio(ax, map_extent=map_extent, datacrs=datacrs)
    plt.title(title, loc='left', fontsize=title_fontsize)
    # add grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=info_zorder)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='coastline',
                                          edgecolor='gray',
                                          lw=0.8,
                                          zorder=info_zorder,
                                          alpha=0.5)
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=info_zorder)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=info_zorder)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=info_zorder,
                                          alpha=0.5)

    if add_city:
        small_city = False
        if (map_extent[1] - map_extent[0] < 25):
            small_city = True
        utl.add_city_on_map(ax,
                            map_extent=map_extent,
                            size=12,
                            transform=datacrs,
                            zorder=info_zorder + 1,
                            small_city=small_city)

    if add_background:
        ax.add_feature(cfeature.OCEAN)
        utl.add_cartopy_background(ax, name='RD')

    if south_China_sea:
        l, b, w, h = ax.get_position().bounds
        utl.add_south_China_sea(pos=[l + w - 0.0875, b, .1, .2])

    if forcast_info:
        l, b, w, h = ax.get_position().bounds
        bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
        bax.set_yticks([])
        bax.set_xticks([])
        bax.axis([0, 10, 0, 10])
        bax.text(
            2.2,
            9.8,
            forcast_info,
            size=15,
            va='top',
            ha='left',
        )

    l, b, w, h = ax.get_position().bounds
    utl.add_logo_extra_in_axes(pos=[l - 0.022, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    return fig, ax, map_extent
Exemplo n.º 2
0
def draw_gh_uv_VVEL(gh=None,
                    uv=None,
                    VVEL=None,
                    map_extent=(50, 150, 0, 65),
                    regrid_shape=20,
                    add_china=True,
                    city=True,
                    south_China_sea=True,
                    output_dir=None,
                    Global=False):

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # draw figure
    plt.figure(figsize=(16, 9))

    # set data projection
    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)

    plt.title('[' + gh.attrs['model'] + '] ' +
              str(int(gh['level'].values[0])) + 'hPa 位势高度场, ' +
              str(int(uv['level'].values[0])) + 'hPa 风场和垂直气压速度',
              loc='left',
              fontsize=30)

    datacrs = ccrs.PlateCarree()

    #adapt to the map ratio
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)
    #adapt to the map ratio

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=5,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=5)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=5)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=5,
                                          alpha=0.5)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if VVEL is not None:
        x, y = np.meshgrid(VVEL['lon'], VVEL['lat'])
        clevs_VVEL = [0.1, 4, 13, 25, 60, 120]

        clevs_VVEL = [
            -30, -20, -10, -5, -2.5, -1, -0.5, 0.5, 1, 2.5, 5, 10, 20, 30
        ]

        z = np.squeeze(VVEL['data'] / 10.)

        cmap, norm = dk_ctables.cm_vertical_velocity_nws(pos=clevs_VVEL)
        #cmap.set_under(color=[0,0,0,0],alpha=0.0)

        plots['VVEL'] = ax.pcolormesh(x,
                                      y,
                                      z,
                                      norm=norm,
                                      cmap=cmap,
                                      zorder=1,
                                      transform=datacrs,
                                      alpha=0.5)

    # draw -hPa wind bards
    if uv is not None:
        x, y = np.meshgrid(uv['lon'], uv['lat'])
        u = np.squeeze(uv['u']) * 2.5
        v = np.squeeze(uv['v']) * 2.5
        plots['uv'] = ax.barbs(x,
                               y,
                               u.values,
                               v.values,
                               length=6,
                               regrid_shape=regrid_shape,
                               transform=datacrs,
                               fill_empty=False,
                               sizes=dict(emptybarb=0.05),
                               zorder=2)

    # draw -hPa geopotential height
    if gh is not None:
        x, y = np.meshgrid(gh['lon'], gh['lat'])
        clevs_gh = np.append(
            np.append(
                np.arange(0, 480, 4),
                np.append(np.arange(480, 584, 8), np.arange(580, 604, 4))),
            np.arange(604, 2000, 8))
        plots['gh'] = ax.contour(x,
                                 y,
                                 np.squeeze(gh['data']),
                                 clevs_gh,
                                 colors='black',
                                 linewidths=2,
                                 transform=datacrs,
                                 zorder=3)
        plt.clabel(plots['gh'],
                   inline=1,
                   fontsize=20,
                   fmt='%.0f',
                   colors='black')

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=4)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')

    #forecast information
    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(str(
        gh.coords['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(
        hours=gh.coords['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(int(gh.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (VVEL != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['VVEL'],
                          cax=cax,
                          orientation='horizontal',
                          ticks=clevs_VVEL[:],
                          extend='max',
                          extendrect=False)
        cb.ax.tick_params(labelsize='x-large')
        cb.set_label('Vertical Velocity (0.1Pa/s)', size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True
    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=110,
                            size=13,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '高度场_风场_垂直气压速度_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(gh.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200,
                    bbox_inches='tight')

    if (output_dir == None):
        plt.show()
Exemplo n.º 3
0
def draw_cumulated_precip_evo(
        rain=None,
        map_extent=(50, 150, 0, 65),
        regrid_shape=20,
        add_china=True,city=True,south_China_sea=True,
        output_dir=None,Global=False):
# set font
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

# set figure
    fig = plt.figure(figsize=(16,9))

    plotcrs = ccrs.AlbersEqualArea(central_latitude=(map_extent[2]+map_extent[3])/2., 
        central_longitude=(map_extent[0]+map_extent[1])/2., standard_parallels=[30., 60.])

    datacrs = ccrs.PlateCarree()

    ax = plt.axes([0.01,0.1,.98,.84], projection=plotcrs)
    map_extent2=utl.adjust_map_ratio(ax,map_extent=map_extent,datacrs=datacrs)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if rain is not None:
        x, y = np.meshgrid(rain['lon'], rain['lat'])
        z=np.squeeze(rain['data'].values)
        z[z<0.1]=np.nan
        znan=np.zeros(shape=x.shape)
        znan[:]=np.nan
        cmap,norm=dk_ctables.cm_qpf_nws(atime=24)
        cmap.set_under(color=[0,0,0,0],alpha=0.0)
        plots['rain'] = ax.pcolormesh(
            x,y,znan, norm=norm,
            cmap=cmap, zorder=1,transform=datacrs,alpha=0.5)
#additional information
    plt.title('['+rain.attrs['model']+'] '+
    str(int(rain.coords['forecast_period'].values[0])-rain.attrs['t_gap'])+
        '至'+str(int(rain.coords['forecast_period'].values[-1]))+'时效累积降水预报',
        loc='left', fontsize=25)

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(
        ax, name='coastline', edgecolor='gray', lw=0.8, zorder=3,alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(
            ax, name='province', edgecolor='gray', lw=0.5, zorder=3)
        utl.add_china_map_2cartopy_public(
            ax, name='nation', edgecolor='black', lw=0.8, zorder=3)
        utl.add_china_map_2cartopy_public(
            ax, name='river', edgecolor='#74b9ff', lw=0.8, zorder=3,alpha=0.5)

    # grid lines
    gl = ax.gridlines(
        crs=datacrs, linewidth=2, color='gray', alpha=0.5, linestyle='--', zorder=1)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax,name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information


    initTime = pd.to_datetime(
    str(rain.coords['forecast_reference_time'].values)).replace(tzinfo=None).to_pydatetime()

    #发布时间
    if(sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if(sys.platform[0:3] == 'win'):        
        locale.setlocale(locale.LC_CTYPE, 'chinese')

    # add color bar
    cax=plt.axes([l,b-0.04,w,.02])
    cb = plt.colorbar(plots['rain'], cax=cax, orientation='horizontal')
    cb.ax.tick_params(labelsize='x-large')                      
    cb.set_label('Precipitation (mm)',size=20)
    fcst_time=initTime+timedelta(hours=rain.coords['forecast_period'].values[0])
    bax=plt.axes([l,b+h-0.1,.25,.1])
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])   
    fcst_time1=initTime+timedelta(hours=rain.coords['forecast_period'].values[0]-6)
    bax.text(2.5, 7.5,'起始时间: '+fcst_time1.strftime("%Y年%m月%d日%H时"),size=15)
    bax.text(2.5, 0.5,'www.nmc.cn',size=15)
    valid_fhour=bax.text(2.5, 5,'截至时间: ',size=15)
    txt_fhour=bax.text(2.5, 2.5,'预报时效: ',size=15)
    utl.add_logo_extra_in_axes(pos=[l-0.02,b+h-0.1,.1,.1],which='nmc', size='Xlarge')
    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l+w-0.091,b,.1,.2])

    small_city=False
    if(map_extent2[1]-map_extent2[0] < 25):
        small_city=True
    if city:
        utl.add_city_on_map(ax,map_extent=map_extent2,transform=datacrs,zorder=2,size=13,small_city=small_city)

    def update(frame_number):
        fcst_time2=initTime+timedelta(hours=rain.coords['forecast_period'].values[frame_number])
        valid_fhour.set_text('截至时间: '+fcst_time2.strftime("%Y年%m月%d日%H时"))
        txt_fhour.set_text('预报时效: '+str(int(rain.coords['forecast_period'].values[frame_number]))+'小时')
        return ax.pcolormesh(
            x,y,np.squeeze(z[frame_number,:,:]), norm=norm,
            cmap=cmap, zorder=1,transform=datacrs,alpha=0.5)
    nframes=rain['data'].shape[0]
    animation1 = FuncAnimation(fig, update, frames=nframes,interval=1000)
    # ffmpegpath = os.path.abspath(r"C:\Users\HEYGY\Desktop\ffmpeg-20200824-3477feb-win64-static\bin\ffmpeg.exe")
    # import matplotlib
    # matplotlib.rcParams["animation.ffmpeg_path"] = ffmpegpath
    # writer = animation.FFMpegWriter()
    # show figure
    plt.subplots_adjust(top=1, bottom=0, right=0.93, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    if(output_dir != None):
        animation1.save(output_dir+'累积降水演变_'+
        '起报时间_'+initTime.strftime("%Y年%m月%d日%H时")+
        '预报时效_'+str(int(rain.coords['forecast_period'].values[-1]))+'小时_'+
        '['+rain.attrs['model']+'] '+'.gif',writer='pillow')

    if(output_dir == None):
        #animation.save('rain.gif', fps=75, writer='imagemagick')
        plt.show()
Exemplo n.º 4
0
def draw_cumulated_precip(
        rain=None,
        map_extent=(50, 150, 0, 65),
        regrid_shape=20,
        add_china=True,city=True,south_China_sea=True,
        output_dir=None,Global=False):
# set font
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

# set figure
    fig = plt.figure(figsize=(9,14))
    camera = Camera(fig)
    nframe=rain['data'].shape[0]
    plotcrs = ccrs.AlbersEqualArea(central_latitude=(map_extent[2]+map_extent[3])/2., 
        central_longitude=(map_extent[0]+map_extent[1])/2., standard_parallels=[30., 60.])

    datacrs = ccrs.PlateCarree()

    ax = plt.axes([0.01,0.1,.98,.84], projection=plotcrs)
    map_extent2=utl.adjust_map_ratio(ax,map_extent=map_extent,datacrs=datacrs)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if rain is not None:
        x, y = np.meshgrid(rain['lon'], rain['lat'])
        z=np.squeeze(rain['data'].values)
        z[z<0.1]=np.nan
        znan=np.zeros(shape=x.shape)
        znan[:]=np.nan
        # cmap,norm=dk_ctables.cm_qpf_nws(atime=None,
        #         pos=np.concatenate((
        #         np.array([0, 0.1, 0.5, 1]), np.arange(2.5, 25, 2.5),
        #         np.arange(25, 50, 5), np.arange(50, 150, 10),
        #         np.arange(150, 800, 50))))
        cmap,norm=dk_ctables.cm_qpf_nws(atime=24)

        cmap.set_under(color=[0,0,0,0],alpha=0.0)
        plots['rain'] = ax.pcolormesh(
            x,y,znan, norm=norm,
            cmap=cmap, zorder=1,transform=datacrs,alpha=0.5)
#additional information
    plt.title('['+rain.attrs['model']+'] '+
    str(int(rain.coords['forecast_period'].values[0]))+'至'+str(int(rain.coords['forecast_period'].values[-1]))+'时效累积降水预报',
        loc='left', fontsize=30)

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(
        ax, name='coastline', edgecolor='gray', lw=0.8, zorder=3,alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(
            ax, name='province', edgecolor='gray', lw=0.5, zorder=3)
        utl.add_china_map_2cartopy_public(
            ax, name='nation', edgecolor='black', lw=0.8, zorder=3)
        utl.add_china_map_2cartopy_public(
            ax, name='river', edgecolor='#74b9ff', lw=0.8, zorder=3,alpha=0.5)

    # grid lines
    gl = ax.gridlines(
        crs=datacrs, linewidth=2, color='gray', alpha=0.5, linestyle='--', zorder=1)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax,name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information


    initTime = pd.to_datetime(
    str(rain.coords['forecast_reference_time'].values)).replace(tzinfo=None).to_pydatetime()

    #发布时间
    if(sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if(sys.platform[0:3] == 'win'):        
        locale.setlocale(locale.LC_CTYPE, 'chinese')

    # add color bar
    cax=plt.axes([l,b-0.04,w,.02])
    cb = plt.colorbar(plots['rain'], cax=cax, orientation='horizontal')
    cb.ax.tick_params(labelsize='x-large')                      
    cb.set_label('Precipitation (mm)',size=20)
    fcst_time=initTime+timedelta(hours=rain.coords['forecast_period'].values[0])
    bax=plt.axes([l,b+h-0.07,.45,.07])
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])   
    fcst_time1=initTime+timedelta(hours=rain.coords['forecast_period'].values[0]-6)
    bax.text(2.5, 7.5,'起始时间: '+fcst_time1.strftime("%Y年%m月%d日%H时"),size=15)
    bax.text(2.5, 0.5,'www.nmc.cn',size=15)
    valid_fhour=bax.text(2.5, 5,'截至时间: ',size=15)
    txt_fhour=bax.text(2.5, 2.5,'预报时效: ',size=15)
    utl.add_logo_extra_in_axes(pos=[l-0.0,b+h-0.085,.1,.1],which='nmc', size='Xlarge')
    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l+w-0.091,b,.1,.2])

    small_city=False
    if(map_extent2[1]-map_extent2[0] < 25):
        small_city=True
    if city:
        utl.add_city_on_map(ax,map_extent=map_extent2,transform=datacrs,zorder=2,size=13,small_city=small_city)

    fcst_time2=initTime+timedelta(hours=rain.coords['forecast_period'].values[-1])
    valid_fhour.set_text('截至时间: '+fcst_time2.strftime("%Y年%m月%d日%H时"))
    txt_fhour.set_text('预报时效: '+str(int(rain.coords['forecast_period'].values[-1]))+'小时')
    ax.pcolormesh(
    x,y,np.squeeze(z[-1,:,:]), norm=norm,
            cmap=cmap, zorder=1,transform=datacrs,alpha=0.5)
    
    # plt.draw()
    plt.savefig(output_dir+
        '起报时间_'+initTime.strftime("%Y年%m月%d日%H时")+
        '预报时效_'+str(int(rain.coords['forecast_period'].values[-1]))+'小时_'+rain.attrs['model']+'.png', dpi=200,bbox_inches='tight')
Exemplo n.º 5
0
def draw_gh_rain(gh=None, rain=None,
                    map_extent=(50, 150, 0, 65),
                    regrid_shape=20,
                    add_china=True,city=True,south_China_sea=True,
                    output_dir=None,Global=False):
# set font
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

# set figure
    plt.figure(figsize=(16,9))

    if(Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(central_latitude=(map_extent[2]+map_extent[3])/2., 
            central_longitude=(map_extent[0]+map_extent[1])/2., standard_parallels=[30., 60.])
 
    datacrs = ccrs.PlateCarree()

    ax = plt.axes([0.01,0.1,.98,.84], projection=plotcrs)
    map_extent2=utl.adjust_map_ratio(ax,map_extent=map_extent,datacrs=datacrs)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if rain is not None:
        x, y = np.meshgrid(rain['lon'], rain['lat'])
        z=np.squeeze(rain['data'].values)
        z[z<0.1]=np.nan
        cmap,norm=dk_ctables.cm_qpf_nws(atime=rain.attrs['atime'])
        cmap.set_under(color=[0,0,0,0],alpha=0.0)
        plots['rain'] = ax.pcolormesh(
            x,y,z, norm=norm,
            cmap=cmap, zorder=1,transform=datacrs,alpha=0.5)

    # draw -hPa geopotential height
    if gh is not None:
        x, y = np.meshgrid(gh['lon'], gh['lat'])
        clevs_gh = np.append(np.append(np.arange(0, 480, 4),np.append(np.arange(480, 584, 8), np.arange(580, 604, 4))), np.arange(604, 2000, 8))
        plots['gh'] = ax.contour(
            x, y, np.squeeze(gh['data']), clevs_gh, colors='black',
            linewidths=2, transform=datacrs, zorder=3)
        plt.clabel(plots['gh'], inline=2, fontsize=20, fmt='%.0f',colors='black')
#additional information
    plt.title('['+gh.attrs['model']+'] '+
    str(int(gh['level'].values[0]))+'hPa 位势高度场, '+
    str(int(rain.attrs['atime']))+'小时降水', 
        loc='left', fontsize=30)
        
    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(
        ax, name='coastline', edgecolor='gray', lw=0.8, zorder=3,alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(
            ax, name='province', edgecolor='gray', lw=0.5, zorder=3)
        utl.add_china_map_2cartopy_public(
            ax, name='nation', edgecolor='black', lw=0.8, zorder=3)
        utl.add_china_map_2cartopy_public(
            ax, name='river', edgecolor='#74b9ff', lw=0.8, zorder=3,alpha=0.5)


    # grid lines
    gl = ax.gridlines(
        crs=datacrs, linewidth=2, color='gray', alpha=0.5, linestyle='--', zorder=1)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax,name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax=plt.axes([l,b+h-0.1,.25,.1],facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(
    str(gh.coords['forecast_reference_time'].values)).replace(tzinfo=None).to_pydatetime()
    fcst_time=initTime+timedelta(hours=gh.coords['forecast_period'].values[0])
    #发布时间
    if(sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if(sys.platform[0:3] == 'win'):        
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5,'起报时间: '+initTime.strftime("%Y年%m月%d日%H时"),size=15)
    plt.text(2.5, 5,'预报时间: '+fcst_time.strftime("%Y年%m月%d日%H时"),size=15)
    plt.text(2.5, 2.5,'预报时效: '+str(int(gh.coords['forecast_period'].values[0]))+'小时'+'(降水'+str(int(gh.coords['forecast_period'].values[0]+12))+'小时)',size=15)
    plt.text(2.5, 0.5,'www.nmc.cn',size=15)

    # add color bar
    if(rain != None):
        cax=plt.axes([l,b-0.04,w,.02])
        cb = plt.colorbar(plots['rain'], cax=cax, orientation='horizontal')
        cb.ax.tick_params(labelsize='x-large')                      
        cb.set_label(str(int(rain.attrs['atime']))+'h precipitation (mm)',size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l+w-0.091,b,.1,.2])

    small_city=False
    if(map_extent2[1]-map_extent2[0] < 25):
        small_city=True
    if city:
        utl.add_city_on_map(ax,map_extent=map_extent2,transform=datacrs,zorder=2,size=13,small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l-0.02,b+h-0.1,.1,.1],which='nmc', size='Xlarge')

    # show figure
    if(output_dir != None):
        plt.savefig(output_dir+'高度场_降水_预报_'+
        '起报时间_'+initTime.strftime("%Y年%m月%d日%H时")+
        '预报时效_'+str(int(gh.coords['forecast_period'].values[0]))+'小时'+'.png', dpi=200)
    
    if(output_dir == None):
        plt.show()
Exemplo n.º 6
0
def draw_Rain_evo(
        rain=None,fcs_lvl=4,
        map_extent=(50, 150, 0, 65),
        regrid_shape=20,
        add_china=True,city=True,south_China_sea=True,
        output_dir=None,Global=False):
# set font
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)
    if(sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if(sys.platform[0:3] == 'win'):        
        locale.setlocale(locale.LC_CTYPE, 'chinese')
# set figure
    plt.figure(figsize=(16,9))

    if(Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(central_latitude=(map_extent[2]+map_extent[3])/2., 
            central_longitude=(map_extent[0]+map_extent[1])/2., standard_parallels=[30., 60.])
 
    ax = plt.axes([0.01,0.1,.98,.84], projection=plotcrs)
    
    datacrs = ccrs.PlateCarree()
    map_extent2=utl.adjust_map_ratio(ax,map_extent=map_extent,datacrs=datacrs)

    plt.title('['+rain.attrs['model']+'] 预报逐'+
        str(rain.attrs['t_gap'])+'小时'+str(fcs_lvl)+'mm降水范围演变', 
        loc='left', fontsize=30)
#draw data
    plots = {}
    if rain is not None:
        x, y = np.meshgrid(rain['lon'], rain['lat'])
        for itime in range(0,len(rain['time'].values)):
            z=np.squeeze(rain['data'].values[itime,:,:])
            z[z<=0.1]=np.nan
            initTime = pd.to_datetime(str(rain.coords['forecast_reference_time'].values)).replace(tzinfo=None).to_pydatetime()
            labels=(initTime+timedelta(hours=rain.coords['forecast_period'].values[itime])).strftime("%m月%d日%H时")
            cmap=mpl.cm.jet
            per_color=utl.get_part_clev_and_cmap(cmap=cmap,clev_range=[0,len(rain['time'].values)],clev_slt=itime)
            ax.contourf(
                x,y,z, levels=[fcs_lvl,800],
                colors=per_color, zorder=3,transform=datacrs,
                alpha=0.2+itime*((1-0.2)/len(rain['time'].values)))
            if(itime == 0):
                label_handles = [mpatches.Patch(color=per_color.reshape(4),
                    alpha=0.2+itime*((1-0.2)/len(rain['time'].values)), label=labels)]
            else:
                label_handles.append(mpatches.Patch(color=per_color.reshape(4),alpha=0.2+itime*((1-0.2)/len(rain['time'].values)), label=labels))
        leg = plt.legend(handles=label_handles, loc=3,framealpha=1)
#additional information
    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(
        ax, name='coastline', edgecolor='gray', lw=0.8, zorder=1,alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(
            ax, name='province', edgecolor='gray', lw=0.5, zorder=1)
        utl.add_china_map_2cartopy_public(
            ax, name='nation', edgecolor='black', lw=0.8, zorder=1)
        utl.add_china_map_2cartopy_public(
            ax, name='river', edgecolor='#74b9ff', lw=0.8, zorder=1,alpha=0.5)

    # grid lines
    gl = ax.gridlines(
        crs=datacrs, linewidth=2, color='gray', alpha=0.5, linestyle='--', zorder=1)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax,name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax=plt.axes([l,b+h-0.1,.25,.1],facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(
    str(rain.coords['forecast_reference_time'].values)).replace(tzinfo=None).to_pydatetime()
    fcst_time=initTime+timedelta(hours=rain.coords['forecast_period'].values[0])
    #发布时间
    if(sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if(sys.platform[0:3] == 'win'):        
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5,'起报时间: '+initTime.strftime("%Y年%m月%d日%H时"),size=15)
    plt.text(2.5, 5,'起始时间: '+
        (initTime+timedelta(hours=rain.coords['forecast_period'].values[0])).strftime("%Y年%m月%d日%H时"),size=15)
    plt.text(2.5, 2.5,'终止时间: '+
        (initTime+timedelta(hours=rain.coords['forecast_period'].values[1])).strftime("%Y年%m月%d日%H时"),size=15)
    plt.text(2.5, 0.5,'www.nmc.cn',size=15)

    # add color bar
    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l+w-0.091,b,.1,.2])

    small_city=False
    if(map_extent2[1]-map_extent2[0] < 25):
        small_city=True
    if city:
        utl.add_city_on_map(ax,map_extent=map_extent2,transform=datacrs,zorder=110,size=13,small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l-0.02,b+h-0.1,.1,.1],which='nmc', size='Xlarge')

    # show figure
    if(output_dir != None):
        plt.savefig(output_dir+'海平面气压_降水_预报_'+
        '起报时间_'+initTime.strftime("%Y年%m月%d日%H时")+
        '预报时效_'+str(int(rain.coords['forecast_period'].values[0]))+'小时'+'.png', dpi=200)
    
    if(output_dir == None):
        plt.show()        
Exemplo n.º 7
0
def draw_gh_uv_mslp(gh=None,
                    uv=None,
                    mslp=None,
                    map_extent=(50, 150, 0, 65),
                    regrid_shape=20,
                    add_china=True,
                    city=True,
                    south_China_sea=True,
                    output_dir=None,
                    Global=False):

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # draw figure
    plt.figure(figsize=(16, 9))

    # set data projection
    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)

    plt.title('[' + gh.attrs['model'] + '] ' +
              str(int(gh['level'].values[0])) + 'hPa 位势高度场, ' +
              str(int(uv['level'].values[0])) + 'hPa 风场, 海平面气压场',
              loc='left',
              fontsize=30)

    datacrs = ccrs.PlateCarree()

    #adapt to the map ratio
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)
    #adapt to the map ratio

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=5,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=5)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=5)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=5,
                                          alpha=0.5)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if mslp is not None:
        x, y = np.meshgrid(mslp['lon'], mslp['lat'])
        clevs_mslp = np.arange(960, 1065, 5)
        cmap = guide_cmaps(26)
        plots['mslp'] = ax.contourf(x,
                                    y,
                                    np.squeeze(mslp['data']),
                                    clevs_mslp,
                                    cmap=cmap,
                                    alpha=0.8,
                                    zorder=1,
                                    transform=datacrs)
        #+画高低压中心
        res = mslp['lon'].values[1] - mslp['lon'].values[0]
        nwindow = int(9.5 / res)
        mslp_hl = np.ma.masked_invalid(mslp['data'].values).squeeze()
        local_min, local_max = utl.extrema(mslp_hl,
                                           mode='wrap',
                                           window=nwindow)
        #Get location of extrema on grid
        xmin, xmax, ymin, ymax = map_extent2
        lons2d, lats2d = x, y
        transformed = datacrs.transform_points(datacrs, lons2d, lats2d)
        x = transformed[..., 0]
        y = transformed[..., 1]
        xlows = x[local_min]
        xhighs = x[local_max]
        ylows = y[local_min]
        yhighs = y[local_max]
        lowvals = mslp_hl[local_min]
        highvals = mslp_hl[local_max]
        yoffset = 0.022 * (ymax - ymin)
        dmin = yoffset
        #Plot low pressures
        xyplotted = []
        for x, y, p in zip(xlows, ylows, lowvals):
            if x < xmax - yoffset and x > xmin + yoffset and y < ymax - yoffset and y > ymin + yoffset:
                dist = [
                    np.sqrt((x - x0)**2 + (y - y0)**2) for x0, y0 in xyplotted
                ]
                if not dist or min(dist) > dmin:  #,fontweight='bold'
                    a = ax.text(x,
                                y,
                                'L',
                                fontsize=28,
                                ha='center',
                                va='center',
                                color='r',
                                fontweight='normal',
                                transform=datacrs)
                    b = ax.text(x,
                                y - yoffset,
                                repr(int(p)),
                                fontsize=14,
                                ha='center',
                                va='top',
                                color='r',
                                fontweight='normal',
                                transform=datacrs)
                    a.set_path_effects([
                        path_effects.Stroke(linewidth=1.5, foreground='black'),
                        path_effects.SimpleLineShadow(),
                        path_effects.Normal()
                    ])
                    b.set_path_effects([
                        path_effects.Stroke(linewidth=1.0, foreground='black'),
                        path_effects.SimpleLineShadow(),
                        path_effects.Normal()
                    ])
                    xyplotted.append((x, y))

        #Plot high pressures
        xyplotted = []
        for x, y, p in zip(xhighs, yhighs, highvals):
            if x < xmax - yoffset and x > xmin + yoffset and y < ymax - yoffset and y > ymin + yoffset:
                dist = [
                    np.sqrt((x - x0)**2 + (y - y0)**2) for x0, y0 in xyplotted
                ]
                if not dist or min(dist) > dmin:
                    a = ax.text(x,
                                y,
                                'H',
                                fontsize=28,
                                ha='center',
                                va='center',
                                color='b',
                                fontweight='normal',
                                transform=datacrs)
                    b = ax.text(x,
                                y - yoffset,
                                repr(int(p)),
                                fontsize=14,
                                ha='center',
                                va='top',
                                color='b',
                                fontweight='normal',
                                transform=datacrs)
                    a.set_path_effects([
                        path_effects.Stroke(linewidth=1.5, foreground='black'),
                        path_effects.SimpleLineShadow(),
                        path_effects.Normal()
                    ])
                    b.set_path_effects([
                        path_effects.Stroke(linewidth=1.0, foreground='black'),
                        path_effects.SimpleLineShadow(),
                        path_effects.Normal()
                    ])
                    xyplotted.append((x, y))
        #-画高低压中心

    # draw -hPa wind bards
    if uv is not None:
        x, y = np.meshgrid(uv['lon'], uv['lat'])
        u = np.squeeze(uv['u']) * 2.5
        v = np.squeeze(uv['v']) * 2.5
        plots['uv'] = ax.barbs(x,
                               y,
                               u.values,
                               v.values,
                               length=6,
                               regrid_shape=regrid_shape,
                               transform=datacrs,
                               fill_empty=False,
                               sizes=dict(emptybarb=0.05),
                               zorder=2)

    # draw -hPa geopotential height
    if gh is not None:
        x, y = np.meshgrid(gh['lon'], gh['lat'])
        clevs_gh = np.append(
            np.append(
                np.arange(0, 480, 4),
                np.append(np.arange(480, 584, 8), np.arange(580, 604, 4))),
            np.arange(604, 2000, 8))
        linewidths_gh = np.zeros(clevs_gh.shape) + 2
        idx_588 = np.where(clevs_gh == 588)
        linewidths_gh[idx_588[0]] = 4
        plots['gh'] = ax.contour(x,
                                 y,
                                 np.squeeze(gh['data']),
                                 clevs_gh,
                                 colors='purple',
                                 linewidths=linewidths_gh,
                                 transform=datacrs,
                                 zorder=3)
        ax.clabel(plots['gh'],
                  inline=1,
                  fontsize=20,
                  fmt='%.0f',
                  colors='black')

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=4)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')
    #forecast information
    l, b, w, h = ax.get_position().bounds

    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(str(
        gh.coords['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(
        hours=gh.coords['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(int(gh.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    cax = plt.axes([l, b - 0.04, w, .02])
    cb = plt.colorbar(plots['mslp'],
                      cax=cax,
                      orientation='horizontal',
                      ticks=clevs_mslp[:-1],
                      extend='max',
                      extendrect=False)
    cb.ax.tick_params(labelsize='x-large')
    cb.set_label('Mean sea level pressure (hPa)', size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True
    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=6,
                            size=15,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')
    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '最高温度_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(gh.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200,
                    bbox_inches='tight')

    if (output_dir == None):
        plt.show()
Exemplo n.º 8
0
def draw_Miller_Composite_Chart(fcst_info=None,
                                u_300=None,
                                v_300=None,
                                u_500=None,
                                v_500=None,
                                u_850=None,
                                v_850=None,
                                pmsl_change=None,
                                hgt_500_change=None,
                                Td_dep_700=None,
                                Td_sfc=None,
                                pmsl=None,
                                lifted_index=None,
                                vort_adv_500_smooth=None,
                                map_extent=(50, 150, 0, 65),
                                add_china=True,
                                city=True,
                                south_China_sea=True,
                                output_dir=None,
                                Global=False):
    # set font
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # set figure
    plt.figure(figsize=(16, 9))

    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])
    datacrs = ccrs.PlateCarree()
    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)

    #draw data
    plots = {}

    lons = fcst_info['lon']
    lats = fcst_info['lat']
    cs1 = ax.contour(lons,
                     lats,
                     lifted_index,
                     range(-8, -2, 2),
                     transform=ccrs.PlateCarree(),
                     colors='red',
                     linewidths=0.75,
                     linestyles='solid',
                     zorder=7)
    cs1.clabel(fontsize=10,
               inline=1,
               inline_spacing=7,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True)

    # Plot Surface pressure falls
    cs2 = ax.contour(lons,
                     lats,
                     pmsl_change.to('hPa'),
                     range(-10, -1, 4),
                     transform=ccrs.PlateCarree(),
                     colors='k',
                     linewidths=0.75,
                     linestyles='dashed',
                     zorder=6)
    cs2.clabel(fontsize=10,
               inline=1,
               inline_spacing=7,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True)

    # Plot 500-hPa height falls
    cs3 = ax.contour(lons,
                     lats,
                     hgt_500_change,
                     range(-60, -29, 15),
                     transform=ccrs.PlateCarree(),
                     colors='k',
                     linewidths=0.75,
                     linestyles='solid',
                     zorder=5)
    cs3.clabel(fontsize=10,
               inline=1,
               inline_spacing=7,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True)

    # Plot surface pressure
    ax.contourf(lons,
                lats,
                pmsl.to('hPa'),
                range(990, 1011, 20),
                alpha=0.5,
                transform=ccrs.PlateCarree(),
                colors='yellow',
                zorder=1)

    # Plot surface dewpoint
    ax.contourf(lons,
                lats,
                Td_sfc.to('degF'),
                range(65, 76, 10),
                alpha=0.4,
                transform=ccrs.PlateCarree(),
                colors=['green'],
                zorder=2)

    # Plot 700-hPa dewpoint depression
    ax.contourf(lons,
                lats,
                Td_dep_700,
                range(15, 46, 30),
                alpha=0.5,
                transform=ccrs.PlateCarree(),
                colors='tan',
                zorder=3)

    # Plot Vorticity Advection
    ax.contourf(lons,
                lats,
                vort_adv_500_smooth,
                range(5, 106, 100),
                alpha=0.5,
                transform=ccrs.PlateCarree(),
                colors='BlueViolet',
                zorder=4)

    # Define a skip to reduce the barb point density
    skip_300 = (slice(None, None, 12), slice(None, None, 12))
    skip_500 = (slice(None, None, 10), slice(None, None, 10))
    skip_850 = (slice(None, None, 8), slice(None, None, 8))
    x, y = np.meshgrid(fcst_info['lon'], fcst_info['lat'])
    # 300-hPa wind barbs
    jet300 = ax.barbs(x[skip_300],
                      y[skip_300],
                      u_300[skip_300].m,
                      v_300[skip_300].m,
                      length=6,
                      transform=ccrs.PlateCarree(),
                      color='green',
                      zorder=10,
                      label='300-hPa Jet Core Winds (m/s)')

    # 500-hPa wind barbs
    jet500 = ax.barbs(x[skip_500],
                      y[skip_500],
                      u_500[skip_500].m,
                      v_500[skip_500].m,
                      length=6,
                      transform=ccrs.PlateCarree(),
                      color='blue',
                      zorder=9,
                      label='500-hPa Jet Core Winds (m/s)')

    # 850-hPa wind barbs
    jet850 = ax.barbs(x[skip_850],
                      y[skip_850],
                      u_850[skip_850].m,
                      v_850[skip_850].m,
                      length=6,
                      transform=ccrs.PlateCarree(),
                      color='k',
                      zorder=8,
                      label='850-hPa Jet Core Winds (m/s)')

    #additional information
    plt.title('[' + fcst_info['model'] + '] ' + 'Miller 综合分析图',
              loc='left',
              fontsize=30)

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=105,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=105)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=105)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=105,
                                          alpha=0.5)

    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=40)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')

    l, b, w, h = ax.get_position().bounds

    # Legend
    purple = mpatches.Patch(color='BlueViolet',
                            label='Cyclonic Absolute Vorticity Advection')
    yellow = mpatches.Patch(color='yellow', label='Surface MSLP < 1010 hPa')
    green = mpatches.Patch(color='green', label='Surface Td > 65 F')
    tan = mpatches.Patch(color='tan',
                         label='700 hPa Dewpoint Depression > 15 C')
    red_line = lines.Line2D([], [], color='red', label='Best Lifted Index (C)')
    dashed_black_line = lines.Line2D(
        [], [],
        linestyle='dashed',
        color='k',
        label='12-hr Surface Pressure Falls (hPa)')
    black_line = lines.Line2D([], [],
                              linestyle='solid',
                              color='k',
                              label='12-hr 500-hPa Height Falls (m)')
    leg = plt.legend(handles=[
        jet300, jet500, jet850, dashed_black_line, black_line, red_line,
        purple, tan, green, yellow
    ],
                     loc=3,
                     title='Composite Analysis Valid: ',
                     framealpha=1)
    leg.set_zorder(100)

    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(str(
        fcst_info['forecast_reference_time'])).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(hours=fcst_info['forecast_period'])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(fcst_info['forecast_period']) + '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True

    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=110,
                            size=13,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + 'Miller_综合图_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(fcst_info['forecast_period']) + '小时' + '.png',
                    dpi=200,
                    bbox_inches='tight')
        plt.close()

    if (output_dir == None):
        plt.show()
Exemplo n.º 9
0
def draw_PV_Div_uv(pv=None,
                   uv=None,
                   div=None,
                   map_extent=(50, 150, 0, 65),
                   regrid_shape=20,
                   add_china=True,
                   city=False,
                   south_China_sea=True,
                   output_dir=None,
                   Global=False):

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # draw figure
    plt.figure(figsize=(16, 9))

    # set data projection
    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)

    plt.title('[' + pv.attrs['model'] + '] ' + str(int(pv['level'])) +
              'hPa 位涡扰动, 风场, 散度',
              loc='left',
              fontsize=30)

    datacrs = ccrs.PlateCarree()

    #adapt to the map ratio
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)
    #adapt to the map ratio

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=5,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=5)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=5)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=5,
                                          alpha=0.5)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if div is not None:

        x, y = np.meshgrid(div['lon'], div['lat'])
        z = np.squeeze(div['data'])
        clevs_div = np.arange(-15, 16, 1)
        # plots['div'] = ax.contourf(
        #     x, y, z*1e5,clevs_div,cmap=plt.cm.PuOr,
        #     transform=datacrs,alpha=0.5, zorder=1,extend='both')

        cmap = dk_ctables2.ncl_cmaps('hotcolr_19lev')
        plots['div'] = ax.contourf(x,
                                   y,
                                   z * 1e5,
                                   levels=clevs_div[:],
                                   vmin=-15,
                                   vmax=15,
                                   cmap=cmap,
                                   transform=datacrs,
                                   alpha=0.5,
                                   zorder=1,
                                   extend='both')

    # draw -hPa wind bards
    if uv is not None:
        x, y = np.meshgrid(uv['lon'], uv['lat'])
        u = np.squeeze(uv['u'].values) * 2.5
        v = np.squeeze(uv['v'].values) * 2.5
        plots['uv'] = ax.barbs(x,
                               y,
                               u,
                               v,
                               length=6,
                               regrid_shape=regrid_shape,
                               transform=datacrs,
                               fill_empty=False,
                               sizes=dict(emptybarb=0.05),
                               zorder=2)

    # draw -hPa geopotential height
    if pv is not None:
        x, y = np.meshgrid(pv['lon'], pv['lat'])
        clevs_pv = np.arange(4, 25, 1)
        plots['pv'] = ax.contour(x,
                                 y,
                                 np.squeeze(pv['data']) * 1e6,
                                 clevs_pv,
                                 colors='black',
                                 linewidths=2,
                                 transform=datacrs,
                                 zorder=3)
        plt.clabel(plots['pv'],
                   inline=1,
                   fontsize=20,
                   fmt='%.0f',
                   colors='black')

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=4)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')

    l, b, w, h = ax.get_position().bounds
    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(str(
        pv['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(hours=pv['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(int(pv.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (div != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['div'],
                          cax=cax,
                          orientation='horizontal',
                          ticks=clevs_div[:],
                          extend='both',
                          extendrect=False)
        cb.ax.tick_params(labelsize='x-large')
        cb.set_label('Divergence ($10^5$ s$^{-1}$)', size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True
    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=110,
                            size=13,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '位涡_风场_散度_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(pv.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200,
                    bbox_inches='tight')
        plt.close()

    if (output_dir == None):
        plt.show()
Exemplo n.º 10
0
def draw_isentropic_uv(isentrh=None,
                       isentuv=None,
                       isentprs=None,
                       map_extent=(50, 150, 0, 65),
                       regrid_shape=20,
                       add_china=True,
                       city=False,
                       south_China_sea=True,
                       output_dir=None,
                       Global=False):

    # set font
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # set figure
    plt.figure(figsize=(16, 9))

    # set data projection
    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    datacrs = ccrs.PlateCarree()
    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)

    #draw data
    plots = {}
    if isentrh is not None:
        x, y = np.meshgrid(isentrh['lon'], isentrh['lat'])
        z = np.squeeze(isentrh['data'])
        clevs_rh = range(10, 106, 5)
        plots['isentrh'] = ax.contourf(x,
                                       y,
                                       z,
                                       clevs_rh,
                                       cmap=plt.cm.gist_earth_r,
                                       transform=datacrs,
                                       alpha=0.5,
                                       extend='both')

    # draw -hPa wind bards
    if isentuv is not None:
        x, y = np.meshgrid(isentuv['lon'], isentuv['lat'])
        u = np.squeeze(isentuv['isentu'].values) * 2.5
        v = np.squeeze(isentuv['isentv'].values) * 2.5
        plots['uv'] = ax.barbs(x,
                               y,
                               u,
                               v,
                               length=6,
                               regrid_shape=regrid_shape,
                               transform=datacrs,
                               fill_empty=False,
                               sizes=dict(emptybarb=0.05),
                               zorder=20)

    # draw -hPa geopotential height
    if isentprs is not None:
        x, y = np.meshgrid(isentprs['lon'], isentprs['lat'])
        clevs_isentprs = np.arange(0, 1000, 25)
        z = gaussian_filter(np.squeeze(isentprs['data']), 5)
        plots['isentprs'] = ax.contour(x,
                                       y,
                                       z,
                                       clevs_isentprs,
                                       colors='black',
                                       linewidths=2,
                                       transform=datacrs,
                                       zorder=30)
        plt.clabel(plots['isentprs'],
                   inline=1,
                   fontsize=20,
                   fmt='%.0f',
                   colors='black')
#additional information
    plt.title('[' + isentrh.attrs['model'] + '] ' +
              str(isentrh['level'].values) + '等熵面  风场 相对湿度 气压',
              loc='left',
              fontsize=30)

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=105,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=105)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=105)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=105,
                                          alpha=0.5)

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=40)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(
        str(isentrh.coords['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(
        hours=isentrh.coords['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(int(isentrh.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (isentrh != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['isentrh'],
                          cax=cax,
                          orientation='horizontal',
                          ticks=clevs_rh[:],
                          extend='both',
                          extendrect=False)
        cb.ax.tick_params(labelsize='x-large')
        cb.set_label('Relative Humidity (%)', size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True
    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=110,
                            size=13,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + isentrh['lev'] + '等熵面分析_相对湿度_风场_气压_预报_' +
                    '起报时间_' + initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(isentrh.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200)

    if (output_dir == None):
        plt.show()
Exemplo n.º 11
0
def draw_T2m_mslp_uv10m(t2m=None,
                        mslp=None,
                        uv10m=None,
                        map_extent=(50, 150, 0, 65),
                        regrid_shape=20,
                        add_china=True,
                        city=True,
                        south_China_sea=True,
                        output_dir=None,
                        Global=False):

    # set font
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # draw figure
    plt.figure(figsize=(16, 9))

    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])
    datacrs = ccrs.PlateCarree()
    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if t2m is not None:
        x, y = np.meshgrid(t2m['lon'], t2m['lat'])
        z = np.squeeze(t2m['data'])
        cmap = dk_ctables.cm_high_temperature_nws()
        cmap.set_under(color=[0, 0, 0, 0], alpha=0.0)
        plots['t2m'] = ax.pcolormesh(x,
                                     y,
                                     z,
                                     cmap=cmap,
                                     zorder=1,
                                     transform=datacrs,
                                     alpha=0.5)

    if uv10m is not None:
        x, y = np.meshgrid(uv10m['lon'].values, uv10m['lat'].values)
        u = np.squeeze(uv10m['u10m'].values) * 2.5
        v = np.squeeze(uv10m['v10m'].values) * 2.5
        plots['uv'] = ax.barbs(x,
                               y,
                               u,
                               v,
                               length=6,
                               regrid_shape=regrid_shape,
                               transform=datacrs,
                               fill_empty=False,
                               sizes=dict(emptybarb=0.05),
                               zorder=2,
                               color='white')

    if mslp is not None:
        x, y = np.meshgrid(mslp['lon'], mslp['lat'])
        clevs_mslp = np.arange(900, 1100, 2.5)
        z = gaussian_filter(np.squeeze(mslp['data']), 5)
        plots['mslp'] = ax.contour(x,
                                   y,
                                   z,
                                   clevs_mslp,
                                   colors='black',
                                   linewidths=1,
                                   transform=datacrs,
                                   zorder=3)
        cl = ax.clabel(plots['mslp'],
                       inline=1,
                       fontsize=20,
                       fmt='%.0f',
                       colors='black')


#additional information
    plt.title('[' + mslp.attrs['model'] + '] ' + '海平面气压, ' + '10米风场, ' +
              '2米 温度',
              loc='left',
              fontsize=30)
    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=4,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=4)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=4)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=4,
                                          alpha=0.5)

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=5)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(str(
        mslp['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(
        hours=mslp.coords['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(mslp.coords['forecast_period'].values[0]) + '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (t2m != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['t2m'], cax=cax, orientation='horizontal')
        cb.ax.tick_params(labelsize='x-large')
        cb.set_label('Temperature at 2m Above Ground (' + u'°C' + ')', size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True
    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=6,
                            size=13,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '海平面气压_10米风场_2米温度_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(mslp.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200,
                    bbox_inches='tight')
        plt.close()

    if (output_dir == None):
        plt.show()
Exemplo n.º 12
0
def draw_T_2m(T_2m=None,
              map_extent=(50, 150, 0, 65),
              regrid_shape=20,
              add_china=True,
              city=True,
              south_China_sea=True,
              output_dir=None,
              Global=False):
    # set font
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # set figure
    plt.figure(figsize=(16, 9))

    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)
    datacrs = ccrs.PlateCarree()
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)

    # define return plots
    plots = {}
    if T_2m is not None:
        x, y = np.meshgrid(T_2m['lon'], T_2m['lat'])
        z = np.squeeze(T_2m['data'])
        cmap = dk_ctables.cm_temp()
        cmap.set_under(color=[0, 0, 0, 0], alpha=0.0)
        plots['T_2m'] = ax.pcolormesh(x,
                                      y,
                                      z,
                                      cmap=cmap,
                                      zorder=1,
                                      transform=datacrs,
                                      alpha=0.5,
                                      vmin=-45,
                                      vmax=45)

        z = gaussian_filter(z, 5)
        plots['T_2m_zero'] = ax.contour(x,
                                        y,
                                        z,
                                        levels=[0],
                                        colors='#232B99',
                                        linewidths=2,
                                        transform=datacrs,
                                        zorder=2)
        cl_zero = plt.clabel(plots['T_2m_zero'],
                             inline=1,
                             fontsize=15,
                             fmt='%i',
                             colors='#232B99')
        for t in cl_zero:
            t.set_path_effects([
                path_effects.Stroke(linewidth=3, foreground='white'),
                path_effects.Normal()
            ])

        plots['T_2m_35'] = ax.contour(x,
                                      y,
                                      z,
                                      levels=[35, 37, 40],
                                      colors=['#FF8F00', '#FF6200', '#FF0000'],
                                      linewidths=2,
                                      transform=datacrs,
                                      zorder=2)
        cl_35 = plt.clabel(plots['T_2m_35'],
                           inline=1,
                           fontsize=15,
                           fmt='%i',
                           colors='#FF0000')
        for t in cl_35:
            t.set_path_effects([
                path_effects.Stroke(linewidth=3, foreground='white'),
                path_effects.Normal()
            ])

    plt.title('[' + T_2m.attrs['model'] + ']' + ' ' + T_2m.attrs['title'],
              loc='left',
              fontsize=30)

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=4,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=4)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=4)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=4,
                                          alpha=0.5)

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=5)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(
        str(T_2m.coords['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(
        hours=T_2m.coords['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(int(T_2m.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (T_2m != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['T_2m'], cax=cax, orientation='horizontal')
        cb.ax.tick_params(labelsize='x-large')
        cb.set_label(u'°C', size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    #if(map_extent2[1]-map_extent2[0] < 25):
    #    small_city=True
    #if city:
    utl.add_city_and_number_on_map(ax,
                                   data=T_2m,
                                   map_extent=map_extent2,
                                   transform=datacrs,
                                   zorder=6,
                                   size=13,
                                   small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '最低温度_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(T_2m.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200,
                    bbox_inches='tight')
        plt.close()
    if (output_dir == None):
        plt.show()
Exemplo n.º 13
0
def draw_low_level_wind(uv=None,
                        map_extent=(50, 150, 0, 65),
                        regrid_shape=20,
                        add_china=True,
                        city=True,
                        south_China_sea=True,
                        output_dir=None,
                        Global=False):

    # set font
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # set figure
    plt.figure(figsize=(16, 9))

    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])
    datacrs = ccrs.PlateCarree()
    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if uv is not None:
        x, y = np.meshgrid(uv['lon'], uv['lat'])
        wsp = np.squeeze((uv['u'].values**2 + uv['v'].values**2)**0.5)
        z = wsp

        cmap = dk_ctables.cm_wind_speed_nws()
        cmap.set_under(color=[0, 0, 0, 0], alpha=0.0)
        plots['wsp'] = ax.pcolormesh(x,
                                     y,
                                     z,
                                     cmap=cmap,
                                     zorder=1,
                                     transform=datacrs,
                                     alpha=0.5)

    # draw -hPa wind bards
    if uv is not None:
        x, y = np.meshgrid(uv['lon'], uv['lat'])
        u = np.squeeze(uv['u'].values) * 2.5
        v = np.squeeze(uv['v'].values) * 2.5

    x, y = np.meshgrid(uv['lon'], uv['lat'])
    lw = 5 * wsp / wsp.max()
    plots['stream'] = ax.streamplot(x,
                                    y,
                                    u,
                                    v,
                                    density=2,
                                    color='r',
                                    linewidth=lw,
                                    zorder=100,
                                    transform=datacrs)

    spd_rtio = 0.03
    for i in range(0, len(uv['lon']) - 1, 10):
        for j in range(0, len(uv['lat']) - 1, 10):
            ax.arrow(x[j, i],
                     y[j, i],
                     u[j, i] * spd_rtio,
                     v[j, i] * spd_rtio,
                     color='black',
                     zorder=100,
                     transform=datacrs,
                     width=0.05)

    plt.title('[' + uv.attrs['model'] + '] ' + uv.attrs['level'] + ' 风场, 风速',
              loc='left',
              fontsize=30)

    #adapt to the map ratio
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)
    #adapt to the map ratio

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=2,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=2)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=2)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=2,
                                          alpha=0.5)

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=3)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(str(
        uv.coords['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(
        hours=uv.coords['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(int(uv.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (wsp is not None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['wsp'],
                          cax=cax,
                          orientation='horizontal',
                          extend='max',
                          extendrect=False)
        cb.ax.tick_params(labelsize='x-large')
        cb.set_label('(m/s)', size=20)
    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True
    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=4,
                            size=13,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '低层风_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(uv.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200,
                    bbox_inches='tight')
        plt.close()

    if (output_dir == None):
        plt.show()