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 make_stations(network,latmin,latmax,lonmin,lonmax,dlat,dlon,plot=True,**kwargs): head = kwargs.get('head','RM') elev = kwargs.get('elev',0) dep = kwargs.get('dep',0) lats = np.arange(latmin,latmax+dlat,dlat) lons = np.arange(lonmin,lonmax+dlon,dlon) lats_pts,lons_pts = np.meshgrid(lats,lons) if plot: m = Basemap(projection='hammer',lon_0=0,resolution='l') m.drawcoastlines() m.drawmeridians(np.arange(0,351,10)) m.drawparallels(np.arange(-80,81,10)) lons_pts2,lats_pts2 = m(lons_pts,lats_pts) m.scatter(lons_pts2,lats_pts2) plt.show() f = open('STATIONS','w') print 'total number of stations : ',len(lats_pts) st = 1 for i in range(0,len(lats)): for j in range(0,len(lons)): f.write('{}{:04d} {} {:5.2f} {:5.2f} {:5.2f} {:5.2f}'.format(head,st,network,lats[i],lons[j],elev,dep)+'\n') st += 1
def plot(text, size): from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # setup Lambert Conformal basemap. m = Basemap(width=3000000,height=3000000,projection='lcc', resolution='c',lat_0=18,lon_0=78) m.drawcoastlines() #m.fillcontinents(color='coral',lake_color='aqua') m.shadedrelief() colors = numpy.random.rand(30,3) lat = [17.38,13.08,12.98,19.07,22.57,26.84,26.91,28.63] lon = [78.49,80.28,77.61,72.88,88.34,80.95,75.78,77.25] df_x = [0.5,0,0.5] df_y = [-0.5,0,-0.5] f_lat = [] f_lon = [] f_size = [] f_color = [] for place_id in range(len(lat)): for i in range(3): f_lat.append(lat[place_id] + df_y[i]) f_lon.append(lon[place_id] + df_x[i]) f_size.append(size[place_id][i]*500) f_color.append(colors[text[place_id][i]]) #m.plot(lon[place_id]+df_y[i],lat[place_id]+ df_x[i], 'bo',markersize = size[place_id][i], latlon = True) m.scatter(f_lon, f_lat, s = f_size, c = f_color, alpha = 0.5, latlon = True) m.scatter(lon, lat, s = 8000, c = 'b', alpha = 0.2, latlon = True) #m.scatter(f_lon, f_lat, s = f_size, c = f_color, latlon = True) #m.plot(f_lon,f_lat,'bo',markersize = 5, latlon = True) plt.show()
def GDELT_maplot(self, point_counts, centro_lat, centro_lon, llat, llon, ulat, ulon): #,centro_lat,centro_lon,llat,llon,ulat,ulon): # print point_counts # print centro_lat, centro_lon, llat, llon, ulat, ulon def get_size(count): ''' Convert a count to a point size. Log-scaled.''' scale_factor = 2 return np.log10(count + 1) * scale_factor # Note that we're drawing on a regular matplotlib figure, so we set the # figure size just like we would any other. plt.figure(figsize=(10, 10)) # Create the Basemap event_map = Basemap(projection='merc', resolution='l', area_thresh=1000.0, # Low resolution lat_0= centro_lat, lon_0=centro_lon, # Map center llcrnrlon=llon, llcrnrlat=llat, # Lower left corner urcrnrlon=ulon, urcrnrlat=ulat) # Upper right corner # Draw important features event_map.drawcoastlines() event_map.drawcountries() event_map.fillcontinents(color='0.8') # Light gray event_map.drawmapboundary() # Draw the points on the map: for point, count in point_counts.iteritems(): x, y = event_map(point[1], point[0]) # Convert lat, long to y,x # print x , y marker_size = get_size(count) event_map.plot(x, y, 'ro', markersize=marker_size, alpha=0.3) plt.show()
def Map(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 el_plot(data, Map=False, show=True): """ Plot the elevation for the region from the last time series :Parameters: **data** -- the standard python data dictionary **Map** -- {True, False} (optional): Optional argument. If True, the elevation will be plotted on a map. """ trigrid = data['trigrid'] plt.gca().set_aspect('equal') plt.tripcolor(trigrid, data['zeta'][-1,:]) plt.colorbar() plt.title("Elevation") if Map: #we set the corners of where the map should show up llcrnrlon, urcrnrlon = plt.xlim() llcrnrlat, urcrnrlat = plt.ylim() #we construct the map. Note that resolution serves to increase #or decrease the detail in the coastline. Currently set to #'i' for 'intermediate' m = Basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, \ resolution='i', suppress_ticks=False) #set color for continents. Default is grey. m.fillcontinents(color='ForestGreen') m.drawmapboundary() m.drawcoastlines() if show: plt.show()
def test_plot_map_vels(xml): track = GPX(xml) vels = track.calculate_vels(smooth_vels=True) lllat, lllon = min(track.lat) - 0.01, min(track.lon) - 0.01 urlat, urlon = max(track.lat) + 0.01, max(track.lon) + 0.01 # find the centre point lat_0 = (urlat - lllat) / 2 + lllat lon_0 = (urlon - lllon) / 2 + lllon # FIXME: rsphere required because my Proj is screwy m = Basemap(projection='cyl', llcrnrlon=lllon, llcrnrlat=lllat, urcrnrlon=urlon, urcrnrlat=urlat, lat_0=lat_0, lon_0=lon_0, resolution='h') # rsphere=(6378137.00, 6356752.3142)) x, y = m(vels.lon, vels.lat) m.drawcoastlines() m.drawrivers() m.barbs(x, y, vels.u, vels.v) #, vels.anom, cmap=plt.get_cmap('RdBu_r')) plt.show()
def mapMake(self,renderdpi,table,msize): cn = 0 start = time() #initialize connection to database cn = psycopg2.connect(secret.DB_CONNECT) cr = cn.cursor() #get map ready to go fig = plt.figure(figsize=(8,4),dpi = renderdpi) fig.add_subplot(1,1,1) m = Basemap(projection='merc',llcrnrlat=-60,urcrnrlat=75,\ llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='i') m.drawcoastlines(linewidth=.05) m.drawcountries(linewidth=.05) photoCnt = 0 points = [] cr.execute('SELECT latitude,longitude FROM %s;' % table) for row in cr.fetchall(): x,y = m(row[1],row[0])#convert to merc projection coords points.append((x,y)) photoCnt += 1 xs,ys = zip(*points) plt.title("%d %s" % (photoCnt,table)) plt.scatter(xs,ys,s=msize,marker='.',c='green',edgecolors='none') plt.savefig(table,dpi = renderdpi) print "{:d} {:s} mapped in {:f} seconds".format(photoCnt,\ table,time()-start)
def 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 mapTut(): m = Basemap(projection='mill',llcrnrlat=20,urcrnrlat=50,\ llcrnrlon=-130,urcrnrlon=-60,resolution='c') m.drawcoastlines() m.drawcountries() m.drawstates() m.fillcontinents(color='#04BAE3',lake_color='#FFFFFF') m.drawmapboundary(fill_color='#FFFFFF') # Houston, Texas lat,lon = 29.7630556,-95.3630556 x,y = m(lon,lat) m.plot(x,y, 'ro') lon, lat = -104.237, 40.125 # Location of Boulder xpt,ypt = m(lon,lat) m.plot(xpt,ypt, 'go') plt.title("Geo Plotting") plt.show()
def draw_latlon(llclat, urclat, llclon, urclon, rsphere=6371200, resolution='h', area_thresh=0.1, projection='merc'): m = Basemap(llcrnrlat=llclat, urcrnrlat=urclat, llcrnrlon=llclon, urcrnrlon=urclon, rsphere=rsphere, resolution=resolution, area_thresh=area_thresh, projection=projection) m.drawcoastlines() m.drawcountries()
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 plot_drainage_areas(path = "data/hydrosheds/test_using_splitting_amno.nc"): ds = Dataset(path) #basemap = polar_stereographic.basemap basemap = Basemap() lons = ds.variables["lon"][:] lats = ds.variables["lat"][:] channel_slope = ds.variables["slope"][:] lons[lons < 0] += 360 x, y = basemap(lons, lats) acc_area = ds.variables["accumulation_area"][:] acc_area = np.log(acc_area) acc_area = np.ma.masked_where(channel_slope < 0, acc_area) basemap.pcolormesh(x, y, acc_area) basemap.drawcoastlines() plt.colorbar() plt.xlim(x.min(), x.max()) plt.ylim(y.min(), y.max()) plt.show()
def contourMap(grdROMS, tlon, tlat, mydata1, mydata2, mydata3, var, mytype, currentdate): plt.figure(figsize=(10,10), frameon=False) map = Basemap(lon_0=25,boundinglat=50, resolution='l',area_thresh=100.,projection='npstere') x, y = list(map(tlon,tlat)) map.drawcoastlines() map.fillcontinents(color='grey') map.drawcountries() if var=='wind': levels = np.arange(np.min(mydata3),np.max(mydata3),0.1) CS1 = map.contourf(x, y, mydata3, levels, cmap=cm.get_cmap('RdYlBu_r',len(levels)-1) )#,alpha=0.5) plt.colorbar(CS1, orientation='vertical', extend='both', shrink=0.5) if mytype=="REGSCEN": step=8 else: step=1 map.quiver(x[0:-1:step,0:-1:step],y[0:-1:step,0:-1:step], mydata1[0:-1:step,0:-1:step],mydata2[0:-1:step,0:-1:step], scale=400) # plt.title('Var:%s - depth:%s - time:%s'%(var,grdROMS.time)) plotfile='figures/'+str(var)+'_'+str(mytype)+'_time_'+str(currentdate)+'.png' if not os.path.exists('figures'): os.makedirs('figure') plt.savefig(plotfile) print("Saved figure: %s"%(plotfile))
def individual_ocean_map(eof = '1', phase = 'lanina', showplot = True): ### This function combines several others to make a map patterns, lats, lons, lams, pcs = combine_regions(phase = phase) data, lns, lts = create_full_map_individual(patterns, lats, lons, eof = eof) from numpy import linspace fig = plt.figure() ax = fig.add_subplot(111) m = Basemap(ax = ax, projection = 'robin', lon_0 = 180, resolution = 'i') m.drawmapboundary(fill_color='aqua') m.drawcoastlines(linewidth = 0.25) m.drawcountries() m.fillcontinents(color='green',lake_color='aqua') parallels = np.linspace(m.llcrnrlat, m.urcrnrlat, 4) meridians = np.linspace(m.llcrnrlon, m.urcrnrlon, 4) m.drawparallels(parallels, linewidth = 1, labels = [0,0,0,0]) m.drawmeridians(meridians, linewidth = 1, labels = [0,0,0,0]) cmap = cm.RdBu_r im = m.pcolormesh(lns,lts,data, vmin = data[~isnan(data)].min(), \ vmax=data[~isnan(data)].max(), cmap = cmap, latlon=True) cb = m.colorbar(im,'bottom', size="5%", pad="2%") if showplot: plt.show() return return fig, ax, m
def plot_world_sst(): # Read some NetCDF data import netCDF4 as nc ostia = nc.Dataset('ostia.nc') tmp = ostia.variables['analysed_sst'][0] ice = ostia.variables['sea_ice_fraction'][0] lon = ostia.variables['lon'][:] lat = ostia.variables['lat'][:] from mpl_toolkits.basemap import Basemap # Set up a map map = Basemap(projection='cyl') map.drawcoastlines() map.drawcountries() map.fillcontinents(color='lightgreen', lake_color='lightblue'); map.drawmapboundary(fill_color='lightblue') # Re-project the data onto the map image = map.transform_scalar(tmp,lon,lat,200,200) # Plot the data map.imshow(image); plt.show()
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 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_interiorAK( width=1800000, height=1200000, water='lightskyblue', earth='snow', resolution='i'): """ Albers Equal Area map of interior Alaska, with some overridable presets. """ bmap = Basemap( width=width, height=height, resolution=resolution, projection='aea', lat_1=55., lat_2=75., lat_0=65., lon_0=-150.) bmap.drawcoastlines() bmap.drawrivers(color=water) bmap.drawcountries() bmap.fillcontinents(lake_color=water, color=earth) # labels = [left,right,top,bottom] bmap.drawmeridians( np.arange(-180, 180, 10), labels=[False, False, False, 1]) bmap.drawparallels( np.arange(0, 80, 5), labels=[1, 1, False, False]) bmap.drawmapboundary(fill_color=water) return bmap
def sstMap(nipaPhase, phase = 'allyears', field = 'sst', fig = None, ax = None, monte = False): from numpy import linspace if fig == None: fig = plt.figure() ax = fig.add_subplot(111) m = Basemap(ax = ax, projection = 'robin', lon_0 = 270, resolution = 'i') m.drawmapboundary(fill_color='aqua') m.drawcoastlines(linewidth = 0.25) m.drawcountries() m.fillcontinents(color='green',lake_color='aqua') parallels = np.linspace(m.llcrnrlat, m.urcrnrlat, 4) meridians = np.linspace(m.llcrnrlon, m.urcrnrlon, 4) m.drawparallels(parallels, linewidth = 1, labels = [0,0,0,0]) m.drawmeridians(meridians, linewidth = 1, labels = [0,0,0,0]) lons = nipaPhase.lon[field] lats = nipaPhase.lat[field] if monte: data = nipaPhase.monte_grid[phase] levels = linspace(0, data.max(), data.max()) cmap = cm.Reds else: data = nipaPhase.corr_grid[field][phase] levels = linspace(-0.8,0.8,9) cmap = cm.RdBu lons, lats = np.meshgrid(lons,lats) im1 = m.pcolormesh(lons,lats,data, vmin = np.min(levels), \ vmax=np.max(levels), cmap = cmap, latlon=True) cb = m.colorbar(im1,'bottom', size="5%", pad="2%") ax.set_title('%s, %s' % (phase, field)) return fig, ax, m
def regional_subplot(lons, lats, data, extreme, cent_lat, cent_lon, min_lon, max_lon, min_lat, max_lat, parallels, meridians, cmap, vmin, title, plot_number, coastline_color, background_color): ax = plt.subplot(plot_number) ax.set_axis_bgcolor(background_color) ETA_m = haversine_distance((min_lat, cent_lon), (max_lat, cent_lon), True) XI_m = haversine_distance((min_lat, min_lon), (max_lat, max_lon),True) map = Basemap(height=ETA_m, width=XI_m, resolution='l', area_thresh=1000., projection='omerc', \ lon_0=cent_lon, lat_0=cent_lat, lon_2=cent_lon, lat_2=min_lat, lon_1=cent_lon, lat_1=max_lat) map.drawcoastlines(color=coastline_color) # labels = [left,right,top,bottom] map.drawparallels(parallels, labels=[True, False, False, False]) map.drawmeridians(meridians, labels=[False, False, False, True]) cs = map.contourf(lons, lats, data, levels=numpy.linspace((-1 * extreme), extreme, 101), cmap=cmap, vmin=vmin, vmax=extreme, extend='both', latlon=True) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="2%", pad=0.05) plt.colorbar(cs, cax=cax, ticks=[-1 * extreme, 0, extreme], extend='both') ax.set_title(title) return ax
def plot_sites_by_characteristic(dataframe, lat_col, long_col, title=None, char_column=None, bins=None, dataframe2=None, lat_col2=None, long_col2=None): map = Basemap(projection='merc',llcrnrlat=23.5,urcrnrlat=57, llcrnrlon=-140,urcrnrlon=-50,lat_ts=20,resolution='l') map.drawcoastlines(linewidth = 1.25) plt.title(title) if not char_column: lats = dataframe[lat_col] longs = dataframe[long_col] x,y = map(longs.values,lats.values) map.plot(x, y, ls='', marker='o', markersize=4) if char_column: blues = sns.color_palette("Blues", n_colors=bins) dataframe['quantile'] = pd.qcut(dataframe[char_column], bins) grouped = dataframe.groupby('quantile') i= -1 for groupname, groupdata, in grouped: i = i + 1 colors = blues[i] lats = groupdata["lat"] longs = groupdata["long"] x,y = map(longs.values,lats.values) map.plot(x, y, ls='', marker='o', color=colors, markersize=4) plt.hold(True) if lat_col2: lats = dataframe2[lat_col2] longs = dataframe2[long_col2] x,y = map(longs.values,lats.values) map.plot(x, y, ls='', marker='o', markersize=4, color='brown')
def plot_map(lons, lats, c, legend_label, projection='mill', llcrnrlat=-80, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='i'): ''' Optional Arguments: projection - map projection, default set as 'mill' llcrnrlat - lower left corner latitude value, default is -80 urcrnrlat - upper right corner latitude value, default is 90 llcrnrlon - lower left corner longitude value, default is -180 urcrnrlon - upper right corner longitude value, default is 180 resolution - the resolution of the plot, default is 'i' Required Arguments: lons - list of longitude values to be plotted lats - list of latitude values to be plotted c - the color of the points to be plotted legend_label - how this set of points will be labeled on the legend Returns: m - a basemap object defined by input bounds with input points included ''' # Creates a basic plot of a series of lat,lon points over a defined region m = Basemap(projection=projection, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution=resolution) m.drawcoastlines() m.drawmapboundary() m.drawcountries() m.etopo() m.drawmeridians(np.arange(llcrnrlon, urcrnrlon, 5), labels=[0,0,0,1], fontsize=10) m.drawparallels(np.arange(llcrnrlat, urcrnrlat, 5), labels=[1,0,0,0], fontsize=10) x,y = m(lons, lats) m.scatter(x, y, color=c, label=legend_label, marker='o', edgecolor='none', s=10) return m
def mapper(image): fig = plt.figure() cmap = mpc.ListedColormap(palettable.colorbrewer.diverging.PiYG_5.mpl_colors) # cmap.set_bad('grey',1.) # ax = fig.add_subplot(1) plt.plot() plt.title("a. ((maxNDVI/mm AcuPrecip)/year)", loc= 'left') #set the spatial cordinates of the grid, mask the ocean and draw coastlines map = Basemap(llcrnrlon=112.0,llcrnrlat=-44.5,urcrnrlon=156.25,urcrnrlat=-10, resolution = 'h', epsg=4326) map.drawmapboundary(fill_color='grey') map.fillcontinents(color= 'none', lake_color='white') map.drawlsmask(land_color='none', ) map.drawcoastlines() map.imshow(np.flipud(image), cmap=cmap, vmin=-0.006, vmax=0.009,) # cb = plt.colorbar() #Tweaking the colorbar so the the ticks allign with the grid. cb = map.colorbar()#ticks= [-0.01, -0.0075, -0.0050, -0.00250, 0.0000, 0.0025, 0.0050, 0.0075, 0.010, 0.0125]) tick_locator = ticker.MaxNLocator(nbins=5) cb.locator = tick_locator cb.update_ticks() #add in the grid map.drawparallels(np.arange(-50, -10, 10),labels=[1,0,0,0], dashes=[1,2])#color= 'none') map.drawmeridians(np.arange(110, 156.25, 10),labels=[0,0,0,1], dashes=[1,2]) plt.show()
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 Map_plot_subregion(subregions, ref_dataset, directory): lons, lats = np.meshgrid(ref_dataset.lons, ref_dataset.lats) fig = plt.figure() ax = fig.add_subplot(111) m = Basemap( ax=ax, projection='cyl', llcrnrlat=lats.min(), urcrnrlat=lats.max(), llcrnrlon=lons.min(), urcrnrlon=lons.max(), resolution='l') m.drawcoastlines(linewidth=0.75) m.drawcountries(linewidth=0.75) m.etopo() x, y = m(lons, lats) #subregion_array = ma.masked_equal(subregion_array, 0) #max=m.contourf(x, y, subregion_array, alpha=0.7, cmap='Accent') for subregion in subregions: draw_screen_poly(subregion[1], m, 'w') plt.annotate( subregion[0], xy=(0.5 * (subregion[1][2] + subregion[1][3]), 0.5 * (subregion[1][0] + subregion[1][1])), ha='center', va='center', fontsize=8) fig.savefig(directory + 'map_subregion', bbox_inches='tight')
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 map_trace(tr,ax='None',showpath=True,showplot=True,Lat_0=0.0,Lon_0=60.0): from mpl_toolkits.basemap import Basemap if ax == 'None': m = Basemap(projection='ortho',lat_0=Lat_0,lon_0=Lon_0,resolution='l') m.drawmapboundary() m.drawcoastlines() m.fillcontinents(color='gray',lake_color='white') else: m = ax x1,y1 = m(tr.stats.sac['evlo'],tr.stats.sac['evla']) x2,y2 = m(tr.stats.sac['stlo'],tr.stats.sac['stla']) m.scatter(x1,y1,s=200.0,marker='*',facecolors='y',edgecolors='k',zorder=99) m.scatter(x2,y2,s=20.0,marker='^',color='b',zorder=99) if showpath == True: m.drawgreatcircle(tr.stats.sac['evlo'],tr.stats.sac['evla'], tr.stats.sac['stlo'],tr.stats.sac['stla'], linewidth=1,color='k',alpha=0.5) if showplot == True: plt.show() else: return m
def displayWindMapPlot(vdata,udata, lons, lats,): """ TODO add a docstring! """ #plt.clf() #pc = plt.contourf(lons, lats, data, 20) #plt.colorbar(pc, orientation='horizontal') #plt.title(title) #plt.xlabel("longitude (degrees east)") #plt.ylabel("latitude (degrees north)") #plt.show() fig, ax = plt.subplots() # Do the plot code # make orthographic basemap. m = Basemap(projection='cyl',llcrnrlat=-40,urcrnrlat=0,\ llcrnrlon=-20,urcrnrlon=60,resolution='l') X,Y=np.meshgrid(lons, lats) x,y=m(X,Y) #Convert to map coordinates #m.barbs(x,y,vdata,udata,20) m.quiver(x,y,vdata,udata,10) plt.streamplot(x,y,vdata,udata,10) #plt.colorbar(pc,orientation='horizontal') m.drawmapboundary() m.drawcountries() m.drawcoastlines(linewidth=1.5) fig.savefig('myimage.svg', format='svg', dpi=1200) plt.show() #m.drawparallels(parallels) #m.drawmeridians(meridians) """ Contains code for displaying data """
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 run(FILE_NAME): # Identify the data field. DATAFIELD_NAME = 'High_res_cloud' if USE_GDAL: import gdal import mpl_toolkits.basemap.pyproj as pyproj GRID_NAME = 'GlobalGrid' gname = 'HDF4_EOS:EOS_GRID:"{0}":{1}:{2}'.format( FILE_NAME, GRID_NAME, DATAFIELD_NAME) gdset = gdal.Open(gname) data = gdset.ReadAsArray().astype(np.float64) # Construct the grid. The projection is GEO, so this immediately # gives us latitude and longitude. meta = gdset.GetMetadata() x0, xinc, _, y0, _, yinc = gdset.GetGeoTransform() nx, ny = (gdset.RasterXSize, gdset.RasterYSize) x = np.linspace(x0, x0 + xinc * nx, nx) y = np.linspace(y0, y0 + yinc * ny, ny) longitude, latitude = np.meshgrid(x, y) scale_factor = float(meta['Scale']) units = meta['Unit'] del gdset else: from pyhdf.SD import SD, SDC hdf = SD(FILE_NAME, SDC.READ) # Read dataset. data2D = hdf.select(DATAFIELD_NAME) data = data2D[:, :].astype(np.float64) # Retrieve attributes. attrs = data2D.attributes(full=1) sfa = attrs["Scale"] scale_factor = sfa[0] ua = attrs["Unit"] units = ua[0] # Read global attribute. fattrs = hdf.attributes(full=1) ga = fattrs["StructMetadata.0"] gridmeta = ga[0] # Construct the grid. The needed information is in a global attribute # called 'StructMetadata.0'. Use regular expressions to tease out the # extents of the grid. In addition, the grid is in packed decimal # degrees, so we need to normalize to degrees. ul_regex = re.compile( r'''UpperLeftPointMtrs=\( (?P<upper_left_x>[+-]?\d+\.\d+) , (?P<upper_left_y>[+-]?\d+\.\d+) \)''', re.VERBOSE) match = ul_regex.search(gridmeta) x0 = np.float(match.group('upper_left_x')) / 1e6 y0 = np.float(match.group('upper_left_y')) / 1e6 lr_regex = re.compile( r'''LowerRightMtrs=\( (?P<lower_right_x>[+-]?\d+\.\d+) , (?P<lower_right_y>[+-]?\d+\.\d+) \)''', re.VERBOSE) match = lr_regex.search(gridmeta) x1 = np.float(match.group('lower_right_x')) / 1e6 y1 = np.float(match.group('lower_right_y')) / 1e6 ny, nx = data.shape x = np.linspace(x0, x1, nx) y = np.linspace(y0, y1, ny) longitude, latitude = np.meshgrid(x, y) # Apply the attributes information. data[data == -9999] = np.nan data = data * scale_factor data = np.ma.masked_array(data, np.isnan(data)) long_name = DATAFIELD_NAME.replace('_', ' ') m = Basemap(projection='cyl', resolution='l', lon_0=0, llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(-90, 91, 45), labels=[1, 0, 0, 0]) m.drawmeridians(np.arange(-180, 181, 45), labels=[0, 0, 0, 1]) m.pcolormesh(longitude, latitude, data, latlon=True) cb = m.colorbar() cb.set_label(units) basename = os.path.basename(FILE_NAME) plt.title('{0}\n{1}'.format(basename, long_name)) fig = plt.gcf() # plt.show() pngfile = "{0}.py.png".format(basename) fig.savefig(pngfile)
inp2.close() cetesb_st = pd.DataFrame({ 'name': ['PIN', 'PDP', 'CC', 'JUND'], 'lat': [-23.5611, -23.5445, -23.5531, -23.1916], 'lon': [-46.7016, -46.6294, -46.6723, -46.8967] }) plt.subplot(111) m = Basemap(llcrnrlon=xlon1.min(), llcrnrlat=xlat1.min(), urcrnrlon=xlon1.max(), urcrnrlat=xlat1.max(), projection='merc', resolution='h') m.drawcoastlines() m.drawstates() m.drawcountries() m.drawparallels(np.arange(-90., 90., 0.5), linewidth=0.01, labels=[1, 0, 0, 0], fontsize=10) m.drawmeridians(np.arange(-180., 180., 1.25), linewidth=0.01, labels=[0, 0, 0, 1], fontsize=10) x, y = m(cetesb_st['lon'].values, cetesb_st['lat'].values) m.scatter(x, y, marker='o', color='tab:orange', s=40) m.readshapefile('rmsp/MunRM07', 'MunRM07') plt.show()
%matplotlib inline rcParams['figure.figsize'] = (14,10) llon=-140 ulon=-50 llat=40 ulat=65 pdf = pdf[(pdf['Long'] > llon) & (pdf['Long'] < ulon) & (pdf['Lat'] > llat) &(pdf['Lat'] < ulat)] my_map = Basemap(projection='merc', resolution = 'l', area_thresh = 1000.0, llcrnrlon=llon, llcrnrlat=llat, #min longitude (llcrnrlon) and latitude (llcrnrlat) urcrnrlon=ulon, urcrnrlat=ulat) #max longitude (urcrnrlon) and latitude (urcrnrlat) my_map.drawcoastlines() my_map.drawcountries() # my_map.drawmapboundary() my_map.fillcontinents(color = 'white', alpha = 0.3) my_map.shadedrelief() # To collect data based on stations xs,ys = my_map(np.asarray(pdf.Long), np.asarray(pdf.Lat)) pdf['xm']= xs.tolist() pdf['ym'] =ys.tolist() #Visualization1 for index,row in pdf.iterrows(): # x,y = my_map(row.Long, row.Lat) my_map.plot(row.xm, row.ym,markerfacecolor =([1,0,0]), marker='o', markersize= 5, alpha = 0.75)
map = Basemap(projection='merc', llcrnrlon=latlon[0], llcrnrlat=latlon[1], urcrnrlon=latlon[2], urcrnrlat=latlon[3], resolution='i') x, y = map(lons_prism, lats_prism) #precip_ncar = maskoceans(lons_prism, lats_prism, precip_ncar) #map.drawlsmask(land_color=(0, 0, 0, 0), ocean_color='deeppink', lakes=False) csAVG = map.contourf(x, y, totalprecip_arw, levels, cmap=cmap, norm=matplotlib.colors.BoundaryNorm(levels, cmap.N)) map.drawcoastlines(linewidth=.5) map.drawstates() map.drawcountries() cbar = map.colorbar(csAVG, location='bottom', pad="5%") cbar.ax.tick_params(labelsize=12) plt.title('nam', fontsize=18) #cbar.ax.set_xlabel('Mean Daily Precipitation from Oct. 2015 to Mar. 2016 (mm)', fontsize = 10) ######################## prism ############################################# ax = fig.add_subplot(232) map = Basemap(projection='merc', llcrnrlon=latlon[0], llcrnrlat=latlon[1], urcrnrlon=latlon[2], urcrnrlat=latlon[3],
cetesb_st = pd.DataFrame({ 'name': ['PIN', 'PDP', 'CC', 'JUND'], 'lat': [-23.5611, -23.5445, -23.5531, -23.1916], 'lon': [-46.7016, -46.6294, -46.6723, -46.8967] }) fig = plt.figure(figsize=(15, 8)) ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (1, 0)) ax3 = plt.subplot2grid((2, 2), (0, 1), rowspan=2) m1 = Basemap(projection='ortho', lon_0=-48, lat_0=-23, ax=ax1) m1.drawmapboundary(fill_color='#afeeee') m1.fillcontinents(color='beige', lake_color='#afeeee') m1.drawcoastlines() m1.drawcountries() m2 = Basemap(llcrnrlon=xlon1.min(), llcrnrlat=xlat1.min(), urcrnrlon=xlon1.max(), urcrnrlat=xlat1.max(), projection='merc', resolution='i', ax=ax2) m2.drawcoastlines() m2.drawstates() m2.drawcountries() m2.drawmapboundary(fill_color='#afeeee') m2.fillcontinents(color='beige', lake_color='#afeeee', zorder=1) m2.drawparallels(np.arange(-90., 90., 0.75),
def visualMap(): fig = plt.figure() ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) map = Basemap(llcrnrlon=80.33, llcrnrlat=3.01, urcrnrlon=138.16, urcrnrlat=56.123, resolution='h', projection='lcc', lat_0=42.5, lon_0=120, ax=ax1) shp_info = map.readshapefile("CHN_adm_shp\CHN_adm1", 'states', drawbounds=True) # CHN_adm1的数据是中国各省区域 for info, shp in zip(map.states_info, map.states): poly = Polygon(shp, facecolor='coral', edgecolor='w', lw=1) ax1.add_patch(poly) map.drawcoastlines() # 绘制海岸线 map.drawcountries() # 绘制国家 # start_lat = 39.85915479295669 # start_lon = 116.455078125 # end_lat = 39.061849134291535 # end_lon = 117.235107421875 # # if abs(end_lat - start_lat) < 180 and abs(end_lon - start_lon) < 180: # map.drawgreatcircle(start_lon, start_lat, end_lon, end_lat, linewidth=1) # x1, y1 = map(116.455078125, 39.85915479295669) x2, y2 = map(117.235107421875, 39.061849134291535) x3, y3 = map(117.147216796875, 36.59788913307022) x4, y4 = map(114.521484375, 38.004819966413194) plt.text(x1, y1, 'Lagos', fontsize=7, fontweight='bold', ha='left', va='bottom', color='y') # gpsLoc = [[39.85915479295669, 116.455078125], # [39.061849134291535, 117.235107421875], # [36.59788913307022, 117.147216796875], # [38.004819966413194, 114.521484375]] # # for index, value in enumerate(gpsLoc): # lons= value[1] # lats = value[0] # x, y = map(lons,lats) # print value # map.scatter(x,y,s=100,marker='D',facecolors='r',edgecolors='r') plt.plot([x1, x2, x3, x4], [y1, y2, y3, y4], color='k', linestyle='-', linewidth=1)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) #m = Basemap(projection='kav7',lon_0=-80,resolution='l') m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, projection='lcc', resolution='i', area_thresh=1000., lat_1=lat_1, lon_0=lon_0) m.drawmapboundary(fill_color='0.8') m.drawcoastlines(linewidth=1.) #m.fillcontinents(color='0.8') m.drawparallels(np.arange(46, 60, 2), labels=[1, 0, 1, 0], fontsize=12) m.drawmeridians(np.arange(-20, 0, 2), labels=[0, 0, 0, 1], fontsize=12) pc = m.pcolor(lo, la, var_d, cmap=plt.cm.jet, vmin=-vminmax, vmax=vminmax, latlon=True) cb = m.colorbar(pc, "right", size="5%", pad="10%") cb.set_label(var.units, fontsize=24) cb.ax.tick_params(axis='both', which='major', labelsize=12)
data = pr.readFromFile(inputfile) if args.debug: print("Arrays built") if args.autoscale: args.xdim = args.ydim = (2 * max_dist) + 50 mymap = Basemap(width=args.xdim, height=args.ydim, resolution='h', projection='tmerc', \ lat_0=args.latitude, lon_0=args.longitude) lons, lats = mymap(xx, yy) fig = plt.figure(figsize=(10, 10)) #ax = Axes3D(fig) ax = fig.add_subplot(111, projection='3d') ax.plot(lons, lats, alts, ',', color='red') #ax.view_init(azim=40, elev=20000) #ax.scatter(lons, lats, alts, marker='.', color='red', s=1) ax.add_collection3d(mymap.drawcoastlines()) ax.add_collection3d(mymap.drawstates()) if args.title: ax.set_title(args.title) ax.set_zlabel('Altitude (m)') ax.grid(True) plt.draw() if args.debug: print("showing plot") plt.show()
def wtsig_plot(multimodel,lat,lon,outDIR,flag_svplt,var,prod,dpi): # list of rcps (no flagging) rcps = ['rcp26','rcp60','rcp85'] tscale = 'annual' #============================================================================== #DEFINE PLOT SETTINGS #============================================================================== # font settings title_font = 11 cbtitle_font = 11 tick_font = 9 arrow_font = 10 # list of model titles model_titles = ['Multi-model mean', 'CLM4.5', 'SIMSTRAT-UoG', 'ALBM', 'VIC-LAKE'] # continent fill color col_cont='white' # ocean fill color col_ocean='whitesmoke' # zero change color col_zero='gray' # list of figure panel ids letters = ['a', 'b', 'c',\ 'd', 'e', 'f',\ 'g', 'h', 'i',\ 'j', 'k', 'l',\ 'm', 'n', 'o'] #========== COLORBAR ==========# cmap_whole = plt.cm.get_cmap('RdBu') cmap55 = cmap_whole(0.01) cmap50 = cmap_whole(0.05) #blue cmap45 = cmap_whole(0.1) cmap40 = cmap_whole(0.15) cmap35 = cmap_whole(0.2) cmap30 = cmap_whole(0.25) cmap25 = cmap_whole(0.3) cmap20 = cmap_whole(0.325) cmap10 = cmap_whole(0.4) cmap5 = cmap_whole(0.475) cmap0 = col_zero cmap_5 = cmap_whole(0.525) cmap_10 = cmap_whole(0.6) cmap_20 = cmap_whole(0.625) cmap_25 = cmap_whole(0.7) cmap_30 = cmap_whole(0.75) cmap_35 = cmap_whole(0.8) cmap_40 = cmap_whole(0.85) cmap_45 = cmap_whole(0.9) cmap_50 = cmap_whole(0.95) #red cmap_55 = cmap_whole(0.99) # declare list of colors for discrete colormap of colorbar cmap = mpl.colors.ListedColormap([cmap_45,cmap_35,cmap_25,cmap_10,cmap_5,cmap0, cmap5,cmap10,cmap20,cmap30,cmap40],N=11) # set color of over/under arrows in colorbar cmap.set_over(cmap50) cmap.set_under(cmap_50) # colorbar args values = [-5,-4,-3,-2,-1,-0.5,0.5,1,2,3,4,5] tick_locs = [-5,-4,-3,-2,-1,0,1,2,3,4,5] norm = mpl.colors.BoundaryNorm(values,cmap.N) # colorbar label cblabel = 'Change in lake temperature (at 2m depth) in °C' # bbox (arrow plot relative to this axis) cb_x0 = 0.2275 cb_y0 = 0.175 cb_xlen = 0.55 cb_ylen = 0.015 #========== ARROWS ==========# # blue arrow label bluelabel = 'Colder' x0_bluelab = 0.25 y0_bluelab = -2.9 # blue arrow x0_bluearr = 0.495 y0_bluearr = -3.4 xlen_bluearr = -0.4 ylen_bluearr = 0 # red arrow label redlabel = 'Warmer' x0_redlab = 0.75 y0_redlab = -2.9 # red arrow x0_redarr = 0.505 y0_redarr = -3.4 xlen_redarr = 0.4 ylen_redarr = 0 # general arrow_width = 0.25 arrow_linew = 0.1 arrow_headwidth = 0.5 arrow_headlength = 0.06 #========== SUBPLOTS ==========# left_border = 0.15 right_border = 0.85 bottom_border = 0.25 top_border = 0.925 width_space = 0.05 height_space = 0.175 # figsize = (x,y) x = 10 y = 12 #============================================================================== #INITIALIZE PLOTTING #============================================================================== lon, lat = np.meshgrid(lon, lat) for rcp in rcps: data = multimodel[rcp] f, axes = plt.subplots(len(data),1,figsize=(x,y)); count = 0 for ax,array in zip(axes.flatten(),data): count += 1 m = Basemap(llcrnrlon=-170, llcrnrlat=-60, urcrnrlon=180, urcrnrlat=90, suppress_ticks=False); m.ax = ax m.drawcoastlines(linewidth=0.1); m.drawmapboundary(fill_color=col_ocean) m.fillcontinents(color=col_cont); m.pcolormesh(lon,lat,array,latlon=True,cmap=cmap,norm=norm,vmax=5,vmin=-5,zorder=3) ax.set_title(letters[count-1],loc='left',pad=10,fontsize=title_font,fontweight='bold') ax.set_title(model_titles[count-1],loc='right',fontsize=title_font,pad=10) ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False, bottom=False, top=False, left=False, right=False, color='0.2',\ labelcolor='0.2',width=0.4,direction="in",length=2.5) ax.spines['bottom'].set_color('0.2') ax.spines['bottom'].set_linewidth(0.4) ax.spines['top'].set_color('0.2') ax.spines['top'].set_linewidth(0.4) ax.xaxis.label.set_color('0.2') ax.spines['left'].set_color('0.2') ax.spines['left'].set_linewidth(0.4) ax.spines['right'].set_color('0.2') ax.spines['right'].set_linewidth(0.4) ax.yaxis.label.set_color('0.2') #colorbar setup cbax = f.add_axes([cb_x0, cb_y0, cb_xlen, cb_ylen]) cb = mpl.colorbar.ColorbarBase(ax=cbax, cmap=cmap, norm=norm, spacing='proportional', orientation='horizontal', extend='both', ticks=tick_locs) cb.set_label(cblabel,size=cbtitle_font) cb.ax.xaxis.set_label_position('top'); cb.ax.tick_params(labelcolor='0.2', labelsize=tick_font, color='0.2',length=2.5, width=0.4, direction='out'); #change color of ticks? cb.ax.set_xticklabels([r'$\leq$-5','-4','-3','-2','-1','0','1','2','3','4',r'5$\leq$']) cb.outline.set_edgecolor('0.2') cb.outline.set_linewidth(0.4) #arrows plt.text(x0_redlab, y0_redlab, redlabel, size=arrow_font, ha='center', va='center') plt.text(x0_bluelab, y0_bluelab, bluelabel, size=arrow_font, ha='center', va='center') plt.arrow(x0_bluearr, y0_bluearr, xlen_bluearr, ylen_bluearr, width=arrow_width, linewidth=arrow_linew,\ shape='left', head_width=arrow_headwidth, head_length=arrow_headlength,\ facecolor=cmap_40, edgecolor='k', clip_on=False) plt.arrow(x0_redarr, y0_redarr, xlen_redarr, ylen_redarr, width=arrow_width, linewidth=arrow_linew,\ shape='right', head_width=arrow_headwidth, head_length=arrow_headlength,\ facecolor=cmap40, edgecolor='k', clip_on=False) plt.subplots_adjust(left=left_border, right=right_border, bottom=bottom_border, top=top_border,\ wspace=width_space, hspace=height_space) plt.show() # save figure if flag_svplt == 0: None elif flag_svplt == 1: if rcp == 'rcp26': f.savefig(outDIR+'/si_f02.png',bbox_inches='tight',dpi=dpi) elif rcp == 'rcp60': f.savefig(outDIR+'/si_f03.png',bbox_inches='tight',dpi=dpi) elif rcp == 'rcp85': f.savefig(outDIR+'/si_f04.png',bbox_inches='tight',dpi=dpi)
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(projection='ortho', lat_0=0, lon_0=0) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral', lake_color='aqua') map.drawcoastlines() x, y = map(0, 0) map.plot(x, y, marker='D', color='m') plt.savefig('globe.png')
def process_interseismic(cnn, stnlist, force_stnlist, stack, sigma_cutoff, vel_cutoff, lat_lim, filename, kmz): # start by checking that the stations in the list have a linear start (no post-seismic) # and more than 2 years of data until the first earthquake or non-linear behavior tqdm.write( ' >> Analyzing suitability of station list to participate in interseismic trajectory model...' ) tqdm.write(' -- velocity cutoff: %.2f mm/yr; output filename: %s' % (vel_cutoff, filename)) use_station = [] discarded = [] velocities = [] min_lon = 9999 max_lon = -9999 min_lat = 9999 max_lat = -9999 for stn in tqdm(stnlist, ncols=160, disable=None): try: etm = pyETM.GamitETM(cnn, stn['NetworkCode'], stn['StationCode'], stack_name=stack) use = True # only check everything is station not included in the force list if stn not in force_stnlist: # check that station is within latitude range if etm.gamit_soln.lat[0] < lat_lim[0] or etm.gamit_soln.lat[ 0] > lat_lim[1]: tqdm.write( ' -- %s.%s excluded because it is outside of the latitude limit' % (stn['NetworkCode'], stn['StationCode'])) use = False # check that station has at least 2 years of data if etm.gamit_soln.date[-1].fyear - etm.gamit_soln.date[ 0].fyear < 2 and use: tqdm.write( ' -- %s.%s rejected due having less than two years of observations %s -> %s' % (stn['NetworkCode'], stn['StationCode'], etm.gamit_soln.date[0].yyyyddd(), etm.gamit_soln.date[-1].yyyyddd())) use = False # other checks if etm.A is not None: if len(etm.Jumps.table) > 0 and use: eq_jumps = [ j for j in etm.Jumps.table if j.p.jump_type == pyETM.CO_SEISMIC_JUMP_DECAY and j.fit ] for j in eq_jumps: if j.magnitude >= 7 and j.date.fyear < etm.gamit_soln.date[ 0].fyear + 1.5: tqdm.write( ' -- %s.%s has a Mw %.1f in %s and data starts in %s' % (stn['NetworkCode'], stn['StationCode'], j.magnitude, j.date.yyyyddd(), etm.gamit_soln.date[0].yyyyddd())) use = False break eq_jumps = [ j for j in etm.Jumps.table if j.p.jump_type == pyETM.CO_SEISMIC_DECAY and j.fit ] if len(eq_jumps) > 0 and use: tqdm.write( ' -- %s.%s has one or more earthquakes before data started in %s' % (stn['NetworkCode'], stn['StationCode'], etm.gamit_soln.date[0].yyyyddd())) use = False if (etm.factor[0] * 1000 > sigma_cutoff or etm.factor[1] * 1000 > sigma_cutoff) and use: tqdm.write( ' -- %s.%s rejected due to large wrms %5.2f %5.2f %5.2f' % (stn['NetworkCode'], stn['StationCode'], etm.factor[0] * 1000, etm.factor[1] * 1000, etm.factor[2] * 1000)) use = False norm = np.sqrt( np.sum(np.square(etm.Linear.p.params[0:2, 1] * 1000))) if norm > vel_cutoff and use: tqdm.write( ' -- %s.%s rejected due to large NEU velocity: %5.2f %5.2f %5.2f NE norm %5.2f' % (stn['NetworkCode'], stn['StationCode'], etm.Linear.p.params[0, 1] * 1000, etm.Linear.p.params[1, 1] * 1000, etm.Linear.p.params[2, 1] * 1000, norm)) use = False elif use: tqdm.write(' -- %s.%s too few solutions to calculate ETM' % (stn['NetworkCode'], stn['StationCode'])) use = False else: tqdm.write(' -- %s.%s was forced to be included in the list' % (stn['NetworkCode'], stn['StationCode'])) if use: tqdm.write( ' -- %s.%s added NEU wrms: %5.2f %5.2f %5.2f NEU vel: %5.2f %5.2f %5.2f' % (stn['NetworkCode'], stn['StationCode'], etm.factor[0] * 1000, etm.factor[1] * 1000, etm.factor[2] * 1000, etm.Linear.p.params[0, 1] * 1000, etm.Linear.p.params[1, 1] * 1000, etm.Linear.p.params[2, 1] * 1000)) use_station.append(stn) velocities.append({ 'NetworkCode': etm.NetworkCode, 'StationCode': etm.StationCode, 'lat': etm.gamit_soln.lat[0], 'lon': etm.gamit_soln.lon[0], 'vn': etm.Linear.p.params[0, 1], 've': etm.Linear.p.params[1, 1], 'etm': etm.plot(plot_missing=False, plot_outliers=False, fileio=BytesIO()) }) if etm.gamit_soln.lon[0] < min_lon: min_lon = etm.gamit_soln.lon if etm.gamit_soln.lon[0] > max_lon: max_lon = etm.gamit_soln.lon if etm.gamit_soln.lat[0] < min_lat: min_lat = etm.gamit_soln.lat if etm.gamit_soln.lat[0] > max_lat: max_lat = etm.gamit_soln.lat elif not use and etm.A is not None: discarded.append({ 'NetworkCode': etm.NetworkCode, 'StationCode': etm.StationCode, 'lat': etm.gamit_soln.lat[0], 'lon': etm.gamit_soln.lon[0], 'vn': etm.Linear.p.params[0, 1], 've': etm.Linear.p.params[1, 1], 'etm': etm.plot(plot_missing=False, plot_outliers=False, fileio=BytesIO()) }) except pyETM.pyETMException as e: tqdm.write(' -- %s.%s: %s' % (stn['NetworkCode'], stn['StationCode'], str(e))) tqdm.write(' >> Total number of stations for linear model: %i' % len(use_station)) map = Basemap(llcrnrlon=min_lon - 2, llcrnrlat=min_lat - 2, urcrnrlon=max_lon + 2, urcrnrlat=max_lat + 2, resolution='i', projection='merc', lon_0=(max_lon - min_lon) / 2 + min_lon, lat_0=(max_lat - min_lat) / 2 + min_lat) plt.figure(figsize=(15, 10)) map.drawcoastlines() map.drawcountries() # map.drawstates() # map.fillcontinents(color='#cc9966', lake_color='#99ffff') # draw parallels and meridians. # map.drawparallels(np.arange(np.floor(min_lat), np.ceil(max_lat), 2.)) # map.drawmeridians(np.arange(np.floor(min_lon), np.ceil(max_lon), 2.)) # map.drawmapboundary(fill_color='#99ffff') map.quiver([l['lon'] for l in velocities], [l['lat'] for l in velocities], [l['ve'] for l in velocities], [l['vn'] for l in velocities], scale=0.25, latlon=True, color='blue', zorder=3) plt.title("Transverse Mercator Projection") plt.savefig('production/test.png') plt.close() outvar = np.array([[v['lon'], v['lat'], v['ve'], v['vn']] for v in velocities]) np.savetxt(filename, outvar) if kmz: generate_kmz(kmz, velocities, discarded)
fig1 = pl.figure(1, figsize=(16, 8.5), facecolor='w') print " " print "Plotting Map ..............." ##################################################################### p1 = pl.subplot(121) pc = m.contourf(lon, lat, mag, np.arange(5, 21, 0.5), cmap=pl.cm.Reds, extend='both') m.quiver(lon, lat, um, vm, scale=300, color='k') m.contourf(xb, yb, zbm, colors=('w'), linewidth=0) m.drawcoastlines(zorder=5) m.drawcountries(zorder=4) m.fillcontinents(zorder=3) m.drawparallels(pl.arange(-24, 0, 3), labels=[1, 0, 0, 0], dashes=[1, 1000], zorder=6) m.drawmeridians(pl.arange(-45, -20, 3), labels=[0, 0, 0, 1], dashes=[1, 1000], zorder=7) ax, ay = m(-37, -18) m.plot(ax, ay, '*y', mec='k', mfc='y', ms=15) ax, ay = m(-40.3, -23) m.plot(ax, ay, '*y', mec='k', mfc='y', ms=15) ax, ay = m(-41, -14.5)
def map_haz(fig, plt, haz_map_file, sitelon, sitelat, **kwargs): ''' kwargs: shpfile: path to area source - is a list of files resolution: c (crude), l (low), i (intermediate), h (high), f (full) mbuffer: map buffer in degrees ''' from openquake.nrmllib.hazard.parsers import GMFScenarioParser from mpl_toolkits.basemap import Basemap from numpy import arange, array, log10, mean, mgrid, percentile from matplotlib.mlab import griddata from matplotlib import colors, colorbar, cm from os import path from mapping_tools import drawshapepoly, labelpolygon import shapefile # set kwargs drawshape = False res = 'c' mbuff = -0.3 keys = ['shapefile', 'resolution', 'mbuffer'] for key in keys: if key in kwargs: if key == 'shapefile': shpfile = kwargs[key] drawshape = True if key == 'resolution': res = kwargs[key] if key == 'mbuffer': mbuff = kwargs[key] gmfsp = GMFScenarioParser(haz_map_file).parse() metadata, values = parse_nrml_hazard_map(haz_map_file) hazvals = [] latlist = [] lonlist = [] for val in values: lonlist.append(val[0]) latlist.append(val[1]) hazvals.append(val[2]) # get map bounds llcrnrlat = min(latlist) - mbuff / 2. urcrnrlat = max(latlist) + mbuff / 2. llcrnrlon = min(lonlist) - mbuff urcrnrlon = max(lonlist) + mbuff lon_0 = mean([llcrnrlon, urcrnrlon]) lat_1 = percentile([llcrnrlat, urcrnrlat], 25) lat_2 = percentile([llcrnrlat, urcrnrlat], 75) 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=1000.) m.drawcoastlines(linewidth=0.5, color='k') m.drawcountries() # draw parallels and meridians. m.drawparallels(arange(-90., 90., 1.), labels=[1, 0, 0, 0], fontsize=10, dashes=[2, 2], color='0.5', linewidth=0.5) m.drawmeridians(arange(0., 360., 1.), labels=[0, 0, 0, 1], fontsize=10, dashes=[2, 2], color='0.5', linewidth=0.5) # make regular grid N = 150j extent = (min(lonlist), max(lonlist), min(latlist), max(latlist)) xs, ys = mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N] resampled = griddata(array(lonlist), array(latlist), log10(array(hazvals)), xs, ys) ############################################################################# # transform grid to basemap # get 1D lats and lons for map transform lons = ogrid[extent[0]:extent[1]:N] lats = ogrid[extent[2]:extent[3]:N] # transform to map projection if max(lonlist) - min(lonlist) < 1: transspace = 500 elif max(lonlist) - min(lonlist) < 5: transspace = 1000 elif max(lonlist) - min(lonlist) < 10: transspace = 2000 else: transspace = 5000 nx = int((m.xmax - m.xmin) / transspace) + 1 ny = int((m.ymax - m.ymin) / transspace) + 1 transhaz = m.transform_scalar(resampled.T, lons, lats, nx, ny) m.imshow(transhaz, cmap='Spectral_r', extent=extent, vmin=-2, vmax=log10(2.), zorder=0) # plot site xx, yy = m(sitelon, sitelat) plt.plot(xx, yy, '*', ms=20, mec='k', mew=2.0, mfc="None") # superimpose area source shapefile if drawshape == True: for shp in shpfile: sf = shapefile.Reader(shp) drawshapepoly(m, plt, sf, col='k', lw=1.5, polyline=True) labelpolygon(m, plt, sf, 'CODE', fsize=14) # set colourbar # set cb for final fig plt.gcf().subplots_adjust(bottom=0.1) cax = fig.add_axes([0.6, 0.05, 0.25, 0.02]) # setup colorbar axes. norm = colors.Normalize(vmin=-2, vmax=log10(2.)) cb = colorbar.ColorbarBase(cax, cmap=cm.Spectral_r, norm=norm, orientation='horizontal') # set cb labels #linticks = array([0.01, 0.03, 0.1, 0.3 ]) logticks = arange(-2, log10(2.), 0.25) cb.set_ticks(logticks) labels = [str('%0.2f' % 10**x) for x in logticks] cb.set_ticklabels(labels) # get map probabiltiy from filename mprob = path.split(haz_map_file)[-1].split('_')[-1].split('-')[0] probstr = str(int(float(mprob) * 100)) # set colourbar title if metadata['statistics'] == 'mean': titlestr = ''.join((metadata['imt'], ' ', metadata['sa_period'], ' s ', \ probstr,'% in ',metadata['investigation_time'][0:-2], \ ' Year Mean Hazard (g)')) #cb.set_ticklabels(labels) cb.set_label(titlestr, fontsize=12) return plt
urcrnrlon = maxlon lon_0 = mean([llcrnrlon, urcrnrlon]) 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)
def openwindow1(): data = pd.read_csv("india-districts-census-2011.csv") # In[3]: data.shape # In[4]: data.head() # In[5]: data.describe() # In[6]: data.info() # In[7]: data.groupby('State name').size() # In[8]: ''' Calculating state wise literacy rates ''' states_group = data.groupby(by="State name") agri_rate = [] for key, group in states_group: total_state_pop = 0 total_agri_pop = 0 # Iterating through all the rows for calculating the sum of total population and the literate population for row in group.iterrows(): total_state_pop += row[1][3] total_agri_pop += row[1][22] # Calculate literacy rate for the state rate1 = (total_agri_pop / total_state_pop) * 100 # Store the result as a tuple in the list literacy_rate, contaning pairs of state names and literacy rates agri_rate.append((key, rate1)) print("Statewise agricultural workers are : \n") agri_rate1 = pd.Series(agri_rate) agri_rate1 # In[11]: fig, ax = plt.subplots() m = Basemap(projection='merc', lat_0=54.5, lon_0=-4.36, llcrnrlon=68.1, llcrnrlat=6.5, urcrnrlon=97.4, urcrnrlat=35.5) m.drawmapboundary(fill_color='#46bcec') m.fillcontinents(color='#f2f2f2', lake_color='#46bcec') # Draw coast lines m.drawcoastlines() # Load the shape file of India m.readshapefile("C:\\Users\\USER\\Downloads\\INDIA", "INDIA") ''' STEP 4 : CREATING A DATAFRAME MAPPING SHAPES TO STATE NAME AND LITERACY RATES ''' agri1_rate = [] #Iterate through INDIA_info file for state_info in m.INDIA_info: state = state_info['ST_NAME'].upper( ) #Converting the state names in upper case # initialize rate = 0 rate1 = 0 for x in agri_rate1: if x[0] == state: rate = x[1] break agri1_rate.append(rate) df_poly = pd.DataFrame({ 'shapes': [Polygon(np.array(shape), True) for shape in m.INDIA], 'area': [area['ST_NAME'] for area in m.INDIA_info], 'agri1_rate': agri1_rate }) # Get all the shapes shapes = [Polygon(np.array(shape), True) for shape in m.INDIA] # Create a colormap cmap = plt.get_cmap('Oranges') pc = PatchCollection(shapes, zorder=2) norm = Normalize() # Set color according to the literacy rate of the state pc.set_facecolor(cmap(norm(df_poly['agri1_rate'].fillna(0).values))) ax.add_collection(pc) mapper = matplotlib.cm.ScalarMappable(cmap=cmap) mapper.set_array(agri1_rate) plt.colorbar(mapper, shrink=0.4) ax.set_title("AGRICULTURAL WORKERS OF INDIAN STATES") plt.rcParams['figure.figsize'] = (15, 15) plt.rcParams.update({'font.size': 20}) plt.show() fig.savefig('agriculture.png')
labels = db.labels_ # Number of clusters in labels, ignoring noise if present. n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) # Black removed and is used for noise instead. unique_labels = set(labels) plt.figure() m = Basemap(projection='mill', lat_ts=10, llcrnrlon=-83, urcrnrlon=rlon, llcrnrlat=24, urcrnrlat=28, resolution='h') m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(-90., 120., 1.), labels=[1, 0, 0, 0]) m.drawmeridians(np.arange(-180., 180., 1.), labels=[0, 0, 0, 1]) m.drawcountries() m.drawstates() colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels))) filepoly = folder + datestr + '.vtx' fil = open(filepoly, 'w') for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise. col = 'k' class_member_mask = (labels == k)
lon_0 = mean([llcrnrlon, urcrnrlon]) lat_1 = percentile([llcrnrlat, urcrnrlat], 25) lat_2 = percentile([llcrnrlat, urcrnrlat], 75) fig = plt.figure(figsize=(18, 10)) plt.tick_params(labelsize=16) ax = fig.add_subplot(111) m = Basemap(projection='lcc',lat_1=lat_1,lat_2=lat_2,lon_0=lon_0,\ llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat, \ urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat,\ rsphere=6371200.,resolution='h',area_thresh=500.) # draw coastlines, state and country boundaries, edge of map. #m.shadedrelief() m.drawcoastlines(color='0.5', linewidth=0.5) #m.fillcontinents(color=None, lake_color='lightskyblue') m.drawstates(color='0.5', linewidth=0.5) m.drawcountries(color='0.5', linewidth=0.5) m.drawparallels(arange(-90., 90., 1.), labels=[1, 0, 0, 0], fontsize=16, dashes=[2, 2], color='0.5', linewidth=0.5) m.drawmeridians(arange(0., 360., 2.), labels=[0, 0, 0, 1], fontsize=16, dashes=[2, 2], color='0.5', linewidth=0.5)
def plotExtremeGlobal(metric): """ this function plots the chosen metric globallly using the basemap library metric = {'corr', 'rmse', 'nse'} """ #call processData here if metric == 'corr': dat = starter()[0] #remove tg that have negative correlation dat = dat[~(dat['Correlation'] < 0)] varToPlot = 'Correlation' title = 'Pearson\'s Correlation - 1980-2010 - above 95%ile' bubbleSizeMultiplier = 250 elif metric == 'nse': dat = starter()[2] varToPlot = 'NSE(%)' title = 'NSE - 1980-2010' bubbleSizeMultiplier = 900 else: dat = starter()[1] varToPlot = 'RMSE(cm)' title = 'RMSE(cm) - 1980-2010 - above 95%ile' bubbleSizeMultiplier = 4 #increase plot font size sns.set_context('notebook', font_scale=1.5) plt.figure(figsize=(20, 10)) m = Basemap(projection='cyl', lat_ts=20, llcrnrlon=-180, urcrnrlon=180, llcrnrlat=-90, urcrnrlat=90, resolution='c') x, y = m(dat['lon'].tolist(), dat['lat'].tolist()) m.drawcoastlines() #draw parallels and meridians parallels = np.arange(-80, 81, 20.) meridians = np.arange(-180., 180., 40.) m.drawparallels(parallels, labels=[True, False, False, False], linewidth=0) m.drawparallels(parallels, labels=[True, True, False, False], linewidth=0.5) m.drawmeridians(meridians, labels=[False, False, False, True], linewidth=0.5) m.bluemarble(alpha=0.8) #define markers markers = { "20CR": "o", "ERA-20C": "o", "ERA-Interim": 'o', "MERRA": 'o', "ERA-FIVE": 'o' } #define palette color_dict = dict({ '20CR': 'green', 'ERA-20C': 'magenta', 'ERA-Interim': 'black', 'MERRA': 'red', 'ERA-FIVE': 'aqua' }) #define bubble sizes minSize = min(dat[varToPlot]) * bubbleSizeMultiplier if minSize < 0: minSize = 0 maxSize = max(dat[varToPlot]) * bubbleSizeMultiplier sns.scatterplot(x = x, y = y, markers = markers, style = 'Reanalysis',\ size = varToPlot, sizes=(minSize, maxSize),\ hue = 'Reanalysis', palette = color_dict, data = dat) plt.legend(loc='lower left', ncol=12) plt.title(title) os.chdir( "G:\\data\\allReconstructions\\validation\\commonPeriodValidationExtremes\\percentile\\plotFiles" ) saveName = 'allReanalysesExtremes' + metric + '.svg'
T.append(t) tidx =np.argmin(abs(np.array(T)-starttime)) #find nearest time zlev = -1 # last layer is surface layer in ROMS u = nc.variables['u'][tidx, zlev, j0:j1, i0:(i1-1)] v = nc.variables['v'][tidx, zlev, j0:(j1-1), i0:i1] lon=lon_rho[(j0+1):(j1-1), (i0+1):(i1-1)] lat=lat_rho[(j0+1):(j1-1), (i0+1):(i1-1)] mask = 1 - nc.variables['mask_rho'][(j0+1):(j1-1), (i0+1):(i1-1)] ang = nc.variables['angle'][(j0+1):(j1-1), (i0+1):(i1-1)] u = shrink(u, mask.shape) v = shrink(v, mask.shape) # average u,v to central rho points U, V = rot2d(u, v, ang) # rotate grid_oriented u,v to east/west u,v basemap = Basemap(projection='merc',llcrnrlat=bbox[2]-0.3,urcrnrlat=bbox[3],llcrnrlon=bbox[0]-0.3,urcrnrlon=bbox[1]+0.3, lat_ts=30,resolution='i') fig1 = plt.figure(figsize=(15,10)) ax = fig1.add_subplot(111) basemap.drawcoastlines() basemap.fillcontinents() basemap.drawcountries() basemap.drawstates() basemap.drawparallels(np.arange(int(bbox[2]-0.5),int(bbox[3]+0.5),0.5),labels=[1,0,0,0], linewidth=0) basemap.drawmeridians(np.arange(int(bbox[0]-0.5),int(bbox[1]+0.5),0.5),labels=[0,0,0,1], linewidth=0) x_rho, y_rho = basemap(lon,lat) spd = np.sqrt(U*U + V*V) nsub=3 scale=0.05 Q=basemap.quiver(x_rho[::nsub,::nsub],y_rho[::nsub,::nsub],U[::nsub,::nsub],V[::nsub,::nsub],scale=1.0/scale, zorder=1e35, width=0.005) maxvel=np.nanmax(spd) maxstr='%3.1f m/s' % maxvel qk = quiverkey(Q,0.92,0.08,maxvel,maxstr,labelpos='W') plt.title('Surface current,'+str(T[tidx])[0:-6]+'(local time)',fontsize=15) plt.savefig('/var/www/html/ioos/sf/fig/roms'+method+'.png')
lon_low = np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) lons, lats = np.meshgrid(lons, lats) m =\ Basemap(llcrnrlon=lon_low_plot,llcrnrlat=lat_low_plot,urcrnrlon=lon_high_plot,urcrnrlat=lat_high_plot,projection='mill', rsphere=6371229) x, y = m(lons, lats) fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0.05, 0.05, 0.9, 0.85]) # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines(linewidth=0.5, color='#262626') #m.drawstates() m.drawcountries(linewidth=0.5, color='#262626') # draw parallels. parallels = np.arange(0., 90, divisor) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10, color='#262626') # draw meridians meridians = np.arange(0., 360., divisor) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10, color='#262626') cs_col = m.contourf(x, y, sensible_mean, np.linspace(clev_min, clev_max, 16), cmap=cmap, extend='both')
def f2(): #was used for plotting stuff from the evaluator clist = ["green", "red", "purple", "orange"] ptimes = [0, 24, 48, 72] target = np.array([[42.733156, 13.449431 + 360]]) files = list(map(load_file2, range(1, 79))) const = list(map(load_file2, [0])) files2 = [] for i in ptimes: files2.append( list(map(load_file2, range(100 + i * 100, 100 + (i + 1) * 100)))) fig, ax = plt.subplots(2, 3, gridspec_kw={ 'height_ratios': [1, .63], "hspace": 0, }, figsize=(10, 5)) gs = gridspec.GridSpec(2, 3, width_ratios=[0.06, .14, 1], height_ratios=[1, 0.56]) gs.update(left=0.05, wspace=0, hspace=0.05) ax0 = plt.subplot(gs[0, 2:3]) ax1 = plt.subplot(gs[1, 1:3]) ax1.plot(0, 14, c="#be1e2d") ax1.plot(0, 14, c="blue") all_vals = np.concatenate(files + [i1 for i2 in files2 for i1 in i2]) real_vals = np.concatenate(files) for j, fs in enumerate(files2): c = clist[j] vals = fs[0] N = vals.shape[0] ax1.plot(ptimes[j] + np.arange(N) / 6, vals[:, 3] / 1000 - vals[:, 4] / 1000, "--", c=c, alpha=0.5) ax1.plot(ptimes[j] + np.arange(N) / 6, vals[:, 3] / 1000 + vals[:, 4] / 1000, "--", c=c, alpha=0.5) for i in range(0, 50): if (i + 1) % 8 != 0: continue vals = fs[i] N = vals.shape[0] #ax1.plot(ptimes[j] + np.arange(N)/6,vals[:,2]/1000,c=c,alpha=0.1) N = real_vals.shape[0] ax1.plot(np.arange(N) / 6, real_vals[:, 3] / 1000 + real_vals[:, 4] / 1000, "--", c="blue", alpha=1) ax1.plot(np.arange(N) / 6, real_vals[:, 3] / 1000 - real_vals[:, 4] / 1000, "--", c="blue", alpha=1) ax1.plot(np.arange(N) / 6, real_vals[:, 2] / 1000, c="blue", alpha=1) #ax1.legend(["initial","optimized"],loc=(.18,.05)) ax1.set_xlabel( "hours from " + datetime.fromtimestamp(1543492801).strftime("%Y-%m-%d %H:%M:%S")) ax1.set_ylabel("altitude (km)") ax1.grid() all_lls = np.vstack((all_vals[:, :2], target)) m = Basemap( projection='merc', llcrnrlat=np.min(all_lls[:, 0]) - 5, urcrnrlat=np.max(all_lls[:, 0]) + 5, llcrnrlon=np.min(all_lls[:, 1]) - 5, urcrnrlon=np.max(all_lls[:, 1]) + 5, resolution='l', ax=ax0, ) m.drawcoastlines(color="grey") m.drawcountries(color="grey") m.drawstates(color="grey") for j, fs in enumerate(files2): for i in range(0, 50): if (i + 1) % 8 != 0: continue vals = fs[i] xpred, ypred = m(vals[:, 1], vals[:, 0]) c = clist[j] ax0.plot(xpred, ypred, color=c, alpha=0.2) #ax0.plot(xpred[-1],ypred[-1],"*",c=c,alpha=0.2) ax0.plot(xpred[0], ypred[0], "*", c=c, alpha=1) cv = const[0] xpred, ypred = m(cv[:, 1], cv[:, 0]) ax0.plot(xpred, ypred, color="black", alpha=1, label="pre-optimized \ntrajectory") ax0.plot(xpred[-1], ypred[-1], "*", c="black") xpred, ypred = m(real_vals[:, 1], real_vals[:, 0]) ax0.plot(xpred, ypred, color="blue", alpha=1, label="evalaton \nsimulation \ntrajectory") ax0.plot(xpred[-1], ypred[-1], "*", c="blue") xt, yt = m(target[0, 1], target[0, 0]) p = ax0.plot(xt, yt, ".", c="red") legend_elements = [ li.Line2D([0], [0], color='b', lw=1.5, label="evalaton \nsimulation \ntrajectory"), li.Line2D([0], [0], color='black', lw=1.5, label="pre-optimized \ntrajectory"), li.Line2D([0], [0], linestyle="--", color='b', alpha=0, lw=2, label="------------------"), li.Line2D([0], [0], color='b', lw=1.5, label="evalaton \nsimulation \naltitude"), li.Line2D([0], [0], linestyle="--", color='b', lw=1.5, label="controller \ncounds"), li.Line2D([0], [0], marker='o', markerfacecolor='r', color='w', label='goal') ] print(p) ax0.legend(handles=legend_elements, loc='uppper right', bbox_to_anchor=(0, 1.03), ncol=1) plt.savefig("mpc2.png")
fig = plt.figure() ### Orient our data onto a map the_map = Basemap( width=12000000, height=9000000, projection="lcc", lat_1=25, # lower-left corner longitude lat_2=55, # lower-left corner latitude lat_0=40, # upper-right corner longitude lon_0=-80, # upper-right corner latitude resolution="c") ### Add map features -- e.g. coastlines the_map.drawcoastlines() the_map.drawcountries() the_map.drawstates() the_map.fillcontinents(color="coral") the_map.drawmapboundary(fill_color="steelblue") ### Add a point on our map lon = -75 lat = 40 x, y = the_map(lon, lat) the_map.plot(x, y, 'yo', markersize=8) ### Project our data #x, y = the_map(defect_locations["lon"], defect_locations["lat"]) #longitudes = [ -1*x for x in longitudes ]
def createNiceMap(grd, h, polygon_data_KINO, polygon_data_NS8KM, plotSelectedStations): fig = plt.figure(figsize=(12, 12)) ax = fig.add_subplot(111) levels = [10, 25, 50, 100, 250, 500, 1000, 2500, 5000] mymap = Basemap(llcrnrlon=-18.0, llcrnrlat=46.0, urcrnrlon=25.5, urcrnrlat=67.5, resolution='i', projection='tmerc', lon_0=0, lat_0=50, area_thresh=50.) mymap.drawcoastlines() mymap.drawcountries() mymap.fillcontinents(color='grey') mymap.drawmeridians(np.arange(grd.hgrid.lon_rho.min(), grd.hgrid.lon_rho.max(), 10), labels=[0, 0, 0, 1]) mymap.drawparallels(np.arange(grd.hgrid.lat_rho.min(), grd.hgrid.lat_rho.max(), 4), labels=[1, 0, 0, 0]) x, y = mymap(grd.hgrid.lon_rho, grd.hgrid.lat_rho) print np.min(grd.hgrid.lon_rho), np.max(grd.hgrid.lon_rho) print np.min(grd.hgrid.lat_rho), np.max(grd.hgrid.lat_rho) CS1 = mymap.contourf(x, y, h, levels, cmap=mpl_util.LevelColormap(levels, cmap=cm.Blues), extend='upper', alpha=1.0, origin='lower', rasterized=True) CS1.axis = 'tight' """Draw grid boundaries""" drawGridBoundaries(ax, mymap, polygon_data_NS8KM, mycolor="red") drawGridBoundaries(ax, mymap, polygon_data_KINO, mycolor="magenta") if (plotSelectedStations): xpos, ypos = getSelectedStations() xloc, yloc = mymap(grd.hgrid.lon_rho[ypos, xpos], grd.hgrid.lat_rho[ypos, xpos]) mymap.plot(xloc, yloc, marker="o", color="red", markersize=10, linewidth=0) plotfile = 'figures/map_NS8KM_and_KINO1600M.pdf' plt.savefig(plotfile, dpi='200') plt.show()
date2='20111030' ice_conc, lons, lats = siF.getMeanConcDates(dataPath, poleStr='AA', alg=0, date1=date1, date2=date2, lonlat=1, mean=1) xpts, ypts =m(lons, lats) textwidth=3. minval=0 maxval=1 #### fig = figure(figsize=(textwidth,textwidth)) ax1=subplot(1, 1, 1) im1 = m.pcolormesh(xpts , ypts, ice_conc, cmap=cm.viridis, vmin=minval, vmax=maxval,shading='gouraud', zorder=2) m.drawcoastlines(linewidth=0.25, zorder=5) m.drawparallels(np.arange(90,-90,-10), linewidth = 0.25, zorder=3) m.drawmeridians(np.arange(-180.,180.,30.), linewidth = 0.25, zorder=3) #ax1.annotate(files[x][-8:-4]+'-'+files[x][-4:-2]+'-'+files[x][-2:], xy=(0.98, 0.98), bbox=bbox_args,xycoords='axes fraction', horizontalalignment='right', verticalalignment='top', zorder=10) label_str=r'$A$' #ax1.annotate(str(start_year)+'-'+str(end_year-1), xy=(0.02, 0.86),xycoords='axes fraction', horizontalalignment='left', verticalalignment='bottom', zorder=10) cax = fig.add_axes([0.84, 0.95, 0.12, 0.03]) cbar = colorbar(im1,cax=cax, orientation='horizontal', extend='both', use_gridspec=True) cbar.set_label(label_str, labelpad=1) cbar.set_ticks(np.arange(minval, maxval+0.1, 1)) cbar.solids.set_rasterized(True) #SHIFT COLOR SPACE SO OFF WHITE COLOR IS AT 0 m #cbar.set_clim(minval, maxval) subplots_adjust(bottom=0., top=1., left=0.0, right=1.)
def animateTSP(country, history, points): """ :param country: string :param history: list[int, float, float] :param points: list[int, float, float] :return: """ try: # Prepare the coordinates for plotting the trip cityName = [] latitude = [] longitude = [] for city in points: cityName.append(city[0]) latitude.append(city[1] / 1000.) longitude.append(city[2] / 1000.) cityName.append(cityName[0]) latitude.append(latitude[0]) longitude.append(longitude[0]) plt.figure(figsize=(7, 7)) # Specify tripMap width and height if country == "Djibouti": tripMap = Basemap(width=350000, height=270000, resolution='i', projection='tmerc', lat_0=11.572076, lon_0=43.145645) else: tripMap = Basemap(width=250000, height=250000, resolution='i', projection='tmerc', lat_0=25.286106, lon_0=51.534817) tripMap.drawmapboundary(fill_color='aqua') tripMap.fillcontinents(color='#FFE4B5', lake_color='aqua') tripMap.drawcoastlines() tripMap.drawcountries() # Range the frames _frames = len(history) // 1500 _frameRange = range(0, len(history), _frames) # Path is represented as line line = tripMap.plot([], [], 'D-', markersize=3, linewidth=1, color='r')[0] # initial function def init_func(): # Draw node dots on graph x = [longitude[i] for i in history[0]] y = [latitude[i] for i in history[0]] x, y = tripMap(x, y) tripMap.plot(x, y, 'bo', markersize=3) # Empty initialization line.set_data([], []) return line, # animate function def gen_function(frame): # Update the graph for each frame x = [longitude[i] for i in history[frame] + [history[frame][0]]] y = [latitude[i] for i in history[frame] + [history[frame][0]]] x, y = tripMap(x, y) line.set_data(x, y) return line # Animate the graph _animation = FuncAnimation(plt.gcf(), func=gen_function, frames=_frameRange, init_func=init_func, interval=10, repeat=False) plt.show() except: EH()
### Set limits for contours and colorbars limit = np.arange(0, 0.5001, 0.005) barlim = np.round(np.arange(0, 0.6, 0.1), 2) cmap = cm.classic_16.mpl_colormap label = r'\textbf{RELEVANCE}' fig = plt.figure(figsize=(5, 3)) for r in range(len(runs)): var = runs[r] ax1 = plt.subplot(3, 4, r + 1) m = Basemap(projection='moll', lon_0=0, resolution='l', area_thresh=10000) circle = m.drawmapboundary(fill_color='dimgrey') circle.set_clip_on(False) m.drawcoastlines(color='darkgrey', linewidth=0.27) var, lons_cyclic = addcyclic(var, lon1) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat1) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='dimgrey', color='dimgray', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x, y, var, limit, extend='max') cs.set_cmap(cmap) if any([r == 0, r == 4, r == 8]):
def _plot_basemap_into_axes( ax, lons, lats, size, color, bmap=None, labels=None, projection='global', resolution='l', continent_fill_color='0.8', water_fill_color='1.0', colormap=None, marker="o", title=None, adjust_aspect_to_colorbar=False, **kwargs): # @UnusedVariable """ Creates a (or adds to existing) basemap plot with a data point scatter plot in given axes. See :func:`plot_basemap` for details on most args/kwargs. :type ax: :class:`matplotlib.axes.Axes` :param ax: Existing matplotlib axes instance, optionally with previous basemap plot (see `bmap` kwarg). :type bmap: :class:`mpl_toolkits.basemap.Basemap` :param bmap: Basemap instance in provided matplotlib Axes `ax` to reuse. If specified, any kwargs regarding the basemap plot setup will be ignored (i.e. `projection`, `resolution`, `continent_fill_color`, `water_fill_color`). :rtype: :class:`matplotlib.collections.PathCollection` :returns: Matplotlib path collection (e.g. to reuse for colorbars). """ fig = ax.figure if bmap is None: if projection == 'global': bmap = Basemap(projection='moll', lon_0=round(np.mean(lons), 4), resolution=_BASEMAP_RESOLUTIONS[resolution], ax=ax) elif projection == 'ortho': bmap = Basemap(projection='ortho', resolution=_BASEMAP_RESOLUTIONS[resolution], area_thresh=1000.0, lat_0=round(np.mean(lats), 4), lon_0=round(mean_longitude(lons), 4), ax=ax) elif projection == 'local': if min(lons) < -150 and max(lons) > 150: max_lons = max(np.array(lons) % 360) min_lons = min(np.array(lons) % 360) else: max_lons = max(lons) min_lons = min(lons) lat_0 = max(lats) / 2. + min(lats) / 2. lon_0 = max_lons / 2. + min_lons / 2. if lon_0 > 180: lon_0 -= 360 deg2m_lat = 2 * np.pi * 6371 * 1000 / 360 deg2m_lon = deg2m_lat * np.cos(lat_0 / 180 * np.pi) if len(lats) > 1: height = (max(lats) - min(lats)) * deg2m_lat width = (max_lons - min_lons) * deg2m_lon margin = 0.2 * (width + height) height += margin width += margin else: height = 2.0 * deg2m_lat width = 5.0 * deg2m_lon # do intelligent aspect calculation for local projection # adjust to figure dimensions w, h = fig.get_size_inches() ax_bbox = ax.get_position() aspect = (w * ax_bbox.width) / (h * ax_bbox.height) if adjust_aspect_to_colorbar: aspect *= 1.2 if width / height < aspect: width = height * aspect else: height = width / aspect bmap = Basemap(projection='aea', resolution=_BASEMAP_RESOLUTIONS[resolution], area_thresh=1000.0, lat_0=round(lat_0, 4), lon_0=round(lon_0, 4), width=width, height=height, ax=ax) # not most elegant way to calculate some round lats/lons def linspace2(val1, val2, n): """ returns around n 'nice' values between val1 and val2 """ dval = val2 - val1 round_pos = int(round(-np.log10(1. * dval / n))) # Fake negative rounding as not supported by future as of now. if round_pos < 0: factor = 10 ** (abs(round_pos)) delta = round(2. * dval / n / factor) * factor / 2 else: delta = round(2. * dval / n, round_pos) / 2 new_val1 = np.ceil(val1 / delta) * delta new_val2 = np.floor(val2 / delta) * delta n = int((new_val2 - new_val1) / delta + 1) return np.linspace(new_val1, new_val2, n) n_1 = int(np.ceil(height / max(width, height) * 8)) n_2 = int(np.ceil(width / max(width, height) * 8)) parallels = linspace2(lat_0 - height / 2 / deg2m_lat, lat_0 + height / 2 / deg2m_lat, n_1) # Old basemap versions have problems with non-integer parallels. try: bmap.drawparallels(parallels, labels=[0, 1, 1, 0]) except KeyError: parallels = sorted(list(set(map(int, parallels)))) bmap.drawparallels(parallels, labels=[0, 1, 1, 0]) if min(lons) < -150 and max(lons) > 150: lon_0 %= 360 meridians = linspace2(lon_0 - width / 2 / deg2m_lon, lon_0 + width / 2 / deg2m_lon, n_2) meridians[meridians > 180] -= 360 bmap.drawmeridians(meridians, labels=[1, 0, 0, 1]) else: msg = "Projection '%s' not supported." % projection raise ValueError(msg) # draw coast lines, country boundaries, fill continents. if MATPLOTLIB_VERSION >= [2, 0, 0]: ax.set_facecolor(water_fill_color) else: ax.set_axis_bgcolor(water_fill_color) bmap.drawcoastlines(color="0.4") bmap.drawcountries(color="0.75") bmap.fillcontinents(color=continent_fill_color, lake_color=water_fill_color) # draw the edge of the bmap projection region (the projection limb) bmap.drawmapboundary(fill_color=water_fill_color) # draw lat/lon grid lines every 30 degrees. bmap.drawmeridians(np.arange(-180, 180, 30)) bmap.drawparallels(np.arange(-90, 90, 30)) fig.bmap = bmap # compute the native bmap projection coordinates for events. x, y = bmap(lons, lats) # plot labels if labels: if 100 > len(lons) > 1: for name, xpt, ypt, _colorpt in zip(labels, x, y, color): # Check if the point can actually be seen with the current bmap # projection. The bmap object will set the coordinates to very # large values if it cannot project a point. if xpt > 1e25: continue ax.text(xpt, ypt, name, weight="heavy", color="k", zorder=100, path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white")]) elif len(lons) == 1: ax.text(x[0], y[0], labels[0], weight="heavy", color="k", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white")]) # scatter plot is removing valid x/y points with invalid color value, # so we plot those points separately. try: nan_points = np.isnan(np.array(color, dtype=np.float)) except ValueError: # `color' was not a list of values, but a list of colors. pass else: if nan_points.any(): x_ = np.array(x)[nan_points] y_ = np.array(y)[nan_points] size_ = np.array(size)[nan_points] bmap.scatter(x_, y_, marker=marker, s=size_, c="0.3", zorder=10, cmap=None) scatter = bmap.scatter(x, y, marker=marker, s=size, c=color, zorder=10, cmap=colormap) if title: ax.set_title(title) return scatter
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap districts = combined.groupby("school_dist").agg(numpy.mean) districts.reset_index(inplace=True) m = Basemap(projection='merc', llcrnrlat=40.496044, urcrnrlat=40.915256, llcrnrlon=-74.255735, urcrnrlon=-73.700272, resolution='i') m.drawmapboundary(fill_color='#85A6D9') m.drawcoastlines(color='#6D5F47', linewidth=.4) m.drawrivers(color='#6D5F47', linewidth=.4) # Temporary bug: if you run the following line of code in the Jupyter Guided Project interface on Dataquest, you'll get an error. # We're working on a fix, thanks for your patience! This should work fine locally on your own computer though. # m.fillcontinents(color='white',lake_color='#85A6D9') longitudes = districts["lon"].tolist() latitudes = districts["lat"].tolist() m.scatter(longitudes, latitudes, s=50, zorder=2, latlon=True, c=districts["saf_s_11"], cmap="summer") plt.show()
for line in open("major_city"): info = line.split() names.append(info[0]) pops.append(float(info[1])) lat = float(info[2][:-1]) if info[2][-1] == 'S': lat = -lat lats.append(lat) lon = float(info[3][:-1]) if info[3][-1] == 'w': lon = -lon lons.append(lon) country = info[4] countries.append(country) # lat: 维度 lon:经度 map = Basemap(projection='ortho', lat_0=35, lon_0=120, resolution='l') map.drawcoastlines(linewidth=0.25) map.drawcountries(linewidth=0.25) map.drawmapboundary(fill_color='#689CD2') # 每隔 30 画一条经线 map.drawmeridians(np.arange(0, 360, 30)) # 每隔 30 画一条维线 map.drawparallels(np.arange(-90, 90, 30)) # 填充大陆和海洋颜色 map.fillcontinents(color='#BF9E30', lake_color='#689CD2', zorder=0) x, y = map(lons, lats) max_pop = max(pops) size_factor = 80.0 y_offset = 15.0 rotation = 30
def displaymap(data, filename=None, iproj=4, LCOlon=-127, LCOlat=19, UCOlon=-59, UCOlat=54, lon=-95, lat=25, grid='Fill', statlons=None, statlats=None, stations=True, levels=None, title=None): ''' Displaymap takes input data and projection information to display data on a geographical map Inputs are: Data: An array of data to be plotted. The dimensions must match the desired lat and lon grid. filename: If set, resulting image will be saved as a .png file. If None, resulting image will be displayed. Default is None. iproj: an integer value related to the grid projection from a grib gds. The integer is read into a dictionary to determine the exact projection to plot. Default is 3 = Lambert Conformal Conic LCOlon/LCOlat: Lower Corner Longitude and Latitude. The coordinates for the lower left corner of the desired grid. Default: 127W, 19N UCOlon/UCOlat: Upper Corner Longitude and Latitude. The coordinates for the upper right corner of the desired grid. Default: 95W, 54N lon: A central or reference longitude used by different projections. Default: 95W lat: A central or reference latitude used by different projections. Default: 25N grid: A value of Fill will create a filled contour plot. A value of Contour will create a regular contour plot. A value of None will create a plot based solely on station data. Note: stations argument must also be 'True' for stations data plot. Default: Fill stations: Boolean value. If True with a grid argument value of 'Fill' or 'Contour', data value at point of stations is plotted on grid. If True with a grid argument value of 'None', station data will be plotted. If False, no station data will be plotted. Which stations are plotted is based upon scale of grid. If grid is None, stations must be True. Default: True levels: A list of values to use as levels for contours. Also, data below the first value will be masked. Default: An evenly spaced array from data min to data max. ''' #Checks stations and grid arguments for validity if not stations and not grid: raise ValueError('grid and stations arguments cannot both be empty.') proj = projs[str(iproj)] print "LCOlon = ", LCOlon, " UCOlon = ", UCOlon, " LCOlat = ", LCOlat, " UCOlat = ", UCOlat #set a "zoom_level" based on the span of lat and lon. zoom_level is used to determine how many stations #Would be plotted to reduce oversaturation if (UCOlon - LCOlon >= 50 or UCOlat - LCOlat >= 30): zoom_level = 0 elif (UCOlon - LCOlon >= 25 or UCOlat - LCOlat >= 15): zoom_level = 1 elif (UCOlon - LCOlon >= 12 or UCOlat - LCOlat >= 7): zoom_level = 2 elif (UCOlon - LCOlon >= 6 or UCOlat - LCOlat >= 3): zoom_level = 3 elif (UCOlon - LCOlon < 6 or UCOlat - LCOlat < 3): zoom_level = 4 logging.info("ZOOM LEVEL = " + str(zoom_level)) plt.figure(figsize=(14, 7)) #setup Basemap map mapplot = Basemap(llcrnrlon=LCOlon, llcrnrlat=LCOlat, urcrnrlon=UCOlon, urcrnrlat=UCOlat, lon_0=lon, lat_0=lat, resolution='l', projection=proj) mapplot.drawlsmask(ocean_color='#3333ff', resolution='h') mapplot.drawcoastlines() mapplot.drawstates() mapplot.drawcountries() mapplot.fillcontinents(color='grey', lake_color='#3333ff') parallels = np.arange(LCOlat, UCOlat + 1, (UCOlat - LCOlat) / 6) meridians = np.arange(LCOlon, UCOlon + 1, (UCOlon - LCOlon) / 6) mapplot.drawparallels(parallels, labels=[False, True, True, False], fmt='%.02f') mapplot.drawmeridians(meridians, labels=[True, False, False, True], fmt='%.02f') # Get X/Y values of lat/lons if grid is not None: lons, lats = mapplot.makegrid(data.shape[1], data.shape[0]) X, Y = mapplot(lons, lats) else: lons, lats = mapplot.makegrid(data.shape[0], data.shape[0]) X, Y = mapplot(lons, lats) # Create contour levels if not given in arguments if levels is None: levels = np.arange(np.min(data), np.max(data)) masked_data = np.ma.masked_array(data, data <= levels[0]) # Plot data as countours or filled contours based on 'grid' argument if grid == 'Fill': mapplot.contourf(lons, lats, masked_data, levels=levels, latlon=True) mapplot.colorbar(size='2.5%', pad='12%') elif grid == 'Contour': levels = levels[::4] C = mapplot.contour(lons, lats, data, levels=levels, latlon=True) plt.clabel(C, inline=True, fmt='%1.0f', fontsize=10, colors='k') # If contour is plotted and stations is True, will plot data values at locations of stations if grid == 'Fill' or grid == 'Contour': if stations: # Grab station table. stationfile = registry.__path__[0] + '/station.tbl' statfile = open(stationfile, 'r') statlons = [] statlats = [] # Create list of station lat and lons from station table for L in statfile: statlons.append(float( re.split('[WE]', re.split(':', L)[7])[1])) if 'W' in re.split(':', L)[7]: statlons[-1] = statlons[-1] * -1 statlats.append(float( re.split('[NS]', re.split(':', L)[6])[1])) if 'S' in re.split(':', L)[6]: statlats[-1] = statlats[-1] * -1 statlatlon = zip(statlats, statlons) plotstats = [] plotdata = [] # Set a skip value based on zoom_level statskip = 20 - 4 * zoom_level # Determine which stations are within plot bounds xmax = mapplot.xmax ymax = mapplot.ymax xmin = mapplot.xmin ymin = mapplot.ymin xs, ys = mapplot(statlons, statlats) xys = zip(xs, ys) xy_valid = [ xy for xy in xys if xy[0] > xmin and xy[0] < xmax and xy[1] > ymin and xy[1] < ymax ] for i, xy in enumerate(xy_valid): dists = np.sqrt((X - xy[0])**2 + (Y - xy[1])**2) idx = np.unravel_index(dists.argmin(), data.shape) datapoint = data[idx] if datapoint > levels[0]: plotstats.append(mapplot(xy[0], xy[1])) plotdata.append(datapoint) # Skip stations based on statskip and then plot value of data at location of station if (len(plotstats) % statskip == 0): plt.text(xy[0], xy[1], "{:.3f}".format(datapoint), horizontalalignment='center', verticalalignment='center', weight='bold', fontsize=8, color='w') # When grid is none. Data is treated as station data and plotted. elif grid is None: # Checks to be sure stations is True if stations: # Checks to be sure lat/lon of station locations is given if statlats is None or statlons is None: raise ValueError( 'latitude and/or longitude locations of stations are unknown' ) # Set a skip value based on zoom_level statskip = 20 - 4 * zoom_level xmax = mapplot.xmax ymax = mapplot.ymax xmin = mapplot.xmin ymin = mapplot.ymin xs, ys = mapplot(statlons, statlats) xys = zip(xs, ys) xy_valid, data_valid = [], [] # Determine which stations are within plot bounds for i, xy in enumerate(xys): if (xy[0] > xmin and xy[0] < xmax and xy[1] > ymin and xy[1] < ymax): xy_valid.append(xy), data_valid.append(data[i]) xy_sort = sorted(xy_valid, key=lambda tup: tup[0]) data_sort = [d for _, d in sorted(zip(xy_valid, data_valid))] dists = np.sqrt((np.array(zip(*xy_sort)[0][0:-1]) - np.array(zip(*xy_sort)[0][1:]))**2 + (np.array(zip(*xy_sort)[1][0:-1]) - np.array(zip(*xy_sort)[1][1:]))**2) xy_apart = [ xy[0] for xy in np.array(xy_sort)[np.argwhere(dists > .5)] ] data_apart = [ d[0] for d in np.array(data_sort)[np.argwhere(dists > .5)] ] # Plot station values on map, skipping values based on skip value for i, xy in enumerate(xy_apart[0::statskip]): plt.text(xy[0], xy[1], "{:.3f}".format(data_apart[i]), horizontalalignment='center', verticalalignment='center', weight='bold', fontsize=8, color='w') if not stations: raise ValueError('stations cannot be False while grid is None.') # Place title plt.title(title, fontsize=10) # If filename is given, then save image. Otherwise, show image if filename: plt.savefig(filename) plt.close() else: plt.show()