Example #1
0
def test_plot_all_map_vels():
    def gen_tracks():
        for fn in glob('tracks/*.json'):
            with open(fn, 'rb') as fp:
                try:
                    yield RKJSON(fp)
                except BadInputException:
                    pass

    tracks = list(gen_tracks())

    print "Considering {} tracks".format(len(tracks))

    lllat, urlat, lllon, urlon = Grid.calculate_bounds(tracks)

    m = Basemap(projection='cyl',
                llcrnrlon=lllon, llcrnrlat=lllat,
                urcrnrlon=urlon, urcrnrlat=urlat,
                resolution='h')
    m.drawcoastlines()

    for t in tracks:
        vels = t.calculate_vels()
        x, y = m(vels.lon, vels.lat)
        m.barbs(x, y, vels.u, vels.v)

    plt.annotate("Docklands", (144.948, -37.815))
    plt.annotate("Brunswick", (144.960, -37.767))
    plt.annotate("Brunswick East", (144.979, -37.769))
    plt.annotate("Richmond", (144.999, -37.819))
    plt.annotate("Fitzroy", (144.978, -37.800))

    plt.show()
Example #2
0
def test_plot_map_vels(json):
    track = RKJSON(json)
    vels = track.calculate_vels()

    lllat, lllon = min(track.lat) - 0.01, min(track.lon) - 0.01
    urlat, urlon = max(track.lat) + 0.01, max(track.lon) + 0.01

    print vels.bearing

    # find the centre point
    lat_0 = (urlat - lllat) / 2 + lllat
    lon_0 = (urlon - lllon) / 2 + lllon

    # FIXME: rsphere required because my Proj is screwy
    m = Basemap(projection='cyl',
                llcrnrlon=lllon, llcrnrlat=lllat,
                urcrnrlon=urlon, urcrnrlat=urlat,
                lat_0=lat_0, lon_0=lon_0,
                resolution='h')

    x, y = m(vels.lon, vels.lat)
    plt.annotate("Start", (x[0], y[0]))

    m.barbs(x, y, vels.u, vels.v) #, vels.anom, cmap=plt.get_cmap('RdBu_r'))
    plt.show()
Example #3
0
def test_plot_map_vels(xml):
    track = GPX(xml)
    vels = track.calculate_vels(smooth_vels=True)

    lllat, lllon = min(track.lat) - 0.01, min(track.lon) - 0.01
    urlat, urlon = max(track.lat) + 0.01, max(track.lon) + 0.01

    # find the centre point
    lat_0 = (urlat - lllat) / 2 + lllat
    lon_0 = (urlon - lllon) / 2 + lllon

    # FIXME: rsphere required because my Proj is screwy
    m = Basemap(projection='cyl',
                llcrnrlon=lllon, llcrnrlat=lllat,
                urcrnrlon=urlon, urcrnrlat=urlat,
                lat_0=lat_0, lon_0=lon_0,
                resolution='h')
                # rsphere=(6378137.00, 6356752.3142))

    x, y = m(vels.lon, vels.lat)

    m.drawcoastlines()
    m.drawrivers()
    m.barbs(x, y, vels.u, vels.v) #, vels.anom, cmap=plt.get_cmap('RdBu_r'))
    plt.show()
Example #4
0
def sfc_plot(starttime, endtime, variables, variablest, locations, met, xi, yi,
             xmin, xmax, ymin, ymax):
    ''' Script for plotting the mesonet data with wind barbs over a 
    county map in a given time interval 
    '''
    interval = int((endtime - starttime).total_seconds() / 300)
    z_max = np.max(met[variablest[1]])
    z_min = np.min(met[variablest[1]])
    levels = np.arange(z_min, z_max + 0.1, 0.1)
    shapefile = 'UScounties/UScounties'
    if not os.path.exists('%s' % (variables)):
        os.makedirs('%s' % (variables))
    for i in range(interval):
        time_selection = starttime + dt.timedelta(minutes=5 * i)
        zi = interpolate.griddata(
            (met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat']),
            met.ix[time_selection][variablest[1]], (xi, yi),
            method='linear')
        maps = Basemap(llcrnrlon=xmin,
                       llcrnrlat=ymin,
                       urcrnrlon=xmax,
                       urcrnrlat=ymax,
                       projection='cyl')
        maps.readshapefile(shapefile, name='counties')
        if (variables == 'dew_point'):
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r)
        if (variables == 'temperature'):
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.jet)
        if variables == 'rainfall':
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.YlGn)
        if ((variables == 'pressure') or (variables == 'wind_speed')
                or (variables == 'gust_speed')):
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth)
        c = plt.colorbar()
        c.set_label(variablest[0])
        maps.scatter(met.ix[time_selection]['Lon'],
                     met.ix[time_selection]['Lat'],
                     latlon=True,
                     marker='o',
                     c='b',
                     s=5)
        maps.barbs(met.ix[time_selection]['Lon'],
                   met.ix[time_selection]['Lat'],
                   met.ix[time_selection]['u'].values * 1.94384,
                   met.ix[time_selection]['v'].values * 1.94384,
                   latlon=True)
        maps.drawparallels(np.arange(31., 36, 1.),
                           color='0.5',
                           labels=[1, 0, 0, 0],
                           fontsize=10)
        maps.drawmeridians(np.arange(-104., -98., 1.),
                           color='0.5',
                           labels=[0, 0, 0, 1],
                           fontsize=10)
        plt.title(variablest[1])
        filename = '%s_%s.png' % (variables,
                                  time_selection.strftime('%Y%m%d_%H%M'))
        plt.tight_layout()
        plt.savefig(variables + '/' + filename, dpi=150)
        plt.clf()
Example #5
0
def sfc_plot(starttime, endtime, variables, variablest, locations, 
             met, xi, yi, xmin, xmax, ymin, ymax):
    ''' Script for plotting the mesonet data with wind barbs over a 
    county map in a given time interval 
    '''
    interval = int((endtime - starttime).total_seconds()/300)
    z_max = np.max(met[variablest[1]])                                                                  
    z_min = np.min(met[variablest[1]])                                                                  
    levels = np.arange(z_min, z_max+1, 1)
    shapefile = 'UScounties/UScounties'
    if not os.path.exists('%s' %(variables)):
        os.makedirs('%s' %(variables))
    for i in range(interval):
        time_selection = starttime + dt.timedelta(minutes=5*i)
        zi = interpolate.griddata((met.ix[time_selection]['Lon'], 
                                   met.ix[time_selection]['Lat']), 
                                   met.ix[time_selection][variablest[1]],
                                   (xi, yi), method='cubic')
        maps = Basemap(llcrnrlon=xmin, llcrnrlat=ymin, 
                       urcrnrlon=xmax, urcrnrlat=ymax, projection='cyl')
        maps.readshapefile(shapefile, name='counties')
        # mzi = np.ma.masked_array(zi,np.isnan(zi))
        # levels = np.arange(np.min(mzi), np.max(mzi)+1., 1)
        if (variables == 'dew_point'):
            maps.contourf(xi, yi, zi, np.arange(0.,21, 1), cmap=plt.cm.gist_earth_r)
            # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r)
        if (variables == 'relative_humidity'):
            maps.contourf(xi, yi, zi, np.arange(15.,51., 1.), cmap=plt.cm.gist_earth_r)
            # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r)
        if ((variables == 'temperature') or (variables== 'theta_e')):
            maps.contourf(xi, yi, zi, np.arange(24,40.5,0.5), cmap=plt.cm.jet)
            # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.jet)
        if variables == 'rainfall':
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.YlGn)
        if ((variables == 'pressure') or (variables == 'wind_speed') or 
            (variables == 'gust_speed')):
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth)
        c = plt.colorbar()  
        c.set_label(variablest[0])  
        maps.scatter(met.ix[time_selection]['Lon'], 
                     met.ix[time_selection]['Lat'], latlon=True, marker='o', c='b', s=5)
        maps.barbs(met.ix[time_selection]['Lon'], 
                   met.ix[time_selection]['Lat'], 
                   met.ix[time_selection]['u'].values*1.94384, 
                   met.ix[time_selection]['v'].values*1.94384, latlon=True)
        maps.drawparallels(np.arange(31.,36,1.), color='0.5',
            labels=[1,0,0,0], fontsize=10)
        maps.drawmeridians(np.arange(-104.,-98.,1.), color='0.5',
            labels=[0,0,0,1], fontsize=10)
        plt.title(variablest[1]) 
        filename = '%s_%s.png' % (variables, 
                                  time_selection.strftime('%Y%m%d_%H%M'))
        plt.tight_layout()
        plt.savefig(variables + '/' + filename, dpi=150)
        plt.clf()
def main():
    fname = '/Users/hhuang/Downloads/gfsanl_4_20160628_0000_000.nc'
    # fname = '/Users/hhuang/Downloads/fnl_20160628_00_00.grib2.nc'
    axis_lim = [60., 130., 15., 60.]
    lon_min, lon_max, lat_min, lat_max = [80., 130., 15., 50.]
    level = 500.
    time_str, lon, lat, t_var, hgt_var, u_var, v_var = read_gfs_data(
        fname, level=level, axis_lim=axis_lim)

    t_min, t_max, t_step = -20., 8., 2.
    t_level = np.linspace(t_min, t_max, (t_max - t_min) / t_step + 1)

    h_min, h_max, h_step = 560, 592., 4
    h_level = np.linspace(h_min, h_max, (h_max - h_min) / h_step + 1)

    projection = 'lcc'
    # projection = 'mill'
    resolution = 'l'
    lat_0 = (lat_min + lat_max) / 2.
    lon_0 = (lon_min + lon_max) / 2.
    area_thresh = 10000
    plt.figure(figsize=(10, 8))
    basemap = Basemap(
        llcrnrlon=lon_min, llcrnrlat=lat_min,
        urcrnrlon=lon_max, urcrnrlat=lat_max,
        lat_0=lat_0, lon_0=lon_0, projection=projection,
        area_thresh=area_thresh, resolution=resolution, ax=plt.gca())

    basemap.drawcoastlines(linewidth=1.25)
    basemap.drawcountries()
    basemap.drawmeridians(np.arange(0, 360, 10),
                          labels=[False, False, False, True])
    basemap.drawparallels(np.arange(-90, 90, 10),
                          labels=[True, False, False, False])
    x0, y0 = basemap(lon, lat)
    plt.title('%g' % level +
              ' hPa Synoptic Analysis with GSF Analysis Data\nUTC' + time_str)
    cf = basemap.contourf(
        x0, y0, t_var, vmin=t_min, vmax=t_max,
        cmap=cmaps.WhiteBlueGreenYellowRed,
        levels=t_level)
    #
    cb = basemap.colorbar(cf, ax=plt.gca(), ticks=t_level)
    cb.set_label('$\mathrm{Temperature(^\circ C)}$')
    #
    cs = basemap.contour(x0, y0, hgt_var, colors='b', levels=h_level)
    plt.clabel(cs, cs.levels, fmt='%g', fontsize=12, inline_spacing=10)
    basemap.barbs(x0[::5, ::5], y0[::5, ::5], u_var[::5, ::5], v_var[::5, ::5],
                  length=5)
    plt.show()
def plot(gridArray, windu, windv, title):
    lon = []
    lat = []
    for i in range(0, 161):
        lat.append(15 + i * 0.25)
    for i in range(0, 281):
        lon.append(70 + i * 0.25)
    x, y = np.meshgrid(lon, lat)

    m = Basemap(llcrnrlon=70, llcrnrlat=15, urcrnrlon=140, urcrnrlat=55, resolution='l', area_thresh=100)
    x, y = m(x, y)
    fig = plt.figure(figsize=(10, 7), dpi=200)
    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.spines['bottom'].set_color('none')
    ax.spines['top'].set_color('none')

    my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', color.pm25, 256)
    norm = mpl.colors.Normalize(0, 500)
    m.contourf(x, y, gridArray, 500, cmap=my_cmap, norm=norm)  # ,norm=norm

    skip = slice(None, None, 5)
    m.barbs(x[skip, skip], y[skip, skip], windu[skip, skip], windv[skip, skip], length=3.5,
            sizes=dict(emptybarb=0, spacing=0.2, height=0.5), barb_increments=dict(half=2, full=4, flag=20),
            linewidth=0.2, color='black')

    plt.title('Concentration of PM2.5(China) Forecast - ' + title + '\nL126_H13 Regional Air Quality Model [In trial] @Louis-He',
              loc='left', fontsize=11)
    m.drawparallels(np.arange(0, 65, 10), labels=[1, 0, 0, 0], fontsize=8, linewidth=0.5, color='dimgrey',
                    dashes=[1, 1])
    m.drawmeridians(np.arange(65., 180., 10), labels=[0, 0, 0, 1], fontsize=8, linewidth=0.5, color='dimgrey',
                    dashes=[1, 1])
    m.drawcoastlines(linewidth=0.5)
    m.drawstates(linewidth=0.4, color='dimgrey')
    m.readshapefile('cnhimap', 'states', drawbounds=True, linewidth=0.5, color='black')
    ax2 = fig.add_axes([0.92, 0.16, 0.018, 0.67])
    clevs1 = [0, 35, 75, 115, 150, 250, 500]
    cmap1 = mpl.colors.ListedColormap([[0, 228 / 255, 0], [1, 1, 0],
                                       [1, 126 / 255, 0], [1, 0, 0],
                                       [153 / 255, 0, 76 / 255], [126 / 255, 0, 35 / 255]])
    norm1 = mpl.colors.BoundaryNorm(clevs1, cmap1.N)
    cbar1 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap1, spacing='uniform', norm=norm1, ticks=clevs1,
                                      orientation='vertical', drawedges=False)
    cbar1.ax.set_ylabel('pm2.5(ug/m**3)', size=8)
    cbar1.ax.tick_params(labelsize=8)
    plt.savefig('output/' + title + '.png', bbox_inches='tight')
    fig = fig.clear()
    plt.clf()
    plt.close()
Example #8
0
def plot_gini_grid_barbs(gini_grid, box = [-110, -70, 20, 52], resolution = 'l',
                   parallels = None,
                   meridians = None,
                   vmin = None, vmax = None,
                   fld = 'IR', title = None,
                   degrade = 5, u='u', v='v'):
    m = Basemap(llcrnrlon = box[0] ,llcrnrlat = box[2] , urcrnrlon = box[1],
                   urcrnrlat = box[3] , projection = 'mill', area_thresh =1000 ,
                   resolution = resolution)
    
    x, y = m(gini_grid.fields['lon']['data'], gini_grid.fields['lat']['data'])
    # create figure.
    if parallels == None:
        parallels = np.linspace(10,50, 9)
    if meridians == None:
        meridians = np.linspace(-110, -80,7)
    m.drawparallels(parallels, labels=[1,1,0,0])
    m.drawmeridians(meridians,labels=[0,0,0,1]) 
    pc = m.pcolormesh(x, y , gini_grid.fields[fld]['data'][0,:], cmap=plt.get_cmap('gray'),
                      vmin = vmin, vmax = vmax)
    qq = m.barbs(x[::degrade,::degrade], y[::degrade,::degrade], 
                  gini_grid.fields[u]['data'][0,::degrade,::degrade], 
                  gini_grid.fields[v]['data'][0,::degrade,::degrade])

    plt.title(title)
    m.drawcoastlines(linewidth=1.25)
    m.drawstates()
    plt.colorbar(mappable=pc, label = 'Counts')
def DrawUVMap(lons, lats, uu, vv, title=""):
    m = Basemap(llcrnrlon=90,
                llcrnrlat=0,
                urcrnrlon=180,
                urcrnrlat=40,
                resolution='c',
                epsg=3415)
    lon, lat = np.meshgrid(lons, lats)
    xi, yi = m(lon, lat)
    m.barbs(xi, yi, uu, vv, length=3, linewidth=0.6, pivot='middle')
    # cs = m.pcolor(xi, yi, np.squeeze(tlml))
    m.drawparallels(np.arange(0., 50., 5), labels=[1, 0, 0, 0], fontsize=10)
    m.drawmeridians(np.arange(90., 181., 5), labels=[0, 0, 0, 1], fontsize=10)
    m.drawcoastlines()
    m.drawcountries()
    # cbar = m.colorbar(cs, location='bottom', pad="10%")
    plt.title(title)
    plt.show()
Example #10
0
def sfc_plot(starttime, endtime, variables, variablest, locations, 
             met, xi, yi, xmin, xmax, ymin, ymax):
    ''' Script for plotting the mesonet data with wind barbs over a 
    county map in a given time interval 
    '''
    interval = int((endtime - starttime).total_seconds()/300)
    z_max = np.max(met[variablest[1]])                                                                  
    z_min = np.min(met[variablest[1]])                                                                  
    levels = np.arange(z_min, z_max+0.1, 0.1)
    shapefile = 'UScounties/UScounties'
    if not os.path.exists('%s' %(variables)):
        os.makedirs('%s' %(variables))
    for i in range(interval):
        time_selection = starttime + dt.timedelta(minutes=5*i)
        zi = interpolate.griddata((met.ix[time_selection]['Lon'], 
                                   met.ix[time_selection]['Lat']), 
                                   met.ix[time_selection][variablest[1]],
                                   (xi, yi), method='linear')
        maps = Basemap(llcrnrlon=xmin, llcrnrlat=ymin, 
                       urcrnrlon=xmax, urcrnrlat=ymax, projection='cyl')
        maps.readshapefile(shapefile, name='counties')
        if (variables == 'dew_point'):
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r)
        if (variables == 'temperature'):
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.jet)
        if variables == 'rainfall':
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.YlGn)
        if ((variables == 'pressure') or (variables == 'wind_speed') or 
            (variables == 'gust_speed')):
            maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth)
        c = plt.colorbar()  
        c.set_label(variablest[0])  
        maps.scatter(met.ix[time_selection]['Lon'], 
                     met.ix[time_selection]['Lat'], marker='o', c='b', s=5)
        maps.barbs(met.ix[time_selection]['Lon'], 
                   met.ix[time_selection]['Lat'], 
                   met.ix[time_selection]['u'].values, 
                   met.ix[time_selection]['v'].values)
        plt.title(variablest[1]) 
        filename = '%s_%s.png' % (variables, 
                                  time_selection.strftime('%Y%m%d_%H%M'))
        plt.tight_layout()
        plt.savefig(variables + '/' + filename, dpi=150)
        plt.clf()
Example #11
0
def CO2nWind(file,outputdir):
  """
  Outputs plots of CO2 in the lowest level and 10m winds
  """
  import matplotlib
  matplotlib.use('Agg')
  import numpy as np
  import sys
  from netCDF4 import Dataset
  import matplotlib.pyplot as plt
  from mpl_toolkits.basemap import Basemap
  # read in file and vars
  f = Dataset(file,'r')
  wrfeta = f.variables['ZNU'][0][:]
  times = f.variables['Times'][:]
  wrflats = f.variables['XLAT'][0][:]
  wrflons = f.variables['XLONG'][0][:]
  var = f.variables['CO2_ANT'][:,0,:,:]
  u = f.variables['U'][:,0,:,:]
  v = f.variables['V'][:,0,:,:]
  # destagger u/v
  u = (u[:,:,:-1] + u[:,:,1:])/2.
  v = (v[:,:-1,:] + v[:,1:,:])/2.

  # four corners of domain
  wrflat_s = wrflats[0,len(wrflats)-1]
  wrflat_n = wrflats[len(wrflats)-1,len(wrflons[0])-1]
  wrflon_w = wrflons[0,0]
  wrflon_e = wrflons[len(wrflats)-1,len(wrflons[0])-1]

  z = 0 # assuming lowest level of model

  # set up map
  map = Basemap(projection='merc',llcrnrlon=wrflon_w,urcrnrlon=wrflon_e,llcrnrlat=wrflat_s,urcrnrlat=wrflat_n,resolution='i')
  map.drawstates()
  map.drawcounties()
  map.drawcoastlines()
  x,y = map(wrflons,wrflats)

  # loop through times
  for t in range(len(times)):
    timestr = ''.join(times[t,:])
    map.drawstates(color='gray',linewidth=1)
    map.drawcounties(color='white')
    map.drawcoastlines(color='gray',linewidth=1)
    plt1 = map.pcolormesh(x,y,var[t,:,:],vmin=380,vmax=450)
    #plt1 = map.pcolormesh(x,y,var[t,:,:],vmin=np.amin(var),vmax=np.amax(var))
    winds = map.barbs(x[::20,::20],y[::20,::20],u[t,::20,::20]*1.94,v[t,::20,::20]*1.94,length=6,color='white') # *1.94 to convert m/s to knots (barb convention)
    colorbar = map.colorbar(plt1,"right", size="5%",pad="2%")
    colorbar.set_label(f.variables['CO2_ANT'].description+' '+f.variables['CO2_ANT'].units)
    plt.title('WRF output valid: '+timestr)
    plt.savefig(outputdir+'/%03d_' % (t) +timestr+'_CO2_wind.png')
    plt.clf()
def DrawEcUV(uu=[], vv=[]):
    lats = np.arange(0, 41, 0.75)  # 纬度间隔
    lons = np.arange(99.75, 180.5, 0.75)
    m = Basemap(llcrnrlon=90,
                llcrnrlat=0,
                urcrnrlon=180,
                urcrnrlat=40,
                resolution='c',
                epsg=3415)
    lon, lat = np.meshgrid(lons, lats)
    xi, yi = m(lon, lat)
    m.drawcoastlines(color='tan')
    # print(xi.shape())
    # print(yi.shape())
    b = m.barbs(xi, yi, uu, vv)
    plt.show()
Example #13
0
        date2 = dt.strftime('%d %b %Y @ %H%M UTC')
        plt.title('Dynamic Tropopause (%s PVU)\n' \
            'Potential Temperature (K)\n' \
            '%s' % (PVU, date2), fontsize=18)

        # Hack to fix colorbar not plotting on first time through
        if initial:
            initial = False
            continue

        # Save the image
        imgfile = os.path.join(IMGPATH, 'dt_%03i_%s_%sUTC.png' % (CLON,
            date, hour))
        #plt.set_frame_on(False)
        plt.savefig(imgfile, dpi=100, bbox_inches='tight')

        imgfile2 = os.path.join(IMGPATH2, 'dt_%03i_%s_%sUTC.png' % (CLON,
            date, hour))

        WINDBARBS=False
        # Create the image with wind barbs (if chosen)
        if WINDBARBS:
            ax1.set_title('Dynamic Tropopause (%s PVU)\n' \
                'Potential Temperature (K) & Wind Barbs (kts)\n' \
                '%s' % (PVU, date2), fontsize=18)

            m.barbs(x[::iskip, ::jskip], y[::iskip, ::jskip],
                u[::iskip, ::jskip], v[::iskip, ::jskip], pivot='middle',
                length=5.5, zorder=10, ax=ax1)
            plt.savefig(imgfile2, dpi=100, bbox_inches='tight')
Example #14
0
                      cmap=plt.cm.Greens)
    print 'contour', datetime.now() - timer

    timer = datetime.now()
    ## Wind Barbs
    units = 'm/s'
    if units == 'm/s':
        HALF = 2.5
        FULL = 5
        FLAG = 25
    if units == 'mph':
        HALF = 2.5
        FULL = 5
        FLAG = 25
    barbs = m.barbs(x,y,u,v,length=6,barbcolor="k",\
                       flagcolor='r',linewidth=.5,\
                        barb_increments=dict(half=HALF, full=FULL, flag=FLAG))

    print 'barbs', datetime.now() - timer

    timer = datetime.now()
    ## MesoWest Wind Barbs
    units = 'm/s'
    if units == 'm/s':
        HALF = 2.5
        FULL = 5
        FLAG = 25
    if units == 'mph':
        HALF = 2.5
        FULL = 5
        FLAG = 25
Example #15
0
lon = np.squeeze(file.variables['XLONG'][:,:]);
lat = np.squeeze(file.variables['XLAT'][:,:]);

U,V = np.multiply(U,1.94384449),np.multiply(V,1.94384449); 
XA,YA = m(lon,lat); 

os.chdir('/home/disk/manta14/awsmith/umcm/umcm_runs/katrina_awo_gfs10/output/')
file = Dataset('umwmout_2005-08-29_12:00:00.nc','r'); 
SWH = np.squeeze(file.variables['swh'][:,:]);
lonw = np.squeeze(file.variables['lon'][:,:]); 
latw = np.squeeze(file.variables['lat'][:,:]); 

XW,YW = m(lonw,latw); 

m.contourf(XW,YW,SWH,np.arange(0,31,1),cmap='jet')
m.barbs(XA[0:-1:8,0:-1:8],YA[0:-1:8,0:-1:8],U[0:-1:8,0:-1:8],V[0:-1:8,0:-1:8],barbcolor='k',flagcolor='r',linewidth=0.5)
plt.title('Hurricane Katrina (2005) SWH (m) & Surface Winds (kt), August 29 1200 UTC',fontsize=8)
## Add land mask over 
m.fillcontinents(color='w')
m.drawcountries()
m.drawstates()

## Add ocean mask over
plt.figure(num=5,figsize=(6,6))
m = Basemap(llcrnrlon=-95.,llcrnrlat=20.,urcrnrlon=-80.,urcrnrlat=35.,projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60.,resolution ='l',area_thresh=1000.)
m.drawcoastlines()
m.drawcountries()
m.drawparallels(np.arange(20,36,2),labels=[1,0,0,0])
m.drawmeridians(np.arange(-95,-78,2),labels=[0,0,0,1])
import mpl_toolkits.basemap
REFD_OM = mpl_toolkits.basemap.maskoceans(lon,lat,REFD,'True','l');
Example #16
0
    bmap.drawparallels(range(-90, 91, 30),
                       linewidth=1,
                       labels=[1, 0, 0, 0],
                       color='b')
    bmap.drawmeridians(range(-180, 180, 45),
                       linewidth=1,
                       labels=[0, 0, 0, 1],
                       color='b',
                       rotation=45)  # Rotate the axis text labels by 45 deg

    # Plot barbs, choosing every downsample_factor data point rather then all
    # of them
    bmap.barbs(x[::downsample_factor, ::downsample_factor],
               y[::downsample_factor, ::downsample_factor],
               merdianalWinds[t, ::downsample_factor, ::downsample_factor],
               zonalWinds[t, ::downsample_factor, ::downsample_factor],
               pivot='middle',
               length=4,
               zorder=2,
               barb_increments=barb_increments)

    bmap.contourf(x,
                  y,
                  pressure[t, :, :],
                  levels=color_levels,
                  extend='both',
                  cmap=cm.plasma,
                  zorder=1)

    cbar = plt.colorbar()
    cbar.set_label('Pressure (KPa)')
    cbar.set_ticks(color_ticks)
def plot_tdwr(scan):
    print scan
    fig, axes = plt.subplots(1, 1, figsize=(5.5, 10))
    #for v, ctable, ax in zip(('N0Q', 'N0U'), ('NWSReflectivity', 'NWSVelocity'), axes):

    ax = axes
    #scan = 'Level3_SLC_%s_20160912_0000.nids' % v
    date = datetime.strptime(scan[-18:-5], '%Y%m%d_%H%M')
    FILE = path + scan

    f = Level3File(FILE)

    # Pull the data out of the file object (this stuff is in 8-bit)
    datadict = f.sym_block[0][0]

    # Turn into an array, then mask
    data = f.map_data(datadict['data']) # I'm confident this maps the data to floats with units of m/s
    data = ma.array(data)
    data[np.isnan(data)] = ma.masked

    # Convert knots to m/s
    data = data * .5144

    # Grab azimuths and calculate a range based on number of gates
    az = np.array(datadict['start_az'] + [datadict['end_az'][-1]])
    rng = np.linspace(0, f.max_range, data.shape[-1] + 1)

    # Convert az, range to a lat/lon
    g = Geod(ellps='clrk66') # This is the type of ellipse the earth is projected on. 
                             # There are other types of ellipses you can use,
                             # but the differences will be small
    center_lat = np.ones([len(az),len(rng)])*f.lat
    center_lon = np.ones([len(az),len(rng)])*f.lon
    az2D = np.ones_like(center_lat)*az[:,None]
    rng2D = np.ones_like(center_lat)*np.transpose(rng[:, None])*1000
    lon, lat, back = g.fwd(center_lon, center_lat, az2D, rng2D)

    # Convert az,range to x,y 
    # (use these variables if don't want to plot on a basemap. 
    # Value is range from the radar.)
    xlocs = rng * np.sin(np.deg2rad(az[:, np.newaxis]))
    ylocs = rng * np.cos(np.deg2rad(az[:, np.newaxis]))

    # Create Basemap
    domain = get_domain('salt_lake_valley')
    top_right_lat = domain['top_right_lat']+.3
    top_right_lon = domain['top_right_lon']
    bot_left_lat = domain['bot_left_lat']-.2
    bot_left_lon = domain['bot_left_lon']-.2

    ## Map in cylindrical projection
    m = Basemap(resolution='i',projection='cyl',\
        llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\
        urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,)
    maps = ['ESRI_Imagery_World_2D',    # 0
            'ESRI_StreetMap_World_2D',  # 1
            'NatGeo_World_Map',         # 2
            'NGS_Topo_US_2D',           # 3
            'Ocean_Basemap',            # 4
            'USA_Topo_Maps',            # 5
            'World_Imagery',            # 6
            'World_Physical_Map',       # 7
            'World_Shaded_Relief',      # 8
            'World_Street_Map',         # 9
            'World_Terrain_Base',       # 10
            'World_Topo_Map'            # 11
           ]

    ## Draw high resolution background image from ESRI
    m.arcgisimage(service=maps[8], xpixels = 1000, verbose= False)
    m.drawcoastlines()
    m.drawstates()

    # get mesowest winds
    mesowest_time = date.strftime('%Y%m%d%H%M')
    a = get_mesowest_radius_winds(mesowest_time, '10')

    ## Now plot data on basemap

    # This uses the same colorbar as the NWS Velocity color scheme
    norm, cmap = ctables.registry.get_with_steps(ctable, -20, 2.5)
    this = m.pcolormesh(lon, lat, data, norm=norm, cmap=cmap)
    bar = plt.colorbar(this,ax=ax,orientation='horizontal',shrink=.8,pad=.01)
    bar.ax.set_xlabel('Radial Velocity ($\mathregular{m s^{-1}}$)',fontsize=10)
    ax.set_title(scan)
    #ax.set_aspect('equal', 'datalim')
    # Add MesoWest wind barbs
    u,v = wind_spddir_to_uv(a['WIND_SPEED'],a['WIND_DIR'])
    m.barbs(a['LON'],a['LAT'],u,v,
            length=5.5,                
            barb_increments=dict(half=2.5, full=5, flag=25),
            sizes=dict(spacing=0.15, height=0.3, emptybarb=.1))
    # Location of TDWR and other observing stations for reference
    m.scatter(-111.93,40.9669, s=75, c='w',zorder=40)               # TDWR
    plt.savefig(out_dir+"__"+scan[0:-5]+'.png',bbox_inches='tight')

    fig, axes = plt.subplots(1, 1, figsize=(5.5, 10))
    ax = axes
    # This uses the brown/green colorbar used in my MS Thesis
    m.arcgisimage(service=maps[8], xpixels = 1000, verbose= False)
    thesis_color = m.pcolormesh(lon,lat,data,cmap="BrBG_r",vmax=10,vmin=-10)
    bar = plt.colorbar(thesis_color,orientation='horizontal',shrink=.8,pad=.01,
                       label=r'Radial Velocity ($\mathregular{m s^{-1}}$)')
    # Add Mesowest Wind Barbs
    u,v = wind_spddir_to_uv(a['WIND_SPEED'],a['WIND_DIR'])
    m.barbs(a['LON'], a['LAT'], u, v,
            length=5.5,   
            barb_increments=dict(half=2.5, full=5, flag=25),
            sizes=dict(spacing=0.15, height=0.3, emptybarb=.1))
    # Location of TDWR and other observing stations for reference
    m.scatter(-111.93,40.9669, s=75, c='w',zorder=40)               # TDWR
    ax.set_title(scan)
    
    plt.savefig(out_dir+scan[0:-5]+'.png',bbox_inches='tight')
Example #18
0
m5.readshapefile(
    "CHN_adm_shp//china-shapefiles-master//china_nine_dotted_line",
    'nine_dotted',
    drawbounds=True)
m5.readshapefile("CHN_adm_shp//CHN_adm3", "states",
                 drawbounds=False)  #全国图不显示地级市界(含地级市内容)
lon, lat = np.meshgrid(lon, lat)
x, y = m5(lon, lat)
wind_slice = (slice(None, None, 9), slice(None, None, 9))
cs = m5.barbs(x[wind_slice],
              y[wind_slice],
              u_700[wind_slice],
              v_700[wind_slice],
              pivot='middle',
              color='black',
              barb_increments={
                  'half': 2,
                  'full': 4,
                  'flag': 20
              },
              length=5,
              alpha=0.8)
m5.drawparallels(np.arange(0, 55., 5.),
                 labels=[1, 0, 0, 0],
                 fontsize=6,
                 linewidth=0.4,
                 alpha=0.8)  #坐标轴为经纬度
m5.drawmeridians(np.arange(70., 140., 5.),
                 labels=[0, 0, 0, 1],
                 fontsize=6,
                 linewidth=0.4,
Example #19
0
import numpy as np

wrf_out_file = "wrfout_v2_Lambert.nc"

ds_lon = gdal.Open('NETCDF:"'+wrf_out_file+'":XLONG')
ds_lat = gdal.Open('NETCDF:"'+wrf_out_file+'":XLAT')

ds_u = gdal.Open('NETCDF:"'+wrf_out_file+'":U10')
ds_v = gdal.Open('NETCDF:"'+wrf_out_file+'":V10')

map = Basemap(llcrnrlon=-93.7, llcrnrlat=28., urcrnrlon=-66.1, urcrnrlat=39.5,
              resolution = 'l',
              projection='lcc', lat_1=30., lat_2=60., lat_0=34.83158, lon_0=-98.)

x, y = map(ds_lon.ReadAsArray()[1], ds_lat.ReadAsArray()[1])


u = ds_u.ReadAsArray()[1]
v = ds_v.ReadAsArray()[1]

yy = np.arange(0, y.shape[0], 4)
xx = np.arange(0, x.shape[1], 4)

points = np.meshgrid(yy, xx) 

map.contourf(x, y, np.sqrt(u*u + v*v), alpha = 0.4) 
map.barbs(x[points], y[points], u[points], v[points]) 

map.drawcoastlines(color = '0.15')
plt.show()
    #clevs=[14,17,20,23,26,29,32,35,38,41,44,47,50]

    clevs = np.arange(980,1040,4)
    cs =m.contour(x,y,ps,clevs,colors='k',linewidths=1.3,animated=True,alpha=0.9) 
    plt.clabel(cs, inline=1, fontsize=10,colors='k',fmt='%1.0f',inline_spacing=8,rightside_up=True, use_clabeltext=True)
    #m.readshapefile('/home/vkvalappil/Data/shapeFiles/uae/ARE_adm1','uae',drawbounds=True, zorder=None, linewidth=1.0, color='k', antialiased=1, ax=None, default_encoding='utf-8')
    #m.readshapefile('/home/vkvalappil/Data/EGU_paper/continents/continent','uae',drawbounds=True, zorder=None, linewidth=1.0, color='k', antialiased=1, ax=None, default_encoding='utf-8')
    skip=(slice(None,None,15),slice(None,None,15))
    #urot,vrot,xv,yv = m.rotate_vector(uwnd,vwnd,lon,lat,returnxy=True)
    #Q = m.quiver(x[skip],y[skip],uwnd[skip],vwnd[skip],units='xy',color='b',headwidth=10,headlength=25)
    #Q = m.quiver(xv[skip],yv[skip],urot[skip],vrot[skip],units='xy',color='b',headwidth=10,headlength=25)
    
    #qk = plt.quiverkey(Q, 0.95, 1.05, 25, '25 m/s', labelpos='W')
    
    #ua, va, xv, yv = m.transform_vector(g_uu,g_vv,lon1,lat1,lon1.shape[0],lon1.shape[0],returnxy=True)
    #m.barbs(x[skip],y[skip],uwnd[skip],vwnd[skip], length=7, color='k',)
    m.barbs(x[skip],y[skip],uwnd[skip],vwnd[skip],length=5,sizes=dict(emptybarb=0, spacing=0.05, height=0.5,length=3),barbcolor='k',alpha=0.6)

    m.drawparallels(np.arange(0.,50.,15.), labels=[1,0,0,0], linewidth=0.1)
    m.drawmeridians(np.arange(20.,85.,15.), labels=[0,0,0,1],linewidth=0.1)
    #m.drawmapboundary(fill_color='white') 
    m.drawcoastlines(linewidth=0.5,color='r') ; 
    #m.drawcountries(linewidth=0.5,color='r')
    # m.drawstates(linewidth=0.25)
    #cbar=m.colorbar(cs,location='right', pad='5%') ; cbar.set_ticks([clevs]) ; cbar.ax.tick_params(labelsize=8) 
    #(cbar.set_label('m/s')) ;
    #(plt.title('Average Temperature DJF ',fontsize=12,color='k')); 
    plt.savefig('/home/vkvalappil/Data/EGU_paper/'+fnme+'.png', dpi=100);
    plt.close()
#################################################################################################################################
Example #21
0
z_min = np.min(met[to_plot])
levels = np.arange(z_min, z_max + 0.1, 0.1)

zi = interpolate.griddata(
    (met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat']),
    met.ix[time_selection][to_plot], (xi, yi),
    method='linear')
shapefile = 'UScounties/UScounties'
maps = Basemap(llcrnrlon=xmin,
               llcrnrlat=ymin,
               urcrnrlon=xmax,
               urcrnrlat=ymax,
               projection='cyl')
maps.readshapefile(shapefile, name='counties')
maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r)
c = plt.colorbar()
c.set_label('2 m Temperature')
maps.scatter(met.ix[time_selection]['Lon'],
             met.ix[time_selection]['Lat'],
             marker='o',
             c='b',
             s=5,
             latlon=True)
maps.barbs(met.ix[time_selection]['Lon'],
           met.ix[time_selection]['Lat'],
           met.ix[time_selection]['u'].values * 1.94384,
           met.ix[time_selection]['v'].values * 1.94384,
           latlon=True)
plt.title(to_plot)
plt.tight_layout()
plt.show()
Example #22
0
def make_plot(cffield,lfield,lfield2,ufld,vfld,params):
# Get the latitude and longitude points

    print(params['time_index'])
    
    lats, lons = latlon_coords(cffield)

    # Get the basemap object

    #Original large domain ---    
    bm = Basemap(projection='lcc',width=3000*550,height=3000*375,
             resolution='i',lat_1=-32.8,lat_2=-32.8,lat_0=-32.8,lon_0=-67.0)

    #Cordoba inset ---- 
    #bm = Basemap(projection='lcc',width=1500*550,height=1500*375,
    #          resolution='i',lat_1=-32.2,lat_2=-32.2,lat_0=-32.2,lon_0=-65.0) 
    
    #Mendoza inset ---- 
    #bm = Basemap(projection='lcc',width=1500*550,height=1500*375,
    #          resolution='i',lat_1=-33.2,lat_2=-33.2,lat_0=-33.2,lon_0=-69.0) 
    
    # Create a figure
    fig = plt.figure(figsize=(12,9))

    # Add geographic outlines
    bm.drawcoastlines(linewidth=0.75)
    bm.drawstates(linewidth=1.)
    bm.drawcountries(linewidth=1.)

    # Convert the lats and lons to x and y.  Make sure you convert the lats and lons to
    # numpy arrays via to_np, or basemap crashes with an undefined RuntimeError.
    x, y = bm(to_np(lons), to_np(lats))


    if lfield is not None:
        CS=bm.contour(x, y, to_np(lfield), 10, colors="black", levels=params['llevels'],linewidths=1.0)
        plt.clabel(CS, inline=1, fontsize=12, fmt='%d')

    if lfield2 is not None:
        CS=bm.contour(x, y, to_np(lfield2), 10, colors="dimgrey", levels=params['llevels2'],linewidths=2.25)
        #plt.clabel(CS, inline=1, fontsize=12, fmt='%d')
    
    if ufld is not None:
        bm.barbs(x[::params['skip'],::params['skip']], 
                 y[::params['skip'],::params['skip']], 
                 to_np(ufld[::params['skip'],::params['skip']]),
                 to_np(vfld[::params['skip'],::params['skip']]), length=5, linewidth=0.75, zorder=10)

    if not('lalpha' in params):
        params['lalpha']=None
        

    # Draw the contours and filled contours
    bm.contourf(x, y, to_np(cffield), 10, cmap=get_cmap(params['ccmap']), levels=params['clevels'], extend='both',
               alpha=params['lalpha'])


    parallels = np.arange(-50.,-10.,2.)
    # labels = [left,right,top,bottom]
    bm.drawparallels(parallels,labels=[False,True,False,False],linewidth=0.5,dashes=[2,2])
    meridians = np.arange(-90.,-50.,2.)
    bm.drawmeridians(meridians,labels=[False,False,False,True],linewidth=0.5,dashes=[2,2])

    # Add a color bar
    plt.colorbar(shrink=.62, extend='both')

    timediff=params['times'][params['time_index']]-params['times'][0]
    timediff_secs=int(timediff.total_seconds()//3600)

    plt.title(titlestr+' '+cffield.description+' ('+cffield.units+')\n'+
             "Initialized: "+params['times'][0].strftime('%Y-%m-%d %H:%M')+"Z Forecast hour: "+'{:03d}'.format(timediff_secs)+" Valid: "+params['times'][params['time_index']].strftime('%Y-%m-%d %H:%M')+'Z')

    for key in landmark_dict.keys():
        kx,ky=bm(landmark_dict[key][0],landmark_dict[key][1])
        plt.text(kx,ky,key,fontsize=12,
                        ha='center',va='center',color='b')
    #fig.figimage(im, fig.bbox.xmax-290, fig.bbox.ymin,zorder=10)


#----
#    def draw_screen_poly( lats, lons, bm):
#             x, y = bm( lons, lats )
#             xy = zip(x,y)
#             poly = Polygon( xy, facecolor='black', alpha=0.45 )
#             plt.gca().add_patch(poly)
#            
#    lats = [ -33, -30, -30, -33 ]
#    lons = [ -65, -65, -62, -62 ]
#    draw_screen_poly( lats, lons, bm )

#----

#Drawing a 200-km range ring around S-PolKa site----
    def shoot(lon, lat, azimuth, maxdist=None):
        """Shooter Function
        Original javascript on http://williams.best.vwh.net/gccalc.htm
        Translated to python by Thomas Lecocq
        """
        glat1 = lat * np.pi / 180.
        glon1 = lon * np.pi / 180.
        s = maxdist / 1.852
        faz = azimuth * np.pi / 180.
 
        EPS= 0.00000000005
        if ((np.abs(np.cos(glat1))<EPS) and not (np.abs(np.sin(faz))<EPS)):
            alert("Only N-S courses are meaningful, starting at a pole!")
 
        a=6378.13/1.852
        f=1/298.257223563
        r = 1 - f
        tu = r * np.tan(glat1)
        sf = np.sin(faz)
        cf = np.cos(faz)
        if (cf==0):
            b=0.
        else:
            b=2. * np.arctan2 (tu, cf)
 
        cu = 1. / np.sqrt(1 + tu * tu)
        su = tu * cu
        sa = cu * sf
        c2a = 1 - sa * sa
        x = 1. + np.sqrt(1. + c2a * (1. / (r * r) - 1.))
        x = (x - 2.) / x
        c = 1. - x
        c = (x * x / 4. + 1.) / c
        d = (0.375 * x * x - 1.) * x
        tu = s / (r * a * c)
        y = tu
        c = y + 1
        while (np.abs (y - c) > EPS):
 
            sy = np.sin(y)
            cy = np.cos(y)
            cz = np.cos(b + y)
            e = 2. * cz * cz - 1.
            c = y
            x = e * cy
            y = e + e - 1.
            y = (((sy * sy * 4. - 3.) * y * cz * d / 6. + x) *
                  d / 4. - cz) * sy * d + tu
 
        b = cu * cy * cf - su * sy
        c = r * np.sqrt(sa * sa + b * b)
        d = su * cy + cu * sy * cf
        glat2 = (np.arctan2(d, c) + np.pi) % (2*np.pi) - np.pi
        c = cu * cy - su * sy * cf
        x = np.arctan2(sy * sf, c)
        c = ((-3. * c2a + 4.) * f + 4.) * c2a * f / 16.
        d = ((e * cy * c + cz) * sy * c + y) * sa
        glon2 = ((glon1 + x - (1. - c) * d * f + np.pi) % (2*np.pi)) - np.pi    
 
        baz = (np.arctan2(sa, b) + np.pi) % (2 * np.pi)
 
        glon2 *= 180./np.pi
        glat2 *= 180./np.pi
        baz *= 180./np.pi
 
        return (glon2, glat2, baz)


    def equi(bm, centerlon, centerlat, radius, *args, **kwargs):
        glon1 = centerlon
        glat1 = centerlat
        X = []
        Y = []
        for azimuth in range(0, 360):
            glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius)
            X.append(glon2)
            Y.append(glat2)
        X.append(X[0])
        Y.append(Y[0])
 
        #m.plot(X,Y,**kwargs) #Should work, but doesn't...
        X,Y = bm(X,Y)
        plt.plot(X,Y,**kwargs)

    radii = [200]
 
    # S-PolKa:
    centerlon = -63.978435
    centerlat = -31.715689
    for radius in radii:
        equi(bm, centerlon, centerlat, radius,lw=1.5,color='k')

    # San Rafael:
    centerlon = -68.285522
    centerlat = -34.587997
    for radius in radii:
        equi(bm, centerlon, centerlat, radius,lw=1.5,color='k')

    # Mendoza:
    centerlon = -68.7987
    centerlat = -32.8278
    for radius in radii:
        equi(bm, centerlon, centerlat, radius,lw=1.5,color='k')

#----

    os.system('mkdir -p '+outpath+'/'+params['modfld'])
    plt.savefig(outpath+'/'+params['modfld']+'/model.'+params['modname']+'.'+params['times'][0].strftime('%Y%m%d%H%M')+'.'+'{:03d}'.format(timediff_secs)+'_'+params['modfld']+'.png',dpi=225,bbox_inches='tight')
ymin = np.min(met['Lat'])
ymax = np.max(met['Lat'])
xi, yi = np.meshgrid(np.linspace(xmin, xmax, 200), 
                     np.linspace(ymin, ymax, 200))

to_plot = '2 m Temperature'
z_max   = np.max(met[to_plot])                                                                    
z_min   = np.min(met[to_plot])                                                                    
levels  = np.arange(z_min, z_max+0.1, 0.1)


zi = interpolate.griddata((met.ix[time_selection]['Lon'], 
                           met.ix[time_selection]['Lat']), 
                           met.ix[time_selection][to_plot], 
                           (xi, yi), method='linear')
shapefile = 'UScounties/UScounties'
maps = Basemap(llcrnrlon=xmin, llcrnrlat=ymin, 
               urcrnrlon=xmax, urcrnrlat=ymax, projection='cyl')
maps.readshapefile(shapefile, name='counties')
maps.contourf(xi, yi, zi, levels, cmap = plt.cm.gist_earth_r)
c = plt.colorbar()  
c.set_label('2 m Temperature')  
maps.scatter(met.ix[time_selection]['Lon'], 
             met.ix[time_selection]['Lat'], marker='o', c='b', s=5, latlon=True)
maps.barbs(met.ix[time_selection]['Lon'], 
           met.ix[time_selection]['Lat'], 
           met.ix[time_selection]['u'].values*1.94384, 
           met.ix[time_selection]['v'].values*1.94384, latlon=True)
plt.title(to_plot)             
plt.tight_layout()
plt.show()
Example #24
0
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 14:05:43 2015

@author: Kolb
"""

# http://stackoverflow.com/questions/11487797/python-matplotlib-basemap-overlay-small-image-on-map-plot

from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap
import Image
from numpy import arange

lats = arange(26,29,0.5)
lons = arange(-90,-87,0.5)

m = Basemap(projection='cyl',llcrnrlon=min(lons)-2,llcrnrlat=min(lats)-2,
            urcrnrlon=max(lons)+2,urcrnrlat=max(lats)+2,resolution='i')

x,y = m(lons,lats)
u,v, = arange(0,51,10),arange(0,51,10)
barbs = m.barbs(x,y,u,v)
m.drawcoastlines(); m.drawcountries(); m.drawstates()
Example #25
0
m = Basemap(width=10000000,height=10000000,lon_0=-90,lat_0=45.,lat_ts=45,
            resolution='l',projection='stere')
x,y = m(lons,lats)
# transform from spherical to map projection coordinates (rotation
# and interpolation).
nxv = 25; nyv = 25
udat, vdat, xv, yv = m.transform_vector(u,v,lons1,lats1,nxv,nyv,returnxy=True)
# create a figure, add an axes.
fig=plt.figure(figsize=(8,6))
ax = fig.add_axes([0.1,0.1,0.8,0.8])
# plot color-filled contours over map
levs = np.arange(960,1051,4)
cs1 = m.contour(x,y,p,levs,colors='k',linewidths=0.5)
cs2 = m.contourf(x,y,p,levs)
# plot barbs.
m.barbs(xv,yv,udat,vdat,length=6,barbcolor='k',flagcolor='r',linewidth=0.5)
# plot colorbar for pressure
m.colorbar(pad='12%') # draw colorbar
# draw coastlines
m.drawcoastlines()
# draw parallels
m.drawparallels(np.arange(0,81,20),labels=[1,1,0,0])
# draw meridians
m.drawmeridians(np.arange(-180,0,20),labels=[0,0,0,1])
plt.title('Surface Wind Barbs and Pressure (NH)')

# stereogrpaphic projection (SH).
# 'flip_barb' flag is automatically set for SH data, so that
# barbs point toward lower pressure (in both Hemisphere).
m = Basemap(width=10000000,height=10000000,lon_0=-90,lat_0=-45.,lat_ts=-45,
            resolution='l',projection='stere')
lats = np.linspace(-90, 90, 10)

lons, lats = np.meshgrid(lons, lats)

v10 = np.ones((lons.shape)) * 15
u10 = np.zeros((lons.shape))

u10_rot, v10_rot, x, y = map.rotate_vector(u10, v10, lons, lats, returnxy=True)

ax = fig.add_subplot(121)
ax.set_title('Without rotation')

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#cc9955', lake_color='aqua', zorder = 0)
map.drawcoastlines(color = '0.15')


map.barbs(x, y, u10, v10,
    pivot='middle', barbcolor='#333333')

ax = fig.add_subplot(122)
ax.set_title('Rotated vectors')

map.drawmapboundary(fill_color='#89999F')
map.fillcontinents(color='#ddaa66', lake_color='#89999F', zorder = 0)
map.drawcoastlines(color = '0.15')

map.barbs(x, y, u10_rot, v10_rot,
    pivot='middle', barbcolor='#ff7777')

plt.show()
Example #27
0
                   yoffset=80000,
                   fontsize=12)
 map.drawparallels(np.arange(-90, 90, 10),
                   labels=[1, 0, 0, 0],
                   fontsize=12)
 CS = map.contourf(xx,
                   yy,
                   spd,
                   np.arange(8, 81, 8),
                   cmap=cm.GMT_haxby_r,
                   extend='max')
 nskip = 4
 brb = map.barbs(xx[::nskip, ::nskip],
                 yy[::nskip, ::nskip],
                 ugrid[::nskip, ::nskip],
                 vgrid[::nskip, ::nskip],
                 length=5,
                 barbcolor='k',
                 flagcolor='r',
                 linewidth=0.5)
 plot_tracks(map, fcstracks, obtracks, ifhr, ifhrinc)
 cb = plt.colorbar(CS, orientation='horizontal')
 cb.ax.set_xlabel('wind speed (knots)')
 if run == 'gfsenkf':
     plt.title('T574 GFS/EnKF 10-m wind cntl %s-hr fcst for %s from %s' %\
             (fhr,strmid,date))
     plt.savefig(os.path.join(pngdir,'10mwind%s_%s_gfsenkf_cntrl_f%03i.png'%\
             (date,strmid,ifhr)))
 else:
     plt.title('T574 GFS/Opnl 10-m wind cntl %s-hr fcst for %s from %s' %\
             (fhr,strmid,date))
     plt.savefig(os.path.join(pngdir,'10mwind%s_%s_gfsopnl_cntrl_f%03i.png'%\
map.drawcountries(linewidth=1, color="#444444", zorder=5)
map.drawstates(linewidth=0.66, color="#444444", zorder=4)
map.drawmapboundary

x, y = map(X, Y)
cf = map.contour(x, y, temperature_plot, levels=clevs, extend="both", zorder=1, linewidths=2)
plt.clabel(cf, inline=1, fontsize=10)

# plot wind vectors on projection grid.
# first, shift grid so it goes from -180 to 180 (instead of 0 to 360
# in longitude).  Otherwise, interpolation is messed up.
ugrid, newlons = shiftgrid(180.0, u_plot, lons, start=False)
vgrid, newlons = shiftgrid(180.0, v_plot, lons, start=False)
# transform vectors to projection grid and plot windbarbs.
uproj, vproj, xx, yy = map.transform_vector(ugrid, vgrid, newlons, lats, 41, 41, returnxy=True)
barbs = map.barbs(xx, yy, uproj, vproj, length=5, barbcolor="k", flagcolor="r", linewidth=0.5)
# Title
ax1.set_title(str(levelh) + " hPa temperature and wind barbs")

# <codecell>

# Temperature advection plot
cbar_min = -0.0001
cbar_max = 0.0001
cfint = 0.00001
cflevs = np.arange(cbar_min, cbar_max + cfint - (cfint / 2), cfint)
ncolors = np.size(cflevs) - 1
cmap = cm.get_cmap("jet")
djet = cmap_whitezero(cmap, ncolors, 1, -1)

Example #29
0
m5.readshapefile(
    "CHN_adm_shp//china-shapefiles-master//china_nine_dotted_line",
    'nine_dotted',
    drawbounds=True)
m5.readshapefile("CHN_adm_shp//CHN_adm3", "states",
                 drawbounds=False)  #全国图不显示地级市界(含地级市内容)
lon, lat = np.meshgrid(lon, lat)
x, y = m5(lon, lat)
wind_slice = (slice(None, None, 1), slice(None, None, 1))
cs = m5.barbs(x[wind_slice],
              y[wind_slice],
              u_700[wind_slice],
              v_700[wind_slice],
              color='black',
              barb_increments={
                  'half': 2,
                  'full': 4,
                  'flag': 20
              },
              length=5,
              alpha=0.8,
              zorder=5)
m5.drawparallels(np.arange(25, 35., 3.),
                 labels=[1, 0, 0, 0],
                 fontsize=6,
                 linewidth=0.4,
                 alpha=0.8)  #坐标轴为经纬度
m5.drawmeridians(np.arange(70., 140., 5.),
                 labels=[0, 0, 0, 1],
                 fontsize=6,
                 linewidth=0.4,
Example #30
0
def plot_gridded_ensemble(gfsx, contour_units=None, max_level=None,
        barb_units='knot', cols=2, save_path=None, save_fmt='svg'):
    """
    Plots the average windspeed deviation of ensemble forecast members over
    the published GSF forecast for each grid point and forecast time.
    The result is (for each forecast time) a color filled contour plot
    indicating the ensemble deviation superimposed over the usual wind barbs
    with the published GFS forecast vectors.

    Parameters:
    -----------
    fcst_gfsx: xray.Dataset
        Dataset with the GFS forecast for windspeed (uwnd and vwnd) and
        ensemble forecast deviation (other forecast variables will be ignored
        if present).
    contour_units: str
        The units in which to plot the ensemble spread indicator (heatmap). If
        specified, the data sets current unit must be convertible into the
        desired unit by slocum.lib.units. If not specified the exsiting units in
        the data set will be used.
    max_level: float
        Heatmap/contour plot maximum level. Minimum level is assumed to be 0.
        Values greater tha max_level will be mapped onto the max_level color.
        If not specified, the maximum value found in the data set will be used
        as the upper end of the color bar.
    barb_units: str
        Units in which to plot the GFS wind speed/direction forecast data (wind
        bars). If specified, the data sets current unit must be convertible
        into the desired unit by slocum.lib.units.
    cols: int
        Number of columns for subplot layout.
    save_path: str
        If specified the plot will be saved into this directory with file
        name ``ens_<bounding box>_<t0>.svg`` where *bounding box* is
        specified as *ll_lat, ll_lon - ur_lat, ur_lon*.  If not specified or
        ``None`` the plot will be displayed interactively.
    save_fmt: str
        Format under which to save the image (only relevant if *save_path* is
        specified). Can be any image file extension that plt.savefig() will
        recognize as a valid format.
    """
    # adjust units as requested:
    for v in (conv.UWND, conv.VWND):
        units.convert_units(gfsx[v], barb_units)
    if contour_units:
        units.convert_units(gfsx[conv.ENS_SPREAD_WS], contour_units)
    if not max_level:
        max_level = gfsx[conv.ENS_SPREAD_WS].max()

    if isinstance(gfsx, np.datetime64): # True is gfsx has not been packed
        f_times = gfsx[conv.TIME].values
    else:                               # time variable has int offsets
        f_times = xray.conventions.decode_cf_datetime(
                gfsx['time'], gfsx['time'].attrs['units'])

    lats = gfsx[conv.LAT].values
    lons = gfsx[conv.LON].values

    # Basemap.transform_vector requires lats and lons each to be in ascending
    # order:
    lat_inds = range(len(lats))
    lon_inds = range(len(lons))
    if NautAngle(lats[0]).is_north_of(NautAngle(lats[-1])):
        lat_inds.reverse()
        lats = lats[lat_inds]
    if NautAngle(lons[0]).is_east_of(NautAngle(lons[-1])):
        lon_inds.reverse()
        lons = lons[lon_inds]

    # determine layout:
    fig_width_inches = 10
    plot_aspect_ratio = (abs(lons[-1] - lons[0]) /
                         float(abs(lats[-1] - lats[0])))
    rows = int(np.ceil(gfsx.dimensions[conv.TIME] / float(cols)))
    fig_height_inches = (fig_width_inches / (float(cols) * plot_aspect_ratio)
                         * rows + 2)
    fig = plt.figure(figsize=(fig_width_inches, fig_height_inches))
    fig.suptitle("GFS wind forecast in %s and "
                 "ensemble wind speed deviation" % barb_units,
                 fontsize=12)
    grid = AxesGrid(fig, [0.01, 0.01, 0.95, 0.93],
                    nrows_ncols=(rows, cols),
                    axes_pad=0.8,
                    cbar_mode='single',
                    cbar_pad=0.0,
                    cbar_size=0.2,
                    cbar_location='bottom',
                    share_all=True,)

    # size for lat/lon labels, timestamp:
    label_fontsize = 'medium' if cols <= 2 else 'small'
    # format string for colorbar labels:
    decimals = max(0, int(2 - np.floor(np.log10(max_level))))
    cb_label_fmt = '%.' + '%d' % decimals + 'f'

    # heatmap color scaling and levels
    spread_levels = np.linspace(0., max_level, 50)

    m = Basemap(projection='merc', llcrnrlon=lons[0], llcrnrlat=lats[0],
            urcrnrlon=lons[-1], urcrnrlat=lats[-1], resolution='l')

    for t_step, t in enumerate(f_times):

        ax = grid[t_step]
        m.drawcoastlines(ax=ax)
        m.drawparallels(lats,labels=[1,0,0,0], ax=ax,
                fontsize=label_fontsize)
        m.drawmeridians(lons,labels=[0,0,0,1], ax=ax,
                fontsize=label_fontsize, rotation='vertical')

        # ensemble spread heatmap:
        x, y = m(*np.meshgrid(lons, lats))
        data = gfsx[conv.ENS_SPREAD_WS]
        data = data.indexed(**{conv.TIME: t_step})
        data = data.indexed(**{conv.LAT: lat_inds})
        data = data.indexed(**{conv.LON: lon_inds}).values
        cs = m.contourf(x, y, data, spread_levels, ax=ax, extend='max',
                cmap=cm.jet)

        # wind barbs:
        u = gfsx[conv.UWND].indexed(**{conv.TIME: t_step})
        u = u.indexed(**{conv.LAT: lat_inds})
        u = u.indexed(**{conv.LON: lon_inds}).values
        v = gfsx[conv.VWND].indexed(**{conv.TIME: t_step})
        v = v.indexed(**{conv.LAT: lat_inds})
        v = v.indexed(**{conv.LON: lon_inds}).values
        # transform from spherical to map projection coordinates (rotation
        # and interpolation).
        nxv = len(lons)
        nyv = len(lats)
        barb_length = 8 - cols
        barb_width = 1.2 - (cols / 10.)
        udat, vdat, xv, yv = m.transform_vector(
                u, v, lons, lats, nxv, nyv, returnxy=True)
        # plot barbs.
        m.barbs(xv, yv, udat, vdat, ax=ax, length=barb_length, barbcolor='w',
                flagcolor='r', linewidth=barb_width)

        ax.set_title(t.astype('M8[h]').item().strftime('%Y-%m-%dT%H:%MZ'),
                fontsize=label_fontsize)

    cbar = fig.colorbar(cs, cax=grid.cbar_axes[0], orientation='horizontal',
            format=cb_label_fmt)
    attr = gfsx[conv.ENS_SPREAD_WS].attrs
    cb_label = attr.get('long_name',
            'Average (normalized) wind speed delta (ens - gfs)')
    s = ["%s = %s" % (k, attr[k]) for k in attr if k != 'long_name']
    if s:
        cb_label = "%s (%s)" % (cb_label, ', '.join(s))
    cbar.set_label(cb_label)

    if save_path:
        t0_str = f_times[0].astype('M8[h]').item().strftime('%Y%m%dT%H%MZ')
        file_name = "ens_%s%s-%s%s_%s.%s" % (
                NautAngle(lats[0]).named_str(conv.LAT),
                NautAngle(lons[0]).named_str(conv.LON),
                NautAngle(lats[-1]).named_str(conv.LAT),
                NautAngle(lons[-1]).named_str(conv.LON),
                t0_str, save_fmt)
        plt.savefig(os.path.join(save_path, file_name), bbox_inches='tight')
    else:
        plt.show()

    plt.close()
   putstuffhere = 1
   
else:
   # Plot geostrophic vorticity and wind at either the upper or lower level
   CS1 = m.contourf(x,y,var_upper,cmap=plt.cm.hot_r,levels=cflevs_upper, extend='both',zorder=1)
   cbar = plt.colorbar(CS1, shrink=0.95, orientation='horizontal',extend='both')
   CS2 = m.contour(x, y, var_upper, cflevs_upper, colors='k', linewidths=0.5)
   cbar.set_ticks(cflevs_upper_ticks)
   clabs = ['%i K' % f for f in cflevs_upper_ticks]
   cbar.ax.set_yticklabels(clabs, size=10)      
if plot_barbs == "true":
   # Rotate and interpolate wind from lat/lon grid to map projection grid.
   uproj_lower,vproj_lower, xx_lower, yy_lower = m.transform_vector(ugrid_lower,vgrid_lower,newlons,lats,41,41,returnxy=True)
   uproj_upper,vproj_upper, xx_upper, yy_upper = m.transform_vector(ugrid_upper,vgrid_upper,newlons,lats,41,41,returnxy=True)  
   uproj_mid,vproj_mid, xx_mid, yy_mid = m.transform_vector(ugrid_mid,vgrid_mid,newlons,lats,41,41,returnxy=True)     
   barbs = m.barbs(xx_upper,yy_upper,uproj_upper,vproj_upper,length=5,barbcolor='k',flagcolor='r',linewidth=1.0)
ax1.set_title(titletext1)
save_name = figname + "_01.png"
plt.savefig(save_name, bbox_inches='tight')

# Figure 2
fig = plt.figure(figsize=(8., 16./golden), dpi=128)   # New figure
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
if map_projection == 'ortho':
   m = Basemap(projection='ortho', lat_0 = 50, lon_0 = 260,
          resolution = 'l', area_thresh = 1000.,ax=ax1)
elif map_projection == 'lcc':
   #   m = Basemap(llcrnrlon=-125.5,llcrnrlat=15.,urcrnrlon=-30.,urcrnrlat=50.352,\
   m = Basemap(llcrnrlon=-120.0,llcrnrlat=20.,urcrnrlon=-60.0,urcrnrlat=50.0,\
       rsphere=(6378137.00,6356752.3142),\
       resolution='l',area_thresh=1000.,projection='lcc',\
Example #32
0
def make_wind_map(ax, ax_ctr, grb_1, grb_2, jump, t_zero, use_knots=True):
    """
    Convention for barbs:
      - Each half of a flag depicts five knots
      - Each full flag depicts 10 knots
      - Each pennant (filled triangle) depicts 50 knots[4]

      http://de.wikipedia.org/wiki/Windgeschwindigkeit

      1 kn      = 1 sm/h (exakt)           = 1,852 km/h (exakt)    = 0,514 m/s
      1 m/s     = 3,6 km/h (exakt)         = 1,944 kn              = 2,237 mph
      1 km/h    = 0,540 kn                 = 0,278 m/s             = 0,621 mph
      1 mph     = 1,609344 km/h (exakt)    = 0,8690 kn             = 0,447 m/s
    """
    u = grb_1[0]
    v = grb_2[0]
    if use_knots == True:
        u = u * 1.944
        v = v * 1.944
    wind_v = np.sqrt(u**2. + v**2.)
    print "min: %d,    max: %d" % (wind_v.min(), wind_v.max())

    cur_lats = grb_1[1]
    cur_lons = grb_2[2]

    cur_t = 6.0 + (ax_ctr * (jump * 6.0))
    time_delta = datetime.timedelta(hours=cur_t)
    cur_time = t_zero + time_delta

    # create polar stereographic Basemap instance.
    m = Basemap(
        projection='cyl'  # Stereographic
        #               , lon_0 = 0.
        #               , lat_0 = 90.
        #               , lat_ts = 0.
        ,
        llcrnrlat=cur_lats.min(),
        urcrnrlat=cur_lats.max(),
        llcrnrlon=cur_lons.min(),
        urcrnrlon=cur_lons.max()
        #               , rsphere=6371200.
        ,
        resolution='l',
        area_thresh=10000,
        ax=ax)

    # draw parallels.
    parallels = np.arange(0., 90, 10.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
    # draw meridians
    meridians = np.arange(0., 180., 10.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)

    ny = wind_v.shape[0]
    nx = wind_v.shape[1]
    lons, lats = m.makegrid(nx,
                            ny)  # get lat/lons of ny by nx evenly space grid.
    x, y = m(lons, lats)  # compute map proj coordinates.

    # draw filled contours.
    #clevs = [0,1,2.5,5,7.5,10,15,20,30,40,50,70,100,150,200,250,300,400,500,600,750]
    #cs = m.contourf(x,y,wind_v,clevs,cmap=cm.s3pcpn)

    barbs = m.barbs(x,
                    y,
                    u,
                    v,
                    length=6,
                    barbcolor='k',
                    flagcolor='r',
                    linewidth=0.5,
                    zorder=999)

    # draw coastlines, state and country boundaries, edge of map.
    m.drawcoastlines(color="Gray", zorder=0)
    #m.drawmapboundary(fill_color='aqua')
    #m.drawstates()
    #m.drawcountries()
    m.fillcontinents(color='coral', lake_color='aqua', alpha=0.2, zorder=1)

    # add colorbar.
    #cbar = m.colorbar(cs,location='bottom',pad="5%")
    #cbar.set_label('m/s')

    # add title
    cur_ti_str = cur_time.strftime('%Y-%m-%d, %H:%M')
    ax.set_title('t_0 + %ih | %s' % (cur_t, cur_ti_str))
Example #33
0
from osgeo import gdal
import numpy as np


map = Basemap(llcrnrlon=-93.7, llcrnrlat=28., urcrnrlon=-66.1, urcrnrlat=39.5,
              projection='lcc', lat_1=30., lat_2=60., lat_0=34.83158, lon_0=-98.)

ds = gdal.Open("../sample_files/wrf.tiff")
lons = ds.GetRasterBand(4).ReadAsArray()
lats = ds.GetRasterBand(5).ReadAsArray()
u10 = ds.GetRasterBand(1).ReadAsArray()
v10 = ds.GetRasterBand(2).ReadAsArray()

x, y = map(lons, lats)

yy = np.arange(0, y.shape[0], 4)
xx = np.arange(0, x.shape[1], 4)

points = np.meshgrid(yy, xx)

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#cc9955', lake_color='aqua', zorder = 0)
map.drawcoastlines(color = '0.15')

map.barbs(x[points], y[points], u10[points], v10[points], 
    pivot='middle', barbcolor='#333333')


plt.show()

Example #34
0
                                        lats1,
                                        nxv,
                                        nyv,
                                        returnxy=True)
# create a figure, add an axes.
fig = plt.figure(figsize=(8, 6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# plot color-filled contours over map
levs = np.arange(960, 1051, 4)
cs1 = m.contour(x, y, p, levs, colors='k', linewidths=0.5)
cs2 = m.contourf(x, y, p, levs)
# plot barbs.
m.barbs(xv,
        yv,
        udat,
        vdat,
        length=6,
        barbcolor='k',
        flagcolor='r',
        linewidth=0.5)
# plot colorbar for pressure
cax = plt.axes([0.875, 0.1, 0.05, 0.8])  # setup colorbar axes.
plt.colorbar(cax=cax)  # draw colorbar
plt.axes(ax)  # make the original axes current again
# draw coastlines
m.drawcoastlines()
# draw parallels
m.drawparallels(np.arange(0, 81, 20), labels=[1, 1, 0, 0])
# draw meridians
m.drawmeridians(np.arange(-180, 0, 20), labels=[0, 0, 0, 1])
plt.title('Surface Wind Barbs and Pressure (NH)')
Example #35
0
    cs = m.pcolormesh(x, y, (valores), shading='flat', cmap=plt.cm.jet)
    m.drawcoastlines(color='w', linewidth=3.5)
    m.drawcoastlines(color='k', linewidth=3.0)
    levels = np.arange(900, 1100, 4)
    CS = plt.contour(x, y, (valores), colors='k', levels=levels)
    plt.clabel(CS, inline=1, fontsize=8, inline_spacing=5)
    m.drawmapboundary()
    m.drawparallels(np.arange(-90., 120., 10.), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180., 180., 10.), labels=[0, 0, 0, 1])

    wind_u = file_1.select(name='10 metre U wind component')[0].values
    wind_v = file_1.select(name='10 metre V wind component')[0].values

    m.barbs(reduction(x),
            reduction(y),
            reduction(wind_u),
            reduction(wind_v),
            rounding=False,
            sizes=dict(emptybarb=0.05, spacing=0.2, height=0.3))
    plt.title('Análisis a presión superficial (mbar) para el día ' +
              str(uu)[6:8] + ' del mes ' + str(uu)[4:6] + ' del año ' +
              str(uu)[0:4] + ' a las ' + str(uu)[8:10] + ' UTC')
    #m.streamplot(x, y, wind_u, wind_v, color='blue', density=[5, 5])
    plt.colorbar(cs, orientation='vertical')
    print(uu)

    plt.savefig(
        '/media/edwin/6F71AD994355D30E/Edwin/Maestría Meteorologia/Tesis/cartas_gfs/'
        + str(uu)[0:10] + '.png',
        figsize=(20, 10),
        dpi=199)
    plt.close()
Example #36
0
            urcrnrlon=15.,
            urcrnrlat=59.,
            projection='lcc',
            lat_1=40.,
            lat_2=50.,
            lon_0=-50.,
            resolution='l')

# Calculate positions of vectors on map projection
x, y = m(lon, lat)

# Calculate the orientation of the vectors
x1, y1 = m(lon + u, lat + v)
u_map, v_map = x1 - x, y1 - y

# Rescale the magnitudes of the vectors...
mag_scale = numpy.hypot(u_map, v_map) / numpy.hypot(u, v)
u_map /= mag_scale
v_map /= mag_scale

# Draw barbs
m.barbs(x, y, u_map, v_map, length=7, color='red')

# Draw some grid lines for reference
parallels = numpy.arange(-80., 90, 20.)
meridians = numpy.arange(0., 360., 20.)
m.drawparallels(parallels)
m.drawmeridians(meridians)
m.drawcoastlines(linewidth=0.5)

plt.show()
Example #37
0
              lat_0=0, lon_0=0)

lons = np.linspace(-180, 180, 8)
lats = np.linspace(-90, 90, 8)

v10 = np.ones((lons.shape)) * 15
u10 = np.zeros((lons.shape))

u10, v10 = np.meshgrid(u10, v10)

u10_rot, v10_rot, x_rot, y_rot = map.transform_vector(u10, v10, 
                                                      lons, lats, 
                                                      15, 15, 
                                                      returnxy=True)

map.drawmapboundary(fill_color='#9999FF')
map.fillcontinents(color='#ddaa66', lake_color='#9999FF', zorder = 0)
map.drawcoastlines(color = '0.15')

#Drawing the original points
lons, lats = np.meshgrid(lons, lats)
x, y = map(lons, lats)
map.barbs(x, y, u10, v10, 
    pivot='middle', barbcolor='#333333')

#Drawing the rotated & interpolated points
map.barbs(x_rot, y_rot, u10_rot, v10_rot, 
    pivot='middle', barbcolor='#ff5555')

plt.show()
Example #38
0
    llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\
    urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,)

plt.figure(figsize=[16*1.5,10*1.5])
m.drawcoastlines()
m.drawcountries()
m.drawstates()

x,y = m(lon,lat)    

# Now plot wind and geopotential height
m.pcolormesh(x,y,speed,cmap="gist_stern_r")
cb = plt.colorbar(shrink=.7)
cb.set_label("Wind Speed (m/s)")

interval = 50
m.barbs(x[::50,::50],y[::50,::50],U[::50,::50],V[::50,::50])  

# Just becuase we can, add 500 mb Geopotential Height Contours on top.
CS = m.contour(x,y,Z,colors='black',levels=np.arange(0,6000,60),linewidths=3)
plt.clabel(CS, inline=1, fontsize=12,fmt='%1.0f')      


validDate = grb.validDate

plt.title('HRRR Analysis Valid '+validDate.strftime('%Y-%b-%d %H:%M:%S')+'\n'+
          str(grb.level)+' mb '+Zname+'and Wind')

plt.savefig('HRRR_anl_'+str(mb)+'.png',dpi=300,bbox_inches='tight')
plt.show()
Example #39
0
def plotBarb(x,y,u,v,llLon=None,llLat=None,urLon=None,
             urLat=None, res='i', dl=10.,cmapName='jet_r',
             title=None, xlab='Longitude',ylab='Latitude',
             clab=None, plotMagnitude=False, outputFile=None):
    """
    Plot vector data on a grid using wind barbs. Options exist (plotMagnitude)
    to add a filled contour map indicating the magnitude of the data,
    though wind barbs already perform that action through the use of
    barbs and flags.
    """

    pyplot.rcdefaults()
    pyplot.figure()
    if (len(x.shape)<2)and(len(y.shape)<2):
        [xx,yy] = meshgrid(x,y)
    else:
        xx = x
        yy = y

    if llLon is not None:
        llcrnrlon = llLon
    else:
        llcrnrlon = x.min()

    if llLat is not None:
        llcrnrlat = llLat
    else:
        llcrnrlat = y.min()

    if urLon is not None:
        urcrnrlon = urLon
    else:
        urcrnrlon = x.max()

    if urLat is not None:
        urcrnrlat = urLat
    else:
        urcrnrlat = y.max()

    meridians = arange(dl*floor(llcrnrlon/dl), dl*ceil(urcrnrlon/dl), dl)
    parallels = arange(dl*floor(llcrnrlat/dl), dl*ceil(urcrnrlat/dl), dl)
    m = Basemap(projection='cyl',
                resolution=res,
                llcrnrlon=llcrnrlon,
                urcrnrlon=urcrnrlon,
                llcrnrlat=llcrnrlat,
                urcrnrlat=urcrnrlat)

    if plotMagnitude:
        mag = sqrt(u*u+v*v)
        m.contourf(xx, yy, ws, levels, extend='both', cmap=cmap)
        cb = pyplot.colorbar(shrink=0.5, orientation='horizontal', extend='both',
                     ticks=levels[::2], pad=0.05)

        cb.set_label(clab, fontsize=10)
        if cb.orientation=='horizontal':
            for t in cb.ax.get_xticklabels():
                t.set_fontsize(8)

    dx = numpy.mean(numpy.diff(lon))
    xdim = urcrnrlon - llcrnrlon
    nx = xdim/dx
    skip = int(numpy.round(nx/25))
    m.barbs(xx[0::skip,0::skip],yy[0::skip,0::skip],
            u[0::skip,0::skip],v[0::skip,0::skip],
            length=5,linewidth=0.5)

    m.drawcoastlines()

    # Save the image:
    if outputFile:
        pyplot.savefig(outputFile)
    else:
        pyplot.show()
Example #40
0
def make_plev_map(filename=None,
                  level=None,
                  cfld=None,
                  cscl=None,
                  coff=None,
                  colormap=None,
                  cmin=None,
                  cmax=None,
                  cbunits=None,
                  nc=None,
                  z1fld=None,
                  z1levs=None,
                  z1off=None,
                  z1scl=None,
                  z2fld=None,
                  z2levs=None,
                  z2off=None,
                  z2scl=None,
                  ufld=None,
                  vfld=None,
                  titletext=None,
                  filepat=None):



    wrf=xr.open_dataset(filename,engine='pynio')

    run=filename.split('/')[-1]
    init=datetime.strptime(run.split('_')[0],'%Y%m%d%H')
    fhr=run.split('.')[1]
    valid=init+timedelta(hours=int(fhr))


    level=float(level)*100.
    terr=wrf['HGT_P0_L1_GLC0'].values
    hgt=wrf['HGT_P0_L100_GLC0'].sel(lv_ISBL0=level,method='nearest').values

    lon=wrf['gridlon_0'].values
    lat=wrf['gridlat_0'].values
    ug=wrf[ufld].sel(lv_ISBL0=level,method='nearest').values
    vg=wrf[vfld].sel(lv_ISBL0=level,method='nearest').values
    u=ug*np.cos(wrf['gridrot_0'])-vg*np.sin(wrf['gridrot_0'])
    v=ug*np.sin(wrf['gridrot_0'])+vg*np.cos(wrf['gridrot_0'])

    if cfld=='SPD':
        c=cscl*np.sqrt(u**2+v**2)+coff
    elif cfld=='AVO':
        f=2.*7.29e-5*np.sin(lat* np.pi / 180.)
        dudx,dudy=np.gradient(u,3000.,edge_order=2)
        dvdx,dvdy=np.gradient(v,3000.,edge_order=2)
        c=cscl*(dvdx-dudy+f)+coff
    else:
        c=cscl*wrf[cfld].sel(lv_ISBL0=level).values+coff
    z1=(z1scl*wrf[z1fld].sel(lv_ISBL0=level).values)+z1off
    z2=(z2scl*wrf[z2fld].sel(lv_ISBL0=level).values)+z2off
    fields=titletext+str(int(level/100.))+' hPa'

    c=np.ma.masked_where(terr > hgt,c)
    u=np.ma.masked_where(terr > hgt,u)
    v=np.ma.masked_where(terr > hgt,v)
    z1=np.ma.masked_where(terr > hgt,z1)
    z2=np.ma.masked_where(terr > hgt,z2)
    mask=np.ones_like(terr)
    mask=np.ma.masked_where(terr < hgt+50,mask)

    m=Basemap(projection='lcc',width=3000*550,height=3000*375,
             resolution='i',lat_1=-32.8,lat_2=-32.8,lat_0=-32.8,lon_0=-67.0)
    x,y=m(lon,lat)
    N=19.

    font0 = FontProperties()
    font0.set_family('monospace')
    my_dpi=100
    fig, ax = plt.subplots(figsize=(11.0, 8.5))
    m.drawcoastlines()
    m.drawcountries(linewidth=1.0)
    m.drawstates(color=(0.5,0.5,0.5),linewidth=0.5)
    #m.drawparallels(np.arange(-80.,81.,1.))
    #m.drawmeridians(np.arange(-180.,181.,1.))
    C=m.pcolormesh(x,y,c,vmin=cmin,vmax=cmax,ax=ax,cmap=colormap)
    plt.title('Initialized '+init.isoformat()+' UTC\n'
              'F'+fhr+' Valid '+valid.isoformat()+' UTC',loc='right',fontdict={'family': 'monospace'})#plt.colorbar(orientation='horizontal',shrink=0.5,pad=0.0)
    plt.title('University of Illinois 3 km WRF Forecast\n'+
              fields,loc='left',fontdict={'family': 'sans-serif'})#plt.colorbar(orientation='horizontal',shrink=0.5,pad=0.0)
    for key in landmark_dict.keys():
        kx,ky=m(landmark_dict[key][0],landmark_dict[key][1])
        plt.text(kx,ky,key,fontsize=8,fontweight='light',
                        ha='center',va='center',color='b')
    CS = m.contour(x,y,z1,z1levs,colors='k',lw=2,ax=ax)
    cl=plt.clabel(CS, fontsize=9, inline=1, fmt='%1.0f',fontproperties=font0)
    CS2 = m.contour(x,y,z2,z2levs,colors='g',lw=2)
    for cl in CS2.collections:
        cl.set_dashes([(0, (2.0, 2.0))])
    print(level)
    print(np.min(c))
    print(np.max(c))
    cl2=plt.clabel(CS2, fontsize=9, inline=1, fmt='%1.0f',fontproperties=font0,ax=ax)
    Urot, Vrot = m.rotate_vector(u,v,lon,lat)
    m.barbs(x[::20,::20],y[::20,::20],Urot[::20,::20],Vrot[::20,::20],
            barb_increments=dict(half=2.5, full=5., flag=25),
           length=5,flagcolor='none',barbcolor='k',lw=0.5,ax=ax)
    m.contour(x,y,terr,[500.,1500.],colors=('blue','red'),alpha=0.5)
    m.pcolormesh(x,y,mask,cmap=cm.Gray5,vmin=0.,vmax=1.)
    cax = fig.add_axes([0.2, 0.12, 0.4, 0.02])
    cb=plt.colorbar(C, cax=cax, orientation='horizontal')
    cb.set_label(cbunits, labelpad=-10, x=1.1)
    ram = cStringIO.StringIO()
    plt.savefig(ram, format='png',dpi=my_dpi, bbox_inches='tight')
    ram.seek(0)
    im = Image.open(ram)
    im2 = im.convert('RGB')
    im2.save( run+'_'+filepat+'_'+str(int(level/100.))+'_'+fhr+'.png' , format='PNG')
Example #41
0
              llcrnrlon=lower_left[0],
              llcrnrlat=lower_left[1],
              urcrnrlon=upper_right[0],
              urcrnrlat=upper_right[1],
              resolution='c')

map.drawcoastlines()

skip = 2  # Spacing of wind barbs

#cs2 = map.contourf(lon2d[:,::skip], lat2d[:,::skip],C[:,::skip],5) # Contour map

cs = map.barbs(lon2d[:, ::skip],
               lat2d[:, ::skip],
               u[time_index, :, :][:, ::skip],
               v[time_index, :, :][:, ::skip],
               C[:, ::skip],
               length=5,
               sizes=dict(emptybarb=0.1))

# For color bar

norm = mpl.colors.Normalize(0, max_speed)
c_m = mpl.cm.jet
s_m = mpl.cm.ScalarMappable(cmap=c_m, norm=norm)
s_m.set_array([])
cb = map.colorbar(s_m)
cb.set_label("Wind speed (m/s)")

# Plot touches
Example #42
0
def plotWTP(file):
    #read in files
    grbs = pygrib.open('rawfile/' + file)
    # extract data from grib file
    Temperature = grbs.select(name='2 metre temperature')[0]
    wind10m_u = grbs.select(name='10 metre U wind component')[0]
    wind10m_v = grbs.select(name='10 metre V wind component')[0]
    MSLP = grbs.select(name='MSLP (Eta model reduction)')[0]

    # define longitude and latitude
    lats, lons = Temperature.latlons()
    lats = (lats.T)[0]
    lons = lons[0]

    # define the initial forecast hour
    analysistime = Temperature.analDate
    fcit = analysistime.timetuple()  # time.struct_time
    formatfcit = time.strftime('%Hz %m %d %Y', fcit)  # formatted initial time
    timestampfcit = time.mktime(fcit)  # timestamp of initial time

    fcst = Temperature.forecastTime  # integer
    formatvalid = time.strftime(
        '%Hz %m %d %Y',
        time.localtime(timestampfcit + fcst * 60 * 60))  # formatted validtime

    # extract each data
    subT = Temperature.values - 273.15
    subWU = wind10m_u.values
    subWV = wind10m_v.values
    subMSLP = MSLP.values / 100.0

    # delete unnecessary variables
    del Temperature
    del wind10m_u
    del wind10m_v
    del MSLP
    del grbs

    # generatre basemap
    m = Basemap(llcrnrlon=77,
                llcrnrlat=13,
                urcrnrlon=145,
                urcrnrlat=52,
                projection='lcc',
                lat_0=30,
                lon_0=105,
                resolution='l',
                area_thresh=1)
    lon, lat = np.meshgrid(lons, lats)
    x, y = m(lon, lat)

    fig = plt.figure(figsize=(10, 7), dpi=100)
    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.spines['bottom'].set_color('none')
    ax.spines['top'].set_color('none')

    # generate legend
    TT = {
        'red': (
            (0, 246 / 255, 246 / 255),
            (20 / 110, 241 / 255, 241 / 255),  #CDG-81
            (35 / 110, 188 / 255, 188 / 255),  #CMG-80.9
            (40 / 110, 123 / 255, 123 / 255),  #CMG-76
            (45 / 110, 183 / 255, 183 / 255),  #LG-63.9
            (50 / 110, 76 / 255, 76 / 255),  #LG-54
            (55 / 110, 44 / 255, 44 / 255),  #MG-53.9
            (599 / 1100, 4 / 255, 4 / 255),  #MG-42
            (60 / 110, 109 / 255, 109 / 255),  #DG-41.9
            (67 / 110, 21 / 255, 21 / 255),  #DG-31
            (75 / 110, 253 / 255, 253 / 255),  #OW-30.9
            (85 / 110, 191 / 255, 191 / 255),  #OW+9
            (90 / 110, 159 / 255, 159 / 255),  #WMG+9
            (100 / 110, 246 / 255, 246 / 255),  #WMG+9
            (105 / 110, 118 / 255, 118 / 255),  #WMG+9
            (1.0, 145 / 255, 145 / 255)),
        'green': (
            (0, 183 / 255, 183 / 255),
            (20 / 110, 18 / 255, 18 / 255),  #CDG-81
            (35 / 110, 114 / 255, 114 / 255),  #CMG-80.9
            (40 / 110, 81 / 255, 81 / 255),  #CMG-76
            (45 / 110, 184 / 255, 184 / 255),  #LG-63.9
            (50 / 110, 73 / 255, 73 / 255),  #LG-54
            (55 / 110, 144 / 255, 144 / 255),  #MG-53.9
            (599 / 1100, 255 / 255, 255 / 255),  #MG-42
            (60 / 110, 231 / 255, 231 / 255),  #DG-41.9
            (67 / 110, 167 / 255, 167 / 255),  #DG-31
            (75 / 110, 235 / 255, 235 / 255),  #OW-30.9
            (85 / 110, 31 / 255, 31 / 255),  #OW+9
            (90 / 110, 32 / 255, 32 / 255),  #WMG+9
            (100 / 110, 183 / 255, 183 / 255),  #WMG+9
            (105 / 110, 114 / 255, 114 / 255),  #WMG+9
            (1.0, 40 / 255, 40 / 255)),
        'blue': (
            (0, 244 / 255, 244 / 255),
            (20 / 110, 134 / 255, 134 / 255),  #CDG-81
            (35 / 110, 199 / 255, 199 / 255),  #CMG-80.9
            (40 / 110, 169 / 255, 169 / 255),  #CMG-76
            (45 / 110, 226 / 255, 226 / 255),  #LG-63.9
            (50 / 110, 182 / 255, 182 / 255),  #LG-54
            (55 / 110, 254 / 255, 254 / 255),  #MG-53.9
            (599 / 1100, 255 / 255, 255 / 255),  #MG-42
            (60 / 110, 153 / 255, 153 / 255),  #DG-41.9
            (67 / 110, 31 / 255, 31 / 255),  #DG-31
            (75 / 110, 118 / 255, 118 / 255),  #OW-30.9
            (85 / 110, 17 / 255, 17 / 255),  #OW+9
            (90 / 110, 51 / 255, 51 / 255),  #WMG+9
            (100 / 110, 244 / 255, 244 / 255),  #WMG+9
            (105 / 110, 199 / 255, 199 / 255),  #WMG+9
            (1.0, 139 / 255, 139 / 255))
    }

    my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', TT, 256)
    norm = mpl.colors.Normalize(-60, 50)

    #c=plt.contourf(x, y, rt, 750, cmap=my_cmap, norm=norm)
    m.contourf(x, y, subT, 110, cmap=my_cmap,
               norm=norm)  #,norm=norm cmaps.temp_19lev NCV_jaisnd
    d = m.contour(x, y, subT, 110, colors='red', linewidths=0.6, levels=0)
    d1 = m.contour(x, y, subMSLP, 70, colors='whitesmoke',
                   linewidths=0.5)  #, alpha=0.6
    plt.clabel(d, inline=True, fmt='%.0f', fontsize=2)
    plt.clabel(d1, inline=True, fmt='%.0f', colors='whitesmoke',
               fontsize=2)  #alpha=0.6,

    skip = slice(None, None, 5)
    #m.streamplot(x, y, u, v, linewidth=0.25, density=4, color='black', arrowsize=0.4, arrowstyle='->')

    m.barbs(x[skip, skip],
            y[skip, skip],
            subWU[skip, skip],
            subWV[skip, skip],
            length=3.5,
            sizes=dict(emptybarb=0, spacing=0.2, height=0.5),
            barb_increments=dict(half=2, full=4, flag=20),
            linewidth=0.2,
            color='black')

    plt.title('GFS 10m Wind & 2m Air Temperature & MSLP\nlnit:' + formatfcit +
              ' Forecast Hour[' + str(fcst) + '] valid at ' + formatvalid +
              '\n@myyd & Louis-He',
              loc='left',
              fontsize=11)
    m.drawparallels(np.arange(0, 65, 10),
                    labels=[1, 0, 0, 0],
                    fontsize=8,
                    linewidth=0.5,
                    color='dimgrey',
                    dashes=[1, 1])
    m.drawmeridians(np.arange(65., 180., 10),
                    labels=[0, 0, 0, 1],
                    fontsize=8,
                    linewidth=0.5,
                    color='dimgrey',
                    dashes=[1, 1])
    m.drawcoastlines(linewidth=0.5)
    m.drawstates(linewidth=0.4, color='dimgrey')
    #m.readshapefile('D:\\shp\\provinces', 'states', drawbounds=True, linewidth=0.5, color='black')
    ax2 = fig.add_axes([0.88, 0.11, 0.018, 0.77])
    cbar = mpl.colorbar.ColorbarBase(ax2,
                                     cmap=my_cmap,
                                     norm=norm,
                                     orientation='vertical',
                                     drawedges=False)
    cbar.set_ticks(np.linspace(-60, 50, 23))
    cbar.ax.set_ylabel('Temperature(℃)', size=8)  #Temperature(℃)
    cbar.ax.tick_params(labelsize=8)
    #Temperature(℃)

    #GFS 10m Wind and 2m Air Temperature\nlnit:00z Nov 04 2017 Forecast Hour[36] valid at 12z Sun,Nov 05 2017 6-hour #ERA Interim 850hpa Wind speed and Temperature & 500hpa Geopotential Height#Streamlines
    plt.savefig('product/WTP/' + file + '.png', bbox_inches='tight')

    # delete plot for memory
    del fig
    plt.cla
    plt.clf()
    plt.close(0)
    del subMSLP, subWU, subWV, subT, m, lon, lat, lons, lats, TT, my_cmap, norm, d, d1, cbar, ax, ax2, x, y, skip, analysistime, fcit, formatfcit, timestampfcit, fcst, formatvalid
Example #43
0
lons, lats = np.meshgrid(lons, lats)

v10 = np.ones((lons.shape)) * 15
u10 = np.zeros((lons.shape))

u10_rot, v10_rot, x, y = map.rotate_vector(u10, v10, lons, lats, returnxy=True)

ax = fig.add_subplot(121)
ax.set_title('Without rotation')

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#cc9955', lake_color='aqua', zorder = 0)
map.drawcoastlines(color = '0.15')


map.barbs(x, y, u10, v10, 
    pivot='middle', barbcolor='#333333')

ax = fig.add_subplot(122)
ax.set_title('Rotated vectors')

map.drawmapboundary(fill_color='9999FF')
map.fillcontinents(color='#ddaa66', lake_color='9999FF', zorder = 0)
map.drawcoastlines(color = '0.15')

map.barbs(x, y, u10_rot, v10_rot, 
    pivot='middle', barbcolor='#ff7777')

plt.show()
Example #44
0
cb.set_label('hPa')
# set plot title
ax.set_title('SLP and Wind Vectors ' + str(date))
plt.show()

# create 2nd figure, add axes
fig2 = plt.figure(figsize=(8, 10))
ax = fig2.add_axes([0.1, 0.1, 0.8, 0.8])
# plot SLP contours
CS1 = m.contour(x, y, slp, clevs, linewidths=0.5, colors='k', animated=True)
CS2 = m.contourf(x, y, slp, clevs, cmap=plt.cm.RdBu_r, animated=True)
# plot wind barbs over map.
barbs = m.barbs(xx,
                yy,
                uproj,
                vproj,
                length=5,
                barbcolor='k',
                flagcolor='r',
                linewidth=0.5)
# draw coastlines, parallels, meridians.
m.drawcoastlines(linewidth=1.5)
m.drawparallels(parallels)
m.drawmeridians(meridians)
# add colorbar
cb = m.colorbar(CS2, "bottom", size="5%", pad="2%")
cb.set_label('hPa')
# set plot title.
ax.set_title('SLP and Wind Barbs ' + str(date))
plt.show()
Example #45
0
map = Basemap(llcrnrlon=-82., llcrnrlat=28., urcrnrlon=-79., urcrnrlat=29.5,
              projection='lcc', lat_1=30., lat_2=60., lat_0=34.83158, lon_0=-98.,
              resolution='i')

ds = gdal.Open("../sample_files/wrf.tiff")
lons = ds.GetRasterBand(4).ReadAsArray()
lats = ds.GetRasterBand(5).ReadAsArray()
u10 = ds.GetRasterBand(1).ReadAsArray()
v10 = ds.GetRasterBand(2).ReadAsArray()

x, y = map(lons, lats)

x2 = np.linspace(x[0][0],x[0][-1],x.shape[1]*2)
y2 = np.linspace(y[0][0],y[-1][0],y.shape[0]*2)

x2, y2 = np.meshgrid(x2, y2)

u10_2 = interp(u10,  x[0], np.flipud(y[:, 0]), x2, np.flipud(y2),order=1)
v10_2 = interp(v10,  x[0], np.flipud(y[:, 0]), x2, np.flipud(y2),order=1)

map.drawmapboundary(fill_color='#9999FF')
map.fillcontinents(color='#cc9955', lake_color='#9999FF', zorder = 0)
map.drawcoastlines(color = '0.15')

map.barbs(x, y, u10, v10, 
    pivot='middle', barbcolor='#555555')

map.barbs(x2, y2, u10_2, v10_2, 
    pivot='middle', barbcolor='#FF3333')

plt.show()
m.drawstates(linewidth=0.66, color='#444444', zorder=4)
m.drawmapboundary

# draw lat/lon grid lines every 30 degrees.
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))

x, y = m(X, Y)
CS = m.contourf(x,y,zeta_a1,cmap=plt.cm.hot_r,levels=cflevs, extend='both',zorder=1)
cbar = plt.colorbar(CS, shrink=0.95, orientation='horizontal',extend='both')
CS2 = m.contour(x, y, zeta_a1, cflevs, colors='k', linewidths=0.5)

if plot_barbs == "true":
    # Rotate and interpolate wind from lat/lon grid to map projection grid.
   uproj1,vproj1, xx1, yy1 = m.transform_vector(ugrid1,vgrid1,newlons,lats,41,41,returnxy=True)    
   barbs = m.barbs(xx1,yy1,uproj1,vproj1,length=5,barbcolor='k',flagcolor='r',linewidth=1.0)


cbar.set_ticks(cflevs_ticks)
clabs = ['%i K' % f for f in cflevs_ticks]
cbar.ax.set_yticklabels(clabs, size=10)
ax1.set_title(titletext1)
save_name = figname + "_01.png"
plt.savefig(save_name, bbox_inches='tight')


# Figure 2
fig = plt.figure(figsize=(8., 16./golden), dpi=128)   # New figure
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])

if map_projection == 'ortho':
Example #47
0
qk = plt.quiverkey(Q, 0.1, 0.1, 20, '20 m/s', labelpos='W')
# draw coastlines, parallels, meridians.
m.drawcoastlines(linewidth=1.5)
m.drawparallels(parallels)
m.drawmeridians(meridians)
# add colorbar
cb = m.colorbar(CS2,"bottom", size="5%", pad="2%")
cb.set_label('hPa')
# set plot title
ax.set_title('SLP and Wind Vectors '+str(date))
fig1.savefig('plotwindvec1.png')

# create 2nd figure, add axes
fig2 = plt.figure(figsize=(8,10))
ax = fig2.add_axes([0.1,0.1,0.8,0.8])
# plot SLP contours
CS1 = m.contour(x,y,slp,clevs,linewidths=0.5,colors='k',animated=True)
CS2 = m.contourf(x,y,slp,clevs,cmap=plt.cm.RdBu_r,animated=True)
# plot wind barbs over map.
barbs = m.barbs(xx,yy,uproj,vproj,length=5,barbcolor='k',flagcolor='r',linewidth=0.5)
# draw coastlines, parallels, meridians.
m.drawcoastlines(linewidth=1.5)
m.drawparallels(parallels)
m.drawmeridians(meridians)
# add colorbar
cb = m.colorbar(CS2,"bottom", size="5%", pad="2%")
cb.set_label('hPa')
# set plot title.
ax.set_title('SLP and Wind Barbs '+str(date))
fig2.savefig('plotwindvec2.png')
Example #48
0
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
m = Basemap(projection='cyl',resolution='i',  llcrnrlat=44.30,urcrnrlat=60.5,\
            llcrnrlon=4.750,urcrnrlon=18.00)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,91.,5), labels=[True, True, True, False])
m.drawmeridians(np.arange(-180.,181.,5), labels=[True, False, True, True])
#m.drawmapboundary(fill_color='aqua') 
x = np.linspace(5, 18, 10)
y=np.linspace(45, 60, 10)
X,Y = np.meshgrid(x, y)
U, V = 12*(X-11), 12*(Y-52)
#Default parameters, uniform grid
m.barbs(X, Y, U, V)
#plt.show()
plt.savefig('/home/s.von.hall/seminar/bspbarbs.png')
Example #49
0
    basemap.drawcoastlines(linewidth=1.25)
    basemap.drawcountries()
    basemap.drawmeridians(np.arange(0, 360, 10),
                          labels=[False, False, False, True])
    basemap.drawparallels(np.arange(-90, 90, 10),
                          labels=[True, False, False, False])
    x0, y0 = basemap(lon, lat)
    plt.title('%g' % level +
              ' hPa Synoptic Analysis with GSF Analysis Data\nUTC' + time_str)
    cf = basemap.contourf(x0,
                          y0,
                          t_var,
                          vmin=t_min,
                          vmax=t_max,
                          cmap=cmaps.WhiteBlueGreenYellowRed,
                          levels=t_level)

    cb = basemap.colorbar(cf, ax=plt.gca(), ticks=t_level)
    cb.set_label('$\mathrm{Temperature(^\circ C)}$')

    cs = basemap.contour(x0, y0, hgt_var, colors='b', levels=h_level)
    plt.clabel(cs, cs.levels, fmt='%g', inline_spacing=10)
    basemap.barbs(x0[::5, ::5],
                  y0[::5, ::5],
                  u_var[::5, ::5],
                  v_var[::5, ::5],
                  length=5)
    plt.show()
    # </editor-fold>
Example #50
0
        resolution='l')

    # Get U,V components from wind speed and direction
    u,v = metpy.get_wind_components(speed, wdir)

    # Rotate the vectors to be properly aligned in the map projection
    u,v = bm.rotate_vector(u, v, lon, lat)

    # Generate grid of x,y positions
    lon_grid, lat_grid, x_grid, y_grid = bm.makegrid(130, 60, returnxy=True)

    # Transform the obs to basemap space for gridding
    obx,oby = bm(lon, lat)

    # Perform analysis of height obs using Cressman weights
    heights_oban = grid_data(height, x_grid, y_grid, obx, oby,
        obans[which_oban][0], obans[which_oban][1])

    heights_oban = maskoceans(lon_grid, lat_grid, heights_oban)

    # Map plotting
    contours = np.arange(5000., 5800., 60.0)
    bm.drawstates()
    bm.drawcountries()
    bm.drawcoastlines()
    cp = bm.contour(x_grid, y_grid, heights_oban, contours)
    bm.barbs(obx, oby, u, v)
    plt.clabel(cp, fmt='%.0f', inline_spacing=0)
    plt.title('500mb Height map')
    plt.show()
Example #51
0
norm = mpl.colors.Normalize(vmin=-35, vmax=80)
ax.text(0.5, .97, title, transform=plt.gca().transAxes,fontsize=16, horizontalalignment='center', bbox=dict(facecolor='white', alpha=0.9, boxstyle='round'))                                                     
#cax = m.pcolormesh(x, y, data, cmap=cmap, norm=norm)
cax = m.imshow(data, extent = (x.min(), x.max(), y.min(), y.max()), cmap=cmap, norm=norm, origin="upper")
m.drawcoastlines(color='#FFFFFF')
m.drawstates(color='#FFFFFF')
m.drawcountries(color='#FFFFFF')
m.drawcounties(color='#FFFFFF', linewidth=0.09)
cbar = m.colorbar(cax)

x_grid, y_grid = m(cape_grid_lon, cape_grid_lat)
c = m.contour(x_grid, y_grid, CAPE, np.arange(500,6500,500), cmap='spring_r')
plt.clabel(c, fmt='%4.0f')
stride = 10
#m.barbs(x_grid[::stride, ::stride], y_grid[::stride, ::stride], u_shear[::stride,::stride], v_shear[::stride,::stride], mag[::stride,::stride], cmap='RdPu') 
m.barbs(grid_lon, grid_lat, u_shear.T, v_shear.T, mag.T, clim=[30,70], latlon=True, cmap='RdPu') 

plt.tight_layout()
# Make the newest graphic.
out_filename = path_to_imgs + 'nexrad_rap_composite_' + today.strftime("%Y%m%d_%H%M.png")
plt.savefig(out_filename, bbox_inches='tight')

# Delete the oldest graphic.
old_filename = path_to_imgs + 'nexrad_rap_composite_' + end.strftime("%Y%m%d_%H%M.png")
os.system('/usr/bin/rm ' + old_filename)

print "Making looper"
path_to_looper = '/data/soundings/blumberg/programs/wx_maps/looper/make_looper.py'
os.system('/data/soundings/anaconda/bin/python ' + path_to_looper + ' ' + path_to_imgs + ' nexrad_rap')

def plot_pm25_map(mobile,other_mobile=False,auto_map_boundaries=True,background='WRF'):
    print "--plot map--"    
    """
    makes a map of the helicopter observations. Also plots MesoWest
    input: mobile=ksl observations from the get moblie function
    
    other_mobile: if set to true will plot truck and trax data if available
    auto_map_boundaries: will find the location of the helicopter and will set auto boundaries
                         else, will map the salt lake valley or you can change the lat/lon manually
    background: 'WRF' will use a wrf file to contour the boundary
                'sat' will use an old satellite image
                'topo' will use a topographical image
    
    DON'T PLOT PURPLE AIR MONITORS

    return: a string of the URL the figure is saved
    """
    plt.cla()
    plt.clf()
    plt.close()
    
    
    width=4
    height=4.5
    
    
    fig, (ax1) = plt.subplots(1,1,figsize=(width,height))
    
    
    ## ---- Draw map
    top_right_lat = 40.9 + .17
    top_right_lon = -111.60
    bot_left_lat = 40.4+.05
    bot_left_lon = -112.19785-.1
    
    # Might need to make the map bigger if the chopper flew out of the valley
    try:    
        if np.nanmax(mobile['latitude']) > top_right_lat:
            top_right_lat = np.nanmax(mobile['latitude'])+.02
        if np.nanmin(mobile['latitude'][mobile['latitude']>-9999]) < bot_left_lat:
            bot_left_lat = np.nanmin(mobile['latitude'][mobile['latitude']>-9999])-.02
        if np.nanmax(mobile['longitude']) > top_right_lon:
            top_right_lon = np.nanmax(mobile['longitude'])+.02
        if np.nanmin(mobile['longitude'][mobile['longitude']>-9999]) < bot_left_lon:
            bot_left_lon = np.nanmin(mobile['longitude'][mobile['longitude']>-9999])-.02
    except:
        # something funny with the lat/lon data not having a max or min
        # must have ozone or pm25 data but no lat lon data
        pass
        
        
    ## Map in cylindrical projection (data points may apear skewed)
    m = Basemap(resolution='i',projection='cyl',\
        llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\
        urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,)    
    
    
    
    # -----Set Background images
    
    if background == 'WRF':
        ## ---- Grab terrain data
        directory = '/uufs/chpc.utah.edu/common/home/horel-group4/model/bblaylock/WRF3.7_spinup/DATA/FULL_RUN_June14-19/'
        spat = 'auxhist23_d02_2015-06-14_00:00:00'
        nc_spatial = netcdf.netcdf_file(directory+spat,'r')
        # This sets the standard grid point structure at full resolution
        #	Converts WRF lat and long to the maps x an y coordinate
        XLONG = nc_spatial.variables['XLONG'][0]
        XLAT  = nc_spatial.variables['XLAT'][0]
        HGT = nc_spatial.variables['HGT'][0,:,:] #topography
        landmask = nc_spatial.variables['LANDMASK'][0,:,:]
            
        # Plot Terrain 
        X,Y = m(XLONG,XLAT)
        plt.contourf(X,Y,HGT,levels=np.arange(1000,4000,500),cmap='binary')            
        # Draw major roads from shapefile
        m.readshapefile('/uufs/chpc.utah.edu/common/home/u0553130/shape_files/tl_2015_UtahRoads_prisecroads/tl_2015_49_prisecroads','roads', linewidth=.2)
    
        ## Contour Lake Outline
        plt.contour(X,Y,landmask, [0,1], linewidths=1, colors="b")


    maps = [
                'ESRI_Imagery_World_2D',    # 0
                'ESRI_StreetMap_World_2D',  # 1
                'NatGeo_World_Map',         # 2
                'NGS_Topo_US_2D',           # 3
                'Ocean_Basemap',            # 4
                'USA_Topo_Maps',            # 5
                'World_Imagery',            # 6
                'World_Physical_Map',       # 7
                'World_Shaded_Relief',      # 8
                'World_Street_Map',         # 9
                'World_Terrain_Base',       # 10
                'World_Topo_Map'            # 11
                ]    
    if background == 'sat':
        ## Instead of using WRF terrain fields you can get a high resolution image from ESRI
        m.arcgisimage(service=maps[0], xpixels = 1000, verbose= True)
    if background == 'topo':
        ## Instead of using WRF terrain fields you can get a high resolution image from ESRI
        m.arcgisimage(service=maps[8], xpixels = 1000, verbose= True)
        # Draw major roads from shapefile
        m.readshapefile('/uufs/chpc.utah.edu/common/home/u0553130/shape_files/tl_2015_UtahRoads_prisecroads/tl_2015_49_prisecroads','roads', linewidth=.2)
    # can use any other map background from maps list
    
    
    
    # Plot Other Mobile data
    if other_mobile == True:
        # Plot Mobile Ozone points (TRAX01)
        try:
            x,y = m(trax_mobile['longitude'],trax_mobile['latitude']) 
            m.scatter(x[:],y[:],c=trax_mobile['pm25'][:],vmax=45,vmin=0.,lw = .3,marker='d',s=30,cmap=plt.cm.get_cmap('jet'),zorder=50)
        except:
            print 'no TRAX01 data'
            
        # Plot Mobile Truck points (UUTK3)
        try:
            x,y = m(trk3_mobile['longitude'],trk3_mobile['latitude']) 
            m.scatter(x[:],y[:],c=trk3_mobile['pm25'][:],vmax=45,vmin=0.,lw = .3,marker='p',s=30,cmap=plt.cm.get_cmap('jet'),zorder=50)
        except:
            print 'no UUTK3 data'
        
        # Plot Mobile Truck points (UUTK1)
        try:
            x,y = m(trk1_mobile['longitude'],trk1_mobile['latitude']) 
            m.scatter(x[:],y[:],c=trk1_mobile['pm25'][:],vmax=45,vmin=0.,lw = .3,marker='p',s=30,cmap=plt.cm.get_cmap('jet'),zorder=50)
        except:
            print 'no UUTK1 data'
    
    
    ## Plot MesoWest  (top of the hour, +/- 10 mins) 
    # Plot MesoWest wind data
    mesowest_time = str(request_time.year).zfill(2)+str(request_time.month).zfill(2)+str(request_time.day).zfill(2)+str(request_time.hour).zfill(2)+'00'
    print 'plotting mesowest observations within 10 minutes of top of the hour',mesowest_time, ' because the request time is:', request_time    
    a = MW.get_mesowest_radius_winds(mesowest_time,'10')
    u,v = MW.wind_spddir_to_uv(a['WIND_SPEED'],a['WIND_DIR'])
    m.barbs(a['LON'],a['LAT'],u,v,
            length=4.5,                
            linewidth=.5,
            barb_increments=dict(half=1, full=2, flag=10),
            sizes=dict(spacing=0.15, height=0.3, emptybarb=.1))
    
    # pm 2.5
    # DON'T PLOT THE PURPLE AIR SITES!!!
    # which indexes are the purple air sites??
    for z in range(0,len(a['STNID'])):
        if a['STNID'][z][0:3] != 'PUR': 
            m.scatter(a['LON'][z],a['LAT'][z],c=a['pm25'][z], 
                      vmax=45,vmin=0.,lw =.3,s=20, marker='s',
                      edgecolor='k',
                      cmap=plt.cm.get_cmap('jet'),zorder=50)
    
    ## plot KSL on top of everything becuase it is flying    
    # Plot Mobile Ozone points (KSL)
    x,y = m(mobile['longitude'],mobile['latitude']) 
    # plot every 30 seconds rather than every 10 seconds (thus the [::3] indexes)    
    m.scatter(x[::3],y[::3],c=ksl_mobile['pm25'][::3],
              vmax=45,vmin=0.,lw = .3,s=30,
              edgecolor='k',cmap=plt.cm.get_cmap('jet'),zorder=50)
    cbar = plt.colorbar(orientation='horizontal',extend='both',shrink=.8,pad=.03)
    cbar.ax.set_xlabel(r'PM 2.5 ($\mu$g m$\mathregular{^{-3}}$)',fontsize=10)
    cbar.ax.tick_params(labelsize=8)
    cbar.set_ticks([0,5,10,15,20,25,30,35,40,45])    
    
    # ERIK PAPER: Draw Utah Valley parallel
    m.drawparallels([40.48])

    # Manually plot other Sensor locations by lat/lon
    """
    m.scatter(-111.93,40.9669, s=75, c='w',zorder=40)
    m.scatter(-112.01448,40.71152, s=75, c='b',zorder=40) # NAA
    m.scatter(-111.93072,40.95733, s=75, c='darkorange',zorder=40) # O3S02                        
    m.scatter(-111.828211,40.766573, s=75, c='r',zorder=40) # MTMET                       
    m.scatter(-111.8717,40.7335, s=75, c='darkgreen',zorder=40) # QHW               
    m.scatter(-111.96503,40.77069, s=75, c='w',zorder=40) # SLC               
    m.scatter(-112.34551,40.89068 , s=75, c='w',zorder=40) # GSLBY
    """
    
    ## Sidebar Text
    
    # is trax_in_yard, is trax available?
    if trax_mobile == 'No Data Available from TRX01 at this time':
        trax_time_range = 'n/a'
        trax_ozone_text = 'TRAX \n  n/a'
    else:
        trax_in_yard = ''
        if trax_mobile['longitude'].max()==-9999:
            trax_in_yard = '  -Yard-'
        trax_time_range = trax_mobile['DATES'][0].strftime('%H:%M - ')+trax_mobile['DATES'][-1].strftime('%H:%M UTC')     
        trax_ozone_text = 'TRAX'+trax_in_yard+'\n  Max:  %.2f ug m-3\n  Mean: %.2f ug m-3\n  Min:  %.2f ug m-3' % (np.nanmax(trax_mobile['pm25']), np.mean(trax_mobile['pm25'][trax_mobile['pm25']>0]),np.nanmin(trax_mobile['pm25']))    
        
    obs_day = mobile['DATES'][-1].strftime('%d %b %Y')    
    ksl_time_range = mobile['DATES'][0].strftime('%H:%M - ')+mobile['DATES'][-1].strftime('%H:%M UTC')
 
    mesowest_time_range =  datetime.strptime(mesowest_time,"%Y%m%d%H%M").strftime('%H:%M UTC')
    
    date_text='%s\nKSL:  %s\nTRAX: %s\nMesoWest: %s' % (obs_day,ksl_time_range,trax_time_range,mesowest_time_range)
    ksl_ozone_text =  'KSL   \n  Max:  %.2f ug m-3\n  Mean: %.2f ug m-3\n  Min:  %.2f ug m-3' % (np.nanmax(mobile['pm25']),  np.mean(mobile['pm25'][mobile['pm25']>0]),np.nanmin(mobile['pm25']))    
   
    mesowest_ozone_text = ''
    for i in range(0,len(a['pm25'][a['pm25']>0])):
        station_obs = '%s: %.2f\n' % (a['STNID'][a['pm25']>0][i], a['pm25'][a['pm25']>0][i])
        mesowest_ozone_text +=station_obs
    all_text = date_text+'\n\n'+ksl_ozone_text+'\n\n'+trax_ozone_text+'\n\n'+mesowest_ozone_text
    #fig.text(.93,.8,all_text,fontname='monospace',va='top',backgroundcolor='white',fontsize=7)
    
    plt.savefig(FIGDIR+string_time+'_KSL5_map_pm25.png',dpi=500,bbox_inches="tight")
    print 'saved map', FIGDIR+string_time+'_KSL5_map_pm25.png'
    print ""
    return 'http://home.chpc.utah.edu/~u0553130/oper/KSL_daily/'+string_time+'_KSL5_map_pm25.png\n'
Example #53
0
# grab most recent observations 15 mins before and after the radar scan. Grab stations within a 150 mile radius of radar.
a = get_mesowest_radius_winds(mesowest_time,
                              '15,15',
                              radius=str(rLAT) + ',' + str(rLON) + ',' + '150')

# (There are some funky IRAWS stations stashed in the parking lot. Don't plot these)
raws_lat = 43.565
raws_idx = np.argwhere(a['LAT'] == 43.565)
a['WIND_SPEED'][np.argwhere(a['LAT'] == 43.565)] = np.nan

# Add MesoWest wind barbs
u, v = wind_spddir_to_uv(a['WIND_SPEED'], a['WIND_DIR'])
m.barbs(a['LON'],
        a['LAT'],
        u,
        v,
        length=5.5,
        barb_increments=dict(half=2.5, full=5, flag=25),
        sizes=dict(spacing=0.15, height=0.3, emptybarb=.1),
        zorder=500)

### ---------------- Add Points of Interest --------- -------------------------
# NEXRAD location
m.scatter(rLON, rLAT, s=75, c='w', zorder=500)

### ----------- Loop through each sweep (scan elevation) ---------------------
# Pull data out of the file
# sweep reprsents the scan elevation angle (Note: sweep number is not in order of lowest to highest scan)
# to get the elevation angle try: f.sweeps[x][0][0].el_angle where x is your sweep index

s = range(0, 21)  # a list of sweeps
#s = [1]