def __init__(self, model): self.src_crs = ccrs.LambertCylindrical() self.tgt_crs = ccrs.Mercator(central_longitude=-87.200012, min_latitude=18.091648, max_latitude=31.960648) self.file = glob.glob(model.data_dir + '/*')[0] data = Dataset(self.file) self.lats = data['Latitude'][:] self.lons = data['Longitude'][:] self.depths = data['Depth'][:] self.lons, self.lats = np.meshgrid(self.lons, self.lats) transformed = self.tgt_crs.transform_points(self.src_crs, self.lons, self.lats) self.lons = self.lons[0] self.lats = self.lats.T[0] self.x = transformed[0, :, 0] self.y = transformed[:, 0, 1] x, y = np.meshgrid(self.x, self.y) self.points = np.array([self.x, self.y], dtype=object) # VisibleDeprecationWarning: Creating an ndarray from ragged nested # sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays # with different lengths or shapes) is deprecated. If you meant to do # this, you must specify 'dtype=object' when creating the ndarray coords = np.array([x.ravel(), y.ravel()]).T self.tree = cKDTree(coords, leafsize=model.leafsize)
def xarray_plot(data, path='default', name = 'default', saving=False): # from plotting import save_figure import matplotlib.pyplot as plt import cartopy.crs as ccrs import numpy as np plt.figure() data = data.squeeze() if len(data.longitude[np.where(data.longitude > 180)[0]]) != 0: data = convert_longitude(data) else: pass if data.ndim != 2: print("number of dimension is {}, printing first element of first dimension".format(np.squeeze(data).ndim)) data = data[0] else: pass if 'mask' in list(data.coords.keys()): cen_lon = data.where(data.mask==True, drop=True).longitude.mean() data = data.where(data.mask==True, drop=True) else: cen_lon = data.longitude.mean().values proj = ccrs.LambertCylindrical(central_longitude=cen_lon) # proj = ccrs.Orthographic(central_longitude=cen_lon, central_latitude=data.latitude.mean()) ax = plt.axes(projection=proj) ax.coastlines() # ax.set_global() if 'mask' in list(data.coords.keys()): plot = data.where(data.mask==True).plot.pcolormesh(ax=ax, cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree(), add_colorbar=True) else: plot = data.plot.pcolormesh(ax=ax, cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree(), add_colorbar=True) if saving == True: save_figure(data, path=path) plt.show()
def draw_cartopy_map(counties, colors, names, filname=None, cmap=cm.get_cmap('seismic')): #norm = Normalize(vmin=0.0, vmax=100.0) #norms = map(norm, colors) #rgb_colors = map(cmap, norms) fig, ax = mpl.subplots(figsize=(12, 8), subplot_kw=dict(projection=ccrs.LambertCylindrical())) i = 0 for name, cty, col in zip(names, counties, colors): ax.add_geometries([cty], ccrs.LambertCylindrical(), facecolor=col) if name == 'San Diego': print name, col, colors[i] i += 1 ax.set_xlim(-125, -65) ax.set_ylim(24, 50) mpl.show()
def test_multiple_projections(): projections = [ ccrs.PlateCarree(), ccrs.Robinson(), ccrs.RotatedPole(pole_latitude=45, pole_longitude=180), ccrs.OSGB(approx=True), ccrs.TransverseMercator(approx=True), ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)), min_latitude=-85., max_latitude=85.), ccrs.LambertCylindrical(), ccrs.Miller(), ccrs.Gnomonic(), ccrs.Stereographic(), ccrs.NorthPolarStereo(), ccrs.SouthPolarStereo(), ccrs.Orthographic(), ccrs.Mollweide(), ccrs.InterruptedGoodeHomolosine(emphasis='land'), ccrs.EckertI(), ccrs.EckertII(), ccrs.EckertIII(), ccrs.EckertIV(), ccrs.EckertV(), ccrs.EckertVI(), ] rows = np.ceil(len(projections) / 5).astype(int) fig = plt.figure(figsize=(10, 2 * rows)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(rows, 5, i, projection=prj) ax.set_global() ax.coastlines(resolution="110m") plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def test_multiple_projections(): projections = [ ccrs.PlateCarree(), ccrs.Robinson(), ccrs.RotatedPole(pole_latitude=45, pole_longitude=180), ccrs.OSGB(), ccrs.TransverseMercator(), ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)), min_latitude=-85., max_latitude=85.), ccrs.LambertCylindrical(), ccrs.Miller(), ccrs.Gnomonic(), ccrs.Stereographic(), ccrs.NorthPolarStereo(), ccrs.SouthPolarStereo(), ccrs.Orthographic(), ccrs.Mollweide(), ccrs.InterruptedGoodeHomolosine(), ] if ccrs.PROJ4_VERSION < (5, 0, 0): # Produce the same sized image for old proj, to avoid having to replace # the image. If this figure is regenerated for both old and new proj, # then drop this condition. rows = 5 else: rows = np.ceil(len(projections) / 5) fig = plt.figure(figsize=(10, 2 * rows)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(rows, 5, i, projection=prj) ax.set_global() ax.coastlines() plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def test_cartopy_projection(self): cube = iris.load_cube( tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))) projections = {} projections['RotatedPole'] = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) projections['Robinson'] = ccrs.Robinson() projections['PlateCarree'] = ccrs.PlateCarree() projections['NorthPolarStereo'] = ccrs.NorthPolarStereo() projections['Orthographic'] = ccrs.Orthographic(central_longitude=-90, central_latitude=45) projections[ 'InterruptedGoodeHomolosine'] = ccrs.InterruptedGoodeHomolosine() projections['LambertCylindrical'] = ccrs.LambertCylindrical() # Set up figure fig = plt.figure(figsize=(10, 10)) gs = matplotlib.gridspec.GridSpec(nrows=3, ncols=3, hspace=1.5, wspace=0.5) for subplot_spec, (name, target_proj) in itertools.izip( gs, projections.iteritems()): # Set up axes and title ax = plt.subplot(subplot_spec, frameon=False, projection=target_proj) ax.set_title(name) # Transform cube to target projection new_cube, extent = iris.analysis.cartography.project(cube, target_proj, nx=150, ny=150) # Plot plt.pcolor( new_cube.coord('projection_x_coordinate').points, new_cube.coord('projection_y_coordinate').points, new_cube.data) # Add coastlines ax.coastlines() # Tighten up layout gs.tight_layout(plt.gcf()) # Verify resulting plot self.check_graphic(tol=6e-4)
def test_multiple_projections(): projections = [ ccrs.PlateCarree(), ccrs.Robinson(), ccrs.RotatedPole(pole_latitude=45, pole_longitude=180), ccrs.OSGB(), ccrs.TransverseMercator(), ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)), min_latitude=-85., max_latitude=85.), ccrs.LambertCylindrical(), ccrs.Miller(), ccrs.Gnomonic(), ccrs.Stereographic(), ccrs.NorthPolarStereo(), ccrs.SouthPolarStereo(), ccrs.Orthographic(), ccrs.Mollweide(), ccrs.InterruptedGoodeHomolosine(), ] fig = plt.figure(figsize=(10, 10)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(5, 5, i, projection=prj) ax.set_global() ax.coastlines() plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def plot_corr_maps(corr_xr, mask_xr=None, map_proj=None, row_dim='split', col_dim='lag', clim='relaxed', hspace=-0.6, size=2.5, cbar_vert=-0.01, units='units', cmap=None, clevels=None, cticks_center=None, drawbox=None, subtitles=None, zoomregion=None, lat_labels=True): ''' zoombox = tuple(east_lon, west_lon, south_lat, north_lat) ''' #%% # # default parameters # row_dim='split'; col_dim='lag'; clim='relaxed'; hspace=-0.6; # size=2.5; cbar_vert=-0.01; units='units'; cmap=None; # clevels=None; cticks_center=None; # drawbox=None; subtitles=None; lat_labels=True; # if map_proj is None: cen_lon = int(corr_xr.longitude.mean().values) map_proj = ccrs.LambertCylindrical(central_longitude=cen_lon) if row_dim not in corr_xr.dims: corr_xr = corr_xr.expand_dims(row_dim, 0) if mask_xr is not None: mask_xr = mask_xr.expand_dims(row_dim, 0) if col_dim not in corr_xr.dims: corr_xr = corr_xr.expand_dims(col_dim, 0) if mask_xr is not None: mask_xr = mask_xr.expand_dims(col_dim, 0) var_n = corr_xr.name rows = corr_xr[row_dim].values cols = corr_xr[col_dim].values rename_dims = {row_dim: 'row', col_dim: 'col'} rename_dims_inv = {'row': row_dim, 'col': col_dim} plot_xr = corr_xr.rename(rename_dims) if mask_xr is not None: plot_mask = mask_xr.rename(rename_dims) dim_coords = plot_xr.squeeze().dims dim_coords = [d for d in dim_coords if d not in ['latitude', 'longitude']] rename_subs = {d: rename_dims_inv[d] for d in dim_coords} lat = plot_xr.latitude lon = plot_xr.longitude zonal_width = abs(lon[-1] - lon[0]).values g = xr.plot.FacetGrid(plot_xr, col='col', row='row', subplot_kws={'projection': map_proj}, sharex=True, sharey=True, aspect=(lon.size) / lat.size, size=size) figheight = g.fig.get_figheight() # ============================================================================= # Coordinate labels # ============================================================================= import cartopy.mpl.ticker as cticker longitude_labels = np.linspace(np.min(lon), np.max(lon), 6, dtype=int) longitude_labels = np.array( sorted(list(set(np.round(longitude_labels, -1))))) latitude_labels = np.linspace(lat.min(), lat.max(), 4, dtype=int) latitude_labels = sorted(list(set(np.round(latitude_labels, -1)))) g.set_ticks(max_xticks=5, max_yticks=5, fontsize='large') g.set_xlabels(label=[str(el) for el in longitude_labels]) g.fig.subplots_adjust(hspace=hspace) if clevels is None: class MidpointNormalize(mcolors.Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint mcolors.Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) if clim == 'relaxed': vmin_ = np.nanpercentile(plot_xr, 1) vmax_ = np.nanpercentile(plot_xr, 99) elif type(clim) == tuple: vmin_, vmax_ = clim else: vmin_ = plot_xr.min() - 0.01 vmax_ = plot_xr.max() + 0.01 vmin = np.round(float(vmin_), decimals=2) vmax = np.round(float(vmax_), decimals=2) clevels = np.linspace(-max(abs(vmin), vmax), max(abs(vmin), vmax), 17) # choose uneven number for # steps norm = MidpointNormalize(midpoint=0, vmin=clevels[0], vmax=clevels[-1]) ticksteps = 4 else: clevels = clevels norm = None ticksteps = 1 if cmap is None: cmap = plt.cm.RdBu_r else: cmap = cmap for col, c_label in enumerate(cols): xrdatavar = plot_xr.sel(col=c_label) if abs(lon[-1] - 360) <= (lon[1] - lon[0]): xrdatavar = extend_longitude(xrdatavar) for row, r_label in enumerate(rows): print( f"\rPlotting Corr maps {var_n}, {row_dim} {r_label}, {col_dim} {c_label}", end="") plotdata = xrdatavar.sel(row=r_label).rename(rename_subs).squeeze() if mask_xr is not None: xrmaskvar = plot_mask.sel(col=c_label) if abs(lon[-1] - 360) <= (lon[1] - lon[0]): xrmaskvar = extend_longitude(xrmaskvar) plotmask = xrmaskvar.sel(row=r_label) # if plotdata is already masked (with nans): p_nans = int(100 * plotdata.values[np.isnan(plotdata.values)].size / plotdata.size) if mask_xr is not None: # field not completely masked? all_masked = (plotmask.values == False).all() if all_masked == False: if p_nans < 90: plotmask.plot.contour( ax=g.axes[row, col], transform=ccrs.PlateCarree(), subplot_kws={'projection': map_proj}, colors=['black'], linewidths=np.round(zonal_width / 150, 1) + 0.3, levels=[float(vmin), float(vmax)], add_colorbar=False) # try: # im = plotdata.plot.contourf(ax=g.axes[row,col], transform=ccrs.PlateCarree(), # center=0, # levels=clevels, cmap=cmap, # subplot_kws={'projection':map_proj},add_colorbar=False) # except ValueError: # print('could not draw contourf, shifting to pcolormesh') # if no signifcant regions, still plot corr values, but the causal plot must remain empty if mask_xr is None or all_masked == False or (all_masked and 'tigr' not in c_label): im = plotdata.plot.pcolormesh( ax=g.axes[row, col], transform=ccrs.PlateCarree(), center=0, levels=clevels, cmap=cmap, subplot_kws={'projection': map_proj}, add_colorbar=False) elif all_masked and 'tigr' in c_label: g.axes[row, col].text(0.5, 0.5, 'No regions significant', horizontalalignment='center', fontsize='x-large', verticalalignment='center', transform=g.axes[row, col].transAxes) g.axes[row, col].set_extent([lon[0], lon[-1], lat[0], lat[-1]], ccrs.PlateCarree()) # ============================================================================= # Draw (rectangular) box # ============================================================================= if drawbox is not None: from shapely.geometry.polygon import LinearRing def get_ring(coords): '''tuple in format: west_lon, east_lon, south_lat, north_lat ''' west_lon, east_lon, south_lat, north_lat = coords lons_sq = [west_lon, west_lon, east_lon, east_lon] lats_sq = [north_lat, south_lat, south_lat, north_lat] ring = [LinearRing(list(zip(lons_sq, lats_sq)))] return ring if isinstance(drawbox[1], tuple): ring = get_ring(drawbox[1]) elif isinstance(drawbox[1], list): ring = drawbox[1] if drawbox[0] == g.axes.size or drawbox[0] == 'all': g.axes[row, col].add_geometries(ring, ccrs.PlateCarree(), facecolor='none', edgecolor='green', linewidth=2, linestyle='dashed') # ============================================================================= # Subtitles # ============================================================================= if subtitles is not None: fontdict = dict({'fontsize': 18, 'fontweight': 'bold'}) g.axes[row, col].set_title(subtitles[row, col], fontdict=fontdict, loc='center') # ============================================================================= # set coordinate ticks # ============================================================================= # rcParams['axes.titlesize'] = 'xx-large' if map_proj.proj4_params['proj'] in ['merc', 'eqc', 'cea']: ax = g.axes[row, col] ax.set_xticks(longitude_labels[:-1], crs=ccrs.PlateCarree()) ax.set_xticklabels(longitude_labels[:-1], fontsize=12) lon_formatter = cticker.LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) g.axes[row, col].set_yticks(latitude_labels, crs=ccrs.PlateCarree()) if lat_labels == True: g.axes[row, col].set_yticklabels(latitude_labels, fontsize=12) lat_formatter = cticker.LatitudeFormatter() g.axes[row, col].yaxis.set_major_formatter(lat_formatter) else: fake_labels = [' ' * len(str(l)) for l in latitude_labels] g.axes[row, col].set_yticklabels(fake_labels, fontsize=12) g.axes[row, col].grid(linewidth=1, color='black', alpha=0.3, linestyle='--') g.axes[row, col].set_ylabel('') g.axes[row, col].set_xlabel('') g.axes[row, col].coastlines(color='black', alpha=0.3, facecolor='grey', linewidth=2) if corr_xr.name is not None: if corr_xr.name[:3] == 'sst': g.axes[row, col].add_feature(cfeature.LAND, facecolor='grey', alpha=0.3) # if row == rows.size-1: # last_ax = g.axes[row,col] # lay out settings plt.tight_layout(pad=1.1 - 0.02 * rows.size, h_pad=None, w_pad=None, rect=None) # height colorbor 1/10th of height of subfigure height = g.axes[-1, 0].get_position().height / 10 bottom_ysub = (figheight / 40) / (rows.size * 2) + cbar_vert # bottom_ysub = last_ax.get_position(original=False).bounds[1] # bottom cbar_ax = g.fig.add_axes([0.25, bottom_ysub, 0.5, height]) #[left, bottom, width, height] if units == 'units' and 'units' in corr_xr.attrs: clabel = corr_xr.attrs['units'] elif units != 'units' and units is not None: clabel = units else: clabel = '' if cticks_center is None: plt.colorbar(im, cax=cbar_ax, orientation='horizontal', norm=norm, label=clabel, ticks=clevels[::ticksteps], extend='neither') else: norm = mcolors.BoundaryNorm(boundaries=clevels, ncolors=256) cbar = plt.colorbar(im, cbar_ax, cmap=cmap, orientation='horizontal', extend='neither', norm=norm, label=clabel) cbar.set_ticks(clevels + 0.5) ticklabels = np.array(clevels + 1, dtype=int) cbar.set_ticklabels(ticklabels, update_ticks=True) cbar.update_ticks() if zoomregion is not None: ax.set_extent(zoomregion, crs=ccrs.PlateCarree()) ax.set_xlim(zoomregion[2:]) ax.set_ylim(zoomregion[:2]) print("\n") #%% return
def plot_map(ds: xr.Dataset, var: VarName.TYPE = None, indexers: DictLike.TYPE = None, region: PolygonLike.TYPE = None, projection: str = 'PlateCarree', central_lon: float = 0.0, title: str = None, contour_plot: bool = False, properties: DictLike.TYPE = None, file: str = None) -> object: """ Create a geographic map plot for the variable given by dataset *ds* and variable name *var*. Plots the given variable from the given dataset on a map with coastal lines. In case no variable name is given, the first encountered variable in the dataset is plotted. In case no *time* is given, the first time slice is taken. It is also possible to set extents of the plot. If no extents are given, a global plot is created. The plot can either be shown using pyplot functionality, or saved, if a path is given. The following file formats for saving the plot are supported: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff :param ds: the dataset containing the variable to plot :param var: the variable's name :param indexers: Optional indexers into data array of *var*. The *indexers* is a dictionary or a comma-separated string of key-value pairs that maps the variable's dimension names to constant labels. e.g. "layer=4". :param region: Region to plot :param projection: name of a global projection, see http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html :param central_lon: central longitude of the projection in degrees :param title: an optional title :param contour_plot: If true plot a filled contour plot of data, otherwise plots a pixelated colormesh :param properties: optional plot properties for Python matplotlib, e.g. "bins=512, range=(-1.5, +1.5)" For full reference refer to https://matplotlib.org/api/lines_api.html and https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contourf.html :param file: path to a file in which to save the plot :return: a matplotlib figure object or None if in IPython mode """ if not isinstance(ds, xr.Dataset): raise ValidationError('Only gridded datasets are currently supported.') var_name = None if not var: for key in ds.data_vars.keys(): var_name = key break else: var_name = VarName.convert(var) var = ds[var_name] indexers = DictLike.convert(indexers) or {} properties = DictLike.convert(properties) or {} extents = None bounds = handle_plot_polygon(region) if bounds: lon_min, lat_min, lon_max, lat_max = bounds extents = [lon_min, lon_max, lat_min, lat_max] if len(ds.lat) < 2 or len(ds.lon) < 2: # Matplotlib can not plot datasets with less than these dimensions with # contourf and pcolormesh methods raise ValidationError( 'The minimum dataset spatial dimensions to create a map' ' plot are (2,2)') # See http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html# if projection == 'PlateCarree': proj = ccrs.PlateCarree(central_longitude=central_lon) elif projection == 'LambertCylindrical': proj = ccrs.LambertCylindrical(central_longitude=central_lon) elif projection == 'Mercator': proj = ccrs.Mercator(central_longitude=central_lon) elif projection == 'Miller': proj = ccrs.Miller(central_longitude=central_lon) elif projection == 'Mollweide': proj = ccrs.Mollweide(central_longitude=central_lon) elif projection == 'Orthographic': proj = ccrs.Orthographic(central_longitude=central_lon) elif projection == 'Robinson': proj = ccrs.Robinson(central_longitude=central_lon) elif projection == 'Sinusoidal': proj = ccrs.Sinusoidal(central_longitude=central_lon) elif projection == 'NorthPolarStereo': proj = ccrs.NorthPolarStereo(central_longitude=central_lon) elif projection == 'SouthPolarStereo': proj = ccrs.SouthPolarStereo(central_longitude=central_lon) else: raise ValidationError('illegal projection: "%s"' % projection) figure = plt.figure(figsize=(8, 4)) ax = plt.axes(projection=proj) if extents: ax.set_extent(extents, ccrs.PlateCarree()) else: ax.set_global() ax.coastlines() var_data = get_var_data(var, indexers, remaining_dims=('lon', 'lat')) # transform keyword is for the coordinate our data is in, which in case of a # 'normal' lat/lon dataset is PlateCarree. if contour_plot: var_data.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), subplot_kws={'projection': proj}, **properties) else: var_data.plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree(), subplot_kws={'projection': proj}, **properties) if title: ax.set_title(title) figure.tight_layout() if file: try: figure.savefig(file) except MemoryError: raise MemoryError( 'Not enough memory to save the plot. Try using a different file format' ' or enabling contour_plot.') return figure if not in_notebook() else ax
def plot_map(ds: xr.Dataset, var: VarName.TYPE = None, indexers: DictLike.TYPE = None, time: TimeLike.TYPE = None, region: PolygonLike.TYPE = None, projection: str = 'PlateCarree', central_lon: float = 0.0, title: str = None, properties: DictLike.TYPE = None, file: str = None) -> Figure: """ Create a geographic map plot for the variable given by dataset *ds* and variable name *var*. Plots the given variable from the given dataset on a map with coastal lines. In case no variable name is given, the first encountered variable in the dataset is plotted. In case no *time* is given, the first time slice is taken. It is also possible to set extents of the plot. If no extents are given, a global plot is created. The plot can either be shown using pyplot functionality, or saved, if a path is given. The following file formats for saving the plot are supported: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff :param ds: the dataset containing the variable to plot :param var: the variable's name :param indexers: Optional indexers into data array of *var*. The *indexers* is a dictionary or a comma-separated string of key-value pairs that maps the variable's dimension names to constant labels. e.g. "layer=4". :param time: time slice index to plot, can be a string "YYYY-MM-DD" or an integer number :param region: Region to plot :param projection: name of a global projection, see http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html :param central_lon: central longitude of the projection in degrees :param title: an optional title :param properties: optional plot properties for Python matplotlib, e.g. "bins=512, range=(-1.5, +1.5)" For full reference refer to https://matplotlib.org/api/lines_api.html and https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contourf.html :param file: path to a file in which to save the plot :return: a matplotlib figure object or None if in IPython mode """ if not isinstance(ds, xr.Dataset): raise NotImplementedError( 'Only gridded datasets are currently supported') var_name = None if not var: for key in ds.data_vars.keys(): var_name = key break else: var_name = VarName.convert(var) var = ds[var_name] time = TimeLike.convert(time) indexers = DictLike.convert(indexers) or {} properties = DictLike.convert(properties) or {} extents = None region = PolygonLike.convert(region) if region: lon_min, lat_min, lon_max, lat_max = region.bounds if not _check_bounding_box(lat_min, lat_max, lon_min, lon_max): raise ValueError( 'Provided plot extents do not form a valid bounding box ' 'within [-180.0,+180.0,-90.0,+90.0]') extents = [lon_min, lon_max, lat_min, lat_max] # See http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html# if projection == 'PlateCarree': proj = ccrs.PlateCarree(central_longitude=central_lon) elif projection == 'LambertCylindrical': proj = ccrs.LambertCylindrical(central_longitude=central_lon) elif projection == 'Mercator': proj = ccrs.Mercator(central_longitude=central_lon) elif projection == 'Miller': proj = ccrs.Miller(central_longitude=central_lon) elif projection == 'Mollweide': proj = ccrs.Mollweide(central_longitude=central_lon) elif projection == 'Orthographic': proj = ccrs.Orthographic(central_longitude=central_lon) elif projection == 'Robinson': proj = ccrs.Robinson(central_longitude=central_lon) elif projection == 'Sinusoidal': proj = ccrs.Sinusoidal(central_longitude=central_lon) elif projection == 'NorthPolarStereo': proj = ccrs.NorthPolarStereo(central_longitude=central_lon) elif projection == 'SouthPolarStereo': proj = ccrs.SouthPolarStereo(central_longitude=central_lon) else: raise ValueError('illegal projection: "%s"' % projection) figure = plt.figure(figsize=(8, 4)) ax = plt.axes(projection=proj) if extents: ax.set_extent(extents) else: ax.set_global() ax.coastlines() var_data = _get_var_data(var, indexers, time=time, remaining_dims=('lon', 'lat')) var_data.plot.contourf(ax=ax, transform=proj, **properties) if title: ax.set_title(title) figure.tight_layout() if file: figure.savefig(file) return figure if not in_notebook() else None
data = hm.datasets.fetch_topography_earth() region = (-20, 60, -40, 45) data_africa = data.sel(latitude=slice(*region[2:]), longitude=slice(*region[:2])) print("Topography/bathymetry grid:") print(data_africa) # Calculate the isostatic Moho depth using the default values for densities and # reference Moho moho = hm.isostasy_airy(data_africa.topography) print("\nMoho depth grid:") print(moho) # Draw the maps plt.figure(figsize=(8, 9.5)) ax = plt.axes(projection=ccrs.LambertCylindrical(central_longitude=20)) pc = moho.plot.pcolormesh(ax=ax, cmap="viridis_r", add_colorbar=False, transform=ccrs.PlateCarree()) plt.colorbar(pc, ax=ax, orientation="horizontal", pad=0.01, aspect=50, label="meters") ax.coastlines() ax.set_title("Airy isostatic Moho depth of Africa") ax.set_extent(region, crs=ccrs.PlateCarree()) plt.show()
# Define gridline locations and draw the lines using cartopy's built-in gridliner: xticks = [-180, -90, 0, 90, 180] yticks = [-90, -45, 0, 45, 90] ax.gridlines(xlocs=xticks, ylocs=yticks) # Label the end-points of the gridlines using the custom tick makers: ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) lambert_xticks(ax, xticks) lambert_yticks(ax, yticks) # Create a Lambert Conformal projection: # Draw a set of axes with coastlines: fig = plt.figure(figsize=(9, 4), frameon=True) ax = fig.add_axes([0.08, 0.05, 0.8, 0.94], projection=ccrs.LambertCylindrical()) ax.set_extent([-179, 180, 0, 90], crs=ccrs.PlateCarree()) ax.coastlines(resolution='50m') # *must* call draw in order to get the axis boundary used to add ticks: fig.canvas.draw() # Define gridline locations and draw the lines using cartopy's built-in gridliner: xticks = [-180, -90, 0, 90, 180] yticks = [-90, -45, 0, 45, 90] ax.gridlines(xlocs=xticks, ylocs=yticks) # Label the end-points of the gridlines using the custom tick makers: ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) lambert_xticks(ax, xticks)
def get_map_projection( proj_name, central_longitude=0.0, central_latitude=0.0, false_easting=0.0, false_northing=0.0, globe=None, standard_parallels=(20.0, 50.0), scale_factor=None, min_latitude=-80.0, max_latitude=84.0, true_scale_latitude=None, latitude_true_scale=None, ### BOTH secant_latitudes=None, pole_longitude=0.0, pole_latitude=90.0, central_rotated_longitude=0.0, sweep_axis='y', satellite_height=35785831, cutoff=-30, approx=None, southern_hemisphere=False, zone=15): #### numeric UTM zone proj_name = proj_name.lower() if (proj_name == 'albersequalarea'): proj = ccrs.AlbersEqualArea(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, standard_parallels=standard_parallels) elif (proj_name == 'azimuthalequidistant'): proj = ccrs.AzimuthalEquidistant(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'equidistantconic'): proj = ccrs.EquidistantConic(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, standard_parallels=standard_parallels) elif (proj_name == 'lambertconformal'): proj = ccrs.LambertConformal( central_longitude=-96.0, ########## central_latitude=39.0, ########## false_easting=false_easting, false_northing=false_northing, globe=globe, secant_latitudes=None, standard_parallels=None, ## default: (33,45) cutoff=cutoff) elif (proj_name == 'lambertcylindrical'): proj = ccrs.LambertCylindrical(central_longitude=central_longitude) elif (proj_name == 'mercator'): proj = ccrs.Mercator(central_longitude=central_longitude, min_latitude=min_latitude, max_latitude=max_latitude, latitude_true_scale=latitude_true_scale, false_easting=false_easting, false_northing=false_northing, globe=globe, scale_factor=None) ######### elif (proj_name == 'miller'): proj = ccrs.Miller(central_longitude=central_longitude, globe=globe) elif (proj_name == 'mollweide'): proj = ccrs.Mollweide(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'orthographic'): proj = ccrs.Orthographic(central_longitude=central_longitude, central_latitude=central_latitude, globe=globe) elif (proj_name == 'robinson'): proj = ccrs.Robinson(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'sinusoidal'): proj = ccrs.Sinusoidal(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'stereographic'): proj = ccrs.Stereographic(central_latitude=central_latitude, central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe, true_scale_latitude=true_scale_latitude, scale_factor=scale_factor) elif (proj_name == 'transversemercator'): proj = ccrs.TransverseMercator( central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, scale_factor=1.0, ########## approx=approx) elif (proj_name == 'utm'): proj = ccrs.UTM(zone, southern_hemisphere=southern_hemisphere, globe=globe) elif (proj_name == 'interruptedgoodehomolosine'): proj = ccrs.InterruptedGoodeHomolosine( central_longitude=central_longitude, globe=globe) elif (proj_name == 'rotatedpole'): proj = ccrs.RotatedPole( pole_longitude=pole_longitude, pole_latitude=pole_latitude, globe=globe, central_rotated_longitude=central_rotated_longitude) elif (proj_name == 'osgb'): proj = ccrs.OSGB(approx=approx) elif (proj_name == 'europp'): proj = ccrs.EuroPP elif (proj_name == 'geostationary'): proj = ccrs.Geostationary(central_longitude=central_longitude, satellite_height=satellite_height, false_easting=false_easting, false_northing=false_northing, globe=globe, sweep_axis=sweep_axis) elif (proj_name == 'nearsideperspective'): proj = ccrs.NearsidePerspective(central_longitude=central_longitude, central_latitude=central_latitude, satellite_height=satellite_height, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckerti'): proj = ccrs.EckertI(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertii'): proj = ccrs.EckertII(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertiii'): proj = ccrs.EckertIII(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertiv'): proj = ccrs.EckertIV(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertv'): proj = ccrs.EckertV(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertvi'): proj = ccrs.EckertVI(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'equalearth'): proj = ccrs.EqualEarth(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'gnomonic'): proj = ccrs.Gnomonic(central_latitude=central_latitude, central_longitude=central_longitude, globe=globe) elif (proj_name == 'lambertazimuthalequalarea'): proj = ccrs.LambertAzimuthalEqualArea( central_longitude=central_longitude, central_latitude=central_latitude, globe=globe, false_easting=false_easting, false_northing=false_northing) elif (proj_name == 'northpolarstereo'): proj = ccrs.NorthPolarStereo(central_longitude=central_longitude, true_scale_latitude=true_scale_latitude, globe=globe) elif (proj_name == 'osni'): proj = ccrs.OSNI(approx=approx) elif (proj_name == 'southpolarstereo'): proj = ccrs.SouthPolarStereo(central_longitude=central_longitude, true_scale_latitude=true_scale_latitude, globe=globe) else: # This is same as "Geographic coordinates" proj = ccrs.PlateCarree(central_longitude=central_longitude, globe=globe) return proj
def plot_corr_maps(corr_xr, mask_xr=None, map_proj=None, row_dim='split', col_dim='lag', clim='relaxed', hspace=-0.6, wspace=0.02, size=2.5, cbar_vert=-0.01, units='units', cmap=None, clevels=None, clabels=None, cticks_center=None, cbar_tick_dict: dict = {}, drawbox=None, title=None, title_fontdict: dict = None, subtitles: np.ndarray = None, subtitle_fontdict: dict = None, zoomregion=None, aspect=None, n_xticks=5, n_yticks=3, x_ticks: Union[bool, np.ndarray] = None, y_ticks: Union[bool, np.ndarray] = None, add_cfeature: str = None, scatter: np.ndarray = None, col_wrap: int = None, textinmap: list = None): ''' zoomregion = tuple(east_lon, west_lon, south_lat, north_lat) ''' #%% # default parameters # mask_xr=None ; row_dim='split'; col_dim='lag'; clim='relaxed'; wspace=.03; # size=2.5; cbar_vert=-0.01; units='units'; cmap=None; hspace=-0.6; # clevels=None; clabels=None; cticks_center=None; cbar_tick_dict={}; map_proj=None ; # drawbox=None; subtitles=None; title=None; lat_labels=True; zoomregion=None # aspect=None; n_xticks=5; n_yticks=3; title_fontdict=None; x_ticks=None; # y_ticks=None; add_cfeature=None; textinmap=None; scatter=None; col_wrap=None if map_proj is None: cen_lon = int(corr_xr.longitude.mean().values) map_proj = ccrs.LambertCylindrical(central_longitude=cen_lon) if row_dim not in corr_xr.dims: corr_xr = corr_xr.expand_dims(row_dim, 0) if mask_xr is not None and row_dim not in mask_xr.dims: mask_xr = mask_xr.expand_dims(row_dim, 0) if col_dim not in corr_xr.dims: corr_xr = corr_xr.expand_dims(col_dim, 0) if mask_xr is not None and col_dim not in mask_xr.dims: mask_xr = mask_xr.expand_dims(col_dim, 0) var_n = corr_xr.name rows = corr_xr[row_dim].values cols = corr_xr[col_dim].values rename_dims = {row_dim: 'row', col_dim: 'col'} rename_dims_inv = {'row': row_dim, 'col': col_dim} plot_xr = corr_xr.rename(rename_dims) if mask_xr is not None: plot_mask = mask_xr.rename(rename_dims) dim_coords = plot_xr.squeeze().dims dim_coords = [d for d in dim_coords if d not in ['latitude', 'longitude']] rename_subs = {d: rename_dims_inv[d] for d in dim_coords} lat = plot_xr.latitude lon = plot_xr.longitude zonal_width = abs(lon[-1] - lon[0]).values if aspect is None: aspect = (lon.size) / lat.size if col_wrap is None: g = xr.plot.FacetGrid(plot_xr, col='col', row='row', subplot_kws={'projection': map_proj}, sharex=True, sharey=True, aspect=aspect, size=size) else: g = xr.plot.FacetGrid(plot_xr, col='col', subplot_kws={'projection': map_proj}, sharex=True, sharey=True, aspect=aspect, size=size, col_wrap=col_wrap) figheight = g.fig.get_figheight() # ============================================================================= # Coordinate labels # ============================================================================= import cartopy.mpl.ticker as cticker g.set_ticks(fontsize='large') if x_ticks is None or x_ticks is False: #auto-ticks, if False, will be masked longitude_labels = np.linspace(np.min(lon), np.max(lon), n_xticks, dtype=int) longitude_labels = np.array( sorted(list(set(np.round(longitude_labels, -1))))) else: longitude_labels = x_ticks # if x_ticks==False -> no ticklabels if y_ticks is None or y_ticks is False: #auto-ticks, if False, will be masked latitude_labels = np.linspace(lat.min(), lat.max(), n_yticks, dtype=int) latitude_labels = sorted(list(set(np.round(latitude_labels, -1)))) else: latitude_labels = y_ticks # if y_ticks==False -> no ticklabels g.fig.subplots_adjust(hspace=hspace, wspace=wspace) if clevels is None: class MidpointNormalize(mcolors.Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint mcolors.Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) if clim == 'relaxed': vmin_ = np.nanpercentile(plot_xr, 1) vmax_ = np.nanpercentile(plot_xr, 99) elif type(clim) == tuple: vmin_, vmax_ = clim else: vmin_ = plot_xr.min() - 0.01 vmax_ = plot_xr.max() + 0.01 vmin = np.round(float(vmin_), decimals=2) vmax = np.round(float(vmax_), decimals=2) clevels = np.linspace(-max(abs(vmin), vmax), max(abs(vmin), vmax), 17) # choose uneven number for # steps else: vmin_ = np.nanpercentile(plot_xr, 1) vmax_ = np.nanpercentile(plot_xr, 99) vmin = np.round(float(vmin_), decimals=2) vmax = np.round(float(vmax_), decimals=2) clevels = clevels if cmap is None: cmap = plt.cm.RdBu_r else: cmap = cmap for col, c_label in enumerate(cols): xrdatavar = plot_xr.sel(col=c_label) dlon = abs(lon[1] - lon[0]) if abs(lon[-1] - 360) <= dlon and lon[0] < dlon: xrdatavar = extend_longitude(xrdatavar) for row, r_label in enumerate(rows): if col_wrap is not None: row = np.repeat(list(range(g.axes.shape[0])), g.axes.shape[1])[col] col = (list(range(col_wrap)) * g.axes.shape[0])[col] print( f"\rPlotting Corr maps {var_n}, {row_dim} {r_label}, {col_dim} {c_label}", end="\n") plotdata = xrdatavar.sel(row=r_label).rename(rename_subs).squeeze() if mask_xr is not None: xrmaskvar = plot_mask.sel(col=c_label) if abs(lon[-1] - 360) <= (lon[1] - lon[0]) and lon[0] == 0: xrmaskvar = extend_longitude(xrmaskvar) plotmask = xrmaskvar.sel(row=r_label) # if plotdata is already masked (with nans): p_nans = int(100 * plotdata.values[np.isnan(plotdata.values)].size / plotdata.size) if mask_xr is not None: # field not completely masked? all_masked = (plotmask.values == False).all() if all_masked == False: if p_nans != 100: plotmask.plot.contour( ax=g.axes[row, col], transform=ccrs.PlateCarree(), linestyles=['solid'], colors=['black'], linewidths=np.round(zonal_width / 150, 1) + 0.3, levels=[float(vmin), float(vmax)], add_colorbar=False) # try: # im = plotdata.plot.contourf(ax=g.axes[row,col], transform=ccrs.PlateCarree(), # center=0, # levels=clevels, cmap=cmap, # subplot_kws={'projection':map_proj},add_colorbar=False) # except ValueError: # print('could not draw contourf, shifting to pcolormesh') # if no signifcant regions, still plot corr values, but the causal plot must remain empty if mask_xr is None or all_masked == False or (all_masked and 'tigr' not in str(c_label)): im = plotdata.plot.pcolormesh(ax=g.axes[row, col], transform=ccrs.PlateCarree(), center=0, levels=clevels, cmap=cmap, add_colorbar=False) # subplot_kws={'projection':map_proj}) elif all_masked and 'tigr' in c_label: g.axes[row, col].text(0.5, 0.5, 'No regions significant', horizontalalignment='center', fontsize='x-large', verticalalignment='center', transform=g.axes[row, col].transAxes) # ============================================================================= # Draw (rectangular) box # ============================================================================= if drawbox is not None: from shapely.geometry.polygon import LinearRing def get_ring(coords): '''tuple in format: west_lon, east_lon, south_lat, north_lat ''' west_lon, east_lon, south_lat, north_lat = coords lons_sq = [west_lon, west_lon, east_lon, east_lon] lats_sq = [north_lat, south_lat, south_lat, north_lat] ring = [LinearRing(list(zip(lons_sq, lats_sq)))] return ring if isinstance(drawbox[1], tuple): ring = get_ring(drawbox[1]) elif isinstance(drawbox[1], list): ring = drawbox[1] if drawbox[0] == g.axes.size or drawbox[0] == 'all': g.axes[row, col].add_geometries(ring, ccrs.PlateCarree(), facecolor='none', edgecolor='green', linewidth=2, linestyle='dashed', zorder=4) elif type(drawbox[0]) is tuple: row_box, col_box = drawbox[0] if row == row_box and col == col_box: g.axes[row, col].add_geometries(ring, ccrs.PlateCarree(), facecolor='none', edgecolor='green', linewidth=2, linestyle='dashed', zorder=4) # ============================================================================= # Add text in plot - list([ax_loc, list(tuple(lon,lat,text,kwrgs))]) # ============================================================================= if textinmap is not None: for list_t in textinmap: if list_t[0] == g.axes.size or list_t[0] == 'all': row_text, col_text = row, col if type(list_t[0]) is tuple: row_text, col_text = list_t[0] if type(list_t[1]) is not list: list_t[1] = [list_t[1]] for t in list_t[1]: # loop if multiple textboxes per plot lontext, lattext, text, kwrgs = t # lon in degrees west-east kwrgs.update( dict(horizontalalignment='center', transform=ccrs.Geodetic()) ) # standard settings g.axes[row_text, col_text].text(int(lontext), int(lattext), text, **kwrgs) # ============================================================================= # Add scatter points list([[ax_loc, list(np_array_xy, kwrgs)]]) # ============================================================================= if scatter is not None: for list_s in scatter: loc_ax = list_s[0] if loc_ax == g.axes.size or loc_ax == 'all': # ax_loc row_text, col_text = row, col else: row_text, col_text = loc_ax np_array_xy = list_s[1][ 0] # lon, lat coords - shape=(points, 2) kwrgs_scatter = list_s[1][1] g.axes[row_text, col_text].scatter(x=np_array_xy[:, 0], y=np_array_xy[:, 1], transform=ccrs.PlateCarree(), **kwrgs_scatter) # ============================================================================= # Subtitles # ============================================================================= if subtitles is not None: if subtitle_fontdict is None: subtitle_fontdict = dict({'fontsize': 16}) g.axes[row, col].set_title(np.array(subtitles)[row, col], fontdict=subtitle_fontdict, loc='center') # ============================================================================= # Format coordinate ticks # ============================================================================= if map_proj.proj4_params['proj'] in ['merc', 'eqc', 'cea']: ax = g.axes[row, col] # x-ticks and labels ax.set_xticks(longitude_labels[:], crs=ccrs.PlateCarree()) if x_ticks is not False: ax.set_xticklabels(longitude_labels[:], fontsize=12) lon_formatter = cticker.LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) else: fake_labels = [' ' * len(str(l)) for l in longitude_labels] g.axes[row, col].set_xticklabels(fake_labels, fontsize=12) # y-ticks and labels g.axes[row, col].set_yticks(latitude_labels, crs=ccrs.PlateCarree()) if y_ticks is not False: g.axes[row, col].set_yticklabels(latitude_labels, fontsize=12) lat_formatter = cticker.LatitudeFormatter() g.axes[row, col].yaxis.set_major_formatter(lat_formatter) else: fake_labels = [' ' * len(str(l)) for l in latitude_labels] g.axes[row, col].set_yticklabels(fake_labels, fontsize=12) # ============================================================================= # Gridlines # ============================================================================= if type(y_ticks) is bool and type(x_ticks) is bool: if np.logical_and(y_ticks == False, x_ticks == False): # if no ticks, then also no gridlines pass # else: # gl = g.axes[row,col].grid(linewidth=1, color='black', alpha=0.3, # linestyle='--', zorder=4) else: gl = g.axes[row, col].gridlines(crs=ccrs.PlateCarree(), linewidth=.5, color='black', alpha=0.15, linestyle='--', zorder=4) gl.xlocator = mticker.FixedLocator( (longitude_labels % 360 + 540) % 360 - 180) gl.ylocator = mticker.FixedLocator(latitude_labels) g.axes[row, col].set_ylabel('') g.axes[row, col].set_xlabel('') g.axes[row, col].coastlines(color='black', alpha=0.3, facecolor='grey', linewidth=2) # black outline subplot g.axes[row, col].spines['geo'].set_edgecolor('black') if corr_xr.name is not None: if corr_xr.name[:3] == 'sst': g.axes[row, col].add_feature(cfeature.LAND, facecolor='grey', alpha=0.3, zorder=0) if add_cfeature is not None: g.axes[row, col].add_feature(cfeature.__dict__[add_cfeature], facecolor='grey', alpha=0.3, zorder=4) if zoomregion is not None: g.axes[row, col].set_extent(zoomregion, crs=ccrs.PlateCarree()) else: g.axes[row, col].set_extent([lon[0], lon[-1], lat[0], lat[-1]], crs=ccrs.PlateCarree()) # ============================================================================= # lay-out settings FacetGrid and colorbar # ============================================================================= # height colorbor 1/10th of height of subfigure height = g.axes[-1, 0].get_position().height / 10 bottom_ysub = (figheight / 40) / (rows.size * 2) + cbar_vert cbar_ax = g.fig.add_axes([0.25, bottom_ysub, 0.5, height]) #[left, bottom, width, height] if units == 'units' and 'units' in corr_xr.attrs: clabel = corr_xr.attrs['units'] elif units != 'units' and units is not None: clabel = units else: clabel = '' if cticks_center is None: if clabels is None: clabels = clevels[::2] plt.colorbar( im, cax=cbar_ax, orientation='horizontal', # norm=norm, label=clabel, ticks=clabels, extend='neither') else: cbar = plt.colorbar(im, cbar_ax, orientation='horizontal', extend='neither', label=clabel) cbar.set_ticks(clevels + 0.5) cbar.set_ticklabels(np.array(clevels + 1, dtype=int), update_ticks=True) cbar.update_ticks() cbar_ax.tick_params(**cbar_tick_dict) if title is not None: if title_fontdict is None: title_fontdict = dict({'fontsize': 18, 'fontweight': 'bold'}) g.fig.suptitle(title, **title_fontdict) # plt.tight_layout(pad=1.1-0.02*rows.size, h_pad=None, w_pad=None, rect=None) # print("\n") #%% return g.fig
import matplotlib.pyplot as plt import cartopy.crs as ccrs plt.figure(figsize=(9.42477796076938, 3)) ax = plt.axes(projection=ccrs.LambertCylindrical()) ax.coastlines(resolution='110m') ax.gridlines()
def set_proj(projection='Robinson', proj_default=True): """ Set the projection for Cartopy. Parameters ---------- projection : string the map projection. Available projections: 'Robinson' (default), 'PlateCarree', 'AlbertsEqualArea', 'AzimuthalEquidistant','EquidistantConic','LambertConformal', 'LambertCylindrical','Mercator','Miller','Mollweide','Orthographic', 'Sinusoidal','Stereographic','TransverseMercator','UTM', 'InterruptedGoodeHomolosine','RotatedPole','OSGB','EuroPP', 'Geostationary','NearsidePerspective','EckertI','EckertII', 'EckertIII','EckertIV','EckertV','EckertVI','EqualEarth','Gnomonic', 'LambertAzimuthalEqualArea','NorthPolarStereo','OSNI','SouthPolarStereo' proj_default : bool If True, uses the standard projection attributes from Cartopy. Enter new attributes in a dictionary to change them. Lists of attributes can be found in the Cartopy documentation: https://scitools.org.uk/cartopy/docs/latest/crs/projections.html#eckertiv Returns ------- proj : the Cartopy projection object See Also -------- pyleoclim.utils.mapping.map_all : mapping function making use of the projection """ if proj_default is not True and type(proj_default) is not dict: raise TypeError( 'The default for the projections should either be provided' + ' as a dictionary or set to True') # Set the projection if projection == 'Robinson': if proj_default is True: proj = ccrs.Robinson() else: proj = ccrs.Robinson(**proj_default) elif projection == 'PlateCarree': if proj_default is True: proj = ccrs.PlateCarree() else: proj = ccrs.PlateCarree(**proj_default) elif projection == 'AlbersEqualArea': if proj_default is True: proj = ccrs.AlbersEqualArea() else: proj = ccrs.AlbersEqualArea(**proj_default) elif projection == 'AzimuthalEquidistant': if proj_default is True: proj = ccrs.AzimuthalEquidistant() else: proj = ccrs.AzimuthalEquidistant(**proj_default) elif projection == 'EquidistantConic': if proj_default is True: proj = ccrs.EquidistantConic() else: proj = ccrs.EquidistantConic(**proj_default) elif projection == 'LambertConformal': if proj_default is True: proj = ccrs.LambertConformal() else: proj = ccrs.LambertConformal(**proj_default) elif projection == 'LambertCylindrical': if proj_default is True: proj = ccrs.LambertCylindrical() else: proj = ccrs.LambertCylindrical(**proj_default) elif projection == 'Mercator': if proj_default is True: proj = ccrs.Mercator() else: proj = ccrs.Mercator(**proj_default) elif projection == 'Miller': if proj_default is True: proj = ccrs.Miller() else: proj = ccrs.Miller(**proj_default) elif projection == 'Mollweide': if proj_default is True: proj = ccrs.Mollweide() else: proj = ccrs.Mollweide(**proj_default) elif projection == 'Orthographic': if proj_default is True: proj = ccrs.Orthographic() else: proj = ccrs.Orthographic(**proj_default) elif projection == 'Sinusoidal': if proj_default is True: proj = ccrs.Sinusoidal() else: proj = ccrs.Sinusoidal(**proj_default) elif projection == 'Stereographic': if proj_default is True: proj = ccrs.Stereographic() else: proj = ccrs.Stereographic(**proj_default) elif projection == 'TransverseMercator': if proj_default is True: proj = ccrs.TransverseMercator() else: proj = ccrs.TransverseMercator(**proj_default) elif projection == 'TransverseMercator': if proj_default is True: proj = ccrs.TransverseMercator() else: proj = ccrs.TransverseMercator(**proj_default) elif projection == 'UTM': if proj_default is True: proj = ccrs.UTM() else: proj = ccrs.UTM(**proj_default) elif projection == 'UTM': if proj_default is True: proj = ccrs.UTM() else: proj = ccrs.UTM(**proj_default) elif projection == 'InterruptedGoodeHomolosine': if proj_default is True: proj = ccrs.InterruptedGoodeHomolosine() else: proj = ccrs.InterruptedGoodeHomolosine(**proj_default) elif projection == 'RotatedPole': if proj_default is True: proj = ccrs.RotatedPole() else: proj = ccrs.RotatedPole(**proj_default) elif projection == 'OSGB': if proj_default is True: proj = ccrs.OSGB() else: proj = ccrs.OSGB(**proj_default) elif projection == 'EuroPP': if proj_default is True: proj = ccrs.EuroPP() else: proj = ccrs.EuroPP(**proj_default) elif projection == 'Geostationary': if proj_default is True: proj = ccrs.Geostationary() else: proj = ccrs.Geostationary(**proj_default) elif projection == 'NearsidePerspective': if proj_default is True: proj = ccrs.NearsidePerspective() else: proj = ccrs.NearsidePerspective(**proj_default) elif projection == 'EckertI': if proj_default is True: proj = ccrs.EckertI() else: proj = ccrs.EckertI(**proj_default) elif projection == 'EckertII': if proj_default is True: proj = ccrs.EckertII() else: proj = ccrs.EckertII(**proj_default) elif projection == 'EckertIII': if proj_default is True: proj = ccrs.EckertIII() else: proj = ccrs.EckertIII(**proj_default) elif projection == 'EckertIV': if proj_default is True: proj = ccrs.EckertIV() else: proj = ccrs.EckertIV(**proj_default) elif projection == 'EckertV': if proj_default is True: proj = ccrs.EckertV() else: proj = ccrs.EckertV(**proj_default) elif projection == 'EckertVI': if proj_default is True: proj = ccrs.EckertVI() else: proj = ccrs.EckertVI(**proj_default) elif projection == 'EqualEarth': if proj_default is True: proj = ccrs.EqualEarth() else: proj = ccrs.EqualEarth(**proj_default) elif projection == 'Gnomonic': if proj_default is True: proj = ccrs.Gnomonic() else: proj = ccrs.Gnomonic(**proj_default) elif projection == 'LambertAzimuthalEqualArea': if proj_default is True: proj = ccrs.LambertAzimuthalEqualArea() else: proj = ccrs.LambertAzimuthalEqualArea(**proj_default) elif projection == 'NorthPolarStereo': if proj_default is True: proj = ccrs.NorthPolarStereo() else: proj = ccrs.NorthPolarStereo(**proj_default) elif projection == 'OSNI': if proj_default is True: proj = ccrs.OSNI() else: proj = ccrs.OSNI(**proj_default) elif projection == 'OSNI': if proj_default is True: proj = ccrs.SouthPolarStereo() else: proj = ccrs.SouthPolarStereo(**proj_default) else: raise ValueError('Invalid projection type') return proj
# ~ #*********************************************************************** # ~ # LISTE DES PROJECTIONS # ~ #*********************************************************************** import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt fig = plt.figure(figsize=(16, 18)) fig.suptitle('Projections', fontsize=20, y=0.92) projections = { 'PlateCarree': ccrs.PlateCarree(), 'AlbersEqualArea': ccrs.AlbersEqualArea(), 'AzimuthalEquidistant': ccrs.AzimuthalEquidistant(), 'EquidistantConic': ccrs.EquidistantConic(), 'LambertConformal': ccrs.LambertConformal(), 'LambertCylindrical': ccrs.LambertCylindrical(), 'Mercator': ccrs.Mercator(), 'Miller': ccrs.Miller(), 'Mollweide': ccrs.Mollweide(), 'Orthographic': ccrs.Orthographic(), 'Robinson': ccrs.Robinson(), 'Sinusoidal': ccrs.Sinusoidal(), 'Stereographic': ccrs.Stereographic(), 'TransverseMercator': ccrs.TransverseMercator(), 'InterruptedGoodeHomolosine': ccrs.InterruptedGoodeHomolosine(), 'RotatedPole': ccrs.RotatedPole(), 'OSGB': ccrs.OSGB(), 'EuroPP': ccrs.EuroPP(), 'Geostationary': ccrs.Geostationary(), 'NearsidePerspective': ccrs.NearsidePerspective(), 'EckertI': ccrs.EckertI(),
#declaring tallin's coordinates origin_lat = 59.41329956 origin_lon= 24.83279991 """ importing "merged.csv" row in data, skipping the first row which contains coordinate of Tallinn """ data = pd.read_csv("merged.csv", skiprows=[1]) #here map is being created using cartopy fig = plt.figure(figsize=(5*4,5*4)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.LambertCylindrical()) ax.set_extent([-20, 50,70, 30], crs=ccrs.PlateCarree()) ax.stock_img() ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.BORDERS) ax.add_feature(cfeature.BORDERS, linestyle=':') plt.title('Direct flights from Tallinn') # adding TLL label to point out tallinn airport plt.text(origin_lon, origin_lat, 'TLL', horizontalalignment='right', transform=ccrs.Geodetic()) """
def animate_map(ds: xr.Dataset, var: VarName.TYPE = None, animate_dim: str = 'time', interval: int = 200, true_range: bool = False, indexers: DictLike.TYPE = None, region: PolygonLike.TYPE = None, projection: str = 'PlateCarree', central_lon: float = 0.0, title: str = None, contour_plot: bool = False, cmap_params: DictLike.TYPE = None, plot_properties: DictLike.TYPE = None, file: str = None, monitor: Monitor = Monitor.NONE) -> HTML: """ Create a geographic map animation for the variable given by dataset *ds* and variable name *var*. Creates an animation of the given variable from the given dataset on a map with coastal lines. In case no variable name is given, the first encountered variable in the dataset is animated. It is also possible to set extents of the animation. If no extents are given, a global animation is created. The following file formats for saving the animation are supported: html :param ds: the dataset containing the variable to animate :param var: the variable's name :param animate_dim: Dimension to animate, if none given defaults to time. :param interval: Delay between frames in milliseconds. Defaults to 200. :param true_range: If True, calculates colormap and colorbar configuration parameters from the whole dataset. Can potentially take a lot of time. Defaults to False, in which case the colormap is calculated from the first frame. :param indexers: Optional indexers into data array of *var*. The *indexers* is a dictionary or a comma-separated string of key-value pairs that maps the variable's dimension names to constant labels. e.g. "layer=4". :param region: Region to animate :param projection: name of a global projection, see http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html :param central_lon: central longitude of the projection in degrees :param title: an optional title :param contour_plot: If true plot a filled contour plot of data, otherwise plots a pixelated colormesh :param cmap_params: optional additional colormap configuration parameters, e.g. "vmax=300, cmap='magma'" For full reference refer to http://xarray.pydata.org/en/stable/generated/xarray.plot.contourf.html :param plot_properties: optional plot properties for Python matplotlib, e.g. "bins=512, range=(-1.5, +1.5)" For full reference refer to https://matplotlib.org/api/lines_api.html and https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contourf.html :param file: path to a file in which to save the animation :param monitor: A progress monitor. :return: An animation in HTML format """ if not isinstance(ds, xr.Dataset): raise NotImplementedError('Only gridded datasets are currently supported') var_name = None if not var: for key in ds.data_vars.keys(): var_name = key break else: var_name = VarName.convert(var) try: var = ds[var_name] except KeyError: raise ValidationError('Provided variable name "{}" does not exist in the given dataset'.format(var_name)) indexers = DictLike.convert(indexers) or {} properties = DictLike.convert(plot_properties) or {} cmap_params = DictLike.convert(cmap_params) or {} extents = None bounds = handle_plot_polygon(region) if bounds: lon_min, lat_min, lon_max, lat_max = bounds extents = [lon_min, lon_max, lat_min, lat_max] if len(ds.lat) < 2 or len(ds.lon) < 2: # Matplotlib can not plot datasets with less than these dimensions with # contourf and pcolormesh methods raise ValidationError('The minimum dataset spatial dimensions to create a map' ' plot are (2,2)') # See http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html# if projection == 'PlateCarree': proj = ccrs.PlateCarree(central_longitude=central_lon) elif projection == 'LambertCylindrical': proj = ccrs.LambertCylindrical(central_longitude=central_lon) elif projection == 'Mercator': proj = ccrs.Mercator(central_longitude=central_lon) elif projection == 'Miller': proj = ccrs.Miller(central_longitude=central_lon) elif projection == 'Mollweide': proj = ccrs.Mollweide(central_longitude=central_lon) elif projection == 'Orthographic': proj = ccrs.Orthographic(central_longitude=central_lon) elif projection == 'Robinson': proj = ccrs.Robinson(central_longitude=central_lon) elif projection == 'Sinusoidal': proj = ccrs.Sinusoidal(central_longitude=central_lon) elif projection == 'NorthPolarStereo': proj = ccrs.NorthPolarStereo(central_longitude=central_lon) elif projection == 'SouthPolarStereo': proj = ccrs.SouthPolarStereo(central_longitude=central_lon) else: raise ValidationError('illegal projection: "%s"' % projection) figure = plt.figure(figsize=(8, 4)) ax = plt.axes(projection=proj) if extents: ax.set_extent(extents, ccrs.PlateCarree()) else: ax.set_global() ax.coastlines() if not animate_dim: animate_dim = 'time' indexers[animate_dim] = var[animate_dim][0] var_data = get_var_data(var, indexers, remaining_dims=('lon', 'lat')) with monitor.starting("animate", len(var[animate_dim]) + 3): if true_range: data_min, data_max = _get_min_max(var, monitor=monitor) else: data_min, data_max = _get_min_max(var_data, monitor=monitor) cmap_params = determine_cmap_params(data_min, data_max, **cmap_params) plot_kwargs = {**properties, **cmap_params} # Plot the first frame to set-up the axes with the colorbar properly # transform keyword is for the coordinate our data is in, which in case of a # 'normal' lat/lon dataset is PlateCarree. if contour_plot: var_data.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), subplot_kws={'projection': proj}, add_colorbar=True, **plot_kwargs) else: var_data.plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree(), subplot_kws={'projection': proj}, add_colorbar=True, **plot_kwargs) if title: ax.set_title(title) figure.tight_layout() monitor.progress(1) def run(value): ax.clear() if extents: ax.set_extent(extents, ccrs.PlateCarree()) else: ax.set_global() ax.coastlines() indexers[animate_dim] = value var_data = get_var_data(var, indexers, remaining_dims=('lon', 'lat')) var_data.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), subplot_kws={'projection': proj}, add_colorbar=False, **plot_kwargs) if title: ax.set_title(title) monitor.progress(1) return ax anim = animation.FuncAnimation(figure, run, [i for i in var[animate_dim]], interval=interval, blit=False, repeat=False) anim_html = anim.to_jshtml() # Prevent the animation for running after it's finished del anim # Delete the rogue temp-file try: os.remove('None0000000.png') except FileNotFoundError: pass if file: with open(file, 'w') as outfile: outfile.write(anim_html) monitor.progress(1) return HTML(anim_html)
@author: arkriger basic script to reproduce the Tissot indicatrices on two Equal Area maps and one Mercator~ answer to Question 10 and 11 of Basic Assignment 3 """ import matplotlib.pyplot as plt import cartopy.crs as ccrs def plot_tissot(ax, **kwargs): ax.set_global() ax.stock_img() ax.tissot(facecolor='orange', alpha=0.5) fig = plt.figure(figsize=(14, 8)) ax1 = fig.add_subplot(311, projection=ccrs.LambertAzimuthalEqualArea()) plot_tissot(ax1) ax1.set_title('Lambert Azimuthal Equal Area', fontweight="bold") ax2 = fig.add_subplot( 312, projection=ccrs.LambertCylindrical(central_longitude=-19.0)) plot_tissot(ax2) ax2.set_title('Lambert Cylindrical Equal Area', fontweight="bold") ax3 = fig.add_subplot(313, projection=ccrs.Mercator(central_longitude=-19.0)) plot_tissot(ax3) ax3.set_title('Mercator', fontweight="bold") plt.show()
def _create_projection_axis(projection_type, user_lon_0, lat_lim, subplot_grid, less_output): """Set appropriate axis for projection type See plot_proj_to_latlon_grid for input parameter definitions. Returns ------- ax : matplotlib axis object defined with the correct projection show_grid_labels : logical True = show the grid labels, only currently supported for PlateCarree and Mercator projections """ # initialize (optional) subplot variables row = [] col = [] ind = [] if subplot_grid is not None: if type(subplot_grid) is dict: row = subplot_grid['nrows'] col = subplot_grid['ncols'] ind = subplot_grid['index'] elif type(subplot_grid) is list: row = subplot_grid[0] col = subplot_grid[1] ind = subplot_grid[2] else: raise TypeError('Unexpected subplot_grid type: ', type(subplot_grid)) if projection_type == 'Mercator': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.Mercator(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.Mercator( central_longitude=user_lon_0)) show_grid_labels = True elif projection_type == 'PlateCaree': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.PlateCarree(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.PlateCarree( central_longitude=user_lon_0)) show_grid_labels = True elif projection_type == 'cyl': if subplot_grid is not None: ax = plt.subplot(row, col, ind, projection=ccrs.LambertCylindrical( central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.LambertCylindrical( central_longitude=user_lon_0)) show_grid_labels = False elif projection_type == 'robin': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.Robinson(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.Robinson( central_longitude=user_lon_0)) show_grid_labels = False elif projection_type == 'ortho': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.Orthographic(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.Orthographic( central_longitude=user_lon_0)) show_grid_labels = False elif projection_type == 'stereo': if lat_lim > 0: stereo_proj = ccrs.NorthPolarStereo() else: stereo_proj = ccrs.SouthPolarStereo() if subplot_grid is not None: ax = plt.subplot(row, col, ind, projection=stereo_proj) else: ax = plt.axes(projection=stereo_proj) show_grid_labels = False elif projection_type == 'InterruptedGoodeHomolosine': if subplot_grid is not None: ax = plt.subplot(row, col, ind, projection=ccrs.InterruptedGoodeHomolosine( central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.InterruptedGoodeHomolosine( central_longitude=user_lon_0)) show_grid_labels = False else: raise NotImplementedError( 'projection type must be either "Mercator", "PlateCaree", "cyl", "robin", "ortho", "stereo", or "InterruptedGoodeHomolosine"' ) if not less_output: print('Projection type: ', projection_type) return (ax, show_grid_labels)
def projection(self): if self.proj is None: return ccrs.PlateCarree() proj_dict = ast.literal_eval(self.proj) user_proj = proj_dict.pop("proj") if user_proj == 'PlateCarree': self.xylim_supported = True return ccrs.PlateCarree(**proj_dict) elif user_proj == 'AlbersEqualArea': return ccrs.AlbersEqualArea(**proj_dict) elif user_proj == 'AzimuthalEquidistant': return ccrs.AzimuthalEquidistant(**proj_dict) elif user_proj == 'EquidistantConic': return ccrs.EquidistantConic(**proj_dict) elif user_proj == 'LambertConformal': return ccrs.LambertConformal(**proj_dict) elif user_proj == 'LambertCylindrical': return ccrs.LambertCylindrical(**proj_dict) elif user_proj == 'Mercator': return ccrs.Mercator(**proj_dict) elif user_proj == 'Miller': return ccrs.Miller(**proj_dict) elif user_proj == 'Mollweide': return ccrs.Mollweide(**proj_dict) elif user_proj == 'Orthographic': return ccrs.Orthographic(**proj_dict) elif user_proj == 'Robinson': return ccrs.Robinson(**proj_dict) elif user_proj == 'Sinusoidal': return ccrs.Sinusoidal(**proj_dict) elif user_proj == 'Stereographic': return ccrs.Stereographic(**proj_dict) elif user_proj == 'TransverseMercator': return ccrs.TransverseMercator(**proj_dict) elif user_proj == 'UTM': return ccrs.UTM(**proj_dict) elif user_proj == 'InterruptedGoodeHomolosine': return ccrs.InterruptedGoodeHomolosine(**proj_dict) elif user_proj == 'RotatedPole': return ccrs.RotatedPole(**proj_dict) elif user_proj == 'OSGB': self.xylim_supported = False return ccrs.OSGB(**proj_dict) elif user_proj == 'EuroPP': self.xylim_supported = False return ccrs.EuroPP(**proj_dict) elif user_proj == 'Geostationary': return ccrs.Geostationary(**proj_dict) elif user_proj == 'NearsidePerspective': return ccrs.NearsidePerspective(**proj_dict) elif user_proj == 'EckertI': return ccrs.EckertI(**proj_dict) elif user_proj == 'EckertII': return ccrs.EckertII(**proj_dict) elif user_proj == 'EckertIII': return ccrs.EckertIII(**proj_dict) elif user_proj == 'EckertIV': return ccrs.EckertIV(**proj_dict) elif user_proj == 'EckertV': return ccrs.EckertV(**proj_dict) elif user_proj == 'EckertVI': return ccrs.EckertVI(**proj_dict) elif user_proj == 'EqualEarth': return ccrs.EqualEarth(**proj_dict) elif user_proj == 'Gnomonic': return ccrs.Gnomonic(**proj_dict) elif user_proj == 'LambertAzimuthalEqualArea': return ccrs.LambertAzimuthalEqualArea(**proj_dict) elif user_proj == 'NorthPolarStereo': return ccrs.NorthPolarStereo(**proj_dict) elif user_proj == 'OSNI': return ccrs.OSNI(**proj_dict) elif user_proj == 'SouthPolarStereo': return ccrs.SouthPolarStereo(**proj_dict)
def plot_map(ds: xr.Dataset, var: VarName.TYPE = None, index: DictLike.TYPE = None, time: Union[str, int] = None, region: PolygonLike.TYPE = None, projection: str = 'PlateCarree', central_lon: float = 0.0, file: str = None) -> None: """ Plot the given variable from the given dataset on a map with coastal lines. In case no variable name is given, the first encountered variable in the dataset is plotted. In case no time index is given, the first time slice is taken. It is also possible to set extents of the plot. If no extents are given, a global plot is created. The plot can either be shown using pyplot functionality, or saved, if a path is given. The following file formats for saving the plot are supported: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff :param ds: xr.Dataset to plot :param var: variable name in the dataset to plot :param index: Optional index into the variable's data array. The *index* is a dictionary that maps the variable's dimension names to constant labels. For example, ``lat`` and ``lon`` are given in decimal degrees, while a ``time`` value may be provided as datetime object or a date string. *index* may also be a comma-separated string of key-value pairs, e.g. "lat=12.4, time='2012-05-02'". :param time: time slice index to plot :param region: Region to plot :param projection: name of a global projection, see http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html :param central_lon: central longitude of the projection in degrees :param file: path to a file in which to save the plot """ if not isinstance(ds, xr.Dataset): raise NotImplementedError('Only raster datasets are currently ' 'supported') var_name = None if not var: for key in ds.data_vars.keys(): var_name = key break else: var_name = VarName.convert(var) var = ds[var_name] index = DictLike.convert(index) # 0 is a valid index, hence test if time is None if time is not None and isinstance(time, int) and 'time' in var.coords: time = var.coords['time'][time] if time: if not index: index = dict() index['time'] = time for dim_name in var.dims: if dim_name not in ('lat', 'lon'): if not index: index = dict() if dim_name not in index: index[dim_name] = 0 if region is None: lat_min = -90.0 lat_max = 90.0 lon_min = -180.0 lon_max = 180.0 else: region = PolygonLike.convert(region) lon_min, lat_min, lon_max, lat_max = region.bounds if not _check_bounding_box(lat_min, lat_max, lon_min, lon_max): raise ValueError( 'Provided plot extents do not form a valid bounding box ' 'within [-180.0,+180.0,-90.0,+90.0]') extents = [lon_min, lon_max, lat_min, lat_max] # See http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html# if projection == 'PlateCarree': proj = ccrs.PlateCarree(central_longitude=central_lon) elif projection == 'LambertCylindrical': proj = ccrs.LambertCylindrical(central_longitude=central_lon) elif projection == 'Mercator': proj = ccrs.Mercator(central_longitude=central_lon) elif projection == 'Miller': proj = ccrs.Miller(central_longitude=central_lon) elif projection == 'Mollweide': proj = ccrs.Mollweide(central_longitude=central_lon) elif projection == 'Orthographic': proj = ccrs.Orthographic(central_longitude=central_lon) elif projection == 'Robinson': proj = ccrs.Robinson(central_longitude=central_lon) elif projection == 'Sinusoidal': proj = ccrs.Sinusoidal(central_longitude=central_lon) elif projection == 'NorthPolarStereo': proj = ccrs.NorthPolarStereo(central_longitude=central_lon) elif projection == 'SouthPolarStereo': proj = ccrs.SouthPolarStereo(central_longitude=central_lon) else: raise ValueError('illegal projection') try: if index: var_data = var.sel(**index) else: var_data = var except ValueError: var_data = var fig = plt.figure(figsize=(16, 8)) ax = plt.axes(projection=proj) if extents: ax.set_extent(extents) else: ax.set_global() ax.coastlines() var_data.plot.contourf(ax=ax, transform=proj) if file: fig.savefig(file)
import cartopy.feature as cfeature import matplotlib.pyplot as plt import pandas as pd ## HOME = os.getenv("HOME") birddata = pd.read_csv(os.path.join(HOME, "data", "bird_tracking.csv")) print(birddata.describe()) bird_names = pd.unique(birddata.bird_name) # To move forward, we need to specify a # specific projection that we're interested # in using. proj = ccrs.Mercator() proj = ccrs.PlateCarree() proj = ccrs.LambertCylindrical() proj = ccrs.Mercator() ## plt.figure(figsize=(6.5, 6.5)) ax = plt.axes(projection=proj) ax.stock_img() ## no effect #ax.set_extent((-25.0, 20.0, 52.0, 10.0)) ax.set_extent((-20.0, 10.0, 52.0, 10.0)) ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.BORDERS, linestyle=':') for name in bird_names: ix = (birddata['bird_name'] == name) x, y = birddata.longitude[ix], birddata.latitude[ix]
ex['method'] = 'ran_strat10' ; ex['seed'] = 30 # ex['method'] = 'no_train_test_split' # ============================================================================= # RV events settings (allows to make balanced traintest splits) # ============================================================================= ex['kwrgs_events'] = {'event_percentile':'std', 'min_dur': 1, 'max_break': 0, 'grouped': False} # ============================================================================= # Load some standard settings # ============================================================================= ex = wrapper_RGCPD_tig.standard_settings_and_tests(ex) central_lon_plots = 200 map_proj = ccrs.LambertCylindrical(central_longitude=central_lon_plots) #%% # ***************************************************************************** # ***************************************************************************** # Part 3 Run RGCPD python script with settings # ***************************************************************************** # ***************************************************************************** # ============================================================================= # Find precursor fields (potential precursors) # ============================================================================= ex, outdic_actors = wrapper_RGCPD_tig.calculate_corr_maps(ex, map_proj) #%% # calculate precursor timeseries outdic_actors = wrapper_RGCPD_tig.get_prec_ts(outdic_actors, ex)
# Plot data and create colorbar prec = t.plot.contourf(ax=ax, cmap="Blues_r", transform=ccrs.PlateCarree(), levels = 14, add_colorbar=False) cbar_ticks = np.arange(0, 240, 20) cbar = plt.colorbar(prec, orientation='horizontal', pad=0.075, shrink=0.8, ticks=cbar_ticks) cbar.ax.tick_params(labelsize=10) plt.title(title, loc='center', y=1.17, size=15) plt.title(t.units, loc='right', y=1.08, size=14) plt.title("precipitation", loc='left', y=1.08, size=14) Plot( 2, 2, 1, ccrs.LambertConformal(central_longitude=45, standard_parallels=(36, 55), globe=ccrs.Globe()), "Lambert Conformal") Plot(2, 2, 2, ccrs.LambertCylindrical(central_longitude=45), "Lambert Cylindrical") Plot(2, 2, 3, ccrs.LambertAzimuthalEqualArea(central_longitude=45), "Lambert Azimuthal")