oc.close() # Get pga in format for figure. pga = np.exp(pga_mean) pga = np.flipud(pga) # Calculate Arias intentisy using FP GMPE. (Ia, sc) = gmpe.get_Travasarou(mag, vs30_data, rake, rrup_data) Ia = np.flipud(Ia) ##### ShakeMaps ##### # Mean fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(1, 1, 1, projection=data_crs) ax.set_extent((min_lon, max_lon, min_lat, max_lat)) lons = np.linspace(min_lon, max_lon, num_pts_x) lats = np.linspace(min_lat, max_lat, num_pts_y) ax.coastlines(resolution='50m') ax.add_feature( cfeat.NaturalEarthFeature('physical', 'ocean', '50m', edgecolor='face', facecolor='azure')) cb = ax.contour(lons, lats, Ia, cmap=cm.OrRd, transform=data_crs) plt.colorbar(cb, orientation='vertical', ticklocation='auto') ax.set_title('Travasarou Arias Intensity') plt.show() # Standard Deviation
def main(forest): # dem = pcr.readmap('../Data/DEM.map') # DEM = pcr.pcr2numpy(dem, 9999) # DEM[DEM==9999]=np.nan stamen_terrain = cimgt.StamenTerrain() proj = ccrs.AlbersEqualArea(central_longitude=-110, central_latitude=45.5,standard_parallels=(29.5,45.5)) ax = plt.axes(projection=proj) #ax.outline_patch.set_visible(False) # minx = -1446763 # maxy = 2732249 # maxx = -1340013 # miny = 2615749 # # x = np.linspace(minx,maxx,DEM.shape[1]) # y = np.linspace(miny,maxy,DEM.shape[0]) # xx, yy = np.meshgrid(x,y) # data = np.flipud(DEM) # colormesh = ax.pcolor(xx, yy, data, # transform=proj, # cmap='spring_r',linewidth=0,alpha = .3,vmin=10000,vmax=32000) ax.add_image(stamen_terrain,4) datapath = '../Data/Processed/' df23June = pd.read_csv(datapath + 'df23June.csv') print list(df23June) #df23June = df23June[df23June.Stock_Type == '1-0'] #df23June = df23June[df23June.Stakes >= 30] #df23June = df23June[df23June.Species != 'ES'] #df23June = df23June[df23June.Stock_Type != 'LP'] pcount = 0 for index,column in df23June.iterrows(): plt.plot(column['Longitude'],column['Latitude'],'d',markersize=4,color = 'red',label='Wheat') pcount +=1 #plt.plot(-583100,3062000,'.',color='white',label='Correct') #plt.plot(-583100,3062000,'.',color='black',label='Incorrect') #x = np.linspace(-1550000,-1550001,2) #y = np.linspace(29000000,29000001,2) #xx, yy = np.meshgrid(x,y) #data = xx/xx*.5 #colormesh = ax.pcolor(xx, yy,data , # transform=proj, # cmap='spectral',linewidth=0,vmin=0,vmax=20) #plt.plot(-583100,3262000,'.',color='white',label='_nolegend_') #plt.plot(-2500000,1062000,'.',color='white',label='_nolegend_') #ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.COASTLINE) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax.add_feature(cfeature.BORDERS) ax.add_feature(states_provinces, edgecolor='black') plt.legend(loc=3) scale_bar(ax,50) #plt.savefig('../Figures/Seedling_defense.png') plt.show()
# lons = [[] for _ in range(n_days)] # for point in lh["locations"][-60000:-1]: # t = datetime.fromtimestamp(int(point["timestampMs"]) / 1000) # if start_date <= t <= end_date: # lat, lon = int(point["latitudeE7"]) / 1e7, int(point["longitudeE7"]) / 1e7 # day = (t - start_date).days # times[day].append(t) # lats[day].append(lat) # lons[day].append(lon) # In[60]: states_provinces = cfeature.NaturalEarthFeature( category="cultural", name="admin_1_states_provinces_lines", scale="10m", facecolor="none") # In[89]: # projection = ccrs.PlateCarree() projection = ccrs.LambertConformal(central_latitude=25, central_longitude=265, standard_parallels=(25, 25)) fig = plt.figure(figsize=(16, 9), dpi=300) ax = plt.axes(projection=projection) lon1, lon2 = 236, 299 lat1, lat2 = 22, 55
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER with_cartopy = True except ModuleNotFoundError: warnings.warn("argopy requires cartopy installed for full map plotting functionality") with_cartopy = False try: import seaborn as sns sns.set_style("dark") with_seaborn = True except ModuleNotFoundError: warnings.warn("argopy requires seaborn installed for full plotting functionality") with_seaborn = False if with_cartopy: land_feature = cfeature.NaturalEarthFeature(category='physical', name='land', scale='50m', facecolor=[0.4, 0.6, 0.7]) def open_dashboard(wmo=None, cyc=None, width="100%", height=1000, url=None, type='ea'): """ Insert in a notebook the Euro-Argo dashboard page Parameters ---------- wmo: int The float WMO to display. By default, this is set to None and will insert the general dashboard. Returns ------- IFrame: IPython.lib.display.IFrame """ if type not in ['ea', 'eric', 'coriolis']:
def main(pet_fname, ppt_fname, plot_dir): ds_pet = xr.open_dataset(pet_fname, decode_times=False) ds_ppt = xr.open_dataset(ppt_fname, decode_times=False) bottom, top = np.min(ds_ppt.latitude).values, np.max( ds_ppt.latitude).values left, right = np.min(ds_ppt.longitude).values, np.max( ds_ppt.longitude).values ntime, nrows, ncols = ds_ppt.precip.shape nyears = 10 pet = np.zeros((nyears, nrows, ncols)) ppt = np.zeros((nyears, nrows, ncols)) mth_count = 1 yr_count = 0 count = 0 for year in np.arange(1990, 2000): print(year) for month in np.arange(1, 13): pet[yr_count, :, :] += ds_pet.PET[count, :, :] ppt[yr_count, :, :] += ds_ppt.precip[count, :, :] #print(year, month, np.mean(ds_pet.PET[count,:,:]), np.mean(ds_ppt.precip[count,:,:])) mth_count += 1 if mth_count == 13: mth_count = 1 yr_count += 1 count += 1 ppt = np.mean(ppt, axis=0) pet = np.mean(pet, axis=0) cmi = ppt - pet # just keep deficit areas #cmi = np.where(cmi >= 300., np.nan, cmi) cmi = np.flipud(cmi) #plt.imshow(cmi) #plt.colorbar() #plt.show() #sys.exit() fig = plt.figure(figsize=(9, 6)) plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.size'] = "14" plt.rcParams['font.sans-serif'] = "Helvetica" cmap = plt.cm.get_cmap('BrBG', 10) # discrete colour map projection = ccrs.PlateCarree() axes_class = (GeoAxes, dict(map_projection=projection)) rows = 1 cols = 1 axgr = AxesGrid(fig, 111, axes_class=axes_class, nrows_ncols=(rows, cols), axes_pad=0.2, cbar_location='right', cbar_mode='single', cbar_pad=0.5, cbar_size='5%', label_mode='') # note the empty label_mode for i, ax in enumerate(axgr): # add a subplot into the array of plots #ax = fig.add_subplot(rows, cols, i+1, projection=ccrs.PlateCarree()) plims = plot_map(ax, cmi, cmap, i, top, bottom, left, right) #plims = plot_map(ax, ds.plc[0,0,:,:], cmap, i) import cartopy.feature as cfeature states = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='10m', facecolor='none') # plot state border SOURCE = 'Natural Earth' LICENSE = 'public domain' ax.add_feature(states, edgecolor='black', lw=0.5) cbar = axgr.cbar_axes[0].colorbar(plims) cbar.ax.set_title("P-PET\n(mm yr$^{-1}$)", fontsize=16, pad=12) ofname = os.path.join(plot_dir, "p_minus_pet_pre.png") fig.savefig(ofname, dpi=300, bbox_inches='tight', pad_inches=0.1)
def map_detecs(catalog, dirname, minmag=-5, mindep=-50, title=''): """Make scatter plot of detections with magnitudes (if applicable).""" catalog = catalog[(catalog['mag'] >= minmag) & (catalog['depth'] >= mindep)].copy() if len(catalog) == 0: print('\nCatalog contains no events deeper than %s.' % mindep) return # define map bounds lllat, lllon, urlat, urlon, _, _, _, clon = qcu.get_map_bounds(catalog) plt.figure(figsize=(12, 7)) mplmap = plt.axes(projection=ccrs.PlateCarree(central_longitude=clon)) mplmap.set_extent([lllon, urlon, lllat, urlat], ccrs.PlateCarree()) mplmap.coastlines('50m', facecolor='none') # if catalog has magnitude data if not catalog['mag'].isnull().all(): bins = [0, 5, 6, 7, 8, 15] binnames = ['< 5', '5-6', '6-7', '7-8', r'$\geq$8'] binsizes = [10, 25, 50, 100, 400] bincolors = ['g', 'b', 'y', 'r', 'r'] binmarks = ['o', 'o', 'o', 'o', '*'] catalog.loc[:, 'maggroup'] = pd.cut(catalog['mag'], bins, labels=binnames) for i, label in enumerate(binnames): mgmask = catalog['maggroup'] == label rcat = catalog[mgmask] lons, lats = list(rcat['longitude']), list(rcat['latitude']) if len(lons) > 0: mplmap.scatter(lons, lats, s=binsizes[i], marker=binmarks[i], c=bincolors[i], label=binnames[i], alpha=0.8, zorder=10, transform=ccrs.PlateCarree()) plt.legend(loc='lower left', title='Magnitude') # if catalog does not have magnitude data else: lons, lats = list(catalog['longitude']), list(catalog['latitude']) mplmap.scatter(lons, lats, s=15, marker='x', c='r', zorder=10) mplmap.add_feature( cfeature.NaturalEarthFeature('cultural', 'admin_1_states_provinces_lines', '50m', facecolor='none', edgecolor='k', zorder=9)) mplmap.add_feature(cfeature.BORDERS) plt.title(title, fontsize=20) plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05) if mindep != -50: plt.savefig('%s_morethan%sdetecs.png' % (dirname, mindep), dpi=300) else: plt.savefig('%s_mapdetecs.png' % dirname, dpi=300) plt.close()
def main(): # Define the two coordinate systems with different ellipses. wgs84 = ccrs.PlateCarree(globe=ccrs.Globe(datum='WGS84', ellipse='WGS84')) sphere = ccrs.PlateCarree( globe=ccrs.Globe(datum='WGS84', ellipse='sphere')) # Define the coordinate system of the data we have from Natural Earth and # acquire the 1:10m physical coastline shapefile. geodetic = ccrs.Geodetic(globe=ccrs.Globe(datum='WGS84')) dataset = cfeature.NaturalEarthFeature(category='physical', name='coastline', scale='10m') # Create a Stamen map tiler instance, and use its CRS for the GeoAxes. tiler = StamenTerrain() fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=tiler.crs) ax.set_title('The effect of incorrectly referencing the Solomon Islands') # Pick the area of interest. In our case, roughly the Solomon Islands, and # get hold of the coastlines for that area. extent = [155, 163, -11.5, -6] ax.set_extent(extent, geodetic) geoms = list(dataset.intersecting_geometries(extent)) # Add the Stamen aerial imagery at zoom level 7. ax.add_image(tiler, 7) # Transform the geodetic coordinates of the coastlines into the two # projections of differing ellipses. wgs84_geoms = [ geom_transform(transform_fn_factory(wgs84, geodetic), geom) for geom in geoms ] sphere_geoms = [ geom_transform(transform_fn_factory(sphere, geodetic), geom) for geom in geoms ] # Using these differently referenced geometries, assume that they are # both referenced to WGS84. ax.add_geometries(wgs84_geoms, wgs84, edgecolor='white', color='none') ax.add_geometries(sphere_geoms, wgs84, edgecolor='gray', color='none') # Create a legend for the coastlines. legend_artists = [ Line([0], [0], color=color, linewidth=3) for color in ('white', 'gray') ] legend_texts = ['Correct ellipse\n(WGS84)', 'Incorrect ellipse\n(sphere)'] legend = ax.legend(legend_artists, legend_texts, fancybox=True, loc='lower left', framealpha=0.75) legend.legendPatch.set_facecolor('wheat') # Create an inset GeoAxes showing the location of the Solomon Islands. sub_ax = fig.add_axes([0.7, 0.625, 0.2, 0.2], projection=ccrs.PlateCarree()) sub_ax.set_extent([110, 180, -50, 10], geodetic) # Make a nice border around the inset axes. effect = Stroke(linewidth=4, foreground='wheat', alpha=0.5) sub_ax.outline_patch.set_path_effects([effect]) # Add the land, coastlines and the extent of the Solomon Islands. sub_ax.add_feature(cfeature.LAND) sub_ax.coastlines() extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), color='none', edgecolor='blue', linewidth=2) plt.show()
def chart(self, field, cmap='jet', clim=[190., 300.], txt='', subgrid=None, block=True, xlocs=None): # test existence of key field if field not in self.var.keys(): print('undefined field') return if subgrid == None: geogrid = self.geogrid else: geogrid = subgrid if 'FullAMA' in geogrid.gridtype: fig = plt.figure(figsize=[10, 6]) else: fig = plt.figure(figsize=[11, 4]) fig.subplots_adjust(hspace=0, wspace=0.5, top=0.925, left=0.) fs = 15 # it is unclear how the trick with cm_lon works in imshow but it does # the web says that it is tricky to plot data accross dateline with cartopy # check https://stackoverflow.com/questions/47335851/issue-w-image-crossing-dateline-in-imshow-cartopy cm_lon = 0 # guess that we want to plot accross dateline if geogrid.box_range[0, 1] > 181: cm_lon = 180 proj = ccrs.PlateCarree(central_longitude=cm_lon) ax = plt.axes(projection=proj) if subgrid == None: plotted_field = self.var[field] else: # extraction in subgrid plotted_field = self.var[field][ geogrid.corner[1]:geogrid.corner[1] + geogrid.box_biny, geogrid.corner[0]:geogrid.corner[0] + geogrid.box_binx] iax = ax.imshow(plotted_field, transform=proj, interpolation='nearest', extent=geogrid.box_range.flatten() - np.array([cm_lon, cm_lon, 0, 0]), origin='lower', aspect=1., cmap=cmap, clim=clim) ax.add_feature( feature.NaturalEarthFeature(category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none')) ax.coastlines('50m') #ax.add_feature(feature.BORDERS) # The grid adjusts automatically with the following lines # If crossing the dateline, superimposition of labels there # can be suppressed by specifying xlocs if (cm_lon == 180) & (xlocs == None): xlocs = [0, 30, 60, 90, 120, 150, 180, -150, -120, -90, -60, -30] gl = ax.gridlines(draw_labels=True, xlocs=xlocs, linewidth=2, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False #gl.xformatter = LONGITUDE_FORMATTER #gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': fs} gl.ylabel_style = {'size': fs} #gl.xlabel_style = {'color': 'red', 'weight': 'bold'} plt.title(txt, fontsize=fs) # plot adjusted colorbar and show axpos = ax.get_position() pos_x = axpos.x0 + axpos.x0 + axpos.width + 0.01 pos_cax = fig.add_axes([pos_x, axpos.y0, 0.04, axpos.height]) cbar = fig.colorbar(iax, cax=pos_cax) cbar.ax.tick_params(labelsize=fs) plt.show(block=block) return None
def main(): download_dataset() parser = argparse.ArgumentParser() parser.add_argument('-m', '--map', help='Which type of map to be generated.') args = parser.parse_args() if args.map == 'verywide': map_ = map_utils.VeryWide() elif args.map == 'regional': map_ = map_utils.Regional() elif args.map == 'local': map_ = map_utils.Local() elif args.map == 'tropical': map_ = map_utils.Tropical() elif args.map == 'country': map_ = map_utils.Country() # Open dataset and capture relevant info file = '../output/CPC_data.grb2' dataset = pygrib.open(file) # Grab the temperature and precipitation data from the dataset precipitation_data = [] temperature_data = dataset.select(name='Temperature') for d in dataset: if str(d) not in str(temperature_data): precipitation_data.append(d) temperature_precipitation_data = { 'Temperatures': temperature_data, 'Precipitations': precipitation_data, }.items() for key, values in temperature_precipitation_data: fig = plt.figure(figsize=(15, 9)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mercator()) ax.set_extent(map_.NorthSouthEastWest[::-1], crs=ccrs.Geodetic()) for value in values: lats, lons = value.latlons() vals = value.values # Add boundaries to plot ax.add_feature(cfeature.OCEAN, facecolor=cfeature.COLORS['water']) if map_.map_type == 'verywide': ax.add_feature(cfeature.STATES.with_scale('50m'), linewidth=0.5) elif map_.map_type == 'regional' or map_.map_type == 'local': ax.add_feature(cfeature.STATES.with_scale('50m'), linewidth=0.5) reader = shpreader.Reader('../county_data/countyl010g.shp') counties = list(reader.geometries()) COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree()) ax.add_feature(COUNTIES, facecolor='none', edgecolor='black', linewidth=0.3) elif map_.map_type == 'tropical' or map_.map_type == 'country': countries = cfeature.NaturalEarthFeature( category='cultural', name='admin_0_countries', scale='50m', facecolor='none') ax.add_feature(cfeature.LAND) ax.add_feature(countries, edgecolor='black', linewidth=0.5) ax.add_feature(cfeature.STATES.with_scale('50m'), linewidth=0.5) # Contour temperature value at each lat/lon depending on the key if 'event below' in str(value): if key == 'Temperatures': # Contour temperature at each lat/long cf = ax.contourf(lons, lats, vals, levels=[33, 40, 50, 60, 70, 80, 90], transform=ccrs.PlateCarree(), cmap='Blues') cb1 = plt.colorbar(cf, ax=ax, orientation='horizontal', fraction=0.045, pad=0.04) elif key == 'Precipitations': # Contour temperature at each lat/long cf = ax.contourf(lons, lats, vals, levels=[33, 40, 50, 60, 70, 80, 90], transform=ccrs.PlateCarree(), cmap='Blues') cb1 = plt.colorbar(cf, ax=ax, orientation='horizontal', fraction=0.035, pad=0.08) cb1.ax.set_xlabel('Probability of Below (%)') elif 'event above' in str(value): if key == 'Temperatures': # Contour temperature at each lat/long cf = ax.contourf(lons, lats, vals, levels=[33, 40, 50, 60, 70, 80, 90], transform=ccrs.PlateCarree(), cmap='Reds') cb2 = plt.colorbar(cf, ax=ax, orientation='horizontal', fraction=0.0395, pad=0.08) elif key == 'Precipitations': # Contour temperature at each lat/long cf = ax.contourf(lons, lats, vals, levels=[33, 40, 50, 60, 70, 80, 90], transform=ccrs.PlateCarree(), cmap='Greens') cb2 = plt.colorbar(cf, ax=ax, orientation='horizontal', fraction=0.0395, pad=0.04) cb2.ax.set_xlabel('Probability of Above (%)') # Plot all the cities if map_.map_type is not 'tropical' and map_.map_type is not 'country': for city in map_.cities: ax.plot(city.lon, city.lat, 'ro', zorder=9, markersize=1.90, transform=ccrs.Geodetic()) if map_.map_type == 'local': ax.text(city.lon - 0.3, city.lat + 0.04, city.city_name, fontsize='small', fontweight='bold', transform=ccrs.PlateCarree()) else: ax.text(city.lon - 0.5, city.lat + 0.09, city.city_name, fontsize='small', fontweight='bold', transform=ccrs.PlateCarree()) # Title ax.set_title('{} Probability for {} UTC'.format( key, str(value.validDate)), fontsize=12, loc='left') # Company copyright bottom right corner text = AnchoredText(r'$\mathcircled{{c}}$ NickelBlock Forecasting', loc=4, prop={'size': 9}, frameon=True) ax.add_artist(text) # Data model data_model = AnchoredText('CPC Probability Outlook model', loc=3, prop={'size': 9}, frameon=True) ax.add_artist(data_model) # Add logo logo = Utils.get_logo() if map_.map_type == 'verywide': if key == 'Temperatures': ax.figure.figimage(logo, 1040, 272, zorder=1) elif key == 'Precipitations': ax.figure.figimage(logo, 1045, 265, zorder=1) elif map_.map_type == 'regional': if key == 'Temperatures': ax.figure.figimage(logo, 925, 273, zorder=1) elif key == 'Precipitations': ax.figure.figimage(logo, 930, 267, zorder=1) elif map_.map_type == 'local': if key == 'Temperatures': ax.figure.figimage(logo, 904, 270, zorder=1) elif key == 'Precipitations': ax.figure.figimage(logo, 909, 265, zorder=1) elif map_.map_type == 'tropical': if key == 'Temperatures': ax.figure.figimage(logo, 1110, 272, zorder=1) elif key == 'Precipitations': ax.figure.figimage(logo, 1115, 267, zorder=1) elif map_.map_type == 'country': if key == 'Temperatures': ax.figure.figimage(logo, 1070, 271, zorder=1) elif key == 'Precipitations': ax.figure.figimage(logo, 1075, 266, zorder=1) plt.savefig('CPC_{}_{}_Map.png'.format(key, value.validDate))
def plotmap(data1, data2, data3, time_index, z_index): import matplotlib import matplotlib.cm as mpl_cm import matplotlib.pyplot as plt import cartopy.crs as crs import cartopy.feature as cfe ################################### ################################### ## Plot map (with cartopy) ################################### ################################### ## Get the latitude and longitude points lats, lons = wrf.latlon_coords(data1) ## Get the cartopy mapping object cart_proj = wrf.get_cartopy(data1) data1 = wrf.to_np(data1[z_index,:,:]) data2 = wrf.to_np(data2[z_index,:,:]) data3 = wrf.to_np(data3[z_index,:,:]) # Create a figure fig = plt.figure(figsize=(8,4)) # Set the GeoAxes to the projection used by WRF ax = fig.add_axes([0.1,0.1,0.4,0.8], projection=cart_proj) # left, bottom, width, height # ax = plt.axes(projection=cart_proj) # Add coastlines ax.coastlines('50m', linewidth=0.8) ax.add_feature(cfe.NaturalEarthFeature('physical', 'antarctic_ice_shelves_lines', '50m', linewidth=1.0, edgecolor='k', facecolor='none') ) # Plot contours plt.contourf(wrf.to_np(lons), wrf.to_np(lats), data1, 10, transform=crs.PlateCarree(), cmap = mpl_cm.Reds) # Add a color bar cbar = plt.colorbar(ax=ax, shrink=.62) cbar.set_label(data1.name[-5:]) # Set the map limits. Not really necessary, but used for demonstration. # ax.set_xlim(wrf.cartopy_xlim(qnwfa1)) # ax.set_ylim(wrf.cartopy_ylim(qnwfa1)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title(data1.name+'\n'+str(data1.Time.values)) # Set the GeoAxes to the projection used by WRF ax = fig.add_axes([0.55,0.1,0.4,0.8], projection=cart_proj) # left, bottom, width, height # ax = plt.axes(projection=cart_proj) # Add coastlines ax.coastlines('50m', linewidth=0.8) ax.add_feature(cfe.NaturalEarthFeature('physical', 'antarctic_ice_shelves_lines', '50m', linewidth=1.0, edgecolor='k', facecolor='none') ) # Plot contours plt.contourf(wrf.to_np(lons), wrf.to_np(lats), data2, 10, transform=crs.PlateCarree(), cmap = mpl_cm.Reds) # Add a color bar cbar = plt.colorbar(ax=ax, shrink=.62) cbar.set_label(data2.name[-5:]) # Set the map limits. Not really necessary, but used for demonstration. # ax.set_xlim(wrf.cartopy_xlim(qnwfa2)) # ax.set_ylim(wrf.cartopy_ylim(qnwfa2)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title(data2.name+'\n'+str(data2.Time.values)) plt.show()
def meshplot_region(mme_diff, extent_lonlat=None, central_longitude=None, central_latitude=None, cmap_name=plt.cm.BrBG, vmax=None, vmin=None): lono = mme_diff.getLongitude()[:] lato = mme_diff.getLatitude()[:] if central_latitude is None: central_latitude = np.median(lato) if central_longitude is None: central_longitude = np.median(lono) lon, lat = np.meshgrid(lono, lato) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') #clevs = np.array([-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.2,.3,.4,.5,.6])*2.5 p5 = np.percentile(mme_diff.compressed(), 5) p95 = np.percentile(mme_diff.compressed(), 95) if vmin is None: vmin = -1 * max(np.abs(p5), np.abs(p95)) if vmax is None: vmax = max(np.abs(p5), np.abs(p95)) clevs = np.linspace(vmin, vmax, 13) clevs_units = clevs.copy() nmap = plt.cm.get_cmap(name=cmap_name, lut=clevs.size - 1) ocean_color = np.float64([209, 230, 241]) / 255 fig = plt.figure(figsize=(12, 12), facecolor="white") ax = fig.add_subplot(1, 1, 1, projection=ccrs.Orthographic( central_longitude=central_longitude, central_latitude=central_latitude, globe=None)) m = ax.contourf(lon, lat, mme_diff, clevs, transform=ccrs.PlateCarree(), cmap=nmap, extend="both") #m = ax.pcolormesh(lon, lat, mme_diff,vmin=vmin,vmax=vmax,transform=ccrs.PlateCarree(),cmap=nmap) ax.coastlines() ax.set_global() if extent_lonlat is not None: ax.set_extent(extent_lonlat, crs=ccrs.PlateCarree()) #ax.gridlines(xlocs=np.arange(-180,190,10),ylocs=np.arange(-180,190,10)) ax.add_feature(cfeature.BORDERS, linewidth=0.5, linestyle='-', edgecolor='k') ax.add_feature(states_provinces, linewidth=0.5, linestyle='-', edgecolor='k') #ax.add_feature(newcoast, linewidth=0.5, linestyle='-', edgecolor='k') #ax.add_feature(newlake, linewidth=0.5, linestyle='-', edgecolor='k') ax.add_feature(cartopy.feature.LAND, color='white', zorder=0, edgecolor='k', hatch="/") ax.add_feature(cartopy.feature.OCEAN, color=ocean_color, zorder=0, edgecolor='k') ax.add_feature(cfeature.BORDERS, linewidth=0.5, linestyle='-', edgecolor='k') ax.add_feature(cartopy.feature.OCEAN, color=ocean_color, zorder=1) #ax.add_feature(newcoast, linewidth=1, linestyle='-', zorder=2,edgecolor='k') #ax.text(-122,21,var_txt+' ('+seas_txt+')',transform=ccrs.PlateCarree(),fontsize=32,fontweight="bold", \ #horizontalalignment='center', verticalalignment='center',) #ax.text(-122,17,ssp_txt,transform=ccrs.PlateCarree(),fontsize=28,fontweight="normal", \ #horizontalalignment='center', verticalalignment='center',) #cbar=plt.colorbar(m,orientation="horizontal",fraction=0.08,pad=0.04)#,ticks=clevs_units[np.arange(0,clevs_units.size+1,2)]) if ((vmin == 0) and (vmax == 365)): cbar = plt.colorbar(m, orientation="horizontal", fraction=0.08, pad=0.04, ticks=np.linspace(0, 365, 12)) cbar.ax.set_xticklabels([ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ]) else: cbar = plt.colorbar(m, orientation="horizontal", fraction=0.08, pad=0.04) cbar.ax.tick_params(labelsize=24) shpfilename = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries') reader = shpreader.Reader(shpfilename) countries = reader.records()
def add_inset(fig, extent, pos, bounds, label=None, polygon=None, anom=None, draw_cmap_y=None, hillshade=True, markup_sub=None, sub_pos=None, sub_adj=None): sub_ax = fig.add_axes(pos, projection=ccrs.Robinson(), label=label) sub_ax.set_extent(extent, ccrs.Geodetic()) sub_ax.add_feature( cfeature.NaturalEarthFeature('physical', 'ocean', '50m', facecolor='gainsboro')) sub_ax.add_feature( cfeature.NaturalEarthFeature('physical', 'land', '50m', facecolor='dimgrey')) # if anom is not None: # shape_feature = ShapelyFeature(Reader(shp_buff).geometries(), ccrs.PlateCarree(), edgecolor='black', alpha=0.5, # facecolor='black', linewidth=1) # sub_ax.add_feature(shape_feature) if polygon is None and bounds is not None: polygon = poly_from_extent(bounds) if bounds is not None: verts = mpath.Path(latlon_extent_to_robinson_axes_verts(polygon)) sub_ax.set_boundary(verts, transform=sub_ax.transAxes) if hillshade: def out_of_poly_mask(geoimg, poly_coords): poly = ot.poly_from_coords(inter_poly_coords(poly_coords)) srs = osr.SpatialReference() srs.ImportFromEPSG(54030) # put in a memory vector ds_shp = ot.create_mem_shp(poly, srs) return ot.geoimg_mask_on_feat_shp_ds(ds_shp, geoimg) def inter_poly_coords(polygon_coords): list_lat_interp = [] list_lon_interp = [] for i in range(len(polygon_coords) - 1): lon_interp = np.linspace(polygon_coords[i][0], polygon_coords[i + 1][0], 50) lat_interp = np.linspace(polygon_coords[i][1], polygon_coords[i + 1][1], 50) list_lon_interp.append(lon_interp) list_lat_interp.append(lat_interp) all_lon_interp = np.concatenate(list_lon_interp) all_lat_interp = np.concatenate(list_lat_interp) return np.array(list(zip(all_lon_interp, all_lat_interp))) img = GeoImg(fn_hs) hs_tmp = hs_land.copy() hs_tmp_nl = hs_notland.copy() mask = out_of_poly_mask(img, polygon) hs_tmp[~mask] = 0 hs_tmp_nl[~mask] = 0 sub_ax.imshow(hs_tmp[:, :], extent=ext, transform=ccrs.Robinson(), cmap=cmap2, zorder=2, interpolation='nearest') sub_ax.imshow(hs_tmp_nl[:, :], extent=ext, transform=ccrs.Robinson(), cmap=cmap22, zorder=2, interpolation='nearest') sub_ax.outline_patch.set_edgecolor('white') if anom is not None: if anom == 'dhs_1' or 'dhs_2' or 'dhs_3' or 'dhs_3': col_bounds = np.array([0, 1, 2, 3, 5, 7, 10, 15, 20]) cb = [] cb_val = np.linspace(0, 1, len(col_bounds)) for j in range(len(cb_val)): cb.append(mpl.cm.viridis(cb_val[j])) cmap_cus = mpl.colors.LinearSegmentedColormap.from_list( 'my_cb', list( zip((col_bounds - min(col_bounds)) / (max(col_bounds - min(col_bounds))), cb)), N=1000) if anom == 'dhs_1': vals = dhs_1 elif anom == 'dhs_2': vals = dhs_2 elif anom == 'dhs_3': vals = dhs_3 elif anom == 'dhs_4': vals = dhs_4 lab = 'Number of valid observations' # elif anom == 'dt': # col_bounds = np.array([-0.3, -0.15, 0, 0.3, 0.6]) # cb = [] # cb_val = np.linspace(0, 1, len(col_bounds)) # for j in range(len(cb_val)): # cb.append(mpl.cm.RdBu_r(cb_val[j])) # cmap_cus = mpl.colors.LinearSegmentedColormap.from_list('my_cb', list( # zip((col_bounds - min(col_bounds)) / (max(col_bounds - min(col_bounds))), cb)), N=1000) # # vals = dts # lab = 'Decadal difference in temperature (K)' # # elif anom == 'dp': # col_bounds = np.array([-0.2, -0.1, 0, 0.1, 0.2]) # cb = [] # cb_val = np.linspace(0, 1, len(col_bounds)) # for j in range(len(cb_val)): # cb.append(mpl.cm.BrBG(cb_val[j])) # cmap_cus = mpl.colors.LinearSegmentedColormap.from_list('my_cb', list( # zip((col_bounds - min(col_bounds)) / (max(col_bounds - min(col_bounds))), cb)), N=1000) # # vals = dps # lab = 'Decadal difference in precipitation (m)' # elif anom == 'du': # col_bounds = np.array([-1, -0.5, 0, 0.5, 1]) # cb = [] # cb_val = np.linspace(0, 1, len(col_bounds)) # for j in range(len(cb_val)): # cb.append(mpl.cm.RdBu_r(cb_val[j])) # cmap_cus = mpl.colors.LinearSegmentedColormap.from_list('my_cb', list( # zip((col_bounds - min(col_bounds)) / (max(col_bounds - min(col_bounds))), cb)), N=1000) # # vals = dus # lab = 'Wind speed anomaly (m s$^{-1}$)' # # elif anom == 'dz': # # col_bounds = np.array([-100, -50, 0, 50, 100]) # cb = [] # cb_val = np.linspace(0, 1, len(col_bounds)) # for j in range(len(cb_val)): # cb.append(mpl.cm.RdBu_r(cb_val[j])) # cmap_cus = mpl.colors.LinearSegmentedColormap.from_list('my_cb', list( # zip((col_bounds - min(col_bounds)) / (max(col_bounds - min(col_bounds))), cb)), N=1000) # # vals = dzs # lab = 'Geopotential height anomaly at 500 hPa (m)' # # elif anom =='dk': # # col_bounds = np.array([-200000, -100000, 0, 100000, 200000]) # cb = [] # cb_val = np.linspace(0, 1, len(col_bounds)) # for j in range(len(cb_val)): # cb.append(mpl.cm.RdBu_r(cb_val[j])) # cmap_cus = mpl.colors.LinearSegmentedColormap.from_list('my_cb', list( # zip((col_bounds - min(col_bounds)) / (max(col_bounds - min(col_bounds))), cb)), N=1000) # # vals = dks # lab = 'Net clear-sky downwelling SW surface radiation anomaly (J m$^{-2}$)' if draw_cmap_y is not None: sub_ax_2 = fig.add_axes([0.2, draw_cmap_y, 0.6, 0.05]) sub_ax_2.set_xticks([]) sub_ax_2.set_yticks([]) sub_ax_2.spines['top'].set_visible(False) sub_ax_2.spines['left'].set_visible(False) sub_ax_2.spines['right'].set_visible(False) sub_ax_2.spines['bottom'].set_visible(False) cbaxes = sub_ax_2.inset_axes([0, 0.85, 1, 0.2], label='legend_' + label) norm = mpl.colors.Normalize(vmin=min(col_bounds), vmax=max(col_bounds)) sm = plt.cm.ScalarMappable(cmap=cmap_cus, norm=norm) sm.set_array([]) cb = plt.colorbar(sm, cax=cbaxes, ticks=col_bounds, orientation='horizontal', extend='both', shrink=0.9) # cb.ax.tick_params(labelsize=12) cb.set_label(lab) for i in range(len(tiles)): lat, lon = SRTMGL1_naming_to_latlon(tiles[i]) if group_by_spec: lat, lon, s = latlon_to_spec_center(lat, lon) else: lat = lat + 0.5 lon = lon + 0.5 s = (1, 1) # fac = 0.02 fac = 7000000. if anom == 'dhs_1': errs = errs_1 elif anom == 'dhs_2': errs = errs_2 elif anom == 'dhs_3': errs = errs_3 elif anom == 'dhs_4': errs = errs_4 if np.isnan(errs[i]): continue #need to square because Rectangle already shows a surface f = np.sqrt(((1 / min(max(errs[i], 0.25), 1)**2 - 1 / 1**2) / (1 / 0.25**2 - 1 / 1**2))) * (1 - np.sqrt(0.1)) if ~np.isnan(vals[i]) and areas[i] > 0.2: val = vals[i] val_col = max( 0.0001, min(0.9999, (val - min(col_bounds)) / (max(col_bounds) - min(col_bounds)))) col = cmap_cus(val_col) elif areas[i] <= 5: continue else: col = plt.cm.Greys(0.7) # xy = [lon,lat] xy = coordXform(ccrs.PlateCarree(), ccrs.Robinson(), np.array([lon]), np.array([lat]))[0][0:2] # sub_ax.add_patch( # mpatches.Circle(xy=xy, radius=rad, color=col, alpha=1, transform=ccrs.Robinson(), zorder=30)) xl = np.sqrt(0.1) * s[0] + f * s[0] yl = np.sqrt(0.1) * s[1] + f * s[1] sub_ax.add_patch( mpatches.Rectangle((lon - xl / 2, lat - yl / 2), xl, yl, facecolor=col, alpha=1, transform=ccrs.PlateCarree(), zorder=30)) if markup_sub is not None and anom == 'dhs_1': lon_min = np.min(list(zip(*polygon))[0]) lon_max = np.max(list(zip(*polygon))[0]) lon_mid = 0.5 * (lon_min + lon_max) lat_min = np.min(list(zip(*polygon))[1]) lat_max = np.max(list(zip(*polygon))[1]) lat_mid = 0.5 * (lat_min + lat_max) robin = np.array( list( zip([ lon_min, lon_min, lon_min, lon_mid, lon_mid, lon_max, lon_max, lon_max ], [ lat_min, lat_mid, lat_max, lat_min, lat_max, lat_min, lat_mid, lat_max ]))) if sub_pos == 'lb': rob_x = robin[0][0] rob_y = robin[0][1] ha = 'left' va = 'bottom' elif sub_pos == 'lm': rob_x = robin[1][0] rob_y = robin[1][1] ha = 'left' va = 'center' elif sub_pos == 'lt': rob_x = robin[2][0] rob_y = robin[2][1] ha = 'left' va = 'top' elif sub_pos == 'mb': rob_x = robin[3][0] rob_y = robin[3][1] ha = 'center' va = 'bottom' elif sub_pos == 'mt': rob_x = robin[4][0] rob_y = robin[4][1] ha = 'center' va = 'top' elif sub_pos == 'rb': rob_x = robin[5][0] rob_y = robin[5][1] ha = 'right' va = 'bottom' elif sub_pos == 'rm': rob_x = robin[6][0] rob_y = robin[6][1] ha = 'right' va = 'center' elif sub_pos == 'rt': rob_x = robin[7][0] rob_y = robin[7][1] ha = 'right' va = 'top' if sub_pos[0] == 'r': rob_x = rob_x - 100000 elif sub_pos[0] == 'l': rob_x = rob_x + 100000 if sub_pos[1] == 'b': rob_y = rob_y + 100000 elif sub_pos[1] == 't': rob_y = rob_y - 100000 if sub_adj is not None: rob_x += sub_adj[0] rob_y += sub_adj[1] sub_ax.text(rob_x, rob_y, markup_sub, horizontalalignment=ha, verticalalignment=va, transform=ccrs.Robinson(), color='black', fontsize=4.5, bbox=dict(facecolor='white', alpha=1, linewidth=0.35, pad=1.5), fontweight='bold', zorder=25)
import matplotlib.colors as mcolors except ModuleNotFoundError: warnings.warn( "argopy requires matplotlib installed for any plotting functionality") with_matplotlib = False try: with_cartopy = True import cartopy import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER land_feature = cfeature.NaturalEarthFeature(category="physical", name="land", scale="50m", facecolor=[0.4, 0.6, 0.7]) except ModuleNotFoundError: with_cartopy = False # Default styles: STYLE = {"axes": "whitegrid", "palette": "Set1"} try: import seaborn as sns STYLE["axes"] = "dark" with_seaborn = True except ModuleNotFoundError: with_seaborn = False
def execute(self): """ Raises: NotADirectoryError: When the event data directory does not exist. FileNotFoundError: When the the shake_result HDF file does not exist. """ install_path, data_path = get_config_paths() datadir = os.path.join(data_path, self._eventid, 'current', 'products') if not os.path.isdir(datadir): raise NotADirectoryError('%s is not a valid directory.' % datadir) datafile = os.path.join(datadir, 'shake_result.hdf') if not os.path.isfile(datafile): raise FileNotFoundError('%s does not exist.' % datafile) # Open the ShakeMapOutputContainer and extract the data container = ShakeMapOutputContainer.load(datafile) if container.getDataType() != 'grid': raise NotImplementedError('mapping module can only operate on ' 'gridded data, not sets of points') # get the path to the products.conf file, load the config config_file = os.path.join(install_path, 'config', 'products.conf') spec_file = get_configspec('products') validator = get_custom_validator() config = ConfigObj(config_file, configspec=spec_file) results = config.validate(validator) check_extra_values(config, self.logger) if not isinstance(results, bool) or not results: config_error(config, results) # create contour files self.logger.debug('Mapping...') # get the filter size from the products.conf filter_size = config['products']['contour']['filter_size'] # get the operator setting from config operator = config['products']['mapping']['operator'] # get all of the pieces needed for the mapping functions layers = config['products']['mapping']['layers'] if 'topography' in layers and layers['topography'] != '': topofile = layers['topography'] else: topofile = None if 'roads' in layers and layers['roads'] != '': roadfile = layers['roads'] else: roadfile = None if 'faults' in layers and layers['faults'] != '': faultfile = layers['faults'] else: faultfile = None # Get the number of parallel workers max_workers = config['products']['mapping']['max_workers'] # Reading HDF5 files currently takes a long time, due to poor # programming in MapIO. To save us some time until that issue is # resolved, we'll coarsely subset the topo grid once here and pass # it into both mapping functions # get the bounds of the map info = container.getMetadata() xmin = info['output']['map_information']['min']['longitude'] xmax = info['output']['map_information']['max']['longitude'] ymin = info['output']['map_information']['min']['latitude'] ymax = info['output']['map_information']['max']['latitude'] dy = float( info['output']['map_information']['grid_spacing']['latitude']) dx = float( info['output']['map_information']['grid_spacing']['longitude']) padx = 5 * dx pady = 5 * dy sxmin = float(xmin) - padx sxmax = float(xmax) + padx symin = float(ymin) - pady symax = float(ymax) + pady sampledict = GeoDict.createDictFromBox(sxmin, sxmax, symin, symax, dx, dy) if topofile: topogrid = read(topofile, samplegeodict=sampledict, resample=False) else: tdata = np.full([sampledict.ny, sampledict.nx], 0.0) topogrid = Grid2D(data=tdata, geodict=sampledict) model_config = container.getConfig() imtlist = container.getIMTs() textfile = os.path.join( get_data_path(), 'mapping', 'map_strings.' + config['products']['mapping']['language']) text_dict = get_text_strings(textfile) if config['products']['mapping']['fontfamily'] != '': matplotlib.rcParams['font.family'] = \ config['products']['mapping']['fontfamily'] matplotlib.rcParams['axes.unicode_minus'] = False allcities = Cities.fromDefault() states_provs = None countries = None oceans = None lakes = None extent = (float(xmin), float(ymin), float(xmax), float(ymax)) if 'CALLED_FROM_PYTEST' not in os.environ: states_provs = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='10m', facecolor='none') states_provs = list(states_provs.intersecting_geometries(extent)) if len(states_provs) > 300: states_provs = None else: states_provs = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='10m', facecolor='none') countries = cfeature.NaturalEarthFeature(category='cultural', name='admin_0_countries', scale='10m', facecolor='none') oceans = cfeature.NaturalEarthFeature(category='physical', name='ocean', scale='10m', facecolor=WATERCOLOR) lakes = cfeature.NaturalEarthFeature(category='physical', name='lakes', scale='10m', facecolor=WATERCOLOR) if faultfile is not None: faults = ShapelyFeature(Reader(faultfile).geometries(), ccrs.PlateCarree(), facecolor='none') else: faults = None if roadfile is not None: roads = ShapelyFeature(Reader(roadfile).geometries(), ccrs.PlateCarree(), facecolor='none') if len(list(roads.intersecting_geometries(extent))) > 200: roads = None else: roads = ShapelyFeature(Reader(roadfile).geometries(), ccrs.PlateCarree(), facecolor='none') else: roads = None alist = [] for imtype in imtlist: component, imtype = imtype.split('/') comp = container.getComponents(imtype)[0] d = { 'imtype': imtype, 'topogrid': topogrid, 'allcities': allcities, 'states_provinces': states_provs, 'countries': countries, 'oceans': oceans, 'lakes': lakes, 'roads': roads, 'faults': faults, 'datadir': datadir, 'operator': operator, 'filter_size': filter_size, 'info': info, 'component': comp, 'imtdict': container.getIMTGrids(imtype, comp), 'ruptdict': copy.deepcopy(container.getRuptureDict()), 'stationdict': container.getStationDict(), 'config': model_config, 'tdict': text_dict } alist.append(d) if imtype == 'MMI': g = copy.deepcopy(d) g['imtype'] = 'thumbnail' alist.append(g) h = copy.deepcopy(d) h['imtype'] = 'overlay' alist.append(h) self.contents.addFile('intensityMap', 'Intensity Map', 'Map of macroseismic intensity.', 'intensity.jpg', 'image/jpeg') self.contents.addFile('intensityMap', 'Intensity Map', 'Map of macroseismic intensity.', 'intensity.pdf', 'application/pdf') self.contents.addFile('intensityThumbnail', 'Intensity Thumbnail', 'Thumbnail of intensity map.', 'pin-thumbnail.png', 'image/png') self.contents.addFile( 'intensityOverlay', 'Intensity Overlay and World File', 'Macroseismic intensity rendered as a ' 'PNG overlay and associated world file', 'intensity_overlay.png', 'image/png') self.contents.addFile( 'intensityOverlay', 'Intensity Overlay and World File', 'Macroseismic intensity rendered as a ' 'PNG overlay and associated world file', 'intensity_overlay.pngw', 'text/plain') else: fileimt = oq_to_file(imtype) self.contents.addFile(fileimt + 'Map', fileimt.upper() + ' Map', 'Map of ' + imtype + '.', fileimt + '.jpg', 'image/jpeg') self.contents.addFile(fileimt + 'Map', fileimt.upper() + ' Map', 'Map of ' + imtype + '.', fileimt + '.pdf', 'application/pdf') if max_workers > 0: with cf.ProcessPoolExecutor(max_workers=max_workers) as ex: results = ex.map(make_map, alist) list(results) else: for adict in alist: make_map(adict) container.close()
def main(fname, plot_dir): ds = xr.open_dataset(fname) bottom, top = np.min(ds.latitude).values, np.max(ds.latitude).values left, right = np.min(ds.longitude).values, np.max(ds.longitude).values ntime, nrows, ncols = ds.ndvi.shape """ st_count = 0 for i in range(ntime): year = int(str(ds.time[i].values)[0:4]) #if year == 1990: if year == 1983: break print(year, ds.time[i].values) st_count += 1 print(st_count) print(ds.time[st_count].values) sys.exit() """ #st_count = 6 # 1982 st_count = 18 # 1983 #st_count = 102 # 1990 # Get baseline period # 1993-1999 nyears = (1999 - 1983) + 1 ndvi_pre = np.zeros((nyears, nrows, ncols)) vals = np.zeros((3, nrows, ncols)) # summer yr_count = 0 count = st_count for year in np.arange(1983, 2000): for month in np.arange(1, 13): if month == 12: ndvi_count = np.zeros((nrows, ncols)) dat = ds.ndvi[count, :, :] dat = np.where(np.isnan(dat), 0.0, dat) ndvi_count = np.where(dat > 0.0, ndvi_count + 1, ndvi_count) ndvi_pre[yr_count, :, :] += dat dat = ds.ndvi[count + 1, :, :] dat = np.where(np.isnan(dat), 0.0, dat) ndvi_count = np.where(dat > 0.0, ndvi_count + 1, ndvi_count) ndvi_pre[yr_count, :, :] += dat dat = ds.ndvi[count + 2, :, :] dat = np.where(np.isnan(dat), 0.0, dat) ndvi_count = np.where(dat > 0.0, ndvi_count + 1, ndvi_count) ndvi_pre[yr_count, :, :] += dat ndvi_pre[yr_count, :, :] /= ndvi_count count += 1 yr_count += 1 ndvi_pre = np.mean(ndvi_pre, axis=0) ndvi_pre = np.flipud(ndvi_pre) ndvi_pre = np.where(ndvi_pre < 0.0, np.nan, ndvi_pre) # 2000-2009 nyears = 10 ndvi_dur = np.zeros((nyears, nrows, ncols)) yr_count = 0 for year in np.arange(2000, 2010): for month in np.arange(1, 13): if month == 12: print(ds.time[count].values, ds.time[count + 1].values, ds.time[count + 2].values) ndvi_count = np.zeros((nrows, ncols)) dat = ds.ndvi[count, :, :] dat = np.where(np.isnan(dat), 0.0, dat) ndvi_count = np.where(dat > 0.0, ndvi_count + 1, ndvi_count) ndvi_dur[yr_count, :, :] += dat dat = ds.ndvi[count + 1, :, :] dat = np.where(np.isnan(dat), 0.0, dat) ndvi_count = np.where(dat > 0.0, ndvi_count + 1, ndvi_count) ndvi_dur[yr_count, :, :] += dat dat = ds.ndvi[count + 2, :, :] dat = np.where(np.isnan(dat), 0.0, dat) ndvi_count = np.where(dat > 0.0, ndvi_count + 1, ndvi_count) ndvi_dur[yr_count, :, :] += dat ndvi_dur[yr_count, :, :] /= ndvi_count count += 1 yr_count += 1 ndvi_dur = np.mean(ndvi_dur, axis=0) ndvi_dur = np.flipud(ndvi_dur) ndvi_dur = np.where(ndvi_dur < 0.0, np.nan, ndvi_dur) chg = ((ndvi_dur - ndvi_pre) / ndvi_pre) * 100.0 fig = plt.figure(figsize=(9, 6)) plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.size'] = "14" plt.rcParams['font.sans-serif'] = "Helvetica" cmap = plt.cm.get_cmap('BrBG', 10) # discrete colour map projection = ccrs.PlateCarree() axes_class = (GeoAxes, dict(map_projection=projection)) rows = 1 cols = 1 axgr = AxesGrid(fig, 111, axes_class=axes_class, nrows_ncols=(rows, cols), axes_pad=0.2, cbar_location='right', cbar_mode='single', cbar_pad=0.5, cbar_size='5%', label_mode='') # note the empty label_mode for i, ax in enumerate(axgr): # add a subplot into the array of plots #ax = fig.add_subplot(rows, cols, i+1, projection=ccrs.PlateCarree()) plims = plot_map(ax, chg, cmap, i, top, bottom, left, right) import cartopy.feature as cfeature states = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='10m', facecolor='none') # plot state border SOURCE = 'Natural Earth' LICENSE = 'public domain' ax.add_feature(states, edgecolor='black', lw=0.5) cbar = axgr.cbar_axes[0].colorbar(plims) #cbar.ax.set_title("Percentage\ndifference(%)", fontsize=16) cbar.ax.set_title("% Difference", fontsize=16, pad=10) #cbar.ax.set_yticklabels([' ', '-30', '-15', '0', '15', '<=70']) props = dict(boxstyle='round', facecolor='white', alpha=0.0, ec="white") ax.text(0.95, 0.05, "(b)", transform=ax.transAxes, fontsize=12, verticalalignment='top', bbox=props) ofname = os.path.join(plot_dir, "ndvi.png") fig.savefig(ofname, dpi=300, bbox_inches='tight', pad_inches=0.1)
ax.coastlines(resolution='50m', color='green') ax2.coastlines(resolution='50m', color='green') ax3.coastlines(resolution='50m', color='green') ax9.coastlines(resolution='50m', color='green') # Add country borders with a thick line. ax.add_feature(cfeat.BORDERS, linewidth='1', edgecolor='green') ax2.add_feature(cfeat.BORDERS, linewidth='1', edgecolor='green') ax3.add_feature(cfeat.BORDERS, linewidth='1', edgecolor='green') ax9.add_feature(cfeat.BORDERS, linewidth='1', edgecolor='green') # Set up a feature for the state/province lines. Tell cartopy not to fill in the polygons state_boundaries = cfeat.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lakes', scale='50m', facecolor='none', edgecolor='red') # Add the feature with dotted lines, denoted by ':' ax.add_feature(state_boundaries, linestyle=':') ax2.add_feature(state_boundaries, linestyle=':') ax3.add_feature(state_boundaries, linestyle=':') ax9.add_feature(state_boundaries, linestyle=':') # axes for wi cbaxes1 = fig.add_axes([0.135, 0.12, 0.755, 0.02]) cbar1 = fig.colorbar(im, cax=cbaxes1, orientation='horizontal') font_size = 14 #cbar1.set_label('Brightness Temperature (K)',size=18) cbar1.ax.tick_params(labelsize=font_size)
import pyposeidon.grid as pg import numpy as np import pytest import os import geopandas as gp import cartopy.feature as cf cr = 'i' coast = cf.NaturalEarthFeature(category='physical', name='land', scale='{}m'.format({ 'l': 110, 'i': 50, 'h': 10 }[cr])) natural_earth = gp.GeoDataFrame(geometry=[x for x in coast.geometries()]) coast = cf.GSHHSFeature(scale='auto', levels=[1]) GSHHS = gp.GeoDataFrame(geometry=[x for x in coast.geometries()]) #define the lat/lon window and time frame of interest window0 = {'lon_min': -30, 'lon_max': -10., 'lat_min': 60., 'lat_max': 70.} window1 = { 'lon_min': 175., # lat/lon window 'lon_max': 184., 'lat_min': -21.5, 'lat_max': -14.5 }
def plot_all(dom): t1dom = time.perf_counter() print(('Working on ' + dom)) # Map corners for each domain llcrnrlon = np.min(lon) llcrnrlat = np.min(lat) urcrnrlon = np.max(lon) urcrnrlat = np.max(lat) lat_0 = Lat0 lon_0 = Lon0 extent = [llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat] # create figure and axes instances fig = plt.figure(figsize=(10, 10)) ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Define where Cartopy Maps are located cartopy.config['data_dir'] = CARTOPY_DIR os.environ["CARTOPY_USER_BACKGROUNDS"] = CARTOPY_DIR + '/raster_files' back_res = '50m' back_img = 'off' # set up the map background with cartopy myproj = ccrs.LambertConformal(central_longitude=lon_0, central_latitude=lat_0, false_easting=0.0, false_northing=0.0, secant_latitudes=None, standard_parallels=None, globe=None) ax = plt.axes(projection=myproj) ax.set_extent(extent) fline_wd = 0.5 # line width falpha = 0.3 # transparency # natural_earth # land=cfeature.NaturalEarthFeature('physical','land',back_res, # edgecolor='face',facecolor=cfeature.COLORS['land'], # alpha=falpha) lakes = cfeature.NaturalEarthFeature('physical', 'lakes', back_res, edgecolor='blue', facecolor='none', linewidth=fline_wd, alpha=falpha) coastline = cfeature.NaturalEarthFeature('physical', 'coastline', back_res, edgecolor='blue', facecolor='none', linewidth=fline_wd, alpha=falpha) states = cfeature.NaturalEarthFeature('cultural', 'admin_1_states_provinces', back_res, edgecolor='black', facecolor='none', linewidth=fline_wd, linestyle=':', alpha=falpha) borders = cfeature.NaturalEarthFeature('cultural', 'admin_0_countries', back_res, edgecolor='red', facecolor='none', linewidth=fline_wd, alpha=falpha) # high-resolution background images if back_img == 'on': ax.background_img(name='NE', resolution='high') # ax.add_feature(land) ax.add_feature(lakes) ax.add_feature(states) ax.add_feature(borders) ax.add_feature(coastline) # All lat lons are earth relative, so setup the associated projection correct for that data transform = ccrs.PlateCarree() # Map/figure has been set up here, save axes instances for use again later keep_ax_lst = ax.get_children()[:] ################################# # Plot Total QPF ################################# if (fhr > 0): # Do not make total QPF plot for forecast hour 0 t1 = time.perf_counter() print(('Working on total qpf for ' + dom)) units = 'in' clevs = [ 0.01, 0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5, 7, 10, 15, 20 ] clevsdif = [-3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3] colorlist = [ 'chartreuse', 'limegreen', 'green', 'blue', 'dodgerblue', 'deepskyblue', 'cyan', 'mediumpurple', 'mediumorchid', 'darkmagenta', 'darkred', 'crimson', 'orangered', 'darkorange', 'goldenrod', 'gold', 'yellow' ] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift, lat_shift, qpf, transform=transform, cmap=cm, vmin=0.01, norm=norm) cs_1.cmap.set_under('white', alpha=0.) cs_1.cmap.set_over('pink') cbar1 = plt.colorbar(cs_1, orientation='horizontal', pad=0.05, shrink=0.6, ticks=clevs, extend='max') cbar1.set_label(units, fontsize=8) cbar1.ax.set_xticklabels(clevs) cbar1.ax.tick_params(labelsize=8) ax.text(.5, 1.03, 'WRF ' + fhour + '-hr Accumulated Precipitation (' + units + ') \n initialized: ' + itime + ' valid: ' + vtime + ' (f' + fhour + ')', horizontalalignment='center', fontsize=8, transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.85, boxstyle='square,pad=0.2')) compress_and_save('qpf_' + dom + '_f' + fhour + '.png') t2 = time.perf_counter() t3 = round(t2 - t1, 3) print(('%.3f seconds to plot total qpf for: ' + dom) % t3) plt.clf()
def map_detec_nums(catalog, dirname, title='', numcolors=16, rmin=77, rmax=490, minmag=-5, pltevents=True): """Map detections and a grid of detection density. rmax=510 is white, rmin=0 is black. """ # generate bounds for map mask = catalog['mag'] >= minmag lllat, lllon, urlat, urlon, gridsize, hgridsize, _, clon = \ qcu.get_map_bounds(catalog[mask]) catalog = qcu.add_centers(catalog, gridsize) groupedlatlons, _, cmax = qcu.group_lat_lons(catalog, minmag=minmag) # print message if there are no detections with magnitudes above minmag if cmax == 0: print("No detections over magnitude %s" % minmag) # create color gradient from light red to dark red colors = qcu.range2rgb(rmin, rmax, numcolors) # put each center into its corresponding color group colorgroups = list(np.linspace(0, cmax, numcolors)) groupedlatlons.loc[:, 'group'] = np.digitize(groupedlatlons['count'], colorgroups) # create map plt.figure(figsize=(12, 7)) mplmap = plt.axes(projection=ccrs.PlateCarree(central_longitude=clon)) mplmap.set_extent([lllon, urlon, lllat, urlat], ccrs.PlateCarree()) mplmap.coastlines('50m') mplmap.add_feature(cfeature.BORDERS) mplmap.add_feature( cfeature.NaturalEarthFeature('cultural', 'admin_1_states_provinces_lines', '50m', facecolor='none', edgecolor='k', zorder=9)) plt.title(title, fontsize=20) plt.subplots_adjust(left=0.01, right=0.9, top=0.95, bottom=0.05) # create color map based on rmin and rmax cmap = LinearSegmentedColormap.from_list('CM', colors)._resample(numcolors) # make dummy plot for setting color bar colormesh = mplmap.pcolormesh(colors, colors, colors, cmap=cmap, alpha=1, vmin=0, vmax=cmax) # format color bar cbticks = [x for x in np.linspace(0, cmax, numcolors + 1)] cbar = plt.colorbar(colormesh, ticks=cbticks) cbar.ax.set_yticklabels([('%.0f' % x) for x in cbticks]) cbar.set_label('# of detections', rotation=270, labelpad=15) # plot rectangles with color corresponding to number of detections for center, _, cgroup in groupedlatlons.itertuples(): minlat, maxlat = center[0] - hgridsize, center[0] + hgridsize minlon, maxlon = center[1] - hgridsize, center[1] + hgridsize glats = [minlat, maxlat, maxlat, minlat] glons = [minlon, minlon, maxlon, maxlon] color = colors[cgroup - 1] qcu.draw_grid(glats, glons, color, alpha=0.8) # if provided, plot detection epicenters if pltevents and not catalog['mag'].isnull().all(): magmask = catalog['mag'] >= minmag lons = list(catalog['longitude'][magmask]) lats = list(catalog['latitude'][magmask]) mplmap.scatter(lons, lats, c='k', s=7, marker='x', zorder=5) elif catalog['mag'].isnull().all(): lons = list(catalog['longitude']) lats = list(catalog['latitude']) mplmap.scatter(lons, lats, c='k', s=7, marker='x', zorder=5) plt.savefig('%s_eqdensity.png' % dirname, dpi=300) plt.close()
import cartopy.feature as cfeature import cartopy # Edinburgh, Glasgow, Aberdeen lons = [-3.188267, -4.25763, -2.099075] lats = [55.9533, 55.86515, 57.149651] plt.figure(figsize=(10, 10)) ax = plt.axes(projection=ccrs.Mercator()) ax.coastlines('10m') # Add grey for the land land_10m = cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor=cfeature.COLORS['land']) ax.add_feature(land_10m, edgecolor='gray') ax.xaxis.set_visible(True) ax.yaxis.set_visible(True) ax.set_yticks([56, 57, 58, 59], crs=ccrs.PlateCarree()) ax.set_xticks([-8, -6, -4, -2], crs=ccrs.PlateCarree()) lon_formatter = LongitudeFormatter(zero_direction_label=True, number_format='d') lat_formatter = LatitudeFormatter()
def plot_cartopy(lons, lats, size, color, labels=None, projection='global', resolution='110m', continent_fill_color='0.8', water_fill_color='1.0', colormap=None, colorbar=None, marker="o", title=None, colorbar_ticklabel_format=None, show=True, proj_kwargs=None, **kwargs): # @UnusedVariable """ Creates a Cartopy plot with a data point scatter plot. :type lons: list/tuple of floats :param lons: Longitudes of the data points. :type lats: list/tuple of floats :param lats: Latitudes of the data points. :type size: float or list/tuple of floats :param size: Size of the individual points in the scatter plot. :type color: list/tuple of floats (or objects that can be converted to floats, like e.g. :class:`~obspy.core.utcdatetime.UTCDateTime`) :param color: Color information of the individual data points to be used in the specified color map (e.g. origin depths, origin times). :type labels: list/tuple of str :param labels: Annotations for the individual data points. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world using :class:`~cartopy.crs.Mollweide`.) * ``"ortho"`` (Will center around the mean lat/long using :class:`~cartopy.crs.Orthographic`.) * ``"local"`` (Will plot around local events using :class:`~cartopy.crs.AlbersEqualArea`.) * Any other Cartopy :class:`~cartopy.crs.Projection`. An instance of this class will be created using the supplied ``proj_kwargs``. Defaults to "global" :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be passed directly to the Cartopy module. Possible values are: * ``"110m"`` * ``"50m"`` * ``"10m"`` Defaults to ``"110m"``. For compatibility, you may also specify any of the Basemap resolutions defined in :func:`plot_basemap`. :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type colormap: str, any matplotlib colormap, optional :param colormap: The colormap for color-coding the events as provided in `color` kwarg. The event with the smallest `color` property will have the color of one end of the colormap and the event with the highest `color` property the color of the other end with all other events in between. Defaults to None which will use the default matplotlib colormap. :type colorbar: bool, optional :param colorbar: When left `None`, a colorbar is plotted if more than one object is plotted. Using `True`/`False` the colorbar can be forced on/off. :type title: str :param title: Title above plot. :type colorbar_ticklabel_format: str or function or subclass of :class:`matplotlib.ticker.Formatter` :param colorbar_ticklabel_format: Format string or Formatter used to format colorbar tick labels. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. :type proj_kwargs: dict :param proj_kwargs: Keyword arguments to pass to the Cartopy :class:`~cartopy.ccrs.Projection`. In this dictionary, you may specify ``central_longitude='auto'`` or ``central_latitude='auto'`` to have this function calculate the latitude or longitude as it would for other projections. Some arguments may be ignored if you choose one of the built-in ``projection`` choices. """ import matplotlib.pyplot as plt if isinstance(color[0], (datetime.datetime, UTCDateTime)): datetimeplot = True color = [date2num(getattr(t, 'datetime', t)) for t in color] else: datetimeplot = False fig = plt.figure() # The colorbar should only be plotted if more then one event is # present. if colorbar is not None: show_colorbar = colorbar else: if len(lons) > 1 and hasattr(color, "__len__") and \ not isinstance(color, (str, native_str)): show_colorbar = True else: show_colorbar = False if projection == "local": ax_x0, ax_width = 0.10, 0.80 elif projection == "global": ax_x0, ax_width = 0.01, 0.98 else: ax_x0, ax_width = 0.05, 0.90 proj_kwargs = proj_kwargs or {} if projection == 'global': proj_kwargs['central_longitude'] = np.mean(lons) proj = ccrs.Mollweide(**proj_kwargs) elif projection == 'ortho': proj_kwargs['central_latitude'] = np.mean(lats) proj_kwargs['central_longitude'] = mean_longitude(lons) proj = ccrs.Orthographic(**proj_kwargs) elif projection == 'local': if min(lons) < -150 and max(lons) > 150: max_lons = max(np.array(lons) % 360) min_lons = min(np.array(lons) % 360) else: max_lons = max(lons) min_lons = min(lons) lat_0 = max(lats) / 2. + min(lats) / 2. lon_0 = max_lons / 2. + min_lons / 2. if lon_0 > 180: lon_0 -= 360 deg2m_lat = 2 * np.pi * 6371 * 1000 / 360 deg2m_lon = deg2m_lat * np.cos(lat_0 / 180 * np.pi) if len(lats) > 1: height = (max(lats) - min(lats)) * deg2m_lat width = (max_lons - min_lons) * deg2m_lon margin = 0.2 * (width + height) height += margin width += margin else: height = 2.0 * deg2m_lat width = 5.0 * deg2m_lon # Do intelligent aspect calculation for local projection # adjust to figure dimensions w, h = fig.get_size_inches() aspect = w / h if show_colorbar: aspect *= 1.2 if width / height < aspect: width = height * aspect else: height = width / aspect proj_kwargs['central_latitude'] = lat_0 proj_kwargs['central_longitude'] = lon_0 proj_kwargs['standard_parallels'] = [lat_0, lat_0] proj = ccrs.AlbersEqualArea(**proj_kwargs) # User-supplied projection. elif isinstance(projection, type): if 'central_longitude' in proj_kwargs: if proj_kwargs['central_longitude'] == 'auto': proj_kwargs['central_longitude'] = mean_longitude(lons) if 'central_latitude' in proj_kwargs: if proj_kwargs['central_latitude'] == 'auto': proj_kwargs['central_latitude'] = np.mean(lats) if 'pole_longitude' in proj_kwargs: if proj_kwargs['pole_longitude'] == 'auto': proj_kwargs['pole_longitude'] = np.mean(lons) if 'pole_latitude' in proj_kwargs: if proj_kwargs['pole_latitude'] == 'auto': proj_kwargs['pole_latitude'] = np.mean(lats) proj = projection(**proj_kwargs) else: msg = "Projection '%s' not supported." % projection raise ValueError(msg) if show_colorbar: map_ax = fig.add_axes([ax_x0, 0.13, ax_width, 0.77], projection=proj) cm_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.05]) plt.sca(map_ax) else: ax_y0, ax_height = 0.05, 0.85 if projection == "local": ax_y0 += 0.05 ax_height -= 0.05 map_ax = fig.add_axes([ax_x0, ax_y0, ax_width, ax_height], projection=proj) if projection == 'local': x0, y0 = proj.transform_point(lon_0, lat_0, proj.as_geodetic()) map_ax.set_xlim(x0 - width / 2, x0 + width / 2) map_ax.set_ylim(y0 - height / 2, y0 + height / 2) else: map_ax.set_global() # Pick features at specified resolution. resolution = _CARTOPY_RESOLUTIONS[resolution] try: borders, land, ocean = _CARTOPY_FEATURES[resolution] except KeyError: borders = cfeature.NaturalEarthFeature(cfeature.BORDERS.category, cfeature.BORDERS.name, resolution, edgecolor='none', facecolor='none') land = cfeature.NaturalEarthFeature(cfeature.LAND.category, cfeature.LAND.name, resolution, edgecolor='face', facecolor='none') ocean = cfeature.NaturalEarthFeature(cfeature.OCEAN.category, cfeature.OCEAN.name, resolution, edgecolor='face', facecolor='none') _CARTOPY_FEATURES[resolution] = (borders, land, ocean) # Draw coast lines, country boundaries, fill continents. if MATPLOTLIB_VERSION >= [2, 0, 0]: map_ax.set_facecolor(water_fill_color) else: map_ax.set_axis_bgcolor(water_fill_color) map_ax.add_feature(ocean, facecolor=water_fill_color) map_ax.add_feature(land, facecolor=continent_fill_color) map_ax.add_feature(borders, edgecolor='0.75') map_ax.coastlines(resolution=resolution, color='0.4') # Draw grid lines - TODO: draw_labels=True doesn't work yet. if projection == 'local': map_ax.gridlines() else: # Draw lat/lon grid lines every 30 degrees. map_ax.gridlines(xlocs=range(-180, 181, 30), ylocs=range(-90, 91, 30)) # Plot labels if labels and len(lons) > 0: with map_ax.hold_limits(): for name, xpt, ypt, _colorpt in zip(labels, lons, lats, color): map_ax.text(xpt, ypt, name, weight="heavy", color="k", zorder=100, transform=ccrs.Geodetic(), path_effects=[ patheffects.withStroke(linewidth=3, foreground="white") ]) scatter = map_ax.scatter(lons, lats, marker=marker, s=size, c=color, zorder=10, cmap=colormap, transform=ccrs.Geodetic()) if title: plt.suptitle(title) # Only show the colorbar for more than one event. if show_colorbar: if colorbar_ticklabel_format is not None: if isinstance(colorbar_ticklabel_format, (str, native_str)): formatter = FormatStrFormatter(colorbar_ticklabel_format) elif hasattr(colorbar_ticklabel_format, '__call__'): formatter = FuncFormatter(colorbar_ticklabel_format) elif isinstance(colorbar_ticklabel_format, Formatter): formatter = colorbar_ticklabel_format locator = MaxNLocator(5) else: if datetimeplot: locator = AutoDateLocator() formatter = AutoDateFormatter(locator) # Compat with old matplotlib versions. if hasattr(formatter, "scaled"): formatter.scaled[1 / (24. * 60.)] = '%H:%M:%S' else: locator = None formatter = None cb = Colorbar(cm_ax, scatter, cmap=colormap, orientation='horizontal', ticks=locator, format=formatter) # Compat with old matplotlib versions. if hasattr(cb, "update_ticks"): cb.update_ticks() if show: plt.show() return fig
def add_geoaxes(fig, *args, xtick=None, ytick=None, zero_direction_label=False, dateline_direction_label=False, number_format='g', degree_symbol=u'\u00B0', cl_res='110m', cl_color=None, lw=None, title=None, countries=False, states=False, **kwargs): """ Add a GeoAxes instance to Figure (fig) instance. Parameters ---------- fig : Figure *args It is idential to *args in fig.add_subplot **kwargs It is idential to **kwargs in fig.add_subplot xtick : Longitude ytick : Latitude zero_direction_label : Direction label at 0 degree longitude dateline_direction_label : Direction label at 180 degree longitude number_format : degree_symbol : cl_res : str Coastline resolution. Currently can be one of “110m”, “50m”, and “10m” title : str or None(default) title countries : bool Plot countries states : bool Plot states and provinces Returns ------- ax : GeoAxes """ # Set some default variables if xtick is None: xtick = np.arange(-180, 180.1, 60) if ytick is None: ytick = np.arange(-90, 90.1, 30) # Default projection kwargs['projection'] = kwargs.get('projection', ccrs.PlateCarree()) crs = kwargs.get('projection') ax = fig.add_subplot(*args, **kwargs) if cl_color is None: cl_color = 'black' ax.coastlines(resolution=cl_res, color=cl_color, lw=lw) if countries: ax.add_feature(cfeature.BORDERS) if states: states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax.add_feature(states_provinces, edgecolor='k', linewidth=0.5) # Tick labels tick_proj = ['PlateCarree', 'Mercator'] proj = str(type(ax.projection)).split('.')[-1][0:-2] if proj in tick_proj: ax.set_xticks(xtick, crs=ccrs.PlateCarree()) ax.set_yticks(ytick, crs=ccrs.PlateCarree()) lon_formatter = LongitudeFormatter( zero_direction_label=zero_direction_label, dateline_direction_label=dateline_direction_label, number_format=number_format, degree_symbol=degree_symbol) lat_formatter = LatitudeFormatter(number_format=number_format, degree_symbol=degree_symbol) ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) # title if title is not None: ax.set_title(title) return ax
def plot_all(dom): t1dom = time.perf_counter() print(('Working on '+dom)) # Map corners for each domain llcrnrlon = np.min(lon) llcrnrlat = np.min(lat) urcrnrlon = np.max(lon) urcrnrlat = np.max(lat) lat_0 = Lat0 lon_0 = Lon0 extent=[llcrnrlon,urcrnrlon,llcrnrlat-1,urcrnrlat] # create figure and axes instances fig = plt.figure(figsize=(10,10)) ax1 = fig.add_axes([0.1,0.1,0.8,0.8]) # Define where Cartopy Maps are located cartopy.config['data_dir'] = CARTOPY_DIR os.environ["CARTOPY_USER_BACKGROUNDS"]=CARTOPY_DIR+'/raster_files' back_res='50m' back_img='off' # set up the map background with cartopy myproj=ccrs.LambertConformal(central_longitude=lon_0, central_latitude=lat_0, false_easting=0.0, false_northing=0.0, secant_latitudes=None, standard_parallels=None, globe=None) ax = plt.axes(projection=myproj) ax.set_extent(extent) fline_wd = 0.5 # line width falpha = 0.3 # transparency # natural_earth # land=cfeature.NaturalEarthFeature('physical','land',back_res, # edgecolor='face',facecolor=cfeature.COLORS['land'], # alpha=falpha) lakes=cfeature.NaturalEarthFeature('physical','lakes',back_res, edgecolor='blue',facecolor='none', linewidth=fline_wd,alpha=falpha) coastline=cfeature.NaturalEarthFeature('physical','coastline', back_res,edgecolor='blue',facecolor='none', linewidth=fline_wd,alpha=falpha) states=cfeature.NaturalEarthFeature('cultural','admin_1_states_provinces', back_res,edgecolor='black',facecolor='none', linewidth=fline_wd,linestyle=':',alpha=falpha) borders=cfeature.NaturalEarthFeature('cultural','admin_0_countries', back_res,edgecolor='red',facecolor='none', linewidth=fline_wd,alpha=falpha) # high-resolution background images if back_img=='on': ax.background_img(name='NE', resolution='high') # ax.add_feature(land) ax.add_feature(lakes) ax.add_feature(states) ax.add_feature(borders) ax.add_feature(coastline) # All lat lons are earth relative, so setup the associated projection correct for that data transform = ccrs.PlateCarree() # Map/figure has been set up here, save axes instances for use again later keep_ax_lst = ax.get_children()[:] ################################ # Plot SLP ################################ t1 = time.perf_counter() print(('Working on slp for '+dom)) units = 'mb' clevs = [976,980,984,988,992,996,1000,1004,1008,1012,1016,1020,1024,1028,1032,1036,1040,1044,1048,1052] clevsdif = [-12,-10,-8,-6,-4,-2,0,2,4,6,8,10,12] cm = plt.cm.Spectral_r norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs1_a = plt.pcolormesh(lon_shift,lat_shift,slp,transform=transform,cmap=cm,norm=norm) cbar1 = plt.colorbar(cs1_a,orientation='horizontal',pad=0.05,shrink=0.6,extend='both') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) cs1_b = plt.contour(lon_shift,lat_shift,slpsmooth,np.arange(940,1060,4),colors='black',linewidths=1.25,transform=transform) plt.clabel(cs1_b,np.arange(940,1060,4),inline=1,fmt='%d',fontsize=8) ax.text(.5,1.03,'FV3-LAM SLP ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('slp_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot slp for: '+dom) % t3) ################################# # Plot 2-m T ################################# t1 = time.perf_counter() print(('Working on t2m for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = '\xb0''F' clevs = np.linspace(-16,134,51) cm = cmap_t2m() norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,tmp2m,transform=transform,cmap=cm,norm=norm) cs_1.cmap.set_under('white') cs_1.cmap.set_over('white') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=[-16,-4,8,20,32,44,56,68,80,92,104,116,128],extend='both') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) ax.text(.5,1.03,'FV3-LAM 2-m Temperature ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('2mt_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot 2mt for: '+dom) % t3) ################################# # Plot 2-m Dew Point ################################# t1 = time.perf_counter() print(('Working on 2mdew for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = '\xb0''F' clevs = np.linspace(-5,80,35) cm = cmap_q2m() norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,dew2m,transform=transform,cmap=cm,norm=norm) cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,extend='both') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) ax.text(.5,1.03,'FV3-LAM 2-m Dew Point Temperature ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('2mdew_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot 2mdew for: '+dom) % t3) ################################# # Plot 10-m WSPD ################################# t1 = time.perf_counter() print(('Working on 10mwspd for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'kts' skip = 50 barblength = 4 clevs = [5,10,15,20,25,30,35,40,45,50,55,60] colorlist = ['turquoise','dodgerblue','blue','#FFF68F','#E3CF57','peru','brown','crimson','red','fuchsia','DarkViolet'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,wspd10m,transform=transform,cmap=cm,vmin=5,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('black') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) plt.barbs(lon_shift[::skip,::skip],lat_shift[::skip,::skip],uwind[::skip,::skip],vwind[::skip,::skip],length=barblength,linewidth=0.5,color='black',transform=transform) ax.text(.5,1.03,'FV3-LAM 10-m Winds ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('10mwind_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot 10mwspd for: '+dom) % t3) ################################# # Plot Surface-Based CAPE/CIN ################################# t1 = time.perf_counter() print(('Working on surface-based CAPE/CIN for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'J/kg' clevs = [100,250,500,1000,1500,2000,2500,3000,3500,4000,4500,5000] clevs2 = [-2000,-500,-250,-100,-25] colorlist = ['lightblue','blue','dodgerblue','cyan','mediumspringgreen','#FAFAD2','#EEEE00','#EEC900','darkorange','crimson','darkred'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,cape,transform=transform,cmap=cm,vmin=100,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('darkviolet') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) cs_1b = plt.contourf(lon_shift,lat_shift,cin,clevs2,colors='none',hatches=['**','++','////','..'],transform=transform) ax.text(.5,1.05,'FV3-LAM Surface-Based CAPE (shaded) and CIN (hatched) ('+units+') \n <-500 (*), -500<-250 (+), -250<-100 (/), -100<-25 (.) \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('sfcape_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot surface-based CAPE/CIN for: '+dom) % t3) ################################# # Plot 500 mb HGT/WIND/VORT ################################# # t1 = time.perf_counter() # print(('Working on 500 mb Hgt/Wind/Vort for '+dom)) # # # Clear off old plottables but keep all the map info # cbar1.remove() # clear_plotables(ax,keep_ax_lst,fig) # # units = 'x10${^5}$ s${^{-1}}$' # skip = 70 # barblength = 4 # # vortlevs = [16,20,24,28,32,36,40] # colorlist = ['yellow','gold','goldenrod','orange','orangered','red'] # cm = matplotlib.colors.ListedColormap(colorlist) # norm = matplotlib.colors.BoundaryNorm(vortlevs, cm.N) # # cs1_a = plt.pcolormesh(lon_shift,lat_shift,vort500,transform=transform,cmap=cm,norm=norm) # cs1_a.cmap.set_under('white') # cs1_a.cmap.set_over('darkred') # cbar1 = plt.colorbar(cs1_a,orientation='horizontal',pad=0.05,shrink=0.6,ticks=vortlevs,extend='both') # cbar1.set_label(units,fontsize=8) # cbar1.ax.tick_params(labelsize=8) # plt.barbs(lon_shift[::skip,::skip],lat_shift[::skip,::skip],u500[::skip,::skip],v500[::skip,::skip],length=barblength,linewidth=0.5,color='steelblue',transform=transform) # cs1_b = plt.contour(lon_shift,lat_shift,z500,np.arange(486,600,6),colors='black',linewidths=1,transform=transform) # plt.clabel(cs1_b,np.arange(486,600,6),inline_spacing=1,fmt='%d',fontsize=8) # ax.text(.5,1.03,'FV3-LAM 500 mb Heights (dam), Winds (kts), and $\zeta$ ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) # # compress_and_save('500_'+dom+'_f'+fhour+'.png') # t2 = time.perf_counter() # t3 = round(t2-t1, 3) # print(('%.3f seconds to plot 500 mb Hgt/Wind/Vort for: '+dom) % t3) ################################# # Plot 250 mb WIND ################################# t1 = time.perf_counter() print(('Working on 250 mb WIND for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'kts' skip = 70 barblength = 4 clevs = [50,60,70,80,90,100,110,120,130,140,150] colorlist = ['turquoise','deepskyblue','dodgerblue','#1874CD','blue','beige','khaki','peru','brown','crimson'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,wspd250,transform=transform,cmap=cm,vmin=50,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('red') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) plt.barbs(lon_shift[::skip,::skip],lat_shift[::skip,::skip],u250[::skip,::skip],v250[::skip,::skip],length=barblength,linewidth=0.5,color='black',transform=transform) ax.text(.5,1.03,'FV3-LAM 250 mb Winds ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('250wind_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot 250 mb WIND for: '+dom) % t3) ################################# # Plot Total QPF ################################# if (fhr > 0): # Do not make total QPF plot for forecast hour 0 t1 = time.perf_counter() print(('Working on total qpf for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'in' clevs = [0.01,0.1,0.25,0.5,0.75,1,1.25,1.5,1.75,2,2.5,3,4,5,7,10,15,20] clevsdif = [-3,-2.5,-2,-1.5,-1,-0.5,0,0.5,1,1.5,2,2.5,3] colorlist = ['chartreuse','limegreen','green','blue','dodgerblue','deepskyblue','cyan','mediumpurple','mediumorchid','darkmagenta','darkred','crimson','orangered','darkorange','goldenrod','gold','yellow'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,qpf,transform=transform,cmap=cm,vmin=0.01,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('pink') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.set_xticklabels(clevs) cbar1.ax.tick_params(labelsize=8) ax.text(.5,1.03,'FV3-LAM '+fhour+'-hr Accumulated Precipitation ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('qpf_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot total qpf for: '+dom) % t3) ################################# # Plot composite reflectivity ################################# t1 = time.perf_counter() print(('Working on composite reflectivity for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'dBZ' clevs = np.linspace(5,70,14) clevsdif = [20,1000] colorlist = ['turquoise','dodgerblue','mediumblue','lime','limegreen','green','#EEEE00','#EEC900','darkorange','red','firebrick','darkred','fuchsia'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,refc,transform=transform,cmap=cm,vmin=5,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('black') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) ax.text(.5,1.03,'FV3-LAM Composite Reflectivity ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('refc_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot composite reflectivity for: '+dom) % t3) ################################# # Plot Max/Min Hourly 2-5 km UH ################################# # if (fhr > 0): # Do not make max/min hourly 2-5 km UH plot for forecast hour 0 # t1 = time.perf_counter() # print(('Working on Max/Min Hourly 2-5 km UH for '+dom)) # # # Clear off old plottables but keep all the map info # cbar1.remove() # clear_plotables(ax,keep_ax_lst,fig) # # units = 'm${^2}$ s$^{-2}$' # clevs = [-150,-100,-75,-50,-25,-10,0,10,25,50,75,100,150,200,250,300] ## alternative colormap for just max UH if you don't want to plot the min UH too ## colorlist = ['white','skyblue','mediumblue','green','orchid','firebrick','#EEC900','DarkViolet'] # colorlist = ['blue','#1874CD','dodgerblue','deepskyblue','turquoise','#E5E5E5','#E5E5E5','#EEEE00','#EEC900','darkorange','orangered','red','firebrick','mediumvioletred','darkviolet'] # cm = matplotlib.colors.ListedColormap(colorlist) # norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) # # cs_1 = plt.pcolormesh(lon_shift,lat_shift,uh25,transform=transform,cmap=cm,norm=norm) # cs_1.cmap.set_under('darkblue') # cs_1.cmap.set_over('black') # cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,extend='both') # cbar1.set_label(units,fontsize=8) # cbar1.ax.tick_params(labelsize=8) # ax.text(.5,1.03,'FV3-LAM 1-h Max/Min 2-5 km Updraft Helicity ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) # # compress_and_save('uh25_'+dom+'_f'+fhour+'.png') # t2 = time.perf_counter() # t3 = round(t2-t1, 3) # print(('%.3f seconds to plot Max/Min Hourly 2-5 km UH for: '+dom) % t3) # ###################################################### t3dom = round(t2-t1dom, 3) print(("%.3f seconds to plot all variables for: "+dom) % t3dom) plt.clf()
def eReefs_map(ncdata, tstep, depth, dataname, datalvl, color, size, fname, vecsample, veclenght, vecscale, zoom=None, show=False, vecPlot=False, save=False): ''' This function plots for a specified time index and depth the value of a variable from the eReefs netCDF file available on the AIMS OpenDAP server. args: - ncdata: netcdf dataset - tstep: specified time index - depth: specified depth layer - dataname: specified variable name - datalvl: range of the variable values specified as a list [min,max] - color: colormap to use for the plot (here one can use the cmocean library) - size: figure size - fname: figure name when saved on disk, specified time and depth layer index added - vecsample: sampling on velocity arrows to plot on the maps when velocity verctor are used - veclenght: lenght of the reference vector (in m/s) - vecscale: vector scaling - zoom: study site to plot lower left and upper right corner [lon0,lat0, lon1, lat1] - show: set to True when the map is shown in the jupyter environment directly - vecPlot: set to True when the current flow vector are plotted - save: set to True to save figure on disk ''' # Get data data = ncdata[dataname][tstep, depth, :, :] fig = plt.figure(figsize=size, facecolor='w', edgecolor='k') ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([142.4, 157, -7, -28.6], ccrs.PlateCarree()) # Starting with the spatial domain lat = ncdata['latitude'][:] lon = ncdata['longitude'][:] cf = plt.pcolormesh(lon, lat, data, cmap=color, shading='auto', vmin=datalvl[0], vmax=datalvl[1], transform=ccrs.PlateCarree()) # Plot velocity arrows if vecPlot: loni, lati = np.meshgrid(lon, lat) u = ncdata['u'][tstep, depth, :, :] v = ncdata['v'][tstep, depth, :, :] if zoom is not None: # find non zeros velocity points dataid = np.where( np.logical_and(data.flatten() > datalvl[0], data.flatten() < datalvl[1]))[0] lonid = np.where( np.logical_and(loni.flatten() > zoom[0], loni.flatten() < zoom[2]))[0] latid = np.where( np.logical_and(lati.flatten() > zoom[1], lati.flatten() < zoom[3]))[0] tmpid = np.intersect1d(lonid, latid) ind = np.intersect1d(tmpid, dataid) else: # find non zeros velocity points ind = np.where( np.logical_and(data.flatten() > datalvl[0], data.flatten() < datalvl[1]))[0] np.random.shuffle(ind) Nvec = int(len(ind) / vecsample) idv = ind[:Nvec] Q = plt.quiver(loni.flatten()[idv], lati.flatten()[idv], u.flatten()[idv], v.flatten()[idv], transform=ccrs.PlateCarree(), scale=vecscale) maxstr = '%3.1f m/s' % veclenght qk = plt.quiverkey(Q, 0.1, 0.1, veclenght, maxstr, labelpos='S') # Color bar cbar = fig.colorbar(cf, ax=ax, fraction=0.027, pad=0.045, orientation="horizontal") cbar.set_label(ncdata[dataname].units, rotation=0, labelpad=5, fontsize=10) cbar.ax.tick_params(labelsize=8) # Title dtime = netCDF4.num2date(ncdata['time'][tstep], ncdata['time'].units) daystr = dtime.strftime('%Y-%b-%d %H:%M') plt.title(ncdata[dataname].long_name + ', %s UTC+10' % (daystr), fontsize=11) # Plot lat/lon grid gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.1, color='k', alpha=1, linestyle='--') gl.top_labels = False gl.right_labels = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 8} gl.ylabel_style = {'size': 8} # Add map features ax.add_feature( cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor='lightgray')) ax.coastlines(linewidth=1) if zoom is not None: plt.xlim(zoom[0], zoom[2]) plt.ylim(zoom[1], zoom[3]) if show: if save: plt.savefig(f"{fname}_time{tstep:04}_zc{depth:04}.png", dpi=300, bbox_inches='tight') plt.tight_layout() plt.show() else: plt.savefig(f"{fname}_time{tstep:04}_zc{depth:04}.png", dpi=300, bbox_inches='tight') fig.clear() plt.close(fig) plt.clf() return
def plot_all(dom): t1dom = time.perf_counter() print(('Working on ' + dom)) # Map corners for each domain llcrnrlon = np.min(lon) llcrnrlat = np.min(lat) urcrnrlon = np.max(lon) urcrnrlat = np.max(lat) lat_0 = Lat0 lon_0 = Lon0 extent = [llcrnrlon, urcrnrlon, llcrnrlat - 1, urcrnrlat] # create figure and axes instances fig = plt.figure(figsize=(10, 10)) ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Define where Cartopy Maps are located cartopy.config['data_dir'] = CARTOPY_DIR os.environ["CARTOPY_USER_BACKGROUNDS"] = CARTOPY_DIR + '/raster_files' back_res = '50m' back_img = 'off' # set up the map background with cartopy myproj = ccrs.LambertConformal(central_longitude=lon_0, central_latitude=lat_0, false_easting=0.0, false_northing=0.0, secant_latitudes=None, standard_parallels=None, globe=None) ax = plt.axes(projection=myproj) ax.set_extent(extent) fline_wd = 0.5 # line width falpha = 0.3 # transparency # natural_earth # land=cfeature.NaturalEarthFeature('physical','land',back_res, # edgecolor='face',facecolor=cfeature.COLORS['land'], # alpha=falpha) lakes = cfeature.NaturalEarthFeature('physical', 'lakes', back_res, edgecolor='blue', facecolor='none', linewidth=fline_wd, alpha=falpha) coastline = cfeature.NaturalEarthFeature('physical', 'coastline', back_res, edgecolor='blue', facecolor='none', linewidth=fline_wd, alpha=falpha) states = cfeature.NaturalEarthFeature('cultural', 'admin_1_states_provinces', back_res, edgecolor='black', facecolor='none', linewidth=fline_wd, linestyle=':', alpha=falpha) borders = cfeature.NaturalEarthFeature('cultural', 'admin_0_countries', back_res, edgecolor='red', facecolor='none', linewidth=fline_wd, alpha=falpha) # high-resolution background images if back_img == 'on': ax.background_img(name='NE', resolution='high') # ax.add_feature(land) ax.add_feature(lakes) ax.add_feature(states) ax.add_feature(borders) ax.add_feature(coastline) # All lat lons are earth relative, so setup the associated projection correct for that data transform = ccrs.PlateCarree() # Map/figure has been set up here, save axes instances for use again later keep_ax_lst = ax.get_children()[:] ################################# # Plot 2-m Dew Point ################################# t1 = time.perf_counter() print(('Working on 2mdew for ' + dom)) units = '\xb0' 'F' clevs = np.linspace(-5, 80, 35) cm = cmap_q2m() norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift, lat_shift, dew2m, transform=transform, cmap=cm, norm=norm) cbar1 = plt.colorbar(cs_1, orientation='horizontal', pad=0.05, shrink=0.6, extend='both') cbar1.set_label(units, fontsize=8) cbar1.ax.tick_params(labelsize=8) ax.text(.5, 1.03, 'WRF 2-m Dew Point Temperature (' + units + ') \n initialized: ' + itime + ' valid: ' + vtime + ' (f' + fhour + ')', horizontalalignment='center', fontsize=8, transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.85, boxstyle='square,pad=0.2')) compress_and_save('2mdew_' + dom + '_f' + fhour + '.png') t2 = time.perf_counter() t3 = round(t2 - t1, 3) print(('%.3f seconds to plot 2mdew for: ' + dom) % t3) plt.clf()
# cmap=cm.seismic #cmap.set_under("w",alpha=0) cmap=cm.get_cmap("rainbow_r") cmapL=cmap #cm.get_cmap("rainbow_r") vmin=0.0 vmax=2000.0 norm=Normalize(vmin=vmin,vmax=vmax) hgt=11.69*(1.0/3.0) wdt=8.27 fig=plt.figure(figsize=(wdt, hgt)) G = gridspec.GridSpec(1,1) ax=fig.add_subplot(G[0,0],projection=ccrs.Robinson()) #----------------------------- ax.set_extent([lllon,urlon,lllat,urlat],crs=ccrs.PlateCarree()) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor=land),zorder=100) # pnum=len(nums) for point in np.arange(pnum): eled=leled[point] lon =lons[point] lat =lats[point] c=cmapL(norm(eled)) #print lon,lat,pname[point][0],mean_bias ax.scatter(lon,lat,s=0.5,marker="o",zorder=110,edgecolors=c, facecolors=c,transform=ccrs.PlateCarree()) #-- im=ax.scatter([],[],c=[],cmap=cmapL,s=0.1,vmin=vmin,vmax=vmax,norm=norm)# im.set_visible(False) #cbar=M.colorbar(im,"right",size="2%") ax.outline_patch.set_linewidth(0.0) #colorbar
import plotly.graph_objects as go import numpy as np import pandas as pd import subprocess try: #mapping tool (~GMT) import cartopy.crs as ccrs import cartopy.feature as cfea import cartopy.io.shapereader as shapereader from cartopy.feature import ShapelyFeature # initial setting... color_polygon = "k" lakes_ = cfea.NaturalEarthFeature('physical', 'lakes', '10m', edgecolor=color_polygon, facecolor="none", linewidth=0.5) states_ = cfea.NaturalEarthFeature('cultural', 'admin_1_states_provinces_lines', '10m', edgecolor=color_polygon, facecolor='none', linewidth=0.2) except: print("cartoy not install...") import cv2 # "/home/ysorimachi/.conda/envs/sori_conda/lib/python3.7/site-packages/cv2.cpython-37m-x86_64-linux-gnu.so"
lons = nc_fid.variables['longitude'][:].squeeze() lats = nc_fid.variables['latitude'][:].squeeze() lon2d, lat2d = np.meshgrid(lons, lats) # prectot de l annee courant fig = plt.figure(figsize=(28, 16)) ax = plt.subplot(111, projection=ccrs.LambertConformal()) ax.set_extent([-82, -72, 45, 48]) # ax.coastlines(resolution='110m'); ax.add_feature(cfeature.OCEAN.with_scale('50m')) # couche ocean ax.add_feature(cfeature.LAND.with_scale('50m')) # couche land ax.add_feature(cfeature.LAKES.with_scale('50m')) # couche lac ax.add_feature(cfeature.BORDERS.with_scale('50m')) # couche frontieres ax.add_feature(cfeature.RIVERS.with_scale('50m')) # couche rivières coast = cfeature.NaturalEarthFeature( category='physical', scale='10m', # ajout de la couche cotière facecolor='none', name='coastline') ax.add_feature(coast, edgecolor='black') states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='10m', facecolor='none') ax.add_feature(states_provinces, edgecolor='gray') ## Choisissons une colormap cmap0 = plt.cm.jet cmap0.set_under(
# Set up our array of latitude and longitude values and transform to # the desired projection. tlatlons = crs.transform_points(ccrs.PlateCarree(), lon, lat) tlons = tlatlons[:, :, 0] tlats = tlatlons[:, :, 1] # Coordinates to limit map area bounds = [(-122., -75., 25., 50.)] # Choose a level to plot, in this case 296 K level = 0 # Get data to plot state and province boundaries states_provinces = cfeature.NaturalEarthFeature(category='cultural', name='admin_1_states_provinces_lakes', scale='50m', facecolor='none') fig = plt.figure(1, figsize=(17., 12.)) add_metpy_logo(fig, 120, 245, size='large') ax = fig.add_subplot(1, 1, 1, projection=crs) ax.set_extent(*bounds, crs=ccrs.PlateCarree()) ax.coastlines('50m', edgecolor='black', linewidth=0.75) ax.add_feature(states_provinces, edgecolor='black', linewidth=0.5) # Plot the surface clevisent = np.arange(0, 1000, 25) cs = ax.contour(tlons, tlats, isentprs[level, :, :], clevisent, colors='k', linewidths=1.0, linestyles='solid') plt.clabel(cs, fontsize=10, inline=1, inline_spacing=7, fmt='%i', rightside_up=True, use_clabeltext=True)
def plot_indv_clusters(cluster, cluster_IDs=[], prob_thresh=0.2, zoom=False, zoom_degree=1.0, title="", sub=111, optional_inds=[], optional_text="", optional_text_loc=[], TGF_legend_loc=[0.05, 0.9], TGF_star_color="lime", opt_text_color="blue"): if cluster_IDs == [] or cluster_IDs == 'all': cluster_IDs = cluster.cluster_IDs #plt.subplot(sub) rdata = cluster.rdata color_map = cm.jet( np.linspace(0.0, 1.0, max(set(cluster.cluster_labels)) + 2)) ax = plt.subplot(sub, projection=ccrs.PlateCarree()) ax.coastlines('50m') land_50m = cfeature.NaturalEarthFeature('physical', 'land', '50m', facecolor=cfeature.COLORS['land']) ax.add_feature(land_50m) ax.text(-0.125, 0.55, 'Latitude', va='bottom', ha='center', rotation='vertical', rotation_mode='anchor', transform=ax.transAxes) ax.text(0.5, -0.1, 'Longitude', va='bottom', ha='center', rotation='horizontal', rotation_mode='anchor', transform=ax.transAxes) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_left = True gl.ylabels_right = False plt.title(title) props = dict(boxstyle='round', facecolor='white', alpha=0.7) opt_props = dict(boxstyle='round', facecolor='white', alpha=0.7) if len(optional_inds) > 1: print(cluster.location_df.iloc[optional_inds[0]]['lon']) print(cluster.location_df.iloc[optional_inds[0]]['lat']) ax.scatter(cluster.location_df.iloc[optional_inds[0]]['lon'], cluster.location_df.iloc[optional_inds[0]]['lat'], color='blue', edgecolor='black', marker='*', s=100, zorder=1000) ax.scatter(cluster.location_df.iloc[optional_inds[1]]['lon'], cluster.location_df.iloc[optional_inds[1]]['lat'], color='magenta', edgecolor='green', marker='*', s=100, zorder=1000) if optional_text != "": if optional_text_loc != []: plt.text(optional_text_loc[0], optional_text_loc[1], optional_text, horizontalalignment='left', verticalalignment='center', fontsize=10, transform=ax.transAxes, color=opt_text_color, bbox=opt_props) else: print("No specified text location, not adding text") marker = itertools.cycle(('.', 'v', '+', 'd', '1', 'x')) for cluster_ID in cluster_IDs: if cluster_ID == -1: marker = itertools.cycle(('.')) if cluster_ID == cluster.TGF_cluster: if TGF_legend_loc is not None: plt.text(TGF_legend_loc[0], TGF_legend_loc[1], 'TGF Lat: {} \nTGF Lon: {}'.format( cluster.TGF_lat[0], cluster.TGF_lon[0]), horizontalalignment='left', verticalalignment='center', fontsize=10, transform=ax.transAxes, color='black', bbox=props) # if cluster.TGF_prob >= prob_thresh: ax.scatter(cluster.TGF_lon, cluster.TGF_lat, color=TGF_star_color, edgecolor='black', marker='*', s=100, alpha=1, zorder=1000) else: ax.scatter(cluster.TGF_lon, cluster.TGF_lat, color='black', edgecolor='black', marker='*', s=100, alpha=1, zorder=1000) filt = rdata['probs'][cluster_ID] >= prob_thresh filt2 = rdata['probs'][cluster_ID] < prob_thresh if len(rdata['lons'][cluster_ID][filt]) > 0: mark = next(marker) ax.scatter(rdata['lons'][cluster_ID][filt], rdata['lats'][cluster_ID][filt], color=color_map[cluster_ID], marker=mark, s=20, zorder=100) ax.plot(rdata['lons'][cluster_ID][filt2], rdata['lats'][cluster_ID][filt2], markerfacecolor="None", markeredgecolor='black', markeredgewidth=1, marker=mark, linestyle="None", markersize=5) elif len(rdata['lons'][cluster_ID][filt2]) > 0: ax.plot(rdata['lons'][cluster_ID][filt2], rdata['lats'][cluster_ID][filt2], markerfacecolor="None", markeredgecolor='black', markeredgewidth=1, marker=next(marker), linestyle="None", zorder=10, markersize=5) else: pass if zoom: ax.set_extent([ cluster.TGF_lon - zoom_degree, cluster.TGF_lon + zoom_degree, cluster.TGF_lat - zoom_degree, cluster.TGF_lat + zoom_degree ]) else: ax.set_extent([-180, 180, -90, 90]) return ax