コード例 #1
0
ファイル: anomaly.py プロジェクト: nickszap/mpas-tools
def plot_anomaly_ll(lat, lon, var):
  #Input lat and lon in degrees!!!
  plt.figure()
  
  #m = Basemap(projection='ortho',lon_0=100,lat_0=60, resolution='l')
  m = Basemap(projection='ortho',lon_0=0,lat_0=90, resolution='l')
  x,y = m(lon, lat)
  
  m.drawcoastlines()
  m.drawmapboundary()
  
  #'''
  #set bounds on var
  maxVal = 100.; minVal = -100.
  var[var>maxVal] = maxVal
  var[var<minVal] = minVal
  #'''
  
  m.pcolor(x,y,var,shading='flat',edgecolors='none',cmap=plt.cm.jet) #cmap=plt.cm.hot_r) #,vmin=100,vmax=1000)
  #m.contour(x,y,var,10,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet)
  #m.contourf(x,y,var,10,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet)
  #cbar = m.colorbar(plt1,location='bottom',pad="5%")
  #cbar.set_label('\Delta m')
  plt.colorbar()
  plt.show()
コード例 #2
0
ファイル: LIMTools.py プロジェクト: frodre/pyLIM
def plot_cedata(lats, lons, data, title):
    """
    Plot coefficient of efficiency data.  Lats, lons, and data should have the
    same temporal dimensions.  Lats and lons should denote gridbox edges.
    e.g. data has spatial dimensions of M (lats) x N (lons) then lats and lons
    should have dimensions of M+1 x N+1.

    Parameters
    ----------
    lats: ndarray
        Latitude array (gridbox edges)
    lons: ndarray
        Longitude array (gridbox edges)
    data: ndarray
        CE data
    title: str
        Plot title
    """
    plt.close('all')
    m = Basemap(projection='gall', llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=0, urcrnrlon=360, resolution='c')
    m.drawcoastlines()
    
    if data.min() < 0:
        color = cm.bwr
    else:
        color = cm.OrRd
        
    m.pcolor(lons, lats, data, latlon=True, cmap=color, vmin=-1, vmax=1)
    m.colorbar()
    plt.title(title)
    plt.show()
コード例 #3
0
def nsolLots():
	''' Compare nSol estimates to insolation. '''
	# Read the data first:
	nsolTable = readNsol()
	lons = [p['LonW'] for p in nsolTable]
	lats = [p['LatN'] for p in nsolTable]
	sizes = [p['ArrayOutput'] for p in nsolTable]
	insolSizes = [p['TotalAnnualInsolation'] for p in nsolTable]
	bmOptions = {'projection':'merc', 'lon_0':-95, 'lat_0':35, 'llcrnrlat':20, 'urcrnrlat':50,
		'llcrnrlon':-130, 'urcrnrlon':-60, 'rsphere':6371200., 'resolution':'l', 'area_thresh':10000}
	# First Plot
	plt.subplot(211)
	m1 = Basemap(**bmOptions)
	m1.drawcoastlines()
	m1.drawstates()
	m1.drawcountries()
	plt.title('Panel Output')
	mesh1 = m1.pcolor(lons, lats, sizes, latlon=True, tri=True)
	cbar1 = m1.colorbar(mesh1,location='right',pad='5%')
	cbar1.set_label('kWh')
	# Second Plot
	plt.subplot(212)
	m2 = Basemap(**bmOptions)
	m2.drawcoastlines()
	m2.drawstates()
	m2.drawcountries()
	plt.title('Annual Insolation')
	mesh2 = m2.pcolor(lons, lats, insolSizes, latlon=True, tri=True)
	cbar2 = m2.colorbar(mesh2,location='right',pad='5%')
	cbar2.set_label('kWh/m^2')
コード例 #4
0
ファイル: sm_eof.py プロジェクト: pfuhe1/cpdn_analysis
def plot_region_pnw(data,lat_coord,lon_coord,lat_nw,lat_se,lon_nw,lon_se,title,varfrac):
	plt.clf()
	circles=[30,40,50,60,70]
	meridians=[-130,-120,-110]
	ny,nx=lat_coord.shape
	m = Basemap(projection='stere',lon_0=lon_coord[ny/2,nx/2],lat_0=lat_coord[ny/2,nx/2],resolution='l',llcrnrlon=lon_coord[-1,0],llcrnrlat=lat_coord[-1,0],urcrnrlon=lon_coord[0,-1],urcrnrlat=lat_coord[0,-1])
	x,y=m(lon_coord[:],lat_coord[:])
	
	plt.title('Plotting data for: '+title+'\nvariance:'+str(varfrac))
	try:
		max=np.absolute(data[lat_nw:lat_se,lon_nw:lon_se]).max()
		m.pcolor(x[lat_nw:lat_se,lon_nw:lon_se],y[lat_nw:lat_se,lon_nw:lon_se],data[lat_nw:lat_se,lon_nw:lon_se],vmin=-max,vmax=max)
		plt.colorbar()
	except:
		raise
		m.plot(x[lat_nw:lat_se,lon_nw:lon_se],y[lat_nw:lat_se,lon_nw:lon_se],'r.') # Just put a dot at the x y point
	m.drawcoastlines()
	m.drawcountries()
	y=m.drawstates()
	m.drawparallels(circles)
	m.drawmeridians(meridians)
	try:
		os.remove(output_dir+'/._'+title+'.png')
	except:
		pass
	plt.savefig(output_dir+'/'+title+'.png')
コード例 #5
0
ファイル: pnw_region.py プロジェクト: pfuhe1/cpdn_analysis
def plot_region_pnw(data,lat_coord,lon_coord,lat_nw,lat_se,lon_nw,lon_se,region_name):
	plt.clf()
	circles=[30,40,50,60,70]
	meridians=[-130,-120,-110]
	ny,nx=lat_coord.shape
	m = Basemap(projection='stere',lon_0=lon_coord[ny/2,nx/2],lat_0=lat_coord[ny/2,nx/2],resolution='l',llcrnrlon=lon_coord[-1,0],llcrnrlat=lat_coord[-1,0],urcrnrlon=lon_coord[0,-1],urcrnrlat=lat_coord[0,-1])
	x,y=m(lon_coord[:],lat_coord[:])
	
#	shp_info = m.readshapefile('../st99_d00','states',drawbounds=False)
#	print shp_info
#	for i,shapedict in enumerate(m.states_info):
#		if shapedict['NAME']=='California': break
#	calif=np.array(m.states[i])
# TODO rasterise this to turn into a mask
	
	plt.title('Plotting data for region: '+region_name)
	try:
		m.pcolor(x[lat_nw:lat_se,lon_nw:lon_se],y[lat_nw:lat_se,lon_nw:lon_se],data[lat_nw:lat_se,lon_nw:lon_se])
		plt.colorbar()
	except:
		raise
		m.plot(x[lat_nw:lat_se,lon_nw:lon_se],y[lat_nw:lat_se,lon_nw:lon_se],'r.') # Just put a dot at the x y point
	m.drawcoastlines()
	m.drawcountries()
	y=m.drawstates()
	m.drawparallels(circles)
	m.drawmeridians(meridians)
	try:
		os.remove('check_regions/._'+region_name+'.png')
	except:
		pass
	plt.savefig('check_regions/'+region_name+'.png')
コード例 #6
0
ファイル: plot_mask.py プロジェクト: BobTorgerson/Pyroms
def plot_mask(gridid, Cpos='rho', proj=None, **kwargs):


    # get grid
    if type(gridid).__name__ == 'ROMS_Grid':
        grd = gridid
    else:
        grd = pyroms.grid.get_ROMS_grid(gridid)

    Cpos = str(Cpos)
    print Cpos

    # get grid information
    if Cpos == 'rho':
        lon = grd.hgrid.lon_vert
        lat = grd.hgrid.lat_vert
        mask = grd.hgrid.mask_rho

    elif Cpos == 'u':
        lon = 0.5 * (grd.hgrid.lon_vert[:,:-1] + grd.hgrid.lon_vert[:,1:])
        lat = 0.5 * (grd.hgrid.lat_vert[:,:-1] + grd.hgrid.lat_vert[:,1:])
        mask = grd.hgrid.mask_u

    elif Cpos == 'v':
        lon = 0.5 * (grd.hgrid.lon_vert[:-1,:] + grd.hgrid.lon_vert[1:,:])
        lat = 0.5 * (grd.hgrid.lat_vert[:-1,:] + grd.hgrid.lat_vert[1:,:])
        mask = grd.hgrid.mask_v

    else:
        raise Warning, 'Cpos must be rho, u or v'

    # defined color map
    land_color = kwargs.pop('land_color', (0.6, 1.0, 0.6))
    sea_color = kwargs.pop('sea_color', (0.6, 0.6, 1.0))

    cm = plt.matplotlib.colors.ListedColormap([land_color, sea_color],
                                             name='land/sea')



    if proj is None:
        plt.pcolor(lon, lat, mask, cmap=cm, vmin=0, vmax=1, \
                   edgecolor='k', **kwargs)
        pyroms_toolbox.plot_coast_line(grd)
    else:
        x, y = proj(lon, lat)
        Basemap.pcolor(proj, x, y, mask, cmap=cm, vmin=0, vmax=1, \
                       edgecolor='k', **kwargs)
        pyroms_toolbox.plot_coast_line(grd, proj=proj)

        lon_min = lon.min()
        lon_max = lon.max()
        lat_min = lat.min()
        lat_max = lat.max()

        proj.drawmeridians(np.arange(lon_min,lon_max,(lon_max-lon_min)/5.001), \
                          labels=[0,0,0,1], fmt='%.1f')
        proj.drawparallels(np.arange(lat_min,lat_max,(lat_max-lat_min)/5.001), \
                          labels=[1,0,0,0], fmt='%.1f')
コード例 #7
0
def generate_image(year, month, xs=500, ys=500, elev=60, azim=-90, colormap=cm.seismic):
    m = Basemap(width=12000000,height=12000000,
                rsphere=(6378137.00,6356752.3142),\
                resolution='l',area_thresh=1000.,projection='lcc',\
                lat_0=45,lon_0=170)

    ssl_loc = '/home/guy/Data/cci-ssl/ESACCI-SEALEVEL-L4-MSLA-MERGED-%04d%02d15000000-fv01.nc' % (year, month)
    lons_proj, lats_proj, XX, YY, sla = reproject_data(ssl_loc,'sla', m, xsize=xs, ysize=ys, filter=0)
    sst_loc = '/mnt/surft/data/SST_CCI_L4_monthly_mean_anomalies/%04d%02d--ESACCI-L4_GHRSST-SSTdepth-OSTIA-GLOB_LT-v02.0-fv01.0_anomalies.nc' %(year, month)
    lons_proj, lats_proj, XX, YY, sst = reproject_data(sst_loc,'sst_anomaly', m, xsize=xs, ysize=ys, filter=None)
    
    min_sst = -4
    max_sst = 4
    
    colors = np.empty(sst.shape, dtype=np.dtype((float, (4))))
    for y in range(sst.shape[1]):
        for x in range(sst.shape[0]):
            val = sst[x, y]
            if(np.ma.getmask(sst[x,y]) == True):
                colors[x,y] = (1,0,0,0)
            else:
                zero_to_one = (val - min_sst) / (max_sst - min_sst)
                colors[x, y] = colormap(zero_to_one)
    
    fig = plt.figure(figsize=(19.2,9.6))
    
    ax = plt.subplot(121, projection='3d')
       
    # ax = fig.gca(projection='3d')
    ax.view_init(elev=elev, azim=azim)
    ax.set_axis_off()
     
    surf = ax.plot_surface(XX, YY, sla, rstride=1, cstride=1, facecolors=colors,#cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)
    ax.set_zlim(-3, 3)
    ax.set_xlim((0.22 * xs, 0.78 * xs))
    ax.set_ylim((0.18 * ys, 0.82 * ys))
    
    ax2d = plt.subplot(122, aspect=1)
    m.bluemarble(ax=ax2d, scale=0.2)
    #m.imshow(sst, ax=ax, cmap=cm.coolwarm)
    x, y = m(lons_proj, lats_proj)
    m.pcolor(x,y, sst, ax=ax2d, cmap=colormap, vmin=min_sst, vmax=max_sst)
    
    #matplotlib.rcParams['contour.negative_linestyle'] = 'dashed'
    m.contour(x,y, sla, np.linspace(-1,1,11), colors='k', ax=ax2d)
    # m.pcolor(XX, YY, sla, ax=ax)
    #ax.pcolormesh(XX,YY,sst, vmin=min_sst, vmax=max_sst, cmap=cm.coolwarm)
    
    
    # ax = fig.gca()
    # surf = ax.pcolormesh(XX,YY,sla, vmin=-limit, vmax=limit)
    # fig.colorbar(surf, shrink=0.5, aspect=5)
    
    fig.tight_layout()
    return fig
コード例 #8
0
ファイル: plotPython.py プロジェクト: nickszap/mpas-tools
def plot_2dll(lat, lon, var):  
  #map = Basemap(projection='ortho',lon_0=100,lat_0=60, resolution='l')
  map = Basemap(projection='ortho',lon_0=0,lat_0=90, resolution='l')
  x,y = map(lon, lat)
  
  fig1 = plt.figure(1)
  map.drawcoastlines()
  map.drawmapboundary()
  map.pcolor(x,y,var,shading='flat',edgecolors='none',cmap=plt.cm.jet) #cmap=plt.cm.hot_r) #,vmin=100,vmax=1000)
  #map.contour(x,y,var,10,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet)
  #map.contourf(x,y,var,10,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet)
  plt.colorbar()
  plt.show()
コード例 #9
0
def plot_satellite_image(filename):
    """takes in a file and outputs a plot of satellite"""
    rootgrp = Dataset(filename, "a", format="NETCDF4")
    lons = rootgrp.variables["lon"][:]
    lats = rootgrp.variables["lat"][:]
    data = rootgrp.variables["data"][:]
    rootgrp.close()  # need to close before you can open again

    # Get some parameters for the Stereographic Projection
    m = Basemap(
        width=800000,
        height=800000,  # create a basemap object with these parameters
        resolution="l",
        projection="stere",
        lat_ts=40,
        lat_0=39.5,
        lon_0=-104.5,
    )

    xi, yi = m(lons, lats)  # map onton x and y for plotting
    plt.figure(figsize=(10, 10))  # Plot Data
    cs = m.pcolor(xi, yi, np.squeeze(data))  # data is 1 x 14 x 36, squeeze makes it 14 x 36

    m.drawparallels(np.arange(-80.0, 81.0, 1.0), labels=[1, 0, 0, 0], fontsize=10)  # Add Grid Lines
    m.drawmeridians(np.arange(-180.0, 181.0, 1.0), labels=[0, 0, 0, 1], fontsize=10)  # Add Grid Lines
    m.drawstates(linewidth=3)  # Add state boundaries

    cbar = m.colorbar(cs, location="bottom", pad="10%")  # Add Colorbar
    plt.title("GOES 15 - Sensor 1")  # Add Title
    plt.show()
コード例 #10
0
def hammer_plot_density(density, xmax, xmin, ymax, ymin, no_ra, no_dec, targ_flag, obs_flag, pass_flag):
    if targ_flag ==1:
        targ_type = 'LRG'
    if targ_flag==2:
        targ_type = 'ELG'
    if targ_flag==4:
        targ_type = 'QSO'
    if obs_flag==1:
        name_obs = 'source'
    if obs_flag==2:
        name_obs = 'true'
    
    outfile = "~/DESIhub/target_density_%s_%s_pass%d.pdf" %(targ_type, name_obs, pass_flag)
    bin_size_x = (xmax-xmin)/no_ra
    bin_size_y = (ymax-ymin)/no_dec
    y = np.linspace(ymin, ymax, no_dec)
    x = np.linspace(xmin, xmax, no_ra)
    [X,Y] = np.meshgrid(x,y);
    X=np.transpose(X)
    Y=np.transpose(Y)
    f = plt.figure()
    m = Basemap(projection='moll',lon_0=180,resolution='c')
    cs = m.pcolor(X, Y, density,  cmap=plt.cm.jet,latlon=True)
    cbar = m.colorbar(cs,location='bottom',pad="5%")
    f.savefig(outfile, bbox_inches='tight')
コード例 #11
0
def bp(lon, lat, data, yescbar, region = 'Arctic', ptype = 'contourf', **kwargs):
    
    '''Basic Basemap plot function. Use coordinates (1d or 2d), data and name of the region
     as an input and plot data. Region defines in the "regbase" function.

     You can also provide any argument for matplotlib plotting functions.

     Usage:
         bp(lon, lat, data, region = 'Arctic', ptype = 'contourf', **kwargs)
     
     Input:
        lon         - 2D or 1D array of longitudes
        lat         - 2D or 1D array of latitudes
        data        - 2D array of scalar data.
        region      - one of the predefined regions (for list of regions see the "regbase" function)
        ptype       - plot type (contour, contourf, pcolor, pcolormesh)
        **kwargs    - arguments for plotting functions

     Output:
        Basemap instance.
    '''
    
    mapDict = regbase(region)

    # Create Basemap instance
    if mapDict['projection'] == 'npstere':
        m = Basemap(projection=mapDict['projection'],boundinglat=mapDict['boundinglat'],\
                    lon_0=mapDict['lon_0'],resolution=mapDict['resolution'])
    
    # Check if we have proper number of dimensions for lon (and hopefully lat as well)
    if lon.shape.__len__() == 1:
        lon, lat = np.meshgrid(lon, lat)
    elif lon.shape.__len__() > 2:
        raise Exception("Coordinate variables (lon) has too many dimensions")
    
    # Convert lat/lon to map coordinates
    x, y = m(lon, lat)

    # Make the map look better
    m.fillcontinents(color='gray',lake_color='gray')
    m.drawparallels(np.arange(-80.,81.,20.))
    m.drawmeridians(np.arange(-180.,181.,20.))
    m.drawmapboundary(fill_color='white')
    
    # Draw values on the map
    if ptype == 'contourf':
        cs = m.contourf(x,y,data,**kwargs)
        if yescbar == True:
            cbar3 = plt.colorbar(cs)
        return m
    elif ptype == 'pcolormesh':
        cs = m.pcolormesh(x,y,data,**kwargs)
    elif ptype == 'contour':
        cs = m.contour(x,y,data,**kwargs)
    elif ptype == 'pcolor':
        cs = m.pcolor(x,y,data,**kwargs)
    else:
        raise Exception("Plot type not supported. Valid plot types are: contour, contourf, pcolor, pcolormesh ")
    
    return m
コード例 #12
0
ファイル: seismon_eqmon_plot.py プロジェクト: mcoughlin/gwpy
def worldmap_velocitymap(params,plotName):
    """@worldmap plot

    @param params
        seismon params dictionary
    @param plotName
        name of plot
    """

    plt.figure(figsize=(15,10))
    plt.axes([0,0,1,1])

    # lon_0 is central longitude of robinson projection.
    # resolution = 'c' means use crude resolution coastlines.
    m = Basemap(projection='robin',lon_0=0,resolution='c')
    #set a background colour
    m.drawmapboundary(fill_color='#85A6D9')

    # draw coastlines, country boundaries, fill continents.
    m.fillcontinents(color='white',lake_color='#85A6D9')
    m.drawcoastlines(color='#6D5F47', linewidth=.4)
    m.drawcountries(color='#6D5F47', linewidth=.4)

    # draw lat/lon grid lines every 30 degrees.
    m.drawmeridians(np.arange(-180, 180, 30), color='#bbbbbb',zorder=3)
    m.drawparallels(np.arange(-90, 90, 30), color='#bbbbbb',zorder=3)

    velocityFile = '/home/mcoughlin/Seismon/velocity_maps/GR025_1_GDM52.pix'
    velocity_map = np.loadtxt(velocityFile)
    base_velocity = 3.59738

    lats = velocity_map[:,0]
    lons = velocity_map[:,1]
    velocity = 1000 * (1 + 0.01*velocity_map[:,3])*base_velocity

    lats_unique = np.unique(lats)
    lons_unique = np.unique(lons)
    velocity_matrix = np.zeros((len(lats_unique),len(lons_unique)))

    for k in xrange(len(lats)):
        index1 = np.where(lats[k] == lats_unique)
        index2 = np.where(lons[k] == lons_unique)
        velocity_matrix[index1[0],index2[0]] = velocity[k]

    lons_grid,lats_grid = np.meshgrid(lons_unique,lats_unique)
    x, y = m(lons_grid, lats_grid) # compute map proj coordinates.
    # draw filled contours.

    cs = m.pcolor(x,y,velocity_matrix,alpha=0.5,zorder=2)
    colorbar_label = "Velocity [m/s]"

    try:
       cbar=plt.colorbar()
       cbar.set_label(colorbar_label)
    except:
       pass
    plt.show()
    plt.savefig(plotName,dpi=200)
    plt.close('all')
コード例 #13
0
ファイル: plotPython.py プロジェクト: nickszap/mpas-tools
def example_sfcUpdate_horiz(time,var):
  #The surfaceUpdate.nc files don't have all of the same fields/dimensions,...
  #so we get errors when attempting to access them
  
  import netCDF4
  
  ncfname = '/arctic1/nick/cases/163842/r2614/sfc_update.nc'
  ncfnameG = '/arctic1/nick/cases/163842/r2614/output.163842.2006-07-08_00.00.00.nc' #used for grid since, say, sfc_update.nc doesn't have this info
  dataG = netCDF4.Dataset(ncfnameG,'r')
  data = netCDF4.Dataset(ncfname,'r')
  nCells = len(data.dimensions['nCells'])
  
  lat = dataG.variables['latCell'][:]*180./np.pi; #in degrees
  lon = dataG.variables['lonCell'][:]*180./np.pi;
  
  level = 0; #time=20; var='sst';
  var = data.variables[var][time,:];# minVar = np.amin(var); maxVar = np.amax(var);
  
  #map = Basemap(projection='ortho',lon_0=-105,lat_0=40, resolution='l')
  map = Basemap(projection='ortho',lon_0=-100,lat_0=60, resolution='l')
  x,y = map(lon, lat)
  
  fig1 = plt.figure(1)
  map.drawcoastlines()
  map.drawmapboundary()
  map.pcolor(x,y,var,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet) #cmap=plt.cm.hot_r) #,vmin=100,vmax=1000)
  #map.contour(x,y,var,10,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet)
  #map.contourf(x,y,var,10,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet)
  plt.colorbar()
  
  if(1):
    map = Basemap(projection='ortho',lon_0=100,lat_0=-60, resolution='l')
    x,y = map(lon, lat)

    fig2 = plt.figure(2)
    map.drawcoastlines()
    map.drawmapboundary()
    map.pcolor(x,y,var,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet) #cmap=plt.cm.hot_r) #,vmin=100,vmax=1000)
    #map.contour(x,y,var,10,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet)
    #map.contourf(x,y,var,10,tri=True,shading='flat',edgecolors='none',cmap=plt.cm.jet)
    plt.colorbar()
  
  #plotName = '/home/nickszap/Desktop/sst'+str(time)+'.png'
  #fig1.savefig(plotName)
  
  plt.show()
コード例 #14
0
ファイル: plot_hrrr_sgp.py プロジェクト: EVS-ATMOS/HRRR
def plot_hrrr_sgp(filename,parameter,directory = os.getcwd(),hinp = '', scaling = 1, final_unit = '', margin = 10, vmax = None, vmin = None):

    """
    Plots an hrrr file focused on the SGP site for a given hrrr filename, parameter and height in hPa. 
    Labels the SGP site.  
     
    Leaving the height blank will cause it to plot the maximum values of the file.  The margin defines half the length of 
    the plot area in degrees latitude and longitude.  Scaling and final_unit can be used to tweak the data in order to 
    make it more visible on the graph.  vmax and vmin function the same as in pcolormesh from Basemap.  
    """
    wkdir = os.getcwd()
    os.chdir(directory)
    
    if hinp != '':
        [data,parameterlist,units] = read_hrrr(filename,[parameter])
    else:
        [data,parameterlist,units] = read_hrrr(filename,[parameter],directory = directory,max=True)
        
    if hinp !='':
        datah = HRRR_PS.tolist()
        hindex = datah.index(hinp)
        
    if final_unit == '':
        final_unit = units[0]
        

    f = plt.figure(figsize=[12,10])
    m = Basemap(llcrnrlon = -97.485-margin,llcrnrlat = 36.605-margin, urcrnrlon = -97.485+margin,
                   urcrnrlat = 36.605+margin, projection = 'mill', area_thresh =10000 ,
                   resolution='l')
        
    latlonsgp = [-97.485,36.605]
    cities = ['Lamont,OK']
    sgpx,sgpy = m(latlonsgp[0],latlonsgp[1])
    m.plot(sgpx,sgpy,'bo')
    #plt.text(sgpx+50000,sgpy+50000,'SGP site')
        
    x, y = m(HRRR_DATALOC[1],HRRR_DATALOC[0])
    data = np.array(data)
    
    
    if hinp != '':
        newdata = data[0][hindex][:][:]
    else:
        newdata = data[0]
        
    my_mesh = m.pcolor(x, y, newdata, vmax = .05, norm = colors.LogNorm())
#    my_coast = m.drawcoastlines(linewidth=1.25)
#    my_states = m.drawstates()
#    my_p = m.drawparallels(np.arange(20,80,4),labels=[1,1,0,0])
#    my_m = m.drawmeridians(np.arange(-140,-60,4),labels=[0,0,0,1])
        
    plt.colorbar(label=parameter+' '+final_unit)
    plt.show()
    
    os.chdir(wkdir)
    return
コード例 #15
0
def plot_nc(lons, lats, precips):
    m = Basemap(width=200000, height=200000, projection='stere',
                lat_0=lat_0, lon_0=lon_0)
    lon, lat = np.meshgrid(lons, lats)
    xi, yi = m(lon, lat)
    cs = m.pcolor(xi, yi, precips[0])
    m.drawstates()
    m.drawcounties()
    cbar = m.colorbar(cs, location='bottom', pad='10%')
    plt.show()
コード例 #16
0
ファイル: pres.py プロジェクト: scollis/bom_mds
def reconstruction_plot_pcolor(lats, lons, data_cube, lvl_num, parm, u, v,w, angs, mask, **kwargs):
	ber_loc=[-12.4, 130.85] #location of Berrimah radar
	gp_loc=[-12.2492,  131.0444]#location of CPOL at Gunn Point
	box=kwargs.get('box',[130.0, 132.0, -13.0, -11.5])#box for the plot
	bquiver=kwargs.get('bquiver', [0.1, 0.75])
	ksp=kwargs.get('ksp', 0.05)
	#Set up the map and projection
	mapobj= Basemap(projection='merc',lat_0=(box[2]+box[3])/2.0, lon_0=(box[0]+box[1])/2.0,llcrnrlat=box[2], llcrnrlon=box[0], urcrnrlat=box[3] , urcrnrlon=box[1], resolution='l',area_thresh=1., lat_ts=(box[2]+box[3])/2.0)
	#map.drawmapboundary()
	um=M.masked_where(M.array(mask) < 0.5, M.array(u))
	vm=M.masked_where(M.array(mask) < 0.5, M.array(v))
	mag=M.array(sqrt(u**2+v**2))
	magm=M.masked_where(M.array(mask)<0.5, mag)
	fig_name=kwargs.get('fig_name', 'recon_'+parm+'_.png')
	longr, latgr=meshgrid(lons,lats)
	xx, yy = mapobj(longr, latgr)
	mapobj.drawmapboundary()
	mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None)
	mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstqldmd_r', 'qcoast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None)
	#mapobj.drawmeridians(array([130,130.5, 131, 131.5, 132]), labels=[1,0,0,1])
	#mapobj.drawparallels(array([-13,-12.5,-12,-11.5,-11]), labels=[1,0,0,1])
	data=M.masked_where(M.array(mask) < 0.5, M.array(data_cube[parm][:,:,lvl_num]))
	if parm in ['diff']:
		data=M.masked_where(M.array(mask) < 0.5, M.array(data))
	comp_levs=linspace(-1.,1., 30)
	levs_dict={'VR':linspace(-25,25,51), 'CZ': linspace(-8,64,10), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31), 'VE':linspace(-25,25,51)}
	titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff', 'VE':'Edited velocity'}
	mapobj.pcolor(xx,yy,data, vmin=levs_dict[parm].min(), vmax=levs_dict[parm].max())
	colorbar()
	#mapobj.quiver(xx,yy,u/sqrt(u**2+v**2),v/sqrt(u**2+v**2), scale=50)
	qq=mapobj.quiver(xx,yy,um,vm, scale=kwargs.get('qscale', 200))
	quiverkey(qq, bquiver[0], bquiver[1]+2.*ksp, 10, '10 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']})
	print bquiver[0], bquiver[1]+2.*ksp
	quiverkey(qq, bquiver[0], bquiver[1]+ksp, 5, '5 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']})
	quiverkey(qq, bquiver[0], bquiver[1], 2, '2 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']})
	cobject=mapobj.contour(xx,yy,w, colors=['k'], levels=linspace(-10,10,6))
	fon = { 'fontname':'Tahoma', 'fontsize':5 }
	clabel(cobject, fmt="%1.1f", **fon)
	mapobj.contour(xx,yy,angs, levels=[30.0, 150.0],colors=['r']) 
	mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/nt_coast','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None)
	mapobj.drawmeridians(linspace(0,4,41)+130., labels=[1,0,0,1], fontsize=rcParams['xtick.labelsize'])
	mapobj.drawparallels(linspace(0,4,41)-15.0, labels=[1,0,0,1], fontsize=rcParams['ytick.labelsize'])
	return mapobj
コード例 #17
0
def eof_standard_plot(object, value, var, titleText, filename):
  """ Produces some standard plot output and therefore easier to change 
      these settings than manual work. 
      Figure out some way to default to total range for index (i.e., not just 1)
      obj : post-processed netCDF4 object (i.e., not raw original object)
      var : prescribed abbreviation of climate variable of interest 
      value : when working with array, take a single value (i.e., 1st EOF)
  """
  obj = Dataset(object, mode = 'r')
  lons = obj.variables['lon'][:]
  lats = obj.variables['lat'][:]
  cliva = obj.variables[var][value,:,:]   # climate variable
  cliva_units = obj.variables[var].units

  

  lon_0 = lons.mean()
  lat_0 = lats.mean()

  m = Basemap(width=5000000,height=3500000,
            resolution='l',projection='stere',\
            lat_ts=40,lat_0=lat_0,lon_0=lon_0)

  # Because our lon and lat variables are 1D, 
  # use meshgrid to create 2D arrays 
  # Not necessary if coordinates are already in 2D arrays.
  lon, lat = np.meshgrid(lons, lats)
  xi, yi = m(lon, lat)

  # Plot Data
  cs = m.pcolor(xi,yi,np.squeeze(cliva))

  # Add Grid Lines
  m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10)
  m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10)

  # Add Coastlines, States, and Country Boundaries
  m.drawcoastlines()
  m.drawstates()
  m.drawcountries()

  # Add Colorbar
  cbar = m.colorbar(cs, location='bottom', pad="10%")
  cbar.set_label(cliva_units)

  # Add Title
  plt.title(titleText)
  #plt.show()
  #plt.draw()   
  fn = str(filename) + ".eps"     # hard-coding here can be improved
  plt.savefig(fn)
  #plt.show()
  #fig.show() 
  #def ensemble_avg(modphys)
  obj.close()  # closes the file
コード例 #18
0
ファイル: sc5.py プロジェクト: iaklampanos/bde-climate-1
def plot_clicked(b):
    global tx_plot
    global dd_plot
    IPython.display.clear_output()
    #clear_output(wait=True)
    # tx_plot.value += 'Plot clicked<br/>'
    # tx_plot.value = '<script>$(".output").remove()</script>'
    my_example_nc_file = dd_plot.value

    fh = Dataset(my_example_nc_file, mode='r')

    var = extract_var(my_example_nc_file)
    if var == None:
        tx_plot.value += 'Unknown error <br/>'
        return
    
    # tx_plot.value += var + '<br/>'
    
    lons = fh.variables['lon'][:]
    lats = fh.variables['lat'][:]
    time = fh.variables['time'][:]
    rsdscs = fh.variables[var][:]

    #print(rsdscs.shape)
    #print(rsdscs[0].shape)
    rsdscs_units = fh.variables[var].units
    fh.close()

    lon_0 = lons.mean()
    lat_0 = lats.mean()

    m = Basemap(width=50000000,height=35000000,
                resolution='l',projection='cyl',\
                lat_ts=40,lat_0=lat_0,lon_0=lon_0)
    lon, lat = np.meshgrid(lons, lats)
    xi, yi = m(lon, lat)

    #Add Size
    fig = plt.figure(figsize=(16,16))

    # Plot Data
    cs = m.pcolor(xi,yi,np.squeeze(rsdscs[0]))

    # Add Grid Lines
    m.drawparallels(np.arange(-80., 81., 20.), labels=[1,0,0,0], fontsize=10)
    m.drawmeridians(np.arange(-180., 181., 20.), labels=[0,0,0,1], fontsize=10)

    # Add Coastlines, States, and Country Boundaries
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()

    # Add Colorbar
    cbar = m.colorbar(cs, location='bottom', pad="10%")
    cbar.set_label(rsdscs_units)
コード例 #19
0
ファイル: LIMTools.py プロジェクト: frodre/pyLIM
def plot_spatial(lats, lons, data, title, outfile=None):
    """
    Method for basic spatial data plots.  Uses diverging color scheme, so 
    current implementation is best for anomaly data.  Created initially just
    to plot spatial EOFs
    
    Parameters
    ----------
    lats: ndarray
        MxN matrix of latitude values
    lons: ndarray
        MxN matrix of longitude values
    data: ndarray
        MxN matrix of spatial data to plot
    title: str
        Title string for the plot
    outfile: str
        Filename to save the png image as
    """
    plt.clf()
    plt_range = np.max(np.abs(data))
    m = Basemap(projection='gall', llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=0, urcrnrlon=360, resolution='c')
    m.drawcoastlines()

    if data.min() >= 0:
        color = cm.OrRd
        plt_max = plt_range
        plt_min = 0
    else:
        color = cm.bwr
        plt_max = plt_range
        plt_min = -plt_range

    m.pcolor(lons, lats, data, latlon=True, cmap=color, vmin=plt_min,
             vmax=plt_max)
    m.colorbar()
    
    plt.title(title)
    if outfile is not None:
        plt.savefig(outfile)
    plt.show()
コード例 #20
0
def plot_xyz_image(xyz, fignum=0, logz=True, needTranspose=False, interp_type='nearest', cmap='jet', do_map=True, colorbounds=None):
    #
    if not hasattr(xyz, 'dtype'):
        xyz = numpy.core.records.fromarrays(zip(*xyz), dtype=[('x','>f8'), ('y','>f8'), ('z','>f8')])
    #
    xyz.sort(order='x')
    xyz.sort(order='y')
    X = sorted(list(set(xyz['x'])))
    Y = sorted(list(set(xyz['y'])))
    mgx, mgy = np.meshgrid(X, Y)
    print("len(X) = "+str(len(X)))
    print("len(Y) = "+str(len(Y)))
    print("Total size = "+str(len(xyz)))
    #

    if logz: zz=numpy.log(xyz['z'].copy())
    else: zz=xyz['z'].copy()
    #zz.shape=(len(Y), len(X))
    if needTranspose==True:
        zz.shape=(len(X), len(Y))
        zz = zz.T
    else:
        zz.shape=(len(Y), len(X))
    #
    if colorbounds==None:
        colorbounds = [zz.min(), zz.max()]
    plt.figure(fignum)
    plt.clf()
    #plt.imshow(numpy.flipud(zz.transpose()), interpolation=interp_type, cmap=cmap)
    #plt.colorbar()
    #
    if do_map:
        m = Basemap(projection='cyl', llcrnrlat=min(Y), urcrnrlat=max(Y), llcrnrlon=min(X), urcrnrlon=max(X), resolution='i')
        m.drawcoastlines()
        m.drawmapboundary()#fill_color='PaleTurquoise')
        #m.fillcontinents(color='lemonchiffon',lake_color='PaleTurquoise', zorder=0)
        m.drawstates()
        m.drawcountries()
        m.drawmeridians(np.arange(np.ceil(np.min(mgx)),np.floor(np.max(mgx)),2), labels=[0,0,0,1])
        m.drawparallels(np.arange(np.ceil(np.min(mgy)),np.floor(np.max(mgy)),2), labels=[1,0,0,0])
        m.pcolor(mgx, mgy, zz, cmap=cmap, vmin=colorbounds[0], vmax=colorbounds[1])
コード例 #21
0
ファイル: pytools.py プロジェクト: thackray/pytools
    def plot_map(lat, lon, data, normalized=False):
        """Plots data on a Basemap.
        
        Arguments:
        lat: array of lat locations of data
        lon: array of lon locations of other axis of data
        data: 2D lat-lon grid of data to put on map
        
        Keyword Arguments:
        normalized: if True, show a 0:1 map of ratios of max value
        
        Returns:
        Nothing
        """

        bm = Basemap(projection = 'mill', llcrnrlon=min(lon),
                     llcrnrlat=min(lat), urcrnrlon=max(lon),
                     urcrnrlat=max(lat))
        lons, lats = np.meshgrid(lon, lat)
        x, y = bm(lons, lats)

        pl.figure(figsize=(18,14))
        ax = pl.gca()
        bm.drawcoastlines(linewidth=1.25, color='white')
        bm.drawparallels(np.array([-70,-50,-30,-10,10,30,50,70]),
                         labels=[1,0,0,0])
        bm.drawmeridians(np.arange(min(lon),max(lon),60),labels=[0,0,0,1])
        
        if normalized:
            bm.pcolor(x,y,data.T/np.abs(np.max(data)))
        else:
            bm.pcolor(x,y,data.T)

        if MAL:
            divider = mal(ax)
            cax = divider.append_axes("right", size='5%', pad=0.05)
            pl.colorbar(cax=cax)
        else:
            pl.colorbar()

        return
コード例 #22
0
def Plot(array, correct_Bool):
    path_wbgt = '/Users/DavidKMYang/ClimateResearch/WBGT/gfdl_tasmax_nh/'
    path_wbgt_corrected = '/Users/DavidKMYang/ClimateResearch/WBGT/BiasCorrected_v2/BiasCorrectedVals/'

    tempData_wbgt = scipy.io.loadmat(path_wbgt + 'tasmax_2005_07_01.mat')
    tempData_wbgt = tempData_wbgt['tasmax_2005_07_01'][0]

    tempData_wbgt_corrected = scipy.io.loadmat(path_wbgt_corrected + 'tasmax_2005_07_01.mat_corrected.mat')

    flatTLat = np.array(tempData_wbgt[0])
    flatTLon = np.array(tempData_wbgt[1])
    flatTData = np.array(array)

    if correct_Bool:
        flatTLat = np.array(tempData_wbgt_corrected['tasmax_2005_07_01.mat_corrected_Lat'])
        flatTLon = np.array(tempData_wbgt_corrected['tasmax_2005_07_01.mat_corrected_Long'])
        # flatTData = np.array(tempData_wbgt_corrected['tasmax_2005_07_01.mat_corrected_Val'])


    for i in range(len(flatTLon)):
        for j in range(len(flatTLon[0])):
            flatTLon[i][j] -= 180



    # m = Basemap(width=10000000,height=10000000,
    #             resolution='l',projection='kav7',
    #             lat_ts = 10, lat_0=30, lon_0 = 30)
    m = Basemap(projection = 'kav7', lon_0 = 0, resolution = 'l')


    lon, lat = np.meshgrid(flatTLon[0,:], flatTLat[:,0])
    x, y = m(lon,lat)
    cs = m.pcolor(x,y,np.squeeze(flatTData), vmin=-15, vmax=15)
    m.drawmapboundary(fill_color='0.3')
    # Add Grid Lines
    m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10)
    m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10)

    # Add Coastlines, States, and Country Boundaries
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()

    # Add Colorbar
    cbar = m.colorbar(cs, location='bottom', pad="10%")

    # Add Title
    plt.title('n')

    plt.show()
コード例 #23
0
def spacePlot(obj, slice, var):
  """
  Will assume post-Dataset for now, until can get working 
  """
  lons = obj.variables['lon'][:]
  lats = obj.variables['lat'][:]
  cliva = obj.variables[var][value,:,:]   # climate variable
  cliva_units = obj.variables[var].units

  

  lon_0 = lons.mean()
  lat_0 = lats.mean()

  m = Basemap(width=5000000,height=3500000,
            resolution='l',projection='stere',\
            lat_ts=40,lat_0=lat_0,lon_0=lon_0)

  # Because our lon and lat variables are 1D, 
  # use meshgrid to create 2D arrays 
  # Not necessary if coordinates are already in 2D arrays.
  lon, lat = np.meshgrid(lons, lats)
  xi, yi = m(lon, lat)

  # Plot Data
  cs = m.pcolor(xi,yi,np.squeeze(cliva))

  # Add Grid Lines
  m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10)
  m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10)

  # Add Coastlines, States, and Country Boundaries
  m.drawcoastlines()
  m.drawstates()
  m.drawcountries()

  # Add Colorbar
  cbar = m.colorbar(cs, location='bottom', pad="10%")
  cbar.set_label(cliva_units)

  # Add Title
  plt.title(titleText)
  #plt.show()
  #plt.draw()   
  fn = "EOF1" + str(goodFiles[0][0:-3]) + ".eps"     # hard-coding here can be improved
  plt.savefig(fn)
  #plt.show()
  #fig.show() 
  #def ensemble_avg(modphys)
  obj.close()  # closes the file  
コード例 #24
0
ファイル: plot.py プロジェクト: arokem/spheredwi
def surf_grid(r, theta, phi, ax=None, vmin=None, vmax=None, **basemap_args):
    """Draw a function r = f(theta, phi), evaluated on a grid, on the sphere.

    Parameters
    ----------
    r : (M, N) ndarray
        Function values.
    theta : (M,) ndarray
        Inclination / polar angles of function values.
    phi : (N,) ndarray
        Azimuth angles of function values.
    ax : mpl axis, optional
        If specified, draw onto this existing axis instead.
    basemap_args : dict
        Parameters used to initialise the basemap, e.g. ``projection='ortho'``.

    Returns
    -------
    m : basemap
        The newly created matplotlib basemap.

    """
    basemap_args.setdefault('projection', 'ortho')
    basemap_args.setdefault('lat_0', 0)
    basemap_args.setdefault('lon_0', 0)
    basemap_args.setdefault('resolution', 'c')

    from mpl_toolkits.basemap import Basemap

    m = Basemap(**basemap_args)
    m.drawmapboundary()
    lat, lon = coord.sph2latlon(theta, phi)
    x, y = m(*np.meshgrid(lon, lat))
    m.pcolor(x, y, r, vmin=vmin, vmax=vmax)

    return m
コード例 #25
0
def animator(i):
    print i
    ax.cla()
    
    data = var[i,:,:]
    
    # create basemap
    map = Basemap(projection='cyl',llcrnrlat=lat_e[0],urcrnrlat=lat_e[-1],llcrnrlon=lon_e[0],urcrnrlon=lon_e[-1],resolution='c')
    # make sure map is associated with ax, not axlogo2
    map.ax = ax
    mcoa = map.drawcoastlines(linewidth=0.25)
    mcou = map.drawcountries(linewidth=0.25)
    #add extra stripe of data to complete sphere
    #contour plot data
    pl = map.pcolor(LON,LAT,data, cmap=cmap, norm=cnorm)
    #pl = map.contourf(LON,LAT,data, cmap=cmap, norm=cnorm,antialiased=True)
    ax.set_title('%s %s %s'%(model+add,date[i],time[i]),fontsize=26)
コード例 #26
0
ファイル: plot_params.py プロジェクト: orianac/tonic
def plot_map(ax, yc, xc, data, Projection_Parameters, cbar_loc=False, vmin=-1,
             vmax=1, cmap='GrBG'):

    m = Basemap(**Projection_Parameters)
    m.drawlsmask(land_color='white', ocean_color='0.8')
    m.drawcoastlines()
    m.drawparallels(np.arange(-80, 81, 20))
    m.drawmeridians(np.arange(-180, 181, 20))
    xi, yi = m(xc, yc)
    cm = matplotlib.cm.get_cmap(cmap)
    m.drawlsmask(land_color='white', ocean_color='0.8')
    ax = m.pcolor(xi, yi, data, cmap=cm, vmin=vmin, vmax=vmax)
    if cbar_loc:
        cbar = m.colorbar(ax, location=cbar_loc)
    else:
        cbar = None

    return cbar
コード例 #27
0
ファイル: MChem_tools.py プロジェクト: tsherwen/MChem_tools
def basic_map_plot(scalar, species=None, unit=None, res='4x5', **Kwargs):

    # Setup slices
    # Grid/Mesh values for Lat, lon, & alt
    lon, lat, alt = get_latlonalt4res(res=res)

    # Setup mesh grids
    x, y = np.meshgrid(lon, lat)
    print len(x), len(y)

    # Add Labels for axis + title  if species provided
    plt.ylabel('Latitude', fontsize=20)
    plt.xlabel('Longitude', fontsize=20)
    if not isinstance(species, type(None)):
        plt.title('{} / {} '.format(latex_spec_name(species), unit))

    # Setup map ("m") using Basemap
    m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=-182.5,
                urcrnrlon=177.5,
                resolution='c')
    m.drawcoastlines()

    parallels = np.arange(-90, 91, 15)
    meridians = np.arange(-180, 151, 30)

    plt.xticks(meridians)  # draw meridian lines
    plt.yticks(parallels)  # draw parrelel lines
#    m.drawparallels(parallels) # add to map

    # Create meshgrid to plot onto
    x, y = np.meshgrid(*m(lon, lat))
    print len(x), len(y)

    plt.xlim(-180, 175)
    plt.ylim(-89, 89)

    poly = m.pcolor(lon, lat, scalar, cmap=plt.cm.Blues)

    # Add labels/annotations
    cb = plt.colorbar(poly, ax=m.ax, shrink=0.4)

    return plt, cb
コード例 #28
0
ファイル: AIRS_stuff.py プロジェクト: jibbals/stations
def plot_AIRS_day(date):
    '''
    Create a plot from the AIRS dataset for one day
    '''
    lats,lons,totco = read_AIRS_day(date)
    if lats[0]==-1: return (-1)
    # plot stuff
    lon0=lons.mean()
    lat0=lats.mean()
    
    # width, height in meters, 
    #lon = -137.5, 172.5
    #lat = 15.5, -75.5
    m=Basemap(llcrnrlat=-80,  urcrnrlat=20,
              llcrnrlon=-140, urcrnrlon=175,
              resolution='l',projection='merc',
              lat_0=lat0, lon_0=lon0)
    
    # lat lon are 1D, basemap uses 2D mesh
    lon,lat = np.meshgrid(lons,lats)
    xi, yi = m(lon,lat)
    
    # draw the CO total column onto the map
    cs = m.pcolor(xi,yi,np.squeeze(totco)) # squeeze removes any 1 length dimensions
    
    # set up consistent colour map (the colour bar)
    cmap = plt.cm.jet # blue to red
    plt.set_cmap(cmap)
    plt.clim(1e18, 3.5e18) # bounds for cmap    
    
    #add coastlines and equator
    m.drawcoastlines()
    m.drawparallels([0], labels=[0,0,0,0])
    
    #add title, colorbar
    cb=m.colorbar(cs,"right",size="5%", pad="2%")
    cb.set_label('CO')
    
    #ax.set_title('Total Column Ascending '+str(date))
    plt.title('Total Column CO'+date.strftime("%Y%m%d"))
    return(m)
コード例 #29
0
ファイル: global_map_plot.py プロジェクト: bn506/GCPlot
def plot_the_data(data, wd, Output_Name, debug):
   print 'Plotting the data.'
   #set up plot
#   print data
#   print data.dimensions
   
   fig=plt.figure(figsize=(20,12))
   ax = fig.add_axes([.05, .1, .9, .8])
   fig.patch.set_facecolor('white')
   lat = np.arange(-88,90,4)
   lat = np.insert(lat,0,-90)
   lat = np.append(lat,90)
   lon = np.arange(-182.5,179,5)
   m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
                    llcrnrlon=-182.5,\
                    urcrnrlon=177.5,\
                   resolution='c')

   m.drawcoastlines()
   m.drawmapboundary()
   parallels = np.arange(-90,91,15)
   meridians = np.arange(-180,151,30)

   plt.xticks(meridians)
   plt.yticks(parallels)

   m.drawparallels(parallels)
   m.drawmeridians(meridians)
   x, y = np.meshgrid(*m(lon, lat))
   poly = m.pcolor(lon, lat, data)

   cb = plt.colorbar(poly, ax = m.ax,shrink=0.8)#,#orientation = 'horizontal')
   plt.xlabel('Longitude',fontsize = 20)
   plt.ylabel('Latitude',fontsize = 20)
   #plt.text(191,93,'%s (%s)'%(species,units),fontsize=20)

   #plt.title('%s at Surface, %s to %s'%(species,time[0],end_time[-1]),fontsize=20)
   fig.savefig( Output_Name, transparent=True )


   return ;
コード例 #30
0
ファイル: MChem_tools.py プロジェクト: bn506/MChem_tools
def plot_geos_alt_slice(scalar, **Kwargs):
    # Setup slices                                                                                                 
    # Grid/Mesh values for Lat, lon, & alt                                                                         
    lon = gchemgrid('e_lon_4x5')
    lat = gchemgrid('e_lat_4x5')
    alt = gchemgrid('c_km_geos5_r')#'e_km_geos5_r')#'c_km_geos5_r')                                                
    units= 'ppbv'#diag.unit                                                                                        
    # Setup mesh grids                                                                                             
    x, y = np.meshgrid(lon,lat)
    print len(x), len(y)

    plt.ylabel('Latitude', fontsize = 20)
    plt.xlabel('Longitude',fontsize = 20)

    # Setup map ("m") using Basemap                                                                                
    m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
                    llcrnrlon=-182.5,\
                    urcrnrlon=177.5,\
                    resolution='c')
    m.drawcoastlines()

    parallels = np.arange(-90,91,15)
    meridians = np.arange(-180,151,30)

    plt.xticks(meridians) # draw meridian lines
    plt.yticks(parallels) # draw parrelel lines
#    m.drawparallels(parallels) # add to map
                                                                                                                   
    # Create meshgrid to plot onto                                                                             
    x, y = np.meshgrid(*m(lon, lat))
    print len(x), len(y)

    plt.xlim(-180,175)
    plt.ylim(-89,89)

    poly = m.pcolor(lon, lat, scalar, cmap = plt.cm.Blues)#_r, vmin=-7, vmax=0.0)

    # Add labels/annotations                                                                                       
    cb = plt.colorbar(poly, ax = m.ax,shrink=0.4)#,orientation = 'horizontal')                                    

    return plt , cb #, plt.title  
コード例 #31
0
def classificaGELO(caminhonc, caminhosaidatsmmsg, caminhosaidaantartica):
    # >> Gerando a lista --------------------------------------------
    dirList = os.listdir(caminhonc)
    #print dirList

    controleNome = dirList[0]  #Buscando variaveis nos elementos da lista
    posicA = controleNome.find(
        "CON")  #Buscando variaveis nos elementos da lista
    anoi = posicA + 4  #Buscando variaveis nos elementos da lista
    anof = posicA + 8  #Buscando variaveis nos elementos da lista
    mesi = posicA + 8  #Buscando variaveis nos elementos da lista
    mesf = posicA + 10  #Buscando variaveis nos elementos da lista
    diai = posicA + 10  #Buscando variaveis nos elementos da lista
    diaf = posicA + 12  #Buscando variaveis nos elementos da lista
    horai = posicA + 12  #Buscando variaveis nos elementos da lista
    horaf = posicA + 14  #Buscando variaveis nos elementos da lista
    ano = controleNome[anoi:anof]  #Buscando variaveis nos elementos da lista
    mes = controleNome[mesi:mesf]  #Buscando variaveis nos elementos da lista
    dia = controleNome[diai:diaf]  #Buscando variaveis nos elementos da lista
    horaTIT = controleNome[horai:
                           horaf]  #Buscando variaveis nos elementos da lista

    #imLista = len(dirList)		#Definindo o tamnho da lista
    imLista = 01  #Redefinindo para considerar com base de 24 horas

    #print ano,mes,dia,horaTIT

    #print "################### TRATANDO OS DADOS *composição* ###################"
    # >> Lendo os arquivos e compondo a matriz ----------------------
    entradas = ''
    for hora in range(0, imLista):
        entradas = caminhonc + nomeMSG + ano + mes + dia + str(horaTIT).zfill(
            2) + FMT_nc  #Criando caminho
        #print entradas
        fileCon = Dataset(entradas, 'r')
        #------------------------------------------------------------------
        IC0 = fileCon.variables['ice_conc'][:]
        IC0 = numpy.copy(IC0)
        dims = IC0.shape
        ny = dims[1]
        nx = dims[2]
        IC0 = IC0[0, :, :]
        IC02 = np.zeros((ny, nx))
        for j in range(0, nx):
            for i in range(0, ny):
                if IC0[i, j] > 0. and IC0[i, j] <= 9.9:
                    IC02[i, j] = 426
                elif IC0[i, j] >= 10 and IC0[i, j] <= 39.9:
                    IC02[i, j] = 425
                elif IC0[i, j] >= 40 and IC0[i, j] <= 69.9:
                    IC02[i, j] = 424
                elif IC0[i, j] >= 70 and IC0[i, j] <= 89.9:
                    IC02[i, j] = 423
                elif IC0[i, j] >= 90 and IC0[i, j] <= 100:
                    IC02[i, j] = 422
                elif IC0[i, j] == 0.:
                    IC02[i, j] = 427
                else:
                    IC02[i, j] = 421

    IC02 = IC02
    my_cmap = colores.ListedColormap([(.3, .3, .3), (1., 0., 0.),
                                      (1., 0.4901960784, 0.0274509804),
                                      (1., 1., 0),
                                      (0.5490196078, 1., 0.6274509804),
                                      (0.5882352941, 0.7843137255, 1.),
                                      (0., 0.3921568627, 1.)])

    IC0 = IC02
    print 'eh noix'

    filename2 = '/home/geonetcast/gelo/d-eumetcast/LonLatGelo_OSI-SAF.nc'
    print 'eh noix dep nc'
    file1 = Dataset(filename2, 'r')
    print 'eh noix de novo'

    lon0 = file1.variables['longitude'][:]
    print 'eh noix de novo2'
    lat0 = file1.variables['latitude'][:]

    fig = plt.figure(figsize=(9.5, 9))

    ###original#####    Dmap = Basemap(projection='spstere',lat_0=-90,lon_0=0.,boundinglat=-55,lat_ts=-70, resolution='h',rsphere=(6378273.,6356889.44891)) #modificar a projeção entre os polos
    Dmap = Basemap(projection='lcc',
                   lat_0=-50,
                   lon_0=-80,
                   llcrnrlon=-80,
                   llcrnrlat=-75,
                   urcrnrlon=-40,
                   urcrnrlat=-50,
                   resolution='h')  #modificar a projeção entre os polos

    x0, y0 = Dmap(lon0, lat0)

    #IC0 = np.flipud(IC0[:,:])
    cor = 'black'

    col = Dmap.pcolor(x0,
                      y0,
                      IC0,
                      shading='interp',
                      vmin=421,
                      vmax=427,
                      cmap=my_cmap)

    # define parallels and meridians to draw.
    parallels = np.arange(-90., -55, 10.)
    meridians = np.arange(0., 360., 20.)

    Dmap.fillcontinents(color='gray')
    Dmap.drawcoastlines(linewidth=.5, color=cor)  # Linha de costa
    Dmap.drawcountries(linewidth=0.8,
                       color='k',
                       antialiased=1,
                       ax=None,
                       zorder=None)
    Dmap.drawstates(linewidth=0.5,
                    color='k',
                    antialiased=1,
                    ax=None,
                    zorder=None)
    Dmap.drawparallels(parallels,
                       labels=[1, 0, 0, 0],
                       color=cor,
                       dashes=[1, 1],
                       linewidth=0.2)
    Dmap.drawmeridians(meridians,
                       labels=[0, 0, 0, 1],
                       color=cor,
                       dashes=[1, 1],
                       linewidth=0.2)

    #Paleta de Cor
    bounds = [421.5, 422.5, 423.5, 424.5, 425.5, 426.5, 427.5]
    norm = colores.BoundaryNorm(bounds, my_cmap.N)
    cbar = fig.colorbar(col,
                        cmap=cm.Blues,
                        norm=norm,
                        boundaries=bounds,
                        ticks=[422, 423, 424, 425, 426, 427],
                        orientation='horizontal',
                        shrink=0.8,
                        pad=0.045)
    cbar.set_ticklabels([
        '9-10 Thents', '7-8 Thents', '4-6 Thents', '1-3 Thents', '< 1 Thents',
        'Ice Free'
    ])

    #------------------------------------------------------------------

    #Salvando e apresentado a imagem.
    d1 = datetime.date(int(ano), int(mes), int(dia))

    #DIAS DA SEMANA
    diasem = d1.strftime("%A")
    if diasem == 'Monday':
        diasem = 'SEG'
    elif diasem == 'Tuesday':
        diasem = 'TER'
    elif diasem == 'Wednesday':
        diasem = 'QUA'
    elif diasem == 'Thursday':
        diasem = 'QUI'
    elif diasem == 'Friday':
        diasem = 'SEX'
    elif diasem == 'Saturday':
        diasem = 'SAB'
    elif diasem == 'Sunday':
        diasem = 'DOM'

    #MES EM NOME
    nomemes = d1.strftime("%B")
    if nomemes == 'January':
        nomemes = 'JAN'
    elif nomemes == 'February':
        nomemes = 'FEV'
    elif nomemes == 'March':
        nomemes = 'MAR'
    elif nomemes == 'April':
        nomemes = 'ABR'
    elif nomemes == 'May':
        nomemes = 'MAI'
    elif nomemes == 'June':
        nomemes = 'JUN'
    elif nomemes == 'July':
        nomemes = 'JUL'
    elif nomemes == 'August':
        nomemes = 'AGO'
    elif nomemes == 'September':
        nomemes = 'SET'
    elif nomemes == 'October':
        nomemes = 'OUT'
    elif nomemes == 'November':
        nomemes = 'NOV'
    elif nomemes == 'December':
        nomemes = 'DEZ'

    title('CHM-REMO Concentracao de Gelo Marinho Peninsula' +
          str(dia).zfill(2) + nomemes + ano + '(' + diasem +
          ') - GEONETCAST-EUMETSAT/O&SI-SAF',
          fontsize=8.,
          fontweight='bold')
    dirsaida = caminhosaidatsmmsg
    FMT_png = ".png"
    nome1 = "CON_GELPEN_"
    fname = dirsaida + nome1 + str(ano) + str(mes).zfill(2) + str(dia).zfill(
        2) + 'analise' + FMT_png
    savefig(fname, bbox_inches='tight')
    fnameantartica = caminhosaidaantartica + nome1 + str(ano) + str(mes).zfill(
        2) + str(dia).zfill(2) + 'analise' + FMT_png
    savefig(fnameantartica, dpi=700, bbox_inches='tight')
    plt.close()
コード例 #32
0
                   resolution='c')


if full_image == 'N':
    m.drawcoastlines()
    m.drawmapboundary()
    parallels = np.arange(-60,61,15)
    meridians = np.arange(-180,151,30)
    plt.xticks(meridians)
    plt.yticks(parallels)
    m.drawparallels(parallels)
    m.drawmeridians(meridians)

#plot model gridboxes
if type == 'mag':
	poly = m.pcolor(lon_e, lat_e, z,vmin=0, vmax=23.5,cmap = plt.cm.coolwarm)
else:
    poly = m.pcolor(lon_e, lat_e, z, vmin=phase_min, vmax=phase_max, cmap=plt.cm.hsv)

if full_image == 'N':
    if (period == 'half_annual') & (type == 'phase'):
        cb = plt.colorbar(poly, ticks =[0,1,2,3,4,5],  ax = m.ax,shrink=0.8,orientation = 'horizontal', format='%.2f')
        cb.ax.set_xticklabels(['M1','M2','M3','M4','M5','M6'])
        
    elif (period == 'annual') & (type == 'phase'):
        cb = plt.colorbar(poly, ticks =[0,1.01848,1.94661,2.96509,3.95072,4.96920,5.95483,6.97331,7.99179,8.97741,9.99589,10.98152],  ax = m.ax,shrink=0.8,orientation = 'horizontal', format='%.2f')
        cb.ax.set_xticklabels(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
    else:
        cb = plt.colorbar(poly, ax = m.ax,shrink=0.8,orientation = 'horizontal', format='%.2f')
    cb.set_label('%s'%(label), fontsize = 16)
    plt.xlabel('Longitude',fontsize = 20)
コード例 #33
0
            urcrnrlon=160.0)
m.drawcoastlines()
m.drawparallels(np.array([-45, -35, -25, -15, -5]),
                labels=[1, 0, 0, 0],
                fontsize=7)
m.drawmeridians(np.array([110, 120, 130, 140, 150, 160]),
                labels=[0, 0, 0, 1],
                fontsize=7)
lon, lat = np.meshgrid(lon, lat)
xi, yi = m(lon, lat)
mn_strd_nino = np.ma.masked_invalid(mn_strd_nino)
ss_strd_nino = np.ma.masked_invalid(ss_strd_nino)
v = np.linspace(-28, 28, 29, endpoint=True)
norm = colors.BoundaryNorm(boundaries=v, ncolors=256)
mymap = m.pcolormesh(xi, yi, mn_strd_nino, norm=norm, cmap='bwr')
ss = m.pcolor(xi, yi, ss_strd_nino, hatch='...', norm=norm, cmap='bwr')
cb = m.colorbar(mymap, "right", size="5%", pad="2%", ticks=v)
cb.ax.tick_params(labelsize=6)
for label in cb.ax.yaxis.get_ticklabels()[1::2]:
    label.set_visible(False)
cb.set_label('$W/m^2$', fontsize=8)
plt.title('Longwave downwards', fontsize=10)
ax.set_ylabel('El Nino', labelpad=20)

ax = plt.subplot2grid((4, 5), (2, 0))
m = Basemap(projection='cyl',
            llcrnrlat=-45.0,
            llcrnrlon=110.0,
            urcrnrlat=-5.0,
            urcrnrlon=160.0)
m.drawcoastlines()
コード例 #34
0
    cbl = '[mm day-1]'
    cl = [-1.6, 1.6]
elif precipchange == True:
    titre = 'Mean MCS frequency x change in MCS precip'
    field = np.concatenate((deltaCP[90:, :], deltaCP[:90, :]))
    cbl = '[mm day-1]'
    cl = [-1.6, 1.6]
elif resid == True:
    titre = 'Residual'
    field = np.concatenate((residual[90:, :], residual[:90, :]))
    cbl = '[mm day-1]'
    cl = [-1.6, 1.6]
else:
    print('None of the visualization booleans were specified.')
    sys.exit()

axes.set_title(titre)
carte = Basemap(llcrnrlon=lowlon,urcrnrlon=hilon,llcrnrlat=lowlat,urcrnrlat=hilat,\
                   resolution='i',projection='merc',lon_0=180.,ax=axes)
lons, lats = carte.makegrid(nx, ny)
x, y = carte(lons, lats)
carte.drawparallels(paral.astype(int), labels=[1, 1, 0, 0], dashes=[1, 1])
carte.drawmeridians(merid.astype(int), labels=[0, 0, 0, 1], dashes=[1, 1])
carte.drawcoastlines(linewidth=1)
cpc = carte.pcolor(x, y, field, shading='flat', cmap=cm.RdBu_r)
cbar = carte.colorbar(cpc, location='bottom', pad='20%', size='15%')
cbar.set_label(cbl)
cpc.set_clim(cl[0], cl[1])

plt.show()
コード例 #35
0
m.tissot(x0, y0, R, 100, facecolor='g', alpha=0.2)

cm = plt.cm.get_cmap('jet')

# Plot background from the cluster analysis of Cottaar &Lekic 2016
if plot_background:
    LMC = LMClust_g6_ryb.LMClust()
    LMC.read('/raid2/sc845/Tomographic_models/LMClust/', 'clustgr.txt')
    lon, lat, layer = LMC.get_slice(depth_background)
    x, y = m(lon.ravel(), lat.ravel())
    x = x.reshape(np.shape(layer))
    y = y.reshape(np.shape(layer))
    minval = np.min(np.min(layer))
    maxval = np.max(np.max(layer)) + .1
    m.pcolor(x, y, layer, cmap=LMC.rgb_map_light, linewidth=0, rasterized=True)

# Loop through stations
for s in range(len(seislist)):
    print(s + 1, len(seislist[s]), seislist[s])
    seis = read(seislist[s], format='PICKLE')

    # Get event-station pair delay time and amplitude ratio
    delayTime = delayTimes[s]
    amplRatio = amplRatios[s]

    # Get bounce location of ScS phase
    turnloc = seis[0].stats.turnpoints["ScS"]
    tlon = turnloc[2]
    tlat = turnloc[1]
    x, y = m(tlon, tlat)
コード例 #36
0
m.drawcoastlines(linewidth=1.)

lons, lats = m.makegrid(data1['x_dim'], data1['y_dim']) # get lat/lons of ny by nx evenly space grid.
x, y = m(lons, lats) # compute map proj coordinates.

# contour levels
maxdat1 = 10
mindat1 = 0
#clevs = np.arange(0.0,maxdat,200)

# data = np.nanmean(data1['nisg80'][0:3,zind1,:,:],0)
data = allicebelow1 # w1 # bl1_1
# data[data == 0] = np.nan
# data[data > maxdat] = maxdat

cs = m.pcolor(x,y,data,vmin=mindat1,vmax=maxdat1,cmap=mpl_cm.Reds)


xd3_1,yd3_1 = m(lon3[n3y-1,0],lat3[n3y-1,0]) 
xd3_2,yd3_2 = m(lon3[0,0],lat3[0,0]) 
xd3_3,yd3_3 = m(lon3[0,n3x-1],lat3[0,n3x-1]) 
xd3_4,yd3_4 = m(lon3[n3y-1,n3x-1],lat3[n3y-1,n3x-1])

p3 =  Polygon([(xd3_1,yd3_1),(xd3_2,yd3_2),(xd3_3,yd3_3),(xd3_4,yd3_4)],\
              facecolor='none',linestyle='--',edgecolor='k',linewidth=2)
plt.gca().add_patch(p3)

x27,y27 = m(newlon27, newlat27)
plt.plot(x27,y27,'r',linewidth=1)
plt.annotate(runlab1,xy=(-78,-28),xytext=(-78,-28),fontsize=10)
コード例 #37
0
ファイル: test10.py プロジェクト: Thpffcj/Python-Learning
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

#m = Basemap(resolution="l",projection="ortho",
 #           lat_0=45,lon_0=-100)


lon_0 = lons.mean()
lat_0 = lats.mean()
m = Basemap(width=6800000,height=5500000,resolution="l",projection="stere",
            lat_ts=40,lat_0=lat_0,lon_0=lon_0)

lon,lat = np.meshgrid(lons,lats)
xi,yi = m(lon,lat)

cs = m.pcolor(xi,yi,np.squeeze(tmax))

# Add Grid Lines
m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10)
m.drawmeridians(np.arange(0., 360., 10.), labels=[0,0,0,1], fontsize=10)

# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()

# Add Colorbar
cbar = m.colorbar(cs, location='bottom', pad="10%")
cbar.set_label(tmax_units)

# Add Title
コード例 #38
0
lon_ind_st, lon_ind_fin = gridbounds(lon_ind_st, lon_ind_fin)
lat_ind_st, lat_ind_fin = gridbounds(lat_ind_st, lat_ind_fin)
print(lon_ind_st, lon_ind_fin)
print(lat_ind_st, lat_ind_fin)

print("meshgrid")
lon_g, lat_g = np.meshgrid(lon[lon_ind_st:lon_ind_fin],
                           lat[lat_ind_st:lat_ind_fin])  # хз чо это
x, y = mp(lon_g, lat_g)
print(np.shape(lccs_class))
print("color scheme")
#color_scheme = mp.pcolor(x, y, lccs_class[0, lon_ind_st:lon_ind_fin, lat_ind_st:lat_ind_fin], cmap='jet')
#color_scheme = mp.pcolor(x, y, lccs_class[0, lat_ind_st:lat_ind_fin, lon_ind_st:lon_ind_fin], cmap='jet')
color_scheme = mp.pcolor(x,
                         y,
                         np.squeeze(lccs_class[0, lat_ind_st:lat_ind_fin,
                                               lon_ind_st:lon_ind_fin]),
                         cmap='jet')
print("coastlines")
mp.drawcoastlines()
print("countries")
mp.drawcountries()
print("states")
mp.drawstates()
print("title")
plt.title("Surface classes mothefuccka!")
print("showing...")
plt.show()

# просто рисование матплотлибом
##cs = plt.contourf(lon[100:110], lat[100:110], current_pixel_state[0,100:110,100:110])
コード例 #39
0
def plot_variable(file_list,variable2plot):
    map = Basemap(projection='merc',llcrnrlat=44.,urcrnrlat=58.447,\
    llcrnrlon=-10.,urcrnrlon=18.,resolution='l')   #Paris: lat = 48.5 - 52, lon = 1 - 4.5

#59 , -10
#44 , 18

    # draw coastlines, country boundaries, fill continents.
    map.drawcoastlines(linewidth=0.6, color = 'black')
    map.drawcountries(linewidth = 0.6, color = 'black')
   
    map.drawlsmask(land_color='white',ocean_color='white')

    # draw lat/lon grid lines every x degrees.
    map.drawparallels(np.arange( -90.,90.,1.),linewidth=0.1,color = 'Black',labels=[1,0,0,0])
    map.drawmeridians(np.arange(-180.,180.,1.),linewidth=0.1,color = 'Black',labels=[0,0,0,1])
   
    cmap = cm.get_cmap(name='rainbow')   #NO2: 'rainbow'   clouds: 'Blues_r'
    cmap.set_under('white')
    #cmap.set_under('0.3')
    #cmap.set_over('1.0')

    data_range = None
    dynamic_range = False
    if data_range is None:
        data_range = [1e20, -1e20]
        dynamic_range = True

    filters = [
               'cloud_radiance_fraction_nitrogendioxide_window < 0.5',
               'surface_albedo < 0.3',
               'air_mass_factor_troposphere > 0.2'
]

    data = []

    for f in file_list:    
        var,latb,lonb,extended_name, unit = get_data(f,variable2plot,filters) 

        xtrack_range = None
    
        if dynamic_range:
            try:
                sel_data = var.data[np.logical_not(var.mask)]
                if sel_data.shape[0] == 0:
                    print 'continue in the loop'
            except AttributeError:
                sel_data = var            
        
            data_range[0] = min(np.nanmin(sel_data), data_range[0])
            data_range[1] = max(np.nanmax(sel_data), data_range[1])

        data.append((var, latb, lonb))
    for var, latb, lonb in data:
        x,y = map(lonb,latb)
        if xtrack_range is None:
            cs = map.pcolor(x,y,var,cmap=cmap,latlon=False,vmin=0, vmax=20e15)  #-10e15, vmax=20e15
        else:
                # pcolormesh
            cs = map.pcolor(x[:,:],
                            y[:,:],
                            var[:,:],
                            cmap=cmap,
                            latlon=False, 
                            vmin=data_range[0], vmax=data_range[1])

    cbar = map.colorbar(cs,location='right',pad="12%", extend="both")
    cbar.set_label(unit)
    
    # Label for the plot
    label = 'TROPOMI o00569 - 11-22-2017'
    #if label is None:
     #   plt.title(extended_name)
    #else:
        #plt.title("{0} - {1}".format(extended_name,label))
    
    # Name of the file for figure
    fig = 'paris_1122_tropomi'
    if fig is None:
        plt.show()
    else:
        f = plt.gcf()
        f.set_size_inches(10.0, 6.0, forward=True)
        plt.savefig(fig, dpi=300)
        plt.show()
コード例 #40
0
ファイル: GRACE_validation.py プロジェクト: whigg/PhD
GRACE_xcorr = np.full((59, 361), fill_value=np.NaN)
GRACE_xcorr_pvalues = np.full((59, 361), fill_value=np.NaN)

for ilat in range(len(lat)):
    for ilon in range(len(lon)):
        if np.sum(np.isfinite(GRACE[:, ilat, ilon])) > len(GRACE[:, ilat, ilon]) // 2:
            ts_1 = GRACE[:, ilat, ilon]
            xcorr = stats.pearsonr(ts_1, sam_index)
            GRACE_xcorr[ilat, ilon] = xcorr[0]
            GRACE_xcorr_pvalues[ilat, ilon] = xcorr[1]

#GRACE_xcorr[57, 300] = 1000

pl.figure()
pl.clf()
m = Basemap(projection='spstere', boundinglat=-50, lon_0=180, resolution='l')
m.drawmapboundary()
m.drawcoastlines(zorder=10)
m.fillcontinents(zorder=10)
m.drawparallels(np.arange(-80., 81., 20.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-180., 181., 20.), labels=[0, 0, 0, 1])
        
grid_lats, grid_lons = np.meshgrid(lat, lon)
stereo_x, stereo_y = m(grid_lons, grid_lats)
        
m.pcolor(stereo_x, stereo_y, np.transpose(np.ma.masked_invalid(GRACE_xcorr)), cmap='RdBu_r')
m.colorbar()
pl.clim(1, -1)
m.contour(stereo_x, stereo_y, np.transpose(np.ma.masked_invalid(GRACE_xcorr_pvalues)), [0.2], color='k')
pl.savefig('/Users/jmh2g09/Documents/PhD/Data/GRACE/Validation/GRACE_SAM_corr.png', transparent=True, dpi=300, bbox_inches='tight')
pl.close()
コード例 #41
0
lon, lat = np.meshgrid(lons, lats)
xi, yi = m(lon, lat)

#画u10、v10、swh、mwd、mwp图
i = 0
title = [
    '10 metre U wind component', '10 metre v wind component',
    'significant height of combined waves and swell', 'mean wave direction',
    'mean wave period'
]
units = [u10_units, v10_units, swh_units, mwd_units, mwp_units]

for xx in [u10, v10, swh, mwd, mwp]:
    xx_ = xx[1, :, :]
    # Plot Data
    cs = m.pcolor(xi, yi, np.squeeze(xx_), cmap=plt.cm.jet)
    #    print('xi.shape',xi.shape)
    #    print('yi.shape', yi.shape)
    #    print('np.squeeze shape',np.squeeze(xx_).shape)
    #cs = m.pcolor(xi, yi, np.squeeze(xx_))
    # Add Grid Lines
    m.drawparallels(np.arange(-80., 81., 20.),
                    labels=[1, 0, 0, 0],
                    fontsize=10)
    m.drawmeridians(np.arange(-180., 181., 20.),
                    labels=[0, 0, 0, 1],
                    fontsize=10)

    # Add Coastlines, States, and Country Boundaries
    m.drawcoastlines()
    m.drawstates()
コード例 #42
0
        cMsk_all = cMsk.copy()
        cMsk = maskoceans(lons, lats, cMsk)
        cMsk_r = maskoceans(lons, lats, cMsk_r)

        fig = plt.figure()
        m = Basemap(projection='kav7', lon_0=0)
        #m.pcolor(sstLons.astype(int),sstLats.astype(int),eof_sst,cmap='RdBu_r',latlon=True,vmin=-0.75,vmax=0.75)

        SVDcol = pd.DataFrame(data={'state': eof_states2, 'SVD': eof_prod})

        #Plot everything at the country level first from FAO data before going into subnational data
        world = m.readshapefile(
            '/Volumes/Data_Archive/Data/adminBoundaries/ne_50m_admin_0_countries/ne_50m_admin_0_countries',
            name='cnts',
            drawbounds=True)
        m.pcolor(lons, lats, cMsk_r, cmap='Dark2_r', zorder=1.2, latlon=True)

        names = []
        colors = {}
        i = 0
        for shape_dict in m.cnts_info:
            names.append(shape_dict['NAME'])
            if len(
                    np.where(
                        np.array(eof_states2) == unidecode(
                            str(crop + '_' +
                                shape_dict['NAME'].upper())))[0]) != 0:
                state_color = SVDcol[SVDcol.state == unidecode(
                    str(crop + '_' +
                        shape_dict['NAME'].upper()))]['SVD'].values.astype(
                            float)[0]
コード例 #43
0
"""
import sys
import pylab
from mpl_toolkits.basemap import Basemap

# Set up a projection
bm = Basemap(projection='ortho', lon_0=-80, lat_0=-40,
             resolution='l', area_thresh=10000)

data = pylab.loadtxt(sys.argv[1], unpack=True)
shape = (int(sys.argv[2]), int(sys.argv[3]))
lon = pylab.reshape(data[0], shape)
lat = pylab.reshape(data[1], shape)
glon, glat = bm(lon, lat)

for i, value in enumerate(data[3:]):
    value = pylab.reshape(value, shape)
    pylab.figure(figsize=(4, 3))
    pylab.title("Column %d" % (i + 4))
    bm.drawcoastlines()
    #bm.fillcontinents(color='coral',lake_color='aqua')
    #bm.drawmapboundary(fill_color='aqua')
    bm.drawmapboundary()
    bm.drawparallels(pylab.arange(-90.,120.,30.))
    bm.drawmeridians(pylab.arange(0.,420.,60.))
    #bm.bluemarble()
    bm.pcolor(glon, glat, value)
    pylab.colorbar()
    #bm.contour(glon, glat, value, 12, linewidth=3)
    pylab.savefig('column%d.png' % (i + 4))
コード例 #44
0
def isoview(var, prop, tindex, isoval, grid, filename=None, \
          cmin=None, cmax=None, clev=None, fill=False, \
          contour=False, d=4, range=None, fts=None, \
          title=None, clb=True, pal=None, proj='merc', \
          fill_land=False, outfile=None):
    """
    map = isoview(var, prop, tindex, isoval, grid, {optional switch})

    optional switch:
      - filename     if defined, load the variable from file
      - cmin         set color minimum limit
      - cmax         set color maximum limit
      - clev         set the number of color step
      - fill         use contourf instead of pcolor
      - contour      overlay contour (request fill=True)
      - d            contour density (default d=4)
      - range        set axis limit
      - fts          set font size (default: 12)
      - title        add title to the plot
      - clb          add colorbar (defaul: True)
      - pal          set color map (default: cm.jet)
      - proj         set projection type (default: merc)
      - fill_land    fill land masked area with gray (defaul: True)
      - outfile      if defined, write figure to file

    plot a projection of variable at property == isoval. If filename
    is provided, var and prop must be a strings and the variables will
    be load from the file.
    grid can be a grid object or a gridid. In the later case, the grid
    object correponding to the provided gridid will be loaded.
    If proj is not None, return a Basemap object to be used with quiver
    for example.
    """

    # get grid
    if type(grid).__name__ == 'ROMS_Grid':
        grd = grid
    else:
        grd = pyroms.grid.get_ROMS_grid(grid)

    # get variable
    if filename == None:
        var = var
        prop = prop
    else:
        data = pyroms.io.Dataset(filename)
        var = data.variables[var]
        prop = data.variables[prop]

    Np, Mp, Lp = grd.vgrid.z_r[0, :].shape

    if tindex is not -1:
        assert len(var.shape) == 4, 'var must be 4D (time plus space).'
        K, N, M, L = var.shape
    else:
        assert len(var.shape) == 3, 'var must be 3D (no time dependency).'
        N, M, L = var.shape

    # determine where on the C-grid these variable lies
    if N == Np and M == Mp and L == Lp:
        Cpos = 'rho'
        mask = grd.hgrid.mask_rho

    if N == Np and M == Mp and L == Lp - 1:
        Cpos = 'u'
        mask = grd.hgrid.mask_u

    if N == Np and M == Mp - 1 and L == Lp:
        Cpos = 'v'
        mask = grd.hgrid.mask_v

    # get constante-iso slice
    if tindex == -1:
        var = var[:, :, :]
        prop = prop[:, :, :]
    else:
        var = var[tindex, :, :, :]
        prop = prop[tindex, :, :, :]

    if fill == True:
        isoslice, lon, lat = pyroms.tools.isoslice(var, prop, isoval, \
                                             grd, Cpos=Cpos)
    else:
        isoslice, lon, lat = pyroms.tools.isoslice(var, prop, isoval, \
                                             grd, Cpos=Cpos, vert=True)

    # plot
    if cmin is None:
        cmin = isoslice.min()
    else:
        cmin = float(cmin)

    if cmax is None:
        cmax = isoslice.max()
    else:
        cmax = float(cmax)

    if clev is None:
        clev = 100.
    else:
        clev = float(clev)

    dc = (cmax - cmin) / clev
    vc = np.arange(cmin, cmax + dc, dc)

    if pal is None:
        pal = cm.jet
    else:
        pal = pal

    if fts is None:
        fts = 12
    else:
        fts = fts

    #pal.set_over('w', 1.0)
    #pal.set_under('w', 1.0)
    #pal.set_bad('w', 1.0)

    pal_norm = colors.BoundaryNorm(vc, ncolors=256, clip=False)

    if range is None:
        lon_min = lon.min()
        lon_max = lon.max()
        lon_0 = (lon_min + lon_max) / 2.
        lat_min = lat.min()
        lat_max = lat.max()
        lat_0 = (lat_min + lat_max) / 2.
    else:
        lon_min = range[0]
        lon_max = range[1]
        lon_0 = (lon_min + lon_max) / 2.
        lat_min = range[2]
        lat_max = range[3]
        lat_0 = (lat_min + lat_max) / 2.

    # clear figure
    #plt.clf()

    if proj is not None:
        map = Basemap(projection=proj, llcrnrlon=lon_min, llcrnrlat=lat_min, \
              urcrnrlon=lon_max, urcrnrlat=lat_max, lat_0=lat_0, lon_0=lon_0, \
                 resolution='h', area_thresh=5.)
        #map = pyroms.utility.get_grid_proj(grd, type=proj)
        x, y = list(map(lon, lat))

    if fill_land is True and proj is not None:
        # fill land and draw coastlines
        map.drawcoastlines()
        map.fillcontinents(color='grey')
    else:
        if proj is not None:
            Basemap.pcolor(map, x, y, mask, vmin=-2, cmap=cm.gray)
            pyroms_toolbox.plot_coast_line(grd, map)
        else:
            plt.pcolor(lon, lat, mask, vmin=-2, cmap=cm.gray)
            pyroms_toolbox.plot_coast_line(grd)

    if fill is True:
        if proj is not None:
            cf = Basemap.contourf(map, x, y, isoslice, vc, cmap = pal, \
                                  norm = pal_norm)
        else:
            cf = plt.contourf(lon, lat, isoslice, vc, cmap = pal, \
                              norm = pal_norm)
    else:
        if proj is not None:
            cf = Basemap.pcolor(map, x, y, isoslice, cmap=pal, norm=pal_norm)
        else:
            cf = plt.pcolor(lon, lat, isoslice, cmap=pal, norm=pal_norm)

    if clb is True:
        clb = plt.colorbar(cf, fraction=0.075, format='%.2f')
        for t in clb.ax.get_yticklabels():
            t.set_fontsize(fts)

    if contour is True:
        if fill is not True:
            raise Warning(
                'Please run again with fill=True to overlay contour.')
        else:
            if proj is not None:
                Basemap.contour(map,
                                x,
                                y,
                                isoslice,
                                vc[::d],
                                colors='k',
                                linewidths=0.5,
                                linestyles='solid')
            else:
                plt.contour(lon,
                            lat,
                            isoslice,
                            vc[::d],
                            colors='k',
                            linewidths=0.5,
                            linestyles='solid')

    if proj is None and range is not None:
        plt.axis(range)

    if title is not None:
        plt.title(title, fontsize=fts + 4)

    if proj is not None:
        map.drawmeridians(np.arange(lon_min,lon_max, (lon_max-lon_min)/5.), \
                          labels=[0,0,0,1], fmt='%.1f')
        map.drawparallels(np.arange(lat_min,lat_max, (lat_max-lat_min)/5.), \
                          labels=[1,0,0,0], fmt='%.1f')

    if outfile is not None:
        if outfile.find('.png') != -1 or outfile.find('.svg') != -1 or \
           outfile.find('.eps') != -1:
            print('Write figure to file', outfile)
            plt.savefig(outfile, dpi=200, facecolor='w', edgecolor='w', \
                        orientation='portrait')
        else:
            print(
                'Unrecognized file extension. Please use .png, .svg or .eps file extension.'
            )

    if proj is None:
        return
    else:
        return map
コード例 #45
0
fig.patch.set_facecolor('white')

#setup basemap projection
m = Basemap(projection='cyl',
            llcrnrlat=lat_e[0],
            urcrnrlat=lat_e[-1],
            llcrnrlon=lon_e[0],
            urcrnrlon=lon_e[-1],
            resolution='c')

m.drawcoastlines()
m.drawmapboundary()
parallels = np.arange(-90, 91, 15)
meridians = np.arange(-180, 151, 30)

pl = m.pcolor(lon_e,
              lat_e,
              z,
              vmin=np.min(z),
              vmax=np.max(z),
              linewidth=0.5,
              cmap=plt.cm.coolwarm,
              picker=5)
cb = plt.colorbar(pl,
                  ax=m.ax,
                  shrink=0.8,
                  orientation='horizontal',
                  format='%.2f')

plt.show()
コード例 #46
0
for d in range(0, 360, 50):
    flatTLat = np.array(latGrid)
    flatTLon = np.array(lonGrid)
    flatTData = np.array(np.squeeze(futureWbDownscaling[0, :, :, d]))

    m = Basemap(width=10000000 / 5,
                height=7000000 / 5,
                resolution='l',
                projection='stere',
                lat_ts=40,
                lat_0=sum(latRange) / 2,
                lon_0=sum(lonRange) / 2)

    lon, lat = np.meshgrid(flatTLon[0, :], flatTLat[:, 0])
    x, y = m(lon, lat)
    cs = m.pcolor(x, y, np.squeeze(flatTData), vmin=-5, vmax=25)

    # Add Grid Lines
    m.drawparallels(np.arange(-80., 81., 10.),
                    labels=[1, 0, 0, 0],
                    fontsize=10)
    m.drawmeridians(np.arange(-180., 181., 10.),
                    labels=[0, 0, 0, 1],
                    fontsize=10)

    # Add Coastlines, States, and Country Boundaries
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()

    # Add Colorbar
コード例 #47
0
    # Make nice map images
    plt.rcParams["figure.figsize"] = (10, 10)
    map1 = Basemap(epsg=epsg, llcrnrlon=xmin - 360 - 1, llcrnrlat= ymin - 1, urcrnrlon=xmax - 360 + 3,
                  urcrnrlat=ymax + 1, resolution='i', area_thresh=10000.)
    map1.fillcontinents(color='#e8e8e8', alpha=1, zorder=1)
    map1.drawcountries(color='black', linewidth=2, zorder=3)
    map1.drawstates(color='black', linewidth=1, zorder=4)
    map1.drawparallels(np.arange(ymin, ymax, round(abs(ymin-ymax)/3)), color="black", labels=[1, 0, 0, 0], fontsize=10, linewidth=0.2, zorder=5)
    map1.drawmeridians(np.arange(xmin, xmax, round(abs(xmin-xmax)/3)), color="black", labels=[0, 0, 0, 1], fontsize=10, linewidth=0.2, zorder=6)
	
	x,y = map1(sitesx,sitesy)
	map1.scatter(x, y, marker='o',s=5, zorder=7, color = 'black')
	
	m_lon, m_lat = np.meshgrid(lon, lat)
	xi, yi = map(m_lon, m_lat)
    cs = map1.pcolor(xi, yi, np.squeeze(DD_output), alpha=1, vmin=0, vmax=1, cmap='jet_r', zorder=2)
    cbar = map1.colorbar(cs, location='bottom', pad="5%")
    cbar.set_alpha(1)
    cbar.draw_all()
    cbar.set_label('Proportion of days suitable for deployment', fontsize=12)
    plt.savefig('DD_' + company.name + '_map' + '.png', dpi=300)
    plt.clf()
			#### Map2###
    map2 = Basemap(epsg=epsg, llcrnrlon=xmin - 360 - 1, llcrnrlat= ymin - 1, urcrnrlon=xmax - 360 + 3,
                  urcrnrlat=ymax + 1, resolution='i', area_thresh=10000.)
    map2.fillcontinents(color='#e8e8e8', alpha=1, zorder=1)
    map2.drawcountries(color='black', linewidth=2, zorder=3)
    map2.drawstates(color='black', linewidth=1, zorder=4)
    map2.drawparallels(np.arange(ymin, ymax, round(abs(ymin-ymax)/3)), color="black", labels=[1, 0, 0, 0], fontsize=10, linewidth=0.2, zorder=5)
    map2.drawmeridians(np.arange(xmin, xmax, round(abs(xmin-xmax)/3)), color="black", labels=[0, 0, 0, 1], fontsize=10, linewidth=0.2, zorder=6)
	
コード例 #48
0
def plotCurrents(dsU, dsV, uVar, vVar):

    # get boundaries
    latMin, latMax, lonMin, lonMax = getBoundaries(dsU)

    for t in range(24):

        # create a new figure
        plt.figure()

        # get data for currents
        try:
            lons = dsU.variables[lonVar][:]
            lats = dsU.variables[latVar][:]
            umax = dsU.variables[uVar][t, 0, :, :]
            vmax = dsV.variables[vVar][t, 0, :, :]
            print("Reading variables: ok")
        except KeyError:
            logger.error("Check your variables!")
            sys.exit(1)

        # plot them
        m = Basemap(llcrnrlat=lats.min(),
                    urcrnrlat=lats.max(),
                    llcrnrlon=lons.min(),
                    urcrnrlon=lons.max(),
                    resolution='l')

        lat_indexes = getRangeIndexes(lats, lats.min(), lats.max())
        lon_indexes = getRangeIndexes(lons, lons.min(), lons.max())

        lats_sel = lats[lat_indexes]
        lons_sel = lons[lon_indexes]
        xx, yy = np.meshgrid(lons_sel, lats_sel)

        # Add Coastlines, States, and Country Boundaries
        m.drawcoastlines()
        m.drawstates()
        m.drawcountries()

        # add color
        m.fillcontinents(color='coral', lake_color='aqua')

        # set the title
        plt.title("Currents")

        # color the sea
        lon, lat = np.meshgrid(lons, lats)
        xi, yi = m(lon, lat)
        cs = m.pcolor(xi, yi, np.squeeze(umax))

        ## draw meridians and parallels
        step_lat = float((latMax - latMin) / 5)
        step_lon = float((lonMax - lonMin) / 5)

        # draw arrows
        X = lons[::5]
        Y = lats[::5]
        UU = umax[::5, ::5]
        VV = vmax[::5, ::5]
        m.quiver(X, Y, UU, VV, scale=3)

        # show the plot
        plt.show()
コード例 #49
0
#Get some parameters for the Stereographic Projection
lon_0 = lons.mean()
lat_0 = lats.mean()


m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,\
            llcrnrlon=0,urcrnrlon=360,lat_ts=20,resolution='c')

# Because our lon and lat variables are 1D,
# use meshgrid to create 2D arrays
# Not necessary if coordinates are already in 2D arrays.
lon, lat = np.meshgrid(lons, lats)
xi, yi = m(lon, lat)

# Plot Data
cs = m.pcolor(xi, yi, Z5002)
#cs = m.contour(xi, yi, Z5002,15,linewidths=1.5)

# Add Grid Lines
m.drawparallels(np.arange(-80., 81., 10.), labels=[1, 0, 0, 0], fontsize=10)
m.drawmeridians(np.arange(0., 361., 10.), labels=[0, 0, 0, 1], fontsize=10)

# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()

# Add Colorbar
cbar = m.colorbar(cs, location='bottom', pad="10%")
cbar.set_label(Z500_units)
コード例 #50
0
totp = fh.variables['totp'][:] # Total precipitations

totp_units = fh.variables['totp'].units

fh.close()

map = Basemap(projection='merc',llcrnrlon=20.,llcrnrlat=-20.,urcrnrlon=60.,urcrnrlat=30.,resolution='i')

map.drawcoastlines()
map.drawcountries()
map.drawlsmask(land_color='Linen', ocean_color='#CCFFFF') # can use HTML names or codes for colors

parallels = np.arange(-20,30,5.) # make latitude lines ever 5 degrees from 30N-20S
meridians = np.arange(20,60,5.) # make longitude lines every 5 degrees from 20E to 60E
map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)

lons,lats= np.meshgrid(lon,lat)
x,y = map(lons,lats)

cs = map.pcolor(x,y,np.squeeze(totp))

cbar = map.colorbar(cs, location='bottom', pad="10%")
cbar.set_label(totp_units)

plt.title('Total Precipitations mean per year')

plt.show()
#plt.savefig('totp.png')

コード例 #51
0
            projection='merc',
            lon_0=lon_0,
            lat_0=lat_0,
            llcrnrlon=lonLims[0],
            llcrnrlat=latLims[0],
            urcrnrlon=lonLims[1],
            urcrnrlat=latLims[1],
            resolution='i')
levels = np.linspace(-.0005, .0005, 9)
#levels = 20
xi, yi = m(*np.meshgrid(lon_reg, lat_reg))
#lon_casts, lat_casts = m(lons[idx], lats[idx])
#c = m.contourf(xi, yi, Nmap, levels, cmap=plt.cm.RdBu_r, extend='both')
c = m.pcolor(xi,
             yi,
             Nmap,
             cmap=plt.cm.RdBu_r,
             vmin=levels.min(),
             vmax=levels.max())
x, y = m(*np.meshgrid(lon, lat))
cc = m.contour(x, y, -Zbathy, [100, 500, 1000, 4000], colors='grey')
m.fillcontinents(color='tan')

m.drawparallels([40, 45, 50, 55, 60],
                labels=[1, 0, 0, 0],
                fontsize=12,
                fontweight='normal')
m.drawmeridians([-60, -55, -50, -45],
                labels=[0, 0, 0, 1],
                fontsize=12,
                fontweight='normal')
#plt.title(r'Trends in N $\rm (s^{-1}) yr^{-1}$')
コード例 #52
0
            urcrnrlon=350,
            resolution='l',
            ax=ax1)
m.drawcoastlines(linewidth=1.25, color='#444444')
m.drawmeridians(np.arange(0, 360, 10),
                labels=[0, 0, 0, 1],
                linewidth=1,
                color='gray')
m.drawparallels(np.arange(0, 90, 10),
                labels=[1, 0, 0, 0],
                linewidth=1,
                color='gray')
x, y = np.meshgrid(lons_era, lats_era)
x1, y1 = m(x, y)
m.contourf(x1, y1, decade_slopes_era, temp_levs, cmap="bwr", extend="both")
m.pcolor(x1, y1, pvals_sig_era, hatch='.', alpha=0., zorder=10)
ax1.text(0,
         1.04,
         'a',
         verticalalignment='bottom',
         horizontalalignment='right',
         transform=ax1.transAxes,
         color='k',
         weight='bold')
ax1.set_title('ERA-Interim', weight="bold")

m = Basemap(projection='mill',
            llcrnrlat=30,
            urcrnrlat=70,
            llcrnrlon=280,
            urcrnrlon=350,
コード例 #53
0
ファイル: sst_test.py プロジェクト: Thpffcj/Python-Learning
lats = fh.variables["lat"][:]

sst = fh.variables["sst"][1974]
sst_units = fh.variables["sst"].units

fh.close()

lon_0 = lons.mean()
lat_0 = lats.mean()

m = Basemap(projection='ortho', lat_0=45, lon_0=-100, resolution='l')

lon, lat = np.meshgrid(lons, lats)
xi, yi = m(lon, lat)

cs = m.pcolor(xi, yi, np.squeeze(sst))

# Add Grid Lines
m.drawparallels(np.arange(-90., 90., 10.), labels=[1, 0, 0, 0], fontsize=10)
m.drawmeridians(np.arange(0., 360., 10.), labels=[0, 0, 0, 1], fontsize=10)

# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()

# Add Colorbar
cbar = m.colorbar(cs, location='bottom', pad="10%")
cbar.set_label("温度(ºC)", FontProperties=plot_para())

# Add Title
コード例 #54
0
                labels=[0, 0, 0, 0],
                fmt='%d',
                fontsize=18,
                zorder=map_order + 5)
m.drawparallels([18, 50],
                labels=[0, 0, 0, 0],
                fmt='%d',
                fontsize=18,
                zorder=map_order + 5)

# NOTE: this use of pcolor is incorrect - lats/lons should be the corners, not the actual location
u, v, mag, lats, lons, mon = get_vel(0)
im1 = m.pcolor(lons,
               lats,
               mag,
               vmin=0,
               vmax=.1,
               cmap='Oranges',
               zorder=map_order)
im2 = m.quiver(lons[::afreq],
               lats[::afreq],
               u[::afreq, ::afreq],
               v[::afreq, ::afreq],
               zorder=map_order + 2)


#plt.show()
# ANIMATION
def updatefig(i):
    global im1, im2, tx
    print i
コード例 #55
0
            llcrnrlat=-45.0,
            llcrnrlon=110.0,
            urcrnrlat=-5.0,
            urcrnrlon=160.0)  #define basemap as around Australia
m.drawcoastlines()
m.drawparallels(np.array([-45, -35, -25, -15, -5]),
                labels=[1, 0, 0, 0],
                fontsize=6)
m.drawmeridians(np.array([110, 120, 130, 140, 150, 160]),
                labels=[0, 0, 0, 1],
                fontsize=6)
xi, yi = m(lons, lats)
acorrdjf = np.ma.masked_invalid(acorrdjf)
ass_djf = np.ma.masked_invalid(ass_djf)
print np.ma.max(acorrdjf), np.ma.min(acorrdjf)
mymap = m.pcolor(xi, yi, acorrdjf, norm=norm, cmap=plt.cm.bwr)
ss = m.pcolor(xi, yi, ass_djf, hatch='...', norm=norm,
              cmap=plt.cm.bwr)  #plot ss ontop of correlations
cb = m.colorbar(mymap, "right", size="5%", pad="2%", ticks=v)
for label in cb.ax.yaxis.get_ticklabels()[1::2]:
    label.set_visible(False)
plt.title('DJF', fontsize=12)
cb.ax.tick_params(labelsize=6)
cb.set_label('Corr(AWAP, NINO3.4)', fontsize=8)

#plot DJF era
plt.subplot(2, 3, 3)
m = Basemap(projection='cyl',
            llcrnrlat=-45.0,
            llcrnrlon=110.0,
            urcrnrlat=-5.0,
コード例 #56
0
# Set the box borders in latitudes and langitudes
lats = [90, 60, 30, 0, -30, -60, -90]
lons = [-180, -120, -60, 0, 60, 120, 180]
# fill in some data for the boxes
data = np.array([[1, 0, 1, 0, 1, 0], [1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2],
                 [3, 3, 3, 3, 3, 3], [4, 2, 4, 2, 4, 2], [4, 4, 4, 4, 4, 4]])

# data mask, 1 means that data is masked i.e. not plotted
msk = np.array([[0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 1, 0], [1, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0]],
               dtype=bool)

data_masked = np.ma.array(data, mask=msk)

# List of possible map projections:
#   http://matplotlib.org/basemap/users/mapsetup.html
m = Basemap(projection='robin', lon_0=0)
X, Y = m(*np.meshgrid(lons, lats))
C = data_masked

# list of colormaps:
# http://matplotlib.org/examples/color/colormaps_reference.html
image1 = m.pcolor(X, Y, C, cmap=plt.get_cmap('viridis'), zorder=2)
m.drawcoastlines(zorder=3)
plt.title('My global data')

plt.savefig('figure4.png', dpi=150)

# About zorder:
# Larger value puts stuff on top of others.
コード例 #57
0
        bm.drawmeridians(numpy.arange(X.min(), X.max(), dlon), \
        labels=[0,0,0,1], fontsize=12, linewidth=1, rotation=45)#,labelstyle='+/-')
        bm.drawparallels(numpy.arange(Y.min() + dlat, Y.max() + dlat, dlat), \
        labels=[1,0,0,0], fontsize=12, linewidth=1)#,labelstyle='+/-')
        bm.drawcoastlines(linewidth=1.5)
        #bm.fillcontinents(color='coral')
        bm.drawmapboundary()
        #bm.bluemarble()
        bm.drawcountries(linewidth=1.5)
        #bm.drawstates(linewidth=1)

        X, Y = bm(X, Y)

        cf = bm.pcolor(X,
                       Y,
                       Z,
                       cmap=pylab.cm.gist_earth,
                       vmin=-1000,
                       vmax=1000)

        cb = pylab.colorbar(orientation='vertical', shrink=0.84)

        for t in cb.ax.get_yticklabels():

            t.set_fontsize(14)

        zoom_x, zoom_y = bm(zoom_x, zoom_y)

        bm.plot(zoom_x, zoom_y, '-r', linewidth=3)

        pylab.savefig(prefix + ".png", fmt="png")
コード例 #58
0
m = Basemap(projection='cyl',
            llcrnrlat=-45.0,
            llcrnrlon=110.0,
            urcrnrlat=-5.0,
            urcrnrlon=160.0)  #define basemap as around Australia
m.drawcoastlines()
m.drawparallels(np.array([-45, -35, -25, -15, -5]),
                labels=[1, 0, 0, 0],
                fontsize=8)
m.drawmeridians(np.array([110, 120, 130, 140, 150, 160]),
                labels=[0, 0, 0, 1],
                fontsize=8)
xi, yi = m(lons, lats)
d_txx_e = np.ma.masked_invalid(d_txx_e)
ss_txx_e = np.ma.masked_invalid(ss_txx_e)
mymap = m.pcolor(xi, yi, d_txx_e, norm=norm, cmap=plt.cm.bwr)
ss = m.pcolor(xi, yi, ss_txx_e, hatch='...', norm=norm, cmap='bwr')
plt.title('TXx during El Nino', fontsize=12)
ax.text(0.99,
        0.01,
        'RMSE = %s, CORR = %s' % (rmse_txx_e, sc_xe),
        transform=ax.transAxes,
        horizontalalignment='right',
        verticalalignment='bottom',
        fontsize=8,
        fontweight='bold')

#plot TNn during El Nino
ax = plt.subplot(221)
m = Basemap(projection='cyl',
            llcrnrlat=-45.0,
コード例 #59
0
def latview(var, tindex, latitude, gridid, filename=None, \
            cmin=None, cmax=None, clev=None, fill=False, \
            contour=False, d=4, lonrange=None, hrange=None,\
            fts=None, title=None, map=False, \
            pal=None, clb=True, outfile=None):
    """
    latview(var, tindex, latitude, gridid, {optional switch})

    optional switch:
      - filename         if defined, load the variable from file
      - cmin             set color minimum limit
      - cmax             set color maximum limit
      - clev             set the number of color step
      - fill             use contourf instead of pcolor
      - contour          overlay contour (request fill=True)
      - d                contour density (default d=4) 
      - lonrange         longitude range
      - hrange           h range
      - fts              set font size (default: 12)
      - title            add title to the plot
      - map              if True, draw a map showing islice location
      - pal              set color map (default: cm.jet)
      - clb              add colorbar (defaul: True)
      - outfile          if defined, write figure to file

    plot a constante-latitudinal slice of variable var. If filename 
    is provided, var must be a string and the variable will be load 
    from the file.
    grid can be a grid object or a gridid. In the later case, the grid
    object correponding to the provided gridid will be loaded.
    """

    # get grid
    if type(gridid).__name__ == 'ROMS_Grid':
        grd = gridid
    else:
        grd = pycnal.grid.get_ROMS_grid(gridid)

    # get variable
    if filename == None:
        var = var
    else:
        data = pycnal.io.Dataset(filename)

        var = data.variables[var]

    Np, Mp, Lp = grd.vgrid.z_r[0, :].shape

    if tindex is not -1:
        assert len(var.shape) == 4, 'var must be 4D (time plus space).'
        K, N, M, L = var.shape
    else:
        assert len(var.shape) == 3, 'var must be 3D (no time dependency).'
        N, M, L = var.shape

    # determine where on the C-grid these variable lies
    if N == Np and M == Mp and L == Lp:
        Cpos = 'rho'
        lon = grd.hgrid.lon_vert
        lat = grd.hgrid.lat_vert
        mask = grd.hgrid.mask_rho

    if N == Np and M == Mp and L == Lp - 1:
        Cpos = 'u'
        lon = 0.5 * (grd.hgrid.lon_vert[:, :-1] + grd.hgrid.lon_vert[:, 1:])
        lat = 0.5 * (grd.hgrid.lat_vert[:, :-1] + grd.hgrid.lat_vert[:, 1:])
        mask = grd.hgrid.mask_u

    if N == Np and M == Mp - 1 and L == Lp:
        Cpos = 'v'
        lon = 0.5 * (grd.hgrid.lon_vert[:-1, :] + grd.hgrid.lon_vert[1:, :])
        lat = 0.5 * (grd.hgrid.lat_vert[:-1, :] + grd.hgrid.lat_vert[1:, :])
        mask = grd.hgrid.mask_v

    # get constante-lat slice
    if tindex == -1:
        var = var[:, :, :]
    else:
        var = var[tindex, :, :, :]

    if fill == True:
        latslice, zs, lons, lats, = pycnal.tools.latslice(
            var, latitude, grd, Cpos)
    else:
        latslice, zs, lons, lats, = pycnal.tools.latslice(var,
                                                          latitude,
                                                          grd,
                                                          Cpos,
                                                          vert=True)

    # plot
    if cmin is None:
        cmin = latslice.min()
    else:
        cmin = float(cmin)

    if cmax is None:
        cmax = latslice.max()
    else:
        cmax = float(cmax)

    if clev is None:
        clev = 100.
    else:
        clev = float(clev)

    dc = (cmax - cmin) / clev
    vc = np.arange(cmin, cmax + dc, dc)

    if pal is None:
        pal = cm.jet
    else:
        pal = pal

    if fts is None:
        fts = 12
    else:
        fts = fts

    #pal.set_over('w', 1.0)
    #pal.set_under('w', 1.0)
    #pal.set_bad('w', 1.0)

    pal_norm = colors.BoundaryNorm(vc, ncolors=256, clip=False)

    # clear figure
    #plt.clf()

    if map is True:
        # set axes for the main plot in order to keep space for the map
        if fts < 12:
            ax = None
        else:
            ax = plt.axes([0.15, 0.08, 0.8, 0.65])
    else:
        if fts < 12:
            ax = None
        else:
            ax = plt.axes([0.15, 0.1, 0.8, 0.8])

    if fill is True:
        cf = plt.contourf(lons,
                          zs,
                          latslice,
                          vc,
                          cmap=pal,
                          norm=pal_norm,
                          axes=ax)
    else:
        cf = plt.pcolor(lons, zs, latslice, cmap=pal, norm=pal_norm, axes=ax)

    if clb is True:
        clb = plt.colorbar(cf, fraction=0.075, format='%.2f')
        for t in clb.ax.get_yticklabels():
            t.set_fontsize(fts)

    if contour is True:
        if fill is not True:
            raise Warning(
                'Please run again with fill=True for overlay contour.')
        else:
            plt.contour(lons,
                        zs,
                        latslice,
                        vc[::d],
                        colors='k',
                        linewidths=0.5,
                        linestyles='solid',
                        axes=ax)

    if lonrange is not None:
        plt.xlim(lonrange)

    if hrange is not None:
        plt.ylim(hrange)

    if title is not None:
        if map is True:
            # move the title on the right
            xmin, xmax = ax.get_xlim()
            ymin, ymax = ax.get_ylim()
            xt = xmin - (xmax - xmin) / 9.
            yt = ymax + (ymax - ymin) / 7.
            plt.text(xt, yt, title, fontsize=fts + 4)
        else:
            plt.title(title, fontsize=fts + 4)

    plt.xlabel('Latitude', fontsize=fts)
    plt.ylabel('Depth', fontsize=fts)

    if map is True:
        # draw a map with constant-i slice location
        ax_map = plt.axes([0.4, 0.76, 0.2, 0.23])
        varm = np.ma.masked_where(mask[:, :] == 0, var[var.shape[0] - 1, :, :])
        lon_min = lon.min()
        lon_max = lon.max()
        lon_0 = (lon_min + lon_max) / 2.
        lat_min = lat.min()
        lat_max = lat.max()
        lat_0 = (lat_min + lat_max) / 2.
        map = Basemap(projection='merc', llcrnrlon=lon_min, llcrnrlat=lat_min, \
                 urcrnrlon=lon_max, urcrnrlat=lat_max, lat_0=lat_0, lon_0=lon_0, \
                 resolution='i', area_thresh=10.)
        x, y = list(map(lon, lat))
        if lonrange is None:
            xs, ys = list(map(lons[0, :], lats[0, :]))
        else:
            c1 = lats[0, :] >= lonrange[0]
            c2 = lats[0, :] <= lonrange[1]
            c = c1 & c2
            idx = np.where(c == True)
            xs, ys = list(map(lons[0, idx[0]], lats[0, idx[0]]))
        # fill land and draw coastlines
        map.drawcoastlines()
        map.fillcontinents(color='grey')
        #map.drawmapboundary()
        Basemap.pcolor(map, x, y, varm, axes=ax_map)
        Basemap.plot(map, xs, ys, 'k-', linewidth=3, axes=ax_map)

    if outfile is not None:
        if outfile.find('.png') != -1 or outfile.find(
                '.svg') != -1 or outfile.find('.eps') != -1:
            print('Write figure to file', outfile)
            plt.savefig(outfile,
                        dpi=200,
                        facecolor='w',
                        edgecolor='w',
                        orientation='portrait')
        else:
            print(
                'Unrecognized file extension. Please use .png, .svg or .eps file extension.'
            )

    return
コード例 #60
0
import matplotlib.pyplot as plt 
from mpl_toolkits.basemap import Basemap

# Get some parameters for the Stereographic Projection
lon_0 = lons.mean()
lat_0 = lats.mean()

m = Basemap(width=5000000,height=3500000,
            resolution='l',projection='stere',\
            lat_ts=40,lat_0=lat_0,lon_0=lon_0)

lon, lat = np.meshgrid(lons, lats)
xi, yi = m(lon, lat)

# Plot Data
cs = m.pcolor(xi,yi,np.squeeze(tn))

# Add Grid Lines
m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10)
m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10)

# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()

# Add Colorbar
cbar = m.colorbar(cs, location='bottom', pad="10%")
cbar.set_label(tn_units)

# Add Title