cool_maps package
Submodules
cool_maps.calc module
- cool_maps.calc.calculate_colorbar_ticks(vmin: float, vmax: float, c0: bool = False) ndarray[source]
Calculate tick locations for colorbar
- Parameters:
vmin (float) – minimum value of colorbar (should match vmin of object colorbar is mapped to)
vmax (float) – maximum value of colorbar (should match vmax of object colorbar is mapped to)
c0 (bool) – center values around 0 (for anomaly products)
- Returns:
tick locations
- Return type:
np.ndarray
- cool_maps.calc.calculate_ticks(extent: Tuple[float, ...] | List[float], direction: str, decimal_degrees: bool = False, whole_degree_majors: bool = True) Tuple[ndarray, ndarray, ndarray | List[str]][source]
Define major and minor tick locations and major tick labels
- Parameters:
extent (tuple or list) – extent (x0, x1, y0, y1) of the map in the given coordinate system.
direction (str) – Tell function which bounds to calculate. Must be ‘longitude’ or ‘latitude’.
decimal_degrees (bool, optional) – label ticks in decimal degrees (True) or degree-minute-second (False, default)
whole_degree_majors (bool, optional) – keep major ticks on whole degrees even for small extents (span <= 3 degrees), with minutes only ever shown on minor ticks. Defaults to True. Set to False to allow major ticks at 15’/30’ increments for spans <= 3 degrees, matching pre-1.x behavior.
- Returns:
minor ticks np.ndarray: major ticks Union[np.ndarray, List[str]]: major tick labels
- Return type:
np.ndarray
- cool_maps.calc.dd2dms(vals: ndarray) Tuple[ndarray, ndarray, ndarray][source]
Convert decimal degrees to degree-minute-second
- Parameters:
vals (np.ndarray) – Numpy array of decimal degrees
- Returns:
degrees np.ndarray: minutes np.ndarray: seconds
- Return type:
np.ndarray
- cool_maps.calc.fmt(x: float) str[source]
Function to format bathymetry labels
- Parameters:
x (float) – Bathymetry float value
- Returns:
Formatted string
- Return type:
str
- cool_maps.calc.pad_extent(extent: Tuple[float, ...] | List[float], padding: float | Tuple[float, float] | List[float]) Tuple[float, float, float, float][source]
Expand an extent outward by a padding amount so map ticks and data don’t land right on the edge of the map.
- Parameters:
extent (tuple or list) – extent (x0, x1, y0, y1) to pad.
padding (float or tuple/list of 2 floats) – degrees to subtract from x0/y0 and add to x1/y1. A single number pads longitude and latitude equally; a 2-item sequence is (lon_padding, lat_padding).
- Returns:
padded extent (x0, x1, y0, y1)
- Return type:
tuple
cool_maps.download module
- cool_maps.download.get_bathymetry(extent: Tuple[float, float, float, float] = (-100, -45, 5, 46), source: str = 'https://tds.marine.rutgers.edu/thredds/dodsC/other/bathymetry/GEBCO_2023/GEBCO_2023_sub_ice_topo.nc', lon_var: str = 'lon', lat_var: str = 'lat', elev_var: str = 'elevation', use_cache: bool = True, chunk_size: float | None = 10) Dataset[source]
Retrieves bathymetry data within a specified bounding box, either from a local NetCDF file or an OpenDAP URL. Allows specifying custom variable names for longitude, latitude, and elevation. Caches to disk if enabled.
Large requests against an OpenDAP source are split into tiles no larger than chunk_size degrees on a side, fetched and cached individually, and stitched back together. This keeps each individual request under server-side response-size limits.
- Parameters:
extent (tuple, optional) – Bounding box (min_lon, max_lon, min_lat, max_lat). Defaults to (-100, -45, 5, 46).
source (str, optional) – Path to a local NetCDF file or OpenDAP URL. Defaults to the provided OpenDAP URL.
lon_var (str, optional) – Name of the longitude variable in the dataset. Defaults to ‘lon’.
lat_var (str, optional) – Name of the latitude variable in the dataset. Defaults to ‘lat’.
elev_var (str, optional) – Name of the elevation variable in the dataset. Defaults to ‘elevation’.
use_cache (bool, optional) – Whether to cache OpenDAP requests locally. Defaults to True.
chunk_size (float, optional) – Maximum tile width/height in degrees for each OpenDAP request. Set to None to disable chunking and request the full extent in one shot. Defaults to 10.
- Returns:
Dataset containing the requested bathymetry data.
- Return type:
xarray.Dataset
- cool_maps.download.get_glider_bathymetry(deployment: str, time_start: str | None = None, time_end: str | None = None) DataFrame | None[source]
Function to select bathymetry associated with a glider deployment. This function pulls glider-measured bathymetry data from slocum-data.marine.rutgers.edu and removes spikes.
- Parameters:
deployment (str) – Name of deployment to get bathymetry for (glider-yyyymmddTHHMM).
time_start (str, optional) – Start time. Defaults to None/beginning of deployment.
time_end (str, optional) – End time. Defaults to None/end of deployment.
- Returns:
pandas DataFrame containing bathymetry data, or None if failed.
- Return type:
pandas.DataFrame
- cool_maps.download.get_totals_from_erddap(time_start: str, time_end: str | None = None, extent: Tuple[float, float, float, float] | None = None, server: str = 'https://hfr.marine.rutgers.edu/erddap/', dataset_id: str = '5MHz_6km_realtime-agg_archive_v00') Dataset[source]
Function to select HFR data within a bounding box. This function pulls HFR data from hfr.marine.rutgers.edu
- Parameters:
time_start (str) – Start time to read.
time_end (str, optional) – End time to read. Defaults to None/latest.
extent (tuple, optional) – Cartopy bounding box. Defaults to None.
server (str, optional) – ERDDAP server URL.
dataset_id (str, optional) – ERDDAP dataset ID.
- Returns:
xarray Dataset containing HFR data
- Return type:
xarray.Dataset
cool_maps.plot module
- cool_maps.plot.add_bathymetry(ax, lon, lat, elevation, levels=(-1000,), method='contour', legend_scale=None, fontsize=13, zorder=5, transform=None, transform_first=False, colors=None, engine=None)[source]
Plot bathymetry lines on map
- Parameters:
ax (matplotlib.axes.Axes or mpl_toolkits.basemap.Basemap) – target axes or basemap
lon (array-like) – Longitudes of bathymetry
lat (array-like) – Latitudes of bathymetry
elevation (array-like) – Elevation of bathymetry
levels (tuple, optional) – Number/positions of contour lines. Defaults to (-1000).
method (string) – Method for plotting bathymetry. Defaults to contour. Options: - contour: standard black contour at :levels: - shadedcontour: contours in shades of gray varying with depth - banded: discrete depth bands at :levels: filled with :colors: (deepest to shallowest), plus the usual black isobath lines/labels and a color-swatch legend - blues: pcolormesh using Blues colormap; excludes land and ignores :levels: - blues_log: pcolormesh of log-transformed bathymetry using Blues colormap; excludes land and ignores :levels: - topo: pcolormesh using cmocean topo colormap; excludes land and ignores :levels: - topo_log: pcolormesh of log-transformed bathymetry using cmocean topo colormap; excludes land and ignores :levels: - topofull: pcolormesh using cmocean topo colormap; includes land and ignores :levels: - topofull_log: pcolormesh of log-transformed altitude/bathymetry using cmocean topo colormap; includes land and ignores :levels:
legend_scale (string, optional) – Measurement system to use for legend. Supported for shadedcontour and banded. Defaults to “both” for shadedcontour and “metric” for banded. - metric: meters - imperial: fathoms - both: meters and fathoms - off: no legend
fontsize (int, optional) – Font size for legend
zorder (int, optional) – Drawing order. Defaults to 5.
transform – Cartopy transform/CRS or supported projection string for lon/lat input (cartopy engine only)
transform_first (bool, optional) – Transform points before contouring (cartopy engine only)
colors (list, optional) – Fill colors for method=”banded”, ordered from deepest to shallowest. Must have exactly len(levels) + 1 entries: one for the water deeper than the shallowest level, one for each band between consecutive levels, and one for the band up to 0. If omitted, defaults to [“cornflowerblue”, cfeature.COLORS[“water”], “lightsteelblue”] when levels produces exactly 3 bands (e.g. the default levels=(-1000, -100)); otherwise required.
engine (str, optional) – Override active mapping engine (“cartopy” or “basemap”)
- Returns:
plotted bathymetry handle
- Return type:
object
- cool_maps.plot.add_colorbar(ax, h, label=None, fontsize=12, pad=0.02, **kwargs)[source]
Add a colorbar to the figure attached to the given axes.
- Parameters:
ax (matplotlib.axes) – The axes to attach the colorbar to.
h – Mappable object (e.g. from pcolormesh, contourf, scatter).
label (str, optional) – Colorbar label. Defaults to None.
fontsize (int, optional) – Font size for the label and tick labels. Defaults to 12.
pad (float, optional) – Fraction of original axes between colorbar and axes. Defaults to 0.02.
**kwargs – Additional keyword arguments passed to plt.colorbar().
- Returns:
matplotlib.colorbar.Colorbar
- cool_maps.plot.add_currents(ax, ds, coarsen=2, scale=90, headwidth=2.75, headlength=2.75, headaxislength=2.5, engine=None)[source]
Plot currents on map
- Parameters:
ax (matplotlib.axes) – matplotlib axes
ds (xarray.Dataset) – dataset containing lon, lat, u, and v data.
coarsen (int, optional) – Downsampling factor applied to lon/lat dimensions. Defaults to 2.
scale (float, optional) – Number of data units per arrow length unit. Defaults to 90.
headwidth (float, optional) – Head width as multiple of shaft width. Defaults to 2.75.
headlength (float, optional) – Head length as multiple of shaft width. Defaults to 2.75.
headaxislength (float, optional) – Head length at shaft intersection. Defaults to 2.5.
engine (str, optional) – Override active mapping engine (“cartopy” or “basemap”)
- Returns:
Quiver
- Return type:
object
- cool_maps.plot.add_double_temp_colorbar(ax, h, vmin, vmax, anomaly=False, fontsize=13)[source]
Add colorbar with Celsius and Fahrenheit units https://pythonmatplotlibtips.blogspot.com/2019/07/draw-two-axis-to-one-colorbar.html
- Parameters:
ax (matplotlib.axes) – matplotlib axes
h (matplotlib object handle to match colorbar to)
vmin (float) – minimum value of colorbar (should match vmin of object colorbar is mapped to)
vmax (float) – maximum value of colorbar (should match vmax of object colorbar is mapped to)
anomaly (bool) – whether product is an anomaly
fontsize (int, optional) – font size for tick labels
- Returns:
Colorbar axes: Twin axes for colorbar
- Return type:
object
- cool_maps.plot.add_features(ax, edgecolor='black', landcolor='tan', oceancolor=None, coast='full', zorder=0, engine=None)[source]
Automatically add the following features to make the map nicer looking.
- Parameters:
ax (matplotlib.Axis) – matplotlib axis
edgecolor (str, optional) – Color of edges of polygons. Defaults to “black”.
landcolor (str, optional) – Color of land. Defaults to “tan”.
oceancolor (str, optional) – Color of ocean. Defaults to cartopy default water color
coast (str, optional) – Coastline resolution.
zorder (int, optional) – Drawing order.
engine (str, optional) – Override active mapping engine
- cool_maps.plot.add_glider_bathymetry(ax, deployment, time_start=None, time_end=None, color='black')[source]
Download and plot bathymetry measured by glider during a given deployment
- Parameters:
ax (matplotlib.axes) – matplotlib axes
deployment (str) – name of deployment to grab and plot bathymetry for
time_start (str, optional) – Start time. Defaults to None/beginning of deployment
time_end (str, optional) – End time. Defaults to None/end of deployment
color (str, optional) – name of color to plot bathymetry
- Returns:
Patch
- Return type:
object
- cool_maps.plot.add_legend(ax, *args, **kwargs)[source]
Add a legend to ax without discarding any legend already there.
Matplotlib keeps only one “current” legend per axes – a second ax.legend() call normally replaces the first outright. This is common with cool_maps maps: create() with bathymetry_method=”shadedcontour”/”banded” already builds one legend, and you often want a second one for your own overlaid data (markers, tracks, etc.). This function preserves whatever legend is already on ax (re-registering it as a plain artist, with clipping turned back off since ax.add_artist() would otherwise clip it to the axes’ rectangular patch – fatal for legends positioned outside the axes, like cool_maps’ own bathymetry legends) before creating the new one, so you can call this repeatedly to build up any number of legends on the same axes.
- Parameters:
ax (matplotlib.axes) – Axes to add the legend to.
*args – Passed through to ax.legend().
**kwargs – Passed through to ax.legend().
- Returns:
the newly created legend.
- Return type:
matplotlib.legend.Legend
- cool_maps.plot.add_marker(ax, lon, lat, engine=None, **scatter_kwargs)[source]
Plot one or more markers at geographic coordinates, handling engine differences automatically.
- Parameters:
ax (matplotlib.axes) – Axes created by cool_maps.create().
lon (float or array-like) – Longitude(s) of marker(s).
lat (float or array-like) – Latitude(s) of marker(s).
engine (str, optional) – Override active mapping engine (“cartopy” or “basemap”).
**scatter_kwargs – Keyword arguments passed to ax.scatter() or basemap.scatter(). Common: marker, color/c, s (size), zorder, label.
- Returns:
scatter handle
- Return type:
PathCollection
- cool_maps.plot.add_ticks(ax, extent, proj=None, fontsize=13, label_left=True, label_right=False, label_bottom=True, label_top=False, gridlines=False, decimal_degrees=False, whole_degree_majors=True, engine=None)[source]
Calculate and add nicely formatted ticks to your map
- Parameters:
ax (matplotlib.Axis) – matplotlib Axis
extent (tuple or list) – extent (x0, x1, y0, y1) of the map.
proj (cartopy CRS/str, optional) – projection for ticks (cartopy engine only).
fontsize (int, optional) – Font size of tick labels. Defaults to 13.
gridlines (bool, optional) – Add gridlines to map. Defaults to False.
decimal_degrees (bool, optional) – Label axes with decimal degrees. Defaults to False.
whole_degree_majors (bool, optional) – keep major ticks on whole degrees even for small extents (span <= 3 degrees). Defaults to True. Set to False to allow major ticks at 15’/30’ increments for spans <= 3 degrees, matching pre-1.x behavior.
engine (str, optional) – Override active mapping engine
- cool_maps.plot.available_engines()[source]
Return the mapping engines that are currently importable.
- cool_maps.plot.create(extent, proj=None, data_proj=None, padding=0.25, features=True, edgecolor='black', landcolor='tan', oceancolor=None, coast='full', ticks=True, gridlines=False, bathymetry=False, isobaths=(-1000, -100), bathymetry_method='contour', bathymetry_colors=None, bathymetry_legend_scale=None, bathymetry_file=None, xlabel=None, ylabel=None, tick_label_left=True, tick_label_right=False, tick_label_bottom=True, tick_label_top=False, decimal_degrees=False, whole_degree_majors=True, labelsize=14, ax=None, figsize=(11, 8), zorder=0, engine=None, basemap_kwargs=None, title=None, titlesize=14)[source]
Create a map within a certain extent using the selected mapping engine.
The returned axis is instrumented so that ax.scatter/plot/contour/contourf/pcolormesh/quiver/fill accept plain lon/lat data under either engine without passing transform=/latlon= yourself, and so that downstream cool_maps calls (add_features, add_bathymetry, …) infer the engine from ax automatically.
- Parameters:
extent (tuple or list) – Extent (x0, x1, y0, y1) of the map in geographic coordinates.
proj (optional) – Projection spec. Accepts Cartopy CRS objects, supported projection strings, or Basemap kwargs.
data_proj (optional) – Data CRS when using cartopy. Accepts Cartopy CRS or supported projection strings.
padding (float or tuple/list of 2 floats, optional) – Degrees to expand the extent outward on each side so ticks/data don’t land right on the map edge. A single number pads longitude and latitude equally; a 2-item sequence is (lon_padding, lat_padding). Defaults to 0.25. Set to 0 to use extent exactly as given.
features (bool, optional) – Add preferred map settings: colors, rivers, lakes, etc. Defaults to True.
edgecolor (str, optional) – Color of edges of polygons. Defaults to “black”.
landcolor (str, optional) – Color of land. Defaults to “tan”.
oceancolor (str, optional) – Color of the ocean. Defaults to engine default.
coast (str, optional) – Coastline resolution.
ticks (bool, optional) – Calculate appropriately spaced ticks. Defaults to True.
gridlines (bool, optional) – Add gridlines. Defaults to False.
bathymetry (bool or tuple, optional) – Download and plot bathymetry on map. Defaults to False.
isobaths (tuple or list, optional) – Elevation at which to create bathymetric contour lines.
bathymetry_method (str, optional) – Method for plotting bathymetry.
bathymetry_colors (list, optional) – Fill colors, deepest to shallowest, when bathymetry_method=”banded” (see add_bathymetry’s colors argument, including its default for the 3-band case). Ignored for other methods.
bathymetry_legend_scale (str, optional) – See add_bathymetry’s legend_scale argument, including its per-method defaults (“both” for shadedcontour, “metric” for banded).
bathymetry_file (str or None) – GMRT file to use for bathymetry, None to use ERDDAP.
xlabel (str, optional) – X Axis Label. Defaults to None.
ylabel (str, optional) – Y Axis Label. Defaults to None.
tick_label_left/right/bottom/top (bool, optional) – Control tick labels on each side.
decimal_degrees (bool, optional) – Label axes with decimal degrees instead of DMS.
whole_degree_majors (bool, optional) – keep major ticks on whole degrees even for small extents (span <= 3 degrees). Defaults to True. Set to False to allow major ticks at 15’/30’ increments for spans <= 3 degrees, matching pre-1.x behavior.
labelsize (int, optional) – Font size for axis labels. Defaults to 14.
ax (matplotlib.Axis, optional) – Matplotlib axis to use. Created if None.
figsize (tuple, optional) – Figure size if creating a new figure. Defaults to (11, 8).
zorder (int, optional) – Base zorder for artists.
engine (str, optional) – Override active mapping engine (“cartopy” or “basemap”).
basemap_kwargs (dict, optional) – Additional kwargs passed to Basemap when using the basemap engine.
title (str, optional) – Title for the map axes. Defaults to None.
titlesize (int, optional) – Font size for the title. Defaults to 14.
- Returns:
matplotlib figure (if created) axis: matplotlib axis
- Return type:
figure
- cool_maps.plot.export_fig(path, fname, dpi=150, script=None)[source]
Save figure with minimal whitespace. Include script to print the script that created the plot for future ref.
- Parameters:
path (str or Path) – Path to which you want to export figure
fname (str) – Filename you want to export the figure as
dpi (int, optional) – Dots per inch. Defaults to 150.
script (str, optional) – Print name of script on plot. Defaults to None.
- cool_maps.plot.load_fig(figfile)[source]
Load pickled figure
- Parameters:
figdir (path) – Full file path to pickled figure
Note
Axes produced by create() carry instance-bound escape-hatch methods (see _bind_escape_hatch_methods) and, for the basemap engine, a live Basemap object attached as an attribute; neither generally survives a pickle round-trip (bound closures aren’t stdlib-picklable, and Basemap objects have known pyproj/GEOS pickling limitations). Axes reloaded via this function should be treated as plain matplotlib axes, not as re-instrumented cool_maps axes.
- Returns:
matplotlib figure
- Return type:
object
- cool_maps.plot.save_fig(fig, figdir, figname)[source]
Save figure as pickle file
- Parameters:
fig (matplotlib.Figure) – matplotlib figure
figdir (path) – Path to save pickled figure to
figname (str) – Filename to save pickled figure as
Note
See load_fig() – engine-specific instrumentation on the figure’s axes (escape-hatch methods, attached Basemap objects) is not guaranteed to survive pickling.