Example #1
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
    def Map(self):
        m = Basemap(projection='cyl',  # stere, tmerc, lcc
                    lat_0=39.828127, lon_0=-98.579404,
                    urcrnrlon=-62.208289, urcrnrlat=51.342619,
                    llcrnrlon=-128.936426, llcrnrlat=19.06875)

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

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

        m.drawstates()
        m.drawcountries()

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

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

        m.scatter(lon, lat, latlon=True, c=np.random.rand(3))
        #m.pcolor(lon, lat, latlon=True)
        plt.title('United States Fair Market Rent')  # add a title
        plt.show()
Example #3
0
    def mapMake(self,renderdpi,table,msize):
        cn = 0
        start = time()

        #initialize connection to database
        cn = psycopg2.connect(secret.DB_CONNECT)
        cr = cn.cursor()

        #get map ready to go
        fig = plt.figure(figsize=(8,4),dpi = renderdpi)
        fig.add_subplot(1,1,1)
        m = Basemap(projection='merc',llcrnrlat=-60,urcrnrlat=75,\
            llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='i')
        m.drawcoastlines(linewidth=.05)
        m.drawcountries(linewidth=.05)

        photoCnt = 0
        points = []

        cr.execute('SELECT latitude,longitude FROM %s;' %  table)
        for row in cr.fetchall():
            x,y = m(row[1],row[0])#convert to merc projection coords
            points.append((x,y))
            photoCnt += 1
        xs,ys = zip(*points)

        plt.title("%d %s" % (photoCnt,table))
        plt.scatter(xs,ys,s=msize,marker='.',c='green',edgecolors='none')
        plt.savefig(table,dpi = renderdpi)

        print "{:d} {:s}  mapped in {:f} seconds".format(photoCnt,\
                                                         table,time()-start)
def makeMap(latList, lonList, cityList):
    minLon = -130
    minLat = 25
    maxLon = -60
    maxLat = 50

    # Below is used to offset a bit the labels of the cities, for projection='merc'.
    labelYOffset = -0.9
    labelXOffset = 0.8

    # Below is used to offset a bit the labels of the cities, for projection='cyl'.
    #labelYOffset = -0.4
    #labelXOffset = 0.8

    plt.figure(1, figsize=(15, 15))
    myMap = Basemap(minLon, minLat, maxLon, maxLat, projection='merc', resolution='h')
    myMap.drawcoastlines()
    # Below if we want to show counties.
    #myMap.drawcounties(linewidth=1, linestyle='solid', color='red')
    # Below if we want to show states.
    #myMap.drawstates(linewidth=2, linestyle='solid', color='green')
    myMap.drawcountries(linewidth=3, linestyle='solid', color='black')
    myMap.drawrivers(linewidth=1, linestyle='solid', color='blue')

    # Another nice option is shaderelief().
    #myMap.shadedrelief()
    myMap.etopo()

    myMap.scatter(latList, lonList, latlon=True, c='red', s=100)
    X, Y = myMap(latList, lonList)
    # The for loop is to add the text labels of the cities.
    for x, y, label in zip(X, Y, cityList):
        plt.text(x + labelXOffset, y + labelYOffset, label)

    return plt.show()
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()
Example #6
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()
def draw_latlon(llclat, urclat, llclon, urclon, rsphere=6371200, resolution='h', area_thresh=0.1, projection='merc'):
    m = Basemap(llcrnrlat=llclat, urcrnrlat=urclat,
                llcrnrlon=llclon, urcrnrlon=urclon,
                rsphere=rsphere, resolution=resolution,
                area_thresh=area_thresh, projection=projection)
    m.drawcoastlines()
    m.drawcountries()
Example #8
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
 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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
0
 def worldplot(self,kmeans=None,proj='merc'):
     """
     plots customer GPS location on a map with state and national boundaries.
     IN
         kmeans (int) number of means for k-means clustering, default=None
         proj (string) the map projection to use, use 'robin' to plot the whole earth, default='merc'
     """
     # create a matplotlib Basemap object
     if proj == 'robin':
         my_map = Basemap(projection=proj,lat_0=0,lon_0=0,resolution='l',area_thresh=1000)
     else:
         my_map = Basemap(projection=proj,lat_0=33.,lon_0=-125.,resolution='l',area_thresh=1000.,
                 llcrnrlon=-130.,llcrnrlat=25,urcrnrlon=-65., urcrnrlat=50)
     my_map.drawcoastlines(color='grey')
     my_map.drawcountries(color='grey')
     my_map.drawstates(color='grey')
     my_map.drawlsmask(land_color='white',ocean_color='white')
     my_map.drawmapboundary() #my_map.fillcontinents(color='black')
     x,y = my_map(np.array(self.data['lon']),np.array(self.data['lat']))
     my_map.plot(x,y,'ro',markersize=3,alpha=.4,linewidth=0)
     if kmeans:
         # k-means clustering algorithm---see wikipedia for details
         data_in = self.data.drop(['id','clv','level'],axis=1)
         # vq is scipy's vector quantization module
         output,distortion = vq.kmeans(data_in,kmeans)
         x1,y1 = my_map(output[:,1],output[:,0])
         my_map.plot(x1,y1,'ko',markersize=20,alpha=.4,linewidth=0)
     plt.show()
     return output
def plot_map(lons, lats, c, legend_label, projection='mill',
             llcrnrlat=-80, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='i'):
    
    ''' Optional Arguments: projection - map projection, default set as 'mill'
                            llcrnrlat - lower left corner latitude value, default is -80
                            urcrnrlat - upper right corner latitude value, default is 90
                            llcrnrlon - lower left corner longitude value, default is -180
                            urcrnrlon - upper right corner longitude value, default is 180
                            resolution - the resolution of the plot, default is 'i'
                            
        Required Arguments: lons - list of longitude values to be plotted
                            lats - list of latitude values to be plotted
                            c - the color of the points to be plotted
                            legend_label - how this set of points will be labeled on the legend
                            
        Returns:            m - a basemap object defined by input bounds with input points included '''
    
    # Creates a basic plot of a series of lat,lon points over a defined region
    m = Basemap(projection=projection, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,
                llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution=resolution)
    m.drawcoastlines()
    m.drawmapboundary()
    m.drawcountries()
    m.etopo()
    m.drawmeridians(np.arange(llcrnrlon, urcrnrlon, 5), labels=[0,0,0,1], fontsize=10)
    m.drawparallels(np.arange(llcrnrlat, urcrnrlat, 5), labels=[1,0,0,0], fontsize=10)
    x,y = m(lons, lats)
    m.scatter(x, y, color=c, label=legend_label, marker='o', edgecolor='none', s=10)
    return m
Example #17
0
def nepal_basemap(prams = nepal_ETAS_prams, fnum=0, map_res='i', **kwargs):
	# hours_after: upper time limit for aftershocks to plot.
	prams.update(kwargs)
	#
	lons_nepal = [83., 87.]
	lats_nepal = [26., 30.]
	
	todt=prams.get('todt', None)
	catlen=prams.get('catlen', 5.*365.)
	lons=prams['lons']
	lats=prams['lats']
	mc = prams['mc']
	#
	if todt==None: todt = dtm.datetime.now(pytz.timezone('UTC'))
	dt0 = todt - dtm.timedelta(days=catlen)
	#
	plt.figure(fnum)
	plt.clf()
	ax1=plt.gca()
	cntr = [.5*(lons[0]+lons[1]), .5*(lats[0]+lats[1])]
	#
	cm=Basemap(llcrnrlon=lons_nepal[0], llcrnrlat=lats_nepal[0], urcrnrlon=lons_nepal[1], urcrnrlat=lats_nepal[1], resolution=map_res, projection='cyl', lon_0=cntr[0], lat_0=cntr[1])
	cm.drawcoastlines(color='gray', zorder=1)
	cm.drawcountries(color='gray', zorder=1)
	cm.drawstates(color='gray', zorder=1)
	cm.drawrivers(color='gray', zorder=1)
	cm.fillcontinents(color='beige', zorder=0)
	#
	cm.drawmeridians(list(range(int(lons[0]), int(lons[1]))), color='k', labels=[0,0,1,1])
	cm.drawparallels(list(range(int(lats[0]), int(lats[1]))), color='k', labels=[1, 1, 0, 0])
	#
	return cm
def map_vis(data,title=[],vmin=None,vmax=None,barlabel=None,cmap=None,outputdir=None):
    # print("visualizing : "+title)
    if cmap==None:
        cmap=cm.jet
    if len(data.shape)>2:
        plotdata=data[0,:,:]
    else:
        plotdata=data
    plt.clf()
    # plt.figure(figsize=(3,3),dpi=200)
    ny,nx=plotdata.shape
    geo=[35,43,-113,-101]
    if experiment=="conus":geo=[25,52.7,-124.7,-67]
    m = Basemap(projection='cyl',llcrnrlat=geo[0],urcrnrlat=geo[1],\
                llcrnrlon=geo[2],urcrnrlon=geo[3],resolution="i")
    
    mapimg=m.imshow(plotdata,vmin=vmin,vmax=vmax,cmap=cmap)
    if experiment=="conus":
        m.drawparallels(np.arange(25,55,5.),labels=[1,0,0,0],dashes=[1,4])
        m.drawmeridians(np.arange(-120,-65,10.),labels=[0,0,0,1],dashes=[1,4])
        m.drawstates(linewidth=0.5)
        m.drawcountries(linewidth=0.5)
        m.drawcoastlines(linewidth=0.5)
    else:
        m.drawparallels(np.arange(36,43,2.),labels=[1,0,0,0],dashes=[1,4])
        m.drawmeridians(np.arange(-112,-103,4.),labels=[0,0,0,1],dashes=[1,4])
        m.drawstates(linewidth=1.5)
    cbar=m.colorbar()
    if barlabel:
        cbar.set_label(barlabel)
    plt.title(" ".join(title))
    if outputdir:
        plt.savefig(outputdir+"_".join(title)+'_map.png')
    else:
        plt.savefig("_".join(title)+'_map.png')
Example #19
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)
def displayWindMapPlot(vdata,udata, lons, lats,):
    """ TODO add a docstring! """
    #plt.clf()
    #pc = plt.contourf(lons, lats, data, 20)
    #plt.colorbar(pc, orientation='horizontal')
    #plt.title(title)
    #plt.xlabel("longitude (degrees east)")
    #plt.ylabel("latitude (degrees north)")
    #plt.show()
    fig, ax = plt.subplots()
    # Do the plot code
    # make orthographic basemap.
    m = Basemap(projection='cyl',llcrnrlat=-40,urcrnrlat=0,\
            llcrnrlon=-20,urcrnrlon=60,resolution='l')

    X,Y=np.meshgrid(lons, lats)
    x,y=m(X,Y) #Convert to map coordinates
    #m.barbs(x,y,vdata,udata,20)
    m.quiver(x,y,vdata,udata,10)
    plt.streamplot(x,y,vdata,udata,10)
    #plt.colorbar(pc,orientation='horizontal')
    m.drawmapboundary()
    m.drawcountries()
    
    m.drawcoastlines(linewidth=1.5)
    
    fig.savefig('myimage.svg', format='svg', dpi=1200)
    plt.show()
    #m.drawparallels(parallels)
    #m.drawmeridians(meridians)
    
    
    """ Contains code for displaying data """
Example #21
0
def Map_plot_subregion(subregions, ref_dataset, directory):

    lons, lats = np.meshgrid(ref_dataset.lons, ref_dataset.lats)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    m = Basemap(
        ax=ax,
        projection='cyl',
        llcrnrlat=lats.min(),
        urcrnrlat=lats.max(),
        llcrnrlon=lons.min(),
        urcrnrlon=lons.max(),
        resolution='l')
    m.drawcoastlines(linewidth=0.75)
    m.drawcountries(linewidth=0.75)
    m.etopo()
    x, y = m(lons, lats)
    #subregion_array = ma.masked_equal(subregion_array, 0)
    #max=m.contourf(x, y, subregion_array, alpha=0.7, cmap='Accent')
    for subregion in subregions:
        draw_screen_poly(subregion[1], m, 'w')
        plt.annotate(
            subregion[0],
            xy=(0.5 * (subregion[1][2] + subregion[1][3]),
                0.5 * (subregion[1][0] + subregion[1][1])),
            ha='center',
            va='center',
            fontsize=8)
    fig.savefig(directory + 'map_subregion', bbox_inches='tight')
Example #22
0
def plot_grid2D(lons, lats, tec_grid2D, datetime, title_label = ''):

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

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

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

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

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

	plt.title('%s\n%s' % (title_label, datetime.isoformat(' ')))
Example #23
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 plot_ICON_clt(ICON_data_dict):
	"This function gets ICON data and plots corresponding satellite pictures."

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

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

	# Plotting temperature data
	plt.figure()
	# Plot contourf plot with lat/lon regridded ICON data
	cmap_cloud   = plt.cm.gray
	levels_cloud = np.arange(0,101,10)
	plt.contourf(ICON_data_dict["ICON_X_mesh"], ICON_data_dict["ICON_Y_mesh"], ICON_data_dict["ICON_clt"], levels=levels_cloud, cmap=cmap_cloud)
	plt.colorbar()
	# Plot map data
	map = Basemap(llcrnrlon=4.0,llcrnrlat=47.0,urcrnrlon=15.0,urcrnrlat=55.0,
	             resolution='i')
	map.drawcoastlines()
	map.drawcountries()
	lat_ticks = [55.0,53.0,51.0,49.0,47.0]
	map.drawparallels(lat_ticks, labels=[1,0,0,0], linewidth=0.0)
	lon_ticks = [4.0,6.0,8.0,10.0,12.0,14.0]
	map.drawmeridians(lon_ticks, labels=[0,0,0,1], linewidth=0.0)
	# Save plot and show it
	plt.savefig(output_path + 'TotalCloudCover_' + time_string + '.png')
Example #25
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 #26
0
def Scatter(data, lons, lats, min, max, cmp, tit, unit, figdir, filename):
    # Prepare for drawing
    # ny, nx = (50, 116)
    # draw Chile Basemap with lambert projection at normal x, y settings
    m = Basemap(
        llcrnrlon=-78,
        llcrnrlat=-56,
        urcrnrlon=-66,
        urcrnrlat=-17,
        projection="cyl",
        fix_aspect=False,
        lat_1=-43,
        lat_2=-30,
        lon_0=-72,
    )  # projection='lcc'
    # draw boundaries
    m.drawcoastlines()
    m.drawcountries(linewidth=2)
    m.drawstates()
    m.drawparallels(arange(-60, -15, 15), labels=[1, 0, 0, 0])  # only left ytick
    m.drawmeridians(arange(-80, -60, 5), labels=[0, 0, 0, 1])  # only bottom xtick
    # map data with lon and lat position
    im = m.scatter(lons, lats, 30, marker="o", c=data, vmin=min, vmax=max, latlon=True, cmap=cmp)
    cb = m.colorbar(im, pad="10%")
    plt.title(tit, fontsize=20)
    plt.xlabel(unit, labelpad=50)
    # savefig('%s%s' % (figdir, filename))
    plt.show()
def onpress(event):
    if event.button != 1:
        return
    x, y = event.x, event.y
    coord_lat = 40
    coord_lon = -75
    zoom_map = Basemap(projection='mill',
                     llcrnrlat=coord_lat,
                     llcrnrlon=coord_lon,
                     urcrnrlat=43,
                     urcrnrlon=-69.5,
                     resolution='c')
    zoom_map.drawcoastlines()
    zoom_map.drawcountries()
    zoom_map.drawmapboundary()
    zoom_map.drawstates()

    for i in range(len(size)):
        if size[i] <= 5000:
            zoom_map.plot(x[i], y[i], 'go', markersize=size[i]/1000)
        elif size[i] >= 10000:
            zoom_map.plot(x[i], y[i], 'ro', markersize=size[i]/1000)
        else:
            zoom_map.plot(x[i], y[i], 'bo', markersize=size[i]/1000)
    plt.show()
Example #28
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 #29
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 #30
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()
def map_error_radius(radius, outfile, minradius=None, maxradius=None):
    """Plots a map of storm tracks in the Southern Hemisphere
	Plots a map of storm tracks for one storm in the Southern Hemisphere
	from a list of several TRACK files (e.g. one per year) that have been reformatted to suit Python
	Plots all forecasts of one storm, and the reanalysis and ibtracs tracks.
	Plots the tracks so that they change colour from lighter to darker with time
	Note: the colormap used is hardcoded in the function (where 'colors' is assigned)
	Function takes a list of filenames as  input argument"""

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

    #elif region == "SIO":
    #lat1=30
    #lat2=-55
    #lon1=-10
    #lon2=130

    lat1 = 5
    lat2 = -22
    lon1 = 35
    lon2 = 65

    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='f')

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

    #draw_rectangle(RSMClats,RSMClons,m)

    #m.bluemarble(alpha=0.8)
    m.drawcoastlines(linewidth=0.4, color='darkgray')
    m.drawcountries(linewidth=0.4, color='darkgray')
    m.fillcontinents(color='lightgray', alpha=0.4)

    hurricane = get_hurricane_symbol()

    #xs, ys = m(42.0, -10.0)
    #m.scatter(xs, ys, marker=hurricane, edgecolors='royalblue', facecolors='None', s=100, linewidth=1)

    centrelat = -8.0
    centrelon = 52.0
    radiusindeg = radius / 110.574  #the average location error 3 days ahead in 2015-2016

    x, y = m(centrelon, centrelat)
    x2, y2 = m(centrelon, centrelat + radiusindeg)
    circle1 = plt.Circle((x, y),
                         y2 - y,
                         edgecolor='blue',
                         facecolor='blue',
                         alpha=0.5)
    ax.add_patch(circle1)

    if minradius:
        minradiusindeg = minradius / 110.574
        x, y = m(centrelon, centrelat)
        x2, y2 = m(centrelon, centrelat + minradiusindeg)
        circle2 = plt.Circle((x, y),
                             y2 - y,
                             edgecolor='blue',
                             facecolor='None',
                             linestyle='--',
                             linewidth=0.5,
                             alpha=0.5)
        ax.add_patch(circle2)

    if maxradius:
        maxradiusindeg = maxradius / 110.574
        x, y = m(centrelon, centrelat)
        x2, y2 = m(centrelon, centrelat + maxradiusindeg)
        circle3 = plt.Circle((x, y),
                             y2 - y,
                             edgecolor='blue',
                             facecolor='blue',
                             linestyle='--',
                             linewidth=0.5,
                             alpha=0.2)
        ax.add_patch(circle3)

    x, y = m(centrelon, centrelat)
    m.scatter(x,
              y,
              marker=hurricane,
              edgecolor='k',
              facecolor='None',
              s=50,
              zorder=10,
              linewidth=0.5)

    #legend
    #if cat == "TS":
    #title = cat+" "+str(name)+"\n"
    #else:
    #title="Category "+str(cat)+" "+str(name)+"\n"+str(startdate)+" - "+str(enddate)
    #ib = plt.Line2D((0, 1), (0, 0), color='white', linestyle='--',linewidth=0.5)
    #an = plt.Line2D((0, 1), (0, 0), color='navy', linestyle='-',linewidth=0.5)
    #nwp = plt.Line2D((0, 1), (0, 0), color='orange',linewidth=0.5)
    #legend = ax.legend((an,ib), ['Analysis Track',' '],title=title, fontsize=5, loc='lower left')
    #plt.setp(legend.get_title(), fontsize='5')
    #legend._legend_box.align = "left"

    #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 #32
0
print('=' * 80)
print('Finish calculate mean value ')

mean_array = np.array(mean_array)

print('=' * 80)
print('Draw picture')
#Draw map
plt.figure(figsize=(10, 10))

# sylender map
m = Basemap(projection='cyl', resolution='h', \
            llcrnrlat = Slat, urcrnrlat = Nlat, \
            llcrnrlon=Llon, urcrnrlon = Rlon)
m.drawcoastlines(linewidth=0.25)
m.drawcountries(linewidth=0.25)
#m.fillcontinents(color='coral',lake_color='aqua')
#m.drawmapboundary(fill_color='aqua')
m.drawparallels(np.arange(-90., 90., 10.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-180., 181., 15.), labels=[0, 0, 0, 1])

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

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

plt.title('MODIS AOD', fontsize=20)
plt.savefig(dir_name + f_name + '.png', bbox_inches='tight', dpi=300)

plt.show()
Example #33
0
##import basemap module,so basemap will shows in the background
from mpl_toolkits.basemap import Basemap
#import the matplotlib module to plot the data on the canvas
import matplotlib.pyplot as plt
import numpy as np

##set up the basemap for background :set up the extend for study area, which is South America
##set up the projection for the map which is the web mecator that project angles. 
##
map = Basemap(llcrnrlon=-100., llcrnrlat=-45.,urcrnrlon=-20.,urcrnrlat=20.,
            projection='merc',lat_1=-50.,lat_2=20.,lon_0=-70.,
            resolution ='h',area_thresh=1000.)
##draw coast lines on the map
map.drawcoastlines()
## draw the countries lines
map.drawcountries()
## fill the continent with customize color
map.fillcontinents(color = 'DarkGrey')
## draw map boundaries
map.drawmapboundary()

## creating a funcition that call each sample and set it different color
def get_marker_color(sampleID):
    if sampleID == 'H974':
        return ('go')
    elif sampleID == 'H976':
        return ('yo')
    elif sampleID == 'H978':
        return ('bo')
    elif sampleID == 'H980':
        return ('co')
Example #34
0
def draw_map(map_type, geo_dict, filename, headless):
    import matplotlib as mpl
    if headless:
        mpl.use("Agg")
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap

    ## Map stuff ##
    plt.figure(figsize=(16, 9), dpi=100, frameon=False, tight_layout=True)
    lon_r = 0
    lon_l = 0

    if map_type == 'NA':
        m = Basemap(llcrnrlon=-119,
                    llcrnrlat=22,
                    urcrnrlon=-54,
                    urcrnrlat=55,
                    projection='lcc',
                    resolution='l',
                    lat_1=32,
                    lat_2=45,
                    lon_0=-95)
        lon_r = 66.0
        lon_l = -124.0
    elif map_type == 'EU':
        m = Basemap(llcrnrlon=-15.,
                    llcrnrlat=20,
                    urcrnrlon=75.,
                    urcrnrlat=70,
                    projection='lcc',
                    resolution='l',
                    lat_1=30,
                    lat_2=60,
                    lon_0=35.)
        lon_r = 50.83
        lon_l = -69.03

    elif map_type == 'World':
        m = Basemap(projection='robin',
                    lat_0=0,
                    lon_0=-100,
                    resolution='l',
                    area_thresh=100000.0)
        m.drawmeridians(np.arange(0, 360, 30))
        m.drawparallels(np.arange(-90, 90, 30))
        lon_r = 180
        lon_l = -180.0

    # remove line in legend
    mpl.rcParams['legend.handlelength'] = 0
    m.drawmapboundary(fill_color='#1F1F1F')
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.fillcontinents(color='#3C3C3C', lake_color='#1F1F1F')

    for key, values in geo_dict.items():
        # add Accuracy as plot/marker size, change play count to del_s value.
        for data in values:
            if key == SERVER_FRIENDLY:
                color = '#FFAC05'
                marker = '*'
                markersize = 10
                zord = 3
                alph = 1
            else:
                if data['platform'] in PLATFORM_COLORS:
                    color = PLATFORM_COLORS[data['platform']]
                else:
                    color = DEFAULT_COLOR
                    print(
                        'Platform: {} is missing from PLATFORM_COLORS. Using DEFAULT_COLOR.'
                        .format(data['platform']))
                marker = '.'
                if data['play_count'] >= 100:
                    markersize = (data['play_count'] * .1)
                elif data['play_count'] <= 2:
                    markersize = 2
                else:
                    markersize = 2
                zord = 2
                alph = 0.4
            px, py = m(float(data['lon']), float(data['lat']))
            x, y = m(
                [float(data['lon']), float(SERVER_LON)],
                [float(data['lat']), float(SERVER_LAT)])
            legend = 'Location: {}, {},  User: {}\nPlatform: {}, IP: {}, Play Count: {}'.format(
                data['city'], data['region'], key, data['platform'],
                data['ip'], data['play_count'])
            # Keeping lines inside the Location. Plots outside Location will still be in legend

            if float(data['lon']) != float(SERVER_LON) and float(data['lat']) != float(SERVER_LAT) and \
                                    lon_l < float(data['lon']) < lon_r:
                # Drawing lines from Server location to client location
                if data['location_count'] > 1:
                    lines = m.plot(x,
                                   y,
                                   marker=marker,
                                   color=color,
                                   markersize=0,
                                   label=legend,
                                   alpha=.6,
                                   zorder=zord,
                                   linewidth=2)
                    # Adding dash sequence to 2nd, 3rd, etc lines from same city,state
                    for line in lines:
                        line.set_solid_capstyle('round')
                        dashes = [
                            x * data['location_count'] for x in [5, 8, 5, 8]
                        ]
                        line.set_dashes(dashes)

                else:
                    lines = m.plot(x,
                                   y,
                                   marker=marker,
                                   color=color,
                                   markersize=0,
                                   label=legend,
                                   alpha=.4,
                                   zorder=zord,
                                   linewidth=2)

            client_plot = m.plot(px,
                                 py,
                                 marker=marker,
                                 color=color,
                                 markersize=markersize,
                                 label=legend,
                                 alpha=alph,
                                 zorder=zord)

    handles, labels = plt.gca().get_legend_handles_labels()
    idx = labels.index(
        'Location: {}, {},  User: {}\nPlatform: {}, IP: {}, Play Count: {}'.
        format(SERVER_CITY, SERVER_STATE, SERVER_FRIENDLY, SERVER_PLATFORM,
               REPLACEMENT_WAN_IP, 0))
    labels = labels[idx:] + labels[:idx]
    handles = handles[idx:] + handles[:idx]
    by_label = OrderedDict(zip(labels, handles))

    leg = plt.legend(by_label.values(),
                     by_label.keys(),
                     fancybox=True,
                     fontsize='x-small',
                     numpoints=1,
                     title="Legend",
                     labelspacing=1.,
                     borderpad=1.5,
                     handletextpad=2.)
    if leg:
        lleng = len(leg.legendHandles)
        for i in range(1, lleng):
            leg.legendHandles[i]._legmarker.set_markersize(10)
            leg.legendHandles[i]._legmarker.set_alpha(1)
        leg.get_title().set_color('#7B777C')
        leg.draggable()
        leg.get_frame().set_facecolor('#2C2C2C')
        for text in leg.get_texts():
            plt.setp(text, color='#A5A5A7')

    plt.title(title_string)
    if filename:
        plt.savefig('{}.png'.format(filename))
        print('Image saved as: {}.png'.format(filename))
    if not headless:
        mng = plt.get_current_fig_manager()
        mng.window.state('zoomed')
        plt.show()
Example #35
0
lat_j = str(jingdu[u'纬度']).split()[1]
lat_j = re.findall(r'(\w*[0-9]+)\w*', lat_j)  #get the number
lat_j = float(lat_j[0])

lon_j = str(jingdu[u'经度']).split()[1]
lon_j = re.findall(r'(\w*[0-9]+)\w*', lon_j)  #get the number
lon_j = float(lon_j[0] + '.' + lon_j[1])

img = plt.imread('2.png', format='jpeg')

cv2.destroyAllWindows()

m = Basemap(projection='mill',
            llcrnrlon=-180,
            llcrnrlat=-55,
            urcrnrlon=180,
            urcrnrlat=85)

m.drawcoastlines()
m.fillcontinents()
m.drawcountries()
m.drawgreatcircle(lon_s, lat_s, lon_j, lat_j, linewidth=2, color='b')

x, y = m(lon_s, lat_s)
im = OffsetImage(img, zoom=0.3)
ab = AnnotationBbox(im, (x, y), xycoords='data', frameon=False)

m._check_ax().add_artist(ab)

plt.show()
Example #36
0
    xx, yy = m(lons, lats)

    xlabels = [0, 0, 0, 1]

    if i == 0:
        ylabels = [1, 0, 0, 0]
    elif i == 2:
        ylabels = [0, 1, 0, 0]
    else:
        ylabels = [0, 0, 0, 0]

    m.drawparallels(np.arange(5, 30, 5), labels=ylabels, fontsize=8)
    m.drawmeridians(np.arange(90, 115, 5), labels=xlabels, fontsize=8)

    m.drawcountries(linewidth=0.5, zorder=11)
    m.drawcoastlines(linewidth=0.5, zorder=12)
    m.fillcontinents(color='silver')

    #if cnt == 0:
    #
    #    cb = m.pcolormesh(xx,yy,dSclm,cmap='seismic_r',vmin=-1000,vmax=1000)
    #    ax[i,j].set_title('Baseline',fontsize=10)
    #else:
    cb = m.pcolormesh(xx,
                      yy,
                      trends[i, :, :],
                      cmap='bwr_r',
                      norm=colors.BoundaryNorm(boundaries=clevels,
                                               ncolors=256),
                      zorder=10)
Example #37
0
lon1 = [-80, -80, -68, -68, -80]

lat2 = [29.5, 20, 20, 29.5, 29.5]
lon2 = [-97, -97, -90, -90, -97]

fig = plt.figure(figsize=(8, 8), edgecolor='W', facecolor='W')
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

map = Basemap(projection='merc',
              llcrnrlat=0,
              urcrnrlat=40,
              llcrnrlon=-120,
              urcrnrlon=-55,
              resolution='i')
map.drawcoastlines(linewidth=0.8)
map.drawcountries(linewidth=0.8)
map.drawparallels(np.arange(0, 40, 10), labels=[1, 0, 0, 1])
map.drawmeridians(np.arange(-120, -55, 10), labels=[1, 0, 0, 1])

LON1, LAT1 = map(lon1, lat1)
LON2, LAT2 = map(lon2, lat2)

map.plot(LON1, LAT1, marker=None, color='k', linewidth=1.5)
map.plot(LON2, LAT2, marker=None, color='k', linewidth=1.5)

ax.set_title('$Ubicacion$ $Indices$', size='15')
map.fillcontinents(color='white')

plt.show()

#==============================================================================
Example #38
0
df_events_sample = df_events.sample(n=100000)
plt.figure(1, figsize=(12, 6))

# Mercator of World
m1 = Basemap(projection='merc',
             llcrnrlat=-60,
             urcrnrlat=65,
             llcrnrlon=-180,
             urcrnrlon=180,
             lat_ts=0,
             resolution='c')

m1.fillcontinents(color='#191919',
                  lake_color='#000000')  # dark grey land, black lakes
m1.drawmapboundary(fill_color='#000000')  # black background
m1.drawcountries(linewidth=0.1,
                 color="w")  # thin white line for country borders

# Plot the data
mxy = m1(df_events_sample["longitude"].tolist(),
         df_events_sample["latitude"].tolist())
m1.scatter(mxy[0], mxy[1], s=3, c="#1292db", lw=0, alpha=1, zorder=5)

plt.title("Global view of events")
plt.show()

# Not surprisingly, most of the events are geo-located in China. We also see a few sporadic ones around the globe, most which look real (e.g., Austalia-Sydney/Melbourne/Perth).
#
# One interesting thing is there are a number of events at (lat,lon) = (0,0), and also around that area where there is not much land.

# In[ ]:
Example #39
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import urllib.request
import json

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

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


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


# animation function.  This is called sequentially
def animate(i):
    lons, lats = iss_position()
    x, y = globe(lons, lats)
    point.set_data(x, y)
    return point,
Example #40
0
def main():
    print(df.columns)
    print(len(df))
    df.drop([ 'updated', 'url', 'detail', 'felt',
       'alert', 'status', 'tsunami', 'net', 'code', 'ids', 'sources', 'types',
       'nst', 'dmin', 'rms', 'gap', 'magType', 'type', 'title',
       'geometry_type', 'id'], axis=1, inplace=True)
    print(df.head())
    print(df)
#     ranges = df['time']
#     print(time.ctime(df['time']))
#     print(time.gmtime(df['time']))
    ranges = [0, 5, 6, 7, 8, 99]
    group_mag = df['mag'].groupby(pd.cut(df.mag, ranges, right=False)).count()
#     year_mag = df['mag'].groupby(pd.cut(df.mag, df[], right=False)).count()
    print(group_mag)
    plt.figure(figsize=(27, 12))
    sns.distplot(df['mag'], bins=100, color='g')

#     ax.plot(bins, y, '--')
#     ax.set_xlabel('Smarts')
#     ax.set_ylabel('Probability density')
#     ax.set_title(r('Histogram of IQ: $\mu=' + mu +'$, $\sigma=' + 'signam' + '$'))

    # Tweak spacing to prevent clipping of ylabel
#     fig.tight_layout()
#     plt.show()
#     plt.pause(20)
    df6=df[df['mag'] > 6]
    yearly_count = pd.to_datetime(df6['time'],  unit='ms').dt.year.value_counts().sort_index()
#     sns.barplot(x='year', y='mag6_num', data=df[''])

    print(yearly_count.index, yearly_count.values)
#     fig, ax = plt.subplots()
    plt.figure(figsize=(27, 12))
#     plt.subplot(111)
    plt.bar(yearly_count.index.tolist(), yearly_count.values.tolist())
    plt.title('Num of Earthquakes Mag 6+ 1950-2020')
    plt.show()
    plt.savefig('num_of_earthquakes6_1950_2020.jpg')
    plt.pause(20)
    print(len(df6))
    print(df6)
    plt.figure(figsize=(27, 12))
    m = Basemap()
    ax = plt.gca()

    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.shadedrelief()
    m.readshapefile( 'C:/Users/xuzhen/usgs/gadm36_CHN_shp/gadm36_CHN_1', 'states', drawbounds=True)


    for indexs in df6.index:
        lon2,lat2 = float(df6.loc[indexs].values[5].split(',')[0].replace('[','')), float(df6.loc[indexs].values[5].split(',')[1])
#         print(lon2,lat2)
        x,y = m(lon2,lat2)
#         m.plot(x,y,'ro',markersize = 2) 
        ax.scatter(x, y,  cmap='hsv',  s=np.pi*(df6.loc[indexs].values[0]/4.5)**2, alpha=1)
    plt.title('Earthquakes Mag 6+ 1950-2020')
    plt.savefig('map_of_earthquakes6_1950_2020.jpg')
def draw_map(station_etude,
             latm,
             latM,
             lonm,
             lonM,
             path,
             all_pos,
             hw,
             vn_ITRF,
             ve_ITRF,
             plot_vertical_ITRF,
             incvn_ITRF,
             incve_ITRF,
             incplot_vertical_ITRF,
             plot_GEBCO=False,
             plot_vertical=False,
             plot_topo=True,
             plot_ellipses=True,
             coarse_lines=False,
             legend_arrow_length=("1 cm/yr", 0.01),
             legend_ellipse_size=("2 mm/yr", 0.002),
             legend_position=(0.5, 0.9),
             scale_arrow=15000000,
             scale_ellipse=10000000,
             name_stats=True,
             name_stats_font_size=8,
             name_stats_offset=(0.005, 0.01),
             shorten_oversized_arrows=True,
             exclude_points_out_of_range=True,
             adjust_text=False,
             pixels_hires_backgrnd=2000,
             draw_borders=True,
             full_return=False,
             draw_latlon_lines=True):
    """
    """

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    plt.tight_layout()

    if full_return:
        return fig, ax, m, Text
    else:
        return fig, ax, m, Text
	#ax1 = plt.gca()
	#ax1.set_ylim(ax1.get_ylim()[::-1])
	ax1.scatter(temptemp[i], depthdepth[i], color='r', label='in-situ')
	ax1.scatter(temp[i], dt[15*i:15*i+15], color='b', label='model')
	ax1.legend(loc=3)
	m2 = Basemap(projection='merc', llcrnrlat=51,urcrnrlat=51.9,llcrnrlon=2.0,urcrnrlon=3.5,lat_ts=51.45, resolution='i', ax=ax2)
	m2.drawparallels(arange(51.0,51.9,0.3),labels=[1,0,0,1],fontsize=10)
	m2.drawmeridians(arange(2,3.5,0.5),labels=[1,0,0,1],fontsize=10)
	m2.drawcoastlines()
	m2.drawmapboundary(fill_color='#9999FF')
	x4, y4 = m2(x_bcz, y_bcz); 	lnln, ltlt = m2(lonlon[i], latlat[i]); lg,lt=m2(long[i],lati[i]);clevs = np.arange(0.,60.0,1);cax = fig.add_axes([0.2, 0.08, 0.6, 0.04])
	x2, y2 = m2(lon, lat)
	cs43 = m2.plot(x4,y4,color='black',linewidth=1.0)
	CS4 = m2.contourf(x2,y2,h,clevs,cmap='Blues',animated=True)
	cb1 = colorbar(CS4, cax, orientation='horizontal')
	m2.drawcountries()
	m2.fillcontinents(color='#ddaa66',lake_color='#9999FF')
	m2.scatter(lnln,ltlt,20,marker='o',color='r')
	m2.scatter(lg,lt,20,marker='o',color='b')

show()
'''
#m1 = Basemap(projection='merc',llcrnrlat=49,urcrnrlat=54.0,llcrnrlon=-1,urcrnrlon=6,lat_ts=51.5,resolution='i')
m1 = Basemap(projection='merc', llcrnrlat=51,urcrnrlat=51.9,llcrnrlon=2.0,urcrnrlon=3.5,lat_ts=51.45,resolution='h')
m1.drawparallels
m1.drawmeridians
m1.drawcoastlines()
m1.drawmapboundary(fill_color='#9999FF')
m1.drawcountries()
m1.fillcontinents(color='#ddaa66',lake_color='#9999FF')
x, y = m1(longitude, latitude)
Example #43
0
    def showGlobalPlot(self,fsize=[14,14],cmap='jet',m=None,figname='fig'):
        """
        Utilities for spatio temporal analysis
        @author zed.uchicago.edu

        Plot global distribution of events
        within time period specified

        Inputs -
            fsize (list):
            cmap (string):
            m (mpl.mpl_toolkits.Basemap): mpl instance for plotting
            figname (string): Name of the Plot

        Returns -
            m (mpl.mpl_toolkits.Basemap): mpl instance of heat map of
                crimes from fitted data
        """

        fig=plt.figure(figsize=(14,14))
        # read in data to use for plotted points

        A=[]
        for key,value in self._ts_dict.iteritems():
            A.append(np.array([i.replace("#"," ")
                               .split()[0:4] for i in value.index])
                     .astype(float))

        B=np.array(A[0]).reshape(len(A[0]),4)

        lat = (B[:,0]+B[:,1])/2
        lon = (B[:,2]+B[:,3])/2
        A=[]
        for key,value in self._ts_dict.iteritems():
            A.append(value.sum(axis=1).values)

        val = np.array(A)


        # determine range to print based on min, max lat and lon of the data
        margin = 2 # buffer to add to the range
        lat_min = min(lat) - margin
        lat_max = max(lat) + margin
        lon_min = min(lon) - margin
        lon_max = max(lon) + margin

        # create map using BASEMAP
        if m is None:
            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()
            m.drawmapboundary(fill_color='#acbcec')
            m.fillcontinents(color = 'k',lake_color='#acbcec')

        # convert lat and lon to map projection coordinates
        lons, lats = m(lon, lat)
        # plot points as red dots
        m.scatter(lons, lats,s=val+1, c=val, cmap=cmap,
                  norm=colors.LogNorm(vmin=np.min(val)+1, vmax=np.max(val)+1),
                  zorder=5)

        plt.savefig(figname+'.pdf',dpi=300,bbox_inches='tight',transparent=True)

        return m
def plot_fire_map(wildfire_data):
    '''
    Plot to show the geographic distribution of the fire data
    Takes the input as the lower and upper limit of the fire size

    :param: wildfire dataframe, basemap object, int, int
    :return: fig object
    '''
    plt.subplots(figsize=[15, 8])
    map = Basemap(projection='cyl',llcrnrlat=24,urcrnrlat=72,\
            llcrnrlon=-170,urcrnrlon=-65,)
    map.drawlsmask(ocean_color='lightcyan', lakes=True, zorder=1)
    map.fillcontinents(color='darkgrey', zorder=2, lake_color='lightcyan')
    map.drawcoastlines(linewidth=0.75, zorder=3)
    map.drawcountries(linewidth=0.85, color='black', zorder=3)
    map.drawstates(linewidth=0.15, zorder=3)
    #map.drawmapboundary()
    map.drawparallels(np.arange(0., 90., 20),
                      labels=[1, 0, 0, 0],
                      fontsize=10,
                      zorder=3)
    map.drawmeridians(np.arange(-160, -90, 20),
                      labels=[0, 0, 0, 1],
                      fontsize=10,
                      zorder=3)

    ## Large fires
    lim_low = 65000
    lim_high = 3000000
    w1 = wildfire_data.loc\
        [(wildfire_data['FIRE_SIZE']<lim_high) & (wildfire_data['FIRE_SIZE']>=lim_low)]
    long_temp = w1['LONGITUDE']
    lat_temp = w1['LATITUDE']

    scat = map.scatter(long_temp, lat_temp, s=10)
    scat.set_color('r')
    scat.set_alpha(0.65)
    scat.set_zorder(12)

    # Medium fires
    lim_low = 30000
    lim_high = 65000
    w1 = wildfire_data.loc\
        [(wildfire_data['FIRE_SIZE']<lim_high) & (wildfire_data['FIRE_SIZE']>=lim_low)]
    long_temp = w1['LONGITUDE']
    lat_temp = w1['LATITUDE']

    scat = map.scatter(long_temp, lat_temp, s=10)
    scat.set_color('orange')
    scat.set_alpha(0.95)
    scat.set_zorder(11)

    ## Small fires
    lim_low = 10000
    lim_high = 30000
    w1 = wildfire_data.loc\
        [(wildfire_data['FIRE_SIZE']<lim_high) & (wildfire_data['FIRE_SIZE']>=lim_low)]
    long_temp = w1['LONGITUDE']
    lat_temp = w1['LATITUDE']

    scat = map.scatter(long_temp, lat_temp, s=10)
    scat.set_color('gold')
    scat.set_alpha(1)
    scat.set_zorder(10)

    ## Small fires
    lim_low = 5000
    lim_high = 10000
    w1 = wildfire_data.loc\
        [(wildfire_data['FIRE_SIZE']<lim_high) & (wildfire_data['FIRE_SIZE']>=lim_low)]
    long_temp = w1['LONGITUDE']
    lat_temp = w1['LATITUDE']

    scat = map.scatter(long_temp, lat_temp, s=10)
    scat.set_color('yellow')
    scat.set_alpha(0.75)
    scat.set_zorder(9)

    plt.show()

    return scat
    lon = DS['lon'][:]
    lat = DS['lat'][:]
    time = DS['time'][:]
    area = DS['area'][:] / (1e5)

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


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

    plt.title(out_str)

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

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

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

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

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

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

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

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

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

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

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

    nc_fid.close()

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

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

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

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

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

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

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

    X *= sat_h
    Y *= sat_h

    vmin = 0.0
    vmax = 1200.0

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

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

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

    rincon_de_artigas_poly(ax)

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

    print("Calculando GHI...")

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

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

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

    GHI = FR2GHI_vect(lats, lons, data)

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

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

    plt.clim(vmin, vmax)

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

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

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

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

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

    x_coord = 109
    y_coord = -53

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

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

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

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

    # WHITE

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

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

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

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

    print("NUBOSIDAD")
    # NUBOSIDAD

    plt.clf()

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

    rincon_de_artigas_poly(ax)

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

    vmin = 0.0
    vmax = 100.0

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

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

    plt.clim(vmin, vmax)

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

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

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

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

    x_coord = 109
    y_coord = -53

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

    # CLOUD WHITE

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

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

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

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

    plt.close()
Example #47
0
canvas = FigureCanvas(fig)
ax = fig.add_axes((0, 0, 1, 1),frameon=True)
#fig.set_size_inches((8/m.aspect, 8.))

# Basemap
m = Basemap(llcrnrlon=0, \
            llcrnrlat=-90, \
            urcrnrlon=360, \
            urcrnrlat=90, \
            resolution= 'l', \
            projection = 'cyl', \
            lon_0 = 4.9, \
            lat_0 = 45.1, \
            suppress_ticks= True, \
            ax = ax)
            



# data
lats = [41.38, 43.18, 48.87, 43.60, 46.52, 43.28, 46.20]
lons = [ 2.18,  3.00,  2.32,  1.43,  6.63,  5.37,  6.15]
name = ['Barcelona', 'Narbonne', 'Paris', 'Toulouse', 'Lausanne', 'Marseille', 'Geneva']

#draw and save
m.drawcoastlines(color='gray')
m.drawcountries(color='gray')
m.fillcontinents(color='beige')
x, y = m(lons, lats)
m.plot(x, y, 'bo')
canvas.print_figure('map.png', dpi=100)
Example #48
0
plt.figure(figsize=(10, 6))

xlim = np.array([-97, -94])
ylim = np.array([29, 30.5])

m = Basemap(projection='cyl',
            lon_0=np.mean(xlim),
            lat_0=np.mean(ylim),
            llcrnrlat=ylim[0],
            urcrnrlat=ylim[1],
            llcrnrlon=xlim[0],
            urcrnrlon=xlim[1],
            resolution='i')
m.drawcoastlines()
m.drawstates(), m.drawcountries()
cs = m.contourf(lon2,
                lat2,
                zhmean[3, :, :].T,
                clevs,
                cmap=zhcolor,
                extend='both')
cs2 = m.contour(lonhou.T,
                lathou.T,
                sig_rotation[:, :, 3],
                colors='k',
                linewidths=1.5)

m.drawcounties()
cbar = m.colorbar(cs, size='2%')
cbar.ax.set_ylabel('dBZ', weight='bold', name='Calibri', size=14)
Example #49
0
    def province_distribution(self):
        # 导入sql,获取每个省的购买量
        per_province_sql = 'SELECT province,COUNT(id) num FROM user_action WHERE behavior_type = \'4\' GROUP BY province'
        per_province = pd.read_sql(per_province_sql, self.hadoopguide_connect)

        plt.figure(figsize=(16, 8))  # 定义地图大小
        plt.title('China province consumption amount distribution')
        # 设定中国的经纬度,不设置则是世界地图
        map = Basemap(llcrnrlon=77,
                      llcrnrlat=14,
                      urcrnrlon=140,
                      urcrnrlat=51,
                      projection='lcc',
                      lat_1=33,
                      lat_2=45,
                      lon_0=100)
        map.drawcountries(linewidth=1.25)  # 描绘国界线
        map.drawcoastlines()  # 描绘大陆板块线

        # 导入行政区划包,下载后放入resources文件夹中
        # 31个省、直辖市、自治区
        map.readshapefile('resources/gadm36_CHN_shp/gadm36_CHN_1',
                          'states',
                          drawbounds=True)
        # 香港特别行政区
        map.readshapefile('resources/gadm36_HKG_shp/gadm36_HKG_0',
                          'hongkong',
                          drawbounds=True)
        # 澳门特别行政区
        map.readshapefile('resources/gadm36_MAC_shp/gadm36_MAC_0',
                          'macao',
                          drawbounds=True)
        # 台湾省
        map.readshapefile('resources/gadm36_TWN_shp/gadm36_TWN_0',
                          'taiwan',
                          drawbounds=True)

        # 渲染 获取红黄色调
        cmap = plt.cm.YlOrRd

        colors = {}  #给每个省保存颜色rbg的字典
        statenames = []  #省列表

        # 先遍历31个省、直辖市、自治区
        for shapedict in map.states_info:
            # 获取省的中文名
            statename = shapedict['NL_NAME_1']
            p = statename.split('|')
            if len(p) > 1:
                s = p[1]
            else:
                s = p[0]
            # 将省的中文名解析为数据库中使用的省名
            s = self.parse_province(s)
            statenames.append(s)
            # 找到该省对应的购买量
            value = per_province[per_province.province == s].num
            # 通过cmap函数将购买量转换为RGB值
            colors[s] = cmap(value)[:3]

        # 获取坐标轴 gca: Get Current Axes
        axis = plt.gca()

        # 再遍历每个省
        for nshape, seg in enumerate(map.states):
            # statenames[nshape]可以得到省名,根据省名获取字典colors中的rgb值,获得对应的color
            color = rgb2hex(colors[statenames[nshape]][0])
            poly = Polygon(seg, facecolor=color, edgecolor=color)
            axis.add_patch(poly)

        plt.show()
Example #50
0
def contourMap(grdROMS, tlon, tlat, mydata, depthlevel, var):
    map = Basemap(projection='ortho',
                  lon_0=-20,
                  lat_0=25,
                  resolution='c',
                  area_thresh=10000)
    levels = np.arange(-2.0, 30.0, 0.5)

    plt.figure(figsize=(10, 10), frameon=False)
    #mydata = np.ma.masked_where(mydata==grdROMS.fill_value,mydata)

    if grdROMS.grdName == 'GOM':
        # Plot the Georges Bank region
        map = Basemap(llcrnrlon=-78.5,
                      llcrnrlat=32.5,
                      urcrnrlon=-58,
                      urcrnrlat=45.5,
                      resolution='i',
                      projection='tmerc',
                      lon_0=-70,
                      lat_0=0,
                      area_thresh=10.)
        levels = np.arange(0.0, 26.0, 0.5)

    if grdROMS.grdName == 'Nordic' or grdROMS.grdName == 'Nordic2':
        map = Basemap(lon_0=25,
                      boundinglat=50,
                      resolution='l',
                      area_thresh=100.,
                      projection='npstere')
        levels = np.arange(-2.0, 20.0, 0.1)

    if grdROMS.grdName == 'Troms':
        map = Basemap(projection='merc',llcrnrlat=68,urcrnrlat=72,\
            llcrnrlon=15,urcrnrlon=24,lat_ts=70,resolution='h',area_thresh=0.)
        levels = np.arange(-2.0, 8.0, 0.25)

    if grdROMS.grdName == 'NS8KM':
        map = Basemap(llcrnrlon=-18.5,
                      llcrnrlat=43.5,
                      urcrnrlon=32.5,
                      urcrnrlat=67.7,
                      resolution='i',
                      projection='tmerc',
                      lon_0=0,
                      lat_0=50,
                      area_thresh=20.)
        levels = np.arange(-2.0, 20.0, 0.5)

    if grdROMS.grdName == 'KINO':
        print "KINO"
        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.)
        levels = np.arange(-2.0, 20.0, 0.5)

    if grdROMS.grdName == 'NA':
        map = Basemap(lon_0=25,
                      boundinglat=0,
                      resolution='l',
                      area_thresh=2000.,
                      projection='npstere')
        levels = np.arange(-2.0, 25.0, 0.5)

    if grdROMS.grdName == 'NATL':
        map = Basemap(lon_0=2,
                      boundinglat=0,
                      resolution='l',
                      area_thresh=2000.,
                      projection='npstere')
        levels = np.arange(-2.0, 30.0, 0.5)

    if grdROMS.grdName == 'REGSCEN':
        #  map = Basemap(projection='ortho',lon_0=-20,lat_0=25, resolution='c', area_thresh=10000)
        map = Basemap(llcrnrlon=-50,
                      llcrnrlat=54,
                      urcrnrlon=1,
                      urcrnrlat=78,
                      resolution='i',
                      projection='tmerc',
                      lon_0=-25,
                      lat_0=60,
                      area_thresh=200.)

        levels = np.arange(-2.0, 30.0, 0.5)

    if grdROMS.grdName == 'GREENLAND':
        map = Basemap(llcrnrlon=-50,
                      llcrnrlat=54,
                      urcrnrlon=1,
                      urcrnrlat=78,
                      resolution='i',
                      projection='tmerc',
                      lon_0=-25,
                      lat_0=60,
                      area_thresh=200.)
        levels = np.arange(-2.0, 20.0, 0.5)

    x, y = map(tlon, tlat)

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

    if var == 'temperature':
        levels = np.arange(-2.0, 36.0, 1)
    if var == 'salinity':
        levels = np.arange(25.0, 40.0, 0.3)
    if var == 'runoff':
        levels = np.arange(1e-4, 1e-8, 1e-10)
    if var == 'ssh':
        levels = np.arange(-1.5, 1.5, 0.1)
    if var in ['uvel', 'vvel', 'urot', 'vrot', 'ubar', 'vbar']:
        levels = np.arange(-1.0, 1.0, 0.1)
    if var == 'sodamask':
        levels = np.arange(0, 1, 1)
    if var == 'hice':
        levels = np.arange(0, 100, 0.1)
    if var == 'aice':
        levels = np.arange(0, 100, 5)
    if var == 'uice' or var == "vice":
        levels = np.arange(-100, 100, 5)
    if var == 'ageice':
        levels = np.arange(0, 12, 1)
    if var == 'snow_thick':
        levels = np.arange(0, 2, 0.1)
    if var == 'runoff':
        CS1 = map.contourf(x, y, mydata)  #,alpha=0.5)
        plt.colorbar(orientation='horizontal')
    else:
        CS1 = map.contourf(x,
                           y,
                           mydata,
                           levels,
                           cmap=cm.get_cmap('RdYlBu_r',
                                            len(levels) - 1))  #,alpha=0.5)
        plt.colorbar(CS1, orientation='vertical', extend='both', shrink=0.5)

    plt.title('Var:%s - depth:%s - time:%s' % (var, depthlevel, grdROMS.time))
    plotfile = 'figures/' + str(var) + '_depth_ESMF_' + str(
        depthlevel) + '_time_' + str(grdROMS.time) + '.png'
    if not os.path.exists('figures'):
        os.makedirs('figure')
    plt.savefig(plotfile)
    print "Saved figure: %s" % (plotfile)
    plt.show()
Example #51
0
m = Basemap(projection = 'mill') # Miller cylindrical projection
m.drawcoastlines()
m.fillcontinents()
plt.title('Basemap Tutorial')
plt.show()

#------------------Basemap customization options-----------------
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
m = Basemap(projection='mill',
            llcrnrlat = -90, # latitude: like y’s value; llcrnr: lower left corner
            llcrnrlon = -180, # longitude: like x’s value
            urcrnrlat = 90, # urcrnr: upper right corner
            urcrnrlon = 180)
m.drawcoastlines()
m.drawcountries(linewidth=2)
m.drawstates(color='b') # draw states in each countries
m.drawcounties(color='darkred') # draw counties in each countries
m.etopo() # display topography
plt.title('Basemap Tutorial')
plt.show()

#---------------------Plotting coordinates on a map with Basemap ---------------
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
m = Basemap(projection='mill', # Cover US map
            llcrnrlat = 25,
            llcrnrlon = -130,
            urcrnrlat = 50,
            urcrnrlon = -60,
            resolution='l')
Example #52
0
    def plot_map(self, var1d, lats, lons, sites, plot_name, title, yr):

        from matplotlib.font_manager import FontProperties

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

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

        # --- limits
        map_lims = self.map_lims

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

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

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

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

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

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

        # --- save to plot
        a_saveplot.save_plot(plot_name, ext="png", close=True, verbose=False)
        plt.show()
Example #53
0
def plot_species_distribution(species=("bradypus_variegatus_0",
                                       "microryzomys_minutus_0")):
    """
    Plot the species distribution.
    """
    if len(species) > 2:
        print("Note: when more than two species are provided,"
              " only the first two will be used")

    t0 = time()

    # Load the compressed data
    data = fetch_species_distributions()

    # Set up the data grid
    xgrid, ygrid = construct_grids(data)

    # The grid in x,y coordinates
    X, Y = np.meshgrid(xgrid, ygrid[::-1])

    # create a bunch for each species
    BV_bunch = create_species_bunch(species[0], data.train, data.test,
                                    data.coverages, xgrid, ygrid)
    MM_bunch = create_species_bunch(species[1], data.train, data.test,
                                    data.coverages, xgrid, ygrid)

    # background points (grid coordinates) for evaluation
    np.random.seed(13)
    background_points = np.c_[
        np.random.randint(low=0, high=data.Ny, size=10000),
        np.random.randint(low=0, high=data.Nx, size=10000)].T

    # We'll make use of the fact that coverages[6] has measurements at all
    # land points.  This will help us decide between land and water.
    land_reference = data.coverages[6]

    # Fit, predict, and plot for each species.
    for i, species in enumerate([BV_bunch, MM_bunch]):
        print("_" * 80)
        print("Modeling distribution of species '%s'" % species.name)

        # Standardize features
        mean = species.cov_train.mean(axis=0)
        std = species.cov_train.std(axis=0)
        train_cover_std = (species.cov_train - mean) / std

        # Fit OneClassSVM
        print(" - fit OneClassSVM ... ", end='')
        clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.5)
        clf.fit(train_cover_std)
        print("done.")

        # Plot map of South America
        plt.subplot(1, 2, i + 1)
        if basemap:
            print(" - plot coastlines using basemap")
            m = Basemap(projection='cyl',
                        llcrnrlat=Y.min(),
                        urcrnrlat=Y.max(),
                        llcrnrlon=X.min(),
                        urcrnrlon=X.max(),
                        resolution='c')
            m.drawcoastlines()
            m.drawcountries()
        else:
            print(" - plot coastlines from coverage")
            plt.contour(X,
                        Y,
                        land_reference,
                        levels=[-9999],
                        colors="k",
                        linestyles="solid")
            plt.xticks([])
            plt.yticks([])

        print(" - predict species distribution")

        # Predict species distribution using the training data
        Z = np.ones((data.Ny, data.Nx), dtype=np.float64)

        # We'll predict only for the land points.
        idx = np.where(land_reference > -9999)
        coverages_land = data.coverages[:, idx[0], idx[1]].T

        pred = clf.decision_function((coverages_land - mean) / std)[:, 0]
        Z *= pred.min()
        Z[idx[0], idx[1]] = pred

        levels = np.linspace(Z.min(), Z.max(), 25)
        Z[land_reference == -9999] = -9999

        # plot contours of the prediction
        plt.contourf(X, Y, Z, levels=levels, cmap=plt.cm.Reds)
        plt.colorbar(format='%.2f')

        # scatter training/testing points
        plt.scatter(species.pts_train['dd long'],
                    species.pts_train['dd lat'],
                    s=2**2,
                    c='black',
                    marker='^',
                    label='train')
        plt.scatter(species.pts_test['dd long'],
                    species.pts_test['dd lat'],
                    s=2**2,
                    c='black',
                    marker='x',
                    label='test')
        plt.legend()
        plt.title(species.name)
        plt.axis('equal')

        # Compute AUC with regards to background points
        pred_background = Z[background_points[0], background_points[1]]
        pred_test = clf.decision_function((species.cov_test - mean) / std)[:,
                                                                           0]
        scores = np.r_[pred_test, pred_background]
        y = np.r_[np.ones(pred_test.shape), np.zeros(pred_background.shape)]
        fpr, tpr, thresholds = metrics.roc_curve(y, scores)
        roc_auc = metrics.auc(fpr, tpr)
        plt.text(-35, -70, "AUC: %.3f" % roc_auc, ha="right")
        print("\n Area under the ROC curve : %f" % roc_auc)

    print("\ntime elapsed: %.2fs" % (time() - t0))
Example #54
0
m.drawparallels(circles, labels=[0, 1, 0, 0])
# draw meridians
meridians = np.arange(-180, 180, 30)
m.drawmeridians(meridians, labels=[1, 1, 0, 1])
plt.title('Great Circle from New York to London (Gnomonic)')
sys.stdout.write('plotting Great Circle from New York to London (Gnomonic)\n')

fig = plt.figure()

# Example of Great Circles which exit and reenter the map
m = Basemap(projection='robin', lat_0=0, lon_0=0, resolution='c')

m.drawmapboundary(fill_color='#ffffff', color='#ffffff')
m.fillcontinents(color='#f2f2f2', lake_color='#ffffff')
m.drawcoastlines(color='#e0e0e0')
m.drawcountries(color='#e0e0e0')

parallels = np.arange(-90, 90, 10.)
meridians = np.arange(10., 351., 20.)
m.drawparallels(parallels,
                labels=[False, False, False, False],
                color='#d3d3d3',
                dashes=[1, 3])
m.drawmeridians(meridians,
                labels=[False, False, False, False],
                color='#d3d3d3',
                dashes=[1, 3])

# Choose the lat and longtitude of two points

p1 = (45.27, -75.42)  # roughly Ottawa
Example #55
0
with open(filename) as f:
    reader = csv.reader(f)

    next(reader)

    for row in reader:
        lats.append(float(row[3]))
        lons.append(float(row[4]))
        magnitudes.append(float(row[5]))

# Display the first 5 lats and lons
print('lats', lats[0:5])
print('lons', lons[0:5])

eq_map.drawcoastlines()
eq_map.drawcountries()
eq_map.drawmapboundary()
eq_map.fillcontinents(color='gray')
eq_map.drawmeridians(np.arange(0, 360, 30))
eq_map.drawparallels(np.arange(-90, 90, 30))

x, y = eq_map(lons, lats)


def get_marker_color(magnitude):
    # Returns green for small earthquakes, yellow for moderate
    #  earthquakes, and red for significant earthquakes.
    if magnitude < 5.0:
        return ('go')
    elif magnitude < 6.0:
        return ('yo')
Example #56
0
ext = [-82.0, 36.2, -66.5, 48]
orig_lat = 42.
orig_lon = -77.

fig = plt.figure(figsize=(12, 9))
bmap = Basemap(epsg=4326,
               llcrnrlon=ext[0],
               llcrnrlat=ext[1],
               urcrnrlon=ext[2],
               urcrnrlat=ext[3],
               lat_0=orig_lat,
               lon_0=orig_lon,
               resolution='i')

bmap.drawcoastlines()
bmap.drawcountries()
bmap.drawstates()
bmap.shadedrelief()
#Lat/Lon Lines
#bmap.drawparallels(np.arange(35,50,.5),labels=[1,0,0,0])
#bmap.drawmeridians(np.arange(-90,-65,5),labels=[0,0,0,1])

#########################################################################
######################           PATHS           ########################
#########################################################################

#Directory of CSV directories ie dates as directories containing CSV data from that date
csv_dir = '/home/disk/funnel/impacts/data_archive/asos'

#Date of interest
date_of_interest = '20200122'
Example #57
0
        ax.add_patch(patch)

    m1=Basemap(
        projection='merc',
        llcrnrlat=-80,
        urcrnrlat=80,
        llcrnrlon=-180,
        urcrnrlon=180,
        #lat_ts=20,
        resolution='c',
        fix_aspect=False,
        ax=ax10,
        )
    plot_density(m1)
    m1.drawcoastlines(linewidth=0.25)#,zorder=-1)
    m1.drawcountries(linewidth=0.1)#,zorder=-1)
    #m.drawcoastlines()
    #m.fillcontinents(color='gray',lake_color='white')

    m2=Basemap(
        projection='merc',
        #llcrnrlat=input['gps_'][0]-7,
        #urcrnrlat=input['gps_'][0]+13,
        #llcrnrlon=input['gps_'][1]-10,
        #urcrnrlon=input['gps_'][1]+10,
        llcrnrlat=input['gps_'][0]-3,
        urcrnrlat=input['gps_'][0]+6,
        llcrnrlon=input['gps_'][1]-5,
        urcrnrlon=input['gps_'][1]+5,
        fix_aspect=False,
        #lat_0=input['gps_'][0],
		lon1=20
		lon2=110
	
		#track errors
	
		if error_type == 'track':

			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')


			#m.fillcontinents(color='white')
			m.drawcoastlines(linewidth=0.4, color='k')
			m.drawcountries(linewidth=0.4, color='k')
					
			cmap = 'OrRd'
			cmap = plt.get_cmap(cmap)
			colors = cmap(np.linspace(0.1, 1, cmap.N))

			cmap2 = LinearSegmentedColormap.from_list(cmap, colors)

			bounds=np.linspace(0,2000,21)
			norm = BoundaryNorm(bounds, ncolors=cmap2.N, clip=True)



			x,y = m(obs_lons_mjo, obs_lats_mjo)

			im = m.contourf(x,y,track_error_mjo, cmap=cmap2, levels=bounds, tri=True, extend="max")
Example #59
0
def drawPlot(gridSize, z_rh, extent):
    print "basemap_working..."
    alists = []

    gridSizeX = gridSize
    gridSizeY = gridSizeX * (extent[3] - extent[2]) / (extent[1] - extent[0])
    intervalX = (float)(extent[1] - extent[0]) / gridSizeX
    intervalY = (float)(extent[3] - extent[2]) / gridSizeY
    gridx = np.arange(extent[0], extent[1], intervalX)
    gridy = np.arange(extent[2], extent[3], intervalY)

    for lonnum in range(0, gridx.size):
        for latnum in range(0, gridy.size):
            list0 = list([gridx[lonnum], gridy[latnum], z_rh[latnum][lonnum]])
            latnum = latnum + 1
            alists.append(list0)
        lonnum = lonnum + 1
    df1 = pd.DataFrame(alists, columns=('1', '2', '3'))
    # 用来正常显示中文
    plt.rcParams['font.sans-serif'] = ['SimHei']
    # 用来正常显示负号
    plt.rcParams['axes.unicode_minus'] = True
    # 剔除无效值NAN
    df1 = df1.dropna(axis=0, how='any')
    #获取经纬度
    lat = np.array(df1["2"][:])
    lon = np.array(df1["1"][:])
    rhvalue = np.array(df1["3"][:], dtype=float)
    # 画图
    fig = plt.figure(figsize=(16, 9))
    plt.rc('font', size=15, weight='bold')
    ax = fig.add_subplot(111)
    # 添加标题
    # plt.title(hour[0:4]+u'年'+hour[4:6]+u'月'+hour[6:8]+u'日'+hour[8:10]+u'时'+u'中国AQI分布', size=25, weight='bold')
    # 创建底图,等经纬度投影
    mp = Basemap(llcrnrlon=extent[0],
                 llcrnrlat=extent[2],
                 urcrnrlon=extent[1],
                 urcrnrlat=extent[3],
                 projection='cyl',
                 resolution='h')
    # 添加海岸线
    mp.drawcoastlines()
    # 添加国家行政边界
    mp.drawcountries()
    # 读取中国行政区边界
    mp.readshapefile('../data/gadm36_CHN_shp/gadm36_CHN_1',
                     'states',
                     drawbounds=True)
    # 设置colorbar中颜色间隔个数
    ##levels = np.linspace(np.min(rhvalue), np.max(rhvalue), 20)
    # levels = np.linspace(0, np.min(rhvalue), np.max(rhvalue),endpoint=False, retstep=False, dtype=None)
    # 设置颜色表示数值大小
    cf = mp.scatter(lon, lat, rhvalue, c=rhvalue, cmap='jet',
                    alpha=1)  #alpha=0.75
    # 设置上下标以及单位的希腊字母
    cbar = mp.colorbar(cf,
                       location='right',
                       format='%d',
                       size=0.3,
                       ticks=np.linspace(0,
                                         np.min(rhvalue),
                                         np.max(rhvalue),
                                         endpoint=False,
                                         retstep=False,
                                         dtype=None))  #,label='AQI'
    #ticks=np.linspace(np.min(rhvalue), np.max(rhvalue), 10),
    #label='$\mathrm{PM}_{2.5}$($\mu$g/$\mathrm{m}^{3}$)'
    # plt.savefig('Hour_map_'+hour+'_AQI.png')
    plt.show()
    print "OK."
Example #60
0
#==============================================================================
# para filtrar por una posicion especifica dada arriba con CIRCULO
#==============================================================================

plt.close('all')
fig, ax = plt.subplots(num=6, figsize=(10, 6))
m = Basemap(projection='cyl',llcrnrlat=yi,urcrnrlat=yf,\
            llcrnrlon=xi,urcrnrlon=xf,resolution='l')
#m.fillcontinents(color='0.0')
#m.fillcontinents(color=[0.2980,0.6392,0.0000])
#m.fillcontinents(color=[0.4000,0.6039,0.1960],lake_color=[0.3215,0.5215,0.7176])
#m.drawmapboundary(fill_color='w')
#m.drawmapboundary(fill_color=[0.3215,0.5215,0.7176])
m.bluemarble()
m.drawcoastlines(linewidth=0.25, color='0.1')
m.drawcountries(linewidth=0.25, color='0.1')
parallels = np.arange(yi, yf + 0.1, 5)
m.drawparallels(parallels,
                labels=[1, 0, 0, 0],
                linewidth=0.1,
                fontsize=8,
                color='0.5')
meridians = np.arange(xi, xf + 0.1, 5)
m.drawmeridians(meridians,
                labels=[0, 0, 0, 1],
                linewidth=0.1,
                fontsize=8,
                color='0.5')

if opcion == 1:
    pos = Point(posx, posy).buffer(dl)