Example #1
0
def analysis(filename):
    with open(filename, 'r') as f:
        friends = json.load(f)
        df = pandas.DataFrame(friends)
        df.to_csv(filename.replace('json','csv'),sep='\t',encoding='utf-8')
#        print(df.groupby(['City','Sex']).value_counts())
        print(df['City'].value_counts()[:30])
#        print df
#        for friend in friends:
#            print("%s: %s" % (friend.get('NickName'),friend.get('Sex')))

# Create a map on which to draw.  We're using a mercator projection, and showing the whole world.
	m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')
# Draw coastlines, and the edges of the map.
	m.drawcoastlines()
	m.drawmapboundary()
# Convert latitude and longitude to x and y coordinates
        loc = convertgeo(df['City'])
        print loc
	x, y = m(loc[0], loc[1])
#                list(airports["longitude"].astype(float)), list(airports["latitude"].astype(float)))
# Use matplotlib to draw the points onto the map.
	m.scatter(x,y,1,marker='o',color='red')
# Show the plot.
	plt.show()
    def Map(self):
        m = Basemap(projection='cyl',  # stere, tmerc, lcc
                    lat_0=39.828127, lon_0=-98.579404,
                    urcrnrlon=-62.208289, urcrnrlat=51.342619,
                    llcrnrlon=-128.936426, llcrnrlat=19.06875)

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

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

        m.drawstates()
        m.drawcountries()

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

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

        m.scatter(lon, lat, latlon=True, c=np.random.rand(3))
        #m.pcolor(lon, lat, latlon=True)
        plt.title('United States Fair Market Rent')  # add a title
        plt.show()
Example #3
0
def el_plot(data, Map=False, show=True):
    """
    Plot the elevation for the region from the last time series
    
    :Parameters:
        **data** -- the standard python data dictionary
        
        **Map** -- {True, False} (optional): Optional argument.  If True,
            the elevation will be plotted on a map.  
    """
    trigrid = data['trigrid']
    plt.gca().set_aspect('equal')
    plt.tripcolor(trigrid, data['zeta'][-1,:])
    plt.colorbar()
    plt.title("Elevation")
    if Map:
        #we set the corners of where the map should show up
        llcrnrlon, urcrnrlon = plt.xlim()
        llcrnrlat, urcrnrlat = plt.ylim()
        #we construct the map.  Note that resolution serves to increase
        #or decrease the detail in the coastline.  Currently set to 
        #'i' for 'intermediate'
        m = Basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, \
            resolution='i', suppress_ticks=False)
        #set color for continents.  Default is grey.
        m.fillcontinents(color='ForestGreen')
        m.drawmapboundary()
        m.drawcoastlines()
    if show:
        plt.show()
Example #4
0
def example_1():
    
    orig_file  = '/tmp/comp-tempo/20101206-EUR-L2P_GHRSST-SSTsubskin-AVHRR_METOP_A-eumetsat_sstmgr_metop02_20101206_000403-v01.7-fv01.0.nc'
    
    orig_dset = Dataset(orig_file, 'a')
    
    o_lat = orig_dset.variables['lat'][:].ravel()
    o_lon = orig_dset.variables['lon'][:].ravel()
    
    print(np.mean(o_lon))
    
    
    
    # lon_0 is the central longitude of the projection.
    # resolution = 'l' means use low resolution coastlines.
    # optional parameter 'satellite_height' may be used to
    # specify height of orbit above earth (default 35,786 km).
    m = Basemap(projection='geos',lon_0=133,resolution='l')
    m.drawcoastlines()
    m.fillcontinents(color='coral',lake_color='aqua')
    # draw parallels and meridians.
    m.drawparallels(np.arange(-90.,120.,30.))
    m.drawmeridians(np.arange(0.,420.,60.))
    m.drawmapboundary(fill_color='aqua')
    
    x, y = m(o_lat[0:100] , o_lon[0:100])
    
    #m.plot(x, y)
    
    plt.title("Full Disk Geostationary Projection")
    #plt.savefig('geos_full.png')
    plt.show()
def draw_basic_map_of_toronto(axis):
    """Draw a basic map of Toronto.

    :param axis: where to draw the map
    :returns: Basemap with Toronto
    """
    # These are the latitudes of the City of Toronto.
    # (Fiona can be better to find them, e.g., from the 'icitw_wgs84' Shapefile
    #  below.)

    low_left_corner_longitude = -79.75
    low_left_corner_latitude = 43.40
    up_right_corner_longitude = -79.10
    up_right_corner_latitude = 43.95

    to_map = Basemap(
        llcrnrlon=low_left_corner_longitude,
        llcrnrlat=low_left_corner_latitude,
        urcrnrlon=up_right_corner_longitude,
        urcrnrlat=up_right_corner_latitude,
        ellps="WGS84",
        resolution="h",
        area_thresh=0.1,
        ax=axis,
    )

    to_map.drawmapboundary(fill_color="white")
    return to_map
Example #6
0
    def WorkBook_plotPrisons(self, coords):
        lons = coords[0]
        lats = coords[1]

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

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

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

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

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

        new_img = Image.blend(background, overlay, 0.5)
        new_img.save("SocioEconomic_Prison.png","PNG")
Example #7
0
def plot_map_twts(twts, title='default title'):
    """
    Given an iterable of 'clean' tweets, make a dot map over North America.
    """
    fig1 = plt.figure()
    ax = fig1.add_subplot(111)
    m = Basemap(projection='merc',
        resolution = 'l',
        llcrnrlon=-136.0, llcrnrlat=24.0,
        urcrnrlon=-67.0, urcrnrlat=60.0,
        ax=ax)

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

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

    m.plot(x, y, 'bo', markersize=5)
    plt.title(title)
    plt.show()
Example #8
0
File: pnts.py Project: jdbowman/sim
def plot_pnts(source, ra_0, dec_0, FOV='fullsky', grid_size=15.):
    ra, dec = np.genfromtxt(source, usecols=(0, 1), unpack=True)
    ra *= 15.
    sky = Basemap(projection='ortho', lon_0=-ra_0, lat_0=dec_0, celestial=True)
    if FOV == 'fullsky':
        sky.drawmeridians(np.arange(0., 360., grid_size))
        sky.drawparallels(np.arange(90, -90, -grid_size))
        sky.drawmapboundary(fill_color='White')
        catx, caty = sky(ra, dec)
        sky.scatter(catx, caty, 3, marker='o', color='Black')
    elif isinstance(FOV, float):
        format_label = lambda deg: '{0:2.0f}h{1:2.0f}m'\
            .format(np.floor(deg / 15.), np.remainder(deg, 15.) * 60. / 15.)
        cnreq = np.array([[ra_0 + FOV / 2., dec_0 - FOV / 2.],
                         [ra_0 - FOV / 2., dec_0 + FOV / 2.]])
        cnrxy = np.array(sky(cnreq[:, 0], cnreq[:, 1])).T
        cenxy = np.array(sky(ra_0, dec_0))
        m = Basemap(projection='ortho', lon_0=-ra_0, lat_0=dec_0,
                    celestial=True, llcrnrx=cnrxy[0, 0]-cenxy[0],
                    llcrnry=cnrxy[0, 1]-cenxy[1], urcrnrx=cnrxy[1, 0]-cenxy[0],
                    urcrnry=cnrxy[1, 1]-cenxy[1])
        m.drawmeridians(np.arange(cnreq[0, 0], cnreq[1, 0], -grid_size),
                        labels=[0, 0, 0, 1], fmt=format_label)
        m.drawparallels(np.arange(cnreq[0, 1], cnreq[1, 1], grid_size),
                        labels=[1, 0, 0, 0])
        m.drawmapboundary(fill_color='White')
        catx, caty = m(ra, dec)
        m.scatter(catx, caty, 3, marker='o', color='Black')
Example #9
0
File: bma.py Project: xe1gyq/EekMex
def mapTut():

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


    # Houston, Texas

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

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

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


    
    plt.title("Geo Plotting")
    plt.show()
Example #10
0
def ResearchRegion_surface():
    """
    在地图上画出柱表面混合比图
    :return:
    """

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

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

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

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

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

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

    cmap = cm.RdBu_r

    im = m.pcolormesh(lns,lts,data, vmin = data[~isnan(data)].min(), \
    vmax=data[~isnan(data)].max(), cmap = cmap, latlon=True)
    cb = m.colorbar(im,'bottom', size="5%", pad="2%")
    if showplot:
        plt.show()
        return
    return fig, ax, m
Example #12
0
def plot_world_sst():
    # Read some NetCDF data
    import netCDF4 as nc
    
    ostia = nc.Dataset('ostia.nc')
    tmp = ostia.variables['analysed_sst'][0]
    ice = ostia.variables['sea_ice_fraction'][0]
    lon = ostia.variables['lon'][:]
    lat = ostia.variables['lat'][:]

    from mpl_toolkits.basemap import Basemap

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

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

    # Plot the data
    map.imshow(image);

    plt.show()
Example #13
0
def bb_map(lons, lats, projection='merc', resolution='i', drawparallels=True, drawmeridians=True, ax=plt.gca()):
	"""
	USAGE
	-----
	m = bb_map(lons, lats, **kwargs)

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

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

	plt.ioff() # Avoid showing the figure.
	m.fillcontinents(color='0.9', zorder=9)
	m.drawcoastlines(zorder=10)
	m.drawstates(zorder=10)
	m.drawcountries(linewidth=2.0, zorder=10)
	m.drawmapboundary(zorder=9999)
	if drawmeridians:
		m.drawmeridians(np.arange(np.floor(lonmin), np.ceil(lonmax), 1), linewidth=0.15, labels=[1, 0, 1, 0], zorder=12)
	if drawparallels:
		m.drawparallels(np.arange(np.floor(latmin), np.ceil(latmax), 1), linewidth=0.15, labels=[1, 0, 0, 0], zorder=12)
	plt.ion()
	return m
Example #14
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
Example #15
0
def map_interiorAK(
    width=1800000,
    height=1200000,
    water='lightskyblue',
    earth='snow',
    resolution='i'):
    """
    Albers Equal Area map of interior Alaska, with some overridable presets.
    """
    bmap = Basemap(
        width=width,
        height=height,
        resolution=resolution,
        projection='aea',
        lat_1=55., lat_2=75., lat_0=65., lon_0=-150.)
    bmap.drawcoastlines()
    bmap.drawrivers(color=water)
    bmap.drawcountries()
    bmap.fillcontinents(lake_color=water, color=earth)
    # labels = [left,right,top,bottom]
    bmap.drawmeridians(
        np.arange(-180, 180, 10), labels=[False, False, False, 1])
    bmap.drawparallels(
        np.arange(0, 80, 5), labels=[1, 1, False, False])
    bmap.drawmapboundary(fill_color=water)
    return bmap
Example #16
0
def map_trace(tr,ax='None',showpath=True,showplot=True,Lat_0=0.0,Lon_0=60.0):
   from mpl_toolkits.basemap import Basemap

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

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

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

   if showplot == True:
      plt.show()
   else:
      return m
Example #17
0
def sstMap(nipaPhase, phase = 'allyears', field = 'sst', fig = None, ax = None, monte = False):
	from numpy import linspace
	if fig == None:
		fig = plt.figure()
		ax = fig.add_subplot(111)
	m = Basemap(ax = ax, projection = 'robin', lon_0 = 270, resolution = 'i')
	m.drawmapboundary(fill_color='aqua')
	m.drawcoastlines(linewidth = 0.25)
	m.drawcountries()
	m.fillcontinents(color='green',lake_color='aqua')
	parallels = np.linspace(m.llcrnrlat, m.urcrnrlat, 4)
	meridians = np.linspace(m.llcrnrlon, m.urcrnrlon, 4)
	m.drawparallels(parallels, linewidth = 1, labels = [0,0,0,0])
	m.drawmeridians(meridians, linewidth = 1, labels = [0,0,0,0])

	lons = nipaPhase.lon[field]
	lats = nipaPhase.lat[field]
	if monte:
		data = nipaPhase.monte_grid[phase]
		levels = linspace(0, data.max(), data.max())
		cmap = cm.Reds
	else:
		data = nipaPhase.corr_grid[field][phase]
		levels = linspace(-0.8,0.8,9)
		cmap = cm.RdBu
	lons, lats = np.meshgrid(lons,lats)
	im1 = m.pcolormesh(lons,lats,data, vmin = np.min(levels), \
		vmax=np.max(levels), cmap = cmap, latlon=True)
	cb = m.colorbar(im1,'bottom', size="5%", pad="2%")
	ax.set_title('%s, %s' % (phase, field))
	return fig, ax, m
Example #18
0
def plot_us(lats, lons, save_name=None):
    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)
    big_map = Basemap(resolution='h',
                      lat_0=36, lon_0=-107.5,
                      llcrnrlat=32, llcrnrlon=-125,
                      urcrnrlat=43, urcrnrlon=-110)
    big_map.drawcoastlines()
    big_map.drawstates()
    big_map.drawcountries()
    big_map.drawmapboundary(fill_color='#7777ff')
    big_map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0)
    x, y = big_map(lons, lats)
    big_map.plot(x[0], y[0], 'ro', markersize=2)

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

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

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

    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
    if save_name: 
        fig.savefig(save_name)
def plot_map(lons, lats, c, legend_label, projection='mill',
             llcrnrlat=-80, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='i'):
    
    ''' Optional Arguments: projection - map projection, default set as 'mill'
                            llcrnrlat - lower left corner latitude value, default is -80
                            urcrnrlat - upper right corner latitude value, default is 90
                            llcrnrlon - lower left corner longitude value, default is -180
                            urcrnrlon - upper right corner longitude value, default is 180
                            resolution - the resolution of the plot, default is 'i'
                            
        Required Arguments: lons - list of longitude values to be plotted
                            lats - list of latitude values to be plotted
                            c - the color of the points to be plotted
                            legend_label - how this set of points will be labeled on the legend
                            
        Returns:            m - a basemap object defined by input bounds with input points included '''
    
    # Creates a basic plot of a series of lat,lon points over a defined region
    m = Basemap(projection=projection, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,
                llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution=resolution)
    m.drawcoastlines()
    m.drawmapboundary()
    m.drawcountries()
    m.etopo()
    m.drawmeridians(np.arange(llcrnrlon, urcrnrlon, 5), labels=[0,0,0,1], fontsize=10)
    m.drawparallels(np.arange(llcrnrlat, urcrnrlat, 5), labels=[1,0,0,0], fontsize=10)
    x,y = m(lons, lats)
    m.scatter(x, y, color=c, label=legend_label, marker='o', edgecolor='none', s=10)
    return m
def displayWindMapPlot(vdata,udata, lons, lats,):
    """ TODO add a docstring! """
    #plt.clf()
    #pc = plt.contourf(lons, lats, data, 20)
    #plt.colorbar(pc, orientation='horizontal')
    #plt.title(title)
    #plt.xlabel("longitude (degrees east)")
    #plt.ylabel("latitude (degrees north)")
    #plt.show()
    fig, ax = plt.subplots()
    # Do the plot code
    # make orthographic basemap.
    m = Basemap(projection='cyl',llcrnrlat=-40,urcrnrlat=0,\
            llcrnrlon=-20,urcrnrlon=60,resolution='l')

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

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

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

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

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

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

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

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

        my_map.drawmeridians(np.arange(0, 360, 30))
        my_map.drawparallels(np.arange(-90, 90, 30))
        #m.hexbin(x1,y1, C=sic[beam],gridsize=len(sic[beam]),cmap=plt.cm.jet)
    
    
        plt.gcf().set_size_inches(18,10)
        plt.show()    
Example #23
0
def draw_map_with_labels(labels, map_number):
    """
    Draws a map once the labels substituting country names are given
    """
    min_lon = -20.
    max_lon = 49.
    min_lat = 32.
    max_lat = 60.
    europe = Basemap(
        resolution='l',
        projection='aea',
        lon_0=0,
        lat_0=40,
        llcrnrlat=min_lat,
        urcrnrlat=max_lat,
        llcrnrlon=min_lon,
        urcrnrlon=max_lon,
        lat_ts=(min_lon+max_lon)/2)
    europe.drawcountries(linewidth=0.2, color=COUNTRY_COLOR)
    europe.drawmapboundary(linewidth=0.5, fill_color=SEA_COLOR)
    europe.fillcontinents(color=LAND_COLOR, lake_color=SEA_COLOR)
    europe.drawcoastlines(linewidth=0.2)
    for label in labels:
        lon, lat = europe(label[1], label[2])
        plt.text(lon, lat, label[0],
                 color=TEXT_COLOR, fontweight='heavy', fontstyle='oblique',
                 ha='center', clip_on=True)
    plt.tight_layout()
    logging.info('Saving into file: languages_{}.png'.format(map_number + 1))
    plt.savefig('languages_{}.png'.format(map_number + 1))
def onpress(event):
    if event.button != 1:
        return
    x, y = event.x, event.y
    coord_lat = 40
    coord_lon = -75
    zoom_map = Basemap(projection='mill',
                     llcrnrlat=coord_lat,
                     llcrnrlon=coord_lon,
                     urcrnrlat=43,
                     urcrnrlon=-69.5,
                     resolution='c')
    zoom_map.drawcoastlines()
    zoom_map.drawcountries()
    zoom_map.drawmapboundary()
    zoom_map.drawstates()

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

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

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

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

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

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

	except ValueError as err:
		print "Value Error: " + str(err)
Example #28
0
def plot_hmap_ortho(h, cmap='jet', mode='log', mx=None, drng=None, 
        res=0.25, verbose=False):
    m = Basemap(projection='ortho',lat_0=90,lon_0=180,rsphere=1.)
    if verbose:
        print 'SCHEME:', h.scheme()
        print 'NSIDE:', h.nside()
    lons,lats,x,y = m.makegrid(360/res,180/res, returnxy=True)
    lons = 360 - lons
    lats *= a.img.deg2rad; lons *= a.img.deg2rad
    y,x,z = a.coord.radec2eq(n.array([lons.flatten(), lats.flatten()]))
    ax,ay,az = a.coord.latlong2xyz(n.array([0,0]))
    data = h[x,y,z]
    data.shape = lats.shape
    data /= h[0,0,1]
    #data = data**2 # only if a voltage beam
    data = data_mode(data, mode)
    m.drawmapboundary()
    m.drawmeridians(n.arange(0, 360, 30))
    m.drawparallels(n.arange(0, 90, 10))
    if mx is None: mx = data.max()
    if drng is None:
        mn = data.min()
    #    if min < (max - 10): min = max-10
    else: mn = mx - drng
    step = (mx - mn) / 10
    levels = n.arange(mn-step, mx+step, step)
    return m.imshow(data, vmax=mx, vmin=mn, cmap=cmap)
Example #29
0
def example_2():
    
    # retrieve data
    dir  = "/homespace/gaubert/viirs/Mband-SDR"
    geo_file     = h5py.File("%s/%s" %(dir,"GMODO_npp_d20030125_t0847056_e0848301_b00015_c20090513182937526121_gisf_pop.h5"))
    
    lats = geo_file['All_Data']['VIIRS-MOD-GEO_All']['Latitude'][:]
    lons = geo_file['All_Data']['VIIRS-MOD-GEO_All']['Longitude'][:]
    # draw map with markers for float locations
    #m = Basemap(projection='hammer',lon_0=180)
    lon_ref = lons[0][0]-lons[-1][-1]/2
    lat_ref = 10
    #m = Basemap(projection='ortho',lat_0=lat_ref,lon_0=lon_ref,resolution='l')
    m = Basemap(projection='nsper',lat_0=lat_ref,lon_0=lon_ref,satellite_height=2000*1000,resolution='l')
    
    #x, y = m(lons[0:10],lats[0:10])
    x,y  = m(lons,lats)
    
    #m.drawcoastlines()
    
    m.drawmapboundary(fill_color='#99ffff')
    m.fillcontinents(color='#cc9966',lake_color='#99ffff')
    m.scatter(x,y,s = 1 ,color='k')
    #m.drawgreatcircle(lons[0][0],lats[0][0],lons[0][-1],lats[0][-1],linewidth=2,color='b')
    #m.drawgreatcircle(lons[-1][0],lats[0][0],lons[-1][-1],lats[0][-1],linewidth=2,color='b')
    
    plt.title('Locations of %s ARGO floats active between %s and %s' %\
            (len(lats),'2002', '2003'))
    plt.savefig('/tmp/plotargo.png')
Example #30
0
    def GDELT_maplot(self, point_counts, centro_lat, centro_lon, llat, llon, ulat, ulon): #,centro_lat,centro_lon,llat,llon,ulat,ulon):

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

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

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

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

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

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

        plt.show()
Example #31
0
    plt.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Avant Garde']})

    ### Set limits for contours and colorbars
    limit = np.arange(-6, 6.1, 0.5)
    barlim = np.arange(-6, 7, 2)
    cmap = cmocean.cm.balance
    label = r'\textbf{Temperature [$^{\circ}$C] Change [1991-2020]}'

    fig = plt.figure(figsize=(9, 4))
    ###########################################################################
    ###########################################################################
    ###########################################################################
    var = var1
    ax1 = plt.subplot(1, 2, 1)
    m = Basemap(projection='moll', lon_0=0, resolution='l', area_thresh=10000)
    circle = m.drawmapboundary(fill_color='k')
    circle.set_clip_on(False)
    m.drawcoastlines(color='dimgrey', linewidth=0.35)

    var, lons_cyclic = addcyclic(var, lon)
    var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False)
    lon2d, lat2d = np.meshgrid(lons_cyclic, lat)
    x, y = m(lon2d, lat2d)

    circle = m.drawmapboundary(fill_color='white',
                               color='dimgrey',
                               linewidth=0.7)
    circle.set_clip_on(False)

    cs = m.contourf(x, y, var, limit, extend='both')
Example #32
0
#map = Basemap(projection ='cyl', llcrnrlat=-62, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')
map = Basemap(projection='cyl',
              llcrnrlat=-15,
              urcrnrlat=40,
              llcrnrlon=55,
              urcrnrlon=145,
              resolution='c')
x, y = map(lona11, lat)

aa = ((ma1 / gridarea * 10000) -
      (ma1i / gridarea * 10000)) / (ma1 / gridarea * 10000) * 100
aa = ma.masked_where(aa == 0.0, aa)

map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
cs1 = map.pcolormesh(x, y, aa, cmap=cmap, norm=norm)

plt.axis('off')
cbar = map.colorbar(cs1,
                    location='right',
                    size="5%",
                    pad="2%",
                    ticks=bounds,
                    extend='both')
cbar.ax.tick_params(labelsize=16)

ax1 = fig.add_subplot(422)
map = Basemap(projection='cyl',
              llcrnrlat=-15,
              urcrnrlat=40,
Example #33
0
    state_color = '#999999'
    meridian_color = '#eaeaea'
    marker_fill_color = '#df2d2d'
    marker_edge_color = 'None'

    fig = plt.figure(figsize=(20, 10))
    ax = fig.add_subplot(111, facecolor='#ffffff', frame_on=False)
    ax.set_title(map_title, fontsize=18, color='#333333')

    m = Basemap(projection='mill',
                resolution='i',
                llcrnrlat=14,
                urcrnrlat=55,
                llcrnrlon=70,
                urcrnrlon=140)
    m.drawmapboundary(color=border_color, fill_color=water_color)
    m.drawcoastlines(color=coastline_color)
    m.drawstates(color=state_color)
    m.drawcountries(color=border_color)
    m.readshapefile('resources/gadm36_CHN_shp/gadm36_CHN_1',
                    'provinces',
                    drawbounds=True,
                    color=state_color,
                    linewidth=0.8)
    m.readshapefile('resources/gadm36_TWN_shp/gadm36_TWN_0',
                    'taiwan',
                    drawbounds=True,
                    color=state_color,
                    linewidth=0.8)
    m.fillcontinents(color=land_color, lake_color=water_color)
    m.drawparallels(np.arange(-90., 90., 10.),
Example #34
0
def plot_the_data(data, units, start_time, end_time, wd, Output_Name, debug):
   print 'Plotting the data.'
   #set up plot
#   print data
#   print data.dimensions
   colourbar_tick_size     = 20
   colourbar_title         = species + units
   colourbar_title_size    = 25
   colourbar_number_ticks  = 5
   X_axis_title            = 'Longitude'
   X_axis_size             = 25
   Y_axis_title            = 'Latitude'
   Y_axis_size             = 25
   Plot_title              =  "Surface " + species + ' average between '+ str(start_time) + ' and ' + str(end_time)
   

   # Chose the figure size
   fig=plt.figure(figsize=(20,12))

   ax = fig.add_axes([.05, .1, .9, .8])
   fig.patch.set_facecolor('white')

   # Add the basemap
   lat = np.arange(-88,90,4)
   lat = np.insert(lat,0,-90)
   lat = np.append(lat,90)
   lon = np.arange(-182.5,179,5)
   m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
                    llcrnrlon=-182.5,\
                    urcrnrlon=177.5,\
                   resolution='c')

   m.drawcoastlines()
   m.drawmapboundary()
   parallels = np.arange(-90,91,30)
   meridians = np.arange(-180,151,30)

   plt.xticks(meridians)
   plt.yticks(parallels)

   m.drawparallels(parallels)
   m.drawmeridians(meridians)
   x, y = np.meshgrid(*m(lon, lat))

   # #Add the map
   poly = m.pcolor(lon, lat, data)
      
   
   plt.xlabel(X_axis_title, fontsize = X_axis_size)
   plt.ylabel(Y_axis_title, fontsize = Y_axis_size)

   # Add colourbar title
   cb = plt.colorbar(poly, shrink=0.7)#,#orientation = 'horizontal')
   tick_locator = ticker.MaxNLocator(nbins=colourbar_number_ticks)
   cb.locator = tick_locator
   cb.ax.tick_params(labelsize=colourbar_tick_size)
   cb.update_ticks()
   Colourbar_title = species +' ' +  units
   plt.text(191,93,Colourbar_title,fontsize='25')

   # Add the title
   print species
   print units
   print start_time
   print end_time
   print Plot_title
   plt.title( Plot_title, fontsize='30' )
   fig.savefig( Output_Name, transparent=True )


   return ;
def plot_map():
    global earth_radius_meters
    # setup Lambert Conformal basemap.
    # set resolution=None to skip processing of boundary datasets.
    m = Basemap(width=600000,
                height=450000,
                projection='lcc',
                lat_0=station_lat,
                lon_0=station_lon,
                resolution='c')
    m.drawmapboundary(zorder=-2)
    m.fillcontinents(zorder=-1)
    m.drawcoastlines(linewidth=0.5)
    m.drawstates()
    m.drawcounties()
    m.drawrivers()
    m.scatter(station_lon, station_lat, latlon=True)
    elevation_angle = f.variables['elevationV_HI'][0]
    elevation_angle = np.mean(elevation_angle)
    rounded_elevation_angle = round(elevation_angle, 2)
    data_at_elevation = f.variables['RadialVelocity_HI'][0]
    data_at_elevation = np.array(data_at_elevation)
    data_at_elevation[data_at_elevation == 0] = np.nan
    data_at_elevation[data_at_elevation == 1] = np.nan
    # lowest_angle = (lowest_angle + f.variables['RadialVelocity'].add_offset) * f.variables['RadialVelocity'].scale_factor
    data_at_elevation = data_at_elevation / f.variables[
        'RadialVelocity_HI'].scale_factor
    # data_at_elevation = data_at_elevation.transpose()
    gates = np.array(f.variables['distanceV_HI'])
    gates = gates
    angles = np.array(f.variables['azimuthV_HI'][0])
    min_index = np.argmin(angles)
    angles = np.roll(angles, min_index * -1)
    data_at_elevation = np.roll(data_at_elevation, min_index * -1, axis=1)
    radar_elevation_above_sea_level = getattr(f, 'StationElevationInMeters')
    radar_tower_height = 0
    earth_radius_meters = 6378137
    lon_points = []
    lat_points = []
    distances = []
    for g in range(len(gates)):
        b = (earth_radius_meters + radar_tower_height)
        c = gates[g]
        a = math.sqrt(b**2 + c**2 -
                      (2 * b * c *
                       math.cos(math.radians(90 + elevation_angle))))
        h = a - earth_radius_meters
        # heights_at_angle.append(h)

        theta_at_core = math.asin(
            (gates[g] * math.sin(math.radians(90 + elevation_angle)) / a))
        distance = theta_at_core * earth_radius_meters

        distances.append(distance)
    distances = np.array(distances)
    data = []
    count = 0
    for theta in angles[::5]:
        for distance in distances[::10]:
            results = displace(station_lat, station_lon, theta, distance)
            lat = results[0]
            lon = results[1]
            lat_points.append(lat)
            lon_points.append(lon)
            angle_idx = angles.tolist().index(theta)
            distance_idx = distances.tolist().index(distance)
            data.append((data_at_elevation[angle_idx][distance_idx], lat, lon))
            count += 1
    print(count)
    data = np.array(data)
    # fig, ax = plt.subplots()
    # im = ax.pcolormesh(angles[:], gates[:], data_at_elevation[:])  # if you want contour plot
    # title = "{:.2f}".format(rounded_elevation_angle) + " degrees" + " / HR"
    # ax.set_title(title)
    # ax.set_xlabel('Azimuth angle in degrees: 0 = true north, 90 = east')
    # ax.set_ylabel('Distance from radar in km')
    # bar = fig.colorbar(im, ticks=range(-70, 75, 5), orientation='horizontal')
    # bar.set_label('Radial velocity in m/s')
    lon_points = np.array(lon_points[::])
    lon_points_s = np.sort(lon_points)
    lat_points = np.array(lat_points[::])
    lat_points_s = np.sort(lat_points)

    shaped_data = []
    for y in lat_points:
        row = []
        for x in lon_points:
            point = np.nan
            for d in data:
                if d[1] == y and d[2] == x:
                    point = d[0]
            row.append(point)
        shaped_data.append(row)
    shaped_data = np.array(shaped_data)

    X, Y = np.meshgrid(lon_points, lat_points)
    # plt.pcolormesh(X,Y,Z)
    # plt.show()
    m.pcolormesh(X, Y, shaped_data, latlon=True)
    m.scatter(lon_points, lat_points, latlon=True)
    plt.show()
Example #36
0
        def _plot_surface_data(lats,
                               lons,
                               data,
                               time,
                               lat_min,
                               lat_max,
                               lon_min,
                               lon_max,
                               output_filename='noname.png',
                               title='',
                               units='',
                               cm_edge_values=None,
                               cb_tick_fmt="%.0f",
                               cb_labels=None,
                               cb_label_pos=None,
                               colormap_strategy='nonlinear',
                               cmp_name='jet',
                               colors=None,
                               extend='both',
                               fill_color='1.0',
                               plotStyle='contourf',
                               contourLines=True,
                               contourLabels=True,
                               smoothFactor=1,
                               proj=self._DEFAULT_PROJ,
                               product_label_str=None,
                               vlat=None,
                               vlon=None,
                               u=None,
                               v=None,
                               draw_every=1,
                               arrow_scale=10,
                               resolution=None,
                               area=None,
                               boundaryInUse='True'):

            d_cmap, norm = from_levels_and_colors(cm_edge_values,
                                                  None,
                                                  cmp_name,
                                                  extend=extend)

            m = Basemap(projection=proj,
                        llcrnrlat=lat_min,
                        llcrnrlon=lon_min,
                        urcrnrlat=lat_max,
                        urcrnrlon=lon_max,
                        resolution='i')

            # Plot data
            x2, y2 = m(*np.meshgrid(lons, lats))

            u = data[0][time]
            v = data[1][time]
            mag = np.sqrt(u**2 + v**2)

            img = m.pcolormesh(x2,
                               y2,
                               mag,
                               shading='flat',
                               cmap=d_cmap,
                               norm=norm)
            img.set_clim(cm_edge_values.min(), cm_edge_values.max())

            #plot vectors
            if area == 'pac':
                every = 50
                scale = 10
            else:
                every = 10
                scale = 10

            lons = lons[::every]
            lats = lats[::every]
            x2, y2 = m(*np.meshgrid(lons, lats))
            u2 = u[::every, ::every]
            v2 = v[::every, ::every]
            rad = np.arctan2(v2, u2)
            m.quiver(x2,
                     y2,
                     np.cos(rad),
                     np.sin(rad),
                     scale=scale,
                     zorder=3,
                     scale_units='inches',
                     pivot='middle')

            # Draw land, coastlines, parallels, meridians and add title
            m.drawmapboundary(linewidth=1.0, fill_color=fill_color)
            m.drawcoastlines(linewidth=0.5, color='#505050', zorder=8)
            m.fillcontinents(color='0.58', zorder=7)

            parallels, p_dec_places = get_tick_values(lat_min, lat_max)
            meridians, m_dec_places = get_tick_values(lon_min, lon_max)
            m.drawparallels(parallels,
                            labels=[True, False, False, False],
                            fmt='%.' + str(p_dec_places) + 'f',
                            fontsize=6,
                            dashes=[3, 3],
                            color='gray')
            m.drawmeridians(meridians,
                            labels=[False, False, False, True],
                            fmt='%.' + str(m_dec_places) + 'f',
                            fontsize=6,
                            dashes=[3, 3],
                            color='gray')

            plt.title(title, fontsize=9)

            # Draw colorbar
            ax = plt.gca()
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size=0.2, pad=0.3)
            if cb_label_pos is None:
                tick_pos = cm_edge_values
            else:
                tick_pos = cb_label_pos

            if boundaryInUse == 'True':
                cb = plt.colorbar(
                    img,
                    cax=cax,
                    #                             spacing='proportional',
                    spacing='uniform',
                    drawedges='False',
                    orientation='vertical',
                    extend=extend,
                    ticks=tick_pos,
                    boundaries=cm_edge_values)
            else:
                cb = plt.colorbar(img,
                                  cax=cax,
                                  spacing='uniform',
                                  drawedges='False',
                                  orientation='vertical',
                                  extend=extend,
                                  ticks=tick_pos)

            if cb_labels is None:
                cb.set_ticklabels([cb_tick_fmt % k for k in cm_edge_values])
            else:
                cb.set_ticklabels(cb_labels)
            for tick in cb.ax.get_yticklabels():
                tick.set_fontsize(7)
            cb.set_label(units, fontsize=8)

            # Patch for graphics bug that affects label positions for
            # long/narrow plots
            lat_extent = np.float(lat_max) - np.float(lat_min)
            lon_extent = np.float(lon_max) - np.float(lon_min)
            aspect_ratio = abs(lon_extent / lat_extent)

            if aspect_ratio > 1.7:
                copyright_label_yadj = -0.25
            else:
                copyright_label_yadj = -0.10
            if aspect_ratio < 0.7:
                copyright_label_xadj = -0.2
                product_label_xadj = 1.4
            else:
                copyright_label_xadj = -0.1
                product_label_xadj = 1.04

            # Draw copyright and product labels
            box = TextArea(getCopyright(),
                           textprops=dict(color='k', fontsize=6))
            copyrightBox = AnchoredOffsetbox(
                loc=3,
                child=box,
                borderpad=0.1,
                bbox_to_anchor=(copyright_label_xadj, copyright_label_yadj),
                frameon=False,
                bbox_transform=ax.transAxes)
            ax.add_artist(copyrightBox)

            if product_label_str is not None:
                box = TextArea(product_label_str,
                               textprops=dict(color='k', fontsize=6))
                copyrightBox = AnchoredOffsetbox(
                    loc=4,
                    child=box,
                    borderpad=0.1,
                    bbox_to_anchor=(product_label_xadj, copyright_label_yadj),
                    frameon=False,
                    bbox_transform=ax.transAxes)
                ax.add_artist(copyrightBox)

            # Save figure
            plt.savefig(output_filename,
                        dpi=150,
                        bbox_inches='tight',
                        pad_inches=0.6)

            plt.close()

            pngcrush(output_filename)
Example #37
0
        def _plot_basemap(region,
                          lats,
                          lons,
                          data,
                          time,
                          units='',
                          cb_tick_fmt="%.0f",
                          cb_labels=None,
                          proj=self._DEFAULT_PROJ,
                          **kwargs):

            m = Basemap(projection=proj,
                        llcrnrlat=region['lat_min'],
                        llcrnrlon=region['lon_min'],
                        urcrnrlat=region['lat_max'],
                        urcrnrlon=region['lon_max'],
                        resolution='i')

            # Plot data
            m.drawmapboundary(linewidth=1.0, fill_color='0.02')
            x2, y2 = m(*np.meshgrid(lons, lats))

            u = data[0][time]
            v = data[1][time]
            mag = np.sqrt(u**2 + v**2)

            #img = m.pcolormesh(x2, y2, mag, shading='flat', cmap=d_cmap, norm=norm)
            img = m.pcolormesh(x2,
                               y2,
                               mag,
                               shading='flat',
                               cmap=basemap_cmap,
                               norm=basemap_norm)
            img.set_clim(cm_edge_values.min(), cm_edge_values.max())

            plt.savefig(region['output_filename'],
                        dpi=120,
                        bbox_inches='tight',
                        pad_inches=0.0)
            # generate shape file
            gdal_process(region['output_filename'], region['lon_min'],
                         region['lat_max'], region['lon_max'],
                         region['lat_min'])

            pngcrush(region['output_filename'])

            #plot contouring labels
            if clabel:
                labels = plt.clabel(img,
                                    cm_edge_values[::4],
                                    inline=True,
                                    fmt='%.0f',
                                    colors='k',
                                    fontsize=5,
                                    zorder=2)
                bbox_props = dict(boxstyle="round", fc="w", ec="w", alpha=0.9)
                for text in labels:
                    text.set_linespacing(1)
                    text.set_bbox(bbox_props)

            #plot vectors
            baseName = os.path.splitext(region['output_filename'])[0]
            plt.clf()
            m.drawmapboundary(linewidth=0.0)

            if regionName == 'pac':
                every = 50
                scale = 10
            else:
                every = 10
                scale = 10
            lons = lons[::every]
            lats = lats[::every]
            x2, y2 = m(*np.meshgrid(lons, lats))
            u2 = u[::every, ::every]
            v2 = v[::every, ::every]
            #            u2 = u[::every, ::every]
            #            v2 = v[::every, ::every]
            rad = np.arctan2(v2, u2)
            m.quiver(x2,
                     y2,
                     np.cos(rad),
                     np.sin(rad),
                     scale=scale,
                     zorder=3,
                     scale_units='inches',
                     pivot='middle')

            arrowFile = baseName + '_arrow.png'
            plt.savefig(arrowFile,
                        dpi=120,
                        bbox_inches='tight',
                        pad_inches=0.0,
                        transparent=True)
            # generate shape file
            gdal_process(arrowFile, region['lon_min'], region['lat_max'],
                         region['lon_max'], region['lat_min'])

            pngcrush(arrowFile)
            #            m.drawmapboundary(linewidth=0.0)

            #            m.drawcoastlines(linewidth=0.5, color='#505050', zorder=8)
            #            m.fillcontinents(color='#F1EBB7', zorder=7)
            #            m.fillcontinents(color='0.58', zorder=7)

            # Save figure
            #            plt.savefig(region['output_filename'], dpi=120,
            #                        bbox_inches='tight', pad_inches=0.0)
            plt.close()
Example #38
0
#2.绘制房价地图

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm

%matplotlib inline

map = Basemap(projection='stere',lat_0=31,lon_0=121,
	llcrnrlat=30,urcrnrlat=32,
	llcrnrlon=120,urcrnrlon=122,
	rsphere=6371200.,resolution='h',area_thresh=10)
map.drawmapboundary() # 绘制边界
map.drawstates() # 绘制州
map.drawcoastlines() # 绘制海岸线
map.drawcountries() # 绘制国家
map.drawcounties() # 绘制县

parallels = np.arange(30.,32.,.5)
map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # 绘制纬线
meridians = np.arange(120.,122.,.5)
map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) # 绘制经线
lat = df_loc_group[“lat”] # 获取纬度值
lon = df_loc_group[“lng”] # 获取经度值
price = df_loc_group[“price”] # 获取平均房价
cm = plt.cm.get_cmap('Reds')
z = (price - price.min())/(price.max() - price.min()) # 绘制散点图时散点颜色深浅表示均价高低,颜色越深价格越高
Example #39
0

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(7.66,6))
plt.subplots_adjust(bottom=0.2)
file = Files[0]
nc = Dataset(file,'r')
lats = nc.variables['LATITUDE'][:]
lons = nc.variables['LONGITUDE'][:]
depth = nc.variables['P50DEPTH'][:]
depth = depth.squeeze()
fig1 = plt.subplot(2, 2, 1)
m = Basemap(llcrnrlat=-80.,urcrnrlat=80.,projection='cyl',lon_0=200)
depth_cyclic, lons_cyclic = addcyclic(depth[:,:], lons)
#depth_cyclic, lons_cyclic = shiftgrid(20., depth_cyclic, lons_cyclic, start=True)
x, y = m(*np.meshgrid(lons_cyclic, lats))
m.drawmapboundary() #fill_color='0.5'
m.drawcoastlines()
m.fillcontinents(color='grey', lake_color='0.5')
m.drawparallels(np.arange(-90.,120.,30.),labels=[1,0,0,0])
m.drawmeridians(np.arange(0.,420.,60.),labels=[0,0,0,0])
im1 = m.pcolor(x,y,depth, vmin=0, vmax=1100)
#im2 = m.pcolor(a,b,depth,shading='flat',cmap=plt.cm.jet_r, vmin=0, vmax=1100)
fig1.set_title(r'Low P50 and $-\Delta$H')

file = Files[1]
nc = Dataset(file,'r')
lats = nc.variables['LATITUDE'][:]
lons = nc.variables['LONGITUDE'][:]
depth = nc.variables['P50DEPTH'][:]
depth = depth.squeeze()
fig2 = plt.subplot(2, 2, 2)
Example #40
0
                fontsize=18,
                va='center',
                ha='center',
                clip_on=False)

# INSET VIP MAP
axins = zoomed_inset_axes(ax1, 9.2, loc=1, borderpad=.06)

axins.set_xlim(lons2[0], lons2[1])
axins.set_ylim(lats2[0], lats2[1])

m2 = Basemap(llcrnrlon=lons2[0],
             llcrnrlat=lats2[0],
             urcrnrlon=lons2[1],
             urcrnrlat=lats2[1],
             resolution='f')
m2.drawmapboundary(fill_color='azure', linewidth=2.0)
m2.pcolormesh(lons, lats, DHW_max, vmin=0, vmax=16, cmap=dhw_noaa, latlon=True)
polygon_patch(m2, axins)

axins.plot(121, 14.5, 'D', ms=8, mfc=dhw_noaa.colors[9, :], mec='k')
axins.text(121.09, 14.5, 'Manila', style='italic', fontsize=11, va='center')
axins.text(121.08, 13.1, 'Mindoro', fontsize=14, ha='center', va='center')
axins.text(121.2, 14.08, 'Luzon', fontsize=14, ha='center', va='center')

mark_inset(ax1, axins, loc1=2, loc2=3, fc="none", ec="0", lw=2)
plt_box(axins)

plt.savefig('Fig1_Max_DHW_98.png')
plt.show()
Example #41
0
def plot_status(trk,
                hdr,
                status=None,
                lllat=None,
                urlat=None,
                lllon=None,
                urlon=None,
                mark_id=False,
                color='m',
                basemap=None,
                plot=True):
    '''
    This module will plot tracks with colors depicting their status on the map.
    '''
    lat_idx = hdr.index('LATITUDE')
    lon_idx = hdr.index('LONGITUDE')
    tran_idx = hdr.index('TRANSMITTER_NO')
    name_idx = hdr.index('VESSEL_NAME')
    gear_idx = hdr.index('REGISTERED_GEAR_TYPE')
    date_idx = hdr.index('REPORTDATE')
    #    spd_idx=hdr.index('SPEED')

    lons = []
    lats = []
    for rec in trk:
        lons.append(float(rec[lon_idx]))
        lats.append(float(rec[lat_idx]))

    trans_no = trk[0][tran_idx]
    vessel_name = trk[0][name_idx]
    start_date = trk[0][date_idx].strftime('%Y%m%d')
    end_date = trk[-1][date_idx].strftime('%Y%m%d')
    gear_type = trk[0][gear_idx]

    if mark_id and 'ID_KEY' in hdr:
        idks = []
        idk_idx = hdr.index('ID_KEY')
        for rec in trk:
            idks.append(rec[idk_idx])

    if status is None or 'STATUS' not in hdr:
        if 'STATUS' not in hdr:
            print 'No status is provided.'
            raw_input()
        status = []
        sta_idx = hdr.index('STATUS')
        for rec in trk:
            status.append(rec[sta_idx])

    if basemap == None:
        if lllat == None or urlat == None or lllon == None or urlon == None:
            #            urlat=math.ceil(max(lats))
            #            lllat=math.floor(min(lats))
            #            urlon=math.ceil(max(lons))
            #            lllon=math.floor(min(lons))
            #            print urlat,lllat,urlon,lllon
            #            latran=urlat-lllat
            #            lonran=urlon-lllon
            #            latbuf=latran*0.1
            #            lonbuf=lonran*0.1
            #            print latbuf,lonbuf
            latbuf = 2
            lonbuf = 2
            urlat = math.ceil(max(lats)) + latbuf if math.ceil(
                max(lats)) < 90 - latbuf else 90
            lllat = math.floor(min(lats)) - latbuf if math.floor(
                min(lats)) > -90 + latbuf else -90
            urlon = math.ceil(max(lons)) + lonbuf if math.ceil(
                max(lons)) < 180 - lonbuf else 180
            lllon = math.floor(min(lons)) - lonbuf if math.floor(
                min(lons)) > -180 + lonbuf else -180
#            print urlat,lllat,urlon,lllon

    map = Basemap(projection='merc',
                  llcrnrlat=lllat,
                  urcrnrlat=urlat,
                  llcrnrlon=lllon,
                  urcrnrlon=urlon,
                  lat_ts=0,
                  resolution='f')  #,
    #                        suppress_ticks=False)
    #    print urlat,lllat,urlon,lllon
    intvp = 1.
    intvm = 1.
    parallels = np.arange(lllat, urlat + intvp, intvp)
    meridians = np.arange(lllon, urlon + intvm, intvm)
    while len(parallels) < 3:
        intvp = intvp / 2.
        parallels = np.arange(lllat, urlat + intvp, intvp)
    while len(meridians) < 3:
        intvm = intvm / 2.
        meridians = np.arange(lllon, urlon + intvm, intvm)


#    print parallels
#    print meridians
    prar = map.drawparallels(parallels, labels=[1, 0, 0, 0])
    meri = map.drawmeridians(meridians, labels=[0, 0, 0, 1])
    for m in meri:
        try:
            meri[m][1][0].set_rotation(45)
        except:
            pass
    map.drawcoastlines()
    map.fillcontinents(color='beige', lake_color='lightblue')
    map.drawmapboundary(fill_color='lightblue')
    plt.title(trans_no + '/' + vessel_name + '\n' + gear_type + '\n' +
              start_date + ' to ' + end_date)

    #status types
    #Fishing    fsh RED
    #Stationary sta BLUE
    #Transit    tra YELLOW
    #Landing    lnd GREEN

    #find fishing tracks
    con = list(status)
    color = ['m'] * len(con)
    marker = ['v'] * len(con)
    alpha = [0.4] * len(con)
    alpha_status = ['Transit', 'Landing']
    for i in range(0, len(con) - 1):

        if con[i] == 'Fishing':
            marker[i] = '+'
        if con[i] == 'Stationary':
            marker[i] = 'o'
        if con[i] == 'Transit':
            marker[i] = 'v'
        if con[i] == 'Landing':
            marker[i] = 'o'
        if con[i] == 'Non-Fishing':
            marker[i] = 'v'

        if con[i] == 'Fishing':
            color[i] = 'b'
        if con[i] == 'Stationary':
            color[i] = 'b'
        if con[i] == 'Transit':
            color[i] = 'r'
        if con[i] == 'Landing':
            color[i] = 'g'
        if con[i] == 'Non-Fishing':
            color[i] = 'r'

        if con[i] == 'Fishing' and 'Fishing' in alpha_status:
            alpha[i] = 0.1
        if con[i] == 'Stationary' and 'Stationary' in alpha_status:
            alpha[i] = 0.1
        if con[i] == 'Transit' and 'Transit' in alpha_status:
            alpha[i] = 0.1
        if con[i] == 'Landing' and 'Landing' in alpha_status:
            alpha[i] = 0.1
        if con[i] == 'Non-Fishing' and 'Transit' in alpha_status:
            alpha[i] = 0.1

    marker[0] = 'H'
    marker[-1] = '*'
    marker[-2] = '*'
    for i in range(0, len(marker) - 1):
        x, y = map([lons[i], lons[i + 1]], [lats[i], lats[i + 1]])
        map.plot(x,
                 y,
                 marker=marker[i],
                 color=color[i],
                 alpha=alpha[i],
                 markerfacecolor='none')

        if mark_id:
            x1, y1 = map(float(lons[i]), float(lats[i]))
            plt.annotate(idks[i],
                         xy=(x1, y1),
                         xycoords='data',
                         xytext=(x1, y1),
                         textcoords='data',
                         ha='left',
                         va='bottom',
                         rotation=25)
    print con
    print color

    #    x,y=map(lons,lats)
    #    map.plot(x,y,marker=marker,color=color)

    if plot == True:
        plt.show()
    else:
        return map
Example #42
0
    ### Select variable
    var = composites[i]
    varscat = pvals[i]
    
    m = Basemap(projection='npstere',boundinglat=66,lon_0=270,
                resolution='l',round =True)
                
    var, lons_cyclic = addcyclic(var, lons)
    var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False)
    lon2d, lat2d = np.meshgrid(lons_cyclic, lats)
    x, y = m(lon2d, lat2d)    
    
    varscat,lons_cyclic = addcyclic(varscat, lons)
    varscat,lons_cyclic = shiftgrid(180.,varscat,lons_cyclic,start=False)
      
    m.drawmapboundary(fill_color='white')
    m.drawcoastlines(color='k',linewidth=0.2)
    parallels = np.arange(50,90,10)
    meridians = np.arange(-180,180,30)
#    m.drawparallels(parallels,labels=[False,False,False,False],
#                    linewidth=0.35,color='k',fontsize=1)
#    m.drawmeridians(meridians,labels=[False,False,False,False],
#                    linewidth=0.35,color='k',fontsize=1)
    m.drawlsmask(land_color='darkgrey',ocean_color='mintcream')
    
    ### Adjust maximum limits
    values = np.arange(-3,3.1,0.25)  
    
    ### Plot filled contours    
    cs = m.contourf(x,y,var,
                    values,extend='both')
Example #43
0
]

fig, ax = plt.subplots()

m = Basemap(projection='merc',
            lon_0=3.0,
            lat_0=52.0,
            resolution='h',
            llcrnrlon=3.0,
            llcrnrlat=50.0,
            urcrnrlon=8.0,
            urcrnrlat=54.0)
# m.drawcountries(zorder=4)
m.drawcoastlines(zorder=5)
m.fillcontinents(color='tan', lake_color='lightblue', zorder=2)
m.drawmapboundary(fill_color='lightblue', zorder=1)

parallels = np.arange(50, 54, 1)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,
                labels=[False, True, True, False],
                dashes=[5, 5],
                color="gray",
                size=20)
meridians = np.arange(3, 8, 1)
m.drawmeridians(meridians,
                labels=[True, False, False, True],
                dashes=[5, 5],
                color="gray",
                size=20)
Example #44
0
lon, lat = np.meshgrid(lon, lat)
m = Basemap(llcrnrlon=100,
            llcrnrlat=-90,
            urcrnrlon=85,
            urcrnrlat=90,
            projection='robin',
            lon_0=180)
x, y = m(lon, lat)

# drawing the map
fig = plt.figure()
m.fillcontinents(color='black', lake_color='black')
m.drawcoastlines(linewidth=0.4)
m.drawparallels(np.arange(-90., 90., 15.), labels=[1, 0, 0, 1], fontsize=8)
m.drawmeridians(np.arange(-180., 181., 40.), labels=[0, 1, 0, 1], fontsize=8)
m.drawmapboundary()

# plotting data on the map
plt.contourf(x, y, temp, cmap=plt.cm.Spectral_r)
cb = plt.colorbar(orientation='horizontal')
cb.set_label(r'Sea Surface Temperature (deg C) Jan 1998',
             fontsize=14,
             style='italic')
plt.show()
plt.savefig('SST_globeplot_Hw3.png')

# Part 2: making pandas timeseries

#setting up time for timeseries
time = nc.variables['time']
temp_pac = nc.variables['temp'][:, 0, 200, 400]
Example #45
0
    def draw_kmeans_clusters(self, filename, figsize=(4, 3)):
        import matplotlib as mpl
        mpl.use('Agg')
        import matplotlib.patches as mpatches
        import matplotlib.pyplot as plt
        from sklearn.cluster import KMeans
        from scipy.spatial import Voronoi, voronoi_plot_2d
        from mpl_toolkits.basemap import Basemap, cm, maskoceans
        #from matplotlib import style
        #import seaborn as sns
        #sns.set_style("white")
        #plt.rc('text', usetex=True)
        #plt.rc('font', family='serif')
        #plt.rcParams['axes.facecolor']='white'
        fig = plt.figure(figsize=figsize)
        lllat = 24.396308
        lllon = -124.848974
        urlat = 49.384358
        urlon = -66.885444
        m = Basemap(llcrnrlat=lllat,
                    urcrnrlat=urlat,
                    llcrnrlon=lllon,
                    urcrnrlon=urlon,
                    resolution='c',
                    projection='cyl')
        m.drawmapboundary(fill_color='white')
        m.drawcoastlines(linewidth=0.2)
        m.drawcountries(linewidth=0.2)

        ax = plt.gca()
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)
        for spine in ax.spines.itervalues():
            spine.set_visible(False)

        #fig = plt.figure()  # figsize=(4,4.2)

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)
        train_locs = self.df_train[['lat', 'lon']].values
        n_clusters = int(np.ceil(train_locs.shape[0] / self.bucket_size))
        n_clusters = 128
        logging.info('n_cluster %d' % n_clusters)
        clusterer = KMeans(n_clusters=n_clusters, n_jobs=10)
        clusterer.fit(train_locs)
        centroids = clusterer.cluster_centers_
        centroids[:, [0, 1]] = centroids[:, [1, 0]]
        mlon, mlat = m(*(centroids[:, 0], centroids[:, 1]))
        centroids = np.transpose(np.vstack((mlon, mlat)))

        vor = Voronoi(centroids)

        #ax.set_xlim([-125, -60])  # pylab.xlim([-400, 400])
        #ax.set_ylim([25, 50])

        plt.setp(ax.get_yticklabels(), visible=False)
        plt.setp(ax.get_xticklabels(), visible=False)
        ax.yaxis.set_tick_params(size=0)
        ax.xaxis.set_tick_params(size=0)
        #plt.tick_params(axis='both', which='major', labelsize=25)
        #ax.labelsize = '25'
        #plt.subplots_adjust(bottom=0.2)
        voronoi_plot_2d(vor,
                        show_points=False,
                        show_vertices=False,
                        ax=ax,
                        line_width=0.7)
        m.drawlsmask(land_color='lightgray', ocean_color="#b0c4de", lakes=True)
        plt.tight_layout()
        plt.savefig(filename)
        #plt.close()
        print("the plot saved in " + filename)
Example #46
0
Description: use basemap
    
"""

# must set the path for proj library
import os

os.environ[
    'PROJ_LIB'] = r'C:\Users\chen_\AppData\Local\Continuum\anaconda3\Library\share'

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

map = Basemap()
map.drawcoastlines()
#map.drawcounties(linewidth=1.5)

plt.show()
plt.savefig('test.png')

map = Basemap(projection='ortho', lat_0=0, lon_0=0)

#Fill the globe with a blue color
map.drawmapboundary(fill_color='aqua')
#Fill the continents with the land color
map.fillcontinents(color='coral', lake_color='aqua')

map.drawcoastlines()

plt.show()
Example #47
0
    def draw_kd_clusters2(self, filename, figsize=(4, 3)):
        import matplotlib as mpl
        mpl.use('Agg')
        import matplotlib.patches as mpatches
        import matplotlib.pyplot as plt
        from mpl_toolkits.basemap import Basemap, cm, maskoceans

        class KDTree:
            """Simple KD tree class"""

            # class initialization function
            def __init__(self, data, mins, maxs):
                self.data = np.asarray(data)

                # data should be two-dimensional
                assert self.data.shape[1] == 2

                if mins is None:
                    mins = data.min(0)
                if maxs is None:
                    maxs = data.max(0)

                self.mins = np.asarray(mins)
                self.maxs = np.asarray(maxs)
                self.sizes = self.maxs - self.mins

                self.child1 = None
                self.child2 = None

                if len(data) > 1:
                    # sort on the dimension with the largest spread
                    largest_dim = np.argmax(self.sizes)
                    i_sort = np.argsort(self.data[:, largest_dim])
                    self.data[:] = self.data[i_sort, :]

                    # find split point
                    N = self.data.shape[0]
                    split_point = 0.5 * (self.data[N / 2, largest_dim] +
                                         self.data[N / 2 - 1, largest_dim])

                    # create subnodes
                    mins1 = self.mins.copy()
                    mins1[largest_dim] = split_point
                    maxs2 = self.maxs.copy()
                    maxs2[largest_dim] = split_point

                    # Recursively build a KD-tree on each sub-node
                    self.child1 = KDTree(self.data[N / 2:], mins1, self.maxs)
                    self.child2 = KDTree(self.data[:N / 2], self.mins, maxs2)

            def draw_rectangle(self, ax, depth=None):
                """Recursively plot a visualization of the KD tree region"""
                if depth == 0:
                    rect = plt.Rectangle(self.mins,
                                         *self.sizes,
                                         ec='k',
                                         fc='none',
                                         lw=0.7)
                    ax.add_patch(rect)

                if self.child1 is not None:
                    if depth is None:
                        self.child1.draw_rectangle(ax)
                        self.child2.draw_rectangle(ax)
                    elif depth > 0:
                        self.child1.draw_rectangle(ax, depth - 1)
                        self.child2.draw_rectangle(ax, depth - 1)

        #------------------------------------------------------------
        # Create a set of structured random points in two dimensions
        np.random.seed(0)

        lllat = 24.396308
        lllon = -124.848974
        urlat = 49.384358
        urlon = -66.885444
        fig = plt.figure(figsize=figsize)
        m = Basemap(llcrnrlat=lllat,
                    urcrnrlat=urlat,
                    llcrnrlon=lllon,
                    urcrnrlon=urlon,
                    resolution='c',
                    projection='cyl')
        m.drawmapboundary(fill_color='white')
        m.drawcoastlines(linewidth=0.4)
        m.drawcountries(linewidth=0.4)
        train_locs = self.df_train[['lon', 'lat']].values
        mlon, mlat = m(*(train_locs[:, 1], train_locs[:, 0]))
        train_locs = np.transpose(np.vstack((mlat, mlon)))
        ax = plt.gca()
        #fig = plt.figure()  # figsize=(4,4.2)
        print(fig.get_size_inches())

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)

        #------------------------------------------------------------
        # Use our KD Tree class to recursively divide the space
        KDT = KDTree(train_locs, [lllon - 1, urlon + 1],
                     [lllat - 1, urlat + 1])

        #------------------------------------------------------------
        # Plot four different levels of the KD tree
        fig = plt.figure(figsize=figsize)
        '''
        fig.subplots_adjust(wspace=0.1, hspace=0.15,
                            left=0.1, right=0.9,
                            bottom=0.05, top=0.9)
        '''
        level = 8
        ax = plt.gca()
        #ax.scatter(X[:, 0], X[:, 1], s=9)
        KDT.draw_rectangle(ax, depth=level - 1)

        ax.set_xlim([-125, -60])  # pylab.xlim([-400, 400])
        ax.set_ylim([25, 50])

        plt.setp(ax.get_yticklabels(), visible=False)
        plt.setp(ax.get_xticklabels(), visible=False)
        ax.yaxis.set_tick_params(size=0)
        ax.xaxis.set_tick_params(size=0)
        #plt.tick_params(axis='both', which='major', labelsize=25)
        #ax.labelsize = '25'
        #plt.subplots_adjust(bottom=0.2)
        m.drawlsmask(land_color='lightgray', ocean_color="#b0c4de", lakes=True)
        plt.tight_layout()
        plt.savefig(filename)
Example #48
0
def graph_cities(df,
                 names=["Longitude", "Latitude", "City"],
                 ax=None,
                 linked=False,
                 fLOG=None,
                 loop=False,
                 many=False,
                 drawcoastlines=True,
                 drawcountries=True,
                 fillcontinents=True,
                 drawparallels=True,
                 drawmeridians=True,
                 drawmapboundary=True,
                 **params):
    """
    plots the cities on a map

    @param      df      dataframe
    @param      names   names of the column Latitude, Longitude, City
    @param      ax      existing ax
    @param      linked  draw lines between points
    @param      loop    add a final line to link the first point to the final one
    @param      fLOG    logging function
    @param      params  see below
    @param      many    change the return
    @return             *ax* or *fig, ax, m* if *many* is True

    Other parameters (see `basemap_api <http://matplotlib.org/basemap/api/basemap_api.html>`_):

    * llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat
    * resolution
    * projection
    * color, lake_color
    * style
    * markersize
    * fontname, fontcolor, fontsize, fontweight, fontvalign
    * slon, slat: space between meridians and parellels
    * linestyle, linewidth, line_color, antialiased: lines
    * alpha: fill

    """
    xx = list(df[names[0]])
    yy = list(df[names[1]])
    nn = list(df[names[2]]) if len(names) > 2 else [""] * len(xx)

    if ax is None:
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(**params)
    else:
        fig = None

    minx, maxx = min(xx), max(xx)
    miny, maxy = min(yy), max(yy)
    avex, avey = numpy.mean(xx), numpy.mean(yy)
    dx = (maxx - minx) / 10
    dy = (maxy - miny) / 10
    if fLOG:
        mes = "[graph_cities] Lon:[{0}, {1}] x Lat:[{2}, {3}] - mean={4}, {5} - linked={6}"
        fLOG(mes.format(minx, maxx, miny, maxy, avex, avey, linked))
    minx -= dx
    maxx += dx
    miny -= dy
    maxy += dy

    from mpl_toolkits.basemap import Basemap
    m = Basemap(llcrnrlon=params.get('llcrnrlon', minx),
                llcrnrlat=params.get('llcrnrlat', miny),
                urcrnrlon=params.get('urcrnrlon', maxx),
                urcrnrlat=params.get('urcrnrlat', maxy),
                resolution=params.get('resolution', 'i'),
                projection=params.get('projection', 'merc'),
                lon_0=avex,
                lat_0=avey,
                ax=ax)

    if drawcoastlines:
        m.drawcoastlines(linestyle=params.get('linestyle', 'solid'),
                         linewidth=params.get('linewidth', 0.5),
                         color=params.get('line_color', 'k'),
                         antialiased=params.get('antialiased', 1))
    if drawcountries:
        m.drawcountries(linestyle=params.get('linestyle', 'solid'),
                        linewidth=params.get('linewidth', 0.5),
                        color=params.get('line_color', 'k'),
                        antialiased=params.get('antialiased', 1))
    if fillcontinents:
        m.fillcontinents(color=params.get('color', 'lightblue'),
                         lake_color=params.get('lake_color', 'blue'),
                         alpha=params.get('alpha', None))
    if drawparallels:
        m.drawparallels(numpy.arange(miny, maxy, params.get('slat', 10.)),
                        linestyle=params.get('linestyle', 'solid'),
                        linewidth=params.get('linewidth', 0.5),
                        color=params.get('line_color', 'k'),
                        antialiased=params.get('antialiased', 1))
    if drawmeridians:
        m.drawmeridians(numpy.arange(minx, maxx, params.get('slon', 10.)),
                        linestyle=params.get('linestyle', 'solid'),
                        linewidth=params.get('linewidth', 0.5),
                        color=params.get('line_color', 'k'),
                        antialiased=params.get('antialiased', 1))
    if drawmapboundary:
        m.drawmapboundary(fill_color=params.get('fill_color', 'aqua'),
                          linewidth=params.get('linewidth', 0.5),
                          color=params.get('line_color', 'k'))

    style = params.get('style', 'ro')
    markersize = params.get('markersize', 6)
    fontname = params.get('fontname', 'Arial')
    fontsize = str(params.get('fontsize', '16'))
    fontcolor = params.get('fontcolor', 'black')
    fontweight = params.get('fontweight', 'normal')
    fontvalign = params.get('fontvalign', 'bottom')

    if linked:
        if "-" not in style:
            style += "-"
        xs, ys = [], []
        i = 0
        for lon, lat in zip(xx, yy):
            x, y = m(lon, lat)
            xs.append(x)
            ys.append(y)
            if nn[i] is not None and len(nn[i]) > 0:
                ax.text(x,
                        y,
                        nn[i],
                        fontname=fontname,
                        size=fontsize,
                        color=fontcolor,
                        weight=fontweight,
                        verticalalignment=fontvalign)
            i += 1
        if loop:
            xs.append(xs[0])
            ys.append(ys[0])

        m.plot(xs, ys, style, markersize=markersize)
    else:
        i = 0
        for lon, lat in zip(xx, yy):
            x, y = m(lon, lat)
            m.plot(x, y, style, markersize=markersize)
            if nn[i] is not None and len(nn[i]) > 0:
                ax.text(x,
                        y,
                        nn[i],
                        fontname=fontname,
                        size=fontsize,
                        color=fontcolor,
                        weight=fontweight,
                        verticalalignment=fontvalign)
            i += 1
    return fig, ax, m if many else ax
Example #49
0
    sys.exit()

markersize = float(sys.argv[1])

lats = []
lons = []

with open('data/GeoLiteCity-Location.csv', 'rb') as csvin:
    reader = csv.reader(csvin)
    next(reader)  # copyright notice
    next(reader)  # headings

    for row in reader:
        lats.append(float(row[5]))
        lons.append(float(row[6]))

m = Basemap(projection='mill', lon_0=0, lat_0=0)

# no visible border around map
m.drawmapboundary(fill_color='#ffffff', linewidth=0.0)

x, y = m(lons, lats)
m.scatter(x, y, markersize, marker='.', color='#325CA9')

fig = plt.gcf()
fig.set_alpha(.7)
fig.set_size_inches(36, 24)

plt.savefig('img/world%s.png' % str(markersize),
            bbox_inches='tight',
            pad_inches=0)
Example #50
0
    def draw_kd_clusters(self, filename, figsize=(4, 3)):
        import matplotlib as mpl
        mpl.use('Agg')
        import matplotlib.patches as mpatches
        import matplotlib.pyplot as plt
        from mpl_toolkits.basemap import Basemap, cm, maskoceans
        #from matplotlib import style
        #import seaborn as sns
        #sns.set_style("white")
        #plt.rc('text', usetex=True)
        #plt.rc('font', family='serif')
        #plt.rcParams['axes.facecolor']='white'
        fig = plt.figure(figsize=figsize)

        lllat = 24.396308
        lllon = -124.848974
        urlat = 49.384358
        urlon = -66.885444
        m = Basemap(llcrnrlat=lllat,
                    urcrnrlat=urlat,
                    llcrnrlon=lllon,
                    urcrnrlon=urlon,
                    resolution='c',
                    projection='cyl')
        m.drawmapboundary(fill_color='white')
        m.drawcoastlines(linewidth=0.2)
        m.drawcountries(linewidth=0.2)

        ax = plt.gca()
        #fig = plt.figure()  # figsize=(4,4.2)
        print(fig.get_size_inches())

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)
        clusterer = kdtree.KDTreeClustering(bucket_size=self.bucket_size)
        train_locs = self.df_train[['lat', 'lon']].values
        mlon, mlat = m(*(train_locs[:, 1], train_locs[:, 0]))
        train_locs = np.transpose(np.vstack((mlat, mlon)))

        clusterer.fit(train_locs)
        clusters = clusterer.get_clusters()
        cluster_points = dd(list)
        for i, cluster in enumerate(clusters):
            cluster_points[cluster].append(train_locs[i])
        corners = []
        for i in clusters:
            points = np.vstack(cluster_points[i])
            min_lat, min_lon = points.min(axis=0)
            max_lat, max_lon = points.max(axis=0)
            min_lon, min_lat = m(min_lon, min_lat)
            max_lon, max_lat = m(max_lon, max_lat)
            corners.append([min_lat, min_lon, max_lat, max_lon])
        patches = []
        for corner in corners:
            min_lat, min_lon, max_lat, max_lon = corner
            rect = mpatches.Rectangle((min_lon, min_lat),
                                      max_lon - min_lon,
                                      max_lat - min_lat,
                                      facecolor=None,
                                      fill=False,
                                      linewidth=0.7)
            patches.append(rect)
        ax.add_collection(PatchCollection(patches))
        ax.set_xlim([-125, -60])  # pylab.xlim([-400, 400])
        ax.set_ylim([25, 50])

        plt.setp(ax.get_yticklabels(), visible=False)
        plt.setp(ax.get_xticklabels(), visible=False)
        ax.yaxis.set_tick_params(size=0)
        ax.xaxis.set_tick_params(size=0)
        #plt.tick_params(axis='both', which='major', labelsize=25)
        #ax.labelsize = '25'
        #plt.subplots_adjust(bottom=0.2)
        m.drawlsmask(land_color='gray', ocean_color="#b0c4de", lakes=True)
        plt.tight_layout()
        plt.savefig(filename)
        #plt.close()
        print("the plot saved in " + filename)
Example #51
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

map = Basemap(projection='cyl', lat_0=0, lon_0=0)

map.drawmapboundary(fill_color='#7777ff')
map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0)
map.drawcoastlines()

lons = np.array([-13.7, -10.8, -13.2, -96.8, -7.99, 7.5, -17.3, -3.7])
lats = np.array([9.6, 6.3, 8.5, 32.7, 12.5, 8.9, 14.7, 40.39])
cases = np.array([1971, 7069, 6073, 4, 6, 20, 1, 1])
deaths = np.array([1192, 2964, 1250, 1, 5, 8, 0, 0])
places = np.array([
    'Guinea', 'Liberia', 'Sierra Leone', 'United States', 'Mali', 'Nigeria',
    'Senegal', 'Spain'
])

x, y = map(lons, lats)

map.scatter(x, y, s=cases, c='r', alpha=0.5)

axins = zoomed_inset_axes(ax, 7, loc=1)
axins.set_xlim(-20, 0)
axins.set_ylim(3, 18)
Example #52
0
def plotmap(lons,
            lats,
            labels=None,
            legendlabels=None,
            markers="o",
            colors="#FF4400",
            sizes=20,
            cmap=None,
            fontsize=None,
            fontweight='regular',
            fontcolor='k',
            labels_h_offset=0,
            labels_v_offset=0,
            mapmargins='0.5deg',
            figmargins=2,
            arcgis_service='World_Street_Map',
            arcgis_xpixels=1500,
            arcgis_dpi=96,
            urlfail='ignore',
            maxmeridians=5,
            maxparallels=5,
            legend_pos='bottom',
            legend_borderaxespad=1.5,
            legend_ncol=1,
            title=None,
            show=False,
            **kwargs):  # @UnusedVariable
    """
    Makes a scatter plot of points on a map background using ArcGIS REST API.

    :param lons: (array-like of length N or scalar) Longitudes of the data points, in degreee
    :param lats: (array-like of length N or scalar) Latitudes of the data points, in degree
    :param labels: (array-like of length N or string. Default: None, no labels) Annotations
    (labels) for the individual data points on the map. If non-array (e.g. string), the same value
    will be applied to all points
    :param legendlabels: (array-like of length N or string. Default: None, no legend)
    Annotations (labels) for the legend. You can supply a sparse array where only some points
    will be displayed on the legend. All points with no legend label will not show up in the
    legend
    :param sizes: (array-like of length N or number. Default: 20) Sizes (in points^2) of the
    individual points in the scatter plot.
    :param markers: (array-like of length N,
    `MarkerStyle<http://matplotlib.org/api/markers_api.html#matplotlib.markers.MarkerStyle>`_  or
    string. Default: 'o' - circle) The markers (shapes) to be drawn for each point on the map.
    See `markers <http://matplotlib.org/api/markers_api.html#module-matplotlib.markers>`_ for
    more information on the different styles of markers scatter supports. Marker can be either
    an instance of the class or the text shorthand for a particular marker.
    :param colors:  (array-like of length N,
    `matplotlib color <http://matplotlib.org/api/colors_api.html>`_, e.g. string.
    Default: "#FF4400")
    Colors for the markers (fill color). You can type color transparency by supplying string of 9
    elements where the last two characters denote the transparency ('00' fully transparent,
    'ff' fully opaque). Note that this is a feature not implemented in `matplotlib` colors, where
    transparency is given as the last element of the numeric tuple (r, g, b, a)
    :param fontsize: (numeric or None. Default: None) The fontsize for all texts drawn on the
    map (labels, axis tick labels, legend). None uses the default figure font size for all. Custom
    values for the individual text types (e.g. legend texts vs labels texts) can be supplied
    via the `kwargs` argument and a given prefix (see below)
    :param fontweight: (string or number. Default: 'regular') The font weight for all texts drawn
    on the map (labels, axis tick labels, legend). Accepts the values (see
    http://matplotlib.org/api/text_api.html#matplotlib.text.Text.set_weight):
    ```
    [a numeric value in range 0-1000 | 'ultralight' | 'light' |
    'normal' | 'regular' | 'book' | 'medium' | 'roman' | 'semibold' | 'demibold' | 'demi' |
    'bold' | 'heavy' | 'extra bold' | 'black' ]
    ```
    Custom
    values for the individual text types (e.g. legend texts vs labels texts) can be supplied
    via the `kwargs` argument and a given prefix (see below)
    :param fontcolor: (`matplotlib color <http://matplotlib.org/api/colors_api.html>`_ or
    string. Default: 'k', black) The font color for all texts drawn on the
    map (labels, axis tick labels, legend). Custom
    values for the individual text types (e.g. legend texts vs labels texts) can be supplied
    via the `kwargs` argument and a given prefix (see below)
    :param labels_h_offset: (string, number. Defaults None=0) The horizontal offset to be applied
    to each label on the map relative to its point coordinates. Negative values will shift the
    labels westward, positive values eastward. Useful for not overlapping
    markers and labels.
    If numeric, it is assumed to be the expressed in degrees. Otherwise, you can supply a string
    with a number followed by one of the units 'm', 'km' or 'deg' (e.g., '5km', '0.5deg').
    Note that this value affects the
    `horizontalalignment` and `multialignment` properties of the labels
    (for info see http://matplotlib.org/api/text_api.html#matplotlib.text.Text). Supplying
    `labels_horizontalalignment` or `labels_ha` as optional argument will override
    this behaviour (see `kwargs` below)
    :param labels_v_offset: (string, number. Defaults None=0) The vertical offset to be applied
    to each label on the map relative to its point coordinates. Negative values will shift the
    labels southhward, positive values northward. See notes on `labels_h_offset` for details
    Note that this value affects the
    `verticalalignment` property of the labels
    (for info see http://matplotlib.org/api/text_api.html#matplotlib.text.Text). Supplying
    `labels_verticalalignment` or `labels_va` as optional argument will override
    this behaviour (see `kwargs` below)
    :param mapmargins: (array-like of 1,2,3,4 elements, numeric or string, or None=0.
    Default: '0.5deg').
    The map margins, i.e. how much the map has to 'expand/shrink' in any direction, relative
    to the bounding box calculated to include all points.
    If array-like, it behaves like the css 'margin' property of html: 4 elements will denote
    [top, right, bottom, left], two elements will denote [top/bottom, left/right], three
    elements [top, right/left, bottom], a single element array (or a single number or a string)
    applies the value to all directions.
    Finally, elements of the array must be expressed as the arguments `labels_h_offset` or
    `labels_v_offset`: numbers denoting degrees or strings with units 'm', 'km', 'deg'. Negative
    values will shrink the map.
    If string, the argument will be first splitted using commas, semicolon or spaces as delimiters
    (if no delimiter is found, the string is taken as a single chunk) and converted to an array-like
    object.
    :param figmargins: (array-like of 1,2,3,4 elements, number or None=0. Default:2) The
    figure margins *in font height units* (e.g., 2 means: twice the font height). This argument
    behaves exactly as `mapmargins` but expands/shrinks the distances between map and figure
    (image) bounds. Useful to include axis tick labels or legend, if they overflow.
    Note also that strings
    are allowed only if they are parsable to float (e.g. "5,6; -12  1")
    :param arcgis_service: (string, default:  'World_Street_Map'). The map image type, or
    more technically the service for the map
    hosted on ArcGIS server. Other values are 'ESRI_Imagery_World_2D'
    (default in
    `Basemap.arcgisimage <http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.Basemap.arcgisimage>`_),
    'World_Topo_Map', 'World_Terrain_Base'. For details, see:
    http://server.arcgisonline.com/arcgis/rest/services.
    :param arcgis_xpixels: (numeric, default: 3000). Requested number of image pixels
    in x-direction (default is 400 in
    `Basemap.arcgisimage <http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.Basemap.arcgisimage>`_).
    The documentation is quite unclear but this parameter seems to set the zoom of the image. From
    this `link <http://basemaptutorial.readthedocs.io/en/latest/backgrounds.html#arcgisimage>`_:
    A bigger number will ask a bigger image, so the image will have more detail.
    So when the zoom is bigger, `xsize` must be bigger to maintain the resolution
    :param urlfail: (string, 'raise' or 'ignore'. Default: 'ignore'). Tells what to do if the
    ArcGIS requet fails (URLError, no internet connection etcetera). By default, on failure a raw
    map with continents contour, and oceans will be plotted (good for
    debug). Otherwise, the exception resulting from the web request is raised
    :param maxmeridians: (numeric default: 5). The number of maximum meridians to be drawn. Set to
    <=0 to hide meridians. Note that also x-axis labels are drawn.
    To further manipulate meridians display, use any argument starting with
    'mlabels_', 'mlines_' or 'meridians' (see `kwargs` below). E.g., to show only the labels and not
    the lines, supply as argument `meridians_linewidth=0` or 'mlines_linewidth=0'.
    :param maxparallels: (numeric default: 5). The number of maximum parallels to be drawn. Set to
    <=0 to hide parallels. Note that also y-axis labels are drawn.
    To further manipulate parallels display, use any argument starting with
    'plabels_', 'plines_' or 'parallels' (see `kwargs` below). E.g., to show only the labels and not
    the lines, supply as argument `parallels_linewidth=0` or 'plines_linewidth=0'.
    :param legend_pos: (string in ['top'. 'bottom', 'right', 'left'], default='bottom'). The legend
    location with respect to the map. It also adjusts the bounding box that the legend will be
    anchored to.
    For
    customizing entirely the legend placement overriding this parameter, provide `legend_loc`
    (and optionally `legend_bbox_to_anchor`) in `kwargs` (see below)
    :param legend_borderaxespad: (numeric, default 1.5) The pad between the axes and legend border,
    in font units
    :param legend_ncol: (integer, default=1) The legend number of columns
    :param title (string or None. Default: None): Title above plot (Note: not tested)
    :param show (boolean, default: False): Whether to show the figure after plotting or not
    (Note: not tested). Can be used to do further customization of the plot before showing it.
    :param fig: (matplotlib figure or None, default: None). Note: deprecated, pass None as
    supplying an already existing figure with other axes might break the figure layout
    :param kwargs: any kind of additional argument passed to `matplotlib` and `Basemap` functions
    or objects.
    The name of the argument must be of the form
    ```
    prefix_propertyname=propertyvalue
    ```
    where prefix indicates the function/object to be called with keyword argument:
    ```
    propertyname=propertyvalue
    ```

    Current supported prefixes are (for available property names see links):

    Prefix        Passes `propertyname` to
    ============ ==================================================================================
    arcgis       `Basemap.arcgisimage <http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.Basemap.arcgisimage>_
                 used to retrieve the background map using ArgGIS Server REST API. See also
                 http://basemaptutorial.readthedocs.io/en/latest/backgrounds.html#arcgisimage
    basemap      `Basemap <http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.Basemap>`_
                 the object responsible of drawing and managing the map. Note that
                 `basemap_resolution=h` and `basemap_epsg=4326` by default.
    labels       All `texts <http://matplotlib.org/api/text_api.html#matplotlib.text.Text>`_
                 used to display the point labels on the map
    legend       The `legend <http://matplotlib.org/api/legend_api.html#matplotlib.legend.Legend>`_.
                 See the already implemented arguments `legend_borderaxespad`,
                 `legend_ncol`
    legendlabels All `texts <http://matplotlib.org/api/text_api.html#matplotlib.text.Text>`_
                 used to display the text labels of the legend
    meridians    `Basemap.drawmeridians`. For more detailed settings on meridians, see
                 `mlines` and `mlabels`
    parallels    `Basemap.drawparallels`. For more detailed settings on parallels, see
                 `plines` and `plabels`
    plines       All `lines <http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D>`_
                 used to display the parallels
    plabels      All `texts <http://matplotlib.org/api/text_api.html#matplotlib.text.Text>`_
                 used to display the parallels labels on the y axis
    mlines       All `lines <http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D>`_
                 used to display the meridians
    mlabels      All `texts <http://matplotlib.org/api/text_api.html#matplotlib.text.Text>`_
                 used to display the meridians labels on the x axis
    ============ ==================================================================================

    Examples
    --------

    - `legend_title='abc'` will call `legend(..., title='abc', ...)`
    - `labels_path_effects=[PathEffects.withStroke(linewidth=2, foreground='white')]` will set the
      a white contour around each label text
    - `meridians_labelstyle="+/-"` will call `Basemap.drawmeridians(..., labelstyle="+/-", ...)`

    Notes:
    ------
    The objects referenced by `plines`, `plabels`, `mlines`, `mlabels` and `legendlabels`
    cannot be initialized directly with the given properties, which will be set after they are
    created assuming that for any property `foo` passed as keyword argument in their constructor
    there exist a method `set_foo(...)` (which will be called with the given propertyvalue).
    This is most likely always true according to matplotlib api, but we cannot assure it works
    100% of the times
    """
    lons, lats, labels, sizes, colors, markers, legendlabels =\
        _shapeargs(lons, lats, labels, sizes, colors, markers, legendlabels)

    # convert html strings to tuples of rgba values in [0.1] if the former are in string format,
    # because (maybe too old matplotlib version?) colors in the format '#RGBA' are not supported
    # Also, if cmap is provided, basemap.scatter calls matplotlib.scatter which
    # wants float sequenes in case of color map
    if colors.dtype.char in ('U', 'S'):  # pylint: disable=no-member
        colors = np.array([torgba(c) for c in colors])

    fig = plt.figure()
    map_ax = fig.add_axes([0, 0, 1, 1])  # set axes size the same as figure

    # setup handler for managing basemap coordinates and meridians / parallels calculation:
    handler = MapHandler(lons, lats, mapmargins)

    kwa = _joinargs(
        'basemap',
        kwargs,
        llcrnrlon=handler.llcrnrlon,
        llcrnrlat=handler.llcrnrlat,
        urcrnrlon=handler.urcrnrlon,
        urcrnrlat=handler.urcrnrlat,
        epsg='4326',  # 4326,  # 3395,  # 3857,
        resolution='i',  # 'h',
        ax=map_ax)
    bmap = Basemap(**kwa)

    try:
        kwa = _joinargs("arcgis",
                        kwargs,
                        service=arcgis_service,
                        xpixels=arcgis_xpixels,
                        dpi=arcgis_dpi)
        # set the map image via a map service. In case you need the returned values, note that
        # This function returns an ImageAxis (or AxisImage, check matplotlib doc)
        bmap.arcgisimage(**kwa)
    except (URLError, HTTPError, socket.error) as exc:
        # failed, maybe there is not internet connection
        if urlfail == 'ignore':
            # Print a simple map offline
            bmap.drawcoastlines()
            watercolor = '#4444bb'
            bmap.fillcontinents(color='#eebb66', lake_color=watercolor)
            bmap.drawmapboundary(fill_color=watercolor)
        else:
            raise

    # draw meridians and parallels. From basemap.drawmeridians / drawparallels doc:
    # returns a dictionary whose keys are the meridian values, and
    # whose values are tuples containing lists of the
    # matplotlib.lines.Line2D and matplotlib.text.Text instances
    # associated with each meridian. Deleting an item from the
    # dictionary removes the correpsonding meridian from the plot.
    if maxparallels > 0:
        kwa = _joinargs("parallels",
                        kwargs,
                        linewidth=1,
                        fontsize=fontsize,
                        labels=[0, 1, 1, 0],
                        fontweight=fontweight)
        parallels = handler.get_parallels(maxparallels)
        # Old basemap versions have problems with non-integer parallels.
        try:
            # Note: the method below # returns a list of text object
            # represeting the tick labels
            _dict = bmap.drawparallels(parallels, **kwa)
        except KeyError:
            parallels = sorted(list(set(map(int, parallels))))
            _dict = bmap.drawparallels(parallels, **kwa)

        # set custom properties:
        kwa_lines = _joinargs("plines", kwargs)
        kwa_labels = _joinargs("plabels", kwargs, color=fontcolor)
        _mp_set_custom_props(_dict, kwa_lines, kwa_labels)

    if maxmeridians > 0:
        kwa = _joinargs("meridians",
                        kwargs,
                        linewidth=1,
                        fontsize=fontsize,
                        labels=[1, 0, 0, 1],
                        fontweight=fontweight)
        meridians = handler.get_meridians(maxmeridians)
        _dict = bmap.drawmeridians(meridians, **kwa)

        # set custom properties:
        kwa_lines = _joinargs("mlines", kwargs)
        kwa_labels = _joinargs("mlabels", kwargs, color=fontcolor)
        _mp_set_custom_props(_dict, kwa_lines, kwa_labels)

    # fig.get_axes()[0].tick_params(direction='out', length=15)  # does not work, check basemap
    fig.bmap = bmap

    # compute the native bmap projection coordinates for events.

    # from the docs (this is kind of outdated, however leave here for the moment):
    # Calling a Basemap class instance with the arguments lon, lat will
    # convert lon/lat (in degrees) to x/y map projection
    # coordinates (in meters).  If optional keyword ``inverse`` is
    # True (default is False), the inverse transformation from x/y
    # to lon/lat is performed.

    # For cylindrical equidistant projection (``cyl``), this
    # does nothing (i.e. x,y == lon,lat).

    # For non-cylindrical projections, the inverse transformation
    # always returns longitudes between -180 and 180 degrees. For
    # cylindrical projections (self.projection == ``cyl``,
    # ``cea``, ``mill``, ``gall`` or ``merc``)
    # the inverse transformation will return longitudes between
    # self.llcrnrlon and self.llcrnrlat.

    # Input arguments lon, lat can be either scalar floats,
    # sequences, or numpy arrays.

    # parse hoffset and voffset and assure they are at least arrays of 1 elements
    # (for aligning text labels, see below)
    hoffset = np.array(parse_distance(labels_h_offset, lats),
                       copy=False,
                       ndmin=1)
    voffset = np.array(parse_distance(labels_v_offset), copy=False, ndmin=1)
    lbl_lons = lons + hoffset
    lbl_lats = lats + voffset

    # convert labels coordinates:
    xlbl, ylbl = bmap(lbl_lons, lbl_lats)

    # plot point labels
    max_points = -1  # negative means: plot all
    if max_points < 0 or len(lons) < max_points:
        # Set alignments which control also the corner point reference when placing labels
        # from (FIXME: add ref?)
        # horizontalalignment controls whether the x positional argument for the text indicates
        # the left, center or right side of the text bounding box.
        # verticalalignment controls whether the y positional argument for the text indicates
        # the bottom, center or top side of the text bounding box.
        # multialignment, for newline separated strings only, controls whether the different lines
        # are left, center or right justified
        ha = 'left' if hoffset[
            0] > 0 else 'right' if hoffset[0] < 0 else 'center'
        va = 'bottom' if voffset[
            0] > 0 else 'top' if voffset[0] < 0 else 'center'
        ma = ha
        kwa = _joinargs("labels",
                        kwargs,
                        fontweight=fontweight,
                        color=fontcolor,
                        zorder=100,
                        fontsize=fontsize,
                        horizontalalignment=ha,
                        verticalalignment=va,
                        multialignment=ma)

        for name, xpt, ypt in zip(labels, xlbl, ylbl):
            # Check if the point can actually be seen with the current bmap
            # projection. The bmap object will set the coordinates to very
            # large values if it cannot project a point.
            if xpt > 1e25:
                continue
            map_ax.text(xpt, ypt, name, **kwa)

    # plot points
    x, y = bmap(lons, lats)
    # store handles to points, and relative labels, if any
    leg_handles, leg_labels = [], []
    # bmap.scatter accepts all array-like args except markers. Avoid several useless loops
    # and do only those for distinct markers:
    # unique markers (sorted according to their index in markers, not their value):
    mrks = markers[np.sort(np.unique(markers, return_index=True)[1])]
    for mrk in mrks:
        # Note using masks with '==' (numpy==1.11.3):
        #
        # >>> a = np.array([1,2,3])
        # >>> a == 3
        # array([False, False,  True], dtype=bool)  # OK
        # >>> a == None
        # False                                     # NOT AS EXPECTED!
        # >>> np.equal(a, None)
        # array([False, False, False], dtype=bool)  # OK
        #
        # (Note also that a == None issues:
        # FutureWarning: comparison to `None` will result in an elementwise object
        # comparison in the future.)
        #
        # So the correct way is to write
        # mask = np.equal(array, val) if val is None else (a == val)

        m_mask = np.equal(markers,
                          mrk) if mrk is None else markers == mrk  # see above
        __x = x[m_mask]
        __y = y[m_mask]
        __m = mrk
        __s = sizes[m_mask]
        __c = colors[m_mask]
        __l = legendlabels[m_mask]
        # unique legends (sorted according to their index in __l, not their value):
        for leg in __l[np.sort(np.unique(__l, return_index=True)[1])]:
            l_mask = np.equal(__l,
                              leg) if leg is None else __l == leg  # see above
            _scatter = bmap.scatter(__x[l_mask],
                                    __y[l_mask],
                                    marker=mrk,
                                    s=__s[l_mask],
                                    c=__c[l_mask],
                                    cmap=cmap,
                                    zorder=10)
            if leg:
                leg_handles.append(_scatter)
                leg_labels.append(leg)

    if leg_handles:
        # if we provided `legend_loc`, use that:
        loc = kwargs.get('legend_loc', None)
        bbox_to_anchor = None  # defaults in matplotlib legend
        # we do have legend to show. Adjust legend reference corner:
        if loc is None:
            if legend_pos == 'bottom':
                loc = 'upper center'
                bbox_to_anchor = (0.5, -0.05)
            elif legend_pos == 'top':
                loc = 'lower center'
                bbox_to_anchor = (0.5, 1.05)
            elif legend_pos == 'left':
                loc = 'center right'
                bbox_to_anchor = (-0.05, 0.5)
            elif legend_pos == 'right':
                loc = 'center left'
                bbox_to_anchor = (1, 0.5)
            else:
                raise ValueError('invalid legend_pos value:"%s"' % legend_pos)

        # The plt.legend has the prop argument which sets the font properties:
        # family, style, variant, weight, stretch, size, fname. See
        # http://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.FontProperties
        # However, that property does not allow to set font color. So we
        # use the get_text method of Legend. Note that we pass font size *now* even if
        # setting it later works as well (the legend frame is resized accordingly)
        kwa = _joinargs("legend",
                        kwargs,
                        scatterpoints=1,
                        ncol=legend_ncol,
                        loc=loc,
                        bbox_to_anchor=bbox_to_anchor,
                        borderaxespad=legend_borderaxespad,
                        fontsize=fontsize)
        # http://stackoverflow.com/questions/17411940/matplotlib-scatter-plot-legend
        leg = map_ax.legend(leg_handles, leg_labels, **kwa)
        # set properties supplied via 'legend_'
        _setprop(leg.get_texts(),
                 _joinargs("legendlabels", kwargs, color=fontcolor))

    # re-position the axes. The REAL map aspect ratio seems to be this:
    realratio_h_w = bmap.aspect
    fig_w, fig_h = fig.get_size_inches()
    figratio_h_w = np.true_divide(fig_h, fig_w)

    if figratio_h_w >= realratio_h_w:
        # we have margins (blank space) above and below
        # thus, we assume:
        map_w = fig_w
        # and we calculate map_h
        map_h = map_w * realratio_h_w
        # assume there is the same amount of space above and below:
        vpad = (fig_h - map_h) / 2.0
        # hpad is zero:
        hpad = 0
    else:
        # we have margins (blank space) left and right
        # thus, we assume:
        map_h = fig_h
        # and consequently:
        map_w = map_h / realratio_h_w
        # assume there is the same amount of space above and below:
        hpad = (fig_w - map_w) / 2.0
        # wpad is zero:
        vpad = 0

    # calculate new fig dimensions EXACTLY as contour of the map
    new_fig_w = fig_w - 2 * hpad
    new_fig_h = fig_h - 2 * vpad

    # now margins:
    marginz = parse_margins(
        figmargins)  # margins are in fontheight units. Get font height:
    fontsize_inch = 0
    if len(np.nonzero(marginz)[0]):
        # Calculate the font size in pixels.
        # We want to be consistent with matplotlib way of getting fontsize.
        # inspecting matplotlib.legend.Legend.draw we end up with:
        # 1. Get the renderer
        rend = fig.canvas.get_renderer()
        # 2. get the fontsize in points. We might use `fontsize` but it might be None and we want
        # the default in case. There are several 'defaults' (rcParams['font.size'],
        # rcParams["legend.fontsize"])... we don't care for now, use the first. How to get
        # rcParams['font.size'] ? Either this: (see at matplotlib.Legend.__init__):
        # fontsize_pt = FontProperties(size=fontsize, weight=fontweight).get_size_in_points()
        # or simply do:
        fontsize_pt = fontsize or rcParams['font.size']
        # Now use renderer to convert to pixels:
        # For info see matplotlib.text.Text.get_window_extent
        fontsize_px = rend.points_to_pixels(fontsize_pt)
        # finally inches:
        fontsize_inch = pix2inch(rend.points_to_pixels(fontsize_px), fig)

    # calculate insets in inches (top right bottom left)
    insets_inch = marginz * fontsize_inch

    # set to fig dimensions
    new_fig_w += insets_inch[1] + insets_inch[3]
    new_fig_h += insets_inch[0] + insets_inch[2]

    fig.set_size_inches(new_fig_w, new_fig_h, forward=True)
    # (forward necessary if fig is in GUI, let's set for safety)

    # now the axes which are relative to the figure. Thus first normalize inches:
    insets_inch /= [fig_h, fig_w, fig_h, fig_w]

    # pos1 = map_ax.get_position()  # get the original position
    # NOTE: it seems that pos[0], pos[1] indicate the x and y of the LOWER LEFT corner, not
    # upper left!
    pos2 = [
        insets_inch[3], insets_inch[2], 1 - (insets_inch[1] + insets_inch[3]),
        1 - (insets_inch[0] + insets_inch[2])
    ]
    map_ax.set_position(pos2)

    if title:
        plt.suptitle(title)

    if show:
        plt.show()

    return fig
Example #53
0
    np.round(np.arange(0, 0.051, 0.01), 2),
    np.arange(0, 101, 25)
]
datasetsq = [r'RANDOM'] * 3
colorbarendq = ['max', 'max', 'neither']
cmapq = [
    cm.classic_16.mpl_colormap, cm.cubehelix2_16.mpl_colormap,
    cmocean.cm.dense_r
]

fig = plt.figure(figsize=(10, 2.5))
for i in range(len(dataq)):
    ax1 = plt.subplot(1, 3, i + 1)

    m = Basemap(projection='moll', lon_0=0, resolution='l', area_thresh=10000)
    circle = m.drawmapboundary(fill_color='k')
    circle.set_clip_on(False)
    m.drawcoastlines(color='darkgrey', linewidth=0.35)

    ### Colorbar limits
    barlim = barlimq[i]

    ### Take lrp mean over all years
    lrpstats = dataq[i]

    var, lons_cyclic = addcyclic(lrpstats, lon1)
    var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False)
    lon2d, lat2d = np.meshgrid(lons_cyclic, lat1)
    x, y = m(lon2d, lat2d)

    ### Make the plot continuous
Example #54
0
            urcrnrlat=geo_data['top_lat'],
            llcrnrlon=geo_data['left_lon'],
            urcrnrlon=geo_data['right_lon'],
            lat_ts=20,
            resolution='h',
            ax=ax0)

# just to define colors:
land_color = '#ffedcc'
water_color = '#2980b9'

m.drawcoastlines()
m.drawstates()
m.drawcountries()
m.fillcontinents(color=land_color, lake_color=water_color, zorder=0)
m.drawmapboundary(fill_color=water_color)

for item in geo['line']:
    lons = geo['line'][item]['coordinates'][0]
    lats = geo['line'][item]['coordinates'][1]
    x, y = m(lons, lats)
    lines_u = ax0.plot(x, y, 'k', lw=2.0, zorder=1)  # scatter plot

p_list = []  # colors list
q_list = []  # colors list
c_list = []  # colors list
x_syms_list = []  # x positions list
y_syms_list = []  # y positions list
labels_syms = []
cm = plt.cm.get_cmap('coolwarm')
idx = 0
Example #55
0
###anim.save('D:\Desktop\Thesis\ParcelsFigData\Data\North Atlantic\Animations/Trial2005.mp4',
###          fps=10, extra_args=['-vcodec', 'libx264'])
#Pick the dimensions of the basin we want to cover
#%%
latmin, latmax = -5, 75
lonmin, lonmax = -100, 20
plt.figure(figsize=(10 * 1.5, 8 * 1.5))
my_map = Basemap(projection='cyl',
                 llcrnrlon=lonmin,
                 urcrnrlon=lonmax,
                 llcrnrlat=latmin,
                 urcrnrlat=latmax,
                 resolution='l')
#my_map.drawcoastlines()
my_map.fillcontinents(color='gray')
my_map.drawmapboundary()
#my_map.drawmeridians(np.arange(0, 360, 30))
#my_map.drawparallels(np.arange(-90, 90, 30))
plt.title('Windage 1%', fontsize=14, weight='bold')
plt.tight_layout()
#text=plt.annotate('hi', xy=(0.5, 0.9), xycoords='axes fraction')
text = plt.text(-98.75,
                -3.1,
                '',
                ha='center',
                va='center',
                fontsize=12,
                bbox={
                    'facecolor': 'white',
                    'alpha': 1,
                    'pad': 10
Example #56
0
    GLM = accumulate_GLM(get_GLM_files_for_ABI(ABI))

    ## Make a new map object for the HRRR model domain map projection
    mH = Basemap(resolution='i', projection='lcc', area_thresh=5000, \
                width=1800*3000, height=1060*3000, \
                lat_1=38.5, lat_2=38.5, \
                lat_0=38.5, lon_0=-97.5)

    ## Plot each GLM file on the map
    plt.figure(figsize=[15, 10])

    print('Datetime Range:', GLM['DATETIME'])

    mH.scatter(GLM['longitude'],
               GLM['latitude'],
               marker='+',
               color='yellow',
               latlon=True)

    mH.drawmapboundary(fill_color='k')
    mH.drawcoastlines(color='w')
    mH.drawcountries(color='w')
    mH.drawstates(color='w')

    plt.title('GOES-16 GLM Flashes', fontweight='semibold', fontsize=15)
    plt.title('Start: %s\nEnd: %s' %
              (GLM['DATETIME'][0].strftime('%H:%M:%S UTC %d %B %Y'),
               GLM['DATETIME'][1].strftime('%H:%M:%S UTC %d %B %Y')),
              loc='right')
    plt.show()
Example #57
0
    def detector_plot(self,
                      radius=60.0,
                      point=None,
                      good=False,
                      projection='moll',
                      lat_0=0,
                      lon_0=180,
                      map=None,
                      NaI=True,
                      BGO=True,
                      show_bodies=False):

        map_flag = False

        if map is None:
            fig = plt.figure(figsize=(20, 20))
            ax = fig.add_subplot(111)
            map = Basemap(projection=projection,
                          lat_0=lat_0,
                          lon_0=lon_0,
                          resolution='l',
                          area_thresh=1000.0,
                          celestial=True,
                          ax=ax)
        else:
            map_flag = True

        if good and point:
            detector_list, fovs = self.get_good_fov(radius=radius,
                                                    point=point,
                                                    NaI=NaI,
                                                    BGO=BGO)

        else:
            detector_list, fovs = self.get_fov(radius, NaI=NaI, BGO=BGO)
        if point:
            ra, dec = map(point.ra.value, point.dec.value)
            map.plot(ra, dec, '*', color='#f36c21', markersize=20.)

        for key in detector_list:
            ra, dec = fovs[self.detectors[key].name]
            ra, dec = map(ra, dec)
            map.plot(ra, dec, '.', color='#74787c', markersize=3)
            x, y = map(self.detectors[key].center.icrs.ra.value,
                       self.detectors[key].center.icrs.dec.value)
            plt.text(x - 200000,
                     y - 200000,
                     self.detectors[key].name,
                     color='#74787c',
                     size=22)
        if show_bodies and self.sc_pos is not None:
            earth_points = self.get_earth_point()
            lon, lat = earth_points.ra.value, earth_points.dec.value
            lon, lat = map(lon, lat)
            map.plot(lon, lat, ',', color="#0C81F9", alpha=0.1, markersize=4.5)
            if self.time is not None:
                earth_r = get_body_barycentric('earth', self.time)
                moon_r = get_body_barycentric('moon', self.time)
                r_e_m = moon_r - earth_r
                r = self.sc_pos - np.array(
                    [r_e_m.x.value, r_e_m.y.value, r_e_m.z.value]) * u.km
                moon_point_d = cartesian_to_spherical(-r[0], -r[1], -r[2])
                moon_ra, moon_dec = moon_point_d[2].deg, moon_point_d[1].deg
                moon_point = SkyCoord(moon_ra,
                                      moon_dec,
                                      frame='icrs',
                                      unit='deg')
                moon_ra, moon_dec = map(moon_point.ra.deg, moon_point.dec.deg)
                map.plot(moon_ra,
                         moon_dec,
                         'o',
                         color='#72777b',
                         markersize=20)
                plt.text(moon_ra, moon_dec, '  moon', size=20)
            if show_bodies and self.time is not None:
                tmp_sun = get_sun(self.time)
                sun_position = SkyCoord(tmp_sun.ra.deg,
                                        tmp_sun.dec.deg,
                                        unit='deg',
                                        frame='icrs')
                sun_ra, sun_dec = map(sun_position.ra.value,
                                      sun_position.dec.value)
                map.plot(sun_ra, sun_dec, 'o', color='#ffd400', markersize=40)
                plt.text(sun_ra - 550000, sun_dec - 200000, 'sun', size=20)

        if not map_flag:
            if projection == 'moll':
                az1 = np.arange(0, 360, 30)
                zen1 = np.zeros(az1.size) + 2
                azname = []
                for i in az1:
                    azname.append(r'${\/%s\/^{\circ}}$' % str(i))
                x1, y1 = map(az1, zen1)
                for index, value in enumerate(az1):
                    plt.text(x1[index], y1[index], azname[index], size=20)
            _ = map.drawmeridians(np.arange(0, 360, 30),
                                  dashes=[1, 0],
                                  color='#d9d6c3')
            _ = map.drawparallels(np.arange(-90, 90, 15),
                                  dashes=[1, 0],
                                  labels=[1, 0, 0, 1],
                                  color='#d9d6c3',
                                  size=20)
            map.drawmapboundary(fill_color='#f6f5ec')
Example #58
0
def draw_map(map_type, geo_dict, filename, headless, leg_choice):
    import matplotlib as mpl
    if headless:
        mpl.use("Agg")
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap

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

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

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

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

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

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

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

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

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

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

    plt.title(title_string)
    if filename:
        plt.savefig('{}.png'.format(filename))
        print('Image saved as: {}.png'.format(filename))
    if not headless:
        mng = plt.get_current_fig_manager()
        mng.window.state('zoomed')
        plt.show()
Example #59
0
def PlotCorrMapTS(TheFile,LandCover,TheLatList,TheLonList,TheCorrData,
                    TheUnitee,TheLetter,TheNamee,TheMDI,YrStart,VarType):
    ''' Create a masked array of the correlations grids '''
    ''' Plot corrs on map '''
    ''' Add vertical latitude/corr scatter with average corr overlaid '''
    ''' Add time series of CandTS and CompTS with overall correlation annotated '''
    ''' Save as eps and png '''

    # Create the masked array of corrss
    MSKTheCorrData=ma.masked_where(TheCorrData == TheMDI,TheCorrData)
    
    # Get Latitude Average Trend
    LatCorr=np.zeros(len(TheLatList))
    LatCorr.fill(TheMDI)
    # For each latitude find average correlation (not sure this is strictly sound stats - better to correlate the lat average?'
    for ltt in range(len(TheLatList)):
        gots=np.where(TheCorrData[ltt,:] != TheMDI)[0]
	if (len(gots) > 0):
	    LatCorr[ltt]=np.mean(TheCorrData[ltt,np.where(TheCorrData[ltt,:] != TheMDI)])

    # make 2d arrays of lats and lons
    # nudge -2.5 degrees to make them south/west gridbox corners, not centres
    # add extra row/column to bound the data
    ArrLons,ArrLats=np.meshgrid(TheLonList,TheLatList)
    LngArrLons,LngArrLats=np.meshgrid(np.append(TheLonList-2.5,180.),np.append(TheLatList-2.5,90.))
    
    # set up plot
    plt.clf()
    fig=plt.figure(figsize=(10,5))
    #plt.figure(1,figsize=(10,3))
    plt1=plt.axes([0.01,0.05,0.64,0.9]) # left, bottom, width, height
    
    # plot map without continents and coastlines
    m = Basemap(projection='kav7',lon_0=0)
    # draw map boundary, transparent
    m.drawmapboundary()
    m.drawcoastlines()
    # draw paralells and medians, no labels
    m.drawparallels(np.arange(-90,90.,30.))
    m.drawmeridians(np.arange(-180,180.,60.))

    # make up a blue to red (reverse) colour map
    #cmaps=[plt.cm.Blues_r,plt.cm.Reds]
    #bluelist=[plt.cm.Blues_r(i) for i in range(plt.cm.Blues_r.N)]
    #redlist=[plt.cm.Reds(i) for i in range(plt.cm.Reds.N)]
#    cmap=plt.get_cmap('BrBG')
#    cmap=plt.get_cmap('coolwarm')
#    cmap=plt.get_cmap('bwr')
#    cmap=plt.get_cmap('RdGy')
#    cmap=plt.get_cmap('RdBu')
#    cmap=plt.get_cmap('hot')

    if (VarType == 'Temperature'):
        # Colour for T T
        cmap=plt.get_cmap('YlOrRd')
    elif (VarType == 'Humidity'):    
	# Colour for T /RH
        cmap=plt.get_cmap('bwr')
        
    cmaplist=[cmap(i) for i in range(cmap.N)]

    if (VarType == 'Temperature'):
        # Only for T T
        for loo in range(30):
            cmaplist.remove(cmaplist[0])
        cmap=cmap.from_list('this_cmap',cmaplist,cmap.N)
    
    #vmin=0.5
    #vmax=1
    #nsteps=11	  
    #bounds=np.round(1-np.logspace(0.7,-1,num=15,endpoint='True')/10.,3)
    if (VarType == 'Temperature'):
        # bounds for T T
        bounds=np.array([0,0.5,0.6,0.7,0.8,0.9,0.95,0.97,0.99,0.995,0.999,1])
    elif (VarType == 'Humidity'):    
	# bounds for T q/RH
        bounds=np.array([-1,-0.9,-0.8,-0.7,-0.6,-0.5,0.0,0.5,0.6,0.7,0.8,0.9,1])

    #bounds=np.logspace(vmin,vmax,nsteps)
#    strbounds=["%4.1f" % i for i in bounds]
    strbounds=["%4.3g" % i for i in bounds]
    norm=mpl_cm.colors.BoundaryNorm(bounds,cmap.N)

    # Only pcolor can do boxing on masked arrays, not really sure why we use pcolormesh at all
    grids=m.pcolor(LngArrLons,LngArrLats,MSKTheCorrData,cmap=cmap,norm=norm,latlon='TRUE')


    # extract the poorly correlating stations - reshape to a single array, index by lowest to highest, create a new zero array where 1:10 only have values
    # replot with boundaries.
    sortedlowhigh=np.argsort(np.reshape(MSKTheCorrData,np.size(MSKTheCorrData)))	# Does this work on masks?
    #stop
    LowCorrs=np.zeros(np.size(TheCorrData))
    TheCorrData=np.reshape(TheCorrData,np.size(TheCorrData))
    LowCorrs[sortedlowhigh[0:10]]=TheCorrData[sortedlowhigh[0:10]]
    LowCorrs=np.reshape(LowCorrs,(len(TheLatList),len(TheLonList)))
    TheCorrData=np.reshape(TheCorrData,(len(TheLatList),len(TheLonList)))
    MSKLowCorrs=ma.masked_where(LowCorrs == 0,LowCorrs)
    
    grids=m.pcolor(LngArrLons,LngArrLats,MSKLowCorrs,cmap=cmap,norm=norm, edgecolor='0.2',linewidth=0.5,latlon='TRUE')

    # Output list of all 'worst' correlations
    bads=np.where(MSKLowCorrs > 0)
    print("Number of Low Corrs: ",len(bads[0]))
    print("Corrs GBCentre Longs GBCentre Lats")
    SubCorrs=LowCorrs[bads]
    SubLons=ArrLons[bads]
    SubLats=ArrLats[bads]
    SortingHat=np.argsort(SubCorrs)
#    stop
    for loo in range(len(bads[0])):
        print("%6.2f %8.3f %8.3f" % (SubCorrs[SortingHat[loo]],SubLons[SortingHat[loo]],SubLats[SortingHat[loo]]))
     

    cbax=fig.add_axes([0.03,0.08,0.59,0.03])
    cb=plt.colorbar(grids,cax=cbax,orientation='horizontal',ticks=bounds) #, extend=extend
    cb.ax.tick_params(labelsize=9) 
    cb.ax.set_xticklabels(strbounds)
    plt.figtext(0.31,0.01,TheUnitee,size=12,ha='center')
    plt.figtext(0.05,0.9,TheLetter[0],size=16)

    # add labals and watermark    
#    watermarkstring="/".join(os.getcwd().split('/')[4:])+'/'+os.path.basename( __file__ )+"   "+dt.datetime.strftime(dt.datetime.now(), "%d-%b-%Y %H:%M")
#    plt.figtext(0.01,0.01,watermarkstring,size=6)
    plt.figtext(0.5,0.95,TheNamee,size=16,ha='center')
    
    # Attempt to plot the latitude/ratio scatter
    ax2=plt.axes([0.73,0.12,0.24,0.76]) # map only
    ax2.set_ylim(-90,90)
    #ax2.set_ylabel('Latitude')
    ax2.set_yticks(list([-60,-30,0,30,60]))
    ax2.set_yticklabels(list(['-60$^{o}$N','-30$^{o}$S','Equator','30$^{o}$N','60$^{o}$N'])) #,rotation=90)
    ax2.set_xlabel(TheUnitee)
#    minx=np.min(TheCorrData[np.where(TheCorrData != TheMDI)])-0.1
#    maxx=np.max(TheCorrData[np.where(TheCorrData != TheMDI)])+0.1
    if (VarType == 'Temperature'):
        # min for T T
        minx=0.
    elif (VarType == 'Humidity'):    
	# min for T q/RH
        minx=-1.
    maxx=1.
    ax2.set_xlim(minx,maxx)
    ax2.tick_params(axis='both',labelsize=10)
    # background fill the scatter plot with % land present (light grey) and % land with data (dark gre        
    for ltt in range(len(TheLatList)):
        # First merge LandCover with Data coverage so that at least some small islands are counted initially
	LandCover[ltt,np.where(TheCorrData[ltt,:] > TheMDI)[0]]=100.
        landcount=len(np.where(LandCover[ltt,:] > 0)[0])
	if (landcount > 0):
	    pctland=float(landcount)/72.
	else:
	    pctland=0
	landpresent=len(np.where(TheCorrData[ltt,:] > TheMDI)[0])
#	if (landpresent > landcount):	# small islands not picked up in landcover file so have to add in those that have been observed - not ideal
#	    landcount=landpresent
#	    pctland=float(landcount)/72.
	if (pctland > 0) & (landpresent > 0):
	    pctdata=landpresent/float(landcount)
        else:
	    pctdata=0
#	print(TheLatList[ltt],pctland,pctdata)
#	stop()
	if (pctland > 0): # fill row with appropriate amount of light grey
	    newxmin=0
	    newxmax=maxx*pctland
	    plt.fill_between(np.array([newxmin,newxmax]),TheLatList[ltt]-2.5,TheLatList[ltt]+2.5,facecolor='DimGrey',edgecolor='0.0',linewidth=0.0)
	if (pctdata > 0): # fill row with appropriate amount of dark grey
	    newxmin=0
	    newxmax=(maxx*pctland)*pctdata
	    plt.fill_between(np.array([newxmin,newxmax]),TheLatList[ltt]-2.5,TheLatList[ltt]+2.5,facecolor='Silver',edgecolor='0.0',linewidth=0.0)
    #ax.set_xmargin(0.01)
    plt.plot(np.zeros(2),np.array((-90,90)),color='black')
    plt.scatter(MSKTheCorrData,ArrLats,c=MSKTheCorrData,marker='o',cmap=cmap,norm=norm,edgecolor='0.0',linewidth=0.0)
    plt.plot(LatCorr[np.where(LatCorr != TheMDI)],TheLatList[np.where(LatCorr != TheMDI)],color='black',linewidth=2)
    plt.figtext(0.7,0.9,TheLetter[1],size=16)
    
#    plt.show()
#    stop()

    plt.savefig(TheFile+".eps")
    plt.savefig(TheFile+".png")
     
    return #PlotTrendRatMap
Example #60
0
def maplotC(pdata, colormax=1, mask='no', title='', precip='no'):
    """
    Plots input grid with map of world overlaid

    Parameters
    ----------
    plotdata: array
        data being plotted
    title: str
        optional title
    """
    from mpl_toolkits.basemap import Basemap, shiftgrid
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    from netcdfread import ncread
    lon = ncread(
        '/network/aopp/hera/mad/bakerh/HAPPI/CAM4-2degree/All-Hist/mon/va/va_Amon_CAM4-2degree_All-Hist_est1_v1-0_ens0000_200601-201512.nc',
        'lon')
    lat = ncread(
        '/network/aopp/hera/mad/bakerh/HAPPI/CAM4-2degree/All-Hist/mon/va/va_Amon_CAM4-2degree_All-Hist_est1_v1-0_ens0000_200601-201512.nc',
        'lat')
    plt.figure()
    if mask == 'yes':
        lsm = ncread('/home/bakerh/Documents/DPhil/Python/lsm_n72.nc', 'lsm')
        pdata = np.ma.masked_array(pdata, mask=np.logical_not(lsm))
    pdata, lon = shiftgrid(180., pdata, lon, start=False)
    meshlon, meshlat = np.meshgrid(lon, lat)

    m = Basemap(projection='cyl',
                llcrnrlat=-90,
                urcrnrlat=90,
                llcrnrlon=-180,
                urcrnrlon=180,
                resolution='c')
    m.drawcoastlines()
    m.drawmapboundary()
    x, y = m(meshlon, meshlat)
    mycmap2 = plt.cm.YlOrRd(np.arange(256))
    mycmap1 = plt.cm.Blues_r(np.arange(256))
    my_cmap = np.concatenate((mycmap1, mycmap2), axis=0)
    my_cmap[230:282, :] = 1
    if precip == 'yes':
        my_cmap = my_cmap[::-1]
    newcmap = mpl.colors.LinearSegmentedColormap.from_list("newjet", my_cmap)
    ctrs = np.linspace(-colormax, colormax, 17)
    plot = m.contourf(x,
                      y,
                      pdata,
                      ctrs,
                      cmap=newcmap,
                      vmin=np.min(ctrs),
                      vmax=np.max(ctrs),
                      extend='both')
    b = plt.colorbar(plot,
                     orientation='horizontal',
                     aspect=50,
                     shrink=0.75,
                     spacing='proportional')
    b.set_label(
        label=r'-$\mathbf{v}_\chi\cdot\nabla\zeta$ (10$^{-12}$ s$^{-2}$)')
    parallels = m.drawparallels(np.arange(-90., 91., 15.))
    meridians = m.drawmeridians(np.arange(-180., 181., 30))
    m.drawparallels(parallels, labels=[True, True, True, True])
    m.drawmeridians(meridians, labels=[True, True, True, True])
    plt.title(title, y=1.08)
    plt.show()