dantro.plot_creators._plot_helper module

This module implements the PlotHelper class

class dantro.plot_creators._plot_helper.temporarily_changed_axis(hlpr: dantro.plot_creators._plot_helper.PlotHelper, tmp_ax_coords: Tuple[int, int] = None)[source]

Bases: object

Context manager to temporarily change an axis in the PlotHelper

__init__(hlpr: dantro.plot_creators._plot_helper.PlotHelper, tmp_ax_coords: Tuple[int, int] = None)[source]

Initialize the context manager.

Parameters
  • hlpr (PlotHelper) – The plot helper of which to select a temporary axis

  • tmp_ax_coords (Tuple[int], optional) – The coordinates of the temporary axis. If not given, will not change the axis.

__enter__()[source]

Enter the context, selecting a temporary axis

__exit__(*args)[source]

Change back to the initial axis. Errors are not handled.

dantro.plot_creators._plot_helper.coords_match(coords: Tuple[int], *, match: Union[tuple, str], full_shape: Tuple[int]) → bool[source]

Whether a coordinate is matched by a coordinate match tuple.

Allowed values in the coordinate match tuple are:

  • integers: regarded as coordinates. If negative or exceeding the full

    shape, these are wrapped around.

  • Ellipsis: matches all coordinates

  • None: alias for Ellipsis

Parameters
  • coords (Tuple[int]) – The coordinate to match

  • match (Union[tuple, str]) – The match tuple, where None is interpreted as an Ellipsis and negative values are wrapped around by full_shape. Can also be ‘all’, which is equivalent to a (None, None) tuple. Can also be a list, which is then converted to a tuple.

  • full_shape (Tuple[int]) – The full shape of the axes; needed to wrap around negative values in match.

Returns

Whether coords matches match

Return type

bool

Raises
  • TypeErrormatch not being a tuple or a list

  • ValueError – Any of the arguments not being 2-tuples.

dantro.plot_creators._plot_helper.remove_duplicate_handles_labels(h: list, l: list) → Tuple[list, list][source]

Returns new aligned lists of handles and labels from which duplicates (identified by label) are removed.

This maintains the order and association by keeping track of seen items; see https://stackoverflow.com/a/480227/1827608 for more information.

Parameters
  • h (list) – List of artist handles

  • l (list) – List of labels

Returns

handles and labels

Return type

Tuple[list, list]

dantro.plot_creators._plot_helper.gather_handles_labels(mpo) → Tuple[list, list][source]

Uses .findobj to search a figure or axis for legend objects and returns lists of handles and (string) labels.

dantro.plot_creators._plot_helper.prepare_legend_args(h, l, *, custom_labels: list, hiding_threshold: int) → Tuple[list, list, bool][source]
dantro.plot_creators._plot_helper.calculate_space_needed_hv(fig, obj, *, spacing_h: float = 0.02, spacing_v: float = 0.02) → Tuple[float, float][source]

Calculates the horizontal and vertical space needed for an object in this figure.

Note

This will invoke fig.draw two times and resize the figure!

Parameters
  • fig – The figure

  • obj – The object in that figure to fit

  • spacing_h (float, optional) – Added to space needed (in inches)

  • spacing_v (float, optional) – Added to space needed (in inches)

Returns

the horizontal and vertical space needed to fit

into the figure (in inches).

Return type

Tuple[float, float]

dantro.plot_creators._plot_helper._set_tick_locators_or_formatters(*, ax: matplotlib.pyplot.axis, kind: str, x: dict = None, y: dict = None)[source]

Sets the tick locators or formatters Look at the documentation of the _hlpr_set_tick_{locators/formatters} functions below for more information, respectively.

Parameters
  • ax (plt.axis) – The axis

  • kind (str) – The kind. Valid options are: ‘locator’, ‘formatter’

  • x (dict, optional) – The configuration of the x-axis tick locator/formatter

  • y (dict, optional) – The configuration of the y-axis tick locator/formatter

dantro.plot_creators._plot_helper._resolve_lazy_imports(d: dict)[source]

In-place resolves lazy imports in the given dict

dantro.plot_creators._plot_helper.parse_function_specs(*, _hlpr: dantro.plot_creators._plot_helper.PlotHelper, _funcs: Dict[str, Callable] = {}, _shared_kwargs: dict = {}, function: Union[str, Callable, Tuple[str, str]], args: list = None, pass_axis_object_as: str = None, pass_helper: bool = False, **func_kwargs) → Tuple[str, Callable, list, dict][source]

Parses a function specification used in the invoke_function helper. If function is a string it is looked up from the _funcs dict.

Parameters
  • _hlpr (PlotHelper) – The currently used PlotHelper instance

  • _funcs (Dict[str, Callable]) – The lookup dictionary for callables

  • _shared_kwargs (dict, optional) – Shared kwargs that passed on to all multiplot functions. They are recursively updated with the individual plot functions’ func_kwargs.

  • function (Union[str, Callable, Tuple[str, str]]) – The callable function object or the name of the plot function to look up. If given as 2-tuple (module, name), will attempt an import of that module.

  • args (list, optional) – The positional arguments for the plot function

  • pass_axis_object_as (str, optional) – If given, will add a keyword argument with this name to pass the current axis object to the to-be-invoked function.

  • pass_helper (bool, optional) – If true, passes the helper instance to the function call as keyword argument hlpr.

  • **func_kwargs (dict) – The function kwargs to be passed on to the function object.

Returns

A tuple of function name, callable,

positional arguments, and keyword arguments.

Return type

Tuple[str, Callable, list, dict]

dantro.plot_creators._plot_helper.parse_and_invoke_function(*, hlpr: dantro.plot_creators._plot_helper.PlotHelper, funcs: Dict[str, Callable], shared_kwargs: dict, func_kwargs: dict, show_hints: bool, call_num: int, caution_func_names: List[str] = ()) → Any[source]

Parses function arguments and then calls the multiplot function.

Parameters
  • hlpr (PlotHelper) – The currently used PlotHelper instance

  • funcs (Dict[str, Callable]) – The lookup dictionary for the functions

  • shared_kwargs (dict) – Arguments shared between function calls

  • func_kwargs (dict) – Arguments for this function in particular

  • show_hints (bool) – Whether to show hints

  • call_num (int) – The number of this plot, for easier identification

  • caution_func_names (List[str], optional) – a list of function names that will trigger a log message if no function kwargs were given.

Returns

return value of plot function call

Return type

Any

class dantro.plot_creators._plot_helper.PlotHelper(*, out_path: str, helper_defaults: dict = None, update_helper_cfg: dict = None, raise_on_error: bool = True, animation_enabled: bool = False)[source]

Bases: object

The PlotHelper takes care of the figure setup and saving and allows accessing matplotlib utilities through the plot configuration.

_SPECIAL_CFG_KEYS = ('setup_figure', 'save_figure')
_FIGURE_HELPERS = ('align_labels', 'set_suptitle', 'set_figlegend', 'subplots_adjust', 'figcall')
__init__(*, out_path: str, helper_defaults: dict = None, update_helper_cfg: dict = None, raise_on_error: bool = True, animation_enabled: bool = False)[source]

Initialize a Plot Helper with a certain configuration.

This configuration is the so-called “base” configuration and is not axis-specific. There is the possibility to specify axis-specific configuration entries.

All entries in the helper configuration are deemed ‘enabled’ unless they explicitly specify enabled: false in their configuration.

Parameters
  • out_path (str) – path to store the created figure. This may be an absolute path or a relative path; the latter is regarded as relative to the current working directory. The home directory indicator ~ is expanded.

  • helper_defaults (dict, optional) – The basic configuration of the helpers.

  • update_helper_cfg (dict, optional) – A configuration used to update the existing helper defaults

  • raise_on_error (bool, optional) – Whether to raise on an exception created on helper invocation or just log the error

  • animation_enabled (bool, optional) – Whether animation mode is enabled.

property _axis_cfg

Return the configuration for the current axis; not a deep copy!

property axis_cfg

Returns a deepcopy of the current axis’ configuration.

property base_cfg

Returns a deepcopy of the base configuration, i.e. the configuration that is not axis-specific.

property fig

Returns the current figure

property ax

Returns the current axis of the associated figure

property ax_coords

Returns the current axis coordinates within a subfigure in shape (col, row).

For example, the (0, 0) coordinate refers to the top left subplot of the figure. (1, 2) is the axis object in the second column, third row.

property axes

Returns the axes array, which is of shape (#cols, #rows).

The (0, 0) axis refers to the top left subplot of the figure.

property available_helpers

List of available helper names

property enabled_helpers

Returns a list of enabled helpers for the current axis

property enabled_figure_helpers

Returns a list of enabled figure-level helpers

property out_path

Returns the output path of the plot

property animation_enabled

Whether animation mode is currently enabled or not

property animation_update

Returns the animation update generator callable

property invoke_before_grab

Whether the helpers are to be invoked before grabbing each frame of an animation.

property raise_on_error

Whether the PlotHelper was configured to raise exceptions

property axis_handles_labels

Returns the tracked axis handles and labels for the current axis

property all_handles_labels

Returns all associated handles and labels

property axis_is_empty

Returns true if the current axis is empty, i.e. has no artists added to it. This is basically the inverse of mpl.axes.Axes.has_data.

attach_figure_and_axes(*, fig, axes, skip_if_identical: bool = False) → None[source]

Attaches the given figure and axes to the PlotHelper. This method replaces an existing figure and existing axes with the ones given.

As the PlotHelper relies on axes being accessible via coordinate pairs, multiple axes must be passed as two-dimensional array-like. Since the axes are internally stored as numpy array, the axes-grid must be complete.

Note that by closing the old figure the existing axis-specific config and all existing axes are destroyed. In other words: All information previously provided via the provide_defaults and the mark_* methods is lost. Therefore, if needed, it is recommended to call this method at the beginning of the plotting function.

Note

This function assumes multiple axes to be passed in (y,x) format (as e.g. returned by matplotlib.pyplot.subplots with squeeze set to False) and internally transposes the axes-grid such that afterwards it is accessible via (x,y) coordinates.

Parameters
  • fig – The new figure which replaces the existing.

  • axes – single axis or 2d array-like containing the axes

  • skip_if_identical (bool, optional) – If True, will check if the given fig is identical to the already associated figure; if so, will do nothing. This can be useful if one cannot be sure if the figure was already associated. In such a case, note that the axes argument is completely ignored.

Raises

ValueError – On multiple axes not being passed in 2d format.

Returns

None

setup_figure(**update_fig_kwargs)[source]

Sets up a matplotlib figure instance and axes with the given configuration (by calling matplotlib.pyplot.subplots) and attaches both to the PlotHelper.

If the scale_figsize_with_subplots_shape option is enabled here, this method will also take care of scaling the figure accordingly.

Parameters

**update_fig_kwargs – Parameters that are used to update the figure setup parameters stored in setup_figure.

save_figure(*, close: bool = True)[source]

Saves and (optionally, but default) closes the current figure

Parameters

close (bool, optional) – Whether to close the figure after saving.

close_figure()[source]

Closes the figure and disassociates it from the helper. This method has no effect if no figure is currently associated.

This also removes the axes objects and deletes the axis-specific configuration. All information provided via provide_defaults and the mark_* methods is lost.

select_axis(col: int = None, row: int = None, *, ax=None)[source]

Sets the current axis.

Setting the axis can happen in three ways, depending on the arguments:

  • The axis object at the given col and row coordinates.

  • An explicitly given axis object (if ax is given)

  • The current axis (if all arguments are None)

This method can be used to change to a different associated axis to continue plotting on that axis.

Calling this method may also become necessary if the current axis is changed in a part of the program where the plot helper is not involved; in such a case, the currently selected axis may have been changed directly via the matplotlib interface. This method can then be used to synchronize the two again.

Note

The col and row values are wrapped around according to the shape of the associated axes array, thereby allowing to specify them as negative values for indexing from the back.

Parameters
  • col (int, optional) – The column to select, i.e. the x-coordinate. Can be negative, in which case it indexes backwards from the last column.

  • row (int, optional) – The row to select, i.e. the y-coordinate. Can be negative, in which case it indexes backwards from the last row.

  • ax (optional) – If given this axis object, tries to look it up from the associated axes array.

Raises

ValueError – On failing to set the current axis or if the given axis object or the result of plt.gca() was not part of the associated axes array. To associate the correct figure and axes, use attach_figure_and_axes().

coords_iter(*, match: Union[tuple, str] = None) → Generator[Tuple[int], None, None][source]

Returns a generator to iterate over all coordinates that match match.

Parameters

match (Union[tuple, str]) – The coordinates to match; those that do not match this pattern (evaluated by coords_match function) will not be yielded. If not given, will iterate only over the currently selected axis.

Yields

Generator[Tuple[int], None, None] – The axis coordinates generator

_invoke_helper(helper_name: str, *, axes: Union[tuple, str] = None, mark_disabled_after_use: bool = True, raise_on_error: bool = None, **update_kwargs) → None[source]

Invokes a single helper on the specified axes, if it is enabled, and marks it disabled afterwards. The given update parameters are used to update the existing configuration.

Unlike the public invoke_helper method, this method checks for whether the helper is enabled, while the public method automatically assumes it is meant to be enabled.

Parameters
  • helper_name (str) – helper which is invoked

  • axes (Union[tuple, str], optional) – A coordinate match tuple of the axes to invoke this helper on. If not given, will invoke only on the current axes.

  • mark_disabled_after_use (bool, optional) – If True, the helper is marked as disabled after invoking it

  • raise_on_error (bool, optional) – If given, overwrites the default controlled via the raise_on_error attribute.

  • **update_kwargs – Update parameters for this specific plot helper. Note that these do not persist, but are only used for this invocation.

Raises
  • PlotHelperErrors – On failing plot helper invocations

  • ValueError – No matching helper function defined

invoke_helper(helper_name: str, *, axes: Union[tuple, str] = None, mark_disabled_after_use: bool = True, raise_on_error: bool = None, **update_kwargs)[source]

Invokes a single helper on the specified axes.

Parameters
  • helper_name (str) – The name of the helper to invoke

  • axes (Union[tuple, str], optional) – A coordinate match tuple of the axes to invoke this helper on. If not given, will invoke only on the current axes.

  • mark_disabled_after_use (bool, optional) – If True, the helper is marked as disabled after the invocation.

  • raise_on_error (bool, optional) – If given, overwrites the default controlled via the raise_on_error attribute.

  • **update_kwargs – Update parameters for this specific plot helper. Note that these do not persist, but are only used for this invocation.

Raises

PlotHelperErrors – On failing plot helper invocation

invoke_helpers(*helper_names, axes: Union[tuple, str] = None, mark_disabled_after_use: bool = True, raise_on_error: bool = None, **update_helpers)[source]

Invoke all specified helpers on the specified axes.

Parameters
  • *helper_names – The helper names to invoke

  • axes (Union[tuple, str], optional) – A coordinate match tuple of the axes to invoke this helper on. If not given, will invoke only on the current axes.

  • mark_disabled_after_use (bool, optional) – Whether to mark helpers disabled after they were used.

  • raise_on_error (bool, optional) – If given, overwrites the default controlled via the raise_on_error attribute.

  • **update_helpers – Update parameters for all plot helpers. These have to be grouped under the name of the helper in order to be correctly associated. Note that these do not persist, but are only used for this invocation.

Raises

PlotHelperErrors – On failing plot helper invocations

invoke_enabled(*, axes: Union[tuple, str] = None, mark_disabled_after_use: bool = True, raise_on_error: bool = None, **update_helpers)[source]

Invokes all enabled helpers with their current configuration on the matching axes and all enabled figure-level helpers on the figure.

Internally, this first invokes all figure-level helpers and then calls invoke_helpers() with all enabled helpers for all axes matching the axes argument.

Note

When setting mark_disabled_after_use = False, this will lead to figure-level helpers being invoked multiple times. As some of these helpers do not allow multiple invocation, invoking this method a second time might fail if not disabling them as part of the first call to this method.

Parameters
  • axes (Union[tuple, str], optional) – A coordinate match tuple of the axes to invoke this helper on. If not given, will invoke only on the current axes.

  • mark_disabled_after_use (bool, optional) – If True, the helper is marked as disabled after the invocation.

  • raise_on_error (bool, optional) – If given, overwrites the default controlled via the raise_on_error attribute.

  • **update_helpers – Update parameters for all plot helpers. These have to be grouped under the name of the helper in order to be correctly associated. Note that these do not persist, but are only used for this invocation.

Raises

PlotHelperErrors – On failing plot helper invocations

provide_defaults(helper_name: str, *, axes: Union[tuple, str] = None, mark_enabled: bool = True, **update_kwargs)[source]

Update or add a single entry to a helper’s configuration.

Parameters
  • helper_name (str) – The name of the helper whose config is to change

  • axes (Union[tuple, str], optional) – A coordinate match tuple of the axes to invoke this helper on. If not given, will invoke only on the current axes.

  • mark_enabled (bool, optional) – Whether to mark the helper enabled by providing defaults

  • **update_kwargs – dict containing the helper parameters with which the config is updated recursively

mark_enabled(*helper_names, axes: Union[tuple, str] = None)[source]

Marks the specified helpers as enabled for the specified axes.

Parameters
  • *helper_names – Helpers to be enabled

  • axes (Union[tuple, str], optional) – A coordinate match tuple of the axes to invoke this helper on. If not given, will invoke only on the current axes.

mark_disabled(*helper_names, axes: Union[tuple, str] = None)[source]

Marks the specified helpers as disabled for the specified axes.

Parameters
  • *helper_names – Helpers to be disabled

  • axes (Union[tuple, str], optional) – A coordinate match tuple of the axes to invoke this helper on. If not given, will invoke only on the current axes.

track_handles_labels(handles: list, labels)[source]

Keep track of legend handles and/or labels for the current axis.

Parameters
  • handles (list) – The handles to keep track of

  • labels (list) – The associated labels

register_animation_update(update_func: Callable, *, invoke_helpers_before_grab: bool = False)[source]

Registers a generator used for animations.

Parameters
  • update_func (Callable) – Generator object over which is iterated over to create an animation. This needs

  • invoke_helpers_before_grab (bool, optional) – Whether to invoke all enabled plot helpers before grabbing a frame. This should be set to True if the animation update function overwrites the effects of the previously applied helpers.

enable_animation()[source]

Can be invoked to enter animation mode. An action is only performed if the helper is not currently in animation mode.

Raises

EnterAnimationMode – Conveys to the plot creator that animation mode is to be entered.

disable_animation()[source]

Can be invoked to exit animation mode. An action is only performed if the helper is currently in animation mode.

Raises

ExitAnimationMode – Conveys to the plot creator that animation mode should be left.

_compile_axis_specific_cfg() → Dict[tuple, dict][source]

With a figure set up, compiles the axis-specific helper config.

_raise_on_invalid_helper_name(*helper_names: str, special_cfg_keys_allowed: bool = False)[source]

Makes sure the given helper names are valid.

Parameters
  • *helper_names (str) – Names of the helpers to check

  • special_cfg_keys_allowed (bool, optional) – Whether to regard the special configuration keys as valid or not.

Raises

ValueError – On invalid helper name

_handle_errors(*errors, raise_on_error: bool = None)[source]

Helper method to handle errors

_find_axis_coords(ax) → Tuple[int, int][source]

Find the coordinates of the given axis object in the axes array

_hlpr_align_labels(*, x: bool = True, y: bool = True)[source]

Aligns axis labels in the whole figure

_hlpr_set_suptitle(*, title: str = None, margin: float = 0.025, **title_kwargs)[source]

Set the figure title, i.e. matplotlib.Figure.suptitle.

This figure-level helper automatically vertically adjusts the subplot sizes to fit the suptitle into the figure without overlapping. This is not done if the title string is empty or if the y-position is specified via the y argument. When repetitively invoking this helper on the same figure, the subplot sizes are re-adjusted each time.

Parameters
  • title (str, optional) – The title to be set

  • margin (float, optional) – An additional vertical margin between the figure and the suptitle.

  • **title_kwargs – Passed on to fig.suptitle

_hlpr_set_figlegend(*, gather_from_fig: bool = False, custom_labels: Sequence[str] = (), hiding_threshold: int = None, loc='center right', margin: float = 0.015, **legend_kwargs)[source]

Sets a figure legend.

As a source of handles and labels, uses all those tracked via track_handles_labels(). Furthermore, gather_from_fig controls whether to additionally retrieve already existing handles and labels from any legend used within the figure, e.g. on all of the axes.

For legend locations on the right side of the figure, this will additionally adjust the subplot shape to accomodate for the figure legend without overlapping. This is not done for other loc values.

If no handles could be retrieved by the above procedure, no figure legend will be added.

Parameters
  • gather_from_fig (bool, optional) – Whether to extract figure handles and labels from already existing legends used in the figure.

  • custom_labels (Sequence[str], optional) – Custom labels to assign for the given handles.

  • hiding_threshold (int, optional) – If there are more handles or labels available than the threshold, no figure legend will be added.

  • loc (str, optional) – The location of the figure legend. Note that figure adjustments are done for a figure legend on the right side of the figure; these are not done if the figure is located somewhere else, which might lead to it overlapping with other axes.

  • margin (float, optional) – An additional horizontal margin between the figure legend and the axes.

  • **legend_kwargs – Passed on to fig.legend.

Raises

RuntimeError – If a figure legend was already set via the helper.

_hlpr_subplots_adjust(**kwargs)[source]

Invokes subplots_adjust on the whole figure

_hlpr_figcall(*, functions: Sequence[dict], **shared_kwargs)[source]

Figure-level helper that can be used to call multiple functions. This helper is invoked before the axis-level helper.

See _hlpr_call() for more information and examples.

Parameters
  • functions (Sequence[dict]) – A sequence of function call specifications. Each dict needs to contain at least the key function which determines which function to invoke. Further arguments are parsed into the positional and keyword arguments of the to-be-invoked function.

  • **shared_kwargs – Passed on as keyword arguments to all function calls in functions.

_hlpr_set_title(*, title: str = None, **title_kwargs)[source]

Sets the title of the current axis.

Parameters
  • title (str, optional) – The title to be set

  • **title_kwargs – Passed on to ax.set_title

_hlpr_set_labels(*, x: Union[str, dict] = None, y: Union[str, dict] = None, only_label_outer: bool = False)[source]

Sets the x and y label of the current axis.

Parameters
  • x (Union[str, dict], optional) – Either the label as a string or a dict with key label, where all further keys are passed on to plt.set_xlabel

  • y (Union[str, dict], optional) – Either the label as a string or a dict with key label, where all further keys are passed on to plt.set_ylabel

  • only_label_outer (bool, optional) – If true, call ax.label_outer such that only tick labels on “outer” axes are visible: x-labels are only kept for subplots on the last row; y-labels only for subplots on the first column. Note that this applies to both axes and may lead to existing axes being hidden.

_hlpr_set_limits(*, x: Union[Sequence[Union[float, str]], dict] = None, y: Union[Sequence[Union[float, str]], dict] = None)[source]

Sets the x and y limit for the current axis.

The x and y arguments can have the following form:

  • None: Limits are not set

  • sequence: Specify lower and upper values

  • dict: Expecting keys lower and/or upper

The sequence or dict values can be:

  • None Set automatically / do not set

  • numeric Set to this value explicitly

  • min Set to the data minimum value on that axis

  • max Set to the data maximum value on that axis

Parameters
  • x (Union[Sequence[Union[float, str]], dict], optional) – The limits to set on the x-axis

  • y (Union[Sequence[Union[float, str]], dict], optional) – The limits to set on the y-axis

_hlpr_set_legend(*, use_legend: bool = True, gather_from_fig: bool = False, custom_labels: Sequence[str] = (), hiding_threshold: int = None, **legend_kwargs)[source]

Sets a legend for the current axis.

As a first step, this helper tries to extract all relevant legend handles and labels. If a legend was set previously and no handles and labels could be extracted in the typical way (i.e., using the ax.get_legend_handles_labels method) it will be attempted to retrieve them from existing matplotlib.legend.Legend objects on the current axis. If gather_from_fig is given, the whole figure will be inspected, regardless of whether handles were found previously.

Additionally, all axis-specific handles and labels tracked via track_handles_labels() will always be added.

Note

  • If no handles can be found, the legend is hidden, also meaning that the legend_kwargs will not be passed on.

  • During gathering of handles and labels from the current axis or the figure, duplicates will be removed; duplicates are detected via their label strings, not via their handle.

Hint

To set a figure-level legend, use the set_figlegend helper.

Parameters
  • use_legend (bool, optional) – Whether to set a legend or not. If False, the legend will be removed.

  • gather_from_fig (bool, optional) – If set, will gather legend handles and labels from the whole figure. This can be useful to set if the relevant information is found on another axis or in a figure legend.

  • custom_labels (Sequence[str], optional) – If given, use these labels and associate them with existing labels. Note that if fewer labels are given than handles are available, those without a label will not be drawn.

  • hiding_threshold (int, optional) – If given, will hide legends that have more than this number of handles registered.

  • **legend_kwargs – Passed on to ax.legend

_hlpr_set_texts(*, texts: Sequence[dict])[source]

Sets multiple text elements for the current axis.

Example configuration:

set_texts:
  texts:
    - x: 0
      y: 1
      s: some text
      # ... more arguments to plt.text
Parameters

texts (Sequence[dict]) – A sequence of text specifications, that are passed to matplotlib.pyplot.text

_hlpr_annotate(*, annotations: Sequence[dict])[source]

Sets multiple annotations for the current axis.

Example configuration:

annotate:
  annotations:
    - xy: [1, 3.14159]
      text: this is π
      xycoords: data
      # ... more arguments to plt.annotate
    - xy: [0, 0]
      xycoords: data
      text: this is zero
      xytext: [0.1, 0.1]
      arrowprops:
        facecolor: black
        shrink: 0.05
Parameters

annotations (Sequence[dict]) – A sequence of annotation parameters which will be passed to matplotlib.pyplot.annotate

_hlpr_set_hv_lines(*, hlines: list = None, vlines: list = None)[source]

Sets one or multiple horizontal or vertical lines.

Parameters
  • hlines (list, optional) – list of numeric positions of the lines or or list of dicts with key pos determining the position, key limits determining the relative limits of the line, and all additional arguments being passed on to the matplotlib function.

  • vlines (list, optional) – list of numeric positions of the lines or or list of dicts with key pos determining the position, key limits determining the relative limits of the line, and all additional arguments being passed on to the matplotlib function.

_hlpr_set_scales(*, x: Union[str, dict] = None, y: Union[str, dict] = None)[source]

Sets the scales for the current axis

The arguments are used to call ax.set_xscale or ax.set_yscale, respectively. For string-like arguments, the value is directly used to set the scale for that axis, e.g. linear, log, symlog. Otherwise, dict-like arguments are expected where a scale key is present and defines which type of scale to use. All further arguments are passed on; these are relevant for the symmetrical logarithmic scale, for example.

For more information, see https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xscale.html

Parameters
  • x (Union[str, dict], optional) – The scales to use on the x-axis

  • y (Union[str, dict], optional) – The scales to use on the y-axis

_hlpr_set_ticks(*, x: dict = None, y: dict = None)[source]

Sets the ticks for the current axis

The arguments are used to call ax.set_xticks or ax.set_yticks, and ax.set_xticklabels or ax.set_yticklabels, respectively. The dict-like arguments may contain the keys major and/or minor, referring to major or minor tick locations and labels, respectively. They should either be list-like, directly specifying the ticks’ locations, or dict-like requiring a locs key that contains the ticks’ locations and is passed on to matplotlib.axes.Axes.set_xticks as ticks argument. Further kwargs such as labels can be given and are passed on to matplotlib.axes.Axes.set_xticklabels.

Example:

set_ticks:
  x:
    major: [2, 4, 6, 8]
    minor:
      locs: [1, 3, 5, 7, 9]
  y:
    major:
      locs: [0, 1000, 2000, 3000]
      labels: [0, 1k, 2k, 3k]
      # ... further kwargs here specify label aesthetics

For more information, see:

Parameters
  • x (Union[list, dict], optional) – The ticks and optionally their labels to set on the x-axis

  • y (Union[list, dict], optional) – The ticks and optionally their labels to set on the y-axis

_hlpr_set_tick_locators(*, x: dict = None, y: dict = None)[source]

Sets the tick locators for the current axis

The arguments are used to call ax.{x,y}axis.set_{major/minor}_locator , respectively. The dict-like arguments must contain the keys major and/or minor, referring to major or minor tick locators. These need to specify a name that is looked up in matplotlib.ticker. They can contain a list-like args kwarg that defines the arguments to pass on as positional args to the called function. Further kwargs are passed on to ax.{x,y}axis.set_{major/minor}_locator.

Example:

set_tick_locators:
  x:
    major:
      name: MaxNLocator    # is looked up from matplotlib.ticker module
      nbins: 6
      integer: true
      min_n_ticks: 3
  y:
    major:
      name: MultipleLocator
      args: [2]

For more information, see:

Parameters
  • x (dict, optional) – The configuration of the x-axis tick locator

  • y (dict, optional) – The configuration of the y-axis tick locator

_hlpr_set_tick_formatters(*, x: dict = None, y: dict = None)[source]

Sets the tick formatters for the current axis

The arguments are used to call ax.{x,y}axis.set_{major/minor}_formatter , respectively. The dict-like arguments must contain the keys major and/or minor, referring to major or minor tick formatters. These need to specify a name that is looked up in matplotlib.ticker. They can contain a list-like args kwarg that defines the arguments to pass on as positional args to the called function. Further kwargs are passed on to ax.{x,y}axis.set_{major/minor}_formatter.

Example:

set_tick_formatters:
  x:
    major:
      name: StrMethodFormatter
      args: ['{x:.3g}']
  y:
    major:
      name: FuncFormatter
      args: [!dag_result my_formatter_lambda]
      # any kwargs here passed also to FuncFormatter

For more information, see:

Parameters
  • x (dict, optional) – The configuration of the x-axis tick formatter

  • y (dict, optional) – The configuration of the y-axis tick formatter

_hlpr_call(*, functions: Sequence[dict], **shared_kwargs)[source]

Axis-level helper that can be used to call multiple functions.

Functions can be specified in three ways:

  • as string, being looked up from a pre-defined dict

  • as 2-tuple (module, name) which will be imported on the fly

  • as callable, which will be used directly

The implementation of this is shared with the plot function multiplot(). See there for more information.

The figure-level helper figcall is identical to this helper, but is invoked before the axis-specific helpers are invoked.

Hint

To pass custom callables, use the data transformation framework and the !dag_result placeholder, see Using data transformation results in the plot configuration.

Note

While most matplotlib-based functions will automatically operate on the current axis, some function calls may require an axis object. If so, use the pass_axis_object_as argument, which specifies the name of the keyword argument as which the current axis is passed to the function call.

Example:

call:
  functions:
    # Look up function from dict, containing common seaborn and
    # pyplot plotting functions (see multiplot for more info)
    - function: sns.lineplot
      data: !dag_result my_custom_data

    # Import function via `(module, name)` specification
    - function: [matplotlib, pyplot.subplots_adjust]
      left: 0.1
      right: 0.9

    # Pass a custom callable, selected via DAG framework
    - function: !dag_result my_callable
      args: [foo, bar]
      # ... keyword arguments here

    # Pass current axis object as keyword argument
    - function: !dag_result my_callable_operating_on_ax
      pass_axis_object_as: ax

    # Pass helper object itself as keyword argument
    - function: !dag_result my_callable_operating_on_helper
      pass_helper: true
Parameters
  • functions (Sequence[dict]) – A sequence of function call specifications. Each dict needs to contain at least the key function which determines which function to invoke. Further arguments are parsed into the positional and keyword arguments of the to-be-invoked function.

  • **shared_kwargs – Passed on as keyword arguments to all function calls in functions.

_hlpr_despine(**kwargs)[source]

Despines the current axis using seaborn.despine.

To despine the whole figure, apply this helper to all axes. Refer to the seaborn documentation for available arguments: https://seaborn.pydata.org/generated/seaborn.despine.html

Parameters

**kwargs – Passed on to seaborn.despine.