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:
objectA 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.Axesconstructor.
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
AxisViewhandle 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
The underlying
matplotlib.axes.Axesobject.The Coordinate Reference System of the subplot.
The
matplotlib.axes.Axesthat should receive the next plot call.Layers on this subplot which have a unique Style.
The underlying
matplotlib.figure.Figureobject.The
earthkit.plots.components.figures.Figureobject.- add_logo(logo)[source]¶
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.Axesobject.
- axis(key: str) AxisView[source]¶
Look up a registered y-axis by its display units or user-assigned name and return an
AxisViewhandle for per-axis decoration.The
AxisViewexposesylabel(),ylim(),format_y_ticks(), andfix_y_units(), and always returns thisSubplotso 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 viafix_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_axesisTrue.
- bar(*args, **kwargs)[source]¶
Plot a bar chart on the Subplot.
- Parameters:
data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x and y 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.
style (earthkit.plots.styles.Style, optional) – The Style to use for the bar chart. 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-compliantunitsmetadata in the data. See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.bar(). See the matplotlib bar documentation for the full list of accepted arguments.
- barbs(*args, **kwargs)[source]¶
Plot wind barbs on the Subplot.
- Parameters:
data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x, y, u, and v 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.
u (str, list, numpy.ndarray, or xarray.DataArray, optional) – The u 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.
v (str, list, numpy.ndarray, or xarray.DataArray, optional) – The v 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 wind barbs. 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-compliantunitsmetadata in the data. See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.barbs(). See the matplotlib barbs documentation for the full list of accepted arguments.
- 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-compliantunitsmetadata 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-compliantunitsmetadata in the data. See Unit conversion for examples.resample (earthkit.plots.resample.Resample, bool, or False, optional) – Controls resampling before plotting. Pass a
BilinearorNearestNeighbourinstance (orTruefor defaults) to reproject onto a regular target grid, orFalseto disable. Default isBilinear()(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-compliantunitsmetadata in the data. See Unit conversion for examples.resample (earthkit.plots.resample.Resample, bool, or False, optional) – Controls resampling before plotting. Pass a
BilinearorNearestNeighbourinstance (orTruefor defaults) to reproject onto a regular target grid, orFalseto disable. Default isBilinear()(1000 × 1000 pixels). Pass anUnstructuredinstance 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.Axesthat should receive the next plot call.Returns the top of the twin-axis stack when inside a
twin_axis()context manager, otherwise returns the primaryax. All pipeline render sites usesubplot.current_axso 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:
data_1 (xarray.DataArray or earthkit.data.core.Base, optional) – The data source for which to plot the envelope.
data_2 (xarray.DataArray or earthkit.data.core.Base, optional) – The data source for which to plot the envelope.
alpha (float, optional) – The alpha value of the envelope.
units (str, optional) – Target units for value conversion (e.g.
"celsius"). See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.fill_between(). See the matplotlib fill_between documentation for the full list of accepted arguments.
- property fig¶
The underlying
matplotlib.figure.Figureobject.
- property figure¶
The
earthkit.plots.components.figures.Figureobject.
- 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 precisionAny 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 precisionAny 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 aSource, style is resolved, and the result is attached as aLayer.- 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-compliantunitsmetadata 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, orTruefor defaults. Default isFalsefor 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:
data (xarray.DataArray or earthkit.data.core.Base, optional) – The data source for which to plot the labels.
label (str, optional) – The label to plot.
**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.annotate().
- 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:
data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x and y 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.
style (earthkit.plots.styles.Style, optional) – The Style to use for the line. If None, a Style is automatically generated based on the data.
**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.plot(). See the matplotlib plot documentation for the full list of accepted arguments.
- 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). IfNone, the left-most dimension is used. When quantiles isNone(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 keycapwidth(default1.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:
- 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:
- 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-compliantunitsmetadata 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, orTruefor defaults. Default isFalsefor 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:
data (xarray.DataArray or earthkit.data.core.Base) – The data to plot.
style (earthkit.plots.styles.Style, optional) – An explicit
Styleto use. IfNone, a style is detected automatically from the data metadata.units (str, optional) – Target units for value conversion (e.g.
"celsius"). See Unit conversion for examples.**kwargs – Additional keyword arguments forwarded to the resolved plot method.
- 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:
data (xarray.DataArray or earthkit.data.core.Base) – The data to plot. Must contain a quantile coordinate or dimension.
x (str or array-like, optional) – The x-axis coordinate name or values.
style (earthkit.plots.styles.Style, optional) – Style to apply. If
None, a style is generated automatically.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().
- 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:
data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x, y, u, and v 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.
u (str, list, numpy.ndarray, or xarray.DataArray, optional) – The u 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.
v (str, list, numpy.ndarray, or xarray.DataArray, optional) – The v 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 quiver 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-compliantunitsmetadata in the data. See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.quiver(). See the matplotlib quiver documentation for the full list of accepted arguments.
- 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).
- scatter(*args, **kwargs)[source]¶
Plot a scatter plot on the Subplot.
- Parameters:
data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x and y 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.
style (earthkit.plots.styles.Style, optional) – The Style to use for the scatter 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-compliantunitsmetadata in the data. See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.scatter(). See the matplotlib scatter documentation for the full list of accepted arguments.
- set_title(label=None, **kwargs)[source]¶
Set the title of the subplot.
Alias for
title()that matches the matplotlibset_titleconvention. Accepts the same arguments.
- 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
levelsin 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_labelif 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
highlightis also set. Defaults to"Control"iflabelis set andhighlightis set buthighlight_labelis 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 includelinewidths,alpha, andlabels.
- streamplot(*args, **kwargs)[source]¶
Plot streamlines on the Subplot.
- Parameters:
data (list, numpy.ndarray, xarray.DataArray, or earthkit.data.core.Base, optional) – The data to plot. If None, x, y, u, and v 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.
u (str, list, numpy.ndarray, or xarray.DataArray, optional) – The u 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.
v (str, list, numpy.ndarray, or xarray.DataArray, optional) – The v 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 stream 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-compliantunitsmetadata in the data. See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.streamplot(). See the matplotlib streamplot documentation for the full list of accepted arguments.
- 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
Nonean 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:
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 tricontour 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-compliantunitsmetadata in the data. See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.tricontour(). See the matplotlib tricontour documentation for the full list of accepted arguments.
- tricontourf(*args, **kwargs)[source]¶
Plot a filled tricontour 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 tricontour 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-compliantunitsmetadata in the data. See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.tricontourf(). See the matplotlib tricontourf documentation for the full list of accepted arguments.
- tripcolor(*args, **kwargs)[source]¶
Plot a tripcolor 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 tripcolor 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-compliantunitsmetadata in the data. See Unit conversion for examples.**kwargs – Additional keyword arguments passed to
matplotlib.axes.Axes.tripcolor(). See the matplotlib tripcolor documentation for the full list of accepted arguments.
- 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
indexvalues.- 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.
0is the first twin,1the second, etc. Defaults to0for the firsttwin_axis()call on a given position, incrementing automatically for each new call on that position.
- Returns:
A context manager that yields
selfso 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’slayerslist andfigureso that decoration methods called on the primary subplot (legend(),title(),show()) see layers from both axes.The twin’s
_chainableflag 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}". IfNone, 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_axesisTrueand multiple y-axes have been created by the auto-routing system, callingylabel()with no arguments labels all axes from their respective layer metadata in one call — so you rarely needaxis()for the common case.- Parameters:
label (str, optional) – The label text. Supports metadata format placeholders such as
"{variable_name}"and"{units}". IfNone, a label is inferred from the data. Pass an explicit string to set the same label on every axis (or useaxis()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.