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 get_SAL_native_grid(): global Nlim Nlim = 45.0 global Elim Elim = -85.0 global Slim Slim = 34.0 global Wlim Wlim = -110.0 m = Basemap(projection='merc', llcrnrlat=Slim, llcrnrlon=Wlim, urcrnrlat=Nlim, urcrnrlon=Elim, lat_ts=39.5, resolution='h') # m = Basemap(projection='lcc',llcrnrlat=34.0,llcrnrlon=-110.0, # urcrnrlat=45.0,urcrnrlon=-85.0,lat_0=30.0,lat_1=50.0,lon_0=-95.0) lons, lats, xx, yy = m.makegrid(537, 308, returnxy=True) # print(xx[5,-1] - xx[5,-2]) # print(xx[5,1] - xx[5,0]) # print(yy[-1,5] - yy[-2,5]) # print(yy[1,5] - yy[0,5]) # import pdb; pdb.set_trace() # 4 km spacing return m, lons, lats, xx[0, :], yy[:, 0]
def plot_map(values, axis, cmap=plt.cm.get_cmap("viridis"), colorbar=True, invert_colorbar=False): """ Plot values on a Basemap map Args: values (numpy.ndarray): 2-d array with dimensions latitude and longitude axis: Axis on which the map should be displayed cmap (optional): matplotlib.Colormap to use Defaults to plt.cm.get_cmap("viridis") colorbar (boolean, optional): Boolean indicating if a colorbar should be plotted Defaults to True invert_colorbar (boolean, optional): Boolean indicating if the colobar should be inverted """ #Create map m = Basemap(projection='mill', lon_0=30, resolution='l', ax=axis) m.drawcoastlines() lons, lats = m.makegrid(512, 256) x, y = m(lons, lats) #Draw values in map cs = m.contourf(x, y, values, cmap=cmap) if colorbar: cbar = m.colorbar(cs, location='bottom', pad="5%") cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), rotation=45) if invert_colorbar: cbar.ax.invert_xaxis()
def plot(mp): from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(projection='mill', llcrnrlon=0,llcrnrlat=-90,urcrnrlon=360,urcrnrlat=90) map.drawcoastlines(linewidth=0.25) map.drawmeridians(numpy.arange(0,360,30)) map.drawparallels(numpy.arange(-90,90,30)) data = mp.data lons, lats = map.makegrid(mp.width, mp.height) x, y = map(*numpy.meshgrid(mp.longitudes, mp.latitudes)) #clevs = range(200, 325, 5) clevs = list(frange(0, 8, 0.25)) cs = map.contourf(x, y, data, clevs, cmap=plt.cm.jet) cbar = map.colorbar(cs, location='bottom', pad="5%") cbar.set_label('K') lon, lat = 174.7772, -41.2889 xpt,ypt = map(lon,lat) map.plot(xpt,ypt,'bo') plt.title(mp.name) plt.gcf().set_size_inches(10,10) plt.savefig(mp.name + '.png',dpi=100)
class HRRR_native_grid(WRF_native_grid): """AS WRF_native_grid, but with some info about operational HRRR. """ def __init__(self, fpath): W = HRRR(fpath) cen_lat = 38.5 cen_lon = -97.5 tlat1 = 38.5 tlat2 = 38.5 # lllon = -105.43488 # [0,0] lllon = W.lons[0, 0] #lllat = 35.835026 # [0,0] lllat = W.lats[0, 0] #urlon = -96.506653 # [-1,-1] urlon = W.lons[-1, -1] #urlat = 42.708714 # [-1,-1] urlat = W.lats[-1, -1] self.m = Basemap(projection='lcc', lat_1=tlat1, lat_2=tlat2, lat_0=cen_lat, lon_0=cen_lon, llcrnrlon=lllon, llcrnrlat=lllat, urcrnrlon=urlon, urcrnrlat=urlat, resolution='i') self.lons, self.lats, self.xx, self.yy = self.m.makegrid( W.lons.shape[1], W.lons.shape[0], returnxy=True)
def plot_hmap_ortho(h, cmap='jet', mode='log', mx=None, drng=None, res=0.25, verbose=False): m = Basemap(projection='ortho',lat_0=90,lon_0=180,rsphere=1.) if verbose: print 'SCHEME:', h.scheme() print 'NSIDE:', h.nside() lons,lats,x,y = m.makegrid(360/res,180/res, returnxy=True) lons = 360 - lons lats *= a.img.deg2rad; lons *= a.img.deg2rad y,x,z = a.coord.radec2eq(n.array([lons.flatten(), lats.flatten()])) ax,ay,az = a.coord.latlong2xyz(n.array([0,0])) data = h[x,y,z] data.shape = lats.shape data /= h[0,0,1] #data = data**2 # only if a voltage beam data = data_mode(data, mode) m.drawmapboundary() m.drawmeridians(n.arange(0, 360, 30)) m.drawparallels(n.arange(0, 90, 10)) if mx is None: mx = data.max() if drng is None: mn = data.min() # if min < (max - 10): min = max-10 else: mn = mx - drng step = (mx - mn) / 10 levels = n.arange(mn-step, mx+step, step) return m.imshow(data, vmax=mx, vmin=mn, cmap=cmap)
def draw_map(data, time): map = Basemap(projection='cyl', llcrnrlon=0, llcrnrlat=50, urcrnrlon=30, urcrnrlat=75, resolution='l') #, # draw coastlines, country boundaries, fill continents. map.drawcoastlines(linewidth=0.25) map.drawcountries(linewidth=0.25) # map.fillcontinents(color='coral',lake_color='blue') # draw the edge of the map projection region (the projection limb) # map.drawmapboundary(fill_color='aqua') # draw lat/lon grid lines every 30 degrees. map.drawmeridians(np.arange(0, 360, 10)) map.drawparallels(np.arange(-90, 90, 10)) ny = data.shape[0] nx = data.shape[1] lons, lats = map.makegrid( nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = map(lons, lats) # compute map proj coordinates. # draw filled contours. clevs = [ 0, 1, 2.5, 5, 7.5, 10, 15, 20, 30, 40, 50, 70, 100, 150, 200, 250, 300, 400, 500, 600, 750 ] cs = map.contourf(x, y, data, clevs, cmap=cm.s3pcpn) # add colorbar. cbar = map.colorbar(cs, location='bottom', pad="5%") cbar.set_label('mm') plt.title('Radar at {}'.format(time)) plt.show()
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_hmap_ortho(h, cmap='jet', mode='log', mx=None, drng=None, res=0.25, verbose=False): m = Basemap(projection='ortho', lat_0=90, lon_0=180, rsphere=1.) if verbose: print 'SCHEME:', h.scheme() print 'NSIDE:', h.nside() lons, lats, x, y = m.makegrid(360 / res, 180 / res, returnxy=True) lons = 360 - lons lats *= a.img.deg2rad lons *= a.img.deg2rad y, x, z = a.coord.radec2eq(n.array([lons.flatten(), lats.flatten()])) ax, ay, az = a.coord.latlong2xyz(n.array([0, 0])) data = h[x, y, z] data.shape = lats.shape data /= h[0, 0, 1] data = data_mode(data, mode) m.drawmapboundary() m.drawmeridians(n.arange(0, 360, 30)) m.drawparallels(n.arange(0, 90, 10)) if mx is None: mx = data.max() if drng is None: mn = data.min() # if min < (max - 10): min = max-10 else: mn = mx - drng return m.imshow(data, vmax=mx, vmin=mn, cmap=cmap)
def plot_precip(data): ''' data is a 813*1051 matrix containing unnormalized precipitation values ''' fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) m = Basemap(projection='stere',lon_0=lon_0,lat_0=90.,lat_ts=lat_0,\ llcrnrlat=latcorners[0],urcrnrlat=latcorners[2],\ llcrnrlon=loncorners[0],urcrnrlon=loncorners[2],\ rsphere=6371200.,resolution='i', area_thresh=10000) m.drawcoastlines() m.drawstates() m.drawcountries() m.drawlsmask(land_color="#FCF8F3", ocean_color='#E6FFFF') parallels = np.arange(0., 90, 10.) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) meridians = np.arange(180., 360., 10.) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) ny = data.shape[0] nx = data.shape[1] lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) # compute map proj coordinates. clevs = np.array([ 0, 1, 2.5, 5, 7.5, 10, 15, 20, 30, 40, 50, 70, 100, 150, 200, 250, 300, 400, 500, 600, 750 ]) cs = m.contourf(x, y, data, clevs, cmap=cm.s3pcpn) cbar = m.colorbar(cs, location='bottom', pad="5%") cbar.set_label('mm') plt.show()
class WRF_native_grid: def __init__(self, fpath): """Generates a basemap object for a WRF file's domain. """ if not isinstance(fpath, str): W = fpath else: W = WRFOut(fpath) cen_lat = W.nc.CEN_LAT cen_lon = W.nc.CEN_LON tlat1 = W.nc.TRUELAT1 tlat2 = W.nc.TRUELAT2 lllon = W.lons[0, 0] lllat = W.lats[0, 0] urlon = W.lons[-1, -1] urlat = W.lats[-1, -1] self.m = Basemap(projection='lcc', lat_1=tlat1, lat_2=tlat2, lat_0=cen_lat, lon_0=cen_lon, llcrnrlon=lllon, llcrnrlat=lllat, urcrnrlon=urlon, urcrnrlat=urlat, resolution='i') self.lons, self.lats, self.xx, self.yy = self.m.makegrid( W.lons.shape[1], W.lons.shape[0], returnxy=True)
def plot_field_on_map(lat, lon, field, title=""): fig = plt.figure(figsize=(8, 5)) # m = Basemap(projection='cyl', llcrnrlat=-85, urcrnrlat=85, llcrnrlon=-180, urcrnrlon=180, resolution=None) m = Basemap(projection="mill", lon_0=0) parallels = np.arange(-180., 180., 45.) meridians = np.arange(-120., 140., 60.) m.drawmeridians(meridians, labels=[0, 0, 0, 1]) m.drawparallels(parallels, labels=[1, 0, 0, 0]) # m.drawlsmask(land_color="dimgrey", ocean_color="white", lakes=True) m.drawcoastlines() m.drawmapboundary(fill_color='aqua') # m.fillcontinents(color='coral', lake_color='aqua', alpha=0.5) ny, nx = field.shape lons, lats = m.makegrid(nx, ny) x, y = m(lons, lats) # print(x) # print(x.shape) cs = m.contourf(x, y, field) cb = m.colorbar(cs, location="bottom", pad="5%", label="Precipitation") # plt.tight_layout() # plt.gca() # plt.subplots_adjust(bottom=-0.8) plt.savefig("Images/map.png", dpi=300) plt.show() plt.close()
def gr_map(chirps_mean, data, min_lat, max_lat, min_lon, max_lon): print 'hi' print 'extents', min_lat, max_lat, min_lon, max_lon data = np.mean(data, axis=(1, 2))[1, :, :] print data.shape print np.max(data.flatten()) print np.min(data.flatten()) m = Basemap(projection='merc', llcrnrlat=min_lat, urcrnrlat=max_lat, llcrnrlon=min_lon, urcrnrlon=max_lat, lat_ts=20, resolution='c') m.drawcoastlines() #m.fillcontinents(color='coral',lake_color='aqua') # draw parallels and meridians. m.drawparallels(np.arange(-90., 91., 30.)) m.drawmeridians(np.arange(-180., 181., 60.)) ny = data.shape[0] nx = data.shape[1] lons, lats = m.makegrid(nx, ny) x, y = m(lons, lats) clevs = [0.0001, 0.0002, 0.0003, 0.0004] cs = m.contourf(x, y, data, clevs, cmap=cm.s3pcpn) m.drawmapboundary(fill_color='aqua') plt.title("Mercator Projection") plt.show()
def generate_s5p_image_from_data(data, lon, lat, layer): imgTiff = data * 1e4 xmin, ymin, xmax, ymax = get_bounding_box(lon, lat, 1280, 720, reso=2e3) inProj = Proj(init='epsg:4326') outProj = Proj(init='epsg:3857') photo = io.BytesIO() photo.name = 'image.png' lonmin, latmin = transform(outProj, inProj, xmin, ymin) lonmax, latmax = transform(outProj, inProj, xmax, ymax) m = Basemap(projection='merc', llcrnrlat=latmin, urcrnrlat=latmax, llcrnrlon=lonmin, urcrnrlon=lonmax, resolution='i') m.drawcoastlines() m.drawcountries() ny = imgTiff.shape[0] nx = imgTiff.shape[1] ma1 = np.ma.masked_values(imgTiff, 0, copy=False) ma = np.ma.masked_where(ma1 < 0, ma1, copy=False) lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) # compute map proj coordinates. cs = m.contourf(x, y, np.flip(ma, 0), cmap=plt.cm.jet) cbar = m.colorbar(cs, location='bottom', pad="5%") cbar.set_label(f'{layer}' + r' in $mol / cm^2$ ' + f'at lon = {"%.1f" % lon}, lat = {"%.1f" % lat}') plt.savefig(photo) photo.seek(0) plt.clf() return photo
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 plot_var(lats, lons, data, units, title, clevs=None, mutable={'save': SAVE}): # create figure and axes instances fig = plt.figure(figsize=(10, 10)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) m = Basemap(projection='merc', lat_ts=45.0, llcrnrlat=lats[0], urcrnrlat=lats[-1], llcrnrlon=lons[0], urcrnrlon=lons[-1], resolution='i', ax=ax) # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines() m.drawcountries() # draw parallels. parallels = np.arange(0., 90, 5.) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) # draw meridians meridians = np.arange(0., 360., 5.) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) ny = data.shape[0] nx = data.shape[1] lonz, latz = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = m(lonz, latz) # compute map proj coordinates. # draw filled contours. #clevs = [0,1,2.5,5,7.5,10,15,20,30,40,50,70,100,150,200,250,300,400,500,600,750] if clevs is None: cs = m.contourf(x, y, np.transpose(data)) #,clevs)cmap=cm.s3pcpn) #cs = m.contourf(x,y,data) #,clevs)cmap=cm.s3pcpn) else: cs = m.contourf(x, y, np.transpose(data), levels=clevs) #,clevs)cmap=cm.s3pcpn) #cs = m.contourf(x,y,data, levels=clevs) #,clevs)cmap=cm.s3pcpn) # add colorbar. cbar = m.colorbar(cs, location='bottom', pad="5%") cbar.set_label(units) # add title plt.title(title) if 'save' not in mutable: mutable['save'] = True if 'save_cnt' not in mutable: mutable['save_cnt'] = 1 if mutable['save']: plt.savefig('figure_%s.png' % mutable['save_cnt']) mutable['save_cnt'] += 1
def plot_figure(data_0,lat_0,lon_0,dataLimit, title_str, name_str, index): ##Input data information: #data_0 = the temperature file that want to plot. Should be in format data[len(lat_0), len(lon_0)] #lat_0 = latitude #lon_0 = longitude #title_str & name_str = the title refers to the plot, '' will have no title, and name_str is how it will be saved. #dataLimit = the maximum and minimum values for the colorbar in format [min, max] #index = Climatology, Anomaly, Average - one of these three (will alter the title) ## Return data information: # No data is return. Only one file is saved lat_0 = lat_0- 0.5*(lat_0[1]-lat_0[0]) lon_0 = lon_0- 0.5*(lon_0[1]-lon_0[0]) #Caculate borders for the domain latcorners = [lat_0.min(),lat_0.max()] loncorners = [lon_0.min(),lon_0.max()] #Add basemap m = Basemap(projection='merc',llcrnrlon=loncorners[0],llcrnrlat=latcorners[0],urcrnrlon=loncorners[1],urcrnrlat=latcorners[1],resolution='l',area_thresh=10) m.drawmapboundary() m.drawcoastlines() m.drawcountries() #Draw parallels and meridians parallels = np.arange(lat_0.min(),lat_0.max(),10) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=12) meridians = np.arange(lon_0.min(),lon_0.max(),10) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=12) #Compute map proj coordinates data = data_0 ny = data.shape[0] nx = data.shape[1] lons,lats = m.makegrid(nx,ny) x,y = m(lons,lats) #Specify colormaps if index == 'Climatology' or index == 'Average': cmap = plt.cm.coolwarm elif index == 'Anomaly': cmap = plt.cm.bwr else: cmap = plt.cm.coolwarm #Plotting cs = m.pcolormesh(x,y,data,cmap=cmap) #Define data range cs.set_clim(dataLimit[0],dataLimit[1]) #Add colorbar cbar = m.colorbar(cs,location='bottom',pad="5%") cbar.set_label('K',fontsize=13) #Add title and save figures plt.title(title_str,fontsize=13) plt.savefig(name_str,dpi=200,bbox_inches='tight') plt.close()
def PPI(self, rs, data, elev, moment, figname): figname = self.dirname + figname data = rs.cartesian(data[:, :, elev], elev) fig = plt.figure(figsize=(8, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) latmin, latmax, lonmin, lonmax = rs.radar_limits(elev) m = Basemap(projection='cyl', lon_0=rs.radar_lon, lat_0=rs.radar_lat, llcrnrlat=latmin, urcrnrlat=latmax, llcrnrlon=lonmin, urcrnrlon=lonmax, resolution='h', suppress_ticks=True) #m.drawcoastlines(color='0', linewidth=1) #m.drawstates(color='0', linewidth=1) #m.drawcountries(color='0', linewidth=1) #m.drawrivers(color='blue') #m.fillcontinents(color='#cc9955', lake_color='aqua', zorder = 0) #cor do continente #m.drawmapboundary(fill_color='aqua') #cor do mar parallels = np.arange(-90, 0, 1.) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10, linewidth=0.0) meridians = np.arange(180., 360., 1.) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10, linewidth=0.0) numcols, numrows = data.shape lons, lats = m.makegrid( numcols, numrows) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) # compute map proj coordinates. cmap, clevs, unit, title = cm.get_info(moment) norm = mpl.colors.BoundaryNorm(clevs, cmap.N) contour = m.contourf(x, y, data, clevs, cmap=cmap, norm=norm) cbar = m.colorbar(contour, cmap=cmap, norm=norm, spacing='uniform', location='right', pad='2%', size='5%') cbar.set_label(unit, rotation='horizontal') plt.title(title + u' (%.1f°)\n%s' % (rs.fixed_angle[elev], rs.date)) self.draw_circle(rs, m, elev) #desenha o círculo do raio do radar plt.savefig(figname)
def plotmaxT(filepath): grbs = pygrib.open('rawfile/' + filepath) grb = grbs.select(name='Maximum temperature')[0] maxt = grb.values.T lats, lons = grb.latlons() maxt, lats, lons = grb.data(lat1=-90, lat2=90, lon1=0, lon2=359.75) maxt2 = [] for i in range(maxt.shape[0]): maxt2.append(maxt[maxt.shape[0] - i - 1]) maxt = np.array(maxt2) #print(maxt) # create figure and axes instances fig = plt.figure(figsize=(11, 7)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ''' m = Basemap(llcrnrlon=0., llcrnrlat=-90., urcrnrlon=359.75, urcrnrlat=90., \ rsphere=(6378137.00, 6356752.3142), \ resolution='l', projection='merc', \ lat_0=0.25, lon_0=0.25, lat_ts=20.) ''' m = Basemap(llcrnrlon=0., llcrnrlat=-90., urcrnrlon=359.75, urcrnrlat=90.) #m = Basemap(projection='robin',lon_0=0,resolution='c') # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines() m.drawstates() m.drawcountries() # draw parallels. parallels = np.arange(-90., 90., 20.) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) # draw meridians meridians = np.arange(0., 360., 20.) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) ny = maxt.shape[0] nx = maxt.shape[1] lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) # compute map proj coordinates. # draw filled contours. clevs = [ -40, -36, -32, -28, -24, -20, -16, -12, -8, -4, 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40 ] cs = m.contourf(x, y, maxt - 273.15, clevs, cmap=cm.GMT_haxby) # add colorbar. cbar = m.colorbar(cs, location='bottom', pad="5%") cbar.set_label('°C') # add title plt.title('example plot: ' + filepath + 'z global 2m maximum Temprature (°C)') plt.savefig('product/' + filepath + '.png') plt.clf() plt.close(fig)
def plot_processing(data_0, lat_0, lon_0, lat_down, lat_up, lon_left, lon_right, grid_lat, grid_lon, data_range, title_str, name_str, index): #Find borders of the domain L1, R1, L2, R2 = find_point(lat_0, lon_0, lat_down, lat_up, lon_left, lon_right) lat_0 = lat_0 - 0.5 * (lat_0[1] - lat_0[0]) lon_0 = lon_0 - 0.5 * (lon_0[1] - lon_0[0]) lat = lat_0[L1:R1 + 1] lon = lon_0[L2:R2 + 1] latcorners = [lat.min(), lat.max()] loncorners = [lon.min(), lon.max()] #Add basemap #For map resolution, there are five options: c(crude),l(low),i(intermediate),h(high),f(full) #Higher resolution requires more time, defalut using low resolution m = Basemap(projection='merc', llcrnrlon=loncorners[0], llcrnrlat=latcorners[0], urcrnrlon=loncorners[1], urcrnrlat=latcorners[1], resolution='l') m.drawmapboundary() m.drawcoastlines() m.drawcountries() #Draw parallels and meridians parallels = numpy.arange(lat_down, lat_up, grid_lat) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=12) meridians = numpy.arange(lon_left, lon_right, grid_lon) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=12) #Compute map proj coordinates data = data_0[L1:R1 + 1, L2:R2 + 1] ny = data.shape[0] nx = data.shape[1] lons, lats = m.makegrid(nx, ny) x, y = m(lons, lats) #Specify colormaps if index == 'Climatology' or index == 'Average': cmap = plt.cm.gist_earth_r if index == 'Anomaly': cmap = plt.cm.BrBG #Plotting cs = m.pcolormesh(x, y, data, cmap=cmap) #Define data range cs.set_clim(data_range[0], data_range[1]) #Add colorbar cbar = m.colorbar(cs, location='bottom', pad="5%") cbar.set_label('mm/day', fontsize=13) #Add title and save figures plt.title(title_str, fontsize=13) plt.savefig(name_str, dpi=200, bbox_inches='tight') plt.close()
def create_contour_plot(data, out_file_path, lat_min, lon_min, lat_max, lon_max, plot_title, basemap=None, clevs=None, cmap=plt.get_cmap('Reds')): """ create a contour plot using basemap :param cmap: color map :param clevs: color levels :param basemap: creating basemap takes time, hence you can create it outside and pass it over :param plot_title: :param data: 2D grid data :param out_file_path: :param lat_min: :param lon_min: :param lat_max: :param lon_max: :return: """ fig = plt.figure(figsize=(8.27, 11.69)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) if basemap is None: basemap = Basemap(projection='merc', llcrnrlon=lon_min, llcrnrlat=lat_min, urcrnrlon=lon_max, urcrnrlat=lat_max, resolution='h') basemap.drawcoastlines() parallels = np.arange(math.floor(lat_min) - 1, math.ceil(lat_max) + 1, 1) basemap.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) meridians = np.arange(math.floor(lon_min) - 1, math.ceil(lon_max) + 1, 1) basemap.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) ny = data.shape[0] nx = data.shape[1] lons, lats = basemap.makegrid(nx, ny) if clevs is None: clevs = np.arange(-1, np.max(data) + 1, 1) # cs = basemap.contourf(lons, lats, data, clevs, cmap=cm.s3pcpn_l, latlon=True) cs = basemap.contourf(lons, lats, data, clevs, cmap=cmap, latlon=True) cbar = basemap.colorbar(cs, location='bottom', pad="5%") cbar.set_label('mm') plt.title(plot_title) plt.draw() fig.savefig(out_file_path) plt.close()
def get_NAM_native_grid(): m = Basemap(projection='lcc', llcrnrlon=-133.459, llcrnrlat=12.190, urcrnrlon=-49.420, urcrnrlat=57.328, lat_1=25.0, lon_0=-95.0) lons, lats, xx, yy = m.makegrid(614, 428, returnxy=True) return m, lons, lats, xx[0, :], yy[:, 0]
def setMap(lats, lons, data, showstations): x = np.array(lons) y = np.array(lats) z = np.array(data) # corners of the map lon_min = np.min(x) - 1 lon_max = np.max(x) + 1 lat_min = np.min(y) - 1 lat_max = np.max(y) + 1 if individual: data_min = np.min(z) data_max = np.max(z) else: data_min = data_min_fix data_max = data_max_fix # general map m = Basemap(projection='merc', llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, resolution=map_res, area_thresh=100) m.drawcoastlines() m.drawstates() m.drawcountries() if not showstations: y_inc = (lat_max - lat_min) / grd_res x_inc = (lon_max - lon_min) / grd_res y_steps = np.linspace(lat_min, lat_max + grd_res, y_inc) x_steps = np.linspace(lon_min, lon_max + grd_res, x_inc) x_steps, y_steps = np.meshgrid(x_steps, y_steps) zgrd = matplotlib.mlab.griddata(x, y, z, x_steps, y_steps) xgrd, ygrd = m.makegrid(zgrd.shape[1], zgrd.shape[0]) #xgrd,ygrd= np.meshgrid(x_steps,y_steps) #zgrd = scipy.interpolate.griddata((x, y), z, (xgrd, ygrd), method='nearest') xgrd, ygrd = m(xgrd, ygrd) m.contourf(xgrd, ygrd, zgrd, cmap=plt.cm.hot_r, vmin=data_min, vmax=data_max) else: # measurement stations xpts, ypts = m(lons, lats) m.plot(xpts, ypts, 'bo')
def generate_radar_latlons( self): #(dim0,dim1,ll_lon,ll_lat,ur_lon,ur_lat): ''' Generate lats,lons for polar stereographically projected radar from data characteristics (predetermined cases: new Dutch radar, old Dutch radar, European composite) ''' import pickle dim0, dim1 = self.values.shape if dim0 == 765: ## high-res dutch radar raddomain = 'nlrad' (ll_lat, ll_lon) = (49.362, 0.) (ur_lat, ur_lon) = (55.389, 10.856) elif dim0 == 256: ## low-res dutch radar raddomain = 'oldrad' (ll_lat, ll_lon) = (49.769, 0.) (ur_lat, ur_lon) = (54.818, 9.743) elif dim0 == 512: ## european composite raddomain = 'eurrad' (ll_lat, ll_lon) = (41.937, -9.271) (ur_lat, ur_lon) = (58.089, 20.453) home = os.getenv('HOME') mapdir = os.path.join(home, 'python/tools') mappkl = os.path.join(mapdir, raddomain + '.pkl') if os.path.exists(mappkl): f = open(mappkl, 'r') polmap = pickle.load(f) f.close() elif 0: # possibly faster (!?) sys.path.append(mapdir) #'/usr/people/plas/python/tools' import bmap polmap = bmap.myMap(domain=raddomain, modelname='radar').bmap else: # if this fails (?) # import basemap: from mpl_toolkits.basemap import Basemap # map functionality polmap = Basemap(projection='stere', lat_0=90., lon_0=0., lat_ts=60., llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat) lons, lats = polmap.makegrid(dim1, dim0, returnxy=False) #print 'LON',lons,'\nLAT',lats self.latlons = (lats, lons)
def makeSubplot(grid, data, row, col, title, seq_or_div): ax = grid[0] ax.set_facecolor('.25') m = Basemap(ax = ax) ny=data.shape[0] nx=data.shape[1] lons, lats = m.makegrid(nx, ny) x, y = m(lons, lats) # min_val = np.min(np.abs(data)) # max_val = np.max(np.abs(data)) def make_cmap(seq_or_div): min_val = -11 max_val = 11 levels = np.linspace(min_val, max_val, 23) if seq_or_div == 'seq': cmap = cm.Blues norm = Normalize(vmin = min_val, vmax = max_val) elif seq_or_div == 'div': cmap = cm.seismic norm = MidPointNorm(midpoint=0, vmin=min_val, vmax=max_val) return cmap, norm, levels cmap, norm, levels = make_cmap(seq_or_div) cs = m.contourf(x, y, data, levels, ax=ax, cmap=cmap, norm=norm) m.ax.tick_params(labelsize=2) ax.set_title(title, fontsize=10) ax.set_ylabel(row['ylabel'], fontsize=10, labelpad = 60, rotation=0, verticalalignment ='center') # draw parallels and meridians. m.drawparallels([-60, -30, 0, 30, 60], labels=[1,0,0,0], ax = ax, rotation=30, fontsize=8, linewidth=0) m.drawmeridians([-135, -90, -45, 0, 45, 90, 135], labels=[0,0,0,1], ax = ax, rotation=40, fontsize=8, linewidth=0) if row['var'] == 'tsurf': m.contour(x, y, data, ax=ax, levels = [0], colors=('k',),linestyles=('-.',),linewidths=(1,)) parallels = col['parallels'] meridians = col['meridians'] if 'Aqua' not in title: x1, y1 = m(meridians[0], parallels[0]) x2, y2 = m(meridians[0], parallels[1]) x3, y3 = m(meridians[1], parallels[1]) x4, y4 = m(meridians[1], parallels[0]) cont_boundary = Polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], facecolor='none', edgecolor='black', linewidth=1) ax.add_patch(cont_boundary) grid.cbar_axes[0].colorbar(cs)
def get_lat_lon_arr(resolution): """ Purpose: Get longitude and latitude grids to use as features """ datapath = '../../../Data/' m = Basemap(projection='npstere',boundinglat=65,lon_0=0, resolution='l') dx_res = resolution * 1000 nx = int((m.xmax-m.xmin)/dx_res)+1; ny = int((m.ymax-m.ymin)/dx_res)+1 lonsG, latsG, _, _ = m.makegrid(nx, ny, returnxy=True) return latsG, lonsG
def create_new_grid(Nlim=None, Elim=None, Slim=None, Wlim=None, proj='merc', lat_ts=None, resolution='i', nx=None, ny=None, tlat1=30.0, tlat2=60.0, cen_lat=None, cen_lon=None, lllon=None, lllat=None, urlat=None, urlon=None): """Create new domain for interpolating to, for instance. The following are mandatory arguments for mercator ('merc'): Nlim,Elim,Slim,Wlim = lat/lon/lat/lon limits for north/east/south/west respectively lat_ts = latitude of true scale? nx,ny = number of points in the x/y direction respectively """ if proj == 'merc': if None in (Nlim, Elim, Slim, Wlim, lat_ts, nx, ny): print("Check non-optional arguments.") raise Exception m = Basemap(projection=proj, llcrnrlat=Slim, llcrnrlon=Wlim, urcrnrlat=Nlim, urcrnrlon=Elim, lat_ts=lat_ts, resolution='h') elif proj == 'lcc': if None in (tlat1, tlat2, cen_lat, cen_lon, lllon, lllat, urlon, urlat, nx, ny): print("Check non-optional arguments.") raise Exception m = Basemap(projection='lcc', lat_1=tlat1, lat_2=tlat2, lat_0=cen_lat, lon_0=cen_lon, llcrnrlon=lllon, llcrnrlat=lllat, urcrnrlon=urlon, urcrnrlat=urlat, resolution='i') lons, lats, xx, yy = m.makegrid(nx, ny, returnxy=True) return m, lons, lats, xx[0, :], yy[:, 0]
class GridPlot(Argument, Settings): """ROC绘图""" parameters = dict() # 命令行参数,参考 https://docs.python.org/2/howto/argparse.html command_args = [ [('npy',), {'help': u'指定一个csv2npy后生成的.npy文件', 'type': str, 'nargs': 1}], [('-n','--name',), {'help': u'输出结果文件名', 'type': str, 'nargs': 1}], [('-t','--title',), {'help': 'plot image title', 'type': str, 'nargs': 1}], [('-v','--verbose',), {'help': u'输出详细信息', 'action':"store_true"}] ] def __init__(self): """init""" Argument.__init__(self) Settings.__init__(self) self.parse_args() def parse_args(self): """parse arguments""" if self.args.npy and os.path.isfile(self.args.npy[0]): self.parameters['npy'] = self.args.npy[0] else: print('{} not found!'.format(self.args.npy[0])) exit(-1) self.parameters['name'] = self.args.name[0] if self.args.name else tf.mktemp(suffix='.png',dir='.') self.parameters['title'] = self.args.title[0] if self.args.title else 'Grid Plot' if self.args.verbose: print("============parameters===========") for key in self.parameters: print(key,self.parameters[key]) self.process() def process(self): """ process """ ##load data data = np.load(self.parameters['npy']) ##create basemap self.bm = Basemap(projection='cyl',resolution='l',lon_0=120) self.bm.drawcoastlines(linewidth=0.25) self.bm.drawcountries(linewidth=0.25) #self.bm.fillcontinents(color='grey') lons,lats = self.bm.makegrid(360,181) x,y = self.bm(lons,lats) self.bm.contourf(x,y,data) ##add colorbar self.bm.colorbar(location='bottom',size='5%',label="mm") ##add plot title plt.title(self.parameters['title']) ##save plot plt.savefig(self.parameters['name'])
def setMap(lats, lons, data, showstations): x = np.array(lons) y = np.array(lats) z = np.array(data) # corners of the map lon_min = np.min(x) - 1 lon_max = np.max(x) + 1 lat_min = np.min(y) - 1 lat_max = np.max(y) + 1 if individual: data_min = np.min(z) data_max = np.max(z) else: data_min = data_min_fix data_max = data_max_fix # general map m = Basemap( projection="merc", llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, resolution=map_res, area_thresh=100, ) m.drawcoastlines() m.drawstates() m.drawcountries() if not showstations: y_inc = (lat_max - lat_min) / grd_res x_inc = (lon_max - lon_min) / grd_res y_steps = np.linspace(lat_min, lat_max + grd_res, y_inc) x_steps = np.linspace(lon_min, lon_max + grd_res, x_inc) x_steps, y_steps = np.meshgrid(x_steps, y_steps) zgrd = matplotlib.mlab.griddata(x, y, z, x_steps, y_steps) xgrd, ygrd = m.makegrid(zgrd.shape[1], zgrd.shape[0]) # xgrd,ygrd= np.meshgrid(x_steps,y_steps) # zgrd = scipy.interpolate.griddata((x, y), z, (xgrd, ygrd), method='nearest') xgrd, ygrd = m(xgrd, ygrd) m.contourf(xgrd, ygrd, zgrd, cmap=plt.cm.hot_r, vmin=data_min, vmax=data_max) else: # measurement stations xpts, ypts = m(lons, lats) m.plot(xpts, ypts, "bo")
def get_SAL_native_grid(): m = Basemap(projection='merc',llcrnrlat=34.0,llcrnrlon=-110.0, urcrnrlat=45.0,urcrnrlon=-85.0,lat_ts=39.5,) # m = Basemap(projection='lcc',llcrnrlat=34.0,llcrnrlon=-110.0, # urcrnrlat=45.0,urcrnrlon=-85.0,lat_0=30.0,lat_1=50.0,lon_0=-95.0) lons, lats, xx, yy = m.makegrid(537,308,returnxy=True) # print(xx[5,-1] - xx[5,-2]) # print(xx[5,1] - xx[5,0]) # print(yy[-1,5] - yy[-2,5]) # print(yy[1,5] - yy[0,5]) # import pdb; pdb.set_trace() # 4 km spacing return m, lons, lats, xx[0,:], yy[:,0]
class WRF_native_grid: def __init__(self,fpath,resolution='i',xy1D=True): """Generates a basemap object for a WRF file's domain. """ # keyword arguments to basemap generation self.kwargs = {'resolution':resolution} self.load_wrfout(fpath) self.load_attrs() self.load_corners() self.generate_basemap() if xy1D: self.xx = self.xx[0,:] self.yy = self.yy[:,0] self.combine_scopes() def load_wrfout(self,fpath): self.W = WRFOut(fpath) return def load_attrs(self,): self.kwargs['lat_0'] = self.W.nc.CEN_LAT self.kwargs['lon_0'] = self.W.nc.CEN_LON self.kwargs['lat_1'] = self.W.nc.TRUELAT1 self.kwargs['lat_2'] = self.W.nc.TRUELAT2 def load_corners(self): self.kwargs['llcrnrlon'] = self.W.lons[0,0] self.kwargs['llcrnrlat'] = self.W.lats[0,0] self.kwargs['urcrnrlon'] = self.W.lons[-1,-1] self.kwargs['urcrnrlat'] = self.W.lats[-1,-1] def generate_basemap(self): self.m = Basemap(projection='lcc',**self.kwargs) self.lons, self.lats, self.xx, self.yy = self.m.makegrid( self.W.lons.shape[1],self.W.lons.shape[0],returnxy=True) def combine_scopes(self): """ Put kwargs dictionary into self's namespace """ self.__dict__ = dict(self.__dict__,**self.kwargs) # Alias of domain limits self.Wlim = self.llcrnrlon self.Slim = self.llcrnrlat self.Nlim = self.urcrnrlat self.Elim = self.urcrnrlon
def graph_pred_truth(predictions, forMonth, year, resolution): """ Purpose: Graph prediction and truth grids """ #Graph predictions m = Basemap(projection='npstere',boundinglat=65,lon_0=0, resolution='l') dx_res = resolution * 1000 nx = int((m.xmax-m.xmin)/dx_res)+1; ny = int((m.ymax-m.ymin)/dx_res)+1 #grid_str=str(int(dx_res/1000))+'km' lonsG, latsG, xptsG, yptsG = m.makegrid(nx, ny, returnxy=True) # Get lon/lats pf the ice concentration data on polar sterographic grid datapath = '../../../Data/' lats, lons = ff.get_psnlatslons(datapath) xpts, ypts =m(lons, lats) monthStr = get_month_str(forMonth) yearStr = str(year) fig_title = 'Comparison for ' + monthStr + ' ' + yearStr fig = figure(figsize=(6,6)) fig.suptitle(fig_title, fontsize=18) ax = fig.add_subplot(221) ax.set_title('Predictions for ' + monthStr + ' ' + yearStr) im1 = m.pcolormesh(xptsG , yptsG, predictions, cmap=cm.Blues_r, vmin=0, vmax=1,shading='flat', zorder=2) truthGrid = get_conc_grid(forMonth, year, resolution) ax = fig.add_subplot(223) ax.set_title('Truth for ' + monthStr + ' ' + yearStr) im2 = m.pcolormesh(xptsG , yptsG, truthGrid, cmap=cm.Blues_r, vmin=0, vmax=1,shading='flat', zorder=2) #Calculate ice extent and ice areas areaStr = "Ice Area: \n\nIce Extent: " ax = fig.add_subplot(222) ax.axis('off') ax.text(0.05, 0.95, areaStr, fontsize=12, verticalalignment='top') ax = fig.add_subplot(224) ax.axis('off') ax.text(0.05, 0.95, areaStr, fontsize=12, verticalalignment='top') plt.show()
def interpolated_color_map(lats, lons, values, spatial_resolution=0.1, interp='nn', cmap=None): #cm.s3pcpn): lat_0 = 51 lat_min = 47 lat_max = 55 lon_0 = 10 lon_min = 5 lon_max = 16 m = Basemap(projection='tmerc', lat_0=lat_0, lon_0=lon_0, llcrnrlat=lat_min, llcrnrlon=lon_min, urcrnrlat=lat_max, urcrnrlon=lon_max, resolution='i') m.drawcoastlines() m.drawcountries() m.drawmapboundary() lats = np.array(lats) lons = np.array(lons) values = np.array(values) lat_inum = (lat_max - lat_min) / spatial_resolution lon_inum = (lon_max - lon_min) / spatial_resolution # xi = np.linspace(lat_min, lat_max + spatial_resolution, xinum) # yi = np.linspace(lon_min, lon_max + spatial_resolution, yinum) lat_i = np.linspace(lat_min, lat_max, lat_inum) lon_i = np.linspace(lon_min, lon_max, lon_inum) lat_i, lon_i = np.meshgrid(lat_i, lon_i) value_i = griddata(lats, lons, values, lat_i, lon_i, interp=interp) lat_grid, lon_grid = m.makegrid(value_i.shape[1], value_i.shape[0]) x_grid, y_grid = m(lat_grid, lon_grid) m.contourf(x_grid, y_grid, value_i, cmap=cmap) m.scatter(lats, lons, color='k', s=50, latlon=True) plt.show()
def create_new_grid(Nlim=None,Elim=None,Slim=None,Wlim=None,proj='merc', lat_ts=None,resolution='i',nx=None,ny=None, tlat1=30.0,tlat2=60.0,cen_lat=None,cen_lon=None, lats=None,lons=None,dx=None): # lllon=None,lllat=None,urlat=None,urlon=None): """Create new domain for interpolating to, for instance. The following are mandatory arguments for mercator ('merc'): Nlim,Elim,Slim,Wlim = lat/lon/lat/lon limits for north/east/south/west respectively lat_ts = latitude of true scale? nx,ny = number of points in the x/y direction respectively """ if proj == 'merc': if nx is None: assert dx if None in (Nlim,Elim,Slim,Wlim,lat_ts): print("Check non-optional arguments.") raise Exception m = Basemap(projection=proj,llcrnrlat=Slim,llcrnrlon=Wlim, urcrnrlat=Nlim,urcrnrlon=Elim,lat_ts=lat_ts,resolution=resolution) if dx: # llcrnr xW, yS = m(Wlim, Slim) # urcrnr xE, yN = m(Elim, Nlim) # km difference in x (lon) direction xdiff_km = abs(xE-xW)/1000 # and in y (lat) direction ydiff_km = abs(yS-yN)/1000 # nx needed to give dx requested nx = int(N.floor(xdiff_km/dx)) # assume dx=dy ny = int(N.floor(ydiff_km/dx)) elif proj == 'lcc': # if None in (tlat1,tlat2,cen_lat,cen_lon,lllon,lllat,urlon,urlat,nx,ny): if None in (tlat1,tlat2,cen_lat,cen_lon,Nlim,Elim,Slim,Wlim,nx,ny): print("Check non-optional arguments.") raise Exception m = Basemap(projection='lcc',lat_1=tlat1,lat_2=tlat2,lat_0=cen_lat, lon_0=cen_lon,llcrnrlon=Wlim,llcrnrlat=Slim, urcrnrlon=Elim,urcrnrlat=Nlim,resolution='h') lons, lats, xx, yy = m.makegrid(nx,ny,returnxy=True) # pdb.set_trace() return m, lons, lats, xx, yy
def plot_global(dataset, variable, pngpath, dataset_id, debug=False): m = Basemap(projection="eck4",lon_0=0,resolution='c') m.drawcoastlines() m.fillcontinents(color='coral',lake_color='aqua') m.drawparallels(np.arange(-90.,120.,30.)) m.drawmeridians(np.arange(0.,360.,60.)) m.drawmapboundary(fill_color='aqua') ny = dataset[variable].shape[0] nx = dataset[variable].shape[1] lons, lats = m.makegrid(nx, ny) x, y = m(lons, lats) m.contourf(x, y, dataset[variable]) plt.title(variable) plt.plot(variable) plt.savefig(pngpath, dpi=100)
class TkMap: def __init__(self, root): self.fig = None self.ax1 = None self.map = None self.canvas = None self.tk_canvas = None self.zoom = None self.fig = Figure() # add a grid with one row and one column (= a single graph) self.ax1 = self.fig.add_subplot(111) # draw a Basemap onto this grid self.map = Basemap(ax=self.ax1, **params) # link the grid to a Tk.Canvas self.canvas = FigureCanvasTkAgg(self.fig, master=root) self.canvas.show() self.tk_canvas = self.canvas.get_tk_widget() self.tk_canvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) # add zoom/pan functions to the grid self.zoom = Zoom.ZoomPan() self.zoom.zoom_factory(self.ax1) self.zoom.pan_factory(self.ax1) self.draw_basemap() def draw_basemap(self): # draw map self.map.drawcoastlines() self.map.drawmapboundary(fill_color='aqua') self.map.fillcontinents(color='coral', lake_color='aqua') # draw parallels and meridians. # labels = [left,right,top,bottom] parallels = np.arange(-80, 81, 20.) self.map.drawparallels(parallels, labels=[True, False, False, False]) meridians = np.arange(-180, 180, 40.) self.map.drawmeridians(meridians, labels=[False, False, False, True]) def draw_data(self, data): y, x = len(data), len(data[0]) X, Y = self.map.makegrid(x, y) self.map.contour(X, Y, data) # ToDo: Colorbar def redraw(self): self.canvas.draw()
def plot_map(values, axis, cmap=plt.cm.get_cmap("viridis"), colorbar=True, invert_colorbar=False, overwrite_colorbar_boundaries=False, colorbar_min=0, colorbar_max=1): """ Plot values on a Basemap map Args: values (numpy.ndarray): 2-d array with dimensions latitude and longitude axis: Axis on which the map should be displayed cmap (optional): matplotlib.Colormap to use Defaults to plt.cm.get_cmap("viridis") colorbar (boolean, optional): Boolean indicating if a colorbar should be plotted Defaults to True invert_colorbar (boolean, optional): Boolean indicating if the colobar should be inverted overwrite_colorbar_boundaries (boolean, optional): Boolean indicating if the colorbar boundaries should be overwritten Defaults to False colorbar_min (int, optional): Minimum value for colorbar (if colorbar is overwritten) Defaults to 0 colorbar_max (int, optional): Maximum value for colorbar (if colorbar is overwritte) Defaults to 1 """ #Create Colormap vmin = np.min(values) vmax = np.max(values) if overwrite_colorbar_boundaries: vmin = colorbar_min vmax = colorbar_max #Create map m = Basemap(projection='mill', lon_0=30, resolution='l', ax=axis) m.drawcoastlines() lons, lats = m.makegrid(512, 256) x, y = m(lons, lats) #Draw values in map cs = m.contourf(x, y, np.flipud(values), cmap=cmap, vmin=vmin, vmax=vmax) if colorbar: #Create Colorbar cbar = m.colorbar(cs, location='bottom', pad="5%") cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), rotation=45) if invert_colorbar: cbar.ax.invert_xaxis()
def insetplot(self, pt, lonflip=False): '''Create an inset plot that shows where the cross-section is. Be sure to include the top level of potential temperature (pt) here as the only argument passed. Technically, you could use any level of pt, but whichever level you choose will be the one that is used to find the ocean and continents in the inset plot.''' if lonflip: pt = np.hstack((pt[:, (pt.shape[1] / 2):], pt[:, :(pt.shape[1] / 2)])) axin = plt.axes([.14, .35, .15, .12]) xinset, yinset = np.meshgrid(self.dlons, self.dlats) m = Basemap(ax=axin, projection='eck4', lon_0=0, resolution='c') xxinsetold, yyinsetold = m(xinset, yinset) lons, lats, xxinsetnew, yyinsetnew = m.makegrid(500, 500, returnxy=True) ptnew = griddata2((xxinsetold.ravel(), yyinsetold.ravel()), pt.ravel(), (xxinsetnew, yyinsetnew), method='linear') l = ptnew > 100000 # find where land exists s = ptnew < 100000 # find where sea exists sc1 = m.scatter(xxinsetnew[l], yyinsetnew[l], c='coral', edgecolor='None', s=.6) sc1 = m.scatter(xxinsetnew[s], yyinsetnew[s], c='aqua', edgecolor='None', s=.6) # project the coordinates of the vertices of the multi-segmented panel: if lonflip: linex, liney = m( np.rad2deg(self.lons) + 180.0, np.rad2deg(self.lats)) else: linex, liney = m(np.rad2deg(self.lons), np.rad2deg(self.lats)) m.plot(linex, liney, 'r-', lw=2) for i in range(len(linex)): plt.annotate(self.alph[i], xy=(linex[i] + 1000000, liney[i]), size=14)
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 Procedure: 1. make a grid based on the inputs (grd) grd: lon, lat, x, y 2. find the great circle points: note that lon , lat are actually x and y! 3. calculate the distance and find the middle point 4. subtracting 97 degrees from the distance and find all the points on that section 5. data ---> zero array with x*y elements """ 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) # npts points on dist...how many on (dist-97)!: (dist-97)*npts/dist....but we also need to make it half! 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])]) if not len(lons) == len(lats): sys.exit('ERROR: Lengths longitudes and latitudes are not the same! %s and %s' % (len(lons), len(lats))) 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 '\nException: %s' % e
def basemap_lonlat_grid(x,y): """Insert array or list of x and y from slab data, will return proper grids for basemap ('cylindrical' projection) and projection INPUT: x, y are arrays of coordinates OUTPUT: x, y, m where x, y are grids in the projection 'm'""" urcrnrlon, urcrnrlat = max(x), max(y) llcrnrlon, llcrnrlat = min(x), min(y) m = Basemap(projection='cyl', llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon,\ urcrnrlat=urcrnrlat, resolution='h') ny = y.size nx = x.size lons, lats = m.makegrid(nx,ny) x, y = m(lons, lats) return x, y, m
def plot_observation_frequency(locations,SEASONS,config): for year in range(config['START_YEAR'],config['END_YEAR']+1): for season in SEASONS: wanted=SEASONS[season] latitude = np.asarray(locations['LATITUDE']) longitude = np.asarray(locations['LONGITUDE']) Yearly_Data=(locations.loc[locations['YEAR']==year]) Seasonal_Data=(Yearly_Data.loc[Yearly_Data['MONTH'].isin(wanted)]) lats = np.asarray(Seasonal_Data['LATITUDE']) lons = np.asarray(Seasonal_Data['LONGITUDE']) Species_count=np.asarray(Seasonal_Data[config['SPECIES']]) Species_count=np.reshape(Species_count,len(Species_count)) lat_min = min(lats) lat_max = max(lats) lon_min = min(lons) lon_max = max(lons) spatial_resolution = 1 fig = plt.figure() x = np.array(lons) y = np.array(lats) z = np.array(Species_count) xinum = (lon_max - lon_min) / spatial_resolution yinum = (lat_max - lat_min) / spatial_resolution xi = np.linspace(lon_min, lon_max + spatial_resolution, xinum) yi = np.linspace(lat_min, lat_max + spatial_resolution, yinum) xi, yi = np.meshgrid(xi, yi) zi = griddata(x, y, z, xi, yi, interp='linear') m = Basemap(projection = 'merc',llcrnrlat=lat_min, urcrnrlat=lat_max,llcrnrlon=lon_min, urcrnrlon=lon_max,rsphere=6371200., resolution='l', area_thresh=10000) m.drawcoastlines() m.drawstates() m.drawcountries() m.drawparallels(np.arange(lat_min,lat_max,config['GRID_SIZE']),labels=[False,True,True,False]) m.drawmeridians(np.arange(lon_min,lon_max,config['GRID_SIZE']),labels=[True,False,False,True]) lat, lon = m.makegrid(zi.shape[1], zi.shape[0]) x,y = m(lat, lon) z=zi.reshape(xi.shape) levels=np.linspace(0,z.max(),25) cm=plt.contourf(x, y, zi,levels=levels,cmap=plt.cm.Greys) plt.colorbar() plt.title(config['SPECIES']+"-"+str(year)+"-"+str(season)) #plt.show() plt.savefig(config['SPECIES']+"-"+str(year)+"-"+str(season)+".png") plt.close() return
def soda_temp_plot(file_name,t,d): file = '/Users/yuewang/Documents/study/courses/OCVN689/project/'+ str(file_name) nc = netCDF4.Dataset(file) dates=netCDF4.num2date(nc.variables['TIME1'][:],'seconds since 1916-01-02 12:00:00') fig = plt.figure(figsize=(20,10)) ax = fig.add_axes([0.1,0.1,0.8,0.8]) temp = nc.variables['TEMP'] temp_0 = temp[t,d,:,:] lon = nc.variables['LON241_580'][:] lat = nc.variables['LAT142_161'][:] DEPTH = nc.variables['DEPTH1_4'] m = Basemap(llcrnrlat=lat[0],urcrnrlat=lat[-1],\ llcrnrlon=lon[0],urcrnrlon=lon[-1],\ projection='mill',resolution = 'h',ax=ax) parallels = np.arange(-5.,5.,2.) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) meridians = np.arange(120.,300.,30.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) ny = temp_0.shape[0]; nx =temp_0.shape[1] lons, lats = m.makegrid(nx, ny) x, y = m(lons, lats) cs = m.contourf(x,y,temp_0,cmap=cm.sstanom) m.drawcoastlines() cbar = m.colorbar(cs,location='bottom', size="15%", pad='35%') cbar.set_label('Temperature(deg.C)') ax.set_title('Sea Temperature at ' +str(dates[t])+ 'at depth of'+ str(DEPTH[d])+' m') plt.show()
def PPI(self, rs, data, elev, moment, figname): figname = self.dirname+figname data = rs.cartesian(data[:,:,elev], elev) fig = plt.figure(figsize=(8,6)) ax = fig.add_axes([0.1,0.1,0.8,0.8]) latmin, latmax, lonmin, lonmax = rs.radar_limits(elev) m = Basemap(projection='cyl', lon_0=rs.radar_lon, lat_0=rs.radar_lat, llcrnrlat=latmin, urcrnrlat=latmax, llcrnrlon=lonmin, urcrnrlon=lonmax, resolution='h', suppress_ticks=True) #m.drawcoastlines(color='0', linewidth=1) #m.drawstates(color='0', linewidth=1) #m.drawcountries(color='0', linewidth=1) #m.drawrivers(color='blue') #m.fillcontinents(color='#cc9955', lake_color='aqua', zorder = 0) #cor do continente #m.drawmapboundary(fill_color='aqua') #cor do mar parallels = np.arange(-90,0,1.) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10, linewidth=0.0) meridians = np.arange(180.,360.,1.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10, linewidth=0.0) numcols, numrows = data.shape lons, lats = m.makegrid(numcols, numrows) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) # compute map proj coordinates. cmap, clevs, unit, title = cm.get_info(moment) norm = mpl.colors.BoundaryNorm(clevs, cmap.N) contour = m.contourf(x, y, data, clevs, cmap=cmap, norm=norm) cbar = m.colorbar(contour, cmap=cmap, norm=norm, spacing='uniform', location='right', pad='2%', size='5%') cbar.set_label(unit, rotation='horizontal') plt.title(title+u' (%.1f°)\n%s' % (rs.fixed_angle[elev], rs.date)) self.draw_circle(rs, m, elev) #desenha o círculo do raio do radar plt.savefig(figname)
def interpolated_color_map(lats, lons, values, spatial_resolution=0.1, interp='nn', cmap=None):#cm.s3pcpn): lat_0 = 51 lat_min = 47 lat_max = 55 lon_0 = 10 lon_min = 5 lon_max = 16 m = Basemap(projection='tmerc', lat_0=lat_0, lon_0=lon_0, llcrnrlat=lat_min, llcrnrlon=lon_min, urcrnrlat=lat_max, urcrnrlon=lon_max, resolution='i') m.drawcoastlines() m.drawcountries() m.drawmapboundary() lats = np.array(lats) lons = np.array(lons) values = np.array(values) lat_inum = (lat_max - lat_min) / spatial_resolution lon_inum = (lon_max - lon_min) / spatial_resolution # xi = np.linspace(lat_min, lat_max + spatial_resolution, xinum) # yi = np.linspace(lon_min, lon_max + spatial_resolution, yinum) lat_i = np.linspace(lat_min, lat_max, lat_inum) lon_i = np.linspace(lon_min, lon_max, lon_inum) lat_i, lon_i = np.meshgrid(lat_i, lon_i) value_i = griddata(lats, lons, values, lat_i, lon_i, interp=interp) lat_grid, lon_grid = m.makegrid(value_i.shape[1], value_i.shape[0]) x_grid, y_grid = m(lat_grid, lon_grid) m.contourf(x_grid, y_grid, value_i, cmap=cmap) m.scatter(lats, lons, color='k', s=50, latlon=True) plt.show()
lons = np.zeros((361, 361)) lats = np.zeros((361, 361)) lons = np.reshape(lon_lat[:, 3], (361, 361)) lats = np.reshape(lon_lat[:, 2], (361, 361)) xpts, ypts = m(lons, lats) dx_res = 100000. arr_res = int(ceil(100000./dx_res)) grid_str=str(int(dx_res/1000))+'km' nx = int((m.xmax-m.xmin)/dx_res)+1; ny = int((m.ymax-m.ymin)/dx_res)+1 xpts2 = np.linspace(m.xmin, m.xmax, nx) ypts2 = np.linspace(m.ymin, m.ymax, ny) xpts2m, ypts2m = np.meshgrid(xpts2, ypts2) lons_100km, lats_100km = m.makegrid(nx, ny) savetxt(outpath+'lons_'+grid_str+'.txt', lons_100km) savetxt(outpath+'lats_'+grid_str+'.txt', lats_100km) savetxt(outpath+'xpts_'+grid_str+'.txt', xpts2m) savetxt(outpath+'ypts_'+grid_str+'.txt', ypts2m) start_year = 1980 end_year = 2013 num_years = end_year-start_year+1 time_index = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] curl_months = ma.masked_all((num_years, 12, nx, ny)) u_month= ma.masked_all((num_years, 12, nx, ny)) v_month= ma.masked_all((num_years, 12, nx, ny))
data = data[mask] lat = data['latitude'] lon = data['longitude'] height = data['height'] # Generate a map plotting bm = Basemap(projection='tmerc', lat_0=90.0, lon_0=-100.0, lat_ts=40.0, llcrnrlon=-121, llcrnrlat=24, urcrnrlon=-64, urcrnrlat=46, resolution='l') # Transform ob locations to locations on map obx, oby = bm(lon, lat) # Generate grid of x,y positions lon_grid, lat_grid, x_grid, y_grid = bm.makegrid(130, 60, returnxy=True) # Perform analysis of height obs using Cressman weights. Everything is in # meters heights_cress = grid_data(height, x_grid, y_grid, obx, oby, cressman_weights, 600. * kilo) # Mask out values over the ocean so that we don't draw contours there heights_cress = maskoceans(lon_grid, lat_grid, heights_cress) # Map plotting contours = np.arange(4800., 5900., 60.0) bm.drawstates() bm.drawcountries() bm.drawcoastlines()
llcrnrlat=latcorners[0],urcrnrlat=latcorners[2],\ llcrnrlon=loncorners[0],urcrnrlon=loncorners[2],\ rsphere=6371200.,resolution='l',area_thresh=1000) # create figure fig = plt.figure(figsize=(6,5)) ax = plt.gca() # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines() m.drawstates() m.drawcountries() # project data ny = data.shape[0]; nx = data.shape[1] lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) # compute map proj coordinates. # draw filled contours. clevs = np.array([0,1,2.5,5,7.5,10,15,20,30,40,50,70,100,150,200,250,300,400,500,600,750]) cs = m.contourf(x,y,data,clevs,cmap=cm.s3pcpn) # new axis for colorbar pos = ax.get_position() l, b, w, h = pos.bounds cax = plt.axes([l+w+0.025, b, 0.025, h]) # setup colorbar axes # draw colorbar. plt.colorbar(cs, cax, format='%g', ticks=clevs, drawedges=False) plt.axes(ax) # make the original axes current again
o.add_option('--nobar', dest='nobar', action='store_true', help="Do not show colorbar.") o.add_option('--res', dest='res', type='float', default=0.25, help="Resolution of plot (in degrees). Default 0.25.") o.add_option('--nside', dest='nside', type='int', help="Manually set NSIDE (possibly degrading map) to a power of 2.") o.add_option('--mask', dest='mask', type='float', help="Optional dB of weight below which data will be masked. Recommended=30") opts,args = o.parse_args(sys.argv[1:]) cmap = p.get_cmap(opts.cmap) if opts.cen is None: if opts.osys == 'eq': opts.cen = 180 else: opts.cen = 0 map = Basemap(projection=opts.projection,lat_0=0,lon_0=opts.cen, rsphere=1.) lons,lats,x,y = map.makegrid(360/opts.res,180/opts.res, returnxy=True) # Mask off parts of the image to be plotted that are outside of the map lt = lats[:,0] ln1 = n.ones_like(lt) * (lons[lons.shape[0]/2,0]) ln2 = n.ones_like(lt) * (lons[lons.shape[0]/2,-1]) x1,y1 = map(ln1,lt); x2,y2 = map(ln2,lt) x = n.ma.array(x) for c,(i,j) in enumerate(zip(x1,x2)): x[c] = n.ma.masked_outside(x[c], i, j) mask = x.mask if opts.osys == 'eq': lons = 360 - lons lats *= a.img.deg2rad; lons *= a.img.deg2rad print 'Reading %s' % args[0] h = a.map.Map(fromfits=args[0]) print 'SCHEME:', h.scheme() print 'NSIDE:', h.nside() if not opts.nside is None:
print lat_min, lat_max + spatial_resolution, xinum, lon_min, lon_max + spatial_resolution, yinum xi, yi = np.meshgrid(xi, yi) zi = griddata((x, y), z, (xi, yi), method = 'linear') fig = plt.figure(frameon=False) ax = fig.add_axes([0, 0, 1, 1]) ax.axis('off') ax.margins(0) m = Basemap(epsg = '4326',llcrnrlat=lat_min, urcrnrlat=lat_max,llcrnrlon=lon_min, urcrnrlon=lon_max, resolution='l') #m = Basemap(projection='ortho',lat_0=lat_max,lon_0=lon_min,resolution='l') m.drawcoastlines() m.drawstates() m.drawcountries() lat, lon = m.makegrid(zi.shape[1], zi.shape[0]) #print lats #print lons r,t = m(lons,lats) x,y = lat, lon m.plot(r, t, 'bo', markersize=1) #a,b = m(lat_min, lat_max) #c,d = m(lon_min, lon_max) #print a,b,c,d m.contourf(x, y, zi, levels = np.arange(-50,50,2), extend='both') plt.show() #fig.savefig('test.png')
def surgemap(datafolder, mapfolder, tyname, start_datetime, chunk): surgefilename_list = sorted(glob.glob(os.path.join(datafolder, 'zz*.xyz'))) uwindfilename_list = sorted(glob.glob(os.path.join(datafolder, 'wu*.xyz'))) vwindfilename_list = sorted(glob.glob(os.path.join(datafolder, 'wv*.xyz'))) timestep = start_datetime count = 0 start_calc = time.time() file_count = len(surgefilename_list[::chunk]) for (surgefilename, uwindfilename, vwindfilename) in \ zip(surgefilename_list[::chunk], uwindfilename_list[::chunk], vwindfilename_list[::chunk] ): longitude = [] latitude = [] surge = [] uwind = [] vwind = [] figpath = os.path.join(mapfolder, datetime.datetime.strftime(timestep, format='%Y-%m-%d_%H:%M')+'.png') #~ if os.path.exists(figpath) and timestep != start_datetime: #~ timestep = timestep+datetime.timedelta(hours=1) #~ continue with open(surgefilename, 'r') as surgefile: surgelines = surgefile.readlines() for i in range(len(surgelines)): surgelines[i] = surgelines[i].strip('\n').split() longitude.append(float(surgelines[i][0])) latitude.append(float(surgelines[i][1])) surge.append(float(surgelines[i][2])) with open(uwindfilename, 'r') as uwindfile: uwindlines = uwindfile.readlines() for i in range(len(uwindlines)): uwindlines[i] = uwindlines[i].strip('\n').split() uwind.append(float(uwindlines[i][2])) with open(vwindfilename, 'r') as vwindfile: vwindlines = vwindfile.readlines() for i in range(len(vwindlines)): vwindlines[i] = vwindlines[i].strip('\n').split() vwind.append(float(vwindlines[i][2])) #~ print ('Done reading', os.path.basename(surgefilename), \ #~ os.path.basename(uwindfilename), \ #~ os.path.basename(vwindfilename), '...') if timestep == start_datetime: print ('Plotting basemap...') minX = min(longitude) minY = min(latitude) maxX = max(longitude) maxY = max(latitude) surgemap = Basemap(llcrnrlon=minX, llcrnrlat=minY, urcrnrlon=maxX, urcrnrlat=maxY, projection='merc', resolution='f' ) surgemap.drawcoastlines() surgemap.drawmapboundary() meridians = range(int(minX), int(maxX) + 2, 2) parallels = range(int(minY), int(maxY) + 2, 2) surgemap.drawmeridians(meridians, labels=[0, 0, 0, 1]) surgemap.drawparallels(parallels, labels=[1, 0, 0, 0]) surgemap.fillcontinents(color='g') zoomIn = raw_input('Zoom in to a specific region? (y/n): ') if zoomIn.lower() == 'y': crop_minX = float(raw_input('Left longitude (decimal-degree): ')) crop_maxX = float(raw_input('Right longitude (decimal-degree): ')) crop_minY = float(raw_input('Bottom latitude (decimal-degree): ')) crop_maxY = float(raw_input('Top latitude (decimal-degree): ')) x1 = ((crop_minX - minX) / (maxX - minX)) * plt.xlim()[1] x2 = ((crop_maxX - minX) / (maxX - minX)) * plt.xlim()[1] y1 = ((crop_minY - minY) / (maxY - minY)) * plt.ylim()[1] y2 = ((crop_maxY - minY) / (maxY - minY)) * plt.ylim()[1] print('Done plotting basemap...') _, _, Z = xyz2grd(longitude, latitude, surge, quality=100) _, _, Uwind = xyz2grd(longitude, latitude, uwind, quality=20) _, _, Vwind = xyz2grd(longitude, latitude, vwind, quality=20) ny = Z.shape[0] nx = Z.shape[1] windny = Uwind.shape[0] windnx = Uwind.shape[1] # get lat/lons of ny by nx evenly space grid. lons, lats = surgemap.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. windlons, windlats = surgemap.makegrid(windnx, windny) # compute map proj coordinates. x_map, y_map = surgemap(lons, lats) # compute map proj coordinates. windx_map, windy_map = surgemap(windlons, windlats) minlevel = -2.00 maxlevel = 2.00 levelstep = 0.10 left_clevs = np.arange(minlevel - levelstep, 0.0, levelstep) right_clevs = np.arange(0.0, maxlevel + levelstep, levelstep) cs_left = surgemap.contourf(x_map, y_map, Z, left_clevs, cmap=plt.cm.Blues_r) cs_right = surgemap.contourf(x_map, y_map, Z, right_clevs, extend='max', cmap=plt.cm.hot_r) if zoomIn.lower() == 'y': plt.xlim((x1, x2)) plt.ylim((y1, y2)) vectors = surgemap.quiver(windx_map, windy_map, Uwind, Vwind, cmap=plt.cm.Blues_r, pivot='middle', scale=500.0, zorder=100, headwidth=5) title = plt.title(tyname.title() + ' ' + datetime.datetime.strftime(timestep, format='%b %d, %Y %I:%M %p')) if timestep == start_datetime: cbar_right = surgemap.colorbar(cs_right, location='right', pad='10%') cbar_right.set_label('m', rotation=0) plt.quiverkey(vectors, -0.25, 0.50, 50, '50 knots', labelpos='S', coordinates='axes') plt.tight_layout() plt.savefig(figpath) vectors.remove() title.set_text('') timestep = timestep + datetime.timedelta(hours=1) count += 1 percent = count * 100.0 / file_count now_calc = time.time() remaining_time = (100.0 - percent) * (now_calc - start_calc) / percent sys.stdout.write('***** %.2f %% finished. Estimated time left: %.2f seconds *****\r' % (percent, remaining_time)) sys.stdout.flush() end_calc = time.time() duration = end_calc - start_calc print('***** 100 %% finished. Total duration: %.2f seconds *****\r' % duration) plt.clf()
def get_NAM_native_grid(): m = Basemap(projection='lcc',llcrnrlon=-133.459,llcrnrlat=12.190, urcrnrlon=-49.420,urcrnrlat=57.328,lat_1=25.0, lon_0=-95.0) lons, lats, xx, yy = m.makegrid(614,428,returnxy=True) return m, lons, lats, xx[0,:], yy[:,0]
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np fig=plt.figure(figsize=(9, 3)) map = Basemap(width=12000000,height=8000000, resolution='l',projection='stere', lat_ts=50,lat_0=50,lon_0=-107.) lons, lats, x, y = map.makegrid(30, 30, returnxy=True) ax = fig.add_subplot(121) ax.set_title('The regular grid') map.scatter(x, y, marker='o') map.drawcoastlines() ax = fig.add_subplot(122) ax.set_title('Projection changed') map = Basemap(width=12000000,height=9000000,projection='aeqd', lat_0=50.,lon_0=-105.) x, y = map(lons, lats) map.scatter(x, y, marker='o') map.drawcoastlines() plt.show()
def interpolated_color_map(station_lon, station_lat, station_val, param_input = "Parameter", grid_dim=(80,110), interp='nn', return_figure=False): """ Creates a map of values for different stations. The station location can be on an irregular grid, for intermediate locations interpolation is used. Params: station_lon (1D arrya): longitutes of station locations station_lat (1D arrya): latitudes of station locations station_val (1D arrya): values to plot per stations grid_dim (tuple, optional): number of interpolated data points in lon/lat dimension interp ('nn' or 'linear', optional): interpolation type, 'nn': Natgrid nearest neighbour interpolation method return_figure (bool, optional): weather or not to return the figure object, if True, plt.show() is not called """ # map boundries lat_0 = 51 lat_min = 47 lat_max = 55 lon_0 = 10 lon_min = 5 lon_max = 16 m = Basemap(projection='tmerc', lat_0=lat_0, lon_0=lon_0, llcrnrlat=lat_min, llcrnrlon=lon_min, urcrnrlat=lat_max, urcrnrlon=lon_max, resolution='i') #with open('germany_map.pkl', 'rb') as input: #m = pickle.load(input) # open map from disk m.drawcoastlines() m.drawcountries() m.drawmapboundary() # coordinate axes of shapes (grid_dim[i],) lat_axis = np.linspace(lat_min, lat_max, grid_dim[0]) lon_axis = np.linspace(lon_min, lon_max, grid_dim[1]) # coordinate axes meshgrip of shape (grid_dim[0], grid_dim[1]) lon_mesh, lat_mesh = np.meshgrid(lon_axis, lat_axis) # contour levels levels = np.linspace(np.nanmin(station_val), np.nanmax(station_val)) # data points and mesh in x/y coordinates station_x, station_y = m(station_lon, station_lat) x_min, y_min = m(lon_min, lat_min) x_max, y_max = m(lon_max, lat_max) x_axis = np.linspace(x_min, x_max, grid_dim[0]) y_axis = np.linspace(y_min, y_max, grid_dim[1]) x_mesh, y_mesh = np.meshgrid(x_axis, y_axis) value_mesh = griddata(station_x, station_y, station_val, x_mesh, y_mesh, interp=interp) cont = m.contourf(x_mesh, y_mesh, value_mesh, vmin=np.nanmin(station_val), vmax=np.nanmax(station_val), levels=levels) # interpolate datapoints for (station_lon, station_lat) to meshgrid (lat_mesh, lot_mesh) #value_mesh = griddata(station_x, station_y, station_val, lon_mesh, lat_mesh, interp=interp) lon_grid, lat_grid = m.makegrid(value_mesh.shape[1], value_mesh.shape[0]) x_grid, y_grid = m(lon_grid, lat_grid) #m.contourf(x_grid, y_grid, value_mesh, cmap=cmap) #m.contourf(lon_grid, lat_grid, value_mesh, cmap=cmap, latlon=True) m.scatter(station_lon, station_lat, color='k', s=5, latlon=True) print(station_val) cb = m.colorbar(cont, location='bottom', label=param_input, ticks=[np.nanmin(station_val), 0, np.nanmax(station_val)]) if return_figure: return plt.gcf() else: plt.show()
lon = nc.variables['lon'][:] lat = nc.variables['lat'][:] m = Basemap(llcrnrlat=-50.,llcrnrlon=-179.9,\ urcrnrlat= 50,urcrnrlon=179.9,\ projection='mill',resolution = 'h') parallels = np.arange(-60.,60.,10.) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) meridians = np.arange(-180.,180.,60.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) ny = rain_rate_s.shape[0]; nx =rain_rate_s.shape[1] lons, lats = m.makegrid(nx, ny) x, y = m(lons, lats) clevs = [0,0.1,0.2,0.3,0.4,0.6,0.8,1.0,1.5,1.9,2.3,2.7,3.1,3.5,3.9,4.3] cdict = {'red': ((0., 1, 1), (0.05, 1, 1), (0.11, 0, 0), (0.66, 1, 1), (0.89, 1, 1), (1, 0.5, 0.5)), 'green': ((0., 1, 1), (0.05, 1, 1), (0.11, 0, 0), (0.375, 1, 1), (0.64, 1, 1),
enum = 1 nonzero_unique = [] nonzero.sort() for i in range(len(nonzero)-1, -1, -1): if nonzero[i] == nonzero[i-1]: enum += 1 else: nonzero_unique.append([nonzero[i], enum]) enum = 1 if not ray_coverage: for i in range(len(nonzero_unique)): DATA[nonzero_unique[i][0]] = DATA[nonzero_unique[i][0]]/nonzero_unique[i][1] gr_y = gr_x grd = mymap.makegrid(gr_x, gr_y, returnxy=True) print '\nplotting...' #mymap.contourf(grd[2], grd[3], DATA) vmin = max(abs(np.min(DATA)), abs(np.max(DATA))) if not ray_coverage: mymap.pcolormesh(grd[2], grd[3], DATA, cmap=tomo_colormap_2, vmin=-1*vmin/100., vmax=vmin/100.) else: import matplotlib.cm as cm mymap.pcolormesh(grd[2], grd[3], DATA, cmap=cm.gray, vmax=10) #plt.hexbin(grd[2], grd[3], DATA) cbar = plt.colorbar(orientation='horizontal') cbar.ax.tick_params(labelsize=12) plt.show() # Clean 1.0% (dT) import scipy.ndimage as ndimage
def plot_flow_vectors_basemap(lons, lats, uu, vv, flow_speed, subregion:list=None, grid_shape=None, ax:Axes=None, streamplot=False, draw_colorbar=True): from mpl_toolkits.basemap import Basemap if grid_shape is None: grid_shape = (300, 300) if subregion is None: subregion = [0, 1, 0, 1] if ax is None: fig = plt.figure() nx, ny = lons.shape b = Basemap(lon_0=180, llcrnrlon=lons[35, 35], llcrnrlat=lats[35, 35], urcrnrlon=lons[nx // 2, ny // 2], urcrnrlat=lats[nx // 2, ny // 2], resolution="i", area_thresh=2000) # im = b.pcolormesh(xx, yy, flow_speed) # b.colorbar(im) stride = 6 uu1, vv1 = b.rotate_vector(uu, vv, lons, lats) lons_g, lats_g, xx_g, yy_g = b.makegrid(*grid_shape, returnxy=True) nx, ny = lons_g.shape i_start, i_end = int(nx * subregion[0]), int(nx * subregion[1]) j_start, j_end = int(ny * subregion[2]), int(ny * subregion[3]) xt, yt, zt = lat_lon.lon_lat_to_cartesian(lons_g.flatten(), lats_g.flatten()) xs, ys, zs = lat_lon.lon_lat_to_cartesian(lons.flatten(), lats.flatten()) ktree = KDTree(data=list(zip(xs, ys, zs))) dists, inds = ktree.query(list(zip(xt, yt, zt))) uu_to_plot = uu1.flatten()[inds].reshape(lons_g.shape) vv_to_plot = vv1.flatten()[inds].reshape(lons_g.shape) flow_speed_to_plot = flow_speed.flatten()[inds].reshape(lons_g.shape) clevs = [0, 0.01, 0.02, 0.04, 0.06, 0.08, 0.12, 0.16] ncolors = len(clevs) - 1 norm = BoundaryNorm(clevs, ncolors) cmap = cm.get_cmap("gist_ncar_r", ncolors) im = b.pcolormesh(xx_g, yy_g, flow_speed_to_plot, alpha=0.5, cmap=cmap, norm=norm) if not streamplot: b.quiver(xx_g[i_start:i_end:stride, j_start:j_end:stride], yy_g[i_start:i_end:stride, j_start:j_end:stride], uu_to_plot[i_start:i_end:stride, j_start:j_end:stride], vv_to_plot[i_start:i_end:stride, j_start:j_end:stride], headlength=2, headaxislength=2, headwidth=4, units="inches", color="k") else: b.streamplot(xx_g, yy_g, uu_to_plot, vv_to_plot, linewidth=0.4, density=3, arrowstyle="fancy", arrowsize=0.4, ax=ax, color="k") # im = b.contourf(xx_g, yy_g, flow_speed_to_plot, levels=clevs, alpha=0.5, cmap=cmap, norm=norm) cb = b.colorbar(im, location="bottom") cb.ax.set_visible(draw_colorbar) b.drawcoastlines(linewidth=0.3, ax=ax) if ax is None: fig.savefig("nemo/circ_annual_mean_basemap.png", bbox_inches="tight", dpi=300) plt.close(fig) return im
#parse through a bunch of projection crap if opts.projection.startswith('sp'): map = Basemap(projection=opts.projection,boundinglat=cen.dec*a.img.rad2deg+90, lon_0=(360-cenra)%360, rsphere=1.) elif opts.projection.startswith('bigstere'): map = Basemap(projection='spstere',lat_0=cen.dec*a.img.rad2deg,boundinglat=10, lon_0=(360-cenra)%360, rsphere=1.) elif opts.projection.startswith('moll') and opts.osys!='ga': map = Basemap(projection=opts.projection,lat_0=cen.dec*a.img.rad2deg, lon_0=(360-cenra)%360, rsphere=1.,anchor='N') gal = Basemap(projection='moll',lat_0=27.12,lon_0=192.9,rsphere=1,anchor='N') else: map = Basemap(projection=opts.projection,lat_0=cen.dec*a.img.rad2deg, lon_0=(360-cenra)%360, rsphere=1.,anchor='N') lons,lats,x,y = map.makegrid(360/opts.res,180/opts.res, returnxy=True) # Mask off parts of the image to be plotted that are outside of the map lt = lats[:,0] ln1 = n.ones_like(lt) * (lons[lons.shape[0]/2,0]) ln2 = n.ones_like(lt) * (lons[lons.shape[0]/2,-1]) x1,y1 = map(ln1,lt); x2,y2 = map(ln2,lt) x = n.ma.array(x) for c,(i,j) in enumerate(zip(x1,x2)): x[c] = n.ma.masked_outside(x[c], i, j) mask = x.mask #if opts.osys == 'eq': lons = 360 - lons lats *= a.img.deg2rad; lons *= a.img.deg2rad if opts.osys=='ga' and opts.projection!='moll': lons *= -1 if opts.osys=='eq':lons *=-1 def xy2radec(x,y): lon,lat = map(x, y,inverse=True)
rsphere=6371200.,resolution='l',area_thresh=10000) # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines() m.drawstates() m.drawcountries() # draw parallels. parallels = np.arange(0.,90,1.) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # draw meridians meridians = np.arange(180.,360.,1.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) l=np.array(diffVals) lons, lats = m.makegrid(l.shape[1],l.shape[0]) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) # compute map proj coordinates. # draw filled contours. #clevs = [0,1,2.5,5,7.5,10,15,20,30,40,50,70,100,150,200,250,300,400,500,600,750] clevs = [-0.0002,0,0.0002,0.0004,0.0006,0.0008,0.001,0.0012,0.0014,0.0016,0.0018,0.002,0.0022,0.0024,0.0026,0.0028,0.003,0.0032,0.0034,0.0036,0.0038,0.004,0.01,0.02,0.03] cs = m.contourf(x,y,diffVals,clevs,cmap=cm.s3pcpn) # draw points of interest m.scatter(x,y,max_size*pop[city]/pop['New York'],marker='o',color='r') # add colorbar. cbar = m.colorbar(cs,location='bottom',pad="5%") cbar.set_label('kWh') # add title
print 'Plotting:',fn im,hdr=readFITS(fn,hdr=True) print hdr fig=p.figure(figsize=(6,6)) #fig=p.figure() #ax=fig.add_axes([0,0,1,1]) m=Basemap(projection='ortho',lon_0=hdr['ra'],lat_0=hdr['dec'],resolution='l') m.drawmapboundary(linewidth=.5) parallels=n.arange(-90.,120.,15.) m.drawparallels(parallels) meridians=n.arange(0.,360.,30.) m.drawmeridians(meridians) x,y=m.makegrid(im.shape[0],im.shape[1]) pos_thresh=1e10 im=n.fliplr(im) if opts.mask: im=n.ma.masked_where(x+y>pos_thresh,im) if opts.contour: x0,y0=m(x,y) cs=m.contour(x0,y0,im,opts.ncontour) print cs.levels else: m.imshow(im) #class A sources src_ras=[299.86791,350.84583,83.63333,187.705833] src_decs=[40.733888,58.810833,22.01444,12.39111] src_names=['CYG','CAS','TAU','VIR'] ##flip RAs
oname_lat = odir + "/stereo.lat.ASAS.%04d.%02d.bn"%(year,mon) figname_lon = odir + "/stereo.lon.ASAS.%04d.%02d.png"%(year,mon) #********************** fig = plt.figure(figsize=(8,8)) ax = fig.add_axes([0.1,0.1,0.8,0.8]) m = Basemap(projection="stere", lon_0=lon0, lat_0=lat0, lat_ts=latts,\ llcrnrlat=lllat, urcrnrlat=urlat, llcrnrlon=lllon, urcrnrlon=urlon,\ rsphere=6371200.,resolution="l",area_thresh=10000) m.drawcoastlines() # draw parallels. parallels = arange(0.,90,10.) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # draw meridians meridians = arange(0.,360.,10.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) a2lon_dom, a2lat_dom = m.makegrid(nxdom,nydom) #-- correct a2lon west degree --> east degree a2lon_dom = ma.masked_greater_equal(a2lon_dom, 0.0) \ + ones([nydom, nxdom],float32)*360.0 a2lon_dom = a2lon_dom.data m.imshow(a2lon_dom, interpolation="nearest") plt.colorbar() plt.savefig(figname_lon) print figname_lon #********************** a2lon = ones([ny,nx],float32)*miss a2lat = ones([ny,nx],float32)*miss