earthkit.plots.Subplot

class earthkit.plots.Subplot(row=0, column=0, figure=None, figsize=(7, 8), ax=None, size=None, chainable=False, **kwargs)[source]

Bases: object

A single plot within a Figure.

A Subplot is a container for one or more Layers, each of which is a plot of a single data source.

Parameters:
  • row (int, optional) – The row index of the subplot in the Figure.

  • column (int, optional) – The column index of the subplot in the Figure.

  • figure (Figure, optional) – The Figure to which the subplot belongs.

  • **kwargs – Additional keyword arguments to pass to the matplotlib.axes.Axes constructor.

Methods

add_logo(logo)

Add a logo to the figure.

annotate(s, xy[, xytext])

Add an annotation to the Subplot.

attribution(attribution[, location])

Add an attribution to the figure.

axis(key)

Look up a registered y-axis by its display units or user-assigned name and return an AxisView handle for per-axis decoration.

bar(*args, **kwargs)

Plot a bar chart on the Subplot.

barbs(*args, **kwargs)

Plot wind barbs on the Subplot.

block(*args, **kwargs)

Plot a pcolormesh on the Subplot.

coastlines(*args, **kwargs)

Plot coastlines on the Subplot.

contour(*args, **kwargs)

Plot a contour plot on the Subplot.

contourf(*args, **kwargs)

Plot a filled contour plot on the Subplot.

envelope(data_1[, data_2, alpha, units])

Plot an envelope on the Subplot.

fill_between(y1[, y2, x, alpha, units])

Fill the area between two curves.

fix_x_units(units)

Set a permanent unit for the x-axis.

fix_y_units(units)

Set a permanent unit for the y-axis.

format_string(string[, unique, grouped, axis])

Format a string with metadata from the Subplot.

format_x_ticks(format_spec)

Apply a tick formatter to the x-axis.

format_y_ticks(format_spec)

Apply a tick formatter to the y-axis.

gridlines(*args, **kwargs)

Plot gridlines on the Subplot.

hsv_composite(*args)

Plot an HSV composite on the Subplot.

imshow(*args, **kwargs)

Plot an image (imshow) on the Subplot.

labels([data, label, x, y])

Plot labels on the Subplot.

legend([label])

Add a legend to the Subplot.

line(*args, **kwargs)

Plot a line on the Subplot.

multiboxplot(data[, x, dim, quantiles, ...])

Plot a multiboxplot (letter-value plot) from multi-dimensional data.

multiboxplot_legend([location, fontsize, ...])

Add a visual legend for the most recent multiboxplot.

pcolormesh(*args, **kwargs)

Plot a pcolormesh on the Subplot.

plot(data[, style, units])

Auto-detect the best plot type and render the data.

quantiles(*args, **kwargs)

Plot a quantile fill (shaded uncertainty band) on the Subplot.

quickplot(data[, style, units])

Generate a convenient plot from the given data with optional grouping.

quiver(*args, **kwargs)

Plot arrows on the Subplot.

quiverkey([u, x, y, label])

Add a quiverkey (reference arrow) to the plot.

rgb_composite(*args)

Plot an RGB composite on the Subplot.

save(*args, **kwargs)

Save the plot to a file.

scatter(*args, **kwargs)

Plot a scatter plot on the Subplot.

set_title([label])

Set the title of the subplot.

show()

Display the plot.

spaghetti(data_list, *args[, levels, color, ...])

Plot spaghetti contours for ensemble data with optional highlighting.

streamplot(*args, **kwargs)

Plot streamlines on the Subplot.

stripes(*args, **kwargs)

Plot a climate stripes visualisation on the Subplot.

suptitle(*args, **kwargs)

Add a top-level title to the chart.

text(x[, y, s])

Add text to the Subplot at position (x, y).

title([label, unique, wrap, capitalize])

Add a title to the plot.

tricontour(*args, **kwargs)

Plot a tricontour plot on the Subplot.

tricontourf(*args, **kwargs)

Plot a filled tricontour plot on the Subplot.

tripcolor(*args, **kwargs)

Plot a tripcolor plot on the Subplot.

twin_axis([position, index])

Context manager that redirects subsequent plot calls to a twin axes.

twinx()

Create a twin subplot sharing the same x-axis with an independent right y-axis.

wrap_longitudes([axis])

Roll the longitude coordinate from 0–360 to –180 to +180.

xlabel([label])

Add an x-axis label to the subplot.

xticks([frequency, minor_frequency, format, ...])

Set x-axis tick locations and formatting.

ylabel([label, side])

Add a y-axis label to the subplot.

yticks([frequency, minor_frequency, format, ...])

Set y-axis tick locations and formatting.

Attributes

ax

The underlying matplotlib.axes.Axes object.

crs

The Coordinate Reference System of the subplot.

current_ax

The matplotlib.axes.Axes that should receive the next plot call.

distinct_legend_layers

Layers on this subplot which have a unique Style.

fig

The underlying matplotlib.figure.Figure object.

figure

The earthkit.plots.components.figures.Figure object.

Add a logo to the figure.

Parameters:

logo (str) – Either the name of a built-in logo, or a path to the logo image file to add to the figure.

annotate(s, xy, xytext=None, **kwargs)[source]

Add an annotation to the Subplot.

Can be called in two ways:

  • annotate(s, (x, y)) — explicit coordinates.

  • annotate(s, data) — pass an xarray DataArray; xy is extracted from the data’s coordinates and values respectively.

Parameters:
  • s (str) – The annotation text. Supports format strings (e.g. "{time:%Y}").

  • xy (tuple or xarray.DataArray) – The point to annotate. Either an (x, y) tuple in data coordinates, or a DataArray from which both are extracted.

  • xytext (tuple, optional) – The position of the text. If not given, the text is placed at xy. Can be an offset in points when used with textcoords="offset points".

  • **kwargs – Additional keyword arguments passed to matplotlib.axes.Axes.annotate().

attribution(attribution, location='lower center', **kwargs)[source]

Add an attribution to the figure.

Parameters:
  • attribution (str) – The attribution text to add to the figure.

  • location (str, optional) – The location of the attribution text. Accepts the same values as matplotlib legend locations: ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’, ‘upper center’, ‘lower center’, ‘center left’, ‘center right’, ‘center’. Default is ‘lower center’.

  • **kwargs – Additional keyword arguments passed to matplotlib.figure.Figure.text.

property ax

The underlying matplotlib.axes.Axes object.

axis(key: str) AxisView[source]

Look up a registered y-axis by its display units or user-assigned name and return an AxisView handle for per-axis decoration.

The AxisView exposes ylabel(), ylim(), format_y_ticks(), and fix_y_units(), and always returns this Subplot so method-chaining is not broken:

ts.axis("celsius").ylabel("Temperature (°C)")
ts.axis("mm").ylabel("Precipitation (mm)").ylim(0, 50)
ts.show()
Parameters:

key – Canonical units string (e.g. "celsius", "mm") or a name previously registered via fix_y_units().

Raises:

KeyError – If no axis has been registered under key yet. An axis is registered automatically the first time data with those units is plotted when _auto_twin_axes is True.

bar(*args, **kwargs)[source]

Plot a bar chart on the Subplot.

Parameters:
barbs(*args, **kwargs)[source]

Plot wind barbs on the Subplot.

Parameters:
block(*args, **kwargs)[source]

Plot a pcolormesh on the Subplot.

Deprecated: Use pcolormesh() instead.

Parameters:
  • *args (xarray.DataArray or earthkit.data.core.Base) – The data source for which to plot the block.

  • units (str, optional) – Target units for value conversion (e.g. "celsius"). Unit conversion relies on CF-compliant units metadata in the data. See Unit conversion for examples.

  • **kwargs – Additional keyword arguments to pass to pcolormesh().

coastlines(*args, **kwargs)[source]

Plot coastlines on the Subplot.

NOTE: This method is not implemented on Subplots, but may be available on subclasses such as earthkit.plots.components.maps.Map.

contour(*args, **kwargs)[source]

Plot a contour plot on the Subplot.

Parameters:
  • data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x, y, and z must be provided.

  • x (str, list, numpy.ndarray, or xarray.DataArray, optional) – The x values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • y (str, list, numpy.ndarray, or xarray.DataArray, optional) – The y values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • z (str, list, numpy.ndarray, or xarray.DataArray, optional) – The z values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • style (earthkit.plots.styles.Style, optional) – The Style to use for the contour plot. If None, a Style is automatically generated based on the data.

  • units (str, optional) – Target units for value conversion (e.g. "celsius"). Unit conversion relies on CF-compliant units metadata in the data. See Unit conversion for examples.

  • resample (earthkit.plots.resample.Resample, bool, or False, optional) – Controls resampling before plotting. Pass a Bilinear or NearestNeighbour instance (or True for defaults) to reproject onto a regular target grid, or False to disable. Default is Bilinear() (1000 × 1000 pixels).

  • **kwargs – Additional keyword arguments passed to matplotlib.axes.Axes.contour(). See the matplotlib contour documentation for the full list of accepted arguments.

contourf(*args, **kwargs)[source]

Plot a filled contour plot on the Subplot.

Parameters:
  • data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x, y, and z must be provided.

  • x (str, list, numpy.ndarray, or xarray.DataArray, optional) – The x values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • y (str, list, numpy.ndarray, or xarray.DataArray, optional) – The y values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • z (str, list, numpy.ndarray, or xarray.DataArray, optional) – The z values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • style (earthkit.plots.styles.Style, optional) – The Style to use for the filled contour plot. If None, a Style is automatically generated based on the data.

  • units (str, optional) – Target units for value conversion (e.g. "celsius"). Unit conversion relies on CF-compliant units metadata in the data. See Unit conversion for examples.

  • resample (earthkit.plots.resample.Resample, bool, or False, optional) – Controls resampling before plotting. Pass a Bilinear or NearestNeighbour instance (or True for defaults) to reproject onto a regular target grid, or False to disable. Default is Bilinear() (1000 × 1000 pixels). Pass an Unstructured instance to interpolate unstructured data onto a structured grid instead.

  • **kwargs – Additional keyword arguments passed to matplotlib.axes.Axes.contourf(). See the matplotlib contourf documentation for the full list of accepted arguments.

property crs

The Coordinate Reference System of the subplot.

property current_ax

The matplotlib.axes.Axes that should receive the next plot call.

Returns the top of the twin-axis stack when inside a twin_axis() context manager, otherwise returns the primary ax. All pipeline render sites use subplot.current_ax so that twin-axis redirection is transparent to the rest of the code.

property distinct_legend_layers

Layers on this subplot which have a unique Style.

envelope(data_1, data_2=0, alpha=0.4, units=None, **kwargs)[source]

Plot an envelope on the Subplot.

Parameters:
property fig

The underlying matplotlib.figure.Figure object.

property figure

The earthkit.plots.components.figures.Figure object.

fill_between(y1, y2=0, x=None, alpha=0.2, units=None, **kwargs)[source]

Fill the area between two curves.

Parameters:
  • y1 (xarray.DataArray or array-like) – The lower (or upper) bound of the filled region.

  • y2 (xarray.DataArray, array-like, or scalar, optional) – The upper (or lower) bound. Defaults to 0, which shades from y1 down to zero.

  • x (str or array-like, optional) – The x-axis coordinate name or values. If not provided, earthkit-plots will attempt to infer it automatically from y1.

  • alpha (float, optional) – Opacity of the filled region. Default is 0.2.

  • units (str, optional) – Target units for value conversion (e.g. "celsius"). See Unit conversion for examples.

  • **kwargs

    Additional keyword arguments forwarded to matplotlib.axes.Axes.fill_between(). See the matplotlib fill_between documentation for the full list (e.g. color, zorder, label).

Examples

Shade between two pre-computed bounds:

>>> ts.fill_between(mean - std, mean + std, units="celsius")

With an explicit x coordinate:

>>> ts.fill_between(p10, p90, x="valid_time", color="#1f78b4")

Shade from a curve down to zero:

>>> ts.fill_between(values)
fix_x_units(units)[source]

Set a permanent unit for the x-axis.

All subsequent plot calls on this subplot will convert x-axis data to units without needing x_units= on every call.

Parameters:

units (str) – Target units string (e.g. "celsius").

fix_y_units(units)[source]

Set a permanent unit for the y-axis.

All subsequent plot calls on this subplot will convert y-axis data to units without needing units= on every call.

Parameters:

units (str) – Target units string (e.g. "celsius").

format_string(string, unique=True, grouped=True, axis=None)[source]

Format a string with metadata from the Subplot.

Parameters:
  • string (str) – The string to format. This can contain metadata keys in curly braces, e.g. “{variable_name}”.

  • unique (bool, optional) – Whether to use unique metadata values from each Layer. If False, metadata values from all Layers are combined.

  • grouped (bool, optional) – Whether to group metadata values from all Layers into a single string. If False, metadata values from each Layer are listed separately.

  • axis (str, optional) – The axis to format. If None, the format string will use the general metadata of the subplot.

format_x_ticks(format_spec)[source]

Apply a tick formatter to the x-axis.

Supports the same format specifiers as title/label strings:

  • "%Ln" — longitude with E/W direction (e.g. 45°E, 10°W)

  • "%Ln.1f" — longitude with custom decimal precision

  • "%Lt" — latitude with N/S direction (e.g. 45°N)

  • "%Lt.1f" — latitude with custom decimal precision

  • Any standard Python format spec (e.g. ".1f")

Parameters:

format_spec (str) – Format specifier string.

Return type:

self

format_y_ticks(format_spec)[source]

Apply a tick formatter to the y-axis.

Supports the same format specifiers as title/label strings:

  • "%Lt" — latitude with N/S direction (e.g. 45°N, 30°S)

  • "%Lt.1f" — latitude with custom decimal precision

  • "%Ln" — longitude with E/W direction (e.g. 45°E)

  • "%Ln.1f" — longitude with custom decimal precision

  • Any standard Python format spec (e.g. ".1f")

Parameters:

format_spec (str) – Format specifier string.

Return type:

self

gridlines(*args, **kwargs)[source]

Plot gridlines on the Subplot.

NOTE: This method is not implemented on Subplots, but may be available on subclasses such as earthkit.plots.components.maps.Map.

hsv_composite(*args)[source]

Plot an HSV composite on the Subplot.

Parameters:

*args (xarray.DataArray or earthkit.data.core.Base) – The data sources for the H, S, and V channels. If a single argument is provided, it is assumed to be a tuple of (H, S, V).

imshow(*args, **kwargs)[source]

Plot an image (imshow) on the Subplot.

Follows the same pipeline as pcolormesh() — data is wrapped in a Source, style is resolved, and the result is attached as a Layer.

Parameters:
  • data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x, y, and z must be provided.

  • x (str, list, numpy.ndarray, or xarray.DataArray, optional) – The x values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • y (str, list, numpy.ndarray, or xarray.DataArray, optional) – The y values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • z (str, list, numpy.ndarray, or xarray.DataArray, optional) – The z values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • style (earthkit.plots.styles.Style, optional) – The Style to use for the image. If None, a Style is automatically generated based on the data.

  • units (str, optional) – Target units for value conversion (e.g. "celsius"). Unit conversion relies on CF-compliant units metadata in the data. See Unit conversion for examples.

  • resample (earthkit.plots.resample.Resample, bool, or dict, optional) – Controls resampling of data before plotting. Pass a Unstructured (or subclass) instance to interpolate unstructured data onto a regular grid, a dict of keyword arguments to construct one, or True for defaults. Default is False for imshow.

  • **kwargs – Additional keyword arguments passed to matplotlib.axes.Axes.imshow(). See the matplotlib imshow documentation for the full list of accepted arguments.

labels(data=None, label=None, x=None, y=None, **kwargs)[source]

Plot labels on the Subplot.

Parameters:
legend(label=None, *args, **kwargs)[source]

Add a legend to the Subplot.

Parameters:
  • style (Style, optional) – The Style to use for the legend. If None (default), a legend is created for each Layer with a unique Style. If a single Style is provided, a single legend is created based on that Style.

  • location (str or tuple, optional) – The location of the legend(s). Must be a valid matplotlib location (see matplotlib.pyplot.legend()).

  • **kwargs – Additional keyword arguments to pass to matplotlib.pyplot.legend().

line(*args, **kwargs)[source]

Plot a line on the Subplot.

Parameters:
multiboxplot(data, x='auto', dim=None, quantiles='auto', color=None, units=None, x_units=None, y_units=None, label=None, boxprops=None, whiskerprops=None, medianprops=None, capprops=None, showcaps=False, **kwargs)[source]

Plot a multiboxplot (letter-value plot) from multi-dimensional data.

Visualises quantiles as stacked boxes with varying widths — innermost quantile pair is widest and darkest; the outermost pair (min/max) is rendered as a whisker line. Useful for ensemble spread, uncertainty bands, or any distribution that varies along a second axis.

Parameters:
  • data (xarray.DataArray) – The data to plot. Must have at least two dimensions after squeezing: one for the quantile/ensemble dimension and one for the x-axis.

  • x (str, optional) – Dimension name to use as x-axis. Default "auto" uses the remaining dimension after the quantile dimension is removed.

  • dim (str, optional) – Dimension along which to compute quantiles (e.g. 'number' for ensemble members). If None, the left-most dimension is used. When quantiles is None (pre-computed), this names the dimension that already holds quantile values.

  • quantiles (list of float, "auto", or None, optional) –

    • "auto" (default) – compute [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1].

    • list of float – compute the specified quantiles (0–1).

    • None – treat dim as pre-computed quantile values.

  • color (str or tuple, optional) – Fill colour for the innermost (darkest) box. Defaults to the next colour in matplotlib’s colour cycle.

  • units (str, optional) – Target units for y-axis values (e.g. "celsius"). See Unit conversion for examples.

  • x_units (str, optional) – Target units for x-axis values.

  • y_units (str, optional) – Target units for y-axis values (overrides units).

  • label (str, optional) – Legend label. Supports metadata format placeholders such as "{variable_name}".

  • boxprops (dict, optional) – Properties for box rectangles (edgecolor, linewidth, linestyle).

  • whiskerprops (dict, optional) – Properties for the min/max whisker line (color, linewidth, linestyle).

  • medianprops (dict, optional) – Properties for the median line (color, linewidth, linestyle, alpha).

  • capprops (dict, optional) – Properties for whisker cap lines. Only drawn when showcaps=True. Extra key capwidth (default 1.0) controls width as a fraction of the box width.

  • showcaps (bool, optional) – Whether to draw horizontal cap lines at whisker ends. Default False.

  • **kwargs – Extra keyword arguments are ignored (for forward-compat).

Returns:

List of matplotlib artists drawn for this layer.

Return type:

list

multiboxplot_legend(location='right', fontsize=8, color=None, boxprops=None, whiskerprops=None, medianprops=None, **kwargs)[source]

Add a visual legend for the most recent multiboxplot.

Creates a miniature replica of the quantile box structure with labelled percentiles, placed outside the plot area using mpl_toolkits.axes_grid1.make_axes_locatable() (the same mechanism as a colorbar). The legend is always rendered as a small square regardless of which side it is placed on.

Call this after multiboxplot().

Parameters:
  • location (str, optional) – Side of the axes on which to place the legend. One of 'right' (default), 'left', 'top', 'bottom'.

  • fontsize (int, optional) – Font size for the quantile labels. Default 8.

  • color (str or tuple, optional) – Override the fill colour. Defaults to the colour used by the most recent multiboxplot() call.

  • boxprops (dict, optional) – Override box-edge properties (edgecolor, linewidth).

  • whiskerprops (dict, optional) – Override whisker-line properties (color, linewidth).

  • medianprops (dict, optional) – Override median-line properties (color, linewidth).

  • size (float, optional) – Width/height of the legend square in inches. Default 0.75.

  • pad (float, optional) – Gap between the main axes and the legend in inches. Default 0.1.

Returns:

The axes containing the legend.

Return type:

matplotlib.axes.Axes

Raises:

ValueError – If no multiboxplot() has been drawn yet, or location is invalid.

pcolormesh(*args, **kwargs)[source]

Plot a pcolormesh on the Subplot.

Parameters:
  • data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x, y, and z must be provided.

  • x (str, list, numpy.ndarray, or xarray.DataArray, optional) – The x values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • y (str, list, numpy.ndarray, or xarray.DataArray, optional) – The y values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • z (str, list, numpy.ndarray, or xarray.DataArray, optional) – The z values to plot. If data is provided, this is assumed to be the name of a coordinate in the data. If None, data must be provided.

  • style (earthkit.plots.styles.Style, optional) – The Style to use for the pcolormesh. If None, a Style is automatically generated based on the data.

  • units (str, optional) – Target units for value conversion (e.g. "celsius"). Unit conversion relies on CF-compliant units metadata in the data. See Unit conversion for examples.

  • resample (earthkit.plots.resample.Resample, bool, or dict, optional) – Controls resampling of data before plotting. Pass a Unstructured (or subclass) instance to interpolate unstructured data onto a regular grid, a dict of keyword arguments to construct one, or True for defaults. Default is False for pcolormesh.

  • **kwargs – Additional keyword arguments passed to matplotlib.axes.Axes.pcolormesh(). See the matplotlib pcolormesh documentation for the full list of accepted arguments.

plot(data, style=None, units=None, **kwargs)[source]

Auto-detect the best plot type and render the data.

Inspects data metadata to choose the most appropriate method (e.g. contourf(), grid_cells(), pcolormesh()). You can override the selection by passing an explicit style.

Parameters:
quantiles(*args, **kwargs)[source]

Plot a quantile fill (shaded uncertainty band) on the Subplot.

Draws one shaded band per quantile pair (e.g. p10–p90, p25–p75) centred around the median, using progressively lighter shading for outer quantiles.

Parameters:
quickplot(data, style='auto', units=None, **kwargs)[source]

Generate a convenient plot from the given data with optional grouping.

Parameters:
  • *args (list) – The data to be plotted. Can be a single xarray or earthkit data object, or separate x, y, z, u, v arguments.

  • methods (string or list, optional) – The plot method(s) to apply.

  • style (earthkit.plots.styles.Style, optional) – The Style to use for the data.

  • units (string or list, optional) – Units to convert the data to.

  • **kwargs (dict) – Additional arguments for the plot method(s).

quiver(*args, **kwargs)[source]

Plot arrows on the Subplot.

Parameters:
quiverkey(u=None, x=0.9, y=1.02, label=None, **kwargs)[source]

Add a quiverkey (reference arrow) to the plot.

Finds the first quiver layer on this subplot and calls matplotlib.axes.Axes.quiverkey() on it.

Parameters:
  • u (float, optional) – The length of the reference arrow in data units. If not provided, a sensible value is chosen automatically from the data range, picked from the sequence 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, …

  • x (float, optional) – X position of the quiverkey in axes coordinates (0–1). Default 0.85.

  • y (float, optional) – Y position of the quiverkey in axes coordinates. Default 1.02 (just above the axes).

  • label (str, optional) – Label for the reference arrow. Defaults to "{u} {units}" where {u} is the value of u and {units} comes from the layer’s style units or source metadata.

  • **kwargs – Additional keyword arguments passed directly to matplotlib.axes.Axes.quiverkey(), e.g. coordinates, labelpos, fontproperties.

rgb_composite(*args)[source]

Plot an RGB composite on the Subplot.

Parameters:

*args (xarray.DataArray or earthkit.data.core.Base) – The data sources for the R, G, and B channels. If a single argument is provided, it is assumed to be a tuple of (R, G, B).

save(*args, **kwargs)[source]

Save the plot to a file.

scatter(*args, **kwargs)[source]

Plot a scatter plot on the Subplot.

Parameters:
set_title(label=None, **kwargs)[source]

Set the title of the subplot.

Alias for title() that matches the matplotlib set_title convention. Accepts the same arguments.

Parameters:
  • label (str, optional) – The title text. Can contain metadata keys in curly braces, e.g. "{variable_name}".

  • **kwargs – Additional keyword arguments forwarded to title().

show()[source]

Display the plot.

spaghetti(data_list, *args, levels=None, color='#0673e0', label=None, highlight=None, highlight_kwargs=None, highlight_label=None, **kwargs)[source]

Plot spaghetti contours for ensemble data with optional highlighting.

This method plots contour lines for each member in an ensemble dataset, with the ability to highlight specific members based on metadata criteria.

Parameters:
  • data_list (earthkit.data.core.Base, xarray.DataArray, or list) – The ensemble data to plot. Can be an earthkit data object, xarray DataArray, or a list of data objects that can be iterated over.

  • *args – Positional arguments passed to the contour method.

  • levels (float or list of float, optional) – Contour level(s) to plot. Accepts a single value or a list of values. If provided, overrides any levels in kwargs.

  • color (str or list, default "#0673e0") – Color for normal ensemble members.

  • label (str, optional) – Legend label for the ensemble members. If provided (along with highlight_label if highlighting is used), a legend entry is automatically added. Pass an empty string to suppress the entry.

  • highlight (dict, optional) – Dictionary with metadata criteria to select members for highlighting. For example, {‘dataType’: ‘cf’} to highlight control forecast.

  • highlight_kwargs (dict, optional) – Dictionary with keyword arguments to pass to the contour method for highlighted members.

  • highlight_label (str, optional) – Legend label for the highlighted members. Only used when highlight is also set. Defaults to "Control" if label is set and highlight is set but highlight_label is not provided.

  • **kwargs

    Additional keyword arguments passed to matplotlib.axes.Axes.contour() for each member. See the matplotlib contour documentation for the full list. Common parameters include linewidths, alpha, and labels.

streamplot(*args, **kwargs)[source]

Plot streamlines on the Subplot.

Parameters:
stripes(*args, **kwargs)[source]

Plot a climate stripes visualisation on the Subplot.

Draws one vertical bar per data point, colored according to the data value mapped through the given (or auto-detected) style.

Parameters:
  • data (xarray.DataArray or array-like) – The data to plot.

  • x (str or array-like, optional) – The x (time) coordinate. If data is a DataArray this is inferred automatically.

  • y (str or array-like, optional) – The values used to color the stripes. Defaults to the primary data variable.

  • style (earthkit.plots.styles.Style or str, optional) – Style object or named style string. If None an auto-style is chosen from the data metadata.

  • units (str, optional) – Target units for value conversion (e.g. "celsius"). See Unit conversion for examples.

  • ymin (float, optional) – Bottom of the stripes in axes-fraction coordinates (default 0).

  • ymax (float, optional) – Top of the stripes in axes-fraction coordinates (default 1).

  • **kwargs – Additional keyword arguments forwarded to matplotlib.collections.BrokenBarHCollection.

suptitle(*args, **kwargs)[source]

Add a top-level title to the chart.

Parameters:
  • label (str, optional) – The text to use in the title. This text can include format keys surrounded by {} curly brackets, which will extract metadata from your plotted data layers.

  • unique (bool, optional) – If True, format keys which are uniform across subplots/layers will produce a single result. For example, if all data layers have the same variable_name, only one variable name will appear in the title. If False, each format key will evaluate to a list of values found across subplots/layers.

  • grouped (bool, optional) – If True, a single title will be generated to represent all data layers, with each format key evaluating to a list where layers differ - e.g. “{variable} at {time}” might be evaluated to “temperature and wind at 2023-01-01 00:00”. If False, the title will be duplicated by the number of subplots/ layers - e.g. `”{variable} at {time}” might be evaluated to `”temperature at 2023-01-01 00:00 and wind at 2023-01-01 00:00”.

  • kwargs (dict, optional) – Keyword argument to matplotlib.pyplot.suptitle().

text(x, y=None, s='', **kwargs)[source]

Add text to the Subplot at position (x, y).

Can be called in two ways:

  • text(x, y, s) — explicit coordinates and string.

  • text(data, s=...) — pass an xarray DataArray; x and y are extracted from the data’s coordinates and values respectively.

Parameters:
  • x (float, datetime-like, or xarray.DataArray) – The x position in data coordinates, or a DataArray from which both x and y are extracted.

  • y (float, optional) – The y position in data coordinates. Required when x is not a DataArray.

  • s (str, optional) – The text string.

  • **kwargs – Additional keyword arguments passed to matplotlib.axes.Axes.text().

title(label=None, unique=True, wrap=True, capitalize='auto', **kwargs)[source]

Add a title to the plot.

Parameters:
  • label (str, optional) – The title text. If None, a default template is used. The template can contain metadata keys in curly braces, e.g. “{variable_name}”.

  • unique (bool, optional) – Whether to use unique metadata values from each Layer. If False, metadata values from all Layers are combined.

  • wrap (bool, optional) – Whether to wrap the title text. Default is True.

  • capitalize (bool or str, optional) – Whether to capitalize the first letter of the title. Default is “auto”. If “auto”, capitalization is determined based on whether the title starts with a format key (e.g. “{variable_name}”), in which case it is capitalized.

  • **kwargs – Additional keyword arguments to pass to matplotlib.pyplot.title().

tricontour(*args, **kwargs)[source]

Plot a tricontour plot on the Subplot.

Parameters:
tricontourf(*args, **kwargs)[source]

Plot a filled tricontour plot on the Subplot.

Parameters:
tripcolor(*args, **kwargs)[source]

Plot a tripcolor plot on the Subplot.

Parameters:
twin_axis(position='right', index=None)[source]

Context manager that redirects subsequent plot calls to a twin axes.

Creates a new twin axes the first time it is called for a given position / index combination, then reuses it on subsequent calls. Multiple independent twin axes on the same side can be created by passing distinct index values.

Parameters:
  • position ({"right", "top"}, optional) – "right" (default) shares the x-axis (twinx), producing a second independent y-axis on the right-hand side of the plot — the typical use-case for overlaying e.g. temperature and precipitation. "top" shares the y-axis (twiny), adding a second independent x-axis at the top.

  • index (int, optional) – Disambiguates multiple twin axes on the same side. 0 is the first twin, 1 the second, etc. Defaults to 0 for the first twin_axis() call on a given position, incrementing automatically for each new call on that position.

Returns:

A context manager that yields self so the existing method-chaining idiom still works:

with subplot.twin_axis() as ax2:
    ax2.line(precip, color="blue")
    ax2.ylabel("Precipitation (mm)")

Return type:

contextmanager

Examples

Temperature on the left y-axis, precipitation on the right:

ts = fig.add_timeseries()
ts.line(temperature, color="red")
ts.ylabel("Temperature (°C)")
with ts.twin_axis() as ts2:
    ts2.bar(precipitation, color="blue", alpha=0.4)
    ts2.ylabel("Precipitation (mm)")

Three independent y-axes (left + two stacked on the right):

with subplot.twin_axis(position="right", index=0) as ax2:
    ax2.line(data2)
with subplot.twin_axis(position="right", index=1) as ax3:
    ax3.line(data3)
twinx()[source]

Create a twin subplot sharing the same x-axis with an independent right y-axis.

Returns a new instance of the same class (e.g. TimeSeries, Map) wrapping the twinx matplotlib axes. The twin shares this subplot’s layers list and figure so that decoration methods called on the primary subplot (legend(), title(), show()) see layers from both axes.

The twin’s _chainable flag matches the primary so the OO and high-level APIs both behave consistently.

Example

ts = ekp.TimeSeries()
ts.line(anomaly_monthly, label="Monthly anomaly", color="goldenrod")

ts2 = ts.twinx()
ts2.line(relative_anomaly, label="Relative anomaly", color="orchid")
ts2.ylabel("Relative anomaly (%)")

ts.ylabel().legend().show()
wrap_longitudes(axis='x')[source]

Roll the longitude coordinate from 0–360 to –180 to +180.

Call this before plotting when your data’s longitude coordinate runs from 0° to 360° but you want it displayed in the –180° to +180° range (e.g. to align a meridional-mean line chart with a map panel).

Parameters:

axis (str, optional) – The axis that carries longitude values. "x" (default) for the common case where longitude is the x-axis; "y" for transposed plots.

Return type:

self

xlabel(label=None, **kwargs)[source]

Add an x-axis label to the subplot.

If no label is provided, one is generated automatically from the plotted data’s metadata (variable name and units).

Parameters:
  • label (str, optional) – The label text. Supports metadata format placeholders such as "{variable_name}" and "{units}". If None, a label is inferred from the data.

  • **kwargs – Additional keyword arguments passed to matplotlib.axes.Axes.set_xlabel().

xticks(frequency=None, minor_frequency=None, format=None, minor_format=None, period=False, labels='major', **kwargs)[source]

Set x-axis tick locations and formatting.

Parameters:
  • frequency (str, optional) – Major tick frequency (e.g., “Y”, “M6”, “D7”, “H”). Default is None (auto).

  • minor_frequency (str, optional) – Minor tick frequency. If None, uses frequency. Default is None.

  • format (str, optional) – Format string for major tick labels. Default is None (auto).

  • minor_format (str, optional) – Format string for minor tick labels. If None and format is specified, uses format. Default is None.

  • period (bool, optional) – If True, centers labels between ticks for better visual balance. Default is False.

  • labels (str, optional) – Which tick labels to show: “major”, “minor”, “both”, or None. Default is “major”.

  • **kwargs – Additional keyword arguments to pass to the tick locators.

ylabel(label=None, side=None, **kwargs)[source]

Add a y-axis label to the subplot.

If no label is provided, one is generated automatically from the plotted data’s metadata (variable name and units).

When _auto_twin_axes is True and multiple y-axes have been created by the auto-routing system, calling ylabel() with no arguments labels all axes from their respective layer metadata in one call — so you rarely need axis() for the common case.

Parameters:
  • label (str, optional) – The label text. Supports metadata format placeholders such as "{variable_name}" and "{units}". If None, a label is inferred from the data. Pass an explicit string to set the same label on every axis (or use axis() to target one).

  • **kwargs – Additional keyword arguments passed to matplotlib.axes.Axes.set_ylabel().

yticks(frequency=None, minor_frequency=None, format=None, minor_format=None, labels='major', **kwargs)[source]

Set y-axis tick locations and formatting.

Parameters:
  • frequency (str, optional) – Major tick frequency (e.g., “Y”, “M6”, “D7”, “H”). Default is None (auto).

  • minor_frequency (str, optional) – Minor tick frequency. If None, uses frequency. Default is None.

  • format (str, optional) – Format string for major tick labels. Default is None (auto).

  • minor_format (str, optional) – Format string for minor tick labels. If None and format is specified, uses format. Default is None.

  • labels (str, optional) – Which tick labels to show: “major”, “minor”, “both”, or None. Default is “major”.

  • **kwargs – Additional keyword arguments to pass to the tick locators.