dantro.plot_creators.ext_funcs.generic module

Generic, DAG-based plot functions for the ExternalPlotCreator and derived plot creators.

dantro.plot_creators.ext_funcs.generic.determine_plot_kind(d: Union[xarray.core.dataarray.DataArray, xarray.core.dataset.Dataset], *, kind: Union[str, dict], default_kind_map: dict = {1: 'line', 2: 'pcolormesh', 3: 'pcolormesh', 4: 'pcolormesh', 5: 'pcolormesh', 'with_hue': 'line', 'with_x_and_y': 'pcolormesh', 'dataset': 'scatter', 'fallback': 'hist'}, **plot_kwargs) → str[source]

Determines the plot kind to use for the given data. If kind: auto, this will determine the plot kind depending on the dimensionality of the data and other (potentially fixed) encoding specifiers. Otherwise, it will simply return kind.

What if layout encodings were partly fixed? There are two special cases where this is of relevance, and both these cases are covered explicitly:

  • If both x and y are given, line- or hist-like plot kinds are no longer possible; hence, a pcolormesh-like kind has to be chosen.

  • In turn, if hue was given, pcolormesh-like plot kinds are no longer applicable, thus a line-like argument needs to be chosen.

These two special cases are specified via the extra keys with_x_and_y and with_hue in the kind mapping.

A kind mapping may look like this:

1:               "line",
2:               "pcolormesh",
3:               "pcolormesh",
4:               "pcolormesh",
5:               "pcolormesh",
"with_hue":      "line",         # used when `hue` is explicitly set
"with_x_and_y":  "pcolormesh",   # used when _both_ `x` and `y` were set
"dataset":       "scatter",      # used for xr.Dataset-like data
"fallback":      "hist",         # used when none of the above matches
Parameters
  • d (Union[xr.DataArray, xr.Dataset]) – The data for which to determine the plot kind.

  • kind (Union[str, dict]) – The given kind argument. If it is auto, the kind_map is used to determine the kind from the dimensionality of d. If it is a dict, auto is implied and the dict is assumed to be a (ndim -> kind) mapping, updating the default_kind_map.

  • default_kind_map (dict, optional) – The default mapping to use for kind: auto, with keys being d’s dimensionality and values being the plot kind to use. There are two special keys, fallback and dataset. The value belonging to dataset is used for data that is dataset- like, i.e. does not have an ndim attribute. The value of fallback specifies the plot kind for data dimensionalities that match no other key.

  • **plot_kwargs – All remaining plot function arguments, including any layout encoding arguments that aim to fix a dimension; these are used to determine the with_hue and with_x_and_y special cases. Everything else is ignored.

Returns

The selected plot kind. This is equal to the given kind if

it was None or a string unequal to auto.

Return type

str

dantro.plot_creators.ext_funcs.generic.determine_encoding(dims: Union[List[str], Dict[str, int]], *, kind: str, auto_encoding: Union[bool, dict], default_encodings: dict, allow_y_for_x: List[str] = ('line',), plot_kwargs: dict) → dict[source]

Determines the layout encoding for the given plot kind and the available data dimensions (as specified by the dims argument).

If auto_encoding does not evaluate to true or kind is None, this function does nothing and simply returns all given plotting arguments.

Otherwise, it uses the chosen plot kind to associate layout specifiers with dimension names of d. The available layout encoding specifiers (x, y, col etc.) can be specified in two ways:

  • By default, default_encodings is used as a map from plot kind to a sequence of available layout specifiers.

  • If auto_encoding is a dictionary, the default map will be updated with that dictionary.

The association is done in the following way:

  1. Inspecting plot_kwargs, all layout encoding specifiers are extracted, dropping those that evaluate to False.

  2. The encodings mapping is determined (see above).

  3. The available dimension names are determined from dims.

  4. Depending on kind and the already fixed specifiers, the free encoding specifiers and dimension names are extracted.

  5. These free specifiers are associated with free dimension names, in order of descending dimension size.

Example: Assume, the available specifiers are ('x', 'y', 'col') and the data has dimensions dim0, dim1 and dim2. Let’s further say that y was already fixed to dim2, leaving x and col as free specifiers and dim0 and dim1 as free dimensions. With x being specified before col in the list of available specifiers, x would be associated to the remaining dimension with the larger size and col to the remaining one.

An encodings mapping may look like this:

"scatter":      ("hue", "col", "row"),
"line":         ("x", "hue", "col", "row"),
"step":         ("x", "col", "row"),
"contourf":     ("x", "y", "col", "row"),
"contour":      ("x", "y", "col", "row"),
"imshow":       ("x", "y", "col", "row"),
"pcolormesh":   ("x", "y", "col", "row"),
"hist":         (),

This function also implements automatic column wrapping, aiming to produce a more square-like figure with column wrapping. The prerequisites are the following:

  • The dims argument is a dict, containing size information

  • The col_wrap argument is given and set to "auto"

  • The col specifier is in use

  • The row specifier is not used, i.e. wrapping is possible

  • There are more than three columns

In such a case, col_wrap will be set to ceil(sqrt(num_cols)). Otherwise, the entry will be removed from the plot arguments.

Parameters
  • dims (Union[List[str], Dict[str, int]]) – The dimension names (and, if given as dict: their sizes) that are to be encoded. If no sizes are provided, the assignment order will be the same as in the given sequence of dimension names. If sizes are given, these will be used to sort the dimension names in descending order of their sizes.

  • kind (str) – The chosen plot kind. If this was None, will directly return, because auto-encoding information is missing.

  • auto_encoding (Union[bool, dict]) – Whether to perform auto-encoding. If a dict, will regard it as a mapping of available encodings and update default_encodings.

  • default_encodings (dict) – A map from plot kinds to available layout specifiers, e.g. {"line": ("x", "hue", "col", "row")}.

  • allow_y_for_x (List[str], optional) – A list of plot kinds for which the following replacement will be allowed: if a y specifier is given but no x specifier, the "x" in the list of available encodings will be replaced by a "y". This is to support plots that allow either an x or a y specifier, like the line kind.

  • plot_kwargs (dict) – The actual plot function arguments, including any layout encoding arguments that aim to fix a dimension. Everything else is ignored.

class dantro.plot_creators.ext_funcs.generic.make_facet_grid_plot(*, map_as: str, encodings: Tuple[str], supported_hue_styles: Tuple[str] = None, register_as_kind: Union[bool, str] = True, overwrite_existing: bool = False, drop_kwargs: Tuple[str] = ('_fg', 'meta_data', 'hue_style', 'add_guide'), **default_kwargs)[source]

Bases: object

This is a decorator class that transforms a plot function that works on a single axis into one that supports faceting. Additionally, it allows to register the plotting function with the generic facet grid plot by adding the callable to _FACET_GRID_FUNCS.

MAP_FUNCS = {'dataarray': <function make_facet_grid_plot.<lambda>>, 'dataarray_line': <function make_facet_grid_plot.<lambda>>, 'dataset': <function make_facet_grid_plot.<lambda>>}
DEFAULT_ENCODINGS = ('col', 'row', 'frames')
DEFAULT_DROP_KWARGS = ('_fg', 'meta_data', 'hue_style', 'add_guide')
__init__(*, map_as: str, encodings: Tuple[str], supported_hue_styles: Tuple[str] = None, register_as_kind: Union[bool, str] = True, overwrite_existing: bool = False, drop_kwargs: Tuple[str] = ('_fg', 'meta_data', 'hue_style', 'add_guide'), **default_kwargs)[source]

Initialize the decorator, making the decorated function capable of performing a facet grid plot.

Parameters
  • map_as (str) – Which mapping to use. Available: dataset, dataarray and dataarray_line.

  • encodings (Tuple[str]) – The encodings supported by the wrapped plot function, e.g. ("x", "hue").

  • supported_hue_styles (Tuple[str]) – Which hue styles are supported by the wrapped plot function. It is suggested to set this value if mapping via dataset or dataarray_line in order to disallow configurations that will not work with the wrapped plot function. If set to None, no check will be done.

  • register_as_kind (Union[bool, str], optional) – If boolean, controls whether to register the wrapped function with the generic facet grid plot, using its own name. If a string, uses that name for registration.

  • overwrite_existing (bool, optional) – Whether to overwrite an existing registration in _FACET_GRID_FUNCS. If False, an existing entry of the same register_as_kind value will lead to an error.

  • drop_kwargs (Tuple[str], optional) – Which keyword arguments to drop before invocation of the wrapped function; this can be useful to trim down the signature of the wrapped function.

  • **default_kwargs – Additional arguments that are passed to the single-axis plotting function. These are used both when calling it via the selected mapping function and when invoking it without a facet grid. These are recursively updated with those given upon plot function invocation.

parse_wpf_kwargs(data, **kwargs) → dict[source]

Parses the keyword arguments in preparation for invoking the wrapped plot function. This can happen both in context of a facet grid mapping and a single invocation.

__call__(plot_single_axis: Callable) → Callable[source]

Generates a standalone DAG-based plotting function that supports faceting. Additionally, integrates it as kind for the general facet grid plotting function by adding it to the global _FACET_GRID_FUNCS dictionary.

dantro.plot_creators.ext_funcs.generic.errorbar(*, data: dict, hlpr: dantro.plot_creators._plot_helper.PlotHelper, x: str = None, hue: str = None, frames: str = None, auto_encoding: Union[bool, dict] = False, hue_fstr: str = '{value:}', use_bands: bool = False, fill_between_kwargs: dict = None, suptitle_kwargs: dict = None, **errorbar_kwargs) → None[source]

A DAG-based generic errorbar plot.

Deprecated since version 0.15: This function is deprecated. Instead, the more capable and generic errorbars() function or facet_grid() with kind: errorbars can be used. The interface is mostly the same, but data is expected as xr.Dataset instead of as two separate arrays.

This plot expects data to be provided via Plot Data Selection. Expected tags are y and yerr and both should be labelled xarray.DataArray objects. Depending on the given layout encoding specifiers (x, hue, and frames), data may be 1D, 2D, or 3D. The auto-encoding feature is supported.

Uses plot_errorbar() for plotting individual lines.

Parameters
  • data (dict) – The DAG results dict which should contain entries y and yerr, both labelled xr.DataArray objects.

  • hlpr (PlotHelper) – The PlotHelper

  • x (str, optional) – The dimension to represent on the x-axis. If not given, it will be inferred. If no coordinates are associated with the dimension, trivial coordinates are used.

  • hue (str, optional) – Name of the dimension to respresent via the hue colors of the errorbar lines. For adjusting the property cycle of the lines, see Adjusting a plot’s style.

  • frames (str, optional) – Name of the dimension to represent via the frames of an animation. If given, this will automatically enable animation mode and requires animation arguments being specified in the plot configuration. See Animations.

  • auto_encoding (Union[bool, dict], optional) – Whether to choose the layout encoding options automatically, i.e. select x, hue, and frames according to the given data’s dimensionality. For further options, can pass a dict. See Auto-encoding of plot layout for more info.

  • hue_fstr (str, optional) – A format string for the labels used when creating a plot with hue specified. Available keys: dim (which is equivalent to hue), and value, which is set to the value of the corresponding coordinate along that dimension.

  • use_bands (bool, optional) – Whether to use error bands instead of bars

  • fill_between_kwargs (dict, optional) – If using error bands, these arguments are passed on to hlpr.ax.fill_between. This would be the place to adjust alpha; if not given, the corresponding line’s alpha value will be used, reduced to 20%.

  • suptitle_kwargs (dict, optional) – Key passed on to the PlotHelper’s set_suptitle helper function. Only used if animations are enabled. The title entry can be a format string with the following keys, which are updated for each frame of the animation: dim, value. Default: {dim:} = {value:.3g}.

  • **errorbar_kwargs – Passed on to hlpr.ax.errorbar

Returns

None

Raises

ValueError – Upon badly shaped data

dantro.plot_creators.ext_funcs.generic.errorbands(*, data: dict, hlpr: dantro.plot_creators._plot_helper.PlotHelper, **kwargs)[source]

A DAG-based generic errorbands plot.

Invokes errorbar() with use_bands = True. See there for available arguments.

dantro.plot_creators.ext_funcs.generic.facet_grid(*, data: dict, hlpr: dantro.plot_creators._plot_helper.PlotHelper, kind: Union[str, dict] = None, frames: str = None, auto_encoding: Union[bool, dict] = False, suptitle_kwargs: dict = None, squeeze: bool = True, **plot_kwargs)[source]

A generic facet grid plot function for high dimensional data.

This function calls the data['data'].plot function if no plot kind is given, otherwise data['data'].plot.<kind>. It is designed for plotting with xarray objects, i.e. xr.DataArray and xr.Dataset. Specifying the kind of plot requires the data to be of one of those types and have a dimensionality that can be represented in these plots. See the correponding API documentation for more information.

In most cases, this function creates a so-called FacetGrid object that automatically layouts and chooses a visual representation that fits the dimensionality of the data. To specify which data dimension should be represented in which way, it supports a declarative syntax: via the optional keyword arguments x, y, row, col, and/or hue (available options are listed in the corresponding plot function documentation), the representation of the data dimensions can be selected. This is referred to as “layout encoding”.

dantro not only wraps this interface, but adds the following functionality:

  • the frames layout encoding argument, which behaves in the same way as the other encodings, but leads to an animation being generated, thus opening up one further dimension of representation,

  • the auto_encoding feature, which allows to select layout- encodings automatically,

  • and the kind: 'auto' option, which can be used in conjunction with auto_encoding to choose the plot kind automatically as well.

  • allows col_wrap: 'auto', which selects the value such that the figure becomes more square-like (requires auto_encoding: true)

  • allows to register additional plot kind values that create plots with a custom single-axis plotting function, using the make_facet_grid_plot decorator.

For details about auto-encoding and how the plot kind is chosen, see determine_encoding() and determine_plot_kind().

Note

When specifying frames, the animation arguments need to be specified. See here for more information on the expected animation parameters.

The value of the animation.enabled key is not relevant for this function; it will automatically enter or exit animation mode, depending on whether the frames argument is given or not. This uses the animation mode switching feature.

Note

Internally, this function calls .squeeze on the selected data, thus being more tolerant with data that has size-1 dimension coordinates. To suppress this behaviour, set the squeeze argument accordingly.

Warning

Depending on kind and the dimensionality of the data, some plot functions might create their own figure, disregarding any previously set up figure. This includes the figure from the plot helper.

To control figure aesthetics, you can either specify matplotlib RC style parameters (via the style argument), or you can use the plot_kwargs to pass arguments to the respective plot functions. For the latter, refer to the respective documentation to find out about available arguments.

Parameters
  • data (dict) – The data selected by the data transformation framework, expecting the data key.

  • hlpr (PlotHelper) – The plot helper

  • kind (str, optional) – The kind of plot to use. Options are: contourf, contour, imshow, line, pcolormesh, step, hist, scatter, errorbars and any plot kinds that were additionally registered via the make_facet_grid_plot decorator. With auto, dantro chooses an appropriate kind by itself; this setting is useful when also using the auto_encoding feature; see Automatically selecting plot kind for more information. If None is given, xarray automatically determines it using the dimensionality of the data, frequently falling back to hist for higher-dimensional data or lacking specifiers.

  • frames (str, optional) – Data dimension from which to create animation frames. If given, this results in the creation of an animation. If not given, a single plot is generated. Note that this requires animation options as part of the plot configuration.

  • auto_encoding (Union[bool, dict], optional) – Whether to choose the layout encoding options automatically. For further options, can pass a dict. See Auto-encoding of plot layout for more info.

  • suptitle_kwargs (dict, optional) – Key passed on to the PlotHelper’s set_suptitle helper function. Only used if animations are enabled. The title entry can be a format string with the following keys, which are updated for each frame of the animation: dim, value. Default: {dim:} = {value:.3g}.

  • squeeze (bool, optional) – whether to squeeze the data before plotting, such that size-1 dimensions do not take up encoding dimensions.

  • **plot_kwargs – Passed on to <data>.plot or <data>.plot.<kind> These should include the layout encoding specifiers (x, y, hue, col, and/or row).

Raises
  • AttributeError – Upon unsupported kind value

  • ValueError – Upon any upstream error in invocation of the xarray plotting capabilities. This wraps the given error message and provides additional information that helps to track down why the plotting failed.

dantro.plot_creators.ext_funcs.generic.errorbars(*, data: dict, hlpr: dantro.plot_creators._plot_helper.PlotHelper, **kwargs)[source]