def preview(self): '''Preview map in window''' theurl = self.FILENAME.get() if empty(theurl): messagebox.showinfo(message='No image selected') return self.ax1.clear() print('Preview of ',theurl) icdf = Dataset(theurl,'r') lon = icdf.variables['lon'][:] lat = icdf.variables['lat'][:] sst = icdf.variables['mcsst'][0,:,:].squeeze() xxT,yyT = np.meshgrid(lon,lat) SOUTH = np.min(lat) NORTH = np.max(lat) WEST = np.min(lon) EAST = np.max(lon) m = Basemap(llcrnrlat=SOUTH,urcrnrlat=NORTH, \ llcrnrlon=WEST,urcrnrlon=EAST, \ ax=self.ax1) m.fillcontinents(color='coral') m.drawcoastlines(linewidth=1) m.contourf(xxT,yyT,sst) self.canvas.draw() print('done')
def plot_robinson_rossby(model,vec,val,m,l): E = model.physical_constants['E'] Nk = model.Nk Nl = model.Nl th = model.th ## Plot Robinson vector field #### Display waves on a Spherical Map Projection projtype = 'robin' ## Create full vector grid in theta and phi u_1D = model.getVariable(vec,'uph')[0][0] v_1D = model.getVariable(vec,'uth')[0][0] Nph = 2*Nl ph = np.linspace(-180.,180.-360./Nph,Nph) lon_grid, lat_grid = np.meshgrid(ph,th[1:-1]*180./np.pi-90.,) v = (np.exp(1j*m*lon_grid*np.pi/180.).T*v_1D).T u = (np.exp(1j*m*lon_grid*np.pi/180.).T*u_1D).T absu=u**2 + v**2 Nvec = np.floor(Nl/20.) ### Plot Robinson Projection plt.figure(figsize=(10,10)) ## Set up map bmap = Basemap(projection=projtype,lon_0=0.) bmap.drawparallels(np.arange(-90.,90.,15.)) bmap.drawmeridians(np.arange(0.,360.,15.)) ## Convert Coordinates to those used by basemap to plot lon,lat = bmap(lon_grid,lat_grid) bmap.contourf(lon,lat,absu,15,cmap=plt.cm.Reds,alpha=0.5) bmap.quiver(lon[::Nvec,::Nvec],lat[::Nvec,::Nvec],u[::Nvec,::Nvec].real,v[::Nvec,::Nvec].real) plt.title('{0} Projection Vector Field for m={1}, l={2}'.format('Robinson',m,l)) plt.savefig('./output/m={1}/{0}VectorField_m={1}_l={2}.png'.format('Robinson',m,l))
def plot(rec): data = rec.values lats, lons = rec.latlons() fig = plt.figure(figsize=(8,8)) # create figure and axes instances ax = fig.add_axes([0.1,0.1,0.8,0.8]) # create polar stereographic Basemap instance. # m = Basemap(projection='stere',lon_0=lon_0,lat_0=90.,lat_ts=lat_0,\ # llcrnrlat=latcorners[0],urcrnrlat=latcorners[2],\ # llcrnrlon=loncorners[0],urcrnrlon=loncorners[2],\ # rsphere=6371200.,resolution='l',area_thresh=10000) # # Lambert Conformal Conic map. m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57., projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60., resolution ='l',area_thresh=1000.) # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines() m.drawstates() m.drawcountries() # draw parallels. parallels = np.arange(0.,90,10.) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # draw meridians meridians = np.arange(180.,360.,10.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) ny = data.shape[0]; nx = data.shape[1] x, y = m(lons, lats) # compute map proj coordinates. m.contourf(x, y, data) plt.title('{0} ({5}) for period ending {1}/{2}/{3} {4}:00'.format(rec.parameterName, rec.year, rec.month, rec.day, rec.hour, rec.parameterNumber)) plt.show()
def plot(self,key='Re'): """ Create a plot of a variable over the ORACLES study area. Parameters ---------- key : string See names for available datasets to plot. clf : boolean If True, clear off pre-existing figure. If False, plot over pre-existing figure. Modification history -------------------- Written: Michael Diamond, 08/16/2016, Seattle, WA Modified: Michael Diamond, 08/21/2016, Seattle, WA -Added ORACLES routine flight plan, Walvis Bay (orange), and Ascension Island Modified: Michael Diamond, 09/02/2016, Swakopmund, Namibia -Updated flihgt track """ plt.clf() size = 16 font = 'Arial' m = Basemap(llcrnrlon=self.lon.min(),llcrnrlat=self.lat.min(),urcrnrlon=self.lon.max(),\ urcrnrlat=self.lat.max(),projection='merc',resolution='i') m.drawparallels(np.arange(-180,180,5),labels=[1,0,0,0],fontsize=size,fontname=font) m.drawmeridians(np.arange(0,360,5),labels=[1,1,0,1],fontsize=size,fontname=font) m.drawmapboundary(linewidth=1.5) m.drawcoastlines() m.drawcountries() if key == 'Pbot' or key == 'Ptop' or key == 'Nd' or key == 'DZ': m.drawmapboundary(fill_color='steelblue') m.fillcontinents(color='floralwhite',lake_color='steelblue',zorder=0) else: m.fillcontinents('k',zorder=0) if key == 'Nd': m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\ latlon=True,norm = LogNorm(vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1])) elif key == 'Zbf' or key == 'Ztf': levels = [0,250,500,750,1000,1250,1500,1750,2000,2500,3000,3500,4000,5000,6000,7000,8000,9000,10000] m.contourf(self.lon,self.lat,self.ds['%s' % key],levels=levels,\ cmap=self.colors['%s' % key],latlon=True,extend='max') elif key == 'DZ': levels = [0,500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000] m.contourf(self.lon,self.lat,self.ds['%s' % key],levels=levels,\ cmap=self.colors['%s' % key],latlon=True,extend='max') else: m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\ latlon=True,vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1]) cbar = m.colorbar() cbar.ax.tick_params(labelsize=size-2) cbar.set_label('[%s]' % self.units['%s' % key],fontsize=size,fontname=font) if key == 'Pbot' or key == 'Ptop': cbar.ax.invert_yaxis() m.scatter(14.5247,-22.9390,s=250,c='orange',marker='D',latlon=True) m.scatter(-14.3559,-7.9467,s=375,c='c',marker='*',latlon=True) m.scatter(-5.7089,-15.9650,s=375,c='chartreuse',marker='*',latlon=True) m.plot([14.5247,13,0],[-22.9390,-23,-10],c='w',linewidth=5,linestyle='dashed',latlon=True) m.plot([14.5247,13,0],[-22.9390,-23,-10],c='k',linewidth=3,linestyle='dashed',latlon=True) plt.title('%s from MSG SEVIRI on %s/%s/%s at %s UTC' % \ (self.names['%s' % key],self.month,self.day,self.year,self.time),fontsize=size+4,fontname=font) plt.show()
def vec_plot_on_earth(lons, lats, x_data, y_data, vmin=-4, vmax=12, ax=None): if ax == None: ax = plt.gca() plot_lons, plot_x_data = extend_data(lons, lats, x_data) plot_lons, plot_y_data = extend_data(lons, lats, y_data) lons, lats = np.meshgrid(plot_lons, lats) m = Basemap(ax=ax, projection='cyl', resolution='c', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) x, y = m(lons, lats) mag = np.sqrt(plot_x_data**2 + plot_y_data**2) vmin, vmax = mag.min(), mag.max() m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax) #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax) #m.quiver(x, y, plot_x_data, plot_y_data) skip = 5 m.quiver(x[::skip, ::skip], y[::skip, ::skip], plot_x_data[::skip, ::skip], plot_y_data[::skip, ::skip], ax=ax) m.drawcoastlines(ax=ax) m.drawparallels(np.arange(-90.,90.,45.), labels=[1, 0, 0, 0], fontsize=10, ax=ax) m.drawmeridians(np.arange(-180.,180.,60.), labels=[0, 0, 0, 1], fontsize=10, ax=ax) m.colorbar(location='bottom', pad='7%', ax=ax) plt.show()
def vec_plot_south_america(lons, lats, sa_mask, data_x, data_y, ax=None): if ax == None: ax = plt.gca() #print(sa_mask.shape) #print(data_x.shape) #print(data_y.shape) #data_x_masked = np.ma.array(data_x, mask=sa_mask) #data_y_masked = np.ma.array(data_y, mask=sa_mask) plot_lons, plot_x_data = extend_data(lons, lats, data_x) plot_lons, plot_y_data = extend_data(lons, lats, data_y) lons, lats = np.meshgrid(plot_lons, lats) m = Basemap(ax=ax, projection='cyl', resolution='c', llcrnrlat=-60, urcrnrlat=15, llcrnrlon=-85, urcrnrlon=-32) x, y = m(lons, lats) mag = np.sqrt(plot_x_data**2 + plot_y_data**2) vmin, vmax = mag.min(), mag.max() m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax) #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax, ax=ax) m.quiver(x, y, plot_x_data, plot_y_data, scale=40, ax=ax) m.drawcoastlines(ax=ax) m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10, ax=ax) m.drawmeridians(np.arange(-90.,-30.,10.), labels=[0, 0, 0, 1], fontsize=10, ax=ax) m.colorbar(location='right', pad='5%', ax=ax) plt.show()
def interpolated_color_map(station_lon, station_lat, station_val, grid_dim=(80,110), interp='nn', cmap=None):#cm.s3pcpn): # map boundries lat_0 = 51 lat_min = 47 lat_max = 55 lon_0 = 10 lon_min = 5 lon_max = 16 m = Basemap(projection='tmerc', lat_0=lat_0, lon_0=lon_0, llcrnrlat=lat_min, llcrnrlon=lon_min, urcrnrlat=lat_max, urcrnrlon=lon_max, resolution='i') m.drawcoastlines() m.drawcountries() m.drawmapboundary() # x = np.linspace(0, m.urcrnrx, station_val.shape[1]) # y = np.linspace(0, m.urcrnry, station_val.shape[0]) # xx, yy = np.meshgrid(x, y) # m.contourf(xx, yy, station_val) m.contourf(station_lon, station_lat, station_val[:,0], latlon='true') plt.show()
def plot(array,typep=None,clevel=None): fig,ax = plt.subplots() lats=array['lats'] lons=array['lons'] latm,lonm = np.meshgrid(lats,lons) latn = np.min(lats) latx = np.max(lats) lonn = np.min(lons) lonx = np.max(lons) m = Basemap(projection='merc', llcrnrlat=latn, urcrnrlat=latx, llcrnrlon=lonn, urcrnrlon=lonx, resolution='l', ax=ax) if typep == 'pcolor': m.pcolormesh(lonm.T,latm.T,array['data'],latlon=True) elif typep == 'contourf': X,Y=m(lonm.T, latm.T) m.contourf(X,Y,array['data'],clevel) m.drawparallels(lats[1::10],labels=[1,0,0,0]) m.drawmeridians(lons[1::20],labels=[0,0,0,1]) m.drawcoastlines() plt.show(block=False)
def plot_eof(self,name,no_eofs=1): m = Basemap(projection='ortho', lat_0=-60., lon_0=100.)#todo world=[0,-90,360,0] min_lat=self._lat[0] max_lat=self._lat[-1] min_lon=self._lon[0] max_lon=self._lon[-1] dif_lat=(max_lat-min_lat) if max_lon%360==min_lon%360: dif_lon=360 else: dif_lon=(max_lon-min_lon)%360 lon_line=5 while dif_lon/lon_line>9: lon_line+=5 lat_line=5 while dif_lat/lat_line>10: lat_line+=5 for i in range(no_eofs): plt.figure(i) m=Basemap(projection='gall',llcrnrlat=min_lat,urcrnrlat=max_lat,\ llcrnrlon=min_lon,urcrnrlon=max_lon,resolution='c') x, y = m(*np.meshgrid(self._lon, self._lat)) levels = np.linspace(-1,1,11) m.contourf(x, y, self._eof[i].squeeze(),levels, cmap=plt.cm.RdBu_r) m.drawcoastlines() m.drawparallels(np.arange(-80.,86.,lat_line),labels=[True,False,False,False]) m.drawmeridians(np.arange(-180.,181.,lon_line),labels=[False,False,False,True]) plt.title("EOF ("+"%0.1f"%(self._fraction[i]*100)+"%)" , fontsize=16) cb = plt.colorbar(orientation='horizontal') cb.set_label('correlation coefficient', fontsize=12) plt.savefig(name+'.pdf',figsize=(15, 6), dpi=300, facecolor='w', edgecolor='w') plt.clf()
def plot_ppi(sweep_dict, parm, **kwargs): radar_loc=kwargs.get('radar_loc', [-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) 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) #map.drawcoastlines() #map.drawcountries() map.drawmapboundary() map.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) 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]) 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]) 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]) colorbar() savefig(fig_path+fig_name) close(f)
def _vec_plot_on_earth(lons, lats, x_data, y_data, vmin=-4, vmax=12, loc=None, colorbar=False): plot_lons, plot_x_data = _extend_data(lons, lats, x_data) plot_lons, plot_y_data = _extend_data(lons, lats, y_data) lons, lats = np.meshgrid(plot_lons, lats) if not loc: m = Basemap(projection='cyl', resolution='c', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) else: m = Basemap(projection='cyl', resolution='c', **loc) x, y = m(lons, lats) mag = np.sqrt(plot_x_data**2 + plot_y_data**2) vmin, vmax = mag.min(), mag.max() m.contourf(x, y, mag) # m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax) # m.quiver(x, y, plot_x_data, plot_y_data) skip = 1 m.quiver(x[::skip, ::skip], y[::skip, ::skip], plot_x_data[::skip, ::skip], plot_y_data[::skip, ::skip], scale=500) m.drawcoastlines() m.drawparallels(np.arange(-90., 90., 45.), labels=[1, 0, 0, 0], fontsize=10) m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], fontsize=10) if colorbar: m.colorbar(location='right', pad='7%') return m
def triangulation_map(station_lon, station_lat, station_val, cmap=None, *args, **kwargs): """ Using matplotlib.pyplot.tricontourf() function to plot contourplot on an irreguar grid by using triangulation. """ # map boundries lat_0 = 51 lat_min = 47 lat_max = 55 lon_0 = 10 lon_min = 5 lon_max = 16 m = Basemap(projection='tmerc', lat_0=lat_0, lon_0=lon_0, llcrnrlat=lat_min, llcrnrlon=lon_min, urcrnrlat=lat_max, urcrnrlon=lon_max, resolution='i') m.drawcoastlines() m.drawcountries() m.drawmapboundary() m.contourf(station_lon, station_lat, station_val, cmap=cmap, latlon=True, tri=True, *args, **kwargs) m.scatter(station_lon, station_lat, color='k', s=5, latlon=True) # Set Triangulation manual?: #station_x, station_y = m(station_lon, station_lat) #triang = tri.Triangulation(station_x, station_y) #plt.tricontour(station_x, station_y, station_val, 15, linewidths=0.5, colors='k') #plt.tricontourf(x, y, z, 15, cmap=plt.cm.rainbow, norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) plt.show()
def old_plot_cappi(x,y,data,sweep_dict, **kwargs): radar_loc=kwargs.get('radar_loc', [-12.2492, 131.0444]) parm=kwargs.get('parm','') fig_name=kwargs.get('fig_name', 'cappi_'+parm+'_.png') 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*x/(rad_at_radar*2.0*pi) lats=radar_loc[0] + 360.0*y/(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) map= Basemap(projection='merc', resolution='l',area_thresh=1., **loc_dict) longr, latgr=meshgrid(lons,lats) xx, yy = map(longr, latgr) #map.drawcoastlines() #map.drawcountries() map.drawmapboundary() map.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) 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) levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'TEST':linspace(((abs(data)+data)/2.0).min(), data.max(), 200), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs} titles_dict={'VR': 'Velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component'} map.contourf(xx,yy,data, levels=levs_dict[parm]) 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]) colorbar() savefig(getenv('HOME')+'/bom_mds/output/'+fig_name) close(f)
def demo_north_pole(): r = RPN(path = "/home/huziy/skynet3_rech1/classOff_Andrey/era2/temp_3d") t = r.get_first_record_for_name("I0") lon, lat = r.get_longitudes_and_latitudes_for_the_last_read_rec() r.close() nx, ny = lon.shape lon_0, lat_0 = lon[nx//2, ny//2], lat[nx//2, ny//2] basemap = Basemap(projection = "omerc", lon_1=60, lat_1 = 89.999, lon_2=-30, lat_2=0, no_rot=True, lon_0 = lon_0, lat_0 = lat_0, llcrnrlon=lon[0, 0], llcrnrlat=lat[0,0], urcrnrlon=lon[-1, -1], urcrnrlat=lat[-1, -1] ) x, y = basemap(lon, lat) basemap.contourf(x, y, t) basemap.drawcoastlines() basemap.colorbar() #basemap.shadedrelief() plt.show()
def vec_plot_polar(lons, lats, data_x, data_y, pole, ax=None): if ax == None: ax = plt.gca() plot_lons, plot_x_data = extend_data(lons, lats, data_x) plot_lons, plot_y_data = extend_data(lons, lats, data_y) lons, lats = np.meshgrid(plot_lons, lats) if pole == 'N': m = Basemap(ax=ax, resolution='c',projection='stere',lat_0=90.,lon_0=0, width=12000000,height=8000000) elif pole == 'S': m = Basemap(ax=ax, resolution='c',projection='stere',lat_0=-90.,lon_0=0, width=12000000,height=8000000) x, y = m(lons, lats) mag = np.sqrt(plot_x_data**2 + plot_y_data**2) vmin, vmax = mag.min(), mag.max() m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax) #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax, ax=ax) skip = 5 m.quiver(x[::5, ::5], y[::5, ::5], plot_x_data[::5, ::5], plot_y_data[::5, ::5], scale=50, ax=ax) m.drawcoastlines(ax=ax) m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10, ax=ax) m.drawmeridians(np.arange(-180.,180.,10.), fontsize=10, ax=ax) m.colorbar(location='right', pad='5%', ax=ax) plt.show()
def plot_mollyweide_rossby(model,vec,val,m,l): E = model.E Nk = model.Nk Nl = model.Nl th = model.th ## Calculate vector field and contour field for plotting with basemap ## Create full vector grid in theta and phi u_1D = model.getVariable(vec,'uph')[0][0] v_1D = model.getVariable(vec,'uth')[0][0] Nph = 2*Nl ph = np.linspace(-180.,180.-360./Nph,Nph) lon_grid, lat_grid = np.meshgrid(ph,th[1:-1]*180./np.pi-90.,) v = (np.exp(1j*m*lon_grid*np.pi/180.).T*v_1D).T u = (np.exp(1j*m*lon_grid*np.pi/180.).T*u_1D).T absu=u**2 + v**2 Nvec = np.floor(Nl/20.) ### Plot Mollweide Projection plt.figure(figsize=(10,10)) ## Set up map bmap = Basemap(projection='moll',lon_0=0.) bmap.drawparallels(np.arange(-90.,90.,15.)) bmap.drawmeridians(np.arange(0.,360.,15.)) ## Convert Coordinates to those used by basemap to plot lon,lat = bmap(lon_grid,lat_grid) bmap.contourf(lon,lat,absu,15,cmap=plt.cm.Reds,alpha=0.5) bmap.quiver(lon[::Nvec,::Nvec],lat[::Nvec,::Nvec],u[::Nvec,::Nvec].real,v[::Nvec,::Nvec].real) plt.title('Mollweide Projection Vector Field for m={0}, l={1}'.format(m,l)) plt.savefig('./output/m={1}/MollweideVectorField_m={1}_l={2}.png'.format(val.imag,m,l))
def Map_plot_bias_of_multiyear_climatology(obs_dataset, obs_name, model_datasets, model_names, file_name, row, column): '''Draw maps of observed multi-year climatology and biases of models"''' # calculate climatology of observation data obs_clim = utils.calc_temporal_mean(obs_dataset) # determine the metrics map_of_bias = metrics.TemporalMeanBias() # create the Evaluation object bias_evaluation = Evaluation(obs_dataset, # Reference dataset for the evaluation model_datasets, # list of target datasets for the evaluation [map_of_bias, map_of_bias]) # run the evaluation (bias calculation) bias_evaluation.run() rcm_bias = bias_evaluation.results[0] fig = plt.figure() lat_min = obs_dataset.lats.min() lat_max = obs_dataset.lats.max() lon_min = obs_dataset.lons.min() lon_max = obs_dataset.lons.max() string_list = list(string.ascii_lowercase) ax = fig.add_subplot(row,column,1) m = Basemap(ax=ax, projection ='cyl', llcrnrlat = lat_min, urcrnrlat = lat_max, llcrnrlon = lon_min, urcrnrlon = lon_max, resolution = 'l', fix_aspect=False) lons, lats = np.meshgrid(obs_dataset.lons, obs_dataset.lats) x,y = m(lons, lats) m.drawcoastlines(linewidth=1) m.drawcountries(linewidth=1) m.drawstates(linewidth=0.5, color='w') max = m.contourf(x,y,obs_clim,levels = plotter._nice_intervals(obs_dataset.values, 10), extend='both',cmap='PuOr') ax.annotate('(a) \n' + obs_name,xy=(lon_min, lat_min)) cax = fig.add_axes([0.02, 1.-float(1./row), 0.01, 1./row*0.6]) plt.colorbar(max, cax = cax) clevs = plotter._nice_intervals(rcm_bias, 11) for imodel in np.arange(len(model_datasets)): ax = fig.add_subplot(row, column,2+imodel) m = Basemap(ax=ax, projection ='cyl', llcrnrlat = lat_min, urcrnrlat = lat_max, llcrnrlon = lon_min, urcrnrlon = lon_max, resolution = 'l', fix_aspect=False) m.drawcoastlines(linewidth=1) m.drawcountries(linewidth=1) m.drawstates(linewidth=0.5, color='w') max = m.contourf(x,y,rcm_bias[imodel,:],levels = clevs, extend='both', cmap='RdBu_r') ax.annotate('('+string_list[imodel+1]+') \n '+model_names[imodel],xy=(lon_min, lat_min)) cax = fig.add_axes([0.91, 0.1, 0.015, 0.8]) plt.colorbar(max, cax = cax) plt.subplots_adjust(hspace=0.01,wspace=0.05) plt.show() fig.savefig(file_name,dpi=600,bbox_inches='tight')
def plot_eq_displacements(LLD_FILE, LEVELS, save_file): # Read displacement data disp_data = np.genfromtxt(LLD_FILE, dtype=[('lat','f8'),('lon','f8'), ('z','f8')],skip_header=3) # Data ranges lon_min,lon_max = disp_data['lon'].min(),disp_data['lon'].max() lat_min,lat_max = disp_data['lat'].min(),disp_data['lat'].max() mean_lat = 0.5*(lat_min + lat_max) mean_lon = 0.5*(lon_min + lon_max) lon_range = lon_max - lon_min lat_range = lat_max - lat_min z_min,z_max = disp_data['z'].min(),disp_data['z'].max() z_lim = max(np.abs(z_min),np.abs(z_max)) cmap = plt.get_cmap('seismic') norm = mcolor.Normalize(vmin=-z_lim, vmax=z_lim) interp = 'cubic' landcolor = '#FFFFCC' framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=14) # Initialize the frame and axes fig = plt.figure() m = Basemap(projection='cyl',llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, lat_0=mean_lat, lon_0=mean_lon, resolution='h') m.ax = fig.add_subplot(111) m.drawmeridians(np.linspace(lon_min,lon_max,num=5.0),labels=[0,0,0,1], linewidth=0) m.drawparallels(np.linspace(lat_min,lat_max,num=5.0),labels=[1,0,0,0], linewidth=0) m.drawcoastlines(linewidth=0.5) m.fillcontinents(color=landcolor, zorder=0) # Colorbar divider = make_axes_locatable(m.ax) cbar_ax = divider.append_axes("right", size="5%",pad=0.05) plt.figtext(0.96, 0.7, r'displacement $[m]$', rotation='vertical', fontproperties=framelabelfont) cb = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm) # Reshape into matrices Ncols = len(np.unique(disp_data['lon'])) Nrows = len(np.unique(disp_data['lat'])) X = disp_data['lon'].reshape(Nrows, Ncols) Y = disp_data['lat'].reshape(Nrows, Ncols) Z = disp_data['z'].reshape(Nrows, Ncols) # Masked array via conditional, don't color the land unless it has water on it zero_below = int(len(LEVELS)/2)-1 zero_above = zero_below+1 masked_data = np.ma.masked_where(np.logical_and(np.array(Z <= LEVELS[zero_above]),np.array(Z >= LEVELS[zero_below])), Z) # Set masked pixels to the land color cmap.set_bad(landcolor, 0.0) # set alpha=0.0 for transparent # Plot the contours m.contourf(X, Y, masked_data, LEVELS, cmap=cmap, norm=norm, extend='both', zorder=1) plt.savefig(save_file,dpi=100) print("Saved to "+save_file)
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 plt_map(lon,lat,data): m = Basemap(resolution='l',**LAEA_EUROPE) x, y = m(lon, lat) plt.figure(figsize=(20,20)) m.drawcoastlines() # m.drawparallels(np.arange(-80.,81.,20.)) # m.drawmeridians(np.arange(-180.,181.,20.)) m.drawmapboundary(fill_color='white') m.contourf(x,y,data,levels=np.arange(0,0.6,0.01), extend="both"); plt.colorbar( orientation='horizontal', pad=0.05)
def sfc_plot(starttime, endtime, variables, variablest, locations, met, xi, yi, xmin, xmax, ymin, ymax): ''' Script for plotting the mesonet data with wind barbs over a county map in a given time interval ''' interval = int((endtime - starttime).total_seconds()/300) z_max = np.max(met[variablest[1]]) z_min = np.min(met[variablest[1]]) levels = np.arange(z_min, z_max+1, 1) shapefile = 'UScounties/UScounties' if not os.path.exists('%s' %(variables)): os.makedirs('%s' %(variables)) for i in range(interval): time_selection = starttime + dt.timedelta(minutes=5*i) zi = interpolate.griddata((met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat']), met.ix[time_selection][variablest[1]], (xi, yi), method='cubic') maps = Basemap(llcrnrlon=xmin, llcrnrlat=ymin, urcrnrlon=xmax, urcrnrlat=ymax, projection='cyl') maps.readshapefile(shapefile, name='counties') # mzi = np.ma.masked_array(zi,np.isnan(zi)) # levels = np.arange(np.min(mzi), np.max(mzi)+1., 1) if (variables == 'dew_point'): maps.contourf(xi, yi, zi, np.arange(0.,21, 1), cmap=plt.cm.gist_earth_r) # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r) if (variables == 'relative_humidity'): maps.contourf(xi, yi, zi, np.arange(15.,51., 1.), cmap=plt.cm.gist_earth_r) # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r) if ((variables == 'temperature') or (variables== 'theta_e')): maps.contourf(xi, yi, zi, np.arange(24,40.5,0.5), cmap=plt.cm.jet) # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.jet) if variables == 'rainfall': maps.contourf(xi, yi, zi, levels, cmap=plt.cm.YlGn) if ((variables == 'pressure') or (variables == 'wind_speed') or (variables == 'gust_speed')): maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth) c = plt.colorbar() c.set_label(variablest[0]) maps.scatter(met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat'], latlon=True, marker='o', c='b', s=5) maps.barbs(met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat'], met.ix[time_selection]['u'].values*1.94384, met.ix[time_selection]['v'].values*1.94384, latlon=True) maps.drawparallels(np.arange(31.,36,1.), color='0.5', labels=[1,0,0,0], fontsize=10) maps.drawmeridians(np.arange(-104.,-98.,1.), color='0.5', labels=[0,0,0,1], fontsize=10) plt.title(variablest[1]) filename = '%s_%s.png' % (variables, time_selection.strftime('%Y%m%d_%H%M')) plt.tight_layout() plt.savefig(variables + '/' + filename, dpi=150) plt.clf()
class GridPlot(Argument, Settings): """ROC绘图""" parameters = dict() # 命令行参数,参考 https://docs.python.org/2/howto/argparse.html command_args = [ [('npy',), {'help': u'指定一个csv2npy后生成的.npy文件', 'type': str, 'nargs': 1}], [('-n','--name',), {'help': u'输出结果文件名', 'type': str, 'nargs': 1}], [('-t','--title',), {'help': 'plot image title', 'type': str, 'nargs': 1}], [('-v','--verbose',), {'help': u'输出详细信息', 'action':"store_true"}] ] def __init__(self): """init""" Argument.__init__(self) Settings.__init__(self) self.parse_args() def parse_args(self): """parse arguments""" if self.args.npy and os.path.isfile(self.args.npy[0]): self.parameters['npy'] = self.args.npy[0] else: print('{} not found!'.format(self.args.npy[0])) exit(-1) self.parameters['name'] = self.args.name[0] if self.args.name else tf.mktemp(suffix='.png',dir='.') self.parameters['title'] = self.args.title[0] if self.args.title else 'Grid Plot' if self.args.verbose: print("============parameters===========") for key in self.parameters: print(key,self.parameters[key]) self.process() def process(self): """ process """ ##load data data = np.load(self.parameters['npy']) ##create basemap self.bm = Basemap(projection='cyl',resolution='l',lon_0=120) self.bm.drawcoastlines(linewidth=0.25) self.bm.drawcountries(linewidth=0.25) #self.bm.fillcontinents(color='grey') lons,lats = self.bm.makegrid(360,181) x,y = self.bm(lons,lats) self.bm.contourf(x,y,data) ##add colorbar self.bm.colorbar(location='bottom',size='5%',label="mm") ##add plot title plt.title(self.parameters['title']) ##save plot plt.savefig(self.parameters['name'])
def plot(self, path=''): data = self._readFromTxtFile(path) plt.figure() b = Basemap(projection="cyl", llcrnrlon=self.lons2d[0, 0], llcrnrlat=self.lats2d[0, 0], urcrnrlon=self.lons2d[-1, -1], urcrnrlat=self.lats2d[-1, -1] ) x, y = b(self.lons2d, self.lats2d) b.contourf(x, y, data) plt.colorbar() b.drawcoastlines() plt.title(os.path.basename(path)) plt.savefig(os.path.basename(path) + ".png")
def plotdata(llon,dlat,rlon,ulat,delat,delon,ringan,sedang,lebat,ekstrim,time,fimage): print 'Plot Image : ',time.strftime('Time %d-%m-%Y : %H.%M UTC') af = plt.figure(1) ax = plt.subplot(211) baseMap = Basemap(resolution='i',llcrnrlon=llon, llcrnrlat=dlat, urcrnrlon=rlon,urcrnrlat=ulat) #baseMap.readshapefile(fshpProv,'Propinsi',color='#FFFFFF',linewidth=0.1) baseMap.drawparallels(np.arange(-90,90,delat/2.),labels=[1,0,0,0],fontsize=3,linewidth=0.3,color='#999999')#,zorder=15 #baseMap.drawmeridians(np.arange(-180,190,delon/2.),labels=[0,0,0,1],fontsize=3,linewidth=0.3,color='#999999')#,zorder=14 #baseMap.drawcoastlines(linewidth=0.5,color='#FFFFFF')#,zorder=13 #baseMap.drawcountries(linewidth=0.5,color='#FFFFFF')#,zorder=12 baseMap.drawmeridians(np.arange(-180,190,delon/2.),labels=[0,0,0,1],fontsize=3,linewidth=0.3,color='#999999')#,zorder=14 baseMap.drawcoastlines(linewidth=0.5,color='black')#,zorder=13 baseMap.drawcountries(linewidth=0.5,color='black')#,zorder=12 lev = [.99,2] col = ['red'] colringan = ['lightgreen'] colsedang = ['green'] collebat = ['yellow'] colext = ['red'] #tick = [str(i) for i in lev] x,y = np.meshgrid(np.linspace(llon,rlon,len(ringan[0])),np.linspace(dlat,ulat,len(ringan))) hujringan = baseMap.contourf(x,y,ringan,levels=lev,colors=colringan,labels='hujan ringan') hujsedang = baseMap.contourf(x,y,sedang,levels=lev,colors=colsedang,labels='hujan sedang') hujlebat = baseMap.contourf(x,y,lebat,levels=lev,colors=collebat,labels='hujan lebat') hujextrim = baseMap.contourf(x,y,ekstrim,levels=lev,colors=colext,labels='hujan ekstrem') #cb = plt.colorbar(cax,ticks=lev,pad=0.01,orientation='vertical') #cb.ax.set_yticklabels(tick,fontsize=4.) #cb.ax.set_title('Temperature\n(C)',fontsize=4.) #judul colorbar x,y = baseMap(llon,ulat+(ulat-dlat)/20.) plt.text(x,y,'Prediksi hujan',fontsize=5,weight='bold') #judul gambar x,y = baseMap(llon,ulat+(ulat-dlat)/50.) #plt.text(x,y,time.strftime('Time %A,%d-%m-%Y : %H.%M UTC'),fontsize=4) #ket waktu x,y = baseMap(rlon,ulat+(ulat-dlat)/50.) #x,y = baseMap(llon,dlat-(ulat-dlat)/15.) plt.text(x,y,r'$\copyright$ STMKG, '+time.strftime('%Y')+' ',fontsize=3,color='gray',horizontalalignment='right') x,y = baseMap(rlon,ulat+(ulat-dlat)/20.) #x,y = baseMap(rlon,dlat-(ulat-dlat)/15.) plt.text(x,y,r'Data Source by BMKG ',fontsize=3,color='gray',horizontalalignment='right') im = Image.open('stmkg50.png') im = np.array(im).astype(float) / 255 af.figimage(im, 820, 900) ringanlegend = mpatches.Patch(color='lightgreen', label='hujan ringan') sedanglegend = mpatches.Patch(color='green', label='hujan sedang') lebatlegend = mpatches.Patch(color='yellow', label='hujan lebat') extlegend = mpatches.Patch(color='red', label='hujan extrim') plt.legend(handles=[ringanlegend,sedanglegend,lebatlegend,extlegend], loc=4, fontsize = '4') af.savefig(fimage,dpi=500,bbox_inches='tight',pad_inches=0.05) plt.close() print 'Save Image : ',fimage
def hammer_plot(NetworkF,Theta,Phi,theta,phi): from mpl_toolkits.basemap import Basemap, shiftgrid fig,ax = plt.subplots() RAD = 180/np.pi m = Basemap(projection='hammer',lon_0=0,resolution='c') Phi, NetworkF = shiftgrid(180,Phi,NetworkF) m.contourf(Phi*RAD, Theta*RAD, NetworkF, 100, cmap=plt.cm.jet,latlon=True) plt.plot(phi,theta,'go',markersize=5) plt.xlabel(r'$\phi$'' (radians)') plt.ylabel(r'$\theta$'' (radians)') plt.savefig('hammer.png') return plt.show()
def plot_avg_snfall_maps(b: Basemap, xx, yy, hles_snfall, total_snfall, cmap=None, bnorm: BoundaryNorm=None, label=""): fig = plt.figure() gs = GridSpec(1, 3, wspace=0.01) h = hles_snfall.mean(axis=0) t = total_snfall.mean(axis=0) axes_list = [] # hles ax = fig.add_subplot(gs[0, 0]) cs = b.contourf(xx, yy, h, bnorm.boundaries, cmap=cmap, norm=bnorm, extend="max") ax.set_title("HLES (cm)") cb = b.colorbar(cs, location="bottom") cb.ax.set_xticklabels(cb.ax.get_xticklabels(), rotation=45) axes_list.append(ax) # total ax = fig.add_subplot(gs[0, 1]) cs = b.contourf(xx, yy, t, bnorm.boundaries, cmap=cmap, norm=bnorm, extend="max") ax.set_title("Snowfall (cm)") cb = b.colorbar(cs, location="bottom") cb.ax.set_visible(False) axes_list.append(ax) # hles percentage ax = fig.add_subplot(gs[0, 2]) clevs = np.arange(0, 100, 10) cs = b.contourf(xx, yy, h / t * 100, levels=clevs, cmap=get_with_white_added("gist_ncar_r", white_end=0.1, ncolors_out=len(clevs) - 1)) ax.set_title("HLES fraction (%)") cb = b.colorbar(cs, location="bottom") axes_list.append(ax) # plot coastlines for ax in axes_list: b.drawcoastlines(ax=ax, linewidth=0.5) fig.savefig(str(img_dir / f"mean_hles_total_snfall_{label}.png"), bbox_inches="tight", dpi=250) plt.close(fig)
def setMap(lats, lons, data, showstations): x = np.array(lons) y = np.array(lats) z = np.array(data) # corners of the map lon_min = np.min(x) - 1 lon_max = np.max(x) + 1 lat_min = np.min(y) - 1 lat_max = np.max(y) + 1 if individual: data_min = np.min(z) data_max = np.max(z) else: data_min = data_min_fix data_max = data_max_fix # general map m = Basemap( projection="merc", llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, resolution=map_res, area_thresh=100, ) m.drawcoastlines() m.drawstates() m.drawcountries() if not showstations: y_inc = (lat_max - lat_min) / grd_res x_inc = (lon_max - lon_min) / grd_res y_steps = np.linspace(lat_min, lat_max + grd_res, y_inc) x_steps = np.linspace(lon_min, lon_max + grd_res, x_inc) x_steps, y_steps = np.meshgrid(x_steps, y_steps) zgrd = matplotlib.mlab.griddata(x, y, z, x_steps, y_steps) xgrd, ygrd = m.makegrid(zgrd.shape[1], zgrd.shape[0]) # xgrd,ygrd= np.meshgrid(x_steps,y_steps) # zgrd = scipy.interpolate.griddata((x, y), z, (xgrd, ygrd), method='nearest') xgrd, ygrd = m(xgrd, ygrd) m.contourf(xgrd, ygrd, zgrd, cmap=plt.cm.hot_r, vmin=data_min, vmax=data_max) else: # measurement stations xpts, ypts = m(lons, lats) m.plot(xpts, ypts, "bo")
def render_differences_map(diffs, lats, lons, subtit = '', fname = None): fig = plt.figure(figsize=(20,16)) lat_ndx = np.argsort(lats) lats = lats[lat_ndx] m = Basemap(projection = 'merc', llcrnrlat = lats[0], urcrnrlat = lats[-1], llcrnrlon = lons[0], urcrnrlon = lons[-1], resolution = 'i') m.fillcontinents(color = "#ECF0F3", lake_color = "#A9E5FF", zorder = 0) m.drawmapboundary(fill_color = "#A9E5FF") m.drawcoastlines(linewidth = 2, color = "#333333") m.drawcountries(linewidth = 1.5, color = "#333333") m.drawparallels(np.arange(20, 80, 10), linewidth = 1.2, labels = [1,0,0,0], color = "#222222", size = 30) m.drawmeridians(np.arange(-40, 80, 10), linewidth = 1.2, labels = [0,0,0,1], color = "#222222", size = 30) x, y = m(*np.meshgrid(lons, lats)) if not MEANS: levs = np.arange(0.,1.,0.05) # 0.5 - 6 / 0.25 else: levs = np.arange(0.01,8.025,0.025) # 0 - 4 / 0.2 if ECA: cs = m.contourf(x, y, diffs, levels = levs, cmap = plt.get_cmap('CMRmap')) # m.contourf(x, y, perc, 1, colors = "none", hatches = [None, '///']) # m.contour(x, y, perc, 1, linewidths = 2, colors = "#030303" ) else: cs = m.contourf(x, y, diffs[::-1, :], levels = levs, cmap = plt.get_cmap('CMRmap')) # cbar = m.colorbar(cs, location = 'right', size = "5%", pad = "10%") cbar = plt.colorbar(cs, pad = 0.07, shrink = 0.8, fraction = 0.05, ticks = np.arange(0,9,1)) cbar.ax.tick_params(labelsize = 30) if MEANS: cbar.set_label("TEMPERATURE DIFFERENCE [$^{\circ}$C]", size = 38, labelpad = 30) else: cbar.set_label("differecnce in standard deviation [$^{\circ}$C]", size = 23) if SIGN: if MEANS: title = ("%s reanalysis - differences in cond. mean SATA DJF \n %d %s surrogates" % ('ECA&D' if ECA else 'ERA-40', num_surr, SURR_TYPE)) else: title = ("%s reanalysis - differences of conditional standard deviation \n %d %s surrogates" % ('ECA & D' if ECA else 'ERA-40', num_surr, SURR_TYPE)) else: if MEANS: # title = ("%s reanalysis - differences in cond. mean SATA \n DATA" % ('ECA&D' if ECA else 'ERA-40')) # title = ("%s reanalysis - scaled mean of bins \n SAT amplitude - DATA" % ('ECA & D' if ECA else 'ERA-40')) title = "SATA SD -- DJF" else: title = ("%s reanalysis - differences of conditional standard deviation \n MF SURROGATE STD" % ('ECA & D' if ECA else 'ERA-40')) title += subtit # plt.title("EFFECT ON WINTER MEAN TEMPERATURE", size = 35) if fname != None: plt.savefig(fname, bbox_inches = 'tight') else: plt.show()
def plot(data,title=' ',projection='cyl',file_name=datetime.datetime.now().isoformat(),show=1,cblabel='$\mu g/ m^3$',cmap=plt.cm.CMRmap_r,clevs=np.zeros(1),return_fig=0,dpi=300,lon=0,lat=0,colorbar_format_sci=0,saving_format='svg',scatter_points=0,f_size=20): fig=plt.figure(figsize=(20, 12)) m = fig.add_subplot(1,1,1) if projection=='merc': m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,\ llcrnrlon=-180,urcrnrlon=180,lat_ts=20) else: m = Basemap(projection=projection,lon_0=0) m.drawcoastlines() if isinstance(lon, int): lon=readsav('/nfs/a107/eejvt/IDL_CODE/glon.sav') if isinstance(lat, int): lat=readsav('/nfs/a107/eejvt/IDL_CODE/glat.sav') X,Y=np.meshgrid(lon.glon,lat.glat) else: if lon.ndim==1: X,Y=np.meshgrid(lon,lat) else: X=np.copy(lon) Y=np.copy(lat) if type(clevs) is list: cs=m.contourf(X,Y,data,clevs,latlon=True,cmap=cmap,norm= colors.BoundaryNorm(clevs, 256)) if colorbar_format_sci: def fmt(x, pos): a, b = '{:.1e}'.format(x).split('e') b = int(b) return r'${} \times 10^{{{}}}$'.format(a, b) cb = m.colorbar(cs,"right",format=ticker.FuncFormatter(fmt),ticks=clevs) else: cb = m.colorbar(cs,format='%.2e',ticks=clevs) else: cs=m.contourf(X,Y,data,15,latlon=True,cmap=cmap) cb = m.colorbar(cs) if not isinstance(scatter_points,int): m.scatter(scatter_points[:,0],scatter_points[:,100]) cb.set_label(cblabel,fontsize=f_size) cb.ax.tick_params(labelsize=f_size) plt.title(title,fontsize=f_size) if os.path.isdir("PLOTS/"): plt.savefig('PLOTS/'+file_name+'.'+saving_format,format=saving_format,dpi=dpi, bbox_inches='tight') plt.savefig('PLOTS/'+file_name+'.svg',format='svg', bbox_inches='tight') else: plt.savefig(file_name+'.'+saving_format,format=saving_format,dpi=dpi, bbox_inches='tight') plt.savefig(file_name+'.svg',format='svg', bbox_inches='tight') if show: plt.show() if return_fig: return fig
def plotWindfield(xGrid, yGrid, speed, title='Cyclone wind field', xlabel='Longitude', ylabel='Latitude', infostring='', fileName=None, i=0): """ Plot the wind field for a given grid. xGrid, yGrid and speed are arrays of the same size. (xGrid and yGrid are typically generated by [xGrid,yGrid] = meshgrid(lon,lat)) """ vMax = speed.max() infostring = "%s \nMaximum speed: %2.1f m/s" % (infostring, vMax) pylab.clf() dl = 5. llLon = min(xGrid[0, :]) urLon = max(xGrid[0, :]) llLat = min(yGrid[:, 0]) urLat = max(yGrid[:, 0]) meridians = np.arange(dl*floor(llLon/dl), dl*ceil(urLon/dl), dl) parallels = np.arange(dl*floor(llLat/dl), dl*ceil(urLat/dl), dl) levels = np.arange(0, 101, 5) m = Basemap(projection='cyl', resolution='i', llcrnrlon=llLon, urcrnrlon=urLon, llcrnrlat=llLat, urcrnrlat=urLat) #cs = m.contour(xGrid,yGrid,speed,array(arange(0,90,5))) m.contourf(xGrid, yGrid, speed, levels) pylab.colorbar() pylab.title(title) #pylab.figtext(0.175, 0.86, infostring, color='b', # horizontalalignment='left', # verticalalignment='top', fontsize=10) m.drawcoastlines() m.drawparallels(parallels, labels=[1, 0, 0, 1], fontsize=9) m.drawmeridians(meridians, labels=[1, 0, 0, 1], fontsize=9) """ if cfgPlot['Basemap.fill_continents']: m.fillcontinents() """ pylab.grid(True) if fileName is not None: pylab.savefig(fileName)
m.drawcountries() #m.drawrivers() #m.drawcounties() # parallels = np.arange(22,27,1.) # m.drawparallels(parallels,labels=[1,0,0,0]) # draw meridians # meridians = np.arange(108.,118.,1.) # m.drawmeridians(meridians,labels=[0,0,0,1]) x, y = m(lon, lat) #%% # timenow = filepath[-8:-5]+'%02d' % int(timelist[time]%60) timenow = timestr temp = dbz[a, level, ...].copy() pm = m.contourf(x, y, temp, cmap=scmap, levels=np.arange(10, 76, 5)) plt.title('REF1km at ' + timenow, size=24) m.colorbar(mappable=pm) plt.tight_layout() plt.savefig(pathout + '/sm_ref1km_' + timenow, dpi=600) plt.show() plt.close() #if __name__ == '__main__': # main() #else: # pass
# x, y = m(lon2d, lat2d) m.drawmapboundary(fill_color='white',color='dimgrey',linewidth=0.7) m.drawcoastlines(color='darkgrey',linewidth=0.1) m.fillcontinents(color='dimgray') if i < 6: limit = limsit barlim = barlimsit extendq = 'min' else: limit = limsic barlim = barlimsic extendq = 'max' cs = m.contourf(lons2,lats2,var,limit,extend=extendq,latlon=True) cmap = cmocean.cm.dense_r cs.set_cmap(cmap) ### Add experiment text to subplot ax1.annotate(r'\textbf{%s}' % months[i],xy=(0,0),xytext=(0.865,0.90), textcoords='axes fraction',color='k',fontsize=11, rotation=320,ha='center',va='center') if i == 5: ### Add thickness colorbar cbar_ax = fig.add_axes([0.412,0.529,0.2,0.02]) cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal', extend='min',extendfrac=0.07,drawedges=False) cbar.set_label(r'\textbf{$\Delta$SIT [m]}',fontsize=9,color='dimgray',
m.drawmapboundary(fill_color='white') m.drawcoastlines(color='k', linewidth=0.2) parallels = np.arange(50, 90, 10) meridians = np.arange(-180, 180, 30) # m.drawparallels(parallels,labels=[False,False,False,False], # linewidth=0.35,color='k',fontsize=1) # m.drawmeridians(meridians,labels=[False,False,False,False], # linewidth=0.35,color='k',fontsize=1) m.drawlsmask(land_color='darkgrey', ocean_color='mintcream') ### Adjust maximum limits values = np.arange(0, 1.1, 0.1) ### Plot filled contours cs = m.contourf(x, y, var, values, extend='max') cs1 = m.contour(x, y, var, values, linewidths=0.2, colors='darkgrey', linestyles='-') ### Set colormap # cmap = ncm.cmap('temp_19lev') cs.set_cmap('cubehelix_r') cbar_ax = fig.add_axes([0.313, 0.13, 0.4, 0.03]) cbar = fig.colorbar(cs, cax=cbar_ax,
parallels = np.arange(0., 90, delat) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) # draw meridians delon = 10. meridians = np.arange(180., 360., delon) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) ny = data.shape[0] nx = data.shape[1] lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) # compute map proj coordinates. # draw filled contours. clevs = [ 0, 1, 2.5, 5, 7.5, 10, 15, 20, 30, 40, 50, 70, 100, 150, 200, 250, 300, 400, 500, 600, 750 ] cs = m.contourf(x, y, data, clevs, cmap=cm.s3pcpn) # new axis for colorbar. pos = ax.get_position() l, b, w, h = pos.bounds cax = plt.axes([l + w + 0.025, b, 0.025, h]) # setup colorbar axes # draw colorbar. cb = plt.colorbar(cs, cax, format='%g', ticks=clevs, drawedges=False) plt.axes(ax) # make the original axes current again # plot title plt.title(plottitle + '- contourf', fontsize=10) plt.subplot(212) ax = plt.gca() # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines() m.drawstates()
#tmax = np.loadtxt('C:/Users/Yating/Desktop/output/2096-2100meanA_out.txt') tmax = np.transpose(tmax) fig=plt.figure(figsize=(6,4)) m = Basemap(projection='merc',llcrnrlon=-78.5079,llcrnrlat=38.00905,urcrnrlon=-75.6454,urcrnrlat=39.91155,resolution='h') ny = tmax.shape[0]; nx = tmax.shape[1] lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) mdata = maskoceans(lons, lats, tmax) m.drawcoastlines(linewidth=0.4) m.drawcounties(linewidth=0.2) parallels = np.arange(0.,90,0.5) m.drawparallels(parallels,labels=[1,0,0,0],dashes=[2,900],fontsize=10,linewidth=0.4) meridians = np.arange(180.,360.,1) m.drawmeridians(meridians,labels=[0,0,0,1],dashes=[2,900],fontsize=10,linewidth=0.4) cMAP = ListedColormap(['#00bfff','#00bfff','#00ffff','#00ffff','#009933','#33cc33','#33cc33','#33cc33','#c6ff1a','#ffff00','#ffff00','#ffbf00','#ffbf00','#ff8000','#ff8000','#ff4000']) cMAP.set_over('#cc0000') cMAP.set_under('#0080ff') levels = [32,33,34,35,36,37,38,39,40,41] cs = m.contourf(x, y, mdata, levels, cmap=cMAP, extend="both") cbar = m.colorbar(cs, "right", size="5%", pad='2%') cbar.set_label('Amplitude ($^\circ$C)') plt.show()
m.drawcoastlines(color='darkgrey', linewidth=0.27) elif any([r == 2, r == 5]): m.drawcoastlines(color='darkgrey', linewidth=0.27) var, lons_cyclic = addcyclic(var, lon1) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat1) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='dimgrey', color='dimgray', linewidth=0.7) circle.set_clip_on(False) if any([r == 0, r == 1, r == 3, r == 4]): cs1 = m.contourf(x, y, var, limits[r], extend='max') cs1.set_cmap(cmap[r]) elif any([r == 2, r == 5]): cs2 = m.contourf(x, y, var, limits[r], extend='both') cs2.set_cmap(cmap[r]) if any([r == 0, r == 3]): ax1.annotate(r'\textbf{%s}' % labely[r], xy=(0, 0), xytext=(-0.07, 0.5), textcoords='axes fraction', color='k', fontsize=10, rotation=90, ha='center', va='center')
var = var.reshape(nt, nlat, nlon) # Read time dsetFile = 'fort.41' dset = np.loadtxt('%s/%s' % (casePath, dsetFile)) timeND = dset[:, 1] nt = timeND.shape[0] / nlon time = timeND.reshape(nt, nlon)[:, 0] * timeDim # Plot field statistics nlev = 20 fig = plt.figure() field = hc.mean(0) vmax = np.max(field) vmin = np.min(field) levels = np.linspace(vmin, vmax, nlev) cs = map.contourf(X, Y, field, levels, cmap=cm.RdBu_r) map.drawcoastlines() map.drawparallels(np.arange(0, 81., 10.)) map.drawmeridians(np.arange(-180., 181., 30.)) plt.title('Mean of %s' % fieldName) plt.colorbar(orientation='horizontal') fig.savefig('%s/%sMean_%s.png' % (pltDir, fieldFile, postfix), bbox_inches='tight') fig = plt.figure() field = var.std(0) vmax = np.max(field) vmin = np.min(field) levels = np.linspace(vmin, vmax, nlev) cs = map.contourf(X, Y, field, levels, cmap=cm.RdBu_r) map.drawcoastlines()
swot_segment_lat.append(swot_lat[idx_end:-1]) swot_segment_lon.append(swot_lon[idx_end:-1]) ## ---- plot ---- ## fig = plt.figure(1) #m = Basemap(projection='ortho',lon_0=lon_0,lat_0=lat_0,resolution=None) m = Basemap(projection='merc', lon_0=lon_0, lat_0=lat_0, llcrnrlon=lonLims[0], llcrnrlat=latLims[0], urcrnrlon=lonLims[1], urcrnrlat=latLims[1], resolution='l') x, y = m(*np.meshgrid(lon, lat)) c = m.contourf(x, y, np.flipud(Z), v, cmap=plt.cm.PuBu_r, extend="min") #c = m.contourf(x, y, np.flipud(Z), v, cmap=plt.cm.PuRd_r, extend="min"); m.fillcontinents(color='grey') m.drawparallels(np.arange(10, 70, 10), labels=[1, 0, 0, 0], fontsize=12, fontweight='bold') m.drawmeridians(np.arange(-80, 5, 10), labels=[0, 0, 0, 1], fontsize=12, fontweight='bold') cb = plt.colorbar(c) for l in cb.ax.yaxis.get_ticklabels(): l.set_weight("bold") l.set_fontsize(10) cb.set_label('Depth (m)', fontsize=13, fontweight='bold')
def visualise_orientational_distribution(self, axes_to_return=None, cbar=True): """ Creates a plot of the orientational distribution of the unit cells. :param axes_to_return: if None, print to screen, otherwise, requires 3 axes objects, and will return them. :param cbar: boolean to specify if a color bar should be used. """ import matplotlib.pyplot as plt import matplotlib.patheffects as patheffects from mpl_toolkits.basemap import Basemap import scipy.ndimage as ndi def cart2sph(x, y, z): # cctbx (+z to source, y to ceiling) to # lab frame (+x to source, z to ceiling) z, x, y = x, y, z dxy = np.sqrt(x**2 + y**2) r = np.sqrt(dxy**2 + z**2) theta = np.arctan2(y, x) phi = np.arctan2(z, dxy) # angle of the z axis relative to xy plane theta, phi = np.rad2deg([theta, phi]) return theta % 360, phi, r def xy_lat_lon_from_orientation(orientation_array, axis_id): logger.debug("axis_id: {}".format(axis_id)) dist = math.sqrt(orientation_array[axis_id][0]**2 + orientation_array[axis_id][1]**2 + orientation_array[axis_id][2]**2) flon, flat, bla = cart2sph(orientation_array[axis_id][0] / dist, orientation_array[axis_id][1] / dist, orientation_array[axis_id][2] / dist) x, y = euler_map(flon, flat) return x, y, flon, flat orientations = [ flex.vec3_double(flex.double(image.orientation.direct_matrix())) for image in self.members ] space_groups = [ image.orientation.unit_cell().lattice_symmetry_group() for image in self.members ] # Now do all the plotting if axes_to_return is None: plt.figure(figsize=(10, 14)) axes_to_return = [ plt.subplot2grid((3, 1), (0, 0)), plt.subplot2grid((3, 1), (1, 0)), plt.subplot2grid((3, 1), (2, 0)) ] show_image = True else: assert len(axes_to_return) == 3, "If using axes option, must hand" \ " 3 axes to function." show_image = False axis_ids = [0, 1, 2] labels = ["a", "b", "c"] for ax, axis_id, label in zip(axes_to_return, axis_ids, labels): # Lists of x,y,lat,long for the master orientation, and for all # symmetry mates. x_coords = [] y_coords = [] lon = [] lat = [] sym_x_coords = [] sym_y_coords = [] sym_lon = [] sym_lat = [] euler_map = Basemap(projection='eck4', lon_0=0, ax=ax) for orientation, point_group_type in zip(orientations, space_groups): # Get position of main spots. main_x, main_y, main_lon, main_lat \ = xy_lat_lon_from_orientation(list(orientation), axis_id) x_coords.append(main_x) y_coords.append(main_y) lon.append(main_lon) lat.append(main_lat) # Get position of symetry mates symmetry_operations = list(point_group_type.smx())[1:] for mx in symmetry_operations: rotated_orientation = list(mx.r().as_double() * orientation) # <-- # should make sense if orientation was a vector, not clear what is # going on since orientation is a matrix. Or, make some test cases # with 'orientation' and see if the behave as desired. sym_x, sym_y, sym_lo, sym_la \ = xy_lat_lon_from_orientation(rotated_orientation, axis_id) #assert (sym_x, sym_y) != (main_x, main_y) sym_x_coords.append(sym_x) sym_y_coords.append(sym_y) sym_lon.append(sym_lo) sym_lat.append(sym_la) # Plot each image as a yellow sphere logger.debug(len(x_coords)) euler_map.plot(x_coords, y_coords, 'oy', markersize=4, markeredgewidth=0.5) # Plot the symetry mates as black crosses #euler_map.plot(sym_x_coords, sym_y_coords, 'kx') # Use a histogram to bin the data in lattitude/longitude space, smooth it, # then plot this as a contourmap. This is for all the symetry-related # copies #density_hist = np.histogram2d(lat + sym_lat, lon + sym_lon, # bins=[range(-90, 91), range(0, 361)]) # No symmetry mates until we can verify what the cctbx libs are doing density_hist = np.histogram2d( lat, lon, bins=[list(range(-90, 91)), list(range(0, 361))]) smoothed = ndi.gaussian_filter(density_hist[0], (15, 15), mode='wrap') local_intensity = [] x_for_plot = [] y_for_plot = [] for _lat in range(0, 180): for _lon in range(0, 360): _x, _y = euler_map(density_hist[2][_lon], density_hist[1][_lat]) x_for_plot.append(_x) y_for_plot.append(_y) local_intensity.append(smoothed[_lat, _lon]) cs = euler_map.contourf(np.array(x_for_plot), np.array(y_for_plot), np.array(local_intensity), tri=True) # Pretty up graph if cbar: _cbar = plt.colorbar(cs, ax=ax) _cbar.ax.set_ylabel('spot density [AU]') middle = euler_map(0, 0) path_effect = [patheffects.withStroke(linewidth=3, foreground="w")] euler_map.plot(middle[0], middle[1], 'o', markersize=10, mfc='none') euler_map.plot(middle[0], middle[1], 'x', markersize=8) ax.annotate("beam", xy=(0.52, 0.52), xycoords='axes fraction', size='medium', path_effects=path_effect) euler_map.drawmeridians(np.arange(0, 360, 60), labels=[0, 0, 1, 0], fontsize=10) euler_map.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0], fontsize=10) ax.annotate(label, xy=(-0.05, 0.9), xycoords='axes fraction', size='x-large', weight='demi') if show_image: plt.show() return axes_to_return
#Plot #%% cmin = 0; cmax = 20; cint = 0.5; clevs = np.round(np.arange(cmin,cmax,cint),2) nlevs = len(clevs) - 1; cmap = plt.get_cmap(name='GnBu',lut=nlevs) plt.figure(figsize=(10,6)) xlim = np.array([-30,20]); ylim = np.array([40,70]) m = Basemap(projection='cyl',lon_0=np.mean(xlim),lat_0=np.mean(ylim),llcrnrlat=ylim[0],urcrnrlat=ylim[1],llcrnrlon=xlim[0],urcrnrlon=xlim[1],resolution='i') m.drawcoastlines(); m.drawstates(), m.drawcountries() cs = m.contourf(lon2,lat2,precip_nan.T,clevs,cmap='GnBu',extend='both') cbar = m.colorbar(cs,size='2%') cbar.ax.set_ylabel('mm',weight='bold',size=16) cticks = [] for i in clevs: cticks.append(int(i)) if i.is_integer() else cticks.append(i) cbar.set_ticks(clevs[::4]) cbar.set_ticklabels(cticks[::4]) for i in cbar.ax.yaxis.get_ticklabels(): i.set_family('Calibri') i.set_size(14) plt.title('GPM 1.5 Hour Precipitation',name='Calibri',size=16, weight = 'bold') plt.show(block=False)
xm, ym = map(xc,yc) parallels = np.round(np.arange(lat[0],lat[-1]-10,10)) meridians = np.round(np.linspace(lon[0], lon[-1],3)) # SWOT Calval tracks data = np.loadtxt('../data/ephem_calval_june2015_sph.txt') lon_track = data[:,1] lat_track = data[:,2] xs, ys = map(360-125.4, 35.4) xt, yt = map(lon_track,lat_track) ######################################################## Fraction of days of wind seas ######################################################## cmap = 'inferno' lin = np.linspace(0,.5,10) cs = map.contourf(xm,ym, monthly_number['mean'][-1], lin, cmap=cmap) fig=plt.figure(figsize=(14,11), dpi=100) for i in np.arange(-1,11): ax = fig.add_subplot(3,4,i+2) cnt = map.contourf(xm,ym, monthly_number['mean'][i], lin, cmap=cmap) map.plot(xt , yt, '--', color='.8', linewidth = 1.5) map.plot(xs,ys, 'Dr', markersize=12, mew=2, markeredgecolor='black') map.fillcontinents(color='0.5', lake_color='0.5') map.drawparallels(parallels,linewidth=.5,labels=[0,0,0,0],color = '0.5') map.drawmeridians(meridians,linewidth=.5,labels=[0,0,0,0],color = '0.6') if i in [-1,3,7]: map.drawparallels(parallels,linewidth=.5,labels=[1,0,0,0],fontsize=22, color = '0.5') if i in [7,8,9,10]: map.drawmeridians(meridians,linewidth=.5,labels=[0,0,0,1],fontsize=22, color = '0.6') plt.title(mon[i], fontsize=22) plt.tight_layout()
indx = np.where(timevec == (d.toordinal()/11))[0][0]; [lon,lat_tband] = np.meshgrid(lon,lat_tband); X,Y = m(lon,lat_tband); prcpsfc = datafilePRCP.variables['precip'][indx,:,:]; clevs = [0,0.1,0.25,0.5,0.75,1,1.5,2.0,3.0,4.0,5.0,7.0,10.0,15.0,20.0,25.0,30.0] import matplotlib.colors cm_prcp = ((254,254,254),(9,45,187),(18,125,202),(5,170,158),(0,237,41),(180,225,45),(240,242,51),(248,186,47),(215,157,34),(246,120,40),(248,40,25),(216,67,156),(213,69,240),(252,137,174),(254,254,254)); cm_prcp = np.divide(cm_prcp,255.0); cm_prcp = tuple(cm_prcp); cmap_prcp = matplotlib.colors.ListedColormap(cm_prcp,'cmap_prcp'); h2 = m.contourf(X,Y,np.squeeze(prcpsfc[lat_trop,:]),32,cmap=cmap_prcp) #cm.s3pcpn) cbar = m.colorbar(h2,ticks=np.arange(0,35,5),location='right',pad="2%") cbar.set_label('mm') plt.title('January 2014 Monthly Average Surface Precipitation, Tropical Band',fontsize=10) ## Others # Plotting barbs, masking fields (land, ocean) and alpha-transparency plt.figure(num=4,figsize=(6,6)) m = Basemap(llcrnrlon=-95.,llcrnrlat=20.,urcrnrlon=-80.,urcrnrlat=35.,projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60.,resolution ='l',area_thresh=1000.) m.drawcoastlines() m.drawcountries() m.drawparallels(np.arange(20,36,2),labels=[1,0,0,0]) m.drawmeridians(np.arange(-95,-78,2),labels=[0,0,0,1])
#levs = np.power(10, lev_exp) levs = [30, 32, 34, 36, 38, 40, 50, 60, 100, 500000] #f len(levs) < len(cmap): # cmap = cmap[0:len(levs),:] cm = mpl.colors.ListedColormap(cmap) # First create a linear colormap map_nonlin = nlcmap(cm, levs) # Adjust colormap to be non-linear #levs=[30,500000,10e10] #levs=[30] #levs=[10,100,200,300,500,600,1000,50000] #cmap = plt.get_cmap('Greys_r') #norm = colors.BoundaryNorm(levs, ncolors=cmap.N, clip=True) #cs = map.pcolor(x,y,data,cmap=cmap,norm=norm) cs = map.contourf(x, y, data, levs, cmap=map_nonlin, extend="both") # draw blue marble image in background. # (downsample the image by 50% for speed) #map.bluemarble(scale=0.5) bar = plt.colorbar(cs) # Modifies colorbar ticks to match flevs and adds additional labels (where needed) tick_locs = levs tick_labels = levs bar.locator = mpltick.FixedLocator(tick_locs) bar.formatter = mpltick.FixedFormatter(tick_labels) bar.update_ticks() plt.show() figure = plt.gcf() figure.set_size_inches(8, 6)
dh_rm = np.sum(np.sum(dh_rm,-1),-1)/np.sum(area*region_mask) #%% clev = np.arange(-190,191,20) m = Basemap(projection='mill',\ fix_aspect=True,\ llcrnrlat=-90,urcrnrlat=90,llcrnrlon=-180,urcrnrlon=180) latt,lont,nett = pp.grid_for_map(lat,lon,net) latt,lont,Totdivt = pp.grid_for_map(lat,lon,Totdiv) latt,lont,MMCdivt = pp.grid_for_map(lat,lon,MMCdiv) latt,lont,Trdivt = pp.grid_for_map(lat,lon,Trdiv) latt,lont,uvdht = pp.grid_for_map(lat,lon,uvdh) latt,lont,wdht = pp.grid_for_map(lat,lon,wdh) latt,lont,whbott = pp.grid_for_map(lat,lon,whbot) latt,lont,whtopt = pp.grid_for_map(lat,lon,whtop) lons,lats = np.meshgrid(lont,latt) x,y = m(lons,lats) cmap = plt.cm.RdYlBu #%% plt.figure() m.drawcoastlines() m.drawcountries() m.contourf(x,y,np.mean(-nett,0),clev,cmap=cmap,extend='both') cb = m.colorbar(location='bottom',size='5%',pad='8%') plt.tight_layout() plt.figure() m.drawcoastlines() m.drawcountries() m.contourf(x,y,np.mean(Totdivt,0),clev,cmap=cmap,extend='both') cb = m.colorbar(location='bottom',size='5%',pad='8%') plt.tight_layout()
dashes=[1, 1], linewidth=1.0, color='0.5', fontsize='x-large', fontname='Times') m.drawmeridians(np.arange(0., 360., 60.), labels=[1, 0, 0, 1], dashes=[1, 1], linewidth=1.0, color='0.5', fontsize='x-large', fontname='Times') #PLOT ABSOLUTE #cs = m.contourf(X2,Y2,mdata,levels,cmap=cmap,extend='both') cs = m.contourf(X2, Y2, mdata, levels, cmap=cmap) vmin, vmax = (-0.01251 * max_val, max_val) plt.tight_layout() #cbar = m.colorbar(cs,location='bottom',pad='10%',ticks=np.linspace(vmin,vmax,7),format='%.1f') ticks = [ 0., 0.0251 * max_val, .1 * max_val, .3 * max_val, .5 * max_val, .7 * max_val, .8 * max_val, 1. * max_val ] cbar = m.colorbar(cs, location='bottom', pad='10%', ticks=ticks, format='%.2f') #cbar.ax.text(0.98,1,r'$\times$10$^{-3}$',va='bottom',ha='right',size=78) #cbar.ax.get_yaxis().labelpad = 60
def plot_radar_elegant(self,imageIn,ruta=None,figsize=(12,12),extra_lat=-0.2, extra_long=-0.2,lines_spaces=0.4,mask_value=0.0,xy=None, xyColor='red',colorbar=True, texto=None, **kwargs): '\n'\ 'Descripcion: Toma cualquier raster con valores del radar\n'\ ' y hace un plot de este de forma elegante\n'\ '\n'\ 'Parametros\n'\ '----------\n'\ 'imageIn : Imagen con valores o binaria del radar\n'\ 'ruta : si es especificada guarda la imagen.\n'\ 'figsize : Tamano de la figura.\n'\ '\n'\ 'Retornos\n'\ '----------\n'\ 'Plotea la figura y si ruta <> None, la guarda.\n'\ '\n'\ 'Ejemplo\n'\ '----------\n'\ '.\n'\ #Obtiene las latitudes y longitudes longs=np.array([radar_f90.xll+(i+0.5)*radar_f90.dx for i in range(radar_f90.ncols)]) lats=np.array([radar_f90.yll+(i+0.5)*radar_f90.dx for i in range(radar_f90.nrows)]) X,Y=np.meshgrid(longs,lats) Y=Y[::-1] #Cambia el tamano de la figura si tiene que hacerlo if figsize<>None: fig=pl.figure(figsize=figsize) #Genera el lugar de ploteo con el Basemap m = Basemap(projection='merc', llcrnrlat=lats.min()-extra_lat, urcrnrlat=lats.max()+extra_lat, llcrnrlon=longs.min()-extra_long, urcrnrlon=longs.max()+extra_long, resolution='c') #Grafica las lineas horizontales y verticales m.drawparallels(np.arange(lats.min(), lats.max(),lines_spaces), labels=[1,0,0,0], fmt="%.2f", rotation='vertical', xoffset=0.1, linewidth=0.1) m.drawmeridians(np.arange(longs.min(), longs.max(),lines_spaces), labels=[0,0,1,0], fmt="%.2f", yoffset=0.1, linewidth=0.1) #Cambia zeros por nana if mask_value<>None: imageIn=np.ma.array(imageIn,mask=imageIn==mask_value) #Genera el mapa demX,demY=m(X,Y) cs=m.contourf(demX, demY, imageIn, 100, **kwargs) if colorbar: cbar = m.colorbar(cs,location='bottom',pad="5%") #dibuja los circulos XY = [] for i in [30,60,90,120,250]: x,y = self.draw_circle(m,-75.5276,6.1937,i,c='k',lw=0.5) XY.append([x,y]) #Si hay coordenadas de algo las dibuja if xy<>None: xc,yc=m(xy[0],xy[1]) m.plot(xc,yc,color=xyColor, #s=30, linewidth=1,) #edgecolor='black') if texto<>None: pl.annotate(texto, xy=(0.1, 0.9), xycoords='axes fraction', size=16) if ruta<>None: pl.savefig(ruta,bbox_inches='tight') pl.show()
map.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=6, linewidth=0.5, dashes=[2, 2]) map.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=6, linewidth=0.5, dashes=[2, 2]) map.drawcoastlines(linewidth=0.5) map.drawmapboundary(linewidth=0.5) bounds = np.arange(0, 4000, 200) ticks = np.arange(0, 4000, 200) contour = map.contourf(lon, lat, topo[:, :], levels=bounds, cmap='terrain', extend='max') cbar = map.colorbar(contour, ticks=ticks, pad='5%') cbar.set_label('m', rotation=0, labelpad=8, fontsize=7) cbar.ax.tick_params(labelsize=6) plt.title(var[i] + ' Km', fontsize=12, y=1.02) plt.savefig('topo_' + var[i] + 'km' + '.png', bbox_inches='tight', dpi=300) plt.close()
X,Y = np.meshgrid(LON,LAT) steps = sum(STEPS) otime = [] for t in TIME: for i in t: otime.append(i) s_time = ti.time() print("after reading data --- %s seconds ---" % ( s_time)) outname = year+month+day+'_'+value if movie: start = animeData[0] img = frame.contourf(X,Y, start,100) title = ax.text(0.2,1.05, "", bbox={'facecolor':'w', 'alpha':0.5, 'pad':5}, transform=ax.transAxes, ha="center") minmax = ax.text(1.,1.05, "", bbox={'facecolor':'w', 'alpha':0.5, 'pad':5}, transform=ax.transAxes, ha="center") locVal = ax.text(xpt_site + 3*offset, ypt_site - 2*offset, 'val %s' % (0.), color='red', fontsize=12) ani = FuncAnimation(fig, update, frames=np.arange(steps), fargs=(animeData, img, otime, X, Y, value, s_time, site, lon_site, lat_site),
# latitude weights are applied before the computation of EOFs. solver = Eof(sst, weights='coslat') # Retrieve the leading EOF, expressed as the correlation between the leading # PC time series and the input SST anomalies at each grid point, and the # leading PC time series itself. eof1 = solver.eofsAsCorrelation(neofs=1) pc1 = solver.pcs(npcs=1, pcscaling=1) # Plot the leading EOF expressed as correlation in the Pacific domain. m = Basemap(projection='cyl', llcrnrlon=120, llcrnrlat=-20, urcrnrlon=260, urcrnrlat=60) lons, lats = eof1.getLongitude()[:], eof1.getLatitude()[:] x, y = m(*np.meshgrid(lons, lats)) clevs = np.linspace(-1, 1, 11) m.contourf(x, y, eof1(squeeze=True), clevs, cmap=plt.cm.RdBu_r) m.drawcoastlines() m.drawparallels([-20, 0, 20, 40, 60]) m.drawmeridians([120, 140, 160, 180, 200, 220, 240, 260]) cb = plt.colorbar(orientation='horizontal') cb.set_label('correlation coefficient', fontsize=12) plt.title('EOF1 expressed as correlation', fontsize=16) # Plot the leading PC time series. plt.figure() years = range(1962, 2012) plt.plot(years, pc1, color='b', linewidth=2) plt.axhline(0, color='k') plt.title('PC1 Time Series') plt.xlabel('Year') plt.ylabel('Normalized Units')
def iniciarProcesamiento(): # Mac /Users/jorgemauricio/Documents/Research/proyectoCaborca # Linux /home/jorge/Documents/Research/proyectoCaborca URL_CARPETA = "/Users/jorgemauricio/Documents/Research/proyectoCaborca" # ruta para acceder a los archivos shapes# nombre de la ruta para shapes rutaParaArchivosShapes = '{}/shapes/Estados'.format(URL_CARPETA) # coordenadas estaciones dataEstaciones = pd.read_csv( "/Users/jorgemauricio/Documents/Research/proyectoCaborca/data/coordenadas_estaciones.csv" ) # fecha actual fechaActual = strftime("%Y-%m-%d") # fecha -1 anio, mes, dia = generarDiaAnterior(fechaActual) # nombre de la ruta para la descarga rutaDeCarpetaParaElProcesamiento = '{}/data/{}-{:02d}-{:02d}'.format( URL_CARPETA, anio, mes, dia) # constantes LONG_MIN = -115.65 LONG_MAX = -107.94 LAT_MIN = 25.41 LAT_MAX = 33.06 # archivos a procesar listaDeArchivos = [ x for x in os.listdir(rutaDeCarpetaParaElProcesamiento) if x.endswith('.nc') ] # ciclo de procesamiento for archivo in listaDeArchivos: # nombre del archivo # nombreArchivo = "GBBEPx.emis_so2.001.20180118.nc" arrayNombreArchivo = archivo.split(".") arrayComponente = arrayNombreArchivo[1].split("_") nombreParaMapa = arrayComponente[1] rutaArchivo = "{}/{}".format(rutaDeCarpetaParaElProcesamiento, archivo) # leer el archivo netcdf dataset = Dataset(rutaArchivo) # generar las arreglos de las variables biomass = dataset.variables['biomass'][:] Latitude = dataset.variables['Latitude'][:] Longitude = dataset.variables['Longitude'][:] # variable para generar CSV dataText = "Long,Lat,Biomass\n" # procesamiento de información for i in range(Longitude.shape[0]): for j in range(Latitude.shape[0]): tempText = "{},{},{}\n".format(Longitude[i], Latitude[j], biomass[0, j, i]) dataText += tempText # generar archivo temporal csv fileName = "{}/temp/{}-{:02d}-{:02d}/{}.csv".format( URL_CARPETA, anio, mes, dia, nombreParaMapa) textFile = open(fileName, "w") textFile.write(dataText) textFile.close() # leer el archivo temporal csv data = pd.read_csv(fileName) # limites longitud > -115.65 y < -107.94 data = data.loc[data['Long'] > LONG_MIN] data = data.loc[data['Long'] < LONG_MAX] # limites latitud > 25.41 y < 33.06 data = data.loc[data['Lat'] > LAT_MIN] data = data.loc[data['Lat'] < LAT_MAX] # ug/m3 a ppm data['Biomass'] = data['Biomass'] * 10000000000 # obtener valores de x, y lons = np.array(data['Long']) lats = np.array(data['Lat']) #%% iniciar la gráfica plt.clf() # agregar locación de estaciones xC = np.array(dataEstaciones['Long']) yC = np.array(dataEstaciones['Lat']) m = Basemap(projection='mill', llcrnrlat=LAT_MIN, urcrnrlat=LAT_MAX, llcrnrlon=LONG_MIN, urcrnrlon=LONG_MAX, resolution='h') # generar lats, lons x, y = m(lons, lats) # numero de columnas y filas numCols = len(x) numRows = len(y) # generar xi, yi xi = np.linspace(x.min(), x.max(), numCols) yi = np.linspace(y.min(), y.max(), numRows) # generar el meshgrid xi, yi = np.meshgrid(xi, yi) # generar zi z = np.array(data['Biomass']) zi = gd((x, y), z, (xi, yi), method='cubic') # generar clevs stepVariable = 1 step = (z.max() - z.min()) / 10 # verificar el valor del intervalo if step <= 1: stepVariable = 1 clevs = np.linspace(z.min(), z.max() + stepVariable, 10) #clevs = [1,2,3,4,5,6,7,8,9,10] # contour plot cs = m.contourf(xi, yi, zi, clevs, zorder=5, alpha=0.5, cmap='PuBu') # agregar archivo shape de estados m.readshapefile(rutaParaArchivosShapes, 'Estados') # agregar puntos de estaciones m.scatter(xC, yC, latlon=True, s=1, marker='o', color='r', zorder=25) # colorbar cbar = m.colorbar(cs, location='right', pad="5%") cbar.set_label('pm') tituloTemporalParaElMapa = "{} {}-{:02d}-{:02d}".format( nombreParaMapa, anio, mes, dia) plt.title(tituloTemporalParaElMapa) # Mac /Users/jorgemauricio/Documents/Research/proyectoGranizo/Maps/{}_{}.png # Linux /home/jorge/Documents/Research/proyectoGranizo/Maps/{}_{}.png nombreTemporalParaElMapa = "/Users/jorgemauricio/Documents/Research/proyectoCaborca/maps/{}-{:02d}-{:02d}/{}.png".format( anio, mes, dia, nombreParaMapa) plt.annotate('@2018 INIFAP', xy=(-109, 29), xycoords='figure fraction', xytext=(0.45, 0.45), color='g', zorder=50) plt.savefig(nombreTemporalParaElMapa, dpi=300) print('****** Genereate: {}'.format(nombreTemporalParaElMapa))
plt.colorbar(orientation='horizontal', pad=0.005) plt.title('SURFACE ROUGHNESS \n' + DATE_STR) plt.savefig(PATH_OUTPUT + 'SRFC_COLORMESH_2019' + DATE_STR.replace(' ', ''), dpi=100, transparent=False, facecolor=fig.get_facecolor()) plt.close() fig, ax = plt.subplots(figsize=(10, 10), facecolor='white') ax.axis('off') MAP.drawcoastlines() MAP.contourf(x, y, data, levels=levels) x1, y1 = MAP(lonm, latm) MAP.plot(x1, y1, 'ro', markersize=10) MAP.plot(x, y, 'go', markersize=1) plt.colorbar(orientation='horizontal', pad=0.005) plt.title('SURFACE ROUGHNESS \n' + DATE_STR) plt.savefig(PATH_OUTPUT + 'SRFC_CONTOURF_2019' + DATE_STR.replace(' ', ''), dpi=100, transparent=False, facecolor=fig.get_facecolor()) plt.close()
area_thresh=10000.) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) pvar, lons_cyclic = addcyclic(pvar, lon) pvar, lons_cyclic = shiftgrid(180., pvar, lons_cyclic, start=False) climoq, lons_cyclic = addcyclic(climo[i], lon) climoq, lons_cyclic = shiftgrid(180., climoq, lons_cyclic, start=False) m.drawmapboundary(fill_color='white', color='dimgray', linewidth=0.7) if any([i == 2, i == 5]): cs = m.contourf(x, y, var * pvar, limit, extend='both') else: cs = m.contourf(x, y, var, limit, extend='both') if any([i == 0, i == 1, i == 3, i == 4]): cs1 = m.contourf(x, y, pvar, colors='None', hatches=['....'], linewidths=0.4) if varnames[v] == 'Z30': # the interval is 250 m cs2 = m.contour(x, y, climoq, np.arange(21900, 23500, 250), colors='k',
# Set contour levels for precip clevs = [0, 0.1, 2, 5, 10, 15, 20, 25, 35, 50, 75, 100, 125, 150, 175] #Use gempak color table for precipitation gemlist = gem_color_list() # Use gempak fline color levels from pcp verif page colorlist = [31, 23, 22, 21, 20, 19, 10, 17, 16, 15, 14, 29, 28, 24, 25] #Extract these colors to a new list for plotting pcolors = [gemlist[i] for i in colorlist] # Set up the colormap and normalize it so things look nice mycmap = matplotlib.colors.ListedColormap(pcolors) norm = matplotlib.colors.BoundaryNorm(clevs, mycmap.N) # Set up the colormap and normalize it so things look nice cf = m.contourf(xi, yi, apcp, clevs, cmap=mycmap, norm=norm, extend='max') cf.set_clim(0, 175) # add colorbar. cbar = m.colorbar(cf, location='bottom', pad="5%", ticks=clevs, format='%.1f') cbar.ax.tick_params(labelsize=7.0) cbar.set_label('mm') # get input file name w/o the leading directory path, to be used in plot # title and png file name: path, filename = os.path.split(infile) plt.title(filename) plt.savefig(filename + '.png', bbox_inches='tight') plt.close()
resolution='l',area_thresh=1000.,projection='lcc',\ lat_1=fh.stdlat1,lat_2=fh.stdlat2,lat_0=fh.cen_lat,lon_0=fh.cen_lon, suppress_ticks=True, ax=axs[n] ) m.drawstates(linewidth=0.1) m.drawcoastlines(linewidth=0.1) m.drawmapboundary(linewidth=0.1) m.drawcountries(linewidth=0.1) #m.drawparallels(np.arange(-90.,120.,5),labels=[1,0,0,0]); #m.drawmeridians(np.arange(-180.,180.,10),labels=[0,0,0,1]); x, y = m(lon, lat) contours, cm = eq_contours(data2d, 'refl') # Draw the contoured data over the map cs = m.contourf(x, y, data2d, contours, cmap=cm, ax=axs[n]) #m.plot(xx, yy, color='black', linewidth=3, linestyle='--', ax=ax[i]) #fig.colorbar(cs, ax=axs[n], orientation='vertical', shrink=0.7); axs[n].set_title(expt[n], fontsize=8) handles, labels = axs[n].get_legend_handles_labels() plt.suptitle(f"{title} {case}", fontsize=10) fig.subplots_adjust(right=0.90) cbar_ax = fig.add_axes([0.92, 0.2, 0.015, 0.5]) fig.colorbar(cs, cax=cbar_ax, orientation='vertical', shrink=0.7) #plt.show() figname = f"{field}_{fmin//60:02d}h_{case}_{initdate}.png" print(f"Saving figure to {figname} ...") fig.savefig(figname, format='png')
# Use: plt.savefig('sst.png', bbox_inches='tight', dpi=1200) # Specify some things to make the plot look nice. map = Basemap(projection='spaeqd', boundinglat=-35, lon_0=180, round='true') # Draw grid lines and label the longitudes. map.drawparallels(np.arange(-80, 0, 20), linewidth=0.25) map.drawmeridians(np.arange(-180, 180, 30), labels=12 * [True], linewidth=0.25) map.drawmapboundary(fill_color='black') # Draw the contour plot. cs_sst = map.contourf(glamt.T, gphit.T, np.squeeze(sage[:, :, 30:31]).T, np.arange(0., max_age + max_age / 40, max_age / 40), latlon='true', cmap='viridis', vmin=0., vmax=2., extend='both') # Add a colour bar. cbar = map.colorbar(cs_sst, 'right', ticks=np.arange(0., max_age + max_age / 4., max_age / 4.), pad=0.5) # Save a hires version of the figure plt.savefig('../figs/CORE2NYF-ORCH0083-LIM3/EXP00/ssage.png', bbox_inches='tight', dpi=1200)
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
xxb, yyb = np.meshgrid(xb, yb) cc = np.arange(-1.5, 1.500001, 0.05) #cc=np.array([-1., -.75, -.5, -.25, -0.2, -.15, -.1, -0.05, 0., 0.05, .1, .15, .2, .25, .5, .75, 1.]) latsize = [40.5, 45.5] lonsize = [-72, -66] plt.figure() m = Basemap(projection='cyl',llcrnrlat=min(latsize),urcrnrlat=max(latsize),\ llcrnrlon=min(lonsize),urcrnrlon=max(lonsize),resolution='h')#,fix_aspect=False) #m.drawparallels(np.arange(-80,-55,20),labels=[1,1,0,0]) #m.drawmeridians(np.arange(34,48,5),labels=[0,0,0,1]) m.drawparallels(np.arange(int(min(latsize)), int(max(latsize)) + 1, 2), labels=[1, 0, 0, 0]) m.drawmeridians(np.arange(int(min(lonsize)), int(max(lonsize)) + 1, 2), labels=[0, 0, 0, 1]) m.drawcoastlines() m.fillcontinents(color='grey') m.drawmapboundary() ub = np.ma.array(ub_mean, mask=np.isnan(ub_mean)) vb = np.ma.array(vb_mean, mask=np.isnan(vb_mean)) #Q=m.quiver(xxb,yyb,ub.T,vb.T,scale=2.5) #plt.quiverkey(Q,0.7,0.09,0.5, '50cm/s', labelpos='W') QQ = m.contourf(xxb, yyb, total_std.T) b = plt.colorbar(QQ, orientation='vertical') #plt.title('Model_derived mean') plt.title('Model_derived_std mean') #plt.plot(coast_lon,coast_lat,'b-') #plt.axis([-72,-66,40.5,45.5]) plt.show()
llcrnrlat=lat_min, urcrnrlon=lon_max, urcrnrlat=lat_max, projection='merc', resolution='h', area_thresh=1000., ) parallels_spacing = 3 meridian_spacing = -4 parallels = np.arange(round(lat_min, 0), lat_max + 2, parallels_spacing) meridians = np.arange(round(lon_max, 0), lon_min - 2, meridian_spacing) lon, lat = np.meshgrid(lon, lat) ax1 = plt.subplot(121) cs = m.contourf(lon, lat, s1, levels=np.linspace(s1.min(axis=None), s1.max(axis=None), 301), latlon=True) #cs=m.contourf(lon,lat,s1,levels=np.linspace(s1.min(axis=None),s1.max(axis=None),301),latlon=True,vmin=0.5*s1.min(axis=None),vmax=0.5*s1.max(axis=None)) m.drawcoastlines() m.drawstates() m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=0.0) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=0.0) #plt.title('-s$_{1}$',**titlefont) divider = make_axes_locatable(ax1) cax = divider.append_axes('right', size='5%', pad=0.05) cbar = plt.colorbar(cs, cax=cax, orientation='vertical', format="%.2f") #cbar.ax.tick_params(labelsize=8) ax2 = plt.subplot(122)
m = Basemap(projection='moll', lon_0=0, resolution='l', area_thresh=10000) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey', linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white', color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x, y, var, limit, extend='both') cs.set_cmap(cmap) ########################################################################### ########################################################################### ########################################################################### var = var2 ax1 = plt.subplot(1, 2, 2) m = Basemap(projection='moll', lon_0=0, resolution='l', area_thresh=10000) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey', linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False)
m = Basemap(lon_0=lon_0,satellite_height=h,\ rsphere = rsphere,\ resolution='l',area_thresh=10000.,projection='geos') # plot every 50th point. x, y = m(lons, lats) m.scatter(x[::50, ::50].flat, y[::50, ::50].flat, 1, marker='o', color='k', zorder=10) m.drawcoastlines() m.drawcountries() m.drawcoastlines() # contour data. m.contourf(x, y, fld, 30) # pcolor image (slower) #m.pcolor(x,y,fld) m.drawparallels(np.arange(-80, 81, 20)) m.drawmeridians(np.arange(-90, 90, 20)) m.drawmapboundary() plt.title('EUMETSAT geostationary projection grid 1') grb = grbs.readline() fld = grb['values'] lats, lons = grb.latlons() rsphere = (grb.projparams['a'], grb.projparams['b']) lon_0 = grb.projparams['lon_0'] h = grb.projparams['h'] grbs.close()