예제 #1
0
def test_gshhs():
    ax = plt.axes(projection=ccrs.Mollweide())
    ax.set_extent([138, 142, 32, 42], ccrs.Geodetic())

    ax.stock_img()
    # Draw coastlines.
    ax.add_feature(cfeature.GSHHSFeature('coarse', edgecolor='red'))
    # Draw higher resolution lakes (and test overriding of kwargs)
    ax.add_feature(cfeature.GSHHSFeature('low', levels=[2], facecolor='green'),
                   facecolor='blue')
예제 #2
0
def plot_dp(storm, datafile1, datafile2=None):

   #Single file netCDF reading
   ncf=datafile1
   nco=netCDF4.Dataset(ncf)

   #Get fields to plot
   lon=nco.variables['longitude'][:]
   lat=nco.variables['latitude'][:]
   timeindays=nco.variables['time'][:]
   dp=nco.variables['dp'][:]
   triangles=nco.variables['tri'][:,:]

   reflon=np.linspace(lon.min(),lon.max(),1000)
   reflat=np.linspace(lat.min(),lat.max(),1000)
   #reflon=np.linspace(-80.40, -74.75, 1000)
   #reflat=np.linspace(32.50, 36.60, 1000)
   #reflon=np.linspace(-75.70, -71.05, 1000)
   #reflat=np.linspace(38.50, 41.40, 1000)
   reflon,reflat=np.meshgrid(reflon,reflat)

   plt.figure(figsize = [6.4, 3.8])

   flatness=0.10  # flatness is from 0-.5 .5 is equilateral triangle
   triangles=triangles-1  # Correct indices for Python's zero-base
   tri=Triangulation(lon,lat,triangles=triangles)
   mask = TriAnalyzer(tri).get_flat_tri_mask(flatness)
   tri.set_mask(mask)

   # Loop through each time step and plot results
   for ind in range(0, len(timeindays)): 
      plt.clf()
      ax = plt.axes(projection=ccrs.Mercator())

      dt = datetime.datetime.combine(datetime.date(1990, 1, 1), datetime.time(0, 0)) + datetime.timedelta(days=timeindays[ind])
      dstr = datetime.date.strftime(dt,'%Y%m%d%H:%M:%S')
      dstr = dstr[0:8]+' '+dstr[8:17]
      print('Plotting '+dstr)

      par=np.double(dp[ind,:])
      tli=LinearTriInterpolator(tri,par)
      par_interp=tli(reflon,reflat)

      plt.pcolormesh(reflon,reflat,par_interp,vmin=0.0,vmax=360.0,shading='flat',cmap=plt.cm.jet, transform=ccrs.PlateCarree())
      cb = plt.colorbar()
      cb.ax.tick_params(labelsize=8)
      coast = cfeature.GSHHSFeature(scale='high',edgecolor='black',facecolor='none',linewidth=0.25)	
      ax.add_feature(coast)
      plt.xticks(fontsize=9)
      plt.yticks(fontsize=9)
      figtitle = storm.capitalize()+': Peak Dir (deg): '+dstr
      plt.title(figtitle)

      dtlabel = datetime.date.strftime(dt,'%Y%m%d%H%M%S')
      dtlabel = dtlabel[0:8]+'_'+dtlabel[8:14]
      filenm = 'nsem_'+storm+'_dp_'+dtlabel+'.png'
      plt.savefig(filenm,dpi=150,bbox_inches='tight',pad_inches=0.1)

      del(par)
      del(par_interp)
예제 #3
0
def plot_world_map(lons, lats, data, metadata, plotpath):
    # plot generic world map
    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(1,
                         1,
                         1,
                         projection=ccrs.PlateCarree(central_longitude=0))
    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    ax.set_extent([-180, 180, -90, 90])
    if metadata['var'] == 'wind':
        vmin = 0
        vmax = 12
    elif metadata['var'] == 'hs':
        vmin = 0
        vmax = 5.5
    else:
        vmin = np.nanmin(data)
        vmax = np.nanmax(data)
    #cmap = 'viridis' #blue to yellow matlab
    cmap = 'jet'
    cbarlabel = '%s' % (metadata['var'])
    plttitle = 'WW3 Plot of variable %s' % (metadata['var'])
    cs = ax.pcolormesh(lons, lats, data, vmin=vmin, vmax=vmax, cmap=cmap)
    cb = plt.colorbar(cs, orientation='horizontal', shrink=0.5, pad=.04)
    cb.set_label(cbarlabel, fontsize=12)
    plt.title(plttitle)
    plt.savefig(plotpath)
    plt.close('all')
예제 #4
0
def grab_gshhg_features(scale, levels, extent):
    """Grabs lat/lon coordinates for GSHHG features.

    Grab geographical feature data from the GSHHG database for a specified extent,
    level of detail, and resolution. Outputs simple lat/lon coordinates -- useful
    for plotting backends (like Bokeh) that don't have fancy geo feature integration.

    Args:
        scale: A string, can be either f(ull), h(igh), i(ntermediate), l(ow), or c(rap)
               depending upon the desired resolution.
        levels: Specify which level(s) of feature to plot; [1] is only coastlines
                and [1, 2, 3, 4] is everything.
        extent: Specify [lonmin, lonmax, latmin, latmax] in decimal degrees.

    Returns:
        features: A dictionary containing coordinates of geo features
                  (WGS84 lat/lon, decimal degrees).
    """

    unformatted_features = list(cf.GSHHSFeature(scale=scale, levels=levels).intersecting_geometries(extent))

    features = {'latitude':[], 'longitude':[]}
    for feature in unformatted_features:
        lons = feature.exterior.coords.xy[0].tolist()
        lats = feature.exterior.coords.xy[1].tolist()
        features['longitude'].append(lons)
        features['latitude'].append(lats)

    return features
def plot_world_map(lons, lats, data, metadata, plotpath):
    # plot generic world map
    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(1,
                         1,
                         1,
                         projection=ccrs.PlateCarree(central_longitude=0))
    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    ax.set_extent([-180, 180, -90, 90])

    #vmin = np.nanmin(data)
    #vmax = np.nanmax(data)
    vminmax = float(metadata['vminmaxvar'])
    vmin = -1 * vminmax
    vmax = vminmax
    cmap = 'bwr'
    cbarlabel = '%s' % (metadata['var'])
    plttitle = '%s' % (metadata['tag'])
    cs = ax.pcolormesh(lons, lats, data, vmin=vmin, vmax=vmax, cmap=cmap)
    cb = plt.colorbar(cs,
                      extend='both',
                      orientation='horizontal',
                      shrink=0.5,
                      pad=.04)
    cb.set_label(cbarlabel, fontsize=12)
    plt.title(plttitle)
    plt.savefig(plotpath)
    plt.close('all')
예제 #6
0
def plot_world_map(lons, lats, data, metadata, plotpath, screen, lonr, latr, comment):
    # plot generic world map
    if screen.upper() == "NO":
        matplotlib.use('agg')
    fig = plt.figure(figsize=(12,8))
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=0))
    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    listWE = lonr.split(',')
    listSN = latr.split(',')
    lonBeg = lonS2F(listWE[0])
    lonEnd = lonS2F(listWE[1])
    latBeg = latS2F(listSN[0])
    latEnd = latS2F(listSN[1])
    scaleWE = 360/(lonEnd-lonBeg)*10
    scaleSN = 180/(latEnd-latBeg)*10
    scaleMax = max(scaleWE,scaleSN)
    ax.set_extent([lonBeg, lonEnd, latBeg, latEnd])
    vmax = np.nanmean(data)+np.nanstd(data)*2
    vmin = np.nanmean(data)-np.nanstd(data)*2
    cmap = 'viridis'
    cbarlabel = '%s' % (metadata['var'])
    if comment == '':
        plttitle = 'Variable: %s' % (metadata['var'])
    else:
        plttitle = 'Variable: %s; %s' % (metadata['var'], comment)
    cs = plt.scatter(lons, lats, c=data, s=scaleMax,
                     cmap=cmap, transform=ccrs.PlateCarree(),vmin=vmin,vmax=vmax)
    cb = plt.colorbar(cs, orientation='horizontal', shrink=0.5, pad=.04)
    cb.set_label(cbarlabel, fontsize=12)
    plt.title(plttitle)
    if screen.upper() == "NO":
        plt.savefig(plotpath)
        plt.close('all')
    else:
        plt.show()
예제 #7
0
def plot_segments(segments=None,
                  mission_name='',
                  poly=None,
                  lat_min=-22.5,
                  lat_max=-20,
                  lon_min=165.5,
                  lon_max=168.5):
    """
    Plot ADCP transects from regions of intres
    """
    ax = add_map(lat_min=lat_min,
                 lat_max=lat_max,
                 lon_min=lon_min,
                 lon_max=lon_max)
    for ds in segments:
        ax.plot(ds['lon'],
                ds['lat'],
                '.',
                markersize=2,
                label='%s_s%s' %
                (ds.attrs['mission'], ds.attrs['segment_number']))
    land = cfeature.GSHHSFeature(scale='intermediate',
                                 levels=[1],
                                 facecolor=cfeature.COLORS['land'])
    if poly is not None:
        ax.add_geometries(poly, ccrs.PlateCarree(), alpha=0.2)
    plt.title(mission_name)
    #plt.legend()
    plt.tight_layout()
예제 #8
0
def draw_map():
    lat_sp = 20
    lon_sp = 30  #60 #
    title_font = 14
    label_font = 10

    ds = xr.open_dataset(fileout)
    ilon = ds.lon
    ilat = ds.lat
    var = ds['preci'].resample(time="5D").mean()
    var = var * 3600 * 24 * 1000  #mm/day
    time = var.indexes['time'].to_datetimeindex()

    ds = xr.open_dataset(
        "/home/ys17-19/renql/project/TP_NUDG/analysis/mdata/gtopo30_0.9x1.25.nc"
    )
    phis = ds['PHIS'].sel(lon=ilon, lat=ilat, method="nearest").load()
    phis = phis / 9.8  # transfer from m2/s2 to m

    cnlevels = np.arange(1, 18, 1)
    fcolors = cmaps.precip2_17lev
    norm = colors.BoundaryNorm(boundaries=cnlevels,
                               ncolors=fcolors.N,
                               extend='both')

    for nt in range(len(time)):
        title = 'CESM AMIP %02d-%02d preci (mm/day)' % (time[nt].month,
                                                        time[nt].day)

        fig = plt.figure(figsize=(12, 9), dpi=100)
        axe = plt.axes(projection=ccrs.PlateCarree(central_longitude=180.0))
        axe.add_feature(cfeat.GSHHSFeature(levels=[1, 2], edgecolor='k'),
                        linewidth=0.8,
                        zorder=1)
        axe.set_title(title, fontsize=title_font)

        cont = axe.contourf(var.lon,
                            var.lat,
                            var[nt, :, :],
                            cnlevels,
                            transform=ccrs.PlateCarree(),
                            cmap=fcolors,
                            extend='both',
                            norm=norm)
        topo = axe.contour(phis.lon,
                           phis.lat,
                           phis, [1500, 3000],
                           transform=ccrs.PlateCarree(),
                           colors='black',
                           linewidths=1.5)

        axe.set_yticks(np.arange(lats, latn, lat_sp), crs=ccrs.PlateCarree())
        axe.yaxis.set_major_formatter(LatitudeFormatter(degree_symbol=''))
        axe.set_xticks(np.arange(lonl, lonr, lon_sp), crs=ccrs.PlateCarree())
        axe.xaxis.set_major_formatter(LongitudeFormatter(degree_symbol=''))

        cb = plt.colorbar(cont)
        plt.savefig('%s%d' % (figdir, nt),
                    bbox_inches='tight',
                    pad_inches=0.01)
예제 #9
0
def get_map(region=None,
            zoom=1,
            projection=ccrs.Mercator(),
            res='i',
            draw_coastlines=True,
            figsize=(8, 10),
            shape=(1, 1)):
    extents = []
    if isinstance(region, str):
        region = [region]
    for r in region:
        extents.append(extent_from_region(r))

    fig, axes = plt.subplots(
        shape[0],
        shape[1],
        figsize=figsize,
        subplot_kw={
            # kwargs passed to add_subplot()
            'projection': projection
        })
    if not isinstance(axes, (list, np.ndarray)):
        axes = [axes]
    for ax, e in zip(axes, extents):
        ax.set_extent(e)
        ax.add_feature(cfeat.GSHHSFeature(
            scale=res)) if draw_coastlines else False

    if len(axes) == 1:
        return fig, axes[0]
    else:
        return fig, axes
예제 #10
0
def plot_world_map(lons, lats, data, metadata, plotpath):
    # plot generic world map
    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(1,
                         1,
                         1,
                         projection=ccrs.PlateCarree(central_longitude=0))
    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    ax.set_extent([-180, 180, -90, 90])
    cmap = 'jet'
    cbarlabel = '%s' % (metadata['var'])
    plttitle = 'MOM6 Plot of variable %s' % (metadata['var'])
    if metadata['var'] == 'MLD_003':
        bounds = np.array([
            10, 20, 30, 40, 50, 60, 80, 100, 150, 200, 250, 300, 400, 500, 1000
        ])
        norm = mcolors.BoundaryNorm(boundaries=bounds, ncolors=256)
        cs = ax.pcolormesh(lons, lats, data, norm=norm, cmap=cmap)
    else:
        vmin = np.nanmin(data)
        vmax = np.nanmax(data)
        cs = ax.pcolormesh(lons, lats, data, vmin=vmin, vmax=vmax, cmap=cmap)
    cb = plt.colorbar(cs,
                      extend='both',
                      orientation='horizontal',
                      shrink=0.5,
                      pad=.04)
    cb.set_label(cbarlabel, fontsize=12)
    plt.title(plttitle)
    plt.savefig(plotpath)
    plt.close('all')
예제 #11
0
def nice_map(dataarray, ax=None, title='', transform=ccrs.PlateCarree(),
             **kwargs):
	"""
	Make a nice map with gridlines and coordinates

	Parameters
	----------
	ax: matplotlib axes object, optional
		If None, uses the current axis
	title: str, optional
		Title of the plot
	"""
	if ax is None:
		ax = plt.subplot(1, 1, 1, projection=transform)
	dataarray.plot.pcolormesh(ax=ax, transform=transform, **kwargs)
	land = cfeature.GSHHSFeature(scale='intermediate', levels=[1],
	                             facecolor=cfeature.COLORS['land'])
	ax.add_feature(land)
	ax.set_title(title)
	gl = ax.gridlines(draw_labels=True)
	gl.xlabels_top = False
	gl.ylabels_right = False
	gl.xformatter = LONGITUDE_FORMATTER
	gl.yformatter = LATITUDE_FORMATTER
	plt.tight_layout()
예제 #12
0
def plot_spatial(diag):
    
    n = len(diag.diff) 
    mean, std, mx, mn = calculate_stats(diag.diff)
    
    plt.figure(figsize=(15,12))
    ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=0))
    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    ax.set_extent([-180, 180, -90, 90])
    norm = mcolors.BoundaryNorm(boundaries=diag.variables[diag.variable]['boundsize'], ncolors=256)
    
    cs = plt.scatter(diag.lons, diag.lats, c=diag.diff, s=30,
                norm=norm, cmap='bwr', #edgecolors='gray', linewidth=0.25,
                transform=ccrs.PlateCarree())
    
    if diag.dtype == 'conv' and diag.variable == 'q':
        t = ('n: %s\nstd: %s\nmean: %s' % (n,np.round(std,6),np.round(mean,6)))
        ax.text(-175, -70, t, fontsize=16, transform=ccrs.PlateCarree())
    else:
        t = ('n: %s\nstd: %s\nmean: %s\nmax: %s\nmin: %s' % (n,np.round(std,3),np.round(mean,3), np.round(mx,3), np.round(mn,3)))
        ax.text(-175, -70, t, fontsize=16, transform=ccrs.PlateCarree())


    labels = diag.get_labels()
    
    cb = plt.colorbar(cs, shrink=0.5, pad=.04, extend='both')
    cb.set_label(labels[diag.ftype]['xlabel'], fontsize=12)
    
    title_split = labels[diag.ftype]['left_title'].split('\n')
    plt.title("%s\n%s" % (title_split[0], '\n'.join(wrap(title_split[-1], 40))), loc='left', fontsize=14)
    plt.title(labels[diag.ftype]['right_title'], loc='right', fontweight='semibold', fontsize=14)
    plt.savefig(labels[diag.ftype]['save_title'], bbox_inches='tight', pad_inches=0.1)
    
    return 0
예제 #13
0
def plt_ref_vertical(figname):

    f = Dataset(figname, mode='r')
    print(f)
    nlon = f.dimensions['lon'].size
    nlat = f.dimensions['lat'].size
    lat = f.variables['lats'][:]
    lon = f.variables['lons'][:]
    sphum = f.variables['sphum'][:, :, :, :]
    temp = f.variables['T'][:, :, :, :]
    f.close()

    x, y = np.meshgrid(lon, lat)

    print(x[:, :])
    print(y[:, :])

    # create figure and axes instances
    plt.figure(figsize=(15, 12))
    ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=0))
    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    #  ax.coastlines()
    ax.set_extent([-180, 180, -90, 90])

    #  cmap,bounds,norm=ncepy.create_ncep_radar_ref_color_table()
    #  cs=plt.scatter(glat,nlev,c=oref,s=58,cmap=cmap,norm=norm,marker="s",edgecolor='none')
    #  cmap=plt.get_cmap("Greys")

    data = np.zeros((nlat, nlon))
    data[:, :] = temp[0, 0, :, :]
    print(data)
    upperbound = np.max(data)
    lowerbound = np.min(data)
    bins = (upperbound - lowerbound) / 10.0
    clevs = np.arange(lowerbound, upperbound + bins, bins)
    norm = colors.BoundaryNorm(boundaries=clevs, ncolors=256)

    #cs=plt.scatter(x,y,c=pres,s=40,cmap=cmap,norm=norm,marker=(verts_function(1,1,0.25),0),edgecolor='none')
    #cs=plt.scatter(x,y,c=pres,s=40,cmap='bwr',norm=norm,marker="s",edgecolor='none')
    #cs=plt.scatter(x,y,c=data,s=10,cmap='bwr',norm=norm,transform=ccrs.PlateCarree())
    cs = plt.contourf(x,
                      y,
                      data,
                      clevs,
                      cmap='bwr',
                      transform=ccrs.PlateCarree())

    cb = plt.colorbar(cs, shrink=0.5, pad=.04, extend='both')
    cb.ax.tick_params(labelsize=5.0)

    #  plt.ylim([0,60])
    #  plt.xlim([24,52])
    #  plt.title(titlename+' latitude CREF',fontsize=25)

    #  clevs=bins
    #  cbar = plt.colorbar(cs,location='bottom',pad=0.05,ticks=clevs)

    #  titlename=
    plt.savefig('./' + figname + '.png', bbox_inches='tight', dpi=100)
예제 #14
0
def plot_world_map(tiles, lons, lats, data, metadata, plotpath, screen, lonr,
                   latr, extreme, comment):
    # plot generic world map
    if screen.upper() == "NO":
        matplotlib.use('agg')
    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(1,
                         1,
                         1,
                         projection=ccrs.PlateCarree(central_longitude=0))
    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    listWE = lonr.split(',')
    listSN = latr.split(',')
    lonBeg = lonS2F(listWE[0])
    lonEnd = lonS2F(listWE[1])
    latBeg = latS2F(listSN[0])
    latEnd = latS2F(listSN[1])
    ax.set_extent([lonBeg, lonEnd, latBeg, latEnd])
    # dealing with missing values (assuming absolute values > 1.E8)
    data_new = data.copy()
    data_new[abs(data) > 1.E8] = np.nan
    if not extreme == '':
        strMinMax = extreme.split(',')
        vmin = float(strMinMax[0])
        vmax = float(strMinMax[1])
        invalid = np.logical_or(
            data_new == np.nan, np.logical_or(data_new > vmax,
                                              data_new < vmin))
        data_new[invalid] = np.nan
        data_new = np.ma.masked_where(np.isnan(data_new), data_new)
    vmin = np.nanmin(data_new)
    vmax = np.nanmax(data_new)
    #vmax = np.nanmean(data_new)+np.nanstd(data_new)*2
    #vmin = np.nanmean(data_new)-np.nanstd(data_new)*2
    cmap = 'viridis'
    cbarlabel = '%s' % (metadata['var'])
    if comment == '':
        plttitle = 'Variable: %s' % (metadata['var'])
    else:
        plttitle = 'Variable: %s; %s' % (metadata['var'], comment)
    for t in range(tiles):
        cs = ax.pcolormesh(lons[..., t],
                           lats[..., t],
                           data_new[..., t],
                           vmin=vmin,
                           vmax=vmax,
                           cmap=cmap)
    cb = plt.colorbar(cs, orientation='horizontal', shrink=0.5, pad=.04)
    cb.set_label(cbarlabel, fontsize=12)
    plt.title(plttitle)
    if screen.upper() == "NO" or screen.upper() == "ALL":
        plt.savefig(plotpath)
        if screen.upper() == "ALL":
            plt.show()
        plt.close('all')
    else:
        plt.show()
예제 #15
0
def pltallbuoytracks(loc, BD):
    Buoys = ['02', '03', '09', '07', '12', '13', '14', '16']
    fig = plt.figure(figsize=(12, 12), frameon=True)
    ax = plt.axes(projection=ccrs.LambertAzimuthalEqualArea(
        central_longitude=25.0, central_latitude=77.0))
    ax.set_extent([16, 28, 74.5, 80])
    colors = [
        'red', 'green', 'magenta', 'darkblue', 'lime', 'orange', 'yellow',
        'olive'
    ]
    fig.canvas.draw()
    xticks = [0, 4, 12, 16, 20, 24, 28, 32, 36]
    yticks = [72, 74.5, 77, 79.5, 82]
    ax.gridlines(xlocs=xticks, ylocs=yticks)
    # Label the end-points of the gridlines using the custom tick makers:
    ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER)
    ax.yaxis.set_major_formatter(LATITUDE_FORMATTER)
    lambert_xticks(ax, xticks)
    lambert_yticks(ax, yticks)
    i = 0
    pt = 96 * 1
    for b in Buoys:
        # Plotting b-uoy obs and buoy simulated locations
        Xib = BD[b + '_x']
        Yib = BD[b + '_y']
        plt.scatter(Xib[pt],
                    Yib[pt],
                    color='black',
                    transform=ccrs.PlateCarree())
        plt.text(Xib[pt],
                 Yib[pt],
                 b,
                 transform=ccrs.PlateCarree(),
                 fontsize=15,
                 fontweight='bold')
        plt.plot(Xib[pt:],
                 Yib[pt:],
                 color=colors[i],
                 transform=ccrs.PlateCarree(),
                 label=b)
        i += 1
    # gebco wms background
    service = 'https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?'
    ax.add_wms(service,
               layers=['GEBCO_LATEST'],
               wms_kwargs={
                   'width': 900 * 2,
                   'height': 600 * 2
               })
    feature = cpf.GSHHSFeature(scale='i',
                               levels=[1],
                               facecolor='#e6e1e1',
                               alpha=1)
    ax.add_feature(feature)
    plt.savefig(loc + '/allbuoytracks.jpg', format='jpg', dpi=600)
    plt.close(fig)
예제 #16
0
파일: geometry.py 프로젝트: serazing/seaobs
def add_map(lon_min=-180,
            lon_max=180,
            lat_min=-90,
            lat_max=90,
            central_longitude=0.,
            scale='auto',
            ax=None):
    """
    Add the map to the existing plot using cartopy

    Parameterss
    ----------
    lon_min : float, optional
        Western boundary, default is -180
    lon_max : float, optional
        Eastern boundary, default is 180
    lat_min : float, optional
        Southern boundary, default is -90
    lat_max : float, optional
        Northern boundary, default is 90
    central_longitude : float, optional
        Central longitude, default is 180
    scale : {‘auto’, ‘coarse’, ‘low’, ‘intermediate’, ‘high, ‘full’}, optional
        The map scale, default is 'auto'
    ax : GeoAxes, optional
        A new GeoAxes will be created if None

    Returns
    -------
    ax : GeoAxes
    Return the current GeoAxes instance
    """
    extent = (lon_min, lon_max, lat_min, lat_max)
    if ax is None:
        ax = plt.subplot(
            1,
            1,
            1,
            projection=ccrs.PlateCarree(central_longitude=central_longitude))
    ax.set_extent(extent)
    land = cfeature.GSHHSFeature(scale=scale,
                                 levels=[1],
                                 facecolor=cfeature.COLORS['land'])
    ax.add_feature(land)
    gl = ax.gridlines(draw_labels=True,
                      linestyle=':',
                      color='black',
                      alpha=0.5)
    gl.xlabels_top = False
    gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    return ax
예제 #17
0
파일: mapping.py 프로젝트: ivicajan/seapy
    def land(self, facecolor="white", **kwargs):
        """
        Draw the land mask

        Parameters
        ----------
        facecolor: string, optional
            color to draw the mask with
        **kwargs: additional arguments to add_feature
        """
        self.ax.add_feature(cft.GSHHSFeature(self.res, [1]),
                            facecolor=facecolor, **kwargs)
예제 #18
0
def plotMap():
    #Set the projection information
    proj = ccrs.PlateCarree()
    #Create a figure with an axes object on which we will plot. Pass the projection to that axes.
    fig, ax = plt.subplots(subplot_kw=dict(projection=proj))

    #Zoom in
    img_extent = [140, 162, 34, 50]
    ax.set_extent(img_extent, crs=proj)

    #Add map features
    # ax.add_feature(cfeature.LAND, facecolor='0.9'
    # )  #Grayscale colors can be set using 0 (black) to 1 (white)

    land_50m = cfeature.NaturalEarthFeature('physical',
                                            'land',
                                            '50m',
                                            edgecolor='face',
                                            facecolor=cfeature.COLORS['land'])
    ax.add_feature(land_50m)
    ax.add_feature(
        cfeature.LAKES,
        alpha=0.9)  #Alpha sets transparency (0 is transparent, 1 is solid)
    ax.add_feature(cfeature.BORDERS, zorder=10)
    # ax.add_feature(cfeature.COASTLINE, zorder=10)
    gshhs = cfeature.GSHHSFeature(scale='i', levels=None)
    ax.add_feature(gshhs)

    #We can use additional features from Natural Earth (http://www.naturalearthdata.com/features/)
    states_provinces = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_1_states_provinces_lines',
        scale='50m',
        facecolor='none')
    ax.add_feature(states_provinces, edgecolor='gray', zorder=10)

    #Add lat/lon gridlines every 20° to the map
    gl = ax.gridlines(crs=ccrs.PlateCarree(),
                      draw_labels=True,
                      linewidth=0.1,
                      alpha=1,
                      linestyle='-')
    gl.xlabels_top = False
    gl.ylabels_left = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER

    ax.text(142.2, 43.5, 'Hokkaido', transform=proj)
    ax.text(140.4, 39.7, 'Honshu', transform=proj)

    return fig, ax
예제 #19
0
파일: coast2wkb.py 프로젝트: bjornaa/xroms0
def coast2wkb(lonmin, lonmax, latmin, latmax, GSHHSres, coastfile):

    # Global cartopy feature from GSHHS
    gfeat = cfeature.GSHHSFeature(scale=GSHHSres)
    # As shapely collection generator
    coll = gfeat.geometries()

    # Polygon representation of  the regional domain
    frame = geom.box(lonmin, latmin, lonmax, latmax)

    # The intersection
    B = (frame.intersection(p) for p in coll if frame.intersects(p))

    # Save to file
    with open(coastfile, mode='wb') as fp:
        wkb.dump(geom.MultiPolygon(flatten(B)), fp, output_dimension=2)
예제 #20
0
def plot_spatial(data, metadata, lats, lons):

    stats = calculate_stats(data)

    plt.figure(figsize=(15, 12))
    ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=0))
    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    ax.set_extent([-180, 180, -90, 90])

    upperbound = (np.round(stats['Std'] * 2) / 2) * 5
    lowerbound = 0 - upperbound
    bins = (upperbound - lowerbound) / 10

    norm = mcolors.BoundaryNorm(boundaries=np.arange(lowerbound,
                                                     upperbound + bins, bins),
                                ncolors=256)

    cs = plt.scatter(
        lons,
        lats,
        c=data,
        s=30,
        norm=norm,
        cmap='bwr',  #edgecolors='gray', linewidth=0.25,
        transform=ccrs.PlateCarree())

    labels = plot_labels(metadata, stats)

    ax.text(-175,
            -70,
            labels['statText'],
            fontsize=14,
            transform=ccrs.PlateCarree())

    cb = plt.colorbar(cs, shrink=0.5, pad=.04, extend='both')
    cb.set_label(labels['xLabel'], fontsize=12)

    plt.title(labels['leftTitle'], loc='left', fontsize=14)
    plt.title(labels['dateTitle'],
              loc='right',
              fontweight='semibold',
              fontsize=14)
    plt.savefig('%s_spatial.png' % labels['saveFile'],
                bbox_inches='tight',
                pad_inches=0.1)

    return
예제 #21
0
def _plot_geographic_context(ax, hires=False):
    """
    Plot geographic basemap information on a map axis. Plots simple coastlines for
    unprojected plots.

    Args:
        ax (:class:`~cartopy.mpl.geoaxes.GeoAxes`): Existing axis to plot into
        hires (bool): If `True`, use higher-resolution coastlines (default: `False`)
    """

    # Since unprojected grids have regional/global extent, just show the
    # coastlines and borders
    if hires:
        gshhs_scale = 'intermediate'
        lake_scale = '10m'
    else:
        gshhs_scale = 'low'
        lake_scale = '50m'

    ax.add_feature(
        cfeature.GSHHSFeature(scale=gshhs_scale),
        facecolor=cfeature.COLORS['land'],
        zorder=0,
    )
    ax.background_patch.set_facecolor(cfeature.COLORS['water'])
    ax.add_feature(
        cfeature.LAKES.with_scale(lake_scale),
        facecolor=cfeature.COLORS['water'],
        edgecolor='black',
        zorder=0,
    )

    # Add states and provinces borders
    states_provinces = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_1_states_provinces_lines',
        scale='50m',
        facecolor='none')
    ax.add_feature(states_provinces, edgecolor='gray')
    ax.add_feature(cfeature.BORDERS, edgecolor='gray')
    # Add gridlines and labels
    ax.gridlines(draw_labels=["x", "y", "left", "bottom"],
                 linewidth=1,
                 color='gray',
                 alpha=0.5,
                 linestyle='--')
예제 #22
0
def no_data_spatial(metadata, outDir='./'):
    fig = plt.figure(figsize=(15,12))
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=0))

    ax.add_feature(cfeature.GSHHSFeature(scale='auto'))
    ax.set_extent([-180, 180, -90, 90])

    stats = None
    labels = plot_labels(metadata, stats)

    ax.text(0,0, 'No Data', fontsize=32, alpha=0.6, ha='center')
    plt.title(labels['leftTitle'], loc='left', fontsize=14)
    plt.title(labels['dateTitle'], loc='right', fontweight='semibold', fontsize=14)
    plt.savefig(outDir+'/%s_spatial.png' % labels['saveFile'], bbox_inches='tight', pad_inches=0.1)
    plt.close('all')
    
    return
예제 #23
0
def plticepos(Xib, Yib, Xis, Yis, path):
    fig = plt.figure(figsize=(12, 12), frameon=True)
    ax = plt.axes(projection=ccrs.LambertAzimuthalEqualArea(
        central_longitude=25.0, central_latitude=77.0))
    # ax.set_extent([15,33,74,81])
    ax.set_extent([16, 28, 74, 78])
    # Define gridline locations and draw the lines using cartopy's built-in gridliner:
    # *must* call draw in order to get the axis boundary used to add ticks:
    fig.canvas.draw()
    xticks = [0, 4, 12, 16, 20, 24, 28, 32, 36]
    yticks = [72, 74, 76, 78, 80, 82]
    ax.gridlines(xlocs=xticks, ylocs=yticks)
    # Label the end-points of the gridlines using the custom tick makers:
    ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER)
    ax.yaxis.set_major_formatter(LATITUDE_FORMATTER)
    lambert_xticks(ax, xticks)
    lambert_yticks(ax, yticks)

    # Plotting buoy obs and buoy simulated locations
    plt.plot(Xib,
             Yib,
             color='red',
             transform=ccrs.PlateCarree(),
             label='buoy drift')
    plt.plot(Xis,
             Yis,
             '--',
             color='yellow',
             transform=ccrs.PlateCarree(),
             label='simulated ice drift')
    # gebco wms background
    service = 'https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?'
    ax.add_wms(service,
               layers=['GEBCO_LATEST'],
               wms_kwargs={
                   'width': 900 * 2,
                   'height': 600 * 2
               })
    feature = cpf.GSHHSFeature(scale='i',
                               levels=[1],
                               facecolor='#e6e1e1',
                               alpha=1)
    ax.add_feature(feature)
    plt.legend(prop={"size": 16}, framealpha=1)
    plt.savefig(path + '/ice_drift.jpg', dpi=400)
    plt.close(fig)
예제 #24
0
파일: plotting.py 프로젝트: rodcanada/rtm
def _plot_geographic_context(ax, utm, hires=False):
    """
    Plot geographic basemap information on a map axis. Plots a background image
    for UTM-projected plots and simple coastlines for unprojected plots.

    Args:
        ax (:class:`~cartopy.mpl.geoaxes.GeoAxes`): Existing axis to plot into
        utm (bool): Flag specifying if the axis is projected to UTM or not
        hires (bool): If `True`, use higher-resolution images/coastlines
            (default: `False`)
    """

    # Since projected grids cover less area and may not include coastlines,
    # use a background image to provide geographical context (can be slow)
    if utm:
        if hires:
            zoom_level = 12
        else:
            zoom_level = 8
        ax.add_image(Stamen(style='terrain-background'), zoom_level)

    # Since unprojected grids have regional/global extent, just show the
    # coastlines
    else:
        if hires:
            gshhs_scale = 'intermediate'
            lake_scale = '10m'
        else:
            gshhs_scale = 'low'
            lake_scale = '50m'

        ax.add_feature(
            cfeature.GSHHSFeature(scale=gshhs_scale),
            facecolor=cfeature.COLORS['land'],
            zorder=0,
        )
        ax.background_patch.set_facecolor(cfeature.COLORS['water'])
        ax.add_feature(
            cfeature.LAKES.with_scale(lake_scale),
            facecolor=cfeature.COLORS['water'],
            edgecolor='black',
            zorder=0,
        )
예제 #25
0
파일: core.py 프로젝트: rom-py/rompy
    def plot(self, fscale=10):
        import matplotlib.pyplot as plt
        import cartopy.crs as ccrs
        import cartopy.feature as cfeature
        import cartopy.mpl.ticker as cticker
        from shapely.geometry import MultiPoint
        from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

        # First set some plot parameters:
        bbox = self.bbox(buffer=0.1)
        minLon, minLat, maxLon, maxLat = bbox
        extents = [minLon, maxLon, minLat, maxLat]

        # create figure and plot/map
        fig, ax = plt.subplots(1,
                               1,
                               figsize=(fscale, fscale * (maxLon - minLon) /
                                        (maxLat - minLat)),
                               subplot_kw={'projection': ccrs.PlateCarree()})
        ax.set_extent(extents, crs=ccrs.PlateCarree())

        coastline = cfeature.GSHHSFeature(scale='auto',
                                          edgecolor='black',
                                          facecolor=cfeature.COLORS['land'])
        ax.add_feature(coastline, zorder=0)
        ax.add_feature(cfeature.BORDERS, linewidth=2)

        gl = ax.gridlines(crs=ccrs.PlateCarree(),
                          draw_labels=True,
                          linewidth=2,
                          color='gray',
                          alpha=0.5,
                          linestyle='--')

        gl.xformatter = LONGITUDE_FORMATTER
        gl.yformatter = LATITUDE_FORMATTER

        # Plot the model domain
        bx, by = self.boundary_points()
        poly = plt.Polygon(list(zip(bx, by)), facecolor='r', alpha=0.05)
        ax.add_patch(poly)
        ax.plot(bx, by, lw=2, color='k')
        return fig, ax
예제 #26
0
파일: plotting.py 프로젝트: rom-py/rompy
def scatter(ds,
            color,
            minLon=None,
            minLat=None,
            maxLon=None,
            maxLat=None,
            fscale=10):
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    from datetime import datetime
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature
    import cartopy.mpl.ticker as cticker
    from shapely.geometry import MultiPoint
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

    # First set some plot parameters:
    if not minLon: minLon = ds.LONGITUDE.min().values.item()
    if not minLat: minLat = ds.LATITUDE.min().values.item()
    if not maxLon: maxLon = ds.LONGITUDE.max().values.item()
    if not maxLat: maxLat = ds.LATITUDE.max().values.item()
    extents = [minLon, maxLon, minLat, maxLat]

    # create figure and plot/map
    fig, ax = plt.subplots(1,
                           1,
                           figsize=(fscale, fscale * (maxLon - minLon) /
                                    (maxLat - minLat)),
                           subplot_kw={'projection': ccrs.PlateCarree()})
    ax.set_extent(extents, crs=ccrs.PlateCarree())

    coastline = cfeature.GSHHSFeature(scale='auto',
                                      edgecolor='black',
                                      facecolor=cfeature.COLORS['land'])
    ax.add_feature(coastline, zorder=0)
    ax.add_feature(cfeature.BORDERS, linewidth=2)

    gl = ax.gridlines(crs=ccrs.PlateCarree(),
                      draw_labels=True,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--')

    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER

    if 'PARTITION' in ds:
        sc = ax.scatter(
            [ds.sel(PARTITION=part).LONGITUDE for part in ds.PARTITION],
            [ds.sel(PARTITION=part).LATITUDE for part in ds.PARTITION],
            c=[ds.sel(PARTITION=part)[color] for part in ds.PARTITION])
    else:
        sc = ax.scatter(ds.LONGITUDE, ds.LATITUDE, c=ds[color])

    axins0 = inset_axes(ax,
                        width="5%",
                        height="100%",
                        loc='lower left',
                        bbox_to_anchor=(1.07, 0, 1, 1),
                        bbox_transform=ax.transAxes)
    cb = fig.colorbar(sc,
                      orientation='vertical',
                      cax=axins0,
                      ticklocation='right')
    if color == 'TIME':
        cb.ax.set_yticklabels([
            (datetime.fromtimestamp(i // 10**9)).strftime('%b %d %Y')
            for i in cb.get_ticks()
        ])
    if 'units' in ds[color].attrs.keys():
        cb.set_label(f"{ds[color].standard_name}\n [{ds[color].units}]")

    return fig, ax
예제 #27
0
파일: CAO_index.py 프로젝트: ainajoh/islas
def Z500_VEL(datetime, steps=0, model= "MEPS", domain_name = None, domain_lonlat = None, legend=False, info = False,grid=True):

  for dt in datetime: #modelrun at time..
    date = dt[0:-2]
    hour = int(dt[-2:])
    param_sfc = ["air_pressure_at_sea_level", "surface_geopotential"]
    param_pl = ["air_temperature_pl", "geopotential_pl"]  #"air_temperature_2m",
    param_sfx = ["SST","SIC"] #add later
    p_levels = [850,1000]
    param = param_sfc + param_pl
    split = False
    print("\n######## Checking if your request is possible ############")
    try:
      check_all = check_data(date=dt, model=model, param=param, levtype="pl", p_level=p_levels, step=steps)
      check_sfx = check_data(date=dt, model=model, param=param_sfx, step=steps)

    except ValueError:
      split = True
      try:
        print("--------> Splitting up your request to find match ############")
        check_sfc = check_data(date=dt, model=model, param=param_sfc)
        check_pl = check_data(date=dt, model=model, param=param_pl, levtype="pl", p_level=p_levels)
        check_sfx = check_data(date=dt, model=model, param=param_sfx)

        print(check_pl.file)
      except ValueError:
        print("!!!!! Sorry this plot is not availbale for this date. Try with another datetime !!!!!")
        break
    print("--------> Found match for your request ############")


    if not split:
      file_all = check_all.file.loc[0]

      data_domain = domain_input_handler(dt, model,domain_name, domain_lonlat, file_all)

      #lonlat = np.array(data_domain.lonlat)
      dmap_meps = get_data(model=model, data_domain=data_domain, param=param, file=file_all, step=steps,
                           date=dt, p_level=p_levels)
      dmap_mepsdfx = get_data(model=model, data_domain=data_domain, param=param_sfx, file=check_sfx.file.loc[0], step=steps,date=dt)
      print("\n######## Retrieving data ############")
      print(f"--------> from: {dmap_meps.url} ")
      dmap_meps.retrieve()
      tmap_meps = dmap_meps # two names for same value, no copying done.
      dmap_mepsdfx.retrieve()
    else:
      # get sfc level data
      file_sfc = check_sfc.file.loc[0]
      data_domain = domain_input_handler(dt, model,domain_name, domain_lonlat, file_sfc)
      #lonlat = np.array(data_domain.lonlat)
      dmap_meps = get_data(model=model, param=param_sfc, file=file_sfc, step=steps, date=dt, data_domain=data_domain)
      print("\n######## Retrieving data ############")
      print(f"--------> from: {dmap_meps.url} ")
      dmap_meps.retrieve()

      # get pressure level data
      file_pl = check_pl.file.loc[0]
      tmap_meps = get_data(model=model, data_domain=data_domain, param=param_pl, file=file_pl, step=steps, date=dt, p_level=p_levels)
      print("\n######## Retrieving data ############")
      print(f"--------> from: {tmap_meps.url} ")
      tmap_meps.retrieve()

      dmap_mepsdfx = get_data(model=model, data_domain=data_domain, param=param_sfx, file=check_sfx.file.loc[0],
                              step=steps,
                              date=dt)
      dmap_mepsdfx.retrieve()

    #CALCULATE

    pt = potential_temperatur(dmap_meps.air_temperature_pl, dmap_meps.pressure*100.)
    pt_sst = potential_temperatur(dmap_mepsdfx.SST, dmap_meps.air_pressure_at_sea_level[:,0,:,:])

    dpt = pt[:,np.where(dmap_meps.pressure==1000)[0],:,:]-pt[:,np.where(dmap_meps.pressure==850)[0],:,:]
    dpt_sst =pt_sst[:,:,:] - pt[:,np.where(dmap_meps.pressure==850)[0],:,:].squeeze()
    #dpt_sst =abs(pt_sst[:,:,:] - pt[:,np.where(dmap_meps.pressure==850)[0],:,:].squeeze())

    # convert fields
    dmap_meps.air_pressure_at_sea_level/=100
    tmap_meps.geopotential_pl/=10.0


    lon0 = dmap_meps.longitude_of_central_meridian_projection_lambert
    lat0 = dmap_meps.latitude_of_projection_origin_projection_lambert
    parallels = dmap_meps.standard_parallel_projection_lambert

    # setting up projection
    # setting up projection
    globe = ccrs.Globe(ellipse='sphere', semimajor_axis=6371000., semiminor_axis=6371000.)
    crs = ccrs.LambertConformal(central_longitude=lon0, central_latitude=lat0, standard_parallels=parallels,
                                 globe=globe)

    for tim in np.arange(np.min(steps), np.max(steps)+1, 1):
      fig1, ax1 = plt.subplots(1, 1, figsize=(7, 9),
                               subplot_kw={'projection': crs})
      ttt = tim #+ np.min(steps)
      tidx = tim - np.min(steps)
      print('Plotting {0} + {1:02d} UTC'.format(dt, ttt))
      plev2 = 0
      embr = 0
      ZS = dmap_meps.surface_geopotential[tidx, 0, :, :]
      MSLP = np.where(ZS < 3000, dmap_meps.air_pressure_at_sea_level[tidx, 0, :, :], np.NaN).squeeze()
      Z = (tmap_meps.geopotential_pl[tidx, plev2, :, :]).squeeze()
      DELTAPT=dpt[tidx, 0, :, :]
      DELTAPT = dpt_sst[tidx,:,:]
      ICE = dmap_mepsdfx.SIC[tidx, :, :]
      DELTAPT = np.where( ICE <= 0.99,DELTAPT,0)
      lvl = range(-1,13)
      C = [[255,255,255	],  # grey #[255,255,255],#gre
           [204,191,189	],  # grey
           [155,132,127	],  # grey
           [118,86,80],  # lillac, 39	64	197	149,53,229
           [138,109,81],  # blue dark,7,67,194 [218,81,14],
           [181,165,102],  #
           [229,226,124],  ##
           [213,250,128],
           [125,231,111],
           [55,212,95],
           [25,184,111],
           [17,138,234],
           [21,82,198],
           [37,34,137]]
      C = np.array(C)
      C = np.divide(C, 255.)  # RGB has to be between 0 and 1 in python
      CF_prec = plt.contourf(dmap_meps.x, dmap_meps.y, DELTAPT, zorder=0,
                            antialiased=True,extend = "max", levels=lvl, colors=C, vmin=0, vmax=12)#

      CF_ice = plt.contour(dmap_meps.x, dmap_meps.y, ICE, zorder=1, linewidths=2.5, colors="black", levels=[0.1, 0.5])  #
      # MSLP with contour labels every 10 hPa
      C_P = ax1.contour(dmap_meps.x, dmap_meps.y, MSLP, zorder=1, alpha=1.0,
                      levels=np.arange(round(np.nanmin(MSLP), -1) - 10, round(np.nanmax(MSLP), -1) + 10, 1),
                      colors='grey', linewidths=0.5)
      C_P = ax1.contour(dmap_meps.x, dmap_meps.y, MSLP, zorder=2, alpha=1.0,
                        levels=np.arange(round(np.nanmin(MSLP), -1) - 10, round(np.nanmax(MSLP), -1) + 10, 10),
                        colors='grey', linewidths=1.0)
      ax1.clabel(C_P, C_P.levels, inline=True, fmt="%3.0f", fontsize=10)

      #CS = ax1.contour(dmap_meps.x, dmap_meps.y, Z, zorder=3, alpha=1.0,
      #                  levels=np.arange(4600, 5800, 20), colors="blue", linewidths=0.7)
      #ax1.clabel(CS, CS.levels, inline=True, fmt="%4.0f", fontsize=10)

      ax1.add_feature(cfeature.GSHHSFeature(scale='intermediate'))  # ‘auto’, ‘coarse’, ‘low’, ‘intermediate’, ‘high, or ‘full’ (default is ‘auto’).
      ax1.text(0, 1, "{0}_CAOi_{1}+{2:02d}".format(model, dt, ttt), ha='left', va='bottom', transform=ax1.transAxes, color='black')

      ##########################################################
      legend=True
      if legend:
        proxy = [plt.axhline(y=0, xmin=1, xmax=1, color="grey"),
                plt.axhline(y=0, xmin=1, xmax=1, color="black",linewidth=4)]
        try:
          ax_cb = adjustable_colorbar_cax(fig1, ax1)

          plt.colorbar(CF_prec,cax = ax_cb, fraction=0.046, pad=0.01, aspect=25, label=r"$\theta_{SST}-\theta_{850}$", extend="both")

        except:
          pass

        lg = ax1.legend(proxy, [f"MSLP [hPa]",
                               f"Sea ice at 10%, 80%, 99%"])
        frame = lg.get_frame()
        frame.set_facecolor('white')
        frame.set_alpha(1)
      make_modelrun_folder = setup_directory(OUTPUTPATH, "{0}".format(dt))
      if grid:
        nicegrid(ax=ax1)

      if domain_name != model and data_domain != None:  # weird bug.. cuts off when sees no data value
        ax1.set_extent(data_domain.lonlat)
      print("filename: "+make_modelrun_folder + "/{0}_{1}_CAOi_{2}+{3:02d}.png".format(model, domain_name, dt, ttt))
      fig1.savefig(make_modelrun_folder + "/{0}_{1}_CAOi_{2}+{3:02d}.png".format(model, domain_name, dt, ttt), bbox_inches="tight", dpi=200)
      ax1.cla()
      plt.clf()
      plt.close(fig1)
  plt.close("all")
예제 #28
0
def plot2d_bias(cfg, plot_params):
    """Plot 2d maps of the bias relative to climatology.

    Parameters
    ----------
    model_filenames:OrderedDict
        OrderedDict with model names as keys and input files as values.
    cmor_var: str
        name of the variable
    depth: int
        we will plot the data on the model level
        that is closest to the `depth`.
    diagworkdir: str
        path to the working directory
    diagplotdir: str
        path to the plot directory
    levels: tuple
        values to be used for vmin and vmax in the form of (vmin, vmax)
    dpi: int
        the dpi values to save the figure
    observations: str
        name of the observations
    projection: instance of cartopy projection (ccrs)
    bbox: list
        bounding box. It will be the input for cartopy `set_extent`.
    ncols: int
        number of columns.

    Retuns
    ------
    None
    """
    # setupa a base figure
    figure, axis = create_plot(plot_params['model_filenames'],
                               ncols=plot_params['ncols'],
                               projection=plot_params['projection'])
    # get the filename of observations
    ifilename_obs = genfilename(cfg['work_dir'],
                                plot_params['variable'],
                                plot_params['observations'],
                                data_type='timmean',
                                extension='.nc')
    # get the metadata for observations (we just need a size)
    metadata = load_meta(
        datapath=plot_params['model_filenames'][plot_params['observations']],
        fxpath=None)
    lon2d = metadata['lon2d']

    # Create an empty array to store the mean.
    # One point larger along long to acount for cyclic point
    model_mean = np.zeros((lon2d.shape[0], lon2d.shape[1] + 1))
    print("MODEL MEAN SHAPE {}".format(model_mean.shape))

    # delete observations from the model list
    model_filenames = plot_params['model_filenames'].copy()
    del model_filenames[plot_params['observations']]
    # loop over models
    index = None
    for index, mmodel in enumerate(model_filenames):
        logger.info("Plot plot2d_bias %s for %s", plot_params['variable'],
                    mmodel)
        # get the filename with the mean generated by the `timemean`
        ifilename = genfilename(cfg['work_dir'],
                                plot_params['variable'],
                                mmodel,
                                data_type='timmean',
                                extension='.nc')
        # do the interpolation to the observation grid
        # the output is
        lonc, latc, target_depth, data_obs, interpolated = interpolate_esmf(
            ifilename_obs, ifilename, plot_params['depth'],
            plot_params['variable'])
        # get the label and convert data if needed
        cb_label, data_obs = label_and_conversion(plot_params['variable'],
                                                  data_obs)
        cb_label, interpolated = label_and_conversion(plot_params['variable'],
                                                      interpolated)
        # add to the mean model
        model_mean = model_mean + interpolated
        # set the map extent
        left, right, down, upper = plot_params['bbox']
        axis[index].set_extent([left, right, down, upper],
                               crs=ccrs.PlateCarree())
        # Only pcolormesh is working for now with cartopy,
        # contourf is failing to plot curvilinear meshes,
        # let along the unstructures ones.
        image = axis[index].contourf(
            lonc,
            latc,
            interpolated - data_obs,
            levels=plot_params['levels'],
            extend='both',
            # vmin=contours[0],
            # vmax=contours[-1],
            transform=ccrs.PlateCarree(),
            cmap=plot_params['cmap'],
        )
        # fill continents
        axis[index].add_feature(
            cfeature.GSHHSFeature(levels=[1],
                                  scale="low",
                                  facecolor="lightgray"))

        axis[index].set_title("{}, {} m".format(mmodel, int(target_depth)),
                              size=18)
        axis[index].set_rasterization_zorder(-1)
    # calculate the model mean and plot it
    if index:
        index = index
    else:
        index = 0
    model_mean = model_mean / len(model_filenames)
    axis[index + 1].set_extent([left, right, down, upper],
                               crs=ccrs.PlateCarree())
    image = axis[index + 1].contourf(
        lonc,
        latc,
        model_mean - data_obs,
        levels=plot_params['levels'],
        extend='both',
        # vmin=contours[0],
        # vmax=contours[-1],
        transform=ccrs.PlateCarree(),
        cmap=cmo.balance,
    )

    axis[index + 1].add_feature(
        cfeature.GSHHSFeature(levels=[1], scale="low", facecolor="lightgray"))

    axis[index + 1].set_title("Model mean bias, {} m".format(
        int(target_depth)),
                              size=18)
    axis[index + 1].set_rasterization_zorder(-1)
    # delete the axis that are not needed
    for delind in range(index + 2, len(axis)):
        figure.delaxes(axis[delind])
    # set common colorbar
    colorbar = figure.colorbar(image,
                               orientation='horizontal',
                               ax=axis,
                               pad=0.01,
                               shrink=0.9)
    colorbar.set_label(cb_label, rotation='horizontal', size=18)
    colorbar.ax.tick_params(labelsize=18)
    # save the picture
    pltoutname = genfilename(cfg['plot_dir'],
                             plot_params['variable'],
                             "MULTIMODEL",
                             data_type='plot2d_bias_{}_level'.format(
                                 str(int(target_depth))))

    plot_params['basedir'] = cfg['plot_dir']
    plot_params['ori_file'] = [ifilename]
    plot_params['areacello'] = None
    plot_params['mmodel'] = None
    plot_params['region'] = "Global"
    plt.savefig(pltoutname, dpi=plot_params['dpi'])

    provenance_record = get_provenance_record(plot_params, 'plot2d_bias',
                                              'png')
    with ProvenanceLogger(cfg) as provenance_logger:
        provenance_logger.log(pltoutname + '.png', provenance_record)
예제 #29
0
def main():
    """
    
    lon0 = 35.25; lat0 = -23.60
    lon1 = 35.25; lat1 = -24.0
    lon2 = 35.65; lat2 = -24.0
    lon3 = 35.65; lat3 = -23.60
   
    
    https://stackoverflow.com/questions/52356926/how-to-set-offset-for-python-cartopy-geometry
    """


    # Create the figure
    fig = plt.figure(figsize=(5,6))
 
    from cartopy.io.img_tiles import OSM 

           
    # Add OSM image as background for the selected extension
    tiler = OSM()
    ax = plt.axes(projection=tiler.crs)

    # Openstreet layer zoom detail
    zoom=12
    
    ax.add_image(tiler, zoom, alpha=0.75)

    extent = [35.25, 35.65, -24.05, -23.60]

    ax.set_extent(extent)

    # Set figure title
    ax.set_title('Study area',fontsize=10)


    # Plot coastline from GSHHSF
    coast_line=cfeature.GSHHSFeature(scale='full')
    
    ax.add_feature(coast_line,  alpha=1.0,  linewidths=0.5, edgecolor='black' )

        
    plotWetlands(ax)
    plotRivers(ax)
    

    plotInterestPoint(ax)
 
    # plot difters track
    plotTrack(ax) 


    # Plot escale bar
    scaleBar(ax, length=10, location=(0.8, 0.80), linewidth=1.5)
    
    plotGridLines(ax)
    
    # Criate a subfigure 
    #subfigure = [.58, .09, .30, .20]
    ax2 = fig.add_axes([.58, .09, .30, .20]) 
    plotMozambique(ax2)

    # Adjust plot the the figure
    plt.tight_layout()

    plt.show()

    saveFig(fig, file='estudyarea')
예제 #30
0
def plot2d_original_grid(cfg, plot_params):
    """Plot 2d maps on original grid using cartopy.

    Parameters
    ----------
    model_filenames:OrderedDict
        OrderedDict with model names as keys and input files as values.
    cmor_var: str
        name of the variable
    depth: int
        we will plot the data on the model
        level that is closest to the `depth`.
        Ignored if explicit_depths is provided.
    levels: tuple
        values to be used for vmin and vmax in the form of (vmin, vmax)
    diagworkdir: str
        path to the working directory
    diagplotdir: str
        path to the plot directory
    cmap:  matplotlib colormap
        colormap
    dpi: int
        the dpi values to save the figure
    explicit_depths: dict
        Output of the `aw_core` function.
        It's a dictionary where for each model there is a maximum temperature,
        depth level in the model, index of the depth level in the model.
        If provided the `depth` parameter is excluded.
    projection: instance of cartopy projection (ccrs)
    bbox: list
        bounding box. It will be the input for cartopy `set_extent`.
    ncols: int
        number of columns.

    Retuns
    ------
    None
    """
    figure, axis = create_plot(plot_params['model_filenames'],
                               ncols=plot_params['ncols'],
                               projection=plot_params['projection'])
    index = None
    for index, mmodel in enumerate(plot_params['model_filenames']):
        logger.info("Plot plot2d_original_grid %s for %s",
                    plot_params['variable'], mmodel)

        ifilename = genfilename(cfg['work_dir'],
                                plot_params['variable'],
                                mmodel,
                                data_type='timmean',
                                extension='.nc')

        metadata = load_meta(ifilename, fxpath=None)
        datafile = metadata['datafile']
        lon2d = metadata['lon2d']
        lat2d = metadata['lat2d']
        lev = metadata['lev']

        if not plot_params['explicit_depths']:
            depth_target, level_target = closest_depth(lev,
                                                       plot_params['depth'])
        else:
            level_target = plot_params['explicit_depths'][mmodel][
                'maxvalue_index']
            depth_target = lev[level_target]

        if datafile.variables[plot_params['variable']].ndim < 4:
            data = datafile.variables[plot_params['variable']][
                level_target, :, :]
        else:
            data = datafile.variables[plot_params['variable']][
                0, level_target, :, :]

        cb_label, data = label_and_conversion(plot_params['variable'], data)

        left, right, down, upper = plot_params['bbox']

        axis[index].set_extent([left, right, down, upper],
                               crs=ccrs.PlateCarree())
        # Only pcolormesh is working for now with cartopy,
        # contourf is failing to plot curvilinear meshes,
        # let along the unstructures ones.
        image = axis[index].pcolormesh(
            lon2d,
            lat2d,
            data,
            vmin=plot_params['levels'][0],
            vmax=plot_params['levels'][-1],
            transform=ccrs.PlateCarree(),
            cmap=plot_params['cmap'],
        )

        axis[index].add_feature(
            cfeature.GSHHSFeature(levels=[1],
                                  scale="low",
                                  facecolor="lightgray"))
        axis[index].set_title("{}, {} m".format(mmodel,
                                                np.round(depth_target, 1)),
                              size=18)
        axis[index].set_rasterization_zorder(-1)

    # delete unused axis
    for delind in range(index + 1, len(axis)):
        figure.delaxes(axis[delind])

    # set common colorbar
    colorbar = figure.colorbar(image,
                               orientation='horizontal',
                               ax=axis,
                               pad=0.01,
                               shrink=0.9)
    colorbar.set_label(cb_label, rotation='horizontal', size=18)
    colorbar.ax.tick_params(labelsize=18)

    if not plot_params['explicit_depths']:
        plot_type = 'plot2d_{}_depth'.format(str(plot_params['depth']))
    else:
        plot_type = "plot2d_different_levels"

    # save the figure
    pltoutname = genfilename(cfg['plot_dir'],
                             plot_params['variable'],
                             "MULTIMODEL",
                             data_type=plot_type)

    plot_params['basedir'] = cfg['plot_dir']
    plot_params['ori_file'] = [ifilename]
    plot_params['areacello'] = None
    plot_params['mmodel'] = None
    plot_params['region'] = "Global"
    plt.savefig(pltoutname, dpi=plot_params['dpi'])

    provenance_record = get_provenance_record(plot_params, 'plot2d', 'png')
    with ProvenanceLogger(cfg) as provenance_logger:
        provenance_logger.log(pltoutname + '.png', provenance_record)