pylag.processing.plot module

PyLag plotting functions

class pylag.processing.plot.ArakawaAPlotter(grid_metrics_file, **kwargs)[source]

Bases: PyLagPlotter

Create PyLag plot objects based on Arakawa A-Grid model outputs

Class to assist in the creation of plots and animations based on Arakawa A-Grid inputs. The mesh is read from the run’s grid metrics file which is passed to PyLagPlotter during class initialisation. stripy is used to create a spherical triangulation from the underlying data.

Parameters

grid_metrics_file (Dataset or str) – This is either the path to a PyLag grid metrics file or a NetCDF Dataset object. If the former, PyLagPlotter will try to instantiate a new Dataset using the supplied file name.

draw_grid(ax, draw_masked_elements=False, linewidth=0.25, edgecolor='k', facecolor='none')[source]

Draw the underlying grid or mesh

Parameters

ax (matplotlib.axes.Axes) – Axes object

Returns

ax – Axes object

Return type

matplotlib.axes.Axes

plot_field(ax, field, preprocess_array=False, update=False, configure=True, add_colour_bar=True, cb_label=None, tick_inc=True, extents=None, draw_coastlines=False, resolution='10m', **kwargs)[source]

Map the supplied field

The field must be defined on either a) the same triangular mesh that is defined in the grid metrics file, or b) on the original structured grid. In the case of (b), preprocess must be set to True. The field array will then be automatically mapped onto the unstructured triangular mesh. Typically, option (a) applies when plotting values saved in the grid metrics file (e.g. h) while option (b) applies when plotting time dependent variables from the original output file (e.g. current speed).

Cartopy is used to create projections on which to plot. Additional plotting options are passed to matplotlib.pyplot.pcolormesh. See the matplotlib documentation for a full list of supported options.

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • field (NumPy NDArray) – The field to plot.

  • preprocess_array (bool, optional) – Flag signifying whether the field variable should be first mapped onto grid nodal coordinates. Default : False.

  • update (bool, optional) – If true, update the existing plot. Specifically, the axes will be checked to see if it contains a PolyCollection object. If found, the associated data array will be updated with the supplied field data. This is faster than drawing a new map.

  • configure (bool, optional) – If true, configure the plot by setting plot extents, drawing coastlines etc. This can be useful when overlaying plots and you only want to incur the cost of configuring the plot once. The default is True, with the expectation that in most circumstances users will draw any underlying field data before overlaying particle tracks. Default : True.

  • add_colour_bar (bool, optional) – If true, draw a colour bar.

  • cb_label (str, optional) – The colour bar label.

  • tick_inc (bool, optional) – Add coordinate axes (i.e. lat/long).

  • extents (1D array, optional) – Four element numpy array giving lon/lat limits (e.g. [-4.56, -3.76, 49.96, 50.44])

  • draw_coastlines (boolean, optional) – Draw coastlines. Default False.

  • resolution (str, optional) – Resolution to use when plotting the coastline. Only used when draw_coastline=True. Default: ‘10m’.

Returns

  • axes (matplotlib.axes.Axes) – Axes object

  • plot (matplotlib.collections.PolyCollection) – The plot object

plot_quiver(ax, u, v, preprocess_arrays=True, configure=True, update=False, tick_inc=True, extents=None, draw_coastlines=False, resolution='10m', **kwargs)[source]

Produce a quiver plot of the supplied velocity field

preprocess_array(field)[source]

Preprocess field array

Fix up the field array by interpreting moving it onto the unstructured grid used by PyLag. The field array must be 2D and ordered [lon, lat]. Checks for this are not performed. To transform the array automatically, use pylag.grid_metrics.sort_axes. If the field array is global, points at the poles are automatically trimmed.

Parameters

field (2D NumPy) – 2D NumPy array defined on a [lon, lat] grid.

class pylag.processing.plot.ArakawaCPlotter(grid_metrics_file, geographic_coords=True, font_size=10, line_width=0.2)[source]

Bases: object

Create PyLag plot objects based on Arakawa C-grid inputs

Class to assist in the creation of plots and animations for PyLag simulations that used input data defined on an Arakawa C-grid. The C-grid mesh is read from the run’s grid metrics file, which must be passed to ArakawaCPlotter during class initialisation.

Specifically, ArakawaCPlotter will work with:

  1. Arakawa C-grid derived data

Parameters
  • grid_metrics_file (Dataset or str) – This is the path to the PyLag grid metrics file or a NetCDF4 dataset object that has been created from the grid metrics file.

  • geographic_coords (boolean, optional) – Boolean specifying whether or not to use cartopy to create a 2D map on top of which the data will be plotted. The default option is True. If False, a simple Cartesian grid is drawn instead.

  • font_size (int, optional) – Font size to use when rendering plot text

  • line_width (float, optional) – Default line width to use when plotting

draw_grid(ax, grid_name, draw_masked_elements=False, zorder=2, **kwargs)[source]

Draw the underlying grid or mesh

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • grid_name (str) – The name of the grid on which the field data is defined

  • draw_masked_elements (bool) – Include masked elements. Default False.

  • zorder (int) – The zorder.

Returns

ax – Axes object

Return type

matplotlib.axes.Axes

plot_field(ax, grid_name, field, update=False, configure=True, add_colour_bar=True, cb_label=None, tick_inc=True, extents=None, draw_coastlines=False, resolution='10m', **kwargs)[source]

Map the supplied field

The field must be defined on the same triangular mesh that is defined in the grid metrics file (either nodes or element centres). Included here to make it possible to overlay particle tracks on different fields (e.g. bathymetry, temperature). If geographic_coords is True, Cartopy will be used to graph the supplied field.

Additional plotting options are passed to matplotlib.pyplot.pcolormesh. See the matplotlib documentation for a full list of supported options.

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • grid_name (str) – The name of the grid on which the field data is defined

  • field (1D NumPy array) – The field to plot.

  • update (bool, optional) – If true, update the existing plot. Specifically, the axes will be checked to see if it contains a PolyCollection object, as generated by tripcolor. If found, the associated data array will be updated with the supplied field data. This is faster than drawing a new map

  • configure (bool, optional) – If true, configure the plot by setting plot extents, drawing coastlines etc. This can be useful when overlaying plots, and you only want to incur the cost of configuring the plot once. The default is True, with the expectation that in most circumstances users will draw any underlying field data before overlaying particle tracks. Default: True.

  • add_colour_bar (bool, optional) – If true, draw a colour bar.

  • cb_label (str, optional) – The colour bar label.

  • tick_inc (bool, optional) – Add coordinate axes (i.e. lat/long).

  • extents (1D array, optional) – Four element numpy array giving lon/lat limits (e.g. [-4.56, -3.76, 49.96, 50.44])

  • draw_coastlines (boolean, optional) – Draw coastlines. Default False.

  • resolution (str, optional) – Resolution to use when plotting the coastline. Only used when draw_coastline=True. Default: ‘10m’.

Returns

  • axes (matplotlib.axes.Axes) – Axes object

  • plot (matplotlib.collections.PolyCollection) – The plot object

plot_lines(ax, x, y, **kwargs)[source]

Plot path lines.

In addition to the listed parameters, the function accepts all keyword arguments taken by the Matplotlib plot command.

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • x (ND array) – Array of x coordinates to plot.

  • y (ND array) – Array of y coordinates to plot.

  • Returns

  • --------

  • axes (matplotlib.axes.Axes) – Axes object

  • line_plot (matplotlib.collections.Line2D) – The plot object

remove_line_plots(line_plots)[source]

Remove line plots

Useful when updating plots for animations.

Parameters

line_plots (list) – List of line plot objects created during call to plot_lines()

scatter(ax, grid_name, x, y, configure=False, zorder=4, extents=None, draw_coastlines=False, resolution='10m', tick_inc=False, **kwargs)[source]

Create a scatter plot using the provided x and y values

If geographic_coords is True, x and y should be geographic (lat, lon) coordinates. If not, x any y should be given as cartesian coordinates.

See Matplotlib’s scatter documentation for a list of additional key word arguments.

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • grid_name (str) – The name of the grid on which the field data is defined

  • x (1D array) – Array of ‘x’ positions. If plotting in geographic coords, these should be longitudes.

  • y (1D array) – Array of ‘y’ positions. If plotting in geographic coords, these should be latitudes.

  • configure (bool, optional) – If true, configure the plot by setting plot extents, drawing coastlines etc. Default: False.

  • draw_coastlines (bool) – Draw coastlines? Only used if geographic_coords is True. Optional.

  • resolution (str, optional) – Resolution to use when plotting the coastline. Only used when draw_coastline=True. Default: ‘10m’.

  • tick_inc (bool) – Draw ticks? Only used if geographic_coords is True. Optional.

Returns

  • ax (matplotlib.axes.Axes) – Axes object

  • scatter_plot (matplotlib.collection.PathCollection) – The scatter plot

set_title(ax, title)[source]

Set the title

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • title (str) – Plot title

class pylag.processing.plot.FVCOMPlotter(grid_metrics_file, **kwargs)[source]

Bases: PyLagPlotter

Create PyLag plot objects based on FVCOM model outputs

Class to assist in the creation of plots and animations based on FVCOM inputs. The mesh is read from the run’s grid metrics file which is passed to PyLagPlotter during class initialisation. It is assumed the mesh can be faithfully reconstructed from the nodal coordinates and simplices using an instance of matplotlib.tri.Triangulation. In turn, this assumes the mesh has been constructed in Cartesian coordinates. Note - this does not preclude plotting in geographic coordinates.

Parameters

grid_metrics_file (Dataset or str) – This is either the path to a PyLag grid metrics file or a NetCDF Dataset object. If the former, PyLagPlotter will try to instantiate a new Dataset using the supplied file name.

draw_grid(ax, draw_masked_elements=False, **kwargs)[source]

Draw the underlying grid or mesh

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • draw_masked_elements (bool) – Include masked elements. Default False.

Returns

ax – Axes object

Return type

matplotlib.axes.Axes

plot_field(ax, field, update=False, configure=True, add_colour_bar=True, cb_label=None, tick_inc=True, extents=None, draw_coastlines=False, resolution='10m', **kwargs)[source]

Map the supplied field

The field must be defined on the same triangular mesh that is defined in the grid metrics file (either nodes or element centres). Included here to make it possible to overlay particle tracks on different fields (e.g. bathymetry, temperature). If geographic_coords is True, Cartopy will be used to graph the supplied field.

Additional plotting options are passed to matplotlib.pyplot.pcolormesh. See the matplotlib documentation for a full list of supported options.

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • field (1D NumPy array) – The field to plot.

  • update (bool, optional) – If true, update the existing plot. Specifically, the axes will be checked to see if it contains a PolyCollection object, as generated by tripcolor. If found, the associated data array will be updated with the supplied field data. This is faster than drawing a new map

  • configure (bool, optional) – If true, configure the plot by setting plot extents, drawing coastlines etc. This can be useful when overlaying plots, and you only want to incur the cost of configuring the plot once. The default is True, with the expectation that in most circumstances users will draw any underlying field data before overlaying particle tracks. Default: True.

  • add_colour_bar (bool, optional) – If true, draw a colour bar.

  • cb_label (str, optional) – The colour bar label.

  • tick_inc (bool, optional) – Add coordinate axes (i.e. lat/long).

  • extents (1D array, optional) – Four element numpy array giving lon/lat limits (e.g. [-4.56, -3.76, 49.96, 50.44])

  • draw_coastlines (boolean, optional) – Draw coastlines. Default False.

  • resolution (str, optional) – Resolution to use when plotting the coastline. Only used when draw_coastline=True. Default: ‘10m’.

Returns

  • axes (matplotlib.axes.Axes) – Axes object

  • plot (matplotlib.collections.PolyCollection) – The plot object

plot_quiver(ax, u, v, configure=True, update=False, tick_inc=True, extents=None, draw_coastlines=False, resolution='10m', point_res=1, scale=0.5, **kwargs)[source]

Produce a quiver plot of the supplied velocity field

class pylag.processing.plot.GOTMPlotter(file_name, fs=10, time_rounding=None)[source]

Bases: object

Class to assist in the creation of GOTM plot objects

Class to assist in the creation of plots and animations based on output from the GOTM model, including additional support to plot PyLag outputs.

time_series : Plot variable through time at a given depth
profile : Plot depth profile
hovmoller : pcolormesh plot of a variable on a depth - time grid
hovmoller_particles : pcolormesh plot of particle concentrations on a depth - time grid
scatter : scatter plot of particle positions on a depth - time grid
pathlines : line plot of particle pathlines on a depth - time grid
Parameters
  • file_name (str) – File from which to read grid info.

  • fs (int, optional) – Font size to use when rendering plot text

  • time_rounding (int) – Period between saved data points (in seconds) which is used to round datetime objects.

add_colour_bar(figure, axes, plot, cb_label, cb_ticks)[source]

Add a colour bar

hovmoller(axes, var_name, add_colorbar=True, cb_label=None, cb_ticks=None, **kwargs)[source]

Draw a hovmoller diagram

Parameters
  • axes (matplotlib.axes.Axes) – Axes object

  • var_name (str) – Name of variable to plot.

  • cb_label (str, optional) – The colour bar label.

  • cb_ticks (list[float], optional) – Colorbar ticks.

Returns

axes – Axes object

Return type

matplotlib.axes.Axes

hovmoller_particles(axes, file_names, ds, de, time_rounding, mass_factor=1.0, add_colorbar=True, cb_label=None, cb_ticks=None, **kwargs)[source]

Plot particle concentrations

Parameters
  • axes (matplotlib.axes.Axes) – Axes object

  • file_names (list[str]) – List of sorted PyLag output files. Each output file corresponds to one member of the ensemble.

  • ds (datetime) – Start datetime.

  • de (datetime) – End datetime.

  • time_rounding (int) – Period between saved data points (in seconds) which is used to round PyLag datetime objects. This option is included to account for cases in which PyLag times are written to file with limited precision. Once rounded, two datetime objects can be more easily compared. Note this parameter may be different to the GOTM time_rounding parameter, which is an instance variable.

  • mass_factor (float) – Multiplier that is used to generate concentrations from probability densities.

  • add_colorbar (bool, optional) – Add colorbar?

  • cb_label (bool, optional) – Colorbar label.

  • cb_ticks (list[float], optional) – Colorbar ticks.

plot_pathlines(axes, dates, zpos, **kwargs)[source]

Plot pathlines through time

Parameters
  • axes (matplotlib.axes.Axes) – Axes object

  • dates (array_like) – List of dates

  • zpos (array_like) – List of zpositions

  • kwargs (dict) – Dictionary of keyword arguments for the scatter plot

Return type

None

plot_scatter(axes, dates, zpos, **kwargs)[source]

Scatter plot of particle positions through time

Parameters
  • axes (matplotlib.axes.Axes) – Axes object

  • dates (array_like) – List of dates

  • zpos (array_like) – List of z-positions

  • kwargs (dict) – Dictionary of keyword arguments for the scatter plot

profile(axes, var_name, date)[source]

Generate a depth profile of the listed variable at the given time point

Parameters
  • axes (matplotlib.axes.Axes) – Axes object.

  • var_name (str) – The variable to plot.

  • date (datetime) – The date on which to extract the profile.

Returns

axes – Axes object.

Return type

Matplotlib.axes.Axes

set_title(ax, title)[source]

Set title

time_series(axes, var_name, depth, **kwargs)[source]

Make a time series plot

The function plots a time series of the given variable at the given depth below the free surface. GOTM variable data is first interpolated to the given depth.

Parameters
  • axes (matplotlib.axes.Axes) – Axes object

  • var_name (str) – Name of variable to plot.

  • depth (float) – Depth relative to the free surface (= 0 m). Positive up.

Returns

axes – Axes object

Return type

matplotlib.axes.Axes

class pylag.processing.plot.PyLagPlotter(geographic_coords=True, font_size=10, line_width=0.2)[source]

Bases: object

Base class for PyLag plotters

Class to assist in the creation of plots and animations. The class can be used to create a set of basic plot objects. Plots that overlay particle trajectories on top of underlying field data should be created using the appropriate derived class.

Parameters
  • geographic_coords (boolean, optional) – Boolean specifying whether or not to use cartopy to create a 2D map on top of which the data will be plotted. The default option is True. If False, a simple Cartesian grid is drawn instead.

  • font_size (int, optional) – Font size to use when rendering plot text

  • line_width (float, optional) – Default line width to use when plotting

plot_lines(ax, x, y, transform=<Projected CRS: +proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to ...> Name: unknown Axis Info [cartesian]: - E[east]: Easting (unknown) - N[north]: Northing (unknown) - h[up]: Ellipsoidal height (metre) Area of Use: - undefined Coordinate Operation: - name: unknown - method: Equidistant Cylindrical Datum: Unknown based on WGS 84 ellipsoid - Ellipsoid: WGS 84 - Prime Meridian: Greenwich, **kwargs)[source]

Plot path lines.

In addition to the listed parameters, the function accepts all keyword arguments taken by the Matplotlib plot command.

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • x (ND array) – Array of x coordinates to plot.

  • y (ND array) – Array of y coordinates to plot.

Returns

  • axes (matplotlib.axes.Axes) – Axes object

  • line_plot (matplotlib.collections.Line2D) – The plot object

remove_line_plots(line_plots)[source]

Remove line plots

Useful when updating plots for animations.

Parameters

line_plots (list) – List of line plot objects created during call to plot_lines()

scatter(ax, x, y, configure=False, transform=<Projected CRS: +proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to ...> Name: unknown Axis Info [cartesian]: - E[east]: Easting (unknown) - N[north]: Northing (unknown) - h[up]: Ellipsoidal height (metre) Area of Use: - undefined Coordinate Operation: - name: unknown - method: Equidistant Cylindrical Datum: Unknown based on WGS 84 ellipsoid - Ellipsoid: WGS 84 - Prime Meridian: Greenwich, zorder=4, extents=None, draw_coastlines=False, resolution='10m', tick_inc=False, **kwargs)[source]

Create a scatter plot using the provided x and y values

If geographic_coords is True, x and y should be geographic (lat, lon) coordinates. If not, x any y should be given as cartesian coordinates.

See Matplotlib’s scatter documentation for a list of additional key word arguments.

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • x (1D array) – Array of ‘x’ positions. If plotting in geographic coords, these should be longitudes.

  • y (1D array) – Array of ‘y’ positions. If plotting in geographic coords, these should be latitudes.

  • configure (bool, optional) – If true, configure the plot by setting plot extents, drawing coastlines etc. Default: False.

  • transform (cartopy.crs.Projection) – The type of transform to perform if geographic_coords is True. Optional.

  • draw_coastlines (bool) – Draw coastlines? Only used if geographic_coords is True. Optional.

  • resolution (str, optional) – Resolution to use when plotting the coastline. Only used when draw_coastline=True. Default: ‘10m’.

  • tick_inc (bool) – Draw ticks? Only used if geographic_coords is True. Optional.

Returns

  • ax (matplotlib.axes.Axes) – Axes object

  • scatter_plot (matplotlib.collection.PathCollection) – The scatter plot

set_title(ax, title)[source]

Set the title

Parameters
  • ax (matplotlib.axes.Axes) – Axes object

  • title (str) – Plot title

pylag.processing.plot.cm2inch(value)[source]

Convert centimetres to inches.

Parameters

value (float) – Length in cm.

Returns

Length in inches.

Return type

float

pylag.processing.plot.colourmap(variable)[source]

Use a predefined colour map for a given variable.

Leverages the cmocean package for perceptually uniform colour maps.

Parameters

variable (str) – For the given variable name, return the appropriate colour palette from the cmocean/matplotlib colour maps. If the variable is not in the pre-defined variables here, the returned values will be viridis.

Returns

colourmaps – The colour map for the variable given.

Return type

matplotlib.colours.cmap

pylag.processing.plot.create_cbar_ax(ax)[source]

Create colorbar axis alligned with plot axis y limits

Parameters

ax (Axes) – Plot axes instsance

Returns

cax – Colorbar plot axis

Return type

Axes

pylag.processing.plot.create_figure(figure_size=(10.0, 10.0), font_size=10, axis_position=None, projection=None, bg_color='white')[source]

Create a Figure object

Parameters
  • figure_size (tuple(float), optional) – Figure size in cm. This is only used if a new Figure object is created.

  • font_size (int) – Font size to use for axis labels

  • axis_position (1D array, optional) – Array giving axis dimensions

  • projection (ccrs.Projection) – Cartopy projection to use for the plot. If None, a projection will not be used.

  • bg_color (str, optional) – Colour to use for the axis background. Default is white. When creating a figure for plotting FVCOM outputs, it can be useful to set this to gray. When FVCOM is fitted to a coastline, the gray areas mark the land boundary used by the model. This provides a fast alternative to plotting a high resolution (e.g. res = f) land boundary using methods provided by the Basemap class instance.