def download_features(group_names, dry_run=True): for group_name in group_names: feature_defns = FEATURE_DEFN_GROUPS[group_name] if isinstance(feature_defns, Feature): feature = feature_defns level = list(feature._levels)[0] downloader = Downloader.from_config(('shapefiles', 'gshhs', feature._scale, level)) format_dict = {'config': config, 'scale': feature._scale, 'level': level} if dry_run: print('URL: {}'.format(downloader.url(format_dict))) else: downloader.path(format_dict) geoms = list(feature.geometries()) print('Feature {} length: {}'.format(feature, len(geoms))) else: for category, name, scales in feature_defns: if not isinstance(scales, tuple): scales = (scales,) for scale in scales: downloader = Downloader.from_config(('shapefiles', 'natural_earth', scale, category, name)) feature = NaturalEarthFeature(category, name, scale) format_dict = {'config': config, 'category': category, 'name': name, 'resolution': scale} if dry_run: print('URL: {}'.format(downloader.url(format_dict))) else: downloader.path(format_dict) geoms = list(feature.geometries()) print('Feature {}, {}, {} length: {}' ''.format(category, name, scale, len(geoms)))
def plot_background(ax): ax.coastlines(resolution='10m', linewidth=2, color='black', zorder=4) political_boundaries = NaturalEarthFeature( category='cultural', name='admin_0_boundary_lines_land', scale='10m', facecolor='none') states = NaturalEarthFeature(category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax.add_feature(political_boundaries, linestyle='-', edgecolor='black', zorder=4) ax.add_feature(states, linestyle='-', edgecolor='black', linewidth=2, zorder=4) ax.add_feature( USCOUNTIES.with_scale('500k'), edgecolor='black', linewidth=1, zorder=1 ) #### Using Metpy's county shapefiles due to hi-resolution and they also help with spartial awareness ax.add_feature(roads, facecolor='none', edgecolor='dimgrey', zorder=1, linewidth=1) return ax
def add_map_features(ax, states_provinces=True, country_borders=True, land=True, ocean=True, lake=False): '''Add background features to an axis''' if states_provinces: states_provinces = NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax.add_feature(states_provinces, edgecolor='black', alpha=.8, zorder=2) if country_borders: ctry_borders = NaturalEarthFeature( category='cultural', name='admin_0_boundary_lines_land', scale='50m', facecolor='none') ax.add_feature(ctry_borders, edgecolor='black', zorder=2, linewidth=1) if land: land = NaturalEarthFeature( category='physical', name='land', scale='50m', facecolor='gray') ax.add_feature(land, facecolor='lightgray', zorder=0) if ocean: ocean = NaturalEarthFeature( category='physical', name='ocean', scale='50m', facecolor='blue') ax.add_feature(ocean, facecolor='lightblue', zorder=1) if lake: rivers_lakes = NaturalEarthFeature( category='physical', name='rivers_lake_centerlines', scale='50m', facecolor='none') ax.add_feature(rivers_lakes, facecolor='lightblue', zorder=2)
def download_features(group_names, dry_run=True): for group_name in group_names: feature_defns = FEATURE_DEFN_GROUPS[group_name] if isinstance(feature_defns, Feature): feature = feature_defns level = list(feature._levels)[0] downloader = Downloader.from_config(('shapefiles', 'gshhs', feature._scale, level)) format_dict = {'config': config, 'scale': feature._scale, 'level': level} if dry_run: print('URL: {}'.format(downloader.url(format_dict))) else: downloader.path(format_dict) geoms = list(feature.geometries()) print('Feature {} length: {}'.format(feature, len(geoms))) else: for category, name, scales in feature_defns: if not isinstance(scales, tuple): scales = (scales,) for scale in scales: downloader = Downloader.from_config(('shapefiles', 'natural_earth', scale, category, name)) feature = NaturalEarthFeature(category, name, scale) format_dict = {'config': config, 'category': category, 'name': name, 'resolution': scale} if dry_run: print('URL: {}'.format(downloader.url(format_dict))) else: downloader.path(format_dict) geoms = list(feature.geometries()) print('Feature {}, {}, {} length: {}' ''.format(category, name, scale, len(geoms)))
def draw_map(self): """ Draws a map in the background """ land = NaturalEarthFeature(name='land', category='physical', scale='50m', facecolor=COLORS['land']) ocean = NaturalEarthFeature(name='ocean', category='physical', scale='50m', facecolor=COLORS['water']) self.ax.add_feature(land) self.ax.add_feature(ocean)
def plotparticlesforecast(data_path, point, filename, t, dts, latbox, lonbox, proj, uncertain): particles = nc_particles.Reader(data_path+'/'+filename) times = particles.times states = NaturalEarthFeature(category="cultural", scale="10m", facecolor="none", name='admin_1_states_provinces_lines') coastline = NaturalEarthFeature(category="physical", scale="10m", facecolor="none", name='coastline') land = NaturalEarthFeature(category="physical", scale="10m", facecolor='lightgray', name='land',) latmin = latbox[0] latmax = latbox[1] lonmin = lonbox[0] lonmax = lonbox[1] for i in np.arange(0, len(times[:]), dts): tnew = t + timedelta(hours=i) dt = [np.abs(((output_t - tnew).total_seconds())/3600) for output_t in times] tidx = dt.index(min(dt)) TheData = particles.get_timestep(tidx, variables=['latitude', 'longitude', 'status_codes', 'depth']) status = TheData['status_codes'] pid = np.where(status == 2)[0] on_land = np.where(status == 3)[0] fig = plt.figure(figsize=(10, 5)) ax = plt.subplot(1, 1, 1, projection=proj) ax.add_feature(coastline, edgecolor='black', zorder=6,) ax.add_feature(land, zorder=10,) ax.add_feature(states, edgecolor='gray', zorder=12,) ax_leg = ax.gridlines(draw_labels=True, linewidth=0.5, linestyle='--') ax_leg.xlabels_top = False ax_leg.ylabels_right = False ax_leg.xlocator = mticker.FixedLocator(range(int(lonmin), int(lonmax) + 2, 2)) ax_leg.xformatter = LONGITUDE_FORMATTER ax_leg.ylocator = mticker.FixedLocator(range(int(latmin), int(latmax) + 2, 2)) ax_leg.yformatter = LATITUDE_FORMATTER ax_leg.xlabel_style = {'size': 10, 'color': 'black'} ax_leg.ylabel_style = {'size': 10, 'color': 'black'} plt.xlim([lonmin, lonmax]) plt.ylim([latmin, latmax]) ax.set_title(str(tnew)+point, {'fontsize': 15}, 'center') if uncertain: particles_uncertain = nc_particles.Reader(data_path+'/'+filename[0:-3]+'_uncertain.nc') TheData_uncertain = particles_uncertain.get_timestep(tidx, variables=['latitude', 'longitude', 'status_codes', 'depth']) status_uncertain = TheData_uncertain['status_codes'] pid_uncertain = np.where(status_uncertain == 2)[0] on_land_uncertain = np.where(status_uncertain == 3)[0] plotScatter_uncertain = plt.scatter(TheData_uncertain['longitude'][pid_uncertain], TheData_uncertain['latitude'][pid_uncertain], s=20, color='red', marker='.') plotScatter_uncertain_onland = plt.scatter(TheData_uncertain['longitude'][on_land_uncertain], TheData_uncertain['latitude'][on_land_uncertain], s=20, color='red', marker='+') plotScatter = plt.scatter(TheData['longitude'][pid], TheData['latitude'][pid], s=20, color='k', marker='.') plotScatter_onland = plt.scatter(TheData['longitude'][on_land], TheData['latitude'][on_land], s=20, color='k', marker='+') plt.savefig(data_path+'/'+'foreground_'+"{0:05d}".format(i)+'.png', bbox_inches = 'tight', pad_inches = 0.1, quality=95) plt.clf() plt.close()
def WRFplot(plotvar, lats, lons, vmin, vmax, title, varname, ColMap): # Set the cartopy mapping object for the WRF domain # (Taken from wrf getcartopy and cartopy_xlim) cart_proj = cartopy.crs.LambertConformal( central_longitude=-121.0, central_latitude=45.665584564208984, false_easting=0.0, false_northing=0.0, secant_latitudes=None, standard_parallels=[30., 60.], globe=None, cutoff=-30) ax = plt.axes(projection=cart_proj) ax.set_xlim([-875806.9669240027, 1056192.549175313]) ax.set_ylim([-733768.6404772081, 730230.3670079684]) # Download and add the states and coastlines states = NaturalEarthFeature(category="cultural", scale="50m", facecolor="none", name="admin_1_states_provinces_lines") ax.add_feature(states, linewidth=.5, edgecolor="black") borders = NaturalEarthFeature(category="cultural", scale="50m", facecolor="none", name="admin_0_boundary_lines_land") ax.add_feature(borders, linewidth=.75, edgecolor="black") ax.coastlines('50m', linewidth=0.8) # Color in the data on the map with smoothing plt.pcolormesh(lons, lats, plotvar, vmin=vmin, vmax=vmax, transform=crs.PlateCarree(), shading='gouraud', cmap=get_cmap(ColMap)) # Add a color bar cbar = plt.colorbar(ax=ax, shrink=.6) #, orientation='horizontal') cbar.set_label(varname) # Add gridlines #ax.gridlines(color="black", linestyle="dotted") # Add a title plt.title(title)
def update_fid(self): self.dataind = self.dataind.reset_index() self.ax2.cla() land = NaturalEarthFeature( category='cultural', name='admin_0_countries', scale='10m', facecolor='none', edgecolor='#524c50', alpha=0.2) self.ax2.add_feature(land, zorder=2) # todo: actual of Schipol are 3.4, 5.41 (3.2 e 5.8) self.ax2.set_extent((3.2, 5.8, 51, 54)) self.ax2.plot(self.dataind.loc[:, 'lon'], self.dataind.loc[:, 'lat'], zorder=4, transform=Geodetic()) # todo:add different color depending on trajectory self.selected.set_visible(True) self.selected.set_data(self.fid._x, self.fid._y) self.text.set_text('selected: ' + self.fid.get_text()) self.ax3.cla() # todo: add correct units depending on featuer self.ax3.set_aspect('auto') self.ax3.plot(self.dataind.loc[:, 'ts'], self.dataind.loc[:, self.extra_feature]) self.fig.canvas.draw()
def plotter(lat, lon, X, cmap, clevs, units, txt): x, y = np.meshgrid(lon, lat) fig = plt.figure(figsize=(9, 7)) ax = fig.add_subplot(111, projection=ccrs.Mercator()) ax.set_extent([-80, 30, -60, 0], crs=ccrs.PlateCarree()) tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white') ax.add_feature(tierra) ax.coastlines(resolution='50m') grid_style = dict(color='white', linestyle='--', linewidth=.3) gl = ax.gridlines(draw_labels=True, **grid_style) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER pc = ax.contourf(x, y, X, clevs, cmap=cmap, extend='both', transform=ccrs.PlateCarree()) cbar = fig.colorbar(pc, ax=ax, shrink=0.7) cbar.ax.set_ylabel(units) ax.text(-0.1, 1, txt, transform=ax.transAxes, size=15) return fig, ax
def plotter(lat, lon, X, cmap, clevs, title, units): x, y = np.meshgrid(lon, lat) fig = plt.figure(figsize=(9, 7)) ax = fig.add_subplot(111, projection=ccrs.Mercator()) ax.set_extent([-80, 30, -70, 0], crs=ccrs.PlateCarree()) tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white') ax.add_feature(tierra) ax.coastlines(resolution='50m') grid_style = dict(color='white', linestyle='--', linewidth=.3) gl = ax.gridlines(draw_labels=True, **grid_style) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER box = sgeom.box(minx=-80, maxx=-40, miny=-56, maxy=-20) ax.add_geometries([box], ccrs.PlateCarree(), facecolor='none', edgecolor='black') pc = ax.contourf(x, y, X, clevs, cmap=cmap, extend='both', transform=ccrs.PlateCarree()) cbar = fig.colorbar(pc, ax=ax, shrink=0.9) cbar.ax.set_ylabel(units) ax.set_title(title) return fig, ax
def plot_cartopy(self, var: str, plot_var: array, params, time_counter: int = 0): try: import cartopy.crs as ccrs # mapping plots import cartopy.feature # add rivers, regional boundaries etc from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER # deg symb from cartopy.feature import NaturalEarthFeature # fine resolution coastline except ImportError: import sys warn( "No cartopy found - please run\nconda install -c conda-forge cartopy" ) sys.exit(-1) import matplotlib.pyplot as plt plt.close('all') fig = plt.figure(figsize=(10, 10)) ax = fig.gca() ax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree()) cset = self.dataset[var].isel(time_counter=time_counter, deptht=0).plot.pcolormesh \ (np.ma.masked_where(plot_var == np.NaN, plot_var), transform=ccrs.PlateCarree(), cmap=params.cmap) cset.set_clim([params.levs[0], params.levs[-1]]) ax.add_feature(cartopy.feature.OCEAN) ax.add_feature(cartopy.feature.BORDERS, linestyle=':') ax.add_feature(cartopy.feature.RIVERS) coast = NaturalEarthFeature(category='physical', scale='10m', facecolor='none', name='coastline') ax.add_feature(coast, edgecolor='gray') gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.5, color='gray', alpha=0.5, linestyle='-') gl.xlabels_top = False gl.xlabels_bottom = True gl.ylabels_right = False gl.ylabels_left = True gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER plt.colorbar(cset, shrink=params.colorbar_shrink, pad=.05) # tmp = self.dataset.votemper # tmp.attrs = self.dataset.votemper.attrs # tmp.isel(time_counter=time_counter, deptht=0).plot.contourf(ax=ax, transform=ccrs.PlateCarree()) # ax.set_global() # ax.coastlines() plt.show()
def plot_map_carto(data, lat, lon, ax=None, pertile_range=None, fig_size=(8, 8), cmap_str="viridis"): temp = data if pertile_range is None: vmin = np.amin(temp) vmax = np.amax(temp) else: assert 0 <= pertile_range[0] < pertile_range[1] <= 100 vmin = np.percentile(temp, pertile_range[0]) vmax = np.percentile(temp, pertile_range[1]) llcrnrlat = np.min(lat), urcrnrlat = np.max(lat), llcrnrlon = np.min(lon), urcrnrlon = np.max(lon), extent = [llcrnrlon[0], urcrnrlon[0], llcrnrlat[0], urcrnrlat[0]] # Figure only_map = False if ax is None: fig, ax = plt.subplots(1, 1, figsize=fig_size, subplot_kw={'projection': ccrs.PlateCarree()}) only_map = True ax.set_extent(extent) states = NaturalEarthFeature(category="cultural", scale="50m", facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) # auto projection scat = plt.scatter(lon, lat, c=temp, s=10, cmap=cmap_str, vmin=vmin, vmax=vmax) if only_map: # get size and extent of axes: axpos = ax.get_position() pos_x = axpos.x0 + axpos.width + 0.01 # + 0.25*axpos.width pos_y = axpos.y0 cax_width = 0.02 cax_height = axpos.height # create new axes where the colorbar should go. # it should be next to the original axes and have the same height! pos_cax = fig.add_axes([pos_x, pos_y, cax_width, cax_height]) plt.colorbar(ax=ax, cax=pos_cax) return fig else: plt.colorbar() return scat, ax
def make_pc_fig(figsize: Tuple[float, float] = (18, 9), coast_color: str = "#444444", color_bg: bool = True, set_limits_explicitly: bool = True, land_color: Optional[str] = "#999999", ocean_color: Optional[str] = "#98B6E2"): """ Creates a cartopy figure using the PlateCarree projection. :param figsize: The size of the figure for matplotlib (usually in inches). Default (18, 9). :param coast_color: The color of the coastlines. Default '#444444' (dark grey). :param color_bg: Whether to color the background (blue for ocean, orange for land). Default True. :param set_limits_explicitly: Whether to explicitly set the limits to include the entire Earth. This is necessary so that cartopy doesn't resize the limits arbitrarily after a scatter plot. This should have no effect on other plots. Default True. :param land_color: The color to fill land with. Default '#999999' (medium grey). :param ocean_color: The color to fill ocean with. Default '#98B6E2' (bluish; Cartopy default). :return: The axis for the figure. """ # Create a figure and axis with cartopy projection. plt.figure(figsize=figsize) ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines(color=coast_color) # Add and color background if requested. if color_bg: ax.add_feature( NaturalEarthFeature("physical", "land", "110m", facecolor=land_color, zorder=-1)) ax.add_feature( NaturalEarthFeature("physical", "ocean", "110m", facecolor=ocean_color, zorder=-1)) # Set limits explicitly if requested. if set_limits_explicitly: ax.set_xlim(-180, 180) ax.set_ylim(-90, 90) return ax
def plotter(lat, lon, C, serie): x, y = np.meshgrid(lon, lat) gs = gridspec.GridSpec(10, 5) fig = plt.figure(figsize=(10, 7)) plt.clf() ax1 = plt.subplot(gs[1:8, :], projection=ccrs.PlateCarree()) ax1.set_extent([-70, 30, -50, -15], crs=ccrs.PlateCarree()) tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white') ax1.add_feature(tierra) ax1.coastlines(resolution='50m') gl = ax1.gridlines(color='white', linestyle='--', linewidth=.5, draw_labels=True) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER cl = ax1.contourf(x, y, C * 1e7, np.arange(-1, 1.05, .05), cmap='coolwarm', transform=ccrs.PlateCarree(), extend='both') cbar = fig.colorbar(cl, ax=ax1, orientation='vertical', shrink=.7, pad=.08, label='[10$^{-7}$ Pa/m]') ax1.text(-0.15, 1, '(a)', transform=ax1.transAxes, size=20) ax2 = plt.subplot(gs[8:10, :-1]) ax2.plot(-P_clim * 100, linewidth=1.5, color='k') ax2.tick_params(axis='y', labelcolor='k') ax3 = ax2.twinx() ax3.plot(serie, linewidth=1.5, color='r') ax3.tick_params(axis='y', labelcolor='r') ax2.set_xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) ax2.set_xticklabels([ 'Ene', 'Feb.', 'Mar.', 'Abr.', 'May.', 'Jun.', 'Jul.', 'Ago.', 'Sep.', 'Oct.', 'Nov.', 'Dic.' ]) ax3.set_ylabel('Rotor [10$^{-7}$ Pa/m]', color='r') ax2.set_ylabel('Vel.proy. [cm/s]', color='k') ax2.grid(linestyle=':', color='grey') ax2.text(-0.15, 1, '(b)', transform=ax2.transAxes, size=20) plt.tight_layout() fig.subplots_adjust(hspace=.2, wspace=.2)
def countries(**kwargs): params = { "category": "cultural", "name": "admin_0_countries", "scale": "10m", "edgecolor": "#524c50", "facecolor": "none", "alpha": 0.5, **kwargs, } return NaturalEarthFeature(**params)
def ocean(**kwargs): params = { "category": "physical", "name": "ocean", "scale": "10m", "edgecolor": "#226666", "facecolor": "#226666", "alpha": 0.2, **kwargs, } return NaturalEarthFeature(**params)
def rivers(**kwargs): params = { "category": "physical", "name": "rivers_lake_centerlines", "scale": "10m", "edgecolor": "#226666", "facecolor": "none", "alpha": 0.2, **kwargs, } return NaturalEarthFeature(**params)
def lakes(**kwargs: str) -> NaturalEarthFeature: params = { "category": "physical", "name": "lakes", "scale": "10m", "edgecolor": "#226666", "facecolor": "#226666", "alpha": 0.2, **kwargs, } return NaturalEarthFeature(**params)
def download_features(group_names, dry_run=True): for group_name in group_names: feature_defns = FEATURE_DEFN_GROUPS[group_name] if isinstance(feature_defns, Feature): feature = feature_defns level = list(feature._levels)[0] downloader = Downloader.from_config( ("shapefiles", "gshhs", feature._scale, level) ) format_dict = {"config": config, "scale": feature._scale, "level": level} if dry_run: print("URL: {}".format(downloader.url(format_dict))) else: downloader.path(format_dict) geoms = list(feature.geometries()) print("Feature {} length: {}".format(feature, len(geoms))) else: for category, name, scales in feature_defns: if not isinstance(scales, tuple): scales = (scales,) for scale in scales: downloader = Downloader.from_config( ("shapefiles", "natural_earth", scale, category, name) ) feature = NaturalEarthFeature(category, name, scale) format_dict = { "config": config, "category": category, "name": name, "resolution": scale, } if dry_run: print("URL: {}".format(downloader.url(format_dict))) else: downloader.path(format_dict) geoms = list(feature.geometries()) print( "Feature {}, {}, {} length: {}" "".format(category, name, scale, len(geoms)) )
def plotter(t): gs = gridspec.GridSpec(10, 1) fig = plt.figure(figsize=(12, 12)) plt.clf() yr = str(osc['time.year'][t].values) mn = str(osc['time.month'][t].values).zfill(2) dy = str(osc['time.day'][t].values).zfill(2) plt.suptitle(yr + " " + mn + " " + dy) ax1 = plt.subplot(gs[1:7, 0], projection=ccrs.PlateCarree()) ax1.set_title('AVM (colores)') ax1.set_extent([-58, -44, -40, -26], crs=ccrs.PlateCarree()) tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white') ax1.add_feature(tierra) ax1.coastlines(resolution='50m') gl = ax1.gridlines(color='white', linestyle='--', linewidth=.5, draw_labels=True) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER box = sgeom.box(minx=-51.66, maxx=-50.33, miny=-34.33, maxy=-34.33) ax1.add_geometries([box], ccrs.PlateCarree(), facecolor='none', edgecolor='lime', linewidth=2.7) cl = ax1.contourf(x1, y1, VV[t,:,:]*100, np.arange(-50,55,5), cmap='RdBu_r', transform=ccrs.PlateCarree(), extend='both') qvr = ax1.quiver(x1, y1, UU[t,::1,::1], VV[t,::1,::1], units='inches', scale=.8, transform=ccrs.PlateCarree()) b = ax1.contour(x_b, y_b, bati['z'].values, levels=[-1000,-200], colors='k', linewidths=1.4, linestyles='-', transform=ccrs.PlateCarree()) cbar = fig.colorbar(cl, ax=ax1, orientation='vertical', shrink=.7, pad=.08, label='m/s') ax1.quiverkey(qvr, .2, 0.8, .2, '20 cm/s', labelpos='E') ax3 = plt.subplot(gs[8:10, 0]) ax3.plot(serie['time'], vf*100, 'k', linewidth=1) ax3.plot(serie['time'], yM*100, 'k', linewidth=2.5) ax3.plot(serie['time'], ySM*100, 'k', linewidth=2.5, linestyle='--') ax3.plot(serie['time'], ySm*100, 'k', linewidth=2.5, linestyle='--') for i in range(0, int(len(idxED)/2)): ax3.fill_between(serie['time'][idxED[2*i]:idxED[2*i+1]].values, vf[idxED[2*i]:idxED[2*i+1]]*100, (np.mean(vf)+np.std(vf))*100, color='blue', alpha=.7) for i in range(0, int(len(idxEF)/2)): ax3.fill_between(serie['time'][idxEF[2*i]:idxEF[2*i+1]].values, vf[idxEF[2*i]:idxEF[2*i+1]]*100, (np.mean(vf)-np.std(vf))*100, color='red', alpha=.7) ax3.plot(serie['time'][t].values, vf[t]*100, marker='o', color='k') ax3.xaxis.set_minor_locator(mdates.MonthLocator()) ax3.xaxis.grid(which="minor", color='grey', linestyle=':') plt.ylabel('AVM [cm/s]') plt.tight_layout() fig.subplots_adjust(hspace=.2, wspace=.2) plt.savefig('/home/bock/Documents/tesis/resultados/fig_for_an/ee_'+yr+mn+dy+'.png', bbox_inches='tight')
def __setup_maps(self): """basic maps with parallels, meridians, coastlines, U.S. states """ states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') all_axes = self.mapdict all_axes.update({'mapsum': self.axsum}) for this_map in all_axes.itervalues(): this_map.coastlines() this_map.gridlines(draw_labels=False) this_map.set_extent((-122, -114, 32, 43)) this_map.add_feature(states)
def __setup_maps(self): """basic maps with parallels, meridians, coastlines draw state boundaries in california panel """ for this_ax in (self.mapcal, self.mapworld): this_ax.coastlines() this_ax.gridlines(draw_labels=False) self.mapcal.set_extent((-122, -114, 32, 43)) states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') self.mapcal.add_feature(states)
def draw_counties(self, method=3, use_basemap=True): print("About to draw geographical info.") if use_basemap: self.m.drawcountries() self.m.drawcoastlines() self.m.drawstates() self.m.drawcounties() else: scale = '50m' # resolution = '10m' category = 'cultural' # name1 = 'admin_1_countries' name2 = 'admin_1_states_provinces_shp' # names = (name1, name2) names = (name2, ) if method == 1: shp_fname = shapereader.natural_earth(resolution, category, name) df = geopandas.read_file(shp_fname) border = df.loc[df['ADMIN'] == 'USA']['geometry'].values[0] self.ax.add_geometries(border) elif method == 2: for name in names: states = NaturalEarthFeature(category=category, scale=scale, facecolor=None, name=name) self.ax.add_feature(states, edgecolor='gray') elif method == 3: self.ax.add_feature(cartopy.feature.LAND) self.ax.add_feature(cartopy.feature.OCEAN) self.ax.add_feature(cartopy.feature.COASTLINE) self.ax.add_feature(cartopy.feature.BORDERS) self.ax.add_feature(cartopy.feature.LAKES, alpha=0.5) self.ax.add_feature(cartopy.feature.RIVERS) states_provinces = cartopy.feature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lakes_shp', scale='50m', ) self.ax.add_feature(states_provinces, edgecolor='gray') self.ax.background_patch.set_visible(False) ax.outline_patch.set_visible(False) # self.ax.coastlines() return
def plot_netherlands(): ax = plt.axes(projection=EuroPP(), zorder=1) land = NaturalEarthFeature( category='cultural', name='admin_0_countries', scale='10m', facecolor='none', edgecolor='#524c50', alpha= 0.3) ax.add_feature(land, zorder=2) ax.set_extent((3, 7.5, 51, 54)) plotschiphol.plot_schiphol(ax) return ax
def plotter(V, x, y, cmap, clevs, units, save): fig, axes = plt.subplots(4, 3, sharex=True, sharey=True, subplot_kw={'projection': ccrs.PlateCarree()}, figsize=(15, 10)) n = 0 txt = [ '(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)', '(i)', '(j)', '(k)', '(l)' ] for j in range(0, 4): for i in range(0, 3): axes[j, i].set_extent([-80, 30, -60, 0], crs=ccrs.PlateCarree()) tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white') axes[j, i].add_feature(tierra) axes[j, i].coastlines(resolution='50m') cl = axes[j, i].contourf(x, y, V[n, :, :], clevs, cmap=cmap, transform=ccrs.PlateCarree(), extend='both') axes[j, i].text(0.1, 0.86, txt[n], transform=axes[j, i].transAxes, size=15) n = n + 1 grid_style = dict(color='white', linestyle='--', linewidth=0) gl = axes[j, 0].gridlines(draw_labels=True, **grid_style) gl.ylabels_right = gl.xlabels_top = gl.xlabels_bottom = False gl.yformatter = LATITUDE_FORMATTER gl1 = axes[-1, i].gridlines(draw_labels=True, **grid_style) gl1.xlabels_top = gl1.ylabels_right = gl1.ylabels_left = False gl1.xformatter = LONGITUDE_FORMATTER fig.subplots_adjust(wspace=.02, hspace=.02) cbar = fig.colorbar(cl, ax=axes.ravel().tolist(), shrink=0.6) cbar.ax.set_ylabel(units) plt.savefig(save, bbox_inches='tight')
def make_map(bbox, projection=ccrs.PlateCarree()): fig, ax = plt.subplots(figsize=(16, 9), subplot_kw=dict(projection=projection)) ax.set_extent(bbox) ax.coastlines(resolution='50m') states = NaturalEarthFeature(category="cultural", scale="50m", facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=.5, edgecolor="black") gl = ax.gridlines(draw_labels=True) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER return fig, ax
def get_natural_features(): coast = NaturalEarthFeature(category='physical', name="coastline", scale='10m', facecolor='blue', zorder=1) border = NaturalEarthFeature(category='cultural', name='admin_0_countries', scale='10m', edgecolor='black', facecolor="tan", zorder=15) ocean = NaturalEarthFeature(category='physical', name="ocean", scale='50m', facecolor=cfeature.COLORS["water"], zorder=2) lakes = NaturalEarthFeature(category='physical', name='lakes', scale='10m', edgecolor='face', facecolor=cfeature.COLORS["water"], zorder=17) return [coast, border, ocean, lakes]
def prepare_plot_object(ncFile): cart_proj = get_projection_object(ncFile) fig = plt.figure(figsize=(12, 9)) ax = plt.axes(projection=cart_proj) Y, X = getGrid(ncFile, no_time=True) states = NaturalEarthFeature(category="cultural", scale="110m", facecolor="none", name="admin_1_states_provinces_lakes") ax.add_feature(states, edgecolor="black", linestyle=':') ax.coastlines() return fig, ax, X, Y
def prepare_figure(smooth_slp): fig = plt.figure() ax = plt.axes(projection=get_cartopy(smooth_slp)) states = NaturalEarthFeature(category="cultural", scale="10m", facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=.5, edgecolor="black") ax.coastlines('10m', linewidth=0.8) ax.set_xlim(cartopy_xlim(smooth_slp)) ax.set_ylim(cartopy_ylim(smooth_slp)) # box containing San Francisco Bay, Monterey Bay ax.set_extent((-123.0, -121.0, 36.2, 38.0)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") return (fig, ax)
def plotter(x, lat, lon, u, v, cmap, clevs, bati, lat_i, lat_f, lon_i, lon_f, cbar_label, title): from matplotlib import pyplot as plt import cartopy.crs as ccrs from cartopy.feature import NaturalEarthFeature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import matplotlib.gridspec as gridspec import shapely.geometry as sgeom import numpy as np import xarray import cmocean from mpl_toolkits.basemap import cm x_o, y_o = np.meshgrid(u.longitude, v.latitude) x1, y1 = np.meshgrid(lon, lat) x_b, y_b = np.meshgrid(bati['x'], bati['y']) fig = plt.figure(figsize=(10,12)) ax = fig.add_subplot(111, projection=ccrs.Mercator()) ax.set_extent([lon_i, lon_f, lat_f, lat_i], crs=ccrs.PlateCarree()) tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white') ax.add_feature(tierra) ax.coastlines(resolution='50m') gl = ax.gridlines(crs=ccrs.PlateCarree(central_longitude=0), draw_labels=True, color='white', linestyle='--', linewidth=.3) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER box = sgeom.box(minx=-51.67, maxx=-50.33, miny=-34.33, maxy=-34.33) ax.add_geometries([box], ccrs.PlateCarree(), facecolor='none', linewidth=2.5, edgecolor='black') clr = ax.contourf(x1, y1, x, clevs, transform=ccrs.PlateCarree(), cmap=cmap, extend='both') b = ax.contour(x_b, y_b, bati['z'].values, levels=[-1000,-200], colors='k', linewidths=2, linestyles='-', transform=ccrs.PlateCarree()) qvr = ax.quiver(x_o, y_o, u.values, v.values, units='xy', scale=0.2/111139, transform=ccrs.PlateCarree()) cbar = fig.colorbar(clr, ax=ax, shrink=.7) cbar.ax.set_ylabel(cbar_label) ax.quiverkey(qvr, .2, 0.8, .2, '0.2 m/s', labelpos='E') plt.title(title) return fig, ax
def grafico_campos(i): fig = plt.figure(figsize=(9, 7)) ax = fig.add_subplot(111, projection=ccrs.Mercator()) ax.set_extent([-65, -35, -45, -25], crs=ccrs.PlateCarree()) tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white') ax.add_feature(tierra) ax.coastlines(resolution='50m') grid_style = dict(color='white', linestyle='--', linewidth=.3) gl = ax.gridlines(draw_labels=True, **grid_style) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER clr = ax.pcolormesh(x, y, osc.v[i, 0, :, :].values, vmin=-0.7, vmax=0.7, transform=ccrs.PlateCarree(), cmap='RdBu_r') qvr = ax.quiver(x[::2, ::2], y[::2, ::2], osc.u[i, 0, ::2, ::2].values, osc.v[i, 0, ::2, ::2].values, units='xy', scale=2 / 3 / 111139, transform=ccrs.PlateCarree()) cbar = fig.colorbar(clr, ax=ax, shrink=.7) cbar.ax.set_ylabel('m/s') ax.quiverkey(qvr, 1.1, 1.1, 1, '1.5 m/s', labelpos='E') yr = str(osc['time.year'][i].values) mn = str(osc['time.month'][i].values).zfill(2) dy = str(osc['time.day'][i].values).zfill(2) ax.set_title(yr + " " + mn + " " + dy) salida = '/home/bock/Documents/tesis/resultados/figs/oscar_' + yr + mn + dy + '.png' plt.savefig(salida, dpi=250)