Example #1
0
def plot_data(data,lon_data, lat_data, periodname, AODcatname,maptype,cmapname,minv=0,maxv=0,folder=""):
    fig = plt.figure()
    #ax = fig.add_axes([0.1,0.1,0.8,0.8])

    m = Basemap(llcrnrlon=19,llcrnrlat=34,urcrnrlon=29,urcrnrlat=42,
                resolution='h',projection='cass',lon_0=24,lat_0=38)

    nx = int((m.xmax-m.xmin)/1000.)+1
    ny = int((m.ymax-m.ymin)/1000.)+1
    topodat = m.transform_scalar(data,lon_data,lat_data,nx,ny)
    
    if minv<>0 or maxv<>0 :
        im = m.imshow(topodat,cmap=plt.get_cmap(cmapname),vmin=minv,vmax=maxv)
    else:
        im = m.imshow(topodat,cmap=plt.get_cmap(cmapname))
 

    m.drawcoastlines()
    m.drawmapboundary()
    m.drawcountries()
    m.drawparallels(np.arange(35,42.,1.), labels=[1,0,0,1])
    m.drawmeridians(np.arange(-20.,29.,1.), labels=[1,0,0,1])
    cb = m.colorbar(im,"right", size="5%", pad='2%')
    title=maptype+" AOD "+AODcatname+" "+periodname+" 2007-2014"
    plt.title(title)
    pylab.savefig(folder+maptype+"AOD"+AODcatname+"_"+periodname + ".png")
Example #2
0
def make_stations(network,latmin,latmax,lonmin,lonmax,dlat,dlon,plot=True,**kwargs):
    head = kwargs.get('head','RM')
    elev = kwargs.get('elev',0)
    dep  = kwargs.get('dep',0)

    lats = np.arange(latmin,latmax+dlat,dlat)
    lons = np.arange(lonmin,lonmax+dlon,dlon)
    lats_pts,lons_pts = np.meshgrid(lats,lons)

    if plot:
        m = Basemap(projection='hammer',lon_0=0,resolution='l')
        m.drawcoastlines()
        m.drawmeridians(np.arange(0,351,10))
        m.drawparallels(np.arange(-80,81,10))
        lons_pts2,lats_pts2 = m(lons_pts,lats_pts)
        m.scatter(lons_pts2,lats_pts2)
        plt.show()

    f = open('STATIONS','w')
    print 'total number of stations : ',len(lats_pts)
    st = 1
    for i in range(0,len(lats)):
        for j in range(0,len(lons)):
            f.write('{}{:04d} {} {:5.2f} {:5.2f} {:5.2f} {:5.2f}'.format(head,st,network,lats[i],lons[j],elev,dep)+'\n')
            st += 1
Example #3
0
File: pnts.py Project: jdbowman/sim
def plot_pnts(source, ra_0, dec_0, FOV='fullsky', grid_size=15.):
    ra, dec = np.genfromtxt(source, usecols=(0, 1), unpack=True)
    ra *= 15.
    sky = Basemap(projection='ortho', lon_0=-ra_0, lat_0=dec_0, celestial=True)
    if FOV == 'fullsky':
        sky.drawmeridians(np.arange(0., 360., grid_size))
        sky.drawparallels(np.arange(90, -90, -grid_size))
        sky.drawmapboundary(fill_color='White')
        catx, caty = sky(ra, dec)
        sky.scatter(catx, caty, 3, marker='o', color='Black')
    elif isinstance(FOV, float):
        format_label = lambda deg: '{0:2.0f}h{1:2.0f}m'\
            .format(np.floor(deg / 15.), np.remainder(deg, 15.) * 60. / 15.)
        cnreq = np.array([[ra_0 + FOV / 2., dec_0 - FOV / 2.],
                         [ra_0 - FOV / 2., dec_0 + FOV / 2.]])
        cnrxy = np.array(sky(cnreq[:, 0], cnreq[:, 1])).T
        cenxy = np.array(sky(ra_0, dec_0))
        m = Basemap(projection='ortho', lon_0=-ra_0, lat_0=dec_0,
                    celestial=True, llcrnrx=cnrxy[0, 0]-cenxy[0],
                    llcrnry=cnrxy[0, 1]-cenxy[1], urcrnrx=cnrxy[1, 0]-cenxy[0],
                    urcrnry=cnrxy[1, 1]-cenxy[1])
        m.drawmeridians(np.arange(cnreq[0, 0], cnreq[1, 0], -grid_size),
                        labels=[0, 0, 0, 1], fmt=format_label)
        m.drawparallels(np.arange(cnreq[0, 1], cnreq[1, 1], grid_size),
                        labels=[1, 0, 0, 0])
        m.drawmapboundary(fill_color='White')
        catx, caty = m(ra, dec)
        m.scatter(catx, caty, 3, marker='o', color='Black')
Example #4
0
def example_1():
    
    orig_file  = '/tmp/comp-tempo/20101206-EUR-L2P_GHRSST-SSTsubskin-AVHRR_METOP_A-eumetsat_sstmgr_metop02_20101206_000403-v01.7-fv01.0.nc'
    
    orig_dset = Dataset(orig_file, 'a')
    
    o_lat = orig_dset.variables['lat'][:].ravel()
    o_lon = orig_dset.variables['lon'][:].ravel()
    
    print(np.mean(o_lon))
    
    
    
    # lon_0 is the central longitude of the projection.
    # resolution = 'l' means use low resolution coastlines.
    # optional parameter 'satellite_height' may be used to
    # specify height of orbit above earth (default 35,786 km).
    m = Basemap(projection='geos',lon_0=133,resolution='l')
    m.drawcoastlines()
    m.fillcontinents(color='coral',lake_color='aqua')
    # draw parallels and meridians.
    m.drawparallels(np.arange(-90.,120.,30.))
    m.drawmeridians(np.arange(0.,420.,60.))
    m.drawmapboundary(fill_color='aqua')
    
    x, y = m(o_lat[0:100] , o_lon[0:100])
    
    #m.plot(x, y)
    
    plt.title("Full Disk Geostationary Projection")
    #plt.savefig('geos_full.png')
    plt.show()
    def Map(self):
        m = Basemap(projection='cyl',  # stere, tmerc, lcc
                    lat_0=39.828127, lon_0=-98.579404,
                    urcrnrlon=-62.208289, urcrnrlat=51.342619,
                    llcrnrlon=-128.936426, llcrnrlat=19.06875)

        m.drawcoastlines()  # draw coastlines
        m.drawmapboundary()  # draw a line around the map region
        m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])  # draw parallels

        m.drawmeridians(np.arange(0., 420., 60.), labels=[0, 0, 0, 1])  # draw meridians

        m.drawstates()
        m.drawcountries()

        lon = list()
        lon.append(-80.633333)
        lon.append(-74.364684)
        lon.append(-75.387778)
        lon.append(-84.253333)

        lat = list()
        lat.append(28.116667)
        lat.append(40.715622)
        lat.append(40.043889)
        lat.append(30.455)

        m.scatter(lon, lat, latlon=True, c=np.random.rand(3))
        #m.pcolor(lon, lat, latlon=True)
        plt.title('United States Fair Market Rent')  # add a title
        plt.show()
Example #6
0
def ResearchRegion_surface():
    """
    在地图上画出柱表面混合比图
    :return:
    """

    fig = plt.figure(figsize=(11, 8), facecolor="white")
    # data = np.loadtxt('seasonAvr_data/SurfaceMixingRatio/1_seasonAvr.txt')
    data = np.loadtxt("allYearAvr_data/SurfaceMixingRatio/allYearAvr.txt")
    arr = np.zeros((180, 360))
    for i in range(180):
        arr[i, :] = data[179 - i, :]

    longitude = np.loadtxt("lonlat_data/longitude.txt")
    latitude = np.loadtxt("lonlat_data/latitude.txt")

    m = Basemap(llcrnrlon=70, llcrnrlat=15, urcrnrlon=138, urcrnrlat=55, projection="mill", resolution="h")
    m.drawparallels(np.arange(5.5, 90.5, 1.0), color="w", linewidth=0.5, dashes=[1, 1], labels=[0, 0, 0, 0])
    m.drawmeridians(np.arange(60.5, 181.5, 1.0), color="w", linewidth=0.5, dashes=[1, 1], labels=[0, 0, 0, 0])
    m.drawmapboundary(fill_color="0.3")
    m.readshapefile("shp/CHINA", "CHINA", drawbounds=1, color="black")

    topo = maskoceans(longitude, latitude, arr)
    im = m.pcolormesh(longitude, latitude, topo, shading="flat", cmap=plt.cm.jet, latlon=True, vmin=0, vmax=500)
    m.drawlsmask(ocean_color="w", lsmask=0)

    cbar = m.colorbar()
    cbar.ax.set_ylabel("SurfaceMixingRatio", color="black", fontsize="14", rotation=90)
    plt.show()
Example #7
0
def individual_ocean_map(eof = '1', phase = 'lanina', showplot = True):
    ### This function combines several others to make a map

    patterns, lats, lons, lams, pcs = combine_regions(phase = phase)
    data, lns, lts = create_full_map_individual(patterns, lats, lons, eof = eof)
    from numpy import linspace
    fig = plt.figure()
    ax = fig.add_subplot(111)
    m = Basemap(ax = ax, projection = 'robin', lon_0 = 180, resolution = 'i')
    m.drawmapboundary(fill_color='aqua')
    m.drawcoastlines(linewidth = 0.25)
    m.drawcountries()
    m.fillcontinents(color='green',lake_color='aqua')
    parallels = np.linspace(m.llcrnrlat, m.urcrnrlat, 4)
    meridians = np.linspace(m.llcrnrlon, m.urcrnrlon, 4)
    m.drawparallels(parallels, linewidth = 1, labels = [0,0,0,0])
    m.drawmeridians(meridians, linewidth = 1, labels = [0,0,0,0])

    cmap = cm.RdBu_r

    im = m.pcolormesh(lns,lts,data, vmin = data[~isnan(data)].min(), \
    vmax=data[~isnan(data)].max(), cmap = cmap, latlon=True)
    cb = m.colorbar(im,'bottom', size="5%", pad="2%")
    if showplot:
        plt.show()
        return
    return fig, ax, m
Example #8
0
def map_interiorAK(
    width=1800000,
    height=1200000,
    water='lightskyblue',
    earth='snow',
    resolution='i'):
    """
    Albers Equal Area map of interior Alaska, with some overridable presets.
    """
    bmap = Basemap(
        width=width,
        height=height,
        resolution=resolution,
        projection='aea',
        lat_1=55., lat_2=75., lat_0=65., lon_0=-150.)
    bmap.drawcoastlines()
    bmap.drawrivers(color=water)
    bmap.drawcountries()
    bmap.fillcontinents(lake_color=water, color=earth)
    # labels = [left,right,top,bottom]
    bmap.drawmeridians(
        np.arange(-180, 180, 10), labels=[False, False, False, 1])
    bmap.drawparallels(
        np.arange(0, 80, 5), labels=[1, 1, False, False])
    bmap.drawmapboundary(fill_color=water)
    return bmap
Example #9
0
def bb_map(lons, lats, projection='merc', resolution='i', drawparallels=True, drawmeridians=True, ax=plt.gca()):
	"""
	USAGE
	-----
	m = bb_map(lons, lats, **kwargs)

	Returns a Basemap instance with lon,lat bounding limits
	inferred from the input arrays `lons`,`lats`.
	Coastlines, countries, states, parallels and meridians
	are drawn, and continents are filled.
	"""
	lons,lats = map(np.asanyarray, (lons,lats))
	lonmin,lonmax = lons.min(),lons.max()
	latmin,latmax = lats.min(),lats.max()

	m = Basemap(llcrnrlon=lonmin,
				urcrnrlon=lonmax,
				llcrnrlat=latmin,
				urcrnrlat=latmax,
				projection=projection,
				resolution=resolution,
				ax=ax)

	plt.ioff() # Avoid showing the figure.
	m.fillcontinents(color='0.9', zorder=9)
	m.drawcoastlines(zorder=10)
	m.drawstates(zorder=10)
	m.drawcountries(linewidth=2.0, zorder=10)
	m.drawmapboundary(zorder=9999)
	if drawmeridians:
		m.drawmeridians(np.arange(np.floor(lonmin), np.ceil(lonmax), 1), linewidth=0.15, labels=[1, 0, 1, 0], zorder=12)
	if drawparallels:
		m.drawparallels(np.arange(np.floor(latmin), np.ceil(latmax), 1), linewidth=0.15, labels=[1, 0, 0, 0], zorder=12)
	plt.ion()
	return m
Example #10
0
def sstMap(nipaPhase, phase = 'allyears', field = 'sst', fig = None, ax = None, monte = False):
	from numpy import linspace
	if fig == None:
		fig = plt.figure()
		ax = fig.add_subplot(111)
	m = Basemap(ax = ax, projection = 'robin', lon_0 = 270, resolution = 'i')
	m.drawmapboundary(fill_color='aqua')
	m.drawcoastlines(linewidth = 0.25)
	m.drawcountries()
	m.fillcontinents(color='green',lake_color='aqua')
	parallels = np.linspace(m.llcrnrlat, m.urcrnrlat, 4)
	meridians = np.linspace(m.llcrnrlon, m.urcrnrlon, 4)
	m.drawparallels(parallels, linewidth = 1, labels = [0,0,0,0])
	m.drawmeridians(meridians, linewidth = 1, labels = [0,0,0,0])

	lons = nipaPhase.lon[field]
	lats = nipaPhase.lat[field]
	if monte:
		data = nipaPhase.monte_grid[phase]
		levels = linspace(0, data.max(), data.max())
		cmap = cm.Reds
	else:
		data = nipaPhase.corr_grid[field][phase]
		levels = linspace(-0.8,0.8,9)
		cmap = cm.RdBu
	lons, lats = np.meshgrid(lons,lats)
	im1 = m.pcolormesh(lons,lats,data, vmin = np.min(levels), \
		vmax=np.max(levels), cmap = cmap, latlon=True)
	cb = m.colorbar(im1,'bottom', size="5%", pad="2%")
	ax.set_title('%s, %s' % (phase, field))
	return fig, ax, m
def regional_subplot(lons, lats, data, extreme, cent_lat, cent_lon, min_lon, max_lon, min_lat, max_lat, parallels, meridians, cmap, vmin, title,
            plot_number, coastline_color, background_color):

    ax = plt.subplot(plot_number)
    ax.set_axis_bgcolor(background_color)

    ETA_m = haversine_distance((min_lat, cent_lon), (max_lat, cent_lon), True)
    XI_m = haversine_distance((min_lat, min_lon), (max_lat, max_lon),True)
    map = Basemap(height=ETA_m, width=XI_m,
            resolution='l', area_thresh=1000., projection='omerc', \
            lon_0=cent_lon, lat_0=cent_lat, lon_2=cent_lon, lat_2=min_lat, lon_1=cent_lon, lat_1=max_lat)
    map.drawcoastlines(color=coastline_color)

    # labels = [left,right,top,bottom]
    map.drawparallels(parallels, labels=[True, False, False, False])
    map.drawmeridians(meridians, labels=[False, False, False, True])

    cs = map.contourf(lons, lats, data, levels=numpy.linspace((-1 * extreme), extreme, 101), cmap=cmap,
                      vmin=vmin, vmax=extreme, extend='both', latlon=True)
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="2%", pad=0.05)
    plt.colorbar(cs, cax=cax, ticks=[-1 * extreme, 0, extreme], extend='both')
    ax.set_title(title)

    return ax
def plot_map(lons, lats, c, legend_label, projection='mill',
             llcrnrlat=-80, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='i'):
    
    ''' Optional Arguments: projection - map projection, default set as 'mill'
                            llcrnrlat - lower left corner latitude value, default is -80
                            urcrnrlat - upper right corner latitude value, default is 90
                            llcrnrlon - lower left corner longitude value, default is -180
                            urcrnrlon - upper right corner longitude value, default is 180
                            resolution - the resolution of the plot, default is 'i'
                            
        Required Arguments: lons - list of longitude values to be plotted
                            lats - list of latitude values to be plotted
                            c - the color of the points to be plotted
                            legend_label - how this set of points will be labeled on the legend
                            
        Returns:            m - a basemap object defined by input bounds with input points included '''
    
    # Creates a basic plot of a series of lat,lon points over a defined region
    m = Basemap(projection=projection, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,
                llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution=resolution)
    m.drawcoastlines()
    m.drawmapboundary()
    m.drawcountries()
    m.etopo()
    m.drawmeridians(np.arange(llcrnrlon, urcrnrlon, 5), labels=[0,0,0,1], fontsize=10)
    m.drawparallels(np.arange(llcrnrlat, urcrnrlat, 5), labels=[1,0,0,0], fontsize=10)
    x,y = m(lons, lats)
    m.scatter(x, y, color=c, label=legend_label, marker='o', edgecolor='none', s=10)
    return m
Example #13
0
def nepal_basemap(prams = nepal_ETAS_prams, fnum=0, map_res='i', **kwargs):
	# hours_after: upper time limit for aftershocks to plot.
	prams.update(kwargs)
	#
	lons_nepal = [83., 87.]
	lats_nepal = [26., 30.]
	
	todt=prams.get('todt', None)
	catlen=prams.get('catlen', 5.*365.)
	lons=prams['lons']
	lats=prams['lats']
	mc = prams['mc']
	#
	if todt==None: todt = dtm.datetime.now(pytz.timezone('UTC'))
	dt0 = todt - dtm.timedelta(days=catlen)
	#
	plt.figure(fnum)
	plt.clf()
	ax1=plt.gca()
	cntr = [.5*(lons[0]+lons[1]), .5*(lats[0]+lats[1])]
	#
	cm=Basemap(llcrnrlon=lons_nepal[0], llcrnrlat=lats_nepal[0], urcrnrlon=lons_nepal[1], urcrnrlat=lats_nepal[1], resolution=map_res, projection='cyl', lon_0=cntr[0], lat_0=cntr[1])
	cm.drawcoastlines(color='gray', zorder=1)
	cm.drawcountries(color='gray', zorder=1)
	cm.drawstates(color='gray', zorder=1)
	cm.drawrivers(color='gray', zorder=1)
	cm.fillcontinents(color='beige', zorder=0)
	#
	cm.drawmeridians(list(range(int(lons[0]), int(lons[1]))), color='k', labels=[0,0,1,1])
	cm.drawparallels(list(range(int(lats[0]), int(lats[1]))), color='k', labels=[1, 1, 0, 0])
	#
	return cm
def map_vis(data,title=[],vmin=None,vmax=None,barlabel=None,cmap=None,outputdir=None):
    # print("visualizing : "+title)
    if cmap==None:
        cmap=cm.jet
    if len(data.shape)>2:
        plotdata=data[0,:,:]
    else:
        plotdata=data
    plt.clf()
    # plt.figure(figsize=(3,3),dpi=200)
    ny,nx=plotdata.shape
    geo=[35,43,-113,-101]
    if experiment=="conus":geo=[25,52.7,-124.7,-67]
    m = Basemap(projection='cyl',llcrnrlat=geo[0],urcrnrlat=geo[1],\
                llcrnrlon=geo[2],urcrnrlon=geo[3],resolution="i")
    
    mapimg=m.imshow(plotdata,vmin=vmin,vmax=vmax,cmap=cmap)
    if experiment=="conus":
        m.drawparallels(np.arange(25,55,5.),labels=[1,0,0,0],dashes=[1,4])
        m.drawmeridians(np.arange(-120,-65,10.),labels=[0,0,0,1],dashes=[1,4])
        m.drawstates(linewidth=0.5)
        m.drawcountries(linewidth=0.5)
        m.drawcoastlines(linewidth=0.5)
    else:
        m.drawparallels(np.arange(36,43,2.),labels=[1,0,0,0],dashes=[1,4])
        m.drawmeridians(np.arange(-112,-103,4.),labels=[0,0,0,1],dashes=[1,4])
        m.drawstates(linewidth=1.5)
    cbar=m.colorbar()
    if barlabel:
        cbar.set_label(barlabel)
    plt.title(" ".join(title))
    if outputdir:
        plt.savefig(outputdir+"_".join(title)+'_map.png')
    else:
        plt.savefig("_".join(title)+'_map.png')
Example #15
0
def mapper(image):

	fig = plt.figure()
	
	cmap = mpc.ListedColormap(palettable.colorbrewer.diverging.PiYG_5.mpl_colors)
	# cmap.set_bad('grey',1.)

	# ax = fig.add_subplot(1)
	plt.plot()
	plt.title("a. ((maxNDVI/mm AcuPrecip)/year)", loc= 'left')

	#set the spatial cordinates of the grid, mask the ocean and draw coastlines
	map = Basemap(llcrnrlon=112.0,llcrnrlat=-44.5,urcrnrlon=156.25,urcrnrlat=-10, resolution = 'h', epsg=4326)
	map.drawmapboundary(fill_color='grey')
	map.fillcontinents(color= 'none', lake_color='white')
	map.drawlsmask(land_color='none', )
	map.drawcoastlines()

	map.imshow(np.flipud(image), cmap=cmap, vmin=-0.006, vmax=0.009,)
	# cb = plt.colorbar()

	#Tweaking the colorbar so the the ticks allign with the grid.  
	cb = map.colorbar()#ticks= [-0.01, -0.0075, -0.0050, -0.00250, 0.0000, 0.0025, 0.0050, 0.0075, 0.010, 0.0125])
	tick_locator = ticker.MaxNLocator(nbins=5)
	cb.locator = tick_locator
	cb.update_ticks()

	#add in the grid
	map.drawparallels(np.arange(-50, -10, 10),labels=[1,0,0,0], dashes=[1,2])#color= 'none')
	map.drawmeridians(np.arange(110, 156.25, 10),labels=[0,0,0,1], dashes=[1,2])

	plt.show()
Example #16
0
    def drawNPole(self):
        #No es muy ortodoxo dibujar dentro de la clase
        my_map = Basemap(projection='npstere',boundinglat=50,lon_0=270,resolution='h', round=True)    
        my_map.drawcoastlines()
        my_map.drawcountries()
        my_map.fillcontinents(color='coral')
        my_map.drawmapboundary()
    
        #print "tamano:", len(self)
        for measure in self:
            x,y = my_map(measure.getLon(), measure.getLat())
            print  measure.getLat(), measure.getLon(), measure.getSic()
            color = 'go'    
            #print "color->", measure.getSic()        
            if measure.getSic()>0 and measure.getSic()<=0.2:
                color = 'go'    
            elif measure.getSic()>0.2 and measure.getSic()<=0.5:
                color = 'yo'    
            else:
                color = 'ro'    
    
            
            my_map.plot(y, x, color, markersize=12)

        my_map.drawmeridians(np.arange(0, 360, 30))
        my_map.drawparallels(np.arange(-90, 90, 30))
        #m.hexbin(x1,y1, C=sic[beam],gridsize=len(sic[beam]),cmap=plt.cm.jet)
    
    
        plt.gcf().set_size_inches(18,10)
        plt.show()    
Example #17
0
def plot_grid2D(lons, lats, tec_grid2D, datetime, title_label = ''):

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

	m = Basemap(llcrnrlon=-180,
	            llcrnrlat=-55,
	            urcrnrlon=180,
	            urcrnrlat=75,
	            projection='merc',
	            area_thresh=1000,
	            resolution='i')

	m.drawstates()
	m.drawcountries()
	m.drawcoastlines()

	parallels = np.arange(-90,90,20)
	m.drawparallels(parallels,labels=[True,False,False,True])
	meridians = np.arange(0,360,40)
	m.drawmeridians(meridians,labels=[True,False,False,True])

	m.scatter(LONS, LATS, c=tec_grid2D, latlon = True, linewidths=0, s=5)
	m.colorbar()

	plt.title('%s\n%s' % (title_label, datetime.isoformat(' ')))
def run(FILE_NAME):
    
    with h5py.File(FILE_NAME, mode='r') as f:

        name = '/Grid/IRprecipitation'
        data = f[name][:]
        units = f[name].attrs['units']
        _FillValue = f[name].attrs['_FillValue']
        data[data == _FillValue] = np.nan
        data = np.ma.masked_where(np.isnan(data), data)

        
        # Get the geolocation data
        latitude = f['/Grid/lat'][:]
        longitude = f['/Grid/lon'][:]

        
    m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=-180, urcrnrlon=180)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(-90, 91, 45))
    m.drawmeridians(np.arange(-180, 180, 45), labels=[True,False,False,True])
    m.pcolormesh(longitude, latitude, data.T, latlon=True)
    cb = m.colorbar()    
    cb.set_label(units)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, name))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Example #19
0
def plot_hmap_ortho(h, cmap='jet', mode='log', mx=None, drng=None, 
        res=0.25, verbose=False):
    m = Basemap(projection='ortho',lat_0=90,lon_0=180,rsphere=1.)
    if verbose:
        print 'SCHEME:', h.scheme()
        print 'NSIDE:', h.nside()
    lons,lats,x,y = m.makegrid(360/res,180/res, returnxy=True)
    lons = 360 - lons
    lats *= a.img.deg2rad; lons *= a.img.deg2rad
    y,x,z = a.coord.radec2eq(n.array([lons.flatten(), lats.flatten()]))
    ax,ay,az = a.coord.latlong2xyz(n.array([0,0]))
    data = h[x,y,z]
    data.shape = lats.shape
    data /= h[0,0,1]
    #data = data**2 # only if a voltage beam
    data = data_mode(data, mode)
    m.drawmapboundary()
    m.drawmeridians(n.arange(0, 360, 30))
    m.drawparallels(n.arange(0, 90, 10))
    if mx is None: mx = data.max()
    if drng is None:
        mn = data.min()
    #    if min < (max - 10): min = max-10
    else: mn = mx - drng
    step = (mx - mn) / 10
    levels = n.arange(mn-step, mx+step, step)
    return m.imshow(data, vmax=mx, vmin=mn, cmap=cmap)
Example #20
0
def vec_plot_south_america(lons, lats, sa_mask, data_x, data_y, ax=None):
    if ax == None:
	ax = plt.gca()
    #print(sa_mask.shape)
    #print(data_x.shape)
    #print(data_y.shape)
    #data_x_masked = np.ma.array(data_x, mask=sa_mask)
    #data_y_masked = np.ma.array(data_y, mask=sa_mask)
    plot_lons, plot_x_data = extend_data(lons, lats, data_x)
    plot_lons, plot_y_data = extend_data(lons, lats, data_y)

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

    m = Basemap(ax=ax, projection='cyl', resolution='c', llcrnrlat=-60, urcrnrlat=15, llcrnrlon=-85, urcrnrlon=-32)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax, ax=ax)
    m.quiver(x, y, plot_x_data, plot_y_data, scale=40, ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-90.,-30.,10.), labels=[0, 0, 0, 1], fontsize=10, ax=ax)

    m.colorbar(location='right', pad='5%', ax=ax)
    plt.show()
Example #21
0
def vec_plot_polar(lons, lats, data_x, data_y, pole, ax=None):
    if ax == None:
	ax = plt.gca()
    plot_lons, plot_x_data = extend_data(lons, lats, data_x)
    plot_lons, plot_y_data = extend_data(lons, lats, data_y)

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

    if pole == 'N':
	m = Basemap(ax=ax, resolution='c',projection='stere',lat_0=90.,lon_0=0, width=12000000,height=8000000)
    elif pole == 'S':
	m = Basemap(ax=ax, resolution='c',projection='stere',lat_0=-90.,lon_0=0, width=12000000,height=8000000)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax, ax=ax)
    skip = 5
    m.quiver(x[::5, ::5], y[::5, ::5], plot_x_data[::5, ::5], plot_y_data[::5, ::5], scale=50, ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-180.,180.,10.), fontsize=10, ax=ax)

    m.colorbar(location='right', pad='5%', ax=ax)
    plt.show()
Example #22
0
def plot_on_earth(lons, lats, data, vmin=-4, vmax=12, cbar_loc='left', cbar_ticks=None):
    #import ipdb; ipdb.set_trace()
    #if ax == None:
	#ax = plt.gca()
    plot_lons, plot_data = extend_data(lons, lats, data)

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

    m = Basemap(projection='cyl', resolution='c', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    x, y = m(lons, lats)

    m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax)
    #m.pcolormesh(x, y, plot_data)

    m.drawcoastlines()
    if cbar_loc == 'left':
	p_labels = [0, 1, 0, 0]
    else:
	p_labels = [1, 0, 0, 0]

    m.drawparallels(np.arange(-90.,90.1,45.), labels=p_labels, fontsize=10)
    m.drawmeridians(np.arange(-180.,180.,60.), labels=[0, 0, 0, 1], fontsize=10)

    #import ipdb; ipdb.set_trace()
    if cbar_ticks == None:
	cbar = m.colorbar(location=cbar_loc, pad='7%')
    else:
	cbar = m.colorbar(location=cbar_loc, pad='7%', ticks=cbar_ticks)

    if cbar_loc == 'left':
	cbar.ax.xaxis.get_offset_text().set_position((10,0))
def plot_ICON_clt(ICON_data_dict):
	"This function gets ICON data and plots corresponding satellite pictures."

	# Import and create basemap for plotting countries and coastlines
	from mpl_toolkits.basemap import Basemap

	# Create well formatted time_string
	time_string = datetime.fromtimestamp(int(unix_time_in)).strftime('%Y-%m-%d-%H-%M')

	# Plotting temperature data
	plt.figure()
	# Plot contourf plot with lat/lon regridded ICON data
	cmap_cloud   = plt.cm.gray
	levels_cloud = np.arange(0,101,10)
	plt.contourf(ICON_data_dict["ICON_X_mesh"], ICON_data_dict["ICON_Y_mesh"], ICON_data_dict["ICON_clt"], levels=levels_cloud, cmap=cmap_cloud)
	plt.colorbar()
	# Plot map data
	map = Basemap(llcrnrlon=4.0,llcrnrlat=47.0,urcrnrlon=15.0,urcrnrlat=55.0,
	             resolution='i')
	map.drawcoastlines()
	map.drawcountries()
	lat_ticks = [55.0,53.0,51.0,49.0,47.0]
	map.drawparallels(lat_ticks, labels=[1,0,0,0], linewidth=0.0)
	lon_ticks = [4.0,6.0,8.0,10.0,12.0,14.0]
	map.drawmeridians(lon_ticks, labels=[0,0,0,1], linewidth=0.0)
	# Save plot and show it
	plt.savefig(output_path + 'TotalCloudCover_' + time_string + '.png')
Example #24
0
def Scatter(data, lons, lats, min, max, cmp, tit, unit, figdir, filename):
    # Prepare for drawing
    # ny, nx = (50, 116)
    # draw Chile Basemap with lambert projection at normal x, y settings
    m = Basemap(
        llcrnrlon=-78,
        llcrnrlat=-56,
        urcrnrlon=-66,
        urcrnrlat=-17,
        projection="cyl",
        fix_aspect=False,
        lat_1=-43,
        lat_2=-30,
        lon_0=-72,
    )  # projection='lcc'
    # draw boundaries
    m.drawcoastlines()
    m.drawcountries(linewidth=2)
    m.drawstates()
    m.drawparallels(arange(-60, -15, 15), labels=[1, 0, 0, 0])  # only left ytick
    m.drawmeridians(arange(-80, -60, 5), labels=[0, 0, 0, 1])  # only bottom xtick
    # map data with lon and lat position
    im = m.scatter(lons, lats, 30, marker="o", c=data, vmin=min, vmax=max, latlon=True, cmap=cmp)
    cb = m.colorbar(im, pad="10%")
    plt.title(tit, fontsize=20)
    plt.xlabel(unit, labelpad=50)
    # savefig('%s%s' % (figdir, filename))
    plt.show()
 def show(self, proj='moll', lon_0=180, tmap=None, coord=None):
     from mpl_toolkits.basemap import Basemap
     import pylab as plt
     import resources.figures as figures
     figures.set_fancy()
     if coord==None:
         ra = np.rad2deg(self.grid['points'][:,0])
         dec = np.rad2deg(self.grid['points'][:,1])
     else:
         ra = np.rad2deg(coord[:,0])
         dec = np.rad2deg(coord[:,1])
     
     fig = plt.figure()
     m = Basemap(projection=proj,lon_0=lon_0)#,celestial=True) # celestial=True inverses alpha (East towards the right)
     m.drawparallels(np.arange(-60.,90.,30.),labels=[1,0,0,0])
     m.drawmeridians(np.arange(0.,360.,30.))
     
     ra__ = np.arange(0., 360., 30.)
     x, y = m(ra__,ra__*0)
     for x,y,t in zip(x,y,ra__):
         plt.text(x, y, figures.format_degree(t), color='black', ha='center', weight='black', size='small') ##93c6ed
     if tmap==None:
         m.scatter(ra,dec,latlon=True,marker='x',s=20,cmap=plt.cm.binary)
     else:
         m.scatter(ra,dec,c=tmap,latlon=True,marker='x',s=20,cmap=plt.cm.binary)
     plt.show()
Example #26
0
def get_catalog_map(lats=None, lons=None, eq_cat=[], map_res='i', map_projection='cyl', fignum=0, ax=None, do_clf=True):
	#
	if lats==None: lats = [31., 42.]
	if lons==None: lons = [-125., -114.]
	#
	if fignum!=None: plt.figure(fignum)
	if do_clf: plt.clf()
	if ax==None: ax=plt.gca()
	#
	cm = Basemap(llcrnrlon=lons[0], llcrnrlat=lats[0], urcrnrlon=lons[1], urcrnrlat=lats[1], resolution=map_res, projection=map_projection, lon_0=numpy.mean(lons), lat_0=numpy.mean(lats), ax=ax)
	cm.drawcoastlines(color='gray', zorder=1)
	cm.drawcountries(color='gray', zorder=1)
	cm.drawstates(color='gray', zorder=1)
	cm.drawrivers(color='gray', zorder=1)
	cm.fillcontinents(color='beige', zorder=0)
	# drawlsmask(land_color='0.8', ocean_color='w', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=True, resolution='l', grid=5, **kwargs)
	#cm.drawlsmask(land_color='0.8', ocean_color='c', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=True, resolution=mapres, grid=5)

	print("lat, lon ranges: ", lats, lons)
	cm.drawmeridians(list(range(int(lons[0]), int(lons[1]))), color='k', labels=[0,0,1,1])
	cm.drawparallels(list(range(int(lats[0]), int(lats[1]))), color='k', labels=[1, 1, 0, 0])
	#
	if eq_cat!=None:
		# can we also assign sizes dynamically, like colors?
		if hasattr(eq_cat, 'dtype'):
			# it's a recrray:
			X,Y = cm(eq_cat['lon'], eq_cat['lat'])
		else:
			# it's probably a list... though we should check for dicts, etc.
			X,Y = cm([rw[2] for rw in eq_cat], [rw[1] for rw in eq_cat])
		#
		cm.plot(X,Y, '.')
				
	#
	return cm
Example #27
0
 def background_map(self, ax):
     llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon, lat_ts = (31, 44, -126, -113, 37.5)
     m = Basemap(projection='merc', llcrnrlat=llcrnrlat,
                 urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon,
                 lat_ts=lat_ts, resolution='i', ax=ax)
     m.drawmapboundary(fill_color='lightblue', zorder=0)
     m.fillcontinents(zorder=0)
     etopofn = '/home/behry/uni/data/etopo1_central_europe_gmt.grd'
     etopodata = Dataset(etopofn, 'r')
     z = etopodata.variables['z'][:]
     x_range = etopodata.variables['x_range'][:]
     y_range = etopodata.variables['y_range'][:]
     spc = etopodata.variables['spacing'][:]
     lats = np.arange(y_range[0], y_range[1], spc[1])
     lons = np.arange(x_range[0], x_range[1], spc[0])
     topoin = z.reshape(lats.size, lons.size, order='C')
     # transform to nx x ny regularly spaced 5km native projection grid
     nx = int((m.xmax - m.xmin) / 5000.) + 1; ny = int((m.ymax - m.ymin) / 5000.) + 1
     topodat, x, y = m.transform_scalar(np.flipud(topoin), lons, lats, nx, ny, returnxy=True)
     ls = LightSource(azdeg=300, altdeg=15, hsv_min_sat=0.2, hsv_max_sat=0.3,
                      hsv_min_val=0.2, hsv_max_val=0.3)
     # shade data, creating an rgb array.
     rgb = ls.shade(np.ma.masked_less(topodat / 1000.0, 0.0), cm.gist_gray_r)
     m.imshow(rgb)
     m.drawmeridians(np.arange(6, 12, 2), labels=[0, 0, 0, 1], color='white',
                     linewidth=0.5, zorder=0)
     m.drawparallels(np.arange(44, 50, 2), labels=[1, 0, 0, 0], color='white',
                     linewidth=0.5, zorder=0)
     m.drawcoastlines(zorder=1)
     m.drawcountries(linewidth=1.5, zorder=1)
     m.drawstates()
     m.drawrivers(color='lightblue', zorder=1)
     return m
Example #28
0
 def plot(self,key='Re'):
     """
     Create a plot of a variable over the ORACLES study area. 
     
     Parameters
     ----------
     key : string
     See names for available datasets to plot.
     
     clf : boolean
     If True, clear off pre-existing figure. If False, plot over pre-existing figure.
     
     Modification history
     --------------------
     Written: Michael Diamond, 08/16/2016, Seattle, WA
     Modified: Michael Diamond, 08/21/2016, Seattle, WA
        -Added ORACLES routine flight plan, Walvis Bay (orange), and Ascension Island
     Modified: Michael Diamond, 09/02/2016, Swakopmund, Namibia
         -Updated flihgt track
     """
     plt.clf()
     size = 16
     font = 'Arial'
     m = Basemap(llcrnrlon=self.lon.min(),llcrnrlat=self.lat.min(),urcrnrlon=self.lon.max(),\
     urcrnrlat=self.lat.max(),projection='merc',resolution='i')
     m.drawparallels(np.arange(-180,180,5),labels=[1,0,0,0],fontsize=size,fontname=font)
     m.drawmeridians(np.arange(0,360,5),labels=[1,1,0,1],fontsize=size,fontname=font)
     m.drawmapboundary(linewidth=1.5)        
     m.drawcoastlines()
     m.drawcountries()
     if key == 'Pbot' or key == 'Ptop' or key == 'Nd' or key == 'DZ': 
         m.drawmapboundary(fill_color='steelblue')
         m.fillcontinents(color='floralwhite',lake_color='steelblue',zorder=0)
     else: m.fillcontinents('k',zorder=0)
     if key == 'Nd':
         m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\
         latlon=True,norm = LogNorm(vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1]))
     elif key == 'Zbf' or key == 'Ztf':
         levels = [0,250,500,750,1000,1250,1500,1750,2000,2500,3000,3500,4000,5000,6000,7000,8000,9000,10000]
         m.contourf(self.lon,self.lat,self.ds['%s' % key],levels=levels,\
         cmap=self.colors['%s' % key],latlon=True,extend='max')
     elif key == 'DZ':
         levels = [0,500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000]
         m.contourf(self.lon,self.lat,self.ds['%s' % key],levels=levels,\
         cmap=self.colors['%s' % key],latlon=True,extend='max')
     else:
         m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\
         latlon=True,vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1])
     cbar = m.colorbar()
     cbar.ax.tick_params(labelsize=size-2) 
     cbar.set_label('[%s]' % self.units['%s' % key],fontsize=size,fontname=font)
     if key == 'Pbot' or key == 'Ptop': cbar.ax.invert_yaxis() 
     m.scatter(14.5247,-22.9390,s=250,c='orange',marker='D',latlon=True)
     m.scatter(-14.3559,-7.9467,s=375,c='c',marker='*',latlon=True)
     m.scatter(-5.7089,-15.9650,s=375,c='chartreuse',marker='*',latlon=True)
     m.plot([14.5247,13,0],[-22.9390,-23,-10],c='w',linewidth=5,linestyle='dashed',latlon=True)
     m.plot([14.5247,13,0],[-22.9390,-23,-10],c='k',linewidth=3,linestyle='dashed',latlon=True)
     plt.title('%s from MSG SEVIRI on %s/%s/%s at %s UTC' % \
     (self.names['%s' % key],self.month,self.day,self.year,self.time),fontsize=size+4,fontname=font)
     plt.show()
Example #29
0
def ww3_plot(fname,xlim=False,ylim=False,res='c'):
  '''
  ex.:
    f='WW3_data/2012/multi_1.glo_30m.dp.201201.grb2'
    swanu.ww3_plot(f,xlim=[-100,-80],ylim=[20,32],res='i')
  '''

  from mpl_toolkits.basemap import Basemap
  import pylab as pl

  f=pygrib.open(fname)
  lat,lon=f.message(1).latlons()
  lon[lon>180]=lon[lon>180]-360.

  if not xlim: xlim=-180,180
  if not ylim: ylim=-90,90

  m = Basemap(projection='cyl',llcrnrlat=ylim[0],urcrnrlat=ylim[1],
              llcrnrlon=xlim[0],urcrnrlon=xlim[1],resolution=res)

  m.drawcoastlines()
  m.fillcontinents(color='#cccccc',lake_color='w')
  # draw parallels and meridians.
  m.drawparallels(np.arange(-90.,91.,30.))
  m.drawmeridians(np.arange(-180.,181.,60.))

  x,y=m(lon,lat)
  pl.plot(x,y,'b.',ms=.5)
  pl.show()
Example #30
0
def vec_plot_on_earth(lons, lats, x_data, y_data, vmin=-4, vmax=12, ax=None):
    if ax == None:
	ax = plt.gca()
    plot_lons, plot_x_data = extend_data(lons, lats, x_data)
    plot_lons, plot_y_data = extend_data(lons, lats, y_data)

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

    m = Basemap(ax=ax, projection='cyl', resolution='c', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax)
    #m.quiver(x, y, plot_x_data, plot_y_data)
    skip = 5
    m.quiver(x[::skip, ::skip], y[::skip, ::skip], plot_x_data[::skip, ::skip], plot_y_data[::skip, ::skip], ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-90.,90.,45.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-180.,180.,60.), labels=[0, 0, 0, 1], fontsize=10, ax=ax)


    m.colorbar(location='bottom', pad='7%', ax=ax)
    plt.show()
for i in range(40,41):
	fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(16, 10))
	plt.subplots_adjust(left=0.1, right=0.9, bottom=0.1, wspace=0.1)
	ax1 = plt.subplot2grid((1,2), (0,0))
	ax2 = plt.subplot2grid((1,2), (0,1))
	ax1.set_xlim(4,20); ax1.set_xlabel('Temperature, [C]')
	#xlim(30,38); xlabel('Salinity, [psu]')
	ax1.set_ylabel('Depth, [m]')#;ax1.set_ylim(0,80)
	ax1.set_ylim(80, 0)
	#ax1 = plt.gca()
	#ax1.set_ylim(ax1.get_ylim()[::-1])
	ax1.scatter(temptemp[i], depthdepth[i], color='r', label='in-situ')
	ax1.scatter(temp[i], dt[15*i:15*i+15], color='b', label='model')
	ax1.legend(loc=3)
	m2 = Basemap(projection='merc', llcrnrlat=51,urcrnrlat=51.9,llcrnrlon=2.0,urcrnrlon=3.5,lat_ts=51.45, resolution='i', ax=ax2)
	m2.drawparallels(arange(51.0,51.9,0.3),labels=[1,0,0,1],fontsize=10)
	m2.drawmeridians(arange(2,3.5,0.5),labels=[1,0,0,1],fontsize=10)
	m2.drawcoastlines()
	m2.drawmapboundary(fill_color='#9999FF')
	x4, y4 = m2(x_bcz, y_bcz); 	lnln, ltlt = m2(lonlon[i], latlat[i]); lg,lt=m2(long[i],lati[i]);clevs = np.arange(0.,60.0,1);cax = fig.add_axes([0.2, 0.08, 0.6, 0.04])
	x2, y2 = m2(lon, lat)
	cs43 = m2.plot(x4,y4,color='black',linewidth=1.0)
	CS4 = m2.contourf(x2,y2,h,clevs,cmap='Blues',animated=True)
	cb1 = colorbar(CS4, cax, orientation='horizontal')
	m2.drawcountries()
	m2.fillcontinents(color='#ddaa66',lake_color='#9999FF')
	m2.scatter(lnln,ltlt,20,marker='o',color='r')
	m2.scatter(lg,lt,20,marker='o',color='b')

show()
'''
def traj_plot_all_clear_cloudy(*months,
                               path,
                               state,
                               levels=[
                                   '780', '1000', '1400', '1850', '2850',
                                   '3950', '5220', '6730', '8600'
                               ]):
    """
    Function to plot trajectories of all clear or cloudy states or according to month
    path: path to data file to be plotted
    state: clear or cloudy
    """

    # specifying the levels or ask user to give levels as a list
    #levels = ['780', '1000', '1400', '1850', '2850', '3950', '5220', '6730', '8600']
    fig = plt.figure(figsize=(12, 10))
    # plt.figure(figsize=(10,8))

    m = Basemap(projection='ortho', lat_0=80, lon_0=270, resolution='l')
    m.fillcontinents(color='0.75')
    m.drawparallels(np.arange(-80., 81., 20.), color='grey')
    m.drawmeridians(np.arange(-180., 181., 20.))

    mons = [mo for mo in months]

    dates_ = []

    # checking for clear or cloudy
    if (state == 'cloudy'):
        for mo in mons:
            # makes a list of list
            # each month dates are stored as a separate list with dates as strings
            dates_.append(
                open(
                    '/home/ollie/muali/python_notebooks/Avg_dates/3havg_cloudy_'
                    + mo, 'r').read().split('\n'))
    else:
        for mo in mons:
            dates_ = open(
                '/home/ollie/muali/python_notebooks/Avg_dates/3havg_clear_' +
                mo, 'r').read().split('\n')

    for lvl in levels:
        #to loop over all levels
        # inner loop for plotting all the trajectories on one map

        # read the trajectories to be plotted
        for line_ in dates_:
            # element by element reading the dates
            df = pd.read_csv(path + 'tdump_' + lvl + '_' + line_,
                             skiprows=7,
                             header=None,
                             delim_whitespace=True)

            lat = np.array(df.iloc[:, 9].copy())
            lon = np.array(df.iloc[:, 10].copy())

            #Convert lat lon to map coordinates
            x, y = m(lon, lat)

            #Plot the points on the map
            plt.plot(x, y, linewidth=1.0, color='red')

            #source point
            xpt, ypt = m(lon[-1], lat[-1])
            plt.plot(xpt, ypt, marker='*', markerfacecolor='red', markersize=8)
Example #33
0

max_val = np.max(v)

levels=[-0.01251*max_val,0.,0.01251*max_val,0.0251*max_val,0.0625*max_val,.1*max_val,.2*max_val,.3*max_val,.4*max_val,.5*max_val,.6*max_val,.7*max_val,.75*max_val,.8*max_val,.9*max_val,1.*max_val]



for i in xrange(1):
   fig = plt.figure(figsize=(48, 48)) 
   m.drawmapboundary(fill_color='white', zorder=-1, linewidth=4.5)
   m.fillcontinents(color='0.8', lake_color='white', zorder=0)
 
   m.drawcoastlines(color='0.0', linewidth=4.5)
   #m.drawcountries(color='0.', linewidth=4.5)
   m.drawparallels(np.arange(-90.,91.,30.), labels=[1,0,0,1],    dashes=[1,1], linewidth=1.0, color='0.5',fontsize='x-large', fontname='Times')
   m.drawmeridians(np.arange(0., 360., 60.), labels=[1,0,0,1], dashes=[1,1], linewidth=1.0, color='0.5',fontsize='x-large', fontname='Times')

 
   #PLOT ABSOLUTE
   #cs = m.contourf(X2,Y2,mdata,levels,cmap=cmap,extend='both')
   cs = m.contourf(X2,Y2,mdata,levels,cmap=cmap)
   vmin,vmax = (-0.01251*max_val,max_val)


   plt.tight_layout()
   #cbar = m.colorbar(cs,location='bottom',pad='10%',ticks=np.linspace(vmin,vmax,7),format='%.1f')
   ticks = [0.,0.0251*max_val,.1*max_val,.3*max_val,.5*max_val,.7*max_val,.8*max_val,1.*max_val]
   cbar = m.colorbar(cs,location='bottom',pad='10%',ticks=ticks,format='%.1f')
   #cbar.ax.get_yaxis().labelpad = 60
   cbar.ax.get_xaxis().labelpad = 45
Example #34
0
                    color='k',
                    fontweight='bold',
                    fontsize=12,
                    zorder=10)  #xytext=(-500,500),textcoords='offset points'
        else:  # case of multiple drifters
            df = pd.read_csv('http://nefsc.noaa.gov/drifter/drift_' + cluster +
                             '.csv')
            ids = np.unique(df['ID'])
            for k in ids:
                df1 = df[df['ID'] == k]
                df1 = df1[df1['DAY'] == datetime_wanted.day]
                x, y = m(df1['LON'].values, df1['LAT'].values)
                m.plot(x, y, 'k')

    m.drawparallels(np.arange(min(latsize),
                              max(latsize) + 1, tick_int),
                    labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(min(lonsize),
                              max(lonsize) + 1, tick_int),
                    labels=[0, 0, 0, 1])
    #m.drawcoastlines()
    m.drawmapboundary()
    plt.title(
        str(datetime_wanted.strftime("%d-%b-%Y")) + ' ' + agg + '-day ' +
        sat_option + ' composite')  #+cluster)
    plt.savefig(png_dir + sat_option + '_' + area + '_' +
                datetime_wanted.strftime('%Y-%m-%d') + '_' + agg + '.png')
    plt.show()
gif_name = png_dir + gif_name
make_gif(gif_name,
         png_dir,
Example #35
0
delat = lats[1] - lats[0]
lons = (lons - 0.5 * delon).tolist()
lons.append(lons[-1] + delon)
lons = np.array(lons, np.float64)
lats = (lats - 0.5 * delat).tolist()
lats.append(lats[-1] + delat)
lats = np.array(lats, np.float64)
# creat figure, axes instances.
fig = plt.figure()
ax = fig.add_axes([0.05, 0.05, 0.9, 0.9])
# create Basemap instance for Robinson projection.
# coastlines not used, so resolution set to None to skip
# continent processing (this speeds things up a bit)
m = Basemap(projection='robin', lon_0=lons.mean(), resolution=None)
# compute map projection coordinates of grid.
x, y = m(*np.meshgrid(lons, lats))
# draw line around map projection limb.
# color background of map projection region.
# missing values over land will show up this color.
m.drawmapboundary(fill_color='0.3')
# plot sst, then ice with pcolor
im1 = m.pcolor(x, y, sst, shading='flat', cmap=plt.cm.jet)
im2 = m.pcolor(x, y, ice, shading='flat', cmap=plt.cm.gist_gray)
# draw parallels and meridians, but don't bother labelling them.
m.drawparallels(np.arange(-90., 120., 30.))
m.drawmeridians(np.arange(0., 420., 60.))
# add colorbar
cb = m.colorbar(im1, "bottom", size="5%", pad="2%")
# add a title.
ax.set_title('SST and ICE analysis for %s' % date)
plt.savefig('plotsst.png')
Example #36
0
def processing(path):
    """
    Generates images from NetCDF files
    pathDir: root direcotry with "Data", "Output" and "Scripts" folders
    pathFile: path to NetCDF file to be manipulated
    outFolder: path to directory where the generated images should be saved
    Output: .png image file
    """

    # Getting information from the file name ============================================================
    # Search for the GOES-16 channel in the file name
    INPE_Band_ID = (path[path.find("S10635") + 6:path.find("_")])
    # print(INPE_Band_ID)
    # Get the band number subtracting the value by 332
    Band = int(INPE_Band_ID) - 332

    # Create a GOES-16 Bands string array
    Wavelenghts = [
        '[]', '[0.47 μm]', '[0.64 μm]', '[0.865 μm]', '[1.378 μm]',
        '[1.61 μm]', '[2.25 μm]', '[3.90 μm]', '[6.19 μm]', '[6.95 μm]',
        '[7.34 μm]', '[8.50 μm]', '[9.61 μm]', '[10.35 μm]', '[11.20 μm]',
        '[12.30 μm]', '[13.30 μm]'
    ]
    Band_Wavelenght = Wavelenghts[int(Band)]
    # Search for the Scan start in the file name
    Start = (path[path.find(INPE_Band_ID + "_") + 4:path.find(".nc")])
    # Getting the date from the file name
    year = Start[0:4]
    month = Start[4:6]
    day = Start[6:8]
    date = day + "-" + month + "-" + year
    time = Start[8:10] + ":" + Start[
        10:12] + " UTC"  # Time of the Start of the Scan

    # Get the unit based on the channel. If channels 1 trough 6 is Albedo. If channels 7 to 16 is BT.
    Unit = "Albedo (%)"
    # Choose a title for the plot
    Title = " GOES-16 ABI CMI Band " + str(
        Band) + " " + Band_Wavelenght + " " + Unit + " " + date + " " + time
    # Insert the institution name
    Institution = "CEPAGRI - UNICAMP"
    # Required libraries ================================================================================

    # Open the file using the NetCDF4 library
    nc = Dataset(path)

    # Choose the visualization extent (min lon, min lat, max lon, max lat)
    extent = [-115.98, -55.98, -25.01, 34.98]
    min_lon = extent[0]
    max_lon = extent[2]
    min_lat = extent[1]
    max_lat = extent[3]

    # Get the latitudes
    lats = nc.variables['lat'][:]
    # Get the longitudes
    lons = nc.variables['lon'][:]

    # print (lats)
    # print (lons)

    # latitude lower and upper index
    latli = np.argmin(np.abs(lats - extent[1]))
    latui = np.argmin(np.abs(lats - extent[3]))

    # longitude lower and upper index
    lonli = np.argmin(np.abs(lons - extent[0]))
    lonui = np.argmin(np.abs(lons - extent[2]))

    # Extract the Brightness Temperature / Reflectance values from the NetCDF
    data = nc.variables['Band1'][latli:latui, lonli:lonui]

    # Flip the y axis, divede by 100
    data = (np.flipud(data) / 100)

    # Define the size of the saved picture ==============================================================
    DPI = 150
    ax = plt.figure(figsize=(2000 / float(DPI), 2000 / float(DPI)),
                    frameon=True,
                    dpi=DPI)
    #====================================================================================================

    # Plot the Data =====================================================================================
    # Create the basemap reference for the Rectangular Projection
    bmap = Basemap(llcrnrlon=extent[0],
                   llcrnrlat=extent[1],
                   urcrnrlon=extent[2],
                   urcrnrlat=extent[3],
                   epsg=4326)

    # Draw the countries and Brazilian states shapefiles
    bmap.readshapefile('/Scripts/GEONETCast/Shapefiles/BRA_adm1',
                       'BRA_adm1',
                       linewidth=0.50,
                       color='cyan')
    bmap.readshapefile(
        '/Scripts/GEONETCast/Shapefiles/ne_10m_admin_0_countries',
        'ne_10m_admin_0_countries',
        linewidth=0.50,
        color='cyan')

    # Draw parallels and meridians
    bmap.drawparallels(np.arange(-90.0, 90.0, 5.0),
                       linewidth=0.3,
                       dashes=[4, 4],
                       color='white',
                       labels=[False, False, False, False],
                       fmt='%g',
                       labelstyle="+/-",
                       xoffset=-0.80,
                       yoffset=-1.00,
                       size=7)
    bmap.drawmeridians(np.arange(0.0, 360.0, 5.0),
                       linewidth=0.3,
                       dashes=[4, 4],
                       color='white',
                       labels=[False, False, False, False],
                       fmt='%g',
                       labelstyle="+/-",
                       xoffset=-0.80,
                       yoffset=-1.00,
                       size=7)

    # Converts a CPT file to be used in Python
    cpt = loadCPT(
        '/Scripts/GEONETCast/Colortables/Square Root Visible Enhancement.cpt')
    # Makes a linear interpolation
    cpt_convert = LinearSegmentedColormap('cpt', cpt)
    # Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference)
    bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=0, vmax=100)

    # Insert the colorbar at the bottom
    cb = bmap.colorbar(location='bottom',
                       size='2%',
                       pad='-3.5%',
                       ticks=[20, 40, 60, 80])
    cb.ax.set_xticklabels(['20', '40', '60', '80'])
    cb.outline.set_visible(False)  # Remove the colorbar outline
    cb.ax.tick_params(width=0)  # Remove the colorbar ticks
    cb.ax.xaxis.set_tick_params(
        pad=-14.5)  # Put the colobar labels inside the colorbar
    cb.ax.tick_params(
        axis='x', colors='black',
        labelsize=8)  # Change the color and size of the colorbar labels

    # Add a black rectangle in the bottom to insert the image description
    lon_difference = (extent[2] - extent[0])  # Max Lon - Min Lon
    currentAxis = plt.gca()
    currentAxis.add_patch(
        Rectangle((extent[0], extent[1]),
                  lon_difference,
                  lon_difference * 0.015,
                  alpha=1,
                  zorder=3,
                  facecolor='black'))

    # Add the image description inside the black rectangle
    lat_difference = (extent[3] - extent[1])  # Max lat - Min lat
    plt.text(extent[0],
             extent[1] + lat_difference * 0.003,
             Title,
             horizontalalignment='left',
             color='white',
             size=10)
    plt.text(extent[2],
             extent[1] + lat_difference * 0.003,
             Institution,
             horizontalalignment='right',
             color='yellow',
             size=10)

    # Add logos / images to the plot
    logo_GNC = plt.imread('/Scripts/GEONETCast/Logos/GNC_Logo.png')
    logo_INPE = plt.imread('/Scripts/GEONETCast/Logos/INPE_Logo.png')
    logo_NOAA = plt.imread('/Scripts/GEONETCast/Logos/NOAA_Logo.png')
    logo_GOES = plt.imread('/Scripts/GEONETCast/Logos/GOES_Logo.png')
    logo_cepagri = plt.imread('/Scripts/GEONETCast/Logos/Logo_CEPAGRI.png')

    ax.figimage(logo_GNC, 20, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_INPE, 90, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_NOAA, 165, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_GOES, 228, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_cepagri, 326, 70, zorder=3, alpha=1, origin='upper')

    # Save the result
    # print('/Scripts/GEONETCast/Output/' + path[12:18] + '/INPE_G16_CH' + str(Band) + '_' + Start + '.png')
    plt.savefig('/Scripts/GEONETCast/Output/' + path[12:18] + '/INPE_G16_CH' +
                str(Band) + '_' + Start + '.png',
                dpi=DPI,
                bbox_inches='tight',
                pad_inches=0)
Example #37
0
print resCap.shape
#print resCap[:,0]
#print resCap[:,1]
#print resCap[np.all(grid[:]==[10000.,40000.],axis=1)][0,234]
capMax = np.max(resCap)

startpointx, startpointy = (357309.0, 131195.0)
#startpointx, startpointy = (360000.0, 130000.0)

#fig, ax = plt.subplots()

#grid_x, grid_y = np.mgrid[0:maxx-minx:10000, 0:maxy-miny:10000]

m.fillcontinents(color='lightgray', lake_color='blue', zorder=15)
m.drawcoastlines(zorder=15)
m.drawparallels(np.arange(-80., 81., 20.), zorder=10)
#m.drawmeridians(np.arange(-180.,181.,20.),zorder=0);
m.drawmapboundary(fill_color='white', zorder=10)
#m.plot(startpointx,startpointy,marker='*',markersize=15,zorder=20,color='yellow')
m.plot(357309.0,
       131195.0,
       marker='*',
       markersize=40,
       zorder=20,
       color='yellow')
m.plot(255000.0,
       554000.0,
       marker='*',
       markersize=40,
       zorder=20,
       color='yellow')
Example #38
0
    model_tag = model_names[irow]

    m = Basemap(ax=ax,
                projection='tmerc',
                resolution='l',
                llcrnrlat=map_lat_min,
                llcrnrlon=map_lon_min,
                urcrnrlat=map_lat_max,
                urcrnrlon=map_lon_max,
                lat_0=map_lat_center,
                lon_0=map_lon_center)
    m.drawcoastlines(linewidth=0.2)
    m.drawcountries(linewidth=0.2)
    m.drawparallels(map_parallels,
                    linewidth=0.1,
                    labels=[1, 0, 0, 0],
                    fontsize=8)
    m.drawmeridians(map_meridians,
                    linewidth=0.1,
                    labels=[0, 0, 0, 1],
                    fontsize=8)

    # contourf model
    xx, yy = m(lons2, lats2)
    zz = np.transpose(model[model_tag])

    if model_tag in ['dlnvs']:
        #z_max = round_to_1(np.max(np.abs(zz)))
        #dz = 2.0*z_max/10
        #levels = np.arange(-z_max, z_max+dz/2, dz)
        zz = zz * 100  # use percentage
Example #39
0
                resolution='l',
                round=True)
elif style == 'polar':
    m = Basemap(projection='npstere',
                boundinglat=66,
                lon_0=270,
                resolution='l',
                round=True)

m.drawmapboundary(fill_color='white')
m.drawcoastlines(color='k', linewidth=0.3)
parallels = np.arange(50, 90, 10)
meridians = np.arange(-180, 180, 30)
m.drawparallels(parallels,
                labels=[False, False, False, False],
                linewidth=0.5,
                color='k',
                fontsize=4)
mer = m.drawmeridians(meridians,
                      labels=[True, True, False, False],
                      linewidth=0.5,
                      color='k',
                      fontsize=4)
m.drawlsmask(land_color='darkgrey', ocean_color='w')
setcolor(mer, 'white')

### Adjust maximum limits
values = np.arange(-2, 2.1, .2)

### Plot filled contours
cs = m.contourf(lons[:, :],
Example #40
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import urllib.request
import json

# basic map setup
globe = Basemap(projection='robin', resolution='c', lat_0=0, lon_0=0)
globe.drawcoastlines()
globe.drawcountries()
globe.fillcontinents(color="grey")
globe.drawmapboundary()
globe.drawmeridians(np.arange(0, 360, 30))
globe.drawparallels(np.arange(-90, 90, 30))

x, y = globe(0, 0)
point = globe.plot(x, y, 'ro', markersize=7)[0]


def init():
    point.set_data([], [])
    return point,


# animation function.  This is called sequentially
def animate(i):
    lons, lats = iss_position()
    x, y = globe(lons, lats)
    point.set_data(x, y)
    return point,
Example #41
0
                          V2d[zoom[1]:zoom[3], zoom[0]:zoom[2]],
                          cmap=cmap,
                          norm=nrm_value)
    #    ft = carte.pcolormesh(x0[1:nj-3,3:ni],y0[1:nj-3,3:ni],V2d[1:nj-3,3:ni], cmap = cmap, norm=nrm_value )
    #ft = carte.pcolormesh(x0,y0,V2d,  norm=nrm_value )
    #carte.etopo()
    #carte.shadedrelief()
    carte.drawcoastlines(linewidth=0.5)

    #   xstep=45
    #   ystep=20
    carte.drawmeridians(nmp.arange(vp[0], vp[2] + xstep, xstep),
                        labels=[1, 1, 1, 1],
                        linewidth=0.3)
    carte.drawparallels(nmp.arange(vp[1], vp[3] + ystep, ystep),
                        labels=[1, 1, 1, 1],
                        linewidth=0.3)

    # add color bar  :
    ax3 = plt.axes([0.1, 0.05, 0.80, 0.015])

    clb = mpl.colorbar.ColorbarBase(ax3,
                                    ticks=vc_value,
                                    cmap=cmap,
                                    norm=nrm_value,
                                    orientation='horizontal')

    # Add title
    #    ax.annotate('ENERGETICS', xy=(0.02, 0.9), xycoords='figure fraction')
    ax.annotate(cname + '(' + unit + ') ' + datstr,
                xy=(0.3, 0.93),
Example #42
0
m = Basemap(llcrnrlon=0,
            llcrnrlat=-90,
            urcrnrlon=360,
            urcrnrlat=90,
            projection='mill')
lons, lats = np.meshgrid(lon, lat)
x, y = m(lons, lats)

fig1 = plt.figure(figsize=(16, 20))
ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
clevs = np.linspace(-240, 240, 21)
CS1 = m.contour(x, y, pre_1997, clevs, linewidths=0.5, colors='k')
CS2 = m.contourf(x, y, pre_1997, clevs, cmap=plt.cm.RdBu_r)
m.drawmapboundary(fill_color='#99ffff')
m.drawcoastlines(linewidth=1.5)
m.drawparallels(np.arange(-90, 90, 20), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(0., 360., 20.), labels=[0, 0, 0, 1])
cbar = m.colorbar(CS2, location='bottom', pad="5%")
cbar.set_label('mm')
plt.title('Regression Precipitation Anomaly in 1997')
plt.savefig("./1997.png", dpi=500)

fig2 = plt.figure(figsize=(16, 20))
ax = fig2.add_axes([0.1, 0.1, 0.8, 0.8])
clevs = np.linspace(-240, 240, 21)
CS1 = m.contour(x, y, pre_1998, clevs, linewidths=0.5, colors='k')
CS2 = m.contourf(x, y, pre_1998, clevs, cmap=plt.cm.RdBu_r)
m.drawmapboundary(fill_color='#99ffff')
m.drawcoastlines(linewidth=1.5)
m.drawparallels(np.arange(-90, 90, 20), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(0., 360., 20.), labels=[0, 0, 0, 1])
    fig = plt.figure()
    # create an Axes at an arbitrary location, which makes a list of [left, bottom, width, height] values in 0-1 relative figure coordinates:
    ax = fig.add_axes([0.1,0.1,0.8,0.8])
    # create Basemap instance.
    m = Basemap(projection='cyl', lat_0=0, lon_0=0)
    m.drawcoastlines(linewidth=1.25)
    m.fillcontinents(color='0.95')
    #m.drawmapboundary(fill_color='0.9')
    # cacluate colorbar ranges
    #bounds_max=float("{0:.0f}".format(np.nanpercentile(Plot_Var, 99.99))) # Upper bound of plotted values to be used for colorbar, which is 99.99th percentile of data, with 0 decimals
    bounds_max=33
    bounds = np.arange(0, bounds_max, bounds_max/33)
    norm = matplotlib.colors.BoundaryNorm(boundaries=bounds, ncolors=256)
    # create a pseudo-color plot over the map
    im1 = m.pcolormesh(Lon_img, Lat_img, Plot_Var, norm=norm, shading='flat', cmap=plt.cm.jet, latlon=True) # Choose colormap: https://matplotlib.org/users/colormaps.html
    m.drawparallels(np.arange(-90.,90.001,30.),labels=[True,False,False,False], linewidth=0.01) # labels = [left,right,top,bottom]
    m.drawmeridians(np.arange(0.,360.,30.),labels=[False,False,False,True], linewidth=0.01) # labels = [left,right,top,bottom]
    # add colorbar
    cbar = m.colorbar(im1,"right", size="3%", pad="2%", extend='max') # extend='both' will extend the colorbar in both sides (upper side and down side)
    cbar.set_label(Var_plot_unit)
    #set title
    ax.set_title(Var_plot_name+', at surface - hist - average of '+start_date_cal_hist+'-'+end_date_cal_hist + ' - ' +str(GCM))
    mng = plt.get_current_fig_manager()
    mng.window.showMaximized() # Maximizes the plot window to save figures in full
    #plt.show()
    fig.savefig(dir_figs+Var_name+'_'+ str(GCM)+'_surface_hist-' +start_date_cal_hist+'-'+end_date_cal_hist + '.png', format='png', dpi=300, transparent=True, bbox_inches='tight')
    plt.close()
    
    print('Model '+str(GCM)+' - hist - processed successfully')
    
#################################################
def draw_map(station_etude,
             latm,
             latM,
             lonm,
             lonM,
             path,
             all_pos,
             hw,
             vn_ITRF,
             ve_ITRF,
             plot_vertical_ITRF,
             incvn_ITRF,
             incve_ITRF,
             incplot_vertical_ITRF,
             plot_GEBCO=False,
             plot_vertical=False,
             plot_topo=True,
             plot_ellipses=True,
             coarse_lines=False,
             legend_arrow_length=("1 cm/yr", 0.01),
             legend_ellipse_size=("2 mm/yr", 0.002),
             legend_position=(0.5, 0.9),
             scale_arrow=15000000,
             scale_ellipse=10000000,
             name_stats=True,
             name_stats_font_size=8,
             name_stats_offset=(0.005, 0.01),
             shorten_oversized_arrows=True,
             exclude_points_out_of_range=True,
             adjust_text=False,
             pixels_hires_backgrnd=2000,
             draw_borders=True,
             full_return=False,
             draw_latlon_lines=True):
    """
    """

    nstation = len(station_etude)
    fig, ax = plt.subplots(figsize=(7, 8))

    if incvn_ITRF is None:
        incvn_ITRF = np.zeros(len(station_etude))
    if incve_ITRF is None:
        incve_ITRF = np.zeros(len(station_etude))
    if incplot_vertical_ITRF is None:
        incplot_vertical_ITRF = np.zeros(len(station_etude))

    if coarse_lines:
        resolution = "l"
    else:
        resolution = "h"
    m = Basemap(projection='merc',
                llcrnrlat=latm,
                urcrnrlat=latM,
                llcrnrlon=lonm,
                urcrnrlon=lonM,
                lat_ts=-20,
                resolution=resolution,
                area_thresh=1,
                epsg=3395)

    if draw_borders:
        m.drawcoastlines(linewidth=0.25)
        m.drawcountries()
        m.drawstates()

    if plot_topo:
        m.arcgisimage(service='World_Shaded_Relief',
                      xpixels=pixels_hires_backgrnd,
                      verbose=True)
    else:
        m.drawmapboundary(fill_color='#97B6E1')
        m.fillcontinents(color='#EFEFDB', lake_color='#97B6E1', zorder=1)
        m.shadedrelief()

    if not plot_GEBCO:
        color1 = 'black'
    else:
        color1 = 'white'
        levels = [-8000, -7000, -6000, -5500, -5000, -4500,
                  -4000]  #Niveaux pour l'echelle de couleur
        gebconc = Dataset(path + 'GEBCO\\GRIDONE_2D.nc')
        #Vecteur longitudes/latitudes
        long_ini = gebconc.variables['lon'][:]
        lats_ini = gebconc.variables['lat'][:]
        (lats_area, longs_area,
         gebco_area) = area(long_ini, lats_ini, gebconc, latm, latM, lonm,
                            lonM, '0-180')  #lat bas,lat haut, long
        (longs, lats, gebco) = split_grid(longs_area, lats_area, gebco_area, 2)
        (longs_gr, lats_gr) = np.meshgrid(longs, lats)
        fond = m.pcolormesh(longs_gr,
                            lats_gr,
                            gebco,
                            shading='flat',
                            cmap=LevelColormap(list(np.asarray(levels) * (1)),
                                               cmap=cm.deep_r),
                            latlon=True)  #ice,deep
        cbar = m.colorbar(location='top', pad=0.5)
        cbar.set_label('Depth [m] ', rotation=0)

    if draw_latlon_lines:
        m.drawparallels(np.arange(latm, latM, 1.),
                        fontsize=10,
                        color=color1,
                        labels=[True, False, False, False],
                        linewidth=0.25,
                        dashes=[10000, 1])  #de -180 a 360 par pas de 5° ;
        m.drawmeridians(np.arange(lonm, lonM, 1.),
                        fontsize=10,
                        color=color1,
                        labels=[False, False, False, True],
                        linewidth=0.25,
                        dashes=[10000, 1])  # Haut / G/D/BAS
        ### Labels
        plt.xlabel('Longitude (°) ', labelpad=25, fontsize=10)
        plt.ylabel('Latitude (°) ', labelpad=40, fontsize=10)
        ax.yaxis.set_label_position("left")

    all_posx_proj = [0] * nstation
    all_posy_proj = [0] * nstation
    for i in range(nstation):
        all_posx_proj[i], all_posy_proj[i] = m(
            all_pos[i][1], all_pos[i][0]
        )  #positions xy des stations converties a la projection de la carte  [m]
        print(i, all_posx_proj[i], all_posy_proj[i])
        m.plot(
            all_posx_proj[i],
            all_posy_proj[i],
            'xkcd:black',
            marker='.',
            linestyle='none',
            markersize=4,
            lw=4,
            zorder=20
        )  #point rouge à la station, zorder indique l'ordre vertical de dessin sur la carte, les nb elevés sont dessinés les plus hauts
#          plt.text(all_posx_proj[i], all_posy_proj[i], station_etude[i], size=10,ha="center", va="center",bbox=dict(boxstyle="round",
#                           ec=(1., 0.5, 0.5),
#                           fc=(1., 0.8, 0.8),
#                           )
#                 )

############### DICO POUR FLECHES DEFINITION
    arrow_prop_dict = dict(arrowstyle='->,head_length=0.8,head_width=0.3',
                           ec='xkcd:black',
                           fc='xkcd:black',
                           linewidth=2)

    arrow_prop_dict_V_up = dict(arrowstyle='->,head_length=0.8,head_width=0.3',
                                ec='xkcd:green',
                                fc='xkcd:green',
                                linewidth=2)

    arrow_prop_dict_V_down = dict(
        arrowstyle='->,head_length=0.8,head_width=0.3',
        ec='xkcd:red orange',
        fc='xkcd:red orange',
        linewidth=2)

    arrow_prop_dict_V_up_short = dict(
        arrowstyle='->,head_length=0.8,head_width=0.3',
        ec='xkcd:green',
        fc='xkcd:green',
        linewidth=2,
        linestyle="--")

    arrow_prop_dict_V_down_short = dict(
        arrowstyle='->,head_length=0.8,head_width=0.3',
        ec='xkcd:red orange',
        fc='xkcd:red orange',
        linewidth=2,
        linestyle="--")

    if not plot_vertical:  #CHAMP VITESSES HORIZONTALES
        for i in range(nstation):

            ######### Exclude point if not in range
            #latm,latM,lonm,lonM
            bool_good_lat = latm < all_pos[i][0] < latM
            bool_good_lon = lonm < all_pos[i][1] < lonM
            if exclude_points_out_of_range and not (bool_good_lat
                                                    and bool_good_lon):
                print("INFO : exclude point because out of range")
                continue

            x_end_arrow_ok = all_posx_proj[i] + np.multiply(
                ve_ITRF[i], scale_arrow)
            y_end_arrow_ok = all_posy_proj[i] + np.multiply(
                vn_ITRF[i], scale_arrow)

            ax.annotate(
                s='',
                xy=(x_end_arrow_ok, y_end_arrow_ok),
                xytext=(all_posx_proj[i], all_posy_proj[i]),
                arrowprops=arrow_prop_dict,
                annotation_clip=True
            )  #xy point arrivee de la fleche, xytext l'origine de la fleche
            a = math.atan(
                (all_posx_proj[i] + np.multiply(ve_ITRF[i], scale_arrow) -
                 all_posy_proj[i]) /
                (all_posy_proj[i] + np.multiply(ve_ITRF[i], scale_arrow) -
                 all_posy_proj[i])
            )  # l'angle d'orientation de l'ellipsoide, avec 0 au nord et +90 a l'ouest

            e = Ellipse(
                xy=(x_end_arrow_ok, y_end_arrow_ok),
                width=np.multiply(2, incve_ITRF[i]) * scale_ellipse,
                height=np.multiply(2, incvn_ITRF[i]) * scale_ellipse,
                angle=a
            )  #multiplication par 2 pour obtenir la largeur et la hauteur de l'ellipse

            # STATION NAME
            if name_stats:
                offset_x_ok, offset_y_ok = utils.axis_data_coords_sys_transform(
                    ax, name_stats_offset[0], name_stats_offset[1])
                plt.text(all_posx_proj[i] + offset_x_ok,
                         all_posy_proj[i] + offset_y_ok,
                         station_etude[i],
                         fontsize=name_stats_font_size)

            # ELIPSES
            if plot_ellipses:
                ax.add_artist(e)
                e.set_clip_box(ax.bbox)
                e.set_edgecolor('none')
                e.set_facecolor('black')
                e.set_alpha(0.3)
                e.set_zorder(1)

    else:  # Champ de vitesses verticales ITRF
        ############### PLOT FLECHES
        Text = []
        for i in range(nstation):

            ######### Exclude point if not in range
            #latm,latM,lonm,lonM
            bool_good_lat = latm < all_pos[i][0] < latM
            bool_good_lon = lonm < all_pos[i][1] < lonM
            if exclude_points_out_of_range and not (bool_good_lat
                                                    and bool_good_lon):
                print("INFO : exclude point because out of range")
                continue

            ######### AJUSTEMENT SI FLECHES TROP GRANDES
            x_end_arrow, y_end_arrow = all_posx_proj[i], all_posy_proj[
                i] + np.multiply(plot_vertical_ITRF[i], scale_arrow)

            x_end_axis_ref, y_end_axis_ref = utils.axis_data_coords_sys_transform(
                ax, x_end_arrow, y_end_arrow, inverse=True)

            if (y_end_axis_ref < 0.) and shorten_oversized_arrows:
                shortened_arrow = True
                x_end_arrow_ok = x_end_arrow
                _, y_end_arrow_ok = utils.axis_data_coords_sys_transform(
                    ax, x_end_axis_ref, 0, inverse=False)
            elif (y_end_axis_ref > 1.) and shorten_oversized_arrows:
                shortened_arrow = True
                x_end_arrow_ok = x_end_arrow
                _, y_end_arrow_ok = utils.axis_data_coords_sys_transform(
                    ax, x_end_axis_ref, 1., inverse=False)
            else:
                shortened_arrow = False
                x_end_arrow_ok = x_end_arrow
                y_end_arrow_ok = y_end_arrow

            ######### FIN AJUSTEMENT SI FLECHES TROP GRANDES

            ### SELECT ARROW PROPERTY DEPENDING ON THE TYPE
            if plot_vertical_ITRF[i] > 0 and not shortened_arrow:
                arrow_prop_dict_V = arrow_prop_dict_V_up
            elif plot_vertical_ITRF[i] > 0 and shortened_arrow:
                arrow_prop_dict_V = arrow_prop_dict_V_up_short
            elif plot_vertical_ITRF[i] <= 0 and not shortened_arrow:
                arrow_prop_dict_V = arrow_prop_dict_V_down
            elif plot_vertical_ITRF[i] <= 0 and shortened_arrow:
                arrow_prop_dict_V = arrow_prop_dict_V_down_short

            ### PLOT
            ax.annotate(s='',
                        xy=(x_end_arrow_ok, y_end_arrow_ok),
                        xytext=(all_posx_proj[i], all_posy_proj[i]),
                        arrowprops=arrow_prop_dict_V,
                        annotation_clip=False)
            #xy point arrivee de la fleche, xytext l'origine de la fleche

            ### STATION NAME
            if name_stats:
                offset_x_ok, offset_y_ok = utils.axis_data_coords_sys_transform(
                    ax, name_stats_offset[0], name_stats_offset[1])

                Text.append(
                    plt.text(all_posx_proj[i] + offset_x_ok,
                             all_posy_proj[i] + offset_y_ok,
                             station_etude[i],
                             fontsize=name_stats_font_size))

            ############### PLOT ELLIPSES
            # angle de l'ellipse dépend de la direction du vecteur vitesse
            a = math.atan(
                (all_posx_proj[i] + np.multiply(
                    plot_vertical_ITRF[i], scale_arrow) - all_posx_proj[i]) /
                (all_posy_proj[i] + np.multiply(
                    plot_vertical_ITRF[i], scale_arrow) - all_posy_proj[i])
            )  # l'angle d'orientation de l'ellipsoide, avec 0 au nord et +90 a l'ouest

            # weird previous xy definition
            # [all_posx_proj[i]+np.multiply(plot_vertical_ITRF[i],0),all_posy_proj[i]+0.85*np.multiply(plot_vertical_ITRF[i],scale_arrow)]

            e = Ellipse(
                xy=(x_end_arrow_ok, y_end_arrow_ok),
                width=np.multiply(2, incplot_vertical_ITRF[i]) * scale_ellipse,
                height=np.multiply(2, incplot_vertical_ITRF[i]) *
                scale_ellipse,
                angle=a
            )  #multiplication par 2 pour obtenir la largeur et la hauteur de l'ellipse
            # ax.plot(all_posx_proj[i]+np.multiply(plot_vertical_ITRF[i],0),all_posy_proj[i]+np.multiply(plot_vertical_ITRF[i],scale_arrow),'xkcd:green',marker='.',linestyle='none',markersize=4,lw=4,zorder=20) #point rouge à la station, zorder indique l'ordre vertical de dessin sur la carte, les nb elevés sont dessinés les plus hauts

            ax.add_artist(e)
            e.set_clip_box(ax.bbox)
            e.set_edgecolor('none')
            e.set_facecolor('black')
            e.set_alpha(0.3)
            e.set_zorder(1)

    ############### LEGENDE
    legend_arrow_length_label = legend_arrow_length[0]
    legend_ellipse_size_label = legend_ellipse_size[0]
    legend_arrow_length_metric = legend_arrow_length[1]
    legend_ellipse_size_metric = legend_ellipse_size[1]
    legend_position_x = legend_position[0]
    legend_position_y = legend_position[1]

    ######## Fleche de Legende
    ### origine de la fleche de legende
    xl, yl = utils.axis_data_coords_sys_transform(ax,
                                                  legend_position_x,
                                                  legend_position_y + 0.02,
                                                  inverse=False)
    ### fin de la fleche de legende
    xe, ye = xl + np.multiply(legend_arrow_length_metric, scale_arrow), yl

    plt.annotate(
        s='', xy=(xe, ye), xytext=(xl, yl), arrowprops=arrow_prop_dict
    )  #xy point arrivee de la fleche, xytext l'origine de la fleche

    props = dict(boxstyle='round', facecolor='black', alpha=0)
    ax.text(legend_position_x,
            legend_position_y + 0.035,
            'Velocity : ' + legend_arrow_length_label,
            transform=ax.transAxes,
            fontsize=11,
            color='black',
            verticalalignment='bottom',
            bbox=props)  # place a text box in upper left in axes coords

    ######## Légende de l'ellipse d'incertitude
    ax.text(legend_position_x,
            legend_position_y,
            '+/- ' + legend_ellipse_size_label + ' (radius)',
            transform=ax.transAxes,
            fontsize=11,
            color='black',
            verticalalignment='top',
            bbox=props)
    ells_legend = Ellipse(xy=[xe, ye],
                          width=np.multiply(
                              2,
                              np.multiply(legend_ellipse_size_metric,
                                          scale_ellipse)),
                          height=np.multiply(
                              2,
                              np.multiply(legend_ellipse_size_metric,
                                          scale_ellipse)),
                          angle=a)

    if plot_ellipses:
        ax.add_artist(ells_legend)
        ells_legend.set_clip_box(ax.bbox)
        ells_legend.set_edgecolor('none')
        ells_legend.set_facecolor('black')
        ells_legend.set_alpha(0.3)
        ells_legend.set_zorder(1)

    ############### FINITION

    for T in Text:  #Put label in front
        T.set_zorder(100)

    if adjust_text:
        from adjustText import adjust_text
        adjust_text(
            Text,
            on_basemap=True)  #arrowprops=dict(arrowstyle='->', color='red')

    plt.tight_layout()

    if full_return:
        return fig, ax, m, Text
    else:
        return fig, ax, m, Text
    lon = DS['lon'][:]
    lat = DS['lat'][:]
    time = DS['time'][:]
    area = DS['area'][:] / (1e5)

    ## Plot
    # set up orthographic map projection with
    # perspective of satellite looking down at 50N, 100W.
    # use low resolution coastlines.
    #map = Basemap(projection='hammer',lon_0=180)
    map = Basemap(llcrnrlon=0.,llcrnrlat=-50.,urcrnrlon=360.,urcrnrlat=50.,\
                resolution='l',projection='merc')
    # draw coastlines, country boundaries, fill continents.
    map.fillcontinents(color='lightgray',zorder=1)
    map.drawcoastlines(color='k',linewidth=0.7,zorder=10)
    map.drawcountries(color='k',linewidth=0.5,zorder=10)
    # draw the edge of the map projection region (the projection limb)
    map.drawmapboundary()
    # draw lat/lon grid lines every 30 degrees.
    map.drawmeridians(np.arange(0,360,30),zorder=15)
    map.drawparallels(np.arange(-90,90,30),zorder=15)


    x, y = map(lon, lat)
    map.scatter(x,y, area, marker='o',facecolors='none', edgecolors='blue',zorder=5)

    plt.title(out_str)

    print(fout)
    plt.savefig(fout, dpi = 150,bbox_inches='tight')
Example #46
0
def fr2ghi2png(url,
               colormapPath,
               colormapName,
               dirDest,
               lat_name,
               lon_name,
               data_name,
               geos=False):

    # Dataset is the class behavior to open the file
    # and create an instance of the ncCDF4 class
    nc_fid = netCDF4.Dataset(url, 'r')

    t_coverage = repr(nc_fid.getncattr('time_coverage_start'))
    # print t_coverage

    ds_name = repr(nc_fid.getncattr('dataset_name'))
    # print ds_name

    date = re.search('\'(.*?)\'', t_coverage).group(1)
    print(date)

    channel = re.search('-M\d(.*?)_', ds_name).group(1)
    print(channel)

    yl = date[0:4]
    yy = date[2:4]
    mt = date[5:7]
    dd = date[8:10]
    hh = date[11:13]
    mm = date[14:16]
    ss = date[17:19]

    str_date = str(dd) + '/' + str(mt) + '/' + str(yl) + " " + str(
        hh) + ":" + str(mm)
    date = datetime.datetime.strptime(
        str_date, '%d/%m/%Y %H:%M') - datetime.timedelta(hours=3)
    name = channel + " " + date.strftime('%d-%m-%Y %H:%M')
    filename = channel + "_" + yy + mt + dd + "_" + hh + mm + ss
    # print "name: " + name

    # extract/copy the data
    data = nc_fid.variables[data_name][:]

    if data_name == 'CMI' or data_name == 'Rad':
        # Satellite height
        sat_h = nc_fid.variables[
            'goes_imager_projection'].perspective_point_height
        # Satellite longitude
        sat_lon = nc_fid.variables[
            'goes_imager_projection'].longitude_of_projection_origin
        # Satellite sweep
        sat_sweep = nc_fid.variables['goes_imager_projection'].sweep_angle_axis
        X = nc_fid.variables[lon_name][:]  # longitud, eje X
        Y = nc_fid.variables[lat_name][:]  # latitud, eje Y

        scene_id_val = repr(nc_fid.getncattr('scene_id'))
        scene_id = re.search('\'(.*?)\'', scene_id_val).group(1)

    nc_fid.close()

    print("Realizando pasaje a K en C13 y truncamiento en los otros")

    for d in numpy.nditer(data, op_flags=['readwrite']):
        d = truncUno(d)
    data *= 100

    #######################################
    #######################################

    name = "GHI " + date.strftime('%d-%m-%Y %H:%M')

    nc_fid_ghi = netCDF4.Dataset(url, 'r')

    data = nc_fid_ghi.variables[data_name][:]
    X = nc_fid_ghi.variables[lon_name][:]  # longitud, eje X
    Y = nc_fid_ghi.variables[lat_name][:]  # latitud, eje Y
    nc_fid_ghi.close()

    for d in numpy.nditer(data, op_flags=['readwrite']):
        d = truncUno(d)
    data *= 100

    X *= sat_h
    Y *= sat_h

    vmin = 0.0
    vmax = 1200.0

    ax = Basemap(projection='merc',\
        llcrnrlat=-35.00,urcrnrlat=-30.00,\
        llcrnrlon=-58.77,urcrnrlon=-53.00,\
        resolution='f')
    projection = Proj(proj='geos',
                      h=sat_h,
                      lon_0=sat_lon,
                      sweep=sat_sweep,
                      ellps='WGS84')

    x_mesh, y_mesh = numpy.meshgrid(X, Y)
    lons, lats = projection(x_mesh, y_mesh, inverse=True)
    x, y = ax(lons, lats)

    ax.drawcoastlines(linewidth=0.40)
    ax.drawcountries(linewidth=0.40)
    ax.drawstates(linewidth=0.20)

    rincon_de_artigas_poly(ax)

    par = ax.drawparallels(numpy.arange(-40, -20, 2),
                           labels=[1, 0, 0, 0],
                           linewidth=0.0,
                           fontsize=7,
                           color='white')
    mer = ax.drawmeridians(numpy.arange(-70, -40, 2),
                           labels=[0, 0, 1, 0],
                           linewidth=0.0,
                           fontsize=7,
                           color='white')
    setcolor(par, 'white')
    setcolor(mer, 'white')

    print("Calculando GHI...")

    Isc = 1367.0
    # JPTv1
    a = 0.602
    b = 0.576
    c = -0.341
    d = -13.149

    def FR2GHI(lat, lon, fr):
        Cz, Gamma = cosSolarZenithAngle(lat, lon, date, 0)
        ghi = 0.
        if Cz > 0.:
            Fn = FnFunc(Gamma)
            ghi = Isc * Fn * Cz * (a + b * Cz + c * Cz) + d * fr
            if Isc * Fn * Cz != 0:
                Kt = ghi / (Isc * Fn * Cz)
                Kt = numpy.clip(Kt, 0.09, 0.85)
            ghi = Kt * Isc * Fn * Cz
        return ghi

    FR2GHI_vect = numpy.vectorize(FR2GHI, otypes=[float])

    GHI = FR2GHI_vect(lats, lons, data)

    ticks = [0, 200, 400, 600, 800, 1000, 1200]
    ticksLabels = ticks

    cmap = gmtColormap('irradiancia_v6', colormapPath, 2048)
    cs = ax.pcolormesh(x, y, GHI, vmin=vmin, vmax=vmax, cmap=cmap)

    plt.clim(vmin, vmax)

    # agrego el colorbar
    cbar = ax.colorbar(cs, location='bottom', ticks=ticks)  # , pad='3%'
    cbar.ax.set_xlabel(
        "Irradiancia solar global en plano horizontal ($W/m^2$)",
        fontsize=7,
        color='white')
    cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='white')

    # agrego el logo en el documento
    logo_bw = plt.imread('/sat/PRS/dev/PRS-sat/PRSgoes/logo_300_bw.png')
    plt.figimage(logo_bw, xo=5, yo=5)

    if not os.path.isdir(dirDest + channel + '/' + yl + '/ghi'):
        os.mkdir(dirDest + channel + "/" + yl + '/ghi')
    # if

    outPath = dirDest + channel + "/" + yl + "/ghi/"

    whitePath = outPath + filename + '_ghi_white.png'  # determino el nombre del archivo a escribir
    outPath = outPath + filename + '_ghi.png'  # determino el nombre del archivo a escribir

    x_coord = 109
    y_coord = -53

    Noche = numpy.sum(data) <= 0.

    if Noche:  # print "es noche"
        plt.annotate("NOCHE", (0, 0), (204, 15),
                     color='white',
                     xycoords='axes fraction',
                     textcoords='offset points',
                     va='top',
                     fontsize=10,
                     family='monospace')

    plt.annotate(name + " UY", (0, 0), (x_coord, y_coord),
                 xycoords='axes fraction',
                 textcoords='offset points',
                 va='top',
                 fontsize=11,
                 family='monospace',
                 color='white')
    plt.savefig(outPath, bbox_inches='tight', dpi=400,
                transparent=True)  # , facecolor='#4F7293'

    cbar.ax.set_xlabel(
        "Irradiancia solar global en plano horizontal ($W/m^2$)",
        fontsize=7,
        color='black')
    cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='black')

    # WHITE

    setcolor(par, 'black')
    setcolor(mer, 'black')

    logo_color = plt.imread('/sat/PRS/dev/PRS-sat/PRSgoes/logo_300_color.png')
    plt.figimage(logo_color, xo=5, yo=5)

    nota_ghi_w = plt.annotate(name + " UY", (0, 0), (x_coord, y_coord),
                              xycoords='axes fraction',
                              textcoords='offset points',
                              va='top',
                              fontsize=11,
                              family='monospace',
                              color='black')
    plt.savefig(whitePath,
                bbox_inches='tight',
                dpi=400,
                transparent=False,
                facecolor='white')  # , facecolor='#4F7293'

    copyfile(outPath, dirDest + channel + '_ghi.png')
    copyfile(whitePath, dirDest + channel + '_ghi_white.png')

    print("NUBOSIDAD")
    # NUBOSIDAD

    plt.clf()

    ax.drawcoastlines(linewidth=0.40)
    ax.drawcountries(linewidth=0.40)
    ax.drawstates(linewidth=0.20)

    rincon_de_artigas_poly(ax)

    par = ax.drawparallels(numpy.arange(-40, -20, 2),
                           labels=[1, 0, 0, 0],
                           linewidth=0.0,
                           fontsize=7,
                           color='white')
    mer = ax.drawmeridians(numpy.arange(-70, -40, 2),
                           labels=[0, 0, 1, 0],
                           linewidth=0.0,
                           fontsize=7,
                           color='white')
    setcolor(par, 'white')
    setcolor(mer, 'white')

    vmin = 0.0
    vmax = 100.0

    ticks = [0, 20, 40, 60, 80, 100]
    ticksLabels = ticks

    cmap = gmtColormap('nubosidad', colormapPath, 2048)
    cs = ax.pcolormesh(x, y, data, vmin=vmin, vmax=vmax, cmap=cmap)

    plt.clim(vmin, vmax)

    # agrego el colorbar
    cbar = ax.colorbar(cs, location='bottom', ticks=ticks)  # , pad='3%'
    cbar.ax.set_xlabel("Nubosidad (%)", fontsize=7, color='white')
    cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='white')

    plt.figimage(logo_bw, xo=5, yo=5)

    outPath = dirDest + channel + "/" + yl + "/ghi/"

    outPath = outPath + filename + '_cloud.png'  # determino el nombre del archivo a escribir
    whitePath = outPath + filename + '_cloud_white.png'  # determino el nombre del archivo a escribir

    x_coord = 109
    y_coord = -53

    plt.annotate("C02 " + date.strftime('%d-%m-%Y %H:%M') + " UY", (0, 0),
                 (x_coord, y_coord),
                 xycoords='axes fraction',
                 textcoords='offset points',
                 va='top',
                 fontsize=11,
                 family='monospace',
                 color='white')
    plt.draw()
    plt.savefig(outPath, bbox_inches='tight', dpi=400,
                transparent=True)  # , facecolor='#4F7293'

    # CLOUD WHITE

    setcolor(par, 'black')
    setcolor(mer, 'black')

    logo_color = plt.imread('/sat/PRS/dev/PRS-sat/PRSgoes/logo_300_color.png')
    plt.figimage(logo_color, xo=5, yo=5)

    plt.annotate("C02 " + date.strftime('%d-%m-%Y %H:%M') + " UY", (0, 0),
                 (x_coord, y_coord),
                 xycoords='axes fraction',
                 textcoords='offset points',
                 va='top',
                 fontsize=11,
                 family='monospace',
                 color='black')
    plt.savefig(whitePath,
                bbox_inches='tight',
                dpi=400,
                transparent=False,
                facecolor='white')  # , facecolor='#4F7293'

    copyfile(outPath, dirDest + channel + '_cloud.png')
    copyfile(whitePath, dirDest + channel + '_cloud_white.png')

    plt.close()
Example #47
0
def cs_figure(profile,
              structures,
              min_length=None,
              max_length=None,
              ymin=None,
              ylim=None,
              extrap_range=300,
              contacts=None,
              locations=None,
              id_measurements=False,
              save=False,
              save_name='cross_section.pdf'):
    if min_length is None:
        min_length = int(min(profile.length.tolist()))
    if max_length is None:
        max_length = int(max(profile.length.tolist()))
    if ymin is None:
        ymin = int(min(profile.elevation.tolist()) * 0.5)
    if ylim is None:
        ylim = int(max(profile.elevation.tolist()) * 1.3)
    min_ind = profile.loc[profile['length'] == find_nearest(
        np.array(profile.length.tolist()), min_length)].index.tolist()[0]
    med_ind = profile.loc[profile['length'] == find_nearest(
        np.array(profile.length.tolist()), (max_length) / 2)].index.tolist()[0]
    max_ind = profile.loc[profile['length'] == find_nearest(
        np.array(profile.length.tolist()), max_length)].index.tolist()[0]
    min_cs_lat = profile['lat'][min_ind]
    med_cs_lat = profile['lat'][med_ind]
    max_cs_lat = profile['lat'][max_ind]
    min_cs_lon = profile['lon'][min_ind]
    med_cs_lon = profile['lon'][med_ind]
    max_cs_lon = profile['lon'][max_ind]

    if locations:
        loc_coor = {}
        for location in locations:
            loc_mid = np.average(
                [locations[location][0], locations[location][1]])
            loc_ind = profile.loc[profile['length'] == find_nearest(
                np.array(profile.length.tolist()), loc_mid)].index.tolist()[0]
            loc_lat = profile['lat'][loc_ind]
            loc_lon = profile['lon'][loc_ind]
            loc_coor[location] = [loc_lat, loc_lon]

    plt.figure(figsize=(12, 8))
    ax1 = plt.subplot2grid((2, 3), (0, 0), colspan=1)
    m = Basemap(projection='merc',
                llcrnrlat=46.2,
                urcrnrlat=48,
                llcrnrlon=-91,
                urcrnrlon=-88,
                resolution='i')  #lat_ts=-25
    m.drawrivers(color='#99ffff')
    m.drawcoastlines()
    m.drawmapboundary(fill_color='#99ffff')
    m.fillcontinents(color='#cc9966', lake_color='#99ffff')
    parallels = [min_cs_lat]  #np.arange(-90,90,2.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
    meridians = [min_cs_lon]  #np.arange(0.,360.,2.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)
    X, Y = m([min_cs_lon, max_cs_lon, max_cs_lon, min_cs_lon, min_cs_lon],
             [max_cs_lat, max_cs_lat, min_cs_lat, min_cs_lat, max_cs_lat])
    m.plot(X, Y, color='k', markersize=300, zorder=50)

    ax2 = plt.subplot2grid((2, 3), (0, 1), colspan=1)
    zoom_rescale = abs(0.5 * (max(profile.length) / 111100))
    m = Basemap(projection='merc',
                llcrnrlat=med_cs_lat - zoom_rescale,
                urcrnrlat=med_cs_lat + zoom_rescale,
                llcrnrlon=med_cs_lon - 2 * zoom_rescale,
                urcrnrlon=med_cs_lon + 2 * zoom_rescale,
                resolution='i')  #lat_ts=-25
    m.drawrivers(color='#99ffff')
    m.drawcoastlines()
    m.drawmapboundary(fill_color='#99ffff')
    m.fillcontinents(color='#cc9966', lake_color='#99ffff')
    parallels = np.arange(-90, 90, 2.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
    meridians = np.arange(0., 360., 2.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)
    X, Y = m([profile['lon'][min_ind], profile['lon'][max_ind]],
             [profile['lat'][min_ind], profile['lat'][max_ind]])
    m.plot(X, Y, linestyle='dotted', linewidth=2, zorder=50)
    if locations:
        for location in locations:
            X, Y = m(loc_coor[location][1], loc_coor[location][0])
            m.scatter(X, Y, label=location, color='r', zorder=51)
    plt.legend()

    ax3 = plt.subplot2grid((2, 3), (0, 2), colspan=1)
    ax3.plot(profile.length.tolist(), profile.elevation.tolist())
    ax3.text(0,
             1,
             '{:.5}\n{:.5}'.format(profile.lat.tolist()[0],
                                   profile.lon.tolist()[0]),
             transform=ax3.transAxes,
             bbox=dict(facecolor='white', edgecolor='white'),
             zorder=50)
    ax3.text(1,
             1,
             '{:.5}\n{:.5}'.format(profile.lat.tolist()[len(profile) - 1],
                                   profile.lon.tolist()[len(profile) - 1]),
             transform=ax3.transAxes,
             bbox=dict(facecolor='white', edgecolor='white'),
             zorder=50)
    plt.xlim(min(profile.length), max(profile.length))
    plt.tight_layout()

    ax4 = plt.subplot2grid((2, 3), (1, 0), colspan=3)
    plt.plot(profile.length.tolist(), profile.elevation.tolist())
    contact_strat = {}
    strat = 0
    structures = structures.loc[structures['length'] >= min_length].loc[
        structures['length'] <= max_length]
    structures.reset_index(inplace=True, drop=True)
    for n in range(len(structures)):
        if structures['length'][n] >= min_length and structures['length'][
                n] <= max_length:
            x_linspace = np.linspace(structures['length'][n],
                                     max(profile.length.tolist()))
            y = structures['slope'][n] * (x_linspace - structures['length'][n]
                                          ) + structures['elevation'][n]
            if n > 0:
                sep = structures['length'][n] - structures['length'][n - 1]
            else:
                sep = 0
            plt.plot(x_linspace, y, 'r')
            if id_measurements == True:
                site_name = str(structures['id'][n])
                plt.text(x_linspace[0],
                         y[0],
                         site_name,
                         bbox=dict(facecolor='white', edgecolor='white'),
                         horizontalalignment='center')
            dip_d_angle = calc_dip_trend_diff(calc_cs_trend(profile),
                                              structures['dip_d'][n])
            extrap_strat = strat
            strat += sep * np.cos(np.deg2rad(dip_d_angle)) * np.sin(
                np.deg2rad(abs(structures['dip'][n])))
            lab_height = (ylim - max(y)) * (0.1 + 0.1 *
                                            (n % 6))  #(30 + (n * 10)%60)*
            plt.text(structures['length'][n],
                     max(y) + lab_height,
                     '{0}'.format(int(strat)),
                     horizontalalignment='center')
            plt.vlines(structures['length'][n],
                       structures['elevation'][n],
                       max(y) + lab_height - 4,
                       linestyles='dotted')
            if contacts:
                for contact in contacts:
                    if n == 0:
                        contact_strat[contact] = extrap_strat + (
                            contacts[contact] - structures['length'][n]
                        ) * np.sin(np.deg2rad(abs(structures['corr_dip'][n])))
                    elif contacts[contact] <= structures['length'][
                            n] and contacts[contact] >= structures['length'][
                                n - 1]:
                        contact_strat[contact] = extrap_strat + (
                            contacts[contact] -
                            structures['length'][n - 1]) * np.sin(
                                np.deg2rad(abs(structures['corr_dip'][n - 1])))
            if n > 0 and n < len(structures) - 1:
                if structures['length'][n] - structures['length'][
                        n - 1] > extrap_range:
                    for extrap in range(
                            int(structures['length'][n - 1]) + extrap_range,
                            int(structures['length'][n]), extrap_range):
                        extrap_strat += extrap_range * np.cos(
                            np.deg2rad(dip_d_angle)) * np.sin(
                                np.deg2rad(abs(structures['dip'][n - 1])))
                        text_height = 30 + (extrap * 10) % 60
                        plt.text(extrap,
                                 profile.loc[profile['length'] == find_nearest(
                                     profile['length'], extrap)]['elevation'] +
                                 text_height,
                                 '{0}'.format(int(extrap_strat)),
                                 horizontalalignment='center')
                        plt.vlines(
                            extrap,
                            profile.loc[profile['length'] == find_nearest(
                                profile['length'], extrap)]['elevation'],
                            profile.loc[profile['length'] == find_nearest(
                                profile['length'], extrap)]['elevation'] +
                            text_height - 5,
                            linestyles='dotted')
            elif n == len(structures) - 1:
                if max_length - structures['length'][n] > extrap_range:
                    extrap_strat = strat
                    for extrap in range(
                            int(structures['length'][n]) + extrap_range,
                            max_length, extrap_range):
                        extrap_strat += extrap_range * np.cos(
                            np.deg2rad(dip_d_angle)) * np.sin(
                                np.deg2rad(abs(structures['dip'][n])))
                        text_height = 30 + (extrap * 10) % 60
                        plt.text(extrap,
                                 profile.loc[profile['length'] == find_nearest(
                                     profile['length'], extrap)]['elevation'] +
                                 text_height,
                                 '{0}'.format(int(extrap_strat)),
                                 horizontalalignment='center')
                        plt.vlines(
                            extrap,
                            profile.loc[profile['length'] == find_nearest(
                                profile['length'], extrap)]['elevation'],
                            profile.loc[profile['length'] == find_nearest(
                                profile['length'], extrap)]['elevation'] +
                            text_height - 5,
                            linestyles='dotted')
                extrap = int(max(profile.length))
                total_strat = extrap_strat + extrap_range * np.cos(
                    np.deg2rad(dip_d_angle)) * np.sin(
                        np.deg2rad(abs(structures['dip'][n])))
            elif n == 0:
                if structures['length'][n] > extrap_range:
                    for extrap in range(
                            int(min(structures.length)) - extrap_range,
                            min_length, -extrap_range):
                        extrap_strat += -extrap_range * np.cos(
                            np.deg2rad(dip_d_angle)) * np.sin(
                                np.deg2rad(abs(structures['dip'][0])))
                        text_height = 30 + (extrap * 10) % 60
                        plt.text(extrap,
                                 profile.loc[profile['length'] == find_nearest(
                                     profile['length'], extrap)]['elevation'] +
                                 text_height,
                                 '{0}'.format(int(extrap_strat)),
                                 horizontalalignment='center')
                        plt.vlines(
                            extrap,
                            profile.loc[profile['length'] == find_nearest(
                                profile['length'], extrap)]['elevation'],
                            profile.loc[profile['length'] == find_nearest(
                                profile['length'], extrap)]['elevation'] +
                            text_height - 5,
                            linestyles='dotted')
    if contacts:
        for contact in contacts:
            xline = float(contacts[contact])
            ymax = profile.loc[profile['length'] == find_nearest(
                profile['length'], xline)]['elevation']
            plt.vlines(xline,
                       0,
                       float(ymax),
                       colors=np.random.rand(3),
                       linewidth=3.0,
                       linestyles='dotted',
                       label=contact)
            y_place = np.random.randint(ymax + 0.1 * (ylim - ymin),
                                        ylim - 0.1 * (ylim - ymin))
            plt.text(xline,
                     y_place + 5,
                     '{0}'.format(int(contact_strat[contact])),
                     color='g',
                     horizontalalignment='center')
            plt.vlines(xline, ymax, y_place, linestyles='dotted')
    if locations:
        for location in locations:
            y_rng = []
            x_rng = np.linspace(locations[location][0], locations[location][1])
            for x in x_rng:
                y_rng.append(
                    float(profile.loc[profile['length'] == find_nearest(
                        profile['length'], x)]['elevation']))
            vertices = [(x_rng[0], 0)] + list(zip(x_rng,
                                                  y_rng)) + [(x_rng[-1], 0)]
            poly = Polygon(vertices,
                           facecolor='r',
                           alpha=0.4,
                           edgecolor='none',
                           label=location)
            plt.gca().add_patch(poly)

    ax4.text(0,
             1,
             '{:.5}\n{:.5}'.format(profile['lat'][min_ind],
                                   profile['lon'][min_ind]),
             color='r',
             transform=ax4.transAxes,
             bbox=dict(facecolor='white', edgecolor='white'),
             verticalalignment='top',
             zorder=50)
    ax4.text(1,
             1,
             '{:.5}\n{:.5}'.format(profile['lat'][max_ind],
                                   profile['lon'][max_ind]),
             color='r',
             transform=ax4.transAxes,
             bbox=dict(facecolor='white', edgecolor='white'),
             verticalalignment='top',
             zorder=50)

    plt.xlabel('meters')
    plt.ylabel('meters')

    plt.xlim(min_length, max_length)
    plt.ylim(ymin, ylim)

    plt.title('Bearing = {:.4}°, Total Strat = {:.4} km'.format(
        calc_cs_trend(profile), total_strat / 1000))

    if save == True:
        plt.savefig(str(save_name))

    plt.legend()
    plt.show()
def metpyplot(shpFiles, lonlat, mLon, mLat, mTem):
    # 初始化
    #绘图参数设置
    isStationInfoOn = False  #站点信息是否标注
    isaxInfoOn = False  # 坐标轴信息是否标注
    cmap = cmaps.BlAqGrYeOrReVi200  #色标选择 http://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml 参考该网址 MPL_YlOrRd  amwg256
    legendRange = [int(min(mTem)), math.ceil(max(mTem))]
    fbl = 0.05  #克里金插值空间分辨率
    sebiaoNums = 15  #色标个数
    picTitle = 'Temperature'
    zuobiaoSetInter = 0.5  #坐标轴经纬度间隔设置

    #    shpPath=r'./shp/TJ/'
    #    shpName='TJ_all'
    ##    bjName='TJ_bj'
    shpFile = shpFiles[0]
    #    bjshp=shpPath+bjName

    #天津经纬度范围设置
    #    llat=38.5
    #    ulat=40.3
    #    llon=116.7
    #    ulon=118.05
    llon = lonlat[0]
    ulon = lonlat[1]
    llat = lonlat[2]
    ulat = lonlat[3]

    #    fig=plt.figure(figsize=(16,9))
    plt.rc('font', size=15, weight='bold')
    #    ax=fig.add_subplot(111)

    # 底图读取及地图设置
    m=Basemap(llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,\
        projection='cyl',resolution='c')   # 等距投影
    m.readshapefile(shpFile, 'Name', linewidth=1, color='k')
    # 绘制经纬线
    parallels = np.arange(llat, ulat, 0.5)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)  # 绘制纬线

    meridians = np.arange(llon, ulon, 0.5)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)  # 绘制经线

    # 坐标系经纬度转换
    xllon, yllat = m(llon, llat)
    xulon, yulat = m(ulon, ulat)
    xmLon, ymLat = m(mLon, mLat)

    # meshgrid set the grid range
    gridx = np.arange(xllon, xulon, fbl)
    gridy = np.arange(yllat, yulat, fbl)

    Xlon, Ylat = np.meshgrid(gridx, gridy)

    #插值处理
    #    OK=OrdinaryKriging(xmLon,ymLat,mTem,variogram_model='linear',
    #               verbose=False,enable_plotting=False)
    #    z,ss=OK.execute('grid',gridx,gridy)
    gx, gy, img = interpolate(xmLon, ymLat, mTem, \
                              interp_type='linear', hres=fbl)

    levels = np.linspace(legendRange[0], legendRange[1], sebiaoNums)
    cs = m.contourf(gx, gy, img, levels, cmap=cmap)
    m.colorbar(cs)

    #    cf=m.contourf(Xlon,Ylat,z,levels=levels,cmap=cmap)
    #    m.colorbar(cf,location='right',format='%.1f',size=0.3,\
    #            ticks=np.linspace(legendRange[0],legendRange[1],sebiaoNums),label='单位:℃')
    #
    # 添加站名信息
    if isStationInfoOn == True:
        m.scatter(xmLon, ymLat, c='k', s=10, marker='o')
        for i in range(0, len(xmLon)):
            #            pass
            plt.text(xmLon[i],
                     ymLat[i],
                     stationName[i],
                     va='bottom',
                     fontsize=12)
        # plt.text(xmLon[i],ymLat[i],mTem[i],va='top',fontsize=12)

        plt.title(picTitle)

    # 坐标轴标注
    if isaxInfoOn == True:
        lon_label = []
        lat_label = []
        lon_num = np.arange(xllon, xulon, zuobiaoSetInter)
        for lon in lon_num:
            lon_label.append(str(lon) + '°E')

        lat_num = np.arange(yllat, yulat, zuobiaoSetInter)
        for lat in lat_num:
            lat_label.append(str(lat) + '°N')

        plt.yticks(lat_num, lat_label)
        plt.xticks(lon_num, lon_label)

    # 白化
#    maskout.shp2clip(cf,ax,bjshp,0.005588)  #0.005588为gis图周长信息

# picture introduction
    plt.show()
Example #49
0
def run(FILE_NAME):
    GEO_FILE_NAME = 'MYD03.A2002226.0000.005.2009193071127.hdf'
    GEO_FILE_NAME = os.path.join(os.environ['HDFEOS_ZOO_DIR'], GEO_FILE_NAME)
    DATAFIELD_NAME = 'EV_1KM_Emissive'

    if USE_NETCDF4:
        from netCDF4 import Dataset
        nc = Dataset(FILE_NAME)

        # Just read the first level, Band 20.
        # lat/lon resolution.
        data = nc.variables[DATAFIELD_NAME][0, :, :].astype(np.float64)

        # Retrieve the geolocation data from MYD03 product.
        nc_geo = Dataset(GEO_FILE_NAME)
        longitude = nc_geo.variables['Longitude'][:]
        latitude = nc_geo.variables['Latitude'][:]

        # Retrieve attributes.
        units = nc.variables[DATAFIELD_NAME].radiance_units
        long_name = nc.variables[DATAFIELD_NAME].long_name

        # The scale and offset attributes do not have standard names in this
        # case, so we have to apply the scaling equation ourselves.
        scale_factor = nc.variables[DATAFIELD_NAME].radiance_scales[0]
        add_offset = nc.variables[DATAFIELD_NAME].radiance_offsets[0]
        valid_range = nc.variables[DATAFIELD_NAME].valid_range
        _FillValue = nc.variables[DATAFIELD_NAME]._FillValue
        valid_min = valid_range[0]
        valid_max = valid_range[1]

        # Retrieve dimension name.
        dimname = nc.variables[DATAFIELD_NAME].dimensions[0]

    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data3D = hdf.select(DATAFIELD_NAME)
        data = data3D[0, :, :].astype(np.double)

        hdf_geo = SD(GEO_FILE_NAME, SDC.READ)

        # Read geolocation dataset from MOD03 product.
        lat = hdf_geo.select('Latitude')
        latitude = lat[:, :]
        lon = hdf_geo.select('Longitude')
        longitude = lon[:, :]

        # Retrieve attributes.
        attrs = data3D.attributes(full=1)
        lna = attrs["long_name"]
        long_name = lna[0]
        aoa = attrs["radiance_offsets"]
        add_offset = aoa[0][0]
        fva = attrs["_FillValue"]
        _FillValue = fva[0]
        sfa = attrs["radiance_scales"]
        scale_factor = sfa[0][0]
        vra = attrs["valid_range"]
        valid_min = vra[0][0]
        valid_max = vra[0][1]
        ua = attrs["radiance_units"]
        units = ua[0]

        # Retrieve dimension name.
        dim = data3D.dim(0)
        dimname = dim.info()[0]

    invalid = np.logical_or(data > valid_max, data < valid_min)
    invalid = np.logical_or(invalid, data == _FillValue)
    data[invalid] = np.nan
    data = (data - add_offset) * scale_factor
    data = np.ma.masked_array(data, np.isnan(data))

    # The data is close to the equator in Africa, so a global projection is
    # not needed.
    m = Basemap(projection='cyl',
                resolution='l',
                llcrnrlat=-5,
                urcrnrlat=30,
                llcrnrlon=5,
                urcrnrlon=45)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(0, 50, 10), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(0, 50., 10), labels=[0, 0, 0, 1])
    m.pcolormesh(longitude, latitude, data, latlon=True)
    cb = m.colorbar()
    cb.set_label(units, fontsize=8)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}\nat {2}=0'.format(basename,
                                          'Radiance derived from ' + long_name,
                                          dimname),
              fontsize=11)
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Example #50
0
#Plot data on the map
print('='*80)
print(datetime.now(), proc_start_date, '-', proc_end_date, 'Plotting data on the map')
plt.figure(figsize=(10, 10))

# sylender map
m = Basemap(projection='cyl', resolution='h', \
            llcrnrlat = Slat, urcrnrlat = Nlat, \
            llcrnrlon = Llon, urcrnrlon = Rlon)
m.drawcoastlines(linewidth=0.25)
m.drawcountries(linewidth=0.25)
#m.fillcontinents(color='coral',lake_color='aqua')
#m.drawmapboundary(fill_color='aqua')

m.drawparallels(np.arange(-90., 90., 10.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-180., 181., 15.), labels=[0, 0, 0, 1])

x, y = m(lon_array, lat_array) # convert to projection map

plt.pcolormesh(x, y, mean_array)
plt.colorbar(cmap='bwr', fraction=0.038, pad=0.04)

plt.title('MODIS AOD', fontsize=20)
plt.savefig(save_dir_name+'_'+proc_start_date+'-'+proc_end_date+'.png', bbox_inches='tight', dpi = 300)

working_time = (datetime.now() - cht_start_time) #total days for downloading
print(datetime.now(), proc_start_date, '-', proc_end_date, 'Map(image) is created ')
add_log.write('%s: %s-%s Map(image) is created...\n' % (datetime.now(), proc_start_date, proc_end_date))
print(datetime.now(), 'working time (sec) :', working_time)
print('='*80) 
Example #51
0
import matplotlib.pyplot as plt
import numpy as np
# set up orthographic map projection with
# perspective of satellite looking down at 50N, 100W.
# use low resolution coastlines.
map = Basemap(projection='merc', llcrnrlat=-50, urcrnrlat=50,
            llcrnrlon=-180, urcrnrlon=180, resolution='i')
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral',lake_color='aqua')
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary(fill_color='aqua')
# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(np.arange(0,360,30))
map.drawparallels(np.arange(-90,90,30))
# make up some data on a regular lat/lon grid.

nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1)

lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:])
lons = (delta*np.indices((nlats,nlons))[1,:,:])

print(lons)
print(lons.shape)

wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons))

mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.)
# compute native map projection coordinates of lat/lon grid.
x, y = map(lons*180./np.pi, lats*180./np.pi)
Example #52
0
parallel_steps = [44, 44.5, 45, 45.5]

plt.figure(figsize=(10, 10))
# chl
ax = plt.subplot(2, 2, 1)
ax.set_title('Chl')
current_cmap = plt.cm.get_cmap()
current_cmap.set_bad(color='white')

chl_mat.mask = chl_mat == -999

m = Basemap(llcrnrlat=min(lat0),urcrnrlat=max(lat0),\
     llcrnrlon=min(lon0),urcrnrlon=max(lon0), resolution='l')
x, y = np.meshgrid(lon0, lat0)
m.drawparallels(parallel_steps,
                labels=[1, 0, 0, 1],
                color='grey',
                linewidth=0.1)
m.drawmeridians(meridian_steps,
                labels=[1, 0, 0, 1],
                color='grey',
                linewidth=0.1)
m.drawcoastlines(linewidth=0.1)
m.imshow(chl_mat,origin='upper', extent=[min(lon0), max(lon0), min(lat0), max(lat0)],\
                                           norm=LogNorm(),cmap='rainbow',interpolation='nearest')

clb = plt.colorbar(fraction=0.046, pad=0.05, orientation='horizontal')
#    clb.ax.set_xlabel('Absolute Density (counts)')

# wtm
ax = plt.subplot(2, 2, 2)
ax.set_title('wtm(0 =< p1/(p1+p2) =< 1')
Example #53
0
m = Basemap(projection='merc',
            urcrnrlat=limits[1],
            urcrnrlon=limits[3],
            llcrnrlat=limits[0],
            llcrnrlon=limits[2])
m.drawcoastlines()
m.drawstates()
m.drawmeridians(lon,
                labels=[0, 0, 0, 1],
                fontsize=10,
                linewidth=1,
                dashes=(None, None),
                size=12)
m.drawparallels(lat,
                labels=[1, 0, 0, 0],
                fontsize=10,
                linewidth=1,
                dashes=(None, None),
                size=12)
#xi, yi = m(lo, la)
#m.pcolormesh(xi, yi,  t2[0, :,:], edgecolor='Black', linewidth= 0.25,
#             cmap='Blues', alpha = 0.2)
xa, ya = m(pin_df.xa.values, pin_df.ya.values)
xb, yb = m(pin_df.xb.values, pin_df.yb.values)
pts = np.c_[xa, ya, xb, yb].reshape(len(xa), 2, 2)
plt.gca().add_collection(LineCollection(pts, color='crimson', label='streets'))
xx, yy = m(pin_est[1], pin_est[0])
m.plot(xx,
       yy,
       marker="o",
       ls="",
       label="Pinheiros",
# ### Plotting data on a map (Example Gallery) https://matplotlib.org/basemap/users/examples.html
# 
# 
# 

# In[76]:

### PLOT FIGURE
		fig = plt.figure(figsize=(20,16))
		ax = fig.add_subplot(1,1,1)



### Draw Latitude Lines
		m.drawparallels(np.arange(-90.,120.,10.),labels=[1,0,0,0],fontsize=20,linewidth=0.2)


### Draw Longitude Lines
		m.drawmeridians(np.arange(-180.,180.,10.),labels=[0,0,0,1],fontsize=20,linewidth=0.2)


### Draw Map
		m.drawcoastlines()
		m.drawmapboundary()
		m.drawcountries()


### Plot contour lines for pot. temp and fill
		levels = np.arange(258,390,6)
		cmap = colors.ListedColormap([no1, no2, no3, no4, no5, no6, no7, no8, no9, no10,                               no11, no12, no13, no14, no15, no16, no17, no18, no19, no20,                              no21])
Example #55
0
# lonlat, lonlon are lat/lon of London.
lonlat = 51.53
lonlon = 0.08

# find 1000 points along the great circle.
#x,y = m.gcpoints(nylon,nylat,lonlon,lonlat,1000)
# draw the great circle.
#m.plot(x,y,linewidth=2)
# drawgreatcircle performs the previous 2 steps in one call.
m.drawgreatcircle(nylon, nylat, lonlon, lonlat, linewidth=2, color='b')

m.drawcoastlines()
m.fillcontinents()
# draw parallels
circles = np.arange(10, 90, 20)
m.drawparallels(circles, labels=[1, 1, 0, 1])
# draw meridians
meridians = np.arange(-180, 180, 30)
m.drawmeridians(meridians, labels=[1, 1, 0, 1])
plt.title('Great Circle from New York to London (Mercator)')
sys.stdout.write('plotting Great Circle from New York to London (Mercator)\n')

# create new figure
fig = plt.figure()
# setup a gnomonic projection.
m = Basemap(llcrnrlon=-100.,llcrnrlat=20.,urcrnrlon=20.,urcrnrlat=60.,\
            resolution='c',area_thresh=10000.,projection='gnom',\
            lat_0=40.,lon_0=-45.)
# nylat, nylon are lat/lon of New York
nylat = 40.78
nylon = -73.98
Example #56
0
    def plot_map(self, var1d, lats, lons, sites, plot_name, title, yr):

        from matplotlib.font_manager import FontProperties

        fp = FontProperties(fname=r'C:\WINDOWS\Fonts\msgothic.ttc', size=5)

        # --- Build Map ---
        fig = plt.figure()
        plt.rc('font', family='serif')
        my_cmap = plt.get_cmap('rainbow')
        font_size = 10

        # --- limits
        map_lims = self.map_lims

        # --- map labels ---
        mp = Basemap(projection='gall',
                     llcrnrlat=map_lims[0],
                     urcrnrlat=map_lims[1],
                     llcrnrlon=map_lims[2],
                     urcrnrlon=map_lims[3],
                     resolution='l')
        mp.drawcoastlines(color='grey')
        mp.drawcountries(color='grey')
        mp.drawparallels(np.arange(-90, 91, map_lims[4]),
                         labels=[True, False, True, False],
                         fontsize=font_size,
                         color='grey')
        mp.drawmeridians(np.arange(2, 362, map_lims[5]),
                         labels=[False, True, False, True],
                         fontsize=font_size,
                         color='grey')

        x, y = mp(lons, lats)
        mp.scatter(x, y, c=var1d, s=10, cmap=my_cmap)

        # --- selected sites
        o_site = ''
        for j in range(0, len(sites), 1):
            n_lat = lats[j]
            n_lon = lons[j]
            n_site = sites[j]

            # --- plot only unploted sites
            # if n_site != o_site:
            if n_site[:1] != o_site[:1]:
                x, y = mp(n_lon, n_lat)
                plt.text(x,
                         y,
                         n_site,
                         color='k',
                         weight='bold',
                         fontsize=font_size - 6,
                         fontproperties=fp)
            o_site = sites[j]

        # --- title
        plt.title(title + ' for ' + yr)

        # --- legend
        # plt.legend(loc="lower left", ncol=4, prop={'size': font_size - 4}, fancybox=True, shadow=True)
        plt.colorbar()

        # --- save to plot
        a_saveplot.save_plot(plot_name, ext="png", close=True, verbose=False)
        plt.show()
Example #57
0
lat	= HEAT_data.variables['lat'][:] 			
temp	= HEAT_data.variables['TEMP'][:]		

HEAT_data.close()

lon, temp	= PeriodicBoundaries(lon, lat, temp)

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

fig, ax		= subplots()

m = Basemap(projection='spstere',boundinglat=-60,lon_0=180,resolution='i',  area_thresh=0.01) 

m.drawcoastlines(linewidth=0.5)
m.drawcountries()
m.fillcontinents(color='#cc9966',lake_color='#99ffff')
m.drawmapboundary(fill_color='azure')

m.drawparallels(np.arange(-80,81,20),labels=[0,0,0,0])
m.drawmeridians(np.arange(-180,180,30),labels=[1,0,0,1])


x, y	= np.meshgrid(lon, lat)
x, y	= m(x, y)
CS	= m.contourf(x, y, temp, levels = np.arange(-3, 3.01, 0.2), extend = 'both', cmap = 'RdBu_r')
cbar	= m.colorbar(CS, ticks = np.arange(-3, 3.01, 1))
cbar.set_label('Temperature difference ($^{\circ}$C)')

ax.set_title('e) HR-CESM Control minus Mercator')

show()
Example #58
0
def PlotMap(Hydr, MapLabels=True, Savefig=False, Figpath=False, Form='jpg'):
    """ 
    PlotMap 
    PlotMap plots station locations on a map. 
    
    Input:  TripNo, Hydr, MapLabels (station labels, default = True)
    
    Output: None
    """

    # INITIATING FIGURE
    fig, ax = plt.subplots(figsize=(10, 12))

    # BASEMAP PROJECTION
    # find data lon, lat bounds and round to pretty numbers
    lonmin, latmin = Hydr[['Lon', 'Lat']].min()
    lonmax, latmax = Hydr[['Lon', 'Lat']].max()
    lonmin, latmin = varmin(lonmin - 0.005, a=100), varmin(latmin - 0.005,
                                                           a=100)
    lonmax, latmax = varmax(lonmax + 0.005, a=100), varmax(latmax + 0.005,
                                                           a=100)

    m = Basemap(projection='merc',
                resolution=None,
                llcrnrlat=latmin,
                urcrnrlat=latmax,
                llcrnrlon=lonmin,
                urcrnrlon=lonmax)

    # Draw islands from txt file and fill.
    for island in os.listdir('Coasts'):
        lon, aa, lat = np.genfromtxt('Coasts/' + island, delimiter=' ').T
        xpt, ypt = m(lon, lat)
        m.plot(xpt, ypt, 'black', linewidth=1)
        plt.fill(xpt, ypt, 'tan')

# PLOTTING STATIONS INTO MAP
    for lon, lat, name in zip(Hydr.Lon, Hydr.Lat, Hydr.StName):
        xpt, ypt = m(lon, lat)
        m.plot(xpt, ypt, 'bo', markersize=9)
        # setting labels if requested
        if MapLabels == True:
            xp, yp = m(Hydr.Lon.mean(), Hydr.Lat.mean())
            xoffset, yoffset = 0.05 * xp, 0.05 * xp
            ax.text(xpt - xoffset, ypt + yoffset, name, fontsize=12)
            #plt.text(xpt - xoffset, ypt + yoffset, name, fontsize = 9)

    #plt.title('{}'.format(MapName), fontsize=14)
    ax.set_title('CTD stations - {}'.format(Hydr.Date.iloc[0]), fontsize=20)

    # Draw meridional and zonal lines
    # define gap between thick and thin lines depending on map wiev
    if (latmax - latmin) > 0.05:
        dlat, dlon, ddlat, ddlon = 0.1, 0.05, False, False
    elif (latmax - latmin) <= 0.05:
        dlat, dlon, ddlat, ddlon = 0.05, 0.02, 0.01, 0.01
    # draw thick lines
    parallels = np.arange(varmin(latmin, a=20), varmax(latmax, a=20), dlon)
    meridians = np.arange(varmin(lonmin, a=20), varmax(lonmax, a=20), dlat)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], linewidth=0.5, color='k')
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], linewidth=0.5, color='k')
    # draw thin lines
    if ddlat:
        parallels = np.arange(latmin, latmax, ddlon)
        meridians = np.arange(lonmin, lonmax, ddlat)
        m.drawparallels(parallels,
                        labels=[1, 0, 0, 0],
                        linewidth=0.2,
                        color='k')
        m.drawmeridians(meridians,
                        labels=[0, 0, 0, 1],
                        linewidth=0.2,
                        color='k')

    if Savefig:
        path = Figpath + 'map.{}'.format(Form)
        fig.savefig(path, format=Form, dpi=400, bbox_inches='tight')
Example #59
0
# illustrate use of warpimage method to display an image background
# on the map projection region.  Default background is the 'blue
# marble' image from NASA (http://visibleearth.nasa.gov).

# create new figure
fig=plt.figure()
# define orthographic projection centered on North America.
m = Basemap(projection='ortho',lat_0=40,lon_0=-100,resolution='l')
# display a non-default image.
m.warpimage(image='earth_lights_lrg.jpg')
# draw coastlines.
m.drawcoastlines(linewidth=0.5,color='0.5')
# draw lat/lon grid lines every 30 degrees.
m.drawmeridians(np.arange(0,360,30),color='0.5')
m.drawparallels(np.arange(-90,90,30),color='0.5')
plt.title("Lights at Night image warped from 'cyl' to 'ortho' projection",fontsize=12)
print('warp to orthographic map ...')

# create new figure
fig=plt.figure()
# define projection centered on North America.
m = Basemap(projection='mbtfpq',lon_0=-100,resolution='l')
m.bluemarble(scale=0.5)
# draw coastlines.
m.drawcoastlines(linewidth=0.5,color='0.5')
# draw lat/lon grid lines every 30 degrees.
m.drawmeridians(np.arange(0,360,60),color='0.5')
m.drawparallels(np.arange(-90,90,30),color='0.5')
plt.title("Blue Marble image warped from 'cyl' to 'mbtfpq' projection",fontsize=12)
print('warp to McBryde-Thomas Flat-Polar Quartic map ...')
A2 = pd.read_csv(area2_file, delimiter=r",")

## ---- Plot Climato ---- ##
fig, ax = plt.subplots(nrows=1, ncols=1)
m = Basemap(ax=ax, 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(-2, 6, 9)
levels = np.linspace(-2, 6, 17)
xi, yi = m(*np.meshgrid(lon_reg, lat_reg))
c = m.contourf(xi, yi, Tbot_climato, levels, cmap=plt.cm.RdBu_r, extend='both')
cc = m.contour(xi, yi, -Zitp, [100, 500, 1000, 4000], colors='grey');
#c = m.pcolormesh(xi,yi,Tbot_climato, clim=[-2,6], cmap=plt.cm.RdBu_r)
#c = m.pcolormesh(xi,yi,Tbot_climato, clim=[-2,6], cmap=cmocean.cm.thermal)
c.set_clim(-2,6)
plt.clabel(cc, inline=1, fontsize=10, fmt='%d')
m.fillcontinents(color='tan');
m.drawparallels([54, 55, 56, 57, 58, 59], labels=[1,0,0,0], fontsize=12, fontweight='normal');
m.drawmeridians([-62, -60, -58, -56], labels=[0,0,0,1], fontsize=12, fontweight='normal');
# plot casts
x, y = m(lon_orig, lat_orig)
m.scatter(x,y, s=50, marker='.',color='k')
# plot areas
#x, y = m(A1.long_dd.values, A1.lat_dd.values)
#m.plot(x,y, '-k', linewidth=3)
#x, y = m(-63, 57.1)
#plt.text(x, y, '  Area 1', fontsize=12, fontweight='bold')
#x, y = m(A2.long_dd.values, A2.lat_dd.values)
#m.plot(x,y, '-k', linewidth=3)
#x, y = m(-60, 54.5)
#plt.text(x, y, ' Area 2', fontsize=12, fontweight='bold')
m.fillcontinents(color='tan');