dantro.plot package
Contents
dantro.plot package#
The plotting module consolidates the dantro plotting framework
isort:skip_file
Subpackages#
Submodules#
dantro.plot._cfg module#
A module containing tools for generating plot configurations
- _check_visited(visited: Sequence[Tuple[str, str]], *, next_visit: Tuple[str, str]) Sequence[Tuple[str, str]] [source]#
Performs cycle detection on the sequence of visited entries and raises an error if there will be a cycle. Otherwise, returns the new visiting sequence by appending the
next_visit
to the given sequence ofvisited
entries.
- _find_in_pool(name: str, *, base_pools: OrderedDict, skip: Sequence[Tuple[str, str]] = ()) Tuple[str, dict, Tuple[str, dict]] [source]#
Looks up a plot configuration in the given pool and returns the name of the pool, the found configuration, and the subset of pools that were not yet looked up.
With
skip
, certain entries can be skipped, e.g. the entry from which the currentbased_on
is resolved from.
- _resolve_based_on(pcfg: Union[dict, ParamSpace], *, base_pools: OrderedDict, _visited: Sequence[Tuple[str, str]]) Union[dict, ParamSpace] [source]#
Assembles a single plot’s configuration by recursively resolving its
based_on
entry from a pool of available base plot configurations.This function always works on a deep copy of
pcfg
and will remove any potentially existingbased_on
entry on the root level ofpcfg
.Furthermore, it accepts
ParamSpace
objects for plot configuration entries, recursively updating their dict representation and again creating aParamSpace
object from them afterwards.
- resolve_based_on(plots_cfg: Dict[str, Union[dict, ParamSpace]], *, label: str, base_pools: Union[OrderedDict, Sequence[Tuple[str, dict]]]) Dict[str, dict] [source]#
Resolves the
based_on
entries of all plot configurations in the given plot configurations dictionaryplots_cfg
.The procedure is as follows:
Iterate over root-level entries in the
plots_cfg
dictFor each entry, check if a
based_on
entry is present and needs to be resolved.If so, recursively resolve the configuration entry, starting from the first entry in the
based_on
sequence and recursively updating it with content of the following elements. The final recursive update is that of the plot configuration given inplots_cfg
.
Lookups happen from a pool of plot configurations: the
base_pools
, combined with the givenplots_cfg
itself. Thebased_on
entries are looked up by name using the following rules:Other plot configurations within
plots_cfg
have highest precedence.If no name is found there, lookups happen from within
base_pools
, iterating over it in reverse, meaning that entries later in the ordered dict take precedence over those earlier.If entries in a base pool are again using
based_on
, these will be looked up using the same rules, but with the pool restricted to entries with lower precedence than that pool.Lookups within the same pool will exclude the name of the currently updated plot configuration. Example:
some_plot: {based_on: some_plot}
will look forsome_plot
in some lower-precedence pool.
The resolution of plot configurations works on deep copies of the given
plots_cfg
and all thebased_on
entries to avoid mutability issues between parts of these highly nested dictionaries.For integrated use of this functionality, see Plot Configuration Inheritance.
- Parameters
plots_cfg (dict) – A dict with multiple plot configurations to resolve the
based_on
entries of. Root-level keys are assumed to correspond to individual plot configurations. If this argument evaluates to False, will silently assume an empty plots configuration.label (str) – The label to use for the given plots configuration when adding it to the base configuration pool.
base_pools (Union[OrderedDict, Sequence[Tuple[str, dict]]]) – The base configuration pools to look up the
based_on
entries in. This needs to be an OrderedDict or a type that can be converted into one. Keys will be used as labels for the individual pools. The order of this pool is relevant, see above.
- Raises
PlotConfigError – Upon missing
based_on
values or dependency loops.
- resolve_based_on_single(*, name: str, based_on: Union[str, Sequence[str]], plot_cfg: dict, **resolve_based_on_kwargs) dict [source]#
Wrapper for
resolve_based_on()
for cases of single independent plot configurations.- Parameters
name (str) – The name of the single plot
based_on (Union[str, Sequence[str]]) – The extracted
based_on
argument.plot_cfg (dict) – The rest of the single plot’s configuration. This may not include
based_on
! If this argument evaluates to False, will silently assume an empty plots configuration.**resolve_based_on_kwargs – Passed on
dantro.plot.plot_helper module#
This module implements the dantro PlotHelper class, which aims to abstract matplotlib plot operations such that they can be made accessible for a configuration-based declaration.
- class temporarily_changed_axis(hlpr: PlotHelper, tmp_ax_coords: Optional[Tuple[int, int]] = None)[source]#
Bases:
object
Context manager to temporarily change an axis in the
PlotHelper
.- __init__(hlpr: PlotHelper, tmp_ax_coords: Optional[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.
- _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
matchesmatch
- Return type
- Raises
TypeError –
match
not being a tuple or a listValueError – Any of the arguments not being 2-tuples.
- class PlotHelper(*, out_path: str, helper_defaults: Optional[dict] = None, update_helper_cfg: Optional[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: Tuple[str] = ('setup_figure', 'save_figure')#
Configuration keys with special meaning
- _FIGURE_HELPERS: Tuple[str] = ('align_labels', 'set_suptitle', 'set_figlegend', 'subplots_adjust', 'figcall')#
Names of those helpers that are applied on the figure level
- __init__(*, out_path: str, helper_defaults: Optional[dict] = None, update_helper_cfg: Optional[dict] = None, raise_on_error: bool = True, animation_enabled: bool = False)[source]#
Initialize a PlotHelper 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 base_cfg: dict#
Returns a deepcopy of the base configuration, i.e. the configuration that is not axis-specific.
- property ax_coords: Tuple[int]#
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: ndarray#
Returns the axes array, which is of shape
(#cols, #rows)
.The (0, 0) axis refers to the top left subplot of the figure.
- property animation_update: Callable#
Returns the animation update generator callable
- property invoke_before_grab: bool#
Whether the helpers are to be invoked before grabbing each frame of an animation.
- property axis_handles_labels: Tuple[list, list]#
Returns the tracked axis handles and labels for the current axis
- property axis_is_empty: bool#
Returns true if the current axis is empty, i.e. has no artists added to it: Basically, negation of
matplotlib.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 theaxes
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: Optional[int] = None, row: Optional[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
androw
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
androw
values are wrapped around according to the shape of the associatedaxes
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
matplotlib.pyplot.gca()
was not part of the associated axes array. To associate the correct figure and axes, use theattach_figure_and_axes()
method.
- coords_iter(*, match: Optional[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()
) 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: Optional[Union[tuple, str]] = None, mark_disabled_after_use: bool = True, raise_on_error: Optional[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: Optional[Union[tuple, str]] = None, mark_disabled_after_use: bool = True, raise_on_error: Optional[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: Optional[Union[tuple, str]] = None, mark_disabled_after_use: bool = True, raise_on_error: Optional[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: Optional[Union[tuple, str]] = None, mark_disabled_after_use: bool = True, raise_on_error: Optional[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 theaxes
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: Optional[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: Optional[Union[tuple, str]] = None)[source]#
Marks the specified helpers as enabled for the specified axes.
- mark_disabled(*helper_names, axes: Optional[Union[tuple, str]] = None)[source]#
Marks the specified helpers as disabled for the specified axes.
- track_handles_labels(handles: list, labels)[source]#
Keep track of legend handles and/or labels for the current axis.
- 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
- Raises
ValueError – On invalid helper name
- _handle_errors(*errors, raise_on_error: Optional[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 by calling
matplotlib.figure.Figure.align_xlabels()
and/ormatplotlib.figure.Figure.align_ylabels()
.
- _hlpr_set_suptitle(*, title: Optional[str] = None, margin: float = 0.025, **title_kwargs)[source]#
Set the figure title using
matplotlib.figure.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 they
argument. When repetitively invoking this helper on the same figure, the subplot sizes are re-adjusted each time.
- _hlpr_set_figlegend(*, gather_from_fig: bool = False, custom_labels: Sequence[str] = (), hiding_threshold: Optional[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
matplotlib.figure.Figure.legend()
.
- Raises
RuntimeError – If a figure legend was already set via the helper.
- _hlpr_subplots_adjust(**kwargs)[source]#
Invokes
matplotlib.figure.Figure.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_autofmt_xdate(**kwargs)[source]#
Invokes
autofmt_xdate()
on the figure, passing all arguments along. This can be useful when x-labels are overlapping (e.g. because they are dates).
- _hlpr_set_title(*, title: Optional[str] = None, **title_kwargs)[source]#
Sets the title of the current axes.
- Parameters
title (str, optional) – The title to be set
**title_kwargs – Passed on to
matplotlib.axes.Axes.set_title()
- _hlpr_set_labels(*, x: Optional[Union[dict, str]] = None, y: Optional[Union[dict, str]] = None, z: Optional[Union[dict, str]] = None, only_label_outer: bool = False, rotate_z_label: Optional[bool] = None)[source]#
Sets the x, y, and z 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 tomatplotlib.axes.Axes.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 tomatplotlib.axes.Axes.set_ylabel()
z (Union[str, dict], optional) – Either the label as a string or a dict with key
label
, where all further keys are passed on tompl_toolkits.mplot3d.axes3d.Axes3D.set_zlabel()
. If there is no z-axis, this will be silently ignored.only_label_outer (bool, optional) – If True, call
matplotlib.axes.Axes.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.rotate_z_label (bool, optional) – If given, sets
mpl_toolkits.mplot3d.axis3d.Axis.set_rotate_label()
. If there is no z-axis, this will be silently ignored.
- _hlpr_set_limits(*, x: Optional[Union[Sequence[Union[float, str]], dict]] = None, y: Optional[Union[Sequence[Union[float, str]], dict]] = None, z: Optional[Union[Sequence[Union[float, str]], dict]] = None)[source]#
Sets the x, y, and z limits for the current axis. Allows some convenience definitions for the arguments and then calls
matplotlib.axes.Axes.set_xlim()
and/ormatplotlib.axes.Axes.set_ylim()
.mpl_toolkits.mplot3d.axes3d.Axes3D.set_zlim()
.The
x
,y
, andz
arguments can have the following form:None: Limits are not set
sequence: Specify lower and upper values
dict: Expecting keys
lower
and/orupper
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 axismax
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
z (Union[Sequence[Union[float, str]], dict], optional) – The limits to set on the z-axis If there is no z-axis, this will be silently ignored.
- _hlpr_set_margins(*, margins: Optional[Union[float, Tuple[float, float]]] = None, x: Optional[float] = None, y: Optional[float] = None, tight: bool = True)[source]#
Sets the axes’ margins via
matplotlib.axes.Axes.margins()
.The padding added to each limit of the Axes is the margin times the data interval. All input parameters must be floats within the range [0, 1].
Specifying any margin changes only the autoscaling; for example, if
xmargin
is not None, thenxmargin
times the X data interval will be added to each end of that interval before it is used in autoscaling.- Parameters
margins (Union[float, Tuple[float, float]], optional) – If a scalar argument is provided, it specifies both margins of the x-axis and y-axis limits. If a list- or tuple-like positional argument is provided, they will be interpreted as
xmargin
, andymargin
. If setting the margin on a single axis is desired, use the keyword arguments described below.x (float, optional) – Specific margin values for the x-axis and y-axis, respectively. These cannot be used in combination with the
margins
argument, but can be used individually to alter on e.g., only the y-axis.y (float, optional) – Specific margin values for the x-axis and y-axis, respectively. These cannot be used in combination with the
margins
argument, but can be used individually to alter on e.g., only the y-axis.tight (bool, optional) – The tight parameter is passed to
matplotlib.axes.Axes.autoscale_view()
, which is executed after a margin is changed; the default here is True, on the assumption that when margins are specified, no additional padding to match tick marks is usually desired. Set tight to None will preserve the previous setting.
- _hlpr_set_legend(*, use_legend: bool = True, gather_from_fig: bool = False, custom_labels: Sequence[str] = (), hiding_threshold: Optional[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 existingmatplotlib.legend.Legend
objects on the current axis. Ifgather_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: Optional[list] = None, vlines: Optional[list] = None)[source]#
Sets one or multiple horizontal or vertical lines using
matplotlib.axes.Axes.axhline()
and / ormatplotlib.axes.Axes.axvline()
.- Parameters
hlines (list, optional) – list of numeric positions of the lines or or list of dicts with key
pos
determining the position, keylimits
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, keylimits
determining the relative limits of the line, and all additional arguments being passed on to the matplotlib function.
- _hlpr_set_scales(*, x: Optional[Union[dict, str]] = None, y: Optional[Union[dict, str]] = None, z: Optional[Union[dict, str]] = None)[source]#
Sets the scales for the current axis
The arguments are used to call
matplotlib.axes.Axes.set_xscale()
and/ormatplotlib.axes.Axes.set_yscale()
andmpl_toolkits.mplot3d.axes3d.Axes3D.set_zscale()
, 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 ascale
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.
- _hlpr_set_ticks(*, x: Optional[Union[list, dict]] = None, y: Optional[Union[list, dict]] = None, z: Optional[Union[list, dict]] = None)[source]#
Sets the ticks for the current axis
The arguments are used to call
matplotlib.axes.Axes.set_xticks()
ormatplotlib.axes.Axes.set_yticks()
ormpl_toolkits.mplot3d.axes3d.Axes3D.set_zticks()
, andmatplotlib.axes.Axes.set_xticklabels()
ormatplotlib.axes.Axes.set_yticklabels()
ormpl_toolkits.mplot3d.axes3d.Axes3D.set_zticklabels()
, respectively.The dict-like arguments may contain the keys
major
and/orminor
, 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 alocs
key that contains the ticks’ locations and is passed on to theset_<x/y/z>ticks
call. asticks
argument. Further kwargs such aslabels
can be given and are passed on to theset_<x/y/z>ticklabels
call.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 z: [-1, 0, +1] # same as z: {major: {locs: [-1, 0, +1]}}
- 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
z (Union[list, dict], optional) – The ticks and optionally their labels to set on the z-axis. If there is no z-axis, this will be silently ignored.
- _hlpr_set_tick_locators(*, x: Optional[dict] = None, y: Optional[dict] = None, z: Optional[dict] = None)[source]#
Sets the tick locators for the current axis
The arguments are used to call
ax.{x,y, z}axis.set_{major/minor}_locator
, respectively. The dict-like arguments must contain the keysmajor
and/orminor
, referring to major or minor tick locators. These need to specify a name that is looked up inmatplotlib.ticker
. They can contain a list-likeargs
keyword argument that defines the arguments to pass on as positional args to the called function. Further kwargs are passed on toax.{x,y, z}axis.set_{major/minor}_locator
.Example:
set_tick_locators: x: major: name: MaxNLocator # looked up from matplotlib.ticker nbins: 6 integer: true min_n_ticks: 3 y: major: name: MultipleLocator args: [2]
For more information, see:
- _hlpr_set_tick_formatters(*, x: Optional[dict] = None, y: Optional[dict] = None, z: Optional[dict] = None)[source]#
Sets the tick formatters for the current axis
The arguments are used to call
ax.{x,y, z}axis.set_{major/minor}_formatter
, respectively. The dict-like arguments must contain the keysmajor
and/orminor
, referring to major or minor tick formatters. These need to specify a name that is looked up inmatplotlib.ticker
. They can contain a list-likeargs
keyword argument that defines the arguments to pass on as positional args to the called function. Further kwargs are passed on toax.{x,y, z}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 z: major: name: DateFormatter # looked up from matplotlib.dates args: ["%H:%M:%S"] # or "%Y-%m-%d"
For more information, see:
- _hlpr_call(*, functions: Sequence[dict], funcs_lookup_dict: Optional[Dict[str, Callable]] = None, **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 flyas 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.funcs_lookup_dict (Dict[str, Callable], optional) – If given, will look up the function names from this dict instead of the default dict.
**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
.