def show_route(self): ''' Display the route coordinates on a map of Tompkins County ''' # plot basemap w/ state and county lines, etc fig = plt.figure() m = Basemap(llcrnrlon=-76.8, llcrnrlat=42.2, urcrnrlon=-76.2, \ urcrnrlat=42.7, rsphere=(6378137.00,6356752.3142), resolution='l', \ projection='merc') m.shadedrelief() m.drawcoastlines() m.drawstates() m.drawcountries() m.drawcounties() # plot ny state water features m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDFlowline','water', color='LightSteelBlue', linewidth=2.) m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDArea','water_area', drawbounds=False) m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDWaterbody','lakes', drawbounds=False) for lake in m.lakes + m.water_area: poly = Polygon(lake, facecolor='LightSteelBlue', edgecolor='CornflowerBlue') plt.gca().add_patch(poly) # read and plot tompkins county shapefile m.readshapefile('data\\parcels\\ParcelPublic2016_WGS84', 'parcels') # plot route coordinates m.plot(self.coordinates[:,0], self.coordinates[:,1], '.-', latlon=True, c='FireBrick', lw=2.) # finalize and show plot fig.show()
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()
def mapTut(): m = Basemap(projection='mill',llcrnrlat=20,urcrnrlat=50,\ llcrnrlon=-130,urcrnrlon=-60,resolution='c') m.drawcoastlines() m.drawcountries() m.drawstates() m.fillcontinents(color='#04BAE3',lake_color='#FFFFFF') m.drawmapboundary(fill_color='#FFFFFF') # Houston, Texas lat,lon = 29.7630556,-95.3630556 x,y = m(lon,lat) m.plot(x,y, 'ro') lon, lat = -104.237, 40.125 # Location of Boulder xpt,ypt = m(lon,lat) m.plot(xpt,ypt, 'go') plt.title("Geo Plotting") plt.show()
def main(): plot_utils.apply_plot_params(width_cm=20, height_cm=20, font_size=10) high_hles_years = [1993, 1995, 1998] low_hles_years = [1997, 2001, 2006] data_path = "/BIG1/skynet1_rech1/diro/sample_obsdata/eraint/eraint_uvslp_years_198111_201102_NDJmean_ts.nc" with xr.open_dataset(data_path) as ds: print(ds) u = get_composit_for_name(ds, "u10", high_years_list=high_hles_years, low_years_list=low_hles_years) v = get_composit_for_name(ds, "v10", high_years_list=high_hles_years, low_years_list=low_hles_years) msl = get_composit_for_name(ds, "msl", high_years_list=high_hles_years, low_years_list=low_hles_years) lons = ds["longitude"].values lats = ds["latitude"].values print(lats) print(msl.shape) print(lons.shape, lats.shape) lons2d, lats2d = np.meshgrid(lons, lats) fig = plt.figure() map = Basemap(llcrnrlon=-130, llcrnrlat=22, urcrnrlon=-28, urcrnrlat=65, projection='lcc', lat_1=33, lat_2=45, lon_0=-95, resolution='i', area_thresh=10000) clevs = np.arange(-11.5, 12, 1) cmap = cm.get_cmap("bwr", len(clevs) - 1) bn = BoundaryNorm(clevs, len(clevs) - 1) x, y = map(lons2d, lats2d) im = map.contourf(x, y, msl / 100, levels=clevs, norm=bn, cmap=cmap) # convert to mb (i.e hpa) map.colorbar(im) stride = 2 ux, vy = map.rotate_vector(u, v, lons2d, lats2d) qk = map.quiver(x[::stride, ::stride], y[::stride, ::stride], ux[::stride, ::stride], vy[::stride, ::stride], scale=10, width=0.01, units="inches") plt.quiverkey(qk, 0.5, -0.1, 2, "2 m/s", coordinates="axes") map.drawcoastlines(linewidth=0.5) map.drawcountries() map.drawstates() #plt.show() fig.savefig("hles_wind_compoosits.png", bbox_inches="tight", dpi=300)
def plot_map_twts(twts, title='default title'): """ Given an iterable of 'clean' tweets, make a dot map over North America. """ fig1 = plt.figure() ax = fig1.add_subplot(111) m = Basemap(projection='merc', resolution = 'l', llcrnrlon=-136.0, llcrnrlat=24.0, urcrnrlon=-67.0, urcrnrlat=60.0, ax=ax) m.drawcoastlines() m.drawcountries() m.drawstates() m.fillcontinents(color = 'coral', alpha=0.5) m.drawmapboundary() lons = [twt['coordinates'][0] for twt in twts] lats = [twt['coordinates'][1] for twt in twts] x,y = m(lons, lats) m.plot(x, y, 'bo', markersize=5) plt.title(title) plt.show()
def 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
def plot_filtered_diff(self): """ function for plotting the difference of filtered vorticity """ w_diff, lon, lat, mask = self.vorticity_filter() south = lat.min(); north =lat.max() west = lon.min(); east = lon.max() timeformat = '%Y%m%d-%H%M' for i in range(len(self.time)): fig = plt.figure(figsize=(10,8)) basemap = Basemap(projection='merc',llcrnrlat=south,urcrnrlat=north,\ llcrnrlon=west,urcrnrlon=east, resolution='h') basemap.drawcoastlines() basemap.fillcontinents(color='coral',lake_color='aqua') basemap.drawcountries() basemap.drawstates() llons, llats=basemap(lon,lat) con = basemap.pcolormesh(llons,llats,w_diff[i,:,:]) #con.set_clim(vmin=-0.0003, vmax=0.0003) cbar = plt.colorbar(con, orientation='vertical') cbar.set_label("vorticity") #plt.show() timestr = datetime.strftime(self.time[i], timeformat) plt.title('vorticity at %s'%timestr) plt.savefig(self.wdr+'/vorticity_figure/vorticity_diff/'+str(i)+'.png') print "Saving figure %s to ROMS figure directory"%str(i)
def nepal_basemap(prams = nepal_ETAS_prams, fnum=0, map_res='i', **kwargs): # hours_after: upper time limit for aftershocks to plot. prams.update(kwargs) # lons_nepal = [83., 87.] lats_nepal = [26., 30.] todt=prams.get('todt', None) catlen=prams.get('catlen', 5.*365.) lons=prams['lons'] lats=prams['lats'] mc = prams['mc'] # if todt==None: todt = dtm.datetime.now(pytz.timezone('UTC')) dt0 = todt - dtm.timedelta(days=catlen) # plt.figure(fnum) plt.clf() ax1=plt.gca() cntr = [.5*(lons[0]+lons[1]), .5*(lats[0]+lats[1])] # cm=Basemap(llcrnrlon=lons_nepal[0], llcrnrlat=lats_nepal[0], urcrnrlon=lons_nepal[1], urcrnrlat=lats_nepal[1], resolution=map_res, projection='cyl', lon_0=cntr[0], lat_0=cntr[1]) cm.drawcoastlines(color='gray', zorder=1) cm.drawcountries(color='gray', zorder=1) cm.drawstates(color='gray', zorder=1) cm.drawrivers(color='gray', zorder=1) cm.fillcontinents(color='beige', zorder=0) # cm.drawmeridians(list(range(int(lons[0]), int(lons[1]))), color='k', labels=[0,0,1,1]) cm.drawparallels(list(range(int(lats[0]), int(lats[1]))), color='k', labels=[1, 1, 0, 0]) # return cm
def worldplot(self,kmeans=None,proj='merc'): """ plots customer GPS location on a map with state and national boundaries. IN kmeans (int) number of means for k-means clustering, default=None proj (string) the map projection to use, use 'robin' to plot the whole earth, default='merc' """ # create a matplotlib Basemap object if proj == 'robin': my_map = Basemap(projection=proj,lat_0=0,lon_0=0,resolution='l',area_thresh=1000) else: my_map = Basemap(projection=proj,lat_0=33.,lon_0=-125.,resolution='l',area_thresh=1000., llcrnrlon=-130.,llcrnrlat=25,urcrnrlon=-65., urcrnrlat=50) my_map.drawcoastlines(color='grey') my_map.drawcountries(color='grey') my_map.drawstates(color='grey') my_map.drawlsmask(land_color='white',ocean_color='white') my_map.drawmapboundary() #my_map.fillcontinents(color='black') x,y = my_map(np.array(self.data['lon']),np.array(self.data['lat'])) my_map.plot(x,y,'ro',markersize=3,alpha=.4,linewidth=0) if kmeans: # k-means clustering algorithm---see wikipedia for details data_in = self.data.drop(['id','clv','level'],axis=1) # vq is scipy's vector quantization module output,distortion = vq.kmeans(data_in,kmeans) x1,y1 = my_map(output[:,1],output[:,0]) my_map.plot(x1,y1,'ko',markersize=20,alpha=.4,linewidth=0) plt.show() return output
def map_vis(data,title=[],vmin=None,vmax=None,barlabel=None,cmap=None,outputdir=None): # print("visualizing : "+title) if cmap==None: cmap=cm.jet if len(data.shape)>2: plotdata=data[0,:,:] else: plotdata=data plt.clf() # plt.figure(figsize=(3,3),dpi=200) ny,nx=plotdata.shape geo=[35,43,-113,-101] if experiment=="conus":geo=[25,52.7,-124.7,-67] m = Basemap(projection='cyl',llcrnrlat=geo[0],urcrnrlat=geo[1],\ llcrnrlon=geo[2],urcrnrlon=geo[3],resolution="i") mapimg=m.imshow(plotdata,vmin=vmin,vmax=vmax,cmap=cmap) if experiment=="conus": m.drawparallels(np.arange(25,55,5.),labels=[1,0,0,0],dashes=[1,4]) m.drawmeridians(np.arange(-120,-65,10.),labels=[0,0,0,1],dashes=[1,4]) m.drawstates(linewidth=0.5) m.drawcountries(linewidth=0.5) m.drawcoastlines(linewidth=0.5) else: m.drawparallels(np.arange(36,43,2.),labels=[1,0,0,0],dashes=[1,4]) m.drawmeridians(np.arange(-112,-103,4.),labels=[0,0,0,1],dashes=[1,4]) m.drawstates(linewidth=1.5) cbar=m.colorbar() if barlabel: cbar.set_label(barlabel) plt.title(" ".join(title)) if outputdir: plt.savefig(outputdir+"_".join(title)+'_map.png') else: plt.savefig("_".join(title)+'_map.png')
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 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()
def plot_grid2D(lons, lats, tec_grid2D, datetime, title_label = ''): LATS, LONS = np.meshgrid(lats, lons) m = Basemap(llcrnrlon=-180, llcrnrlat=-55, urcrnrlon=180, urcrnrlat=75, projection='merc', area_thresh=1000, resolution='i') m.drawstates() m.drawcountries() m.drawcoastlines() parallels = np.arange(-90,90,20) m.drawparallels(parallels,labels=[True,False,False,True]) meridians = np.arange(0,360,40) m.drawmeridians(meridians,labels=[True,False,False,True]) m.scatter(LONS, LATS, c=tec_grid2D, latlon = True, linewidths=0, s=5) m.colorbar() plt.title('%s\n%s' % (title_label, datetime.isoformat(' ')))
def background_map(self, ax): llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon, lat_ts = (31, 44, -126, -113, 37.5) m = Basemap(projection='merc', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, lat_ts=lat_ts, resolution='i', ax=ax) m.drawmapboundary(fill_color='lightblue', zorder=0) m.fillcontinents(zorder=0) etopofn = '/home/behry/uni/data/etopo1_central_europe_gmt.grd' etopodata = Dataset(etopofn, 'r') z = etopodata.variables['z'][:] x_range = etopodata.variables['x_range'][:] y_range = etopodata.variables['y_range'][:] spc = etopodata.variables['spacing'][:] lats = np.arange(y_range[0], y_range[1], spc[1]) lons = np.arange(x_range[0], x_range[1], spc[0]) topoin = z.reshape(lats.size, lons.size, order='C') # transform to nx x ny regularly spaced 5km native projection grid nx = int((m.xmax - m.xmin) / 5000.) + 1; ny = int((m.ymax - m.ymin) / 5000.) + 1 topodat, x, y = m.transform_scalar(np.flipud(topoin), lons, lats, nx, ny, returnxy=True) ls = LightSource(azdeg=300, altdeg=15, hsv_min_sat=0.2, hsv_max_sat=0.3, hsv_min_val=0.2, hsv_max_val=0.3) # shade data, creating an rgb array. rgb = ls.shade(np.ma.masked_less(topodat / 1000.0, 0.0), cm.gist_gray_r) m.imshow(rgb) m.drawmeridians(np.arange(6, 12, 2), labels=[0, 0, 0, 1], color='white', linewidth=0.5, zorder=0) m.drawparallels(np.arange(44, 50, 2), labels=[1, 0, 0, 0], color='white', linewidth=0.5, zorder=0) m.drawcoastlines(zorder=1) m.drawcountries(linewidth=1.5, zorder=1) m.drawstates() m.drawrivers(color='lightblue', zorder=1) return m
def Scatter(data, lons, lats, min, max, cmp, tit, unit, figdir, filename): # Prepare for drawing # ny, nx = (50, 116) # draw Chile Basemap with lambert projection at normal x, y settings m = Basemap( llcrnrlon=-78, llcrnrlat=-56, urcrnrlon=-66, urcrnrlat=-17, projection="cyl", fix_aspect=False, lat_1=-43, lat_2=-30, lon_0=-72, ) # projection='lcc' # draw boundaries m.drawcoastlines() m.drawcountries(linewidth=2) m.drawstates() m.drawparallels(arange(-60, -15, 15), labels=[1, 0, 0, 0]) # only left ytick m.drawmeridians(arange(-80, -60, 5), labels=[0, 0, 0, 1]) # only bottom xtick # map data with lon and lat position im = m.scatter(lons, lats, 30, marker="o", c=data, vmin=min, vmax=max, latlon=True, cmap=cmp) cb = m.colorbar(im, pad="10%") plt.title(tit, fontsize=20) plt.xlabel(unit, labelpad=50) # savefig('%s%s' % (figdir, filename)) plt.show()
def plot(rec): data = rec.values lats, lons = rec.latlons() fig = plt.figure(figsize=(8,8)) # create figure and axes instances ax = fig.add_axes([0.1,0.1,0.8,0.8]) # create polar stereographic Basemap instance. # m = Basemap(projection='stere',lon_0=lon_0,lat_0=90.,lat_ts=lat_0,\ # llcrnrlat=latcorners[0],urcrnrlat=latcorners[2],\ # llcrnrlon=loncorners[0],urcrnrlon=loncorners[2],\ # rsphere=6371200.,resolution='l',area_thresh=10000) # # Lambert Conformal Conic map. m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57., projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60., resolution ='l',area_thresh=1000.) # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines() m.drawstates() m.drawcountries() # draw parallels. parallels = np.arange(0.,90,10.) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # draw meridians meridians = np.arange(180.,360.,10.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) ny = data.shape[0]; nx = data.shape[1] x, y = m(lons, lats) # compute map proj coordinates. m.contourf(x, y, data) plt.title('{0} ({5}) for period ending {1}/{2}/{3} {4}:00'.format(rec.parameterName, rec.year, rec.month, rec.day, rec.hour, rec.parameterNumber)) plt.show()
def get_catalog_map(lats=None, lons=None, eq_cat=[], map_res='i', map_projection='cyl', fignum=0, ax=None, do_clf=True): # if lats==None: lats = [31., 42.] if lons==None: lons = [-125., -114.] # if fignum!=None: plt.figure(fignum) if do_clf: plt.clf() if ax==None: ax=plt.gca() # cm = Basemap(llcrnrlon=lons[0], llcrnrlat=lats[0], urcrnrlon=lons[1], urcrnrlat=lats[1], resolution=map_res, projection=map_projection, lon_0=numpy.mean(lons), lat_0=numpy.mean(lats), ax=ax) cm.drawcoastlines(color='gray', zorder=1) cm.drawcountries(color='gray', zorder=1) cm.drawstates(color='gray', zorder=1) cm.drawrivers(color='gray', zorder=1) cm.fillcontinents(color='beige', zorder=0) # drawlsmask(land_color='0.8', ocean_color='w', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=True, resolution='l', grid=5, **kwargs) #cm.drawlsmask(land_color='0.8', ocean_color='c', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=True, resolution=mapres, grid=5) print("lat, lon ranges: ", lats, lons) cm.drawmeridians(list(range(int(lons[0]), int(lons[1]))), color='k', labels=[0,0,1,1]) cm.drawparallels(list(range(int(lats[0]), int(lats[1]))), color='k', labels=[1, 1, 0, 0]) # if eq_cat!=None: # can we also assign sizes dynamically, like colors? if hasattr(eq_cat, 'dtype'): # it's a recrray: X,Y = cm(eq_cat['lon'], eq_cat['lat']) else: # it's probably a list... though we should check for dicts, etc. X,Y = cm([rw[2] for rw in eq_cat], [rw[1] for rw in eq_cat]) # cm.plot(X,Y, '.') # return cm
def plot_gini_grid_barbs(gini_grid, box = [-110, -70, 20, 52], resolution = 'l', parallels = None, meridians = None, vmin = None, vmax = None, fld = 'IR', title = None, degrade = 5, u='u', v='v'): m = Basemap(llcrnrlon = box[0] ,llcrnrlat = box[2] , urcrnrlon = box[1], urcrnrlat = box[3] , projection = 'mill', area_thresh =1000 , resolution = resolution) x, y = m(gini_grid.fields['lon']['data'], gini_grid.fields['lat']['data']) # create figure. if parallels == None: parallels = np.linspace(10,50, 9) if meridians == None: meridians = np.linspace(-110, -80,7) m.drawparallels(parallels, labels=[1,1,0,0]) m.drawmeridians(meridians,labels=[0,0,0,1]) pc = m.pcolormesh(x, y , gini_grid.fields[fld]['data'][0,:], cmap=plt.get_cmap('gray'), vmin = vmin, vmax = vmax) qq = m.barbs(x[::degrade,::degrade], y[::degrade,::degrade], gini_grid.fields[u]['data'][0,::degrade,::degrade], gini_grid.fields[v]['data'][0,::degrade,::degrade]) plt.title(title) m.drawcoastlines(linewidth=1.25) m.drawstates() plt.colorbar(mappable=pc, label = 'Counts')
def plotPointsOnUSMap(points, blueMarble=False, bkcolor='#85A6D9', returnBaseMapObject = False, pointLabels=[], *args, **kwargs): from mpl_toolkits.basemap import Basemap m = Basemap(llcrnrlon=-125.15625, llcrnrlat=20, urcrnrlon=-59.765625, urcrnrlat=49.61071, projection='mill', lat_1=24, lat_2=50, lon_0=-98, resolution='l', area_thresh=10000) m.drawmapboundary(fill_color='#85A6D9') if blueMarble: m.bluemarble() else: m.drawmapboundary(fill_color=bkcolor) m.fillcontinents(color='white',lake_color=bkcolor) m.drawcoastlines(color='#6D5F47', linewidth=.4) m.drawcountries(color='#6D5F47', linewidth=.4) m.drawstates(color='#6D5F47', linewidth=.4) # m.fillcontinents(color='white',lake_color='#85A6D9') # m.drawstates(color='#6D5F47', linewidth=.4) # m.drawcoastlines(color='#6D5F47', linewidth=.4) # m.drawcountries(color='#6D5F47', linewidth=.4) # m.drawmeridians(n.arange(-180, 180, 30), color='#bbbbbb') # m.drawparallels(n.arange(-90, 90, 30), color='#bbbbbb') lats, lngs = zip(*points) x,y = m(lngs,lats) scatterPlot = m.scatter(x, y, zorder = 2, *args, **kwargs) for population, xpt, ypt in zip(pointLabels, x, y): label_txt = str(population) plt.text( xpt, ypt, label_txt, color = 'black', size='small', horizontalalignment='center', verticalalignment='center', zorder = 3) if not returnBaseMapObject: return scatterPlot else: return (scatterPlot, m)
class Map: def __init__(self, boundary=[[24.527135, -127.792969], [49.61071, -59.765625]], default=True): from mpl_toolkits.basemap import Basemap minLat, minLon, maxLat, maxLon = [item for t in boundary for item in t] self.m = Basemap( llcrnrlon=minLon, llcrnrlat=minLat, urcrnrlon=maxLon, urcrnrlat=maxLat, resolution="l", projection="merc", area_thresh=1000000, lon_0=minLon + (maxLon - minLon) / 2, lat_0=minLat + (maxLat - minLat) / 2, ) if default: self.configure() def configure(self): self.m.drawcoastlines(linewidth=1.0) self.m.drawcountries(linewidth=1.0) self.m.fillcontinents(color="#FFFFFF", lake_color="#FFFFFF") self.m.drawstates(linewidth=0.5) self.m.drawmapboundary(fill_color="#FFFFFF") def plotPoints(self, longitude, latitudes, color, lw=0, marker="o", *args, **kwargs): mlon, mlat = self.m(longitude, latitudes) self.m.plot(mlon, mlat, color=color, lw=lw, marker=marker, *args, **kwargs)
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()
def basemap_setup(self,smooth=1,lats=False,lons=False): """ Needs rewriting to include limited domains based on lats/lons. Currently, assuming whole domain is plotted. """ # Fetch settings basemap_res = self.D.basemap_res width_m = self.W.dx*(self.W.x_dim-1) height_m = self.W.dy*(self.W.y_dim-1) m = Basemap( projection='lcc',width=width_m,height=height_m, lon_0=self.W.cen_lon,lat_0=self.W.cen_lat,lat_1=self.W.truelat1, lat_2=self.W.truelat2,resolution=basemap_res,area_thresh=500, ax=self.ax) m.drawcoastlines() m.drawstates() m.drawcountries() # Draw meridians etc with wrff.lat/lon spacing # Default should be a tenth of width of plot, rounded to sig fig s = slice(None,None,smooth) x,y = m(self.W.lons[s,s],self.W.lats[s,s]) return m, x, y
def displaymap(region=__AUSREGION__, subregions=[], labels=[], colors=[], linewidths=[], fontsize='small', bluemarble=True, drawstates=True): ''' regions are [lat,lon,lat,lon] ''' m = Basemap(projection='mill', resolution='f', llcrnrlon=region[1], llcrnrlat=region[0], urcrnrlon=region[3], urcrnrlat=region[2]) if bluemarble: m.bluemarble() else: m.drawcountries() if drawstates: m.drawstates() # Add lats/lons to map add_grid_to_map(m,xy0=(-10,-80),xyres=(10,10),dashes=[1,1e6],labels=[1,0,0,1]) for r in subregions: if len(labels)<len(r): labels.append('') if len(colors)<len(r): colors.append('k') if len(linewidths)<len(r): linewidths.append(1) # add subregions and little lables: for r,l,c,lw in zip(subregions, labels, colors, linewidths): plot_rec(m,r,color=c, linewidth=lw) lon,lat=r[1],r[2] x,y = m(lon,lat) plt.text(x+100,y-130,l,fontsize=fontsize,color=c) return m
def plotRegion(expertiseRegions, models): colors = ["red", "aqua", "blue", "green", "yellow", "magenta", "purple", "grey", "violet", "white"] # llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon # are the lat/lon values of the lower left and upper right corners # of the map. # lat_ts is the latitude of true scale. # resolution = 'c' means use crude resolution coastlines. m = Basemap(projection="merc", llcrnrlon=-129, llcrnrlat=27, urcrnrlon=-60, urcrnrlat=50, lat_ts=20, resolution="c") m.drawcoastlines() m.fillcontinents(color="coral", lake_color="aqua") # draw parallels and meridians. m.drawstates() lon = -125.3318 lat = 37.0799 x, y = m(lon, lat) index = 0 for region in expertiseRegions: lats = [region._leftTop[0], region._rightBottom[0], region._rightBottom[0], region._leftTop[0]] lons = [region._leftTop[1], region._leftTop[1], region._rightBottom[1], region._rightBottom[1]] draw_screen_poly(lats, lons, m, color=colors[index]) for model in models: x = model["center"][0] y = model["center"][1] m.plot(x, y, "bo", markersize=10) m.drawmapboundary(fill_color="aqua") plt.title("Expert Regions") plt.savefig("region.png") plt.clf()
def plot_quakes(years, figsize, quantity): res = get_plot_res(years) colors = get_colormap(years) quakes = get_quakes_subset(years, quantity) lat_0 = quakes['LAT'].mean() lon_0 = quakes['LON'].mean() fig = matplotlib.pyplot.figure(figsize=figsize) m = Basemap(resolution = res, projection='nsper', area_thresh = 1000., satellite_height = 200000, lat_0 = lat_0, lon_0 = lon_0) m.drawcoastlines() m.drawcountries() m.drawstates() m.fillcontinents(color = 'green', lake_color = 'aqua') m.drawmapboundary(fill_color = 'blue') x, y = m(quakes.LON, quakes.LAT) for i in range(0, len(x) - 1): color = colors[get_year(quakes[i:i+1])-years[0]] m.plot(x[i:i+1], y[i:i+1], color = color, marker = 'o', markersize = (pi*(quakes.MAG[i:i+1]).apply(float)**2), alpha = 0.5)
def visualize(self): """ Visuzalise the edges References: * http://stackoverflow.com/questions/11603537/plot-multiple-lines-in-python-basemap """ from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np m = Basemap(projection='mill', llcrnrlat=self.bounds[0], urcrnrlat=self.bounds[2], llcrnrlon=self.bounds[1], urcrnrlon=self.bounds[3], resolution='c') m.drawcoastlines() m.drawcountries() m.drawstates() m.fillcontinents(color='#EEEEEE', lake_color='#FFFFFF') m.drawmapboundary(fill_color='#FFFFFF') # Plotting segments for path in self.get_paths(): latlngs = np.array(map(lambda node: (node.lat, node.lng), path.get_nodes())) x, y = m(latlngs.T[1], latlngs.T[0]) m.plot(x, y, color="#000000", marker='o', linestyle='-', linewidth=2, alpha=.5) plt.title('Segment plotting') plt.show()
def nice_plot(data,xmin,xmax,xint,centerlat,centerlon,stations,color,cmin, cmax,levels_t): """Make plots in map projection, requires input array, x-min max and interval (also used for y), center of data in lat, lon, station locations, color scale, min and max limits and levels array for color scale. """ domain = xmax-xint/2. maps = Basemap(projection='laea',lat_0=centerlat,lon_0=centerlon, width=domain*2,height=domain*2) s = plt.pcolormesh(np.arange(xmin-xint/2.,xmax+3*xint/2.,xint)+domain, np.arange(xmin-xint/2.,xmax+3*xint/2.,xint)+domain, data, cmap = color) s.set_clim(vmin=cmin,vmax=cmax) CS = plt.contour(np.arange(xmin,xmax+xint,xint)+domain, np.arange(xmin,xmax+xint,xint)+domain, data, colors='k',levels=levels_t) plt.clabel(CS, inline=1, fmt='%1.2f',fontsize=8) plt.scatter(stations[:,0]+domain, stations[:,1]+domain, color='k',s=2) maps.drawstates() fig = plt.gcf() circle=plt.Circle((domain,domain),100000,color='0.5',fill=False) fig.gca().add_artist(circle) circle=plt.Circle((domain,domain),200000,color='0.5',fill=False) fig.gca().add_artist(circle)
def draw(self, pop): fig=plt.figure() ax=fig.add_axes([0.1,0.1,0.8,0.8]) m = Basemap(llcrnrlon=-125.,llcrnrlat=25.,urcrnrlon=-65.,urcrnrlat=52., rsphere=(6378137.00,6356752.3142), resolution='l',projection='merc', lat_0=40.,lon_0=-20.,lat_ts=20.) l = pop[0] for i in range(len(l.sol)): lat1 = l.sol[i].lat lon1 = l.sol[i].lon m.drawgreatcircle(lon1,lat1,lon1,lat1, linewidth=4, color = 'r') if i == len(l.sol) - 1: lat2 = l.sol[0].lat lon2 = l.sol[0].lon else: lat2 = l.sol[i+1].lat lon2 = l.sol[i+1].lon m.drawgreatcircle(lon1,lat1,lon2,lat2, color = 'b') m.drawcoastlines() m.drawstates() m.drawcountries() m.fillcontinents() ax.set_title('GREEDY') plt.show()
def plot(self,reports,itime,ftime,fname,outdir,Nlim=False, Elim=False,Slim=False,Wlim=False, annotate=True,fig=False,ax=False,ss=50,color='blue'): reportidx = N.array([n for n,t in zip(range(len(self.r['EVENT_TYPE'])),self.r['EVENT_TYPE']) if reports in t]) lateidx = N.where(self.datetimes > itime) earlyidx = N.where(self.datetimes < ftime) timeidx = N.intersect1d(earlyidx,lateidx,)#assume_unique=True) plotidx = N.intersect1d(reportidx,timeidx) from mpl_toolkits.basemap import Basemap if fig==False: fig,ax = plt.subplots(1,figsize=(6,6)) m = Basemap(projection='merc', llcrnrlat=Slim, llcrnrlon=Wlim, urcrnrlat=Nlim, urcrnrlon=Elim, lat_ts=(Nlim-Slim)/2.0, resolution='i', ax=ax) m.drawcoastlines() m.drawstates() m.drawcountries() m.scatter(self.r['BEGIN_LON'][plotidx],self.r['BEGIN_LAT'][plotidx],latlon=True, marker='D',facecolors=color,edgecolors='black',s=ss) fig.tight_layout() plt.savefig(os.path.join(outdir,fname))
def plotData(csvFile, index): data = genfromtxt('ressources/results/' + csvFile, delimiter='\t', dtype=None) #### data preparation lats = data[:, 0] # # lon => x lons = data[:, 1] # # values => z values = data[:, index] print "Lat Min :", min(lats), "Lat Max :", max(lats) print "Lon Min :", min(lons), "Lon Max :", max(lons) #### later in the defined map map = Basemap(projection='cyl', llcrnrlat=min(lats), urcrnrlat=max(lats), llcrnrlon=min(lons), urcrnrlon=max(lons), resolution='l') map.drawcoastlines() map.drawstates() map.drawcountries() print "Maximum Speed ", max(values) #clevs = [0,0.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10,10.5,11,11.5,12,12.5,13,13.5,14] # clevs = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14] # clevs = [0,1000,1250,1500,2000,2500,3000,8000] clevs = [44,45] cs = map.contourf(lons, lats, values,clevs, latlon=True, tri=True) cbar = map.colorbar(cs, location='bottom', pad="5%") cbar.set_label('m/s') plt.show() return
# Draw a scatter plot assigning point sizes to injection volumes and color to # mean pressure sns.set(style="whitegrid") # # Draw the map background fig = plt.figure(figsize=(12, 5)) m = Basemap(projection='lcc', resolution='h', lat_0=35.5, lon_0=-98.6, width=8.5E5, height=5.0E5) m.shadedrelief() m.drawcoastlines(color='gray') m.drawcountries(color='gray') m.drawstates(color='gray') # # Scatter plot of injection data, with color reflecting well type and size # reflecting 2017 injection volume m.scatter(list(df['Lon']), list(df['Lat']), latlon=True, s=list(df['Vol_Tot'] / 250000), alpha=0.5, c=list(df['Pres_2017']), cmap='Reds') # # Create colorbar and legend plt.colorbar(label=r'$Mean Pressure({\rm PSI})$') plt.clim(0, 5000) plt.title(
# (0.2, 0.6, 0.2), c('yellow'), # (np.median(depth1)+2*depth1.std())/depth1.max(), # c('yellow'),(1.0, 0.0, 0.0)]) fig = plt.figure(figsize=(8,8)) ax = fig.add_axes([0.1,0.1,0.8,0.8]) # Set up figures and background m = Basemap(projection='merc', llcrnrlat=46, urcrnrlat=46.5, llcrnrlon=-113, urcrnrlon=-112, lat_ts=45, resolution='h') m.drawstates(linewidth=0.5, linestyle='solid', color='1') m.drawparallels(np.arange(46.,47.,.5), linewidth=.25, labels=[1, 1, 0, 0], color='1') m.drawmeridians(np.arange(-113.,-112.,1.), linewidth=.25, labels=[0, 0, 0, 1], color='1') #m.shadedrelief() # create color map cmap = mpl.cm.get_cmap('viridis') sizemin = 3000 sizerange = 3000 # Add beachballs #ax = plt.gca() x1, y1 = m(lons1, lats1) for i in range(len(focmecs1)):
def map_plot1(grid, var, yr, season=4, lonmin=-65, lonmax=-125, latmin=25, latmax=50, grid_change=0): import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap, cm if season == 0: sn = 'DJF' elif season == 1: sn = 'MAM' elif season == 2: sn = 'JJA' elif season == 3: sn = 'SON' else: sn = '' # create figure and axes: fig, axs = plt.subplots(1, 1, figsize=(15, 10)) # setup stereographic basemap: if latmax < 90: m = Basemap(projection='merc', llcrnrlon=lonmax, llcrnrlat=latmin, urcrnrlon=lonmin, urcrnrlat=latmax, resolution='l') m.ax = axs sn_min = np.min(grid) sn_max = np.max(grid) ch_min = np.min(grid_change) ch_max = np.max(grid_change) pic = m.imshow(grid_change, origin='lower', vmin=ch_min, vmax=ch_max) ny = grid.shape[0]; nx = grid.shape[1] lons, lats = m.makegrid(nx,ny) x, y = m(lons,lats) # plot the contours for all of the grid data as dashed lines: con = m.contour(x,y,grid,cmap=cm.s3pcpn, vmin=sn_min, vmax=0, linestyles='dashdot') plt.clabel(con, inline=True, fmt='%1.0f', fontsize=10) # plot the positive contours as solid lines: con1 = m.contour(x,y,grid,cmap=cm.s3pcpn, vmin=0, vmax=sn_max, linestyles='solid') plt.clabel(con1, inline=True, fmt='%1.0f', fontsize=10) m.drawparallels(np.arange(-90., 91., 10.), labels=[1,0,0,0], fontsize=12) m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=12) #pic = m.imshow(grid, origin='lower', vmin=sn_min, vmax=sn_max) m.drawcoastlines() m.drawstates() m.drawcountries() elif latmax == 90: m = Basemap(projection='cyl') m.ax = axs sn_min = np.min(grid) sn_max = np.max(grid) ch_min = np.min(grid_change) ch_max = np.max(grid_change) pic = m.imshow(grid_change, origin='lower', vmin=ch_min, vmax=ch_max) ny = grid.shape[0]; nx = grid.shape[1] lons, lats = m.makegrid(nx,ny) x, y = m(lons,lats) # plot the contours for all of the grid data as dashed lines: con = m.contour(x,y,grid,cmap=cm.s3pcpn, vmin=sn_min, vmax=0, linestyles='dashdot') plt.clabel(con, inline=True, fmt='%1.0f', fontsize=10) # plot the positive contours as solid lines: con1 = m.contour(x,y,grid,cmap=cm.s3pcpn, vmin=0, vmax=sn_max, linestyles='solid') plt.clabel(con1, inline=True, fmt='%1.0f', fontsize=10) m.drawparallels(np.arange(-90., 91., 30.), labels=[1,0,0,0], fontsize=12) m.drawmeridians(np.arange(-180., 181., 30.), labels=[0,0,0,1], fontsize=12) m.drawcoastlines() m.drawcountries() div = make_axes_locatable(axs) cax = div.append_axes("bottom", size="5%", pad="15%") cbar = fig.colorbar(pic, cax=cax, orientation="horizontal", ticks=[ch_min, 0, ch_max]) cbar.ax.tick_params(labelsize=12) axs.set_title(f'{yr} {sn} {var} (m/s)', fontsize=14) #plt.tight_layout(pad=0.1) fig.savefig(f'{yr}_{var}_{sn}_avgmap_lat{latmin}_{latmax}.png') plt.show()
def map_plot(file, var, yr): import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.pyplot as plt from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap data = Dataset(file) u500 = data.variables[f'{var}'][yr-1980] djf = u500[0] mam = u500[1] jja = u500[2] son = u500[3] # create figure and axes: fig, axs = plt.subplots(2, 2, figsize=(20, 20), sharey='row', sharex='col') plt.subplots_adjust(wspace=0.15, hspace=0.15) # setup stereographic basemap: # make sure this is plotting the right lat/lon ranges # lat range : 25, 50 # lon range : -65, -125 (west) m = Basemap(projection='merc', lat_0=37.5, lon_0=-95, llcrnrlon=-125, llcrnrlat=25,urcrnrlon=-65, urcrnrlat=50, resolution='l') #projection='stere',lat_0=37.5,lon_0=-95 sns = [djf, mam, jja, son] sn_min = np.min(sns) sn_max = np.max(sns) fig.suptitle(f'{yr} {var} (m/s)') m.ax = axs[0,0] m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10) m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10) m.drawcoastlines() m.drawstates() m.drawcountries() pic = m.imshow(djf, origin='lower', vmin=sn_min, vmax=sn_max) ''' nlats = 50; nlons = 96 #delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-0.5*np.indices((nlats,nlons))[0,:,:]) lons = (0.625*np.indices((nlats,nlons))[1,:,:]) x, y = m(lons*180./np.pi, lats*180./np.pi) pic = m.contour(x, y, djf, np.arange(-1,15), origin='lower', vmin=sn_min, vmax=sn_max) ''' div = make_axes_locatable(axs[0,0]) cax = div.append_axes("bottom", size="5%", pad="15%") cbar = fig.colorbar(pic, cax=cax, orientation="horizontal", ticks=[sn_min, sn_max]) cbar.ax.tick_params(labelsize=9) axs[0,0].set_title('DJF') m.ax = axs[0,1] m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10) m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10) m.drawcoastlines() m.drawstates() m.drawcountries() pic = m.imshow(mam, origin='lower', vmin=sn_min, vmax=sn_max) ''' nlats = 50; nlons = 96 #delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-0.5*np.indices((nlats,nlons))[0,:,:]) lons = (0.625*np.indices((nlats,nlons))[1,:,:]) x, y = m(lons*180./np.pi, lats*180./np.pi) pic = m.contour(x, y, mam, np.arange(-1,15), origin='lower', vmin=sn_min, vmax=sn_max) ''' div = make_axes_locatable(axs[0,1]) cax = div.append_axes("bottom", size="5%", pad="15%") cbar = fig.colorbar(pic, cax=cax, orientation="horizontal", ticks=[sn_min, sn_max]) cbar.ax.tick_params(labelsize=9) axs[0,1].set_title('MAM') m.ax = axs[1,0] m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10) m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10) m.drawcoastlines() m.drawstates() m.drawcountries() pic = m.imshow(jja, origin='lower', vmin=sn_min, vmax=sn_max) ''' nlats = 50; nlons = 96 #delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-0.5*np.indices((nlats,nlons))[0,:,:]) lons = (0.625*np.indices((nlats,nlons))[1,:,:]) x, y = m(lons*180./np.pi, lats*180./np.pi) pic = m.contour(x, y, jja, np.arange(-1,15), origin='lower', vmin=sn_min, vmax=sn_max) ''' div = make_axes_locatable(axs[1,0]) cax = div.append_axes("bottom", size="5%", pad="15%") cbar = fig.colorbar(pic, cax=cax, orientation="horizontal", ticks=[sn_min, sn_max]) cbar.ax.tick_params(labelsize=9) axs[1,0].set_title('JJA') m.ax = axs[1,1] m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10) m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10) m.drawcoastlines() m.drawstates() m.drawcountries() pic = m.imshow(son, origin='lower', vmin=sn_min, vmax=sn_max) ''' nlats = 50; nlons = 96 #delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-0.5*np.indices((nlats,nlons))[0,:,:]) lons = (0.625*np.indices((nlats,nlons))[1,:,:]) x, y = m(lons*180./np.pi, lats*180./np.pi) pic = m.contour(x, y, son, np.arange(-1,15), origin='lower', vmin=sn_min, vmax=sn_max) ''' cax = fig.add_axes([.13, 0.07, .08, .01]) div = make_axes_locatable(axs[1,1]) cax = div.append_axes("bottom", size="5%", pad="15%") cbar = fig.colorbar(pic, cax=cax, orientation="horizontal", ticks=[sn_min, sn_max]) cbar.ax.tick_params(labelsize=9) axs[1,1].set_title('SON') #plt.tight_layout(pad=0.1) fig.savefig(f'{yr}_{var}_snavgmaps_change.png') plt.show()
def netcdf2png(url, dirDest): # Dataset is the class behavior to open the file # and create an instance of the ncCDF4 class nc_fid = netCDF4.Dataset(url, 'r') # extract/copy the data lats = nc_fid.variables['lat'][:] lons = nc_fid.variables['lon'][:] data = nc_fid.variables['data'][:] band = nc_fid.variables['bands'][:] nc_fid.close() lon_0 = lons.mean() lat_0 = lats.mean() ax1 = Basemap(projection='merc',lon_0=lon_0,lat_0=lat_0,\ llcrnrlat=-42.866693,urcrnrlat=-22.039758,\ llcrnrlon=-66.800000,urcrnrlon=-44.968092,\ resolution='l') # data = data[0] # me quedo con el primer elemento de data # shape = numpy.shape(data) # guardo el shape original de data # data_vector = numpy.reshape(data,numpy.size(data)) # genero un vector de data usando su size (largo*ancho) # data_vector = normalizarData(band, data_vector) # invoco la funcion sobre el vector # img = numpy.reshape(data_vector, shape) # paso el vector a matriz usando shape como largo y ancho # print numpy.amin(img) # print numpy.amax(img) img = data[0] img *= 1024.0/numpy.amax(img) # normalizo los datos desde cero hasta 1024 # http://matplotlib.org/users/colormapnorms.html # dadas las lat y lon del archivo, obtengo las coordenadas x y para # la ventana seleccionada como proyeccion x, y = ax1(lons,lats) # dibujo img en las coordenadas x e y calculadas cs = ax1.pcolormesh(x, y, img, vmin=0., vmax=1024., cmap='jet') # ax1.pcolormesh(x, y, img, cmap='jet') # agrego los vectores de las costas, departamentos/estados/provincias y paises ax1.drawcoastlines() ax1.drawstates() ax1.drawcountries() # dibujo los valores de latitudes y longitudes ax1.drawparallels(numpy.arange(-45, -20, 5), labels=[1,0,0,0], linewidth=0.0, fontsize=10) ax1.drawmeridians(numpy.arange(-70, -45, 5), labels=[0,0,1,0], linewidth=0.0, fontsize=10) # agrego el colorbar cbar = ax1.colorbar(cs, location='bottom', pad='3%', ticks=[0., 512., 1024.]) cbar.ax.set_xticklabels(['Low', 'Medium', 'High'], fontsize=10) # agrego el logo en el documento logo = plt.imread('/sat/PRS/libs/PRS-auto/PRSpng/imgs/les-logo.png') plt.figimage(logo, 5, 5) # genero los datos para escribir el pie de pagina name = basename(url) # obtengo el nombre base del archivo destFile = dirDest + name + '.png' # determino el nombre del archivo a escribir name_split = name.split(".")[1:4] year = name_split[0] doy = name_split[1] hms = name_split[2] month = ymd(int(year), int(doy))[1] day = ymd(int(year), int(doy))[2] str_day = str(day).zfill(2) str_month = str(month).zfill(2) str_hm = hms[0:2] + ":" +hms[2:4] str_chnl = nameTag(band) tag = str_chnl + " " + str_day + "-" + str_month + "-" + year + " " + str_hm + " UTC" # agego el pie de pagina usando annotate plt.annotate(tag, (0,0), (140, -50), xycoords='axes fraction', textcoords='offset points', va='top', fontsize=10, family='monospace') plt.savefig(destFile, bbox_inches='tight', dpi=200) plt.close()
if state_name not in pollution: pollution[state_name] = [int(round(float(i['O3 Mean'])))] else: pollution[state_name].append(int(round(float(i['O3 Mean'])))) for i in pollution: lons.extend([coor_state[i][1]]*int(sum(pollution[i])/len(pollution[i]))) lats.extend([coor_state[i][0]]*int(sum(pollution[i])/len(pollution[i]))) # m = Basemap(projection = 'merc', llcrnrlat=10, urcrnrlat=50, llcrnrlon=-160, urcrnrlon=-60) m.drawcoastlines() m.drawcountries() m.drawstates() db = 1 # bin padding lon_bins = np.linspace(min(lons)-db, max(lons)+db, 36) # 10 bins lat_bins = np.linspace(min(lats)-db, max(lats)+db, 18) # 13 bins density, _, _ = np.histogram2d(lats, lons, [lat_bins, lon_bins]) # Turn the lon/lat of the bins into 2 dimensional arrays ready # for conversion into projected coordinates lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bins, lat_bins) # convert the bin mesh to map coordinates: xs, ys = m(lon_bins_2d, lat_bins_2d) # will be plotted using pcolormesh cdict = {'red': ( (0.0, 1.0, 1.0),
print "lon[0]: ", lonsout[0], "lon[-1]: ", lonsout[-1] print "lat[0]: ", lat[0], "lat[-1]: ", lat[-1] print lonsout[:] print lat[:] #-- create figure and axes instances fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0.1, 0.4, 0.7, 0.7]) #-- create map map = Basemap(projection='cyl',llcrnrlat= -90.,urcrnrlat= 90.,\ resolution='c', llcrnrlon=-180.,urcrnrlon=180.) #-- draw coastlines, state and country boundaries, edge of map map.drawcoastlines() map.drawstates() map.drawcountries() #-- create and draw meridians and parallels grid lines map.drawparallels(np.arange(-90., 90., 30.), labels=[1, 0, 0, 0], fontsize=10) map.drawmeridians(np.arange(-180., 180., 30.), labels=[0, 0, 0, 1], fontsize=10) #-- convert latitude/longitude values to plot x/y values x, y = map(*np.meshgrid(lon, lat)) #-- transform vector and coordinate data veclon = u10.shape[1] / 2 #-- only every 2nd vector veclat = u10.shape[0] / 2 #-- only every 2nd vector uproj, vproj, xx, yy = map.transform_vector(u,
m.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(0, 360, 60), labels=[1, 0, 0, 1]) plt.title('Cylindrical Equal Area', y=1.1) print('plotting Cylindrical Equal Area example ...') print(m.proj4string) # create new figure fig = plt.figure() # setup mercator map projection (-80 to +80). m = Basemap(llcrnrlon=-180.,llcrnrlat=-75,urcrnrlon=180.,urcrnrlat=75.,\ resolution='c',area_thresh=10000.,projection='merc',lat_ts=20) # plot image over map. im = m.pcolormesh(lons, lats, topodat, cmap=cmap, latlon=True) cb = m.colorbar() # draw colorbar m.drawcoastlines() # draw coastlines m.drawstates() # draw state boundaries m.fillcontinents() # fill continents # draw parallels and meridiands m.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(0, 360, 60), labels=[1, 0, 0, 1]) plt.title('Mercator', y=1.1) print('plotting Mercator example ...') print(m.proj4string) # create new figure fig = plt.figure() # setup cassini-soldner basemap. m = Basemap(llcrnrlon=-6,llcrnrlat=49,urcrnrlon=4,urcrnrlat=59,\ resolution='l',area_thresh=1000.,projection='cass',\ lat_0=54.,lon_0=-2.) # plot image over map.
def classificaGELO(caminhonc,caminhosaidatsmmsg,caminhosaidaantartica): # >> Gerando a lista -------------------------------------------- dirList=os.listdir(caminhonc) print dirList controleNome = dirList[0] #Buscando variaveis nos elementos da lista posicA = controleNome.find("CON") #Buscando variaveis nos elementos da lista anoi = posicA+4 #Buscando variaveis nos elementos da lista anof = posicA+8 #Buscando variaveis nos elementos da lista mesi = posicA+8 #Buscando variaveis nos elementos da lista mesf = posicA+10 #Buscando variaveis nos elementos da lista diai = posicA+10 #Buscando variaveis nos elementos da lista diaf = posicA+12 #Buscando variaveis nos elementos da lista horai = posicA+12 #Buscando variaveis nos elementos da lista horaf = posicA+14 #Buscando variaveis nos elementos da lista ano = controleNome[anoi:anof] #Buscando variaveis nos elementos da lista mes = controleNome[mesi:mesf] #Buscando variaveis nos elementos da lista dia = controleNome[diai:diaf] #Buscando variaveis nos elementos da lista horaTIT = controleNome[horai:horaf] #Buscando variaveis nos elementos da lista #imLista = len(dirList) #Definindo o tamnho da lista imLista = 01 #Redefinindo para considerar com base de 24 horas print ano,mes,dia,horaTIT print "################### TRATANDO OS DADOS *composição* ###################" # >> Lendo os arquivos e compondo a matriz ---------------------- entradas = '' for hora in range(0,imLista): entradas = caminhonc+nomeMSG+ano+mes+dia+str(horaTIT).zfill(2)+FMT_nc #Criando caminho print entradas fileCon = Dataset(entradas,'r') #------------------------------------------------------------------ IC0 = fileCon.variables['ice_conc'][:] IC0 = numpy.copy(IC0) dims = IC0.shape ny = dims[1] nx = dims[2] IC0 = IC0[0,:,:] IC02 = np.zeros((ny,nx)) #print min(IC0) #print max(IC0) #exit() for j in range(0,nx): for i in range(0,ny): if IC0[i,j] > 0. and IC0[i,j] <= 9.9 : IC02[i,j] = 3 elif IC0[i,j] > 9.9 and IC0[i,j] <= 39.9: IC02[i,j] =2 elif IC0[i,j] > 39.9 and IC0[i,j] <= 100.0: IC02[i,j] = 1 elif IC0[i,j] == 0.: IC02[i,j] = 3 else: IC02[i,j] = 0 IC02 = IC02 my_cmap = colors.ListedColormap(['gray','red','yellow','green']) #print IC02.shape IC0 = IC02 #figure() #histDado = IC0.reshape(830*790) #bins = arange(-100,100,50) #events,edges,patches = plt.hist(histDado)#, bins=bins, facecolor='green', alpha=0.75) #plt.ylabel('Pixels (un.)') #plt.xlabel('Valores') #plt.title('Histograma dos dados brutos da imagem MUR') #plt.grid(True) #show() filename2='/home/geonetcast/gelo/d-eumetcast/LonLatGelo_OSI-SAF.nc' print filename2 file1=Dataset(filename2, 'r') lon0=file1.variables['longitude'][:] lat0=file1.variables['latitude'][:] fig = plt.figure(figsize=(9.5,9)) #fig = plt.figure() #print "to aqui" Dmap = Basemap(projection='spstere',lat_0=-90,lon_0=0.,boundinglat=-55,lat_ts=-70, resolution='h',rsphere=(6378273.,6356889.44891)) #modificar a projeção entre os polos #Dmap.fillcontinents(color='gray') cor = 'black' x0,y0=Dmap(lon0,lat0) cmap=cm.Blues #IC0 = np.flipud(IC0[:,:]) col=Dmap.pcolor(x0,y0,IC0,shading='interp',vmin=0,vmax=3,cmap=my_cmap) # define parallels and meridians to draw. parallels = np.arange(-90.,-55,10.) meridians = np.arange(0.,360.,20.) Dmap.drawcoastlines(linewidth=.5, color = cor) # Linha de costa Dmap.drawcountries(linewidth=0.8, color='k', antialiased=1, ax=None, zorder=None) Dmap.drawstates(linewidth=0.5, color='k', antialiased=1, ax=None, zorder=None) # Dmap.drawparallels(parallels, labels = [1,0,0,0], color = cor, dashes=[1,0], linewidth=0.2) # Dmap.drawmeridians(meridians, labels = [0,0,0,1], color = cor, dashes=[1,0], linewidth=0.2) # Alteracao CT(T) Leandro corrigindo erro #https://stackoverflow.com/questions/22942855/plt-savefig-valueerror-all-values-in-the-dash-list-must-be-positive Dmap.drawparallels(parallels, labels = [1,0,0,0], color = cor, dashes=[1,1], linewidth=0.2) Dmap.drawmeridians(meridians, labels = [0,0,0,1], color = cor, dashes=[1,1], linewidth=0.2) #Paleta de Cor #bounds=[421.5,422.5,423.5,424.5,425.5,426.5,427.5] bounds=[0.5,1.5,2.5,3.5] norm = colores.BoundaryNorm(bounds, my_cmap.N) #l_label = '0-Mascara/1-Sem Gelo/2-Gelo Aberto/3-Gelo Fechado' #cbar = fig.colorbar(col, cmap=cm.Blues, norm=norm, boundaries=bounds, ticks=[422,423,424,425,426,427], orientation='horizontal', shrink=0.8,pad=0.045) #cbar.set_ticklabels(['9-10 Thents', '7-8 Thents', '4-6 Thents', '1-3 Thents', '< 1 Thents', 'Ice Free']) cbar = fig.colorbar(col, cmap=cmap, norm=norm, boundaries=bounds, ticks=[1,2,3], orientation='horizontal',shrink=0.8,pad=0.045) cbar.set_ticklabels(['Gelo Fechado', 'Gelo Aberto','Sem Gelo'])# horizontal colorbar #cbar = fig.colorbar(col, cmap=cmap, norm=norm, boundaries=bounds, ticks=[0,1,2,3], orientation='horizontal', shrink=0.8,pad=0.045) #cbar.set_ticklabels(['Gelo Fechado', 'Gelo Aberto','Sem Gelo']) #------------------------------------------------------------------ #Salvando e apresentado a imagem. d1 = datetime.date(int(ano),int(mes),int(dia)) #DIAS DA SEMANA diasem = d1.strftime("%A") if diasem == 'Monday': diasem = 'SEG' elif diasem == 'Tuesday': diasem = 'TER' elif diasem == 'Wednesday': diasem = 'QUA' elif diasem == 'Thursday': diasem = 'QUI' elif diasem == 'Friday': diasem = 'SEX' elif diasem == 'Saturday': diasem = 'SAB' elif diasem == 'Sunday': diasem = 'DOM' #MES EM NOME nomemes = d1.strftime("%B") if nomemes == 'January': nomemes = 'JAN' elif nomemes == 'February': nomemes = 'FEV' elif nomemes == 'March': nomemes = 'MAR' elif nomemes == 'April': nomemes = 'ABR' elif nomemes == 'May': nomemes = 'MAI' elif nomemes == 'June': nomemes = 'JUN' elif nomemes == 'July': nomemes = 'JUL' elif nomemes == 'August': nomemes = 'AGO' elif nomemes == 'September': nomemes = 'SET' elif nomemes == 'October': nomemes = 'OUT' elif nomemes == 'November': nomemes = 'NOV' elif nomemes == 'December': nomemes = 'DEZ' title('CHM-REMO Limite de Gelo Marinho '+str(dia).zfill(2)+nomemes+ano+'('+diasem+') - GEONETCAST-EUMETSAT/O&SI-SAF',fontsize=8.,fontweight='bold') dirsaida = caminhosaidatsmmsg FMT_png = ".png" nome1 = "LIM_GEL_" fname = dirsaida+nome1+str(ano)+str(mes).zfill(2)+str(dia).zfill(2)+'analise'+FMT_png #savefig(fname, bbox_inches='tight') savefig(fname,dpi=700,bbox_inches='tight') # Incluida 3 linhas abaixos pelo CT Leandro para salvar tambem no d-saida/antartica dirsaida = caminhosaidaantartica fname = dirsaida+nome1+str(ano)+str(mes).zfill(2)+str(dia).zfill(2)+'analise'+FMT_png savefig(fname,dpi=700,bbox_inches='tight')
def fr2png(url, colormapPath, colormapName, dirDest, lat_name, lon_name, data_name, geos=False): # Dataset is the class behavior to open the file # and create an instance of the ncCDF4 class nc_fid = netCDF4.Dataset(url, 'r') t_coverage = repr(nc_fid.getncattr('time_coverage_start')) # print t_coverage ds_name = repr(nc_fid.getncattr('dataset_name')) # print ds_name date = re.search('\'(.*?)\'', t_coverage).group(1) print(date) channel = re.search('-M\d(.*?)_', ds_name).group(1) print(channel) channelInfo(channel) yl = date[0:4] yy = date[2:4] mt = date[5:7] dd = date[8:10] hh = date[11:13] mm = date[14:16] ss = date[17:19] str_date = str(dd) + '/' + str(mt) + '/' + str(yl) + " " + str( hh) + ":" + str(mm) date = datetime.datetime.strptime( str_date, '%d/%m/%Y %H:%M') - datetime.timedelta(hours=3) name = channel + " " + date.strftime('%d-%m-%Y %H:%M') filename = channel + "_" + yy + mt + dd + "_" + hh + mm + ss # extract/copy the data data = nc_fid.variables[data_name][:] if data_name == 'CMI' or data_name == 'Rad': # Satellite height sat_h = nc_fid.variables[ 'goes_imager_projection'].perspective_point_height # Satellite longitude sat_lon = nc_fid.variables[ 'goes_imager_projection'].longitude_of_projection_origin # Satellite sweep sat_sweep = nc_fid.variables['goes_imager_projection'].sweep_angle_axis X = nc_fid.variables[lon_name][:] # longitud, eje X Y = nc_fid.variables[lat_name][:] # latitud, eje Y scene_id_val = repr(nc_fid.getncattr('scene_id')) scene_id = re.search('\'(.*?)\'', scene_id_val).group(1) nc_fid.close() print("Realizando pasaje a K en C13 y truncamiento en los otros") if isBrightTemp(channel): # Los datos estan en kelvin, asi que los paso a Celsius data -= 273.15 else: for d in numpy.nditer(data, op_flags=['readwrite']): d = truncUno(d) data *= 100 # if if channel == 'C13': #::::::::::::::::::::::::::::: # Basemap print("Ventana Río de la Plata") # https://github.com/blaylockbk/pyBKB_v2/blob/master/BB_goes16/mapping_GOES16_data.ipynb X *= sat_h Y *= sat_h # Región ax = Basemap(projection='merc',\ llcrnrlat=-42.94,urcrnrlat=-22.0,\ llcrnrlon=-67.0,urcrnrlon=-45.04,\ resolution='f') x_mesh, y_mesh = numpy.meshgrid(X, Y) projection = Proj(proj='geos', h=sat_h, lon_0=sat_lon, sweep=sat_sweep, ellps='WGS84') lons, lats = projection(x_mesh, y_mesh, inverse=True) x, y = ax(lons, lats) # https://stackoverflow.com/questions/16598393/how-to-write-variables-as-binary-data-with-python #::::::::::::::::::::::::::::: # Basemap End # llamo al garbage collector para que borre los elementos que ya no se van a usar gc.collect() # agrego los vectores de las costas, departamentos/estados/provincias y paises ax.drawcoastlines(linewidth=0.40) ax.drawcountries(linewidth=0.40) ax.drawstates(linewidth=0.20) paraguay_poly(ax) rincon_de_artigas_poly(ax) if not geos: # dibujo los valores de latitudes y longitudes al margen de la imagen par = ax.drawparallels(numpy.arange(-45, -20, 5), labels=[1, 0, 0, 0], linewidth=0.0, fontsize=7, color='white') mer = ax.drawmeridians(numpy.arange(-70, -45, 5), labels=[0, 0, 1, 0], linewidth=0.0, fontsize=7, color='white') setcolor(par, 'white') setcolor(mer, 'white') # defino el min y max en funcion de la banda vmin, vmax = rangoColorbar(channel) data = numpy.ma.masked_where(numpy.isnan(data), data) # defino el colormap y la disposicion de los ticks segun la banda if isBrightTemp(channel): ticks = [ -100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70 ] ticksLabels = ticks else: ticks = [0, 20, 40, 60, 80, 100] ticksLabels = ticks # if FR o RP cmap = gmtColormap(colormapName, colormapPath, 2048) cs = ax.pcolormesh(x, y, data, vmin=vmin, vmax=vmax, cmap=cmap) # seteo los limites del colorbar plt.clim(vmin, vmax) # agrego el colorbar cbar = ax.colorbar(cs, location='bottom', ticks=ticks) # , pad='3%' if isBrightTemp(channel): cbar.ax.xaxis.labelpad = 0 cbar.ax.set_xlabel("Temperatura de brillo ($^\circ$C)", fontsize=7, color='white') cbar.ax.set_xticklabels(ticksLabels, rotation=45, fontsize=7, color='white') else: cbar.ax.set_xlabel("Factor de reflectancia (%)", fontsize=7, color='white') cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='white') # agrego el logo en el documento logo_bw = plt.imread('/sat/PRS/dev/PRS-sat/PRSgoes/logo_300_bw.png') plt.figimage(logo_bw, xo=5, yo=5) # si no existe la carpeta asociada a la banda la creo if not os.path.isdir(dirDest + channel): os.mkdir(dirDest + channel) # if # si no existe la carpeta asociada al ano la creo if not os.path.isdir(dirDest + channel + '/' + yl): os.mkdir(dirDest + channel + "/" + yl) # if outPath = dirDest + channel + "/" + yl + "/" # si estoy dibujando toda la proyección geos adjunto el string al nombre del archivo if geos: outPath = outPath + filename + '_geos.png' # determino el nombre del archivo a escribir else: whitePath = outPath + filename + '_white.png' # determino el nombre del archivo a escribir outPath = outPath + filename + '.png' # determino el nombre del archivo a escribir # llamo al garbage collector para que borre los elementos que ya no se van a usar gc.collect() print(outPath) print("numpy.sum(data): %f" % (numpy.sum(data))) Noche = numpy.sum(data) <= 0. if Noche: # print "es noche" plt.annotate("NOCHE", (0, 0), (180, 15), color='white', xycoords='axes fraction', textcoords='offset points', va='top', fontsize=10, family='monospace') x_coord = 85 y_coord = -53 # genero el pie de la imagen, con el logo y la info del archivo plt.annotate(name + " UY", (0, 0), (x_coord, y_coord), xycoords='axes fraction', textcoords='offset points', va='top', fontsize=11, family='monospace', color='white') plt.savefig(outPath, bbox_inches='tight', dpi=400, transparent=True) # , facecolor='#4F7293' #################### ## WHITE if isBrightTemp(channel): cbar.ax.xaxis.labelpad = 0 cbar.ax.set_xlabel("Temperatura de brillo ($^\circ$C)", fontsize=7, color='black') cbar.ax.set_xticklabels(ticksLabels, rotation=45, fontsize=7, color='black') else: cbar.ax.set_xlabel("Factor de reflectancia (%)", fontsize=7, color='black') cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='black') setcolor(par, 'black') setcolor(mer, 'black') logo_color = plt.imread('/sat/PRS/dev/PRS-sat/PRSgoes/logo_300_color.png') plt.figimage(logo_color, xo=5, yo=5) plt.annotate(name + " UY", (0, 0), (x_coord, y_coord), xycoords='axes fraction', textcoords='offset points', va='top', fontsize=11, family='monospace', color='black') plt.savefig(whitePath, bbox_inches='tight', dpi=400, transparent=False, facecolor='white') # , facecolor='#4F7293' #################### #################### # copio la ultima imagen de cada carpeta en la raiz PNG para subir a la web # plt.savefig(dirDest + channel + '.png', bbox_inches='tight', dpi=300, transparent=True) # , facecolor='#4F7293' copyfile(outPath, dirDest + channel + '.png') copyfile(whitePath, dirDest + channel + '_white.png') plt.close() if channel == 'C02': return yl + mt + dd + hh + mm + ss
def map_results(self): "save the nexrad locations to an array from the PyART library" locs = pyart.io.nexrad_common.NEXRAD_LOCATIONS "set up the figure for plotting" fig = plt.figure(figsize=(12, 8), dpi=100) ax = fig.add_subplot(111) "create a basemap for CONUS" m = Basemap(projection='lcc', lon_0=-95, lat_0=35., llcrnrlat=20, urcrnrlat=50, llcrnrlon=-120, urcrnrlon=-60, resolution='l') "draw the geography for the basemap" m.drawcoastlines(linewidth=1) m.drawcountries(linewidth=1) m.drawstates(linewidth=0.5) "plot a point and a label for each of the radar site locations within the CONUS domain" for key in locs: lon = locs[key]['lon'] lat = locs[key]['lat'] name = key if lon >= -120 and lon <= -60 and lat >= 20 and lat <= 50: m.scatter(lon, lat, marker='o', color='b', latlon=True) x, y = m(lon + 0.2, lat + 0.2) plt.text(x, y, name, color='k', fontsize=7) "create a figure title" fig.text(0.5, 0.92, 'CONUS NEXRAD locations', horizontalalignment='center') plt.show() "base map has been fully developed at this time, move on to display data on base map" "select the radar site" site = get_results() "Here I want to fetch the site value that the user inputted from the previous function" "get the radar location (this is used to set up the basemap and plotting grid)" loc = pyart.io.nexrad_common.get_nexrad_location(site) lon0 = loc[1] lat0 = loc[0] "use boto to connect to the AWS nexrad holdings directory" s3conn = boto.connect_s3() bucket = s3conn.get_bucket('noaa-nexrad-level2') "create a datetime object for the current time in UTC and use the" "year, month, and day to drill down into the NEXRAD directory structure." start_time = get_results() """get the bucket list for the selected date Note: this returns a list of all of the radar sites with data for the selected date""" ls = bucket.list(prefix=start_time, delimiter=',') for key in ls: "only pull the data and save the arrays for the site we want" if site in key.name.split(',')[-2]: "set up the path to the NEXRAD files" path = start_time + site + ',' + site "grab the last file in the file list" fname = bucket.get_all_keys(prefix=path)[-1] "get the file" s3key = bucket.get_key(fname) "save a temporary file to the local host" localfile = tempfile.NamedTemporaryFile(delete=False) "write the contents of the NEXRAD file to the temporary file" s3key.get_contents_to_filename(localfile.name) "use the read_nexrad_archive function from PyART to read in NEXRAD file" radar = pyart.io.read_nexrad_archive(localfile.name) "get the date and time from the radar file for plot enhancement" time = radar.time['units'].split(' ')[-1].split('T') print(site + ': ' + time[0] + ' at ' + time[1]) "set up the plotting grid for the data" display = pyart.graph.RadarMapDisplay(radar) x, y = display._get_x_y(0, True, None) # set up a 1x1 figure for plotting fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(9, 9), dpi=100) # set up a basemap with a lambert conformal projection centered # on the radar location, extending 1 degree in the meridional direction # and 1.5 degrees in the longitudinal in each direction away from the # center point. m = Basemap(projection='lcc', lon_0=lon0, lat_0=lat0, llcrnrlat=lat0 - 1.25, llcrnrlon=lon0 - 1.5, urcrnrlat=lat0 + 1.25, urcrnrlon=lon0 + 1.5, resolution='h') # get the plotting grid into lat/lon coordinates x0, y0 = m(lon0, lat0) glons, glats = m((x0 + x * 1000.), (y0 + y * 1000.), inverse=True) # read in the lowest scan angle reflectivity field in the NEXRAD file refl = np.squeeze(radar.get_field(sweep=0, field_name='reflectivity')) # set up the plotting parameters (NWSReflectivity colormap, contour levels, # and colorbar tick labels) cmap = 'pyart_NWSRef' levs = np.linspace(0, 80, 41, endpoint=True) ticks = np.linspace(0, 80, 9, endpoint=True) label = 'Radar Reflectivity Factor ($\mathsf{dBZ}$)' # define the plot axis to the be axis defined above ax = axes # normalize the colormap based on the levels provided above norm = mpl.colors.BoundaryNorm(levs, 256) # create a colormesh of the reflectivity using with the plot settings defined above cs = m.pcolormesh(glons, glats, refl, norm=norm, cmap=cmap, ax=ax, latlon=True) # add geographic boundaries and lat/lon labels m.drawparallels(np.arange(20, 70, 0.5), labels=[1, 0, 0, 0], fontsize=12, color='k', ax=ax, linewidth=0.001) m.drawmeridians(np.arange(-150, -50, 1), labels=[0, 0, 1, 0], fontsize=12, color='k', ax=ax, linewidth=0.001) m.drawcounties(linewidth=0.5, color='gray', ax=ax) m.drawstates(linewidth=1.5, color='k', ax=ax) m.drawcoastlines(linewidth=1.5, color='k', ax=ax) # mark the radar location with a black dot m.scatter(lon0, lat0, marker='o', s=20, color='k', ax=ax, latlon=True) # add the colorbar axes and create the colorbar based on the settings above cax = fig.add_axes([0.075, 0.075, 0.85, 0.025]) cbar = plt.colorbar(cs, ticks=ticks, norm=norm, cax=cax, orientation='horizontal') cbar.set_label(label, fontsize=12) cbar.ax.tick_params(labelsize=11) # add a title to the figure fig.text(0.5, 0.92, site + ' (0.5$^{\circ}$) Reflectivity\n ' + time[0] + ' at ' + time[1], horizontalalignment='center', fontsize=16) # display the figure plt.show()
urcrnrlon = geo_data['right_lon'] lat_ts = 20 land_color = '#ffedcc' water_color = '#2980b9' time0 = time.time() map1 = Basemap(projection='merc',llcrnrlat=llcrnrlat,urcrnrlat=urcrnrlat,\ llcrnrlon=llcrnrlon,urcrnrlon=urcrnrlon,lat_ts=lat_ts,resolution='h', ax=ax1) map1.drawmapboundary(fill_color=water_color) map1.fillcontinents(color=land_color, lake_color=water_color) map1.drawcoastlines() map1.drawcountries() map1.drawstates() print('time map1: {:f}'.format(time.time() - time0)) time0 = time.time() llcrnrlon = -70.7574 urcrnrlat = -21.4249 urcrnrlon = -67.8708 llcrnrlat = -23.7175 map2 = Basemap(projection='merc',llcrnrlat=llcrnrlat,urcrnrlat=urcrnrlat,\ llcrnrlon=llcrnrlon,urcrnrlon=urcrnrlon,lat_ts=lat_ts,resolution='h', ax=ax2) map2.drawmapboundary(fill_color=water_color) map2.fillcontinents(color=land_color, lake_color=water_color) map2.drawcoastlines()
def plot_fp_act(FP_ID, FP_utilize_df, act_track_data, flight_plan_data, feed_track=None, pred_track=None, pred_track_mu=None, pred_track_cov=None, k=9, nstd=3, sort=True, plot_weather_info=False, **kwargs): # TODO: plot error ellipse ori_lat = 29.98333333 ori_lon = -95.33333333 des_lat = 42.36666667 des_lon = -71 fig = plt.figure(figsize=(8, 6)) m = Basemap(llcrnrlon=-100, llcrnrlat=27, urcrnrlon=-68, urcrnrlat=46, projection='merc') m.drawmapboundary(fill_color='#8aeaff') m.fillcontinents(color='#c5c5c5', lake_color='#8aeaff') m.drawcoastlines(linewidth=0.5) m.drawcountries(linewidth=0.5) m.drawstates(linewidth=0.5) m.drawparallels(np.arange(10., 35., 5.)) m.drawmeridians(np.arange(-120., -80., 10.)) x1, y1 = m(ori_lon, ori_lat) x2, y2 = m(des_lon, des_lat) plt.plot(x1, y1, 'r*', ms=15, zorder=10) plt.plot(x2, y2, 'r*', ms=15, zorder=10) fid_fp1 = FP_utilize_df.loc[FP_utilize_df.FLT_PLAN_ID == FP_ID, 'FID'].values print('%d flights filed flight plan %s' % (fid_fp1.shape[0], FP_ID)) plot_track = act_track_data.loc[act_track_data.FID.isin(fid_fp1)] plot_fp = flight_plan_data.loc[flight_plan_data.FLT_PLAN_ID_REAL == FP_ID] x_fp, y_fp = m(plot_fp.LONGITUDE.values, plot_fp.LATITUDE.values) feed_x, feed_y = m(feed_track.Lon.values, feed_track.Lat.values) feed, = plt.plot(feed_x, feed_y, 'o-', ms=4, linewidth=3, color='g', label='Feed tracks', zorder=9) for gpidx, gp in plot_track.groupby('FID'): x, y = m(gp.Lon.values, gp.Lat.values) actual, = plt.plot(x, y, '--', linewidth=2, color='b', label='Actual Tracks', zorder=8) fp, = plt.plot(x_fp, y_fp, '-', linewidth=2, color='r', label='Flight Plans', zorder=5) if pred_track is not None: if sort: x, y = m(pred_track[k][pred_track[k][:, 3].argsort()][:, 1], pred_track[k][pred_track[k][:, 3].argsort()][:, 0]) else: x, y = m(pred_track[k, :, 1], pred_track[k, :, 0]) pred_fig, = plt.plot(x, y, 'o--', ms=3, zorder=7) if pred_track_mu is not None: if sort: x, y = m(pred_track_mu[k][pred_track_mu[k][:, 3].argsort()][:, 1], pred_track_mu[k][pred_track_mu[k][:, 3].argsort()][:, 0]) else: x, y = m(pred_track_mu[k][:, 1], pred_track_mu[k][:, 0]) plt.plot(x, y, 'mo--', ms=4, zorder=7, label='Predicted tracks') if pred_track_cov is not None: for t in range(pred_track_mu[k].shape[0]): lon_a = np.sqrt(pred_track_cov[k, t, 1, 1]) * nstd lat_b = np.sqrt(pred_track_cov[k, t, 0, 0]) * nstd # assume independency # cov_width, cov_height, cov_theta = get_cov_ellipse_wh(predicted_tracks_cov[k, t, :2, :2], nstd = 3) centre_lon, centre_lat = (pred_track_mu[k, t, 1], pred_track_mu[k, t, 0]) poly = m.ellipse(centre_lon, centre_lat, lon_a, lat_b, 50, facecolor='green', zorder=6, alpha=0.25) plt.legend(fontsize=12, loc=2) if plot_weather_info: grbs_common_info_file = kwargs.get( 'grbs_common_info_file', '/media/storage/DATA/filtered_weather_data/grbs_common_info.npz') wind_file_root = kwargs.get( 'wind_file_root', '../../DATA/filtered_weather_data/namanl_small_npz/') wx_file_root = kwargs.get('wx_file_root', '../../DATA/NCWF/gridded_storm_hourly/') resolution = kwargs.get('resolution', 50) wind_scale = kwargs.get('wind_scale', 1000) wind_fname_list = [ os.path.join(wind_file_root, wf) for wf in np.unique(plot_track['wind_fname']) ] wx_file_time = plot_track['wx_fname'].values wx_file_time = np.unique(wx_file_time[~pd.isnull(wx_file_time)]) wx_fname_list = [ os.path.join( wx_file_root, wf.replace('-', '_').replace(' ', '_').replace(':', '')[:15] + 'Z.npz') for wf in wx_file_time ] _ = plot_wx(m, wind_fname_list=wind_fname_list, wx_fname_list=wx_fname_list, grbs_common_info_file=grbs_common_info_file, resolution=resolution, wind_scale=wind_scale) plt.title('Flight %s with flight plan %s' % (plot_track.FID.unique(), FP_ID)) plt.show() return plot_track, fig
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt m = Basemap(projection='mill', llcrnrlat = -90, llcrnrlon = -180, urcrnrlat = 90, urcrnrlon = 180) m.drawcoastlines() m.drawcountries(linewidth=2) m.drawstates(color='b') m.drawcounties(color='darkred') plt.title('Basemap Tutorial') plt.show()
def make_map(llcrnrlon=-51, urcrnrlon=-30.2, llcrnrlat=-15, urcrnrlat=7.1, projection='merc', resolution='i', figsize=(6, 6), inset=True, axe=None, steplat=2, steplon=2, inloc=1, contcolor='0.85'): ''' This function creates a basemap map easily with option of inset axe with geolocation. It's all based on make_map from Filipe Fernandes, but with some changes ''' if axe == None: fig, ax = plt.subplots(figsize=figsize) m = Basemap(llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, projection=projection, resolution=resolution) else: m = Basemap(llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, projection=projection, resolution=resolution, ax=axe) ax = axe print('Map Created!') m.drawstates(zorder=22) m.drawcoastlines(zorder=21) m.fillcontinents(color=contcolor, zorder=20) meridians = np.arange(np.floor(llcrnrlon), np.ceil(urcrnrlon) + 2, steplon) parallels = np.arange(np.floor(llcrnrlat), np.ceil(urcrnrlat) + 2, steplat) m.drawparallels(parallels, linewidth=0.4, labels=[1, 0, 0, 0], zorder=23) m.drawmeridians(meridians, linewidth=0.4, labels=[0, 0, 0, 1], zorder=24) m.llcrnrlon = llcrnrlon m.urcrnrlon = urcrnrlon m.llcrnrlat = llcrnrlat m.urcrnrlat = urcrnrlat m.ax = ax if inset: axin = inset_axes(m.ax, width="30%", height="30%", loc=inloc) # Global inset map. inmap = Basemap(projection='ortho', lon_0=np.mean(-42), lat_0=np.mean(-4), ax=axin, anchor='NE') inmap.drawcountries(color='white') inmap.fillcontinents(color='gray') bx, by = inmap(m.boundarylons, m.boundarylats) xy = list(zip(bx, by)) mapboundary = Polygon(xy, edgecolor='r', linewidth=1, fill=False) inmap.ax.add_patch(mapboundary) if axe == None: return fig, m else: return m
def plot_card(): """ **Title: Function for plotting a geographical map** *Description: Plotting a geographical map which contains a marker und text* :variable fig: plots figure with figuresize 12,8 :variable m: creates a Basemap instance :variable parallels: includes coordinates range and interval :variable meridians: includes coordinates range and interval :variable Vienna: include coordinates of city Vienna :method m.drawparallels: draws paralells :method m.drawmeridians: draws meridians :method m.drawcoastlines: draws coastlines :method m.drawstates: draws states :method m.drawcountries: draws countries :method m.drawlsmask: coloring the ocean and the land :method m.shadedrelief: add relief :method m.plot: add marker the the card at position of vienna :method plt.text: add name of city to the marker :method plt.title: add title above the card plotted before :method plt.savefig: saving the card as png-file :method plt.show: shows plot after setting the properties """ fig = plt.figure(figsize=(12, 8)) # create a Basemap instance m = Basemap( projection='cyl', # try different projection, e.g. 'merc' for mercator llcrnrlon=5.0, llcrnrlat=45, urcrnrlon=30, urcrnrlat=62.5, resolution='l', area_thresh=10.) # draw parallels parallels = np.arange(-90., 90., 10.0) m.drawparallels(parallels, labels=[True, False, False, True], fontsize=10) # draw meridians meridians = np.arange(-180.0, 180.0, 10.0) m.drawmeridians(meridians, labels=[True, False, False, True], fontsize=10) # draw coastlines, states and countries m.drawcoastlines() m.drawstates() m.drawcountries() # coloring the oceans and the land m.drawlsmask(land_color='lightgreen', ocean_color='aqua', lakes=True) # add relief m.shadedrelief() # draw some data to the map (coordinates) Vienna = (16.3720800, 48.2084900) # transform coordinates for the projection Vienna = m(Vienna[0], Vienna[1]) # add marker the the card at position of Vienna m.plot(Vienna[0], Vienna[1], 'c*', markersize=12, color='black' ) # the markers are the same as in the case of normal plot.. # add name of city to the marker plt.text(Vienna[0] + 0.25, Vienna[1] + 0.25, "Vienna", size=18) # add title above the card plotted before plt.title("9th of July 2018, 12:00 UTC, Hohe Warte, Vienna") # saving the card as png-file and show plot plt.savefig('basemap.png') plt.show()
def main(show=True, outfile=None): db = connect() stations = get_stations(db, all=False) coords = [(sta.Y, sta.X) for sta in stations] coords = np.array(coords) sta_map = folium.Map( location=[np.mean(coords[:, 0]), np.mean(coords[:, 1])], zoom_start=3, tiles='OpenStreetMap') folium.RegularPolygonMarker(location=[np.mean(coords[:, 1]), np.mean(coords[:, 0])]).\ add_to(sta_map) for sta in stations: folium.RegularPolygonMarker(location=[sta.Y, sta.X], popup="%s_%s" % (sta.net, sta.sta), fill_color='red', number_of_sides=3, radius=12).add_to(sta_map) sta_map.add_child(folium.LatLngPopup()) if outfile: tmp = outfile if outfile.startswith("?"): now = datetime.datetime.now() now = now.strftime('station map on %Y-%m-%d %H.%M.%S') tmp = outfile.replace('?', now) print("output to:", tmp) sta_map.save('%s.html' % tmp) # plot topography/bathymetry as an image. bufferlat = (np.amax(coords[:, 0]) - np.amin(coords[:, 0])) + .1 bufferlon = (np.amax(coords[:, 1]) - np.amin(coords[:, 1])) + .1 m = Basemap(projection='mill', llcrnrlat=np.amin(coords[:, 0]) - bufferlat, urcrnrlat=np.amax(coords[:, 0]) + bufferlat, llcrnrlon=np.amin(coords[:, 1]) - bufferlon, urcrnrlon=np.amax(coords[:, 1]) + bufferlon, resolution='i') # Draw station coordinates x, y = m(coords[:, 1], coords[:, 0]) # create new figure, axes instance. fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # attach new axes image to existing Basemap instance. m.ax = ax try: m.shadedrelief() except: traceback.print_exc() m.scatter(x, y, 50, marker='v', color='r') for sta in stations: xpt, ypt = m(sta.X, sta.Y) plt.text(xpt, ypt, "%s_%s" % (sta.net, sta.sta), fontsize=9, ha='center', va='top', color='k', bbox=dict(boxstyle="square", ec='None', fc=(1, 1, 1, 0.5))) # draw coastlines and political boundaries. m.drawcoastlines() m.drawcountries() m.drawstates() # draw parallels and meridians. # label on left and bottom of map. parallels = np.arange(-90, 90, 10.) m.drawparallels(parallels, labels=[1, 0, 0, 1]) meridians = np.arange(0., 360., 10.) m.drawmeridians(meridians, labels=[1, 0, 0, 1]) # add colorbar ax.set_title('Station map') if outfile: if outfile.startswith("?"): now = datetime.datetime.now() now = now.strftime('station map on %Y-%m-%d %H.%M.%S') outfile = outfile.replace('?', now) print("output to:", outfile) plt.savefig(outfile) if show: plt.show()
def map2DGrid(ax, grid, tstr, xlen=1.0, ylen=1.0, isLeft=False, prj='lcc', bous=0, gmap=0, xinc=None, yinc=None, pnts=None, cmap='gist_earth'): """ grid is a Grid2D object prj : lcc / merc """ xmin, xmax, ymin, ymax = grid.getBounds() pdata = grid.getData() nr, nc = pdata.shape lonrange = np.linspace(xmin, xmax, num=nc) latrange = np.linspace(ymin, ymax, num=nr) lon, lat = np.meshgrid(lonrange, latrange) if xinc != None: xmax = xmax + xinc if yinc != None: ymax = ymax + yinc latmean = np.mean([ymin, ymax]) lonmean = np.mean([xmin, xmax]) #"Lambert Conformal Conic",lcc 'merc': "Mercator", if gmap == 1: m = Basemap(projection='robin',ellps='WGS84',\ resolution='c',area_thresh=1000.,\ lat_0 = latmean, lon_0=lonmean, ax=ax) elif gmap == 2: m = Basemap(projection='hammer',ellps='WGS84',\ resolution='c',area_thresh=1000.,\ lat_0 = latmean, lon_0=lonmean, ax=ax) else: #print(xmin,xmax,ymin,ymax, latmean, lonmean) m = Basemap(llcrnrlon=xmin,llcrnrlat=ymin,urcrnrlon=xmax,urcrnrlat=ymax,\ ellps='WGS84',\ resolution='c',area_thresh=1000.,projection=prj,\ lat_0 = latmean, lon_0=lonmean,ax=ax) # #print('else') # m = Basemap(llcrnrlon=xmin,llcrnrlat=ymin,urcrnrlon=xmax,urcrnrlat=ymax,\ # rsphere=(6378137.00,6356752.3142),\ # resolution='c',area_thresh=1000.,projection= prj,\ # lat_1=latmean,lon_0=lonmean,ax=ax) # draw coastlines and political boundaries. m.drawcoastlines() if bous == 1: m.drawcountries() elif bous == 2: m.drawcountries() m.drawstates() lons = np.arange(xmin, xmax, xlen) lats = np.arange(ymin, ymax, ylen) if isLeft: labels = labels = [1, 0, 0, 0] else: labels = labels = [0, 0, 0, 0] if not gmap: m.drawparallels(lats, labels=labels, color='white', fmt='%.1f') # draw parallels m.drawmeridians(lons, labels=[0, 0, 0, 1], color='white', fmt='%.1f') # draw meridians pmesh = m.pcolormesh(lon, lat, np.flipud(grid.getData()), latlon=True, cmap=cmap) if pnts != None: x, y = m(*np.meshgrid(pnts[0], pnts[1])) #(lons,lats)) m.scatter(x, y, marker='o', color='m') if ax is not None: ax.set_title(tstr) m.colorbar(pmesh)
def execute(self): ds = Dataset(self.dataset.getValue(), mode='r') if 'rlon' in ds.variables: lons = ds.variables['rlon'][:] lats = ds.variables['rlat'][:] else: lons = ds.variables['lon'][:] lats = ds.variables['lat'][:] # Guess variable name = longname = None for key, variable in ds.variables.items(): if key.lower() in ds.dimensions: # skip dimension variables continue if '_bnds' in key.lower(): continue if key.lower() in self.SPATIAL_VARIABLES: continue name = key longname = getattr(variable, 'long_name', key) break var = ds.variables[name][0][:] units = ds.variables[name].units ds.close() # Get some parameters for the Stereographic Projection lon_0 = lons.mean() lat_0 = lats.mean() m = Basemap(llcrnrlon=lons[0], llcrnrlat=lats[0], urcrnrlon=lons[-1], urcrnrlat=lats[-1], resolution='l', projection='cyl', lat_0=lat_0, lon_0=lon_0) # Because our lon and lat variables are 1D, # use meshgrid to create 2D arrays # Not necessary if coordinates are already in 2D arrays. lon, lat = np.meshgrid(lons, lats) xi, yi = m(lon, lat) # Plot Data cs = m.pcolor(xi, yi, np.squeeze(var)) # Add Grid Lines # m.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10) # m.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10) # Add Coastlines, States, and Country Boundaries m.drawcoastlines() m.drawstates() m.drawcountries() # Add Colorbar cbar = m.colorbar(cs, location='bottom', pad="10%") cbar.set_label(units) # Add Title plt.title(longname) plt.savefig('output.png') self.output.setValue('output.png')
def event_plot(self, assoc_id, west=-104.5, east=-94, south=33.5, north=37.5, deltalon=1.0, deltalat=1.0): """ Plot all the circles, stations, location and residual distribution on one map by calling the event number after the event been associated. """ from itertools import cycle plot_colors = cycle(['r', 'g', 'b', 'c', 'm', 'y']) fig = plt.figure(figsize=(15, 8)) ax = fig.add_subplot(111) # ============================================================= ### Map bound # # North # # West East # # South # # ============================================================= ### Basemap Module m = Basemap(projection='merc', llcrnrlat=south, urcrnrlat=north, llcrnrlon=west, urcrnrlon=east, lat_ts=0, resolution='c') m.drawcountries() m.drawstates() m.fillcontinents(color='white', lake_color='aqua', zorder=1) # ============================================================= # draw parallels, meridians and structures. # m.drawparallels(np.arange(South,North,deltalat),labels=[1,0,0,0],color='gray',dashes=[1,1e-5],labelstyle='+/-',linewidth=0.1) # m.drawmeridians(np.arange(West,East,deltalon),labels=[0,0,0,1],color='gray',dashes=[1,1e-5],labelstyle='+/-',linewidth=0.1) m.drawmapboundary(fill_color='blue') # ============================================================= # plot matches and mismatches circles matches = self.assoc_db.query(Candidate).filter( Candidate.assoc_id == assoc_id).filter( Candidate.locate_flag == True).all() mismatches = self.assoc_db.query(Candidate).filter( Candidate.assoc_id == assoc_id).filter( Candidate.locate_flag == False).all() lon_eve, lat_eve = self.assoc_db.query( Associated.longitude, Associated.latitude).filter(Associated.id == assoc_id).first() radius_rainbow = [] s_p_rainbow = [] rainbow = [] sta_rainbow = [] for match in matches: lon, lat = self.tt_stations_db_1D.query( Station1D.longitude, Station1D.latitude).filter(Station1D.sta == match.sta).first() s_p_rainbow.append((match.ts - match.tp).total_seconds()) radius_rainbow.append(match.d_km) Color = plot_colors.__next__() rainbow.append(Color) sta_rainbow.append(match.sta) LocPair, = equi(m, lon, lat, match.d_km, lw=2., color=Color) legend_list = {"Pair for locating": LocPair} for mismatch in mismatches: lon, lat = self.tt_stations_db_1D.query( Station1D.longitude, Station1D.latitude).filter( Station1D.sta == mismatch.sta).first() s_p_rainbow.append((mismatch.ts - mismatch.tp).total_seconds()) radius_rainbow.append(mismatch.d_km) Color = plot_colors.__next__() rainbow.append(Color) sta_rainbow.append(mismatch.sta) UnlocPair, = equi(m, lon, lat, mismatch.d_km, ls='--', lw=1., color=Color) try: mismatch except NameError: pass else: legend_list["Pair not for locating"] = UnlocPair # ============================================================= # plot stations # stations = self.assoc_db.query(Pick.sta).filter(Pick.assoc_id==assoc_id).distinct().all() stations = sta_rainbow lon_STA = [] lat_STA = [] sta_STA = [] for index, sta in enumerate(stations): # the comma is needed lon, lat = self.tt_stations_db_1D.query( Station1D.longitude, Station1D.latitude).filter(Station1D.sta == sta).first() lon_STA.append(lon) lat_STA.append(lat) sta_STA.append(sta) x, y = m(lon_STA, lat_STA) m.scatter(x, y, marker='^', s=100, c=rainbow, zorder=3) for xi, yi, stai in zip(x, y, sta_STA): plt.text(xi, yi + 1, stai, fontweight='bold', ha='center', color='k') # ============================================================= # plot event location and uncertainty event = self.assoc_db.query(Associated).filter( Associated.id == assoc_id).first() t_create = event.t_create t_update = event.t_update ot = event.ot uncert = event.loc_uncert * 6371 * np.pi / 180. lon = event.longitude lat = event.latitude location = (lon, lat) x, y = m(lon, lat) m.scatter(x, y, marker='*', s=100, c='k', zorder=3) equi(m, lon, lat, uncert, color='k', lw=2.) # plt.title('Event %d at Origin Time: %s'%(event.id,ot), fontsize=18) plt.title('Event at Origin Time: %s' % (ot), fontsize=18) # add in the create and update time text # x_text,y_text=m(West+(East-West)*0.2,South+(North-South)*0.05) # plt.text(x_text,y_text,'Create Time: %s\nUpdate Time:%s'%(t_create,t_update),horizontalalignment='center',fontsize=12,fontweight='bold') # ============================================================= # plot single phases circles single_phases = self.assoc_db.query(PickModified).filter( PickModified.assoc_id == assoc_id).filter( PickModified.locate_flag == None).all() for single_phase in single_phases: lon, lat = self.tt_stations_db_1D.query( Station1D.longitude, Station1D.latitude).filter( Station1D.sta == single_phase.sta).first() x, y = m(lon, lat) pick_time = single_phase.time travel_time = (pick_time - ot).total_seconds() if single_phase.phase == 'P': tt, tt_uncert = self.distance_singlephase( single_phase.phase, travel_time) d_km = tt.d_km UnlocPhase, = equi(m, lon, lat, d_km, ls=':', lw=2., c='gray', zorder=4) m.scatter(x, y, marker='^', s=100, c='gray', zorder=5) plt.text(x, y + 1, single_phase.sta, fontweight='bold', ha='center') if single_phase.phase == 'S': tt, tt_uncert = self.distance_singlephase( single_phase.phase, travel_time) d_km = tt.d_km UnlocPhase, = equi(m, lon, lat, d_km, ls=':', lw=2., c='gray', zorder=4) m.scatter(x, y, marker='^', s=100, c='gray', zorder=5) plt.text(x, y + 1, single_phase.sta, fontweight='bold', ha='center') try: single_phase except NameError: pass else: legend_list["Single Phase"] = UnlocPhase # add on the legend # legend = plt.legend(legend_list.values(),legend_list.keys(),'upper left') # ============================================================= # plot residual distribution subpos = [0.05, 0.28, 0.35, 0.6] subax = add_subplot_axes(ax, subpos) Dist = self.tt_stations_db_1D.query(TTtable1D.d_km).all() SP_intv = self.tt_stations_db_1D.query(TTtable1D.s_p).all() S_P = [] D_S_P = [] for dist, in Dist: D_S_P.append(dist) for s_p, in SP_intv: S_P.append(s_p) subax.plot(D_S_P, S_P, 'k-', linewidth=2, zorder=1) for i in range(len(radius_rainbow)): subax.scatter(radius_rainbow[i], s_p_rainbow[i], s=50, color=rainbow[i], zorder=2) plt.xlim([0, 350]) plt.ylim([0, 40]) plt.xlabel('Distance (km)') plt.ylabel('S-P (s)') plt.show()
# Set universal figure margins width = 10 height = 8 plt.figure(t + 1) print 'Plotting', time_str plt.figure(figsize=(width, height)) """ plt.rc("figure.subplot", left = .001) #gets rid of white space in plot plt.rc("figure.subplot", right = .999) plt.rc("figure.subplot", bottom = .001) plt.rc("figure.subplot", top = .999) F = plt.gcf() # Gets the current figure """ m.drawstates(color='k', linewidth=1.25) #m.drawcoastlines(color='k') #m.drawcountries(color='k', linewidth=1.25) ###################################################### plt.contour(x, y, landmask, levels=[1]) plt.contourf(x, y, HGT, cmap=plt.get_cmap('binary')) #plt.pcolormesh(x,y,plume,cmap='PuOr', vmin=0,vmax=.01) plt.pcolormesh(x, y, plumeN_composite, cmap=cmapred, vmax=8, vmin=0) plt.pcolormesh(x, y, plumeS_composite, cmap=cmapblue, vmax=8, vmin=0) cbar_loc = plt.colorbar(shrink=.8, pad=.01, ticks=np.arange(0, 8, 1)) cbar_loc.ax.set_ylabel('Tracers [units of stuff]') plt.contour(x, y, landmask, [0, 1], linewidths=1, colors="k") #plt.contour(x,y,HGT)
# llcrnrlon=-180, urcrnrlon=180, ) # map=Basemap(projection='mill') map.readshapefile('D:/zzt/PyWorkSpace/CHN_adm_shp/CHN_adm1', 'states', drawbounds=True) # map.readshapefile('D:/PyWorkSpace/航海项目/CHN_adm_shp/CHN_adm1', 'states', drawbounds=True) # map.readshapefile('D:/PyWorkSpace/CHN_adm_shp/CHN_adm1', 'states', drawbounds=True) # map.readshapefile('D:/PyWorkSpace/航海项目/MYS_adm_shp/MYS_adm1', 'states', drawbounds=True,color='blue') # map.readshapefile('D:/PyWorkSpace/航海项目/SGP_adm_shp/SGP_adm1', 'states', drawbounds=True,color='red') # map.readshapefile('D:/PyWorkSpace/航海项目/IDN_adm_shp/IDN_adm1', 'states', drawbounds=True,color='blue') # map.readshapefile('D:/PyWorkSpace/航海项目/LKA_adm_shp/LKA_adm1', 'states', drawbounds=True,color='blue') # map.readshapefile('D:/PyWorkSpace/航海项目/IND_adm_shp/IND_adm1', 'states', drawbounds=True,color='blue') map.drawstates(linewidth=0.1, linestyle='solid', color='k', antialiased=1, ax=None, zorder=None) # map.drawcoastlines(linewidth=1.0, linestyle='solid', color='blue', antialiased=1, ax=None, zorder=None) map.drawcountries() map.drawmeridians(np.arange(0, 360, 30)) map.drawparallels(np.arange(-90, 90, 30)) map.fillcontinents(color='#BF9E30', lake_color='#689CD2', zorder=0) # map.fillcontinents(color='coral',lake_color='#689CD2',zorder=0) def mapshow(): ## filter v1 lon,lat in defined range # posi_fea = pd.read_csv(feature_filepath + suffix, header=None) # 添加判断条件
cs = (m.contourf(x, y, data, clevs, cmap=nice_cmap, extended='both')) (m.readshapefile('/home/Data/shapeFiles/uae/ARE_adm1', 'uae', drawbounds=True, zorder=None, linewidth=1.0, color='k', antialiased=1, ax=None, default_encoding='utf-8')) m.drawparallels(np.arange(20., 30., 5.), labels=[1, 0, 0, 0]) m.drawmeridians(np.arange(50., 60., 5.), 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_ticks([clevs]) #(cbar.set_label('m/s')) ; (plt.title('GSI V wind at model level ' + str(lev_1), fontsize=12, color='k')) savefig( '/home/vkvalappil/Data/modelWRF/GSI/gsiout/2016122006_hybrid_02/vwind/vwind_gsi_' + str(lev_1) + '.png', dpi=100) plt.close() ################################################################################################################################### fig = plt.figure(figsize=(8, 8), dpi=100) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) m = Basemap(projection='mill',
lon_0 = 134. lat_1 = percentile([llcrnrlat, urcrnrlat], 25) lat_2 = percentile([llcrnrlat, urcrnrlat], 75) # set map # Projection used for National Mapping m = Basemap(llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat, \ urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat, projection='lcc',lat_1=lat_1,lat_2=lat_2,lon_0=lon_0, resolution=res,area_thresh=2000.) #m.drawmapboundary(fill_color='lightgray') #m.fillcontinents(color='white',lake_color='lightgray',zorder=0) m.drawcoastlines(linewidth=0.5, color='k') m.drawcountries(color='0.2') m.drawstates(color='0.2') m.drawparallels(arange(-90., 90., 6), labels=[0, 0, 0, 0], fontsize=10, dashes=[2, 2], color='0.5', linewidth=0.5) m.drawmeridians(arange(0., 360., 6), labels=[0, 0, 0, 0], fontsize=10, dashes=[2, 2], color='0.5', linewidth=0.5) # get colormap from cpt file
cores = scipy.linspace(0, 2, num=5) CS = m.contourf(x, y, M, levels=cores, cmap=plt.cm.Blues) # Opções de formatação do mapa m.drawcoastlines() m.fillcontinents(color='coral', lake_color='aqua') m.drawparallels(np.arange(float(lat_sul), float(lat_norte), 0.5), labels=[1, 0, 0, 0], fmt='%g') m.drawmeridians(np.arange(float(lon_oeste), float(lon_leste), 0.5), labels=[0, 0, 0, 1]) m.drawcountries(linewidth=0.8, color='k', antialiased=1, ax=None, zorder=None) m.drawstates(linewidth=0.5, color='k', antialiased=1, ax=None, zorder=None) # m.drawrivers(linewidth=0.5, linestyle='solid', color='b', antialiased=1, ax=None, zorder=None) # Incluindo os vetores de corrente na figura # Q=m.quiver(x[::skip, ::skip], y[::skip, ::skip], uu[::skip, ::skip], vv[::skip, ::skip],\ Q=m.quiver(x, y, uu, vv,\ scale=2,units='inches',scale_units='inches',width=0.008,headlength=5,headwidth=3.5,headaxislength=5,\ pivot='tail',color='k',minshaft=2,minlength=1) # Incluindo ponto de interesse na figura A, B = m(plon1, plat1) m.plot(A, B, 'ko', markersize=10) plt.text(A, B, ' ' + pNome1 + '', ha='right', color='k') A, B = m(plon2, plat2) m.plot(A, B, 'ko', markersize=5) plt.text(A, B, ' ' + pNome2 + '', ha='right', color='k')
def geramapa(star, data, title, labelx, nameimg, mapstyle='1', resolution='l', centermap=None, lats=None, erro=None, ring=None, atm=None, clat=None, sitearq=None, fmt='png', dpi=100, mapsize=None): lon = star.ra - data.sidereal_time('mean', 'greenwich') center_map = EarthLocation(lon.value, star.dec.value) if not centermap == None: center_map = EarthLocation(centermap[0], centermap[1]) m = Basemap(projection='ortho', lat_0=center_map.latitude.value, lon_0=center_map.longitude.value, resolution=resolution) # m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.) # kx = fig.add_axes([-0.003,-0.001,1.006,1.002]) # kx.set_rasterization_zorder(1) m.nightshade(data.datetime, alpha=0.2, zorder=0.5) m.drawcoastlines(linewidth=0.5) m.drawcountries(linewidth=0.5) m.drawstates(linewidth=0.5) m.drawmeridians(np.arange(0, 360, 30)) m.drawparallels(np.arange(-90, 90, 30)) m.drawmapboundary() style = { '1': { 'ptcolor': 'red', 'lncolor': 'blue', 'ercolor': 'blue', 'rncolor': 'blue', 'atcolor': 'blue' }, '2': { 'ptcolor': 'red', 'lncolor': 'blue', 'ercolor': 'red', 'rncolor': 'black', 'atcolor': 'black' }, '3': { 'ptcolor': 'red', 'lncolor': 'blue', 'ercolor': 'red', 'rncolor': 'black', 'atcolor': 'black' }, '4': { 'ptcolor': 'red', 'lncolor': 'red', 'ercolor': 'red', 'rncolor': 'black', 'atcolor': 'black' }, '5': { 'ptcolor': 'red', 'lncolor': 'red', 'ercolor': 'red', 'rncolor': 'black', 'atcolor': 'black' } } if mapstyle == '2': m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='coral', lake_color='aqua') elif mapstyle == '3': m.shadedrelief() elif mapstyle == '4': m.bluemarble() elif mapstyle == '5': m.etopo() if not lats == None: xs, ys = m(lats[0], lats[1]) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, color=style[mapstyle]['lncolor']) xt, yt = m(lats[2], lats[3]) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, color=style[mapstyle]['lncolor']) if not erro == None: xs, ys = m(erro[0], erro[1]) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, '--', color=style[mapstyle]['ercolor']) xt, yt = m(erro[2], erro[3]) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, '--', color=style[mapstyle]['ercolor']) if not ring == None: xs, ys = m(ring[0], ring[1]) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, '--', color=style[mapstyle]['rncolor']) xt, yt = m(ring[2], ring[3]) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, '--', color=style[mapstyle]['rncolor']) if not atm == None: xs, ys = m(atm[0], atm[1]) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, color=style[mapstyle]['atcolor']) xt, yt = m(atm[2], atm[3]) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, color=style[mapstyle]['atcolor']) if not clat == None: xc, yc = m(clon, clat) labe = [lab[i] for i in np.arange(len(lab)) if xc[i] < 1e+30] xc = [i for i in xc if i < 1e+30] yc = [i for i in yc if i < 1e+30] m.plot(xc, yc, 'o', color=style[mapstyle]['ptcolor']) # m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46)) # m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46)) # m.plot(ax3.to(u.m), by3.to(u.m), color='red') # m.plot(ax4.to(u.m), by4.to(u.m), color='red') # m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005) # ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus) # by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus) # # labels = [i.iso.split()[1][0:8] for i in temposplot] # m.plot(ax2, by2, 'ro') # for label, axpt, bypt in zip(labe, xc, yc): # kx.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold') # if os.path.isfile(sitearq) == True: # xpt,ypt = m(sites['lon'],sites['lat']) # m.plot(xpt,ypt,'bo') # offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]] # for i in np.arange(len(xpt)): # ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold') # m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro)) # m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor) # plt.legend(fontsize=mapsize[0].value*21/46) fig = plt.gcf() fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value) plt.title(title, fontsize=mapsize[0].value * 25 / 46, fontproperties='FreeMono', weight='bold') plt.xlabel(labelx, fontsize=mapsize[0].value * 21 / 46, fontproperties='FreeMono', weight='bold') plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi) print 'Gerado: {}.{}'.format(nameimg, fmt) plt.clf()
) # adding an alpha channel will plot faster, according to stackoverflow. Not sure why. # Now we can plot the GOES data on the HRRR map domain and projection plt.figure(figsize=[10, 8]) # The values of R are ignored becuase we plot the color in colorTuple, but pcolormesh still needs its shape. newmap = mH.pcolormesh(lons, lats, R, color=colorTuple, linewidth=0, latlon=True) newmap.set_array( None ) # without this line the linewidth is set to zero, but the RGB colorTuple is ignored. I don't know why. mH.drawcoastlines(color='w') mH.drawcountries(color='w') mH.drawstates(color='w') plt.title('GOES-16 Fire Temperature', fontweight='semibold', fontsize=15) plt.title('%s' % dt.strftime('%H:%M UTC %d %B %Y'), loc='right') plt.show() # location of South Sugarloaf fire l = {'latitude': 41.812, 'longitude': -116.324} # Baltimore harbour #l = {'latitude': 39.2827513, # 'longitude':-76.6214623} # Buzzard fire #l = {'latitude': 33.724, # 'longitude': -108.538} mZ = Basemap( projection='lcc',
aClTime *= 365.25*24 # --> hr print('min time interval:',min(aClTime),'max time interval:' ,max(aClTime)) print('earthquakes within 72h:',len(aClTime)) # ================================================================================ # plot map # ================================================================================ fig = plt.figure() ax = plt.subplot() # set basemap mymap = Basemap(llcrnrlon=dPar['minlon'], llcrnrlat=dPar['minlat'], urcrnrlon=dPar['maxlon'], urcrnrlat=dPar['maxlat'], resolution='f') mymap.drawcoastlines(linewidth=0.25) mymap.drawcountries(linewidth=0.25) mymap.drawstates(linewidth=0.25) mymap.fillcontinents(color='none', lake_color='aqua') # plot faults data = np.loadtxt(fault_file) x = [] y = [] for plot in data: if plot[0] < 0: x.append(plot[0]) y.append(plot[1]) else: mymap.plot(x, y, marker='None', color='black', linewidth=.2) x = [] y = []
def plotGpsMapTrajectory(lat=[], lon=[], rx=None, labels=None, timelim=None, totalityc=[], totalityu=[], totalityd=[], latlim=[41, 44], ms=10, color='k', lonlim=[-74, -69], center=[42.36, -71.06], parallels=[42, 44], meridians=[-73, -70, -67], ax=None, m=None): """ """ if ax is None: (fig, ax) = plt.subplots(1, 1, facecolor='w') m = Basemap(llcrnrlat=latlim[0], urcrnrlat=latlim[1], llcrnrlon=lonlim[0], urcrnrlon=lonlim[1], projection='merc', resolution='i', ax=ax) m.drawparallels(parallels, labels=[False, True, True, True], linewidth=1) m.drawmeridians(meridians, labels=[True, True, False, True], linewidth=1) if len(totalityc) > 0: x, y = m(totalityc[1], totalityc[0]) m.plot(x, y, lw=2, color='r') if len(totalityu) > 0: x, y = m(totalityu[1], totalityu[0]) m.plot(x, y, lw=2, color='b') if len(totalityd) > 0: x, y = m(totalityd[1], totalityd[0]) m.plot(x, y, lw=2, color='b') if len(lat) > 0 and len(lon) > 0: for i in range(len(lat)): idx = np.where(np.isfinite(lon[i]))[0] x, y = m(lon[i][idx], lat[i][idx]) if labels is not None: m.plot(x, y, lw=2, label='sv' + str(labels[i])) else: m.plot(x, y, lw=2) if (rx is not None) and isinstance(rx, np.ndarray): if len(rx.shape) > 1: for i in range(rx.shape[1]): x, y = m(rx[1][i], rx[0][i]) m.scatter(x, y, marker='o', color=color, s=ms) else: x, y = m(rx[1], rx[0]) m.scatter(x, y, marker='o', color=color, s=ms) m.drawcoastlines() m.drawstates() else: if len(lat) > 0 and len(lon) > 0: for i in range(len(lat)): idx = np.where(np.isfinite(lon[i]))[0] x, y = m(lon[i][idx], lat[i][idx]) if labels is not None: m.plot(x, y, lw=2, label='sv' + str(labels[i])) else: m.plot(x, y, lw=2) if (rx is not None) and isinstance(rx, np.ndarray): if len(rx.shape) > 1: for i in range(rx.shape[1]): x, y = m(rx[1][i], rx[0][i]) m.scatter(x, y, marker='o', color=color, s=ms) else: x, y = m(rx[1], rx[0]) m.scatter(x, y, marker='o', color=color, s=ms) return ax, m
def makeNearestNeighborsDensityPlot(filename, col_of_interest=None, title_string=None, min_lat=15, max_lat=50, min_lon=-130, max_lon=-65, maskOffWater=True, cmap='bwr', color_min=None, color_max=None, n_neighbors=20, res=.2, weights=lambda x: np.exp(-(x**2) / 3**2)): """ Makes a map of the density of events. Red = higher density, blue = lower density. filename: the name of the file that contains the data. See sample_data.csv for an example. Should contain at least two columns: lat (latitude) and lon (longitude). col_of_interest: If None, uses kernel density estimation to just plot the overall density of events. If not None, col_of_interest should be a column that contains 0s and 1s, where 1 denotes events of interest and 0 denotes background events; then uses k-nearest neighbors to estimate the fraction of events which are 1s. title_string: The title for the map. min_lat, max_lat, min_long, max_long: the boundaries of the map, in degrees. Negative longitudes = west; negative latitudes = south. By default set to borders of North America. maskOffWater: if True, does not map for water. True by default. cmap: the name of the colormap to use. See http://matplotlib.org/examples/color/colormaps_reference.html for list of options. color_min, color_max: which densities are mapped to the maximum and minimum colors. For k-nearest neighbors, set to 0 and 1 by default; for kernel density estimation, set to 0 and the maximum density estimate by default. May have to play with these to get informative maps. n_neighbors: for k-nearest neighbors, the number of neighbors to use to compute densities. Try increasing if the map is very spiky. res: how high-resolution the map is. Lower numbers = HIGHER resolution (but will take longer to make.) weights: for k-nearest neighbors, how to weight the points as a function of distance. By default uses a Gaussian kernel. Don't play with this unless you know what you're doing. """ d = pd.read_csv(filename) if not (('lat' in d.columns) and ('lon' in d.columns)): raise Exception('Error: dataset must contain lat and lon') if (col_of_interest is not None) and (col_of_interest not in d.columns): raise Exception('Error: dataset must contain column labeled %s' % col_of_interest) if not set(d[col_of_interest]) == set([0, 1]): raise Exception("Error: column %s must contain 0s and 1s" % col_of_interest) #Filter for events with locations. geolocated = d.dropna(subset=['lat', 'lon']) idxs = (geolocated['lat'] > min_lat) & (geolocated['lat'] < max_lat) idxs = idxs & (geolocated['lon'] > min_lon) & (geolocated['lon'] < max_lon) geolocated = geolocated.loc[idxs] #Fit the appropriate model: k-nearest neighbors if col_of_interest is not None, otherwise Kernel Density Estimation. if col_of_interest is not None: model = KNeighborsClassifier(n_neighbors=n_neighbors, weights=weights) print 'Total number of points', len( geolocated ), 'in column of interest nonzero', geolocated[col_of_interest].sum() model.fit(geolocated[['lat', 'lon']], geolocated[col_of_interest]) else: print 'Total number of points', len(geolocated) model = KernelDensity(kernel='gaussian', bandwidth=3).fit(geolocated[['lat', 'lon']]) #Create a grid of points at which to predict. x = np.arange(min_lat, max_lat, res) y = np.arange(min_lon, max_lon, res) X, Y = meshgrid(x, y) numel = len(X) * len(X[0, :]) Z = np.zeros(X.shape) unraveled_x = X.reshape([numel, 1]) unraveled_y = Y.reshape([numel, 1]) data_to_eval = np.hstack([unraveled_x, unraveled_y]) #Make predictions using appropriate model. if col_of_interest is not None: density = model.predict_proba(data_to_eval)[:, 1] if color_min is None: color_min = 0 if color_max is None: color_max = 1 else: density = np.exp(model.score_samples(data_to_eval)) if color_min is None: color_min = 0 if color_max is None: color_max = density.max() #Make map. figure(figsize=[20, 10]) m = Basemap(llcrnrlat=min_lat, urcrnrlat=max_lat, llcrnrlon=min_lon, urcrnrlon=max_lon, resolution='l', fix_aspect=False) if maskOffWater: m.drawcoastlines() x, y = m(data_to_eval[:, 1], data_to_eval[:, 0]) loc = np.c_[x, y] polys = [p.boundary for p in m.landpolygons] on_land = points_in_polys(loc, polys) density[~on_land] = (color_min + color_max) / 2 density = density.reshape(X.shape) contourf(Y, X, density, levels=np.linspace(color_min, color_max, 25)) m.drawcoastlines(linewidth=2) m.drawcountries(linewidth=2) m.drawstates(linewidth=2) colorbar() set_cmap(cmap) if title_string is not None: title(title_string, fontsize=30, fontweight='bold') savefig('%s' % title_string, dpi=300, format='png') else: savefig('plot.png', dpi=300, format='png') show()