Example #1
0
def plot_annotaiton_gps(X_Data):
    """ Plots gps coordinates on a map projection """
    from mpl_toolkits.basemap import Basemap
    #lat = X_data[1:5, 1]
    #lon = X_data[1:5, 2]
    lat = X_data[:, 1]
    lon = X_data[:, 2]
    fig = df2.figure(fnum=1, doclf=True, docla=True)
    df2.close_figure(fig)
    fig = df2.figure(fnum=1, doclf=True, docla=True)
    # setup Lambert Conformal basemap.
    m = Basemap(llcrnrlon=lon.min(),
                urcrnrlon=lon.max(),
                llcrnrlat=lat.min(),
                urcrnrlat=lat.max(),
                projection='cea',
                resolution='h')
    # draw coastlines.
    #m.drawcoastlines()
    #m.drawstates()
    # draw a boundary around the map, fill the background.
    # this background will end up being the ocean color, since
    # the continents will be drawn on top.
    #m.bluemarble()
    m.drawmapboundary(fill_color='aqua')
    m.fillcontinents(color='coral', lake_color='aqua')
    # Convert GPS to projected coordinates
    x1, y1 = m(lon, lat)  # convert to meters # lon==X, lat==Y
    m.plot(x1, y1, 'o')
    fig.show()
Example #2
0
def el_plot(data, Map=False, show=True):
    """
    Plot the elevation for the region from the last time series
    
    :Parameters:
        **data** -- the standard python data dictionary
        
        **Map** -- {True, False} (optional): Optional argument.  If True,
            the elevation will be plotted on a map.  
    """
    trigrid = data['trigrid']
    plt.gca().set_aspect('equal')
    plt.tripcolor(trigrid, data['zeta'][-1,:])
    plt.colorbar()
    plt.title("Elevation")
    if Map:
        #we set the corners of where the map should show up
        llcrnrlon, urcrnrlon = plt.xlim()
        llcrnrlat, urcrnrlat = plt.ylim()
        #we construct the map.  Note that resolution serves to increase
        #or decrease the detail in the coastline.  Currently set to 
        #'i' for 'intermediate'
        m = Basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, \
            resolution='i', suppress_ticks=False)
        #set color for continents.  Default is grey.
        m.fillcontinents(color='ForestGreen')
        m.drawmapboundary()
        m.drawcoastlines()
    if show:
        plt.show()
Example #3
0
    def WorkBook_plotPrisons(self, coords):
        lons = coords[0]
        lats = coords[1]

        print("Graphing image...")
        m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64,
            urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45,
            lon_0=-95, resolution='h', area_thresh=10000)
        x, y = m(lons, lats)

        m.drawmapboundary(fill_color='white')
        m.fillcontinents(color='white',lake_color='white')
        m.scatter(x,y,10,marker='D',color='m')

        plt.figure(frameon=False)
        plt.title('US Prison Locations',fontsize=12)
        plt.savefig("USPrisons.png")

        background = Image.open("SocioEconomicBackground.png")
        overlay = Image.open("USPrisons.png")

        background = background.convert("RGBA")
        overlay = overlay.convert("RGBA")

        new_img = Image.blend(background, overlay, 0.5)
        new_img.save("SocioEconomic_Prison.png","PNG")
Example #4
0
class Map:
    def __init__(self, boundary=[[24.527135, -127.792969], [49.61071, -59.765625]], default=True):
        from mpl_toolkits.basemap import Basemap

        minLat, minLon, maxLat, maxLon = [item for t in boundary for item in t]
        self.m = Basemap(
            llcrnrlon=minLon,
            llcrnrlat=minLat,
            urcrnrlon=maxLon,
            urcrnrlat=maxLat,
            resolution="l",
            projection="merc",
            area_thresh=1000000,
            lon_0=minLon + (maxLon - minLon) / 2,
            lat_0=minLat + (maxLat - minLat) / 2,
        )
        if default:
            self.configure()

    def configure(self):
        self.m.drawcoastlines(linewidth=1.0)
        self.m.drawcountries(linewidth=1.0)
        self.m.fillcontinents(color="#FFFFFF", lake_color="#FFFFFF")
        self.m.drawstates(linewidth=0.5)
        self.m.drawmapboundary(fill_color="#FFFFFF")

    def plotPoints(self, longitude, latitudes, color, lw=0, marker="o", *args, **kwargs):
        mlon, mlat = self.m(longitude, latitudes)
        self.m.plot(mlon, mlat, color=color, lw=lw, marker=marker, *args, **kwargs)
Example #5
0
def plot_map_twts(twts, title='default title'):
    """
    Given an iterable of 'clean' tweets, make a dot map over North America.
    """
    fig1 = plt.figure()
    ax = fig1.add_subplot(111)
    m = Basemap(projection='merc',
        resolution = 'l',
        llcrnrlon=-136.0, llcrnrlat=24.0,
        urcrnrlon=-67.0, urcrnrlat=60.0,
        ax=ax)

    m.drawcoastlines()
    m.drawcountries()
    m.drawstates()
    m.fillcontinents(color = 'coral', alpha=0.5)
    m.drawmapboundary()

    lons = [twt['coordinates'][0] for twt in twts]
    lats = [twt['coordinates'][1] for twt in twts]
    x,y = m(lons, lats)

    m.plot(x, y, 'bo', markersize=5)
    plt.title(title)
    plt.show()
 def plot_filtered_diff(self):
     """
     function for plotting the difference of filtered vorticity
     """
     
     w_diff, lon, lat, mask = self.vorticity_filter()
     
     south = lat.min(); north =lat.max()
     west = lon.min(); east = lon.max()
     
     timeformat = '%Y%m%d-%H%M'
     for i in range(len(self.time)):
         fig = plt.figure(figsize=(10,8))
         basemap = Basemap(projection='merc',llcrnrlat=south,urcrnrlat=north,\
                   llcrnrlon=west,urcrnrlon=east, resolution='h')
         
         basemap.drawcoastlines()
         basemap.fillcontinents(color='coral',lake_color='aqua')
         basemap.drawcountries()
         basemap.drawstates()  
         
         llons, llats=basemap(lon,lat)   
         con = basemap.pcolormesh(llons,llats,w_diff[i,:,:])
         #con.set_clim(vmin=-0.0003, vmax=0.0003)
         cbar = plt.colorbar(con, orientation='vertical')
         cbar.set_label("vorticity")
         #plt.show()
         timestr = datetime.strftime(self.time[i], timeformat)
         plt.title('vorticity at %s'%timestr)
         plt.savefig(self.wdr+'/vorticity_figure/vorticity_diff/'+str(i)+'.png')
         print "Saving figure %s to ROMS figure directory"%str(i)
Example #7
0
File: bma.py Project: xe1gyq/EekMex
def mapTut():

    m = Basemap(projection='mill',llcrnrlat=20,urcrnrlat=50,\
                llcrnrlon=-130,urcrnrlon=-60,resolution='c')
    m.drawcoastlines()
    m.drawcountries()
    m.drawstates()
    m.fillcontinents(color='#04BAE3',lake_color='#FFFFFF')
    m.drawmapboundary(fill_color='#FFFFFF')


    # Houston, Texas

    lat,lon = 29.7630556,-95.3630556
    x,y = m(lon,lat)
    m.plot(x,y, 'ro')
    

    lon, lat = -104.237, 40.125 # Location of Boulder

    xpt,ypt = m(lon,lat)
    m.plot(xpt,ypt, 'go')


    
    plt.title("Geo Plotting")
    plt.show()
Example #8
0
def contourMap(grdROMS, tlon, tlat, mydata1, mydata2, mydata3, var, mytype, currentdate):

    plt.figure(figsize=(10,10), frameon=False)
    
    map = Basemap(lon_0=25,boundinglat=50,
                      resolution='l',area_thresh=100.,projection='npstere')
    
    x, y = list(map(tlon,tlat))

    map.drawcoastlines()
    map.fillcontinents(color='grey')
    map.drawcountries()

    if var=='wind':
        levels = np.arange(np.min(mydata3),np.max(mydata3),0.1)
   
        CS1 = map.contourf(x, y, mydata3, levels, cmap=cm.get_cmap('RdYlBu_r',len(levels)-1) )#,alpha=0.5)
        plt.colorbar(CS1, orientation='vertical', extend='both', shrink=0.5)
            
        if mytype=="REGSCEN":
          step=8
        else:
          step=1
        map.quiver(x[0:-1:step,0:-1:step],y[0:-1:step,0:-1:step],
            mydata1[0:-1:step,0:-1:step],mydata2[0:-1:step,0:-1:step],
            scale=400)
   
  #  plt.title('Var:%s - depth:%s - time:%s'%(var,grdROMS.time))
    plotfile='figures/'+str(var)+'_'+str(mytype)+'_time_'+str(currentdate)+'.png'
    if not os.path.exists('figures'):
        os.makedirs('figure')
    plt.savefig(plotfile)
    print("Saved figure: %s"%(plotfile))
Example #9
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 #10
0
def plot_world_sst():
    # Read some NetCDF data
    import netCDF4 as nc
    
    ostia = nc.Dataset('ostia.nc')
    tmp = ostia.variables['analysed_sst'][0]
    ice = ostia.variables['sea_ice_fraction'][0]
    lon = ostia.variables['lon'][:]
    lat = ostia.variables['lat'][:]

    from mpl_toolkits.basemap import Basemap

    # Set up a map
    map = Basemap(projection='cyl')
    map.drawcoastlines()
    map.drawcountries()
    map.fillcontinents(color='lightgreen', lake_color='lightblue');
    map.drawmapboundary(fill_color='lightblue')

    # Re-project the data onto the map
    image = map.transform_scalar(tmp,lon,lat,200,200)

    # Plot the data
    map.imshow(image);

    plt.show()
Example #11
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 #12
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
Example #13
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 #14
0
def map_trace(tr,ax='None',showpath=True,showplot=True,Lat_0=0.0,Lon_0=60.0):
   from mpl_toolkits.basemap import Basemap

   if ax == 'None':
       m = Basemap(projection='ortho',lat_0=Lat_0,lon_0=Lon_0,resolution='l')
       m.drawmapboundary()
       m.drawcoastlines()
       m.fillcontinents(color='gray',lake_color='white')
   else:
      m = ax

   x1,y1 = m(tr.stats.sac['evlo'],tr.stats.sac['evla'])
   x2,y2 = m(tr.stats.sac['stlo'],tr.stats.sac['stla'])
   m.scatter(x1,y1,s=200.0,marker='*',facecolors='y',edgecolors='k',zorder=99)
   m.scatter(x2,y2,s=20.0,marker='^',color='b',zorder=99)

   if showpath == True:
      m.drawgreatcircle(tr.stats.sac['evlo'],tr.stats.sac['evla'],
                        tr.stats.sac['stlo'],tr.stats.sac['stla'],
                        linewidth=1,color='k',alpha=0.5)

   if showplot == True:
      plt.show()
   else:
      return m
Example #15
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
Example #16
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 #17
0
def plot_us(lats, lons, save_name=None):
    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)
    big_map = Basemap(resolution='h',
                      lat_0=36, lon_0=-107.5,
                      llcrnrlat=32, llcrnrlon=-125,
                      urcrnrlat=43, urcrnrlon=-110)
    big_map.drawcoastlines()
    big_map.drawstates()
    big_map.drawcountries()
    big_map.drawmapboundary(fill_color='#7777ff')
    big_map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0)
    x, y = big_map(lons, lats)
    big_map.plot(x[0], y[0], 'ro', markersize=2)

    axins = zoomed_inset_axes(ax, 20, loc=1)
    ll_lat, ll_lon = 37.8, -122.78
    ur_lat, ur_lon = 38.08, -122.43

    axins.set_xlim(ll_lon, ur_lon)
    axins.set_ylim(ur_lon, ur_lat)

    small_map = Basemap(resolution='h',
                        llcrnrlat=ll_lat, llcrnrlon=ll_lon,
                        urcrnrlat=ur_lat, urcrnrlon=ur_lon,
                        ax=axins)
    small_map.drawcoastlines()
    small_map.drawmapboundary(fill_color='#7777ff')
    small_map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0)
    x, y = small_map(lons, lats)
    small_map.plot(x, y, 'ro', markersize=3)

    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
    if save_name: 
        fig.savefig(save_name)
Example #18
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 #19
0
    def GDELT_maplot(self, point_counts, centro_lat, centro_lon, llat, llon, ulat, ulon): #,centro_lat,centro_lon,llat,llon,ulat,ulon):

        # print point_counts
        # print centro_lat, centro_lon, llat, llon, ulat, ulon

        def get_size(count):
            ''' Convert a count to a point size. Log-scaled.'''
            scale_factor = 2
            return np.log10(count + 1) * scale_factor

        # Note that we're drawing on a regular matplotlib figure, so we set the
        # figure size just like we would any other.
        plt.figure(figsize=(10, 10))

        # Create the Basemap
        event_map = Basemap(projection='merc',
                            resolution='l', area_thresh=1000.0,  # Low resolution
                            lat_0= centro_lat, lon_0=centro_lon,  # Map center
                            llcrnrlon=llon, llcrnrlat=llat,  # Lower left corner
                            urcrnrlon=ulon, urcrnrlat=ulat)  # Upper right corner

        # Draw important features
        event_map.drawcoastlines()
        event_map.drawcountries()
        event_map.fillcontinents(color='0.8')  # Light gray
        event_map.drawmapboundary()

        # Draw the points on the map:
        for point, count in point_counts.iteritems():
            x, y = event_map(point[1], point[0])  # Convert lat, long to y,x
            # print x , y
            marker_size = get_size(count)
            event_map.plot(x, y, 'ro', markersize=marker_size, alpha=0.3)

        plt.show()
Example #20
0
def draw_map_with_labels(labels, map_number):
    """
    Draws a map once the labels substituting country names are given
    """
    min_lon = -20.
    max_lon = 49.
    min_lat = 32.
    max_lat = 60.
    europe = Basemap(
        resolution='l',
        projection='aea',
        lon_0=0,
        lat_0=40,
        llcrnrlat=min_lat,
        urcrnrlat=max_lat,
        llcrnrlon=min_lon,
        urcrnrlon=max_lon,
        lat_ts=(min_lon+max_lon)/2)
    europe.drawcountries(linewidth=0.2, color=COUNTRY_COLOR)
    europe.drawmapboundary(linewidth=0.5, fill_color=SEA_COLOR)
    europe.fillcontinents(color=LAND_COLOR, lake_color=SEA_COLOR)
    europe.drawcoastlines(linewidth=0.2)
    for label in labels:
        lon, lat = europe(label[1], label[2])
        plt.text(lon, lat, label[0],
                 color=TEXT_COLOR, fontweight='heavy', fontstyle='oblique',
                 ha='center', clip_on=True)
    plt.tight_layout()
    logging.info('Saving into file: languages_{}.png'.format(map_number + 1))
    plt.savefig('languages_{}.png'.format(map_number + 1))
def test_geographic_histogram():
    tropics = UniformRandomPointSource()
    tropics.num_points = 100000
    tropics.bbox_min = ( -180, -23.4378 )
    tropics.bbox_max = ( 180, 23.4378 )

    try:
        pyplot.figure()
        pyplot.subplot(111, aspect='equal')

        mymap = Basemap(projection='moll',
                        lon_0=0,
                        resolution='l')
        mymap.drawcoastlines(color='white', zorder=5)
        mymap.fillcontinents(color='black', lake_color='white')

        artists = geographic_histogram( mymap,
                                        tropics.points(),
                                        bbox_lowerleft=(-180, -90),
                                        bbox_upperright=(180, 90)
                                        )

        pyplot.savefig('tracktable_geographic_histogram_test.png', figsize=(4, 4), dpi=150)
        return True
    except Exception, e:
        traceback.print_exc()
        return False
Example #22
0
def basemap():
	#basemap
	try:
		from mpl_toolkits.basemap import Basemap
		import matplotlib.pyplot as plt
		#import numpy as np

		# use low resolution coastlines.
		map = Basemap(boundinglat=22,lon_0=0,projection='npaeqd',resolution='l')

		# draw coastlines, country boundaries, fill continents.
		map.drawcoastlines(linewidth=0.25)
		map.drawcountries(linewidth=0.25)
		map.fillcontinents(color='white')

		# draw the edge of the map projection region (the projection limb)
		map.drawmapboundary()

		plt.title('Contours of countries for orthographic basemap')
		plt.show()
		return 0

	except IOError as err:
		print "File error: " + str(err)

	except ValueError as err:
		print "Value Error: " + str(err)
Example #23
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 #24
0
def example_2():
    
    # retrieve data
    dir  = "/homespace/gaubert/viirs/Mband-SDR"
    geo_file     = h5py.File("%s/%s" %(dir,"GMODO_npp_d20030125_t0847056_e0848301_b00015_c20090513182937526121_gisf_pop.h5"))
    
    lats = geo_file['All_Data']['VIIRS-MOD-GEO_All']['Latitude'][:]
    lons = geo_file['All_Data']['VIIRS-MOD-GEO_All']['Longitude'][:]
    # draw map with markers for float locations
    #m = Basemap(projection='hammer',lon_0=180)
    lon_ref = lons[0][0]-lons[-1][-1]/2
    lat_ref = 10
    #m = Basemap(projection='ortho',lat_0=lat_ref,lon_0=lon_ref,resolution='l')
    m = Basemap(projection='nsper',lat_0=lat_ref,lon_0=lon_ref,satellite_height=2000*1000,resolution='l')
    
    #x, y = m(lons[0:10],lats[0:10])
    x,y  = m(lons,lats)
    
    #m.drawcoastlines()
    
    m.drawmapboundary(fill_color='#99ffff')
    m.fillcontinents(color='#cc9966',lake_color='#99ffff')
    m.scatter(x,y,s = 1 ,color='k')
    #m.drawgreatcircle(lons[0][0],lats[0][0],lons[0][-1],lats[0][-1],linewidth=2,color='b')
    #m.drawgreatcircle(lons[-1][0],lats[0][0],lons[-1][-1],lats[0][-1],linewidth=2,color='b')
    
    plt.title('Locations of %s ARGO floats active between %s and %s' %\
            (len(lats),'2002', '2003'))
    plt.savefig('/tmp/plotargo.png')
Example #25
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 #26
0
File: evis.py Project: adeze/Evis
def main():
    data = numpy.genfromtxt("data.csv", dtype=None, delimiter=',', names=True)
#lat - data[x][1]
#lon - data[x][2]
    print(data)

    # Note that we're drawing on a regular matplotlib figure, so we set the
    # figure size just like we would any other.
    plt.figure(figsize=(28,18))

    # Create the Basemap
    event_map = Basemap(projection='merc',
                        resolution='l', area_thresh=1000.0, # Low resolution
                        lat_0 = 55.0, lon_0=60.0, # Map center
                        llcrnrlon=-179, llcrnrlat=-72, # Lower left corner
                        urcrnrlon=179, urcrnrlat=78) # Upper right corner

    # Draw important features
    event_map.drawcoastlines()
    event_map.drawcountries()
    event_map.fillcontinents(color='0.8') # Light gray
    event_map.drawmapboundary()

    a = [f for f in data if int(f[2])<500]
    b = [f for f in data if int(f[2])<500]

    # Draw the points on the map:
    for i in range(len(data)-8000):
        x, y = event_map(data[i][2], data[i][1]) # Convert lat, long to y,x
        marker_size = data[i][3]/4
        event_map.plot(x,y, 'ro', markersize=marker_size, alpha=0.3)

    plt.savefig('map.png', bbox_inches='tight')
Example #27
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()
Example #28
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 #29
0
def plotPointsOnUSMap(points, blueMarble=False, bkcolor='#85A6D9', returnBaseMapObject = False, pointLabels=[], *args, **kwargs):
    from mpl_toolkits.basemap import Basemap
    m = Basemap(llcrnrlon=-125.15625, llcrnrlat=20, urcrnrlon=-59.765625, urcrnrlat=49.61071, projection='mill', lat_1=24, lat_2=50, lon_0=-98, resolution='l', area_thresh=10000)
    m.drawmapboundary(fill_color='#85A6D9')
    
    if blueMarble: m.bluemarble()
    else:
        m.drawmapboundary(fill_color=bkcolor)
        m.fillcontinents(color='white',lake_color=bkcolor)
        m.drawcoastlines(color='#6D5F47', linewidth=.4)
        m.drawcountries(color='#6D5F47', linewidth=.4)
        m.drawstates(color='#6D5F47', linewidth=.4)
    
#    m.fillcontinents(color='white',lake_color='#85A6D9')
#    m.drawstates(color='#6D5F47', linewidth=.4)
#    m.drawcoastlines(color='#6D5F47', linewidth=.4)
#    m.drawcountries(color='#6D5F47', linewidth=.4)
    
#    m.drawmeridians(n.arange(-180, 180, 30), color='#bbbbbb')
#    m.drawparallels(n.arange(-90, 90, 30), color='#bbbbbb')
    lats, lngs = zip(*points)
    
    x,y = m(lngs,lats)
    scatterPlot = m.scatter(x, y, zorder = 2, *args, **kwargs)
    
    for population, xpt, ypt in zip(pointLabels, x, y):
        label_txt = str(population)
        plt.text( xpt, ypt, label_txt, color = 'black', size='small', horizontalalignment='center', verticalalignment='center', zorder = 3)
    if not returnBaseMapObject: return scatterPlot
    else: return (scatterPlot, m)
Example #30
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 #31
0
#!/usr/bin/env python

from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
#m = Basemap(width=15.e6,height=15.e6,\
#            projection='gnom',lat_0=60.,lon_0=-30.)
m = Basemap(projection='merc',llcrnrlat=41,urcrnrlat=52,\
            llcrnrlon=-6,urcrnrlon=10,lat_ts=15,resolution='c')
m.drawmapboundary(fill_color='aqua')
m.drawcoastlines()
m.fillcontinents(color='green', lake_color='aqua')
m.drawparallels(np.arange(10, 90, 20))
m.drawmeridians(np.arange(-180, 180, 30))
m.drawcountries()

m.plot(2.85, 45.9667, 'ro', latlon=True)
m.plot(2.89667, 45.7659, 'ro', latlon=True)
m.plot(3.23333, 45.7667, 'ro', latlon=True)
m.plot(3.43333, 45.7333, 'ro', latlon=True)
m.plot(3.4, 45.75, 'ro', latlon=True)
m.plot(2.58333, 45.9333, 'ro', latlon=True)
m.plot(3.16667, 45.4667, 'ro', latlon=True)
m.plot(3.58333, 45.6667, 'ro', latlon=True)
m.plot(3.3, 45.75, 'ro', latlon=True)
m.plot(3.25, 45.8, 'ro', latlon=True)
m.plot(2.9, 46.0333, 'ro', latlon=True)
m.plot(3.26667, 45.9667, 'ro', latlon=True)
m.plot(3.49973, 45.5506, 'ro', latlon=True)
m.plot(3.21667, 45.75, 'ro', latlon=True)
m.plot(3.58333, 45.6333, 'ro', latlon=True)
def map_all_obs_tracks_SIO(ib_track_file_list, an_track_file_list, outfile,
                           region):
    """Plots a map of storm tracks (analysis track) in the SWIO, that had their genesis in a given MJO phase (pair)
	Colour-codes the track according to the SWIO intensity category scale, using max winds from IBTrACS"""

    # set up map of region
    if region == "SH":
        lat1 = 30
        lat2 = -60
        lon1 = -25
        lon2 = 335

    elif region == "SIO":
        lat1 = 10
        lat2 = -50
        lon1 = 10
        lon2 = 110

    fig = plt.figure(figsize=(6, 3))
    ax = fig.add_axes([0.05, 0.1, 0.9, 0.96])

    m = Basemap(llcrnrlon=lon1,
                llcrnrlat=lat2,
                urcrnrlon=lon2,
                urcrnrlat=lat1,
                projection='mill',
                resolution='l')

    def draw_rectangle(lats, lons, m):
        x, y = m(lons, lats)
        xy = zip(x, y)
        poly = Polygon(xy,
                       facecolor='None',
                       edgecolor='darkgrey',
                       linewidth=0.75,
                       alpha=0.75)
        plt.gca().add_patch(poly)

    RSMClats = [-40, 0, 0, -40]
    RSMClons = [30, 30, 90, 90]

    draw_rectangle(RSMClats, RSMClons, m)

    m.fillcontinents(color='white')
    m.drawcoastlines(linewidth=0.4, color='k')
    m.drawcountries(linewidth=0.4, color='k')

    colours = ['#fcc200', '#f05238', '#a1005c', '#08025c']

    no_tracks = len(an_track_file_list)
    #colors = cm.viridis(np.linspace(0, 1, no_tracks))
    for file_in_list, i in zip(ib_track_file_list,
                               range(len(ib_track_file_list))):

        # load in data from a specified TRACK file (reformatted & interpolated)
        #an_data = np.genfromtxt(file_in_list, dtype=float, skip_header=1)
        ib_data = np.genfromtxt(ib_track_file_list[i],
                                dtype=float,
                                skip_header=1)

        obs_wind = ib_data[:, 10]

        obs_dates = pl.get_dates(
            ib_data)  #get the start date of the ibtracs track

        first_date = datetime.datetime.strptime(str(obs_dates[0]), "%Y%m%d%H")

        #print "TC start date: ", first_date.strftime("%Y-%m-%d")

        if first_date.strftime("%m-%d") == '02-29':
            continue

        else:

            #print obs_dates[0]
            #print first_date

            z = MJOdates.index(first_date.strftime("%Y-%m-%d"))
            #print "Date in MJO file at this index: ", MJOdates[z]

            amp = MJOamp[z]

            #print amp
            #print "MJO phase: ", MJOphase[z]
            #print "Amplitude: ", MJOamp[z]

            if MJOphase[z] == MJO and MJOamp[z] >= 1.0:

                print MJOdates[z]
                print MJOphase[z]
                print MJOamp[z]

                for i in range(len(obs_wind)):
                    if obs_wind[i] > 10000:
                        obs_wind[i] = np.nan

                max_wind = np.nanmax(obs_wind) * 3.6

                if max_wind < 51:
                    c = 'khaki'
                    ls = 'dotted'
                elif 51 <= max_wind < 63:
                    c = 'gold'
                    ls = 'dotted'
                elif 63 <= max_wind < 89:
                    c = 'darkorange'
                    ls = 'dotted'
                elif 89 <= max_wind < 118:
                    c = 'black'
                    ls = 'dotted'
                elif 118 <= max_wind < 166:
                    c = 'orangered'
                    ls = '-'
                elif 166 <= max_wind < 213:
                    c = 'firebrick'
                    ls = '-'
                elif max_wind >= 213:
                    c = 'k'
                    ls = '-'
                elif np.isnan(max_wind):
                    c = 'grey'
                    ls = '--'

                #plot this forecast track
                x, y = m(ib_data[:, 7], ib_data[:, 8])
                m.plot(x, y, linewidth=1, color=c, linestyle=ls)

                hurricane = get_hurricane_symbol()
                xs, ys = m(ib_data[0, 7], ib_data[0, 8])
                m.scatter(xs,
                          ys,
                          marker=hurricane,
                          edgecolors=c,
                          facecolors='None',
                          s=50,
                          linewidth=0.6)

            else:
                continue
    #legend
    tdf = plt.Line2D((0, 1), (0, 0),
                     color='khaki',
                     linestyle='dotted',
                     linewidth=1)
    td = plt.Line2D((0, 1), (0, 0),
                    color='yellow',
                    linestyle='dotted',
                    linewidth=1)
    tsm = plt.Line2D((0, 1), (0, 0),
                     color='darkorange',
                     linestyle='dotted',
                     linewidth=1)
    tsf = plt.Line2D((0, 1), (0, 0),
                     color='black',
                     linestyle='dotted',
                     linewidth=1)
    tc = plt.Line2D((0, 1), (0, 0), color='orangered', linewidth=1)
    tci = plt.Line2D((0, 1), (0, 0), color='firebrick', linewidth=1)
    tcti = plt.Line2D((0, 1), (0, 0), color='black', linewidth=1)
    title = "2010-2018\n" + str(no_tracks) + " Cyclones\nCategory:"
    #legend = ax.legend((tdf, td, tsm, tsf, tc, tci, tcti), ['Weak Depression', 'Tropical Depression', 'Moderate Tropical Storm', 'Strong Tropical Storm', 'Tropical Cyclone', 'Intense Tropical Cyclone', 'Very Intense Tropical Cyclone'], fontsize=5, loc='lower left')
    #plt.setp(legend.get_title(), fontsize='5')

    #save and close the plot
    fig.subplots_adjust(wspace=0)
    plt.savefig(outfile, bbox_inches='tight', pad_inches=0.05, dpi=500)
    plt.close()
Example #33
0
def plot_2D_density(Year, MapStyle):
    '''
    Parameters
        - Year      : between 1970-2015     | str
        - MapStyle  : style palette         | str
    Return
        A 2D Geo Map: The denser the red marker in a country,
                      the more severe damages had taken place.
    '''
    # use regular expression to check the format
    if not re.match(r'[\[|\(][0-9]{4}\,\s?[0-9]{4}[\]|\)]$', str(Year)):
        raise NotIntervalError

    # the starting year should be less than the ending yer
    elif Year[0] >= Year[1]:
        raise IntervalReverseError

    # catch the missing value exceptions in 1993
    elif Year == (1993, 1993):
        print('Data of 1993 is not available in Global Terrorism Database.\n\
Click the link to learn why.\nhttps://www.start.umd.edu/gtd/faq/')

    # catch the out of range yer interval input errors
    elif (Year[0] < 1970) or (Year[1] > 2015):
        raise IntervalLeakError

    else:
        if Year[0] == Year[1]:  # catch the excetion the starting year and the ending year converge
            df_gt = data.load_df()
            df = df_gt[df_gt.year == Year[0]]
        else:
            df = ut.df_sel_btw_years(Year)

        plt.figure(figsize=(18,10), frameon=False)

        m = Basemap('mill')
        m.drawcountries(linewidth=0.5,
                        linestyle='solid',
                        color='white',
                        antialiased=1,
                        ax=None,
                        zorder=None
                        )

        # Background settings
        if MapStyle == 'Blue Marble':
            m.drawcoastlines()
            m.bluemarble()
        elif MapStyle == 'Etopo':
            m.etopo()
        else:
            m.drawcoastlines(color='w')
            m.drawcountries(color='w')
            m.drawstates(color='w')
            m.fillcontinents(color='lightblue',lake_color='w')
            m.drawmapboundary(fill_color='w', color='w')

        # get latitude and longitude
        lat = ut.make_array(df, 'latitude')
        lon = ut.make_array(df, 'longitude')

        x,y = m(lon, lat)
        m.plot(x, y, 'r^', marker='o', markersize=4, alpha=.3)

        plt.title('Global Attack Density Plot: {}-{}'.format(Year[0], Year[1]), size=16)
        plt.show()
Example #34
0
def plot_basemap(lons, lats, size, color, labels=None, projection='global',
                 resolution='l', continent_fill_color='0.8',
                 water_fill_color='1.0', colormap=None, colorbar=None,
                 marker="o", title=None, colorbar_ticklabel_format=None,
                 show=True, fig=None, **kwargs):  # @UnusedVariable
    """
    Creates a basemap plot with a data point scatter plot.

    :type lons: list/tuple of floats
    :param lons: Longitudes of the data points.
    :type lats: list/tuple of floats
    :param lats: Latitudes of the data points.
    :type size: float or list/tuple of floats
    :param size: Size of the individual points in the scatter plot.
    :type color: list/tuple of floats (or objects that can be
        converted to floats, like e.g.
        :class:`~obspy.core.utcdatetime.UTCDateTime`)
    :param color: Color information of the individual data points to be
        used in the specified color map (e.g. origin depths,
        origin times).
    :type labels: list/tuple of str
    :param labels: Annotations for the individual data points.
    :type projection: str, optional
    :param projection: The map projection. Currently supported are
        * ``"global"`` (Will plot the whole world.)
        * ``"ortho"`` (Will center around the mean lat/long.)
        * ``"local"`` (Will plot around local events)
        Defaults to "global"
    :type resolution: str, optional
    :param resolution: Resolution of the boundary database to use. Will be
        based directly to the basemap module. Possible values are
        * ``"c"`` (crude)
        * ``"l"`` (low)
        * ``"i"`` (intermediate)
        * ``"h"`` (high)
        * ``"f"`` (full)
        Defaults to ``"l"``. For compatibility, you may also specify any of the
        Cartopy resolutions defined in :func:`plot_cartopy`.
    :type continent_fill_color: Valid matplotlib color, optional
    :param continent_fill_color:  Color of the continents. Defaults to
        ``"0.9"`` which is a light gray.
    :type water_fill_color: Valid matplotlib color, optional
    :param water_fill_color: Color of all water bodies.
        Defaults to ``"white"``.
    :type colormap: str, any matplotlib colormap, optional
    :param colormap: The colormap for color-coding the events as provided
        in `color` kwarg.
        The event with the smallest `color` property will have the
        color of one end of the colormap and the event with the highest
        `color` property the color of the other end with all other events
        in between.
        Defaults to None which will use the default matplotlib colormap.
    :type colorbar: bool, optional
    :param colorbar: When left `None`, a colorbar is plotted if more than one
        object is plotted. Using `True`/`False` the colorbar can be forced
        on/off.
    :type title: str
    :param title: Title above plot.
    :type colorbar_ticklabel_format: str or function or
        subclass of :class:`matplotlib.ticker.Formatter`
    :param colorbar_ticklabel_format: Format string or Formatter used to format
        colorbar tick labels.
    :type show: bool
    :param show: Whether to show the figure after plotting or not. Can be used
        to do further customization of the plot before showing it.
    :type fig: :class:`matplotlib.figure.Figure`
    :param fig: Figure instance to reuse, returned from a previous
        :func:`plot_basemap` call. If a previous basemap plot is reused, any
        kwargs regarding the basemap plot setup will be ignored (i.e.
        `projection`, `resolution`, `continent_fill_color`,
        `water_fill_color`). Note that multiple plots using colorbars likely
        are problematic, but e.g. one station plot (without colorbar) and one
        event plot (with colorbar) together should work well.
    """
    min_color = min(color)
    max_color = max(color)

    if any([isinstance(c, (datetime.datetime, UTCDateTime)) for c in color]):
        datetimeplot = True
        color = [
            (np.isfinite(float(t)) and
             date2num(getattr(t, 'datetime', t)) or
             np.nan)
            for t in color]
    else:
        datetimeplot = False

    scal_map = ScalarMappable(norm=Normalize(min_color, max_color),
                              cmap=colormap)
    scal_map.set_array(np.linspace(0, 1, 1))

    # The colorbar should only be plotted if more then one event is
    # present.
    if colorbar is None:
        if len(lons) > 1 and hasattr(color, "__len__") and \
                not isinstance(color, (str, native_str)):
            colorbar = True
        else:
            colorbar = False

    if fig is None:
        fig = plt.figure()

        if projection == "local":
            ax_x0, ax_width = 0.10, 0.80
        elif projection == "global":
            ax_x0, ax_width = 0.01, 0.98
        else:
            ax_x0, ax_width = 0.05, 0.90

        if colorbar:
            map_ax = fig.add_axes([ax_x0, 0.13, ax_width, 0.77])
            cm_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.05])
        else:
            ax_y0, ax_height = 0.05, 0.85
            if projection == "local":
                ax_y0 += 0.05
                ax_height -= 0.05
            map_ax = fig.add_axes([ax_x0, ax_y0, ax_width, ax_height])

        if projection == 'global':
            bmap = Basemap(projection='moll', lon_0=round(np.mean(lons), 4),
                           resolution=_BASEMAP_RESOLUTIONS[resolution],
                           ax=map_ax)
        elif projection == 'ortho':
            bmap = Basemap(projection='ortho',
                           resolution=_BASEMAP_RESOLUTIONS[resolution],
                           area_thresh=1000.0, lat_0=round(np.mean(lats), 4),
                           lon_0=round(np.mean(lons), 4), ax=map_ax)
        elif projection == 'local':
            if min(lons) < -150 and max(lons) > 150:
                max_lons = max(np.array(lons) % 360)
                min_lons = min(np.array(lons) % 360)
            else:
                max_lons = max(lons)
                min_lons = min(lons)
            lat_0 = max(lats) / 2. + min(lats) / 2.
            lon_0 = max_lons / 2. + min_lons / 2.
            if lon_0 > 180:
                lon_0 -= 360
            deg2m_lat = 2 * np.pi * 6371 * 1000 / 360
            deg2m_lon = deg2m_lat * np.cos(lat_0 / 180 * np.pi)
            if len(lats) > 1:
                height = (max(lats) - min(lats)) * deg2m_lat
                width = (max_lons - min_lons) * deg2m_lon
                margin = 0.2 * (width + height)
                height += margin
                width += margin
            else:
                height = 2.0 * deg2m_lat
                width = 5.0 * deg2m_lon
            # do intelligent aspect calculation for local projection
            # adjust to figure dimensions
            w, h = fig.get_size_inches()
            aspect = w / h
            if colorbar:
                aspect *= 1.2
            if width / height < aspect:
                width = height * aspect
            else:
                height = width / aspect

            bmap = Basemap(projection='aea',
                           resolution=_BASEMAP_RESOLUTIONS[resolution],
                           area_thresh=1000.0, lat_0=round(lat_0, 4),
                           lon_0=round(lon_0, 4),
                           width=width, height=height, ax=map_ax)
            # not most elegant way to calculate some round lats/lons

            def linspace2(val1, val2, N):
                """
                returns around N 'nice' values between val1 and val2
                """
                dval = val2 - val1
                round_pos = int(round(-np.log10(1. * dval / N)))
                # Fake negative rounding as not supported by future as of now.
                if round_pos < 0:
                    factor = 10 ** (abs(round_pos))
                    delta = round(2. * dval / N / factor) * factor / 2
                else:
                    delta = round(2. * dval / N, round_pos) / 2
                new_val1 = np.ceil(val1 / delta) * delta
                new_val2 = np.floor(val2 / delta) * delta
                N = (new_val2 - new_val1) / delta + 1
                return np.linspace(new_val1, new_val2, N)

            N1 = int(np.ceil(height / max(width, height) * 8))
            N2 = int(np.ceil(width / max(width, height) * 8))
            parallels = linspace2(lat_0 - height / 2 / deg2m_lat,
                                  lat_0 + height / 2 / deg2m_lat, N1)

            # Old basemap versions have problems with non-integer parallels.
            try:
                bmap.drawparallels(parallels, labels=[0, 1, 1, 0])
            except KeyError:
                parallels = sorted(list(set(map(int, parallels))))
                bmap.drawparallels(parallels, labels=[0, 1, 1, 0])

            if min(lons) < -150 and max(lons) > 150:
                lon_0 %= 360
            meridians = linspace2(lon_0 - width / 2 / deg2m_lon,
                                  lon_0 + width / 2 / deg2m_lon, N2)
            meridians[meridians > 180] -= 360
            bmap.drawmeridians(meridians, labels=[1, 0, 0, 1])
        else:
            msg = "Projection '%s' not supported." % projection
            raise ValueError(msg)

        # draw coast lines, country boundaries, fill continents.
        map_ax.set_axis_bgcolor(water_fill_color)
        bmap.drawcoastlines(color="0.4")
        bmap.drawcountries(color="0.75")
        bmap.fillcontinents(color=continent_fill_color,
                            lake_color=water_fill_color)
        # draw the edge of the bmap projection region (the projection limb)
        bmap.drawmapboundary(fill_color=water_fill_color)
        # draw lat/lon grid lines every 30 degrees.
        bmap.drawmeridians(np.arange(-180, 180, 30))
        bmap.drawparallels(np.arange(-90, 90, 30))
        fig.bmap = bmap
    else:
        error_message_suffix = (
            ". Please provide a figure object from a previous call to the "
            ".plot() method of e.g. an Inventory or Catalog object.")
        try:
            map_ax = fig.axes[0]
        except IndexError as e:
            e.args = tuple([e.args[0] + error_message_suffix] +
                           list(e.args[1:]))
            raise
        try:
            bmap = fig.bmap
        except AttributeError as e:
            e.args = tuple([e.args[0] + error_message_suffix] +
                           list(e.args[1:]))
            raise

    # compute the native bmap projection coordinates for events.
    x, y = bmap(lons, lats)
    # plot labels
    if labels:
        if 100 > len(lons) > 1:
            for name, xpt, ypt, _colorpt in zip(labels, x, y, color):
                # Check if the point can actually be seen with the current bmap
                # projection. The bmap object will set the coordinates to very
                # large values if it cannot project a point.
                if xpt > 1e25:
                    continue
                map_ax.text(xpt, ypt, name, weight="heavy",
                            color="k", zorder=100,
                            path_effects=[
                                PathEffects.withStroke(linewidth=3,
                                                       foreground="white")])
        elif len(lons) == 1:
            map_ax.text(x[0], y[0], labels[0], weight="heavy", color="k",
                        path_effects=[
                            PathEffects.withStroke(linewidth=3,
                                                   foreground="white")])

    # scatter plot is removing valid x/y points with invalid color value,
    # so we plot those points separately.
    try:
        nan_points = np.isnan(np.array(color, dtype=np.float))
    except ValueError:
        # `color' was not a list of values, but a list of colors.
        pass
    else:
        if nan_points.any():
            x_ = np.array(x)[nan_points]
            y_ = np.array(y)[nan_points]
            size_ = np.array(size)[nan_points]
            scatter = bmap.scatter(x_, y_, marker=marker, s=size_, c="0.3",
                                   zorder=10, cmap=None)
    scatter = bmap.scatter(x, y, marker=marker, s=size, c=color,
                           zorder=10, cmap=colormap)

    if title:
        plt.suptitle(title)

    if colorbar:
        if colorbar_ticklabel_format is not None:
            if isinstance(colorbar_ticklabel_format, (str, native_str)):
                formatter = FormatStrFormatter(colorbar_ticklabel_format)
            elif hasattr(colorbar_ticklabel_format, '__call__'):
                formatter = FuncFormatter(colorbar_ticklabel_format)
            elif isinstance(colorbar_ticklabel_format, Formatter):
                formatter = colorbar_ticklabel_format
            locator = MaxNLocator(5)
        else:
            if datetimeplot:
                locator = AutoDateLocator()
                formatter = AutoDateFormatter(locator)
                # Compat with old matplotlib versions.
                if hasattr(formatter, "scaled"):
                    formatter.scaled[1 / (24. * 60.)] = '%H:%M:%S'
            else:
                locator = None
                formatter = None

        # normal case: axes for colorbar was set up in this routine
        if "cm_ax" in locals():
            cb_kwargs = {"cax": cm_ax}
        # unusual case: reusing a plot that has no colorbar set up previously
        else:
            cb_kwargs = {"ax": map_ax}

        cb = fig.colorbar(
            mappable=scatter, cmap=colormap, orientation='horizontal',
            ticks=locator, format=formatter, **cb_kwargs)
        # Compat with old matplotlib versions.
        if hasattr(cb, "update_ticks"):
            cb.update_ticks()

    if show:
        plt.show()

    return fig
Example #35
0
lon_max = max(lon) + margin

m = Basemap(llcrnrlon=lon_min,
            llcrnrlat=lat_min,
            urcrnrlon=lon_max,
            urcrnrlat=lat_max,
            lat_0=(lat_max - lat_min)/2,
            lon_0=(lon_max-lon_min)/2,
            projection='merc',
            resolution='h',
            area_thresh=10000.,
            )
m.drawcoastlines()
m.drawcountries()
m.drawstates()


# Colors
water = '#46bcec'
land = '#ffffff'
m.drawmapboundary(fill_color=water)
m.fillcontinents(color=land, lake_color=water)
# convert lat and lon to map projection coordinates
lons, lats = m(lon, lat)
# plot points as red dots
m.scatter(lons, lats, marker='o', c=colors, cmap='plasma', zorder=5, s=2)
plt.colorbar().set_label(f'{var_to_viz}', rotation=90)
plt.title(
    f'Global {var_to_viz} at {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
plt.savefig('maps/sensor_map.png', dpi=300)
Example #36
0
                                                         fill_value=np.nan)
            lon = np.mod(xsec['lon'] + 360, 360)
            pts = np.vstack((lon, xsec['lat'])).T
            xsec['data'][n, :] = interp(pts)
            xsec['dates'].append(
                datetime.datetime.strptime(output_date, '%Y %m %d %H %M'))

    for xsec in transect_points:
        print xsec['name']

        # Plot transect
        fig = plt.figure(figsize=[12.0, 4.0])
        ax = fig.add_subplot(2, 1, 1)
        m = Basemap(projection='cyl',llcrnrlat= -90,urcrnrlat=90,\
                                     llcrnrlon=-180,urcrnrlon=180,resolution='c')
        m.fillcontinents(color='tan', lake_color='lightblue')
        m.drawcoastlines()
        ax.plot(xsec['lon'], xsec['lat'], 'r-')

        # Plot data
        ax = fig.add_subplot(2, 1, 2)
        dates = np.asarray(xsec['dates'], dtype='O')
        idx = np.where(np.absolute(xsec['data']) > 1e10)
        xsec['data'][idx] = np.nan
        cf = ax.contourf(dates, xsec['dist'], xsec['data'].T)
        cb = plt.colorbar(cf)
        cb.set_label('Significant wave height (m)')
        ax.set_xlabel('Date')
        ax.set_ylabel('Distance along transect (km)')
        plt.tight_layout()
        plt.savefig('hovmoller_' + '_'.join(xsec['name'].split()) + '.png',
Example #37
0
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# setup south polar stereographic basemap.
# The longitude lon_0 is at 6-o'clock, and the
# latitude circle boundinglat is tangent to the edge
# of the map at lon_0. Default value of lat_ts
# (latitude of true scale) is pole.
m = Basemap(projection='spstere', boundinglat=-10, lon_0=90, resolution='l')
m.drawcoastlines()
m.fillcontinents(color='coral', lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-80., 81., 20.))
m.drawmeridians(np.arange(-180., 181., 20.))
m.drawmapboundary(fill_color='aqua')
# draw tissot's indicatrix to show distortion.
ax = plt.gca()
for y in np.linspace(19 * m.ymin / 20, m.ymin / 20, 10):
    for x in np.linspace(19 * m.xmin / 20, m.xmin / 20, 10):
        lon, lat = m(x, y, inverse=True)
        poly = m.tissot(lon,lat,2.5,100,\
                        facecolor='green',zorder=10,alpha=0.5)
plt.title("South Polar Stereographic Projection")
plt.show()
Example #38
0
#m = Basemap(lon_0=180)
#m = Basemap(llcrnrlon=80.,llcrnrlat=-10.,urcrnrlon=190.,urcrnrlat=50.,
m = Basemap(llcrnrlon=110.,
            llcrnrlat=10.,
            urcrnrlon=140.,
            urcrnrlat=30.,
            projection='lcc',
            lat_1=20.,
            lat_2=40.,
            lon_0=120.,
            resolution='h',
            area_thresh=1000.)

m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)
m.fillcontinents(color='grey', alpha=0.7, lake_color='grey', zorder=10)
m.drawcoastlines(linewidth=0.1, color="white")
m.drawparallels(np.arange(0, 70, 10), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(80, 190, 10), labels=[0, 0, 0, 1])

#----------------------------------------------------------------------------------------#
# NCEP BUFR
#----------------------------------------------------------------------------------------#
# filename
dtg = '17091712'
filename = 'gdas.satwnd.tm00.bufr_d.' + dtg

# string
hdrstr = 'SAID CLAT CLON YEAR MNTH DAYS HOUR MINU SWCM SAZA GCLONG SCCF SWQM'
obstr = 'HAMD PRLC WDIR WSPD'
qcstr = 'OGCE GNAP PCCF'
Example #39
0
if (int(mm) == 10): monIndx = 3

timeIndx = yearIndx + monIndx

infile = '../Data/heat_content_anomaly_0-700_seasonal.nc'
outpng = './Images/Seasonal/Orig/heat_content_anomaly_0-700_' + yyyy + '-' + mm + '.png'

fig = plt.figure(figsize=(figxsize, figysize))
ax1 = fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False, axisbg='#F5F5F5')

# setup basemap.
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,area_thresh=10000,\
 llcrnrlon=-180,urcrnrlon=180,resolution='l')
#m.drawlsmask(land_color='#E2E2E2', ocean_color='#E2E2E2', lakes=False)

cdict1 = gmtColormap('./OceanHeatContent.cpt')
cmap_temp = LinearSegmentedColormap('cmap_temp', cdict1)

levs = np.arange(101) - 50

m.fillcontinents(color='#E2E2E2', lake_color='#E2E2E2')
#m.drawcoastlines(color='#787878',linewidth=0.15)
#m.drawrivers(color='#E2E2E2',linewidth=1)

#plt.show()
plt.savefig(outpng,
            dpi=figdpi,
            orientation='landscape',
            bbox_inches='tight',
            pad_inches=0.0)
Example #40
0
grand_total_rossby_count = 0
grand_total_lpt_count = 0

## Set up figure

fig = plt.figure(figsize=(8, 6))
ax1 = fig.add_subplot(211)

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

fout = (out_dir + '/rossby_system_tracks_20yrs__map_with_lpt__' +
        season_label + '.png')

for fn in sorted(glob.glob(dir + '/TIMECLUSTERS_*.rejoin2.nc')):

    # Skip RT 2018 for now.
    if "2018112721" in fn:
Example #41
0
WU = WU / len(b)  # period average wind
WV = WV / len(b)

modulus = np.sqrt(WU**2 + WV**2)  # normalized vectors
U = WU / modulus
V = WV / modulus

#############################
### Plotting with Basemap ###
#############################

m = Basemap(projection='npstere',boundinglat=65,lat_0=90,lat_ts=70,lon_0=-45,\
            resolution='l',round=False)
#m.drawcoastlines()
m.fillcontinents(color='grey')  #,lake_color='aqua')
#m.drawparallels(np.arange(-80.,81.,20.))
#m.drawmeridians(np.arange(-180.,181.,20.))
#m.drawmapboundary(fill_color='aqua')

x, y = m(lon1, lat1)  # transforms from spherical til flat

Q = m.quiver(x, y, U, V, modulus,
             scale=40)  #,units='xy',width=8,angles='xy',scale_units='xy',\
#,headlength=5,headwidth=5,latlon=False)#,cmap=cm.seismic,
cb = m.colorbar()
plt.set_cmap('jet')
cb.set_label('m/s')
#cb.set_clim(np.nanmin(modulus),np.nanmax(modulus))
#qk = plt.quiverkey(Q, 0.1, 0.95, 1.5, 'm/s', labelpos='W')
plt.title("Winds _ " + str(b[0]) + '-' + str(b[-1] + 1) + " average")
Example #42
0
def plot():
    file = 'TFtempsalfluo.csv'
    a = 0.1
    df_tf = pd.read_csv(file)
    df_tf_fluo = pd.read_csv('TFfluo_raw.csv')    
    df_tf_temp= pd.read_csv('TFtemp_raw.csv')  
    df_tf_sal= pd.read_csv('TFsal_raw.csv')      
           
    df_tf = df_tf[df_tf.latitude > 67.5]
    df_tf = df_tf[df_tf.latitude < 69.5]

    df_tf_sal = df_tf_sal[df_tf_sal.latitude > 67.5]
    df_tf_sal = df_tf_sal[df_tf_sal.latitude < 69.5] 
    
    df_tf_fluo = df_tf_fluo[df_tf_fluo.latitude > 67.5]
    df_tf_fluo = df_tf_fluo[df_tf_fluo.latitude < 69.5]    
    
    df_tf_temp = df_tf_temp[df_tf_temp.latitude > 67.5]
    df_tf_temp = df_tf_temp[df_tf_temp.latitude < 69.5]     
    
    fig = plt.figure(figsize=(11.27,5.27), dpi=100)

    ax = plt.subplot2grid((3, 2), (0, 0), rowspan  = 3)
    ax1 = plt.subplot2grid((3, 2), (0, 1), rowspan = 1)    
    ax2 = plt.subplot2grid((3, 2), (1, 1), rowspan = 1)        
    ax3 = plt.subplot2grid((3, 2), (2, 1), rowspan = 1) 
       
    Fmt = mdates.DateFormatter('%b')
    
    map = Basemap(
                resolution='i',projection='stere',\
                lat_0=70,lon_0=14,
                llcrnrlon = 12 ,llcrnrlat = 67,
                urcrnrlon = 21 ,urcrnrlat = 70, ax = ax )
   
    map.drawmapboundary(fill_color='#cae2f7')
    map.fillcontinents(color='#bdad95')
    map.drawcoastlines(linewidth=0.5)
    
    parallels = [67,68,69,70]
    meridians = [5,10,15,20]
    
    map.drawparallels(parallels, labels = [1,1,0,0]) # draw parallels
    map.drawmeridians(meridians, labels = [0,0,1,1]) # draw parallels
    map.scatter(df_tf.longitude.values,df_tf.latitude.values,latlon = True,
                s = 15,ax = ax ,zorder = 5,c='#1e5e75', alpha = 0.7,label = 'TrollFjord \nFerry') #) 
    
    df_tf = df_tf.set_index('time')    
    df_tf.index= pd.to_datetime(df_tf.index)    
    
    df_tf_fluo = df_tf_fluo.set_index('time')    
    df_tf_fluo.index= pd.to_datetime(df_tf_fluo.index)    
    
    df_tf_temp = df_tf_temp.set_index('time').sort_index() 
    df_tf_temp.index= pd.to_datetime(df_tf_temp.index) 

    df_tf_sal = df_tf_sal.set_index('time').sort_index() 
    df_tf_sal.index= pd.to_datetime(df_tf_sal.index) 
           
    df_tf_fluo_1 = df_tf_fluo.where(df_tf_fluo['chla_fluorescence'] < 0.94)
    df_tf_fluo_2 = df_tf_fluo.where(df_tf_fluo['chla_fluorescence'] > 0.96)     
             
    ax1.scatter(df_tf_sal.index, df_tf_sal['ctd_salinity'].values,
                label = 'salinity all',c = '#1e5e75',alpha = a)         
     
    ax2.scatter(df_tf_temp.index, df_tf_temp['ctd_temperature'].values,
                label = 'temperature all raw',c = '#1e5e75',alpha = a)      
      
    ax3.scatter(df_tf_fluo_1.index, df_tf_fluo_1['chla_fluorescence'].values,
                label = 'fluorescence all raw',c = '#1e5e75',alpha = 0.2)       
    ax3.scatter(df_tf_fluo_2.index, df_tf_fluo_2['chla_fluorescence'].values,
                c = '#1e5e75',alpha = 0.2)           
    col = '#b21e1e'
    
    df_1 = pd.read_csv(file)    
    df_1 = df_1.set_index('time')
    df_1.index = pd.to_datetime(df_1.index)
    df_1 = df_1[df_1.latitude > 67.6]
    df_1 = df_1[df_1.latitude < 68] 

    df_tf_sal = df_tf_sal[df_tf_sal.latitude > 67.6]
    df_tf_sal = df_tf_sal[df_tf_sal.latitude < 68] 
    group_sal = df_tf_sal.groupby(df_tf_sal.index.dayofyear).median()
    group_sal.index = pd.to_datetime(group_sal.index,unit = 'D',origin = '2018-01-01')   

    ax1.plot(group_sal.index.values,group_sal['ctd_salinity'].values,c = col,linewidth = 3,
             marker='o',label = 'median ctd_salinity', markeredgecolor = 'k')   
   
    df_tf_temp = df_tf_temp[df_tf_temp.latitude > 67.6]
    df_tf_temp = df_tf_temp[df_tf_temp.latitude < 68] 
    
    group = df_tf_temp.groupby(df_tf_temp.index.dayofyear).median()
    group.index = pd.to_datetime(group.index,unit = 'D',origin = '2018-01-01')

    ax2.plot(group.index.values,group['ctd_temperature'].values,c = col,linewidth = 3,
             marker='o',label = 'median ctd_temperature', markeredgecolor = 'k')    
    map.scatter(df_1.longitude.values,df_1.latitude.values,latlon = True,
                s = 35,ax = ax ,c = col, edgecolors = 'k',zorder = 9,alpha = 1) #) 
        
    df_fluo = pd.read_csv('TFfluo_raw.csv')
    
    df_fluo = df_fluo.set_index('time')
    df_fluo.index = pd.to_datetime(df_fluo.index)
    df_fluo = df_fluo[df_fluo.latitude > 67.6]
    df_fluo = df_fluo[df_fluo.latitude < 68] 

    df_fluo_1 = df_fluo.where(df_fluo['chla_fluorescence'] < 0.94)
    df_fluo_2 = df_fluo.where(df_fluo['chla_fluorescence'] > 0.96)
    df_fluo = pd.concat([df_fluo_1,df_fluo_2],join = 'outer')
    
    group_f = df_fluo.groupby(df_fluo.index.dayofyear).median()
    group_f.index = pd.to_datetime(group_f.index,unit = 'D',origin = '2018-01-01')    

    ax3.plot(group_f.index, group_f['chla_fluorescence'].values,
                label = 'median chla_fluorescence',c = col,linewidth = 3,marker='o',markeredgecolor = 'k') 
        

    r'''with open(r"C:\Users\elp\OneDrive\Python_workspace\climatologyjs\climatology.json") as data_file:    
        data = json.load(data_file)    
 
    d = pd.DataFrame(data)   
    #coord = data['properties']['coordinates']    
        
    days = ["2018-W{}".format(w) for w in d['week']]
    d['days']= [datetime.datetime.strptime(n + '-0', "%Y-W%W-%w") for n in days] 
              
    ax1.plot(d['days'], d['ctd_salinity'].values,label = 'salinity')       
    ax2.plot(d['days'], d['ctd_temperature'].values,label = 'temperature')     
    ax3.plot(d['days'], d['chla_fluorescence'].values,label = 'fluorescence') '''    
    
    axes = (ax,ax1,ax2,ax3)
    for a in axes: 
        a.xaxis.set_major_formatter(Fmt)
        a.legend()    
    plt.tight_layout()
    #plt.show()
    plt.savefig('TF_Ferrybox.png')
Example #43
0
from grib2 import Grib2Decode
from pylab import *
from mpl_toolkits.basemap import Basemap
grbs = Grib2Decode('../sampledata/dspr.temp.grb')
lats, lons = grbs[0].grid()
llcrnrlon = lons[0, 0]
llcrnrlat = lats[0, 0]
urcrnrlon = lons[-1, -1]
urcrnrlat = lats[-1, -1]
print llcrnrlat, llcrnrlon, urcrnrlat, urcrnrlon
rsphere = (grbs[0].earthRmajor, grbs[0].earthRminor)
lat_ts = grbs[0].proj4_lat_ts
lon_0 = grbs[0].proj4_lon_0
projection = grbs[0].proj4_proj
m = Basemap(llcrnrlon=llcrnrlon,
            llcrnrlat=llcrnrlat,
            urcrnrlon=urcrnrlon,
            urcrnrlat=urcrnrlat,
            rsphere=rsphere,
            lon_0=lon_0,
            lat_ts=lat_ts,
            resolution='i',
            projection=projection)
x, y = m(lons, lats)
m.scatter(x.flat, y.flat, 1, marker='o', color='k', zorder=10)
m.drawcoastlines()
m.fillcontinents()
title('Mercator Grid (Puerto Rico)')
show()
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
# set up orthographic map projection with
# perspective of satellite looking down at 50N, 100W.
# use low resolution coastlines.
# don't plot features that are smaller than 1000 square km.
map = Basemap(projection='ortho',
              lat_0=50,
              lon_0=-100,
              resolution='l',
              area_thresh=1000.)
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines()
map.drawcountries()
map.fillcontinents(color='coral')
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary()
# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(np.arange(0, 360, 30))
map.drawparallels(np.arange(-90, 90, 30))
plt.show()
Example #45
0
    np.min(lat[data_bounds]),
    np.max(lon[data_bounds]),
    np.max(lat[data_bounds])
]  # set bounds for plotting

# figure routine for visualization
fig = plt.figure(figsize=(9, 4), dpi=200)

n_add = 0  # for zooming in and out
m = Basemap(llcrnrlon=bbox[0] - n_add,
            llcrnrlat=bbox[1] - n_add,
            urcrnrlon=bbox[2] + n_add,
            urcrnrlat=bbox[3] + n_add,
            resolution='i',
            projection='cyl')
m.fillcontinents(color='#d9b38c', lake_color='#bdd5d5',
                 zorder=1)  # continent colors
m.drawmapboundary(fill_color='#bdd5d5', zorder=0)  # ocean color
m.drawcoastlines(linewidth=0.5)
m.drawcountries(linewidth=0.25)
m.drawstates(zorder=2)
m.pcolormesh(lon.data, lat.data, data, latlon=True,
             zorder=999)  # plotting actual LST data
parallels = np.linspace(bbox[1], bbox[3], 5.)
m.drawparallels(parallels,
                labels=[True, False, False, False],
                zorder=2,
                fontsize=8)
meridians = np.linspace(bbox[0], bbox[2], 5.)
m.drawmeridians(meridians,
                labels=[False, False, False, True],
                zorder=1,
Example #46
0
                 pvalue_onq,
                 colors='None',
                 hatches=['....'],
                 linewidths=0.4)

ax1.annotate(r'\textbf{ON}',
             xy=(0, 0),
             xytext=(0.35, 1.05),
             xycoords='axes fraction',
             fontsize=25,
             color='dimgrey',
             rotation=0)

cmap = ncm.cmap('nrl_sirkes')
cs.set_cmap(cmap)
m.fillcontinents(color='dimgray')

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

ax2 = plt.subplot(132)

m = Basemap(projection='ortho',
            lon_0=0,
            lat_0=89,
            resolution='l',
            area_thresh=10000.)

var, lons_cyclic = addcyclic(diff_dj, lon)
var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False)
lon2d, lat2d = np.meshgrid(lons_cyclic, lat)
x, y = m(lon2d, lat2d)
Example #47
0
    def plot_global_map_weights(self):
        """
        Plot global map of event and stations
        """

        # import basemap here due to error
        from mpl_toolkits.basemap import Basemap

        # ax = plt.subplot(211)
        plt.title(self.cmtsource.eventname + "_Weights")
        m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0, resolution='c')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawparallels(np.arange(-90., 120., 30.))
        m.drawmeridians(np.arange(0., 420., 60.))
        m.drawmapboundary()

        #x, y = m(self.sta_lon, self.sta_lat)
        x, y = self.sta_lon, self.sta_lat
        w = [meta.weights for meta in self.metas]
        print(w)
        w /= max(w)
        w = map(float, w)
        #w = map(str, w)
        w = list(w)
        s = [np.sqrt(x) * 100 for x in w]
        w = [x**0.5 for x in w]
        #print(self.sta_lon,self.sta_lat)
        #print(self.metas)
        #print(len(self.metas),len(self.sta_lon))
        #print(w)

        m.scatter(x, y, s=s, c=w, marker="^", cmap='hsv', zorder=3)
        cmt_lat = self.cmtsource.latitude
        cmt_lon = self.cmtsource.longitude
        focmecs = get_cmt_par(self.cmtsource)[:6]
        ax = plt.gca()
        if self.mode == 'regional':
            minlon = min(self.sta_lon)
            maxlon = max(self.sta_lon)
            minlat = min(self.sta_lat)
            maxlat = max(self.sta_lat)
            padding = 0.2
            m.drawparallels(np.arange(-90., 120., padding),
                            labels=[1, 1, 0, 0],
                            fmt="%.2f",
                            dashes=[2, 2])
            m.drawmeridians(np.arange(0., 420., padding),
                            labels=[0, 0, 1, 1],
                            fmt="%.2f",
                            dashes=[2, 2])
            m.etopo()
            ax.set_xlim(minlon - padding, maxlon + padding)
            ax.set_ylim(minlat - padding, maxlat + padding)
            width_beach = min((maxlon + 2 * padding - minlon) / (40 * padding),
                              (maxlat + 2 * padding - minlat) / (40 * padding))

        bb = beach(focmecs,
                   xy=(cmt_lon, cmt_lat),
                   width=width_beach,
                   linewidth=1,
                   alpha=1.0)
        bb.set_zorder(10)
        ax.add_collection(bb)
Example #48
0
def contourMap(myCDF, myvar, mylev):
    """Get the apporporiate grid"""
    tlat = myCDF.variables["lat"][:]
    tlon = myCDF.variables["lon"][:]
    levels = myCDF.variables["lev"][:]
    times = myCDF.variables["time"][:]

    mylevindex = 0
    for lev in xrange(len(levels)):
        if (float(levels[lev]) == float(mylev)):
            mylevindex = lev
            print "Will plot depth: %s m (index=%s)" % (mylev, lev)

    mydata = np.squeeze(myCDF.variables[myvar][0, mylevindex, :, :])
    refdate = datetime.datetime(1948, 1, 1)
    current = refdate + datetime.timedelta(days=times[0])
    print "Date of file is: %s" % (current)
    plt.figure(figsize=(10, 10), frameon=False)

    map = Basemap(llcrnrlon=-18.0,
                  llcrnrlat=46.0,
                  urcrnrlon=25.5,
                  urcrnrlat=67.5,
                  resolution='i',
                  projection='tmerc',
                  lon_0=0,
                  lat_0=50,
                  area_thresh=50.)
    delta = 20.
    levels = np.arange(mydata.min(), mydata.max(),
                       (mydata.max() - mydata.min()) / delta)
    levels = np.arange(272, 288, 0.5)
    print "Range of input data: %s - %s" % (mydata.min(), mydata.max())
    print np.shape(tlon), np.shape(tlat), np.shape(mydata)

    tlons, tlats = np.meshgrid(tlon, tlat)
    x, y = map(tlons, tlats)

    map.drawcoastlines()
    map.fillcontinents(color='grey')
    map.drawcountries()
    map.drawmapboundary()

    #  map.drawmeridians(np.arange(0,360,1))
    #  map.drawparallels(np.arange(0,90,1))

    CS1 = map.contourf(x,
                       y,
                       mydata,
                       levels,
                       cmap=cm.get_cmap('RdBu_r',
                                        len(levels) - 1),
                       alpha=1.0)
    plt.colorbar(CS1, orientation='vertical', extend='both', shrink=0.5)

    if current.month < 10:
        currentdate = str(current.year) + '0' + str(current.month)
    else:
        currentdate = str(current.year) + str(current.month)

    if not os.path.exists('figures'):
        os.makedirs('figures')
    plotfile = 'figures/rectangular_' + str(myvar) + '_yyyymm_' + str(
        currentdate) + 'lev_' + str(mylev) + '.pdf'
    print plotfile
    plt.savefig(plotfile, bbox_inches='tight')
    # plt.show()
    plt.close()
Example #49
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

map = Basemap(llcrnrlon=-0.5,
              llcrnrlat=39.8,
              urcrnrlon=4.,
              urcrnrlat=43.,
              resolution='i',
              projection='tmerc',
              lat_0=39.5,
              lon_0=1)

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#ddaa66', lake_color='aqua')
map.drawcoastlines()

map.readshapefile('./stockholm/data/3D_Block/sample_files/comarques',
                  'comarques')

lightning_info = map.readshapefile(
    './stockholm/data/3D_Block/sample_files/lightnings', 'lightnings')

print lightning_info

for info, lightning in zip(map.lightnings_info, map.lightnings):
    if float(info['amplitude']) < 0:
        marker = '_'
    else:
        marker = '+'
    map.plot(lightning[0],
             lightning[1],
Example #50
0
 
#define the figure
fig, axes = plt.subplots(1,1,figsize=(12, 10), facecolor='w', edgecolor='k')

#get simulation dates and length
sim_start_date = dateutil.parser.parse(str(PES.getHeaderAttribute(p_header, 'SIMULATION_START_DATE')))
sim_start_datetime = dateutil.parser.parse(str(PES.getHeaderAttribute(p_header, 'SIMULATION_START_DATE')) + str(PES.getHeaderAttribute(p_header, 'SIMULATION_START_TIME')))
sim_end_date   = dateutil.parser.parse(str(PES.getHeaderAttribute(p_header, 'SIMULATION_END_DATE')))
simulation_length = sim_start_date - sim_end_date
day_of_year = sim_start_date.timetuple().tm_yday
                    
#create a basemap instance
m = Basemap(width=4700000,height=4700000, resolution='l',projection='stere',lat_0=70,lon_0=-83.)
m.drawcoastlines(linewidth=0.5)
m.drawmapboundary(fill_color = '#084B8A', zorder = 0)
m.fillcontinents(color = '#D4BD8B', lake_color = '#084B8A', zorder=0)
parallels = np.arange(0.,81,10.) # labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(10.,351.,20.)
m.drawmeridians(meridians,labels=[True,False,False,True])

#sea ice and snow info
m.readshapefile('/Users/mcallister/projects/INP/NOAA snow and ice 4km-GEOtiff/ims2014195_4km_GIS_v1.2/test/test_WGS84', 'surface_cover', drawbounds = False)

#snow
i = 0
patches   = []
for info, shape in zip(m.surface_cover_info, m.surface_cover):    
    if info['DN'] ==4 and info['RINGNUM'] ==1:
        patches.append(Polygon(np.array(shape), True) )
        i+=1
axa[0].text(xpt, ypt, 'uwnd')

cob = m.pcolor(x,
               y,
               slope_ccmp_wspd,
               vmin=vmin,
               vmax=vmax,
               cmap=cmap_anom,
               ax=axa[1],
               rasterized=True)
axa[1].text(xpt, ypt, 'wspd')

for i, ax in enumerate(axa.flatten()):
    ax.autoscale(enable=True, axis='both', tight=True)
    m.drawcoastlines(linewidth=1.25, ax=ax)
    m.fillcontinents(color='0.8', ax=ax, zorder=2)
    if i % 2 == 0:
        m.drawparallels(np.arange(-80, 81, 20),
                        labels=[1, 0, 0, 0],
                        linewidth=0,
                        ax=ax)

m.drawmeridians(np.arange(0, 360, 90),
                labels=[0, 0, 0, 1],
                linewidth=0,
                yoffset=0.5e6,
                ax=axa[1])

box = axa[0].get_position()
tl = fig.add_axes([box.x0 * 1.1 + box.width * 1., box.y0, 0.02, box.height])
bounds = np.linspace(vmin, vmax, ncols)
Example #52
0
    def plot_global_map(self):
        """
        Plot global map of event and stations
        """

        # import basemap here due to error
        from mpl_toolkits.basemap import Basemap

        # ax = plt.subplot(211)
        plt.title(self.cmtsource.eventname)
        m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0, resolution='c')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawparallels(np.arange(-90., 120., 30.))
        m.drawmeridians(np.arange(0., 420., 60.))
        m.drawmapboundary()

        x, y = m(self.sta_lon, self.sta_lat)

        #print(self.sta_lon,self.sta_lat)
        #print(self.metas)
        #print(len(self.metas),len(self.sta_lon))
        #print(w)

        plt.scatter(x,
                    y,
                    s=30,
                    c='red',
                    cmap='afmhot',
                    marker="^",
                    edgecolor="k",
                    linewidth=0.3,
                    zorder=3)

        cmt_lat = self.cmtsource.latitude
        cmt_lon = self.cmtsource.longitude
        focmecs = get_cmt_par(self.cmtsource)[:6]
        ax = plt.gca()
        if self.mode == 'regional':
            minlon = min(self.sta_lon)
            maxlon = max(self.sta_lon)
            minlat = min(self.sta_lat)
            maxlat = max(self.sta_lat)
            padding = 0.2
            m.drawparallels(np.arange(-90., 120., padding),
                            labels=[1, 1, 0, 0],
                            fmt="%.2f",
                            dashes=[2, 2])
            m.drawmeridians(np.arange(0., 420., padding),
                            labels=[0, 0, 1, 1],
                            fmt="%.2f",
                            dashes=[2, 2])
            m.etopo()
            ax.set_xlim(minlon - padding, maxlon + padding)
            ax.set_ylim(minlat - padding, maxlat + padding)
            width_beach = min((maxlon + 2 * padding - minlon) / (40 * padding),
                              (maxlat + 2 * padding - minlat) / (40 * padding))
        else:
            width_beach = 20
        bb = beach(focmecs,
                   xy=(cmt_lon, cmt_lat),
                   width=width_beach,
                   linewidth=1,
                   alpha=1.0)
        bb.set_zorder(10)
        ax.add_collection(bb)
float(space_station_location['iss_position']['longitude'])

import os
os.environ[
    'PROJ_LIB'] = r'C:\Users\HP\Anaconda3\pkgs\proj4-5.2.0-ha925a31_1\Library\share'

# Let's plot the ISS current location
# You will need to pip install Basemap
from mpl_toolkits.basemap import Basemap

# Set the dimension of the figure
plt.figure(figsize=(16, 8))

# Make the background
m = Basemap(llcrnrlon=-180, llcrnrlat=-65, urcrnrlon=180, urcrnrlat=80)
m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)
m.fillcontinents(color='grey', alpha=0.3)
m.drawcoastlines(linewidth=0.1, color="white")

import requests
r = requests.get(url='http://api.open-notify.org/astros.json')
r.json()
r = requests.get(url='http://api.open-notify.org/iss-now.json')
space_station_location = (r.json())

m.scatter(space_station_location['iss_position']['latitude'],
          space_station_location['iss_position']['longitude'],
          s=500,
          alpha=0.4,
          color='blue')
Example #54
0
import matplotlib.pyplot as plt

# set of latitudes and longitudes for plotting points
latSt = [52.1017, 52.9533, 50.905378, 49.9135, 51.1919]
lonSt = [5.1783, 4.7899, 4.457858, 5.5044, 3.0641]

# define figure attributes
plt.figure(num=None, figsize=(16, 9), dpi=80, facecolor='w', edgecolor='k')

# define map attributes
m = Basemap(width=1400000,height=700000,
            resolution='i',projection='eqdc',\
            lat_1=50.,lat_2=54,lat_0=52,lon_0=4)
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color='lightsage', lake_color='lightblue')
m.drawmapboundary(fill_color='lightblue')
m.drawmapscale(10.7,
               49.1,
               4,
               52,
               200,
               barstyle='fancy',
               units='km',
               fontsize=12,
               yoffset=None,
               labelstyle='simple',
               fontcolor='k',
               fillcolor1='w',
               fillcolor2='k',
               ax=None,
Example #55
0
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.path import Path
import matplotlib.patches as patches

fig = plt.figure()

ax1 = plt.subplot2grid((2, 2), (0, 0))
ax2 = plt.subplot2grid((2, 2), (1, 0))
ax3 = plt.subplot2grid((2, 2), (0, 1), rowspan=2)

map1 = Basemap(projection='ortho', lon_0=0, lat_0=40, ax=ax1)

map1.drawmapboundary(fill_color='#9999FF')
map1.fillcontinents(color='#ddaa66', lake_color='#9999FF')
map1.drawcoastlines()

map2 = Basemap(projection='cyl',
               llcrnrlon=-15,
               llcrnrlat=30,
               urcrnrlon=15.,
               urcrnrlat=50.,
               resolution='i',
               ax=ax2)

map2.drawmapboundary(fill_color='#9999FF')
map2.fillcontinents(color='#ddaa66', lake_color='#9999FF')
map2.drawcoastlines()

map3 = Basemap(llcrnrlon=-1.,
               llcrnrlat=37.5,
Example #56
0
# setup Lambert Conformal basemap.
m = Basemap(llcrnrlon=-95.,
            llcrnrlat=30.,
            urcrnrlon=-75.,
            urcrnrlat=45.,
            projection='mill',
            resolution='i')
#            projection='merc', area_thresh=1000,
#            resolution='i',lat_1=45.,lat_2=55,lat_0=40,lon_0=-85.)

# draw coastlines and fill the continents (alpha value is set to partial transparancy because for some
# reason the fill is over top the quivers used to denote the wind vectors
m.drawcoastlines()
m.drawstates()
m.fillcontinents(color='0.8')
m.drawparallels(np.arange(30, 45, 5), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(-95, -75, 5), labels=[0, 0, 0, 1])

# draw coastlines and fill the continents (alpha value is set to partial transparancy because for some
# reason the fill is over top the quivers used to denote the wind vectors
m.drawcoastlines()
m.drawstates()

m.plot(0, 0, 'g^', label='Site Online')
m.plot(0, 0, 'r^', label='Site Cloudy')
m.plot(0, 0, 'y^', label='No Cloud Data')
m.plot(0, 0, 'rx', label='Site Offline')

for s in sites:
    # Parse the cloud data
Example #57
0
def latview(var, tindex, latitude, gridid, filename=None, \
            cmin=None, cmax=None, clev=None, fill=False, \
            contour=False, d=4, lonrange=None, hrange=None,\
            fts=None, title=None, map=False, \
            pal=None, clb=True, outfile=None):
    """
    latview(var, tindex, latitude, gridid, {optional switch})

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

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

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

    # 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'
        lon = grd.hgrid.lon_vert
        lat = grd.hgrid.lat_vert
        mask = grd.hgrid.mask_rho

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

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

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

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


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

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

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

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

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

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

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

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

    # clear figure
    #plt.clf()

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


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

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

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


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

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

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

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

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


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


    return
Example #58
0
rcParams['figure.figsize'] = (14,10)   
llon=-140                     # Columbia britanic
ulon=-50
llat=40
ulat=65

pdf = pdf[(pdf['Long'] > llon) & (pdf['Long'] < ulon) & (pdf['Lat'] > llat) &(pdf['Lat'] < ulat)]

my_map0 = Basemap(projection='merc',
            resolution = 'l', area_thresh = 1000.0,
            llcrnrlon=llon, llcrnrlat=llat, #min longitude (llcrnrlon) and latitude (llcrnrlat)
            urcrnrlon=ulon, urcrnrlat=ulat) #max longitude (urcrnrlon) and latitude (urcrnrlat)

my_map0.drawcoastlines()
my_map0.drawcountries()
my_map0.fillcontinents(color = 'white', alpha = 0.3)
my_map0.shadedrelief()

# To collect data based on stations        
xs,ys = my_map0(np.asarray(pdf.Long), np.asarray(pdf.Lat))
pdf['xm']= xs.tolist() # long
pdf['ym'] =ys.tolist() # lat

#Visualization1
#for index,row in pdf.iterrows():
    #my_map0.plot(row.xm, row.ym,markerfacecolor =([1,0,0]),  marker='o', markersize= 5, alpha = 0.75)

# Clustering group of stations which show the same location (lat and long)

    # DBSCAN form sklearn library can runs DBSCAN clustering from vector array or distance matrix
    # we pass it the Numpy array Clus_dataSet to find core samples of high density and expands clusters from this sample
Example #59
0
args = parser.parse_args()

fig = plt.figure(figsize=(11.7, 8.3))
plt.subplots_adjust(left=0.05,
                    right=0.95,
                    top=0.90,
                    bottom=0.05,
                    wspace=0.15,
                    hspace=0.05)
ax = plt.subplot(111)
#if args.proj == 'default':
#    m = Basemap(resolution='l')
#elif args.proj == 'npstere':
m = Basemap(projection='npstere', boundinglat=40, lon_0=60, resolution='l')
#else:
#    print('unknown projection type')

m.drawmapboundary(fill_color='azure')
m.fillcontinents(color='palegoldenrod', lake_color='azure')
m.drawcoastlines()
m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(0., 420., 60.), labels=[0, 0, 0, 1])
if args.resolution == 0.:
    grid_res = float(input("Grid resolution in km: "))
else:
    grid_res = args.resolution

click = Click(ax, grid_gen)
#fig.canvas.mpl_connect("button_press_event", onclick)
plt.show()
                     np.arange(-3, 3.01, 0.25),
                     extend='both',
                     alpha=1,
                     zorder=1)
    cs3 = m.contour(x,
                    y,
                    varsicmean,
                    np.arange(15, 30, 15),
                    alpha=1,
                    linewidths=2,
                    colors='gold',
                    zorder=3)

    m.drawlsmask(land_color='dimgrey', ocean_color='k')
    m.drawcoastlines(color='k', linewidth=0.1, zorder=6)
    m.fillcontinents(color='dimgrey', lake_color='dimgrey', zorder=5)
    parallels = np.arange(50, 86, 5)
    meridians = np.arange(-180, 180, 30)
    m.drawparallels(parallels,
                    labels=[False, False, False, False],
                    linewidth=0.0,
                    color='w')
    par = m.drawmeridians(meridians,
                          labels=[True, True, False, False],
                          linewidth=0.0,
                          fontsize=4,
                          color='w')
    setcolor(par, 'darkgrey')

    ### Set colormap
    cmap2 = cmocean.cm.balance