Beispiel #1
0
def basemap_plot_paths(filename):
	m = Basemap(projection='merc', resolution='i', **map_bounds['europe'])

	fig = plt.figure()
	ax = Axes3D(fig)

	ax.add_collection3d(m.drawcoastlines(linewidth=0.25))
	ax.add_collection3d(m.drawcountries(linewidth=0.35))

	collection = py1090.FlightCollection()

	#with py1090.Connection() as connection:
	with open(filename, 'r') as connection:
		collection.add_list(connection)

	for flight in collection:
		if flight.hexident in blacklist_hexidents:
			continue

		path = list(flight.path)
		if len(path) > 1:
			lats, lons, alts = np.array(path).T
			x, y = m(lons, lats)
			m.plot(x,y, alts,".-")

	plt.title("Flights in file '{:s}'".format(filename))
	plt.show()
Beispiel #2
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()
Beispiel #3
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
Beispiel #4
0
def lambert_conformal(request):
    import matplotlib
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    width = float(request.GET.get('width', 6000000))
    height = float(request.GET.get('height', 4500000))
    lat = float(request.GET.get('lat',-7))
    lon = float(request.GET.get('lon',107))
    true_lat1 = float(request.GET.get('true_lat1',5))
    true_lat2 = float(request.GET.get('true_lat2',5))
    
    m = Basemap(width=width,height=height,
            rsphere=(6378137.00,6356752.3142),\
            resolution=None,projection='lcc',\
            lat_1=true_lat1,lat_2=true_lat2,lat_0=lat,lon_0=lon)
    
    fig = Figure()
    canvas = FigureCanvas(fig)
    m.ax = fig.add_axes([0, 0, 1, 1])
    
    m.drawlsmask(land_color='gray',ocean_color='white',lakes=True)
    m.drawparallels(np.arange(-90.,91.,30.), color='black')
    m.drawmeridians(np.arange(-180.,181.,60.), color='black')
    
    x, y = m(lon, lat)
    m.plot(x, y, 'ro')
    
    response = HttpResponse(content_type='image/png')
    canvas.print_figure(response, dpi=100)
    return response
Beispiel #5
0
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()
Beispiel #6
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 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 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()
Beispiel #9
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()    
Beispiel #10
0
def get_catalog_map(lats=None, lons=None, eq_cat=[], map_res='i', map_projection='cyl', fignum=0, ax=None, do_clf=True):
	#
	if lats==None: lats = [31., 42.]
	if lons==None: lons = [-125., -114.]
	#
	if fignum!=None: plt.figure(fignum)
	if do_clf: plt.clf()
	if ax==None: ax=plt.gca()
	#
	cm = Basemap(llcrnrlon=lons[0], llcrnrlat=lats[0], urcrnrlon=lons[1], urcrnrlat=lats[1], resolution=map_res, projection=map_projection, lon_0=numpy.mean(lons), lat_0=numpy.mean(lats), ax=ax)
	cm.drawcoastlines(color='gray', zorder=1)
	cm.drawcountries(color='gray', zorder=1)
	cm.drawstates(color='gray', zorder=1)
	cm.drawrivers(color='gray', zorder=1)
	cm.fillcontinents(color='beige', zorder=0)
	# drawlsmask(land_color='0.8', ocean_color='w', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=True, resolution='l', grid=5, **kwargs)
	#cm.drawlsmask(land_color='0.8', ocean_color='c', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=True, resolution=mapres, grid=5)

	print("lat, lon ranges: ", lats, lons)
	cm.drawmeridians(list(range(int(lons[0]), int(lons[1]))), color='k', labels=[0,0,1,1])
	cm.drawparallels(list(range(int(lats[0]), int(lats[1]))), color='k', labels=[1, 1, 0, 0])
	#
	if eq_cat!=None:
		# can we also assign sizes dynamically, like colors?
		if hasattr(eq_cat, 'dtype'):
			# it's a recrray:
			X,Y = cm(eq_cat['lon'], eq_cat['lat'])
		else:
			# it's probably a list... though we should check for dicts, etc.
			X,Y = cm([rw[2] for rw in eq_cat], [rw[1] for rw in eq_cat])
		#
		cm.plot(X,Y, '.')
				
	#
	return cm
Beispiel #11
0
class Mapper:
    def __init__(self, state):
        with open(state_boundries_file_loc) as f:
            for line in f:
                line = line.rstrip().split(',')
                if line[0].lower() == state.lower():
                    ur_lon, ll_lat = float(line[1]), float(line[3])
                    ll_lon, ur_lat = float(line[2]), float(line[4])
                    center_lon = ll_lon + ur_lon
                    if math.copysign(1, ll_lon) != math.copysign(1, ur_lon):
                        center_lon = -180 + center_lon
                    else:
                        center_lon = center_lon / 2
                    center_lat = (ll_lat + ur_lat) / 2

                    self.m = Basemap(llcrnrlon = ll_lon, llcrnrlat = ll_lat,
                                urcrnrlon = ur_lon, urcrnrlat = ur_lat,
                                projection = 'lcc', lat_1 = center_lat,
                                lon_0 = center_lon)
    def setBorders(self):
        self.m.readshapefile(states_shapefile_loc,
                            'states', drawbounds = True)

    def plotPoint(self, lat, lon):
        self.m.plot(lat, lon, latlon=True, marker='o', color='m')

    def displayMap(self):
        plt.show()
def plot_region_pnw(data,lat_coord,lon_coord,lat_nw,lat_se,lon_nw,lon_se,region_name):
	plt.clf()
	circles=[30,40,50,60,70]
	meridians=[-130,-120,-110]
	ny,nx=lat_coord.shape
	m = Basemap(projection='stere',lon_0=lon_coord[ny/2,nx/2],lat_0=lat_coord[ny/2,nx/2],resolution='l',llcrnrlon=lon_coord[-1,0],llcrnrlat=lat_coord[-1,0],urcrnrlon=lon_coord[0,-1],urcrnrlat=lat_coord[0,-1])
	x,y=m(lon_coord[:],lat_coord[:])
	
#	shp_info = m.readshapefile('../st99_d00','states',drawbounds=False)
#	print shp_info
#	for i,shapedict in enumerate(m.states_info):
#		if shapedict['NAME']=='California': break
#	calif=np.array(m.states[i])
# TODO rasterise this to turn into a mask
	
#	plt.title('Plotting data for region: '+region_name)
	try:
		y=m.pcolor(x[lat_nw:lat_se,lon_nw:lon_se],y[lat_nw:lat_se,lon_nw:lon_se],data[lat_nw:lat_se,lon_nw:lon_se],vmin=0.5,vmax=30,alpha=0.5,edgecolors=None)
		y.set_cmap('YlGnBu')
		y.cmap.set_under('w',alpha=1.0)
		plt.colorbar()
	except:
		raise
		m.plot(x[lat_nw:lat_se,lon_nw:lon_se],y[lat_nw:lat_se,lon_nw:lon_se],'r.') # Just put a dot at the x y point
	m.drawcoastlines()
	m.drawcountries()
	y=m.drawstates()
	m.drawparallels(circles)
	m.drawmeridians(meridians)
	try:
		os.remove('pnw_movie/._'+region_name+'.png')
	except:
		pass
	plt.savefig('pnw_movie/'+region_name+'.png')
Beispiel #13
0
def main():
    data = numpy.genfromtxt("data.csv", dtype=None, delimiter=',', names=True)
#lat - data[x][1]
#lon - data[x][2]
    print(data)

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

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

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

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

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

    plt.savefig('map.png', bbox_inches='tight')
Beispiel #14
0
def plot_annotaiton_gps(X_Data):
    """ Plots gps coordinates on a map projection """
    from mpl_toolkits.basemap import Basemap
    #lat = X_data[1:5, 1]
    #lon = X_data[1:5, 2]
    lat = X_data[:, 1]
    lon = X_data[:, 2]
    fig = df2.figure(fnum=1, doclf=True, docla=True)
    df2.close_figure(fig)
    fig = df2.figure(fnum=1, doclf=True, docla=True)
    # setup Lambert Conformal basemap.
    m = Basemap(llcrnrlon=lon.min(),
                urcrnrlon=lon.max(),
                llcrnrlat=lat.min(),
                urcrnrlat=lat.max(),
                projection='cea',
                resolution='h')
    # draw coastlines.
    #m.drawcoastlines()
    #m.drawstates()
    # draw a boundary around the map, fill the background.
    # this background will end up being the ocean color, since
    # the continents will be drawn on top.
    #m.bluemarble()
    m.drawmapboundary(fill_color='aqua')
    m.fillcontinents(color='coral', lake_color='aqua')
    # Convert GPS to projected coordinates
    x1, y1 = m(lon, lat)  # convert to meters # lon==X, lat==Y
    m.plot(x1, y1, 'o')
    fig.show()
Beispiel #15
0
class Map:
    def __init__(self, boundary=[[24.527135, -127.792969], [49.61071, -59.765625]], default=True):
        from mpl_toolkits.basemap import Basemap

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

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

    def plotPoints(self, longitude, latitudes, color, lw=0, marker="o", *args, **kwargs):
        mlon, mlat = self.m(longitude, latitudes)
        self.m.plot(mlon, mlat, color=color, lw=lw, marker=marker, *args, **kwargs)
Beispiel #16
0
def draw_marker_on_map(lat, lon, fname, fmt='png', location_name=' ', gridshape=(1, 1)):
    '''
    Purpose::
        Draw a marker on a map

    Input::
        lat - latitude for plotting a marker
        lon - longitude for plotting a marker
        fname  - a string specifying the filename of the plot
    '''
    fig = plt.figure()
    fig.dpi = 300
    ax = fig.add_subplot(111)

    m = Basemap(projection='cyl', resolution='c', llcrnrlat=lat -
                30, urcrnrlat=lat + 30, llcrnrlon=lon - 60, urcrnrlon=lon + 60)
    m.drawcoastlines(linewidth=1)
    m.drawcountries(linewidth=1)
    m.drawmapboundary(fill_color='aqua')
    m.fillcontinents(color='coral', lake_color='aqua')
    m.ax = ax

    xpt, ypt = m(lon, lat)
    m.plot(xpt, ypt, 'bo')  # plot a blue dot there
    # put some text next to the dot, offset a little bit
    # (the offset is in map projection coordinates)
    plt.text(xpt + 0.5, ypt + 1.5, location_name +
             '\n(lon: %5.1f, lat: %3.1f)' % (lon, lat))

    fig.savefig('%s.%s' % (fname, fmt), bbox_inches='tight', dpi=fig.dpi)
    fig.clf()
def plot_quakes(quakes):
    ll_lon, ll_lat, ur_lon, ur_lat = find_left_most(quakes)
    print ll_lon
    print ll_lat
    print ur_lon
    print ur_lat
    m = Basemap(llcrnrlon=ll_lon,llcrnrlat=ll_lat,
                urcrnrlon=ur_lon,urcrnrlat=ur_lat,
                resolution='l',area_thresh=1000.,projection='merc',
                lat_0=62.9540,lon_0=-149.2697)
    m.drawcoastlines()
    m.drawcountries()
    m.fillcontinents(color='coral',lake_color='blue')
    m.drawmapboundary(fill_color='aqua')

    mags = quakes.Mag
    lons = quakes.Lon
    lats = quakes.Lat
    x, y = m(quakes.Lon, quakes.Lat)
    #Documentation from http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.Basemap.plot
    #Additional hints from http://stackoverflow.com/questions/8409095/matplotlib-set-markers-for-individual-points-on-a-line

    for key in x.keys(): #Note that an entry's data in the series share the same key.
        m.plot(x[key], y[key], marker='o', markersize=mags[key]*4, color='b', alpha = 0.5)
        #alpha is transparency
        #color is blue
        #marker size is magnitude * 4
        #marker is circular shaped
    #x, y = m(quakes.Lon, quakes.Lat)
    #m.plot(x, y, 'k.')
    return m
def plot_quakes(years, figsize, quantity):
    
    res = get_plot_res(years)
    
    colors = get_colormap(years)
    
    quakes = get_quakes_subset(years, quantity)
    
    lat_0 = quakes['LAT'].mean()
    lon_0 = quakes['LON'].mean()
    fig = matplotlib.pyplot.figure(figsize=figsize)
    m = Basemap(resolution = res, projection='nsper',
                area_thresh = 1000., satellite_height = 200000,
                lat_0 = lat_0, lon_0 = lon_0)
    m.drawcoastlines()
    m.drawcountries()
    m.drawstates()
    m.fillcontinents(color = 'green', lake_color = 'aqua')
    m.drawmapboundary(fill_color = 'blue')
    x, y = m(quakes.LON, quakes.LAT)
    
    for i in range(0, len(x) - 1):
        color = colors[get_year(quakes[i:i+1])-years[0]]
        m.plot(x[i:i+1], y[i:i+1], color = color, 
               marker = 'o', markersize = (pi*(quakes.MAG[i:i+1]).apply(float)**2), 
               alpha = 0.5)
Beispiel #19
0
def map_rupture(rupture):
    """
    Method for making a simple representation of a Rupture instance.
    This method draws the surface projection of the rupture on a map.

    Args:
        rupture: A Rupture instance.

    """
    rlats = rupture.lats
    rlons = rupture.lons

    minbufx = 0.2
    minbufy = 0.2
    lat1 = np.nanmin(rupture.lats)
    lat2 = np.nanmax(rupture.lats)
    dlat = lat2 - lat1
    bufy = np.max([dlat/2, minbufy])
    lon1 = np.nanmin(rupture.lons)
    lon2 = np.nanmax(rupture.lons)
    dlon = lon2 - lon1
    bufx = np.max([dlon/2, minbufx])
    m = Basemap(llcrnrlat=lat1-bufy,urcrnrlat=lat2+bufy, llcrnrlon=lon1-bufy,urcrnrlon=lon2+bufy)
    m.arcgisimage(service='World_Shaded_Relief', xpixels = 500, verbose= True)
    x, y = m(rlons, rlats)
    m.plot(x, y, 'r')
Beispiel #20
0
	def draw_map(self, graph_name):
		plt.figure(figsize=(50,50));

		#draw background.
		m = Basemap( projection = 'mill',\
		             resolution = 'i',\
		             llcrnrlon = -180.,\
		             llcrnrlat = -90.,\
		             urcrnrlon = 180.,\
		             urcrnrlat = 90.);

		m.drawmapboundary(fill_color='aqua');
		m.fillcontinents(color = 'coral', lake_color= 'aqua');
		m.drawcountries();
		m.drawparallels(np.arange(-90,90,30), labels=[1,1,0,0], linewidth=0.8, color='g');
		m.drawmeridians(np.arange(-180,180,30), labels=[0,0,1,1], linewidth=0.8, color='g');
		
		for i in range(len(self.map_paths)):
			src = self.map_paths[i]["source"];
			tgt = self.map_paths[i]["target"];
			parent_lonlat = (self.map_nodes[src]["lon"], self.map_nodes[src]["lat"]);
			root_lonlat = (self.map_nodes[tgt]["lon"], self.map_nodes[tgt]["lat"]);
			
			x,y = self.get_dots(parent_lonlat, root_lonlat);
			m.plot(x, y, latlon=True, linewidth=0.3, color='r');

		for i in range(len(self.map_nodes)):
			m.plot(self.map_nodes[i]["lon"], self.map_nodes[i]["lat"], latlon=True, marker = 'o', markerfacecolor='red', markersize=1.5);
		
		plt.savefig(graph_name+"_map.png",dpi=300);
Beispiel #21
0
def plotRegion(expertiseRegions, models):
    colors = ["red", "aqua", "blue", "green", "yellow", "magenta", "purple", "grey", "violet", "white"]
    # llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
    # are the lat/lon values of the lower left and upper right corners
    # of the map.
    # lat_ts is the latitude of true scale.
    # resolution = 'c' means use crude resolution coastlines.
    m = Basemap(projection="merc", llcrnrlon=-129, llcrnrlat=27, urcrnrlon=-60, urcrnrlat=50, lat_ts=20, resolution="c")
    m.drawcoastlines()
    m.fillcontinents(color="coral", lake_color="aqua")
    # draw parallels and meridians.
    m.drawstates()
    lon = -125.3318
    lat = 37.0799
    x, y = m(lon, lat)
    index = 0
    for region in expertiseRegions:
        lats = [region._leftTop[0], region._rightBottom[0], region._rightBottom[0], region._leftTop[0]]
        lons = [region._leftTop[1], region._leftTop[1], region._rightBottom[1], region._rightBottom[1]]
        draw_screen_poly(lats, lons, m, color=colors[index])

    for model in models:
        x = model["center"][0]
        y = model["center"][1]
        m.plot(x, y, "bo", markersize=10)
    m.drawmapboundary(fill_color="aqua")
    plt.title("Expert Regions")
    plt.savefig("region.png")
    plt.clf()
Beispiel #22
0
    def __init__(self, subPlot = None, gpxData = None):
        GeoSectionViewerGpxData.__init__(self, subPlot, gpxData)

        latitudes, longitudes, elevations, timestamps = self.gpxData.getLatLongElevTs()

        latitudeMax = max(latitudes)
        latitudeMin = min(latitudes)
        longitudeMax = max(longitudes)
        longitudeMin = min(longitudes)
        elevationMax = max(elevations)
        elevationMin = min(elevations)

        scalledMax = 30
        scalledMin = 1

        scalledElevations = [((((point.elevation - elevationMin) * (scalledMax - scalledMin)) / (elevationMax - elevationMin)) + scalledMin) for i, point in enumerate(self.gpxData)]
        bbox = longitudeMin, latitudeMin, longitudeMax, latitudeMax

        mm = geotiler.Map(extent=bbox, zoom=14)
        img = geotiler.render_map(mm)
        img.save("geotiler.png")

        map = Basemap(
            llcrnrlon=bbox[0], llcrnrlat=bbox[1],
            urcrnrlon=bbox[2], urcrnrlat=bbox[3],
            projection='merc',
            resolution='i',
            ax=self.subPlot)
        map.imshow(img, aspect='auto', origin='upper')
        map.scatter(longitudes, latitudes, c='red', s=scalledElevations, marker='o', cmap=cm.hot_r, alpha=0.4, latlon=True)
        map.plot(longitudes, latitudes, 'k', c='red', latlon=True)
Beispiel #23
0
    def show_route(self):
        '''
        Display the route coordinates on a map of Tompkins County
        '''

        # plot basemap w/ state and county lines, etc
        fig = plt.figure()
        m = Basemap(llcrnrlon=-76.8, llcrnrlat=42.2, urcrnrlon=-76.2, \
            urcrnrlat=42.7, rsphere=(6378137.00,6356752.3142), resolution='l', \
            projection='merc')
        m.shadedrelief()
        m.drawcoastlines()
        m.drawstates()
        m.drawcountries()
        m.drawcounties()

        # plot ny state water features
        m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDFlowline','water', color='LightSteelBlue', linewidth=2.)
        m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDArea','water_area', drawbounds=False)
        m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDWaterbody','lakes', drawbounds=False)
        for lake in m.lakes + m.water_area:
            poly = Polygon(lake, facecolor='LightSteelBlue', edgecolor='CornflowerBlue')
            plt.gca().add_patch(poly)

        # read and plot tompkins county shapefile
        m.readshapefile('data\\parcels\\ParcelPublic2016_WGS84', 'parcels')

        # plot route coordinates
        m.plot(self.coordinates[:,0], self.coordinates[:,1], '.-',
               latlon=True, c='FireBrick', lw=2.)

        # finalize and show plot
        fig.show()
Beispiel #24
0
class MapDrawer:
    
    mymap = None;
    projection = 'hammer';
    
    def __init__(self, projection = 'hammer', lon_0 = 0, resolution = 'c'):
        self.mymap = Basemap(projection, lon_0, resolution);
        self.mymap.bluemarble()
    
    def show_map(self):
        self.mymap.show();
        
    def draw_markers(self, lats, longs, title = '', clever_mode = 0):
        
        # draw parallels and meridians.
        lats = np.array(lats)
        longs = np.array(longs)
        if clever_mode:
            print "Clever mode is under construction" 
        xpt,ypt = self.mymap(longs,lats)
        print xpt;
        self.mymap.plot(xpt, ypt, 'ro')
        if title:
            plt.title('Tweets about ' + title) 
            plt.show()        
        
        #mymap = Basemap(projection = 'hammer', lon_0 = 0, resolution = 'c');
        #xpt,ypt = mymap(longs,lats)
        #mymap.plot(xpt, ypt, 'ro')
Beispiel #25
0
def plot_region_pnw(data,lat_coord,lon_coord,lat_nw,lat_se,lon_nw,lon_se,title,varfrac):
	plt.clf()
	circles=[30,40,50,60,70]
	meridians=[-130,-120,-110]
	ny,nx=lat_coord.shape
	m = Basemap(projection='stere',lon_0=lon_coord[ny/2,nx/2],lat_0=lat_coord[ny/2,nx/2],resolution='l',llcrnrlon=lon_coord[-1,0],llcrnrlat=lat_coord[-1,0],urcrnrlon=lon_coord[0,-1],urcrnrlat=lat_coord[0,-1])
	x,y=m(lon_coord[:],lat_coord[:])
	
	plt.title('Plotting data for: '+title+'\nvariance:'+str(varfrac))
	try:
		max=np.absolute(data[lat_nw:lat_se,lon_nw:lon_se]).max()
		m.pcolor(x[lat_nw:lat_se,lon_nw:lon_se],y[lat_nw:lat_se,lon_nw:lon_se],data[lat_nw:lat_se,lon_nw:lon_se],vmin=-max,vmax=max)
		plt.colorbar()
	except:
		raise
		m.plot(x[lat_nw:lat_se,lon_nw:lon_se],y[lat_nw:lat_se,lon_nw:lon_se],'r.') # Just put a dot at the x y point
	m.drawcoastlines()
	m.drawcountries()
	y=m.drawstates()
	m.drawparallels(circles)
	m.drawmeridians(meridians)
	try:
		os.remove(output_dir+'/._'+title+'.png')
	except:
		pass
	plt.savefig(output_dir+'/'+title+'.png')
def plot_clinic_locations():
	fig = plt.figure(figsize=(20,10))

	# define the map
	m = Basemap(llcrnrlon=-145.5,llcrnrlat=1.,urcrnrlon=-2.566,urcrnrlat=46.352,\
				rsphere=(6378137.00,6356752.3142),\
				resolution='l',area_thresh=1000.,projection='lcc',\
				lat_1=50.,lon_0=-107.)

	# # Draw the coastlines on the map
	m.drawcoastlines()

	# # Draw country borders on the map
	m.drawcountries()

	# Fill the land with grey
	m.fillcontinents(color = '#888888', zorder=0)

	# Draw the map boundaries
	m.drawmapboundary(fill_color='#f4f4f4')

	# Define our longitude and latitude points
	# We have to use .values because of a wierd bug when passing pandas data
	# to basemap.
	#x,y = m(cities['lng'].values, cities['lat'].values)

	# Plot them using round red markers of size 6
	for lat in data.latitude:
		lon = data.longitude[data.latitude==lat].iloc[0]
		x,y = m(lon, lat)
		m.plot(x, y, marker='o', color='r', markersize=6)

	# Show the map
	plt.show()
def map_sites_inset(datasets, data_dir='./data/', focal_sites=[], markers = ['o'],
                    colors=['b', 'r', 'g', 'y', 'c'], markersizes=4):
    """Generate a US map with sites color-coded by database"""
    
    from mpl_toolkits.basemap import Basemap
    
    map = Basemap(projection='merc',llcrnrlat=24.5,urcrnrlat=49,\
                llcrnrlon=-125,urcrnrlon=-69,lat_ts=50,resolution='l')
    
    map.drawcoastlines(linewidth=1.5)
    map.drawcountries(linewidth=1.5)
    map.drawmapboundary()     
    
    for i, dataset in enumerate(datasets):
        latlong_data = import_latlong_data(data_dir + dataset + '_lat_long.csv')
        lats = latlong_data["lat"]
        longs = latlong_data["long"]  
    
        x,y = map(longs,lats)
        map.plot(x,y, ls = '', marker = markers[i], markerfacecolor = colors[i], 
                 markeredgewidth = 0.25, markersize = markersizes)
    if len(focal_sites) > 0:
        focal_x, focal_y = map(focal_sites[1], focal_sites[0])
        map.plot(focal_x, focal_y, ls = '', marker='o', markeredgecolor='k',
                 markerfacecolor='w', markeredgewidth=4, markersize=50)    
    plt.savefig('map_of_sites_US.png', dpi=320, bbox_inches = 'tight', pad_inches=0)
Beispiel #28
0
def plot(mp):
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt

    map = Basemap(projection='mill', llcrnrlon=0,llcrnrlat=-90,urcrnrlon=360,urcrnrlat=90)
    
    map.drawcoastlines(linewidth=0.25)
    
    map.drawmeridians(numpy.arange(0,360,30))
    map.drawparallels(numpy.arange(-90,90,30))

    data = mp.data
    
    lons, lats = map.makegrid(mp.width, mp.height)
    x, y = map(*numpy.meshgrid(mp.longitudes, mp.latitudes))
    #clevs = range(200, 325, 5)
    clevs = list(frange(0, 8, 0.25))
    cs = map.contourf(x, y, data, clevs, cmap=plt.cm.jet)
    
    cbar = map.colorbar(cs, location='bottom', pad="5%")
    cbar.set_label('K')
    
    lon, lat = 174.7772, -41.2889
    xpt,ypt = map(lon,lat)
    map.plot(xpt,ypt,'bo')
    
    plt.title(mp.name)
    plt.gcf().set_size_inches(10,10)
    plt.savefig(mp.name + '.png',dpi=100)
def create_png(url, outfile): 
  quakes = get_earthquake_data('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.csv')
  print(quakes[0].__dict__)

  # Set up Basemap
  mpl.rcParams['figure.figsize'] = '16, 12'
  m = Basemap(projection='kav7', lon_0=-90, resolution = 'l', area_thresh = 1000.0)
  m.drawcoastlines()
  m.drawcountries()
  m.drawmapboundary(fill_color='0.3')
  m.drawparallels(np.arange(-90.,99.,30.))
  junk = m.drawmeridians(np.arange(-180.,180.,60.))

  # sort earthquakes by magnitude so that weaker earthquakes
  # are plotted after (i.e. on top of) stronger ones
  # the stronger quakes have bigger circles, so we'll see both
  start_day = quakes[-1].timestamp[:10]
  end_day = quakes[0].timestamp[:10]
  quakes.sort(key=lambda q: q.magnitude, reverse=True)

  # add earthquake info to the plot
  for q in quakes:
    x,y = m(q.lon, q.lat)
    mcolor, msize = get_marker(q.magnitude)
    m.plot(x, y, mcolor, markersize=msize)

  # add a title
  plt.title("Earthquakes {0} to {1}".format(start_day, end_day))
  plt.savefig(outfile)
Beispiel #30
0
    def visualize(self):
        """
        Visuzalise the edges

        References:
        * http://stackoverflow.com/questions/11603537/plot-multiple-lines-in-python-basemap
        """
        from mpl_toolkits.basemap import Basemap
        import matplotlib.pyplot as plt
        import numpy as np

        m = Basemap(projection='mill', llcrnrlat=self.bounds[0], urcrnrlat=self.bounds[2],
                    llcrnrlon=self.bounds[1], urcrnrlon=self.bounds[3], resolution='c')

        m.drawcoastlines()
        m.drawcountries()
        m.drawstates()
        m.fillcontinents(color='#EEEEEE', lake_color='#FFFFFF')
        m.drawmapboundary(fill_color='#FFFFFF')

        # Plotting segments
        for path in self.get_paths():
            latlngs = np.array(map(lambda node: (node.lat, node.lng), path.get_nodes()))
            x, y = m(latlngs.T[1], latlngs.T[0])
            m.plot(x, y, color="#000000", marker='o', linestyle='-', linewidth=2, alpha=.5)

        plt.title('Segment plotting')
        plt.show()
Beispiel #31
0
def plot_map(data, specs, outputpath):
    '''
    routine plots balloon flight on a map.
    INPUT:
        - data: dictionnary with data (eg filled by read_ncfile())
        - specs: dictionnary with filename specifications
            (filled by read_ncfile())
        - outputpath: path where png will be stored in.
    OUTPUT: .png file stored in outputpath.
    REQUIRES: basemap-data-hires package to be installed.
    '''
    logging.info('now plotting map of sounding.........')
    # define outputname of .png-file:
    variable = 'trajectory'
    outputname = '{platform}_SoundingProfile_{variable}_{date}_{tempres}.png'.format(
        platform=specs['platform_short'],
        instrument=specs['type'].replace(' ', '').replace('_', ''),
        direction=specs['direction'],
        variable=variable,
        date=specs['date'] + '_' + specs['time'],
        tempres=specs['tempres'].replace(' ', ''))

    #fig = plt.figure(figsize=(8, 6))
    fig, ax = plt.subplots(1, figsize=(8, 6))
    # determine the boundaries of the map from sounding lon and lat:
    maxlon = math.ceil(np.max(data['longitude']) / 0.5) * 0.5
    minlon = math.floor(np.min(data['longitude']) / 0.5) * 0.5

    maxlat = math.ceil(np.max(data['latitude']) / 0.5) * 0.5
    minlat = math.floor(np.min(data['latitude']) / 0.5) * 0.5

    # set up basemap projection
    try:
        m = Basemap(projection='cyl',
                    resolution='h',
                    llcrnrlat=minlat,
                    urcrnrlat=maxlat,
                    llcrnrlon=minlon,
                    urcrnrlon=maxlon,
                    area_thresh=1,
                    ax=ax)
    except OSError:
        logging.warning('High resolution map data has not been installed and'
                        ' the low resolution resolution will be used. For the'
                        ' hight resolution install with e.g. conda install -c'
                        ' conda-forge basemap-data-hires')
        m = Basemap(projection='cyl',
                    resolution='l',
                    llcrnrlat=minlat,
                    urcrnrlat=maxlat,
                    llcrnrlon=minlon,
                    urcrnrlon=maxlon,
                    area_thresh=1,
                    ax=ax)
    # plot a topography on top:
    m.etopo(alpha=0.4)

    # coastlines, countries, boundary, background-color, gridlines
    m.drawcoastlines()
    m.drawcountries()
    m.drawmapboundary()
    m.shadedrelief()
    m.fillcontinents(color='#00a500')
    m.drawparallels(np.arange(10, 70, 0.25), labels=[1, 1, 0, 0])
    m.drawmeridians(np.arange(-100, 0, 0.25), labels=[0, 0, 0, 1])

    # plot balloon path:
    x, y = m(data['longitude'], data['latitude'])
    sca = m.scatter(x,
                    y,
                    marker='.',
                    c=data['altitude'],
                    cmap='Reds',
                    vmin=0.,
                    vmax=30000.,
                    zorder=10)
    fig.subplots_adjust(right=0.75, left=0.1)
    cax = plt.axes([0.85, 0.27, 0.025, 0.45])
    plt.colorbar(sca, cax=cax, label='Altitude [m]')
    #m.plot(x, y, '-k')

    # plot launch position as red square:
    m.plot(float(data['longitude'][0]),
           float(data['latitude'][0]),
           'sb',
           markersize=5,
           zorder=15)

    # and the figure title:
    ax.set_title('%s, %s %sUTC %s' %
                 (specs['location'], specs['date'],
                  data['time_of_launch_HHmmss'][:-2], specs['direction']))

    fig.savefig(outputpath + outputname)

    logging.info('Map saved at {}'.format(outputpath + outputname))
Beispiel #32
0
        yi[:, :],
        rgrWTcentroids[rgiSorted[pa], :, :, 0] / 9.81,
        levels=np.arange(4000, 6000, 100).astype('int'),
        linewidths=2,
        colors='k'
    )  #['#d9f0a3','#addd8e','#78c679','#41ab5d','#238443','#005a32'])
    plt.clabel(CS, inline=1, fontsize=12, fmt='%d')
    # plot cluster region
    iLatMax = rgrLatWT1D[rgiSrWT[0, :].max()]
    iLatMin = rgrLatWT1D[rgiSrWT[0, :].min()]
    iLonMax = rgrLonWT1D[rgiSrWT[1, :].max()]
    iLonMin = rgrLonWT1D[rgiSrWT[1, :].min()]
    lats = [iLatMin, iLatMax, iLatMax, iLatMin, iLatMin]
    lons = np.array([iLonMin, iLonMin, iLonMax, iLonMax, iLonMin]) - 360
    x, y = m(lons, lats)
    m.plot(x, y, lw=3, ls='--', c='r')

    # Lable the map
    plt.title(rgsLableABC[pa] + ') WT' + str(pa + 1) + ', ' +
              str(iSampleSize) + ' days',
              fontsize=16)

    m.drawcoastlines(color='#525252')
    m.drawcountries(color='#525252')
    m.drawstates(color='#525252')
    # add shapefile of catchment
    XX, YY = m(Subregion[:, 1], Subregion[:, 0])
    m.plot(XX, YY, c='r', lw=2)

    # Add Histogram in the lower left corner
    rect = [0.1, 0.1, 0.4, 0.25]
        # to the current x and y coordinates gives the new x and y coordinates.
        #
        ###########################################################################
        startx += a['UWIND'][caindex]
        starty += a['VWIND'][caindex]
        newx[count] = startx
        newy[count] = starty
        count += 1

# Convert the predicted x and y projection coordinates to lat/lon
printlon, printlat = m(newx, newy, inverse=True)
print "Latitude,Longitude"
for x, y, in zip(printlat, printlon):
    print str(x) + "," + str(y)

#m.drawrivers()
#plotfx, plotfy = m(flon,flat)
#m.plot(plotfx, plotfy, color='red')
m.plot(plotx, ploty)
m.plot(newx, newy)
#fig5.show()
#plt.show()
"""
x = np.arange(0,10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y, fill_value='extrapolate')

print f(9)
print f(11)
"""
Beispiel #34
0
def transectview(var, tindex, istart, iend, jstart, jend, gridid, \
          filename=None, spval=1e37, cmin=None, cmax=None, clev=None, \
          fill=False, contour=False, c=None, jrange=None, hrange=None,\
          fts=None, title=None, map=False, \
          pal=None, clb=True, xaxis='lon', outfile=None):
    """
    transectview(var, tindex, istart, iend, jstart, jend, gridid,
                 {optional switch})

    optional switch:
      - filename         if defined, load the variable from file
      - spval            specify spval
      - cmin             set color minimum limit
      - cmax             set color maximum limit
      - clev             set the number of color step
      - fill             use contourf instead of pcolor
      - contour          overlay contour
      - c                desired contour level. If not specified,
                         plot every 4 contour level.
      - jrange           j range
      - hrange           h range
      - fts              set font size (default: 12)
      - title            add title to the plot
      - map              if True, draw a map showing transect location
      - pal              set color map (default: cm.jet)
      - clb              add colorbar (defaul: True)
      - xaxis            use lon or lat for x axis
      - outfile          if defined, write figure to file

    plot vertical transect between the points P1=(istart, jstart)
    and P2=(iend, jend) from 3D variable var. If filename is provided,
    var must be a string and the variable will be load from the file.
    grid can be a grid object or a gridid. In the later case, the grid
    object correponding to the provided gridid will be loaded.
    """

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

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

        var = data.variables[var]

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

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

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

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

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

    # get transect
    if tindex == -1:
        var = var[:, :, :]
    else:
        var = var[tindex, :, :, :]

    if fill == True:
        transect, zt, lont, latt, = pyroms.tools.transect(var, istart, iend, \
                                     jstart, jend, grd, Cpos, spval=spval)
    else:
        transect, zt, lont, latt, = pyroms.tools.transect(var, istart, iend, \
                                     jstart, jend, grd, Cpos, vert=True, spval=spval)

    if xaxis == 'lon':
        xt = lont
    elif xaxis == 'lat':
        xt = latt

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

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

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

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

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

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

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

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

    # clear figure
    #plt.clf()

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

    if fill:
        cf = plt.contourf(xt,
                          zt,
                          transect,
                          vc,
                          cmap=pal,
                          norm=pal_norm,
                          axes=ax)
    else:
        cf = plt.pcolor(xt, zt, transect, cmap=pal, norm=pal_norm, axes=ax)

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

    if contour:
        if c is None:
            c = vc[::10]
        if fill:
            plt.contour(xt,
                        zt,
                        transect,
                        c,
                        colors='k',
                        linewidths=0.5,
                        linestyles='solid',
                        axes=ax)
        else:
            xc = 0.5 * (xt[1:, :] + xt[:-1, :])
            xc = 0.5 * (xc[:, 1:] + xc[:, :-1])
            zc = 0.5 * (zt[1:, :] + zt[:-1, :])
            zc = 0.5 * (zc[:, 1:] + zc[:, :-1])
            plt.contour(xc,
                        zc,
                        transect,
                        c,
                        colors='k',
                        linewidths=0.5,
                        linestyles='solid',
                        axes=ax)

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

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

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

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

    if map:
        # draw a map with constant-i slice location
        ax_map = plt.axes([0.4, 0.76, 0.2, 0.23])
        varm = np.ma.masked_where(mask[:, :] == 0, var[var.shape[0] - 1, :, :])
        lon_min = lon.min()
        lon_max = lon.max()
        lon_0 = (lon_min + lon_max) / 2.
        lat_min = lat.min()
        lat_max = lat.max()
        lat_0 = (lat_min + lat_max) / 2.
        map = Basemap(projection='merc', llcrnrlon=lon_min, llcrnrlat=lat_min, \
                 urcrnrlon=lon_max, urcrnrlat=lat_max, lat_0=lat_0, lon_0=lon_0, \
                 resolution='i', area_thresh=10.)
        x, y = list(map(lon, lat))
        xt, yt = list(map(lont[0, :], latt[0, :]))
        # fill land and draw coastlines
        map.drawcoastlines()
        map.fillcontinents(color='grey')
        #map.drawmapboundary()
        Basemap.pcolor(map, x, y, varm, axes=ax_map)
        Basemap.plot(map, xt, yt, 'k-', linewidth=3, axes=ax_map)

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

    return
Beispiel #35
0
def multiCaPlot(pipeline,
                mogiFlag=False,
                offset=.15,
                direction='H',
                pca_comp=0,
                scaleFactor=2.5,
                map_res='i'):
    '''
    The multiCaPlot function generates a geographic eigenvector plot of several pipeline runs
    
    This function plots multiple pipeline runs over perturbed pipeline
    parameters. The various perturbations are plotted more
    transparently (alpha=.5), while the median eigen_vector and Mogi
    inversion are plotted in solid blue and red

    @param pipeline: The pipeline object with multiple runs
    @param mogiFlag: Flag to indicate plotting the Mogi source as well as the PCA
    @param offset: Offset for padding the corners of the generated map
    @param direction: Indicates the eigenvectors to plot. Only Horizontal component is currently supported ('H')
    @param pca_comp: Choose the PCA component to use (integer)
    @param scaleFactor: Size of the arrow scaling factor
    @param map_res: Map data resolution for Basemap ('c', 'i', 'h', 'f', or None)
    '''

    # as this is a multi_ca_plot function, assumes GPCA
    plt.figure()

    meta_data = pipeline.data_generator.meta_data
    station_list = pipeline.data_generator.station_list

    lat_range, lon_range = pbo_tools.getLatLonRange(meta_data, station_list)
    coord_list = pbo_tools.getStationCoords(meta_data, station_list)

    # Create a map projection of area
    bmap = Basemap(llcrnrlat=lat_range[0] - offset,
                   urcrnrlat=lat_range[1] + offset,
                   llcrnrlon=lon_range[0] - offset,
                   urcrnrlon=lon_range[1] + offset,
                   projection='gnom',
                   lon_0=np.mean(lon_range),
                   lat_0=np.mean(lat_range),
                   resolution=map_res)

    # bmap.fillcontinents(color='white')
    # bmap.drawmapboundary(fill_color='white')
    bmap.drawmapboundary(fill_color='#41BBEC')
    bmap.fillcontinents(color='white')

    # Draw just coastlines, no lakes
    for i, cp in enumerate(bmap.coastpolygons):
        if bmap.coastpolygontypes[i] < 2:
            bmap.plot(cp[0], cp[1], 'k-')

    parallels = np.arange(np.round(lat_range[0] - offset, decimals=1),
                          np.round(lat_range[1] + offset, decimals=1), .1)
    meridians = np.arange(np.round(lon_range[0] - offset, decimals=1),
                          np.round(lon_range[1] + offset, decimals=1), .1)

    bmap.drawmeridians(meridians, labels=[0, 0, 0, 1])
    bmap.drawparallels(parallels, labels=[1, 0, 0, 0])

    # Plot station coords
    for coord in coord_list:
        bmap.plot(coord[1],
                  coord[0],
                  'ko',
                  markersize=6,
                  latlon=True,
                  zorder=12)
        x, y = bmap(coord[1], coord[0])
        plt.text(x + 250,
                 y - 450,
                 station_list[coord_list.index(coord)],
                 zorder=12)

    # loop over each pipeline run
    elatmean = np.zeros(len(station_list))
    elonmean = np.zeros_like(elatmean)
    # check if want to plot Mogi as well
    if mogiFlag:
        avg_mogi = np.array([0., 0.])
        mlatmean = np.zeros_like(elatmean)
        mlonmean = np.zeros_like(elatmean)

    for nrun in range(len(pipeline.RA_results)):
        pca = pipeline.RA_results[nrun]['GPCA']['CA']
        station_lat_list, station_lon_list, ev_lat_list, ev_lon_list, dir_sign = pbo_tools.dirEigenvectors(
            coord_list, pca.components_[pca_comp])

        elatmean += ev_lat_list
        elonmean += ev_lon_list
        # plot each run in light blue
        bmap.quiver(station_lon_list,
                    station_lat_list,
                    ev_lon_list,
                    ev_lat_list,
                    latlon=True,
                    scale=scaleFactor,
                    alpha=.25,
                    color='blue',
                    zorder=11)

        if mogiFlag:
            mogi_res = pipeline.RA_results[nrun]['Mogi']
            avg_mogi += np.array([mogi_res['lon'], mogi_res['lat']])
            mogi_x_disp, mogi_y_disp = mogi.MogiVectors(
                mogi_res, station_lat_list, station_lon_list)
            mlatmean += mogi_y_disp
            mlonmean += mogi_x_disp

            bmap.plot(mogi_res['lon'],
                      mogi_res['lat'],
                      "g^",
                      markersize=10,
                      latlon=True,
                      alpha=.25,
                      zorder=12)
            bmap.quiver(station_lon_list,
                        station_lat_list,
                        mogi_x_disp * dir_sign,
                        mogi_y_disp * dir_sign,
                        latlon=True,
                        scale=scaleFactor,
                        color='red',
                        alpha=.25,
                        zorder=11)

    #plot the mean ev in blue
    elatmean = elatmean / len(pipeline.RA_results)
    elonmean = elonmean / len(pipeline.RA_results)
    bmap.quiver(station_lon_list,
                station_lat_list,
                elonmean,
                elatmean,
                latlon=True,
                scale=scaleFactor,
                color='blue',
                alpha=1,
                zorder=11)
    if mogiFlag:
        # plot mean mogi results
        avg_mogi = avg_mogi / len(pipeline.RA_results)
        mlatmean = mlatmean / len(pipeline.RA_results)
        mlonmean = mlonmean / len(pipeline.RA_results)
        bmap.plot(avg_mogi[0],
                  avg_mogi[1],
                  "g^",
                  markersize=10,
                  latlon=True,
                  alpha=1,
                  zorder=12)
        bmap.quiver(station_lon_list,
                    station_lat_list,
                    mlonmean * dir_sign,
                    mlatmean * dir_sign,
                    latlon=True,
                    scale=scaleFactor,
                    color='red',
                    alpha=1,
                    zorder=11)

    ax_x = plt.gca().get_xlim()
    ax_y = plt.gca().get_ylim()
    x, y = bmap(ax_x[0] + .1 * (ax_x[1] - ax_x[0]),
                ax_y[0] + .1 * (ax_y[1] - ax_y[0]),
                inverse=True)
    bmap.quiver(x,
                y,
                0,
                .2,
                latlon=True,
                scale=scaleFactor,
                headwidth=3,
                headlength=3,
                zorder=11)
    plt.text(ax_x[0] + .1 * (ax_x[1] - ax_x[0]) - 650,
             ax_y[0] + .1 * (ax_y[1] - ax_y[0]) - 1000,
             '20%',
             zorder=11)
Beispiel #36
0
m2t=rr.variables['tide_Eamp'][0,:,:]#; s2t=rr.variables['tide_Eamp'][1,:,:]; n2t=rr.variables['tide_Eamp'][2,:,:]; 
lat=rr.variables['lat_rho'][:]; lon=rr.variables['lon_rho'][:]; maska=rr.variables['mask_rho'][:]; rr.close()

m2=np.zeros((len(m2r),len(m2r.T)))#; s2=np.zeros((len(m2r),len(m2r.T))); n2=np.zeros((len(m2r),len(m2r.T))); 
maska=np.zeros((np.shape(m2r)[0],np.shape(m2r)[1]), dtype=bool)
m2=np.array(np.matrix(m2r)-(np.matrix(m2t)+0.001))#; s2=np.array(np.matrix(s2r)-(np.matrix(s2t)+0.001)); n2=np.array(np.matrix(n2r)-(np.matrix(n2t)+0.001));  
maska=np.zeros((np.shape(m2r)[0],np.shape(m2r)[1]), dtype=bool)


#; s2[s2>maxim]=maxim; n2[n2>maxim]=maxim #### Decrease amplitude ratio down to 5

m2=np.ma.array(m2,mask=maska)#; s2=np.ma.array(s2,mask=maska)#; n2=np.ma.array(n2,mask=maska)

#tide=[m2,s2,n2]; varlist=['M21','S21','N21']; amplitude_roms=[m2r,s2r,n2r]; amplitude_tpox=[m2t,s2t,n2t]; 
tide=[m2]; varlist=['M21']; amplitude_roms=[m2r]; amplitude_tpox=[m2t]; 

fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 10)); m1 = Basemap(projection='merc',llcrnrlat=48,urcrnrlat=55,llcrnrlon=-4,urcrnrlon=5,lat_ts=51.5,resolution='h', ax=ax)
y_bcz=np.array([51.37361, 51.37361, 51.37268, 51.33611, 51.32416, 51.31485, 51.27638, 51.24972, 51.21334, 51.09403, 51.09111, 51.09111, 51.09111, 51.09361, 51.09433, 51.26917, 51.55472, 51.55777, 51.55777, 51.61306, 51.61306, 51.80500, 51.87000, 51.87000, 51.55167, 51.48472, 51.45000, 51.37944, 51.37361, 51.37361]); x_bcz=np.array([3.36472, 3.36472, 3.36491, 3.17972, 3.13166, 3.10403, 3.02000, 2.95528, 2.86305, 2.55555, 2.54166, 2.54166, 2.54166, 2.54361, 2.54298, 2.39028, 2.23973, 2.23812, 2.23812, 2.25333, 2.25333, 2.48167, 2.53944, 2.53944, 3.08139, 3.21222, 3.29639, 3.35389, 3.36472, 3.36472])
m1.drawparallels(np.arange(48,55,0.5),labels=[1,0,0,1],fontsize=10); m1.drawmeridians(np.arange(-4,5,0.5),labels=[1,1,1,0],fontsize=10); m1.drawcoastlines(); m1.drawmapboundary(fill_color='#9999FF')
x4, y4 = m1(x_bcz, y_bcz); cs43 = m1.plot(x4,y4,color='black',linewidth=1.0); x1,y1 = m1(lon,lat); mintemp=-1.25;  division=0.05; maxim=1.25; m2r[m2r<mintemp]=mintemp; m2r[m2r>maxim]=maxim
clevs = np.arange(mintemp,maxim+division,division); bounds=np.arange(mintemp,maxim+division,division); 
cax = make_axes_locatable(ax).append_axes("right", size=0.4, pad=0.15); norm = mpl.colors.Normalize(vmin=mintemp, vmax=maxim); mpl.colorbar.ColorbarBase(cax, cmap=mpl.cm.bwr, norm=norm, boundaries=[-10] + bounds + [10], orientation='vertical')
for i in range(0,1):
	CS2 = m1.contourf(x1,y1,tide[i],clevs,cmap=mpl.cm.bwr)#gist_ncar) 
	#CS2 = m1.contourf(x1,y1,amplitude_roms[i],clevs,cmap=mpl.cm.rainbow)
	#CS2 = m1.contourf(x1,y1,amplitude_tpox[i],clevs,cmap=mpl.cm.rainbow)
	m1.drawcountries(); m1.fillcontinents(color='#ddaa66',lake_color='#9999FF')
	lol=ax.annotate('%s' %(varlist[i][:-1]), xy=(0,0),  xycoords='axes points',xytext=(300,20), family='Courier New, monospace',textcoords='axes points',fontsize=50, bbox=dict(facecolor='none', edgecolor='none', pad=5.0))
	file_name = os.path.abspath("%s" %(varlist[i])+".png"); fig.savefig(file_name, dpi=200); lol.remove()

t = 0
m.drawcoastlines()
m.drawstates()
#m.drawparallels(parallels,labels=[1,0,0,0],**tickfont,linewidth=0.0)
#m.drawmeridians(meridians,labels=[0,0,0,1],**tickfont,linewidth=0.0)
m.drawparallels(parallels, labels=[1, 0, 0, 0], **tickfont)
m.drawmeridians(meridians, labels=[0, 0, 0, 1], **tickfont)
plt.yticks(**tickfont)
plt.xticks(**tickfont)
for i in range(len(repelling_ridges_lat)):
    x = [elem for elem in repelling_ridges_lon[i][:, t].data if elem < 99999]
    y = [elem for elem in repelling_ridges_lat[i][:, t].data if elem < 99999]
    tck, u = interpolate.splprep([x, y], u=None, s=smoothing_coef)
    u_new = np.linspace(u.min(), u.max(), interp_number)
    xnew, ynew = interpolate.splev(u_new, tck, der=0)
    m.plot(xnew, ynew, c='r', latlon=True)
    #m.plot(x,y,c='r',latlon=True)
for i in range(len(attracting_ridges_lat)):
    x = [elem for elem in attracting_ridges_lon[i][:, t].data if elem < 99999]
    y = [elem for elem in attracting_ridges_lat[i][:, t].data if elem < 99999]
    tck, u = interpolate.splprep([x, y], u=None, s=smoothing_coef)
    u_new = np.linspace(u.min(), u.max(), interp_number)
    xnew, ynew = interpolate.splev(u_new, tck, der=0)
    m.plot(xnew, ynew, c='b', latlon=True)
    #m.plot(x,y,c='b',latlon=True)
m.scatter(t_lon[:, t],
          t_lat[:, t],
          color=marker_color,
          s=marker_size,
          latlon=True)
plt.annotate('A', xy=(0.91, 0.02), xycoords='axes fraction')
Beispiel #38
0
    def __init__(self, outfile, t, lat, lon, air_u, air_v, tair, cloud, rh,
                 pair, rain, **kwargs):

        from maptools import readShpPointLine

        self.__dict__.update(kwargs)

        self.outfile = outfile
        self.t = t
        self.lat = lat
        self.lon = lon
        self.air_u = air_u
        self.air_v = air_v
        self.tair = tair
        self.cloud = cloud
        self.rh = rh
        self.pair = pair
        self.rain = rain

        ##SUNTANS wind coordinates
        shp_file = '../../../coarse_gis/wind_stations_LM.shp'
        XY, field0 = readShpPointLine(shp_file)
        lon_new = []
        lat_new = []
        for i in range(len(XY)):
            lon_new.append(XY[i][0])
            lat_new.append(XY[i][1])

        ## Test predefined locations
        import matplotlib.pyplot as plt
        from mpl_toolkits.basemap import Basemap

        #west = -97.458207; east = -96.72
        #south = 27.368078; north = 28.291049
        #25.883046, -97.966679
        #27.658327, -96.824101
        west = -97.966679
        east = -96.824101
        south = 25.883046
        north = 27.658327

        fig = plt.figure(figsize=(10, 10))
        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_new, lat_new)
        basemap.plot(llons, llats, 'ob', markersize=8.5)
        plt.show()

        self.xsun = np.zeros([len(lat_new)])
        self.ysun = np.zeros([len(lon_new)])
        for i in range(len(lon_new)):
            (self.xsun[i],
             self.ysun[i]) = utm.from_latlon(lat_new[i], lon_new[i])[0:2]

        #pdb.set_trace()

        ## Step One: interpolate wind data
        self.interp()
        self.writeNC(self.outfile, self.t, self.xsun, self.ysun, self.air_u_new, \
                    self.air_v_new, self.tair_new, self.cloud_new, self.rh_new, \
                    self.pair_new, self.rain_new)
                        zorder=10)
    if (i < 2):
        mplot.drawparallels(np.arange(90, -90, -10),
                            labels=[False, False, True, False],
                            fontsize=8,
                            linewidth=0.25,
                            zorder=10)
    if (i > 3):
        mplot.drawmeridians(np.arange(-180., 180., 60.),
                            labels=[False, False, False, True],
                            fontsize=8,
                            latmax=85,
                            linewidth=0.25,
                            zorder=10)

    mplot.plot(xptsCA, yptsCA, '--', linewidth=1, color='r', zorder=12)
    mplot.plot(xptsBC, yptsBC, '--', linewidth=1, color='b', zorder=12)
    xS, yS = mplot(177, 64.8)
    vars()['ax' + str(i)].text(xS, yS, str(i + 2009), zorder=11)

cax = fig.add_axes([0.25, 0.09, 0.5, 0.03])
cbar = colorbar(im1,
                cax=cax,
                orientation='horizontal',
                extend='both',
                use_gridspec=True)

cbar.set_label(label_str, labelpad=2)
xticks = np.linspace(minval, maxval, 6)
cbar.set_ticks(xticks)
cbar.solids.set_rasterized(True)
Beispiel #40
0
class HMTKBaseMap(object):
    '''
    Class to plot the spatial distribution of events based in the Catalogue
    imported from openquake.hmtk.
    '''
    def __init__(self,
                 config,
                 title=None,
                 dpi=300,
                 ax=None,
                 lat_lon_spacing=2.):
        """
        :param dict config:
            Configuration parameters of the algorithm, containing the
            following information -
                'min_lat' Minimum value of latitude (in degrees, float)
                'max_lat' Minimum value of longitude (in degrees, float)
                (min_lat, min_lon) Defines the inferior corner of the map

                'min_lon' Maximum value of latitude (in degrees, float)
                'max_lon' Maximum value of longitude (in degrees, float)
                (min_lon, max_lon) Defines the upper corner of the map
        :param str title:
            Title string
        """
        self.config = config
        self.title = title
        self.dpi = dpi
        self.lat_lon_spacing = lat_lon_spacing
        self.fig = None
        self.ax = ax
        self.m = None
        self._build_basemap()

    def _build_basemap(self):
        '''
        Creates the map according to the input configuration
        '''
        if self.config['min_lon'] >= self.config['max_lon']:
            raise ValueError('Upper limit of long is smaller than lower limit')

        if self.config['min_lon'] >= self.config['max_lon']:
            raise ValueError('Upper limit of long is smaller than lower limit')
        # Corners of the map
        lowcrnrlat = self.config['min_lat']
        lowcrnrlon = self.config['min_lon']
        uppcrnrlat = self.config['max_lat']
        uppcrnrlon = self.config['max_lon']
        if 'resolution' not in self.config.keys():
            self.config['resolution'] = 'l'

        lat0 = lowcrnrlat + ((uppcrnrlat - lowcrnrlat) / 2)
        lon0 = lowcrnrlon + ((uppcrnrlon - lowcrnrlon) / 2)
        if (uppcrnrlat - lowcrnrlat) >= (uppcrnrlon - lowcrnrlon):
            fig_aspect = PORTRAIT_ASPECT
        else:
            fig_aspect = LANDSCAPE_ASPECT

        if self.ax is None:
            self.fig, self.ax = plt.subplots(figsize=fig_aspect,
                                             facecolor='w',
                                             edgecolor='k')
        else:
            self.fig = self.ax.get_figure()

        if self.title:
            self.ax.set_title(self.title, fontsize=16)
        parallels = np.arange(-90., 90., self.lat_lon_spacing)
        meridians = np.arange(0., 360., self.lat_lon_spacing)

        # Build Map
        # Do not import Basemap at top level since it's an optional feature
        # and it would break doctests
        from mpl_toolkits.basemap import Basemap
        self.m = Basemap(llcrnrlon=lowcrnrlon,
                         llcrnrlat=lowcrnrlat,
                         urcrnrlon=uppcrnrlon,
                         urcrnrlat=uppcrnrlat,
                         projection='stere',
                         resolution=self.config['resolution'],
                         area_thresh=1000.0,
                         lat_0=lat0,
                         lon_0=lon0,
                         ax=self.ax)
        self.m.drawcountries()
        self.m.drawmapboundary()
        self.m.drawcoastlines()
        self.m.drawstates()
        self.m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=12)
        self.m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=12)
        self.m.fillcontinents(color='wheat')

    def savemap(self, filename, filetype='png', papertype="a4"):
        """
        Save the figure
        """
        self.fig.savefig(filename,
                         dpi=self.dpi,
                         format=filetype,
                         papertype=papertype)

    def add_catalogue(self, catalogue, overlay=False):
        '''
        :param catalogue:
            Earthquake catalogue as instance of
            :class:`openquake.hmtk.seismicity.catalogue.Catalogue`

        :param dict config:
            Configuration parameters of the algorithm, containing the
            following information:
            'min_lat' Minimum value of latitude (in degrees, float)
            'max_lat' Minimum value of longitude (in degrees, float)
            (min_lat, min_lon) Defines the inferior corner of the map
            'min_lon' Maximum value of latitude (in degrees, float)
            'max_lon' Maximum value of longitude (in degrees, float)
            (min_lon, max_lon) Defines the upper corner of the map

        :returns:
            Figure with the spatial distribution of the events.
        '''
        # Magnitudes bins and minimum marrker size
        # min_mag = np.min(catalogue.data['magnitude'])
        # max_mag = np.max(catalogue.data['magnitude'])
        con_min = np.where(
            np.array([symb[0] for symb in DEFAULT_SYMBOLOGY]) < np.min(
                catalogue.data['magnitude']))[0]
        con_max = np.where(
            np.array([symb[1] for symb in DEFAULT_SYMBOLOGY]) > np.max(
                catalogue.data['magnitude']))[0]
        if len(con_min) == 1:
            min_loc = con_min[0]
        else:
            min_loc = con_min[-1]
        if len(con_max) == 1:
            max_loc = con_max[0]
        else:
            max_loc = con_max[1]
        # min_loc = np.where(np.array([symb[0] for symb in DEFAULT_SYMBOLOGY])
        #                   < np.min(catalogue.data['magnitude']))[0][-1]
        # max_loc = np.where(np.array([symb[1] for symb in DEFAULT_SYMBOLOGY])
        #                   > np.max(catalogue.data['magnitude']))[0][1]
        symbology = DEFAULT_SYMBOLOGY[min_loc:max_loc]
        for sym in symbology:
            # Create legend string
            if np.isinf(sym[0]):
                leg_str = 'M < %5.2f' % sym[1]
            elif np.isinf(sym[1]):
                leg_str = 'M >= %5.2f' % sym[0]
            else:
                leg_str = '%5.2f <= M < %5.2f' % (sym[0], sym[1])
            idx = np.logical_and(catalogue.data['magnitude'] >= sym[0],
                                 catalogue.data['magnitude'] < sym[1])
            mag_size = 1.2 * np.min([sym[0] + 0.5, sym[1] - 0.5])
            x, y = self.m(catalogue.data['longitude'][idx],
                          catalogue.data['latitude'][idx])
            self.m.plot(x, y, sym[2], markersize=mag_size, label=leg_str)

        self.ax.legend(bbox_to_anchor=LEGEND_OFFSET)
        if self.title:
            self.ax.set_title(self.title, fontsize=16)
        if not overlay:
            plt.show()

    def _plot_area_source(self, source, border='k-', border_width=1.0):
        """
        Plots the area source
        :param source:
            Area source as instance of :class: mtkAreaSource
        :param str border:
            Line properties of border (see matplotlib documentation for detail)
        :param float border_width:
            Line width of border (see matplotlib documentation for detail)
        """
        lons = np.hstack([source.geometry.lons, source.geometry.lons[0]])
        lats = np.hstack([source.geometry.lats, source.geometry.lats[0]])
        x, y = self.m(lons, lats)
        self.m.plot(x, y, border, linewidth=border_width)

    def _plot_point_source(self, source, point_marker='ks', point_size=2.0):
        """
        Plots the area source
        :param source:
            Area source as instance of :class: mtkPointSource
        :param str point_marker:
            Marker style for point (see matplotlib documentation for detail)
        :param float marker size for point:
            Line width of border (see matplotlib documentation for detail)
        """
        x, y = self.m(source.geometry.longitude, source.geometry.latitude)
        self.m.plot(x, y, point_marker, markersize=point_size)

    def _plot_simple_fault(self, source, border='k-', border_width=1.0):
        """
        Plots the simple fault source as a composite of the fault trace
        and the surface projection of the fault.
        :param source:
            Fault source as instance of :class: mtkSimpleFaultSource
        :param str border:
            Line properties of border (see matplotlib documentation for detail)
        :param float border_width:
            Line width of border (see matplotlib documentation for detail)
        """
        # Get the trace
        trace_lons = np.array(
            [pnt.longitude for pnt in source.fault_trace.points])
        trace_lats = np.array(
            [pnt.latitude for pnt in source.fault_trace.points])
        surface_projection = _fault_polygon_from_mesh(source)
        # Plot surface projection first
        x, y = self.m(surface_projection[:, 0], surface_projection[:, 1])
        self.m.plot(x, y, border, linewidth=border_width)
        # Plot fault trace
        x, y = self.m(trace_lons, trace_lats)
        self.m.plot(x, y, border, linewidth=1.3 * border_width)

    def _plot_complex_fault(self,
                            source,
                            border='k-',
                            border_width=1.0,
                            min_depth=0.,
                            max_depth=None,
                            alpha=1.0):
        """
        Plots the simple fault source as a composite of the fault trace
        and the surface projection of the fault.
        :param source:
            Fault source as instance of :class: mtkSimpleFaultSource
        :param str border:
            Line properties of border (see matplotlib documentation for detail)
        :param float border_width:
            Line width of border (see matplotlib documentation for detail)
        """
        if not max_depth:
            max_depth = 70.
        # Get outline
        top_edge = np.column_stack(
            [source.geometry.mesh.lons[0], source.geometry.mesh.lats[0]])

        bottom_edge = np.column_stack([
            source.geometry.mesh.lons[-1][::-1],
            source.geometry.mesh.lats[-1][::-1]
        ])
        outline = np.vstack([top_edge, bottom_edge, top_edge[0, :]])
        lons = source.geometry.mesh.lons.flatten()
        lats = source.geometry.mesh.lats.flatten()
        depths = source.geometry.mesh.depths.flatten()
        norm = Normalize(vmin=min_depth, vmax=max_depth)
        x1, y1 = self.m(lons, lats)
        self.m.scatter(x1,
                       y1,
                       marker=".",
                       s=20,
                       c=depths,
                       norm=norm,
                       cmap="jet_r",
                       alpha=alpha,
                       linewidths=0.0,
                       zorder=4)
        # Plot border
        x2, y2 = self.m(outline[:, 0], outline[:, 1])
        self.m.plot(x2, y2, border, linewidth=border_width)

    def add_source_model(self,
                         model,
                         area_border='k-',
                         border_width=1.0,
                         point_marker='ks',
                         point_size=2.0,
                         overlay=False,
                         min_depth=0.,
                         max_depth=None,
                         alpha=1.0):
        """
        Adds a source model to the map

        :param model:
            Source model of mixed typologies as instance of :class:
            openquake.hmtk.sources.source_model.mtkSourceModel
        """
        for source in model.sources:
            if isinstance(source, mtkAreaSource):
                self._plot_area_source(source, area_border, border_width)
            elif isinstance(source, mtkPointSource):
                self._plot_point_source(source, point_marker, point_size)
            elif isinstance(source, mtkComplexFaultSource):
                self._plot_complex_fault(source, area_border, border_width,
                                         min_depth, max_depth, alpha)
            elif isinstance(source, mtkSimpleFaultSource):
                self._plot_simple_fault(source, area_border, border_width)
            else:
                pass
        if not overlay:
            plt.show()

    def add_colour_scaled_points(self,
                                 longitude,
                                 latitude,
                                 data,
                                 shape='s',
                                 alpha=1.0,
                                 size=20,
                                 norm=None,
                                 overlay=False):
        """
        Overlays a set of points on a map with a fixed size but colour scaled
        according to the data

        :param np.ndarray longitude:
            Longitude
        :param np.ndarray latitude:
            Latitude
        :param np.ndarray data:
            Data for plotting
        :param str shape:
            Marker style
        :param float alpha:
            Sets the transparency of the marker (0 for transparent, 1 opaque)
        :param int size:
            Marker size
        :param norm:
            Normalisation as instance of :class: matplotlib.colors.Normalize
        """
        if not norm:
            norm = Normalize(vmin=np.min(data), vmax=np.max(data))
        x, y, = self.m(longitude, latitude)
        mappable = self.m.scatter(x,
                                  y,
                                  marker=shape,
                                  s=size,
                                  c=data,
                                  norm=norm,
                                  alpha=alpha,
                                  linewidths=0.0,
                                  zorder=4)
        self.m.colorbar(mappable=mappable, fig=self.fig, ax=self.ax)
        if not overlay:
            plt.show()

    def add_size_scaled_points(self,
                               longitude,
                               latitude,
                               data,
                               shape='o',
                               logplot=False,
                               alpha=1.0,
                               colour='b',
                               smin=2.0,
                               sscale=2.0,
                               overlay=False):
        """
        Plots a set of points with size scaled according to the data

        :param bool logplot:
            Choose to scale according to the logarithm (base 10) of the data
        :param float smin:
            Minimum scale size
        :param float sscale:
            Scaling factor
        """
        if logplot:
            data = np.log10(data.copy())

        x, y, = self.m(longitude, latitude)
        self.m.scatter(x,
                       y,
                       marker=shape,
                       s=(smin + data**sscale),
                       c=colour,
                       alpha=alpha,
                       zorder=2)
        if not overlay:
            plt.show()

    def _select_color_mag(self, mag):
        if (mag > 8.0):
            color = 'k'
            # color.append('k')
        elif (mag < 8.0) and (mag >= 7.0):
            color = 'b'
            # color.append('b')
        elif (mag < 7.0) and (mag >= 6.0):
            color = 'y'
            # color.append('y')
        elif (mag < 6.0) and (mag >= 5.0):
            color = 'g'
            # color.append('g')
        elif (mag < 5.0):
            color = 'm'
            # color.append('m')
        return color

    def add_focal_mechanism(self, catalogue, magnitude=None, overlay=True):
        """
        Plots a the the focal mechanism based on the beachball representation.
        The focal_menchanism flag must contain: strike, dip, rake.
        """
        longitude = catalogue.data['longitude']
        latitude = catalogue.data['latitude']
        strike = catalogue.data['strike1']
        dip = catalogue.data['dip1']
        rake = catalogue.data['rake1']

        if not magnitude or (magnitude < 0):
            magnitude = catalogue.data['magnitude']
            for i, mag in enumerate(magnitude):
                color = self._select_color_mag(mag)
                focal_mechanism = [strike[i], dip[i], rake[i]]
                x, y = self.m(longitude[i], latitude[i])
                self.m.plot(x, y)
                size = mag * 10000
                beach = Beach(focal_mechanism,
                              linewidth=1,
                              xy=(x, y),
                              width=size,
                              zorder=size,
                              facecolor=color)
                self.ax.add_collection(beach)
                if not overlay:
                    plt.show()
        else:
            for i in range(0, catalogue.get_number_tensors()):
                x, y = self.m(longitude[i], latitude[i])
                self.m.plot(x, y)
                focal_mechanism = [strike[i], dip[i], rake[i]]
                size = magnitude * 10000.
                beach = Beach(focal_mechanism,
                              linewidth=1,
                              xy=(x, y),
                              width=size,
                              zorder=size,
                              facecolor='r')
                self.ax.add_collection(beach)
                if not overlay:
                    plt.show()

    def add_catalogue_cluster(self,
                              catalogue,
                              vcl,
                              flagvector,
                              cluster_id=None,
                              overlay=True):
        """
        Creates a plot of a catalogue showing where particular clusters exist
        """
        # Create simple magnitude scaled point basemap
        self.add_size_scaled_points(catalogue.data['longitude'],
                                    catalogue.data['latitude'],
                                    catalogue.data['magnitude'],
                                    shape="o",
                                    alpha=0.8,
                                    colour=(0.5, 0.5, 0.5),
                                    smin=1.0,
                                    sscale=1.5,
                                    overlay=True)
        # If cluster ID is not specified just show mainshocks
        if cluster_id is None:
            idx = flagvector == 0
            self.add_size_scaled_points(catalogue.data['longitude'][idx],
                                        catalogue.data['latitude'][idx],
                                        catalogue.data['magnitude'][idx],
                                        shape="o",
                                        colour="r",
                                        smin=1.0,
                                        sscale=1.5,
                                        overlay=overlay)
            return
        if not isinstance(cluster_id, collections.Iterable):
            cluster_id = [cluster_id]
        for iloc, clid in enumerate(cluster_id):
            if iloc == (len(cluster_id) - 1):
                # On last iteration set overlay to function overlay
                temp_overlay = overlay
            else:
                temp_overlay = True
            idx = vcl == clid
            self.add_size_scaled_points(
                catalogue.data["longitude"][idx],
                catalogue.data["latitude"][idx],
                catalogue.data["magnitude"][idx],
                shape="o",
                colour=DISSIMILAR_COLOURLIST[(iloc + 1) % NCOLS],
                smin=1.0,
                sscale=1.5,
                overlay=temp_overlay)
    '轨道交通3号线': '#ffd823',
    '轨道交通4号线': '#320177',
    '轨道交通5号线': '#823094',
    '轨道交通6号线': '#ce047a',
    '轨道交通7号线': '#f3560f',
    '轨道交通8号线': '#008cc1',
    '轨道交通9号线': '#91c5db'
}

for i in range(len(df)):
    line_color = sta_linecolor[df.iloc[i, 2]]
    lon, lat = m(df.iloc[i, -1][0], df.iloc[i, -1][1])
    # m.scatter(lon, lat, s=10)
    m.plot(lon,
           lat,
           marker='o',
           markersize=get_logsize(sta_df.iloc[i, 2]) + 1,
           color=line_color)
    # if df.iloc[i,2] == '轨道交通10号线':
    #     plt.text(lon, lat, df.iloc[i,6],fontdict={'size':5,'color':'r'})

for line in sta_linecolor.keys():
    df2 = df.loc[df.LINEBELONG == line, :]

    if line == '浦江线':
        df2.loc[326, 'ID'] = '0891'
        df2.loc[328, 'ID'] = '0892'
        df2.loc[329, 'ID'] = '0893'
        df2.loc[331, 'ID'] = '0894'
        df2.loc[327, 'ID'] = '0895'
        m.drawgreatcircle(121.507905886,
# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon are the lat/lon values of the lower left and upper right corners of the map.
# resolution = 'i'means use intermediate resolution coastlines.lon_0, lat_0 are the central longitude and latitude of
# the projection.
m = Basemap(projection='merc',
            llcrnrlon=des_big[2][1],
            llcrnrlat=des_big[2][0],
            urcrnrlon=des_big[0][1],
            urcrnrlat=des_big[0][0],
            resolution='f',
            area_thresh=0.1,
            lat_0=lat_S,
            lon_0=long_S,
            epsg=4269)
m.arcgisimage(service='World_Topo_Map', xpixels=1200, verbose=True, zorder=1)
p1, p2 = m(long_S, lat_S)
m.plot(p1, p2, 'r*', markersize=10)

#label = 'Denver'
#plt.text(p1+1000, p2+500, label)
#m.drawcoastlines(linewidth=1.5)
#m.drawcountries(linewidth=1.5)
#m.fillcontinents(color="#ffe4b5",lake_color="#afeeee")
#m.drawmapboundary(fill_color="#afeeee")


# function to draw polygons
def draw_screen_poly(lats, lons, m):
    x, y = m(lons, lats)
    xy = zip(x, y)
    poly = Polygon(xy, facecolor='red', alpha=0.1)
    plt.gca().add_patch(poly)
Beispiel #43
0
    lons = next(coord_iter)
    print('lats is: ' + str(lats) + '   ' + 'lons is : ' + str(lons))
    x, y = m(lons, lats)
    point.set_data(x, y)
    return point,


#Config Map
m = Basemap(lat_0=0, lon_0=0, projection='moll', resolution='l')
m.drawmapboundary(fill_color='lightblue')
m.fillcontinents(color='tan', lake_color='lightblue')
#m.drawcoastlines()
m.shadedrelief()
#Init and define first point
x, y = m(0, 0)
point = m.plot(x, y, 'ro', markersize=5)[0]

ip_list = []
ip_list = ParseTraceRoute()
json_list = []
coord_list = []

#Read from STDIN
[
    print('About to get coordinates for: ' + ip_list[i])
    for i in range(0, len(ip_list))
]

for i in ip_list:
    ##Change for + data
    with urllib.request.urlopen('http://ip-api.com/json/' + str(i) +
def genImage(bands, enhanced, indy, fig):
    fig = fig
    #-----------------------------------------------------------------------------#
    #Change Directory to Data
    #os.chdir('./Task_1_2_3/Data')
    path = '.\\Task_1_2_3\\Data\\'
    #-----------------------------------------------------------------------------#
    #----------------------------------------------------------------------------------------#
    # inputs

    file_name_myd021km = path + 'MYD021KM.A2015190.1340.061.2018051014602.hdf'
    file_name_myd03 = path + 'MYD03.A2015190.1340.061.2018048194846.hdf'

    file_myd021km = SD(file_name_myd021km, SDC.READ)

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

    selected_sds = file_myd021km.select('EV_250_Aggr1km_RefSB')

    selected_sds_attributes = selected_sds.attributes()

    for key, value in selected_sds_attributes.items():
        #print(key, value)
        if key == 'reflectance_scales':
            reflectance_scales_250_Aggr1km_RefSB = np.asarray(value)
        if key == 'reflectance_offsets':
            reflectance_offsets_250_Aggr1km_RefSB = np.asarray(value)

    sds_data_250_Aggr1km_RefSB = selected_sds.get()

    data_shape = sds_data_250_Aggr1km_RefSB.shape

    along_track = data_shape[1]
    cross_trak = data_shape[2]

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

    selected_sds = file_myd021km.select('EV_500_Aggr1km_RefSB')

    selected_sds_attributes = selected_sds.attributes()
    #print(selected_sds_attributes)
    for key, value in selected_sds_attributes.items():
        if key == 'reflectance_scales':
            reflectance_scales_500_Aggr1km_RefSB = np.asarray(value)
        if key == 'reflectance_offsets':
            reflectance_offsets_500_Aggr1km_RefSB = np.asarray(value)

    sds_data_500_Aggr1km_RefSB = selected_sds.get()

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

    file_myd03 = SD(file_name_myd03, SDC.READ)

    selected_sds = file_myd03.select('Latitude')
    myd03_lat = selected_sds.get()

    selected_sds = file_myd03.select('Longitude')
    myd03_long = selected_sds.get()

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

    data_shape = sds_data_250_Aggr1km_RefSB.shape

    along_track = data_shape[1]
    cross_trak = data_shape[2]

    z = np.zeros((along_track, cross_trak, 3))

    #This Block goes through the different bands you wanted.

    for p in range(len(bands)):
        if bands[p] < 3:
            for i in np.arange(along_track):
                for j in np.arange(cross_trak):
                    z[i,j,p] = ( sds_data_250_Aggr1km_RefSB[bands[p]-1,i,j] - \
                    reflectance_offsets_250_Aggr1km_RefSB[bands[p]-1] ) * \
                    reflectance_scales_250_Aggr1km_RefSB[bands[p]-1]
        if bands[p] > 2:
            for i in np.arange(along_track):
                for j in np.arange(cross_trak):
                    z[i,j,p] = ( sds_data_500_Aggr1km_RefSB[bands[p]-3,i,j] - \
                    reflectance_offsets_500_Aggr1km_RefSB[bands[p]-3] ) * \
                    reflectance_scales_500_Aggr1km_RefSB[bands[p]-3]

    z[z > 1] = 1.0
    z[z < 0] = 0.0

    #----------------------------------------------------------------------------------------#
    # Color enhancement
    if enhanced == 1:
        x = np.array([0, 30, 60, 120, 190, 255], dtype=np.uint8)
        y = np.array([0, 110, 160, 210, 240, 255], dtype=np.uint8)

        def scale_image(image, x, y):
            scaled = np.zeros((along_track, cross_trak), dtype=np.uint8)
            for i in range(len(x) - 1):
                x1 = x[i]
                x2 = x[i + 1]
                y1 = y[i]
                y2 = y[i + 1]
                m = (y2 - y1) / float(x2 - x1)
                b = y2 - (m * x2)
                mask = ((image >= x1) & (image < x2))
                scaled = scaled + mask * np.asarray(m * image + b,
                                                    dtype=np.uint8)

            mask = image >= x2
            scaled = scaled + (mask * 255)

            return scaled

        z_color_enh = np.zeros((along_track, cross_trak, 3), dtype=np.uint8)
        z_color_enh[:, :, 0] = scale_image(img_as_ubyte(z[:, :, 0]), x, y)
        z_color_enh[:, :, 1] = scale_image(img_as_ubyte(z[:, :, 1]), x, y)
        z_color_enh[:, :, 2] = scale_image(img_as_ubyte(z[:, :, 2]), x, y)

        #print z_color_enh

        z = z_color_enh / 256.0

    #----------------------------------------------------------------------------------------#
    # Rough estimation of latitude and longitude at granule center (long_0, lat_0)

    lat_min = myd03_lat[0, 0]
    lat_max = myd03_lat[along_track - 1, cross_trak - 1]

    lat_0 = lat_min + (lat_max - lat_min) / 2.

    long_min = min(myd03_long[0, 0], myd03_long[along_track - 1,
                                                cross_trak - 1])
    long_max = max(myd03_long[0, 0], myd03_long[along_track - 1,
                                                cross_trak - 1])

    lon_0 = long_min + (long_max - long_min) / 2.

    #-----------------------------------------------------------------------------#
    #-----------------------------------------------------------------------------#
    # CALIPSO file input
    # CAL_LID_L2_333mMLay file to obtain dataset 'Number_Layers_Found'
    # Can edit DATAFIELD_NAME to plot 'Feature_Classification_Flags' or
    # 'Land_Water_Mask' or 'IGBP_Surface_Type' or dataset of interest along the
    # orbit path

    #FILE_NAME = 'CAL_LID_L2_333mMLay-Standard-V4-20.2015-07-09T14-40-55ZD.hdf'
    #FILE_NAME = 'CAL_LID_L2_333mMLay-Standard-V4-20.2015-07-09T11-23-10ZD.hdf'
    #FILE_NAME = 'CAL_LID_L2_333mMLay-Standard-V4-20.2015-07-09T13-02-00ZD.hdf'
    FILE_NAME = path + 'CAL_LID_L2_333mMLay-Standard-V4-20.2015-07-09T13-02-00ZD.hdf'
    DATAFIELD_NAME = 'Number_Layers_Found'

    #-----------------------------------------------------------------------------#
    #-----------------------------------------------------------------------------#
    # Read CALIPSO file

    hdf = SD(FILE_NAME, SDC.READ)

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

    # Read dataset.
    data1D = hdf.select(DATAFIELD_NAME)
    data = data1D[:, 0]

    # Read geolocation datasets.
    latitude = hdf.select('Latitude')
    lat = latitude[:]

    longitude = hdf.select('Longitude')
    lon = longitude[:]

    # Subset data. Otherwise, all points look black.
    lat = lat[::15]
    lon = lon[::15]
    data = data[::15]

    # Focus on layer (> 1) data only.
    data[data == 0] = 0
    data[data > 0] = 1

    # Make a color map of fixed colors.
    cmap = colors.ListedColormap(['blue', 'red'])
    #-----------------------------------------------------------------------------#
    #-----------------------------------------------------------------------------#

    #----------------------------------------------------------------------------------------#
    # Orthographic Map Projection

    #fig = plt.figure()

    #Creates subplots
    subplot_num = 220 + indy
    ax = fig.add_subplot(subplot_num)

    ax.patch.set_facecolor((0.75, 0.75, 0.75))

    m1 = Basemap(projection='ortho', lon_0=lon_0, lat_0=lat_0, resolution=None)

    xpt0, ypt0 = m1(lon_0, lat_0)

    xpt1, ypt1 = m1(myd03_long[0, 0], myd03_lat[0, 0])
    xpt2, ypt2 = m1(myd03_long[0, cross_trak - 1], myd03_lat[0,
                                                             cross_trak - 1])
    xpt3, ypt3 = m1(myd03_long[along_track-1,cross_trak-1], \
                    myd03_lat[along_track-1,cross_trak-1])
    xpt4, ypt4 = m1(myd03_long[along_track - 1, 0], myd03_lat[along_track - 1,
                                                              0])

    llx = min(xpt1, xpt2, xpt3, xpt4) - xpt0  # lower left
    lly = min(ypt1, ypt2, ypt3, ypt4) - ypt0

    urx = max(xpt1, xpt2, xpt3, xpt4) - xpt0  # upper right
    ury = max(ypt1, ypt2, ypt3, ypt4) - ypt0

    m = Basemap(projection='ortho',lon_0=lon_0,lat_0=lat_0,resolution='l',\
        llcrnrx=llx,llcrnry=lly,urcrnrx=urx,urcrnry=ury)

    x_igrid, y_igrid = m(myd03_long, myd03_lat)

    x_igrid = x_igrid - xpt0
    y_igrid = y_igrid - ypt0

    z_igrid_01 = np.zeros((along_track, cross_trak))
    z_igrid_02 = np.zeros((along_track, cross_trak))
    z_igrid_03 = np.zeros((along_track, cross_trak))

    for i in np.arange(2030):
        for j in np.arange(1354):
            z_igrid_01[i, j] = z[i, j, 0]
            z_igrid_02[i, j] = z[i, j, 1]
            z_igrid_03[i, j] = z[i, j, 2]

    x1_igrid = x_igrid.ravel()
    y1_igrid = y_igrid.ravel()
    z_igrid_01 = z_igrid_01.ravel()
    z_igrid_02 = z_igrid_02.ravel()
    z_igrid_03 = z_igrid_03.ravel()

    xy1_igrid = np.vstack((x1_igrid, y1_igrid)).T
    xi, yi = np.mgrid[llx:urx:1000j, lly:ury:1000j]

    z_01 = griddata(xy1_igrid, z_igrid_01, (xi, yi), method='cubic')
    z_02 = griddata(xy1_igrid, z_igrid_02, (xi, yi), method='cubic')
    z_03 = griddata(xy1_igrid, z_igrid_03, (xi, yi), method='cubic')

    rgb_projected = np.zeros((1000, 1000, 3))
    for i in np.arange(1000):
        for j in np.arange(1000):
            rgb_projected[i, j, 0] = z_01[i, j]
            rgb_projected[i, j, 1] = z_02[i, j]
            rgb_projected[i, j, 2] = z_03[i, j]

    #rgb_projected[ z > 1 ] = 1.0
    #rgb_projected[ z < 0 ] = 0.0
    whereAreNaNs = np.isnan(rgb_projected)
    rgb_projected[whereAreNaNs] = 0.75

    #print rgb_projected

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

    img = m.imshow(np.rot90((np.fliplr(rgb_projected)) * 255).astype(np.uint8),
                   origin='lower')

    img.set_clim(0.0, 1.0)
    #plt.show()
    m.drawcoastlines()

    m.drawparallels(np.arange(-90., 120., 10.),
                    color='k',
                    fontsize=12,
                    labels=[True, False, False, False])
    m.drawmeridians(np.arange(0., 420., 20.),
                    color='k',
                    fontsize=12,
                    labels=[False, False, False, True])

    # Map data along orbit path in plot
    x, y = m(lon, lat)
    i = 0
    for feature in data:
        m.plot(x[i], y[i], 'o', color=cmap(feature), markersize=1)
        i = i + 1

    ax.set_xlabel("", fontsize=5)
    ax.set_ylabel("", fontsize=5)

    #convert bands to string
    slist = ''.join(map(str, bands))

    enhanced_word = ''
    if enhanced == 1:
        enhanced_word = ' Enhanced'

    #Change font size of title
    plt.rcParams["axes.titlesize"] = 5

    # Set title
    long_name = f'MODIS RGB\n{slist}{enhanced_word} Orthographic Projection'
    #basename = os.path.basename(FILE_NAME)
    plt.title(long_name, fontsize=15)

    fig = plt.gcf()

    # Set bounds and normalize
    bounds = np.linspace(0, 2, 3)
    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

    # create a second axes for the colorbar
    ax2 = fig.add_axes([0.25, -0.038, 0.5, 0.02])
    cb = mpl.colorbar.ColorbarBase(ax2,
                                   cmap=cmap,
                                   norm=norm,
                                   spacing='proportional',
                                   ticks=bounds,
                                   boundaries=bounds,
                                   format='%1i',
                                   orientation='horizontal')
    cb.set_ticks([0.5, 1.5])
    cb.ax.tick_params(size=0)
    cb.ax.set_xticklabels(['clear', 'layered'], fontsize=12)

    #os.chdir('..')
    #fig.tight_layout(pad=2)

    #--------------------------#
    #This is only for individual outputs rather than table.

    #Set Name of File
    #name = f'RGBenhance010CALIPSO2_bands-{slist}-{enhanced}.png'

    #plt.savefig(name, dpi=200) #Do this if you want to output each specific projection, make sure to comment out subplot code as well.
    return fig
#With given information in OSM file plotting Ahmedabad on map, I plotted the city as seen on the map , it at the
#west side of India, plotted using a magenta plot

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

map = Basemap(projection='cyl', lat_0=22, lon_0=72)

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

# x=longitude, y = lattitude
x, y = map(72, 22)

map.plot(x, y, marker='D', color='m')

plt.show()

# In[2]:

import folium
# Setup the coordinates of the map center and the zoom option.
map_osm = folium.Map(location=[22.900, 72.800], zoom_start=8)
# Add labels with coordinates.
folium.LatLngPopup().add_to(map_osm)
# Setup the coordinates of the map area.
points = [[21.900, 70.900], [21.900, 73.00], [23.500, 73.00], [23.500, 70.900],
          [21.900, 70.900]]
# Setup the border line with options.
folium.PolyLine(points, color="red", weight=5, opacity=0.3).add_to(map_osm)
Beispiel #46
0
def plot_basemap_results(**kwargs):

    # Retrieving the arguments
    show = kwargs.get('show', True)
    RDV = kwargs.get('rdv', None)
    BYE = kwargs.get('bye', None);
    A1_orig = kwargs.get('A1_orig', None);
    A1_dest = kwargs.get('A1_dest', None);
    A2_orig = kwargs.get('A2_orig', None);
    A2_dest = kwargs.get('A2_dest', None);
    bounds = kwargs.get('Bounds', None);
    output_file = kwargs.get('out_file', None);
    region = kwargs.get('Region', None);
    
    # Setting the map
    fig = plt.figure(num=1, figsize=(12,12)) 
    map=Basemap(llcrnrlon=region[0],llcrnrlat=region[1],urcrnrlon=region[2],urcrnrlat=region[3])
    map.fillcontinents(color='grey', alpha=0.3, lake_color='grey')
    
    # Plots the position, destination and RDV & BYE points
    Airc_1 = map.plot(A1_orig[0], A1_orig[1], 'b4', markersize=18, label='Aircraft 1')
    Airc_2 = map.plot(A2_orig[0], A2_orig[1], 'r4', markersize=18, label='Aircraft 2')
    Dest_1 = map.plot(A1_dest[0], A1_dest[1], 'bs', markersize=10, label='Destination 1')
    Dest_2 = map.plot(A2_dest[0], A2_dest[1], 'rs', markersize=10, label='Destination 2')
    RDV_point = map.plot(RDV[0], RDV[1], 'ko', markersize=10, label='RDV')
    BYE_point = map.plot(BYE[0], BYE[1], 'kx', markersize=10, label='BYE')
    
    # Draw the boundaries
    p1, p2, p_RDV, p_BYE, d1, d2 = (A1_orig[0],A1_orig[1]), (A2_orig[0],A2_orig[1]), (RDV[0], RDV[1]), (BYE[0], BYE[1]), (A1_dest[0], A1_dest[1]), (A2_dest[0], A2_dest[1])
    plt.fill_between([bounds[0][0],bounds[0][1]], bounds[1][0],bounds[1][1], color='#163A6B', alpha=0.15, label='Boundaries', linewidth=0)
    #[point_set, y_1, y_2] = compute_boundaries_great_circle(p1, p2, p_d, 30)
    #plt.fill_between(point_set, y_1,y_2, color='#163A6B', alpha=0.15, label='Boundaries', linewidth=0)
    
    # Add connections
    line_1_start = map.drawgreatcircle(A1_orig[0],A1_orig[1],RDV[0],RDV[1], linestyle="solid", linewidth=0.6, color='b', label='A1: Cruise alone 1')
    line_2_start = map.drawgreatcircle(A2_orig[0],A2_orig[1],RDV[0],RDV[1], linestyle="solid", linewidth=0.6, color='r', label='A2: Cruise alone 1')
    line_formation = map.drawgreatcircle(RDV[0],RDV[1],BYE[0],BYE[1], linestyle="solid", linewidth=1, color='k', label='Formation flight')
    line_1_end = map.drawgreatcircle(BYE[0],BYE[1],A1_dest[0],A1_dest[1], linestyle="dashdot", linewidth=1, color='b', label='A1: Cruise alone 2')
    line_2_end = map.drawgreatcircle(BYE[0],BYE[1],A2_dest[0],A2_dest[1], linestyle="dashdot", linewidth=1, color='r', label='A2: Cruise alone 2')
    map.drawgreatcircle(A1_orig[0],A1_orig[1],A1_dest[0],A1_dest[1], linestyle="dashdot", linewidth=0.6, alpha=0.5, color='b', label='A1: Alone flight')
    map.drawgreatcircle(A2_orig[0],A2_orig[1],A2_dest[0],A2_dest[1], linestyle="dashdot", linewidth=0.6, alpha=0.5, color='r', label='A2: Alone flight')
    
    # Add arrows
    midpoint_1_start = gcc.intermediate_point(p1, p_RDV, fraction=0.5)
    midpoint_2_start = gcc.intermediate_point(p2, p_RDV, fraction=0.5)
    midpoint_form = gcc.intermediate_point(p_RDV, p_BYE, fraction=0.5)
    midpoint_1_end = gcc.intermediate_point(p_BYE, d1, fraction=0.5)
    midpoint_2_end = gcc.intermediate_point(p_BYE, d2, fraction=0.5)
    add_arrow(line_1_start[0], position=midpoint_1_start)
    add_arrow(line_2_start[0], position=midpoint_2_start)
    add_arrow(line_formation[0], position=midpoint_form)
    add_arrow(line_1_end[0], position=midpoint_1_end)
    add_arrow(line_2_end[0], position=midpoint_2_end)
    
    # Legend
    plt.legend(frameon = True, loc='upper right', edgecolor='1', ncol = 2, borderpad = 1, markerscale = 1.2, labelspacing = 2, facecolor='white')
    
    # Show/hide figure
    if not show: 
        plt.close();
    
    # Saving the file and parameters
    plt.gca().set_axis_off()
    plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
                hspace = 0, wspace = 0)
    plt.margins(0,0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    fig.savefig(output_file, dpi=900, bbox_inches = 'tight',
        pad_inches = 0, facecolor='w', edgecolor='w', transparent=True, optimize = True, quality=95)
    lon_0, lat_0 = .5 * (dPar['xmin'] + dPar['xmax']), .5 * (dPar['ymin'] +
                                                             dPar['ymax'])
    m = Basemap(
        llcrnrlon=dPar['xmin'],
        urcrnrlon=dPar['xmax'],
        llcrnrlat=dPar['ymin'],
        urcrnrlat=dPar['ymax'],
        lon_0=lon_0,
        lat_0=lat_0,
        resolution='l',
        projection=dPar['projection'],
    )

m.drawcoastlines()
aX_we, aY_we = m(injection_wells[2][sel_we], injection_wells[3][sel_we])
m.plot(aX_we, aY_we, 'go', ms=2)
aX_eq, aY_eq = m(seismic_activity[1][sel_eq], seismic_activity[2][sel_eq])
m.plot(aX_eq, aY_eq, 'ro', ms=2)
m.drawparallels(np.arange(33, 38, 1), fmt='%i', labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-100, -92, 2), fmt='%i', labels=[0, 0, 0, 1])

matplotlib.pause(.5)
matplotlib.clf()
"""
Part E
"""
"""
Based on my analysis of earthquake rates and locations, seismicity rates 
started to significanty exceed historic values in the year 2010. In 
2017, earthquake rates started to decrease. This is beacause 
man-made earthquakes were no longer happening.
Beispiel #48
0
            lat_1=50.,lon_0=-107.,ax=ax)
# transform to nx x ny regularly spaced native projection grid
nx = int((m.xmax - m.xmin) / 40000.) + 1
ny = int((m.ymax - m.ymin) / 40000.) + 1
topodat, x, y = m.transform_scalar(topoin, lons, lats, nx, ny, returnxy=True)
# plot image over map with imshow.
im = m.imshow(topodat, cm.jet)
# setup colorbar axes instance.
pos = ax.get_position()
l, b, w, h = pos.bounds
cax = fig.add_axes([l + w + 0.075, b, 0.05, h],
                   frameon=False)  # setup colorbar axes
fig.colorbar(im, cax=cax)  # draw colorbar
# plot blue dot on boulder, colorado and label it as such.
xpt, ypt = m(-104.237, 40.125)
m.plot([xpt], [ypt], 'bo')
ax.text(xpt + 100000, ypt + 100000, 'Boulder')
# draw coastlines and political boundaries.
m.drawcoastlines()
m.drawcountries()
m.drawstates()
# draw parallels and meridians.
# label on left, right and bottom of map.
parallels = np.arange(0., 80, 20.)
m.drawparallels(parallels, labels=[1, 1, 0, 1])
meridians = np.arange(10., 360., 30.)
m.drawmeridians(meridians, labels=[1, 1, 0, 1])
# set title.
ax.set_title('ETOPO Topography - Lambert Conformal Conic')
# save image (width 800 pixels with dpi=100 and fig width 8 inches).
canvas.print_figure('plotmap', dpi=100)
Beispiel #49
0
lon = list(dfGrid['X'])
lat = list(dfGrid['Y'])
fig = plt.figure()
a = fig.add_subplot(1, 1, 1)
my_map = Basemap(projection='gall',
                 lat_0=45,
                 lon_0=-63,
                 resolution='h',
                 area_thresh=0.3,
                 llcrnrlon=-68,
                 llcrnrlat=42.0,
                 urcrnrlon=-57.6,
                 urcrnrlat=48)
my_map.drawcountries()
my_map.fillcontinents(color='gray')
my_map.drawmapboundary()
x, y = my_map(dfGrid['X'].values, dfGrid['Y'].values)
my_map.plot(x,
            y,
            '-',
            markersize=10,
            linewidth=2,
            color='r',
            markerfacecolor='b')
my_map.drawcoastlines()
a.set_title('Lobster Fishing areas', fontsize=10)
my_map.drawparallels(np.arange(40, 80, 3), labels=[1, 0, 0, 0])
my_map.drawmeridians(np.arange(-180, 180, 3), labels=[1, 1, 0, 1])
plt.savefig(save_dir + 'lobster_fishing_areas)', dpi=200)
plt.show()
Beispiel #50
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

m = Basemap(projection='mill',
            llcrnrlat=7,
            llcrnrlon=65,
            urcrnrlat=37,
            urcrnrlon=100,
            resolution='l')
m.drawcoastlines()
m.drawcountries(linewidth=1)
m.etopo()
xs = []
ys = []
Dlat, Dlon = 28.7041, 77.1025
xpt, ypt = m(Dlon, Dlat)
xs.append(xpt)
ys.append(ypt)
m.plot(xpt, ypt, 'co', markersize=10)

Clat, Clon = 13.0827, 80.2707
xpt, ypt = m(Clon, Clat)
xs.append(xpt)
ys.append(ypt)
m.plot(xpt, ypt, 'ro', markersize=10)
m.plot(xs, ys, color='orange', label='Delhi to Chennai')
plt.legend()
plt.title('Pollution Hotspots')
plt.show()
Beispiel #51
0
#URL of the dataset to obtain the zip codes
#https://public.opendatasoft.com/explore/dataset/us-zip-code-latitude-and-longitude/export/?location=2,43.32518,-69.78516&basemap=jawg.streets

df = pd.read_csv('us-zip-code-latitude-and-longitude.csv', sep=';')

#Remove the zip code of Alaska (AK) and Hawak (HI)
df.drop(df[df['State'] == 'AK'].index, inplace=True)
df.drop(df[df['State'] == 'HI'].index, inplace=True)

#United States Map bounding box
map = Basemap(llcrnrlon=-125,
              llcrnrlat=23,
              urcrnrlon=-66,
              urcrnrlat=50,
              projection='mill',
              resolution='c')

map.drawcountries()
map.drawcoastlines()

for str_point in df.geopoint:
    point = str_point.split(",")
    #convert the longitude and latitude to image coordinate
    x, y = map(float(point[1]), float(point[0]))
    rgb = [rd.random(), rd.random(),
           rd.random()]  # generate a random color to each zip code location
    map.plot(x, y, marker='s', color=rgb)

plt.show()
def main(lon1,lat1,lon2,lat2,variable,files,filetype="archive",clim=None,sectionid="",
      ijspace=False,xaxis="distance",section_map=False,dpi=180) :

   logger.info("Filetype is %s"% filetype)
   gfile = abfile.ABFileGrid("regional.grid","r")
   plon=gfile.read_field("plon")
   plat=gfile.read_field("plat")
   qlon=gfile.read_field("qlon")
   qlat=gfile.read_field("qlat")

   # Set up section info
   if ijspace :
      sec = gridxsec.SectionIJSpace([lon1,lon2],[lat1,lat2],plon,plat)
   else  :
      sec = gridxsec.Section([lon1,lon2],[lat1,lat2],plon,plat)
   I,J=sec.grid_indexes
   dist=sec.distance
   slon=sec.longitude
   slat=sec.latitude

   # In testing
   #J,I,slon,slat,case,dist=sec.find_intersection(qlon,qlat)
   #print I,J
   #raise NameError,"test"



   logger.info("Min max I-index (starts from 0):%d %d"%(I.min(),I.max()))
   logger.info("Min max J-index (starts from 0):%d %d"%(J.min(),J.max()))


   if section_map :
      ll_lon=slon.min()-10.
      ur_lon=slon.max()+10.
      ll_lat=numpy.maximum(-90.,slat.min()-10.)
      ur_lat=numpy.minimum(90. ,slat.max()+10.)
      m = Basemap(projection='mill', llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat, resolution='l')
      (x,y) = m(slon,slat)
      figure = matplotlib.pyplot.figure()
      ax=figure.add_subplot(111)
      m.drawcoastlines()
      #m.fillcontinents(color='coral',lake_color='aqua')
      m.drawparallels(numpy.arange(-90.,120.,30.),labels=[1,0,0,0]) # draw parallels
      m.drawmeridians(numpy.arange(0.,420.,60.),labels=[0,0,0,1]) # draw meridians
      m.drawmapboundary() # draw a line around the map region
      m.plot(x,y,"r",lw=3)
      m.etopo()
      #m.scatter(x,y,s=20,c=dist)
      pos = ax.get_position()
      #print pos
      asp=pos.height/pos.width
      #print asp
      w=figure.get_figwidth()
      #print w
      h=asp*w
      figure.set_figheight(h)
      if sectionid :
         figure.canvas.print_figure("map_%s.png"%sectionid,dpi=dpi)
      else :
         figure.canvas.print_figure("map.png",dpi=dpi)

   # Get layer thickness variable used in hycom
   dpname = modeltools.hycom.layer_thickness_variable[filetype]
   logger.info("Filetype %s: layer thickness variable is %s"%(filetype,dpname))


   if xaxis == "distance" :
      x=dist/1000.
      xlab="Distance along section[km]"
   elif xaxis == "i" :
      x=I
      xlab="i-index"
   elif xaxis == "j" :
      x=J
      xlab="j-index"
   elif xaxis == "lon" :
      x=slon
      xlab="longitude"
   elif xaxis == "lat" :
      x=slat
      xlab="latitude"
   else :
      logger.warning("xaxis must be i,j,lo,lat or distance")
      x=dist/1000.
      xlab="Distance along section[km]"

   # Loop over archive files
   figure = matplotlib.pyplot.figure()
   ax=figure.add_subplot(111)
   pos = ax.get_position()
   for fcnt,myfile0 in enumerate(files) :

      # Remove [ab] ending if present
      m=re.match("(.*)\.[ab]",myfile0)
      if m :
         myfile=m.group(1)
      else :
         myfile=myfile0

      # Add more filetypes if needed. By def we assume archive
      if filetype == "archive" :
         i_abfile = abfile.ABFileArchv(myfile,"r")
      elif filetype == "restart" :
         i_abfile = abfile.ABFileRestart(myfile,"r",idm=gfile.idm,jdm=gfile.jdm)
      else :
         raise NotImplementedError,"Filetype %s not implemented"%filetype

      # kdm assumed to be max level in ab file
      kdm=max(i_abfile.fieldlevels)

      # Set up interface and daat arrays
      intfsec=numpy.zeros((kdm+1,I.size))
      datasec=numpy.zeros((kdm+1,I.size))

      # Loop over layers in file. 
      logger.info("File %s"%(myfile))
      for k in range(kdm) :
         logger.debug("File %s, layer %03d/%03d"%(myfile,k,kdm))

         # Get 2D fields
         dp2d=i_abfile.read_field(dpname,k+1)
         data2d=i_abfile.read_field(variable,k+1)
         dp2d=numpy.ma.filled(dp2d,0.)/modeltools.hycom.onem
         data2d=numpy.ma.filled(data2d,1e30)

         # Place data into section arrays
         intfsec[k+1,:] = intfsec[k,:] + dp2d[J,I]
         if k==0 : datasec[k,:] = data2d[J,I]
         datasec[k+1,:] = data2d[J,I]

      i_maxd=numpy.argmax(numpy.abs(intfsec[kdm,:]))
      #print i_maxd
      
      # Set up section plot
      #datasec = numpy.ma.masked_where(datasec==1e30,datasec)
      datasec = numpy.ma.masked_where(datasec>0.5*1e30,datasec)
      #print datasec.min(),datasec.max()
      #figure = matplotlib.pyplot.figure()
      #ax=figure.add_subplot(111)
      #P=ax.pcolormesh(dist/1000.,-intfsec,datasec)
      P=ax.pcolormesh(x,-intfsec,datasec,cmap="jet")
      if clim is not None : P.set_clim(clim)

      # Plot layer interfaces
      for k in range(1,kdm+1) :
         if k%10 == 0 : 
            PL=ax.plot(x,-intfsec[k,:],"--",color="k",lw=.5)
         elif k%5 == 0 : 
            PL=ax.plot(x,-intfsec[k,:],"--",color="k",lw=.5)
         else :
            PL=ax.plot(x,-intfsec[k,:],"--",color=".5",lw=.5)

         textx = x[i_maxd]
         texty = -0.5*(intfsec[k-1,i_maxd] + intfsec[k,i_maxd])
         ax.text(textx,texty,str(k),verticalalignment="center",horizontalalignment="center",fontsize=6)
      cb=ax.figure.colorbar(P)
      ax.set_title(myfile)
      ax.set_ylabel(variable)
      ax.set_xlabel(xlab)
      #ax.set_position(pos)
      #matplotlib.pyplot.tight_layout()

      # Print in different y-lims 
      suff=os.path.basename(myfile)
      if sectionid : suff=suff+"_"+sectionid
      figure.canvas.print_figure("sec_%s_full_%s.png"%(variable,suff),dpi=dpi)
      ax.set_ylim(-1000,0)
      figure.canvas.print_figure("sec_%s_1000m_%s.png"%(variable,suff),dpi=dpi)
      ax.set_ylim(-300,0)
      figure.canvas.print_figure("sec_%s_300m_%s.png"%(variable,suff),dpi=dpi)

      # Close input file
      i_abfile.close()

      #
      ax.clear()
      cb.remove()
Beispiel #53
0
width = 28000000
height = 28000000

lon_0 = -105
lat_0 = 40

m = Basemap(width=width,
            height=height,
            projection='aeqd',
            lat_0=lat_0,
            lon_0=lon_0)

# fill background.
m.drawmapboundary(fill_color='aqua')

# draw coasts and fill continents.
m.drawcoastlines(linewidth=0.5)
m.fillcontinents(color='coral', lake_color='red')

# 20 degree graticule.
m.drawparallels(np.arange(-80, 81, 20))
m.drawmeridians(np.arange(-180, 180, 20))

# draw a black dot at the center.
xpt, ypt = m(lon_0, lat_0)

m.plot([xpt], [ypt], 'ko')

# draw the title.
plt.title('Mi casa')
plt.show()
Beispiel #54
0
m.drawparallels(np.arange(20, 71, 10), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-120, -40, 10), labels=[0, 0, 0, 1])
# plot state boundaries from shapefile using ogr.
g = ogr.Open("st99_d00.shp")
L = g.GetLayer(0)  # data is in 1st layer.
for feat in L:  # iterate over features in layer
    geo = feat.GetGeometryRef()
    # iterate over geometries.
    for count in range(geo.GetGeometryCount()):
        geom = geo.GetGeometryRef(count)
        if not geom.GetGeometryCount():  # just one geometry.
            # get lon,lat points
            lons = [geom.GetX(i) for i in range(geom.GetPointCount())]
            lats = [geom.GetY(i) for i in range(geom.GetPointCount())]
            # convert to map projection coords.
            x, y = m(lons, lats)
            # plot on map.
            m.plot(x, y, 'k')
        else:  # iterate over nested geometries.
            for cnt in range(geom.GetGeometryCount()):
                g = geom.GetGeometryRef(cnt)
                lons = [g.GetX(i) for i in range(g.GetPointCount())]
                lats = [g.GetY(i) for i in range(g.GetPointCount())]
                x, y = m(lons, lats)
                m.plot(x, y, 'k')
# draw colorbar.
m.colorbar(im)
plt.title(gd.GetDescription() + ' with state boundaries from ' + g.GetName(),
          y=1.05)
plt.show()
Beispiel #55
0
                     llcrnrlat=41.6,
                     urcrnrlon=18,
                     urcrnrlat=48.7)

    print("Drawing detail")
    my_map.drawcoastlines()
    my_map.drawcountries()
    my_map.fillcontinents(color='#29ba52', lake_color='#29a9ba')
    my_map.drawmapboundary(fill_color='#29a9ba')

    print("Plotting flights")
    for item in fls(user):
        lats = item[0]
        longs = item[1]
        x, y = my_map(longs, lats)
        my_map.plot(x, y, 'b-', markersize=0, linewidth=2)

    print("Plotting airports")
    apla, arplo, names = aps()
    for _, (la, lo, na) in enumerate(zip(apla, arplo, names)):
        x, y = my_map(lo, la)
        my_map.plot(x, y, 'ro', markersize=12)
        plt.text(x + 5000,
                 y - 32000,
                 na,
                 fontsize=12,
                 bbox=dict(facecolor='white', alpha=0.5, pad=1))

    plt.savefig(f"img/{username}.png", bbox_inches="tight", pad_inches=0.1)
    plt.clf()
Beispiel #56
0
        im = m.pcolormesh(lon,
                          lat,
                          species,
                          vmin=c_min,
                          vmax=c_max,
                          latlon=True,
                          cmap='Greys',
                          shading='gouraud')

        flow_y = r_r[k]
        flow_x = r_r[k + 3]
        for p in range(len(flow_x)):
            x = flow_x[p]
            y = flow_y[p]
            if len(x) > 6:
                m.plot(x, y, 'r-')  #, latlon=True)

        flow_y = a_r[k]
        flow_x = a_r[k + 3]
        for p in range(len(flow_x)):
            x = flow_x[p]
            y = flow_y[p]
            if len(x) > 6:
                m.plot(x, y, 'b-')  #, latlon=True)

        plt.annotate('{0}'.format(label[k]),
                     xy=(0.03 * m.urcrnrx, 0.03 * m.urcrnry),
                     fontsize=7)
        m.drawcoastlines()
        m.drawstates()
        m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=7)
Beispiel #57
0
            lat_2=55,
            lat_0=50,
            lon_0=-107.)
# draw a boundary around the map, fill the background.
# this background will end up being the ocean color, since
# the continents will be drawn on top.
m.drawmapboundary(fill_color='aqua')
# fill continents, set lake color same as ocean color.
m.fillcontinents(color='coral', lake_color='aqua')
# draw parallels and meridians.
# label parallels on right and top
# meridians on bottom and left
parallels = np.arange(0., 81, 10.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels, labels=[False, True, True, False])
meridians = np.arange(10., 351., 20.)
m.drawmeridians(meridians, labels=[True, False, False, True])
# plot blue dot on Boulder, colorado and label it as such.
lon, lat = -104.237, 40.125  # Location of Boulder
# convert to map projection coords.
# Note that lon,lat can be scalars, lists or numpy arrays.
xpt, ypt = m(lon, lat)
# convert back to lat/lon
lonpt, latpt = m(xpt, ypt, inverse=True)
m.plot(xpt, ypt, 'bo')  # plot a blue dot there
# put some text next to the dot, offset a little bit
# (the offset is in map projection coordinates)
plt.text(xpt + 100000, ypt + 100000,
         'Boulder (%5.1fW,%3.1fN)' % (lonpt, latpt))
plt.savefig('plotboulder.png')
Beispiel #58
0
    #    vlats = xlat[:1, 14:15, :].squeeze()[0]
    #    ##-38.5025 -13.0076
    #    u, v = m(ulons, vlats)
    #    m.plot(u, v, 'bo', markersize=4, color='white')
    #
    #    ulons = xlong[:1, :,25:26].squeeze()[0]
    #    vlats = xlat[:1, 14:15, :].squeeze()[0]
    #    ##-38.5025 -13.0076
    #    u, v = m(ulons, vlats)
    #    m.plot(u, v, 'bo', markersize=4, color='white')

    ulons = xlong[:1, :, 24:25].squeeze()[0]
    vlats = xlat[:1, 16:17, :].squeeze()[0]
    ##-38.5025 -13.0076
    u, v = m(ulons, vlats)
    m.plot(u, v, 'bo', markersize=4, color='white')

    ulons = xlong[:1, :, 25:26].squeeze()[0]
    vlats = xlat[:1, 16:17, :].squeeze()[0]
    ##-38.5025 -13.0076
    u, v = m(ulons, vlats)
    m.plot(u, v, 'bo', markersize=4, color='white')

    ulons = xlong[:1, :, 24:25].squeeze()[0]
    vlats = xlat[:1, 14:15, :].squeeze()[0]
    ##-38.5025 -13.0076
    u, v = m(ulons, vlats)
    m.plot(u, v, 'bo', markersize=4, color='white')

    ulons = xlong[:1, :, 25:26].squeeze()[0]
    vlats = xlat[:1, 14:15, :].squeeze()[0]
                        bathymetrie_array,
                        levels,
                        cmap="Blues",
                        latlon=True)
cntr = map_ax.contour(xx,
                      yy,
                      bathymetrie_array,
                      levels,
                      colors="black",
                      latlon=True)

cbar = map_ax.colorbar(cntrf, location='right', pad='5%')
cbar.ax.invert_yaxis()
cbar.set_label("depth [m]")

map_ax.plot(emb217_flach[1], emb217_flach[0], ".", color="red", latlon=True)
map_ax.plot(emb217_tief[1], emb217_tief[0], ".", color="green", latlon=True)

curr_axis.set_xlim(20.58, 20.65)
curr_axis.set_ylim(YLLCORNER, 57.34)

curr_axis.set_xlabel("longitude")
curr_axis.set_ylabel("latitude")

oxygen_axis.plot(PME_utc_flach,
                 saturation_flach[PME_index_tief, :],
                 color="tab:red")
oxygen_axis.plot(PME_utc_tief,
                 saturation_tief[PME_index_tief, :],
                 color="tab:green")
#oxygen_axis.plot(utc_tief,west_east_tief[:],color = "tab:red")
Beispiel #60
0
def draw_city_map(data_city, headcount_scale, title):

    data_location = pd.read_csv('../city_locations.csv')
    data_location = data_location.set_index('city')

    #cities = []
    scale = 5

    locations = [(116.407526, 39.90403), (120, 30)]
    #fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
    plt.rcParams['figure.figsize'] = [13, 13]
    #plt.figure(figsize = (10,5))
    fig, ax = plt.subplots()
    fig.title = title
    fig.figsize = (10, 5)
    fig.dpi = 80
    cn_map= Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, \
               projection='lcc', lat_1=33, lat_2=45, lon_0=100) # ‘lcc'将投影方式设置为兰伯特投影

    # load the shapefile, use the name 'states'
    cn_map.readshapefile(r'D:/data/basemap/gadm36_CHN_shp/gadm36_CHN_1',
                         name='china',
                         drawbounds=True,
                         color='gray')
    cn_map.readshapefile(r'D:/data/basemap/gadm36_TWN_shp/gadm36_TWN_1',
                         name='taiwan',
                         drawbounds=True,
                         color='gray')
    #geolocator = Nominatim(user_agent="my-application")

    salary_min = data_city['平均工资'].min()
    salary_max = data_city['平均工资'].max()
    salary_middle = (salary_min + salary_max) / 2
    salary_scale = salary_max - salary_min

    for index, row in data_city.iterrows():
        city = row['city']

        longitude = data_location.loc[city, 'longitude']
        latitude = data_location.loc[city, 'latitude']
        salary = row['平均工资']
        headcount = row['招聘人数']
        #color
        color_red = 0
        color_green = 0
        color_blue = 0
        if salary > salary_middle:
            color_red = 255  #int((salary - salary_middle) / (salary_scale/2)*255)
            color_green = int((salary_max - salary) / (salary_scale / 2) * 255)
        else:
            color_blue = int(
                (salary_middle - salary) / (salary_scale / 2) * 255)
            color_green = int((salary - salary_min) / (salary_scale / 2) * 255)
            color_red = int((salary - salary_min) / (salary_scale / 2) * 255)

        color = '#{:02x}{:02x}{:02x}'.format(color_red, color_green,
                                             color_blue)

        x, y = cn_map(longitude, latitude)
        cn_map.plot(x,
                    y,
                    marker='o',
                    color=color,
                    markersize=int(math.sqrt(headcount / headcount_scale)) + 8)
        #ax.annotate(city, (x,y), xytext=(5, 5), textcoords='offset points', fontsize=15)
        #"{}{:.0f}".format(city_cn, salary)
        #ax.text(x+5, y+5,city , fontweight='bold', fontsize=int(headcount/2500+12))
        fontsize = int(math.sqrt(headcount / headcount_scale)) + 13
        if city == '杭州':
            x = x - 400000
            y = y + 10000
        elif city == '广州':
            x = x - 400000
            y = y + 10000
        elif city == '合肥':
            x = x - 300000
            y = y + 10000
        elif city == '深圳':
            y = y - 100000
        elif city == '南京':
            x = x - 100000
        elif city == '天津':
            y = y - 50000
        elif city == '上海':
            x = x + 50000
        elif city == '武汉':
            y = y - 50000
        elif city == '厦门':
            pass
        elif city == '福州':
            pass
        elif city == '苏州':
            y = y - 100000
            pass
        elif city == '宁波':
            y = y - 100000
            pass

        ax.text(x,
                y,
                "{}{:.0f}k".format(city, np.round(salary / 1000)),
                fontweight='bold',
                fontsize=fontsize,
                bbox={
                    'facecolor': color,
                    'alpha': 0.3,
                    'pad': 0
                })
    ax.text(1100000,
            1077845,
            "https://github.com/juwikuang/china_job_survey".format(
                city, np.round(salary / 1000)),
            fontweight='bold',
            color='#999999',
            fontsize=20,
            bbox={
                'facecolor': '#eeeeee',
                'alpha': 0.4,
                'pad': 0
            })
    ax.text(205805,
            107845,
            "https://github.com/juwikuang/china_job_survey".format(
                city, np.round(salary / 1000)),
            fontweight='bold',
            color='#999999',
            fontsize=20,
            bbox={
                'facecolor': '#eeeeee',
                'alpha': 0.4,
                'pad': 0
            })
    ax.text(805805,
            4007845,
            title.format(city, np.round(salary / 1000)),
            fontweight='bold',
            color='#111111',
            fontsize=25)
    ax.text(805805,
            3807845,
            "(城市大小代表招聘数量,颜色代表工资,红色最高,黄色次之,蓝最少)",
            fontweight='bold',
            color='#111111',
            fontsize=13)
    #cn_map.drawcoastlines() #绘制海岸线
    #cn_map.drawcountries(linewidth=1.5) #绘制国家边界线
    plt.show()