Graphics module

Graphics module for environmental data visualization.

This module provides comprehensive plotting and visualization tools for environmental data, including time series, spatial data, statistical distributions, and regime analysis.

Submodules:

temporal: Core plotting functions for time series and statistical analysis spatial: Spatial data visualization and mapping processes: Process-specific visualizations joint: Joint and conditional distribution plots spatiotemporal: Spatiotemporal covariance plots utils: Utility functions for plot handling

environmentaltools.graphics.anisotropic_spatiotemporal_covariance(covdist, covdistd, covdistt, empcovang, slag, type)[source]

Plot anisotropic spatiotemporal covariance as polar or 3D visualization.

Displays directional (angular) spatiotemporal covariance patterns to identify anisotropy in the spatial correlation structure.

Parameters:
  • covdist (numpy.ndarray) – Spatial distance values for covariance.

  • covdistd (numpy.ndarray) – Angular direction values (degrees) for covariance.

  • covdistt (numpy.ndarray) – Temporal distances for each covariance slice.

  • empcovang (numpy.ndarray) – Empirical angular covariance values (shape: [n_distances, n_angles, n_times]).

  • slag (float) – Spatial lag distance for scaling.

  • type (tuple) – Two-element tuple specifying visualization: - type[0]: “polar” for polar plots, “3d” for 3D surface plots - type[1]: “variogram” for variogram display, other for covariance

Returns:

Displays the plots.

Return type:

None

Note

Angular values are extended by 360° to create continuous polar plots. For variogram mode, displays gamma(h) = c(0) - c(h).

environmentaltools.graphics.annotate_heatmap(im, data=None, valfmt='{x:.2f}', textcolors=['black', 'white'], threshold=None, **textkw)[source]

A function to annotate a heatmap.

Parameters:
  • im – The AxesImage to be labeled.

  • data – Data used to annotate. If None, the image’s data is used. Optional.

  • valfmt – The format of the annotations inside the heatmap. This should either use the string format method, e.g. “$ {x:.2f}”, or be a matplotlib.ticker.Formatter. Optional.

  • textcolors – A list or array of two color specifications. The first is used for values below a threshold, the second for those above. Optional.

  • threshold – Value in data units according to which the colors from textcolors are applied. If None (the default) uses the middle of the colormap as separation. Optional.

  • **kwargs – All other arguments are forwarded to each call to text used to create the text labels.

environmentaltools.graphics.annual_maxima_analysis(boot, orig, ci, tr, peaks, npeaks, eventanu, func, flabel='H$_{m0}$ (m)', tr_plot=100)[source]

Plot annual maxima extreme value analysis with bootstrap results.

Generates a comprehensive visualization including parameter distributions, return period estimates with confidence intervals, and goodness-of-fit assessment for extreme value distributions.

Parameters:
  • boot (tuple) – Bootstrap results tuple (boot_params, boot_alternative). boot_params: Array of bootstrap parameter estimates (n_boot x n_params). boot_alternative: Optional alternative distribution bootstrap results.

  • orig (tuple) – Original fitted parameters (orig_params, orig_alternative).

  • ci (tuple) – Confidence intervals (ci_params, ci_alternative). Format: [lower_bounds, upper_bounds].

  • tr (array-like) – Return periods for evaluation.

  • peaks (array-like) – Peak values extracted from the time series.

  • npeaks (array-like) – Empirical frequencies for plotting positions.

  • eventanu (array-like) – Annual event values.

  • func (str) – Distribution function name (‘genpareto’, ‘genextreme’, etc.).

  • flabel (str, optional) – Label for the variable with LaTeX formatting. Defaults to r”H$_{m0}$ (m)”.

  • tr_plot (int, optional) – Specific return period to highlight in histogram. Defaults to 100 years.

Returns:

Displays the plot.

Return type:

None

Note

The function displays parameter stability through histograms and evaluates model fit using return period curves with confidence bands.

environmentaltools.graphics.bivariate_ensemble_pdf(df_sim: DataFrame, df_obs: dict, varp: list, file_name: str = None)[source]

Plot ensemble of bivariate PDFs comparing simulation with multiple observations.

Displays a grid of contour plots showing the bivariate probability density function for a simulation and multiple observational datasets.

Parameters:
  • df_sim (pd.DataFrame) – Simulated time series data.

  • df_obs (dict) – Dictionary where each key contains an observed time series DataFrame. Each will be plotted in a separate subplot.

  • varp (list) – List of two variable names [var1, var2] to plot.

  • file_name (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

Array of axes with the plots.

Return type:

matplotlib.axes.Axes

Note

Creates 3x3 grid with simulation in first subplot and observations following.

environmentaltools.graphics.bivariate_pdf(df_sim: DataFrame, df_obs: DataFrame, variables: list, bins: int = None, levels: list = None, ax=None, file_name: str = None, logx: str = False, logy: str = False, contour: bool = False)[source]

Plot bivariate PDF comparison between observed and simulated data.

Creates side-by-side contour or image plots of the bivariate probability density functions for visual model validation.

Parameters:
  • df_sim (pd.DataFrame) – Simulated time series data.

  • df_obs (pd.DataFrame) – Observed time series data.

  • variables (list) – List of two variable names [var1, var2] to plot.

  • bins (int or list, optional) – Number of bins for histogram. If None, uses [25, 25]. Defaults to None.

  • levels (list, optional) – Contour levels. If None, auto-computed. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axes for the plot. Creates new if None. Defaults to None.

  • file_name (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

  • logx (bool) – If True, applies log transform to first variable. Defaults to False.

  • logy (bool) – If True, applies log transform to second variable. Defaults to False.

  • contour (bool) – If True, uses contour plot instead of image. Defaults to False.

Returns:

Array of axes with the plots.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.boxplot(data: DataFrame, variable: str, ax=None, file_name: str = None)[source]

Draw monthly box plot of variable.

Creates box plots showing the distribution of a variable across calendar months.

Parameters:
  • data (pd.DataFrame) – Time series with datetime index.

  • variable (str) – Name of the variable column to plot.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • file_name (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.cadency(data, label='', ax=None, legend=False, fname=None)[source]

Plot temporal differences (cadency) of time series.

Displays the time intervals between consecutive data points to identify gaps or irregular sampling in the time series.

Parameters:
  • data (pd.DataFrame) – Time series with datetime index.

  • label (str) – Label for the plotted line. Defaults to “”.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • legend (bool) – If True, displays legend. Defaults to False.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.calc_extent(lon, lat, dist)[source]

Calculate map extent from center point and distance.

Computes the bounding box coordinates for a map centered at given lon/lat with specified distance to edges using geodesic calculations.

Parameters:
  • lon (float) – Center longitude in degrees.

  • lat (float) – Center latitude in degrees.

  • dist (float) – Distance from center to edge in meters.

Returns:

Map extent as [lon_min, lon_max, lat_min, lat_max].

Return type:

list

environmentaltools.graphics.cdf(data: DataFrame, var: str, ax=None, file_name: str = None, seaborn: bool = False, legend: str = False, label: str = None)[source]

Plot cumulative distribution function (CDF) of data.

Displays the empirical CDF either using custom ECDF calculation or seaborn’s distribution plot with cumulative option.

Parameters:
  • data (pd.DataFrame) – Time series data.

  • var (str) – Name of the variable column to plot.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • file_name (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

  • seaborn (bool) – If True, uses seaborn.distplot for CDF visualization. Defaults to False.

  • legend (bool) – If True, displays legend. Defaults to False.

  • label (str, optional) – Custom label for the plot. If None, uses variable name with units. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.cme_calibration(cme_coastlines: dict, satellite_coastlines: dict, polygons: dict, nDate2date: dict, selected: str, ax=None, file_name: str = None, title: str = None)[source]

Draw the calibration plot of Coastal Modelling Environment

Parameters:
  • cme_coastlines (dict) – The cme coastlines for every date

  • satellite_coastlines (dict) – The satellite coastlines for every date

  • polygons (dict) – The polygons created between cme and satellite coastlines

  • nDate2date (dict) – conversion beetween dates and number of coastlines outputs

  • selected (str) – the selected test

  • ax (matplotlib.ax, optional) – An ax where plot the new figure. Defaults to None.

  • file_name (str, optional) – The name to be saved. Defaults to None.

  • title (str, optional) – Title name. Defaults to None.

environmentaltools.graphics.coastline_ci(coast_lines, title=None, fname=None, ax=None)[source]

Plot coastline position evolution with confidence intervals.

Displays temporal evolution of coastline position showing mean, initial, final positions, and envelope (min-max range) over time.

Parameters:
  • coast_lines (pd.DataFrame) – DataFrame containing coastline positions with columns: - ‘x’: Along-shore coordinate - ‘mean’: Mean coastline position - ‘min’: Minimum (most seaward) position - ‘max’: Maximum (most landward) position - ‘ini’: Initial coastline position - ‘end’: Final coastline position

  • title (str, optional) – Plot title. Defaults to None.

  • fname (str, optional) – Filename to save the figure. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. Defaults to None.

Returns:

The axes object with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.corr(data: DataFrame, lags: int = 24, ax=None, file_name: str = None)[source]

Plot autocorrelation function of time series.

Displays the normalized autocorrelation as a function of time lag to identify temporal dependencies and periodicity.

Parameters:
  • data (pd.DataFrame) – Time series data (single column or Series).

  • lags (int) – Maximum lag time in hours. Defaults to 24.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • file_name (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.covariance_comparison(covDistanceS, covDistanceT, covEmpST, tLag, res, family, type)[source]

Plot empirical and theoretical spatiotemporal covariance comparison.

Visualizes the fit between empirical spatiotemporal covariance and the theoretical covariance model, displaying both as 3D surfaces or 2D contours.

Parameters:
  • covDistanceS (numpy.ndarray) – Spatial distance grid for covariance evaluation.

  • covDistanceT (numpy.ndarray) – Temporal distance grid for covariance evaluation.

  • covEmpST (numpy.ndarray) – Empirical spatiotemporal covariance values.

  • tLag (array-like) – Temporal lag values.

  • res (scipy.optimize.OptimizeResult) – Optimization result containing fitted covariance parameters in res.x.

  • family (str) – Covariance family name for theoretical model.

  • type (str) – Plot type - “3d” for 3D surface plot, other for 2D contour plot.

Returns:

Displays the plots.

Return type:

None

Note

For “3d” type, displays wireframe theoretical covariance with empirical surface overlay, plus contour plot of residuals. For 2D type, shows side-by-side contour comparisons of theoretical and empirical covariances.

environmentaltools.graphics.crosscorr(xy, xys, variable, lags=48, fname=None)[source]

Plot cross-correlation between observed and simulated variables.

Displays the cross-correlation function comparing two time series to assess temporal relationships and model performance.

Parameters:
  • xy (tuple) – Tuple of two arrays (x, y) for observed data.

  • xys (tuple) – Tuple of two arrays (x, y) for simulated data.

  • variable (str) – Name of variable for plot labeling.

  • lags (int) – Maximum lag time in hours. Defaults to 48.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

Note

Cross-correlation is normalized by standard deviations and means.

environmentaltools.graphics.dimensionless_fits(event, df, ajuste, fun, ejes)[source]

Plot dimensionless scatter plots for wave parameters.

Generates scatter plots for fitting Hs and Tp, limiting values according to fully developed sea conditions using dimensionless wave parameters.

Parameters:
  • event (list) – List of values exceeding each threshold (length equals number of thresholds).

  • df (pd.DataFrame) – DataFrame with all time series including ‘hs’, ‘tp’, ‘vv’.

  • ajuste (dict) – Dictionary with fit values (x, upper_ci, mean, lower_ci) for each threshold. Keys include: - ‘x’+variable+function: x-values for the fit - ‘y’+variable+function: mean fit values - ‘ysup’+variable+function: upper confidence interval - ‘yinf’+variable+function: lower confidence interval - ‘hs_aux’, ‘t_aux’: Auxiliary curve for fully developed conditions

  • fun – Function identifier used for fitting.

  • ejes (list) – Axis labels [x-label, y-label-tp, y-label-vv].

Returns:

Displays the plots.

Return type:

None

Note

Uses dimensionless parameters: Hs*g/(1.1*Vv²) and Tp*g/(1.1*Vv). The plot includes the theoretical curve for fully developed sea.

environmentaltools.graphics.dscatter(x, y, *varargin)[source]

Create density scatter plot with smoothed 2D histogram coloring.

Generates a scatter plot where point colors represent local density, computed using 2D histogram binning and smoothing.

Parameters:
  • x (array-like) – X-coordinates of data points.

  • y (array-like) – Y-coordinates of data points.

  • *varargin – Additional variable arguments (currently unused).

Note

This function uses a smoothing parameter lambda_=20 and limits bins to 200.

environmentaltools.graphics.enable_latex_rendering()[source]

Enable LaTeX rendering for matplotlib plots.

environmentaltools.graphics.ensemble_acorr(lags: list, lagsim: list, corr_: list, corrsim_: list, vars_: list, ax=None, file_name: str = None)[source]

Plots the correlation bands of RCMs and a given simulation

Parameters:
  • lags (list) – lags of RCM data from correlation functions (x-axis)

  • lagsim (list) – lags of simulation data from correlation functions (x-axis)

  • corr (list) – correlation of RCM data

  • corrsim (list) – correlation of simulations

  • vars (list) – variables to be plotted

  • ax ([matplotlib.ax], optional) – Axis where to plot the figure. Defaults to None.

  • file_name (str, optional) – A file name for saving the figure. Defaults to None.

Returns:

the figure

Return type:

ax.matplotlib

environmentaltools.graphics.era5_time_series_plot(data, variable_name: str = 'swh', variable_label: str = 'Significant Wave Height', variable_units: str = 'm', start_year: int = None, end_year: int = None, output_path: str = None, file_name: str = None) str[source]

Create a comprehensive time series plot of ERA5 data.

Creates a multi-panel visualization including: - Complete time series - Monthly statistics (mean, IQR, max) - Distribution histogram with mean and 95th percentile

Parameters:
  • data (pd.DataFrame) – Data with datetime index and variable column.

  • variable_name (str, optional) – Column name in dataframe. Defaults to ‘swh’.

  • variable_label (str, optional) – Label for plots. Defaults to ‘Significant Wave Height’.

  • variable_units (str, optional) – Units for axis labels. Defaults to ‘m’.

  • start_year (int, optional) – Start year for plot title. If None, extracted from data.

  • end_year (int, optional) – End year for plot title. If None, extracted from data.

  • output_path (str, optional) – Directory to save plot. If None, uses current directory.

  • file_name (str, optional) – Custom filename. If None, auto-generated.

Returns:

Path to the saved plot file.

Return type:

str

Raises:

ValueError – If plot creation fails.

Example

>>> import pandas as pd
>>> from environmentaltools.graphics.spatiotemporal import era5_time_series_plot
>>>
>>> # For wave height
>>> plot_path = era5_time_series_plot(
...     data,
...     variable_name='swh',
...     variable_label='Significant Wave Height',
...     variable_units='m',
...     output_path='./plots'
... )
>>>
>>> # For wind speed
>>> plot_path = era5_time_series_plot(
...     data,
...     variable_name='u10',
...     variable_label='10m U Wind',
...     variable_units='m/s'
... )
environmentaltools.graphics.flood_map(data, coast_line, flood_line, points, flood_polygon, title=None, fname=None, ax=None)[source]

Plot coastal flood inundation map.

Visualizes coastal flooding extent showing the initial coastline, flood boundary, reference points, and calculated inundation area.

Parameters:
  • data (xarray.Dataset or dict) – Background spatial data (typically bathymetry/topography).

  • coast_line (pd.DataFrame or gpd.GeoDataFrame) – Initial coastline geometry with x, y coordinates.

  • flood_line (dict or pd.DataFrame) – Flood extent boundary with ‘x’ and ‘y’ coordinates.

  • points (pd.DataFrame or gpd.GeoDataFrame) – Reference points with x, y coordinates.

  • flood_polygon (gpd.GeoDataFrame) – Polygon geometry of flooded area with ‘area’ attribute.

  • title (str, optional) – Plot title. Defaults to None.

  • fname (str, optional) – Filename to save the figure. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. Defaults to None.

Returns:

The axes object with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.folium_map(data, more=[], fname='folium_map')[source]

Create an interactive Folium web map with spatial data.

Generates an HTML-based interactive map using Folium library, displaying spatial features as line geometries. Coordinates are automatically transformed from UTM to WGS84.

Parameters:
  • data (np.ndarray) – Array of coordinates in UTM format (x, y).

  • more (list, optional) – List of additional GeoJSON-compatible geometries to overlay on the map. Defaults to [].

  • fname (str, optional) – Output HTML filename (without extension). Defaults to “folium_map”.

environmentaltools.graphics.handle_axis(ax, row_plots: int = 1, col_plots: int = 1, dim: int = 2, figsize: tuple = (5, 5), projection=None, kwargs: dict = {})[source]

Create matplotlib axis for figure if needed.

Creates a new matplotlib axis/figure if none provided, supporting 2D, 3D, and projection-based plots with customizable layout.

Parameters:
  • ax (matplotlib.axes.Axes) – Existing axis for the plot, or None to create new.

  • row_plots (int) – Number of subplot rows. Defaults to 1.

  • col_plots (int) – Number of subplot columns. Defaults to 1.

  • dim (int) – Number of dimensions (2 for 2D, 3 for 3D plots). Defaults to 2.

  • figsize (tuple) – Figure size as (width, height) in inches. Defaults to (5, 5).

  • projection – Projection type for the axis (e.g., ‘polar’, CRS objects). Defaults to None.

  • kwargs (dict) – Additional keyword arguments passed to plt.subplots. Defaults to {}.

Returns:

(fig, ax) where fig is the Figure object (or None if ax was provided)

and ax is the Axes object(s). If multiple subplots, ax is flattened array.

Return type:

tuple

environmentaltools.graphics.heatmap(data: ndarray, param: dict, cmap: str = 'bwr_r', type_: str = None, file_name: str = None, ax=None, minmax=False)[source]

Create a heatmap from a numpy array and two lists of labels.

Parameters:
  • data (*) – A 2D array of shape (N, M).

  • param (*) – A list or array of length N with the labels for the rows.

  • type (*) – type of variable to be plotted. B stands for the parameter matrix and Q for the covariance matrix

  • file_name (*) – name of the oputput file

environmentaltools.graphics.image_spoof(self, tile)[source]

Reformat web requests from OSM for cartopy compatibility.

Spoofs the user agent in HTTP requests to OpenStreetMap tile servers, allowing cartopy to download and display map tiles.

Heavily based on code by Joshua Hrisko: https://makersportal.com/blog/2020/4/24/geographic-visualizations-in-python-with-cartopy

Parameters:
  • self – The tile image object (OSM or QuadtreeTiles instance).

  • tile – Tile coordinates tuple.

Returns:

(image, extent, origin) compatible with cartopy.

Return type:

tuple

environmentaltools.graphics.include_Andalusian_coast(path, ax)[source]

Add Andalusian coastline to map plot.

Reads shapefile data and plots the Andalusian coast (two segments) on the provided axes, transforming coordinates from UTM to WGS84.

Parameters:
  • path (str) – Path to the shapefile containing coastline data.

  • ax (matplotlib.axes.Axes) – Axes object to plot the coastline on.

environmentaltools.graphics.include_coastal_Andalusian_cities(ax)[source]

Add labels and markers for coastal Andalusian cities to map.

Plots markers and labels for major coastal cities in Andalusia (Spain) including Malaga, Cadiz, Huelva, Almeria, Ceuta, Melilla, Motril, and Algeciras. Coordinates are automatically transformed from UTM/EPSG to WGS84.

Parameters:

ax (matplotlib.axes.Axes) – Axes object with geographic projection to add city labels to.

environmentaltools.graphics.include_seas(ax)[source]

Add labels for Atlantic Ocean and Mediterranean Sea to map.

Places text labels for major water bodies adjacent to the Andalusian coast. Coordinates are transformed from UTM/EPSG to WGS84.

Parameters:

ax (matplotlib.axes.Axes) – Axes object with geographic projection to add sea labels to.

environmentaltools.graphics.joint_plot(data: DataFrame, varx: str, vary: str, ax=None)[source]

Plot joint probability distribution of two variables.

Creates a joint plot with marginal distributions using seaborn to visualize the bivariate relationship and individual distributions.

Parameters:
  • data (pd.DataFrame) – Time series containing both variables.

  • varx (str) – Name of variable for x-axis.

  • vary (str) – Name of variable for y-axis.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.labels(variable)[source]

Gives the labels and units for plots

Parameters:

variable (*) – name of the variable

Returns:

label with the name of the variable and the units

Return type:

  • units (string)

environmentaltools.graphics.line_ci(ppfs, var_, keys=['mean', 'std'], ax=None, fname=None, title=None)[source]

[summary]

Parameters:
  • ppfs ([type]) – [description]

  • var ([type]) – [description]

  • keys (list, optional) – [description]. Defaults to [‘mean’, ‘std’].

  • ax ([type], optional) – [description]. Defaults to None.

  • fname ([type], optional) – [description]. Defaults to None.

  • title ([type], optional) – [description]. Defaults to None.

environmentaltools.graphics.look_models(data, variable, params, num=10, fname=None)[source]

Plot CDFs of multiple distribution fits for model comparison.

Overlays empirical CDF with theoretical CDFs from top-ranked fitted distributions to visually compare goodness of fit.

Parameters:
  • data (pd.DataFrame) – Time series data.

  • variable (str) – Name of the variable column.

  • params (pd.DataFrame) – DataFrame with fitted distribution parameters containing columns: distribution name, SSE, and parameter values. Should be sorted by fit quality (best first).

  • num (int) – Maximum number of distributions to plot. Defaults to 10.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

Note

Plots up to ‘num’ best-fitting distributions based on sum of squared errors.

environmentaltools.graphics.mda(data, cases, variables, title=None, ax=None, fname=None)[source]

Plots a 3D scatter figure of the MDA cases over the data cloud of points

Parameters:
  • data (*) – time series of the data.

  • cases (*) – mda cases.

  • variables (*) – the name of the variables.

  • title (*) – text for the figure title.

  • ax (*) – axis for the plot or None. Defaults to None.

  • fname (*) – name of the file to save the plot or None to see plots on the screen. Defaults to None.

Returns:

axis for the plot or None

Return type:

  • ax (matplotlib.axis)

environmentaltools.graphics.nonstat_cdf_ensemble(data: DataFrame, variable: str, param: dict = None, models: list = None, daysWindowsLength: int = 14, equal_windows: bool = False, ax=None, log: bool = False, file_name: str = None, label: str = None, legend: bool = True, legend_loc: str = 'right', title: str = None, date_axis: bool = False, pemp: list = None)[source]

Plots the time variation of given percentiles of data and theoretical function if provided

Parameters:
  • data (*) – time series

  • variable (*) – name of the variable to be adjusted

  • param (*) – the parameters of the the theoretical model if they are also plotted.

  • daysWindowsLength (*) – period of windows length for making the non-stationary empirical distribution function. Defaults to 14 days. * equal_windows (bool): use the windows for the ecdf of total data and timestep

  • ax (*) – matplotlib.ax

  • log (*) – logarhitmic scale

  • file_name (*) – name of the file to save the plot or None to see plots on the screen. Defaults to None.

  • label (*) – string with the label

  • legend (*) – plot the legend

  • legend_loc (*) – locate the legend

  • title (*) – draw the title

  • date_axis (*) – create a secondary axis with time

  • pemp (*) – list with percentiles to be plotted

Returns:

axis for the plot or None

Return type:

  • ax (matplotlib.axis)

environmentaltools.graphics.nonstationary_cdf(data: DataFrame, variable: str, param: dict = None, daysWindowsLength: int = 14, equal_windows: bool = False, ax=None, log: bool = False, file_name: str = None, label: str = None, lst='-', legend: bool = True, legend_loc: str = 'right', title: str = None, date_axis: bool = False, pemp: list = None, emp: bool = True)[source]

Plots the time variation of given percentiles of data and theoretical function if provided

Parameters:
  • data (*) – time series

  • variable (*) – name of the variable to be adjusted

  • param (*) – the parameters of the the theoretical model if they are also plotted.

  • daysWindowsLength (*) – period of windows length for making the non-stationary empirical distribution function. Defaults to 14 days.

  • equal_windows (*) – use the windows for the ecdf of total data and timestep

  • ax (*) – matplotlib.ax

  • log (*) – logarhitmic scale

  • file_name (*) – name of the file to save the plot or None to see plots on the screen. Defaults to None.

  • label (*) – string with the label

  • lst (*) – linestyle for theoretical distribution.

  • legend (*) – plot the legend

  • legend_loc (*) – locate the legend

  • title (*) – draw the title

  • date_axis (*) – create a secondary axis with time

  • pemp (*) – list with percentiles to be plotted

  • emp (*) – if True plot the empirical nonst distribution

Returns:

axis for the plot or None

Return type:

  • ax (matplotlib.axis)

environmentaltools.graphics.nonstationary_cdf_ensemble(data: DataFrame, variable: str, ax=None, marker: str = '.', file_name: str = None)[source]

Plots the time variation of given percentiles of data and the theoretical function if provided

Parameters:
  • data (*) – raw time series

  • variable (*) – name of the variable to be adjusted

  • ax (*) – axis for the plot

  • marker (*) – symbol feature of the plot

  • file_name (*) – name of the file to save the plot or None to see plots on the screen. Defaults to None.

Returns:

axis for the plot

Return type:

  • ax (matplotlib.axis)

environmentaltools.graphics.nonstationary_percentiles(data: DataFrame, variable: str, fun: str, pars=None, ax=None, fname=None)[source]

Plot monthly CDFs in normalized space.

Displays cumulative distribution functions for each month in normalized (Gaussian) space to assess seasonal nonstationarity in the distribution.

Parameters:
  • data (pd.DataFrame) – Time series with datetime index.

  • variable (str) – Name of the variable column to analyze.

  • fun (str) – Name of scipy.stats probability distribution (e.g., ‘norm’, ‘lognorm’, ‘genextreme’).

  • pars (tuple, optional) – Distribution parameters. If None, fits parameters to data. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

Note

Each month is represented by a different color. Deviations from the 45° line indicate departures from the annual distribution.

environmentaltools.graphics.nonstationary_qq_plot(data: DataFrame, var_: str, prob_model: str = 'norm', fname=None)[source]

Draw monthly QQ-plots to assess seasonal distribution changes.

Creates a 3x4 grid of QQ-plots, one for each calendar month, to visualize how the distribution varies throughout the year.

Parameters:
  • data (pd.DataFrame) – Time series with datetime index.

  • var (str) – Name of the variable column to analyze.

  • prob_model (str) – Name of scipy.stats probability distribution. Defaults to ‘norm’.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

Displays the plot.

Return type:

None

Note

Each subplot shows data for one calendar month. Deviations from the reference line indicate non-normality for that month.

environmentaltools.graphics.onclick(event)[source]

Handle mouse click events on matplotlib figures.

Prints information about click location (pixel and data coordinates) to console. Useful for interactive data exploration.

Parameters:

event (matplotlib.backend_bases.MouseEvent) – Mouse click event containing click position and button information.

environmentaltools.graphics.osm_image(lons, lats, style='satellite', epsg=None, title=None, ax=None, fname=None)[source]

Create OpenStreetMap background image for spatial visualization.

Generates a map with OpenStreetMap imagery (satellite or street map style) as background. Automatically handles coordinate transformations and scale calculations. Based on code by Mathew Lipson (m.lipson@unsw.edu.au).

Parameters:
  • lons (list or np.ndarray) – Longitude or x-coordinate bounds [min, max]. Format depends on epsg parameter.

  • lats (list or np.ndarray) – Latitude or y-coordinate bounds [min, max]. Format depends on epsg parameter.

  • style (str, optional) – Map style - either “satellite” or “map”. Defaults to “satellite”.

  • epsg (int, optional) – EPSG code of input coordinates. Supported values: - 25829, 25830: UTM zones (automatically transforms to WGS84) - 4326, 4328: WGS84 geodetic (lon/lat) - None: Assumes WGS84 and calculates distance Defaults to None.

  • title (str, optional) – Plot title. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axes object with cartopy projection. Defaults to None.

  • fname (str, optional) – Filename to save the figure. Defaults to None.

Returns:

The axes object with the map.

Return type:

matplotlib.axes.Axes

Note

Be careful with scale and radius combinations. Large scale (>16) with large radius (>1000m) may violate OSM policies (https://operations.osmfoundation.org/policies/tiles/).

Scale guidelines: - 2: Worldwide or continental scales - 4-6: Countries and larger states - 6-10: Smaller states, regions, and cities - 10-12: City boundaries and zip codes - 14+: Roads, blocks, buildings

environmentaltools.graphics.pdf_n_i(df_obs: DataFrame, ns: list, param: dict = None, variable: str = None, nbins: int = 12, wlen: float = 0.038329911019849415, file_name: str = None, stationary: bool = False)[source]

Compute the pdf at n-times

Parameters:
  • df_obs (pd.DataFrame) – input data

  • ns (list) – [description]

  • param (dict) – [description]

  • variable (str, optional) – [description]. Defaults to None.

  • nbins (int) – number of bins. Defaults to 12.

  • wlen (float) – length of the moving windows in days. Defautls 14/365.25

  • file_name (str, optional) – [description]. Defaults to None.

Returns:

the figure

Return type:

matplotlib.ax

environmentaltools.graphics.peaks_over_threshold(event, df, umb)[source]

Plot pairwise scatter plots of variables with peaks over threshold.

Displays two-by-two scatter plots of variables with annual extreme events and values exceeding specified thresholds highlighted.

Parameters:
  • event (pd.DataFrame) – DataFrame with annual peaks of the main variable and values of accompanying variables.

  • df (pd.DataFrame) – DataFrame with all data for main and accompanying variables.

  • umb (array-like) – Series of threshold values to plot.

Returns:

Figure containing the scatter plots.

Return type:

matplotlib.figure.Figure

environmentaltools.graphics.plot_2d_plan_view(topobat, isolines, fname)[source]

Plot 2D horizontal plan view with bathymetry contours.

Creates a plan view visualization of topography/bathymetry with labeled contour lines, typically used for coastal and marine engineering applications.

Parameters:
  • topobat (pd.DataFrame) – DataFrame containing ‘x’, ‘y’ (UTM coordinates) and ‘z’ (elevation/depth) columns.

  • isolines (list or np.ndarray) – Contour levels to display.

  • fname (str) – Filename to save the figure.

environmentaltools.graphics.plot_ascifiles(data, title=None, fname=None, ax=None)[source]

Plot data from ASCII grid files.

Displays raster data with contour lines, typically used for DEM (Digital Elevation Model) or bathymetry visualization from ASCII format files.

Parameters:
  • data (dict) – Dictionary containing ‘x’, ‘y’, and ‘z’ arrays representing grid coordinates and elevation/depth values.

  • title (str, optional) – Plot title. Defaults to None.

  • fname (str, optional) – Filename to save the figure. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. Defaults to None.

Returns:

The axes object with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.plot_conditional_regime(xpar, xparaux, xlim, ylim, alpha, dist, param, yest, reg, xg, yg, pdfg, ci, x, y, xlab, ylab, yrlab, valmed)[source]

Plot joint regime results from conditional distribution function.

Visualizes the relationship between two variables through conditional probability distributions and regression models with confidence intervals.

Parameters:
  • xpar (array-like) – Primary conditioning parameter values.

  • xparaux (array-like) – Auxiliary conditioning parameter values.

  • xlim (tuple) – X-axis limits (min, max).

  • ylim (tuple) – Y-axis limits (min, max).

  • alpha (float) – Significance level for confidence intervals.

  • dist (str) – Distribution type (‘GEV’, ‘Lognormal’, ‘Normal’, etc.).

  • param (array-like) – Distribution parameters for each regime.

  • yest (array-like) – Estimated response values.

  • reg (int) – Regression type identifier (1=polynomial1, 2=polynomial2, 3=power1, 4=power2).

  • xg (array-like) – Grid x-coordinates for PDF contours.

  • yg (array-like) – Grid y-coordinates for PDF contours.

  • pdfg (array-like) – Probability density function values on grid.

  • ci (array-like) – Confidence interval bounds.

  • x (array-like) – Observed x data points.

  • y (array-like) – Observed y data points.

  • xlab (str) – X-axis label.

  • ylab (str) – Y-axis label.

  • yrlab (str) – Right y-axis label (for marginal distribution).

  • valmed (float) – Median value for reference line.

Returns:

Displays the plot.

Return type:

None

environmentaltools.graphics.plot_copula(copula, ax=None, labels=[], file_name: str = None, log: bool = False)[source]

Plot copula function with contours and parameters.

Generates a 2D visualization of the copula probability density function with contour lines and displays copula parameters.

Parameters:
  • copula – Copula object with CDF and parameter methods.

  • ax (matplotlib.axes.Axes, optional) – Axis to plot on. Creates new figure if None. Defaults to None.

  • labels (list) – List of two strings for x and y axis labels. Defaults to [].

  • file_name (str, optional) – Path to save the plot. If None, displays interactively. Defaults to None.

  • log (bool) – If True, uses logarithmic scale for color mapping. Defaults to False.

Returns:

Displays or saves the plot.

Return type:

None

environmentaltools.graphics.plot_db(xarr, var_, coords=['lon', 'lat'], ind_=0, levels=[0, 1, 2, 5, 10, 40], title=None, ax=None, fname=None)[source]

Plot spatial database field with optional depth contours.

Visualizes a variable from an xarray dataset with filled contours and optional depth contour lines overlaid.

Parameters:
  • xarr (xarray.Dataset) – Dataset containing coordinates and variables.

  • var (str) – Variable name to plot.

  • coords (list, optional) – List of coordinate names [x_coord, y_coord]. Defaults to [‘lon’, ‘lat’].

  • ind (int, optional) – Index for third dimension (e.g., time or vertical level). Defaults to 0.

  • levels (list, optional) – Depth contour levels to display. Defaults to [0, 1, 2, 5, 10, 40].

  • title (str, optional) – Plot title. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. Defaults to None.

  • fname (str, optional) – Filename to save the figure. Defaults to None.

Returns:

The axes object with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.plot_interps(x, y, z, zoff, niveles=array([-50, -48, -46, -44, -42, -40, -38, -36, -34, -32, -30, -28, -26, -24, -22, -20, -18, -16, -14, -12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]), fname=None)[source]

Plot comparison of two bathymetry interpolations.

Creates a side-by-side comparison plot of GEBCO and IGN/MITECO bathymetry data with contour lines.

Parameters:
  • x (np.ndarray) – X-coordinates mesh grid (m).

  • y (np.ndarray) – Y-coordinates mesh grid (m).

  • z (np.ndarray) – IGN/MITECO bathymetry values (m).

  • zoff (np.ndarray) – GEBCO bathymetry values (m).

  • niveles (np.ndarray, optional) – Contour levels. Defaults to np.arange(-50, 20, 2).

  • fname (str, optional) – Filename to save the figure. Defaults to None.

environmentaltools.graphics.plot_mesh(data, levels=[-10, -1, 0, 1, 2, 5, 10, 20, 50, 100], var_='z', title=None, ax=None, fname=None, regular=False, cmap=<matplotlib.colors.LinearSegmentedColormap object>, bar_label='\\textbf{z (m)}', xlabel='\\textbf{x (m)}', ylabel='\\textbf{y (m)}', centercolormap=False, hide_colorbar=False, alpha=1)[source]

Plot mesh data with contours and color mapping.

Visualizes spatial mesh data (regular or triangular) with filled contours, optional contour lines, and customizable color mapping.

Parameters:
  • data (xarray.Dataset or dict) – Dataset containing ‘x’, ‘y’ coordinates and variable data.

  • levels (list, optional) – Contour line levels to display. If None, no contours shown. Defaults to [-10, -1, 0, 1, 2, 5, 10, 20, 50, 100].

  • var (str, optional) – Variable name to plot from data. Defaults to “z”.

  • title (str, optional) – Plot title. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. Defaults to None.

  • fname (str, optional) – Filename to save the figure. Defaults to None.

  • regular (bool, optional) – If True, uses regular grid contouring. If False, uses triangular mesh. Defaults to False.

  • cmap (matplotlib.colors.Colormap, optional) – Colormap for filled contours. Defaults to cmocean.cm.deep_r.

  • bar_label (str, optional) – Colorbar label. Defaults to r” extbf{z (m)}”.

  • xlabel (str, optional) – X-axis label. Defaults to r” extbf{x (m)}”.

  • ylabel (str, optional) – Y-axis label. Defaults to r” extbf{y (m)}”.

  • centercolormap (bool, optional) – If True, centers colormap at zero. Defaults to False.

  • hide_colorbar (bool, optional) – If True, hides the colorbar. Defaults to False.

  • alpha (float, optional) – Transparency of filled contours (0-1). Defaults to 1.

Returns:

The axes object with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.plot_presence_boundary(contours, mean_map, threshold=None, title=None, figsize=(10, 8), cmap='viridis', output_path=None)[source]

Visualize mean presence boundary with contours and background heatmap.

Creates a visualization showing the spatial mean map as a heatmap with overlaid contour lines indicating the presence boundary threshold.

Parameters:
  • contours (list) – List of contour coordinates from mean_presence_boundary function.

  • mean_map (np.ndarray) – 2D array of temporal mean values for each spatial location.

  • threshold (float, optional) – Threshold value used to define presence boundary. If None, uses the mean of mean_map.

  • title (str, optional) – Plot title. If None, uses default title.

  • figsize (tuple, optional) – Figure size as (width, height). Default is (10, 8).

  • cmap (str, optional) – Colormap for the heatmap. Default is ‘viridis’.

  • output_path (str or Path, optional) – Path to save the figure. If None, displays the plot.

Returns:

If output_path is provided, returns the path where figure was saved. Otherwise, displays the plot and returns None.

Return type:

None or str

Examples

>>> from environmentaltools.spatiotemporal import indicators
>>> from environmentaltools.graphics import spatiotemporal
>>> import numpy as np
>>>
>>> # Generate sample data
>>> data_cube = np.random.random((365, 50, 50))
>>> contours, mean_map = indicators.mean_presence_boundary(data_cube, threshold=0.6)
>>>
>>> # Visualize
>>> spatiotemporal.plot_presence_boundary(contours, mean_map, threshold=0.6)
environmentaltools.graphics.plot_preview(data)[source]

Create an interactive preview scatter plot of spatial data.

Displays a scatter plot with color-coded elevation/depth values and enables click event handling for interactive exploration.

Parameters:

data (pd.DataFrame or dict) – Dataset containing ‘x’, ‘y’ coordinates and ‘z’ values (elevation/depth).

environmentaltools.graphics.plot_profiles(x, y, z, idx, nos=array([0, 100, 200, 300, 400, 500, 600, 700, 800, 900]))[source]

Plot spatial profiles and bathymetric cross-sections.

Creates a two-panel plot showing: (1) spatial view with profile lines, and (2) depth profiles along selected transects.

Parameters:
  • x (np.ndarray) – X-coordinates mesh grid (m).

  • y (np.ndarray) – Y-coordinates mesh grid (m).

  • z (np.ndarray) – Bathymetry or elevation values (m).

  • idx (np.ndarray) – Indices indicating the merge/reference location.

  • nos (np.ndarray, optional) – Array of profile line indices to plot. Defaults to np.arange(0, 1000, 100).

environmentaltools.graphics.plot_quiver(db, is_db=True, vars_=['U', 'DirU'], cadency=1, title=None, scale=1, label_='U', ax=None, fname=None)[source]

Plot vector field using quiver arrows (e.g., currents, wind).

Visualizes directional data such as ocean currents or wind fields using arrow plots with magnitude-based coloring. Handles both xarray datasets and regular arrays.

Parameters:
  • db (xarray.Dataset or dict) – Dataset containing velocity magnitude and direction.

  • is_db (bool, optional) – If True, treats input as xarray Dataset. If False, treats as regular numpy arrays. Defaults to True.

  • vars (list, optional) – List of variable names [magnitude, direction]. Direction should be in degrees (oceanographic convention: direction TO). Defaults to [“U”, “DirU”].

  • cadency (int, optional) – Sampling interval for arrows (plots every nth point). Higher values = fewer arrows. Defaults to 1.

  • title (str, optional) – Plot title. Defaults to None.

  • scale (float, optional) – Arrow scale factor. Smaller values = longer arrows. Defaults to 1.

  • label (str, optional) – Label for the colorbar. Defaults to “U”.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. Defaults to None.

  • fname (str, optional) – Filename to save the figure. Defaults to None.

Returns:

The axes object with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.plot_voronoi_diagram(vor, bounding_box, fname=False)[source]

Plot Voronoi diagram with vertices and regions.

Visualizes a Voronoi tessellation showing input points, region vertices, and boundaries within a specified bounding box.

Parameters:
  • vor (scipy.spatial.Voronoi) – Voronoi diagram object with attributes: - filtered_points: Input points used for tessellation - filtered_regions: List of region vertex indices - vertices: Coordinates of Voronoi vertices

  • bounding_box (tuple or list) – Box limits as (xmin, xmax, ymin, ymax).

  • fname (str or bool, optional) – Filename to save the figure. If False, doesn’t save. Defaults to False.

Returns:

(fig, ax) - Figure and axes objects.

Return type:

tuple

environmentaltools.graphics.pot_lmom(info, nvar, file_name: str = None)[source]

Plot Peaks Over Threshold analysis results using L-moments method.

environmentaltools.graphics.pr2flow(df: DataFrame, ax=None, file_name: str = None, title: str = '')[source]

Plot a graph that includes precipitation, infiltration, and base flow

Parameters:
  • df (pd.DataFrame) – raw timeseries

  • ax (matplotlib.axis, optional) – Axis where include the new plot. Defaults to None.

  • file_name ([type], optional) – [description]. Defaults to None.

  • legend (bool, optional) – [description]. Defaults to True.

  • title (str, optional) – Title name.

Returns:

The figure

environmentaltools.graphics.probplot(data, ax=None, fit=True, fname=None)[source]

Plot probability plot using statsmodels.

Creates a probability plot to assess distributional assumptions with optional distribution fit.

Parameters:
  • data (pd.DataFrame or array-like) – Data values to plot.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • fit (bool) – If True, fits a distribution to the data. Defaults to True.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.qq(data, prob_model='norm', marker='.', color='k', line='45', ax=None, label=None, fname=None)[source]

Draw QQ-plot comparing data against theoretical distribution.

Creates a quantile-quantile plot to assess how well data matches a specified probability distribution.

Parameters:
  • data (pd.DataFrame) – Time series data to plot.

  • prob_model (str) – Name of scipy.stats probability distribution. Defaults to ‘norm’.

  • marker (str) – Matplotlib marker style. Defaults to ‘.’.

  • color (str) – Color for data points. Defaults to ‘k’ (black).

  • line (str) – Reference line style (‘45’, ‘s’, ‘r’, ‘q’, or None). Defaults to ‘45’.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • label (str, optional) – Label for the data. Defaults to None.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.qqplot(df1, df2, variable, noperc, ax=None, fname=None, label=None, legend=True, title=None)[source]

[summary]

Parameters:
  • df1 ([type]) – [description]

  • df2 ([type]) – [description]

  • variable ([type]) – [description]

  • noperc ([type]) – [description]

  • ax ([type], optional) – [description]. Defaults to None.

  • fname ([type], optional) – [description]. Defaults to None.

environmentaltools.graphics.scatter(df1, df2, variables, names=['Observed', 'Modeled'], fname=None, ax=None)[source]

Plot scatter comparison between two datasets.

Creates scatter plots comparing corresponding variables between two datasets (e.g., observed vs. modeled values).

Parameters:
  • df1 (pd.DataFrame) – First dataset (typically observed data).

  • df2 (pd.DataFrame) – Second dataset (typically modeled data).

  • variables (list) – List of variable names to plot.

  • names (list) – Labels for [x-axis, y-axis] data sources. Defaults to [“Observed”, “Modeled”].

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

Returns:

List of axes objects for each subplot.

Return type:

list

environmentaltools.graphics.scatter_error_dependencies(df_dt: dict, variables: list, label: str, ax=None, file_name: str = None)[source]

Plot scatter comparison before and after temporal dependency correction.

Displays side-by-side scatter plots showing data before and after removing temporal dependencies to assess the effect of the transformation.

Parameters:
  • df_dt (dict) – Dictionary containing temporal dependency parameters with keys: - ‘data_before’: Original time series DataFrame - ‘data_after’: Decorrelated time series DataFrame

  • variables (list) – List of two variable names to plot [var_x, var_y].

  • label (str) – Title label for the plot.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • file_name (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.seasonalbox(data, variable, fname=None)[source]

Draws a boxplot

Parameters:
  • data (*) – raw time series

  • variable (*) – name of the variable

  • fname (*) – name of the file to save the plot or None to see plots on the screen. Defaults to None.

Returns:

axis for the plot or None

Return type:

  • ax (matplotlib.axis)

environmentaltools.graphics.serie_peaks(df_serie, df_peaks, ylab, nombre)[source]

Plot time series with identified peak values.

Displays the complete time series and overlays the extracted peak events for visual verification of peak detection algorithms.

Parameters:
  • df_serie (pd.DataFrame) – Complete time series data with datetime index.

  • df_peaks (pd.DataFrame) – Subset containing only peak values with datetime index.

  • ylab (str) – Y-axis label describing the variable.

  • nombre (str) – Plot title.

Returns:

Displays the plot.

Return type:

None

environmentaltools.graphics.serie_peaks_umbral(df_serie, df_peaks, ylab, umbral, nombre)[source]

Plot time series with peaks over threshold.

Displays the time series and highlights values exceeding a specified threshold for Peaks Over Threshold (POT) analysis.

Parameters:
  • df_serie (pd.DataFrame) – Complete time series data with datetime index.

  • df_peaks (pd.DataFrame) – Values exceeding the threshold with datetime index.

  • ylab (str) – Y-axis label describing the variable.

  • umbral (float) – Threshold value used for peak extraction.

  • nombre (str) – Plot title.

Returns:

Displays the plot.

Return type:

None

environmentaltools.graphics.show(file_name: str = None, res: int = 600)[source]

Save figure to file or display on screen.

Saves the current matplotlib figure to a file with specified resolution or displays it interactively.

Parameters:
  • file_name (str, optional) – Path to save the plot. If None, displays interactively. If “to_axes”, returns without action. Defaults to None.

  • res (int) – Resolution in DPI for saved figure. Defaults to 600.

Returns:

Either displays the figure or saves it to file.

Return type:

None

environmentaltools.graphics.smooth1D(y, lambda_)[source]

Apply 1D smoothing to data using regularization matrix.

Implements smoothing through matrix operations with penalty terms based on first and second differences.

Parameters:
  • y (array-like) – Input data to smooth (m x n array).

  • lambda (float) – Smoothing parameter controlling penalty strength.

Returns:

Smoothed data with same shape as input.

Return type:

numpy.ndarray

environmentaltools.graphics.soujourn(data, variable, info, case='above', ax=None, fname=None)[source]

Plots the distribution function of soujourn above or below a given threshold

Parameters:
  • data (_type_) – _description_

  • variable (_type_) – _description_

  • info (_type_) – _description_ time_step = “1H” min_duration = 3 inter_time = 3 threshold = threshold interpolation = True

  • ax (_type_, optional) – _description_. Defaults to None.

  • case (str, optional) – _description_. Defaults to “above”.

  • fname (_type_, optional) – _description_. Defaults to None.

Raises:

ValueError – _description_

Returns:

_description_

Return type:

_type_

environmentaltools.graphics.spectra(data, semilog=True, title=None, fname=None, ax=None, xlabel='Periods $T$ (years)', label='LombScargle')[source]

Plot power spectral density from spectral analysis.

Displays the power spectrum with frequency or period on x-axis and power on y-axis, highlighting statistically significant peaks.

Parameters:
  • data (pd.DataFrame) – Spectral data with ‘psd’ column for power values and ‘significant’ boolean column. Index contains frequencies/periods.

  • semilog (bool) – If True, uses semilog y-axis. Defaults to True.

  • title (str, optional) – Plot title. Defaults to None.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • xlabel (str) – X-axis label. Defaults to “Periods $T$ (years)”.

  • label (str) – Legend label for method type (‘LombScargle’, ‘FFT’, etc.). Defaults to ‘LombScargle’.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

environmentaltools.graphics.storm_timeseries(df_sim: DataFrame, df_obs: DataFrame, variables: list, file_name: str = None)[source]

Plots the time series of simulation and observations (from differents RCM) for the choosen variables

Parameters:
  • df_sim (*) – simulated time series

  • df_obs (*) – any key of the dict should be a pd.DataFrame of observed time series

  • variables (*) – name of the variables

  • file_name (*) – name of the file to save the plot or None to see plots on the screen. Defaults to None.

Returns:

axis for the plot or None

Return type:

  • ax (matplotlib.axis)

environmentaltools.graphics.test_normality(data, params, ax=None, fname=None)[source]

Test and visualize data normality with QQ-plot.

Performs normality test on transformed data and displays a probability plot to assess Gaussian distribution fit.

Parameters:
  • data (array-like) – Raw data values to test.

  • params (dict) – Transformation parameters for data normalization.

  • ax (matplotlib.axes.Axes, optional) – Axis for the plot. Creates new if None. Defaults to None.

  • fname (str, optional) – File path to save the plot. If None, displays interactively. Defaults to None.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

Note

Prints chi-squared statistic and p-value from D’Agostino-Pearson test. Null hypothesis: data comes from a normal distribution (α=0.05).

environmentaltools.graphics.threshold_fits(event, df, ajuste, umb, comb, fun, ejes)[source]

Plot pairwise scatter plots with regression fits over threshold.

Displays two-by-two scatter plots with fitted regression curves for values exceeding different thresholds, including confidence intervals.

Parameters:
  • event (list) – List of values exceeding each threshold (length equals number of thresholds).

  • df (pd.DataFrame) – DataFrame containing all time series.

  • ajuste (dict) – Dictionary with fit values (x, upper_ci, mean, lower_ci) for each threshold. Keys follow format: ‘x’+comb+fun+threshold, ‘y’+comb+fun+threshold, ‘ysup’+comb+fun+threshold, ‘yinf’+comb+fun+threshold. For directional variables (dh, dv), includes directional sector keys.

  • umb (array-like) – Threshold values to evaluate.

  • comb (list) – Variable combinations to plot.

  • fun (list) – Function names used for fitting.

  • ejes (list) – Axis labels for each variable.

Returns:

Displays the plots.

Return type:

None

Note

Directional variables (dh, dv) are handled specially with modulo 360 for angular wrapping and may include multiple directional sectors.

environmentaltools.graphics.timeseries(data: DataFrame, variable: str, ax=None, file_name: str = None)[source]

Plots the time series of the variable

Parameters:
  • data (*) – time series

  • variable (*) – variable

  • ax (*) – axis for the plot or None. Defaults to None.

  • file_name (*) – name of the file to save the plot or None to see plots on the screen. Defaults to None.

Returns:

axis for the plot or None

Return type:

  • ax (matplotlib.axis)

environmentaltools.graphics.transport_mode(df: DataFrame, ax=None, file_name: str = None, type_: str = 'hist')[source]

Plot a graph that show the transport mode

Parameters:
  • df (pd.DataFrame) – [description]

  • ax (matplotlib.axis, optional) – An axis where plot the new figure. Defaults to None.

  • file_name (str, optional) – [description]. Defaults to None.

  • type (str, optional) – [description]. Defaults to “hist”.

Returns:

[description]

Return type:

[type]

environmentaltools.graphics.wrose(wd: ndarray, ws: ndarray, legend_title: str = 'Wave rose', fig_title: str = None, var_name: str = 'Wave height (m)', bins: list = [0, 0.25, 0.5, 1.5, 2.5], calm_limit=0, file_name: str = None)[source]

Draws a wind or wave rose

Parameters:
  • wd (*) – time series with the circular variable

  • ws (*) – time series with the linear variable

  • legend_title (*) – set the title of the rose. Defaults to ‘Wave rose’.

  • fig_title (*) – set the title of the figure. Defaults to None.

  • var_name (*) – name of the mean variable. Default ‘Wave height (m)’

  • bins (*) – value of segments for variable

  • file_name (*) – name of the file to save the plot or None to see plots on the screen. Defaults to None.

Returns:

axis for the plot or None

Return type:

  • ax (matplotlib.axis)

The graphics module provides comprehensive visualization tools for environmental data analysis. It builds upon the scientific Python ecosystem, leveraging NumPy [1] for numerical computations, SciPy [2] for statistical analysis, and Matplotlib [3] for creating publication-quality figures.

Core Plotting Functions

Time Series and Basic Plots

enable_latex_rendering()

Enable LaTeX rendering for matplotlib plots.

timeseries(data, variable[, ax, file_name])

Plots the time series of the variable

storm_timeseries(df_sim, df_obs, variables)

Plots the time series of simulation and observations (from differents RCM) for the choosen variables

cadency(data[, label, ax, legend, fname])

Plot temporal differences (cadency) of time series.

boxplot(data, variable[, ax, file_name])

Draw monthly box plot of variable.

seasonalbox(data, variable[, fname])

Draws a boxplot

Statistical Analysis Plots

test_normality(data, params[, ax, fname])

Test and visualize data normality with QQ-plot.

spectra(data[, semilog, title, fname, ax, ...])

Plot power spectral density from spectral analysis.

cdf(data, var[, ax, file_name, seaborn, ...])

Plot cumulative distribution function (CDF) of data.

qq(data[, prob_model, marker, color, line, ...])

Draw QQ-plot comparing data against theoretical distribution.

probplot(data[, ax, fit, fname])

Plot probability plot using statsmodels.

qqplot(df1, df2, variable, noperc[, ax, ...])

[summary]

corr(data[, lags, ax, file_name])

Plot autocorrelation function of time series.

ensemble_acorr(lags, lagsim, corr_, ...[, ...])

Plots the correlation bands of RCMs and a given simulation

crosscorr(xy, xys, variable[, lags, fname])

Plot cross-correlation between observed and simulated variables.

Non-Stationary Analysis

nonstationary_percentiles(data, variable, fun)

Plot monthly CDFs in normalized space.

nonstationary_qq_plot(data, var_[, ...])

Draw monthly QQ-plots to assess seasonal distribution changes.

nonstationary_cdf(data, variable[, param, ...])

Plots the time variation of given percentiles of data and theoretical function if provided

nonstat_cdf_ensemble(data, variable[, ...])

Plots the time variation of given percentiles of data and theoretical function if provided

nonstationary_cdf_ensemble(data, variable[, ...])

Plots the time variation of given percentiles of data and the theoretical function if provided

Multivariate and Joint Distributions

scatter(df1, df2, variables[, names, fname, ax])

Plot scatter comparison between two datasets.

scatter_error_dependencies(df_dt, variables, ...)

Plot scatter comparison before and after temporal dependency correction.

joint_plot(data, varx, vary[, ax])

Plot joint probability distribution of two variables.

bivariate_pdf(df_sim, df_obs, variables[, ...])

Plot bivariate PDF comparison between observed and simulated data.

bivariate_ensemble_pdf(df_sim, df_obs, varp)

Plot ensemble of bivariate PDFs comparing simulation with multiple observations.

plot_copula(copula[, ax, labels, file_name, log])

Plot copula function with contours and parameters.

heatmap(data, param[, cmap, type_, ...])

Create a heatmap from a numpy array and two lists of labels.

annotate_heatmap(im[, data, valfmt, ...])

A function to annotate a heatmap.

Model Analysis and Visualization

look_models(data, variable, params[, num, fname])

Plot CDFs of multiple distribution fits for model comparison.

line_ci(ppfs, var_[, keys, ax, fname, title])

[summary]

pdf_n_i(df_obs, ns[, param, variable, ...])

Compute the pdf at n-times

soujourn(data, variable, info[, case, ax, fname])

Plots the distribution function of soujourn above or below a given threshold

Specialized Plots

mda(data, cases, variables[, title, ax, fname])

Plots a 3D scatter figure of the MDA cases over the data cloud of points

wrose(wd, ws[, legend_title, fig_title, ...])

Draws a wind or wave rose

Spatial Plotting Functions

Interpolation and Mesh Visualization

plot_interps(x, y, z, zoff[, niveles, fname])

Plot comparison of two bathymetry interpolations.

plot_mesh(data[, levels, var_, title, ax, ...])

Plot mesh data with contours and color mapping.

plot_profiles(x, y, z, idx[, nos])

Plot spatial profiles and bathymetric cross-sections.

plot_ascifiles(data[, title, fname, ax])

Plot data from ASCII grid files.

Interactive and Database Plots

onclick(event)

Handle mouse click events on matplotlib figures.

plot_preview(data)

Create an interactive preview scatter plot of spatial data.

plot_db(xarr, var_[, coords, ind_, levels, ...])

Plot spatial database field with optional depth contours.

Mapping and Geographic Visualization

folium_map(data[, more, fname])

Create an interactive Folium web map with spatial data.

flood_map(data, coast_line, flood_line, ...)

Plot coastal flood inundation map.

osm_image(lons, lats[, style, epsg, title, ...])

Create OpenStreetMap background image for spatial visualization.

calc_extent(lon, lat, dist)

Calculate map extent from center point and distance.

image_spoof(self, tile)

Reformat web requests from OSM for cartopy compatibility.

Regional Features

include_Andalusian_coast(path, ax)

Add Andalusian coastline to map plot.

include_coastal_Andalusian_cities(ax)

Add labels and markers for coastal Andalusian cities to map.

include_seas(ax)

Add labels for Atlantic Ocean and Mediterranean Sea to map.

Advanced Spatial Plots

plot_quiver(db[, is_db, vars_, cadency, ...])

Plot vector field using quiver arrows (e.g., currents, wind).

coastline_ci(coast_lines[, title, fname, ax])

Plot coastline position evolution with confidence intervals.

plot_voronoi_diagram(vor, bounding_box[, fname])

Plot Voronoi diagram with vertices and regions.

plot_2d_plan_view(topobat, isolines, fname)

Plot 2D horizontal plan view with bathymetry contours.

Regime Analysis

Extreme Value Analysis

peaks_over_threshold(event, df, umb)

Plot pairwise scatter plots of variables with peaks over threshold.

threshold_fits(event, df, ajuste, umb, comb, ...)

Plot pairwise scatter plots with regression fits over threshold.

dimensionless_fits(event, df, ajuste, fun, ejes)

Plot dimensionless scatter plots for wave parameters.

pot_lmom(info, nvar[, file_name])

Plot Peaks Over Threshold analysis results using L-moments method.

annual_maxima_analysis(boot, orig, ci, tr, ...)

Plot annual maxima extreme value analysis with bootstrap results.

serie_peaks(df_serie, df_peaks, ylab, nombre)

Plot time series with identified peak values.

serie_peaks_umbral(df_serie, df_peaks, ylab, ...)

Plot time series with peaks over threshold.

Process Visualization

pr2flow(df[, ax, file_name, title])

Plot a graph that includes precipitation, infiltration, and base flow

transport_mode(df[, ax, file_name, type_])

Plot a graph that show the transport mode

cme_calibration(cme_coastlines, ...[, ax, ...])

Draw the calibration plot of Coastal Modelling Environment

Joint Distribution Analysis

dscatter(x, y, *varargin)

Create density scatter plot with smoothed 2D histogram coloring.

smooth1D(y, lambda_)

Apply 1D smoothing to data using regularization matrix.

plot_conditional_regime(xpar, xparaux, xlim, ...)

Plot joint regime results from conditional distribution function.

Spatiotemporal Analysis

covariance_comparison(covDistanceS, ...)

Plot empirical and theoretical spatiotemporal covariance comparison.

anisotropic_spatiotemporal_covariance(...)

Plot anisotropic spatiotemporal covariance as polar or 3D visualization.

era5_time_series_plot(data[, variable_name, ...])

Create a comprehensive time series plot of ERA5 data.

plot_presence_boundary(contours, mean_map[, ...])

Visualize mean presence boundary with contours and background heatmap.

Utility Functions

show([file_name, res])

Save figure to file or display on screen.

handle_axis(ax[, row_plots, col_plots, dim, ...])

Create matplotlib axis for figure if needed.

labels(variable)

Gives the labels and units for plots

References