def getMDAreas(self,dx=20000,dy=20000, llcrnrlon=-119.2, llcrnrlat=23.15, urcrnrlon=-65.68, urcrnrlat=48.7): bmap = Basemap(projection="lcc", llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, resolution='l', lat_0=38.5, lat_1=38.5, lon_0=-97.0) from matplotlib.nxutils import points_inside_poly xs = np.arange(bmap.llcrnrx,bmap.urcrnrx + dx,dx) ys = np.arange(bmap.llcrnry,bmap.urcrnry + dy,dy) lon,lat,x_grid,y_grid = bmap.makegrid(xs.shape[0],ys.shape[0],returnxy=True) x, y = x_grid.flatten(), y_grid.flatten() points = np.vstack((x,y)).T nx = xs.shape[0] ny = ys.shape[0] areas = np.zeros((self.data.shape[0],)) for i in xrange(self.data.shape[0]): md_x,md_y = bmap(self.data['Lon'][i],self.data['Lat'][i]) poly_xy = np.vstack((md_x,md_y)).T areas[i] = np.nonzero(points_inside_poly(points,poly_xy))[0].shape[0] * dx * dy / 1000**2 return areas
def plot_brights(ax, path, star, regionList, goal=False): ''' Components of this routine: Projected brightness map Please note that this has been modified for use in diagnostic plots, there should really be a way to specify a windowNumber for real data ''' currentWindow = 0 ########################### # Make the brightness map # ########################### img = make_bright_image(star, regionList, currentWindow, goal=goal) plt.imsave(path + "temp.jpg", img, cmap='hot', vmin=0.85, vmax=1.15) plt.imshow(img, cmap='hot') #Create the plot bmap = Basemap(projection='moll', lon_0 = 0, ax=ax) bmap.warpimage(path + "temp.jpg", ax=ax) if goal: ax.set_title("Desired Map") else: ax.set_title("Average Map")
def main(): ds = nC.Dataset("../../grid_arctic.nc") data = ds.variables["tas"][:].squeeze() lon2d_nc = ds.variables["lon"][:] lat2d_nc = ds.variables["lat"][:] rplon, rplat = -115.850877297, 21.1216893478 lon_0 = -123.403723307 basemap = Basemap(projection="rotpole", o_lon_p=rplon, o_lat_p=rplat, lon_0=lon_0 - 180, llcrnrlon=lon2d_nc[-1, -1], llcrnrlat=lat2d_nc[-1, -1], urcrnrlon=lon2d_nc[0, 0], urcrnrlat=lat2d_nc[0, 0], resolution="l") import matplotlib.pyplot as plt im = basemap.etopo() x, y = basemap(lon2d_nc, lat2d_nc) # basemap.contourf(x, y, data) # basemap.colorbar() # basemap.drawcoastlines() # basemap.drawmeridians(np.arange(-180, 180, 30)) # basemap.drawparallels(np.arange(-90, 90, 40)) plt.show() pass
def _draw_basemap(self, proj_prop=None, drawparallels=True, vmin_polygons=None, vmax_polygons=None, **kwargs): """ """ if proj_prop is None: raise ValueError( 'No projection properties are given! Please modify or choose a different backend!') the_map = Basemap(ax=self.pax, **proj_prop) xm = self.x.timmean() Z = xm lon = self.x.lon lat = self.x.lat X, Y = the_map(lon, lat) self.im = the_map.pcolormesh(X, Y, Z, **kwargs) self.__basemap_ancillary(the_map, drawparallels=drawparallels) # add polygons to map if self.polygons is not None: if False: # individual polygons for p in self.polygons: self._add_single_polygon_basemap(the_map, p) else: # plot all polygons at once self._add_polygons_as_collection_basemap( the_map, vmin=vmin_polygons, vmax=vmax_polygons)
def draw_basic_map_of_toronto(axis): """Draw a basic map of Toronto. :param axis: where to draw the map :returns: Basemap with Toronto """ # These are the latitudes of the City of Toronto. # (Fiona can be better to find them, e.g., from the 'icitw_wgs84' Shapefile # below.) low_left_corner_longitude = -79.75 low_left_corner_latitude = 43.40 up_right_corner_longitude = -79.10 up_right_corner_latitude = 43.95 to_map = Basemap( llcrnrlon=low_left_corner_longitude, llcrnrlat=low_left_corner_latitude, urcrnrlon=up_right_corner_longitude, urcrnrlat=up_right_corner_latitude, ellps="WGS84", resolution="h", area_thresh=0.1, ax=axis, ) to_map.drawmapboundary(fill_color="white") return to_map
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 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_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 basemap_raster_mercator(lon, lat, grid, cmap = None): """ Render a raster in mercator projection. Locations with no values are rendered transparent. """ # longitude/latitude extent lons = (np.amin(lon), np.amax(lon)) lats = (np.amin(lat), np.amax(lat)) if cmap is None: cmap = mpl.cm.jet cmap.set_bad('w', 1.0) # construct spherical mercator projection for region of interest m = Basemap(projection='merc',llcrnrlat=lats[0], urcrnrlat=lats[1], llcrnrlon=lons[0],urcrnrlon=lons[1]) vmin,vmax = np.nanmin(grid),np.nanmax(grid) masked_grid = np.ma.array(grid,mask=np.isnan(grid)) fig = plt.figure(frameon=False) plt.axis('off') m.pcolormesh(lon,lat,masked_grid,latlon=True,cmap=cmap,vmin=vmin,vmax=vmax) str_io = StringIO.StringIO() plt.savefig(str_io,bbox_inches='tight',format='png',pad_inches=0,transparent=True) bounds = [ (lons[0],lats[0]),(lons[1],lats[0]),(lons[1],lats[1]),(lons[0],lats[1]) ] return str_io.getvalue(), bounds
def do_calc(LATLIMS_AM, LONLIMS_AM, indir, outdir): land_checker = Basemap() if land_checker.is_land(LATLIMS_AM, LONLIMS_AM): print "SOS! Sorry you have selected a land pixel!" pygame.mixer.music.load("SOS.midi") pygame.mixer.music.play() while pygame.mixer.music.get_busy(): # plot animado? time.sleep(1) else: dataAM = extract_series(LATLIMS_AM, LONLIMS_AM, indir) data_am = np.double(dataAM["Series"]) if all(np.isnan(a) for a in data_am): print "THE SOUND OF SILENCE. Also, BATMAN. Everything is Rest and NaN" pygame.mixer.music.load("Batman_song.midi") pygame.mixer.music.play() while pygame.mixer.music.get_busy(): # Anim plot? See Matplotlib.Animation time.sleep(1) else: am = get_music(data_am) music = pygame.mixer.Sound("Oc.midi") pygame.mixer.music.load("Oc.midi") pygame.mixer.music.play() anim = plot_animation( data_am, (u"Music from Lat = %.2f Lon = %.2f" % (dataAM["Lat"], dataAM["Lon"])), "serie.png", t_max=36000, ) # music.get_length())
def plot2D_parameter(self,grid,filename): fig = plt.figure(figsize=(figsize,figsize),dpi=self.cfg.map_dpi) Lon,Lat = np.meshgrid(self.lon, self.lat) map = Basemap(llcrnrlon=self.BB['lon'][0],llcrnrlat=self.BB['lat'][0],urcrnrlon=self.BB['lon'][1],urcrnrlat=self.BB['lat'][1], rsphere=(6378137.00,6356752.3142), resolution='l',projection='merc') x, y = map(Lon, Lat) cs2 = map.contourf(x,y,grid,512) plt.subplots_adjust(left=0.0, right=figsize, top=figsize, bottom=0.0) self.saveplot(plt,filename) plt.close() fig1 = plt.figure(figsize=(11,11),dpi=100) cb = map.colorbar(cs2,"bottom", size="5%", pad="100%") name = filename + '_legend.jpg' plt.savefig("maps/"+name, dpi=100,bbox_inches='tight',transparent=False) plt.close() list_of_maps_to_send.append("maps/"+name) img1 = Image.open("maps/"+name) w, h = img1.size box = (20, h-70, w-10, h-10) area = img1.crop(box) area.save("maps/"+name,'jpeg') plt.close()
def test_geographic_histogram(): tropics = UniformRandomPointSource() tropics.num_points = 100000 tropics.bbox_min = ( -180, -23.4378 ) tropics.bbox_max = ( 180, 23.4378 ) try: pyplot.figure() pyplot.subplot(111, aspect='equal') mymap = Basemap(projection='moll', lon_0=0, resolution='l') mymap.drawcoastlines(color='white', zorder=5) mymap.fillcontinents(color='black', lake_color='white') artists = geographic_histogram( mymap, tropics.points(), bbox_lowerleft=(-180, -90), bbox_upperright=(180, 90) ) pyplot.savefig('tracktable_geographic_histogram_test.png', figsize=(4, 4), dpi=150) return True except Exception, e: traceback.print_exc() return False
def draw_samples(self, n_samples, burnin=100, thin=10): if not self.kde_model: self.fit_kde() # pick starting point start_x = np.array([[0., 31.]]) # get region for restricting samples margin = 0.5 m = Basemap(llcrnrlon=self.uganda_data.LONGITUDE.min() - margin, llcrnrlat=self.uganda_data.LATITUDE.min() - margin, urcrnrlon=self.uganda_data.LONGITUDE.max() + margin, urcrnrlat=self.uganda_data.LATITUDE.max() + margin, resolution='l', area_thresh=10000) m.readshapefile("data/regions/UGA_adm0", "regions", drawbounds=True) for xy, info in zip(m.regions, m.regions): p = path.Path(xy) slice_samples, _ = SliceSampler.SliceSampler.mvslice(self.kde_model.pdf, start_x, sample_size=n_samples, burnin=burnin, thin=thin, confirm_region=p) # we get lat, long; we want x, y return np.fliplr(slice_samples)
def calculator(DATA, passed_staev, gr_x, npts, start, end, projection='robin', ray_coverage=False): global long_0 mymap = Basemap(projection=projection, lon_0=long_0, lat_0=0) nonzero = [] gr_y = gr_x grd = mymap.makegrid(gr_x, gr_y, returnxy=True) for i in range(start, end): print i, sys.stdout.flush() data, exist_flag = ray_density(passed_staev[i][4], passed_staev[i][5], passed_staev[i][0], passed_staev[i][1], dt=passed_staev[i][2], gr_x=gr_x, gr_y=gr_y, npts=npts, projection=projection, ray_coverage=ray_coverage) if not i == end-1: if not exist_flag: continue if DATA is None: DATA = data.copy() else: DATA += data nonzero_tmp = np.nonzero(data) for j in range(len(nonzero_tmp[0])): nonzero.append((nonzero_tmp[0][j], nonzero_tmp[1][j])) fi = open('MAP_OUTPUT/DATA-' + str(start), 'w') pickle.dump(DATA, fi) fi.close() fi = open('MAP_OUTPUT/nonzero-' + str(start), 'w') pickle.dump(nonzero, fi) fi.close()
def run(FILE_NAME): with h5py.File(FILE_NAME, mode='r') as f: name = '/Grid/IRprecipitation' data = f[name][:] units = f[name].attrs['units'] _FillValue = f[name].attrs['_FillValue'] data[data == _FillValue] = np.nan data = np.ma.masked_where(np.isnan(data), data) # Get the geolocation data latitude = f['/Grid/lat'][:] longitude = f['/Grid/lon'][:] m = Basemap(projection='cyl', resolution='l', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(-90, 91, 45)) m.drawmeridians(np.arange(-180, 180, 45), labels=[True,False,False,True]) m.pcolormesh(longitude, latitude, data.T, latlon=True) cb = m.colorbar() cb.set_label(units) basename = os.path.basename(FILE_NAME) plt.title('{0}\n{1}'.format(basename, name)) fig = plt.gcf() # plt.show() pngfile = "{0}.py.png".format(basename) fig.savefig(pngfile)
def render_nextbus_dataframe(route, nextbus_df): """Plots the NextBus Vehicle Location's Panda Data frame to a Matplotlib and Basemap Geospatial image.""" min_long = min(nextbus_df.lon) min_lat = min(nextbus_df.lat) max_long = max(nextbus_df.lon) max_lat = max(nextbus_df.lat) bmap = Basemap(llcrnrlon=min_long, llcrnrlat=min_lat, urcrnrlon=max_long, urcrnrlat=max_lat, ellps='WGS84', resolution='h', area_thresh=1000) bmap.drawmapboundary(fill_color='white') bmap.scatter(nextbus_df.lon, nextbus_df.lat, marker='d', edgecolor='g', facecolor='g', alpha=0.5) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.axis([min_long, max_long, min_lat, max_lat]) plt.title('NextBus Vehicle Locations for route {}'.format(route)) plt.grid(True) # plt.legend(loc='lower center') plt.savefig('nextbus_vehicle_locations.png', fmt='png', dpi=600) # plt.show() # Other components (like GMaps plotting) will also use Matplotlib, so # it's better to clear the figure that Matplotlib generated plt.clf()
class Mapper: def __init__(self, state): with open(state_boundries_file_loc) as f: for line in f: line = line.rstrip().split(',') if line[0].lower() == state.lower(): ur_lon, ll_lat = float(line[1]), float(line[3]) ll_lon, ur_lat = float(line[2]), float(line[4]) center_lon = ll_lon + ur_lon if math.copysign(1, ll_lon) != math.copysign(1, ur_lon): center_lon = -180 + center_lon else: center_lon = center_lon / 2 center_lat = (ll_lat + ur_lat) / 2 self.m = Basemap(llcrnrlon = ll_lon, llcrnrlat = ll_lat, urcrnrlon = ur_lon, urcrnrlat = ur_lat, projection = 'lcc', lat_1 = center_lat, lon_0 = center_lon) def setBorders(self): self.m.readshapefile(states_shapefile_loc, 'states', drawbounds = True) def plotPoint(self, lat, lon): self.m.plot(lat, lon, latlon=True, marker='o', color='m') def displayMap(self): plt.show()
def prepare_map0(coordinates, res): m = Basemap(llcrnrlon=coordinates[0], llcrnrlat=coordinates[2], urcrnrlon=coordinates[1], urcrnrlat=coordinates[3], resolution=res) fig = plt.figure() ax = plt.subplot(111) m.ax = ax return fig, m, ax
def plot(self): ''' plot some random stuff ''' # random data '''data = [random.random() for i in range(2)] # create an axis ax = self.figure.add_subplot(111) # discards the old graph ax.hold(False) # plot data ax.plot(data, '*-')''' m = Basemap(projection='robin',lon_0=0,resolution='c')#,latlon=True) m.bluemarble(scale=0.2) for friend in rpc.bridge.getFriendList(): print '' pd = rpc.bridge.getPeerDetails(friend) print pd['name'] print pd['extAddr'] ld = gi.record_by_addr(pd['extAddr']) print ld if ld: print ld['latitude'],ld['longitude'] x, y = m(ld['longitude'],ld['latitude']) #m.scatter(x, y,30,marker='o',color='k') plt.plot(x, y,'ro') plt.text(x,y,pd['name'],fontsize=9, ha='center',va='top',color='r', bbox = dict(boxstyle="square",ec='None',fc=(1,1,1,0.5))) #plt.text(x,y,pd['name'],fontsize=14,fontweight='bold', # ha='center',va='center',color='r') # refresh canvas self.canvas.draw()
def map_rupture(rupture): """ Method for making a simple representation of a Rupture instance. This method draws the surface projection of the rupture on a map. Args: rupture: A Rupture instance. """ rlats = rupture.lats rlons = rupture.lons minbufx = 0.2 minbufy = 0.2 lat1 = np.nanmin(rupture.lats) lat2 = np.nanmax(rupture.lats) dlat = lat2 - lat1 bufy = np.max([dlat/2, minbufy]) lon1 = np.nanmin(rupture.lons) lon2 = np.nanmax(rupture.lons) dlon = lon2 - lon1 bufx = np.max([dlon/2, minbufx]) m = Basemap(llcrnrlat=lat1-bufy,urcrnrlat=lat2+bufy, llcrnrlon=lon1-bufy,urcrnrlon=lon2+bufy) m.arcgisimage(service='World_Shaded_Relief', xpixels = 500, verbose= True) x, y = m(rlons, rlats) m.plot(x, y, 'r')
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 get_basemap(): # Lambert Conformal map of lower 48 states m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49, projection='lcc',lat_1=33,lat_2=45,lon_0=-95) shp_info = m.readshapefile('maps/st99_d00','states',drawbounds=True) # print(shp_info) return m
def drawMap(self, var, strMonth): m = Basemap( projection = 'cyl',llcrnrlon = p.lon0, \ llcrnrlat = self.lat0, urcrnrlon = self.lon0 + self.dxy * self.nX,\ urcrnrlat = self.lat0 + self.dxy * self.nY, resolution='i') var = np.flipud( np.ma.masked_array( var, var >= -0.2) ) var = np.ma.masked_array( var, var < -10) levels = [ -0.1, -0.3, -0.5, -0.7, -0.9] im = m.pcolormesh( self.longitude, self.latitude,var, vmin = -0.9, vmax = 0.1) m.drawmeridians(np.arange( -10.0, 30, 5), labels = [1,0,0,1], fontsize = 10, rotation = 20) m.drawparallels(np.arange( 30.0, 60.0, 5), labels = [1,0,0,1], fontsize = 10, rotation = 20) m.drawcoastlines() m.drawcountries() plt.colorbar(im, orientation = 'vertical' , pad = 0.05 ) plt.title( "CorrCoeff for month " + strMonth) plt.savefig( "corrCoeff" + strMonth + ".png", orientation = "landscape") plt.clf()
def main(): unusable_name = 'unusable_%s.csv' % AREA unusable_data = csv.writer(open(unusable_name,'wb')) for i in range(2004,2013): m = Basemap(projection='merc',resolution=None,llcrnrlat=small_lat, \ urcrnrlon=big_long,urcrnrlat=big_lat,llcrnrlon=small_long) fig = plt.figure(figsize=(11,11)) ax = plt.subplot(111) m.drawmapboundary(fill_color='#1B1B1B') crime_dictionary = get_crimes(i,m,unusable_data) plot_crimes(crime_dictionary['nonviolent'],m) plot_crimes_violent(crime_dictionary['violent'],m) plot_crimes_murder(crime_dictionary['murder'],m) plot_buildings(m) plot_streets(m) label_streets() output_file_name = '%s/%s_%s.png' % (AREA,AREA,str(i)) ax.text(0.01,0.01,'https://github.com/oneschirm',color='white',\ fontsize=12,transform=ax.transAxes) ax.text(0.9, 0.01, str(i),color='white', fontsize=20,transform=ax.transAxes) plt.savefig(output_file_name, dpi=150,bbox_inches='tight')
def ray_density(lat1, lon1, lat2, lon2, dt=1, gr_x=360, gr_y=180, npts=180, projection='robin', ray_coverage=False): ''' Create the DATA array which contains the info for ray density ''' global long_0 mymap = Basemap(projection=projection, lon_0=long_0, lat_0=0) #npts=max(gr_x, gr_y) # grd[2]: longitude # grd[3]: latitude grd = mymap.makegrid(gr_x, gr_y, returnxy=True) lons, lats = mymap.gcpoints(lon1, lat1, lon2, lat2, npts) dist = locations2degrees(lat1, lon1, lat2, lon2) bap = int((dist - 97.0)*npts/dist)/2 midlon = len(lons)/2 midlat = len(lats)/2 lons = lons[midlon-bap:midlon+1+bap] lats = lats[midlat-bap:midlat+1+bap] data = np.zeros([len(grd[2]), len(grd[3])]) for i in range(len(lons)): xi, yi = point_finder(lons[i], lats[i], grd) # first one is latitude and second longitude try: #data[yi][xi] = dt/float(dist-97.0) data[yi][xi] += dt/len(lons) except Exception, e: print e
def arc_map(region=[-33.7, 149.4, -31.8, 151.8], res=1000, service='World_Topo_Map',epsg=4326, resolution='h',projection='mill'): ''' Create and return the thingy Inputs: region: [bot,left,top,right] service= one of 'World_Imagery', or 'World_Topo_Map' Imagery is more like blue marble, with no site labels Topo has inbuilt site labels, which render based on the resolution -> higher res for more zoomed in image. epsg: tell arcGIS where to pull image from, affects the image orientation Use 4326 for Sydney centric maps Use 3577 for Australia centred view ''' # set up basemap projection # epsg is used to inform basemap that we will pull an image from ArcGIS servers # epsg=28355 does not work... # 3577 is centred at middle of Australia... # 4326 works for East Australia! m = Basemap(projection=projection, epsg=epsg, resolution=resolution, llcrnrlon=region[1], llcrnrlat=region[0], urcrnrlon=region[3], urcrnrlat=region[2]) # Download backgroud to basemap's projection. #m.arcgisimage(service='World_Topo_Map', xpixels=res, verbose=True) m.arcgisimage(server='http://server.arcgisonline.com/ArcGIS', service=service, xpixels=res, verbose=True) return m
def drawMap(report): entries = get_site_status(report) # entries = {'unl.edu': [276, 0, 246, 0], 'desy.de': [107, 0, 0, 0], 'fnal.gov': [16, 0, 294, 0], 'N/A': [0, 0, 0, 0]} posList = get_positions(entries) #bounds = [(-60, -120), (60, 120)] #bounds = [(30, -10), (60, 40)] bounds = get_bounds(posList, margin = 10) matplotlib.pyplot.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0) fig = matplotlib.pyplot.figure(figsize=(12, 6)) ax = matplotlib.pyplot.subplot(111) m = Basemap(projection='cyl', lat_0=0, lon_0=0, llcrnrlon=bounds[0][0], llcrnrlat=bounds[0][1], urcrnrlon=bounds[1][0], urcrnrlat=bounds[1][1]) map_positions(m, posList) #posList = remove_all_overlap(posList) #print posList m.bluemarble() for pos in posList: draw_pie(ax, pos['info'], (pos['x'], pos['y']), pos['size']) ax.text(pos['x']+5, pos['y']+5, pos['site'], color='white', fontsize=8) fig.savefig(os.path.expanduser('~/map.png'), dpi=300)
def create_map(): poverty_data, error = world_bank_api.most_recent_poverty_data() if error is not None: print(error) return poverty_data = utils.dictify_list_of_dicts(poverty_data, 'country_code') world_map = Basemap() world_map.readshapefile('borders', 'countries') country_to_color, country_names = decide_colors_and_countries(world_map, poverty_data) axes = plt.gca() # get current axes instance for nshape, seg in enumerate(world_map.countries): country_name = country_names[nshape] if country_name not in country_to_color: print('could not find: ' + country_name) continue color = country_to_color[country_name] poly = Polygon(seg, facecolor=color, edgecolor=color) axes.add_patch(poly) add_legend() fig = plt.gcf() fig.set_size_inches(30, 15) plt.axis('off') fig.savefig('countries_by_poverty_rate_world_bank_data.png', dpi=100, bbox_inches='tight', pad_inches=0)
def p_Zmap(event_no, min_dist, max_dist, basin_width, basin, CI_only): from obspy import UTCDateTime from obspy import Stream, Trace from obspy import read from obspy.geodetics import gps2dist_azimuth import numpy as np import os os.environ["PROJ_LIB"] = "/Users/vidale/opt/anaconda3/share/proj" from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import time import sys # don't show any warnings import warnings if not sys.warnoptions: warnings.simplefilter("ignore") warnings.filterwarnings("ignore") start_time_wc = time.time() # for timing code operation #%% Find event details for origin time, lat, lon ev_file = '/Users/vidale/Documents/PyCode/LAB/ricardo/event_list.txt' file_ev = open(ev_file, 'r') for line in file_ev: # pull numbers off the rest of the lines split_line = line.split() event = split_line[0] if event == event_no: ev_lat = float(split_line[3]) ev_lon = float(split_line[2]) t1 = UTCDateTime(split_line[5]) date_label = split_line[5][0:10] year1 = split_line[5][0:4] print(event_no + str(t1) + ' ' + date_label + ' ' + year1 + ' ' + str(ev_lat) + ' ' + str(ev_lon)) #%% Find event details for origin time, lat, lon badt_file = '/Users/vidale/Documents/PyCode/LAB/ricardo/Mseed_data/bad_trace.txt' file_badt = open(badt_file, 'r') badt_lines = file_badt.readlines() badt_event = [] badt_station = [] badt_compo = [] for line in badt_lines: # pull numbers off all the lines split_line = line.split() badt_event.append(split_line[0]) badt_station.append(split_line[1]) badt_compo.append(split_line[2]) print(str(len(badt_event)) + ' bad traces in list') #%% Open station location file sta_file = '/Users/vidale/Documents/PyCode/LAB/ricardo/ricardo_stations.txt' file_st = open(sta_file, 'r') line = file_st.readline() # read first line to skip header information lines = file_st.readlines() print(str(len(lines)) + ' stations read from ' + sta_file) # Load station coords into arrays, many more stations than used station_index = range(len(lines)) st_num = [] st_netw = [] st_name = [] st_dist = [] st_az = [] st_baz = [] st_lat = [] st_lon = [] for line in lines: split_line = line.split() st_num.append(split_line[0]) st_netw.append(split_line[2]) st_name.append(split_line[3]) st_lat.append(split_line[4]) st_lon.append(split_line[5]) distance = gps2dist_azimuth(ev_lat, ev_lon, float( split_line[4]), float(split_line[5])) # Get traveltime and azimuth # print('Event ' + str(ev_lat) + ' ' + str(ev_lon) + ' station ' + split_line[4] + ' ' + split_line[5] + ' distance ' + str(distance[0])) st_dist.append(distance[0] / 1000.) # azimuth st_az.append(distance[1]) # azimuth st_baz.append(distance[2]) # back-azimuth print('number of stations in list is ' + str(len(st_num)) + ' or ' + str(station_index)) # print('lat is ' + str(st_lat[807]) + ', lon is ' + str(st_lon[807]) + ' distance is ' + str(st_dist[807])) #%% Load data and synthetic waveforms st_datZ = Stream() nstart = '/Users/vidale/Documents/PyCode/LAB/ricardo/Mseed_data/rot/vz_' fname_datZ = nstart + event_no + '.mseed' st_datZ = read(fname_datZ) print('1st data trace has : ' + str(len(st_datZ[0].data)) + ' time pts ') print('Z has ' + str(len(st_datZ)) + ' traces') print('Z trace starts at ' + str(st_datZ[0].stats.starttime) + ', event at ' + str(t1)) #%% Reject data on bad trace list, either individual components or A for all components st_datZ_good = Stream() for tr in st_datZ: # examine traces one by one do_write = 1 for ii in range(len(badt_event)): if event_no == badt_event[ii] and tr.stats.station == badt_station[ ii]: # find station in inventory if badt_compo[ii] == 'Z' or badt_compo[ii] == 'A': do_write = 0 if do_write == 1: st_datZ_good += tr print('After rejecting labeled bad traces ones, Z data has ' + str(len(st_datZ_good)) + ' traces') #%% Select data and syn # select data by distance (and azimuth?), and cull synthetics to match data st_datZ_select = Stream() for tr in st_datZ_good: # examine traces one by one if tr.stats.network == 'CI' or CI_only == False: for ii in range( len(st_name)): # find matching entry in station roster if (tr.stats.network == st_netw[ii] and tr.stats.station == st_name[ii]): # find station in inventory if st_dist[ii] < max_dist: # exclude stations too far away # basin is roughly within 15 km of these 3 stations distance = gps2dist_azimuth( 33.99053, -118.36171, float(st_lat[ii]), float(st_lon[ii])) # station BHP dist1 = distance[0] / 1000 # convert m to km distance = gps2dist_azimuth( 33.88110, -118.17568, float(st_lat[ii]), float(st_lon[ii])) # station LTP dist2 = distance[0] / 1000 distance = gps2dist_azimuth( 33.80776, -117.98116, float(st_lat[ii]), float(st_lon[ii])) # station BRE dist3 = distance[0] / 1000 # print(tr.stats.station + ' ' + str(dist1) + ' ' + str(dist2) + ' ' + str(dist3)) if basin == False or (dist1 < basin_width) or ( dist2 < basin_width ) or ( dist3 < basin_width ): # keep stations only within X km of basin axis # print('selected: ' + tr.stats.station) tr.stats.distance = st_dist[ii] tr.stats.stla = st_lat[ii] tr.stats.stlo = st_lon[ii] st_datZ_select += tr print('After distance and basin culling') print('now Z has ' + str(len(st_datZ_select)) + ' traces') #%% Plot map # make basemap figure plt.figure(figsize=(15, 10)) # setup mercator map projection. m = Basemap(projection='merc', llcrnrlon=-118.8, llcrnrlat=33.5, urcrnrlon=-117.5, urcrnrlat=34.6, epsg=4269) # add imagery layer #http://server.arcgisonline.com/arcgis/rest/services -- EPSG Number for America is 4269 (see above) m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels=2000, verbose=True) # plot stations for tr in st_datZ_select: # m.drawgreatcircle(stlon,stlat,ev_lon,ev_lat,linewidth=1,color='b') xx, yy = m(float(tr.stats.stlo), float(tr.stats.stla)) m.scatter(xx, yy, marker="*", s=150, c="b", edgecolors="k", alpha=1) # plot the event print('E lat and lon: ' + str(ev_lat) + ' ' + str(ev_lon)) xx, yy = m(ev_lon, ev_lat) m.scatter(xx, yy, marker="*", s=200, c="r", edgecolors="k", alpha=1) plt.title('Event ' + str(event_no) + ' Zmap') plt.show() elapsed_time_wc = time.time() - start_time_wc print('Plotting map took ' + str(elapsed_time_wc) + ' seconds') os.system('say "Done"')
plt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']}) ### Set limits for contours and colorbars if varnames[0] == 'U10': limit = np.arange(-5,5.1,0.5) barlim = np.arange(-5,6,1) elif varnames[0] == 'Z30': limit = np.arange(-100,100.1,10) barlim = np.arange(-100,101,50) fig = plt.figure() var = ficthitpos pvar = testp ax1 = plt.subplot(111) m = Basemap(projection='ortho',lon_0=0,lat_0=89,resolution='l', area_thresh=10000.) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) pvar,lons_cyclic = addcyclic(pvar, lon) pvar,lons_cyclic = shiftgrid(180.,pvar,lons_cyclic,start=False) m.drawmapboundary(fill_color='white',color='dimgray',linewidth=0.7) cs = m.contourf(x,y,var,limit,extend='both') cs1 = m.contourf(x,y,pvar,colors='None',hatches=['....'], linewidths=0.4) m.drawcoastlines(color='dimgray',linewidth=0.8)
def calcfaixa(vel, data, star, dist, ca, pa, tamanho, step, erro=None, ring=None, atm=None): vec = np.arange(0, int(8000/(np.absolute(vel.value))), step) g = np.sort(np.concatenate((vec,-vec[1:]), axis=0)) latlon = {'clat':{'lon':[], 'lat':[], 'lab': [], 'x': [], 'y': [], 'labx': []}, 'lats': {'lon':[], 'lat':[], 'lon2':[], 'lat2':[], 'x': [], 'y': [], 'x2':[], 'y2':[]}} if not erro == None: latlon['erro'] = {'lon': [], 'lat': [], 'lon2':[], 'lat2':[]} err = erro*u.mas errd = (dist.to(u.km)*err.to(u.rad)).value*u.km if not ring == None: latlon['ring'] = {'lon': [], 'lat': [], 'lon2':[], 'lat2':[]} if not atm == None: latlon['atm'] = {'lon': [], 'lat': [], 'lon2':[], 'lat2':[]} paplus = ((pa > 90*u.deg) and pa - 180*u.deg) or pa for delt in g: deltatime = delt*u.s datas1 = data + TimeDelta(deltatime) datas1.delta_ut1_utc = 0 lon = star.ra - datas1.sidereal_time('mean', 'greenwich') m = Basemap(projection='ortho',lat_0=star.dec.value,lon_0=lon.value,resolution=None) a, b = m(lon.value, star.dec.value) a = a*u.m b = b*u.m dista = (dist.to(u.km)*ca.to(u.rad)).value*u.km ax = a + dista*np.sin(pa) + (deltatime*vel)*np.cos(paplus) by = b + dista*np.cos(pa) - (deltatime*vel)*np.sin(paplus) ax2 = ax - tamanho/2*np.sin(paplus) by2 = by - tamanho/2*np.cos(paplus) ax3 = ax + tamanho/2*np.sin(paplus) by3 = by + tamanho/2*np.cos(paplus) clon1, clat1 = m(ax.value, by.value, inverse=True) if delt == 0: latlon['clat']['cxy'] = [ax.value, by.value] if clon1 < 1e+30: latlon['clat']['lon'].append(clon1) latlon['clat']['lat'].append(clat1) latlon['clat']['lab'].append(datas1.iso) else: latlon['clat']['x'].append(ax.value) latlon['clat']['y'].append(by.value) latlon['clat']['labx'].append(datas1.iso) lon1, lat1 = m(ax2.value, by2.value, inverse=True) if lon1 < 1e+30: latlon['lats']['lon'].append(lon1) latlon['lats']['lat'].append(lat1) else: latlon['lats']['x'].append(ax2.value) latlon['lats']['y'].append(by2.value) lon2, lat2 = m(ax3.value, by3.value, inverse=True) if lon2 < 1e+30: latlon['lats']['lon2'].append(lon2) latlon['lats']['lat2'].append(lat2) else: latlon['lats']['x2'].append(ax3.value) latlon['lats']['y2'].append(by3.value) if not erro == None: ax2 = ax - errd*np.sin(paplus) by2 = by - errd*np.cos(paplus) ax3 = ax + errd*np.sin(paplus) by3 = by + errd*np.cos(paplus) lon1, lat1 = m(ax2.value, by2.value, inverse=True) if lon1 < 1e+30: latlon['erro']['lon'].append(lon1) latlon['erro']['lat'].append(lat1) lon2, lat2 = m(ax3.value, by3.value, inverse=True) if lon2 < 1e+30: latlon['erro']['lon2'].append(lon2) latlon['erro']['lat2'].append(lat2) if not ring == None: rng = ring*u.km ax2 = ax - rng*np.sin(paplus) by2 = by - rng*np.cos(paplus) ax3 = ax + rng*np.sin(paplus) by3 = by + rng*np.cos(paplus) lon1, lat1 = m(ax2.value, by2.value, inverse=True) if lon1 < 1e+30: latlon['ring']['lon'].append(lon1) latlon['ring']['lat'].append(lat1) lon2, lat2 = m(ax3.value, by3.value, inverse=True) if lon2 < 1e+30: latlon['ring']['lon2'].append(lon2) latlon['ring']['lat2'].append(lat2) if not atm == None: atmo = atm*u.km ax2 = ax - atmo*np.sin(paplus) by2 = by - atmo*np.cos(paplus) ax3 = ax + atmo*np.sin(paplus) by3 = by + atmo*np.cos(paplus) lon1, lat1 = m(ax2.value, by2.value, inverse=True) if lon1 < 1e+30: latlon['atm']['lon'].append(lon1) latlon['atm']['lat'].append(lat1) lon2, lat2 = m(ax3.value, by3.value, inverse=True) if lon2 < 1e+30: latlon['atm']['lon2'].append(lon2) latlon['atm']['lat2'].append(lat2) return latlon
def geramapa(star, data, title, labelx, nameimg, mapstyle='1', resolution='l', centermap=None, lats=None, erro=None, ring=None, atm=None, clat=None, sitearq='sites.dat', fmt='png', dpi=100, mapsize=None, cpoints=60, off=0): lon = star.ra - data.sidereal_time('mean', 'greenwich') center_map = EarthLocation(lon.value, star.dec.value) fig = plt.figure(figsize=(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).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=-3500000.,llcrnry=-3717000.,urcrnrx=500000.,urcrnry=-413000.) kx = fig.add_axes([0.105,0.1,0.894,0.894]) kx.set_rasterization_zorder(1) m.nightshade(data.datetime, alpha=0.3, zorder=0.5) ## desenha a sombra da noite m.drawcoastlines(linewidth=0.5) ## desenha as linhas da costa m.drawcountries(linewidth=0.5) ## desenha os paises # m.drawstates(linewidth=0.5) ## Desenha os estados m.drawmeridians(np.arange(0,360,30)) ## desenha os meridianos m.drawparallels(np.arange(-90,90,30)) ## desenha os paralelos m.drawmapboundary() ## desenha o contorno do mapa mapsstyle = {'STE' : 'blue', 'JPL' : 'red', '22fev' : 'black', '03mar' : 'green'} pontos = {'STE' : '-', 'JPL' : '--', '22fev' : '-.', '03mar' : ':'} style = {'1': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'blue', 'rncolor':'blue', 'atcolor':'blue', 'outcolor':'red'}, '2': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}, '3': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}, '4': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}, '5': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}} 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() for tipo in ['STE', 'JPL', '22fev', '03mar']: # if not lats == None: xs, ys = m(lats[tipo][0], lats[tipo][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=mapsstyle[tipo]) xt, yt = m(lats[tipo][2], lats[tipo][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=mapsstyle[tipo]) # m.plot(lats[tipo][4], lats[tipo][5], color=mapsstyle[tipo], zorder=-0.2) # m.plot(lats[tipo][6], lats[tipo][7], color=mapsstyle[tipo], zorder=-0.2) # else: # m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2) # m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2) # 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, lab = [], [], [] cp = Time(clat[tipo][5], format='iso') vec = np.arange(0, (cp[-1] - data).sec, cpoints) vec = np.sort(np.concatenate((vec,-vec[1:]), axis=0))*u.s # for i in vec: # g = data + TimeDelta(i) + TimeDelta(off*u.s) # if g.iso in clat[tipo][2]: # a = np.where(np.array(clat[tipo][2]) == g.iso) # x, y = m(np.array(clat[tipo][0])[a], np.array(clat[tipo][1])[a]) # xc.append(x) # yc.append(y) # lab.append(g.iso.split()[1][0:8]) # elif g.iso in clat[tipo][5]: # a = np.where(np.array(clat[tipo][5]) == g.iso) # xc.append(np.array(clat[tipo][3])[a]) # yc.append(np.array(clat[tipo][4])[a]) # lab.append(g.iso.split()[1][0:8]) # else: # if len(clat[tipo][2]) == 0: # a = [0] # else: # co = Time(clat[tipo][2], format='iso') # a = np.argsort(np.absolute(co - g))[0:2] # if 0 not in a and len(co)-1 not in a: # b = np.absolute((co[a] - g).sec) # x, y = m(np.array(clat[tipo][0])[a], np.array(clat[tipo][1])[a]) # xc.append(np.sum(x*(1/b))/np.sum(1/b)) # yc.append(np.sum(y*(1/b))/np.sum(1/b)) # lab.append(g.iso.split()[1][0:8]) # else: # co = Time(clat[tipo][5], format='iso') # a = np.argsort(np.absolute(co - g))[0:2] # b = np.absolute((co[a] - g).sec) # xc.append(np.sum(np.array(clat[tipo][3])[a]*(1/b))/np.sum(1/b)) # yc.append(np.sum(np.array(clat[tipo][4])[a]*(1/b))/np.sum(1/b)) # lab.append(g.iso.split()[1][0:8]) x, y = m(np.array(clat[tipo][0]), np.array(clat[tipo][1])) m.plot(x, y, color=mapsstyle[tipo])#, markersize=mapsize[0].value*8/46) m.plot(clat[tipo][6][0], clat[tipo][6][1], 'o', color=mapsstyle[tipo], markersize=mapsize[0].value*10/46)#, marker=(2,0,165)) # print clat[6][0], clat[6][1] # for label, axpt, bypt in zip(lab, xc, yc): # plt.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold') # 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') if os.path.isfile(sitearq) == True: sites = np.loadtxt(sitearq, dtype={'names': ('lat', 'lon', 'alt', 'nome'), 'formats': ('f8', 'f8', 'f8', 'S30')}) xpt,ypt = m(sites['lon'],sites['lat']) m.plot(xpt,ypt,'go') # 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) # m.plot(5771363.97687, 4156344.21479, '+', color='black', markersize=mapsize[0].value*20/46) #5771363.97687 4156344.21479 # 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') # e,w = m(center_map.longitude.value,center_map.latitude.value) e, w = clat['STE'][6][0], clat['STE'][6][1] plt.errorbar(e - 50000, w + 1250000, yerr=75000, color='black') plt.errorbar(e - 50000, w + 1000000, yerr=98000, color='black') plt.text(e, w + 1225000, 'Himalia Diameter (150 km)', fontsize=sizel) plt.text(e, w + 975000, 'Estimated Error (60 mas)', fontsize=sizel) plt.xscale(u'linear') plt.xticks(np.arange(-2500000, 1500000, 500000) + e, np.arange(-2.5, 1.5, 0.5), fontsize=sizel) plt.xlabel(r'$\times 10^{3}$(km)', fontsize=sizel) plt.yscale(u'linear') plt.yticks(np.arange(-1500000, 2000000, 500000) + w, np.arange(-1.5, 2.0, 0.5), fontsize=sizel)#, rotation=90) plt.ylabel(r'$\times 10^{3}$(km)', fontsize=sizel) plt.savefig('HIMALIA.{}'.format(fmt), format=fmt, dpi=dpi, bbox_inches='tight') print 'Gerado: HIMALIA.{}'.format(fmt) plt.clf()
# . VISULIZATION from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt from pylab import rcParams %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
# create time vector with dt_map spacing at_bin = np.arange( dPar['tmin'], 2018, dPar['dt_map']) for i in range( at_bin.shape[0]-1): t1, t2 = at_bin[i], at_bin[i+1] #TODO: select earthquakes between t1 and t2 use np.logical_and sel_eq = np.logical_and( mSeis[0] >= t1, mSeis[0] < t2) #TODO: select wells with start dates before t1 ??? print t1, t2, 'No. earthquakes', sel_eq.sum(), 'No. of wells', sel_we.sum() ### create basemap object plt.figure(2) plt.cla() ax2 = plt.subplot(111) lon_0, lat_0 = .5*( dPar['xmin']+dPar['xmax']), .5*( dPar['ymin']+dPar['ymax']) m = Basemap(llcrnrlon = dPar['xmin'], urcrnrlon=dPar['xmax'], llcrnrlat = dPar['ymin'], urcrnrlat=dPar['ymax'], lon_0 = lon_0, lat_0 = lat_0 resolution = 'l', projection=dPar['projection'], ) #TODO: draw state boundaries ??? #TODO: convert spherical to 2D coordinate system using basemap ??? ??? # TODO: plot seismicity and well locations ??? ??? # x and y labels
# In[86]: # event lat/lon source_lat = event.preferred_origin().latitude source_lon = event.preferred_origin().longitude print("source: lat/lon = ",source_lat,source_lon) # epicentral distance plot from mpl_toolkits.basemap import Basemap fig = plt.figure(figsize=(20,10)) # Mercator: 'merc', Orthographic: 'ortho' #m = Basemap(projection='moll',lat_0=source_lat,lon_0=source_lon,resolution='l') # centered at Greenwich meridian m = Basemap(projection='cyl',lat_0=0,lon_0=0,resolution='l') # limit lon to range [-180,180] if source_lon < -180.0: source_lon += 360.0 if source_lon > 180.0: source_lon -= 360.0 # epicentral distances to source location lats = np.linspace(-90, 90, num=100) lons = np.linspace(-180, 180, num=200) # epicentral distance def epi_distance_np(lon1,lat1,source_lon=0.0,source_lat=0.0): # calculates epicentral distance towards source position (in degrees) # converts to radians radlon0 = np.radians(source_lon) radlat0 = np.radians(source_lat)
grbsPT.close() # close the grib file. grbsUV.close() # close the grib file. grbsVO.close() # close the grib file. # In[58]: ### calculating 925-850 hPa layer-averaged cyclonic relative vorticity (every 0.5 x10^-4 s-1) # all three layers divided by number of layers rel_vort = (RV[850] + RV[900] + RV[925]) / 3 # arithmetric mean rel_vort = ndimage.filters.gaussian_filter(rel_vort, sigma=2) # In[75]: # Plotting data on a map (Example Gallery) https://matplotlib.org/basemap/users/examples.html m = Basemap(projection='merc', llcrnrlon=-80., urcrnrlon=50., llcrnrlat=15., urcrnrlat=75., resolution='l') # In[60]: ### Latitudes, Longitudes and shiftgrid plonsPT, platsPT, PT = shiftgrb(grbPT, PT) plonsVO, platsVO, rel_vort = shiftgrb(grbVO, rel_vort) plonsU, platsU, wind_u = shiftgrb(grbUV, wind_u) plonsV, platsV, wind_v = shiftgrb(grbUV, wind_v) # In[61]: ### Dates for plotting
x, y = np.meshgrid(x, y) lon_min = np.min(lon, axis=None) lon_max = np.max(lon, axis=None) lat_min = np.min(lat, axis=None) lat_max = np.max(lat, axis=None) #reflat=(lat_max + lat_min)/2, #reflon=(lon_max + lon_min)/2, height = (ydim - 1) * dy #+10*1000 width = (xdim - 1) * dx #+10*1000 m = Basemap( llcrnrlon=lon_min, llcrnrlat=lat_min, urcrnrlon=lon_max, urcrnrlat=lat_max, projection='merc', resolution='h', area_thresh=1000., ) parallels = np.arange(round(lat_min, 0), lat_max + 2, 2) meridians = np.arange(round(lon_max, 0), lon_min - 2, -2) s1 = np.ma.empty(u.shape) #[ydim,xdim]) for t in range(u.shape[0]): dudy, dudx = np.gradient(u[t, :, :], dy, dx) dvdy, dvdx = np.gradient(v[t, :, :], dy, dx) #s1 = np.ma.empty([ydim,xdim]) J = np.array([[0, 1], [-1, 0]]) for i in range(ydim): for j in range(xdim):
def yieldout(year): bb = year - 1901 region1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/HistoricalGLM_crop_150901.nc', 'r') maitrop = region1.variables['maize_trop'][99, :, :] maitemp = region1.variables['maize_temp'][99, :, :] maitropi = region1.variables['maize_trop_irrig'][99, :, :] maitempi = region1.variables['maize_temp_irrig'][99, :, :] gridarea = region1.variables['area'][:, :] maitrop = ma.masked_where(maitrop <= 0, maitrop) maitrop = ma.filled(maitrop, fill_value=0.) maitemp = ma.masked_where(maitemp <= 0, maitemp) maitemp = ma.filled(maitemp, fill_value=0.) maitropi = ma.masked_where(maitropi <= 0, maitropi) maitropi = ma.filled(maitropi, fill_value=0.) maitempi = ma.masked_where(maitempi <= 0, maitempi) maitempi = ma.filled(maitempi, fill_value=0.) maizetor = maitrop + maitemp maizetoi = maitropi + maitempi maizetrop = maitrop + maitropi maizetemp = maitemp + maitempi maizeto = maitrop + maitemp + maitropi + maitempi ff = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/HistoricalFertilizer.nc', 'r') fert_maitrop = ff.variables['maize_trop_fert'][bb, :, :] fert_maitemp = ff.variables['maize_temp_fert'][bb, :, :] clm = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetrop_historical_co2_rf_fert_0.5x0.5.nc', 'r') clmtropf = clm.variables['yield'][bb, :, :] clmtropfer = clm.variables['fertilizer'][bb, :, :] clm1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetemp_historical_co2_rf_fert_0.5x0.5.nc', 'r') clmtempf = clm1.variables['yield'][bb, :, :] clmtempfer = clm1.variables['fertilizer'][bb, :, :] clm2 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetrop_historical_co2_irrig_fert_0.5x0.5.nc', 'r') clmtropfi = clm2.variables['yield'][bb, :, :] clm3 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetemp_historical_co2_irrig_fert_0.5x0.5.nc', 'r') clmtempfi = clm3.variables['yield'][bb, :, :] clma = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetrop_historical_co2_rf_nofert_0.5x0.5.nc', 'r') clmtropfno = clma.variables['yield'][bb, :, :] clm1a = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetemp_historical_co2_rf_nofert_0.5x0.5.nc', 'r') clmtempfno = clm1a.variables['yield'][bb, :, :] clm2a = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetrop_historical_co2_irrig_nofert_0.5x0.5.nc', 'r') clmtropfnoi = clm2a.variables['yield'][bb, :, :] clm3a = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetemp_historical_co2_irrig_nofert_0.5x0.5.nc', 'r') clmtempfnoi = clm3a.variables['yield'][bb, :, :] clmtropf = N.flipud(clmtropf) clmtempf = N.flipud(clmtempf) clmtropfi = N.flipud(clmtropfi) clmtempfi = N.flipud(clmtempfi) clmtropfno = N.flipud(clmtropfno) clmtempfno = N.flipud(clmtempfno) clmtropfnoi = N.flipud(clmtropfnoi) clmtempfnoi = N.flipud(clmtempfnoi) clmtropfer = N.flipud(clmtropfer) clmtempfer = N.flipud(clmtempfer) clmtropf = ma.masked_where(maitrop <= 0, clmtropf) clmtempf = ma.masked_where(maitemp <= 0, clmtempf) clmtropf = ma.filled(clmtropf, fill_value=0.) clmtempf = ma.filled(clmtempf, fill_value=0.) clmtropfi = ma.masked_where(maitropi <= 0, clmtropfi) clmtempfi = ma.masked_where(maitempi <= 0, clmtempfi) clmtropfi = ma.filled(clmtropfi, fill_value=0.) clmtempfi = ma.filled(clmtempfi, fill_value=0.) clmtropfno = ma.masked_where(maitrop <= 0, clmtropfno) clmtempfno = ma.masked_where(maitemp <= 0, clmtempfno) clmtropfno = ma.filled(clmtropfno, fill_value=0.) clmtempfno = ma.filled(clmtempfno, fill_value=0.) clmtropfnoi = ma.masked_where(maitropi <= 0, clmtropfnoi) clmtempfnoi = ma.masked_where(maitempi <= 0, clmtempfnoi) clmtropfnoi = ma.filled(clmtropfnoi, fill_value=0.) clmtempfnoi = ma.filled(clmtempfnoi, fill_value=0.) fertfractiontrop = N.zeros((360, 720)) nofertfractiontrop = N.zeros((360, 720)) fertfractiontemp = N.zeros((360, 720)) nofertfractiontemp = N.zeros((360, 720)) for x in range(0, 360): for y in range(0, 720): if clmtropfer[x, y] > 0.0: fertfractiontrop[x, y] = min( 1.0, fert_maitrop[x, y] / clmtropfer[x, y]) nofertfractiontrop[x, y] = 1.0 - fertfractiontrop[x, y] else: fertfractiontrop[x, y] = 0.0 nofertfractiontrop[x, y] = 1.0 for x in range(0, 360): for y in range(0, 720): if clmtempfer[x, y] > 0.0: fertfractiontemp[x, y] = min( 1.0, fert_maitemp[x, y] / clmtempfer[x, y]) nofertfractiontemp[x, y] = 1.0 - fertfractiontemp[x, y] else: fertfractiontemp[x, y] = 0.0 nofertfractiontemp[x, y] = 1.0 clmtropfnew = N.zeros((360, 720)) clmtempfnew = N.zeros((360, 720)) clmtropfinew = N.zeros((360, 720)) clmtempfinew = N.zeros((360, 720)) for x in range(0, 360): for y in range(0, 720): clmtropfnew[x, y] = (nofertfractiontrop[x, y] * clmtropfno[x, y]) + ( fertfractiontrop[x, y] * clmtropf[x, y]) clmtempfnew[x, y] = (nofertfractiontemp[x, y] * clmtempfno[x, y]) + ( fertfractiontemp[x, y] * clmtempf[x, y]) clmtropfinew[x, y] = (nofertfractiontrop[x, y] * clmtropfnoi[x, y] ) + (fertfractiontrop[x, y] * clmtropfi[x, y]) clmtempfinew[x, y] = (nofertfractiontemp[x, y] * clmtempfnoi[x, y] ) + (fertfractiontemp[x, y] * clmtempfi[x, y]) yield_clmtf = clmtropf + clmtempf yield_clmtf = ma.masked_where(yield_clmtf <= 0, yield_clmtf) #yield_clmtf = ma.masked_where(maizetor<=0,yield_clmtf ) yield_clmtf = ma.filled(yield_clmtf, fill_value=0.) yield_clmtfi = clmtropfi + clmtempfi yield_clmtfi = ma.masked_where(yield_clmtfi <= 0, yield_clmtfi) #yield_clmtfi = ma.masked_where(maizetoi<=0,yield_clmtfi) yield_clmtfi = ma.filled(yield_clmtfi, fill_value=0.) yield_clmtfnew = clmtropfnew + clmtempfnew yield_clmtfnew = ma.masked_where(yield_clmtfnew <= 0, yield_clmtfnew) #yield_clmtf = ma.masked_where(maizetor<=0,yield_clmtf ) yield_clmtfnew = ma.filled(yield_clmtfnew, fill_value=0.) yield_clmtfinew = clmtropfinew + clmtempfinew yield_clmtfinew = ma.masked_where(yield_clmtfinew <= 0, yield_clmtfinew) #yield_clmtfi = ma.masked_where(maizetoi<=0,yield_clmtfi) yield_clmtfinew = ma.filled(yield_clmtfinew, fill_value=0.) area = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf.nc', 'r') gridarea = area.variables['cell_area'][:, :] gridlon = area.variables['lon'][:] gridlat = area.variables['lat'][:] gridarea, gridlon = shiftgrid(180.5, gridarea, gridlon, start=False) lon2, lat2 = N.meshgrid(gridlon, gridlat) map = Basemap(projection='cyl', llcrnrlat=-65, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') x, y = map(lon2, lat2) yield_clmtf = maskoceans(x, y, yield_clmtf) yield_clmtf = ma.masked_where(maizeto <= 0, yield_clmtf) yield_clmtfi = maskoceans(x, y, yield_clmtfi) yield_clmtfi = ma.masked_where(maizeto <= 0, yield_clmtfi) clmy = ((yield_clmtf * maizetor * gridarea) + (yield_clmtfi * maizetoi * gridarea)) / ((maizetoi * gridarea) + (maizetor * gridarea)) yield_clmtfnew = maskoceans(x, y, yield_clmtfnew) yield_clmtfnew = ma.masked_where(maizeto <= 0, yield_clmtfnew) yield_clmtfinew = maskoceans(x, y, yield_clmtfinew) yield_clmtfinew = ma.masked_where(maizeto <= 0, yield_clmtfinew) clmynew = ((yield_clmtfnew * maizetor * gridarea) + (yield_clmtfinew * maizetoi * gridarea)) / ( (maizetoi * gridarea) + (maizetor * gridarea)) return clmynew
# Exercise 3 Basemap from example_code.map_data import * import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np # top import will ensure following variables exist in local scope # tas (temp), lons, lats # create figure fig = plt.figure() # set up Basemap instance with regular lat/lon coord ref system m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') # add coastlines m.drawcoastlines() # create 'Jet' colourmap
plt.rc('text', usetex=True) plt.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Avant Garde']}) ### Set limits for contours and colorbars limit = np.arange(0, 1.1, 0.1) barlim = np.round(np.arange(0, 1.1, 0.2), 2) lonq, latq = np.meshgrid(lon, lat) fig = plt.figure() for i in range(len(var)): ax1 = plt.subplot(5, 6, i + 1) m = Basemap(projection='ortho', lon_0=0, lat_0=89, resolution='l', area_thresh=10000.) varn, lons_cyclic = addcyclic(var[i], lon) varn, lons_cyclic = shiftgrid(180., varn, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white', color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x, y, varn, limit, extend='max')
class myMap: nlmap = { 'alias': 'nl', 'file': './nlmap.pkl', 'res': 'h', 'latlon0': (52.1, 4.7), 'dim': (5.e5, 5.e5) } eurmap = { 'alias': 'eur', 'file': './eurmap.pkl', 'res': 'i', 'latlon0': (51., 3.), 'dim': (20.e5, 20.e5) } rotmap = { 'alias': 'rot', 'file': './rotmap.pkl', 'res': 'h', 'latlon0': (52., 4.5), 'dim': (1.2e5, 1.2e5) } ijsmap = { 'alias': 'ijs', 'file': './ijsmap.pkl', 'res': 'h', 'latlon0': (52.7, 5.3), 'dim': (1.e5, 1.e5) } def __init__(self, domain='nl', modelname='harmonie', res='h', latlon0=(52.1, 4.7), dim=(5.e5, 5.e5)): maps = (self.nlmap, self.eurmap, self.rotmap, self.ijsmap) if not hasattr(self.__class__, 'pmap'): self.__class__.pmap = {} if not self.__class__.pmap.has_key((domain, modelname)): #check if pickle dump file exists map_index = None for (i, m) in enumerate(maps): if m['alias'] == domain: map_index = i if map_index is not None: mapdef = maps[map_index] if mapdef['alias'] == domain: if os.path.isfile( mapdef['file']): #open dumpfile, read bmap print 'read map', str(domain) f = open(mapdef['file'], 'r') self.bmap = pickle.load(f) f.close() else: # construct instance self.bmap = Basemap(projection='lcc', resolution=mapdef['res'], lat_0=mapdef['latlon0'][0], lon_0=mapdef['latlon0'][1], lat_1=45., lat_2=55., width=mapdef['dim'][0], height=mapdef['dim'][1]) print 'write map ', domain f = open(mapdef['file'], 'wb') pickle.dump(self.bmap, f) f.close() else: # map definition not recognized print 'Domain not pre-defined: ', domain try: self.bmap = Basemap(projection='lcc', resolution=res, lat_0=latlon0[0], lon_0=latlon0[1], lat_1=45., lat_2=55., width=dim[0], height=dim[1]) print 'map was constructed, not written to file' except: # not enough or not the right arguments 'Define or modify domain in myMap class' sys.exit(1) # finally: construct bmap instance self.__class__.pmap[(domain, modelname)] = self.bmap else: # read from self.__class__ : self.bmap = self.__class__.pmap[(domain, modelname)] self.domain = domain self.ax = "None" #self.xymap(file) self.cl = None self.cnt = None self.par = None self.mer = None #self.dress_up_map(domain = domain) def set_axes(self, ax): self.ax = ax def dress_up_map(self, domain=None, par_bot=45, par_top=60, par_int=1, mer_bot=-1, mer_top=10, mer_int=1, labelfont=6, lsmask_colour='black'): if domain in ('nl', 'rot', 'ijs'): par_bot, par_top, par_int = 45, 60, 1 mer_bot, mer_top, mer_int = -1, 10, 1 elif domain == 'eur': par_bot, par_top, par_int = 40, 60, 2 mer_bot, mer_top, mer_int = -16, 21, 2 else: par_bot, par_top, par_int = 45, 60, 1 mer_bot, mer_top, mer_int = -1, 10, 1 try: for key in self.cl: del (self.cl[key]) for key in self.cnt: del (self.cnt[key]) for key in self.par: del (self.par[key]) for key in self.mer: del (self.mer[key]) except: pass #print 'to draw coastlines etc',time.clock() - t0, int(time.clock() - t0)*'=' #print 'drawing coastlines ', domain self.cl = self.bmap.drawcoastlines(ax=self.ax, color=lsmask_colour) self.cnt = self.bmap.drawcountries(ax=self.ax, color=lsmask_colour) #print self.cl #print 'to draw parallels etc',time.clock() - t0, int(time.clock() - t0)*'=' self.par = self.bmap.drawparallels(numpy.arange( par_bot, par_top, par_int), labels=[1, 1, 0, 0]) self.mer = self.bmap.drawmeridians(numpy.arange( mer_bot, mer_top, mer_int), labels=[0, 0, 0, 1]) #print 'new font size in labels:',time.clock() - t0, int(time.clock() - t0)*'=' new_fontsize = labelfont for key in self.par.keys(): line, text = self.par[key] for txt in text: txt.set_fontsize(new_fontsize) for key in self.mer.keys(): line, text = self.mer[key] for txt in text: txt.set_fontsize(new_fontsize) def xymap(self, latlons=[], files=[], domain='nl', modelname='harmonie'): '''Mapping the lats and lons to actual locations on the map ''' #print '==> xymap start: ', #report_mem_usage() # create dict of possible x,y if not hasattr(self.__class__, 'map_xy'): self.__class__.map_xy = {} if self.__class__.map_xy.has_key((domain, modelname)): # read x,y from class memory (self.x, self.y) = self.__class__.map_xy[(domain, modelname)] elif not self.__class__.map_xy.has_key((domain, modelname)): try: lats, lons = latlons self.x, self.y = self.bmap(lons, lats) # write to class memory: self.__class__.map_xy[(domain, modelname)] = (self.x, self.y) except: try: # open file, extract lats,lons and map to x,y grbs = pygrib.open(files[0]) lats, lons = grbs[1].latlons() self.x, self.y = self.bmap(lons, lats) # write to class memory: self.__class__.map_xy[(domain, modelname)] = (self.x, self.y) except: print 'no files in specified location', domain, modelname, files sys.exit(1) #print '==> xymap end: ', #report_mem_usage() def testmap(self, fig, ax, var, param, level, plotlevels=range(10), draw_line=False, cmap=None, colors=None, name='Variable', date=20040514, leadtime=0, outdir='./'): '''A plotting method, not generally used, needs a figure, axis instance and some plotting information ''' levels = plotlevels if cmap == None and colors == None: cmap = CM.get_cmap('jet') elif cmap is not None: cmap.set_over(color='k', alpha=None) colors = None else: pass leadtime = suf3(leadtime) ax.set_title(name + ' (parameter ' + str(param) + ', level ' + str(level) + ') at ' + str(date) + '+' + str(leadtime)) pcont = self.bmap.contourf(self.x, self.y, var, levels, cmap=cmap, colors=colors, ax=self.ax) if draw_line: plcont = self.bmap.contour(self.x, self.y, var, levels, ax=self.ax) # colorbar: cb = fig.colorbar(pcont, shrink=0.9, extend='both', format='%.1e') cb.set_label(name, fontsize=9) # naming and saving plotfile = os.path.join(outdir, 'test_'+self.domain+\ '_'+str(param)+'_'+str(level)+'_'\ +str(date)+'+'+str(leadtime)+'.png') sf = fig.savefig(plotfile) print 'created plot: ' + plotfile #clean up for coll in pcont.collections: coll.remove() try: for coll in plcont.collections: coll.remove() except: pass # delete colorbar cbcoll = fig.get_axes()[1] cbcoll.collections = [] fig.delaxes(cbcoll) fig.subplots_adjust(right=0.90)
time[0] )] # 0 para o tempo/rodada inicial! se for a rodada depois da inicial poem 1 e assim por diante arr = arr[0, :, :] #Aqui vai zero simplesmente pq o python pede :) margin = 2 # buffer to add to the range lat_min = -29.5 #min(lat) - margin lat_max = -25.8 #max(lat) + margin lon_min = -54.5 #min(lon) - margin lon_max = -48 #max(lon) + margin # create map using BASEMAP m = Basemap(llcrnrlon=lon_min, llcrnrlat=lat_min, urcrnrlon=lon_max, urcrnrlat=lat_max, lat_0=(lat_max - lat_min) / 2, lon_0=(lon_max - lon_min) / 2, projection='merc', resolution='h') m.drawcoastlines() m.drawcountries() m.drawstates() m.drawmapboundary(fill_color='#46bcec' ) #comentar linha caso queira apenas os dados do continente m.drawparallels(np.arange(-31., -24., 1), labels=[1, 0, 0, 0], linewidth=0.0) # draw meridians m.drawmeridians(np.arange(-56., -47., 1), labels=[0, 0, 0, 1], linewidth=0.0) lon, lat = np.meshgrid(lons, lats) xi, yi = m(lon, lat)
def write_domain_map(border, out_filename, lon_vec=None, lat_vec=None, lon_border=10., lat_border=10.,figure_size=(6, 6), dpi=50, projection='cyl', resolution='c', continets_color='coral',meridians=10, parallels=10, p_color='r', p_line='k', p_alpha=0.5, padding=0., mer_labels=[False, False, False, False], par_labels=[False, False, False, False], pltshow=False, labels=None): """Create an image with a map of the domain Uses Basemap to create a World Map Adds a semitransparent patch with outline of the Domain Writes to an image file Parameters ----------- out_filename : string name of the output file name lon_vec : [floats] or [[floats]] longitudes of patches to display lat_vec : [floats] or [[floats]] latitudes of patches to display lon_border : float 10, horisontal border around patch (degrees of longitude) lat_border : float 10, vertical border around patch (degrees of latitude) figure_size : tuple of two integers (6, 6), size of the generated figure in inches dpi: int 50, resolution of the output figure (size 6,6 and dpi 50 produces 300 x 300 figure) projection : string, one of Basemap projections 'cyl', projection of the map resolution : string, resolution of the map 'c', crude 'l', low 'i', intermediate 'h', high 'f', full continets_color : string or any matplotlib color representation 'coral', color of continets meridians : int 10, number of meridians to draw parallels : int 10, number of parallels to draw p_color : string or any matplotlib color representation 'r', color of the Domain patch p_line : string or any matplotlib color representation 'k', color of the Domain outline p_alpha : float 0 - 1 0.5, transparency of Domain patch padding : float 0., width of white padding around the map mer_labels : list of 4 booleans where to put meridian labels, see also Basemap.drawmeridians() par_lables : list of 4 booleans where to put parallel labels, see also Basemap.drawparallels() labels : list of str labels to print on top of patches """ if not BASEMAP_LIB_IS_INSTALLED: raise ImportError(' Basemap is not installed. Cannot use Domain.write_map. ' ' Enable by: conda install -c conda forge basemap ') # if lat/lon vectors are not given as input if lon_vec is None or lat_vec is None or len(lon_vec) != len(lat_vec): lon_vec, lat_vec = border # convert vectors to numpy arrays lon_vec = np.array(lon_vec) lat_vec = np.array(lat_vec) # estimate mean/min/max values of lat/lon of the shown area # (real lat min max +/- latBorder) and (real lon min max +/- lonBorder) min_lon = max(-180, lon_vec.min() - lon_border) max_lon = min(180, lon_vec.max() + lon_border) min_lat = max(-90, lat_vec.min() - lat_border) max_lat = min(90, lat_vec.max() + lat_border) mean_lon = lon_vec.mean() mean_lat = lat_vec.mean() # generate template map (can be also tmerc) plt.figure(num=1, figsize=figure_size, dpi=dpi) bmap = Basemap(projection=projection, lat_0=mean_lat, lon_0=mean_lon, llcrnrlon=min_lon, llcrnrlat=min_lat, urcrnrlon=max_lon, urcrnrlat=max_lat, resolution=resolution) # add content: coastline, continents, meridians, parallels bmap.drawcoastlines() bmap.fillcontinents(color=continets_color) bmap.drawmeridians(np.linspace(min_lon, max_lon, meridians), labels=mer_labels, fmt='%2.1f') bmap.drawparallels(np.linspace(min_lat, max_lat, parallels), labels=par_labels, fmt='%2.1f') # convert input lat/lon vectors to arrays of vectors with one row # if only one vector was given if len(lon_vec.shape) == 1: lon_vec = [lon_vec] lat_vec = [lat_vec] for i in range(len(lon_vec)): # convert lat/lons to map units map_x, map_y = bmap(list(lon_vec[i].flat), list(lat_vec[i].flat)) # from x/y vectors create a Patch to be added to map boundary = Polygon(list(zip(map_x, map_y)), alpha=p_alpha, ec=p_line, fc=p_color) # add patch to the map plt.gca().add_patch(boundary) plt.gca().set_aspect('auto') if labels is not None and labels[i] is not None: plt.text(np.mean(map_x), np.mean(map_y), labels[i], va='center', ha='right', alpha=0.5, fontsize=10) # save figure and close plt.savefig(out_filename, bbox_inches='tight', dpi=dpi, pad_inches=padding) if pltshow: plt.show() else: plt.close('all')
def __init__(self, domain='nl', modelname='harmonie', res='h', latlon0=(52.1, 4.7), dim=(5.e5, 5.e5)): maps = (self.nlmap, self.eurmap, self.rotmap, self.ijsmap) if not hasattr(self.__class__, 'pmap'): self.__class__.pmap = {} if not self.__class__.pmap.has_key((domain, modelname)): #check if pickle dump file exists map_index = None for (i, m) in enumerate(maps): if m['alias'] == domain: map_index = i if map_index is not None: mapdef = maps[map_index] if mapdef['alias'] == domain: if os.path.isfile( mapdef['file']): #open dumpfile, read bmap print 'read map', str(domain) f = open(mapdef['file'], 'r') self.bmap = pickle.load(f) f.close() else: # construct instance self.bmap = Basemap(projection='lcc', resolution=mapdef['res'], lat_0=mapdef['latlon0'][0], lon_0=mapdef['latlon0'][1], lat_1=45., lat_2=55., width=mapdef['dim'][0], height=mapdef['dim'][1]) print 'write map ', domain f = open(mapdef['file'], 'wb') pickle.dump(self.bmap, f) f.close() else: # map definition not recognized print 'Domain not pre-defined: ', domain try: self.bmap = Basemap(projection='lcc', resolution=res, lat_0=latlon0[0], lon_0=latlon0[1], lat_1=45., lat_2=55., width=dim[0], height=dim[1]) print 'map was constructed, not written to file' except: # not enough or not the right arguments 'Define or modify domain in myMap class' sys.exit(1) # finally: construct bmap instance self.__class__.pmap[(domain, modelname)] = self.bmap else: # read from self.__class__ : self.bmap = self.__class__.pmap[(domain, modelname)] self.domain = domain self.ax = "None" #self.xymap(file) self.cl = None self.cnt = None self.par = None self.mer = None
yield_fine2 = interp(yield_new2, lona11,lata1,lon,lat , order=1) yield_clmtf1 = interp(yield_clmtf, lona11,lata1,lon,lat , order=1) yield_clmtfi1 = interp(yield_clmtfi, lona11,lata1,lon,lat , order=1) mask_clm = interp(maizeto, lona11,lata1,lon,lat , order=1) mask_clmra=interp(maizetor, lona11,lata1,lon,lat , order=1) mask_clmii=interp(maizetoi, lona11,lata1,lon,lat , order=1) fig, ax = plt.subplots(figsize=(8,6)) ax.set_title("M3 Soybean Yield gridecll (g/$\mathregular{m^2}$)",fontsize=20) map = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c') map.drawcoastlines() map.drawcountries() map.drawmapboundary() lone,late = N.meshgrid(lonnc,latnc) #Returns coordinate matrices from coordinate vectors x,y = map(lone,late) ncvar_maizef=maskoceans(x,y,ncvar_maizef) ncvar_maizef=ma.filled(ncvar_maizef, fill_value=0.) ncvar_maizef = ma.masked_where(ncvar_maizef<=0,ncvar_maizef) ncvar_maizef = ma.masked_where(mask_clm<=0,ncvar_maizef) #print maskus_new m3y=mask_clm*ncvar_maizef*100
def mapplot(plotdata, lat, lon, title=''): """ Plots input grid with map of world overlaid Parameters ---------- plotdata: array data being plotted title: str optional title """ from mpl_toolkits.basemap import Basemap, shiftgrid import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt ''' long = np.zeros((193)) long[:-1], long[-1] = lon, 360.000 temp = plotdata[:, 0] plotdata = np.c_[plotdata, temp] ''' plotdata, lon = shiftgrid(180., plotdata, lon, start=False) meshlon, meshlat = np.meshgrid(lon, lat) plt.figure() m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') m.drawcoastlines() m.drawmapboundary() x, y = m(meshlon, meshlat) my_cmap = plt.cm.jet(np.arange(256)) my_cmap[120:136, :] = 0.99 newcmap = mpl.colors.LinearSegmentedColormap.from_list("newjet", my_cmap) # ctrs = np.linspace(-30, 30, 21) ctrs = np.linspace(-20, 50, 29) # ctrs = np.linspace(-0.2, 1, 12) for i in range(np.ma.size(lat)): for j in range(np.ma.size(lon)): if plotdata[i, j] == 'masked': plotdata[i, j] = np.nan plot = m.contourf(x, y, plotdata, ctrs, cmap=newcmap, vmin=np.min(ctrs), vmax=np.max(ctrs), extend='both') plt.colorbar(plot, orientation='horizontal', shrink=0.5, spacing='proportional') parallels = m.drawparallels(np.arange(-90., 91., 15.)) meridians = m.drawmeridians(np.arange(-180., 181., 30.)) m.drawparallels(parallels, labels=[True, True, True, True]) m.drawmeridians(meridians, labels=[True, True, True, True]) plt.title(title, y=1.08) plt.show()
import numpy as np from mpl_toolkits.basemap import Basemap os.chdir('/home/edwin/Downloads/') nc = Dataset('ECMWF_ERA-40_subset.nc', mode='r') lat = nc.variables['latitude'][:] lon = nc.variables['longitude'][:] time = nc.variables['time'][:] t2 = nc.variables['p2t'][:] # 2 meter temperature mslp = nc.variables['msl'][:] # mean sea level pressure u = nc.variables['p10u'][:] # 10m u-component of winds v = nc.variables['p10v'][:] # 10m v-component of winds map = Basemap(projection='merc',llcrnrlon=-93.,llcrnrlat=35.,urcrnrlon=-73.,urcrnrlat=45.,resolution='i') # projection, lat/lon extents and resolution of polygons to draw # resolutions: c - crude, l - low, i - intermediate, h - high, f - full map.drawcoastlines() map.drawstates() map.drawcountries() map.drawlsmask(land_color='Linen', ocean_color='#CCFFFF') # can use HTML names or codes for colors map.drawcounties() # you can even add counties (and other shapefiles!) parallels = np.arange(30,50,5.) # make latitude lines ever 5 degrees from 30N-50N meridians = np.arange(-95,-70,5.) # make longitude lines every 5 degrees from 95W to 70W map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)
def generate_figure(coords,trigger_time_corr,phones_to_trigger,Md_tt,Md_ti,Ph_tt,Ph_co,counter): ''' Function to generate figure showing the phones that have been triggered and various trigger delay times ''' lonmin = coords[0] lonmax = coords[1] latmin = coords[2] latmax = coords[3] figure = plt.figure(figsize=(20,20)) ax1 = figure.add_subplot(321) proportion_triggered = np.sum(phones_to_trigger['triggered'])/len(phones_to_trigger) total_phones = len(phones_to_trigger) sns.countplot(x='appVersion',data=phones_to_trigger,hue='triggered',ax=ax1) ax1.set_xlabel('App version') ax1.set_ylabel('Count') ax1.legend(loc='upper left',title='Triggered') ax1.grid() ax1.set_title('Proportion triggered: %.2f' %proportion_triggered) ax2 = figure.add_subplot(322) triggered_phones = phones_to_trigger[phones_to_trigger['triggered']==1] untriggered_phones = phones_to_trigger[phones_to_trigger['triggered']==0] map = Basemap(llcrnrlon=lonmin, llcrnrlat=latmin, urcrnrlon=lonmax, urcrnrlat=latmax, lat_0=latmin+(latmax-latmin)/2, lon_0=lonmin+(lonmax-lonmin)/2, resolution = 'i',ax=ax2) map.fillcontinents(color='#cc9955', lake_color='aqua', zorder = 0) map.drawcoastlines(color = '0.15') xtrig, ytrig = map(triggered_phones['longitude'].values,triggered_phones['latitude'].values) xutrig, yutrig = map(untriggered_phones['longitude'].values,untriggered_phones['latitude'].values) map.scatter(xutrig,yutrig,8,marker='o',color='r') map.scatter(xtrig,ytrig,8,marker='o',color='g') ax2.set_title("Map of phones: Green = triggered, Red = did not trigger") ax3 = figure.add_subplot(323) Md_ti = np.array(Md_ti) Md_tt = np.array(Md_tt) Ph_tt = np.array(Ph_tt) Md_tt[Md_tt>20] = 0 Ph_tt[Ph_tt>20] = 0 Md_ti[Md_ti>20] = 0 median_delay = np.median(Md_tt) ax3.hist(Md_tt,bins=20) ax3.axvline(median_delay,color='g',linestyle='--') ax3.set_xlim(0,10) ax3.set_ylabel('Number of phones') ax3.set_xlabel('MDB triggertime delay time [s]') ax3.grid() ax3.set_title('Delay times: MDB tt. Median: %g s' %median_delay) ax4 = figure.add_subplot(324) median_delay = np.median(Ph_tt) ax4.hist(Ph_tt,bins=20) ax4.axvline(median_delay,color='g',linestyle='--') ax4.set_xlim(0,10) ax4.set_ylabel('Number of phones') ax4.set_xlabel('SDB triggertime delay time [s]') ax4.grid() ax4.set_title('Delay times: SDB tt. Median: %g s' %median_delay) ax5 = figure.add_subplot(325) median_delay = np.median(Md_ti) ax5.hist(Md_ti,bins=20) ax5.axvline(median_delay,color='g',linestyle='--') ax5.set_xlim(0,10) ax5.set_ylabel('Number of phones') ax5.set_xlabel('MDB triggerinject delay time [s]') ax5.grid() ax5.set_title('Delay times: MDB ti. Median: %g s' %median_delay) ax6 = figure.add_subplot(326) median_delay = np.median(Ph_co) ax6.hist(Ph_co,bins=50) ax6.axvline(median_delay,color='g',linestyle='--') ax6.set_ylabel('Number of phones') ax6.set_xlabel('SBD CreatedOn delay time [s]') ax6.grid() ax6.set_title('Delay times: SDB createdOn. Median: %g s' %median_delay) figure.suptitle('Experiment from trigger at %s. Total phones: %i' %(trigger_time_corr,total_phones) ) figname = "Triggering_experiment_%s.png" %counter plt.savefig(figname,dpi=400) print("Done figure generation!")
U3 = np.array(U2)**2 V3 = np.array(V2)**2 maxu = np.where(U3[0] == np.max(U3)) maxv = np.where(V3[0] == np.max(V3)) for i in range(0, len(U3)): U3[i][maxu] = 'nan' V3[i][maxv] = 'nan' # ------------------------------------------------------ # Start Basemap # ------------------------------------------------------ m = Basemap(projection='merc', llcrnrlat=17, urcrnrlat=18, llcrnrlon=-65, urcrnrlon=-60, resolution='i', area_thresh=0.01) m.drawcoastlines(linewidth=0.2) m.fillcontinents(color='#cc9966') x, y = m(Lon_bath, Lat_bath) c = plt.contour(x, y, -Depth, levels=[10, 30, 100, 1000], cmap=plt.cm.Greys, norm=colors.LogNorm(vmin=3, vmax=10000)) par = m.drawparallels(np.arange(-80, 81, 0.5), labels=[1, 0, 0, 0])
cmap = plt.cm.bwr #bounds=[-0.1,0.0,0.01,0.05,0.1,0.5,1,2,3,4,5,6] #bounds=[-0.1,0.0,1,2,4,6,8,10,12,14,16] bounds = [-100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100] norm = colors.BoundaryNorm(bounds, cmap.N) fig = plt.figure(figsize=(20, 10)) ax1 = fig.add_subplot(221) ax1 = fig.add_subplot(222) ax1.set_title("Maize ISAM (t grains / ha gridarea)", fontsize=20) map = Basemap(projection='cyl', llcrnrlat=-62, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') x, y = map(lon, lat) ma1 = ma.masked_where(ma1 <= 0.0, ma1) map.drawcoastlines() map.drawcountries() map.drawmapboundary() #ncvar_y=maskoceans(x1,y1,ncvar_y) aa = (ma1 - ma1h) / ma1h * 100 aa = ma.masked_where(aa == 0.0, aa) cs1 = map.pcolormesh(x, y, aa, cmap=cmap, norm=norm) #cs1 = map.pcolormesh(x,y,ma1,cmap=plt.cm.gist_earth,vmin=0,vmax=10)
def mov_files(data, incli, VPs, inten, nphi, ntheta, plot_cbar=True): from mpl_toolkits.basemap import Basemap rprof = data[..., 0] rprof = symmetrize(rprof, gr.minc)[:, ::-1] lons = N.linspace(-180, 180, nphi) lats = N.linspace(-90, 90, ntheta) if not os.path.exists('movie_light_curve'): os.mkdir('movie_light_curve') fig = P.figure() LC = fig.add_subplot(2, 1, 1) LC.set_xlim([-10, 370]) LC.set_ylim([inten.min(), inten.max()]) LC.set_xlabel('Longitudes') LC.set_ylabel('Visible intensity') for i in range(len(inten)): LC.plot(VPs[i] * 180 / N.pi, inten[i], 'o', mfc='b') map = Basemap(projection='ortho', lon_0=my2ortho_lon(VPs[i]) * 180 / N.pi, lat_0=my2ortho_lat(incli) * 180 / N.pi, resolution=None) plot2 = fig.add_subplot(2, 1, 2) map.drawparallels(N.linspace(90, -90, 7), dashes=[2, 3], linewidth=0.5) map.drawmeridians(N.arange(-180, 180, 30), dashes=[2, 3], linewidth=0.5) map.drawmapboundary() new_dat = map.transform_scalar(rprof.T, lons, lats, nphi, ntheta, masked=True) im = map.imshow(new_dat, cmap=P.get_cmap('gist_heat')) if plot_cbar == True: cbar = map.colorbar(im, location='right', pad="5%") filename = 'movie_light_curve/img%04d.png' % i P.savefig(filename, dpi=100) plot2.lines = [] if plot_cbar == True: fig.delaxes(fig.axes[2])
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap data=Dataset("hycomRe.nc") lon=data.variables['LON'][:] lat=data.variables['LAT'][:] temp=data.variables['WATER_TEMP'][0,0,:,:] fig = plt.figure() # resolution ='l' is ok , nor use 'h' will work sloyly m=Basemap(projection='merc',llcrnrlat=21,urcrnrlat=26,\ llcrnrlon=115,urcrnrlon=123,resolution='l') #set fig size fig.set_size_inches(15, 8, forward=True) ax = plt.gca() # need to 2D due to data is 2D x,y=np.meshgrid(lon,lat) #contour mk linspace to adjust, cmap is color to choose , extebd is the colorbar extend ,cmap='rainbow' cs=m.contourf(x,y,temp, np.linspace(15,25,21) ,extend='both',cmap='rainbow' ,latlon=True) #color bar pad is distance in colobar to pic cbar = m.colorbar(cs, location='right', pad="10%") #set fontsize in color bar
gdal.Warp(prj_output_name,iras,dstSRS = "EPSG:"+str(epsg)) # convert sites dataframe to sites geodataframe sites_gdf = df_to_gdf (sites,"lat","lon",4326) # project the geodataframe sites_gdf.crs={'init' :'epsg:4326'} sites_gdf = sites_gdf.to_crs({'init': 'epsg:'+str(epsg)}) sitesx = np.array(sites_gdf.geometry.x) sitesy = np.array(sites_gdf.geometry.y) # Make nice map images plt.rcParams["figure.figsize"] = (10, 10) map1 = Basemap(epsg=epsg, llcrnrlon=xmin - 360 - 1, llcrnrlat= ymin - 1, urcrnrlon=xmax - 360 + 3, urcrnrlat=ymax + 1, resolution='i', area_thresh=10000.) map1.fillcontinents(color='#e8e8e8', alpha=1, zorder=1) map1.drawcountries(color='black', linewidth=2, zorder=3) map1.drawstates(color='black', linewidth=1, zorder=4) map1.drawparallels(np.arange(ymin, ymax, round(abs(ymin-ymax)/3)), color="black", labels=[1, 0, 0, 0], fontsize=10, linewidth=0.2, zorder=5) map1.drawmeridians(np.arange(xmin, xmax, round(abs(xmin-xmax)/3)), color="black", labels=[0, 0, 0, 1], fontsize=10, linewidth=0.2, zorder=6) x,y = map1(sitesx,sitesy) map1.scatter(x, y, marker='o',s=5, zorder=7, color = 'black') m_lon, m_lat = np.meshgrid(lon, lat) xi, yi = map(m_lon, m_lat) cs = map1.pcolor(xi, yi, np.squeeze(DD_output), alpha=1, vmin=0, vmax=1, cmap='jet_r', zorder=2) cbar = map1.colorbar(cs, location='bottom', pad="5%") cbar.set_alpha(1) cbar.draw_all()
ax.scatter(x, y, z, c=z, cmap='viridis', linewidth=0.5); #triangulate with trisurf ax = plt.axes(projection='3d') ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none'); #geographics plotting #need basemap and pillow installed. if on Linux you need a hack: import os import conda conda_file_dir = conda.__file__ conda_dir = conda_file_dir.split('lib')[0] proj_lib = os.path.join(os.path.join(conda_dir, 'share'), 'proj') os.environ["PROJ_LIB"] = proj_lib from mpl_toolkits.basemap import Basemap plt.figure(figsize=(8, 8)) m = Basemap(projection='ortho', resolution=None, lat_0=50, lon_0=-100) m.bluemarble(scale=0.5); fig = plt.figure(figsize=(8, 8)) m = Basemap(projection='lcc', resolution=None, width=8E6, height=8E6, lat_0=29, lon_0=41,) m.etopo(scale=0.5, alpha=0.5)
import pandas import matplotlib import matplotlib.pyplot as plt from matplotlib.patches import Polygon from mpl_toolkits.basemap import Basemap from matplotlib.collections import PatchCollection font = { 'family': 'SimHei' } matplotlib.rc('font', **font) fig = plt.figure() ax = fig.add_subplot(111) basemap = Basemap(llcrnrlon=-128, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=53) usaAdm1 = basemap.readshapefile('D:\\PDA\\6.6\\USA\\USA_adm1', 'states', drawbounds=True) mainColor = (42 / 256, 87 / 256, 141 / 256, 1) mapData = pandas.DataFrame(basemap.states_info) patches = [] for info, shape in zip(basemap.states_info, basemap.states): if info['NAME_1'] == 'Alabama': patches.append(Polygon(numpy.array(shape), True)) ax.add_collection( PatchCollection(patches,
def us_map_2016(): """ Color-coded map of the results of 2016 U.S. Presidential Election """ m = Basemap( llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49, # coordinates for US Map projection='lcc', # Lambert Conformal projection lat_1=33, lat_2=45, lon_0=-95, resolution='c') plt.title('Map of 2016 Presidential Elections') # Title for the Plot # https://github.com/matplotlib/basemap/raw/master/examples/st99_d00.shp m.readshapefile('st99_d00', name='states', drawbounds=True) state_names = [] for shape_dict in m.states_info: state_names.append( shape_dict['NAME'] ) # Gathers the names of states from the shp file to look up by name ax = plt.gca() # current axes seg = m.states[state_names.index('Texas')] # Selects the desired state poly = Polygon(seg, facecolor='red', edgecolor='red') # changes the color to red or blue ax.add_patch(poly) seg = m.states[state_names.index('Florida')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Georgia')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Alabama')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Mississippi')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Louisiana')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Oklahoma')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Arkansas')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('South Carolina')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('North Carolina')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Tennessee')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Kentucky')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('West Virginia')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Pennsylvania')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Ohio')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Indiana')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Michigan')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Wisconsin')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Missouri')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Kansas')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Nebraska')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Iowa')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('South Dakota')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('North Dakota')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Montana')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Wyoming')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Idaho')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Utah')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Arizona')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('Alaska')] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) seg = m.states[state_names.index('California')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Oregon')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Washington')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Nevada')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Colorado')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('New Mexico')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Minnesota')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Illinois')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Virginia')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Maryland')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('District of Columbia')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Delaware')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('New Jersey')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Connecticut')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Rhode Island')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Massachusetts')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('New York')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Vermont')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('New Hampshire')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Maine')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) seg = m.states[state_names.index('Hawaii')] poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) plt.show()
urcrnrlon = lons[-1, -1] urcrnrlat = lats[-1, -1] rsphere = (g.projparams['a'], g.projparams['b']) lat_1 = g.projparams['lat_1'] lat_2 = g.projparams['lat_2'] lon_0 = g.projparams['lon_0'] projection = g.projparams['proj'] fig = plt.figure() sys.stdout.write(repr(g.projparams) + '\n') ax = fig.add_axes([0.1, 0.1, 0.75, 0.75]) m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, rsphere=rsphere, lon_0=lon_0, lat_1=lat_1, lat_2=lat_2, resolution='l', projection=projection, area_thresh=10000) x, y = m(lons, lats) cs = m.contourf(x, y, data, 20, cmap=plt.cm.jet) m.drawcoastlines() m.drawstates() m.drawcountries() # new axis for colorbar. cax = plt.axes([0.875, 0.15, 0.03, 0.65]) plt.colorbar(cs, cax, format='%g') # draw colorbar plt.axes(ax) # make the original axes current again plt.title('NDFD Temp CONUS %d-h forecast' % g['forecastTime'], fontsize=12)
def colormap(mystatedict): # create the map plt.ion() map = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45, lon_0=-95) # load the shapefile, use the name 'states' map.readshapefile('st99_d00', name='states', drawbounds=True) # collect the state names from the shapefile attributes so we can # look up the shape obect for a state by it's name state_names = [] for shape_dict in map.states_info: state_names.append(shape_dict['NAME']) ax = plt.gca() # get current axes instance # get Texas and draw the filled polygon """ seg = map.states[state_names.index('Texas')] seg1 = map.states[state_names.index('Washington')] poly = Polygon(seg, facecolor='red',edgecolor='red') poly1 = Polygon(seg1, facecolor='blue',edgecolor='blue') ax.add_patch(poly) for key in mystatedict: seg = map.states[state_names.index(key)] poly = Polygon(seg, facecolor=mystatedict[key],edgecolor=mystatedict[key]) ax.add_patch(poly) """ for i, seg in enumerate(map.states): #print("name:{}, shape:{}".format(state_names[i], seg)) if state_names[i] in mystatedict: poly = Polygon(seg, facecolor=mystatedict[state_names[i]], edgecolor=mystatedict[state_names[i]]) ax.add_patch(poly) #plt.show() plt.draw() #time.sleep(20) plt.pause(0.0000000000001) """ for i, seg in enumerate(map.states): #print("name:{}, shape:{}".format(state_names[i], seg)) poly = Polygon(seg, facecolor='blue', edgecolor='blue') ax.add_patch(poly) #patches.append(poly) #MapAx.add_patch(poly) """ #[p.remove() for p in reversed(ax.patches)] return plt, ax