示例#1
0
def draw_low_level_wind(uv=None,
                        wsp=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('[' + uv['model'] + '] ' + uv['lev'] + ' 风场, 风速',
              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=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)

    # define return plots
    plots = {}
    # draw mean sea level pressure
    if wsp is not None:
        x, y = np.meshgrid(wsp['lon'], wsp['lat'])
        z = np.squeeze(wsp['data'])

        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=90,
                                     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['udata']) * 2.5
        v = np.squeeze(uv['vdata']) * 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=100)

    x, y = np.meshgrid(uv['lon'], uv['lat'])
    lw = 5 * wsp['data'] / wsp['data'].max()
    plots['stream'] = ax.streamplot(x,
                                    y,
                                    uv['udata'],
                                    uv['vdata'],
                                    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)
            #ax.quiver(x[j,i], y[j,i], x[j,i]+u[j,i]*spd_rtio, y[j,i]+v[j,i]*spd_rtio, color='black', zorder=100, transform=datacrs)
    # 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))

    #http://earthpy.org/cartopy_backgroung.html
    #C:\ProgramData\Anaconda3\Lib\site-packages\cartopy\data\raster\natural_earth
    ax.background_img(name='RD', resolution='high')

    #forecast information
    bax = plt.axes([0.01, 0.835, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initial_time = pd.to_datetime(str(
        uv['init_time'])).replace(tzinfo=None).to_pydatetime()
    fcst_time = initial_time + timedelta(hours=uv['fhour'])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5,
             7.5,
             '起报时间: ' + initial_time.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(uv['fhour']) + '小时', size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (wsp != None):
        cax = plt.axes([0.11, 0.06, .86, .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=[0.85, 0.13, .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=[-0.01, 0.835, .1, .1],
                               which='nmc',
                               size='Xlarge')

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

    if (output_dir == None):
        plt.show()
示例#2
0
def draw_mslp_gust10m(gust=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('[' + mslp['model'] + '] ' + '海平面气压, ' + '逐6小时最大阵风 ',
              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=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)

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

    # draw -hPa geopotential height
    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=110)
        plt.clabel(plots['mslp'],
                   inline=1,
                   fontsize=15,
                   fmt='%.0f',
                   colors='black')

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

    #http://earthpy.org/cartopy_backgroung.html
    #C:\ProgramData\Anaconda3\Lib\site-packages\cartopy\data\raster\natural_earth
    ax.background_img(name='RD', resolution='high')

    #forecast information
    bax = plt.axes([0.01, 0.835, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initial_time = pd.to_datetime(str(
        mslp['init_time'])).replace(tzinfo=None).to_pydatetime()
    fcst_time = initial_time + timedelta(hours=mslp['fhour'])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5,
             7.5,
             '起报时间: ' + initial_time.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['fhour']) + '小时', size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (gust != None):
        cax = plt.axes([0.11, 0.06, .86, .02])
        cb = plt.colorbar(plots['gust'], cax=cax, orientation='horizontal')
        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=[0.85, 0.13, .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=[-0.01, 0.835, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '海平面气压_逐6小时最大风速_预报_' + '起报时间_' +
                    initial_time.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(mslp['fhour']) + '小时' + '.png',
                    dpi=200)

    if (output_dir == None):
        plt.show()
示例#3
0
def draw_mslp_gust10m(gust=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):

    # 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 = {}
    if gust is not None:
        x, y = np.meshgrid(gust['lon'], gust['lat'])
        z = np.squeeze(gust['data'].values)
        cmap = dk_ctables.cm_wind_speed_nws()
        cmap.set_under(color=[0, 0, 0, 0], alpha=0.0)
        z[z < 7.9] = np.nan
        plots['gust'] = ax.pcolormesh(x,
                                      y,
                                      z,
                                      cmap=cmap,
                                      vmin=7.9,
                                      vmax=65,
                                      zorder=1,
                                      transform=datacrs,
                                      alpha=0.5)

    # draw -hPa geopotential height
    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=2)
        plt.clabel(plots['mslp'],
                   inline=1,
                   fontsize=15,
                   fmt='%.0f',
                   colors='black')


#additional information
    plt.title('[' + mslp.attrs['model'] + '] ' + '海平面气压, ' + '逐' +
              '%i' % gust.attrs['t_gap'] + '小时最大阵风 ',
              loc='left',
              fontsize=30)

    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=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')
    ax.add_feature(cfeature.LAND, color='#F5E19F')
    ax.add_feature(cfeature.OCEAN)

    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.coords['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(int(mslp.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (gust != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['gust'],
                          cax=cax,
                          orientation='horizontal',
                          extend='max',
                          ticks=[
                              8.0, 10.8, 13.9, 17.2, 20.8, 24.5, 28.5, 32.7,
                              37, 41.5, 46.2, 51.0, 56.1, 61.3
                          ])
        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=5,
                            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 + '海平面气压_逐6小时最大风速_预报_' + '起报时间_' +
                    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()
示例#4
0
def draw_mslp_gust10m_uv10m(gust=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  # 步骤二(解决坐标轴负数的负号显示问题)

    # 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 = {}
    if gust is not None:
        x, y = np.meshgrid(gust['lon'], gust['lat'])
        z = np.squeeze(gust['data'].values)
        cmap = dk_ctables.cm_wind_speed_nws()
        cmap.set_under(color=[0, 0, 0, 0], alpha=0.0)
        z[z < 7.9] = np.nan
        plots['gust'] = ax.pcolormesh(x,
                                      y,
                                      z,
                                      cmap=cmap,
                                      vmin=7.9,
                                      vmax=65,
                                      zorder=1,
                                      transform=datacrs,
                                      alpha=0.5)

    ax.quiver(x,
              y,
              np.squeeze(uv10m['u10m'].values),
              np.squeeze(uv10m['v10m'].values),
              transform=datacrs,
              regrid_shape=40,
              width=0.001)

    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=2,
                                   alpha=0.5)
        cl = plt.clabel(plots['mslp'],
                        inline=1,
                        fontsize=15,
                        fmt='%.1f',
                        colors='black')
        for t in cl:
            t.set_path_effects([
                path_effects.Stroke(linewidth=3, foreground='white'),
                path_effects.Normal()
            ])
        #+画高低压中心
        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))
        #-画高低压中心


#additional information
    plt.title('[' + mslp.attrs['model'] + '] ' + '海平面气压, ' + '过去' +
              '%i' % gust.attrs['t_gap'] + '小时10米最大阵风和10米平均风',
              loc='left',
              fontsize=30)

    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=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')
    ax.add_feature(cfeature.LAND, color='#F5E19F')
    ax.add_feature(cfeature.OCEAN)

    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.coords['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(int(mslp.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (gust != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['gust'],
                          cax=cax,
                          orientation='horizontal',
                          extend='max',
                          ticks=[
                              8.0, 10.8, 13.9, 17.2, 20.8, 24.5, 28.5, 32.7,
                              37, 41.5, 46.2, 51.0, 56.1, 61.3
                          ])
        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=5,
                            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 + '海平面气压_逐6小时最大风速_预报_' + '起报时间_' +
                    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()
示例#5
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()