def generate_image(year, month, xs=500, ys=500, elev=60, azim=-90, colormap=cm.seismic): m = Basemap(width=12000000,height=12000000, rsphere=(6378137.00,6356752.3142),\ resolution='l',area_thresh=1000.,projection='lcc',\ lat_0=45,lon_0=170) ssl_loc = '/home/guy/Data/cci-ssl/ESACCI-SEALEVEL-L4-MSLA-MERGED-%04d%02d15000000-fv01.nc' % (year, month) lons_proj, lats_proj, XX, YY, sla = reproject_data(ssl_loc,'sla', m, xsize=xs, ysize=ys, filter=0) sst_loc = '/mnt/surft/data/SST_CCI_L4_monthly_mean_anomalies/%04d%02d--ESACCI-L4_GHRSST-SSTdepth-OSTIA-GLOB_LT-v02.0-fv01.0_anomalies.nc' %(year, month) lons_proj, lats_proj, XX, YY, sst = reproject_data(sst_loc,'sst_anomaly', m, xsize=xs, ysize=ys, filter=None) min_sst = -4 max_sst = 4 colors = np.empty(sst.shape, dtype=np.dtype((float, (4)))) for y in range(sst.shape[1]): for x in range(sst.shape[0]): val = sst[x, y] if(np.ma.getmask(sst[x,y]) == True): colors[x,y] = (1,0,0,0) else: zero_to_one = (val - min_sst) / (max_sst - min_sst) colors[x, y] = colormap(zero_to_one) fig = plt.figure(figsize=(19.2,9.6)) ax = plt.subplot(121, projection='3d') # ax = fig.gca(projection='3d') ax.view_init(elev=elev, azim=azim) ax.set_axis_off() surf = ax.plot_surface(XX, YY, sla, rstride=1, cstride=1, facecolors=colors,#cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_zlim(-3, 3) ax.set_xlim((0.22 * xs, 0.78 * xs)) ax.set_ylim((0.18 * ys, 0.82 * ys)) ax2d = plt.subplot(122, aspect=1) m.bluemarble(ax=ax2d, scale=0.2) #m.imshow(sst, ax=ax, cmap=cm.coolwarm) x, y = m(lons_proj, lats_proj) m.pcolor(x,y, sst, ax=ax2d, cmap=colormap, vmin=min_sst, vmax=max_sst) #matplotlib.rcParams['contour.negative_linestyle'] = 'dashed' m.contour(x,y, sla, np.linspace(-1,1,11), colors='k', ax=ax2d) # m.pcolor(XX, YY, sla, ax=ax) #ax.pcolormesh(XX,YY,sst, vmin=min_sst, vmax=max_sst, cmap=cm.coolwarm) # ax = fig.gca() # surf = ax.pcolormesh(XX,YY,sla, vmin=-limit, vmax=limit) # fig.colorbar(surf, shrink=0.5, aspect=5) fig.tight_layout() return fig
def plotmap(variable, mode='multi', tstep=0, proj='merc', style='pcolormesh', clevs=20): latitudes = variable.coords['latitude'][:] longitudes = variable.coords['longitude'][:] lats, lons = makegrid(latitudes, longitudes, variable.shape[-2:]) vmin, vmax = variable[:].min(), variable[:].max() llcrnrlat, urcrnrlat = lats.min(), lats.max() llcrnrlon, urcrnrlon = lons.min(), lons.max() lat_ts = lats.mean() lon_0 = lons.mean() fig = plt.figure(figsize=(10,14)) cols, rows = 1, 1 if mode == 'tstep': data = variable[:][tstep] elif mode == 'mean': data = variable[:].mean(axis=0) elif mode == 'multi': nplots = variable.shape[0] cols = int(np.floor(np.sqrt(nplots))) rows = int(np.ceil(np.sqrt(nplots))) print nplots, cols, rows fig, axes = plt.subplots(rows, cols, squeeze=False) for col in range(cols): for row in range(rows): print col, row, col+cols*row if proj == 'merc': m = Basemap(projection='merc',llcrnrlat=llcrnrlat,urcrnrlat=urcrnrlat,llcrnrlon=llcrnrlon,urcrnrlon=urcrnrlon,lat_ts=lat_ts,resolution='l', ax=axes[row][col]) elif proj == 'lcc': m = Basemap(projection='lcc',llcrnrlat=llcrnrlat,urcrnrlat=urcrnrlat,llcrnrlon=llcrnrlon,urcrnrlon=urcrnrlon,lat_0=lat_ts,lon_0=lon_0,resolution='l', ax=axes[row][col]) x, y = m(lons, lats) if mode == 'multi': data = variable[col+cols*row] if style == 'pcolormesh': m.pcolormesh(x, y, data, vmin=vmin, vmax=vmax, cmap='Blues') elif style == 'contour': m.contourf(x, y, data, clevs) m.contour(x, y, data, clevs, colors='black') m.fillcontinents(color='white',lake_color='aqua',zorder=0) m.drawcoastlines(linewidth=1.0) plt.tight_layout() return plt
def main(file_name='Greenland1km.nc'): '''Description''' # Set up the file and projection data = os.path.dirname(os.path.abspath(__file__)) + os.sep + '..' + os.sep \ + 'data' + os.sep + file_name proj_file = pyproj.Proj('+proj=stere +ellps=WGS84 +datum=WGS84 +lat_ts=71.0 +lat_0=90 ' \ + '+lon_0=321.0 +k_0=1.0') proj_lat_long = pyproj.Proj('+proj=latlong +ellps=WGS84 +datum=WGS84') fig, ax = plt.subplots(1,2) # Open up the file and grab the data we want out of it greenland = Dataset(data) x = greenland.variables['x'][:] y = greenland.variables['y'][:] nx = x.shape[0] ny = y.shape[0] y_grid, x_grid = scipy.meshgrid(y[:], x[:], indexing='ij') thk = greenland.variables['thk'][0] bheatflx = greenland.variables['bheatflx'][0] # Now transform the coordinates to the correct lats and lons lon, lat = pyproj.transform(proj_file, proj_lat_long, x_grid.flatten(), y_grid.flatten()) lat = lat.reshape(ny,nx) lon = lon.reshape(ny,nx) # Put thickness in a basemap mapThk = Basemap(projection='stere',lat_0=65, lon_0=-25,\ llcrnrlat=55,urcrnrlat=85,\ llcrnrlon=-50,urcrnrlon=0,\ rsphere=6371200.,resolution='l',area_thresh=10000, ax=ax[0]) mapThk.drawcoastlines(linewidth=0.25) mapThk.fillcontinents(color='grey') mapThk.drawmeridians(np.arange(0,360,30)) mapThk.drawparallels(np.arange(-90,90,30)) x, y = mapThk(lon,lat) cs = mapThk.contour(x, y, thk, 3) # Put basal heat flux in a basemap mapFlx = Basemap(projection='stere',lat_0=65, lon_0=-25,\ llcrnrlat=55,urcrnrlat=85,\ llcrnrlon=-50,urcrnrlon=0,\ rsphere=6371200.,resolution='l',area_thresh=10000, ax=ax[1]) mapFlx.drawcoastlines(linewidth=0.25) mapFlx.fillcontinents(color='grey') mapFlx.drawmeridians(np.arange(0,360,30)) mapFlx.drawparallels(np.arange(-90,90,30)) x, y = mapFlx(lon,lat) cs = mapFlx.contour(x, y, bheatflx, 3) plugins.connect(fig, ClickInfo(cs)) mpld3.show()
def plot_cappi(data,parm,lnum, **kwargs): x=data['xar'] y=data['yar'] radar_loc=data['radar_loc'] radar_name=kwargs.get('radar_name', data['radar_name']) fig_name=kwargs.get('fig_name', 'cappi_'+parm+'_.png') f=figure() Re=6371.0*1000.0 rad_at_radar=Re*sin(pi/2.0 -abs(radar_loc[0]*pi/180.0))#ax_radius(float(lat_cpol), units='degrees') lons=radar_loc[1]+360.0*(x-data['displacement'][0])/(rad_at_radar*2.0*pi) lats=radar_loc[0] + 360.0*(y-data['displacement'][1])/(Re*2.0*pi) def_loc_dict={'lat_0':lats.mean(), 'lon_0':lons.mean(),'llcrnrlat':lats.min(), 'llcrnrlon':lons.min(), 'urcrnrlat':lats.max() , 'urcrnrlon':lons.max(), 'lat_ts':lats.mean()} loc_dict=kwargs.get('loc_dict', def_loc_dict) #print 'Here' map= Basemap(projection='merc', resolution='l',area_thresh=1., **loc_dict) longr, latgr=meshgrid(lons,lats) xx, yy = map(longr, latgr) #print 'there' map.drawmapboundary() darwin_loc=[-12.5, 130.85] disp_from_darwin=mathematics.corner_to_point(darwin_loc, radar_loc) dist_from_darwin=sqrt(disp_from_darwin[0]**2+disp_from_darwin[1]**2) if dist_from_darwin < 500.*1000.: map.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) else: map.drawcoastlines() map.drawmeridians(array([129,130,131,132,133]), labels=[1,0,0,1]) map.drawparallels(array([-14,-13,-12,-11,-10]), labels=[1,0,0,1]) comp_levs=linspace(-1.,1., 30) #print 'everywhere' levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'PH': linspace(0,185,255), "RH": linspace(0,1.5,16), "SW":linspace(0, 5, 11), "ZD":linspace(-10,10,21), 'VE':linspace(-30,30,31), 'TI':linspace(-30,30,31)} #print 'or here?' titles_dict={'VR': 'Velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'PH': 'Differential Prop Phase (degrees)', 'RH':'Correlation Co-ef', 'SW':'Spectral Width (m/s)', 'ZD':'Differentail Reflectivity dBz', 'VE':'Edited Velocity (m/s)', 'TI':'Simualated winds,(m/s)'} #print parm if 'mask' in kwargs.keys(): mask=kwargs['mask'][:,:,lnum] mdata=M.masked_where(M.array(mask) < 0.5, M.array(data[parm][:,:,lnum])) map.contourf(xx,yy,mdata, levels=levs_dict[parm]) else: map.contourf(xx,yy,data[parm][:,:,lnum], levels=levs_dict[parm]) colorbar() if 'angs' in kwargs.keys(): map.contour(xx,yy,kwargs['angs'], levels=[30.0, 150.0],colors=['r']) p=data['date'] dtstr='%(#1)02d-%(#2)02d-%(#3)04d %(#4)02d%(#5)02dZ ' %{"#1":p.day, "#2":p.month, "#3":p.year, "#4":p.hour, '#5':p.minute} title(radar_name+' '+dtstr+titles_dict[parm]) savefig(getenv('HOME')+'/bom_mds/output/'+fig_name) close(f)
def bp(lon, lat, data, yescbar, region = 'Arctic', ptype = 'contourf', **kwargs): '''Basic Basemap plot function. Use coordinates (1d or 2d), data and name of the region as an input and plot data. Region defines in the "regbase" function. You can also provide any argument for matplotlib plotting functions. Usage: bp(lon, lat, data, region = 'Arctic', ptype = 'contourf', **kwargs) Input: lon - 2D or 1D array of longitudes lat - 2D or 1D array of latitudes data - 2D array of scalar data. region - one of the predefined regions (for list of regions see the "regbase" function) ptype - plot type (contour, contourf, pcolor, pcolormesh) **kwargs - arguments for plotting functions Output: Basemap instance. ''' mapDict = regbase(region) # Create Basemap instance if mapDict['projection'] == 'npstere': m = Basemap(projection=mapDict['projection'],boundinglat=mapDict['boundinglat'],\ lon_0=mapDict['lon_0'],resolution=mapDict['resolution']) # Check if we have proper number of dimensions for lon (and hopefully lat as well) if lon.shape.__len__() == 1: lon, lat = np.meshgrid(lon, lat) elif lon.shape.__len__() > 2: raise Exception("Coordinate variables (lon) has too many dimensions") # Convert lat/lon to map coordinates x, y = m(lon, lat) # Make the map look better m.fillcontinents(color='gray',lake_color='gray') m.drawparallels(np.arange(-80.,81.,20.)) m.drawmeridians(np.arange(-180.,181.,20.)) m.drawmapboundary(fill_color='white') # Draw values on the map if ptype == 'contourf': cs = m.contourf(x,y,data,**kwargs) if yescbar == True: cbar3 = plt.colorbar(cs) return m elif ptype == 'pcolormesh': cs = m.pcolormesh(x,y,data,**kwargs) elif ptype == 'contour': cs = m.contour(x,y,data,**kwargs) elif ptype == 'pcolor': cs = m.pcolor(x,y,data,**kwargs) else: raise Exception("Plot type not supported. Valid plot types are: contour, contourf, pcolor, pcolormesh ") return m
def grid_plot(lon,lat, topoin, etlats, etlons, llimx=-180.,\ ulimx=-130.,llimy=50.,ulimy=75.): """" Parameters ---------- lat: array_like 0->360 Prime to Prime or -180 -> 180 IDL -> IDL Returns ------- figure and plot instances """ fig1 = plt.figure(1) #Custom adjust of the subplots ax = plt.subplot(1,1,1) #Let's create a basemap of Alaska x1 = llimx x2 = ulimx y1 = llimy y2 = ulimy m = Basemap(resolution='i',projection='merc', llcrnrlat=y1,urcrnrlat=y2,llcrnrlon=x1,urcrnrlon=x2,lat_ts=((y1+y2)/2)) x, y = m(lon,lat) ex, ey = m(etlons, etlats) #lonpt, latpt = m(x,y,inverse=True) m.drawcountries(linewidth=0.5) m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(y1,y2,5.),labels=[1,0,0,0],color='black',dashes=[1,1],labelstyle='+/-',linewidth=0.2) # draw parallels m.drawmeridians(np.arange(x1-20,x2,5.),labels=[0,0,0,1],color='black',dashes=[1,1],labelstyle='+/-',linewidth=0.2) # draw meridians m.fillcontinents(color='black') m.contour(ex,ey,topoin, levels=[ -70, -100, -200, -1000], linewidths=0.2) m.scatter(x,y,20,marker='+') f = plt.gcf() DefaultSize = f.get_size_inches() f.set_size_inches( (DefaultSize[0]*4, DefaultSize[1]*2) ) return (fig1, plt)
def plot_topo(filename,savename): """ Reads in the topography/bathemetry text file and plots the data. """ f = open(filename,'r') lon=[] lat=[] topo=[] for line in f.readlines(): temp = line.split() if (float(temp[0]) == -180.0): lat.append(float(temp[1])) if (float(temp[1]) == -90.0): lon.append(float(temp[0])) topo.append(float(temp[2])) topo = np.array(topo).reshape((len(lat),len(lon))) lons,lats = np.meshgrid(lon,lat) m = Basemap(projection='cyl', llcrnrlon=-180, urcrnrlon=180, llcrnrlat=-90, urcrnrlat=90) x,y = m(lons,lats) fig = plt.figure(figsize=(10,5)) m.drawmeridians(np.arange(-180,181,30),labels=[1,0,0,1]) m.drawparallels(np.arange(-90,91,30), labels=[0,1,1,0]) pcm = m.pcolormesh(x,y,topo,cmap='RdBu_r',vmin=-6000,vmax=6000) m.contour(x,y,topo,[-1000,0,1000],colors='k',linewidths=[.5, 1, .5]) cax = fig.add_axes([0.68, 0.17, 0.14, 0.02]) cb = plt.colorbar(pcm, cax=cax, orientation='horizontal',ticks=[-6000,-3000,0,3000,6000]) cb.set_label('Topography/Bathymetry [m]',fontsize=6) xtl = cax.get_xticklabels() for foo in xtl: foo.set_fontsize(6) plt.savefig(savename,dpi=600)
def reconstruction_plot_pcolor(lats, lons, data_cube, lvl_num, parm, u, v,w, angs, mask, **kwargs): ber_loc=[-12.4, 130.85] #location of Berrimah radar gp_loc=[-12.2492, 131.0444]#location of CPOL at Gunn Point box=kwargs.get('box',[130.0, 132.0, -13.0, -11.5])#box for the plot bquiver=kwargs.get('bquiver', [0.1, 0.75]) ksp=kwargs.get('ksp', 0.05) #Set up the map and projection mapobj= Basemap(projection='merc',lat_0=(box[2]+box[3])/2.0, lon_0=(box[0]+box[1])/2.0,llcrnrlat=box[2], llcrnrlon=box[0], urcrnrlat=box[3] , urcrnrlon=box[1], resolution='l',area_thresh=1., lat_ts=(box[2]+box[3])/2.0) #map.drawmapboundary() um=M.masked_where(M.array(mask) < 0.5, M.array(u)) vm=M.masked_where(M.array(mask) < 0.5, M.array(v)) mag=M.array(sqrt(u**2+v**2)) magm=M.masked_where(M.array(mask)<0.5, mag) fig_name=kwargs.get('fig_name', 'recon_'+parm+'_.png') longr, latgr=meshgrid(lons,lats) xx, yy = mapobj(longr, latgr) mapobj.drawmapboundary() mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstqldmd_r', 'qcoast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) #mapobj.drawmeridians(array([130,130.5, 131, 131.5, 132]), labels=[1,0,0,1]) #mapobj.drawparallels(array([-13,-12.5,-12,-11.5,-11]), labels=[1,0,0,1]) data=M.masked_where(M.array(mask) < 0.5, M.array(data_cube[parm][:,:,lvl_num])) if parm in ['diff']: data=M.masked_where(M.array(mask) < 0.5, M.array(data)) comp_levs=linspace(-1.,1., 30) levs_dict={'VR':linspace(-25,25,51), 'CZ': linspace(-8,64,10), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31), 'VE':linspace(-25,25,51)} titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff', 'VE':'Edited velocity'} mapobj.pcolor(xx,yy,data, vmin=levs_dict[parm].min(), vmax=levs_dict[parm].max()) colorbar() #mapobj.quiver(xx,yy,u/sqrt(u**2+v**2),v/sqrt(u**2+v**2), scale=50) qq=mapobj.quiver(xx,yy,um,vm, scale=kwargs.get('qscale', 200)) quiverkey(qq, bquiver[0], bquiver[1]+2.*ksp, 10, '10 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) print bquiver[0], bquiver[1]+2.*ksp quiverkey(qq, bquiver[0], bquiver[1]+ksp, 5, '5 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) quiverkey(qq, bquiver[0], bquiver[1], 2, '2 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) cobject=mapobj.contour(xx,yy,w, colors=['k'], levels=linspace(-10,10,6)) fon = { 'fontname':'Tahoma', 'fontsize':5 } clabel(cobject, fmt="%1.1f", **fon) mapobj.contour(xx,yy,angs, levels=[30.0, 150.0],colors=['r']) mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/nt_coast','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) mapobj.drawmeridians(linspace(0,4,41)+130., labels=[1,0,0,1], fontsize=rcParams['xtick.labelsize']) mapobj.drawparallels(linspace(0,4,41)-15.0, labels=[1,0,0,1], fontsize=rcParams['ytick.labelsize']) return mapobj
def plot_topBL(self,datagrid,ugrid,vgrid,filename): module = (np.sqrt(ugrid*ugrid+vgrid*vgrid))*3.6 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,datagrid,512) levels = np.arange(0, 5000, 100) CS = map.contour(x,y,datagrid, levels, linewidths=0.01,colors = 'k') plt.clabel(CS,inline=1,fmt='%d') lw = 1 + 4*module/50 map.streamplot(x,y,ugrid,vgrid, density=3, color='k', linewidth=lw , arrowsize=2 ) for ix in np.arange(0,module.shape[1],2): for iy in np.arange(0,module.shape[0],2): #print ix,iy ilon = self.lon[ix] ilat = self.lat[iy] a,b = map(ilon, ilat) plt.text(a,b ,int(module[iy,ix]),fontsize=fontsize,fontweight='bold', ha='center',va='center',color='r') plt.subplots_adjust(left=0.0, right=figsize, top=figsize, bottom=0.0) self.saveplot(plt,filename) plt.close() # Legend 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 plot_map(data_grid, grid_spacing, orientation, title, file_name, topo=None): pylab.clf() nx, ny = data_grid.shape grid_x, grid_y = grid_spacing map = Basemap(projection='lcc', resolution=None, width=(nx * grid_x), height=(ny * grid_y), lat_0=40.61998, lon_0=-107.344, lat_1=30., lat_2=60.) ctr_x, ctr_y = map(-104.344, 41.61998) move_x = ctr_x - nx * grid_x / 2 move_y = ctr_y - ny * grid_y / 2 llcrnrlon, llcrnrlat = map(move_x, move_y, inverse=True) urcrnrlon, urcrnrlat = map(nx * grid_x + move_x, ny * grid_y + move_y, inverse=True) map = Basemap(projection='lcc', resolution='l', llcrnrlat=llcrnrlat, llcrnrlon=llcrnrlon, urcrnrlat=urcrnrlat, urcrnrlon=urcrnrlon, lat_0=40.61998, lon_0=-107.344, lat_1=30., lat_2=60.) x, y = np.meshgrid(grid_x * np.arange(nx), grid_y * np.arange(ny)) interval = (data_grid.max() - data_grid.min()) / 100. pylab.contourf(x, y, data_grid, levels=np.arange(data_grid.min(), data_grid.max() + interval, interval)) if topo is not None: topo_data, topo_lats, topo_lons = topo topo_lats, topo_lons = np.meshgrid(topo_lats, topo_lons) topo_x, topo_y = map(topo_lons, topo_lats) map.contour(topo_x, topo_y, topo_data, colors='#808080') map.drawstates() map.drawcountries() map.drawcoastlines() pylab.colorbar() pylab.title(title) pylab.savefig(file_name) return
def plot_ppi_lobes_qld(sweep_dict, parm, **kwargs): #[-27.669166564941406, 152.8619384765625] radar_loc=kwargs.get('radar_loc', [-12.2492, 131.0444]) radar_loc2=kwargs.get('radar_loc2', [-12.2492, 131.0444]) fig_name=kwargs.get('fig_name', 'ppi_'+parm+'_.png') fig_path=kwargs.get('fig_path', getenv('HOME')+'/bom_mds/output/') f=figure() #gp_loc=[-12.2492, 131.0444] Re=6371.0*1000.0 rad_at_radar=Re*sin(pi/2.0 -abs(radar_loc[0]*pi/180.0))#ax_radius(float(lat_cpol), units='degrees') lons=radar_loc[1]+360.0*sweep_dict['xar']/(rad_at_radar*2.0*pi) lats=radar_loc[0] + 360.0*sweep_dict['yar']/(Re*2.0*pi) alats=linspace(radar_loc[0]-2.0, radar_loc[0]+2.0, 100.0) alons=linspace(radar_loc[1]-2.0, radar_loc[1]+2.0, 100.0) angs=array(propigation.make_lobe_grid(radar_loc, radar_loc2, alats,alons)) def_loc_dict={'lat_0':lats.mean(), 'lon_0':lons.mean(),'llcrnrlat':lats.min(), 'llcrnrlon':lons.min(), 'urcrnrlat':lats.max() , 'urcrnrlon':lons.max(), 'lat_ts':lats.mean()} loc_dict=kwargs.get('loc_dict', def_loc_dict) map= Basemap(projection='merc', resolution='l',area_thresh=1., **loc_dict) xx, yy = map(lons, lats) galons, galats=meshgrid(alons, alats) xxl, yyl=map(galons, galats) #map.drawcoastlines() #map.drawcountries() map.drawmapboundary() map.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstqldmd_r', 'qcoast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) map.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) map.drawmeridians(array([152,152.5,153,153.5,154]), labels=[1,0,0,1]) map.drawparallels(array([-29,-28.5,-28,-27.5,-27]), labels=[1,0,0,1]) levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'PH': linspace(0,185,255), "RH": linspace(0,1.5,16), "SW":linspace(0, 5, 11), "ZD":linspace(-10,10,21), 'VE':linspace(-30,30,31), 'TI':linspace(-30,30,31), 'KD':linspace(-1.0,6.0,30)} titles_dict={'VR': 'Velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'PH': 'Differential Prop Phase (degrees)', 'RH':'Correlation Co-ef', 'SW':'Spectral Width (m/s)', 'ZD':'Differentail Reflectivity dBz', 'VE':'Edited Velocity (m/s)', 'TI':'Simualated winds,(m/s)', 'KD':'Specific differential Phase (Degrees/m)'} map.contourf(xx,yy,sweep_dict[parm], levels=levs_dict[parm]) colorbar() map.contour(xxl,yyl,angs, levels=[30.0, 150.0],colors=['r']) p=sweep_dict['date'] dtstr='%(#1)02d-%(#2)02d-%(#3)04d %(#4)02d%(#5)02dZ ' %{"#1":p.day, "#2":p.month, "#3":p.year, "#4":p.hour, '#5':p.minute} title(sweep_dict['radar_name']+' '+dtstr+titles_dict[parm]) savefig(fig_path+fig_name) close(f)
def polar_quiver_wind(self, ax, ns='N'): # Wind vector in lat-long coordinates. # For different map projections, the arithmetics to calculate xywind # are different if self.empty: return from mpl_toolkits.basemap import Basemap from apexpy import Apex # Creat polar coordinates projection,fc = ('npstere',1) if ns=='N' else ('spstere',-1) m = Basemap(projection=projection,boundinglat=fc*40,lon_0=0,resolution='l') m.drawcoastlines(color='gray',zorder=1) m.fillcontinents(color='lightgray',zorder=0) dt = self.index.min() + (self.index.max()-self.index.min())/2 m.nightshade(dt,zorder=2) #m.drawparallels(np.arange(-80,81,20)) #m.drawmeridians(np.arange(-180,181,60),labels=[1,1,1,1]) # Calculate mlat and mlon lat_grid = np.arange(-90,91,10) lon_grid = np.arange(-180,181,10) lon_grid, lat_grid = np.meshgrid(lon_grid, lat_grid) gm = Apex(date=2005) mlat,mlon = gm.convert(lat_grid,lon_grid,'geo','apex') hc1 = m.contour(lon_grid,lat_grid,mlat,levels=np.arange(-90,91,10), colors='k', zorder=3, linestyles='dashed', linewidths=1, latlon=True) # hc2 = m.contour(lon_grid,lat_grid,mlon,levels=np.arange(-180,181,45), # colors='k', zorder=3, linestyles='dashed', latlon=True) plt.clabel(hc1,inline=True,colors='k',fmt='%d') # plt.clabel(hc2,inline=True,colors='k',fmt='%d') # Calculate and plot x and y winds lat = self.lat lon = self.long wind = self.wind winde1 = self.winde winde = winde1*wind windn1 = self.windn windn = windn1*wind # only appropriate for the npstere and spstere xwind = fc*winde*np.cos(lon/180*np.pi)-windn*np.sin(lon/180*np.pi) ywind = winde*np.sin(lon/180*np.pi)+fc*windn*np.cos(lon/180*np.pi) hq = m.quiver(np.array(lon),np.array(lat),xwind,ywind,color='blue', scale=300, scale_units='inches',zorder=3, latlon=True) #plt.quiverkey(hq,1.05,1.05,100,'100 m/s',coordinates='axes',labelpos='E') #m.scatter(np.array(lon),np.array(lat), # s=50, c=self.index.to_julian_date(),linewidths=0, zorder=4,latlon=True) return m
def gera_contour (msg,tipo): lat,lon = msg.latlons() data=msg.values #Plotagem do campo usando o Basemap. Inicia a projeção do mapa usando os limites min e max dos proprios dados m=Basemap(projection='mill',lat_ts=10,llcrnrlon=lon.min(), \ urcrnrlon=lon.max(),llcrnrlat=lat.min(),urcrnrlat=lat.max(), \ resolution='c') #Convertendo os valores de lat/lon para as projeções de x/y x, y = m(lon,lat) #Opção colors define a cor da linha. Nesse caso preto. # cs=m.contour (x,y ,data,linewidth=5,colors='k' ) #inline estabele que os rotulos são desenhados através das linhas #fmt controla o formato do número plt.clabel(cs, fontsize=10, inline=1,fmt='%.1f') #Adicionado a linha de costa e limites dos eixos m.drawcoastlines() #m.fillcontinents() #m.drawmapboundary() m.drawparallels(np.arange(-90.,120.,30.),labels=[1,0,0,0]) m.drawmeridians(np.arange(-180.,180.,60.),labels=[0,0,0,1]) plt.title('Altura do '+tipo+ ' em 500 hPa em 1 jan 2016') fig_out='/home/eduardo/dado/fig1/'+'Altura do geopotencial '+tipo+' _janeiro_2016 v1' + '.png' plt.savefig(fig_out) plt.show() plt.close()
def plotmap(): # create figure fig = plt.figure(figsize=(8, 8)) # set up orthographic map projection with # perspective of satellite looking down at 50N, 100W. # use low resolution coastlines. map = Basemap(projection='ortho', lat_0=50, lon_0=-100, resolution='l') # lat/lon coordinates of five cities. lats = [40.02, 32.73, 38.55, 48.25, 17.29] lons = [-105.16, -117.16, -77.00, -114.21, -88.10] cities = ['Boulder, CO', 'San Diego, CA', 'Washington, DC', 'Whitefish, MT', 'Belize City, Belize'] # compute the native map projection coordinates for cities. xc, yc = map(lons, lats) # make up some data on a regular lat/lon grid. nlats = 73 nlons = 145 delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0, :, :]) lons = (delta*np.indices((nlats, nlons))[1, :, :]) wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons)) mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.) # compute native map projection coordinates of lat/lon grid. # (convert lons and lats to degrees first) x, y = map(lons*180./np.pi, lats*180./np.pi) # draw map boundary map.drawmapboundary(color="0.9") # draw graticule (latitude and longitude grid lines) map.drawmeridians(np.arange(0, 360, 30), color="0.9") map.drawparallels(np.arange(-90, 90, 30), color="0.9") # plot filled circles at the locations of the cities. map.plot(xc, yc, 'wo') # plot the names of five cities. for name, xpt, ypt in zip(cities, xc, yc): plt.text(xpt+100000, ypt+100000, name, fontsize=9, color='w') # contour data over the map. cs = map.contour(x, y, wave+mean, 15, linewidths=1.5) # draw blue marble image in background. # (downsample the image by 50% for speed) map.bluemarble(scale=0.5)
y_max = 47. + (50. / 60.) # Create arrays with all lon/lat values from min to max. lats = np.linspace(y_max, y_min, srtm3.shape[0]) lons = np.linspace(x_min, x_max, srtm3.shape[1]) # Create Basemap instance with Mercator projection. m = Basemap(projection='merc',lon_0=13,lat_0=48,resolution="h", llcrnrlon=12.75, llcrnrlat=47.69, urcrnrlon=12.95, urcrnrlat=47.81) # Create grids and compute map projection coordinates for lon/lat grid. x, y = m(*np.meshgrid(lons,lats)) # Make gradient plot. #ps = m.pcolor(x, y, srtm3) # Make contour plot. cs = m.contour(x, y, srtm3, 40, colors=".4", lw=0.5, alpha=0.3) m.drawcountries(color="red", linewidth=1) # Draw a lon/lat grid (20 lines for an interval of one degree). m.drawparallels(np.linspace(47, 48, 21), labels=[1,1,0,0], fmt="%.2f", dashes=[2,2]) m.drawmeridians(np.linspace(12, 13, 21), labels=[0,0,1,1], fmt="%.2f", dashes=[2,2]) # Calculate map projection for the coordinates. x, y = m(stations_long, stations_lat) m.scatter(x, y, 200, color="r", marker="v", edgecolor="k", zorder=3) for i in range(len(stations_id)): plt.text(x[i], y[i], " " + stations_id[i], color='k', va="top", family="monospace", weight="bold")
label = r'$\delta^{18} O$' + u' (' + u'\u2030' + ')' f = Dataset(path) var = f.variables[var_name][:, :] #[0,0,:,:] lat = f.variables['latitude'][:] lon = f.variables['longitude'][:] f.close() fig = plt.figure() m = Basemap(projection='spstere', boundinglat=-60, lon_0=-180, resolution='h') var_cyclic, lon_cyclic = addcyclic(var, lon) var_cyclic, lon_cyclic = shiftgrid(180., var_cyclic, lon_cyclic, start=False) lon2d, lat2d = np.meshgrid(lon_cyclic, lat) x, y = m(lon2d, lat2d) mdata = maskoceans(lon2d, lat2d, var_cyclic, resolution='h', grid=1.25, inlands=True) cs = m.contourf(x, y, mdata, cmap=plt.cm.rainbow, alpha=0.5) levels = np.arange(var.min(), var.max(), 5) cs2 = m.contour(x, y, mdata, levels=levels, linewidth=1.) plt.clabel(cs2, fmt='%4.0f', fontsize=8) m.drawcoastlines(color='grey') m.drawmapboundary() cbar = m.colorbar(cs, location='bottom') cbar.set_label(label) cbar.ax.tick_params(labelsize=8) plt.show()
def zview(var, tindex, depth, grid, filename=None, \ cmin=None, cmax=None, clev=None, clb_format='%.2f', \ fill=False, contour=False, d=4, range=None, fts=None, \ title=None, clb=True, pal=None, proj='merc', \ fill_land=False, outfile=None): """ map = zview(var, tindex, depth, grid, {optional switch}) optional switch: - filename if defined, load the variable from file - cmin set color minimum limit - cmax set color maximum limit - clev set the number of color step - fill use contourf instead of pcolor - contour overlay contour (request fill=True) - range set axis limit - fts set font size (default: 12) - title add title to the plot - clb add colorbar (defaul: True) - pal set color map (default: cm.jet) - proj set projection type (default: merc) - fill_land fill land masked area with gray (defaul: True) - outfile if defined, write figure to file plot a constant-z slice of variable var. If filename is provided, var must be a string and the variable will be load from the file. grid can be a grid object or a gridid. In the later case, the grid object correponding to the provided gridid will be loaded. If proj is not None, return a Basemap object to be used with quiver for example. """ # get grid if type(grid).__name__ == 'ROMS_Grid': grd = grid else: grd = pyroms.grid.get_ROMS_grid(grid) # get variable if filename == None: var = var else: data = pyroms.io.Dataset(filename) var = data.variables[var] Np, Mp, Lp = grd.vgrid.z_r[0,:].shape if tindex is not -1: assert len(var.shape) == 4, 'var must be 4D (time plus space).' K, N, M, L = var.shape else: assert len(var.shape) == 3, 'var must be 3D (no time dependency).' N, M, L = var.shape # determine where on the C-grid these variable lies if N == Np and M == Mp and L == Lp: Cpos='rho' mask = grd.hgrid.mask_rho if N == Np and M == Mp and L == Lp-1: Cpos='u' mask = grd.hgrid.mask_u if N == Np and M == Mp-1 and L == Lp: Cpos='v' mask = grd.hgrid.mask_v # get constante-z slice if tindex == -1: var = var[:,:,:] else: var = var[tindex,:,:,:] depth = -abs(depth) if fill == True: zslice, lon, lat = pyroms.tools.zslice(var, depth, grd, \ Cpos=Cpos) else: zslice, lon, lat = pyroms.tools.zslice(var, depth, grd, \ Cpos=Cpos, vert=True) # plot if cmin is None: cmin = zslice.min() else: cmin = float(cmin) if cmax is None: cmax = zslice.max() else: cmax = float(cmax) if clev is None: clev = 100. else: clev = float(clev) dc = (cmax - cmin)/clev ; vc = np.arange(cmin,cmax+dc,dc) if pal is None: pal = cm.jet else: pal = pal if fts is None: fts = 12 else: fts = fts #pal.set_over('w', 1.0) #pal.set_under('w', 1.0) #pal.set_bad('w', 1.0) pal_norm = colors.BoundaryNorm(vc,ncolors=256, clip = False) if range is None: lon_min = lon.min() lon_max = lon.max() lon_0 = (lon_min + lon_max) / 2. lat_min = lat.min() lat_max = lat.max() lat_0 = (lat_min + lat_max) / 2. else: lon_min = range[0] lon_max = range[1] lon_0 = (lon_min + lon_max) / 2. lat_min = range[2] lat_max = range[3] lat_0 = (lat_min + lat_max) / 2. # clear figure #plt.clf() if proj is not None: map = Basemap(projection=proj, llcrnrlon=lon_min, llcrnrlat=lat_min, \ urcrnrlon=lon_max, urcrnrlat=lat_max, lat_0=lat_0, lon_0=lon_0, \ resolution='h', area_thresh=5.) #map = pyroms.utility.get_grid_proj(grd, type=proj) x, y = map(lon,lat) if fill_land is True and proj is not None: # fill land and draw coastlines map.drawcoastlines() map.fillcontinents(color='grey') else: if proj is not None: Basemap.pcolor(map, x, y, mask, vmin=-2, cmap=cm.gray) pyroms_toolbox.plot_coast_line(grd, map) else: plt.pcolor(lon, lat, mask, vmin=-2, cmap=cm.gray) pyroms_toolbox.plot_coast_line(grd) if fill is True: if proj is not None: cf = Basemap.contourf(map, x, y, zslice, vc, cmap = pal, \ norm = pal_norm) else: cf = plt.contourf(lon, lat, zslice, vc, cmap = pal, \ norm = pal_norm) else: if proj is not None: cf = Basemap.pcolor(map, x, y, zslice, cmap = pal, norm = pal_norm) else: cf = plt.pcolor(lon, lat, zslice, cmap = pal, norm = pal_norm) if clb is True: clb = plt.colorbar(cf, fraction=0.075,format=clb_format) for t in clb.ax.get_yticklabels(): t.set_fontsize(fts) if contour is True: if fill is not True: raise Warning, 'Please run again with fill=True to overlay contour.' else: if proj is not None: Basemap.contour(map, x, y, zslice, vc[::d], colors='k', linewidths=0.5, linestyles='solid') else: plt.contour(lon, lat, zslice, vc[::d], colors='k', linewidths=0.5, linestyles='solid') if proj is None and range is not None: plt.axis(range) if title is not None: plt.title(title, fontsize=fts+4) if proj is not None: map.drawmeridians(np.arange(lon_min,lon_max, (lon_max-lon_min)/5.001), \ labels=[0,0,0,1], fmt='%.1f') map.drawparallels(np.arange(lat_min,lat_max, (lat_max-lat_min)/5.001), \ labels=[1,0,0,0], fmt='%.1f') if outfile is not None: if outfile.find('.png') != -1 or outfile.find('.svg') != -1 or \ outfile.find('.eps') != -1: print 'Write figure to file', outfile plt.savefig(outfile, dpi=200, facecolor='w', edgecolor='w', \ orientation='portrait') else: print 'Unrecognized file extension. Please use .png, .svg or .eps file extension.' if proj is None: return else: return map
urcrnrlon=lonLims[1], urcrnrlat=latLims[1], resolution='i') levels = np.linspace(-.0005, .0005, 9) #levels = 20 xi, yi = m(*np.meshgrid(lon_reg, lat_reg)) #lon_casts, lat_casts = m(lons[idx], lats[idx]) #c = m.contourf(xi, yi, Nmap, levels, cmap=plt.cm.RdBu_r, extend='both') c = m.pcolor(xi, yi, Nmap, cmap=plt.cm.RdBu_r, vmin=levels.min(), vmax=levels.max()) x, y = m(*np.meshgrid(lon, lat)) cc = m.contour(x, y, -Zbathy, [100, 500, 1000, 4000], colors='grey') m.fillcontinents(color='tan') m.drawparallels([40, 45, 50, 55, 60], labels=[1, 0, 0, 0], fontsize=12, fontweight='normal') m.drawmeridians([-60, -55, -50, -45], labels=[0, 0, 0, 1], fontsize=12, fontweight='normal') #plt.title(r'Trends in N $\rm (s^{-1}) yr^{-1}$') plt.title(r'$\rm \frac{dN}{dt} (s^{-1} yr^{-1})$') # Draw NAFO divisions ## x,y = m(np.array(div3K['lon']), np.array(div3K['lat']))
z1 = np.reshape(z, (numlon,numlat)) return x1, y1, z1 if __name__ == '__main__': """ Plots the etopo5 data """ x, y, z = read_topo('global_merged5.txt') m = Basemap(projection = 'cyl', llcrnrlon = -180, llcrnrlat = -90, urcrnrlon = 180, urcrnrlat = 90, resolution = 'l') fig = plt.figure(figsize = [10,5]) plt.title('World Topography') pcm = m.pcolormesh(x,y,z,cmap='RdBu_r') m.contour(x,y,z, [-1000,0,1000], colors = 'k', linewidths = [0.5,1.0,0.5]) m.drawmeridians(np.arange(-180,180,40), dashes = [1,0], labels = [1, 0,0,1]) m.drawparallels(np.arange(-90,90,20), dashes = [1,0], labels = [0, 1,0,0]) cax = fig.add_axes([0.16, 0.3, 0.15, 0.02]) cb = plt.colorbar(pcm, cax = cax, orientation = 'horizontal', ticks = [-6000, 0, 6000]) plt.show()
returnxy=True) D = n.ma.array(n.zeros_like(lons), mask=n.zeros_like(lons)) # print M.shape,mask.shape mpl.rcParams['contour.negative_linestyle'] = 'solid' if scale == 1: D = data else: print "smoothing image" for i in range(data.shape[0]): for j in range(data.shape[1]): D[i / scale, j / scale] += data[i, j] if len(data.mask.shape) == 2: D.mask[i / scale, j / scale] |= data.mask[i, j] D /= scale print "computing and plotting contours" DC = map.contour(x, y, D, levels, colors='k', lw=6) p.clabel(DC, fontsize=10, inline=1) print "flux levels = ", 10**n.array(DC.levels) if opts.skip_im: pass if opts.osys == 'ga': print data.shape data = n.fliplr(data) print data.shape map.imshow(data, vmax=max, vmin=min, cmap=cmap, interpolation=opts.interp) ax.format_coord = format_coord # Plot src labels and markers on top of map image if not opts.src is None: sx, sy = map(slons, slats) for name, xpt, ypt, flx in zip(snams, sx, sy, sflxs): if xpt >= 1e30 or ypt >= 1e30: continue if opts.src_mark != '':
statistics = pd.read_table( '/home/timok/ensex/statistics/multiday/Quantile_ld2/statistics_quantile200.txt', sep=',') #[,2:4] fig = plt.figure(linewidth=5.5) ax = fig.add_axes([0.044, 0.05, 0.9, 0.9]) statistics_threshold = np.array(statistics['Quantile 200-yr']) im1 = m.pcolormesh(np.array(statistics['lon']).reshape(100, 141), np.array(statistics['lat']).reshape(100, 141), np.array(statistics['Quantile 200-yr']).reshape(100, 141), shading='flat', cmap=Oslo, latlon=True) #vmin=vmin_vmax[k][0],vmax=vmin_vmax[k][1], m.contour(np.array(statistics['lon']).reshape(100, 141), np.array(statistics['lat']).reshape(100, 141), np.array(statistics['Quantile 200-yr']).reshape(100, 141), levels=[90], colors='white', latlon=True) #vmin=vmin_vmax[k][0],vmax=vmin_vmax[k][1], x1, y1 = m([4, 4, 7, 7], [58, 63, 63, 58]) #m.scatter(x1,y1,s=1, c='k', marker='.', alpha=.5) xy = zip(x1, y1) poly = matplotlib.patches.Polygon(xy, edgecolor='red', facecolor='None') plt.gca().add_patch(poly) #ax.set_title('SEAS5 RV2 (mm/3days)') cb = m.colorbar( im1, "right", size="5%", pad="2%" ) #m.readshapefile('gadm36_NOR_shp/gadm36_NOR_0',name='gadm36_NOR_0',drawbounds=True,color='black') m.drawcoastlines() m.drawcountries() #m.pcolor(lons_merge_grid[mask_WC_merge].reshape(11,9),lats_merge_grid[mask_WC_merge].reshape(11,9),RV20_seas5[mask_WC_merge].reshape(11,9),latlon=True, hatch='///', alpha=0.5, vmin=80, vmax=3000) #m.contour(lons_merge_grid[mask_WC_merge].reshape(11,9),lats_merge_grid[mask_WC_merge].reshape(11,9),RV20_seas5[mask_WC_merge].reshape(11,9),levels=[0,80,300],latlon=True)
# make 2-d grid of lons, lats lons, lats = np.meshgrid(longitudes, latitudes) # make orthographic basemap. m = Basemap(resolution='c', projection='ortho', lat_0=60., lon_0=-60.) # create figure, add axes fig1 = plt.figure(figsize=(8, 10)) ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8]) # set desired contour levels. clevs = np.arange(960, 1061, 5) # compute native x,y coordinates of grid. x, y = m(lons, lats) # define parallels and meridians to draw. parallels = np.arange(-80., 90, 20.) meridians = np.arange(0., 360., 20.) # plot SLP contours. CS1 = m.contour(x, y, slp, clevs, linewidths=0.5, colors='k', animated=True) CS2 = m.contourf(x, y, slp, clevs, cmap=plt.cm.RdBu_r, animated=True) # plot wind vectors on projection grid. # first, shift grid so it goes from -180 to 180 (instead of 0 to 360 # in longitude). Otherwise, interpolation is messed up. ugrid, newlons = shiftgrid(180., u, longitudes, start=False) vgrid, newlons = shiftgrid(180., v, longitudes, start=False) # transform vectors to projection grid. uproj,vproj,xx,yy = \ m.transform_vector(ugrid,vgrid,newlons,latitudes,31,31,returnxy=True,masked=True) # now plot. Q = m.quiver(xx, yy, uproj, vproj, scale=700) # make quiver key. qk = plt.quiverkey(Q, 0.1, 0.1, 20, '20 m/s', labelpos='W') # draw coastlines, parallels, meridians. m.drawcoastlines(linewidth=1.5)
# examples of filled contour plots on map projections. # read in data on lat/lon grid. hgt = np.loadtxt('500hgtdata.gz') lons = np.loadtxt('500hgtlons.gz') lats = np.loadtxt('500hgtlats.gz') lons, lats = np.meshgrid(lons, lats) # create new figure fig = plt.figure() # setup of sinusoidal basemap m = Basemap(resolution='c', projection='sinu', lon_0=0) # make a filled contour plot. # create contour lines CS1 = m.contour(lons, lats, hgt, 15, linewidths=0.5, colors='k', latlon=True) # fill between contour lines. CS2 =\ m.contourf(lons,lats,hgt,CS1.levels,cmap=plt.cm.jet,extend='both',latlon=True) m.colorbar(CS2) # draw colorbar # draw coastlines and political boundaries. m.drawcoastlines() m.drawmapboundary() m.fillcontinents() # draw parallels and meridians. parallels = np.arange(-60., 90, 30.) m.drawparallels(parallels, labels=[1, 0, 0, 0]) meridians = np.arange(-360., 360., 30.) m.drawmeridians(meridians) plt.title('Sinusoidal Filled Contour Demo') sys.stdout.write('plotting with sinusoidal basemap ...\n')
m.drawlsmask(land_color='darkgrey', ocean_color='w') ### Adjust maximum limits values = np.arange(-0.2, 0.21, 0.01) ### Plot filled contours cs = m.contourf(lons[:, :], lats[:, :], val[:, :], values, latlon=True, extend='both') cs1 = m.contour(lons[:, :], lats[:, :], val[:, :], values, latlon=True, linestyles='-', colors='k', linewidths=0.05) ### Set colormap cmap = plt.cm.get_cmap('seismic_r') cs.set_cmap(cmap) cbar = m.colorbar(cs, drawedges=True, location='bottom', pad=0.3, extend='both') cbar.set_label(r'Ice Production [m/day]')
# (higher value, fewer highs and lows) local_min, local_max = extrema(prmsl, mode='wrap', window=50) # create Basemap instance. m =\ Basemap(llcrnrlon=0,llcrnrlat=-80,urcrnrlon=360,urcrnrlat=80,projection='mill') # add wrap-around point in longitude. prmsl, lons = addcyclic(prmsl, lons1) # contour levels clevs = np.arange(900, 1100., 5.) # find x,y of map projection grid. lons, lats = np.meshgrid(lons, lats) x, y = m(lons, lats) # create figure. fig = plt.figure(figsize=(8, 4.5)) ax = fig.add_axes([0.05, 0.05, 0.9, 0.85]) cs = m.contour(x, y, prmsl, clevs, colors='k', linewidths=1.) m.drawcoastlines(linewidth=1.25) m.fillcontinents(color='0.8') m.drawparallels(np.arange(-80, 81, 20), labels=[1, 1, 0, 0]) m.drawmeridians(np.arange(0, 360, 60), labels=[0, 0, 0, 1]) xlows = x[local_min] xhighs = x[local_max] ylows = y[local_min] yhighs = y[local_max] lowvals = prmsl[local_min] highvals = prmsl[local_max] # plot lows as blue L's, with min pressure value underneath. xyplotted = [] # don't plot if there is already a L or H within dmin meters. yoffset = 0.022 * (m.ymax - m.ymin) dmin = yoffset
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() station_plot(data, proj=bm, layout=dict(C='height', NW=None, SW=None), zorder=10) cp = bm.contour(x_grid, y_grid, heights_cress, contours) plt.clabel(cp, fmt='%.0f', inline_spacing=0) plt.title('500mb Height map') plt.show()
Ynew = yi[0::10, 0::10] #MSL height range range_mslHgts = np.arange(950, 1050, 3) #Sfc temps range range_sfcTemps = np.arange(-10, 50, 5) #Add contour fills MSL values contour_MSLh = m.contour(xi, yi, sfc_Heights, range_mslHgts, colors='Black') clab = plt.clabel(contour_MSLh, inline=True, fontsize=14, fmt='%1.0f') #Add contour fills for geo heights values 500 mb contour_sfcTemps = m.contourf(xi, yi, sfcTemps_C, range_sfcTemps, cmap='ocean') ## plot wind barbs over map
Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high,projection='mill', rsphere=6371229) x, y = m(lons, lats) x_w, y_w = m(lons_w2deg, lats_w2deg) #print x_w.shape fig=plt.figure(figsize=(8,8)) ax = fig.add_axes([0.05,0.05,0.9,0.85],axisbg='#262626') m.drawcountries(color='#262626') m.drawcoastlines(linewidth=0.5,color='#262626' ) #m.fillcontinents(color='#CCFF99') m.drawparallels(np.arange(-80,81,10),labels=[1,1,0,0]) m.drawmeridians(np.arange(0,360,10),labels=[0,0,0,1]) cs_lin = m.contour(x,y, plt_h, clevs_lin,colors='#262626',linewidths=0.5) if plot_diag=='temp': plt_v = np.ma.masked_outside(mean_var[:,:,-(s+1)], clevpt_max+20, clevpt_min-20) cs_col = m.contourf(x,y, plt_v, np.linspace(clevpt_min, clevpt_max), cmap=plt.cm.RdBu_r, extend='both') cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%d') cbar.set_label('K') plt.suptitle('Height, Potential Temperature and Wind Vectors at %s hPa'% (p), fontsize=10) elif plot_diag=='sp_hum': plt_v = np.ma.masked_outside(mean_var[:,:,-(s+1)], clevsh_max+20, clevsh_min-20) cs_col = m.contourf(x,y, plt_v, np.linspace(clevsh_min, clevsh_max), cmap=plt.cm.RdBu_r, extend='both') cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%.3f') cbar.set_label('kg/kg')
max_down = line_32.values xmin, xmax, ymin, ymax = cut_data(HRRR_lat, HRRR_lon, bot_left_lat, top_right_lat, bot_left_lon, top_right_lon) HRRR_lat = HRRR_lat[xmin:xmax, ymin:ymax] HRRR_lon = HRRR_lon[xmin:xmax, ymin:ymax] max_up = max_up[xmin:xmax, ymin:ymax] max_down = max_down[xmin:xmax, ymin:ymax] plot_levels = np.arange(-2, 2.1, .5) UD = m.contour(HRRR_lon, HRRR_lat, max_up, plot_levels, cmap='bwr', vmin=-2, vmax=2) DD = m.contour(HRRR_lon, HRRR_lat, max_down, plot_levels, cmap='bwr', vmin=-2, vmax=2) if plotted_cb == False: cbar = plt.colorbar(UD, orientation='vertical', shrink=.8, pad=.02) plotted_cb = True
def isoview(var, prop, tindex, isoval, grid, filename=None, \ cmin=None, cmax=None, clev=None, fill=False, \ contour=False, d=4, range=None, fts=None, \ title=None, clb=True, pal=None, proj='merc', \ fill_land=False, outfile=None): """ map = isoview(var, prop, tindex, isoval, grid, {optional switch}) optional switch: - filename if defined, load the variable from file - cmin set color minimum limit - cmax set color maximum limit - clev set the number of color step - fill use contourf instead of pcolor - contour overlay contour (request fill=True) - d contour density (default d=4) - range set axis limit - fts set font size (default: 12) - title add title to the plot - clb add colorbar (defaul: True) - pal set color map (default: cm.jet) - proj set projection type (default: merc) - fill_land fill land masked area with gray (defaul: True) - outfile if defined, write figure to file plot a projection of variable at property == isoval. If filename is provided, var and prop must be a strings and the variables will be load from the file. grid can be a grid object or a gridid. In the later case, the grid object correponding to the provided gridid will be loaded. If proj is not None, return a Basemap object to be used with quiver for example. """ # get grid if type(grid).__name__ == 'ROMS_Grid': grd = grid else: grd = pyroms.grid.get_ROMS_grid(grid) # get variable if filename == None: var = var prop = prop else: data = pyroms.io.Dataset(filename) var = data.variables[var] prop = data.variables[prop] Np, Mp, Lp = grd.vgrid.z_r[0, :].shape if tindex is not -1: assert len(var.shape) == 4, 'var must be 4D (time plus space).' K, N, M, L = var.shape else: assert len(var.shape) == 3, 'var must be 3D (no time dependency).' N, M, L = var.shape # determine where on the C-grid these variable lies if N == Np and M == Mp and L == Lp: Cpos = 'rho' mask = grd.hgrid.mask_rho if N == Np and M == Mp and L == Lp - 1: Cpos = 'u' mask = grd.hgrid.mask_u if N == Np and M == Mp - 1 and L == Lp: Cpos = 'v' mask = grd.hgrid.mask_v # get constante-iso slice if tindex == -1: var = var[:, :, :] prop = prop[:, :, :] else: var = var[tindex, :, :, :] prop = prop[tindex, :, :, :] if fill == True: isoslice, lon, lat = pyroms.tools.isoslice(var, prop, isoval, \ grd, Cpos=Cpos) else: isoslice, lon, lat = pyroms.tools.isoslice(var, prop, isoval, \ grd, Cpos=Cpos, vert=True) # plot if cmin is None: cmin = isoslice.min() else: cmin = float(cmin) if cmax is None: cmax = isoslice.max() else: cmax = float(cmax) if clev is None: clev = 100. else: clev = float(clev) dc = (cmax - cmin) / clev vc = np.arange(cmin, cmax + dc, dc) if pal is None: pal = cm.jet else: pal = pal if fts is None: fts = 12 else: fts = fts #pal.set_over('w', 1.0) #pal.set_under('w', 1.0) #pal.set_bad('w', 1.0) pal_norm = colors.BoundaryNorm(vc, ncolors=256, clip=False) if range is None: lon_min = lon.min() lon_max = lon.max() lon_0 = (lon_min + lon_max) / 2. lat_min = lat.min() lat_max = lat.max() lat_0 = (lat_min + lat_max) / 2. else: lon_min = range[0] lon_max = range[1] lon_0 = (lon_min + lon_max) / 2. lat_min = range[2] lat_max = range[3] lat_0 = (lat_min + lat_max) / 2. # clear figure #plt.clf() if proj is not None: map = Basemap(projection=proj, llcrnrlon=lon_min, llcrnrlat=lat_min, \ urcrnrlon=lon_max, urcrnrlat=lat_max, lat_0=lat_0, lon_0=lon_0, \ resolution='h', area_thresh=5.) #map = pyroms.utility.get_grid_proj(grd, type=proj) x, y = list(map(lon, lat)) if fill_land is True and proj is not None: # fill land and draw coastlines map.drawcoastlines() map.fillcontinents(color='grey') else: if proj is not None: Basemap.pcolor(map, x, y, mask, vmin=-2, cmap=cm.gray) pyroms_toolbox.plot_coast_line(grd, map) else: plt.pcolor(lon, lat, mask, vmin=-2, cmap=cm.gray) pyroms_toolbox.plot_coast_line(grd) if fill is True: if proj is not None: cf = Basemap.contourf(map, x, y, isoslice, vc, cmap = pal, \ norm = pal_norm) else: cf = plt.contourf(lon, lat, isoslice, vc, cmap = pal, \ norm = pal_norm) else: if proj is not None: cf = Basemap.pcolor(map, x, y, isoslice, cmap=pal, norm=pal_norm) else: cf = plt.pcolor(lon, lat, isoslice, cmap=pal, norm=pal_norm) if clb is True: clb = plt.colorbar(cf, fraction=0.075, format='%.2f') for t in clb.ax.get_yticklabels(): t.set_fontsize(fts) if contour is True: if fill is not True: raise Warning( 'Please run again with fill=True to overlay contour.') else: if proj is not None: Basemap.contour(map, x, y, isoslice, vc[::d], colors='k', linewidths=0.5, linestyles='solid') else: plt.contour(lon, lat, isoslice, vc[::d], colors='k', linewidths=0.5, linestyles='solid') if proj is None and range is not None: plt.axis(range) if title is not None: plt.title(title, fontsize=fts + 4) if proj is not None: map.drawmeridians(np.arange(lon_min,lon_max, (lon_max-lon_min)/5.), \ labels=[0,0,0,1], fmt='%.1f') map.drawparallels(np.arange(lat_min,lat_max, (lat_max-lat_min)/5.), \ labels=[1,0,0,0], fmt='%.1f') if outfile is not None: if outfile.find('.png') != -1 or outfile.find('.svg') != -1 or \ outfile.find('.eps') != -1: print('Write figure to file', outfile) plt.savefig(outfile, dpi=200, facecolor='w', edgecolor='w', \ orientation='portrait') else: print( 'Unrecognized file extension. Please use .png, .svg or .eps file extension.' ) if proj is None: return else: return map
def plot_evo(data, year, day0, lat, lon, center=None, days=[0], show_map=True, cmap=plt.cm.RdBu_r,clev_bound=None, clev_num=20, show_day=True, lat_ticks=10, lon_ticks=30): """ This function will create a set of plots (e.g. total/standing/travelling) side by side showing the evolution of the data sets. data - array containing data with dimensions [# of datasets,year,day,plev=1,lat,lon] year - year 0 refers to first index in data (e.g. don't use 1982, use 3 if data starts in 1979) day0 - what day to center the evolution on lat - array of latitudes corresponding to data lon - array of longitudes corresponding to data center - a point to plot on the map (e.g. center of heat wave) days - list of integers representing days relative to day0 for which to create plots Returns: fig - a pyplot figure ax - an array of pyplot axes with dimensions [days.size,# of datasets] """ # create figure/axes fig, ax = plt.subplots(len(days), data.shape[0], subplot_kw={'frame_on':True}, facecolor='w', figsize=(17,11)) marker_style = dict(marker='o', color='black', markersize=10) # create basemap instance m = Basemap(projection='cyl',llcrnrlat=np.min(lat),\ urcrnrlat=np.max(lat),llcrnrlon=np.min(lon),\ urcrnrlon=np.max(lon),resolution='c') # make x,y grid from lat,lon lon_grid,lat_grid = np.meshgrid(lon,lat) x,y = m(lon_grid,lat_grid) # contour levels if clev_bound is None: # extract data in the range of interest for generating contours if len(days) == 1: data_chunk = np.real(data[:,year,day0+days[0]]) else: data_chunk = np.real(data[:,year,day0+days[0]:day0+days[-1]]) extreme = np.max(np.absolute(data_chunk)) clevs = np.linspace(-((extreme+10)//10)*10,((extreme+10)//10)*10, num=clev_num) else: clevs = np.linspace(clev_bound[0],clev_bound[1],num=clev_num) # fill in individual plots for i in range(data.shape[0]): for j in range(len(days)): # set current axes if len(days) == 1: if data.shape[0] == 1: plt.sca(ax) else: plt.sca(ax[i]) else: if data.shape[0] == 1: plt.sca(ax[j]) else: plt.sca(ax[j,i]) # check that the day is in range if 0 <= day0 + days[j] < data.shape[2]: plot_data = np.real(data[i][year][day0+days[j]][0]) if show_map: # draw map features m.drawcoastlines(linewidth=2) m.drawcountries(linewidth=2) if i == 0: m.drawparallels(np.arange((np.min(lat)//10)*10+10,np.max(lat),lat_ticks),labels=[1,0,0,0]) else: m.drawparallels(np.arange((np.min(lat)//10)*10+10,np.max(lat),lat_ticks)) if j == len(days) - 1: m.drawmeridians(np.arange((np.min(lon)//10)*10+10,np.max(lon),lon_ticks),labels=[0,0,0,1]) else: m.drawmeridians(np.arange((np.min(lon)//10)*10+10,np.max(lon),lon_ticks)) # fit plot to axis # plot contours cs = m.contourf(x,y,plot_data,clevs,cmap=cmap) csf = m.contour(x,y,plot_data,clevs,linewidths=1,colors='k') # label day number if show_day == True: day_lab = AnchoredText('Day %d' % days[j], loc=1, frameon=True) day_lab.patch.set_boxstyle('round,pad=0.,rounding_size=0.2') if data.shape[0] == 1: ax[j].add_artist(day_lab) else: ax[j,i].add_artist(day_lab) # plot center point if center is not None: plt.plot(center[i,1],center[i,0], **marker_style) else: plt.text(0.2,0.5,'Date out of range') plt.subplots_adjust(left=0.1, right=0.85, wspace=0.01, hspace=0.05) cax = fig.add_axes([0.875, 0.1, 0.025, 0.8]) cbar = plt.colorbar(cs, cax=cax, orientation='vertical') return fig, ax, cax, cbar
m.drawmeridians(meridians, labels=[True, True, False, False], linewidth=0.3, color='k', fontsize=6) m.drawlsmask(land_color='darkgrey', ocean_color='mintcream') # Make the plot continuous barlim = np.arange(0, 110, 10) values = np.arange(0, 101, 1) cs = m.contourf(lon2, lat2, var[:, :] * 100., values, latlon=True) cs1 = m.contour(lon2, lat2, var[:, :] * 100., barlim, linewidths=0.2, colors='k', linestyles='-', latlon=True) cs.set_cmap(cmap) cbar = m.colorbar(cs, location='right', pad='10%', drawedges=False) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str, barlim))) cbar.ax.tick_params(axis='x', size=.1) cbar.set_label(r'\textbf{sic (\%)}') m.fillcontinents(color='dimgrey') fig.suptitle(r'\textbf{Testing PIOMAS Regrid}')
if i==0: #----------------------------------------------------------------------------- # Plot Data using Basemap mercator projection #----------------------------------------------------------------------------- fig=plt.figure(num=None, figsize=(10, 10), dpi=300, facecolor='w') plt.clf() m=Basemap(projection='merc',llcrnrlat=20,urcrnrlat=lat[481,401-25]+8,\ llcrnrlon=-90.75,urcrnrlon=lon[481,401-25]+5,lat_ts=20,resolution='f') # Draw a thick border around the whole map m.drawmapboundary(linewidth=3) xi, yi = m(lon2,lat2) cs = m.pcolormesh(xi,yi,rtime,cmap=cm.gist_ncar,vmin=0, vmax = 365.25*4) xi, yi = m(lon,lat) cM = m.contour( xi,yi,scope2,[1,1],colors='k',linewidth=2.0) cn = m.contour( xi,yi,rtime,[365.25,547.875,730.5],colors='0.5',linewidth=1.0) # Add Grid Lines #m.drawparallels(np.arange(0.,90.,5.), labels=[1,0,0,0],\ # fontsize=10, linewidth=0.75, color='.5') #m.drawmeridians(np.arange(-105.,-35.,5.), labels=[0,0,0,1],\ # fontsize=10, linewidth=0.75, color='.5') # Add Coastlines, States, and Country Boundaries m.drawcoastlines() m.drawstates() m.drawcountries() m.fillcontinents(color='grey') # Add Colorbar
parallels = np.arange(50,90,10) meridians = np.arange(-180,180,30) #m.drawparallels(parallels,labels=[False,False,False,False], # linewidth=0.3,color='k',fontsize=6) #m.drawmeridians(meridians,labels=[False,False,False,False], # linewidth=0.3,color='k',fontsize=6) m.drawlsmask(land_color='darkgrey',ocean_color='mintcream') # Make the plot continuous barlim = np.arange(0,1.1,0.5) values = np.arange(0,1.1,0.1) cs = m.contourf(lons,lats,var, values,latlon=True,extend='max') cs1 = m.contour(lons,lats,var, values,linewidths=0.2,colors='darkgrey', linestyles='-',latlon=True) cmap = plt.cm.get_cmap('cubehelix_r') cs.set_cmap(cmap) ax.annotate(r'\textbf{JFM}', xy=(0, 0), xytext=(-0.23, 0.9), xycoords='axes fraction',fontsize=22,color='darkgrey') ########################################################################### ########################################################################### ax = plt.subplot(222) m = Basemap(projection='npstere',boundinglat=66,lon_0=270, resolution='l',round =True)
#Define range of MSLP values to be printed clevs = np.arange(960, 1041, 4) #Add contour tick marks cticks = np.arange(960, 1041, 8) #Define MSLP values as a color filler mslpfill = m.contourf(xi, yi, mslp00, clevs, cmap = 'rainbow') #Add a color bar cbar = plt.colorbar(mslpfill, orientation = 'horizontal', pad = 0.05, shrink = 0.75, ax = ax, ticks = cticks) #increase size of labels cbar.ax.tick_params(labelsize = 14) cbar.set_label('MSLP (mb)', fontsize = 14) mslplines = m.contour(xi, yi, mslp00, clevs, colors = 'k') mslplab = plt.clabel(mslplines, clevs, inline = True, fontsize = 12, fmt = '%1.0f') # add a title ax.set_title('Test plot of MSLP (mb) from netCDF file') plt.show()
def main(): def unrotate_pole(rotated_lons, rotated_lats, pole_lon, pole_lat): """ Convert rotated-pole lons and lats to unrotated ones. Example:: lons, lats = unrotate_pole(grid_lons, grid_lats, pole_lon, pole_lat) .. note:: Uses proj.4 to perform the conversion. """ src_proj = ccrs.RotatedGeodetic(pole_longitude=pole_lon, pole_latitude=pole_lat) target_proj = ccrs.Geodetic() res = target_proj.transform_points(x=rotated_lons, y=rotated_lats, src_crs=src_proj) unrotated_lon = res[..., 0] unrotated_lat = res[..., 1] return unrotated_lon, unrotated_lat # Set rotated pole longitude and latitude, not ideal but easier than trying to find how to get iris to tell me what it is. plot_levels = [925, 850, 700, 500] #plot_levels = [925] experiment_id = 'djznw' p_levels = [1000, 950, 925, 850, 700, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10] expmin1 = experiment_id[:-1] plot_type='mean' # for pl in plot_diags: plot_diag='temp' fname_h = '/projects/cascade/pwille/temp/408_pressure_levels_interp_pressure_%s_%s' % (experiment_id, plot_type) fname_d = '/projects/cascade/pwille/temp/%s_pressure_levels_interp_%s_%s' % (plot_diag, experiment_id, plot_type) print fname_h print fname_d # Height data file with h5py.File(fname_h, 'r') as i: mh = i['%s' % plot_type] mean_heights = mh[. . .] print mean_heights.shape with h5py.File(fname_d, 'r') as i: mh = i['%s' % plot_type] mean_var = mh[. . .] print mean_var.shape #lon_low= 60 #lon_high = 105 #lat_low = -10 #lat_high = 30 f_oro = '/projects/cascade/pwille/moose_retrievals/%s/%s/33.pp' % (expmin1, experiment_id) oro = iris.load_cube(f_oro) print oro for i, coord in enumerate (oro.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_oro = i if coord.standard_name=='grid_longitude': lon_dim_coord_oro = i fu = '/projects/cascade/pwille/moose_retrievals/%s/%s/30201_mean.pp' % (expmin1, experiment_id) u_wind,v_wind = iris.load(fu) # Wind may have different number of grid points so need to do this twice lat_w = u_wind.coord('grid_latitude').points lon_w = u_wind.coord('grid_longitude').points p_levs = u_wind.coord('pressure').points lat = oro.coord('grid_latitude').points lon = oro.coord('grid_longitude').points cs_w = u_wind.coord_system('CoordSystem') cs = oro.coord_system('CoordSystem') if isinstance(cs_w, iris.coord_systems.RotatedGeogCS): print ' Wind - %s - Unrotate pole %s' % (experiment_id, cs_w) lons_w, lats_w = np.meshgrid(lon_w, lat_w) lons_w,lats_w = unrotate_pole(lons_w,lats_w, cs_w.grid_north_pole_longitude, cs_w.grid_north_pole_latitude) lon_w=lons_w[0] lat_w=lats_w[:,0] csur_w=cs_w.ellipsoid for i, coord in enumerate (u_wind.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_uwind = i if coord.standard_name=='grid_longitude': lon_dim_coord_uwind = i u_wind.remove_coord('grid_latitude') u_wind.remove_coord('grid_longitude') u_wind.add_dim_coord(iris.coords.DimCoord(points=lat_w, standard_name='grid_latitude', units='degrees', coord_system=csur_w),lat_dim_coord_uwind ) u_wind.add_dim_coord(iris.coords.DimCoord(points=lon_w, standard_name='grid_longitude', units='degrees', coord_system=csur_w), lon_dim_coord_uwind) v_wind.remove_coord('grid_latitude') v_wind.remove_coord('grid_longitude') v_wind.add_dim_coord(iris.coords.DimCoord(points=lat_w, standard_name='grid_latitude', units='degrees', coord_system=csur_w), lat_dim_coord_uwind) v_wind.add_dim_coord(iris.coords.DimCoord(points=lon_w, standard_name='grid_longitude', units='degrees', coord_system=csur_w),lon_dim_coord_uwind ) if isinstance(cs, iris.coord_systems.RotatedGeogCS): print ' 33.pp - %s - Unrotate pole %s' % (experiment_id, cs) lons, lats = np.meshgrid(lon, lat) lon_low= np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) lon_corners, lat_corners = np.meshgrid((lon_low, lon_high), (lat_low, lat_high)) lons,lats = unrotate_pole(lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) lon_corner_u,lat_corner_u = unrotate_pole(lon_corners, lat_corners, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) #lon_highu,lat_highu = unrotate_pole(lon_high, lat_high, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) lon=lons[0] lat=lats[:,0] lon_low = lon_corner_u[0,0] lon_high = lon_corner_u[0,1] lat_low = lat_corner_u[0,0] lat_high = lat_corner_u[1,0] for i, coord in enumerate (oro.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_oro = i if coord.standard_name=='grid_longitude': lon_dim_coord_oro = i csur=cs.ellipsoid oro.remove_coord('grid_latitude') oro.remove_coord('grid_longitude') oro.add_dim_coord(iris.coords.DimCoord(points=lat, standard_name='grid_latitude', units='degrees', coord_system=csur), lat_dim_coord_oro) oro.add_dim_coord(iris.coords.DimCoord(points=lon, standard_name='grid_longitude', units='degrees', coord_system=csur), lon_dim_coord_oro) else: lons, lats = np.meshgrid(lon, lat) lons_w, lats_w = np.meshgrid(lon_w, lat_w) lon_low= np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) ######## Regrid to global, and difference ####### ############################################################################ ## Heights f_glob_h = '/projects/cascade/pwille/temp/408_pressure_levels_interp_pressure_djznw_%s' % (plot_type) f_glob_d = '/projects/cascade/pwille/temp/%s_pressure_levels_interp_djznw_%s' % (plot_diag, plot_type) with h5py.File(f_glob_h, 'r') as i: mh = i['%s' % plot_type] mean_heights_global = mh[. . .] with h5py.File(f_glob_d, 'r') as i: mh = i['%s' % plot_type] mean_var_global = mh[. . .] # Wind fw_global = '/projects/cascade/pwille/moose_retrievals/djzn/djznw/30201_mean.pp' fo_global = '/projects/cascade/pwille/moose_retrievals/djzn/djznw/33.pp' u_global,v_global = iris.load(fw_global) oro_global = iris.load_cube(fo_global) # Unrotate global coordinates cs_glob = u_global.coord_system('CoordSystem') cs_glob_v = v_global.coord_system('CoordSystem') cs_glob_oro = oro_global.coord_system('CoordSystem') lat_g = u_global.coord('grid_latitude').points lon_g = u_global.coord('grid_longitude').points lat_g_oro = oro_global.coord('grid_latitude').points lon_g_oro = oro_global.coord('grid_longitude').points if cs_glob!=cs_glob_v: print 'Global model u and v winds have different poles of rotation' # Unrotate global winds if isinstance(cs_glob, iris.coord_systems.RotatedGeogCS): print ' Global Model - Winds - djznw - Unrotate pole %s' % cs_glob lons_g, lats_g = np.meshgrid(lon_g, lat_g) lons_g,lats_g = unrotate_pole(lons_g,lats_g, cs_glob.grid_north_pole_longitude, cs_glob.grid_north_pole_latitude) lon_g=lons_g[0] lat_g=lats_g[:,0] for i, coord in enumerate (u_global.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_uglobal = i if coord.standard_name=='grid_longitude': lon_dim_coord_uglobal = i csur_glob=cs_glob.ellipsoid u_global.remove_coord('grid_latitude') u_global.remove_coord('grid_longitude') u_global.add_dim_coord(iris.coords.DimCoord(points=lat_g, standard_name='grid_latitude', units='degrees', coord_system=csur_glob), lat_dim_coord_uglobal) u_global.add_dim_coord(iris.coords.DimCoord(points=lon_g, standard_name='grid_longitude', units='degrees', coord_system=csur_glob), lon_dim_coord_uglobal) #print u_global v_global.remove_coord('grid_latitude') v_global.remove_coord('grid_longitude') v_global.add_dim_coord(iris.coords.DimCoord(points=lat_g, standard_name='grid_latitude', units='degrees', coord_system=csur_glob), lat_dim_coord_uglobal) v_global.add_dim_coord(iris.coords.DimCoord(points=lon_g, standard_name='grid_longitude', units='degrees', coord_system=csur_glob), lon_dim_coord_uglobal) #print v_global # Unrotate global model if isinstance(cs_glob_oro, iris.coord_systems.RotatedGeogCS): print ' Global Model - Orography - djznw - Unrotate pole %s - Winds and other diagnostics may have different number of grid points' % cs_glob_oro lons_go, lats_go = np.meshgrid(lon_g_oro, lat_g_oro) lons_go,lats_go = unrotate_pole(lons_go,lats_go, cs_glob_oro.grid_north_pole_longitude, cs_glob_oro.grid_north_pole_latitude) lon_g_oro=lons_go[0] lat_g_oro=lats_go[:,0] for i, coord in enumerate (oro_global.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_og = i if coord.standard_name=='grid_longitude': lon_dim_coord_og = i csur_glob_oro=cs_glob_oro.ellipsoid oro_global.remove_coord('grid_latitude') oro_global.remove_coord('grid_longitude') oro_global.add_dim_coord(iris.coords.DimCoord(points=lat_g_oro, standard_name='grid_latitude', units='degrees', coord_system=csur_glob_oro), lat_dim_coord_og) oro_global.add_dim_coord(iris.coords.DimCoord(points=lon_g_oro, standard_name='grid_longitude', units='degrees', coord_system=csur_glob_oro), lon_dim_coord_og) ############## Regrid and Difference ################################# # Regrid Height and Temp/Specific humidity to global grid h_regrid = np.empty((len(lat_g_oro), len(lon_g_oro), len(p_levels))) v_regrid = np.empty((len(lat_g_oro), len(lon_g_oro), len(p_levels))) for y in range(len(p_levels)): h_regrid[:,:,y] = scipy.interpolate.griddata((lats.flatten(),lons.flatten()),mean_heights[:,:,y].flatten() , (lats_go,lons_go),method='cubic') v_regrid[:,:,y] = scipy.interpolate.griddata((lats.flatten(),lons.flatten()),mean_var[:,:,y].flatten() , (lats_go,lons_go),method='cubic') # Difference heights mean_heights = np.where(np.isnan(h_regrid), np.nan, h_regrid - mean_heights_global) #Difference temperature/specific humidity mean_var = np.where(np.isnan(v_regrid), np.nan, v_regrid - mean_var_global) # Difference winds u_wind_regrid = iris.analysis.interpolate.regrid(u_wind, u_global, mode='bilinear') v_wind_regrid = iris.analysis.interpolate.regrid(v_wind, v_global, mode='bilinear') u_wind=u_wind_regrid-u_global v_wind=v_wind_regrid-v_global ####################################################################################### # 2 degree lats lon lists for wind regridding on plot lat_wind_1deg = np.arange(lat_low,lat_high, 2) lon_wind_1deg = np.arange(lon_low,lon_high, 2) lons_w,lats_w = np.meshgrid(lon_wind_1deg, lat_wind_1deg) for p in plot_levels: m_title = 'Height of %s-hPa level (m)' % (p) # Set pressure height contour min/max if p == 925: clev_min = -24. clev_max = 24. elif p == 850: clev_min = -24. clev_max = 24. elif p == 700: clev_min = -24. clev_max = 24. elif p == 500: clev_min = -24. clev_max = 24. else: print 'Contour min/max not set for this pressure level' # Set potential temperature min/max if p == 925: clevpt_min = -3. clevpt_max = 3. elif p == 850: clevpt_min = -3. clevpt_max = 3. elif p == 700: clevpt_min = -3. clevpt_max = 3. elif p == 500: clevpt_min = -3. clevpt_max = 3. else: print 'Potential temperature min/max not set for this pressure level' # Set specific humidity min/max if p == 925: clevsh_min = -0.0025 clevsh_max = 0.0025 elif p == 850: clevsh_min = -0.0025 clevsh_max = 0.0025 elif p == 700: clevsh_min = -0.0025 clevsh_max = 0.0025 elif p == 500: clevsh_min = -0.0025 clevsh_max = 0.0025 else: print 'Specific humidity min/max not set for this pressure level' #clevs_col = np.arange(clev_min, clev_max) clevs_lin = np.linspace(clev_min, clev_max, num=24) s = np.searchsorted(p_levels[::-1], p) sc = np.searchsorted(p_levs, p) # Set plot contour lines for pressure levels plt_h = mean_heights[:,:,-(s+1)] #plt_h[plt_h==0] = np.nan # Set plot colours for variable plt_v = mean_var[:,:,-(s+1)] #plt_v[plt_v==0] = np.nan # Set u,v for winds, linear interpolate to approx. 1 degree grid u_interp = u_wind[sc,:,:] v_interp = v_wind[sc,:,:] sample_points = [('grid_latitude', lat_wind_1deg), ('grid_longitude', lon_wind_1deg)] u = iris.analysis.interpolate.linear(u_interp, sample_points).data v = iris.analysis.interpolate.linear(v_interp, sample_points).data lons_w, lats_w = np.meshgrid(lon_wind_1deg, lat_wind_1deg) m =\ Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high,projection='mill') #x, y = m(lons, lats) x, y = m(lons_go, lats_go) x_w, y_w = m(lons_w, lats_w) fig=plt.figure(figsize=(8,8)) ax = fig.add_axes([0.05,0.05,0.9,0.85]) m.drawcoastlines(color='gray') m.drawcountries(color='gray') m.drawcoastlines(linewidth=0.5) #m.fillcontinents(color='#CCFF99') #m.drawparallels(np.arange(-80,81,10),labels=[1,1,0,0]) #m.drawmeridians(np.arange(0,360,10),labels=[0,0,0,1]) cs_lin = m.contour(x,y, plt_h, clevs_lin,colors='k',linewidths=0.5) #cs_lin = m.contour(x,y, plt_h,colors='k',linewidths=0.5) #wind = m.barbs(x_w,y_w, u, v, length=6) if plot_diag=='temp': cs_col = m.contourf(x,y, plt_v, np.linspace(clevpt_min, clevpt_max), cmap=plt.cm.RdBu_r, colorbar_extend='both') #cs_col = m.contourf(x,y, plt_v, cmap=plt.cm.RdBu_r) cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%d') cbar.set_label('K') plt.suptitle('Difference from Global Model (Model - Global Model ) of Height, Potential Temperature and Wind Vectors at %s hPa'% (p), fontsize=10) elif plot_diag=='sp_hum': cs_col = m.contourf(x,y, plt_v, np.linspace(clevsh_min, clevsh_max), cmap=plt.cm.RdBu_r) cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%.3f') cbar.set_label('kg/kg') plt.suptitle('Difference from Global Model (Model - Global Model ) of Height, Specific Humidity and Wind Vectors at %s hPa'% (p), fontsize=10) wind = m.quiver(x_w,y_w, u, v, scale=150) qk = plt.quiverkey(wind, 0.1, 0.1, 5, '5 m/s', labelpos='W') plt.clabel(cs_lin, fontsize=10, fmt='%d', color='black') #plt.title('%s\n%s' % (m_title, model_name_convert_title.main(experiment_id)), fontsize=10) plt.title('\n'.join(wrap('%s' % (model_name_convert_title.main(experiment_id)), 80)), fontsize=10) #plt.show() if not os.path.exists('/home/pwille/figures/%s/%s' % (experiment_id, plot_diag)): os.makedirs('/home/pwille/figures/%s/%s' % (experiment_id, plot_diag)) plt.savefig('/home/pwille/figures/%s/%s/geop_height_difference_%shPa_%s_%s.tiff' % (experiment_id, plot_diag, p, experiment_id, plot_diag), format='tiff', transparent=True)
# meshgrid of lon lats lons, lats = np.meshgrid(lon, lat) # use projection template to create x and y axis x, y = m(lons, lats) # draw land outlines m.drawcoastlines(linewidth=0.05) m.fillcontinents(color='white') # filled contour plot contf_lvls = np.linspace(-0.5,0.5,21) # levels to show on colourbar contf = m.contourf(x, y, heat_fluxes_4000_avg, contf_lvls, cmap=cmap, extend='both') matplotlib.rcParams['contour.negative_linestyle'] = 'solid' #m.contour(x,y,bottom_temp,fcont_lvls,linewidths=0.25,colors='k') m.contour(x,y,heat_fluxes_4000_avg,(0,),linewidths=0.1,colors='k') # title ... title_name = 'Heat flux below 4000m from Pauls mom 0.25 IAF run: \n' \ '1998to2007 - 1988to1997 (inspired from Purkey and Johnson 2010 fig 8)' ax.set_title(title_name) def round_to_base(x, base=5): return int(base * round(float(x) / base)) # meridians. last input is meridians tick label meridians = map(round_to_base, np.arange(-210, 170, 30)) m.drawmeridians(meridians, linewidth=0.2, labels=[0,0,0,1]) # parallels. last input is paralles tick label parallels = map(round_to_base, np.arange(-80, 100, 20)) m.drawparallels(parallels, linewidth=0.2, labels=[1,0,0,0])
resolution='l') # Get U,V components from wind speed and direction u,v = metpy.get_wind_components(speed, wdir) # Rotate the vectors to be properly aligned in the map projection u,v = bm.rotate_vector(u, v, lon, lat) # Generate grid of x,y positions lon_grid, lat_grid, x_grid, y_grid = bm.makegrid(130, 60, returnxy=True) # Transform the obs to basemap space for gridding obx,oby = bm(lon, lat) # Perform analysis of height obs using Cressman weights heights_oban = grid_data(height, x_grid, y_grid, obx, oby, obans[which_oban][0], obans[which_oban][1]) heights_oban = maskoceans(lon_grid, lat_grid, heights_oban) # Map plotting contours = np.arange(5000., 5800., 60.0) bm.drawstates() bm.drawcountries() bm.drawcoastlines() cp = bm.contour(x_grid, y_grid, heights_oban, contours) bm.barbs(obx, oby, u, v) plt.clabel(cp, fmt='%.0f', inline_spacing=0) plt.title('500mb Height map') plt.show()
#define basemap; draw appropriate lines m = Basemap(boundinglat = 25,lon_0 = 260,resolution = "l",projection = "npstere", ax = ax) m.drawparallels(np.arange(-80.,81.,10.), labels = [1,0,0,0], fontsize = 12) m.drawmeridians(np.arange(0.,359.,20.), labels = [0,0,0,1], fontsize = 12) m.drawcoastlines() m.drawstates() m.drawcountries() #convert lat/lon data to plot coordinates xi, yi = m(lon,lat) #plot 500 mb geopotential height data #include colorbar zlevs = np.arange(486, 601, 6) z500 = m.contourf(xi, yi, z, zlevs, cmap = 'rainbow') cbar = plt.colorbar(z500, orientation = 'vertical', pad = 0.05, shrink = 0.7, ax = ax, ticks = zlevs) cbar.set_label('500 mb geopotential height (dam)',fontsize = 14) cbar.ax.tick_params(labelsize = 12) #plot MSLP data; label contour lines clevs = np.arange(960, 1040, 4) cmslp = m.contour(xi, yi, mslp, clevs, colors= 'k') clab = plt.clabel(cmslp, inline = True, fontsize = 12, fmt='%1.0f') #add figure title ax.set_title("500 mb geopotential height (dam) and MSLP (mb) on 2015-11-08 at 12Z",fontsize=14) #save figure; close plot plt.savefig('parsotak_wx272_lab6.png') plt.show()
GRACE_xcorr = np.full((59, 361), fill_value=np.NaN) GRACE_xcorr_pvalues = np.full((59, 361), fill_value=np.NaN) for ilat in range(len(lat)): for ilon in range(len(lon)): if np.sum(np.isfinite(GRACE[:, ilat, ilon])) > len(GRACE[:, ilat, ilon]) // 2: ts_1 = GRACE[:, ilat, ilon] xcorr = stats.pearsonr(ts_1, sam_index) GRACE_xcorr[ilat, ilon] = xcorr[0] GRACE_xcorr_pvalues[ilat, ilon] = xcorr[1] #GRACE_xcorr[57, 300] = 1000 pl.figure() pl.clf() m = Basemap(projection='spstere', boundinglat=-50, lon_0=180, resolution='l') m.drawmapboundary() m.drawcoastlines(zorder=10) m.fillcontinents(zorder=10) m.drawparallels(np.arange(-80., 81., 20.), labels=[1, 0, 0, 0]) m.drawmeridians(np.arange(-180., 181., 20.), labels=[0, 0, 0, 1]) grid_lats, grid_lons = np.meshgrid(lat, lon) stereo_x, stereo_y = m(grid_lons, grid_lats) m.pcolor(stereo_x, stereo_y, np.transpose(np.ma.masked_invalid(GRACE_xcorr)), cmap='RdBu_r') m.colorbar() pl.clim(1, -1) m.contour(stereo_x, stereo_y, np.transpose(np.ma.masked_invalid(GRACE_xcorr_pvalues)), [0.2], color='k') pl.savefig('/Users/jmh2g09/Documents/PhD/Data/GRACE/Validation/GRACE_SAM_corr.png', transparent=True, dpi=300, bbox_inches='tight') pl.close()
linewidth=0.25) map.fillcontinents('lightgrey') x, y = map(lon, lat) CF = map.contourf(x, y, data, variables[var]['clev'], cmap=cmap, norm=colors.BoundaryNorm(variables[var]['clev'], cmap.N), extend='both') CF.cmap.set_under('black') CF.cmap.set_over('black') CS = map.contour(x, y, data, CF.levels, colors='k', linewidths=0.25) CB = fig.colorbar(CF, ax=ax, drawedges=True, shrink=0.5, aspect=12, ticks=variables[var]['clev'][1:-1], format='%G') CB.set_label(variables[var]['units']) for line in CB.ax.get_yticklines(): # remove tick lines line.set_markersize(0) bottom_labels(ax, case.replace('_', ' '),
pvarn,lons_cyclic = shiftgrid(180.,pvarn,lons_cyclic,start=False) climoq,lons_cyclic = addcyclic(climossub, lon) climoq,lons_cyclic = shiftgrid(180.,climoq,lons_cyclic,start=False) circle = m.drawmapboundary(fill_color='white', color='dimgrey',linewidth=0.7) circle.set_clip_on(False) if varnamesq[i] == 'RNET': varn = varn * -1. # change sign for upward fluxes as positive ### Plot contours cs = m.contourf(x,y,varn,limit,extend='both') cs1 = m.contourf(x,y,pvarn,colors='None',hatches=['.....']) if varnames[v] == 'Z50': # the interval is 250 m cs2 = m.contour(x,y,climoq,np.arange(21900,23500,250), colors='k',linewidths=1.1,zorder=10) ### Set map geography if varnamesq[i] == 'RNET': m.drawcoastlines(color='darkgrey',linewidth=0.15) m.fillcontinents(color='dimgrey') else: m.drawcoastlines(color='dimgrey',linewidth=0.5) ### Set colormap cs.set_cmap(cmocean.cm.balance) if i < len(varnames): ax1.annotate(r'\textbf{%s}' % varnamesq[i], xy=(0, 0),xytext=(0.5,1.13),xycoords='axes fraction', fontsize=13,color='k',rotation=0,
resolution='l',area_thresh=1000.,projection='lcc',\ lat_1=50.,lon_0=-107.,ax=ax1) # draw countries, states, and differentiate land from water areas. m.drawcoastlines(linewidth=2, color='#444444', zorder=6) m.drawcountries(linewidth=1, color='#444444', zorder=5) m.drawstates(linewidth=0.66, color='#444444', zorder=4) m.drawmapboundary # draw lat/lon grid lines every 30 degrees. m.drawmeridians(np.arange(0, 360, 30)) m.drawparallels(np.arange(-90, 90, 30)) x, y = m(X, Y) CS = m.contourf(x,y,zeta_a1,cmap=plt.cm.hot_r,levels=cflevs, extend='both',zorder=1) cbar = plt.colorbar(CS, shrink=0.95, orientation='horizontal',extend='both') CS2 = m.contour(x, y, zeta_a1, cflevs, colors='k', linewidths=0.5) if plot_barbs == "true": # Rotate and interpolate wind from lat/lon grid to map projection grid. uproj1,vproj1, xx1, yy1 = m.transform_vector(ugrid1,vgrid1,newlons,lats,41,41,returnxy=True) barbs = m.barbs(xx1,yy1,uproj1,vproj1,length=5,barbcolor='k',flagcolor='r',linewidth=1.0) cbar.set_ticks(cflevs_ticks) clabs = ['%i K' % f for f in cflevs_ticks] cbar.ax.set_yticklabels(clabs, size=10) ax1.set_title(titletext1) save_name = figname + "_01.png" plt.savefig(save_name, bbox_inches='tight')
def make_plot(data, title, cbartitle, lon, lat, mymin, mymax, myticks, ncolors, ncontours, mycolormap, timestamp, savename, ufield=None, vfield=None): fontfam = 'serif' plt.figure() # basemap m = Basemap(llcrnrlon=lon[0], llcrnrlat=lat[0], urcrnrlon=lon[-1], urcrnrlat=lat[-1], projection='cyl') lon, lat = np.meshgrid(lon, lat) x, y = m(lon, lat) m.drawcoastlines() m.drawstates() m.drawcountries() # contouring cmap = m.contourf(x, y, data, np.linspace(mymin, mymax, ncolors), cmap=mycolormap) m.contour(x, y, data, np.linspace(mymin, mymax, ncontours), colors='black', linewidths=1) # colorbar cbar = m.colorbar(cmap, ticks=np.linspace( mymin, mymax, myticks)) #, format=ticker.FuncFormatter(fmt)) cbar.ax.yaxis.label.set_font_properties( matplotlib.font_manager.FontProperties(family=fontfam, size=16)) cbar.ax.set_title(cbartitle, y=1.04) # neutral wind vectors if supplied if ufield is not None and vfield is not None: speed = np.sqrt(ufield * ufield + vfield * vfield) m.quiver(x, y, ufield, vfield, speed, latlon=True) # standard labeling #plt.xlabel('Geographic Longitude ($^o$E)', fontsize=18, fontname=fontfam) #plt.ylabel('Geographic Latitude ($^o$N)', fontsize=18, fontname=fontfam) plt.xticks([0, 90, 180, 270, 360], ['$0^o E$', '$90^o E$', '$180^o E$', '$270^o E$', '$360^o E$']) plt.yticks([-90, -45, 0, 45, 90], ['$90^o S$', '$45^o S$', '$0^o$', '$45^o N$', '$90^o N$']) plt.grid() plt.title(title + '\n' + timestamp, fontsize=20, fontname=fontfam) # output plt.savefig( path.join(args.output_directory, savename + '.' + timestamp + '.eps')) plt.close()
m.drawlsmask(land_color='darkgrey', ocean_color='mintcream') # Make the plot continuous barlim = np.arange(-3, 4, 1) values = np.arange(-3, 3.1, 0.25) var1, lons_cyclic = addcyclic(var1, lons) var1, lons_cyclic = shiftgrid(180., var1, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lats) x, y = m(lon2d, lat2d) cs = m.contourf(x, y, var1, values, extend='both') cs1 = m.contour(x, y, var1, values, linewidths=0.2, colors='darkgrey', linestyles='-') cmap = ncm.cmap('nrl_sirkes') cs.set_cmap(cmap) ax.annotate(r'\textbf{EOF1}', xy=(0, 0), xytext=(0.35, 1.05), textcoords='axes fraction', fontsize=20, color='darkgrey') ###########################################################################
def __init__(self, in_file, vg_files = [1], data_type = 1, projection = 'cyl', color_map = 'jet', time_zone = 0, plot_contours = False, plot_center = 't', plot_meridians = True, plot_parallels = True, plot_terminator = True, resolution = 'c', points_of_interest = [], save_file = '', run_quietly = False, dpi = 150, parent = None): self.run_quietly = run_quietly self.dpi=float(dpi) plot_parameters = VOAFile((in_file+'.voa')) plot_parameters.parse_file() if (plot_parameters.get_projection() != 'cyl'): print _("Error: Only lat/lon (type 1) input files are supported") sys.exit(1) grid = plot_parameters.get_gridsize() self.image_defs = VOAAreaPlot.IMG_TYPE_DICT[int(data_type)] # TODO This needs a little more work... what if the pcenter card is not specified if plot_center == 'p': plot_centre_location = plot_parameters.get_location(plot_parameters.P_CENTRE) else: plot_centre_location = plot_parameters.get_location(plot_parameters.TX_SITE) self.points_of_interest = [plot_centre_location] if len(points_of_interest) > 0: self.points_of_interest.extend(points_of_interest) imageBuf = P.zeros([grid, grid], float) area_rect = plot_parameters.get_area_rect() points = P.zeros([grid,grid], float) lons = P.zeros(grid*grid, float) lats = P.zeros(grid*grid, float) lons = P.arange(area_rect.get_sw_lon(), area_rect.get_ne_lon()+0.001,(area_rect.get_ne_lon()-area_rect.get_sw_lon())/float(grid-1)) lats = P.arange(area_rect.get_sw_lat(), area_rect.get_ne_lat()+0.001,(area_rect.get_ne_lat()-area_rect.get_sw_lat())/float(grid-1)) colString = 'P.cm.'+color_map colMap = eval(colString) self.subplots = [] matplotlib.rcParams['axes.edgecolor'] = 'gray' matplotlib.rcParams['axes.facecolor'] = 'white' matplotlib.rcParams['figure.facecolor'] = 'white' #matplotlib.rcParams['figure.figsize'] = (6, 10) # matplotlib.rcParams['figure.subplot.hspace'] = 0.45 # matplotlib.rcParams['figure.subplot.wspace'] = 0.35 # matplotlib.rcParams['figure.subplot.right'] = 0.85 colorbar_fontsize = 8 self.num_rows = 1 self.main_title_fontsize = 18 matplotlib.rcParams['legend.fontsize'] = 12 matplotlib.rcParams['axes.labelsize'] = 10 matplotlib.rcParams['axes.titlesize'] = 10 matplotlib.rcParams['xtick.labelsize'] = 8 matplotlib.rcParams['ytick.labelsize'] = 8 # matplotlib.rcParams['figure.subplot.top'] = 0.8 # single figure plots have a larger title so require more space at the top. self.fig=Figure(figsize=(9,5)) # self.main_title_label = self.fig.suptitle(unicode(self.image_defs['title'],'utf-8'), fontsize=self.main_title_fontsize) ax = self.fig.add_subplot(111,axisbg = 'white') self.subplots.append(ax) ax.label_outer() #print "opening: ",(in_file+'.vg'+str(vg_files[plot_ctr])) plot_ctr = 0 # dir_name = os.path.dirname(in_file) # if not os.path.exists(dir_name): # os.makedirs(dir_name) vgFile = open(in_file+'.vg'+str(vg_files[plot_ctr])) pattern = re.compile(r"[a-z]+") for line in vgFile: match = pattern.search( line ) if not match: value = float(line[int(self.image_defs['first_char']):int(self.image_defs['last_char'])]) # TODO Does this need to be normalised here if it's also being done in the plot? value = max(self.image_defs['min'], value) value = min(self.image_defs['max'], value) #if value < self.image_defs[2] : value = self.image_defs[2] #if value > self.image_defs[3] : value = self.image_defs[3] points[int(line[3:6])-1][int(line[0:3])-1] = value vgFile.close() map = Basemap(\ llcrnrlon=area_rect.get_sw_lon(), llcrnrlat=area_rect.get_sw_lat(),\ urcrnrlon=area_rect.get_ne_lon(), urcrnrlat=area_rect.get_ne_lat(),\ projection=projection,\ lat_0=plot_centre_location.get_latitude(),\ lon_0=plot_centre_location.get_longitude(),\ resolution=resolution, ax=ax) map.drawcoastlines(color='black') map.drawcountries(color='grey') map.drawmapboundary(color='black', linewidth=1.0) warped = ma.zeros((grid, grid),float) warped, warped_lon, warped_lat = map.transform_scalar(points,lons,lats,grid,grid, returnxy=True, checkbounds=False, masked=True) warped = warped.filled(self.image_defs['min']-1.0) colMap.set_under(color ='k', alpha=0.0) im = map.imshow(warped, cmap=colMap, extent = (-180, 180, -90, 90), origin = 'lower', norm = P.Normalize(clip = False, vmin=self.image_defs['min'], vmax=self.image_defs['max'])) ####################### # Plot greyline ####################### if plot_terminator: the_sun = Sun() the_month = plot_parameters.get_month(vg_files[plot_ctr]-1) the_day = plot_parameters.get_day(vg_files[plot_ctr]-1) the_hour = plot_parameters.get_utc(vg_files[plot_ctr]-1) if (the_day == 0): the_day = 15 the_year = datetime.date.today().year num_days_since_2k = the_sun.daysSince2000Jan0(the_year, the_month, the_day) res = the_sun.sunRADec(num_days_since_2k) declination = res[1] if(declination==0.0): declination=-0.001 tau = the_sun.computeGHA(the_day, the_month, the_year, the_hour); if declination > 0: terminator_end_lat = area_rect.get_sw_lat() else: terminator_end_lat = area_rect.get_ne_lat() terminator_lat = [terminator_end_lat] terminator_lon = [area_rect.get_sw_lon()] for i in range(int(area_rect.get_sw_lon()),int(area_rect.get_ne_lon()),1)+[int(area_rect.get_ne_lon())]: longitude=i+tau; tan_lat = - the_sun.cosd(longitude) / the_sun.tand(declination) latitude = the_sun.atand(tan_lat) latitude = max(latitude, area_rect.get_sw_lat()) latitude = min(latitude, area_rect.get_ne_lat()) xpt, ypt = map(i, latitude) terminator_lon.append(xpt) terminator_lat.append(ypt) terminator_lon.append(area_rect.get_ne_lon()) terminator_lat.append(terminator_end_lat) #This is a little simplistic and doesn't work for ortho plots.... ax.plot(terminator_lon, terminator_lat, color='grey', alpha=0.75) ax.fill(terminator_lon, terminator_lat, facecolor='grey', alpha = 0.5) tau = -tau if (tau > 180.0): tau = tau-360.0 if (tau < -180.0): tau = tau+360.0 #Plot the position of the sun (if it's in the coverage area) if area_rect.contains(declination, tau): xpt,ypt = map(tau,declination) #sbplt_ax.plot([xpt],[ypt],'yh') ax.plot([xpt],[ypt],'yh') ########################## # Points of interest ########################## for location in self.points_of_interest: if area_rect.contains(location.get_latitude(), location.get_longitude()): xpt,ypt = map(location.get_longitude(),location.get_latitude()) ax.plot([xpt],[ypt],'ro') ax.text(xpt+100000,ypt+100000,location.get_name()) if plot_meridians: if (area_rect.get_lon_delta() <= 90.0): meridians = P.arange(-180, 190.0, 10.0) elif (area_rect.get_lon_delta() <= 180.0): meridians = P.arange(-180.0, 210.0, 30.0) else: meridians = P.arange(-180, 240.0, 60.0) if ((projection == 'ortho') or (projection == 'vandg')): map.drawmeridians(meridians) else: map.drawmeridians(meridians,labels=[1,1,0,1]) if plot_parallels: if (area_rect.get_lat_delta() <= 90.0): parallels = P.arange(-90.0, 120.0, 60.0) else: parallels = P.arange(-90.0, 120.0, 30.0) if ((projection == 'ortho') or (projection == 'vandg')): map.drawparallels(parallels) else: map.drawparallels(parallels,labels=[1,0,0,1]) if plot_contours: map.contour(warped_lon, warped_lat, warped, self.image_defs['y_labels'], linewidths=1.0, colors='k', alpha=0.5) #add a title title_str = plot_parameters.get_plot_description_string(vg_files[plot_ctr]-1, self.image_defs['plot_type'], time_zone) title_str = title_str + "\n" + plot_parameters.get_detailed_plot_description_string(vg_files[plot_ctr]-1) self.subplot_title_label = ax.set_title(title_str) # Add a colorbar on the right hand side, aligned with the # top of the uppermost plot and the bottom of the lowest # plot. pos = [0.91,0.19,0.02,0.62] self.cb_ax = self.fig.add_axes(pos) cb = self.fig.colorbar(im, cax=self.cb_ax, orientation='vertical', ticks=self.image_defs['y_labels'], format = P.FuncFormatter(eval('self.'+self.image_defs['formatter']))) cb.set_label(unicode(self.image_defs['title'],'utf-8')) #print self.image_defs['y_labels'] for t in self.cb_ax.get_yticklabels(): t.set_fontsize(colorbar_fontsize) canvas = FigureCanvasAgg(self.fig) if save_file : self.save_plot(canvas, save_file)
def main_mapping_tool(self, mode, path, time_list, nx, ny, *, gpv_datalist='None', snap_step=0, level='1000'): fig, ax = plt.subplots() outpath = path + '/fig/' lat_min, lat_max = 17, 50 lon_min, lon_max = 120, 155 mapping = Basemap( projection='lcc', resolution="i", lat_0=35, lon_0=140, fix_aspect=(1,1), llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max ) mapping.drawcoastlines(color='black', linewidth=0.5) mapping.drawmeridians(np.arange(0, 360, 5), labels=[False, True, False, True], fontsize='small', color='gray', linewidth=0.5) mapping.drawparallels(np.arange(-90, 90, 5), labels=[True, False, False, True], fontsize='small', color='gray', linewidth=0.5) lon_list, lat_list = self.prj_coef(nx, ny) x, y = mapping(lon_list, lat_list) if mode == 1 or mode == 2: if level == "1000": hPa, min_list = 0, [0, 200] elif level == "925": hPa, min_list = 1, [0, 600] elif level == "850": hPa, min_list = 2, [0, 750] elif level == "700": hPa, min_list = 3, [0, 1500] elif level == "600": hPa, min_list = 4, "None" elif level == "500": hPa, min_list = 5, "None" elif level == "400": hPa, min_list = 6, "None" elif level == "300": hPa, min_list = 7, "None" elif level == "250": hPa, min_list = 8, "None" elif level == "200": hPa, min_list = 9, "None" elif level == "150": hPa, min_list = 10, "None" elif level == "100": hPa, min_list = 11, "None" gpv_u_data = gpv_datalist[snap_step][0][hPa] gpv_v_data = gpv_datalist[snap_step][1][hPa] speed = np.sqrt(gpv_u_data*gpv_u_data + gpv_v_data*gpv_v_data) speed_list = list(range(0, 50, 25)) gpv_height_data = gpv_datalist[snap_step][4][hPa] num_list = list(range(0, 7500, 10)) contour = mapping.contour(x, y, gpv_height_data, linewidths=0.25, linestyles='-', levels=num_list, colors='m') contour.clabel(fmt='%1.1f', fontsize=6.5) if not min_list == "None": lines = mapping.contourf(x, y, gpv_height_data, min_list, alpha=0.5, hatches=['///'], lw=1., zorder=0, edgecolor='r', colors="y") for i_nx, i_ny in itertools.product(range(nx), range(ny)): if speed[i_ny][i_nx] > 10 and lon_min <= lon_list[i_ny][i_nx] <= lon_max and lat_min <= lat_list[i_ny][i_nx] <= lat_max: print('...... Halfway step, ', i_nx, i_ny, speed[i_ny][i_nx]) vector = mapping.quiver(x[i_ny][i_nx], y[i_ny][i_nx], gpv_u_data[i_ny][i_nx], gpv_v_data[i_ny][i_nx], color='c', units='dots', scale=2.0, alpha=0.6) plt.title(time_list[snap_step] + ' @GSM ' + level + 'hPa' , loc='left', fontsize=10) plt.quiverkey(vector, 0.75, 0.9, 10, '10 m/s', labelpos='W', coordinates='figure') plt.savefig(outpath + 'GPV_elem_' + time_list[snap_step] + '.png') print('...... Saving fig :: ', outpath + 'GPV_elem_' + time_list[snap_step] + '.png')
# meshgrid of lon lats lons, lats = np.meshgrid(lon, lat) # use projection template to create x and y axis x, y = m(lons, lats) # draw land outlines m.drawcoastlines(linewidth=0.05) m.fillcontinents(color='white') # filled contour plot contf_lvls = np.linspace(-0.25,0.25,21) # levels to show on colourbar contf = m.contourf(x, y, bottom_temp, contf_lvls, cmap=cmap, extend='both') matplotlib.rcParams['contour.negative_linestyle'] = 'solid' #m.contour(x,y,bottom_temp,fcont_lvls,linewidths=0.25,colors='k') m.contour(x,y,bottom_temp,(0,),linewidths=0.2,colors='k') # title ... title_name = 'Bottom shelf temperature bias from Pauls mom 0.25 CORE IAF exp.\n' \ ' loop 5 of 1948 to 2007: 1998to2007 - 1958to1967' ax.set_title(title_name) # meridians. last input is meridians tick label meridians = map(round_to_base, np.arange(-210, 170, 30)) m.drawmeridians(meridians, linewidth=0.2) # parallels. last input is paralles tick label parallels = map(round_to_base, np.arange(-80, 100, 20)) m.drawparallels(parallels, linewidth=0.2, labels=[1,0,0,0]) # add a colourbar cbar_pos = [bnd[0]+bnd[2]-0.015, bnd[1], \
## ---- Plot Anomaly ---- ## fig, ax = plt.subplots(nrows=1, ncols=1) m = Basemap(ax=ax, projection='merc', lon_0=lon_0, lat_0=lat_0, llcrnrlon=lonLims[0], llcrnrlat=latLims[0], urcrnrlon=lonLims[1], urcrnrlat=latLims[1], resolution='i') #levels = np.linspace(-1, 1, 6) levels = np.array([-1, -.8, -.6, -.4, -.2, .2, .4, .6, .8, 1]) xi, yi = m(*np.meshgrid(lon_reg, lat_reg)) c = m.contourf(xi, yi, anom, levels, cmap=plt.cm.RdBu_r, extend='both') cc = m.contour(xi, yi, -Zitp, [100, 500, 1000, 4000], colors='grey') plt.clabel(cc, inline=1, fontsize=10, fmt='%d') if season == 'fall': plt.title('Fall Bottom Salinity ' + year + ' Anomaly') elif season == 'spring': plt.title('Spring Bottom Salinity ' + year + ' Anomaly') else: plt.title('Bottom Salinity ' + year + ' Anomaly') m.fillcontinents(color='tan') m.drawparallels([40, 45, 50, 55, 60], labels=[0, 0, 0, 0], fontsize=12, fontweight='normal') m.drawmeridians([-60, -55, -50, -45], labels=[0, 0, 0, 1], fontsize=12,
for ii in range(nx)[1:nx - 1]: for jj in range(ny)[1:ny - 1]: T_adv[:,jj,ii]=-(10**5)*(u[:,0,jj,ii]*(t[:,0,jj,ii+1]-t[:,0,jj,ii-1])/\ (rr*np.cos(latitude[jj]/180.0*3.1415926)*(longitude[ii+1]-longitude[ii-1]))\ +v[:,0,jj,ii]*(t[:,0,jj+1,ii]-t[:,0,jj-1,ii])/(rr*(latitude[jj+1]-latitude[jj-1]))) #mask_ind=np.where(T_adv<=0) #T_adv[mask_ind]=0 m = Basemap(projection='mill',llcrnrlat=15,urcrnrlat=35,\ llcrnrlon=100,urcrnrlon=130,lat_ts=25,resolution='l') lons, lats = np.meshgrid(longitude, latitude) x, y = m(lons, lats) for ii in range(ntimes): cs = m.contour(x, y, hgt[ii, 0, :, :], colors='b', linewidths=1.5) cs1 = m.contour(x, y, t[ii, 0, :, :], colors='r', linestyle='dash', linewidths=1.5) clevs = [-70, -30, -20, -10, 0, 10, 20, 30, 70] cs2 = m.contourf(x, y, T_adv[ii, :, :], clevs, cmap=plt.cm.RdBu_r) #plt.cm.OrRd) cb = m.colorbar(cs2, "right", size="5%", pad='2%') cb.set_label('Thermal advection: $10^{-5}$') plt.clabel(cs, fontsize=10, fmt='%1d') plt.clabel(cs1, fontsize=10, fmt='%1d') ugrid, newlons = shiftgrid(180., u, longitude, start=False) vgrid, newlons = shiftgrid(180., v, longitude, start=False)
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='dimgrey',linewidth=0.7) cs = m.contourf(x,y,var,limit,extend='both') cs1 = m.contourf(x,y,pvar,colors='None',hatches=['....']) if varnamesn[v] == 'Z30': climoq,lons_cyclic = addcyclic(climos, lon) climoq,lons_cyclic = shiftgrid(180.,climoq,lons_cyclic,start=False) cs2 = m.contour(x,y,climoq,np.arange(21900,23500,250), colors='k',linewidths=1.2,zorder=10) elif varnamesn[v] == 'Wave 1': # the interval is 250 m lon2c, lat2c = np.meshgrid(lonc,latc) m.drawmapboundary(fill_color='white',color='dimgrey',linewidth=0.7) cs = m.contourf(lon2c,lat2c,var,limit,extend='both',latlon=True) cs1 = m.contourf(lon2c,lat2c,pvar,colors='None',hatches=['....'],latlon=True) cs2 = m.contour(lon2c,lat2c,climos,np.arange(-200,201,50),colors='k', linewidths=1.2,zorder=10,latlon=True) m.drawcoastlines(color='dimgrey',linewidth=0.6) if varnamesn[v] == 'U300': cmap = cmocean.cm.balance cs.set_cmap(cmap)
xc,yc = bmap(lons,lats) # plot filled circles at the locations of the cities. bmap.plot(xc,yc,'bo') # plot the names of those five cities. for name,xpt,ypt in zip(cities,xc,yc): plt.text(xpt+50000,ypt+50000,name,fontsize=9) # make up some data on a regular lat/lon grid. nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]) wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons)) mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.) # compute native map projection coordinates of lat/lon grid. x, y = bmap(lons*180./np.pi, lats*180./np.pi) # contour data over the map. cs = bmap.contour(x,y,wave+mean,15,linewidths=1.5) plt.title('filled continent background') # as above, but use land-sea mask image as map background. fig = plt.figure() bmap.drawmapboundary() bmap.drawmeridians(np.arange(0,360,30)) bmap.drawparallels(np.arange(-90,90,30)) # plot filled circles at the locations of the cities. bmap.plot(xc,yc,'wo') # plot the names of five cities. for name,xpt,ypt in zip(cities,xc,yc): plt.text(xpt+50000,ypt+50000,name,fontsize=9,color='w') # contour data over the map. cs = bmap.contour(x,y,wave+mean,15,linewidths=1.5) plt.title('land-sea mask background')
lat_ts=71, # latitude of true scale lon_0=-41, # longitude of the plotting domain center lat_0=72) # latitude of the plotting domain center # m.drawcoastlines() # draw the Blue Marble background (requires PIL, the Python Imaging Library) if bluemarble: # seems to reverse N and S m.bluemarble() # convert longitudes and latitudes to x and y: xx, yy = m(lon, lat) if contour100: # mark 100 m/a contour in black: m.contour(xx, yy, myvar, [100], colors="black") # plot log color scale or not if logscale: m.pcolormesh(xx, yy, myvar, norm=colors.LogNorm(vmin=myvmin, vmax=myvmax)) else: m.pcolormesh(xx, yy, myvar, vmin=myvmin, vmax=myvmax) # add a colorbar: plt.colorbar(extend='both', ticks=ticklist, format="%d") # draw parallels and meridians # labels kwarg is where to draw ticks: [left, right, top, bottom] m.drawparallels(np.arange(-55., 90., 5.), labels=[1, 0, 0, 0]) m.drawmeridians(np.arange(-120., 30., 10.), labels=[0, 0, 0, 1])
lon, lat, data = fix_pop_grid(tlon,tlat,vars()[var]) map = Basemap(llcrnrlon=-330,urcrnrlon=30,llcrnrlat=-85, urcrnrlat=85,resolution='l',projection='cyl',ax=ax) map.drawcoastlines(linewidth=0.5) map.drawrivers(linewidth=0.75,color='white') map.drawparallels(N.arange(-90,120,30) ,labels=[0,0,0,0],linewidth=0.25) map.drawmeridians(N.arange(-720,750,30),labels=[0,0,0,0],linewidth=0.25) map.fillcontinents('white') x,y = map(lon,lat) if var in vintlist: # vertically integrated CF = map.contourf(x,y,data,variables[var]['cklev'],cmap=cmap, norm=colors.BoundaryNorm(variables[var]['cklev'],cmap.N),extend='both') CF.cmap.set_under('black') CF.cmap.set_over('black') CS = map.contour(x,y,data,CF.levels,colors = 'k',linewidths = 0.25) CB = fig.colorbar(CF,ax=ax,drawedges=True,shrink=0.5,aspect=12, ticks=variables[var]['cklev'][1:-1],format='%G') CB.set_label(variables[var]['kunits']) else: CF = map.contourf(x,y,data,variables[var]['clev'],cmap=cmap, norm=colors.BoundaryNorm(variables[var]['clev'],cmap.N),extend='both') CF.cmap.set_under('black') CF.cmap.set_over('black') CS = map.contour(x,y,data,CF.levels,colors = 'k',linewidths = 0.25) CB = fig.colorbar(CF,ax=ax,drawedges=True,shrink=0.5,aspect=12, ticks=variables[var]['clev'][1:-1],format='%G') CB.set_label(variables[var]['units']) for line in CB.ax.get_yticklines(): # remove tick lines line.set_markersize(0)
top_right_lat = domain['top_right_lat'] + .1 top_right_lon = domain['top_right_lon'] - .1 bot_left_lat = domain['bot_left_lat'] bot_left_lon = domain['bot_left_lon'] ## Map in cylindrical projection (data points may apear skewed because WRF runs in LCC projection) m = Basemap(resolution='i',area_thresh=10000.,projection='cyl',\ llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\ urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,) m.drawstates() spat = 'auxhist23_d02_2015-06-17_00:00:00' directory = '/uufs/chpc.utah.edu/common/home/horel-group4/model/bblaylock/WRF3.7_urbanforest/DATA/more_trees/' nc_spatial = netcdf.netcdf_file(directory + spat, 'r') landmask = nc_spatial.variables['LANDMASK'][0, :, :] m.contour(XLON, XLAT, landmask, [0, 1], linewidths=1.5, colors="b") m.drawgreatcircle(LON[0], LAT[0], LON[-1], LAT[-1], color='k', linewidth='4') m.contourf(XLON, XLAT, XHGT, levels=np.arange(1000, 4000, 500), cmap=plt.get_cmap('binary')) # add location of tracers tracerS = ncW.variables['S_SLV'][0][0] tracerN = ncW.variables['N_SLV'][0][0] latP = ncW.variables['XLAT'][0] lonP = ncW.variables['XLONG'][0] x, y = m(lonP, latP) plt.pcolormesh(x, y, tracerS, cmap=cmapblue) plt.pcolormesh(x, y, tracerN, cmap=cmapred)
#Adicione a linha de costa. m.drawcoastlines(linewidth=1) # Adicione os continentes. m.fillcontinents(color='#000000') # Adicione os paralelos e meridianos . m.drawparallels(np.arange(-90.,120.,10.), linewidth=0.1, dashes = [1,5], color='black', labels=[1,0,0,1],labelstyle="+/-") m.drawmeridians(np.arange(-180.,180.,10.), linewidth=0.1,dashes = [1,5], color='black', labels=[1,0,0,1],labelstyle="+/-") # Adicione países m.drawcountries(color = '#ffffff') # Adicione uma escala ao mapa. m.drawmapscale(-25,-50,lon.min(),lat.max(),1500, barstyle='fancy', units='km', labelstyle='simple',fillcolor1='w'); # Defina para plotar uma variável. kw = dict(levels=range(-5,5,1),cmap=cm.balance,latlon=True) lon,lat = np.meshgrid(lat, lat) Cf = m.contourf(lon,lat,stab,**kw); cbar = plt.colorbar(Cf); cbar.ax.set_ylabel(ylabel) #precisamos acessar o objeto ax dentro de cbar Cb = m.contour(stab,20,linewidths=2.0, colors='darkgreen', linestyles='-') # Adicione um título. plt.title(titulo) # Salve o arquivo plt.show() plt.savefig(salvar,dpi=500)
weight='bold') tmap.drawcoastlines(linewidth=1) tmap.drawcountries(linewidth=1, color='#0099FF') tmap.drawstates(linewidth=1) tmap.drawparallels(np.arange(-80, 81, 10), labels=[1, 1, 0, 0]) #shpinfo1=tmap.readshapefile(SHAPEDIR2+cmapz,'coast',drawbounds=True,color='black',linewidth=1.0) tmap.drawmeridians(np.arange(-180, 180, 10), labels=[0, 0, 0, 1]) with warnings.catch_warnings(): warnings.simplefilter("ignore") # cs = tmap.contourf(x, y, day[ii], clevs[ii], cmap=mpl.colors.ListedColormap(ncols), # hatches=hatch, extend='neither') if ii == 0: cs11 = tmap.contour(x, y, day[ii], clevs[ii], linewidths=0.5, colors='k') cs1 = tmap.contourf(x, y, day[ii], clevs[ii], cmap=mpl.colors.ListedColormap(ncols), hatches=hatch, extend='neither') if ii == 1: cs21 = tmap.contour(x, y, day[ii - 1], clevsa[ii - 1], linewidths=0.5,
map = Basemap(projection='cyl',llcrnrlon=130,llcrnrlat=-70,urcrnrlon=180,urcrnrlat=-30,resolution='l') # plot (unwarped) rgba image. im = map.bluemarble(scale=0.5) map.drawcoastlines(linewidth=0.5,color='0.5') map.drawmeridians(np.arange(-180,180,10),labels=[0,0,0,1],color='0.5') map.drawparallels(np.arange(-90,90,10),labels=[1,0,0,0],color='0.5') local_min, local_max = extrema(prmsl, mode='wrap', window=50) prmsl, lons = addcyclic(prmsl, lons1) clevs = np.arange(900,1100.,5) lons, lats = np.meshgrid(lons, lats) x, y = map(lons, lats) cs = map.contour(x,y,prmsl,clevs,colors='w',linewidths=1.) map.drawcoastlines(linewidth=1.25) #map.fillcontinents(color='0.8') #map.etopo() map.bluemarble() #map.shadedrelief() xlows = x[local_min]; xhighs = x[local_max] ylows = y[local_min]; yhighs = y[local_max] lowvals = prmsl[local_min]; highvals = prmsl[local_max] # plot lows as blue L's, with min pressure value underneath. xyplotted = [] # don't plot if there is already a L or H within dmin meters. yoffset = 0.022*(map.ymax-map.ymin) dmin = yoffset for x,y,p in zip(xlows, ylows, lowvals):
def write_land(exp, land_mode='square', boundaries=[20., 60., 20., 60.], continents=['all'], topo_mode='none', mountains=['all'], topo_gauss=[40., 40., 20., 10., 3500.], waterworld=False): # Common features of set-ups # specify resolution t_res = 42 #read in grid from approriate file GFDL_BASE = os.environ['GFDL_BASE'] resolution_file = Dataset( GFDL_BASE + 'src/extra/python/scripts/gfdl_grid_files/t' + str(t_res) + '.nc', 'r', format='NETCDF3_CLASSIC') lons = resolution_file.variables['lon'][:] lats = resolution_file.variables['lat'][:] lonb = resolution_file.variables['lonb'][:] latb = resolution_file.variables['latb'][:] nlon = lons.shape[0] nlat = lats.shape[0] topo_array = np.zeros((nlat, nlon)) land_array = np.zeros((nlat, nlon)) #make 2d arrays of latitude and longitude lon_array, lat_array = np.meshgrid(lons, lats) lonb_array, latb_array = np.meshgrid(lonb, latb) #create dictionary for continents cont_dic = {'NA': 0, 'SA': 1, 'EA': 2, 'AF': 3, 'OZ': 4, 'IN': 5, 'SEA': 6} # Firstly determine the land set-up to be used # 1) Set-up in which a square of land is included if land_mode == 'square': idx = (boundaries[0] <= lat_array) & (lat_array < boundaries[1]) & ( boundaries[2] < lon_array) & (boundaries[3] > lon_array) land_array[idx] = 1.0 # 2) Set-up in which some or all of 'original' continents are included elif land_mode == 'continents_old': #Older configuration of continents: Addition of India and SE Asia required some restructuring. This may be removed once obsolete. idx_c = np.zeros((4, nlat, nlon), dtype=bool) idx_c[0, :, :] = (103. - 43. / 40. * (lon_array - 180) < lat_array) & ( (lon_array - 180) * 43. / 50. - 51.8 < lat_array) & ( lat_array < 60.) #North America idx_c[1, :, :] = (737. - 7.2 * (lon_array - 180) < lat_array) & ( (lon_array - 180) * 10. / 7. + -212.1 < lat_array) & ( lat_array < -22. / 45 * (lon_array - 180) + 65.9) #South America eurasia_pos = (17. <= lat_array) & (lat_array < 60.) & ( -5. < lon_array) & (43. / 40. * lon_array - 101.25 < lat_array) eurasia_neg = (17. <= lat_array) & (lat_array < 60.) & (355. < lon_array) idx_c[2, :, :] = eurasia_pos + eurasia_neg #Eurasia africa_pos = (lat_array < 17.) & (-52. / 27. * lon_array + 7.37 < lat_array) & ( 52. / 38. * lon_array - 65.1 < lat_array) africa_neg = (lat_array < 17.) & (-52. / 27. * (lon_array - 360) + 7.37 < lat_array) idx_c[3, :, :] = africa_pos + africa_neg #Africa if 'all' in continents: idx = idx_c[0, :, :] + idx_c[1, :, :] + idx_c[2, :, :] + idx_c[ 3, :, :] land_array[idx] = 1. else: idx = np.zeros((nlat, nlon), dtype=bool) for cont in continents: idx = idx + idx_c[cont_dic[cont], :, :] land_array[idx] = 1.0 # 2) Set-up in which some or all of 'new' continents are included elif land_mode == 'continents': idx_c = np.zeros((7, nlat, nlon), dtype=bool) idx_c[0, :, :] = (103. - 43. / 40. * (lon_array - 180) < lat_array) & ( (lon_array - 180) * 43. / 50. - 51.8 < lat_array) & ( lat_array < 60.) #North America idx_c[1, :, :] = (737. - 7.2 * (lon_array - 180) < lat_array) & ( (lon_array - 180) * 10. / 7. + -212.1 < lat_array) & ( lat_array < -22. / 45 * (lon_array - 180) + 65.9) #South America eurasia_pos = (23. <= lat_array) & (lat_array < 60.) & ( -8. < lon_array) & (43. / 40. * lon_array - 101.25 < lat_array) eurasia_neg = (23. <= lat_array) & (lat_array < 60.) & (352. < lon_array) idx_c[2, :, :] = eurasia_pos + eurasia_neg #Eurasia africa_pos = (lat_array < 23.) & (-52. / 27. * lon_array + 7.59 < lat_array) & ( 52. / 38. * lon_array - 65.1 < lat_array) africa_neg = (lat_array < 23.) & (-52. / 27. * (lon_array - 360) + 7.59 < lat_array) idx_c[3, :, :] = africa_pos + africa_neg #Africa idx_c[4, :, :] = (lat_array > -35.) & (lat_array < -17.) & ( lon_array > 115.) & (lon_array < 150.) #Australia idx_c[5, :, :] = (lat_array < 23.) & (-15. / 8. * lon_array + 152 < lat_array) & ( 15. / 13. * lon_array - 81 < lat_array) #India idx_c[6, :, :] = (lat_array < 23.) & ( 43. / 40. * lon_array - 101.25 < lat_array) & ( -14. / 13. * lon_array + 120 < lat_array) #South East Asia if 'all' in continents: idx = idx_c[0, :, :] + idx_c[1, :, :] + idx_c[2, :, :] + idx_c[ 3, :, :] + idx_c[4, :, :] + idx_c[5, :, :] + idx_c[6, :, :] land_array[idx] = 1. else: idx = np.zeros((nlat, nlon), dtype=bool) for cont in continents: idx = idx + idx_c[cont_dic[cont], :, :] land_array[idx] = 1. elif land_mode == 'none': land_array = np.zeros((nlat, nlon)) # Next produce a topography array if topo_mode == 'none': topo_array = np.zeros((nlat, nlon)) elif topo_mode == 'sauliere2012': # Rockys from Sauliere 2012 h_0 = 2670. central_lon = 247.5 central_lat = 40. L_1 = 7.5 L_2 = 20. gamma_1 = 42. gamma_2 = 42. delta_1 = ( (lon_array - central_lon) * np.cos(np.radians(gamma_1)) + (lat_array - central_lat) * np.sin(np.radians(gamma_1))) / L_1 delta_2 = ( -(lon_array - central_lon) * np.sin(np.radians(gamma_2)) + (lat_array - central_lat) * np.cos(np.radians(gamma_2))) / L_2 h_arr_rockys = h_0 * np.exp(-(delta_1**2. + delta_2**2.)) idx_rockys = ( h_arr_rockys / h_0 > 0.05 ) #s make sure exponentials are cut at some point - use the value from p70 of Brayshaw's thesis. #Tibet from Sauliere 2012 h_0 = 5700. central_lon = 82.5 central_lat = 28 L_1 = 12.5 L_2 = 12.5 gamma_1 = -49.5 gamma_2 = -18. delta_1 = ( (lon_array - central_lon) * np.cos(np.radians(gamma_1)) + (lat_array - central_lat) * np.sin(np.radians(gamma_1))) / L_1 delta_2 = ( -(lon_array - central_lon) * np.sin(np.radians(gamma_2)) + (lat_array - central_lat) * np.cos(np.radians(gamma_2))) / L_2 h_arr_tibet_no_amp = np.exp(-(delta_1**2.)) * (1. / delta_2) * np.exp( -0.5 * (np.log(delta_2))**2.) maxval = np.nanmax( h_arr_tibet_no_amp ) #For some reason my maximum value of h_arr_tibet_no_amp > 1. Renormalise so h_0 sets amplitude. h_arr_tibet = (h_arr_tibet_no_amp / maxval) * h_0 idx_tibet = (h_arr_tibet / h_0 > 0.05) if 'all' in mountains: topo_array[idx_rockys] = h_arr_rockys[idx_rockys] topo_array[idx_tibet] = h_arr_tibet[idx_tibet] elif 'rockys' in mountains: topo_array[idx_rockys] = h_arr_rockys[idx_rockys] elif 'tibet' in mountains: topo_array[idx_tibet] = h_arr_tibet[idx_tibet] else: print 'No valid mountain options detected for Sauliere 2012 topography' elif topo_mode == 'gaussian': #Options to define simple Gaussian Mountain central_lat = topo_gauss[0] central_lon = topo_gauss[1] radius_degrees = topo_gauss[2] std_dev = topo_gauss[3] height = topo_gauss[4] rsqd_array = np.sqrt((lon_array - central_lon)**2. + (lat_array - central_lat)**2.) #generalise to ellipse - needs checking but may be useful later (RG) #ax_rot = 1. #gradient of new x axis #ax_rat = 2. #axis ratio a**2/b**2 #rsqd_array = np.sqrt((lon_array - central_lon + ax_rot*(lat_array - central_lat))**2.+ ax_rat*(lat_array - central_lat - ax_rot*(lon_array - central_lon))**2.)*np.cos(np.arctan(ax_rot)) #divide by factor of cos(atan(m)) to account for change in coords idx = (rsqd_array < radius_degrees) topo_array[idx] = height * np.exp(-(rsqd_array[idx]**2.) / (2. * std_dev**2.)) else: print 'Invalid topography option given' if waterworld != True: #Leave flexibility to allow aquamountains! idx = (land_array == 0.) & (topo_array != 0.) topo_array[idx] = 0. #Show configuration on screen to allow checking lon_0 = lons.mean() lat_0 = lats.mean() m = Basemap(lat_0=lat_0, lon_0=lon_0) xi, yi = m(lon_array, lat_array) plt.figure() if land_mode != 'none': m.contour(xi, yi, land_array) if topo_mode != 'none': cs = m.contourf(xi, yi, topo_array / 1000, cmap=plt.get_cmap('RdBu_r')) cb = plt.colorbar(cs, shrink=0.5, extend='both', label='Height, km') plt.xticks(np.linspace(0, 360, 13)) plt.yticks(np.linspace(-90, 90, 7)) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.savefig('/scratch/rg419/plots/mom_budg_work/land_fig.png') plt.clf()