Example #1
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 #2
0
def sub_plot_pcolor(lons, lats, data, title=None, cmap=cm.jet,
                    vmin=None, vmax=None, cbar=True, cbar_location='bottom',
                    units=None, ncolors=5):

    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()

    m = Basemap(**projection)
    m.drawlsmask(land_color='grey', lakes=False)
    xi, yi = m(np.squeeze(lons), np.squeeze(lats))
    sp = m.pcolormesh(xi, yi, np.squeeze(data), vmin=vmin, vmax=vmax,
                      cmap=cmap)
    m.drawparallels(np.arange(-80., 81., 20.))
    m.drawmeridians(np.arange(-180., 181., 20.))
    m.drawcoastlines(color='k', linewidth=0.25)
    if title:
        plt.title(title, size=13)
    if cbar:
        cmap = cmap_discretize(cmap, ncolors)
        mappable = cm.ScalarMappable(cmap=cmap)
        mappable.set_array([])
        mappable.set_clim(-0.5, ncolors+0.5)
        colorbar = m.colorbar(mappable, location=cbar_location)
        colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
        colorbar.set_ticklabels(np.linspace(vmin, vmax, ncolors))
        colorbar.set_label(units)
    return sp
Example #3
0
def plotMap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, 
            lons, lats, color, title):
        m = Basemap(projection='merc',
                    resolution='i', 
                    llcrnrlon = llcrnrlon,
                    llcrnrlat = llcrnrlat,
                    urcrnrlon = urcrnrlon,
                    urcrnrlat = urcrnrlat)

        m.drawcountries(linewidth=1)
        m.drawcoastlines(linewidth=1)
        m.drawlsmask()
        m.drawstates()
        m.drawrivers(linewidth=.1)

        plt.title((str(len(lats)))+ \
            title,
            fontsize=12)

        x,y = m(lons, lats)
        if color == 'r':
            plt.hexbin(x, y, gridsize=40, cmap=plt.cm.Reds)
        if color == 'b':
            plt.hexbin(x, y, gridsize=40, cmap=plt.cm.Blues)        
        if color == 'g':
            plt.hexbin(x, y, gridsize=40, cmap=plt.cm.Greens)
        m.scatter(lons, lats, 1, marker='o',color=color, latlon=True)
        plt.show()
Example #4
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 #5
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 #6
0
def lambert_conformal(request):
    import matplotlib
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    width = float(request.GET.get('width', 6000000))
    height = float(request.GET.get('height', 4500000))
    lat = float(request.GET.get('lat',-7))
    lon = float(request.GET.get('lon',107))
    true_lat1 = float(request.GET.get('true_lat1',5))
    true_lat2 = float(request.GET.get('true_lat2',5))
    
    m = Basemap(width=width,height=height,
            rsphere=(6378137.00,6356752.3142),\
            resolution=None,projection='lcc',\
            lat_1=true_lat1,lat_2=true_lat2,lat_0=lat,lon_0=lon)
    
    fig = Figure()
    canvas = FigureCanvas(fig)
    m.ax = fig.add_axes([0, 0, 1, 1])
    
    m.drawlsmask(land_color='gray',ocean_color='white',lakes=True)
    m.drawparallels(np.arange(-90.,91.,30.), color='black')
    m.drawmeridians(np.arange(-180.,181.,60.), color='black')
    
    x, y = m(lon, lat)
    m.plot(x, y, 'ro')
    
    response = HttpResponse(content_type='image/png')
    canvas.print_figure(response, dpi=100)
    return response
def mapfig(ax=plt.gca()):
    m = Basemap(projection='merc',llcrnrlat=-25,urcrnrlat=8,llcrnrlon=-15,urcrnrlon=18,resolution='l',ax=ax)
    m.drawcoastlines()
    #m.drawmeridians(np.linspace(-17,11,8),labels=[0,0,0,1],linewidth=0.1)
    #m.drawparallels(np.linspace(-18,4,12),labels=[1,0,0,0],linewidth=0.1)
    m.drawlsmask(land_color='lightgrey',ocean_color='None',lakes=True)
    #m.shadedrelief(alpha=0.4)
    return m
def make_map():
	from mpl_toolkits.basemap import Basemap 
        m=Basemap(llcrnrlon=-125,llcrnrlat=31,urcrnrlon = -102.5,urcrnrlat=50,projection='cyl',lat_1=33,lat_2=42,lon_0=-110,
                resolution='c')
        m.drawcoastlines()
        m.drawstates()
        m.drawcountries()
        m.drawlsmask(land_color='grey',ocean_color='lightblue',lakes=True)
        return(m)
def n_pac_sect_2_w():

    map = Basemap(width=16000000,height=9000000,rsphere=(6378137.00,6356752.3142),projection='lcc',lat_1=0.,lat_2=65,lat_0=30,lon_0=-190.,area_thresh=50000.)
    map.drawcoastlines()
    map.drawmeridians([120,150,210,240,270],dashes=[3,4])
    map.drawmeridians([180],dashes=[6,4])
    map.drawparallels(np.arange(-180,180,30),dashes=[3,4])
    map.drawlsmask(land_color='0.8', ocean_color='w', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=False, resolution='c', grid=10)
    return map
def plotDifference(lats,lons,years,thk_diff,directory):
    """
    Makes large subplot of difference in all the SIT data between
    PIOMAS and the satellites [satellite - PIOMAS]
    """
        
    ### Call parameters
    plt.rcParams['text.usetex']=True
    plt.rcParams['font.family'] = 'sans-serif'
    plt.rcParams['font.sans-serif'] = 'Avant Garde'
    
    ### Define figure
    fig = plt.figure()
    
    for i in xrange(len(thk_diff)):
        ax = plt.subplot(3,4,i+1)    
        m = Basemap(projection='npstere',boundinglat=60,lon_0=-90,
                    round=True,resolution='l')
        m.drawmapboundary(fill_color = 'white')
        m.drawlsmask(land_color='darkgrey',ocean_color='snow')
        parallels = np.arange(50,90,10)
        meridians = np.arange(-180,180,30)
        m.drawparallels(parallels,labels=[False,False,False,False],
                        linewidth=0.25)
        m.drawmeridians(meridians,labels=[False,False,False,False],
                        linewidth=0.25)

        thk_diff[np.where(thk_diff >= 3.)] = 3
        thk_diff[np.where(thk_diff <= -3.)] = -3
        
        cs = m.contourf(lons,lats,thk_diff[i,:,:],np.arange(-3,3.1,0.1),
                        latlon=True,extend='both')
        cs.set_cmap('seismic_r')
        ax.text(0.89,0.95,r'\textbf{%s}' % (years[i]),size='8',
                horizontalalignment='center',backgroundcolor='w',
                verticalalignment='center',bbox=dict(facecolor='w',
                edgecolor='k',alpha=0.9),transform=ax.transAxes)
                
    cbar_ax = fig.add_axes([0.30,0.1,0.4,0.03])                
    cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal',
                        extend='both',extendfrac=0.07)

    cbar.set_label(r'Thickness (m)')
    cbar.set_ticks(np.arange(-3,4,1))
    cbar.set_ticklabels(map(str,np.arange(-3,4,1)))   
    
    fig.suptitle(r'\textbf{SIT Difference [Satellite - PIOMAS]}',fontsize=16)
    plt.tight_layout() 
    fig.subplots_adjust(bottom=0.14)
    fig.subplots_adjust(top=0.92)
    fig.subplots_adjust(wspace=-.56)
    fig.subplots_adjust(hspace=-0.0)         
                
    plt.savefig(directory +'cs2piomas_diff.png',
                dpi=500)
    print 'Completed: Difference subplot finished!'
Example #11
0
def n_am_ortho():

    map = Basemap(projection='ortho',lon_0=-115,lat_0=90,area_thresh=50000.)
    map.drawcoastlines(linewidth=1,color=[.3,.9,.3])
#    map.fillcontinents(color='.9') #[.91,.91,.95]
    map.drawmeridians(np.arange(0,360,90))
    map.drawparallels(np.arange(-180,180,30))
#    map.drawmapboundary(fill_color='w')
    map.drawlsmask(land_color='0.8', ocean_color='w', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=False, resolution='c', grid=10)

    return map
Example #12
0
def preload_map():
    if not os.path.isfile(pickle_file):
        ip_map = Basemap(projection='robin', lon_0=0, resolution='c')
        ip_map.drawlsmask(ocean_color="#99ccff", land_color="#009900")
        ip_map.drawcountries(linewidth=0.25, color='#ffff00')
        ip_map.drawcoastlines(linewidth=0.25)
        pickle.dump(ip_map, open(pickle_file, 'wb'), -1)
    else:
        ip_map = pickle.load(open(pickle_file, 'rb'))

    global pickle_bytes
    pickle_bytes = pickle.dumps(ip_map, -1)
Example #13
0
def map_template():
    """Return template figure for the given title and date."""
    fig = plt.figure(figsize=(11.69, 8.27), dpi=300)
    plt.text(62, -47, "wenfo.org/apwm/", ha="left", fontsize=10)
    plt.text(208, -47, 'Created ' + TODAY.isoformat(), ha="right", fontsize=10)
    m = Basemap(projection='cyl', resolution='l', llcrnrlat=-50, urcrnrlat=40,
                llcrnrlon=60, urcrnrlon=210)
    m.drawcoastlines(linewidth=0.75)
    m.drawcountries()
    m.drawlsmask(land_color=(0, 0, 0, 0), ocean_color='white', lakes=True)
    m.drawparallels(np.arange(-23, 24, 23), labels=[1, 0, 0, 1],
                    linewidth=0.6, color=(0.2, 0.2, 0.2))
    m.drawmeridians(np.arange(-180, 181, 30), labels=[1, 0, 0, 1],
                    linewidth=0.6, color=(0.2, 0.2, 0.2))
    return fig, m
def render_map(grb_file, llclat, llclon, urclat, urclon, altitude_layer):
    """Given a grb file, renders a jpg map on disk."""
    print('processing file %s ' % grb_file)
    grbs = pygrib.open(grb_file)
    data = grbs.select(name='Temperature')[altitude_layer]['values']
    plt.figure(figsize=(12, 12))

    # We don't like the way noaa aligns things. We like monotonic variations.
    data = realign_noaa_data(data)
    lonlat2temp = interpolate.interp2d(ALL_LONS, ALL_LATS, data, kind='linear')
    lats_interp = np.arange(llclat, urclat, 0.01)
    lons_interp = np.arange(llclon, urclon, 0.01)
    data_interp = lonlat2temp(lons_interp, lats_interp)
    # Size of the img to render in meters.
    width, height = width_height_from_bbox(llclat, llclon, urclat, urclon)
    m = Basemap(
        projection='cass',
        lat_ts=10,
        lat_0=(urclat + llclat) / 2,
        lon_0=(llclon + urclon) / 2,
        resolution='i',
        width=width,
        height=height)
    x, y = m(*np.meshgrid(lons_interp, lats_interp))

    # Draw plenty of fancy stuff
    m.drawstates()
    m.drawcountries()
    m.drawlsmask()
    m.drawrivers()
    m.drawcoastlines()
    m.shadedrelief()
    m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1])
    m.pcolormesh(
        x,
        y,
        data_interp,
        shading='flat',
        cmap=plt.cm.jet,
        alpha=0.05,
        vmin=260,
        vmax=305)
    m.colorbar(location='right')
    plt.title('Temperature')
    image = '%s.jpg' % grb_file
    plt.savefig(image)
    plt.close()
def define_map_projection(projection='gall', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180, resolution='i', land_color='grey', ocean_color='lightblue', lakes=True):
    '''Define projected map

    Return: the projection
    '''

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

    m = Basemap(projection=projection, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution=resolution)
    m.drawlsmask(land_color=land_color, ocean_color=ocean_color, lakes=lakes)
    m.drawcoastlines(linewidth=0.75)
    m.drawstates(linewidth=0.5)
    m.drawcountries(linewidth=0.5)

    return m
def plot_map(res, bins, cmap, cropName, fileName, technologyName, variableName, unitLabel, techFolder):
	
	figTitle = cropName + ' ' + technologyName + ' ' + variableName + ' (' + unitLabel + ')' 

	plt.close()
	plt.figtext(0.025,0.92, figTitle, clip_on = 'True', size = 'large', weight = 'semibold'); 
	plt.figtext(0.025,0.86, 'Spatially disaggregated production statistics of circa 2005 using the Spatial Production Allocation Model (SPAM).', clip_on = 'True', size = 'x-small', stretch = 'semi-condensed', weight = 'medium');
	plt.figtext(0.025,0.835,'Values are for 5 arc-minute grid cells.', clip_on = 'True', size = 'x-small', stretch = 'semi-condensed', weight = 'medium');

	plt.figtext(0.025,0.072, 'You, L., U. Wood-Sichra, S. Fritz, Z. Guo, L. See, and J. Koo. 2014', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium')
	plt.figtext(0.025,0.051, 'Spatial Production Allocation Model (SPAM) 2005 Version 2.0.', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium')
	plt.figtext(0.025,0.030, '03.10.2015. Available from http://mapspam.info', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium');

	plt.figimage(logos, 4100, 200)

	map = Basemap(projection='merc',resolution='i', epsg=4326, lat_0 = 0, lon_0 = 20, llcrnrlon=-160, llcrnrlat=-70, urcrnrlon=200, urcrnrlat=90)
	map.drawlsmask(land_color='#fffff0', lakes = False, zorder = 1)
	shp_coast = map.readshapefile(baseShpLoc + '/ne_50m_coastline/ne_50m_coastline', 'scalerank', drawbounds=True, linewidth=0.1, color = '#828282', zorder = 7)
	shp_rivers = map.readshapefile(baseShpLoc + '/ne_110m_rivers_lake_centerlines/ne_110m_rivers_lake_centerlines', 'scalerank', drawbounds=True, color='#e8f8ff', linewidth=0.1, zorder = 5)
	shp_lakes = map.readshapefile(baseShpLoc + '/ne_110m_lakes/ne_110m_lakes', 'scalerank', drawbounds=True, linewidth=0.1, color='#e8f8ff', zorder=4)

	paths = []
	for line in shp_lakes[4]._paths:
		paths.append(matplotlib.path.Path(line.vertices, codes=line.codes))
	coll_lakes = matplotlib.collections.PathCollection(paths, linewidths=0, facecolors='#e8f8ff', zorder=3)

	cs = map.pcolormesh(res.lons, res.lats, res.d2, cmap=cmap, norm=BoundaryNorm(bins, 256, clip=True), zorder = 6)

	map.drawcountries(linewidth=0.1, color='#828282', zorder = 8)

	ax = plt.gca()
	ax.add_collection(coll_lakes)

	cbar = map.colorbar(cs,location='bottom', pad='3%')

	if (variableName == 'Production' or variableName == 'Yield'):
		labelSize = 8
	else :
		labelSize = 7
	labels = [item.get_text() for item in cbar.ax.get_xticklabels()]
	labels[0] = '1'; labels[labelSize - 1] = labels[labelSize - 1] + ' <'; labels[labelSize] = ''
	cbar.ax.set_xticklabels(labels)

	plt.tight_layout(h_pad=0.9, w_pad = 0.9)
	
	outputFile = 'spam2005v2r0_' + techFolder + '_' + fileName + '_' + technologyName.lower()
	plt.savefig(outputFolder + '/' + techFolder + '/' + outputFile + '.png', format='png', dpi=900)
Example #17
0
def maping(rawimage, rawname, image, name):

	import palettable 
	import  matplotlib.colors as mpc
	
	fig = plt.figure()
	
	cmap = mpc.ListedColormap(palettable.colorbrewer.diverging.PiYG_9.mpl_colors)
	# cmap.set_bad('grey',1.)

	ax = fig.add_subplot(121)
	ax.set_title("a. (maxNDVI/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(rawimage), cmap=cmap, vmin=-0.01, vmax=0.0125,)
	map.colorbar()#ticks= [-0.01, -0.0075, -0.0050, -0.00250, 0.0000, 0.0025, 0.0050, 0.0075, 0.010, 0.0125])

	#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])
	# from palettable.colorbrewer.qualitative import Dark2_7


	ax = fig.add_subplot(122)
	ax.set_title("b. ((maxNDVI/mmrainfall)/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()

	#load the data into a figure
	map.imshow(np.flipud(image), cmap=cmap, vmin=-0.01, vmax=0.0125,)
	map.colorbar()#ticks= [-0.01, -0.0075, -0.0050, -0.00250, 0.0000, 0.0025, 0.0050, 0.0075, 0.010, 0.0125])

	#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 #18
0
def cat_mapper(image, cmap, title, vmin, vmax, vmin2=False, vmax2=False, cmap2=False, norm=False, save=False):
	"""To map things by a given number of catogeries"""

	fig = plt.figure()
	

	# cmap.set_bad('grey',1.)

	# ax = fig.add_subplot(1)
	plt.plot()
	if title is True:
		plt.title(title, loc= 'left')
	else:
		pass
	#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.drawstates()
	if norm == False:
		map.imshow(np.flipud(image), cmap=cmap, vmin=vmin, vmax=vmax)
	else:
		map.imshow(np.flipud(image), cmap=cmap, vmin=vmin, vmax=vmax, norm=norm)

	
	# 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])
	if vmax-vmin <= 1:
		tick_locator = ticker.MaxNLocator(nbins=20)
	else:
		tick_locator = ticker.MaxNLocator(nbins=vmax-vmin)
	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])

	if save is not False:
		plt.savefig("%s/CTSR/%d/R4_paperfigures/%s.png" % (path, crn, save))
	plt.show()
Example #19
0
def plot_map(ax, yc, xc, data, Projection_Parameters, cbar_loc=False, vmin=-1,
             vmax=1, cmap='GrBG'):

    m = Basemap(**Projection_Parameters)
    m.drawlsmask(land_color='white', ocean_color='0.8')
    m.drawcoastlines()
    m.drawparallels(np.arange(-80, 81, 20))
    m.drawmeridians(np.arange(-180, 181, 20))
    xi, yi = m(xc, yc)
    cm = matplotlib.cm.get_cmap(cmap)
    m.drawlsmask(land_color='white', ocean_color='0.8')
    ax = m.pcolor(xi, yi, data, cmap=cm, vmin=vmin, vmax=vmax)
    if cbar_loc:
        cbar = m.colorbar(ax, location=cbar_loc)
    else:
        cbar = None

    return cbar
Example #20
0
def mercator(request):
    import matplotlib
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    upper_lat = float(request.GET.get('upper_lat', 20))
    upper_lon = float(request.GET.get('upper_lon', 145))
    lower_lat = float(request.GET.get('lower_lat',-20))
    lower_lon = float(request.GET.get('lower_lon',90))
    true_lat = float(request.GET.get('true_lat',5))
    
    draw_ref_point = False
    try:
        ref_lat = float(request.GET.get('ref_lat'))
        ref_lon = float(request.GET.get('ref_lon'))
        draw_ref_point = True
    except:
        pass
    
    m = Basemap(projection='merc',llcrnrlat=lower_lat,urcrnrlat=upper_lat,
                llcrnrlon=lower_lon,urcrnrlon=upper_lon,lat_ts=true_lat,
                resolution=None)
    
    fig = Figure()
    canvas = FigureCanvas(fig)
    m.ax = fig.add_axes([0, 0, 1, 1])
    
#    m.drawcoastlines()
#    m.drawmapboundary(fill_color='aqua') 
#    m.fillcontinents(color='coral',lake_color='aqua')
#    m.etopo()
    m.drawlsmask(land_color='gray',ocean_color='white',lakes=True)
    m.drawparallels(np.arange(-90.,91.,30.), color='black')
    m.drawmeridians(np.arange(-180.,181.,60.), color='black')
    
    if draw_ref_point:
        x, y = m(ref_lon, ref_lat)
        m.plot(x, y, 'ro')
    
    response = HttpResponse(content_type='image/png')
    canvas.print_figure(response, dpi=100)
    return response
Example #21
0
def plotMap2(data2d):

    fig = figure(figsize=(12, 6))
    # ax=fig.add_axes([0.1,-0.1,0.8,1.3])

    m = Basemap(llcrnrlon=-120.,
                llcrnrlat=20.,
                urcrnrlon=-60.,
                urcrnrlat=50.,
                rsphere=(6378137.00, 6356752.3142),
                resolution='l',
                projection='merc',
                lat_0=40.,
                lon_0=-20.,
                lat_ts=0.)

    m.drawcoastlines()
    # m.fillcontinents()
    # draw parallels
    m.drawparallels(np.arange(50, 30, -10), labels=[1, 1, 0, 1])
    # draw meridians
    m.drawmeridians(np.arange(-120, -60, 30), labels=[1, 1, 0, 1])
    m.drawlsmask(land_color='Linen', ocean_color='#CCFFFF')
    # m.drawstates()
    # m.drawcountries()

    x, y = m(data2d[:, 0], data2d[:, 1])
    # plot(x,y,'o')
    triang = tri.Triangulation(x, y)
    xmid = x[triang.triangles].mean(axis=1)
    ymid = y[triang.triangles].mean(axis=1)
    aa = [m.is_land(xm, ym) for xm, ym in zip(xmid, ymid)]
    mask = np.where(aa, 0, 1)
    triang.set_mask(mask)

    # tripcolor(x,y,z)

    tricontourf(triang, data2d[:, 2], 20)
    colorbar(fraction=.02, pad=0.1)  # location='bottom', pad="10%")

    savefig('map2.eps')
    # show()
    return
Example #22
0
def make_map(fs, label_parallels=None, label_meridians=None):
    """
    function that creates map using Basemap. 
    
    Requires fontsize, and optional arguments governing labels for parallels and meridians. 
    
    Returns matplotlib plotting object. 
    """

    from mpl_toolkits.basemap import Basemap
    import numpy as np
    ##
    m = Basemap(llcrnrlon=-125,
                llcrnrlat=31,
                urcrnrlon=-102.5,
                urcrnrlat=50,
                projection='cyl',
                lat_1=33,
                lat_2=42,
                lon_0=-110,
                resolution='i',
                fix_aspect=True)
    # m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.drawmapboundary()

    m.drawparallels(np.arange(-90., 120., 10.))  # draw parallels
    m.drawmeridians(np.arange(0., 420., 10.))  # draw meridians

    if label_parallels:
        m.drawparallels(np.arange(-90., 120., 10.),
                        labels=[1, 0, 0, 0],
                        size=fs)  # draw parallels
    if label_meridians:
        m.drawmeridians(np.arange(0., 420., 10.), labels=[0, 0, 0, 1],
                        size=fs)  # draw meridians
    m.drawlsmask(land_color='silver',
                 ocean_color='lightblue',
                 lakes=True,
                 resolution='c')
    return (m)
Example #23
0
def map_Arctic(lon, lat, lat0, hit):
    '''
    =======================================================================
        Create a map of Arctic in Stereographic Proj., returns the object 
        of figure, axis and basemap frame.
                            ----- created on 2014/12/22, Yingkai (Kyle) Sha
    -----------------------------------------------------------------------
        fig, ax, proj = map_Arctic(...)
    -----------------------------------------------------------------------
        Input:
                lon, lat: longitude and latitude records, usually nav_lon, nav_lat
                lat0    : bounding latitude for Arctic
                hit     : (=1): maskland + draw parallels/meridians 
        Output:
                fig, ax, proj: figure, axis, basemap object
    =======================================================================    
    '''
    fig = plt.figure(figsize=(14, 14))
    proj = Basemap(projection='npstere',
                   resolution='l',
                   boundinglat=lat0,
                   lon_0=90,
                   round=True)
    ax = plt.gca()
    # parallels & meridians
    parallels = np.arange(-90, 90, 15)
    meridians = np.arange(0, 360, 60)
    lw = 0
    if hit == 1:
        lw = 0.5
    proj.drawparallels(parallels, labels=[1, 1, 1, 1],\
                      fontsize=10, latmax=90, linewidth=lw)
    proj.drawmeridians(meridians, labels=[1, 1, 1, 1],\
                      fontsize=10, latmax=90, linewidth=lw)
    # coastline, maskland
    proj.drawcoastlines(linewidth=1.5, linestyle='-', color='k', zorder=3)
    if hit == 1:
        proj.drawlsmask(land_color=[0.5, 0.5, 0.5],
                        ocean_color='None',
                        lsmask=None,
                        zorder=2)
    return fig, ax, proj
Example #24
0
 def drawAllCars(self, i=0):
     """
     A function to draw a plot of all cars in Shanghai in 1 hour!
     :param i:the target hour accept 0 ~ 23
     :return: None
     """
     if i < 0 or i > 23:
         print('not a valid hour!')
         return None
     s = '2018-04-01 ' + str(i).zfill(2) + ':00:00'
     e = '2018-04-02 ' + '00' + ':00:00'
     start = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
     end = datetime.datetime.strptime(e, '%Y-%m-%d %H:%M:%S')
     result = self.data.filter(
         lambda x: x[9] >= start and x[9] <= end).collect()
     lons = [h[10] for h in result]
     lats = [h[11] for h in result]
     plt.figure(figsize=(15, 15))
     map = Basemap(projection='merc',
                   resolution='h',
                   area_thresh=0.1,
                   llcrnrlon=121.05,
                   llcrnrlat=31.002,
                   urcrnrlon=121.9128,
                   urcrnrlat=31.4466)
     map.drawcoastlines()
     map.drawcountries()
     # map.fillcontinents(color='mistyrose',lake_color='slategrey')
     map.drawlsmask(land_color='slategray',
                    ocean_color='slategray',
                    lakes=True)
     # map.drawrivers(color = 'slategrey',linewidth=0.3)
     # map.drawmapboundary(fill_color='slategray')
     # lons = [h[10] for h in temp]
     # lats = [h[11] for h in temp]
     lon, lat = map(np.array(lons), np.array(lats))
     map.scatter(lon, lat, color='red', s=0.0001, alpha=0.1)
     fig = plt.gcf()
     path = '/home/bigdatalab24/' + str(i) + '.png'
     fig.savefig(path)
     plt.show()
Example #25
0
def sub_plot_pcolor(lons,
                    lats,
                    data,
                    title=None,
                    cmap=cm.jet,
                    vmin=None,
                    vmax=None,
                    cbar=True,
                    cbar_location='bottom',
                    units=None,
                    ncolors=5):

    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()

    m = Basemap(**projection)
    m.drawlsmask(land_color='grey', lakes=False)
    xi, yi = m(np.squeeze(lons), np.squeeze(lats))
    sp = m.pcolormesh(xi,
                      yi,
                      np.squeeze(data),
                      vmin=vmin,
                      vmax=vmax,
                      cmap=cmap)
    m.drawparallels(np.arange(-80., 81., 20.))
    m.drawmeridians(np.arange(-180., 181., 20.))
    m.drawcoastlines(color='k', linewidth=0.25)
    if title:
        plt.title(title, size=13)
    if cbar:
        cmap = cmap_discretize(cmap, ncolors)
        mappable = cm.ScalarMappable(cmap=cmap)
        mappable.set_array([])
        mappable.set_clim(-0.5, ncolors + 0.5)
        colorbar = m.colorbar(mappable, location=cbar_location)
        colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
        colorbar.set_ticklabels(np.linspace(vmin, vmax, ncolors))
        colorbar.set_label(units)
    return sp
Example #26
0
def show_data_on_map(data):
    """Shows probes locations on map of Can. Is."""

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_axes([0.1, 0.05, 0.8, 0.9])
    # create polar stereographic Basemap instance.
    m = Basemap(projection='stere',lon_0=-15.4,lat_0=28.1,lat_ts=28.1,\
            llcrnrlat=26.5,urcrnrlat=29.5,\
            llcrnrlon=-18.5,urcrnrlon=-13.5,\
            rsphere=6371200.,resolution='l',area_thresh=10000,epsg=4326)
    # draw coastlines, state and country boundaries, edge of map.
    m.drawcoastlines()
    m.drawcountries()
    m.drawstates()
    m.drawlsmask(resolution='f')
    m.arcgisimage(
        server='http://server.arcgisonline.com/ArcGIS',
        service='ESRI_Imagery_World_2D',
        xpixels=400,
        ypixels=None,
        dpi=96,
        verbose=False,
    )
    # draw parallels.
    parallels = np.arange(0., 90, 1.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
    # draw meridians
    meridians = np.arange(180., 360., 2.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)

    for ext in best_exts:
        sdata = data[ext]
        lat = sdata['lat'].data.copy()
        lon = sdata['lon'].data.copy()
        m.plot(lon, lat, 'o', label=ext, alpha=0.5)
        #ax.plot(lat,lon,'o',label=ext)

    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles, labels, loc='lower right')
    ax.set_title('Probes Geographical  Distribution', fontsize=14)
    plt.show()
Example #27
0
def surft(ax, scenario, di, lakeplist, laketable):
    '''draws a map of surface temperature on ax
    scenario: scenario dir name
    di: day index
    lakeplist: path the the lakes (under this we find the scenario)
    laketable: pandas.DataFrame with names latitude and longitude
    ** order of lakes in lakeplist and laketable needs to be the same
    '''
    flist = [os.path.join(lp, scenario, 'Tzt.csv.gz') for lp in lakeplist]
    out = np.zeros(shape=(len(lakeplist), )) * np.nan
    for i, gzp in enumerate(flist):
        if i % 1000 == 0: 
            print('... running %sth lake' % i)
        with gzip.open(gzp, 'rb') as gzf:
            for _ in xrange(di):
                next(gzf)
            line = gzf.readline()
            out[i] = line.split(',')[0]
    outfloat = map(float, out)
    m = Basemap(width=1.65e6, height=1.95e6, lat_0=63, lon_0=18, projection='lcc') 
    # m.shadedrelief()
    m.drawlsmask(land_color='gray', ocean_color='lightblue', 
                 lakes=False, resolution='f', grid=1.25)
    # m.drawcoastlines()
    # m.drawcountries()
    # m.drawmapboundary(fill_color='lightgray')
    # m.drawmeridians(range(-10, 45, 2))
    # m.drawparallels(range(50, 80, 5))
    # m.fillcontinents(color='white')
    colours = []
    alpha = 0.7
    for temperature in outfloat:
        if temperature == 0.0:
            colours.append([0.9, 0.9, 0.9, alpha]), 
        else:
            colours.append(mpl.cm.coolwarm(min(1, temperature/23.0), alpha=alpha))
    m.scatter(laketable['longitude'].values, laketable['latitude'].values,
              s=np.sqrt(laketable['area'].values)/50, c=colours, 
              marker='.', # linestyle='None', 
              linewidths=0,         
              latlon=True)
Example #28
0
def plot_compare_map(lons, lats, y_true, y_predict, timestamp, s=None, 
                     cmap=None, outdir='/home/ubuntu/dataset/output/'):
    """
    Plots the actual and predicted values side by side for comparison. 
    """ 
    timestamp = str(int(timestamp))
    yr = timestamp[:4]
    mn = timestamp[4:6]
    dt = timestamp[6:]
    
    if cmap is None:
        cmap=mpl.cm.get_cmap('RdYlGn')
        
    area_thresh=25000
    land_color='grey'
    ocean_color='lightblue'

    fig = plt.figure(figsize=(10,7))
    plt.title('/'.join([yr, mn, dt]), loc='right', fontsize=14)
    plt.axis('off')
    ax = fig.add_subplot(2,1,1)
    m = Basemap(projection='cyl', llcrnrlat=lats.min(), llcrnrlon=lons.min(),
            urcrnrlat=lats.max(), urcrnrlon=lons.max(), resolution='f',
            area_thresh=area_thresh)
    m.scatter(lons, lats, c=y_true, edgecolor='none', cmap=cmap, s=s)
    m.drawlsmask(land_color=land_color, ocean_color=ocean_color, lakes=True)
    m.drawcountries()
    m.drawcoastlines()
    
    ax = fig.add_subplot(2,1,2)
    m = Basemap(projection='cyl', llcrnrlat=lats.min(), llcrnrlon=lons.min(),
            urcrnrlat=lats.max(), urcrnrlon=lons.max(), resolution='f',
            area_thresh=area_thresh)
    m.scatter(lons, lats, c=y_predict,edgecolor='none',cmap=cmap, s=s)
    m.drawlsmask(land_color=land_color, ocean_color=ocean_color, lakes=True)
    m.drawcountries()
    m.drawcoastlines()
    img_path = outdir+str(int(timestamp))+'.png'
    plt.savefig(img_path, bbox_inches='tight', dpi=300)
    return img_path
def basemap_temperature(data_comp,met):
    lat_ts=90.0 ; lat_0=90.0 ; lon_0=-45.0 ;
    sgn=1
    width=7000000. ; height=7000000.0 ;
    vmin = 32 ; vmax = 36 ;
    ind = 0
    
    if met == 5:
        mm = 0
    elif met == 200:
        mm = 16
    elif met == 400:
        mm = 21
    else:
        print "error: wrong depth level"
    
    fig, axes = plt.subplots(2,3)
    for data in data_comp:
        m = Basemap(ax=axes.flat[ind],width=width,height=height,resolution='h',\
                    projection='stere',lat_ts=lat_ts,lat_0=lat_0,lon_0=lon_0)
        # the continents will be drawn on top.
        #m.drawmapboundary(fill_color='white')
        # fill continents, set lake color same as ocean color.
        #m.fillcontinents(color='grey',lake_color='navy')
        m.drawlsmask(land_color='grey',ocean_color='white',lakes=True)

        x,y=m(data_comp[data].lon,data_comp[data].lat)
        datam = data_comp[data].S[mm,:,:]
        sitm = np.ma.masked_where(np.isnan(datam),datam)
        CS=m.pcolormesh(x,y,sitm,cmap=cmocean.cm.salt,vmin=vmin,vmax=vmax)
        m.drawparallels(np.arange(-80.,81.,15.))
        m.drawmeridians(np.arange(-180.,181.,30.))
        #m.drawcoastlines()
        axes.flat[ind].set_title('Sal at '+str(met)+'m - '+data_comp[data].title)
        ind += 1
    cbar_ax = fig.add_axes([1.9, 0.3, 0.045, 1.4])
    cbar = plt.colorbar(CS, cax=cbar_ax,)
    cbar.ax.set_ylabel(r'$psu$')
    plt.delaxes(axes.flat[-1])
    fig.subplots_adjust(right=1.7,top=1.8)
Example #30
0
def plotCOColumn():
    """
    在地图上画出柱浓度图
    """
    fig = plt.figure(figsize=(11, 8))
    rect = fig.patch
    rect.set_facecolor("white")
    data = np.loadtxt("seasonAvr_data/TotalColumn/1_seasonAvr.txt")
    longitude = np.loadtxt("lonlat_data/longitude.txt")
    latitude = np.loadtxt("lonlat_data/latitude.txt")

    m = Basemap(llcrnrlon=75, llcrnrlat=15, urcrnrlon=138, urcrnrlat=55, projection="mill", resolution="h")
    m.drawparallels(np.arange(5.0, 90.0, 10.0), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(60.0, 181.0, 15.0), labels=[0, 0, 1, 0])
    m.readshapefile("shp/CHINA", "CHINA", drawbounds=1, color="black")
    topo = maskoceans(longitude, latitude, data)

    im = m.pcolormesh(longitude, latitude, topo, shading="flat", cmap=plt.cm.jet, latlon=True, vmin=1.0e18, vmax=4.0e18)
    m.drawlsmask(ocean_color="w", lsmask=0)
    cbar = m.colorbar()
    cbar.ax.set_ylabel("CO coloumn(molecules $cm^{-2}$)", color="black", fontsize="13", rotation=90)
    plt.show()
    def _prepare_plot(self, resolution="i"):
        """
        Prepare basemap for plotting results of some query
        :rtype: Basemap
        :param resolution: Set basemap resolution / area threshold that shall
        still be displayed (see Basemap documentation for further details)
        :return: Basemap
        """
        # Determine bounding box if no clipping boundary was supplied
        if not self.region.bounds or type(self.region.bounds) == str:
            if isinstance(self, OSMCollection):
                if hasattr(self, 'Points'):
                    self.region.bounds = self.bbox_of_view(self.Points.results)
                elif hasattr(self, 'Lines'):
                    self.region.bounds = self.bbox_of_view(self.Lines.results)
                elif hasattr(self, 'Polygons'):
                    self.region.bounds = self.bbox_of_view(
                        self.Polygons.results)
            else:
                self.region.bounds = self.bbox_of_view(self.results)

        bbox = {'xmin': self.region.bounds[0],
                'ymin': self.region.bounds[1],
                'xmax': self.region.bounds[2],
                'ymax': self.region.bounds[3]}

        m = Basemap(resolution=resolution,
                    projection='merc',
                    llcrnrlat=bbox['ymin'] - 0.02,
                    urcrnrlat=bbox['ymax'] + 0.02,
                    llcrnrlon=bbox['xmin'] - 0.02,
                    urcrnrlon=bbox['xmax'] + 0.02,
                    lat_ts=(bbox['xmin'] +
                            bbox['xmax']) / 2)
        m.drawcoastlines()
        m.drawlsmask(land_color='white', ocean_color='aqua', lakes=True)
        m.drawcountries()

        return m
def final_map(lonc, latc, sem1, sem2, rot=0, time=0, tstd=0):
    # plots the final answer from the iteration on a tight axis around the
    # epicentral location
    # additionally adds an error ellipse based on supplied values

    # Create map (static boundaries match random initial guess bounds)
    m = Basemap(llcrnrlon=lonc - 3.,
                llcrnrlat=latc - 2.,
                urcrnrlon=lonc + 3.,
                urcrnrlat=latc + 2.,
                resolution='l')

    # map cosmetics
    m.drawstates()
    m.drawcountries()
    m.drawcoastlines()
    m.drawlsmask(land_color='coral', ocean_color='aqua', grid=1.25)

    el = Ellipse((lonc, latc),
                 sem1,
                 sem2,
                 rot,
                 facecolor='b',
                 zorder=10,
                 alpha=0.4)
    plt.gca().add_patch(el)

    xcurr, ycurr = m(lonc, latc)
    m.scatter(xcurr, ycurr, marker='D', color='b')

    if (time * tstd) != 0:
        mylabel = r"t = {:.2f} $\pm$ {:.2f}s".format(time, tstd)
        plt.annotate(mylabel,
                     xy=(xcurr, ycurr),
                     xycoords='data',
                     xytext=(-100., -15.),
                     textcoords='offset points',
                     color='k')
Example #33
0
def plot_sites_on_map(coordinate_dict, problem_sites):
    m = Basemap(projection='merc',llcrnrlat=40,urcrnrlat=50,\
            llcrnrlon=-129,urcrnrlon=-118,resolution='i')
    # Draw the coastlines
    m.drawcoastlines()
    # Color the continents
    # Bug in drawcoastlines does not allow points mapped above land. We use drawlsmask instead.
    m.drawlsmask(land_color='0.8', ocean_color='w')
    # draw parallels and meridians.
    m.drawparallels(np.arange(-90., 91., 2.), labels=[1, 0, 0, 0], fontsize=10)
    m.drawmeridians(np.arange(-180., 181., 2.),
                    labels=[0, 0, 0, 1],
                    fontsize=10)
    plt.title("GPS sites")
    # Transform long and lat to the map projection
    # Each lat and long value in the maps above are 'mapped' to specific pixels that make up the image
    # The mapping, defined by the projection used, needs to also be done on the data set.
    lon = []
    lat = []
    prob_lon = []
    prob_lat = []
    for key in coordinate_dict.keys():
        mod_lon = (360. - float(coordinate_dict[key]['lng'])) * -1.
        mod_lat = coordinate_dict[key]['lat']
        lon.append(mod_lon)
        lat.append(mod_lat)
        if key in problem_sites:
            prob_lon.append(mod_lon)
            prob_lat.append(mod_lat)
    x, y = m(lon, lat)
    px, py = m(prob_lon, prob_lat)
    # Now you can use the plt.scatter method to plot your data!
    plt.scatter(x, y, s=20)
    plt.scatter(px, py, s=20, color='red')
    filename = 'figures/gps_map.png'
    plt.savefig(filename)
    plt.show()
Example #34
0
def plot_diff_map(lons, lats, y_true=None, y_predict=None, y_diff=None, timestamp=None, 
                  s=None, cmap=None, outdir='/home/ubuntu/dataset/output/'):
    """
    Plots the difference between the actual and predicted values on a map. 
    """ 
    timestamp = str(int(timestamp))
    yr = timestamp[:4]
    mn = int(timestamp[4:6])
    dt = timestamp[6:]
    months_lst = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    
    title = months_lst[mn]+' '+dt+', '+yr
    
    if cmap is None:
        cmap=mpl.cm.get_cmap('seismic')
    norm = mpl.colors.Normalize(vmin=-1.5,vmax=1.5)
        
    area_thresh=2500
    land_color='grey'
    ocean_color='lightblue'

    fig = plt.figure(figsize=(9,7))
    plt.title(title, fontsize=18, fontweight='bold', loc='center')
    plt.axis('off')
    m = Basemap(projection='merc', llcrnrlat=lats.min(), llcrnrlon=lons.min(),
            urcrnrlat=lats.max(), urcrnrlon=lons.max(), resolution='f',
            area_thresh=area_thresh)
    xi, yi = m(lons, lats)
    if y_diff is None:
        y_diff = y_predict-y_true
    m.scatter(xi, yi, c=y_diff, edgecolor='none', cmap=cmap, s=s, norm=norm)
    m.drawlsmask(land_color=land_color, ocean_color=ocean_color, lakes=True)
    plt.tight_layout()

    img_path = outdir+str(int(timestamp))+'.png'
    plt.savefig(img_path, bbox_inches='tight', dpi=300)
    return img_path
Example #35
0
plt.title('filled continent background')

# as above, but use land-sea mask image as map background.
fig = plt.figure()
bmap.drawmapboundary()
bmap.drawmeridians(np.arange(0,360,30))
bmap.drawparallels(np.arange(-90,90,30))
# plot filled circles at the locations of the cities.
bmap.plot(xc,yc,'wo')
# plot the names of five cities.
for name,xpt,ypt in zip(cities,xc,yc):
    plt.text(xpt+50000,ypt+50000,name,fontsize=9,color='w')
# contour data over the map.
cs = bmap.contour(x,y,wave+mean,15,linewidths=1.5)
plt.title('land-sea mask background')
bmap.drawlsmask(ocean_color='aqua',land_color='coral')

# as above, but use blue marble image as map background.
fig = plt.figure()
bmap.drawmapboundary()
bmap.drawmeridians(np.arange(0,360,30))
bmap.drawparallels(np.arange(-90,90,30))
# plot filled circles at the locations of the cities.
bmap.plot(xc,yc,'wo')
# plot the names of five cities.
for name,xpt,ypt in zip(cities,xc,yc):
    plt.text(xpt+50000,ypt+50000,name,fontsize=9,color='w')
# contour data over the map.
cs = bmap.contour(x,y,wave+mean,15,linewidths=1.5)
plt.title('blue marble background')
bmap.bluemarble()
Example #36
0
def plotSpatial(argv):
    fig, axes = plt.subplots(nrows=int(len(argv['models'])),
                             ncols=1,
                             figsize=(8, 16),
                             dpi=100,
                             sharex=True,
                             sharey=True)
    axes = axes.flatten()
    for i, model in enumerate(argv['models']):
        fpath = '../data/annual/%s-avg.nc' % model
        dataset = Dataset(fpath, mode='r')
        LONS = dataset.variables['long'][:]
        LATS = dataset.variables['lat'][:]
        var = dataset.variables[argv['variableNames'][i]]
        lon_0 = LONS.mean()
        lat_0 = LATS.mean()

        ax = axes[i]
        ax.set_title(model + ': ' + argv['label'] + ' (' + var.units + ')')
        # fig.subplots_adjust(left=.1, right=.9, top=.9, bottom=.1)
        m = Basemap(projection='kav7', lat_0=lat_0, lon_0=lon_0, ax=ax)
        m.drawlsmask(land_color='#EFEFEF', ocean_color="#FFFFFF")
        m.drawparallels(np.arange(-90., 91., 30.),
                        labels=[1, 0, 0, 0],
                        fontsize=12,
                        linewidth=.2)
        m.drawmeridians(np.arange(-180., 181., 40.),
                        labels=[0, 0, 0, 1],
                        fontsize=8,
                        linewidth=.2)
        m.drawcoastlines(linewidth=.2)

        lon, lat = np.meshgrid(LONS, LATS)
        xi, yi = m(lon, lat)
        # # 以下生成的网格坐标范围为 long: [-180, 180]  lat: [-90, 90],与此处的nc不符
        # ny = data.shape[0]
        # nx = data.shape[1]
        # LONS, LATS = m.makegrid(nx, ny)
        # x, y = m(LONS, LATS)
        cmap = LinearSegmentedColormap.from_list('custom_cb', [
            (0, '#B8B8B8'),
            (0.125, '#615EFE'),
            (0.25, '#0080AC'),
            (0.375, '#01B251'),
            (0.5, '#73C605'),
            (0.675, '#DEF103'),
            (0.75, '#FF9703'),
            (0.875, '#FC0101'),
            (1, '#B30404'),
        ],
                                                 N=125)
        masked = maskoceans(lon, lat, var[:])
        # data = np.ma.masked_equal(masked, 0)
        cs = m.contourf(xi,
                        yi,
                        masked,
                        argv['clevs'][i],
                        cmap=cmap,
                        extend='both')
        cbar = m.colorbar(cs, location='right',
                          pad='5%')  # label='kgC m-2 y-1'
        cbar.ax.tick_params(labelsize=12)
        dataset.close()

    fig.tight_layout()
    fig.subplots_adjust(bottom=.1, hspace=0.2)
    # [left, bottom, width, height]
    # cbar_ax=fig.add_axes([.1, .05, .8, .015])
    # cbar = fig.colorbar(cs, cax=cbar_ax, orientation='horizontal')
    # cbar.set_label('kgC m-2 y-1')

    plt.savefig('../figure/%s.jpg' % argv['label'])
    plt.close('all')
    print(argv['label'] + ' spatial map')
Example #37
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
# setup Lambert Conformal basemap.
# set resolution=None to skip processing of boundary datasets.
m = Basemap(width=12000000,height=9000000,projection='lcc',
            resolution=None,lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.)
# draw a land-sea mask for a map background.
# lakes=True means plot inland lakes with ocean color.
m.drawlsmask(land_color='coral',ocean_color='aqua',lakes=True)
plt.show()
plt.show()
lims['ukraine']       = [  19.0, 42.0,   43.0, 54.0]
lims['mediterranean'] = [ -70.0,  5.0,   75.0, 55.0]
lims['world']         = [-180.0,-60.0,  180.0, 80.0]
lims['nscamerica']    = [-180.0,-60.0,  -30.0, 80.0]
lims['usa_con']       = [-175.0, 24.0,  -40.0, 72.0]
lims['usa_main']      = [-130.0, 23.0,  -62.0, 50.0]

lm = lims[crop_region]
m = Basemap(projection='merc', lat_0 = 0, lon_0 = 0, lat_ts=20.,
            resolution = resolution, area_thresh = 0.1,
            llcrnrlon=lm[0], llcrnrlat=lm[1],
            urcrnrlon=lm[2], urcrnrlat=lm[3])

# Map options
#m.bluemarble() #Use images for backgound. Hard to see routes
m.drawlsmask() #Nice grey outlines
#m.drawcoastlines(linewidth=0.2)  #Unfortunately, has lakes too
m.drawcountries()
#plt.show() #Just to test out


wrap_count=0
line_count=0

if filename.endswith(".gz"):
    file = gzip.open(filename)
elif filename.endswith(".bz2"):
    file = bz2.BZ2File(filename)
else:
    file = open(filename)
Example #39
0
            round=True)
m.drawmapboundary(fill_color='white')
m.drawcoastlines(color='k', linewidth=0.1)
parallels = np.arange(50, 90, 10)
meridians = np.arange(-180, 180, 30)
m.drawparallels(parallels,
                labels=[True, True, True, True],
                linewidth=0.2,
                color='k',
                fontsize=5)
m.drawmeridians(meridians,
                labels=[True, True, True, True],
                linewidth=0.2,
                color='k',
                fontsize=5)
m.drawlsmask(land_color='darkgrey', ocean_color='w')

### Adjust maximum limits
values = np.arange(-0.2, 0.21, 0.01)

### Plot filled contours
cs = m.contourf(lons[:, :],
                lats[:, :],
                val[:, :],
                values,
                latlon=True,
                extend='both')
cs1 = m.contour(lons[:, :],
                lats[:, :],
                val[:, :],
                values,
Example #40
0
def plot_variable(file_list,variable2plot):
    map = Basemap(projection='merc',llcrnrlat=44.,urcrnrlat=58.447,\
    llcrnrlon=-10.,urcrnrlon=18.,resolution='l')   #Paris: lat = 48.5 - 52, lon = 1 - 4.5

#59 , -10
#44 , 18

    # draw coastlines, country boundaries, fill continents.
    map.drawcoastlines(linewidth=0.6, color = 'black')
    map.drawcountries(linewidth = 0.6, color = 'black')
   
    map.drawlsmask(land_color='white',ocean_color='white')

    # draw lat/lon grid lines every x degrees.
    map.drawparallels(np.arange( -90.,90.,1.),linewidth=0.1,color = 'Black',labels=[1,0,0,0])
    map.drawmeridians(np.arange(-180.,180.,1.),linewidth=0.1,color = 'Black',labels=[0,0,0,1])
   
    cmap = cm.get_cmap(name='rainbow')   #NO2: 'rainbow'   clouds: 'Blues_r'
    cmap.set_under('white')
    #cmap.set_under('0.3')
    #cmap.set_over('1.0')

    data_range = None
    dynamic_range = False
    if data_range is None:
        data_range = [1e20, -1e20]
        dynamic_range = True

    filters = [
               'cloud_radiance_fraction_nitrogendioxide_window < 0.5',
               'surface_albedo < 0.3',
               'air_mass_factor_troposphere > 0.2'
]

    data = []

    for f in file_list:    
        var,latb,lonb,extended_name, unit = get_data(f,variable2plot,filters) 

        xtrack_range = None
    
        if dynamic_range:
            try:
                sel_data = var.data[np.logical_not(var.mask)]
                if sel_data.shape[0] == 0:
                    print 'continue in the loop'
            except AttributeError:
                sel_data = var            
        
            data_range[0] = min(np.nanmin(sel_data), data_range[0])
            data_range[1] = max(np.nanmax(sel_data), data_range[1])

        data.append((var, latb, lonb))
    for var, latb, lonb in data:
        x,y = map(lonb,latb)
        if xtrack_range is None:
            cs = map.pcolor(x,y,var,cmap=cmap,latlon=False,vmin=0, vmax=20e15)  #-10e15, vmax=20e15
        else:
                # pcolormesh
            cs = map.pcolor(x[:,:],
                            y[:,:],
                            var[:,:],
                            cmap=cmap,
                            latlon=False, 
                            vmin=data_range[0], vmax=data_range[1])

    cbar = map.colorbar(cs,location='right',pad="12%", extend="both")
    cbar.set_label(unit)
    
    # Label for the plot
    label = 'TROPOMI o00569 - 11-22-2017'
    #if label is None:
     #   plt.title(extended_name)
    #else:
        #plt.title("{0} - {1}".format(extended_name,label))
    
    # Name of the file for figure
    fig = 'paris_1122_tropomi'
    if fig is None:
        plt.show()
    else:
        f = plt.gcf()
        f.set_size_inches(10.0, 6.0, forward=True)
        plt.savefig(fig, dpi=300)
        plt.show()
Example #41
0
def worldmap(grid_data=None,
             boxlat=None,
             boxlon=None,
             label=None,
             scatter=False,
             ax=None,
             df=None,
             dfkey=None,
             vmin=0,
             vmax=1000,
             nb=50.0,
             sb=22.0,
             wb=-130.0,
             eb=-60.0,
             maskocean=True,
             colorbar=True,
             return_cs=False):
    m = Basemap(
        projection='merc',
        resolution='l',
        # get these from conusdata
        llcrnrlon=wb,  # lower right cornet lat
        llcrnrlat=sb,
        urcrnrlon=eb,  # upper right corner
        urcrnrlat=nb,
        ax=ax)  # latitude of the true scale
    # draw coastlines, state and country boundaries, edge of map.
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    parallels = np.arange(-50., 50, 10.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
    meridians = np.arange(-180., 180., 20.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)
    maplat, maplon = np.meshgrid(boxlat, boxlon)
    x, y = m(maplon, maplat)  # compute map proj coordinates.
    np.shape(y)
    if maskocean:
        newdata = maskoceans(maplon, maplat, grid_data)
    else:
        newdata = grid_data
    cs = m.pcolormesh(x,
                      y,
                      newdata,
                      cmap='jet',
                      vmin=vmin,
                      vmax=vmax,
                      norm=mpl.colors.LogNorm())
    if not scatter:
        if colorbar:
            cbar = m.colorbar(cs,
                              location='bottom',
                              pad="8%",
                              norm=mpl.colors.LogNorm())
            cbar.set_label(label)
    if scatter:
        sc = m.scatter(df['LON'].values,
                       df['LAT'].values,
                       marker='o',
                       c=df[dfkey].values,
                       s=5,
                       zorder=10,
                       latlon=True,
                       cmap='jet',
                       vmin=vmin,
                       vmax=vmax)
        if colorbar:
            cbar2 = m.colorbar(sc, location='bottom', pad="8%")
            cbar2.set_label(label)
    m.drawlsmask(land_color=(0, 0, 0, 0), ocean_color='w', lakes=True)
    if return_cs:
        return m, cs
    else:
        return m
Example #42
0
		if args.it:
			inf=float(it[i])
		else:
			inf=0.
		if args.st:
			sup=float(st[i])
		else:
			sup=ma.max(var)
		
		m = Basemap(llcrnrlat=min(lat),urcrnrlat=max(lat),\
			llcrnrlon=min(lon),urcrnrlon=max(lon), resolution='f')
		x,y=np.meshgrid(lon, lat)
		m.drawparallels(np.linspace(min(lat), max(lat), 7),labels=[0,0,0,0])
		m.drawmeridians(np.linspace(min(lon), max(lon), 7),labels=[0,0,0,0])
		if res=='f':
			m.drawlsmask(land_color=RGB.hex_format(RGB(169,169,169)),ocean_color=RGB.hex_format(RGB(169,169,169)),resolution='f',lakes=True, grid=1.25) #same colour for land and ocean
			for (r,i) in zip(borders, range(len(borders))): #plot the borders and fill the continent if the polygon is inside poly_NAD
				#if inf['NAM']!='UNK':
				#if r.intersects(poly_NAD):
				elements=list(r.exterior.coords)
				xx,yy=zip(*elements)
				xy = zip(xx,yy)
				poly = Polygon( xy )
				if poly.intersects(poly_NAD)==True:
					m.plot(xx,yy,marker=None, color='black', linewidth=0.5)
					poly = matplotlib.patches.Polygon( xy, facecolor=RGB.hex_format(RGB(238, 213, 183)) )
					plt.gca().add_patch(poly)
		else:
			m.drawlsmask(land_color=RGB.hex_format(RGB(238, 213, 183)),ocean_color=RGB.hex_format(RGB(169,169,169)),resolution='f',lakes=True, grid=1.25)	
			m.drawcoastlines()
			
Example #43
0
lon_0 = float(raw_input('enter reference longitude (lon_0):'))
lat_0 = float(raw_input('enter reference latitude (lat_0):'))

# map with land/sea mask plotted
fig = plt.figure()
resolution = 'l'
grid = 5
m = Basemap(projection='ortho',
            lon_0=lon_0,
            lat_0=lat_0,
            resolution=resolution)
# land coral, oceans aqua.
# lakes=True means plot inland lakes with ocean color.
# resolution = 5 (default) means use 5 min dataset (can use 2.5)
m.drawcoastlines()
m.drawlsmask(land_color='coral',ocean_color='aqua', lakes=True,\
        resolution=resolution,grid=grid)
# draw parallels and meridians.
m.drawparallels(np.arange(-90., 120., 30.))
m.drawmeridians(np.arange(0., 420., 60.))
m.drawmapboundary()
plt.title('Orthographic Map Centered on Lon=%s, Lat=%s' % (lon_0, lat_0))

# map with continents drawn and filled (continent filling fails for
# lon=-120,lat=60).
fig = plt.figure()
m = Basemap(projection='ortho',
            lon_0=lon_0,
            lat_0=lat_0,
            resolution=resolution)
m.drawcoastlines()
m.fillcontinents(color='coral', lake_color='aqua')
Example #44
0
lons, data = m.shiftdata(lon, datain=temp[0, :, :], lon_0=None)
x, y = m(lons, lat)
Z = maskoceans(lons, lat, data, inlands=True, resolution='c', grid=2.5)
#clevs=[-50,-40,-20,-10,0,5,10,15,20,25,30,35,40,45] ; cmap=plt.get_cmap('hot_r')
clevs = [0, 5, 10, 15, 25, 30, 35, 40]
#nice_cmap= plt.get_cmap('RdYlBu')
#colors = nice_cmap([0,8, 16, 40, 60, 80,100,120,140])
#colors = nice_cmap([0,10,20,40,60,80,100,130,160])
#levels = [0, 5, 10, 15, 25,30,35,40] ;
#cmap, norm = from_levels_and_colors(levels, colors, extend='both')
#cs=m.pcolormesh(x,y,data, cmap=cmap, norm=norm)

cs = (m.contourf(x, y, data, clevs, cmap=plt.cm.RdYlBu))
#m.warpimage(image='venuscyl4.jpg')
#(m.readshapefile('ncfiles/subdiv/India_subdiv','ind',drawbounds=True, zorder=None, linewidth=1.0, color='k', antialiased=1, ax=None, default_encoding='utf-8'))
(m.drawlsmask(land_color='grey', ocean_color='white', lakes=False))
m.fillcontinents(color='white', lake_color='white')
(m.drawparallels(np.arange(-90, 90., 45.), labels=[1, 0, 0, 0]))
(m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1]))
(m.drawmapboundary(fill_color='white'))
(m.drawcoastlines(linewidth=0.25))
(m.drawcountries(linewidth=0.25))
(m.drawstates(linewidth=0.25))
cbar = (m.colorbar(cs, location='right', pad='5%'))
(cbar.set_label('degC'))
# m.shaderelief()
#m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 1500, verbose= True)
(plt.title('Sea Surface Temperature(degC)'))
savefig('sst_globe.png', dpi=100)
plt.show()
""" rainfall """
                     y,
                     varsst,
                     np.arange(-3, 3.01, 0.25),
                     extend='both',
                     alpha=1,
                     zorder=1)
    cs3 = m.contour(x,
                    y,
                    varsicmean,
                    np.arange(15, 30, 15),
                    alpha=1,
                    linewidths=2,
                    colors='gold',
                    zorder=3)

    m.drawlsmask(land_color='dimgrey', ocean_color='k')
    m.drawcoastlines(color='k', linewidth=0.1, zorder=6)
    m.fillcontinents(color='dimgrey', lake_color='dimgrey', zorder=5)
    parallels = np.arange(50, 86, 5)
    meridians = np.arange(-180, 180, 30)
    m.drawparallels(parallels,
                    labels=[False, False, False, False],
                    linewidth=0.0,
                    color='w')
    par = m.drawmeridians(meridians,
                          labels=[True, True, False, False],
                          linewidth=0.0,
                          fontsize=4,
                          color='w')
    setcolor(par, 'darkgrey')
Example #46
0
        llcrnrlat=22,
        urcrnrlon=-60,  # upper right corner
        urcrnrlat=52,
        lat_ts=35)  # latitude of the true scale
    # draw coastlines, state and country boundaries, edge of map.
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    parallels = np.arange(0., 90, 10.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
    meridians = np.arange(180., 360., 10.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)
    maprlon, maprlat = np.meshgrid(rlon, rlat)
    xr, yr = m(maprlon, maprlat)  # compute map proj coordinates.
    cs = m.contourf(xr, yr, Band1)
    m.drawlsmask(land_color=(0, 0, 0, 0), ocean_color='w', lakes=True)
    sc = m.scatter(dfs['LON'].values,
                   dfs['LAT'].values,
                   marker='o',
                   c='red',
                   s=1,
                   zorder=10,
                   latlon=True)
    cbar = m.colorbar(cs, location='bottom', pad="8%")
    cbar.set_label('Elevation [m MSL]')
    plt.title('Elevation', fontsize=12)
    plt.savefig(os.path.join(cfun.outplot, 'Original_elevation.png'), dpi=100)
    plt.show()

    data = mean_el
"""


##Plot data
plt.figure(figsize=(16,10))
plt.tight_layout()
m = Basemap(projection='merc',llcrnrlat=y1m.min(),urcrnrlat=y1m.max(),\
            llcrnrlon=x1m.min(),urcrnrlon=x1m.max(),lat_ts=20,resolution='l', area_thresh=0)
#m = Basemap(projection='merc',llcrnrlat=bminlat,urcrnrlat=bmaxlat,\
            #llcrnrlon=bminlon,urcrnrlon=bmaxlon,lat_ts=20,resolution='l', area_thresh=0)
m.drawparallels(np.arange(-80., 81., 3.), labels=[1, 0, 0, 0], fontsize=15)
m.drawmeridians(np.arange(-180., 181., 3.), labels=[0, 0, 0, 1], fontsize=15)
# Add Bermuda outline
m.drawcoastlines()
m.fillcontinents()
m.drawlsmask(land_color='grey',ocean_color='white',lakes=True)
x1_mask, y1_mask = m(x1m, y1m)
x11, y11 = m(x1, y1)
#plt.contourf(x1_mask, y1_mask,bz_c, cmap = 'Blues')
#plt.contourf(x1_mask, y1_mask,bz_a, cmap = 'Reds')
#plt.contourf(x11, y11,nz_c, cmap = 'Blues')
plt.contourf(x11, y11,nz_a, cmap = 'Reds')
plt.colorbar(label='Eddy concentration (mean counts/year)', orientation='vertical')
plt.title('Frequency of eddies in the Bermuda region \n from ROMS model')
plt.savefig(image_path + 'eddy_freq_Bermuda_NWAT_anticyclonic.png', bbox_inches = 'tight')

#Plot anomaly (sigma)
sigma = (bz_a/5 + bz_c/5) - nz_a - nz_c
a_sigma = bz_a/5 - nz_a
c_sigma = bz_c/5 - nz_c
plt.figure(figsize=(16,10))
Example #48
0
### Call parameters
plt.rcParams['text.usetex']=True
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'Avant Garde'

yearnew = np.arange(2003,2010,1)

### Define figure
fig = plt.figure()    
for i in xrange(len(thickness)):
    ax = plt.subplot(2,4,i+1)    
    m = Basemap(projection='npstere',boundinglat=60,lon_0=-90,resolution='l',round=True)
    m.drawmapboundary(fill_color = 'white')
    m.drawcoastlines(color = 'darkgrey',linewidth=0.2)
    m.drawlsmask(land_color='darkgrey',ocean_color='snow')
    parallels = np.arange(50,90,10)
    meridians = np.arange(-180,180,30)
    m.drawparallels(parallels,labels=[False,False,False,False],linewidth=0.25)
    m.drawmeridians(meridians,labels=[False,False,False,False],linewidth=0.25)
    
    cs = m.contourf(lon,lat,thickness3[i,:,:],np.arange(-3,3.1,0.25),
                    latlon=True,extend='both')
    cs.set_cmap('seismic_r')
    ax.text(0.89,0.95,r'\textbf{%s}' % (yearnew[i]),size='9',
            horizontalalignment='center',backgroundcolor='w',
            verticalalignment='center',bbox=dict(facecolor='w',
            edgecolor='k',alpha=0.9),transform=ax.transAxes)
            
plt.tight_layout()
fig.subplots_adjust(bottom=0.13)
Example #49
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 #50
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(list(zip(labels, handles)))

        leg = plt.legend(list(by_label.values()),
                         list(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.set_draggable(state=True)
            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 #51
0
        if cat == '123':
            self.c_123_x.append(x)
            self.c_123_y.append(y)
        if cat == '45':
            self.c_45_x.append(x)
            self.c_45_y.append(y)


nc_path = r"P:\01_DataOriginals\GOM\Metocean\StormData\Year.2005.ibtracs_wmo.v03r10.nc"

m = Basemap(llcrnrlon=-98., llcrnrlat=17., urcrnrlon=-80., urcrnrlat=31., \
   projection='lcc', lat_0=30., lon_0=-90., \
   resolution='l', area_thresh=1000.)
# draw coastlines and meridians
m.drawcoastlines()
m.drawlsmask(land_color='#827d7c', ocean_color='#8dcef9', lakes=True)
m.drawparallels(np.arange(10, 70, 5), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(-100, 0, 5), labels=[0, 0, 0, 1])

# first open and get all the names of the storms
with Dataset(nc_path, 'r') as ds:
    basin = ds.variables['basin']
    lon = ds.variables['lon_wmo']
    lat = ds.variables['lat_wmo']
    wind = ds.variables['wind_wmo']
    dsLen = len(ds.variables['basin'])

    # loop through each storm
    for i in range(0, dsLen):

        print('storm ' + format(i))
Example #52
0
plt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']}) 

fig = plt.figure()
ax = plt.subplot(221)

m = Basemap(projection='npstere',boundinglat=66,lon_0=270,
            resolution='l',round =True)
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.3,color='k',fontsize=6)
#m.drawmeridians(meridians,labels=[False,False,False,False],
#                linewidth=0.3,color='k',fontsize=6)
m.drawlsmask(land_color='darkgrey',ocean_color='mintcream')

# Make the plot continuous
barlim = np.arange(-1,1.1,.5)
values = np.arange(-1,1.1,0.1)

cs = m.contourf(lons,lats,corr_w,
                values,latlon=True)
cs1 = m.contour(lons,lats,corr_w,
                values,linewidths=0.2,colors='darkgrey',
                linestyles='-',latlon=True)
        
cs.set_cmap('RdBu_r')
ax.annotate(r'\textbf{JFM}', xy=(0, 0), xytext=(-0.23, 0.9),
            xycoords='axes fraction',fontsize=22,color='darkgrey')
Example #53
0
m = Basemap(projection='cyl', llcrnrlon=sys.argv[2], \
    urcrnrlon=sys.argv[3], llcrnrlat=sys.argv[4],urcrnrlat=sys.argv[5], \
    lat_ts=20, resolution='i')
# add wrap-around point in longitude.
prmsl, lons = addcyclic(prmsl, lons)
# contour levels
clevs = np.arange(900, 1100., 5.)
# find x,y of map projection grid.
lons, lats = np.meshgrid(lons, lats)
x, y = m(lons, lats)
# create figure.
fig = plt.figure(figsize=(8, 4.5))
ax = fig.add_axes([0.05, 0.05, 0.9, 0.85])
cs = m.contour(x, y, prmsl, clevs, colors='k', linewidths=1.)
m.drawcoastlines(linewidth=1.25)
m.drawlsmask(land_color=(0.25, 0.5, 0, 1), ocean_color=(0.9, 0.9, 1, 1))
m.fillcontinents(color=(0.25, 0.5, 0, 1))
# m.drawparallels(np.arange(-80,81,20),labels=[1,1,0,0])
# m.drawmeridians(np.arange(0,360,60),labels=[0,0,0,1])
xlows = x[local_min]
xhighs = x[local_max]
ylows = y[local_min]
yhighs = y[local_max]
lowvals = prmsl[local_min]
highvals = prmsl[local_max]

# plot lows as blue L's, with min pressure value underneath.

xyplotted = []

# don't plot if there is already a L or H within dmin meters.
Example #54
0
File: garp.py Project: jahn/basemap
# **it's easy to make this fail with global aeqd plots.
#  For example, if the center point is at the North Pole,
#  the continent filling routines get confused and fills
#  the outside of Antartica instead of the inside**

#m.drawmapboundary(fill_color='white')
#m.drawcoastlines(linewidth=0.5)
#m.fillcontinents(color='black',lake_color='white')
#m.drawparallels(np.arange(-80,81,20),color='0.7')
#m.drawmeridians(np.arange(-180,180,20),color='0.7')

# draw lsmask instead of drawing continents (slower, but more robust).

m.drawlsmask(land_color='black',
             ocean_color='white',
             lakes=True,
             resolution='l',
             grid=5)
m.drawparallels(np.arange(-80, 81, 20), color='0.7')
m.drawmeridians(np.arange(-180, 180, 20), color='0.7')
m.drawmapboundary()

# blue marble background (pretty, but slow).

#m.bluemarble(scale=0.5)
#m.drawparallels(np.arange(-80,81,20),color='0.5')
#m.drawmeridians(np.arange(-180,180,20),color='0.5')
#m.drawmapboundary(color='0.5')

# draw a red dot at the center.
xpt, ypt = m(lon_0, lat_0)
Example #55
0
import numpy as np
df= pd.read_csv(io.BytesIO(uploaded['q3dbscan.csv']))
print(df.shape)

df.dropna(subset=['Lat','Long'],inplace=True)

df

print("Lat max",df['Lat'].max())
print("Lat min",df['Lat'].min())
print("Long max",df['Long'].max())
print("Long min",df['Long'].min())

my_map = Basemap(projection='merc',resolution='l',area_thresh=1000,llcrnrlat=25.753,llcrnrlon=-152,urcrnrlat=57.79,urcrnrlon=-7.539)
my_map.drawstates()
my_map.drawlsmask(land_color='orange',ocean_color='skyblue')
my_map.bluemarble()
my_map.etopo()

my_map.drawstates()
my_map.drawlsmask(land_color='orange',ocean_color='skyblue')
my_map.bluemarble()
my_map.etopo()

xs,ys=my_map(np.asarray(df.Long),np.asarray(df.Lat))
df['xm']= xs.tolist()
df['ym'] =ys.tolist()

df_cluster=df[["Long","Lat"]]
df_cluster=StandardScaler().fit_transform(df_cluster)
x = np.array(df_cluster)
Example #56
0
    def show_clouds_ortho(self, time, centre, map_bkgd='bluemarble', out='show'):
        """
        Show an orthographic projection with 
        cloud cover that ranges from transparent
        for small cloud fraction, to white to
        grey.
        
        args:
        
          time - time_utils.Time instance that the
                 cloud field will get interpolated to
                 and shown for.
                 
          centre - tuple of (lat, lon), indicating the
                   centre of the orthographic projection
                   
          map_bkgd - string to indicate what kind of back-
                     ground will be used for the image. 
                     Can be any of 'bluemarble', 'etopo',
                     or 'mask'
                     
          out - string to indicate what kind of output
                should be provided
        """
        if type(time) == type(dt.datetime(2015, 4, 4)):
            time = time_utils.Time(time, time)

        def col(x):
            """
            Function that provides RGBA values
            for a given cloud fraction between
            0 and 1. 
            """
            
            # get RGB value
            c = 1. - 0.3*x**2.
            
            # transparent if c.f. < 0.1
            if x < 0.1:
                return (c,c,c,0)
            
            # opaque if c.f. > 0.7
            elif x > 0.7:
                return (c,c,c,1.)
            
            # translucent if 0.1 < c.f. < 0.7
            else:
                return (c,c,c,np.clip((x - 0.1)/0.7, 0., 1.)**2.)
        
        # draw map projection
        projection = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='c')
        
        # determine what kind of background
        # is needed, and draw it
        if map_bkgd == 'bluemarble':
            projection.bluemarble()
        elif map_bkgd == 'etopo':
            projection.etopo()
        elif map_bkgd == 'mask':
            projection.drawlsmask(land_color='limegreen', ocean_color='dodgerblue', resolution='l')
            
            projection.drawcoastlines(linewidth=0.75)
            projection.drawcountries(linewidth=0.5)
            projection.drawmeridians(np.arange(-180, 181, 30), latmax=90)
            projection.drawparallels(np.arange(-90, 91, 15), latmax=90)
        else:
            raise ValueError('invalid map background specification')
               
        # use a call to interpolate the cloud 
        # fields to the needed time    
        cf = self(time)

        # define MERRA lat and lon grid
        lats = np.arange(-90., 90.25, 0.5)
        lons = np.arange(-180., 180.3125, 0.625)
        lons, lats = np.meshgrid(lons, lats)
        
        # define contour levels and colors
        levs = np.linspace(0,1,256, endpoint=True)
        clevs = [col(x) for x in levs]
        
        # get the map projection coordinates
        # and mask the cloud data, so that lcoations
        # on the opposite side of th Earth don't get
        # drawn
        x, y = projection(lons, lats)
        
        cfmask = np.ma.masked_greater(x, 1e15).mask
        cfmasked = np.ma.array(cf, mask=cfmask)
        
        # draw contour
        plt.contourf(x, y, cfmasked, levs, colors=clevs, extend='both')
                
        # supply specified output
        if out == 'show':
            plt.show()
        elif out == '':
            pass
        else:
            plt.savefig(out)
        return cfmask
### Define figure
if style == 'ortho':
    m = Basemap(projection='ortho',lon_0=-90,
                lat_0=70,resolution='l',round=True)
elif style == 'polar':
    m = Basemap(projection='npstere',boundinglat=67,lon_0=270,resolution='l',round =True)

for i in range(aug.shape[0]):
    fig = plt.figure()
    ax = plt.subplot(111)
    for txt in fig.texts:
        txt.set_visible(False)
    
    var = sit[i,:,:]
    m.drawmapboundary(fill_color='k')
    m.drawlsmask(land_color='k',ocean_color='k')
    m.drawcoastlines(color='mediumseagreen',linewidth=0.4)
    
    # Make the plot continuous
    barlim = np.arange(0,9,1)
    
#    cmap = colormapSIT()
    cmap = colormapSIT()
    cs = m.contourf(lons,lats,var,
                    np.arange(0,7.1,0.25),extend='max',
                    alpha=1,latlon=True,cmap=cmap)
                
    if i >= 38:
        ccc = 'mediumseagreen'
    else:
        ccc = 'w'
            boundinglat=-50,
            round=True,
            lon_0=180)
#-----------------------------------------
lon, lat = np.meshgrid(lons, lats)
xi, yi = m(lon, lat)
levels = np.linspace(-100, 100, 14, endpoint=True, dtype=int)
ax = fig.add_subplot(421)
ax.set_title('a) GDFL-CM3', fontsize=18)
sic = m.contourf(xi,
                 yi,
                 sic,
                 shading='interp',
                 cmap=plt.cm.seismic,
                 levels=levels)
m.drawlsmask()
m.drawcoastlines()
m.drawparallels(np.arange(-80., 81., 20.))
m.drawmeridians(np.arange(-180., 181., 20.))
#-----------------------------------------
sic = '/home/leticia/Documentos/2020.1/leticia_dados_CMIP/dados_subtraidos/GDFL_dif_cmip6.nc'
fh = Dataset(sic, mode='r')
lons = fh.variables['lon'][:]
lats = fh.variables['lat'][:]
#sic = fh.variables['sic'][2,:,:]
#sic = fh.variables['icec'][9,:,:]
sic = fh.variables['siconc'][9, :, :]
sic_units = fh.variables['siconc'].units
fh.close()
lon_0 = lons.mean()
lat_0 = lats.mean()
Example #59
0
    def plotUH(self, report, date, gsystem, ctype, filepath):
        """Plot horenzital and vertical errors.

        Arg:
            report:report of coor file, type:pandas.dataframe.
            date:coor file date.
            gsystem:GNSS system.
            ctype:calculate type.
            filepath:result path.
        """
        # connect to station database, returieve station b, l
        connect = sqlite3.connect(
            os.path.join(os.path.dirname(__file__), 'station.sqlite'))
        cur = connect.cursor()

        latitude = list()
        longtitude = list()
        index = list()
        for i, name in enumerate(report.name):
            cur.execute('SELECT B, L FROM Station WHERE name=?',
                        (name.lower(), ))
            try:
                cur_fetch = cur.fetchone()
                latitude.append(cur_fetch[0])
                longtitude.append(cur_fetch[1])
                index.append(i)
            except:
                continue

        cur.close()
        connect.close()
        if not latitude:
            return
        # start plot
        # set colorbar range
        if ctype == 'DFPPP':
            colorbar_vmax = 1
        elif ctype == 'SFPPP':
            colorbar_vmax = 3
        elif ctype == 'SFSPP':
            colorbar_vmax = 10

        fig = plt.figure(figsize=(20, 10))
        grid = ImageGrid(fig,
                         111,
                         nrows_ncols=(1, 2),
                         axes_pad=0.2,
                         share_all=True,
                         cbar_mode='single',
                         cbar_size="5%",
                         cbar_pad=0.1)
        for ax, i in zip(grid, [0, 1]):
            if i == 0:
                color = [report.H_95.values[i] for i in index]
                mean = sum(color) / len(color)
                title = 'Horizontal Errors [mean:%.3f]' % mean
            else:
                color = [report.U_95.values[i] for i in index]
                mean = sum(color) / len(color)
                title = 'Vertical Errors [mean:%.3f]' % mean
            ax.set_title(title, size=22, weight='bold')
            m = Basemap(projection='cyl',
                        llcrnrlat=9,
                        urcrnrlat=61,
                        llcrnrlon=70,
                        urcrnrlon=140,
                        ax=ax)
            m.drawcountries(color='#778899')
            m.drawlsmask(land_color='#F0E68C',
                         ocean_color='#87CEEB',
                         lakes=False)
            if i == 0:
                m.drawparallels(np.arange(10, 70, 10),
                                labels=[1, 0, 0, 0],
                                linewidth=0.01,
                                fontsize=18,
                                weight='bold')
            m.drawmeridians(np.arange(75, 140, 10),
                            labels=[0, 0, 0, 1],
                            linewidth=0.01,
                            fontsize=18,
                            weight='bold')
            mscatter = m.scatter(longtitude,
                                 latitude,
                                 latlon=True,
                                 c=color,
                                 s=200,
                                 marker='o',
                                 cmap=cm.get_cmap('jet'),
                                 vmin=0,
                                 vmax=colorbar_vmax,
                                 alpha=0.95)
        cbar = ax.cax.colorbar(mscatter)
        cbar.ax.set_title('m', size=18, weight='bold')
        plt.setp(cbar.ax.yaxis.get_ticklabels(), size=18, weight='bold')
        title = {
            'BDS': 'BDS',
            'GPS': 'GPS',
            'GBS': 'BDS/GPS',
            'MIX': 'GPS+BDS+GLO+GAL'
        }
        fig.suptitle('%s %s %s' % (title[gsystem], ctype, str(date)),
                     y=0.84,
                     size=24,
                     weight='bold')
        fig_name = '-'.join([ctype, gsystem, str(date), 'HV'])
        fig_path = os.path.join(filepath, str(date), '-'.join([ctype,
                                                               gsystem]))
        if not os.path.exists(fig_path):
            os.makedirs(fig_path)
        plt.savefig(os.path.join(fig_path, ''.join([fig_name, '.png'])),
                    bbox_inches='tight')

        # add station name
        for ax in grid:
            for name, lon, lat in zip(report.name.tolist(), longtitude,
                                      latitude):
                x, y = m(lon, lat)
                ax.text(x, y, name, size=12, weight='bold')

        plt.savefig(os.path.join(fig_path, ''.join([fig_name, '_name.png'])),
                    bbox_inches='tight')
        plt.clf()
        plt.close()