dantro.plot_creators._plot_helper module

This module implements the PlotHelper class

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

Bases: object

Context manager to temporarily change an axis in the PlotHelper

__init__(hlpr, *, tmp_ax_coords: Tuple[int] = None)[source]

Initialize the context manager.

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

  • tmp_ax_coords (Tuple[int]) – 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.

class dantro.plot_creators._plot_helper.PlotHelper(*, out_path: str, helper_defaults: dict = None, update_helper_cfg: dict = None, raise_on_error: bool = True)[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')
__init__(*, out_path: str, helper_defaults: dict = None, update_helper_cfg: dict = None, raise_on_error: bool = True)[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

  • 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

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 out_path

Returns the output path of the plot

property animation_update

Returns the animation update generator callable

attach_figure_and_axes(*, fig, axes)[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

Raises

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

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 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, row: int)[source]

Selects the axes at the given coordinate as the current axis.

This does not perform a check on whether the axis is valid or already set.

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

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

Raises

ValueError – On failing to set the current axis

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, **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

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

Raises

ValueError – No matching helper function defined

Returns

None

invoke_helper(helper_name: str, *, axes: Union[tuple, str] = None, mark_disabled_after_use: bool = True, **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.

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

invoke_helpers(*helper_names, axes: Union[tuple, str] = None, mark_disabled_after_use: bool = True, **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.

  • **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.

Deleted Parameters:

helper_names (list): Helpers to be invoked

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

Invokes all enabled helpers with their current configuration on the matching axes.

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.

  • **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.

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.

register_animation_update(update_func: Callable)[source]

Registers a generator used for animations.

Parameters

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

_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

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

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

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

  • **title_kwargs – Passed on to plt.set_title

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

Set the title of the current axis

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

  • **title_kwargs – Passed on to plt.set_title

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

Set 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) – Whether to label only outer axes

_hlpr_set_limits(*, x: Union[tuple, dict] = None, y: Union[tuple, dict] = None)[source]

Set the x and y limit for the current axis

x and y can have the following shapes:

None Limits are not set tuple, list Specify lower and upper values dict expecting keys lower and/or upper

Each entries of the tuple 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[tuple, dict], optional) – Set the x-axis limits. For valid argument values, see above.

  • y (Union[tuple, dict], optional) – Set the y-axis limits. For valid argument values, see above.

_hlpr_set_legend(*, use_legend: bool = True, **legend_kwargs)[source]

Set a legend for the current axis

_hlpr_set_texts(*, texts: list)[source]

Set a list of texts for the current axis

Parameters
  • texts – The list of text dicts, that are passed to

  • matplotlib.pyplot.text

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

Set 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]

Set a scale for the current axis