コード例 #1
0
def drawSST(ax, map, longSST, latSST, filledSST, myalpha):
    # Input arrays has to be 2D
    print "Drawing SST: min %s and max %s" % (filledSST.min(), filledSST.max())
    x2, y2 = map(longSST, latSST)
    levels = np.arange(-2, 18, 0.5)
    #levels=np.arange(filledSST.min(), filledSST.max(),0.2)

    if myalpha > 0.99:
        CS2 = map.contourf(x2,
                           y2,
                           filledSST,
                           levels,
                           cmap=mpl_util.LevelColormap(levels,
                                                       cmap=cm.RdYlBu_r),
                           extend='both',
                           alpha=myalpha)
        #CS2 = map.pcolor(x2,y2,filledSST)

        plt.colorbar(CS2, orientation='vertical', extend='both', shrink=0.5)
    else:
        CS2 = map.contourf(x2,
                           y2,
                           filledSST,
                           levels,
                           cmap=mpl_util.LevelColormap(levels,
                                                       cmap=cm.RdYlBu_r),
                           extend='both',
                           alpha=myalpha)
コード例 #2
0
    def addBathymetry(self):

        etopo1 = '/Users/trondkr/Dropbox/NIVA/ETOPO1/ETOPO1_Ice_g_gmt4.grd'
        etopo = xr.open_dataset(etopo1)
        lats = etopo['y'].values
        lons = etopo['x'].values

        res = self.findSubsetIndices(self.llcrnrlat - 5, self.urcrnrlat + 5,
                                     self.llcrnrlon - 40, self.urcrnrlon + 10,
                                     lats, lons)
        res = [int(x) for x in res]

        bathy = etopo["z"][int(res[2]):int(res[3]),
                           int(res[0]):int(res[1])].values
        bathySmoothed = laplacefilter.laplace_filter(bathy, M=None)
        lon, lat = np.meshgrid(lons[res[0]:res[1]], lats[res[2]:res[3]])

        levels = [
            -6000, -5000, -4000, -3500, -3000, -2500, -2000, -1750, -1500,
            -1250, -1000, -750, -500, -400, -300, -250, -200, -150, -100, -50,
            -10
        ]
        x, y = self.mymap(lon, lat)
        etopo_contour = self.mymap.contourf(x,
                                            y,
                                            bathySmoothed,
                                            levels,
                                            cmap=mpl_util.LevelColormap(
                                                levels, cmap=cm.Blues_r),
                                            extend='upper',
                                            alpha=1.0,
                                            origin='lower')
コード例 #3
0
def plotMap(lon,
            lat,
            mydata,
            period,
            qctype,
            season,
            hotspotsLon=None,
            hotspotsLat=None,
            hostpotsVals=None):
    plt.figure(figsize=(12, 12), frameon=False)
    mymap = Basemap(projection='npstere', lon_0=0, boundinglat=50)
    llat, llon = np.meshgrid(lat, lon)

    x, y = mymap(llon, llat)
    step = (np.max(mydata) - np.min(mydata)) / 10.

    if step > 0:
        print("Plotting season: {} for period {}".format(season, period))

        levels = np.arange(np.min(mydata), np.max(mydata), step)
        levels = np.arange(-1, 6, 0.2)

        print("Number of masked points {}".format(np.sum(mydata.mask == True)))
        CS1 = mymap.contourf(x,
                             y,
                             mydata,
                             levels,
                             cmap=mpl_util.LevelColormap(levels,
                                                         cmap=cm.RdBu_r))

        mymap.drawparallels(np.arange(-90., 120., 15.),
                            labels=[1, 0, 0, 0])  # draw parallels
        mymap.drawmeridians(np.arange(0., 420., 30.),
                            labels=[0, 1, 0, 1])  # draw meridians

        mymap.drawcoastlines()
        mymap.drawcountries()
        if not (hotspotsLat is None and hotspotsLon is None):
            hlon, hlat = mymap(hotspotsLon, hotspotsLat)
            mymap.scatter(hlon,
                          hlat,
                          s=100,
                          alpha=0.5,
                          color='r',
                          edgecolors='k')
        mymap.fillcontinents(color='grey', alpha=0.2)
        plt.colorbar(CS1, shrink=0.5)
        title('QC:' + str(period) + ' season:' + str(season))

        CS1.axis = 'tight'
        if not os.path.exists("Figures"):
            os.mkdir("Figures/")
        plotfile = 'Figures/map_qc_' + str(period) + '_season_' + str(
            season) + '.png'

        plt.savefig(plotfile, dpi=100)
        plt.clf()
        plt.close()
コード例 #4
0
def plotMap(lon, lat, mydata, modelName, scenario, mydate, mytype):

    plt.figure(figsize=(12, 12), frameon=False)
    mymap = Basemap(projection='npstere', lon_0=0, boundinglat=65)

    x, y = mymap(lon, lat)
    if mytype == "anomalies":
        levels = np.arange(np.min(mydata), np.max(mydata), 1)
        #levels=np.arange(-2,5,0.1)
    else:
        levels = np.arange(np.min(mydata), np.max(mydata), 5)
        #levels=np.arange(-2,15,0.5)

    CS1 = mymap.contourf(x,
                         y,
                         mydata,
                         levels,
                         cmap=mpl_util.LevelColormap(levels, cmap=cm.RdBu_r),
                         extend='max',
                         antialiased=False)

    mymap.drawparallels(np.arange(-90., 120., 15.),
                        labels=[1, 0, 0, 0])  # draw parallels
    mymap.drawmeridians(np.arange(0., 420., 30.), labels=[0, 1, 0,
                                                          1])  # draw meridians

    mymap.drawcoastlines()
    mymap.drawcountries()
    mymap.fillcontinents(color='grey')
    plt.colorbar(CS1, shrink=0.5)
    if (mytype == "anomalies"):
        title('Model:' + str(modelName) + ' Year:' + str(mydate.year) +
              ' Month:' + str(mydate.month))

    if (mytype == "regular"):
        title('Model:' + str(modelName) + ' Year:' + str(mydate.year) +
              ' Month:' + str(mydate.month))

    #CS1.axis='tight'
    #plt.show()
    if not os.path.exists("Figures"):
        os.mkdir("Figures/")
    if (mytype == "anomalies"):
        plotfile = 'figures/map_anomalies_' + str(modelName) + '_' + str(
            mydate.year) + '_' + str(mydate.month) + '.png'
    else:
        plotfile = 'figures/map_' + str(modelName) + '_' + str(
            mydate.year) + '_' + str(mydate.month) + '.png'
    plt.savefig(plotfile, dpi=300)
    plt.clf()
    plt.close()
コード例 #5
0
def plotMap(lon, lat, mydata, period, qctype, season):
    plt.figure(figsize=(12, 12), frameon=False)
    mymap = Basemap(projection='npstere', lon_0=0, boundinglat=50)

    llat, llon = np.meshgrid(lat, lon)
    print("Plotting season: {} for period {}".format(season, period))
    x, y = mymap(llon, llat)
    print(np.min(mydata), np.max(mydata))
    levels = np.arange(np.min(mydata), np.max(mydata), 0.01)
    # levels = [0, 1]

    CS1 = mymap.contourf(x,
                         y,
                         mydata,
                         levels,
                         cmap=mpl_util.LevelColormap(levels, cmap=cm.RdBu_r),
                         extend='max')

    mymap.drawparallels(np.arange(-90., 120., 15.),
                        labels=[1, 0, 0, 0])  # draw parallels
    mymap.drawmeridians(np.arange(0., 420., 30.), labels=[0, 1, 0,
                                                          1])  # draw meridians

    mymap.drawcoastlines()
    mymap.drawcountries()
    mymap.fillcontinents(color='grey', alpha=0.2)
    plt.colorbar(CS1, shrink=0.5)
    title('QC:' + str(period) + ' season:' + str(season))

    CS1.axis = 'tight'
    if not os.path.exists("Figures"):
        os.mkdir("Figures/")
    plotfile = 'figures/map_qc_' + str(period) + '_season_' + str(
        season) + '.png'
    # plt.show()

    plt.savefig(plotfile, dpi=100, bbox_inches='tight')
    plt.clf()
    plt.close()
コード例 #6
0
def createNiceMap(grd, h):
    fig = plt.figure()
    levels = [10, 25, 50, 100, 250, 500, 1000, 2500, 5000]

    mymap = Basemap(llcrnrlon=-18.0,
                    llcrnrlat=46.0,
                    urcrnrlon=25.5,
                    urcrnrlat=67.5,
                    resolution='i',
                    projection='tmerc',
                    lon_0=0,
                    lat_0=50,
                    area_thresh=50.)

    # mymap.drawcoastlines()
    # mymap.drawcountries()
    # mymap.fillcontinents(color='grey')
    mymap.drawmeridians(np.arange(grd.hgrid.lon_rho.min(),
                                  grd.hgrid.lon_rho.max(), 10),
                        labels=[0, 0, 0, 1])
    mymap.drawparallels(np.arange(grd.hgrid.lat_rho.min(),
                                  grd.hgrid.lat_rho.max(), 4),
                        labels=[1, 0, 0, 0])

    x, y = mymap(grd.hgrid.lon_rho, grd.hgrid.lat_rho)

    CS1 = mymap.contourf(x,
                         y,
                         h,
                         levels,
                         cmap=mpl_util.LevelColormap(levels, cmap=cm.Blues),
                         extend='upper',
                         alpha=1.0,
                         origin='lower',
                         rasterized=True)
    CS1.axis = 'tight'
    plotfile = 'figures/map_KINO.pdf'
    plt.savefig(plotfile, dpi='200')
コード例 #7
0
def addEtopo1Bathymetry(ax, map):
    """Get the etopo1 data"""
    etopo1name = '/Users/trond/Projects/arcwarm/maps/ETOPO1_Ice_g_gmt4.grd'
    etopo1 = Dataset(etopo1name, 'r')

    lons = etopo1.variables["lon"][:]
    lats = etopo1.variables["lat"][:]

    res = findSubsetIndices(latStart - 5, latEnd + 5, lonStart - 40,
                            lonEnd + 10, lats, lons)

    lon, lat = np.meshgrid(lons[res[0]:res[1]], lats[res[2]:res[3]])
    print "Extracted data for area %s : (%s,%s) to (%s,%s)" % (
        name, lon.min(), lat.min(), lon.max(), lat.max())
    bathy = etopo1.variables["z"][int(res[2]):int(res[3]),
                                  int(res[0]):int(res[1])]
    bathySmoothed = laplaceFilter.laplace_filter(bathy, M=None)

    levels = [
        -6000, -5000, -3000, -2000, -1500, -1000, -500, -400, -300, -250, -200,
        -150, -100, -75, -65, -50, -35, -25, -15, -10, -5, 0
    ]

    x, y = map(lon, lat)
    CS1 = map.contourf(
        x,
        y,
        bathySmoothed,
        levels,
        cmap=mpl_util.LevelColormap(levels, cmap=cm.Blues_r),
        #cmap=cm.get_cmap('Greys_r',len(levels)),
        extend='upper',
        alpha=1.0,
        origin='lower',
        rasterized=True)

    CS1.axis = 'tight'
コード例 #8
0
ファイル: debugOBSfile.py プロジェクト: wangpengphd/romstools
def contourMap(myCDF, bathymetry,lonrho,latrho,myvar,survey,Nobs,obs,first):

    print "Plotting values for index %s to %s"%(sum(Nobs[0:survey]),sum(Nobs[0:survey])+obs)

    """Get the apporporiate grid"""
    lat      = myCDF.variables["obs_lat"][sum(Nobs[0:survey]):sum(Nobs[0:survey])+obs]
    lon      = myCDF.variables["obs_lon"][sum(Nobs[0:survey]):sum(Nobs[0:survey])+obs]
    xgrid    = myCDF.variables["obs_Xgrid"][sum(Nobs[0:survey]):sum(Nobs[0:survey])+obs]
    ygrid    = myCDF.variables["obs_Ygrid"][sum(Nobs[0:survey]):sum(Nobs[0:survey])+obs]
    obs_time = int(np.squeeze(myCDF.variables["obs_time"][sum(Nobs[0:survey]):sum(Nobs[0:survey])+1]))
    mydata   = myCDF.variables[myvar][sum(Nobs[0:survey]):sum(Nobs[0:survey])+obs]

    if sum(np.isnan(mydata)) > 0:
        print "DATA contains NAN!!!!!"
    if first is True:
        print "Max and min latitude: %s - %s"%(lat.max(), lat.min())
        print "Max and min longitude: %s - %s\n"%(lon.max(), lon.min())
        first=False

    """ Current time:"""
    refDate=datetime.datetime(1948,1,1,0,0,0)
    currentDate=refDate + datetime.timedelta(days=obs_time)
    print "Plotting timestep: %s"%(currentDate)

    """Start creating figure"""
    plt.figure(figsize=(10,10), frameon=False)

    map = Basemap(llcrnrlon=-18.0,
                  llcrnrlat=46.0,
                  urcrnrlon=25.5,
                  urcrnrlat=67.5,
                  resolution='i',projection='tmerc',lon_0=0,lat_0=50,area_thresh=50.)

    x, y = map(lon,lat)
    x2, y2 = map(lonrho,latrho)

    ax1=plt.subplot(1,1,1)
    map.drawcoastlines()
    map.fillcontinents(color='grey')
    map.drawcountries()
    map.drawmapboundary()
    print "Min %s and max %s of data"%(np.ma.min(mydata),np.ma.max(mydata))
    levels=np.arange(-2,18,0.5)

    map.scatter(x,y,s=4,c=mydata,cmap=mpl_util.LevelColormap(levels,cmap=cm.RdYlBu_r), edgecolor='none',vmin=-2, vmax=18)
    c = plt.colorbar(orientation='horizontal')
    c.set_label("Obs. SST")

   # h=bathymetry.flatten()
   #
   # ax1=plt.subplot(2,2,2)
   #
   # map.scatter(x,y,s=4,c=bathymetry/np.ma.max(bathymetry),cmap=cm.get_cmap('jet'), edgecolor='none')
   ## c = plt.colorbar(orientation='horizontal')
   # c.set_label("Bathymetry")
   #
   # ax2=plt.subplot(2,2,3)
   # scatter(xgrid,ygrid,s=4,c=mydata/np.ma.max(mydata),cmap=cm.get_cmap('jet'), edgecolor='none')
   # ax2.axis('tight')
   #
   # ax2=plt.subplot(2,2,4)
   # scatter(xgrid,ygrid,s=4,c=bathymetry/np.ma.max(bathymetry),cmap=cm.get_cmap('jet'), edgecolor='none')
   #
   # ax2.axis('tight')
    plotfile='figures/obs_'+str(myvar)+'_'+str(currentDate)+'.jpeg'

    plt.savefig(plotfile)
コード例 #9
0
def plotHistDistribution(shapefile, hist, xii, yii, polygon, experiment,
                         startdate, enddate, plotType):
    plt.clf()

    # plt.figure(figsize=(10,10), frameon=False)
    ax = plt.subplot(111)

    mymap = Basemap(llcrnrlon=17.0,
                    llcrnrlat=69.4,
                    urcrnrlon=19.0,
                    urcrnrlat=70.0,
                    resolution='h',
                    projection='merc',
                    lon_0=np.mean(np.array(xii)),
                    lat_0=np.mean(np.array(yii)),
                    area_thresh=0.)

    xiii, yiii = mymap(xii, yii)
    levels = np.arange(np.min(hist), np.max(hist), 1)
    # levels = np.arange(np.min(hist), 200, 1)
    levels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30]

    CS1 = mymap.contourf(xiii,
                         yiii,
                         np.fliplr(np.rot90(hist, 3)),
                         levels,
                         cmap=mpl_util.LevelColormap(levels,
                                                     cmap=cmocean.cm.haline),
                         origin='lower',
                         extend='both',
                         alpha=1.0)

    plt.colorbar(CS1, orientation='vertical', extend='both', shrink=0.5)
    mymap.drawcoastlines()
    mymap.fillcontinents(color='grey', zorder=2)
    mymap.drawcountries()
    mymap.drawmapboundary()

    mypatches = createPathsForPolygons(shapefile, mymap)
    # colors = 100 * np.random.rand(len(mypatches))
    # p = PatchCollection(mypatches, alpha=0.9, zorder=10)
    # p.set_array(np.array(colors))
    # ax.add_collection(p)

    p = PatchCollection(mypatches,
                        alpha=0.8,
                        facecolor='none',
                        lw=0.5,
                        edgecolor='red',
                        zorder=10)
    ax.add_collection(p)

    if plotType == "individual":
        p = PatchCollection([mypatches[polygon]],
                            alpha=0.9,
                            facecolor='darkorange',
                            lw=0.5,
                            edgecolor='darkorange',
                            zorder=10)
        ax.add_collection(p)

    if plotType == "all":
        p = PatchCollection(mypatches,
                            alpha=0.9,
                            facecolor='darkorange',
                            lw=0.5,
                            edgecolor='darkorange',
                            zorder=10)
        ax.add_collection(p)

    if plotType == "all":

        x = xii.flatten()
        y = yii.flatten()
        hh = np.fliplr(np.rot90(hist, 3))

        z = hh.flatten()

        np.savetxt("allDensityXYZ.csv", (x, y, z))

    # plt.title('Tare sedimentering')
    print "Adding %s release polygons to map" % (len(mypatches))
    # plt.show()

    if plotType == "individual":
        plotfilename = 'distributionFigures/Kelp_polygon_%s_experiment_%s_%s_to_%s.png' % (
            polygon + 1, experiment, startdate, enddate)

    if plotType == "all":
        plotfilename = 'distributionFigures/Kelp_allPolygons_experiment_%s_%s_to_%s.png' % (
            experiment, startdate, enddate)

    print "=> Creating plot %s" % plotfilename
    plt.savefig(plotfilename, dpi=300)
コード例 #10
0
def makeMapnewArctic(lonStart, lonEnd, latStart, latEnd, lat1, lon1, foutPath,
                     ax):
    #    fig= plt.figure(figsize=(10,8))
    """Get the etopo2 data"""
    #    etopo1name='ETOPO1_Ice_g_gmt4.grd'
    #    etopo1name='/home/xuj/work/project/topo/ETOPO1/ETOPO1_Bed_c_gmt4.grd'
    #    etopo1name='/home/xuj/work/project/topo/ETOPO1/barrowStrait.nc'

    #    etopo1name='/home/xuj/work/project/topo/ETOPO1/testnew.nc'
    etopo1name = '/home/xuj/work/project/whaleDectionRange/bathymetry/topo15_eastNew.nc'
    etopo1 = Dataset(etopo1name, 'r')

    lons = etopo1.variables["lon"][:]
    lats = etopo1.variables["lat"][:]

    #    lons = etopo1.variables["x"][:]
    #    lats = etopo1.variables["y"][:]

    print "lons:", max(lons), min(lons)
    print lons

    print "lats:", max(lats), min(lats)
    print lats

    print "lon,lat,start, end:", lonStart, lonEnd, latStart, latEnd
    print " lat lon start end:", latStart - 2, latEnd + 5, lonStart - 5, lonEnd + 5

    res = findSubsetIndices(latStart - 1, latEnd + 1, lonStart - 1, lonEnd + 1,
                            lats, lons)

    print "res:::", res

    lon, lat = np.meshgrid(lons[res[0]:res[1]], lats[res[2]:res[3]])

    print "shape of lon:", np.shape(lon)
    print "shape of lat:", np.shape(lat)
    #    exit(1)

    #    print "Extracted data for area %s : (%s,%s) to (%s,%s)"%(name,lon.min(),lat.min(),lon.max(),lat.max())
    bathy = etopo1.variables["z"][int(res[2]):int(res[3]),
                                  int(res[0]):int(res[1])]
    etopo1.close()
    #    z0 = etopo1.variables["z"][int(res[0]):int(res[1]),int(res[2]):int(res[3])]
    #    print ma.shape(z0)
    #    z = ma.array().flatten()

    bathySmoothed = laplaceFilter.laplace_filter(bathy, M=None)

    y = lons[res[0]:res[1]]
    x = lats[res[2]:res[3]]

    #    print ma.shape(z),ma.shape(x)
    #    zi = matplotlib.mlab.griddata(x,y,z,lat, lon)

    #    levels=[-5500,-5000,-2500, -2000, -1500, -1000,-500, -400, -300, -250, -200, -150, -100, -75, -65, -50, -35, -25, -15, -10, -5, 0]
    levels = [
        -5000, -4000, -3000, -1000, -500, -400, -300, -250, -200, -150, -100,
        -50, -20, -5, -1
    ]

    if lonStart < 0 and lonEnd < 0:
        lon_0 = -(abs(lonEnd) + abs(lonStart)) / 2.0
    else:
        lon_0 = (abs(lonEnd) + abs(lonStart)) / 2.0

    print 'Center longitude ', lon_0

    map = Basemap(llcrnrlat=latStart,urcrnrlat=latEnd,\
            llcrnrlon=lonStart,urcrnrlon=lonEnd,\
            rsphere=(6378137.00,6356752.3142),\
            resolution='h',area_thresh=1000.,projection='lcc',\
            lat_1=latStart,lon_0=lon_0,ax=ax)

    x, y = map(lon, lat)

    map.drawcoastlines(linewidth=0.5)
    map.drawcountries()
    map.fillcontinents(color='grey')
    map.drawmeridians(np.arange(int(lons.min()), int(lons.max()), 2),
                      labels=[0, 0, 0, 1],
                      fontsize=10)
    map.drawparallels(np.arange(int(lats.min()), int(lats.max()), 1),
                      labels=[1, 0, 0, 0],
                      fontsize=10)
    #map.bluemarble()

    #    CS1 = map.contourf(x,y,bathySmoothed,levels,
    #                       cmap=mpl_util.LevelColormap(levels,cmap=cm.Blues_r),
    #                       extend='upper',
    #                       alpha=1.0,
    #                       origin='lower')
    #    CS2 = map.contour(x,y,zi,levels1,linewidths=0.5,colors='k',animated=True)
    #    CS1 = map.contourf(x,y,zi,levels,cmap=mpl_util.LevelColormap(levels,cmap=cm.Blues_r),alpha=1.0)
    levels1 = [-100]
    CS2 = map.contour(x,
                      y,
                      bathySmoothed,
                      levels1,
                      linewidths=0.5,
                      colors='y',
                      linestyles='solid',
                      animated=True)
    plt.clabel(CS2, fontsize=4, inline=True)

    levels1 = [-200]
    CS2 = map.contour(x,
                      y,
                      bathySmoothed,
                      levels1,
                      linewidths=0.5,
                      colors='g',
                      linestyles='solid',
                      animated=True)
    plt.clabel(CS2, fontsize=4, inline=True)

    #    levels1=[-400]
    #    CS2 = map.contour(x,y,bathySmoothed,levels1,linewidths=0.5,colors='r',linestyles='solid',animated=True)
    #    plt.clabel(CS2,fontsize=4,inline=True)
    #
    #    levels1=[-350]
    #    CS2 = map.contour(x,y,bathySmoothed,levels1,linewidths=0.5,colors='k',linestyles='solid',animated=True)
    #    plt.clabel(CS2,fontsize=4,inline=True)

    levels1 = [-300]
    CS2 = map.contour(x,
                      y,
                      bathySmoothed,
                      levels1,
                      linewidths=0.5,
                      colors='c',
                      linestyles='solid',
                      animated=True)
    plt.clabel(CS2, fontsize=4, inline=True)

    CS1 = map.contourf(x,
                       y,
                       bathySmoothed,
                       levels,
                       cmap=mpl_util.LevelColormap(levels, cmap=cm.Blues_r),
                       alpha=1.0)
    #    CS1 = map.contourf(x,y,bathySmoothed,levels,cmap=mpl_util.LevelColormap(levels,cmap=cm.ocean),alpha=1.0)
    #    CS1 = map.contourf(x,y,bathySmoothed,levels,cmap=mpl_util.LevelColormap(levels,cmap=cm.jet),alpha=1.0)
    #

    #    CS1.axis='tight'
    """Plot the station as a position dot on the map"""
    #    cbar= fig.colorbar(CS1,orientation='horizontal')
    cb = map.colorbar(CS1, "right", size="2.5%", pad='2%')
    cb.set_label('Depth (m)', fontsize=10)

    #    map.plot(lon1,lat1,'r*', markersize=6,latlon='true')
    print type(lon1), type(lat1), np.shape(lon1)

    #    for lon2,lat2 in zip(lon1,lat1):
    #        print lon2,lat2
    #        print type(lon2)

    for lon2, lat2 in zip(lon1, lat1):

        map.plot(float(lon2), float(lat2), 'r.', markersize=2, latlon='true')


#    lat2 = Lat2[60]
#    lon2 = Lon2[60]
#    lat2 = Lat2[-1]
#    lon2 = Lon2[-1]

#    map.plot(lon2,lat2,'y*', markersize=1,latlon='true')

#    g = geodesic.Geodesic.WGS84.Inverse(lat1, lon1, lat2, lon2);
# Compute midpoint starting at 1
#    l=geodesic.Geodesic.WGS84.Line(g['lat1'],g['lon1'],g['azi1'])
#    num=50

#    print np.shape(lon)
#    print np.shape(lat)
#    print np.shape(bathySmoothed)
#
##    idx,idy = np.where(lon<-87 & lon<-95)  #  & lat>73 & lat<75  & bitwise operator
#    idx1,idy1 = np.where((lon<-55) & (lon>-60))
#    idx2,idy2 = np.where((lat > 55) & (lat < 58))  #  & lat>73 & lat<75
#
##    print np.shape(idx1)
##    print np.shape(idy1)
#
#    print min(idx2),max(idx2),min(idy1),max(idy1)
#    print min(idx1),max(idx1),min(idy2),max(idy2)
#
#    xn,yn = np.shape(lon)
#
#    idx1,idx2 = min(idx2),max(idx2)
#    idy1,idy2 = min(idy1),max(idy1)

#    idx1,idx2 = 251,551
##    idy1,idy2 = 1201,2201
#
#    bathySmoothedN = bathySmoothed[idx1:idx2,idy1:idy2]
#    lonN = lon[idx1:idx2,idy1:idy2]
#    latN = lat[idx1:idx2,idy1:idy2]
#
#    print np.shape(lonN)
#    print np.shape(latN)
#    print np.shape(bathySmoothedN)
#
#    if False:
#        interpFile = foutPath+'linearInterp.pik'
#        if os.path.isfile(interpFile):
#            print "interpolation file is ready, unpacking it...."
#            with open(interpFile,'rb') as fpik:
#                finterp=pickle.load(fpik)
#                f = finterp
#        else:
#    #    exit(1)
#    #    f = interpolate.interp2d(lonN, latN, bathySmoothedN, kind='cubic')
#            print "interpolation file is not ready, working on it...."
#            f = interpolate.interp2d(lonN, latN, bathySmoothedN, kind='linear')
#            with open(interpFile,'w') as fpik:
#                pickle.dump(f,fpik)

#    f = interpolate.griddata(lonN, latN, bathySmoothedN, method='linear')
#    print "interpolation function is done"

#    exit(1)

#    f = interpolate.RectBivariateSpline(lon, lat, bathySmoothed, kx=2, ky=2, s=0)
#    f = interpolate.Rbf(lonN, latN, bathySmoothedN)

#    for i in range(num+1):
#        b=l.Position(i*g['s12']/num)
##        print(b['lat2'],b['lon2'])
#
#        if i ==0:
#            pass
#        else:
#            map.plot(b['lon2'],b['lat2'],'ko', markersize=0.5,latlon='true')
#
#        lati = b['lat2']
#        loni = b['lon2']
#        zi  = f(loni, lati)
#        zi = interpolate.griddata((lonN, latN), bathySmoothedN, (loni, lati),method='linear')
#        print loni,lati,zi

#    map.plot(lon2,lat2,'r*', markersize=1,latlon='true')

#    h1 = geodesic.Geodesic.WGS84.Direct(lat1, lon1, g['azi1'], g['s12']/2);
#    print(h1['lat2'],h1['lon2']);

# Alternatively, compute midpoint starting at 2
#    h2 = geodesic.Geodesic.WGS84.Direct(lat2, lon2, g['azi2'], -g['s12']/2);
#    print(h2['lat2'],h2['lon2']);

#    p=Geodesic.WGS84.Inverse(40.6, -73.8, 1.4, 104);

#    for i in ma.arange(len(name)):
#
#        print i , name[i]
#        xpt,ypt = map(stLon[i*2],stLat[i*2])
#        xpt1,ypt1 = map(stLon[i*2+1],stLat[i*2+1])
#
#        map.plot([xpt],[ypt],'r.', markersize=5)
#        map.plot([xpt1],[ypt1],'r.', markersize=5)
#
#        plt.text(xpt+10000,ypt+10000,name[i], fontsize=7)

#        font = {'fontname':'Arial','weight':'bold','size':8}

#        matplotlib.rc('font', **font)
#    plt.title('Area %s'%(name))
#    plotfile='/home/xuj/work/project/noise/map_nls_north.jpg'
#    plotfile='/home/xuj/work/codes/barrowStraitSmall.jpg'

#    plt.show()
#    plt.close()
    return map
コード例 #11
0
ファイル: plotNewGrid.py プロジェクト: wangpengphd/romstools
def createNiceMap(grd, h, polygon_data_KINO, polygon_data_NS8KM,
                  plotSelectedStations):
    fig = plt.figure(figsize=(12, 12))
    ax = fig.add_subplot(111)
    levels = [10, 25, 50, 100, 250, 500, 1000, 2500, 5000]

    mymap = Basemap(llcrnrlon=-18.0,
                    llcrnrlat=46.0,
                    urcrnrlon=25.5,
                    urcrnrlat=67.5,
                    resolution='i',
                    projection='tmerc',
                    lon_0=0,
                    lat_0=50,
                    area_thresh=50.)

    mymap.drawcoastlines()
    mymap.drawcountries()
    mymap.fillcontinents(color='grey')
    mymap.drawmeridians(np.arange(grd.hgrid.lon_rho.min(),
                                  grd.hgrid.lon_rho.max(), 10),
                        labels=[0, 0, 0, 1])
    mymap.drawparallels(np.arange(grd.hgrid.lat_rho.min(),
                                  grd.hgrid.lat_rho.max(), 4),
                        labels=[1, 0, 0, 0])

    x, y = mymap(grd.hgrid.lon_rho, grd.hgrid.lat_rho)
    print np.min(grd.hgrid.lon_rho), np.max(grd.hgrid.lon_rho)
    print np.min(grd.hgrid.lat_rho), np.max(grd.hgrid.lat_rho)

    CS1 = mymap.contourf(x,
                         y,
                         h,
                         levels,
                         cmap=mpl_util.LevelColormap(levels, cmap=cm.Blues),
                         extend='upper',
                         alpha=1.0,
                         origin='lower',
                         rasterized=True)
    CS1.axis = 'tight'
    """Draw grid boundaries"""
    drawGridBoundaries(ax, mymap, polygon_data_NS8KM, mycolor="red")
    drawGridBoundaries(ax, mymap, polygon_data_KINO, mycolor="magenta")

    if (plotSelectedStations):

        xpos, ypos = getSelectedStations()
        xloc, yloc = mymap(grd.hgrid.lon_rho[ypos, xpos],
                           grd.hgrid.lat_rho[ypos, xpos])

        mymap.plot(xloc,
                   yloc,
                   marker="o",
                   color="red",
                   markersize=10,
                   linewidth=0)

    plotfile = 'figures/map_NS8KM_and_KINO1600M.pdf'
    plt.savefig(plotfile, dpi='200')

    plt.show()