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()
Example #31
0
def plotmap(lons,
            lats,
            variable,
            savefile=None,
            cmap="RdBu_r",
            levels=None,
            drawcountries=True,
            variable_label='',
            plottitle='',
            plotaxis=None,
            colorbar=1.0,
            labels=True):
    """ Plots a map and displays output or saves to file with path 
    and filename savefile (string). Inputs are lons, lats and the variable
    in format they are outputted from ReadFile (ie from netcdf file). 
    also cmap is colour- eg for tempchange choose RdBu_r"""
    if plotaxis is None:
        plt.clf()

    map = Basemap()
    # draw coastlines, country boundaries, fill continents.
    map.drawcoastlines(linewidth=0.25)
    if drawcountries:
        map.drawcountries(linewidth=0.25)

    # draw the edge of the map projection region (the projection limb)
    map.drawmapboundary(fill_color='white')
    # draw lat/lon grid lines every 30 degrees.
    map.drawmeridians(np.arange(0, 360, 30))
    map.drawparallels(np.arange(-90, 90, 30))

    variable, lons = shiftgrid(180., variable, lons, start=False)

    # Check variable is on same grid as lons and lats: may need to correct
    # lat levels if they are on stagged grid
    #if variable.shape[0] != len(lats):
    #    centred_lats = np.zeros(len(lats)-1)
    #    centred_lats[:] = lats[1:]-(lats[1:]-lats[0:-1])/2.
    #    lats = centred_lats

    # Create lon lat grid for plotting
    longrid, latgrid = np.meshgrid(lons, lats)

    # Plot map
    cmap = map.contourf(longrid,
                        latgrid,
                        variable,
                        cmap=cmap,
                        levels=levels,
                        extend='both')
    if colorbar == 1.0:
        cbar = map.colorbar()
        cbar.set_label(variable_label)
    if labels:
        plt.xlabel('Longitude')
        plt.xticks(np.arange(-180., 185., 90.))
        plt.yticks(np.arange(-90., 91., 30.))
        plt.ylabel('Latitude')
    plt.title(plottitle)
    plt.tight_layout()

    if type(savefile) is str:
        plt.savefig(savefile)
        print('Saved plot as ' + savefile)

    return map, cmap
Example #32
0
    def plot_index_position(self, mesh, numb=[]):
        from set_inputarray import inputarray
        fsize = 16
        #_______________________________________________________________________
        if isinstance(numb, int) == True: numb = [numb]
        if len(numb) == 0: numb = range(0, len(self.box_define))

        #_______________________________________________________________________
        # draw position of box
        for ii in numb:

            #___________________________________________________________________
            xmin, xmax = np.min(self.box_define[ii][0]), np.max(
                self.box_define[ii][0])
            ymin, ymax = np.min(self.box_define[ii][1]), np.max(
                self.box_define[ii][1])
            xmin, xmax, ymin, ymax = xmin - 20.0, xmax + 20.0, ymin - 20.0, ymax + 20.0
            xmin, xmax, ymin, ymax = np.max([xmin, -180.0]), np.min(
                [xmax, 180.0]), np.max([ymin, -90.0]), np.min([ymax, 90.0])

            #___________________________________________________________________
            figp, ax = plt.figure(figsize=(8, 8)), plt.gca()
            map = Basemap(projection='cyl',
                          resolution='c',
                          llcrnrlon=xmin,
                          urcrnrlon=xmax,
                          llcrnrlat=ymin,
                          urcrnrlat=ymax)

            mx, my = map(mesh.nodes_2d_xg, mesh.nodes_2d_yg)

            map.bluemarble()
            fesom_plot_lmask(map, mesh, ax, '0.6')

            xlabels, ylabels = [0, 0, 0, 1], [1, 0, 0, 0]
            xticks, yticks = np.arange(0., 360., 10.), np.arange(-90., 90., 5.)
            map.drawparallels(yticks, labels=ylabels, fontsize=fsize)
            map.drawmeridians(xticks, labels=xlabels, fontsize=fsize)
            map.drawmapboundary(linewidth=1.0)

            #___________________________________________________________________
            patch = []
            if len(self.box_define[ii][0]) > 2:
                ax.plot(self.box_define[ii][0],
                        self.box_define[ii][1],
                        linestyle='None',
                        color='w',
                        linewidth=2.0,
                        marker='o',
                        mfc='w',
                        mec='k',
                        axes=ax)
                patch.append(
                    Polygon(list(
                        zip(self.box_define[ii][0], self.box_define[ii][1])),
                            closed=True,
                            clip_on=True))
            else:
                auxboxx = [ self.box_define[ii][0][0],\
                            self.box_define[ii][0][1],\
                            self.box_define[ii][0][1],\
                            self.box_define[ii][0][0],\
                            self.box_define[ii][0][0]]
                auxboxy = [ self.box_define[ii][1][0],\
                            self.box_define[ii][1][0],\
                            self.box_define[ii][1][1],\
                            self.box_define[ii][1][1],\
                            self.box_define[ii][1][0],]
                ax.plot(auxboxx,
                        auxboxy,
                        linestyle='None',
                        color='w',
                        linewidth=2.0,
                        marker='o',
                        mfc='w',
                        mec='k',
                        axes=ax)
                patch.append(
                    Polygon(list(zip(auxboxx, auxboxy)),
                            closed=True,
                            clip_on=True))
            ax.add_collection(
                PatchCollection(patch,
                                alpha=1.0,
                                facecolor='none',
                                edgecolor='w',
                                zorder=1,
                                linewidth=2.0,
                                hatch='/'))

            # plot selected mesh points
            ax.plot(mesh.nodes_2d_xg[self.box_idx[ii]],
                    mesh.nodes_2d_yg[self.box_idx[ii]],
                    color='r',
                    linestyle='None',
                    marker='.',
                    alpha=0.5)
            plt.title(self.box_define[ii][2],
                      fontdict=dict(fontsize=fsize * 2),
                      verticalalignment='bottom')

            #___________________________________________________________________
            # save figure
            if inputarray['save_fig'] == True:
                print(' --> save figure: png')
                sfname = 'boxplot_' + self.box_define[ii][
                    2] + '_position' + '.png'
                sdname = inputarray['save_figpath']
                if os.path.isdir(sdname) == False: os.mkdir(sdname)
                plt.savefig(sdname+sfname, \
                            format='png', dpi=600, \
                            bbox_inches='tight', pad_inches=0,\
                            transparent=True,frameon=True)

            #___________________________________________________________________
            plt.show()
            figp.canvas.draw()
Example #33
0
    def pltSAGE3(self):

        #------------------------------------------------------------
        # Show General Information Stored in one HDF file
        #------------------------------------------------------------
        if not self.showinfodFlg: self.showHDFinfo()

        #------------------------------------------------------------
        # Get HDF Specific Variables
        #------------------------------------------------------------
        if not self.readFlg: self.ReadVariables()

        #----------------------------------------
        #
        #----------------------------------------
        clmap = 'jet'
        cm = plt.get_cmap(clmap)

        #fig, ax = plt.subplots()

        fig, ax = plt.subplots(figsize=(8, 5))


        m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
                    llcrnrlon=-180,urcrnrlon=180,resolution='c')

        m.drawcoastlines()
        m.drawcountries()

        m.drawparallels([-90, -60, -30, 0, 30, 60, 90],
                        labels=[1, 0, 0, 0],
                        fontsize=10)
        m.drawmeridians([-180, -120, -60, 0, 60, 120, 180],
                        labels=[0, 0, 0, 1],
                        fontsize=10)

        m.drawmapboundary(fill_color='white')
        #m.fillcontinents(color='gray')

        #x, y = m(*np.meshgrid(Lon, Lat))
        x, y = np.meshgrid(self.Lon, self.Lat)
        x, y = m(x, y)

        #plt.scatter(xx,yy,c=zz,cmap=cm.Reds)
        #ax.scatter(x,y,c=O3_Pcol, cmap=mplcm.jet)
        #ax.scatter(x,y, 'k.')
        #z = z.reshape(xx.shape)
        #-- contour levels
        #clevs = np.arange(np.min(O3_Pcol),np.max(O3_Pcol), )

        #cs = m.contourf(x,y,O3_Pcol, cmap=mplcm.jet,extend='both') #,alpha=0.5)
        #cs.axis='tight'

        ax.plot(x, y, '.r', markersize=6, alpha=0.15)

        #plt.title('Track Fields')
        plt.title('Track - SAGE III/ISS - {} - {} '.format(
            self.date[0], self.date[-1]),
                  fontsize=14)

        if self.pdfsav: self.pdfsav.savefig(fig, dpi=200)
        else: plt.show(block=False)

        #----------------------------------------
        #
        #----------------------------------------
        fig, ax = plt.subplots(figsize=(6, 6))

        cm = plt.get_cmap('jet')
        cNorm = colors.Normalize(vmin=np.nanmin(self.Lat),
                                 vmax=np.nanmax(self.Lon))
        scalarMap = mplcm.ScalarMappable(norm=cNorm, cmap=cm)
        scalarMap.set_array(self.Lat)

        ax.set_prop_cycle(
            cycler('color', [scalarMap.to_rgba(x) for x in self.Lat]))

        for i in range(len(self.dateTime)):
            #for i in inds:
            ax.plot(self.O3_prf_conc[i, :] / 1e13,
                    self.altitude[i, :],
                    linewidth=1.0)
            #ax.plot(O3_prf_conc[i,:]/1e13,altitude[i,:], 'k.')

        #ax.fill_betweenx(alt,Prfmean-prfSTD,Prfmean+prfSTD,alpha=0.5,color='0.75')
        ax.set_title('O$_3$ - SAGE III/ISS - {} - {}'.format(
            self.date[0], self.date[-1]),
                     fontsize=14)
        ax.set_ylabel('Altitude [km]', fontsize=14)
        ax.set_xlabel('Concentration [x10$^{13}$ molec/cm$^{3}$]', fontsize=14)
        #ax.set_xlim(xmin=1e10, xmax=1e13)
        ax.grid(True, which='both')
        ax.tick_params(labelsize=14)

        cbar = fig.colorbar(scalarMap, orientation='vertical')
        cbar.set_label('Latitude', fontsize=14)

        fig.subplots_adjust(left=0.12, bottom=0.1, top=0.94, right=0.95)

        if self.pdfsav: self.pdfsav.savefig(fig, dpi=200)
        else: plt.show(block=False)

        #user_input = raw_input('Press any key to exit >>> ')
        #sys.exit()

        #print altitude[0, :].shape, O3_prf_conc.shape, Lat.shape

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

        fig, ax1 = plt.subplots(figsize=(8, 5))

        levels = np.arange(0, 0.6, 0.05)

        cax = ax1.contourf(self.Lat,
                           self.altitude[0, :],
                           np.transpose(self.O3_prf_conc) / 1e13,
                           levels,
                           cmap=mplcm.jet)
        #cax          = ax1.contourf(altitude[0, :], Lat, O3_prf_conc, cmap=mplcm.jet)

        divider = make_axes_locatable(ax1)
        cb = divider.append_axes("right", size="3.5%", pad=0.05)

        cbar = plt.colorbar(cax, cax=cb)
        #cbar.ax.tick_params(labelsize=12)
        #cbar.set_label('VMR [x10$^3$ ppm]', fontsize=12)#, fontsize=14)
        cbar.set_label('Concentration [x10$^{13}$ molec/cm$^{3}$]',
                       fontsize=14)

        #ax1.set_title('Ozone Partial Column')
        ax1.set_title('O$_3$ - SAGE III/ISS - {} - {} '.format(
            self.date[0], self.date[-1]),
                      fontsize=14)
        ax1.set_ylabel('Altitude [km]', fontsize=14)
        ax1.set_xlabel('Latitude', fontsize=14)
        ax1.set_xlim((-55, 60))
        ax1.grid(True, which='both')
        ax1.tick_params(labelsize=14)

        fig.subplots_adjust(left=0.1, bottom=0.1, top=0.94, right=0.92)

        if self.pdfsav: self.pdfsav.savefig(fig, dpi=200)
        else: plt.show(block=False)
Example #34
0
vals = np.interp(midp, [min_contour, midpoint, max_contour], [0, 0.5, 1])
cols = plt.cm.RdBu_r(vals)

clevs_extend = np.linspace(min_contour, max_contour, 254)
cmap, norm = from_levels_and_colors(clevs_extend, cols, extend='both')

# draw coastlines, state and country boundaries, edge of map.
m.drawcoastlines(linewidth=0.5, color='#262626')
#m.drawstates()
m.drawcountries(linewidth=0.5, color='#262626')
# draw parallels.
parallels = np.arange(0., 90, divisor)
m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10, color='#262626')
# draw meridians
meridians = np.arange(0., 360., divisor)
m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10, color='#262626')

cs_col = m.contourf(x,
                    y,
                    waterbalance,
                    clevs,
                    cmap=cmap,
                    norm=norm,
                    extend='both')
cbar = m.colorbar(cs_col, location='bottom', pad="5%")
#cbar.ax.tick_params(labelsize=12,  colors='#262626')

ticks = np.arange(int(min_contour),
                  int(max_contour) + tick_interval, tick_interval)
cbar.set_ticks(ticks, update_ticks=True)
cbar.set_ticklabels(([r"${%s}$" % x for x in ticks]))
Example #35
0
def plot_files(fnames):
    # Converts the CPT file to be used in Python
    cpt = loadCPT('IR4AVHRR6.cpt')
    # Makes a linear interpolation with the CPT file
    cpt_convert = LinearSegmentedColormap('cpt', cpt)

    first = True

    for fname in fnames:
        # Search for the Scan Start in the file name
        time = (fname[fname.find("MG_") + 3:fname.find(".nc")])
        # Format the "Observation Start" string
        date = datetime.strptime(time, '%Y%m%d%H%M%S')

        # Check if we already created the image
        image_string = folder + 'images/%s_%s.png' % (
            channel, datetime.strftime(date, '%Y%m%d%H%M%S'))
        if os.path.isfile(image_string):
            #print('Skipping '+fname)
            continue

        print('Using ' + fname)
        # Open the file using the NetCDF4 library
        nc = Dataset(fname)
        # Extract the Brightness Temperature values from the NetCDF
        temp_b = brigthness_temp(nc.variables[channel])
        hrv = nc.variables[channel_hrv][:]

        fig = plt.figure(figsize=(15, 15))

        if first:
            lons = np.ma.masked_less(np.array(nc.variables['lon']), -180)
            lats = np.ma.masked_less(np.array(nc.variables['lat']), -90)

            lats_hrv, lons_hrv = create_coord_hrv(lats, lons)

            bmap = Basemap(projection='cyl',
                           llcrnrlon=4,
                           llcrnrlat=31,
                           urcrnrlon=26,
                           urcrnrlat=45,
                           resolution='i')

            x, y = bmap(lons, lats)
            x_hrv, y_hrv = bmap(lons_hrv, lats_hrv)

            first = False

        if (hrv.std() > 0.9):
            bmap.pcolormesh(x_hrv, y_hrv, hrv, vmin=0, vmax=20, cmap='gray')
            bmap.pcolormesh(x,
                            y,
                            np.ma.masked_array(temp_b, temp_b > -38),
                            vmin=-80,
                            vmax=50,
                            cmap=cpt_convert,
                            alpha=0.3,
                            linewidth=0,
                            antialiased=True)
        else:
            bmap.pcolormesh(x,
                            y,
                            temp_b,
                            vmin=-80,
                            vmax=50,
                            cmap=cpt_convert,
                            antialiased=True)

        bmap.drawcoastlines(linewidth=0.5, linestyle='solid', color='white')
        bmap.drawcountries(linewidth=0.5, linestyle='solid', color='white')
        bmap.drawparallels(np.arange(-90.0, 90.0, 5.),
                           linewidth=0.2,
                           color='white',
                           labels=[True, False, False, True],
                           fontsize=7)
        bmap.drawmeridians(np.arange(0.0, 360.0, 5.),
                           linewidth=0.2,
                           color='white',
                           labels=[True, False, False, True],
                           fontsize=7)

        # Insert the legend
        bmap.colorbar(location='right',
                      label='Brightness Temperature [C] / HRV radiance',
                      size='2%',
                      pad='1%')

        date_formatted = datetime.strftime(date, '%a %d %b %Y, %H:%MZ')
        annotation(plt.gca(), date_formatted, loc='upper center', fontsize=9)
        annotation(plt.gca(),
                   "SEVIRI %s,%s High Rate data" % (channel, channel_hrv) +
                   u"\N{COPYRIGHT SIGN}" +
                   'EUMETSAT - prepared by Guido Cioni (www.guidocioni.it)',
                   loc='lower left',
                   fontsize=7)
        #print('Saving file %s' % image_string)
        plt.savefig(image_string, bbox_inches='tight', dpi=200)
        plt.clf()

    plt.close('all')
#plot
#define global attributes
lons, lats = np.meshgrid(lon,lat)
v = np.linspace( -2., 2., 9)
norm = colors.BoundaryNorm(boundaries=v, ncolors=256)




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

#plot TNn during El Nino
ax = plt.subplot(221)
m = Basemap(projection='cyl', llcrnrlat=-45.0, llcrnrlon=110.0, urcrnrlat=-5.0, urcrnrlon=160.0)
m.drawcoastlines()
m.drawparallels(np.array([-45, -35, -25, -15, -5]), labels=[1,0,0,0], fontsize=8)
m.drawmeridians(np.array([110, 120, 130, 140, 150, 160]), labels=[0,0,0,1], fontsize=8)
d_tnn_e = np.ma.masked_invalid(d_tnn_e)
Example #37
0
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# create polar stereographic Basemap instance.
m = Basemap(projection='stere',lon_0=lon_0,lat_0=90.,lat_ts=lat_0,\
            llcrnrlat=latcorners[0],urcrnrlat=latcorners[2],\
            llcrnrlon=loncorners[0],urcrnrlon=loncorners[2],\
            rsphere=6371200.,resolution='l',area_thresh=10000)
# draw coastlines, state and country boundaries, edge of map.
m.drawcoastlines()
m.drawstates()
m.drawcountries()
# draw parallels.
parallels = np.arange(0., 90, 10.)
m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
# draw meridians
meridians = np.arange(180., 360., 10.)
m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)
ny = data.shape[0]
nx = data.shape[1]
lons, lats = m.makegrid(nx, ny)  # get lat/lons of ny by nx evenly space grid.
x, y = m(lons, lats)  # compute map proj coordinates.
# draw filled contours.
clevs = [
    0, 1, 2.5, 5, 7.5, 10, 15, 20, 30, 40, 50, 70, 100, 150, 200, 250, 300,
    400, 500, 600, 750
]
cs = m.contourf(x, y, data, clevs, cmap=cm.s3pcpn)
# add colorbar.
cbar = m.colorbar(cs, location='bottom', pad="5%")
cbar.set_label('mm')
# add title
plt.title(prcpvar.long_name + ' for period ending ' + prcpvar.dateofdata)
Example #38
0
    def plot_threshold(self,
                       val,
                       min_val_plot,
                       max_val_plot,
                       colormap='tomo',
                       verbose=False):
        """
        plot depth to a certain threshold value 'val' in an ses3d model


        plot_threshold(val,min_val_plot,max_val_plot,colormap='tomo',
                        verbose=False):
        val=threshold value
        min_val_plot, max_val_plot=minimum and maximum values of the colour
        scale colormap='tomo','mono'
        """
        import matplotlib.pylab as plt
        from mpl_toolkits.basemap import Basemap
        # set up a map and colourmap

        if self.global_regional == 'regional':
            m = Basemap(projection='merc',
                        llcrnrlat=self.lat_min,
                        urcrnrlat=self.lat_max,
                        llcrnrlon=self.lon_min,
                        urcrnrlon=self.lon_max,
                        lat_ts=20,
                        resolution="m")
            m.drawparallels(np.arange(self.lat_min, self.lat_max, self.d_lon),
                            labels=[1, 0, 0, 1])
            m.drawmeridians(np.arange(self.lon_min, self.lon_max, self.d_lat),
                            labels=[1, 0, 0, 1])
        elif self.global_regional == 'global':
            m = Basemap(projection='ortho',
                        lon_0=self.lon_centre,
                        lat_0=self.lat_centre,
                        resolution="l")
            m.drawparallels(np.arange(-80.0, 80.0, 10.0), labels=[1, 0, 0, 1])
            m.drawmeridians(np.arange(-170.0, 170.0, 10.0),
                            labels=[1, 0, 0, 1])

        m.drawcoastlines()
        m.drawcountries()

        m.drawmapboundary(fill_color=[1.0, 1.0, 1.0])

        if colormap == 'tomo':
            my_colormap = cm.make_colormap({
                0.0: [0.1, 0.0, 0.0],
                0.2: [0.8, 0.0, 0.0],
                0.3: [1.0, 0.7, 0.0],
                0.48: [0.92, 0.92, 0.92],
                0.5: [0.92, 0.92, 0.92],
                0.52: [0.92, 0.92, 0.92],
                0.7: [0.0, 0.6, 0.7],
                0.8: [0.0, 0.0, 0.8],
                1.0: [0.0, 0.0, 0.1]
            })
        elif colormap == 'mono':
            my_colormap = cm.make_colormap({
                0.0: [1.0, 1.0, 1.0],
                0.15: [1.0, 1.0, 1.0],
                0.85: [0.0, 0.0, 0.0],
                1.0: [0.0, 0.0, 0.0]
            })

        # loop over subvolumes
        for k in np.arange(self.nsubvol):

            depth = np.zeros(np.shape(self.m[k].v[:, :, 0]))

            nx = len(self.m[k].lat)
            ny = len(self.m[k].lon)

            # find depth

            r = self.m[k].r
            r = 0.5 * (r[0:len(r) - 1] + r[1:len(r)])

            for idx in np.arange(nx - 1):
                for idy in np.arange(ny - 1):

                    n = self.m[k].v[idx, idy, :] >= val
                    depth[idx, idy] = 6371.0 - np.max(r[n])

            # rotate coordinate system if necessary

            lon, lat = np.meshgrid(self.m[k].lon[0:ny], self.m[k].lat[0:nx])

            if self.phi != 0.0:

                lat_rot = np.zeros(np.shape(lon), dtype=float)
                lon_rot = np.zeros(np.shape(lat), dtype=float)

                for idx in np.arange(nx):
                    for idy in np.arange(ny):

                        colat = 90.0 - lat[idx, idy]

                        lat_rot[idx, idy], lon_rot[idx, idy] = \
                            rot.rotate_coordinates(self.n, -self.phi, colat,
                                                   lon[idx, idy])
                        lat_rot[idx, idy] = 90.0 - lat_rot[idx, idy]

                lon = lon_rot
                lat = lat_rot

                # convert to map coordinates and plot

            x, y = m(lon, lat)
            im = m.pcolor(x,
                          y,
                          depth,
                          cmap=my_colormap,
                          vmin=min_val_plot,
                          vmax=max_val_plot)

        m.colorbar(im, "right", size="3%", pad='2%')
        plt.title('depth to ' + str(val) + ' km/s [km]')
        plt.show()
Example #39
0
#-----------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------

fig, ax = plt.subplots()

m = Basemap(
projection = 'merc',
llcrnrlat=-5, urcrnrlat=25,
llcrnrlon=270, urcrnrlon=330,
resolution='l', area_thresh=0.01
) 

m.drawcoastlines(linewidth=0.2)
m.drawcountries()
m.fillcontinents(color='#cc9966',lake_color='#99ffff')
par = m.drawparallels(np.arange(-80,81,10),labels=[1,0,0,0])
mer = m.drawmeridians(np.arange(-180,180,20),labels=[0,0,0,1])

x, y	= m(lon, lat)

levels	= np.arange(-1.0, 1.01, 0.1)

CS	= m.contourf(x, y, vel_trend, levels, extend = 'both', cmap = 'RdBu_r')
cbar 	= m.colorbar(CS, ticks = np.arange(-1, 1.1, 0.5))
cbar.set_label('Velocity trend (cm s$^{-1}$ per decade)')

ax.set_title('LR-CESM')

show()
Example #40
0
# global ortho map centered on lon_0,lat_0
lat_0 = 10.
lon_0 = 57.
# altitude of camera (in km).
h = 3000.
# resolution = None means don't process the boundary datasets.
m1 = Basemap(projection='nsper',satellite_height=h*1000.,\
        lon_0=lon_0,lat_0=lat_0,resolution=None)
# add an axes with a black background
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], axisbg='k')
# plot just upper right quadrant (corners determined from global map).
# keywords llcrnrx,llcrnry,urcrnrx,urcrnry used to define the lower
# left and upper right corners in map projection coordinates.
# llcrnrlat,llcrnrlon,ucrnrlon,urcrnrlat could be used to define
# lat/lon values of corners - but this won't work in cases such as this
# where one of the corners does not lie on the earth.
m = Basemap(projection='nsper',satellite_height=h*1000.,\
        lon_0=lon_0,lat_0=lat_0,resolution='l',\
    llcrnrx=0.,llcrnry=0.,urcrnrx=m1.urcrnrx/2.,urcrnry=m1.urcrnry/2.)
m.drawcoastlines()
m.drawmapboundary(fill_color='aqua')
m.fillcontinents(color='coral', lake_color='aqua')
m.drawcountries()
# draw parallels and meridians.
m.drawparallels(np.arange(-90., 120., 30.))
m.drawmeridians(np.arange(0., 360., 60.))
m.drawmapboundary()
plt.title('Near-Sided Perspective Map Showing A Quadrant of the Globe',\
          fontsize=12)
plt.show()
Example #41
0
def _map_plot(points, path=True, quiver=True):
    minlat = np.min(points[0, :])
    maxlat = np.max(points[0, :])
    minlon = np.min(points[1, :])
    maxlon = np.max(points[1, :])
    lat_d = max(maxlat - minlat, 20)
    lon_d = max(maxlon - minlon, 20)
    minlat -= lat_d / 3
    minlon -= lon_d / 3
    maxlat += lat_d / 3
    maxlon += lon_d / 3
    if minlat < -90:
        minlat = -90
    if maxlat > 90:
        maxlat = 90

    m = Basemap(
        llcrnrlon=minlon,
        llcrnrlat=minlat,
        urcrnrlon=maxlon,
        urcrnrlat=maxlat,
        lat_0=np.mean(points[0, :]),
        lon_0=np.mean(points[1, :]),
        resolution='c',
        projection='merc',
        rsphere=(6378137.00, 6356752.3142),
    )

    if path:
        marker = ''
        if (np.round(points[1, :], 2) == np.round(points[1, 0], 2)).all() and \
                (np.round(points[0, :], 2) == np.round(points[0, 0], 2)).all():
            marker = '.'
        m.plot(points[1, :],
               points[0, :],
               latlon=True,
               color='r',
               linestyle='-',
               marker=marker)
        if quiver:
            qx, qy = m([points[1, -1]], [points[0, -1]])
            qu = points[1, -1] - points[1, -2]
            qv = points[0, -1] - points[0, -2]
            qmag = np.sqrt(qu**2 + qv**2)
            qu /= qmag
            qv /= qmag
            m.quiver(qx,
                     qy,
                     qu,
                     qv,
                     pivot='tip',
                     scale=8,
                     width=0.25,
                     minlength=0.25,
                     color='r')
    else:
        for idx in range(0, points.shape[1]):
            m.plot(points[1, idx], points[0, idx], 'o', latlon=True, color='r')

    # Draw a realistic background "blue marble"
    m.bluemarble()

    m.drawparallels(np.arange(round(minlat), round(maxlat),
                              round(lat_d / 1.5)),
                    labels=[0, 1, 0, 0])
    m.drawmeridians(np.arange(round(minlon), round(maxlon),
                              round(lon_d / 1.5)),
                    labels=[0, 0, 0, 1])
Example #42
0
loc = manager.location()
if loc is None:
 lat, lon = 0,0
else:
 coord = loc.coordinate()
 lat, lon = coord.latitude, coord.longitude
'''
#def convert_to_decimal(degrees, arcminutes, arcseconds):
# return float(degrees + arcminutes/60. + arcseconds/3600.)
lat, lon = 0, 0

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

m.drawcoastlines()
m.drawstates()
m.bluemarble()
m.drawparallels(np.arange(-90., 91., 30.))
m.drawmeridians(np.arange(-180., 181., 60.))
m.drawmapboundary(fill_color='aqua')
m.scatter(lon, lat, 100, latlon=1, color='m', marker='.')

pyplot.title("Mercator Projection | Latitude: " + str(lat) + ", Longitude: " +
             str(lon))
pyplot.show()
Example #43
0
def geramapa(idx):
    lon = stars[idx].ra - datas[idx].sidereal_time('mean', 'greenwich')

    m = Basemap(projection='ortho',
                lat_0=stars[idx].dec.value,
                lon_0=lon.value,
                resolution='l')
    # draw coastlines, country boundaries, fill continents.
    m.shadedrelief()
    m.drawcoastlines(linewidth=0.25)
    m.drawcountries(linewidth=0.4)
    m.drawstates(linewidth=0.4)
    #m.fillcontinents(color='coral',lake_color='aqua')
    # draw the edge of the map projection region (the projection limb)
    #m.drawmapboundary(fill_color='aqua')
    # draw lat/lon grid lines every 30 degrees.
    m.drawmeridians(np.arange(0, 360, 30))
    m.drawparallels(np.arange(-90, 90, 30))
    if os.path.isfile(sitearq) == True:
        xpt, ypt = m(sites['lon'], sites['lat'])
        m.plot(xpt, ypt, 'bo')
    CS = m.nightshade(datas[idx].datetime, alpha=0.2)
    a, b = m(lon.value, stars[idx].dec.value)
    a = a * u.m
    b = b * u.m
    dista = (dist[idx].to(u.km) * ca[idx].to(u.rad)).value * u.km
    disterr = (dist[idx].to(u.km) * erro.to(u.rad)).value * u.km
    ax = a + dista * np.sin(pa[idx])
    ax2 = ax + 1000 * u.km * vec * np.cos(pa[idx])
    ax3 = ax2 - tamanho / 2 * np.sin(pa[idx])
    ax4 = ax2 + tamanho / 2 * np.sin(pa[idx])
    ax5 = a + (dista - disterr) * np.sin(pa[idx]) + 1000 * u.km * vec * np.cos(
        pa[idx])
    ax6 = a + (dista + disterr) * np.sin(pa[idx]) + 1000 * u.km * vec * np.cos(
        pa[idx])
    by = b + dista * np.cos(pa[idx])
    by2 = by - 1000 * u.km * vec * np.sin(pa[idx])
    by3 = by2 - tamanho / 2 * np.cos(pa[idx])
    by4 = by2 + tamanho / 2 * np.cos(pa[idx])
    by5 = b + (dista - disterr) * np.cos(pa[idx]) - 1000 * u.km * vec * np.sin(
        pa[idx])
    by6 = b + (dista + disterr) * np.cos(pa[idx]) - 1000 * u.km * vec * np.sin(
        pa[idx])
    m.plot(ax, by, 'ro', markersize=20)
    m.plot(ax2.to(u.m), by2.to(u.m), 'ro', markersize=8)
    m.plot(ax3.to(u.m), by3.to(u.m), 'b')
    m.plot(ax4.to(u.m), by4.to(u.m), 'b')
    m.plot(ax5.to(u.m), by5.to(u.m), 'r--')
    m.plot(ax6.to(u.m), by6.to(u.m), 'r--')

    fig = plt.gcf()
    fig.set_size_inches(18.0, 15.0)
    plt.title(
        '-{} D={}- dots each 1000km or {:.2f} <> offsets (mas): {:.1f}, {:.1f}\n'
        .format(obj, tamanho, np.absolute(1000 * u.km / vel[idx]),
                off_ra[idx].value, off_de[idx].value),
        fontsize=25,
        fontproperties='FreeMono')
    plt.xlabel(
        '\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta  R*   K*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f} {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
        .format(datas[idx].iso, dados['afh'][idx], dados['afm'][idx],
                dados['afs'][idx], dados['ded'][idx], dados['dem'][idx],
                dados['des'][idx], ca[idx].value, pa[idx].value,
                dados['vel'][idx], dist[idx].value, dados['mR'][idx],
                dados['mK'][idx], dados['long'][idx]),
        fontsize=21,
        fontproperties='FreeMono')
    plt.savefig('{}_{}.png'.format(obj, datas[idx].isot), dpi=100)
    print 'Gerado: {}_{}.png'.format(obj, datas[idx].isot)
    plt.clf()
Example #44
0
m.drawcoastlines(linewidth=0.5)
m.drawmapboundary()

m.fillcontinents(color='gray')

m.drawparallels(parallels,
                labels=[True, True, False, False],
                color='k',
                linewidth=0.5,
                fontweight='bold',
                fontsize=10,
                zorder=999)
m.drawmeridians(meridians,
                labels=[False, False, True, True],
                color='k',
                linewidth=0.5,
                fontweight='bold',
                fontsize=10,
                zorder=999,
                rotation=45)

# m.drawmapscale(-48.7, -16, -40, -22, 400, barstyle = 'fancy', zorder = 3)
# # os dois primeiros argumentos se referem a posição da escala no mapa
# # os dois seguintes se referem a latitude e longitude central para cálculo da escala no mapa
# # o quarto argumento se refere ao tamanho, em Km, da escala
# # o quinto argumento se refere ao estilo.

# # Plotting zonal section in 22°S
# m.plot([-40.46, -39., -39], [-22., -22., -22.], '-',
#        color='r', linewidth=4, latlon=True, zorder=3)

# Because our lon and lat variables are 1D, use meshgrid to create 2D arrays
Example #45
0
ax0 = fig.add_subplot(111, frame_on=False)
ax0.set_xticks([])
ax0.set_yticks([])
ax = fig.add_subplot(111)
for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_linewidth(3.0)
m = Basemap(projection='cyl',
            resolution='h',
            llcrnrlat=-25.2,
            urcrnrlat=-21.5,
            llcrnrlon=-49.0,
            urcrnrlon=-44.3)
m.drawcoastlines(linewidth=1.5)
m.drawstates(linewidth=1.5)
m.drawparallels(np.arange(-90., 120., 1), labels=[1, 0, 0, 0], fontsize=18)
m.drawmeridians(np.arange(-180., 181., 1), labels=[0, 0, 0, 1], fontsize=18)
trend = m.pcolormesh(lon, lat, diff_t, cmap=cmap, norm=norm)
cbar = m.colorbar(trend, location='right', pad="5%", ticks=levels)
cbar.set_label('None', fontsize=19)
ax.set_title("Difference between Terra Satellite and Model Data" + "\n" +
             "over SPMR for June",
             fontsize=20)

fig = plt.figure(figsize=(11, 11))
rect = fig.patch
rect.set_facecolor('lightgoldenrodyellow')
ax0 = fig.add_subplot(111, frame_on=False)
ax0.set_xticks([])
ax0.set_yticks([])
ax = fig.add_subplot(111)
for axis in ['top', 'bottom', 'left', 'right']:
Example #46
0
    def plot_ppi_map(self,
                     field,
                     sweep=0,
                     mask_tuple=None,
                     vmin=None,
                     vmax=None,
                     cmap=None,
                     norm=None,
                     mask_outside=False,
                     title=None,
                     title_flag=True,
                     colorbar_flag=True,
                     colorbar_label=None,
                     ax=None,
                     fig=None,
                     lat_lines=None,
                     lon_lines=None,
                     projection='lcc',
                     area_thresh=10000,
                     min_lon=None,
                     max_lon=None,
                     min_lat=None,
                     max_lat=None,
                     width=None,
                     height=None,
                     lon_0=None,
                     lat_0=None,
                     resolution='h',
                     shapefile=None,
                     edges=True,
                     gatefilter=None,
                     basemap=None,
                     filter_transitions=True,
                     embelish=True,
                     ticks=None,
                     ticklabs=None,
                     **kwargs):
        """
        Plot a PPI volume sweep onto a geographic map.

        Additional arguments are passed to Basemap.

        Parameters
        ----------
        field : str
            Field to plot.
        sweep : int, optional
            Sweep number to plot.

        Other Parameters
        ----------------
        mask_tuple : (str, float)
            Tuple containing the field name and value below which to mask
            field prior to plotting, for example to mask all data where
            NCP < 0.5 set mask_tuple to ['NCP', 0.5]. None performs no masking.
        vmin : float
            Luminance minimum value, None for default value.
            Parameter is ignored is norm is not None.
        vmax : float
            Luminance maximum value, None for default value.
            Parameter is ignored is norm is not None.
        norm : Normalize or None, optional
            matplotlib Normalize instance used to scale luminance data.  If not
            None the vmax and vmin parameters are ignored.  If None, vmin and
            vmax are used for luminance scaling.
        cmap : str or None
            Matplotlib colormap name. None will use the default colormap for
            the field being plotted as specified by the Py-ART configuration.
        mask_outside : bool
            True to mask data outside of vmin, vmax.  False performs no
            masking.
        title : str
            Title to label plot with, None to use default title generated from
            the field and tilt parameters. Parameter is ignored if title_flag
            is False.
        title_flag : bool
            True to add a title to the plot, False does not add a title.
        colorbar_flag : bool
            True to add a colorbar with label to the axis.  False leaves off
            the colorbar.
        ticks : array
            Colorbar custom tick label locations.
        ticklabs : array
                Colorbar custom tick labels.
        colorbar_label : str
            Colorbar label, None will use a default label generated from the
            field information.
        ax : Axis
            Axis to plot on. None will use the current axis.
        fig : Figure
            Figure to add the colorbar to. None will use the current figure.
        lat_lines, lon_lines : array or None
            Locations at which to draw latitude and longitude lines.
            None will use default values which are resonable for maps of
            North America.
        projection : str
            Map projection supported by basemap.  The use of cylindrical
            projections (mill, merc, etc) is not recommended as they
            exhibit large distortions at high latitudes.  Equal area
            (aea, laea), conformal (lcc, tmerc, stere) or equidistant
            projection (aeqd, cass) work well even at high latitudes.
            The cylindrical equidistant projection (cyl) is not supported as
            coordinate transformations cannot be performed.
        area_thresh : float
            Coastline or lake with an area smaller than area_thresh in
            km^2 will not be plotted.
        min_lat, max_lat, min_lon, max_lon : float
            Latitude and longitude ranges for the map projection region in
            degrees.
        width, height : float
            Width and height of map domain in meters.
            Only this set of parameters or the previous set of parameters
            (min_lat, max_lat, min_lon, max_lon) should be specified.
            If neither set is specified then the map domain will be determined
            from the extend of the radar gate locations.
        lon_0, lat_0 : float
            Center of the map domain in degrees.  If the default, None is used
            the latitude and longitude of the radar will be used.
        shapefile : str
            Filename for a ESRI shapefile as background (untested).
        resolution : 'c', 'l', 'i', 'h', or 'f'.
            Resolution of boundary database to use. See Basemap documentation
            for details.
        gatefilter : GateFilter
            GateFilter instance. None will result in no gatefilter mask being
            applied to data.
        filter_transitions : bool
            True to remove rays where the antenna was in transition between
            sweeps from the plot.  False will include these rays in the plot.
            No rays are filtered when the antenna_transition attribute of the
            underlying radar is not present.
        edges : bool
            True will interpolate and extrapolate the gate edges from the
            range, azimuth and elevations in the radar, treating these
            as specifying the center of each gate.  False treats these
            coordinates themselved as the gate edges, resulting in a plot
            in which the last gate in each ray and the entire last ray are not
            not plotted.
        embelish: bool
            True by default. Set to false to supress drawing of coastlines
            etc.. Use for speedup when specifying shapefiles.
        basemap: Basemap instance
            If None, create basemap instance using other keyword info.
            If not None, use the user-specifed basemap instance.

        """
        # parse parameters
        ax, fig = parse_ax_fig(ax, fig)
        vmin, vmax = parse_vmin_vmax(self._radar, field, vmin, vmax)
        cmap = parse_cmap(cmap, field)
        if lat_lines is None:
            lat_lines = np.arange(30, 46, 1)
        if lon_lines is None:
            lon_lines = np.arange(-110, -75, 1)
        if lat_0 is None:
            lat_0 = self.loc[0]
        if lon_0 is None:
            lon_0 = self.loc[1]

        # get data for the plot
        data = self._get_data(field, sweep, mask_tuple, filter_transitions,
                              gatefilter)
        x, y = self._get_x_y(sweep, edges, filter_transitions)

        # mask the data where outside the limits
        if mask_outside:
            data = np.ma.masked_outside(data, vmin, vmax)

        # create the basemap if not provided
        if type(basemap) != Basemap:
            using_corners = (None not in [min_lon, min_lat, max_lon, max_lat])
            if using_corners:
                basemap = Basemap(llcrnrlon=min_lon,
                                  llcrnrlat=min_lat,
                                  urcrnrlon=max_lon,
                                  urcrnrlat=max_lat,
                                  lat_0=lat_0,
                                  lon_0=lon_0,
                                  projection=projection,
                                  area_thresh=area_thresh,
                                  resolution=resolution,
                                  ax=ax,
                                  **kwargs)
            else:  # using width and height
                # map domain determined from location of radar gates
                if width is None:
                    width = (x.max() - y.min()) * 1000.
                if height is None:
                    height = (y.max() - y.min()) * 1000.
                basemap = Basemap(width=width,
                                  height=height,
                                  lon_0=lon_0,
                                  lat_0=lat_0,
                                  projection=projection,
                                  area_thresh=area_thresh,
                                  resolution=resolution,
                                  ax=ax,
                                  **kwargs)

        # The cylindrical equidistant projection does not support conversions
        # from geographic (lon/lat) to map projection (x/y) coordinates and
        # therefore cannot be used.
        if basemap.projection == 'cyl':
            raise ValueError(
                'The cylindrical equidistant projection is not supported')

        # add embelishments
        if embelish is True:
            basemap.drawcoastlines(linewidth=1.25)
            basemap.drawstates()
            basemap.drawparallels(lat_lines,
                                  labels=[True, False, False, False])
            basemap.drawmeridians(lon_lines,
                                  labels=[False, False, False, True])
        self.basemap = basemap
        self._x0, self._y0 = basemap(self.loc[1], self.loc[0])

        # plot the data and optionally the shape file
        # we need to convert the radar gate locations (x and y) which are in
        # km to meters as well as add the map coordiate radar location
        # which is given by self._x0, self._y0.
        if norm is not None:  # if norm is set do not override with vmin/vmax
            vmin = vmax = None
        pm = basemap.pcolormesh(self._x0 + x * 1000.,
                                self._y0 + y * 1000.,
                                data,
                                vmin=vmin,
                                vmax=vmax,
                                cmap=cmap,
                                norm=norm)

        if shapefile is not None:
            basemap.readshapefile(shapefile, 'shapefile', ax=ax)

        if title_flag:
            self._set_title(field, sweep, title, ax)

        # add plot and field to lists
        self.plots.append(pm)
        self.plot_vars.append(field)

        if colorbar_flag:
            self.plot_colorbar(mappable=pm,
                               label=colorbar_label,
                               field=field,
                               fig=fig,
                               ax=ax,
                               ticks=ticks,
                               ticklabs=ticklabs)
        return
Example #47
0
class Hurricane(object):
    def __init__(self, name, network, Latitude, Longitude, color):
        self.name = name
        self.network = network
        self.lat = Latitude
        self.lon = Longitude
        self.c = color
    
    def fileimport(self, data, location):
        '''import information about the hurricane:
        Location, Longitude, Latitude, Wind Pressure, Wind Speed
        '''
        import pandas as pd
        
        CSV = pd.read_csv(location + data)
        
        self.Infoextract(CSV)
    
    def Infoextract(self, CSV):
        '''Extract hurricane information
        '''
        import numpy as np
        
        self.Nlon = np.array(CSV['Longitude'])
        self.Nlat = np.array(CSV['Latitude'])
        self.wp = np.array(CSV['Wind Pressure'])
        self.ws = np.array(CSV['Wind Speed'])
    
    def Basemap(self, Type):
        """Geographical Map within certain locations.
        The location is given by some longitude and latitude interval
        """
        import os
        os.environ['PROJ_LIB'] = r"C:\Users\wany105\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.2.0-ha925a31_1\Library\share"
        
        from mpl_toolkits.basemap import Basemap #Basemap package is used for creating geography map
        from matplotlib import pyplot as plt
        import numpy as np
        
        latinter = self.lat[1] - self.lat[0]
        loninter = self.lon[1] - self.lon[0]
        
        if(Type == 'local'):
            self.Base = Basemap(projection = 'merc', resolution = 'l', area_thresh = 1000.0, lat_0=0, lon_0=0, llcrnrlon = self.lon[0], llcrnrlat = self.lat[0], urcrnrlon = self.lon[1], urcrnrlat = self.lat[1])
        elif(Type == 'whole'):
            self.Base = Basemap(resolution = 'l', area_thresh = 1000.0, lat_0=0, lon_0=0, llcrnrlon = self.lon[0], llcrnrlat = self.lat[1], urcrnrlon = self.lon[1], urcrnrlat = self.lat[1])
        
        plt.figure(figsize = (20, 10))    
        self.Base.drawcoastlines()
        self.Base.drawcountries()
        self.Base.drawmapboundary()
        self.Base.drawparallels(np.arange(self.lat[0] - latinter/5, self.lat[1] + latinter/5, latinter/5), labels=[1,0,0,1], fontsize = 10)
        self.Base.drawmeridians(np.arange(self.lon[0] - loninter/5, self.lon[1] + loninter/5, loninter/5), labels=[1,1,0,1], fontsize = 10)
        
    def verticexy(self, filename, filelocation, Type):
        '''load node coordinates information from CSV
        '''
        import numpy as np
        
        self.fileimport(filename, filelocation)
        self.Basemap(Type)
        self.Nx, self.Ny = self.Base(self.Nlon, self.Nlat)
    
    def trajectory_plot(self, townlon, townlat):
        '''Plot the trajectory of the hurricane
        '''
        import matplotlib.pyplot as plt
        
        townx, towny = self.Base(townlon, townlat)
        self.Base.scatter(townx, towny, marker = 'D', color = 'red', s = 200, label = 'Galveton, Texas')
        self.Base.plot(self.Nx, self.Ny, marker = 'D', color = 'm', label = 'Hurricane Trajectory')
        plt.legend()
    
    def ED_Rm(self):
        '''Calculate the eye diameter for each point along the hurricane trajectory
        '''
        import numpy as np
        
        self.ED = 46.29*np.exp(-0.0153*self.ws*1.852 + 0.0166*np.abs(self.Nlat))
        self.Rm = self.ED/2 + 8
        
    def NetworkXY(self):
        '''Convert the node XY in power network coordinate system to XY in hurricane system 
        '''
        import numpy as np
        
        self.netX, self.netY = self.Base(self.network.Nlon, self.network.Nlat)

    def Dist(self):
        '''Calculate the distance between vertices in power network and eye along the hurricane trajectory
        '''
        import numpy as np
        
        self.NetworkXY()
        self.Dist = np.zeros([len(self.netX), len(self.Nx)])
        for i in range(len(self.netX)):
            for j in range(len(self.Nx)):
                node1 = np.array([self.netX[i], self.netY[i]])
                node2 = np.array([self.Nx[j], self.Ny[j]])
                
                self.Dist[i, j] = sf.dist(node1, node2)/1000
      
    def v(self, a, b):
        '''Calculate the wind speed at specified location (x, y)
        a, b are parameters to calculate the wind speed.
        b is determined by the wind pressure
        a usually takes 0.5
        '''
        import numpy as np
        
        self.v = np.zeros_like(self.Dist)
        for i in range(len(self.netX)):
            for j in range(len(self.Nx)):
                temp = self.Rm[j]/self.Dist[i, j]
                self.v[i, j] = np.max(self.ws)*(temp**b*np.exp(1 - temp**b))**a
    
    def Failprob(self, mu, sigma, a, b):
        '''Calculate the fail probabiilty of each transmission towers
        mu, sigma: normal distribution parameters to calculate the failure probability
        '''
        from scipy.stats import norm
        import numpy as np
        
        self.ED_Rm()
        self.NetworkXY()
        self.Dist()
        self.v(a = 0.5, b = 0.75)
        
        self.failprob = np.zeros(len(self.netX))
        for i in range(len(self.netX)):
            temp = 0
            for j in range(len(self.Nx)):
                vv = 1.287 * self.v[i, j] #Peak gust wind speed
                prob = norm.cdf(np.log(vv/mu)/sigma)
                if(prob >= temp):
                    temp = prob
            self.failprob[i] = temp
            
        
        self.failprob *= 1 ##Lack of knowledge, need to be further researched on

#import Hdata as Hcd
#Hurricanes = []
#for i in range(Hcd.Hnum):
#    Hurricanes.append(Hurricane(Hcd.Hurricane_name[i], TXpower, Hcd.Latitude[i], Hcd.Longitude[i], Hcd.color[i]))
#    Hurricanes[-1].verticexy(Hcd.Data[i], filelocation = Hcd.Data_Location, Type = 'local')
##    Hurricanes[-1].trajectory_plot(townlat = 29.3013, townlon = -94.7977)
#    Hurricanes[-1].Failprob(mu = 100, sigma = 1, a = 0.5, b = 1)
##        if(i == 0): #Since fail probability is nearly the same among all hurricane sceneria, we need to add some noise
##    Hurricanes[-1].failprob -= 0.3
        
        
        
        
                

    
        

        
Example #48
0
import netCDF4 as nc

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

xmin, xmax, ymin, ymax = (-41, -35, -25, -20)

m = Basemap(projection='cyl', llcrnrlat=ymin, urcrnrlat=ymax,
    llcrnrlon=xmin, urcrnrlon=xmax, lat_ts=0, resolution='i')

data = nc.Dataset('/path/nomedoarquivo.nc')
lon = data.variables['lon'][:]
lat = data.variables['lat'][:]
prop = data.variables['prop'][:]

#
# processamento .......
#
#

print lon.shape, lat.shape, prop.shape

# plotting map:
plt.figure()
m.pcolormesh(lon, lat, prop, vmin=xxx, vmax=xxx, cmap=plt.cm.RdBu)
plt.colorbar()
m.fillcontinents()
m.drawcoastlines()
m.drawstates()
m.drawmeridians(meridians, labels=[0,0,0,1], dashes=[1,1000])
m.drawparallels(parallels, labels=[1,0,0,0], dashes=[1,1000])
plt.savefig("filename.png")
Example #49
0
def zview(var, tindex, depth, grid, filename=None, \
          cmin=None, cmax=None, clev=None, clb_format='%.2f', \
          fill=False, contour=False, d=4, range=None, fts=None, \
          title=None, clb=True, pal=None, proj='merc', \
          fill_land=False, outfile=None):
    """
    map = zview(var, tindex, depth, grid, {optional switch})

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

    plot a constant-z slice of variable var. If filename is provided,
    var must be a string and the variable will be load from the file.
    grid can be a grid object or a gridid. In the later case, the grid
    object correponding to the provided gridid will be loaded.
    If proj is not None, return a Basemap object to be used with quiver
    for example.
    """

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

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

        var = data.variables[var]

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

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

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

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

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

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

    depth = -abs(depth)
    if fill == True:
        zslice, lon, lat = pyroms.tools.zslice(var, depth, grd, \
                                  Cpos=Cpos)
    else:
        zslice, lon, lat = pyroms.tools.zslice(var, depth, grd, \
                                  Cpos=Cpos, vert=True)

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

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

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

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

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

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

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

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

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

    # clear figure
    #plt.clf()

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

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

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

    if clb:
        clb = plt.colorbar(cf, fraction=0.075, format=clb_format)
        for t in clb.ax.get_yticklabels():
            t.set_fontsize(fts)

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

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

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

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

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

    if proj is None:
        return
    else:
        return map
Example #50
0
lon, lat = np.meshgrid(lons, lats)
xi, yi = m(lon, lat)
# print("xy,%d  %d",xi,yi)

# Plot Data
# 这里我的tlml数据是24小时的,我这里只绘制第1小时的(tlml_0)
# tlml_0 = tlml[0:1:, ::, ::]
# v代表色标的范围
# v = np.linspace(-1.0, 1.0, 21, endpoint=True)
cs = m.contourf(xi, yi, np.squeeze(sst))
# cs = m.pcolor(xi, yi, np.squeeze(sst))
plt.set_cmap('jet')
# Add Grid Lines
# 绘制经纬线
m.drawparallels(np.arange(-30., 30., 10.), labels=[1, 0, 0, 0], fontsize=15)
m.drawmeridians(np.arange(100., 290., 40.), labels=[0, 0, 0, 1], fontsize=15)

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

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

# Add Title
# plt.title(meteo_file)

h1_units = 'm'
ax = fig.add_subplot(212)
    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)
    cs = m.contourf(X2, Y2, mdata, levels, cmap=plt.cm.bwr, extend='both')

    #vmin,vmax = (-0.01251*max_val,max_val)
    vmin, vmax = (-1. * max_val, 1. * max_val)

    plt.tight_layout()
    #cbar = m.colorbar(cs,location='bottom',pad='10%',ticks=np.linspace(vmin,vmax,7),format='%.1f')
Example #52
0
def write_pdf(inputlist):
    num   = inputlist[0]
    start = int(inputlist[1])
    last  = int(inputlist[2])
    pdfname="./fig/WSE_observation_river_network_"+num+".pdf"
    with PdfPages(pdfname) as pdf:
        for ixiy in pnames.keys():
            unilist=np.unique(np.array(dataname[ixiy]))
            pnum=np.shape(np.unique(np.array(dataname[ixiy])))[0]
            if pnum<2:
                continue
            hgt=11.69
            wdt=8.27
            fig=plt.figure(figsize=(wdt, hgt))
            #plt.title(pname[point][0],fontsize=12)
            G   = gridspec.GridSpec(3,2)
            ax00 = fig.add_subplot(G[0,0])
            ax01 = fig.add_subplot(G[0,1])
            ax1 = fig.add_subplot(G[1,:])
            # get the dimesion of the map
            dec=2
            val=0.25
            lllat = round_half_down(min(latlist[ixiy])-val,dec)
            urlat = round_half_up(max(latlist[ixiy])+val,dec)
            lllon = round_half_down(min(lonlist[ixiy])-val,dec)
            urlon = round_half_up(max(lonlist[ixiy])+val,dec)
            if abs(lllat-urlat) < val:
                urlat=round_half_up(urlat+val,dec)
                lllat=round_half_down(lllat-val,dec)
            if abs(lllon-urlon) < val:
                urlon=round_half_up(urlon+val,dec)
                lllon=round_half_down(lllon-val,dec)
            print lllat, lllon, urlat, urlon
            M = Basemap(resolution='h', projection='cyl',llcrnrlon=lllon, llcrnrlat=lllat, \
                urcrnrlon=urlon, urcrnrlat=urlat, ax=ax00)
            try:
                M.arcgisimage(service=maps[0], xpixels=1500, verbose=False)
            except:
                # Draw some map elements on the map
                M.drawcoastlines()
                M.drawstates()
                M.drawcountries()
                M.drawrivers(color='blue')
            M.drawparallels([lllat,urlat], labels = [1,0,0,0], fontsize=10,linewidth=0,zorder=102)
            M.drawmeridians([lllon,urlon], labels = [0,0,0,1], fontsize=10,linewidth=0,zorder=102)
            obss=[]
            tags=[]
            lines=[]
            labels=[]
            j=0
            #print pnum
            z=0
            for i in np.arange(pnum):
                TAG=unilist[i] #dataname[ixiy][i]
                #print np.where(np.array(dataname[ixiy])==TAG)[0] #.index(TAG)
                repeatlist=np.where(np.array(dataname[ixiy])==TAG)[0]
                #print i, TAG, repeatlist
                obs_frg=[]
                k=0
                rflag=-9
                for j in repeatlist:
                    pname=pnames[ixiy][j]
                    lon=lonlist[ixiy][j]
                    lat=latlist[ixiy][j]
                    M.scatter(lon,lat,c=colors[TAG],s=20,marker=markers[TAG])
                    #ax0.annotate(pname,xy=(lon,lat),fontsize=8,textcoords="offset points",xytext=(lon,lat),arrowprops=dict(arrowstyle="-"),zorder=111) #ha=ha,va=va,xycoords=transform,
                    ax01.text(-0.1,1.0-0.1*z,pnames[ixiy][j],va="center",ha="left",transform=ax01.transAxes,fontsize=10)
                    z=z+1
                    #ax01.text(0.0,1.0-0.1*z,satlist[ixiy][j],va="center",ha="center",transform=ax0.transAxes,fontsize=14)
                    #z=z+1
                    #Observation
                    #print TAG, markers[TAG], colors[TAG]
                    locs,org = get_data(pname,TAG)
                    # try:
                    #     rflag=1
                    #     locs,org = get_data(pname,TAG)
                    # except:
                    #     rflag=0
                    #     continue
                    if k==0:
                        lines.append(ax1.plot(locs,org,color=colors[TAG],label=TAG,linestyle='-',linewidth=0.5,marker=markers[TAG],fillstyle="none",markersize=5)[0])
                    else:
                        ax1.plot(locs,org,color=colors[TAG],label=TAG,linestyle='-',linewidth=0.5,marker=markers[TAG],fillstyle="none",markersize=5)[0]
                    k=k+1
                obss.append(org)
                tags.append(TAG)
                labels.append(TAG)
                print labels
                # if rflag==1:
                #     obss.append(org)
                #     tags.append(TAG)
                #     labels.append(TAG)
                #     print labels
                # else:
                #     continue
            # ax00
            ax00.set_axis_off()
            ax00.spines['top'].set_visible(False)
            ax00.spines['right'].set_visible(False)
            ax00.spines['left'].set_visible(False)
            ax00.spines['bottom'].set_visible(False)
            #ax01
            ax01.set_axis_off()
            ax01.spines['top'].set_visible(False)
            ax01.spines['right'].set_visible(False)
            ax01.spines['left'].set_visible(False)
            ax01.spines['bottom'].set_visible(False)
            #ax1
            ax1.set_xlim(xmin=0,xmax=days+1)
            xxlab=np.arange(syear,eyear+1,5)
            dt=int(math.ceil(((eyear-syear)+2)/5.0))
            xxlist=np.linspace(0,days,dt,endpoint=True)
            ax1.set_xticks(xxlist)
            ax1.set_xticklabels(xxlab,fontsize=8)
            plt.legend(lines,labels,ncol=pnum+1,loc='upper right',bbox_to_anchor=(1.0, 1.13))  
            ######################################
            #boxplot
            ax2 = fig.add_subplot(G[2,0])
            flierprops = dict(marker='o', markerfacecolor='none', markersize=12,linestyle='none', markeredgecolor='k')
            boxprops = dict(color='grey')#facecolor='none'
            whiskerprops = dict(color='grey',linestyle="--")
            capprops = dict(color='grey')
            medianprops = dict(color='r')
            box=ax2.boxplot(obss,labels=labels,boxprops=boxprops,showfliers=False, \
                            whiskerprops=whiskerprops,capprops=capprops,medianprops=medianprops, \
                            notch=False, sym=None, vert=True, whis=1.5,positions=None, widths=None, \
                            patch_artist=True,bootstrap=None, usermedians=None, conf_intervals=None)#flierprops=flierprops,
            for patch, tag in zip(box['boxes'], labels):
                #patch.set_facecolor(colors[tag],alpha=0.5)
                patch.set(facecolor=colors[tag],alpha=0.5)
            ax2.set_ylabel('WSE $(m)$', color='k',fontsize=10)
            ax2.tick_params('y',labelsize=8, colors='k')
            ax2.tick_params('x',labelsize=8, colors='k')#,labelrotation=45)
            ax2.set_xticklabels(labels,rotation=0)
            ######################################
            #pdf
            ax3 = fig.add_subplot(G[2,1])
            #sns.distplot(obss[0], ax=ax3, hist=True, color="xkcd:cornflower", label="CaMa-Flood") #ax=ax3,
            for k,tag in enumerate(tags,start=0):
                sns.distplot(obss[k], ax=ax3, hist=True, color=colors[tag], label=tag) #ax=ax3,
            ax3.set_ylabel('density', color='k',fontsize=10)
            ax3.tick_params('y',labelsize=6, colors='k')
            ax3.set_xlabel('WSE $(m)$', color='k',fontsize=10)
            ax3.tick_params('x',labelsize=6, colors='k')
            #ax3.set_title("Histogram of Bias",fontsize=8)
            #ax3.set_xlim(xmin=-20.0,xmax=20.0)
            #ax3.text(0.01,0.95,"b",transform=ax3.transAxes,fontsize=8)
            ax3.legend(ncol=5, bbox_to_anchor=(0.0, -0.3), loc='lower center') #
            ######################################
            pdf.savefig()  # saves the current figure into a pdf page
            plt.close()
            print "============================"
        # set the file's metadata via the PdfPages object:
        d = pdf.infodict()
        d['Title'] = 'Comparison of HydroWeb, CGLS, HydroSat, ICESat altimetry data'
        d['Author'] = 'Menaka Revel'
        d['Subject'] = 'Comparison of altimetry observations'
        d['Keywords'] = 'HydroWeb, CGLS, HydroSat, ICESat, GRRATS'
        d['CreationDate'] = datetime.datetime(2021, 1, 25)
        d['ModDate'] = datetime.datetime.today()
Example #53
0
#    else :
#       print("The dates are not matcing")

#Mapping
##################

lt = np.amax(lat,axis=1)
#lats=lt.reshape(432,1)
ln = np.amax(lon,axis=0)
#lons=ln.reshape(780,1)
lt.shape
ln.shape
m=Basemap(projection='mill',llcrnrlat=lt.min(),urcrnrlat=lt.max(),llcrnrlon=ln.min(),urcrnrlon=ln.max(),resolution='f')
lon1, lat1 = np.meshgrid(ln, lt)
xi, yi = m(lon1, lat1)

nice_cmap=plt.get_cmap('RdYlGn')
clevs=np.arange(-.5,.5,.02)
cs = (m.contourf(xi,yi,ssh[count,:,:],clevs,cmap=nice_cmap,extended='both'))
m.drawcoastlines()
m.drawcountries()
m.drawparallels(np.arange(20.,31.,5.), labels=[1,0,0,0])
m.drawmeridians(np.arange(47.,70.,5.), labels=[0,0,0,1])
m.fillcontinents(color='w',lake_color='aqua')               #Land Mask 'w' white
#m.fillcontinents(lake_color='aqua')               #Land Mask default Gray color
cbar = m.colorbar(cs, location='bottom', pad="10%")
plt.title('Model Output SSH Timestep-'+ str(date_check),fontsize=12,color='k');
cbar.set_label('meter');
plt.savefig('ssh.png', dpi=100);
plt.show()
Example #54
0
    def createPlot(self, start_datetime, end_datetime):

        if len(self.data) == 0:
            logger.debug('no data found to plot')
            raise Exception('no data found to plot')

        # GridSpecs for plots
        outer_gs = gridspec.GridSpec(nrows=2, ncols=1, height_ratios=[1, 3])

        # tighten up space between plots
        outer_gs.update(left=0.10, right=0.90, hspace=0.05)
        map_gs = gridspec.GridSpecFromSubplotSpec(nrows=1,
                                                  ncols=1,
                                                  subplot_spec=outer_gs[0])
        lower_gs = gridspec.GridSpecFromSubplotSpec(nrows=len(
            self.plotGroupValid),
                                                    ncols=1,
                                                    subplot_spec=outer_gs[1])

        clt = self.readCLT(
            os.path.join(settings.STATICFILES_DIRS[0], 'colormaps',
                         'jetplus.txt'))
        self.cm_jetplus = mpl.colors.ListedColormap(np.array(clt))

        # start a new figure - size is in inches
        fig = plt.figure(figsize=(8, 10))
        fig.suptitle(self.title + '\n' + self.subtitle1 + '\n' +
                     self.subtitle2,
                     fontsize=8)

        pn = self.platformName[0]

        # bound the depth to cover max of all parameter group depths
        # and flag removal of scatter plot if have more than 2000 points in any parameter
        maxy = 0
        for group in self.plotGroupValid:
            parm = [x.strip() for x in group.split(',')]
            for name in parm:
                y = max(self.data[pn + name]['depth'])
                sz = len(self.data[pn + name]['datavalue'])
                if y > maxy:
                    maxy = y

        # pad the depth by 20 meters to make room for parameter name to be displayed at bottom
        rangey = [0.0, int(maxy) + 20]

        i = 0
        # add contour plots for each parameter group
        for group in self.plotGroupValid:
            parm = [x.strip() for x in group.split(',')]
            plot_step = sum([
                self.data[pn + p]['units'].count('bool') for p in parm
            ])  # count the number of boolean plots in the groups
            plot_scatter_contour = len(
                parm
            ) - plot_step  # otherwise all other plots are scatter plots
            plot_scatter = 0

            # this parameter only makes sense to plot as a scatter plot
            if 'vertical_temperature_homogeneity_index' in self.plotGroupValid:
                plot_scatter = 1
                plot_scatter_contour -= 1
            #plot_dense = sum([val for val  in len(self.data[pn+name]['datavalue']) > 2000]) #  if more than 2000 points, skip the scatter plot

            # choose the right type of gridspec to display the data
            if plot_scatter_contour:
                # one row for scatter and one for contour
                plot_gs = gridspec.GridSpecFromSubplotSpec(
                    nrows=len(parm) * 2,
                    ncols=2,
                    subplot_spec=lower_gs[i],
                    width_ratios=[30, 1],
                    wspace=0.05)
            else:
                # one row for single step/scatter/contour plots
                plot_gs = gridspec.GridSpecFromSubplotSpec(
                    nrows=len(parm),
                    ncols=2,
                    subplot_spec=lower_gs[i],
                    width_ratios=[30, 1],
                    wspace=0.05)

            j = 0
            i += 1
            for name in parm:
                title = name
                x = [
                    time.mktime(xe.timetuple())
                    for xe in self.data[pn + name]['datetime']
                ]
                y = self.data[pn + name]['depth']
                z = self.data[pn + name]['datavalue']
                sdt_count = self.data[pn + name]['sdt_count']

                units = '(' + self.data[pn + name]['units'] + ')'

                if len(z):
                    if self.autoscale:
                        rangez = [
                            self.data[pn + name]['p010'],
                            self.data[pn + name]['p990']
                        ]
                    else:
                        rangez = [min(z), max(z)]
                else:
                    rangez = [0, 0]

                if name.find('chlorophyll') != -1:
                    if not self.autoscale:
                        rangez = [0.0, 10.0]
                if name.find('salinity') != -1:
                    if not self.autoscale:
                        rangez = [33.3, 34.9]
                    units = ''
                if name.find('temperature') != -1:
                    if not self.autoscale:
                        rangez = [10.0, 14.0]
                    units = ' ($^\circ$C)'

                logger.debug('getting subplot ax0')
                gs = gridspec.GridSpecFromSubplotSpec(1,
                                                      1,
                                                      subplot_spec=plot_gs[j])
                ax0_plot = plt.Subplot(fig, gs[:])
                fig.add_subplot(ax0_plot)

                gs = gridspec.GridSpecFromSubplotSpec(1,
                                                      1,
                                                      subplot_spec=plot_gs[j +
                                                                           1])
                ax0_colorbar = plt.Subplot(fig, gs[:])
                fig.add_subplot(ax0_colorbar)

                if plot_scatter_contour:
                    logger.debug('getting subplot ax1')
                    gs = gridspec.GridSpecFromSubplotSpec(
                        1, 1, subplot_spec=plot_gs[j + 2])
                    ax1_plot = plt.Subplot(fig, gs[:])
                    fig.add_subplot(ax1_plot)

                    gs = gridspec.GridSpecFromSubplotSpec(
                        1, 1, subplot_spec=plot_gs[j + 3])
                    ax1_colorbar = plt.Subplot(fig, gs[:])
                    fig.add_subplot(ax1_colorbar)

                # if no data found add in some fake data and plot a placeholder time/depth plot
                if not x:
                    tmin = time.mktime(start_datetime.timetuple())
                    tmax = time.mktime(end_datetime.timetuple())
                    x.append(tmin)
                    x.append(tmax)
                    y.append(np.NaN)
                    y.append(np.NaN)
                    z.append(np.NaN)
                    z.append(np.NaN)

                if plot_scatter_contour:
                    cs0, _, scale_factor = self.createContourPlot(
                        title + pn, ax0_plot, x, y, z, rangey, rangez,
                        start_datetime, end_datetime, sdt_count)
                    cs1 = self.createScatterPlot(title + pn, ax1_plot, x, y, z,
                                                 rangey, rangez,
                                                 start_datetime, end_datetime)
                elif plot_step:
                    cs0 = self.createStepPlot(title + pn, title, ax0_plot, x,
                                              z, rangez, start_datetime,
                                              end_datetime)
                elif plot_scatter:
                    cs0 = self.createScatterPlot(title + pn, ax0_plot, x, y, z,
                                                 rangey, rangez,
                                                 start_datetime, end_datetime)
                else:
                    cs0, _, scale_factor = self.createContourPlot(
                        title + pn, ax0_plot, x, y, z, rangey, rangez,
                        start_datetime, end_datetime, sdt_count)

                if plot_scatter_contour:
                    ax1_plot.text(0.95,
                                  0.02,
                                  name,
                                  verticalalignment='bottom',
                                  horizontalalignment='right',
                                  transform=ax1_plot.transAxes,
                                  color='black',
                                  fontsize=8)
                    # Don't show on the upper contour plot
                    ax0_plot.xaxis.set_ticks([])
                    # Rotate date labels and format bottom
                    x_fmt = self.DateFormatter(1)
                    ax1_plot.xaxis.set_major_formatter(x_fmt)
                    for label in ax1_plot.xaxis.get_ticklabels():
                        label.set_rotation(10)
                else:
                    ax0_plot.text(0.95,
                                  0.02,
                                  name,
                                  verticalalignment='bottom',
                                  horizontalalignment='right',
                                  transform=ax0_plot.transAxes,
                                  color='black',
                                  fontsize=8)
                    # Rotate date labels and format bottom
                    x_fmt = self.DateFormatter(1)
                    ax0_plot.xaxis.set_major_formatter(x_fmt)
                    for label in ax0_plot.xaxis.get_ticklabels():
                        label.set_rotation(10)

                self.shadeNight(ax0_plot, sorted(x), rangey[0], rangey[1])
                if plot_scatter:
                    self.shadeNight(ax1_plot, sorted(x), rangey[0], rangey[1])

                logger.debug('plotting colorbars')
                if plot_scatter or plot_scatter_contour:
                    cbFormatter = FormatStrFormatter('%.2f')
                    cb = plt.colorbar(cs0,
                                      cax=ax0_colorbar,
                                      ticks=[min(rangez),
                                             max(rangez)],
                                      format=cbFormatter,
                                      orientation='vertical')
                    cb.set_label(units, fontsize=8)  #,labelpad=5)
                    cb.ax.xaxis.set_ticks_position('top')
                    for t in cb.ax.yaxis.get_ticklabels():
                        t.set_fontsize(8)

                    cb = plt.colorbar(cs1,
                                      cax=ax1_colorbar,
                                      ticks=[min(rangez),
                                             max(rangez)],
                                      format=cbFormatter,
                                      orientation='vertical')
                    cb.set_label(units, fontsize=8)  #,labelpad=5)
                    cb.ax.xaxis.set_ticks_position('top')
                    for t in cb.ax.yaxis.get_ticklabels():
                        t.set_fontsize(8)
                else:
                    if plot_step:
                        ax0_colorbar.xaxis.set_major_locator(plt.NullLocator())
                        ax0_colorbar.yaxis.set_ticks_position('right')
                        for t in ax0_colorbar.yaxis.get_ticklabels():
                            t.set_fontsize(8)
                    else:
                        cbFormatter = FormatStrFormatter('%.2f')
                        cb = plt.colorbar(cs0,
                                          cax=ax0_colorbar,
                                          ticks=[min(rangez),
                                                 max(rangez)],
                                          format=cbFormatter,
                                          orientation='vertical')
                        cb.set_label(units, fontsize=8)  #,labelpad=5)
                        cb.ax.xaxis.set_ticks_position('top')
                        for t in cb.ax.yaxis.get_ticklabels():
                            t.set_fontsize(8)

                if plot_scatter:
                    j += 4
                else:
                    j += 2

        # plot tracks
        ax = plt.Subplot(fig, map_gs[:])
        fig.add_subplot(ax, aspect='equal')

        z = []
        logger.debug('getting measured data')
        z, points, maptracks = self.getMeasuredPPData(start_datetime,
                                                      end_datetime, pn,
                                                      self.plotDotParmName)

        # get the percentile ranges for this to autoscale
        pointsnp = np.array(points)
        lon = pointsnp[:, 0]
        lat = pointsnp[:, 1]

        ltmin = self.extent['maptrack__extent'][1]
        ltmax = self.extent['maptrack__extent'][3]
        lnmin = self.extent['maptrack__extent'][0]
        lnmax = self.extent['maptrack__extent'][2]
        lndiff = abs(lnmax - lnmin)
        ltdiff = abs(ltmax - ltmin)
        logger.debug("lon diff {} lat diff {}".format(lndiff, ltdiff))
        mindeg = .02
        paddeg = .01
        if lndiff < mindeg:
            lnmin -= mindeg
            lnmax += mindeg
        if ltdiff < mindeg:
            ltmin -= mindeg
            ltmax += mindeg

        e = (lnmin - paddeg, ltmin - paddeg, lnmax + paddeg, ltmax + paddeg)
        logger.debug('Extent {},{},{},{})'.format(e[0], e[1], e[2], e[3]))
        # retry up to 5 times to get the basemap
        for i in range(0, 5):
            logger.debug('Getting basemap')
            mp = Basemap(llcrnrlon=e[0],
                         llcrnrlat=e[1],
                         urcrnrlon=e[2],
                         urcrnrlat=e[3],
                         projection='cyl',
                         resolution='l',
                         ax=ax)
            try:
                # Works, but coarse resolution
                ##mp.wmsimage('http://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?', layers=['GEBCO_08_Grid'])
                mp.arcgisimage(
                    server='http://services.arcgisonline.com/ArcGIS',
                    service='Ocean_Basemap')
                mp.drawparallels(np.linspace(e[1], e[3], num=3),
                                 labels=[True, False, False, False],
                                 fontsize=8,
                                 linewidth=0)
                mp.drawmeridians(np.linspace(e[0], e[2], num=3),
                                 labels=[False, False, False, True],
                                 fontsize=8,
                                 linewidth=0)
            except Exception as e:
                logger.error('Could not download ocean basemap ')
                mp = None

            if mp is not None:
                break

        if mp is None:
            logger.debug('Error - cannot cannot fetch basemap')
            return

        try:
            logger.debug('plotting tracks')
            if self.animate:
                try:
                    track = LineString(points).simplify(tolerance=.001)
                    if track is not None:
                        ln, lt = list(zip(*track))
                        mp.plot(ln,
                                lt,
                                '-',
                                c='k',
                                alpha=0.5,
                                linewidth=2,
                                zorder=1)
                except TypeError as e:
                    logger.warning(
                        "{}\nCannot plot map track path to None".format(e))
            else:
                for track in maptracks:
                    if track is not None:
                        ln, lt = list(zip(*track))
                        mp.plot(ln,
                                lt,
                                '-',
                                c='k',
                                alpha=0.5,
                                linewidth=2,
                                zorder=1)

            # if have a valid series, then plot the dots
            if self.plotDotParmName and len(z) > 0:
                if len(z) > 2000:
                    sz = len(z)
                    stride = int(sz / 200)
                    z_stride = z[0:sz:stride]
                    lon_stride = lon[0:sz:stride]
                    lat_stride = lat[0:sz:stride]
                    mp.scatter(lon_stride,
                               lat_stride,
                               c=z_stride,
                               marker='.',
                               lw=0,
                               alpha=1.0,
                               cmap=self.cm_jetplus,
                               label=self.plotDotParmName,
                               zorder=2)
                    if stride > 1:
                        ax.text(0.70,
                                0.1, ('{} (every {} points)'.format(
                                    self.plotDotParmName, stride)),
                                verticalalignment='bottom',
                                horizontalalignment='center',
                                transform=ax.transAxes,
                                color='black',
                                fontsize=8)
                    else:
                        ax.text(
                            0.70,
                            0.1,
                            ('{} (every point)'.format(self.plotDotParmName)),
                            verticalalignment='bottom',
                            horizontalalignment='center',
                            transform=ax.transAxes,
                            color='black',
                            fontsize=8)

                else:
                    mp.scatter(lon,
                               lat,
                               c=z,
                               marker='.',
                               lw=0,
                               alpha=1.0,
                               cmap=self.cm_jetplus,
                               label=self.plotDotParmName,
                               zorder=2)
                    ax.text(0.70,
                            0.1,
                            ('{} (every point)'.format(self.plotDotParmName)),
                            verticalalignment='bottom',
                            horizontalalignment='center',
                            transform=ax.transAxes,
                            color='black',
                            fontsize=8)

            if self.booleanPlotGroup:
                # plot the binary markers
                markers = ['o', 'x', 'd', 'D', '8', '1', '2', '3', '4']
                i = 1
                for g in self.booleanPlotGroup:
                    parm = [z2.strip() for z2 in g.split(',')]
                    for name in parm:
                        if name in self.plotGroupValid:
                            logger.debug(
                                'Plotting boolean plot group parameter {}',
                                name)
                            z, points, maptracks = self.getMeasuredPPData(
                                start_datetime, end_datetime,
                                self.platformName[0], name)
                            pointsnp = np.array(points)
                            lon = pointsnp[:, 0]
                            lat = pointsnp[:, 1]
                            # scale up the size of point
                            s = [20 * val for val in z]
                            if len(z) > 0:
                                mp.scatter(lon,
                                           lat,
                                           s=s,
                                           marker=markers[i],
                                           c='black',
                                           label=name,
                                           zorder=3)
                            i = i + 1

            # plot the legend outside the plot in the upper left corner
            l = ax.legend(loc='upper left',
                          bbox_to_anchor=(1, 1),
                          prop={'size': 8},
                          scatterpoints=1)  # only plot legend symbol once
            l.set_zorder(4)  # put the legend on top

        except Exception as e:
            logger.warning(e)

        if self.animate:
            # append frames output as pngs with an indexed frame number before the gif extension
            fname = '{}/frame_{:02}.png'.format(self.dirpath, self.frame)
        else:
            fname = self.outFilename

        logger.debug('Saving figure {}'.format(fname))
        fig.savefig(fname, dpi=120)  #,transparent=True)
        plt.close()
        self.frame += 1

        logger.debug('Done with contourPlot')
Example #55
0
    im1 = mapProj.contourf(xptsIS2,
                           yptsIS2,
                           griddedVar[i],
                           levels=np.linspace(minval[i], maxval[i],
                                              numConts[i]),
                           cmap=cmaps[i],
                           extend='both',
                           shading='gouraud',
                           edgecolors='None',
                           zorder=4,
                           rasterized=True)
    # lower colorbar bounds
    plt.clim(minval[i], maxval[i])
    mapProj.drawparallels(np.arange(90, -90, -10), linewidth=0.25, zorder=10)
    mapProj.drawmeridians(np.arange(-180., 180., 30.),
                          linewidth=0.25,
                          zorder=10)

    mapProj.fillcontinents(color='0.9', lake_color='grey', zorder=5)
    mapProj.drawcoastlines(linewidth=0.25, zorder=5)
    ax.annotate('(' + chr(97 + i) + ') ' + variables[i],
                xy=(0.03, 0.03),
                backgroundcolor='w',
                xycoords='axes fraction',
                horizontalalignment='left',
                verticalalignment='bottom',
                fontsize=8,
                zorder=10)

    cax = fig.add_axes([cbarx[i], cbary[i], 0.2, 0.025])
Example #56
0
def livemap(wd):
    os.chdir(wd)
    ref_sites = pd.read_csv(wd + '/P_ref/sites_output_0.csv')
    alt_sites = pd.read_csv(wd + '/P_alt/sites_output_0.csv')
    ref_costs = pd.read_csv(wd + '/P_ref/timeseries_output_0.csv')
    alt_costs = pd.read_csv(wd + '/P_alt/timeseries_output_0.csv')
    em_ts = pd.read_csv(wd + 'mean_emissions.csv')
    al_ts = pd.read_csv(wd + 'mean_active_leaks.csv')

    os.chdir("..")
    weather = Dataset('an_2003_2018_AB.nc', 'r')
    os.chdir(wd)

    lat_ref = np.array(ref_sites['lat'])  # [ref_samples]
    lon_ref = np.array(ref_sites['lon'])  # [ref_samples]
    lat_alt = np.array(alt_sites['lat'])  # [alt_samples]
    lon_alt = np.array(alt_sites['lon'])  # [alt_samples]

    # Get grid positions
    nc_lat = weather.variables['latitude'][:]
    nc_lon = []
    lon_360 = weather.variables['longitude'][:]
    for ele in lon_360:
        a = (ele + 180) % 360 - 180
        nc_lon.append(a)

    plt.ion()

    dates = pd.to_datetime((ref_costs.datetime))
    n_sims = len(ref_costs)
    day_list = []
    date_form = DateFormatter("%e %b %Y")

    fig = plt.figure(figsize=(15, 20))

    # Figure 1: Map
    ax1 = fig.add_subplot(121)
    map = Basemap(epsg=3401,
                  llcrnrlon=-121,
                  llcrnrlat=48.5,
                  urcrnrlon=-107,
                  urcrnrlat=60.5,
                  resolution='i',
                  area_thresh=10000.)
    map.fillcontinents(color='#272626', alpha=0.7)
    map.drawcountries(color='white', linewidth=1)
    map.drawstates(color='white', linewidth=1)
    map.drawparallels(np.arange(49., 60., 3.),
                      color="white",
                      labels=[1, 0, 0, 0],
                      fontsize=10,
                      linewidth=0.2)
    map.drawmeridians(np.arange(-120., -110., 3.),
                      color="white",
                      labels=[0, 0, 0, 1],
                      fontsize=10,
                      linewidth=0.2)

    # Build grid for raster
    m_lon, m_lat = np.meshgrid(nc_lon, nc_lat)
    xi, yi = map(m_lon, m_lat)

    # Add O&G facilities to map
    x1, y1 = map(lon_alt, lat_alt)
    x2, y2 = map(lon_ref, lat_ref)
    x1 = np.append(x1, x2)
    y1 = np.append(y1, y2)
    vals = ['Regulatory Program'] * int(len(x1) / 2) + ['Alternative Program'
                                                        ] * int(len(x1) / 2)
    df = pd.DataFrame(dict(x1=x1, y1=y1, vals=vals))
    groups = df.groupby('vals')
    colors = {
        'Regulatory Program': '#b87a02',
        'Alternative Program': '#396dc5'
    }
    for name, group in groups:
        map.plot(group.x1,
                 group.y1,
                 marker='o',
                 linestyle='',
                 ms=4,
                 label=name,
                 c=colors[name],
                 markeredgecolor='black',
                 markeredgewidth=0.8)
    ax1.legend(markerscale=4, prop={'size': 15}, loc=9)

    # Figure 2: Emissions
    ref_emissions = np.array(em_ts['mean'][0:(n_sims - 1)])
    alt_emissions = np.array(em_ts['mean'][-(n_sims - 1):])
    ES1 = []
    ES2 = []
    ax2 = fig.add_subplot(322)
    #ax2.set_xlim([0, 1000])
    #ax2.set_ylim([0, 15])
    ax2.xaxis.set_major_formatter(date_form)
    ax2.xaxis.set_major_locator(ticker.MaxNLocator(5))
    ax2.set_xlabel('')
    ax2.set_ylabel('Average emission rate \n(kg/day/facility)', fontsize=13)

    # Figure 3: Active Leaks
    ref_leaks = np.array(al_ts['mean'][0:(n_sims - 1)])
    alt_leaks = np.array(al_ts['mean'][-(n_sims - 1):])
    AL1 = []
    AL2 = []
    ax3 = fig.add_subplot(324)
    #ax3.set_xlim([0, 1000])
    #ax3.set_ylim([0, 650])
    ax3.xaxis.set_major_formatter(date_form)
    ax3.xaxis.set_major_locator(ticker.MaxNLocator(5))
    ax3.set_xlabel('')
    ax3.set_ylabel('Total active leaks \n(all facilities)', fontsize=13)

    # Figure 4: Cost
    ref_costs = np.array(ref_costs['OGI_cost']) / 500
    alt_costs = (np.array(alt_costs['aircraft_cost']) +
                 np.array(alt_costs['OGI_FU_cost'])) / 500
    C1 = []
    C2 = []
    ax4 = fig.add_subplot(326)
    #ax4.set_xlim([dates[0], dates[len(dates) - 1]])
    ax4.xaxis.set_major_formatter(date_form)
    ax4.xaxis.set_major_locator(ticker.MaxNLocator(5))
    ax4.set_ylabel('Estimated program cost \n(USD/facility/year)', fontsize=13)

    # Plotting loops
    pi = 20  # Plotting interval
    mi = 60  # Mapping interval (must be a multiple of the plotting interval)
    for t in range(int(n_sims / pi)):
        day_list.append(dates[int(t * pi)])

        if int(t * pi) > 120:
            date_form = DateFormatter("%b %Y")
            ax2.xaxis.set_major_formatter(date_form)
            ax3.xaxis.set_major_formatter(date_form)
            ax4.xaxis.set_major_formatter(date_form)

        # Figure 1: Map
        if ((t * pi) / mi).is_integer():
            if (t * pi) / mi >= 2:
                cbar.remove()
                cs.remove()
            tm = weather.variables['t2m'][int(t * pi), :, :] - 273.15
            cs = map.pcolor(xi,
                            yi,
                            np.squeeze(tm),
                            alpha=0.8,
                            ax=ax1,
                            vmin=-20,
                            vmax=20,
                            cmap='jet')
            cbar = map.colorbar(cs, location='bottom', pad="5%", ax=ax1)
            cbar.set_alpha(1)
            cbar.draw_all()
            cbar.set_label('Temperature (' + u'\N{DEGREE SIGN}' + 'C)',
                           fontsize=12)
        ann = ax1.annotate(dates[int(t * pi)].strftime("%b %Y"),
                           xy=(0.38, 0.83),
                           xycoords='axes fraction',
                           fontsize=17,
                           color='white')

        # Figure 2: Emissions
        ES1.append(ref_emissions[int(t * pi)])
        ES2.append(alt_emissions[int(t * pi)])
        ax2.plot(day_list, ES1, color='#b87a02')
        ax2.plot(day_list, ES2, color='#396dc5')

        # Figure 3: Active leaks
        AL1.append(ref_leaks[int(t * pi)])
        AL2.append(alt_leaks[int(t * pi)])
        ax3.plot(day_list, AL1, color='#b87a02')
        ax3.plot(day_list, AL2, color='#396dc5')

        # Figure 4: Costs
        C1.append(sum(ref_costs[0:t * pi]) * 365 / ((t + 1) * pi))
        C2.append(sum(alt_costs[0:t * pi]) * 365 / ((t + 1) * pi))
        ax4.plot(day_list, C1, color='#b87a02')
        ax4.plot(day_list, C2, color='#396dc5')

        plt.pause(0.2)
        ann.remove()

        # if int(t*pi) != ref_costs.shape[0] - 1:
        #     cbar.remove()

    weather.close()
os.chdir('Plots')  # Change directory to Plots folder

# Initialise figure
print('\nInitialise plot...\n')
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

# Plotting map
if proj == 'cyl':
    bmlowlat, bmupperlat, bmleftlon, bmrightlon = -70, -40, -100, -50
    map = Basemap(projection='cyl',llcrnrlat=bmlowlat,urcrnrlat=bmupperlat,\
       llcrnrlon=bmleftlon,urcrnrlon=bmrightlon,resolution='i', ax=ax1)
    # ~ map.fillcontinents(color='#ffdd99', lake_color='#cceeff')
    # ~ map.drawmapboundary(linewidth=0.75, fill_color='#cceeff')
    map.drawcoastlines(linewidth=0.25, color='black', zorder=3)
    map.drawmeridians([-90, -80, -70, -60, -50], linewidth=0.3)
    map.drawparallels([-70, -60, -50], linewidth=0.3)

    # Plotting
    cs = plt.contourf(matlon1,
                      matlat1,
                      matTp1,
                      cmap=rdbucmap,
                      zorder=2,
                      vmin=-20,
                      vmax=20,
                      levels=np.linspace(-20, 20, 17),
                      extend='both')

    # Fix axes
    ax1.set_xticks([-100, -90, -80, -70, -60, -50])
#global_scale = '10m'
# proj = ccrs.Mercator()

map = Basemap(projection='merc',llcrnrlat=-39.5,urcrnrlat=-33.5,\
              llcrnrlon=140.5,urcrnrlon=150.5,lat_ts=20,resolution='h')

map.drawcoastlines()
map.fillcontinents(color='#E6F5B1', lake_color='#D3E4E0')

map.drawparallels(np.arange(-39., -33., 1.0),
                  dashes=[1, 5],
                  color='0.5',
                  labels=[1, 0, 0, 0])
map.drawmeridians(np.arange(140., 151., 1.0),
                  dashes=[1, 5],
                  color='0.5',
                  labels=[0, 0, 0, 1])

map.drawmapboundary(fill_color='#D3E4E0')
ax = plt.axes()
# ax.coastlines(resolution=global_scale)
# gl = ax.gridlines(crs=ccrs.PlateCarree(),draw_labels=True)
# gl.xlabels_top = False
# gl.ylabels_left = False
# gl.xlocator = mticker.FixedLocator(list(range(140,152)))
# gl.ylocator = mticker.FixedLocator(list(range(-33,-41,-1)))
# gl.xformatter = LONGITUDE_FORMATTER
# gl.yformatter = LATITUDE_FORMATTER
# ax.set_extent((140.5,150.5,-33.5,-39.5),crs=ccrs.PlateCarree())
#ax.set_xticks(list(range(140,151)),crs=ccrs.PlateCarree())
# plt.title('Param: FDR',fontweight='light')
Example #59
0
# bmap = Basemap(llcrnrlon=80.33,
#               llcrnrlat=3.01,
#               urcrnrlon=138.16,
#               urcrnrlat=56.123,
#              resolution='h', projection='cass', lat_0 = 42.5,lon_0=120)
#

shp_info = bmap.readshapefile("D:\\GoogleDownload\\CHN_adm_shp\\CHN_adm1",
                              'states',
                              drawbounds=False)

for info, shp in zip(bmap.states_info, bmap.states):
    proid = info['NAME_1']
    if proid == 'Guangdong':
        poly = Polygon(shp, facecolor='g', edgecolor='b', lw=0.8)
        ax1.add_patch(poly)

bmap.drawcoastlines()
#bmap.drawcountries()
bmap.drawparallels(np.arange(3, 55, 10), labels=[1, 0, 0, 0])
bmap.drawmeridians(np.arange(80, 140, 10), labels=[0, 0, 0, 1])
plt.title('Province')
plt.show()
plt.savefig('d:\\fig_province.png', dpi=100, bbox_inches='tight')
plt.clf()
plt.close()
end = time.clock()

print(end - start)
Example #60
0
    def plotmap(self, data, ptype = "map", title = "", ltitle = "", rtitle = "", info = None, filename = "test.png", dpi = 125,
                drawcoast = True, drawgrid = True, levels = 20, vmin = None, vmax = None, bounds = None, ticks = None, zoom = dict(north = 90, south = -90, west = -180, east = 180), custom_cmap=None, plot_cbar=True, label_cbar=None, region=None,cmap_ticks=None,cbar_tick_labels=None,alpha=None):

        # What version supports using an array for alpha?  More recent
        # than 3.4.
        print("Plotting a map using Matplotlib version {}.".format(matplotlib.__version__))

        # I need an axes object for some of these methods
        fig, ax = plt.subplots(figsize=(7, 7))

        delta = 3
        north = min( 90, max(self.lat) + delta, zoom["north"] + delta)
        south = max(-90, min(self.lat) - delta, zoom["south"] - delta)
        west = max(-180, min(self.lon) - delta, zoom["west"] - delta)
        east = min( 180, max(self.lon) + delta, zoom["east"] + delta)
        m = Basemap(projection = "mill", llcrnrlat = south, urcrnrlat = north, llcrnrlon = west, urcrnrlon = east, resolution = "l")
        if drawcoast: m.drawcoastlines(linewidth=0.5)
        if drawgrid:
            if north-south > 150: parallels = [-80, -60, -30, 0, 30, 60, 80]
            else: parallels = np.arange(-90, 91, getStep(south, north))
            m.drawparallels(parallels, labels = [1, 0, 1, 1])
            m.drawmeridians(np.arange(-180, 181, getStep(west, east)), labels = [0, 0, 0, 1])
        if ptype == "map":
            cmap = matplotlib.colors.LinearSegmentedColormap("my_colormap", rainbow, levels)
        elif ptype == "dif":
            cmap = matplotlib.colors.LinearSegmentedColormap("my_colormap", diverge, levels)
            lim = max(abs(np.percentile(data.compressed(), 1)), abs(np.percentile(data.compressed(), 99))) if type(data) is np.ma.masked_array else max(abs(np.percentile(data, 1)), abs(np.percentile(data, 99)))
            vmin = -lim
            vmax = lim
        elif ptype == "custom_cmap":
            cmap = custom_cmap
        elif ptype == "correlation":
            cmap = plt.get_cmap("coolwarm")
        elif ptype == 'correlation_truncated':

            # The point of this is go from blue to white, then stay white for
            # a while, and then go white to red.  In this way, weak correlation
            # values won't be shown.
            coolwarm = cm.get_cmap('coolwarm', 256)
            cool=coolwarm(0.0)
            warm=coolwarm(1.0)
            trunc_colors = {"red"   : [[0.0, cool[0], cool[0]],
                                       [0.4, 1.0, 1.0],
                                       [0.6, 1.0, 1.0],
                                       [1.0, warm[0], warm[0]]],
                            "green"   : [[0.0, cool[1],cool[1]],
                                         [0.4, 1.0, 1.0],
                                         [0.6, 1.0, 1.0],
                                         [1.0, warm[1],warm[1]]],
                            "blue"   : [[0.0, cool[2],cool[2]],
                                        [0.4, 1.0, 1.0],
                                        [0.6, 1.0, 1.0],
                                        [1.0, warm[2],warm[2]]]}
            cmap = matplotlib.colors.LinearSegmentedColormap("my_colormap", trunc_colors, levels)

        #endif

        norm = None if bounds is None else matplotlib.colors.BoundaryNorm(boundaries=bounds, ncolors=levels)
        if bounds is not None: vmin = vmax = None
        o = (self.meshlat <= north) & (self.meshlat >= south) & (self.meshlon >= west) & (self.meshlon <= east)
        inorth = np.where(self.lat <= north)[0][0]
        isouth = np.where(self.lat >= south)[0][-1]
        iwest = np.where(self.lon >= west)[0][0]
        ieast = np.where(self.lon <= east)[0][-1]
        cmesh = m.pcolormesh(self.meshlon[inorth:isouth+2,iwest:ieast+2], self.meshlat[inorth:isouth+2,iwest:ieast+2], data[inorth:isouth+1,iwest:ieast+1],
                                 shading = "flat", cmap = cmap, latlon = True, vmin = vmin, vmax = vmax, norm = norm, alpha = alpha)
        if plot_cbar:
            cbar = m.colorbar(cmesh, pad = 0.08, location = "right")
            if label_cbar is not None:
                cbar.set_label(label_cbar)
            #endif
            if cbar_tick_labels is not None:
                cbar.set_ticklabels(cbar_tick_labels)
            #endif
        #endif
        if bounds is not None: cbar.set_ticks(bounds)
        if ticks is not None: cbar.set_ticks(ticks)
        if info is not None: plt.annotate(info, xy = (0.05, 0.05), xycoords = "axes fraction")
        if title != "": plt.title(title)
        if ltitle != "": plt.title(ltitle, loc = "left")
        if rtitle != "": plt.title(rtitle, loc = "right")
        # Plot some regions
        if region: # This is a list of lists

            #x,y=m(0.0,0.0)
            #print("Origin at ",x,y)

            for region_bounds in region: # [lon, lat, width, height, angle]
                # The map returns lon,lat
                x,y=m(region_bounds[0],region_bounds[1])
                #ax.text(x, y, 'Lagos{}'.format(region_bounds[0]),fontsize=12,fontweight='bold',
                #    ha='left',va='bottom',color='k')
                delx,dely=m(region_bounds[2],region_bounds[3])
                width1,height1=m(region_bounds[0]-region_bounds[2],region_bounds[1]-region_bounds[3])
                width2,height2=m(region_bounds[0]+region_bounds[2],region_bounds[1]+region_bounds[3])
                width=width2-width1
                height=height2-height1
            #    print("REGION ",region_bounds,x,y,width,height)
                ax.add_artist(Ellipse((x,y), width,height,angle=region_bounds[4],fc=None,Fill=False,ec="red",lw=2))

            #endif

            ax.add_artist(Ellipse((0.0,0.0), 0.5,0.5))

        #endif

        plt.tight_layout()

        fig.savefig(filename, dpi = dpi)
        #plt.clf()
        plt.close()