utopya.eval.plots package#
The plot_funcs subpackage supplies general plotting functions.
These can be used via the plotting framework and its ExternalPlotCreator, of which this subpackage is the base package to use for relative module imports.
It extends those capabilities provided by the dantro plotting framework.
Submodules#
utopya.eval.plots._attractor module#
This module holds data processing functionality that is used in the plot functions.
- utopya.eval.plots._attractor.find_endpoint(data: xarray.core.dataarray.DataArray, *, time: int = - 1, **kwargs) Tuple[bool, xarray.core.dataarray.DataArray] [source]#
Find the endpoint of a dataset wrt.
time
coordinate.This function is compatible with the
utopya.eval.plots.attractor.bifurcation_diagram()
.- Parameters
data (xarray.DataArray) – The data
time (int, optional) – The time index to select
**kwargs – Passed on to
xarray.DataArray.isel()
call
- Returns
- The result in the form of a 2-tuple
(endpoint found, endpoint)
- Return type
Tuple[bool, xarray.DataArray]
- utopya.eval.plots._attractor.find_fixpoint(data: xarray.core.dataset.Dataset, *, spin_up_time: int = 0, abs_std: Optional[float] = None, rel_std: Optional[float] = None, mean_kwargs=None, std_kwargs=None, isclose_kwargs=None, squeeze: bool = True) Tuple[bool, float] [source]#
Find the fixpoint(s) of a dataset and confirm it by standard deviation. For dimensions that are not
time
the fixpoints are compared and duplicates removed.This function is compatible with the
utopya.eval.plots.attractor.bifurcation_diagram()
.- Parameters
data (xarray.Dataset) – The data
spin_up_time (int, optional) – The first timestep included
abs_std (float, optional) – The maximal allowed absolute standard deviation
rel_std (float, optional) – The maximal allowed relative standard deviation
mean_kwargs (dict, optional) – Additional keyword arguments passed on to the appropriate array function for calculating mean on data.
std_kwargs (dict, optional) – Additional keyword arguments passed on to the appropriate array function for calculating std on data.
isclose_kwargs (dict, optional) – Additional keyword arguments passed on to the appropriate array function for calculating np.isclose for fixpoint-duplicates across dimensions other than ‘time’.
squeeze (bool, optional) – Use the data.squeeze method to remove dimensions of length one. Default is True.
- Returns
(fixpoint found, mean)
- Return type
- utopya.eval.plots._attractor.find_multistability(*args, **kwargs) Tuple[bool, float] [source]#
Find the multistabilities of a dataset.
Invokes
find_fixpoint()
. This function is conclusive iffind_fixpoint()
is conclusive with multiple entries.- Parameters
*args – passed to
find_fixpoint()
**kwargs – passed to
find_fixpoint()
- Returns
Tuple[bool, float]:
(multistability found, mean value)
- utopya.eval.plots._attractor.find_oscillation(data: xarray.core.dataset.Dataset, *, spin_up_time: int = 0, squeeze: bool = True, **find_peak_kwargs) Tuple[bool, list] [source]#
Find oscillations in a dataset.
This function is compatible with the
utopya.eval.plots.attractor.bifurcation_diagram()
.- Parameters
data (xarray.Dataset) – The data
spin_up_time (int, optional) – The first timestep included
squeeze (bool, optional) – Use the data.squeeze method to remove dimensions of length one. Default is True.
**find_peak_kwargs – Passed on to
scipy.signal.find_peaks()
. If not given, will setheight
kwarg to-1.e+15
.
- Returns
(oscillation found, [min, max])
- Return type
utopya.eval.plots._graph module#
This module provides the GraphPlot
class.
- utopya.eval.plots._graph.POSITIONING_MODELS_NETWORKX = {'bipartite': <function bipartite_layout>, 'circular': <function circular_layout>, 'graphviz': <function graphviz_layout>, 'kamada_kawai': <function kamada_kawai_layout>, 'planar': <function planar_layout>, 'random': <function random_layout>, 'shell': <function shell_layout>, 'spectral': <function spectral_layout>, 'spiral': <function spiral_layout>, 'spring': <function spring_layout>}#
Available networkx node layout options
- class utopya.eval.plots._graph.GraphPlot(g: networkx.classes.graph.Graph, *, fig: matplotlib.figure.Figure = None, ax: matplotlib.axes.Axes = None, select: dict = None, positions: dict = None, nodes: dict = None, edges: dict = None, node_labels: dict = None, edge_labels: dict = None, mark_nodes: dict = None, mark_edges: dict = None)[source]#
Bases:
object
This class provides an interface for visualizing a :py:class`networkx.Graph` object or a graph created from a
GraphGroup
.- __init__(g: networkx.classes.graph.Graph, *, fig: matplotlib.figure.Figure = None, ax: matplotlib.axes.Axes = None, select: dict = None, positions: dict = None, nodes: dict = None, edges: dict = None, node_labels: dict = None, edge_labels: dict = None, mark_nodes: dict = None, mark_edges: dict = None)[source]#
Initializes a
GraphPlot
, which provides drawing utilities for a fixed graph.The drawing kwargs are stored and used when calling
draw()
.A
GraphPlot
can also be initialized from aGraphGroup
via thefrom_group()
classmethod.If drawing multiple times from the same
GraphPlot
instance, be aware that it only keeps track of the nodes/edges/labels/colorbars that were last associated with it. Useclear_plot()
before re-drawing on the same axis.Note
For some graph drawing kwargs it is possible to configure an automatized mapping from node/edge properties. This property mapping has the following syntax:
some_layout_property: from_property: my_node_or_edge_property scale_to_interval: [low_lim, up_lim]
The
from_property
specifies the node or edge property to be mapped from. Ifscale_to_interval
is given, the layout property values are rescaled linearly the specified interval.- Parameters
g (networkx.Graph) – The networkx graph object
fig (matplotlib.figure.Figure, optional) – The matplotlib figure used for drawing
ax (matplotlib.axes.Axes, optional) – The matplotlib axes used for drawing
select (dict, optional) –
Draw only a subgraph induced by a selection of nodes. Either select a list of nodes by passing the
nodelist
argument or do a radial node selection by specifying acenter
node and theradius
. The following arguments can be passed additionally:- open_edges (bool, optional):
Whether to draw the edges for which only one of source and destination is in the set of selected nodes. Disabled by default.
- drop (bool, optional):
Whether to remove the non-selected nodes from the graph. If False, all nodes are passed to the node positioning model. Enabled by default.
positions (dict, optional) –
Configuration for the node positioning. The following arguments are available:
- from_dict (dict, optional):
Node positions (2-tuples) keyed by node. If given, the layouting algorithm given by the
model
argument will be ignored.- model (Union[str, Callable], optional):
The layout model that is used to calculate the node positions (default=``spring``). Available networkx layout models are:
spring
,circular
,shell
,bipartite
,kamada_kawai
,planar
,random
,spectral
,spiral
. SeePOSITIONING_MODELS_NETWORKX
.If installed, GraphViz models can be selected using the
agraph_graphviz
graphviz_layout()
) layout function, with theprog
argument specifying the layout model. Options depend on theGraphViz
version but may include:dot
,neato
,fdp
,sfdp
,twopi
,circo
. Other arguments must be passed as a single string separated by a hyphen, e.g.'-len=1000-overlap_scaling=100-sep=100'
.If the argument is a callable, it is invoked with the graph as the first positional argument and is expected to return networkx-compatible node positions, i.e. a mapping from nodes to a 2-tuple denoting the position.
- further kwargs:
Passed on to the chosen layout model.
nodes (dict, optional) –
Drawing configuration for the nodes. The following arguments are available for property mapping:
node_size
,node_color
,alpha
. The following arguments are allowed:- node_size (scalar or sequence of scalars, optional):
The node size (default=300). Available for property mapping. Can be mapped directly from the nodes’
degree
,in_degree
, orout_degree
by setting thefrom_property
argument accordingly.- node_color (color or sequene of colors, optional):
Single color (string or RGB(A) tuple or numeric value) or sequence of colors (default: ‘#1f78b4’). If numeric values are specified they will be mapped to colors using the cmap and vmin, vmax parameters.
If mapped from property it may contain an additional
map_to_scalar
, which is a dict of numeric target values keyed by property value. This allows to map from non-numeric (e.g. categorical) properties.- cmap (optional):
The colormap. Passed as
cmap
toColorManager
.- cmap_norm (optional):
The norm used for the color mapping. Passed as
norm
toColorManager
. Is overwritten, if a discrete colormap is specified incmap
.- colorbar (dict, optional):
The node colorbar configuration. The following arguments are allowed:
- enabled (bool, optional):
Whether to plot a colorbar. Enabled by default if
node_color
is mapped from property.- labels (dict, optional):
Colorbar tick-labels keyed by tick position (see
create_cbar()
).- tick_params (dict, optional):
Colorbar axis tick parameters
- label (str, optional):
The axis label for the colorbar
- label_kwargs (dict, optional):
Further keyword arguments to adjust the aesthetics of the colorbar label
- further kwargs:
Passed on to
create_cbar()
.
- further kwargs:
Passed to draw_networkx_nodes when calling
draw()
.
edges (dict, optional) –
Drawing configuration for the edges. The following arguments are available for property mapping:
edge_color
,width
.The
edge_color
,edge_cmap
, andcolorbar
arguments behave analogously for the edges as nodes.node_color, nodes.cmap, and nodes.colorbar for the nodes. Any further kwargs are (after applying property mapping), passed on to draw_networkx_edges when callingdraw()
.If arrows are to be drawn (i.e. for directed edges with arrows=True), only norms of type matplotlib.colors.Normalize are allowed.
node_labels (dict, optional) –
Drawing configuration for the node labels. The following arguments are allowed:
- enabled (bool, optional):
Whether to draw node labels. Disabled by default. If enabled, nodes are labeled by their index by default.
- show_only (list, optional):
If given, labels are drawn only for the nodes in this list.
- labels (dict, optional):
Custom text labels keyed by node. Available for property mapping.
- format (str, optional):
If
labels
are mapped from property this format string containing alabel
key is used for all node labels.- decode (str, optional):
Decoding specifier which is applied to all property values if
format
is used.- further kwargs:
Passed on to draw_networkx_labels when calling
draw()
.
edge_labels (dict, optional) –
Drawing configuration for the edge labels. The following arguments are allowed:
- enabled (bool, optional):
Whether to draw edge labels. Disabled by default. If enabled, edges are labeled by their (source, destination) pair by default.
- show_only (list, optional):
If given, labels are drawn only for the edges (2-tuples) in this list.
- edge_labels (dict, optional):
Custom text labels keyed by edge (2-tuple). Available for property mapping.
- format (str, optional):
If
edge_labels
are mapped from property this format string containing alabel
key is used for all edge labels.- decode (str, optional):
Decoding specifier which is applied to all property values if
format
is used.- further kwargs:
Passed on to draw_networkx_edge_labels when calling
draw()
.
mark_nodes (dict, optional) – Mark specific nodes by changing their edgecolor. Either specify a
color
for a list of nodes (nodelist
), or specify acolors
dictionary of colors keyed by node. Updates an existingnodes.edgecolors
entry.mark_edges (dict, optional) – Mark specific edges by changing their color. Either specify a
color
for a list of edges (edgelist
), or specify acolors
dictionary of colors keyed by edge (2-tuple). Updates an existingedges.edge_color
entry.
- property g#
Get a deep copy of the graph associated with this instance.
- Returns
The graph object
- Return type
- draw(*, fig: matplotlib.figure.Figure = None, ax: matplotlib.axes.Axes = None, positions: dict = None, nodes: dict = None, edges: dict = None, node_labels: dict = None, edge_labels: dict = None, mark_nodes: dict = None, mark_edges: dict = None, suppress_cbar: bool = False, update_colormapping: bool = True, **add_colorbars)[source]#
Draws the graph associated with the
GraphPlot
using the current drawing configuration.The current drawing configuration may be temporarily updated for this plot. The respective arguments accept the same input as in
__init__()
.- Parameters
fig (matplotlib.figure.Figure, optional) – matplotlib figure
ax (matplotlib.axes.Axes, optional) – matplotlib axis
positions (dict, optional) – Position configuration. If given, the current positions are replaced. If using a node positioning model the positions are recalculated.
nodes (dict, optional) – Temporarily updates the node-kwargs
edges (dict, optional) – Temporarily updates the edge-kwargs
node_labels (dict, optional) – Temporarily updates the node-label-kwargs
edge_labels (dict, optional) – Temporarily updates the edge-label-kwargs
mark_nodes (dict, optional) – Temporarily mark nodes kwargs
mark_edges (dict, optional) – Temporarily mark edges kwargs
suppress_cbar (bool, optional) – Whether to suppress the drawing of colorbars
update_colormapping (bool, optional) – Whether to reconfigure the nodes’ and edges’
ColorManager
(default=True). If True, the respective configuration entries are ignored. Set to False if doing repetitive plotting with fixed colormapping.**add_colorbars – Passed to
add_colorbars()
- add_colorbars(*, show_node_cbar=True, show_edge_cbar=True, fig=None, ax=None, remove_previous=True, **update_cbar_kwargs)[source]#
Adds colorbars for the drawn nodes and edges.
- Parameters
show_node_cbar (bool, optional) – Whether to create a colorbar for the nodes
show_edge_cbar (bool, optional) – Whether to create a colorbar for the edges
fig (None, optional) – matplotlib figure
ax (None, optional) – matplotlib axis
remove_previous (bool, optional) – Whether the colorbars which are currently associated with the
GraphPlot
are removed. If False, the GraphPlot still loses track of the colorbars, they can not be removed via the GraphPlot afterwards.**update_cbar_kwargs – Update both node and edge colorbar kwargs, passed to
create_cbar()
.
- clear_plot(*, keep_colorbars: bool = False)[source]#
Removes all matplotlib objects associated with the GraphPlot from the respective axis. The GraphPlot loses track of all those objects, the respective class attributes are reset.
- Parameters
keep_colorbars (bool, optional) – Whether to keep the node and edge colorbars. If True, the GraphPlot still loses track of the colorbars, they can not be removed via the GraphPlot afterwards.
- classmethod from_group(graph_group: utopya.eval.groups.GraphGroup, *, graph_creation: dict = None, register_property_maps: dict = None, clear_existing_property_maps: bool = True, **init_kwargs)[source]#
Initializes a
GraphPlot
from aGraphGroup
.- Parameters
graph_group (utopya.eval.groups.GraphGroup) – The graph group
graph_creation (dict, optional) – Configuration of the graph creation. Passed to
create_graph_from_group()
register_property_maps (dict, optional) – Properties to be registered in the graph group before the graph creation keyed by name
clear_existing_property_maps (bool, optional) – Whether to clear any existing property maps from the graph group
**init_kwargs – Passed to
__init__()
- static create_graph_from_group(graph_group: utopya.eval.groups.GraphGroup, *, register_property_maps: dict = None, clear_existing_property_maps: bool = True, **graph_creation) networkx.classes.graph.Graph [source]#
Creates a
networkx.Graph
from a :py:class`utopya.eval.groups.GraphGroup`. Additional property maps may be added to the group beforehand.- Parameters
graph_group (utopya.eval.groups.GraphGroup) – The group to create the graph from
register_property_maps (dict, optional) – Properties to be registered in the graph group before the graph creation keyed by name.
clear_existing_property_maps (bool, optional) – Whether to clear any existing property maps from the graph group.
**graph_creation – Configuration of the graph creation. Passed on to the
create_graph
method implemented in dantro,create_graph()
.
- Returns
The created graph object.
- Return type
- parse_positions(*, from_dict: Optional[Dict[Any, Tuple[float, float]]] = None, model: Optional[Union[Callable, str]] = None, **kwargs)[source]#
Parses the node positioning configuration. If a node positioning model is to be used, (re)calculates the positions.
- Parameters
from_dict (dict, optional) – Explicit node positions (2-tuples keyed by node). If given, the
model
argument will be ignored.model (Union[str, Callable], optional) – The model used for node positioning. If it is a string, it is looked up from the available networkx positioning models. If None, the spring model is used. If it is callable, it will be called with the graph as first positional argument.
**kwargs – Passed to the node positioning routine
- Raises
ModuleNotFoundError – If a graphviz model was chosen but pygraphviz was not importable (via networkx).
- parse_nodes(*, node_size=None, node_color=None, alpha=None, cmap=None, cmap_norm=None, vmin: Optional[float] = None, vmax: Optional[float] = None, edgecolors=None, colorbar: Optional[dict] = None, update_colormapping: bool = True, **kwargs)[source]#
Parses the node layout configuration and updates the node kwargs of the GraphPlot.
The following arguments are available for property mapping:
node_size
,node_color
,alpha
.- Parameters
node_size (None, optional) – Size of nodes (default=300). Available for property mapping. Can be mapped directly from the nodes’
degree
,in_degree
, orout_degree
by setting thefrom_property
argument accordingly.node_color (None, optional) –
Single color (string or RGB(A) tuple or numeric value) or sequence of colors. If numeric values are specified they will be mapped to colors using the cmap and vmin, vmax parameters.
If mapped from property it may contain an additional
map_to_scalar
, which is a dict of numeric target values keyed by property value. This allows to map from non-numeric (e.g. categorical) properties.alpha (None, optional) – The node transparency
cmap (None, optional) – The colormap. Passed as
cmap
toColorManager
.cmap_norm (None, optional) – The norm used for the color mapping. Passed as
norm
toColorManager
. Is overwritten, if a discrete colormap is specified incmap
.vmin (float, optional) – Minimum for the colormap scaling
vmax (float, optional) – Maximum for the colormap scaling
edgecolors (optional) – Colors of node borders. The default is ‘none’, i.e. no node border is drawn.
colorbar (dict, optional) –
The node colorbar configuration. The following keys are available:
- enabled (bool, optional):
Whether to plot a colorbar. Enabled by default if
node_color
is mapped from property.- labels (dict, optional):
Colorbar tick-labels keyed by tick position (see
ColorManager
).- further kwargs: Passed on to
update_colormapping (bool, optional) – Whether to reconfigure the nodes’
ColorManager
(default: True). If False, the respective arguments are ignored. Set to False if doing repetitive plotting with fixed colormapping.**kwargs – Update the node kwargs. Passed to
draw_networkx_nodes()
when callingdraw()
- parse_edges(*, width=None, edge_color=None, edge_cmap=None, cmap_norm=None, alpha=None, edge_vmin: Optional[float] = None, edge_vmax: Optional[float] = None, colorbar: Optional[dict] = None, update_colormapping: bool = True, **kwargs)[source]#
Parses the edge layout configuration and updates the edge kwargs of the GraphPlot.
The following arguments are available for property mapping:
width
,edge_color
.- Parameters
width (None, optional) – Line width of edges
edge_color (None, optional) –
Single color (string or RGB(A) tuple or numeric value) or sequence of colors (default=’k’). If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin, edge_vmax parameters.
If mapped from property it may contain an additional
map_to_scalar
, which is a dict of numeric target values keyed by property value. This allows to map from non-numeric (e.g. categorical) properties.edge_cmap (None, optional) – The colormap. Passed as
cmap
toColorManager
.cmap_norm (None, optional) – The norm used for the color mapping. Passed as
norm
toColorManager
. Is overwritten, if a discrete colormap is specified inedge_cmap
. If arrows are to be drawn (i.e. for directed edges with arrows=True), only norms of type matplotlib.colors.Normalize are allowed.edge_vmin (float, optional) – Minimum for the colormap scaling
edge_vmax (float, optional) – Maximum for the colormap scaling
colorbar (dict, optional) –
The edge colorbar configuration. The following keys are available:
- enabled (bool, optional):
Whether to plot a colorbar. Enabled by default if
edge_color
is mapped from property.- labels (dict, optional):
Colorbar tick-labels keyed by tick position (see
ColorManager
).- further kwargs: Passed on to
update_colormapping (bool, optional) – Whether to reconfigure the edges’
ColorManager
(default=True). If False, the respective arguments are ignored. Set to False if doing repetitive plotting with fixed colormapping.**kwargs – Update the edge kwargs. Passed to
draw_networkx_nodes()
when callingdraw()
.
- Raises
TypeError – On norm type other than
matplotlib.colors.Normalize
and if arrows are to be drawn.
- parse_node_labels(*, enabled: bool = False, show_only: Optional[list] = None, labels: Optional[dict] = None, format: str = '{label}', decode: Optional[str] = None, **kwargs)[source]#
Parses the node labels configuration and updates the node label kwargs of the
GraphPlot
.- Parameters
enabled (bool, optional) – Whether to draw node labels.
show_only (list, optional) – If given, labels are drawn only for the nodes in this list
labels (dict, optional) – Custom text labels keyed by node. Available for property mapping.
format (str, optional) – If
labels
are mapped from property this format string containing alabel
key is used for all node labels.decode (str, optional) – Decoding specifier which is applied to all property values if
format
is used.**kwargs – Update the node label kwargs. Passed to nx.draw_networkx_labels when calling
draw()
.
- parse_edge_labels(*, enabled: bool = False, show_only: Optional[list] = None, edge_labels: Optional[dict] = None, format: str = '{label}', decode: Optional[str] = None, **kwargs)[source]#
Parses the edge labels configuration and updates the edge label kwargs of the GraphPlot.
- Parameters
enabled (bool, optional) – Whether to draw edge labels.
show_only (list, optional) – If given, labels are drawn only for the edges (2-tuples) in this list
edge_labels (dict, optional) – Custom text labels keyed by edge (2-tuple). Available for property mapping.
format (str, optional) – If
edge_labels
are mapped from property this format string containing alabel
key is used for all edge labels.decode (str, optional) – Decoding specifier which is applied to all property values if
format
is used.**kwargs – Update the edge label kwargs. Passed to nx.draw_networkx_edge_labels when calling
draw()
.
- mark_nodes(*, nodelist: Optional[list] = None, color=None, colors: Optional[dict] = None)[source]#
Mark specific nodes by changing their edgecolor.
Note
This function overwrites the
edgecolors
entry in the node kwargs. Thus it might overwrite an existingedgecolors
entry specified viaparse_nodes()
(and vice versa).- Parameters
- Raises
ValueError – On ambiguous or missing mark_nodes configuration
- mark_edges(*, edgelist: Optional[list] = None, color=None, colors: Optional[dict] = None)[source]#
Mark specific edges by changing their color.
Note
This function overwrites the
edge_color
entry in the edge kwargs. Thus it might overwrite an existingedge_color
entry specified viaparse_edges()
(and vice versa).- Parameters
- Raises
ValueError – On ambiguous or missing mark_edges configuration
- _configure_node_patch_sizes()[source]#
In the edge drawing kwargs adjusts the node patch specifications ensuring that, in the case of a directed graph, the arrows end exactly at the node boundaries. Besides the
node_size
also accounts for node boundaries.
- static _scale_to_interval(data: list, interval=None) list [source]#
Rescales the data linearly to the given interval. If no interval is given the data is returned as it is.
- Parameters
data (list) – data that is rescaled linearly to the given interval
interval (optional) – The target interval
- Returns
rescaled data
- Return type
- Raises
ValueError – On invalid interval specification
utopya.eval.plots._mpl module#
This module provides matplotlib-related helper constructs
- utopya.eval.plots._mpl.adjust_figsize_to_aspect(aspect: float, *, fig: matplotlib.figure.Figure) Tuple[float, float] [source]#
Adjusts the given figures size, enlarging it to match the given aspect ratio where
width = height * aspect
.- Parameters
aspect (float) – The aspect ratio
width / height
fig (matplotlib.figure.Figure) – The figure
- Returns
New width and height of the figure in inches.
- Return type
- class utopya.eval.plots._mpl.HandlerEllipse(*args, **kwargs)[source]#
Bases:
matplotlib.legend_handler.HandlerPatch
Custom legend handler to turn an ellipse handle into a legend key.
utopya.eval.plots._utils module#
Utility functions that assist plot functions
- utopya.eval.plots._utils.calc_pxmap_rectangles(*, x_coords: numpy.ndarray, y_coords: numpy.ndarray, x_scale: str = 'lin', y_scale: str = 'lin', default_pos: Tuple[float, float] = (0.0, 0.0), default_distance: float = 1.0, size_factor: float = 1.0, extend: bool = False) Tuple[xarray.core.dataset.Dataset, Dict[str, tuple]] [source]#
Calculates the positions and sizes of rectangles centered at the given coordinates in such a way that they fully cover the 2D space spanned by the coordinates.
The exact values of the coordinates are arbitrary, but they should be ordered. The resulting rectangles will not necessarily be centered around the coordinate, but the distance between rectangle edges is set such that it lies halfway to the next coordinate in that dimension; the “halfway” is evaluated according to a certain scale.
- Parameters
x_coords (numpy.ndarray) – The x coordinates
y_coords (numpy.ndarray) – The y coordinates
x_scale (str, optional) – The x-axis scale, used to determine rectangle sizes.
y_scale (str, optional) – The y-axis scale, used to determine rectangle sizes.
default_pos (Tuple[float, float], optional) – If any of the coordinates is not given, this information will be used for creating the rectangle specification.
default_distance (float, optional) – If any of the coordinates is not given or of size 1, this distance to the next data point is assumed in that dimension. In such a case, the scale does not have an effect on the resulting rectangle.
size_factor (float, optional) – Scaling factor for the rectangle sizes
extend (bool, optional) – Whether to extend the rectangles of the points at the border of the domain such that the coordinate is _not_ at the edge of the rectangle but in the bulk.
- Returns
- The first tuple element is the
dataset of rectangle specifications, each available as a data variable:
pos_x
,pos_y
: position of the lower-value coordinate of the rectangle. Together, this specifies the bottom left- hand corner of the rectangle (in a right-hand coordinate system)len_x
,len_y
: lengths of the rectangle sides in the specified dimensions. Adding both these to the position leads to the top-right hand corner of the rectanglerect_spec
: A matplotlib-compatible rectangle specification, i.e. (position, width, height)
The second tuple element are the limits in x and y direction, given as dict with keys x and y.
- Return type
Tuple[xarray.Dataset, Dict[str, tuple]]
utopya.eval.plots.abm module#
Implements plot functions for agent-based models, e.g. of agents and their movement in a domain.
- utopya.eval.plots.abm.MARKERS: Dict[str, matplotlib.path.Path] = {'fish': Path(array([[-5. , 0. ], [-2. , 0.2], [ 3. , 2. ], [ 3. , 0. ], [ 3. , -2. ], [-2. , -0.2], [-5. , 0. ]]), array([1, 4, 4, 4, 4, 4, 4], dtype=uint8)), 'fish2': Path(array([[-5. , 0. ], [-2. , 0.2], [ 3. , 2.5], [ 3. , 0. ], [ 3. , -2.5], [-2. , -0.2], [-5. , 0. ], [-3. , 0. ], [-5.5, -1.5], [-5. , 0. ], [-5.5, 1.5], [ 2. , 0. ], [-2. , -1.3], [-1. , 0. ], [-2. , 1.3]]), array([1, 4, 4, 4, 4, 4, 4, 1, 2, 2, 2, 1, 2, 2, 2], dtype=uint8)), 'wedge': Path(array([[ 0. , -0.1], [ 0.3, 0. ], [ 0. , 0.1], [ 0. , 0. ]]), array([ 1, 2, 2, 79], dtype=uint8))}#
Custom markers that can be used in
AgentCollection
, an essential part ofabmplot()
.Available markers:
wedge
: A triangle that can be used to denote orientations.fish
: A simple fish-like shape.fish2
: A more elaborate fish-like shape.
Hint
To have consistent orientations, note that markers should point along the positive x-axis. With increasing orientation values, they are rotated in counter-clockwise direction. Angles are measured in radians.
Note
Suggestions for additional markers are welcome.
- class utopya.eval.plots.abm.AgentCollection(xy: Union[numpy.ndarray, Sequence[Union[matplotlib.path.Path, Tuple[float, float]]]], *, marker: Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict] = 'auto', default_marker: Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict] = 'o', default_marker_oriented: Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict] = 'wedge', sizes: Optional[Union[float, Sequence[float]]] = None, size_scale: float = 1.0, normalize_marker_sizes: bool = True, orientations: Optional[Union[float, Sequence[float]]] = None, base_orientation: float = 0.0, tail_length: int = 0, tail_kwargs: Optional[dict] = None, tail_decay: float = 0.0, tail_max_segment_length: Optional[float] = None, use_separate_paths: bool = True, **kwargs)[source]#
Bases:
matplotlib.collections.PathCollection
A collection of agent markers and (optionally) their position history in the form of a tail. Combines
PathCollection
with aLineCollection
for the tails.- __init__(xy: Union[numpy.ndarray, Sequence[Union[matplotlib.path.Path, Tuple[float, float]]]], *, marker: Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict] = 'auto', default_marker: Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict] = 'o', default_marker_oriented: Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict] = 'wedge', sizes: Optional[Union[float, Sequence[float]]] = None, size_scale: float = 1.0, normalize_marker_sizes: bool = True, orientations: Optional[Union[float, Sequence[float]]] = None, base_orientation: float = 0.0, tail_length: int = 0, tail_kwargs: Optional[dict] = None, tail_decay: float = 0.0, tail_max_segment_length: Optional[float] = None, use_separate_paths: bool = True, **kwargs)[source]#
Set up an AgentCollection, visualizing agents and (optionally) their position history using a tail.
Hint
If you need a higher performance for this plot, consider not using the decaying tails, for which the line segments need to be drawn individually.
- Parameters
xy (Sequence[Tuple[float, float]]) – The positions of the agents. The number of agents is extracted from the length of this sequence or
(x, y)
positions or(N, 2)
array.marker (Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict], optional) –
The marker to use to denote agent positions. The following input types are possible:
A
Path
is used as it isA
dict
is used as keyword arguments to thePath
, wherevertices
can be a sequence of 2-tuples that defines the vertices of the path.A
Patch
already defines a path, which is extracted and used as marker. All other properties are ignored.str
is looked up inMARKERS
; if no such entry is available, the remaining options are evaluated.All other input is used to construct a
MarkerStyle
from which the path is extracted.
default_marker (Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict], optional) – The marker to use in case that
marker
is None and agents are not initialized with an orientation.default_marker_oriented (Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict], optional) – The marker to use in case that
marker
is None and agents are initialized with an orientation.sizes (Union[float, Sequence[float]], optional) – Agent sizes in units of area (of bounding box) squared. If a scalar value is given, all agents will have the same size.
size_scale (float, optional) – A scaling factor for the sizes.
normalize_marker_sizes (bool, optional) – If True, will normalize the size of the given
marker
. This is done by computing the area of the bounding box and scaling the path such that the bounding box has an area of one.orientations (Union[float, Sequence[float]], optional) – Single or individual orientations of the agents. Zero corresponds to pointing along the positive x-axis, with increasing orientation values leading to a counter-clockwise rotation. Angles need to be given in radians.
base_orientation (float, optional) – Rotates the given marker by this value such that all
orientations
have a constant offset.tail_length (int, optional) – For non-zero integers, will draw a tail behind the agents that traces their position history. This is only relevant if the collection is used as part of an animation where the position history can be aggregated upon each call to
set_offsets()
.tail_kwargs (dict, optional) – Keyword arguments that are passed to the
LineCollection
which is used to represent the tails.tail_decay (float, optional) – A decay factor. If non-zero, will multiply each consecutive tail segments
alpha
value with(1 - tail_decay)
.tail_max_segment_length (float, optional) – If set, will not draw tail segments that are longer than this value in either the x- or the y-direction. This can be useful if agents move in a periodic space where positions may jump.
use_separate_paths (bool, optional) –
If False, only a single path is used to represent all agents in the underlying
PathCollection
.Warning
Setting this to False should only be done if all agents can be thought of as identical, i.e. have the same size, color, marker, and orientation — otherwise this leads to subtle and seemingly random breakage in the form of markers not being drawn.
**kwargs – Passed on to
PathCollection
- property has_markers: bool#
Whether a marker will be shown; if disabled, can skip setting array data and thus increase performance somewhat …
- property tail_length: int#
Length of the tail of each agent, i.e. the number of historic offset positions that are connected into a line.
- property tails: Optional[matplotlib.collections.LineCollection]#
The
LineCollection
that represents the tails of the agents — or None if tails are not activated.Note
This collection still needs to be registered once with the axes via
add_collection()
.
- property markerpath: Optional[matplotlib.path.Path]#
Returns the used markerpath
- draw_tails(**kwargs) matplotlib.collections.LineCollection [source]#
Draws the tails from scratch, removing the currently added collection if there is one.
Note
If calling this, the collection representing the tails needs to be re-added to the desired axes. To update tail positions according to the offsets history, use
update_tails()
.
- update_tails() matplotlib.collections.LineCollection [source]#
Updates the collection that holds the tails using the offsets history.
- set_markersizes(sizes)[source]#
Sets the marker sizes, taking into account the size scaling.
Note
This behaves differently from the inherited
set_sizes
method and thus has a different name. The difference is thatset_sizes()
is also called during saving of a plot and would thus lead to repeated application of the size scaling, which is not desired.
- set_offsets(offsets) None [source]#
Sets the offsets, i.e. path positions of all agents.
Invokes
set_offsets()
and afterwards stores the offset history, using it forupdate_tails()
.
- set_orientations(orientations: Union[float, Sequence[float]]) None [source]#
Set the orientations of all agents. If a scalar is given, will set all orientations to that value. If any kind of sequence is given, will associate individual orientations with agents.
Note
This can only be used if the collection was initialized with
orientations
, see__init__()
.
- get_orientations() Sequence[float] [source]#
Returns the current orientations of all agents.
Note
Changing the returned object does not rotate the agents! Use
set_orientations()
to achieve that.
- _prepare_marker_path(marker: Union[matplotlib.path.Path, matplotlib.patches.Patch, str, list, dict]) matplotlib.path.Path [source]#
Generates the
Path
needed for the agent marker using a variety of setup methods, depending on argument type:Path
is used as it isPatch
already defines a path, which is extracted and used.str
is looked up inMARKERS
; if no such entry is available, the remaining options are evaluated.Other types construct a
MarkerStyle
from which the path is extracted.
After constructing the path, applies the base orientation by rotating it by that value.
- _compute_size_factors(paths: Sequence[matplotlib.path.Path]) numpy.ndarray [source]#
Given a sequence of Paths, computes the corresponding size factors which are used in
set_markersizes()
to scale the individual marker sizes. The resulting sizes are multiplied with the given size scale.If marker size normalization is activated, size factors may vary between the markers.
- _add_to_offsets_history(new_offsets: numpy.ndarray) None [source]#
Adds the given offset to the left side of the deque, pushing old entries off the right side of the deque.
If the tail segment length is limited, will mask the offset positions for individual agents if they differ by more than that value from their previous position. Note that in this case the history is no longer strictly correct; it is already evaluated for use in
draw_tails()
in order to increase performance and avoid evaluating this over and over again.
- _build_line_segments() numpy.ndarray [source]#
Creates the line segments for the tails using the offsets history
- _rotate_path(path: matplotlib.path.Path, *, base_vertices: numpy.ndarray, orientation: float) None [source]#
Sets the given path’s vertices by rotating (a copy of) the base vertices by the given
orientation
(in radians).
- set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, array=<UNSET>, capstyle=<UNSET>, clim=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, cmap=<UNSET>, color=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, gid=<UNSET>, hatch=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, markersizes=<UNSET>, mouseover=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, orientations=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, urls=<UNSET>, visible=<UNSET>, zorder=<UNSET>)#
Set multiple properties at once.
Supported properties are
- Properties:
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or scalar or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of colors or ‘face’ facecolor or facecolors or fc: color or list of colors figure: .Figure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or dashes or linestyles or ls: str or tuple or list thereof linewidth or linewidths or lw: float or list of floats markersizes: unknown mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: unknown offsets: unknown orientations: unknown path_effects: .AbstractPathEffect paths: unknown picker: None or bool or float or callable pickradius: unknown rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: .Transform url: str urls: list of str or None visible: bool zorder: float
- class utopya.eval.plots.abm.HandlerAgentCollection(yoffsets=None, sizes=None, **kwargs)[source]#
Bases:
matplotlib.legend_handler.HandlerPathCollection
Legend handler for
AgentCollection
instances.- create_collection(orig_handle, sizes, offsets, offset_transform) utopya.eval.plots.abm.AgentCollection [source]#
Returns an AgentCollection from which legend artists are created.
- create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)[source]#
Creates the artists themselves.
For original docstring see
matplotlib.legend_handler.HandlerBase.create_artists()
.
- utopya.eval.plots.abm._get_data(d: Union[xarray.core.dataarray.DataArray, xarray.core.dataset.Dataset], var: str) xarray.core.dataarray.DataArray [source]#
Retrieve data by key, e.g. for hue, size, …
- utopya.eval.plots.abm._parse_vmin_vmax(specs: dict, d: Union[xarray.core.dataarray.DataArray, xarray.core.dataset.Dataset], *, vmin_key: str = 'vmin', vmax_key: str = 'vmax') dict [source]#
Adapts
specs
dict entriesvmin_key
andvmax_key
, replacing their values with the minimum or maximum value of given datad
.
- utopya.eval.plots.abm._set_domain(*, ax: matplotlib.axes.Axes, layers: dict, mode: str = 'auto', extent: Tuple[float, float, float, float] = None, height: float = None, aspect: Union[float, int, str] = 'auto', update_only: bool = False, pad: float = 0.05) Optional[Tuple[float, float]] [source]#
Sets the axis limits and computes the area of the domain
- Parameters
ax (matplotlib.axes.Axes) – The axes to adjust
mode (str, optional) – Domain mode, can be
auto
,manual
,fixed
andfollow
. In fixed mode, all available data inlayers
is inspected to derive domain bounds. Infollow
mode, the currently used collection positions are used to determine the boundaries. Inauto
mode, will use afixed
domain if noextent
was given, otherwisemanual
mode is used.extent (Tuple[float, float, float, float], optional) – A manually set extent in form
(left, right, bottom, top)
. Alternatively, a 2-tuple will be interpreted as(0, right, 0, top)
.height (float, optional) – The height of the domain in data units
aspect (Union[float, int, str], optional) – The aspect ratio of the domain, the width being computed via
height * aspect
. Ifauto
, willupdate_only (bool, optional) – If true, will only make changes to the domain bounds if necessary, e.g. in
follow
mode.pad (float, optional) – Relative padding added to each side.
- Returns
The domain area (in data units squared) and the aspect ratio, i.e.
width/height
. The return value will be None ifupdate_only
was set.- Return type
- utopya.eval.plots.abm.draw_agents(d: Union[xarray.core.dataset.Dataset, xarray.core.dataarray.DataArray], *, x: str, y: str, ax: matplotlib.axes.Axes = None, _collection: Optional[utopya.eval.plots.abm.AgentCollection] = None, _domain_area: float = 1, marker: Union[matplotlib.path.Path, matplotlib.patches.Patch, str, list, dict] = 'auto', hue: str = None, orientation: Union[str, float, Sequence[float]] = None, size: Union[str, float, Sequence[float]] = None, size_norm: Union[str, dict, matplotlib.colors.Normalize] = None, size_vmin: float = None, size_vmax: float = None, size_scale: float = 0.0005, label: str = None, cmap: Union[str, dict] = None, norm: Union[str, dict] = None, vmin: Union[float, str] = None, vmax: Union[float, str] = None, cbar_label: str = None, cbar_labels: dict = None, add_colorbar: bool = None, cbar_kwargs: dict = None, **coll_kwargs) utopya.eval.plots.abm.AgentCollection [source]#
Draws agent positions onto the given axis.
Data can be a
DataArray
orDataset
withx
,y
and the other encodingshue
,orientation
andsize
being strings that denote- Parameters
d (Union[xarray.Dataset, xarray.DataArray]) – The agent data. The recommended format is that of datasets, because it can hold more data variables. If using data arrays, multiple coordinates can be used to set the data. Also, the
name
attribute needs to be set (to avoid accidentally using the wrong data).x (str) – Name of the data dimension or variable that holds x positions.
y (str) – Name of the data dimension or variable that holds y positions.
ax (matplotlib.axes.Axes, optional) – The axis to plot to; will use the current axis if not given.
_collection (Optional[AgentCollection], optional) – If a collection exists, will update this collection instead of creating a new one.
_domain_area (float, optional) – The domain area, used to normalize the marker sizes for a consistent visual appearance. This is only needed when initializing the collection and will set its
size_scale
parameter tosize_scale * _domain_area
.marker (Union[matplotlib.path.Path, matplotlib.patches.Patch, str, list, dict], optional) – Which marker to use for the agents. See
AgentCollection
for available arguments.hue (str, optional) – The name of the data dimension or variable that holds the values from which marker colors are determined.
orientation (Union[str, float, Sequence[float]], optional) – The name of the data variable or dimension that holds the orientation data (in radians). If scalar or sequence, will pass those explicit values through.
size (Union[str, float, Sequence[float]], optional) – The name of the data variable or dimension that holds the values from which the marker size is determined.
size_norm (Union[str, dict, matplotlib.colors.Normalize], optional) – A normalization for the sizes. The
ColorManager
is used to set up this normalization, thus offering all the corresponding capabilities. Actual sizes are computed by xarray.plot.utils._parse_size`.size_vmin (float, optional) – The value that is mapped to the smallest size of the markers.
size_vmax (float, optional) – The value that is mapped to the largest size of the markers.
size_scale (float, optional) – A scaling factor that is applied to the size of all markers; use this to control overall size.
label (str, optional) – How to label the collection that is created. Will be used as default colorbar label and for the legend.
cmap (Union[str, dict], optional) – The colormap to use for the markers. Supports
ColorManager
.norm (Union[str, dict], optional) – Norm to use for the marker colors. Supports
ColorManager
.vmin (Union[float, str], optional) – The value of the
hue
dimension that is mapped to the beginning of the colormap.vmax (Union[float, str], optional) – The value of the
hue
dimension that is mapped to the end of the colormap.cbar_labels (dict, optional) – Colorbar labels, parsed by the
ColorManager
.add_colorbar (bool, optional) – Whether to add a colorbar or not. Only used upon creating the collection.
cbar_kwargs (dict, optional) – Passed on to
create_cbar()
**coll_kwargs – Passed on to
AgentCollection
; see there for further available arguments.
- utopya.eval.plots.abm.abmplot(*, data: Dict[str, Union[xarray.core.dataset.Dataset, xarray.core.dataarray.DataArray]], hlpr: utopya.eval.plothelper.PlotHelper, to_plot: Dict[str, dict], frames: Optional[str] = None, frames_isel: Optional[Union[int, slice]] = None, domain: Union[str, dict, Tuple[float, float, float, float]] = 'fixed', adjust_figsize_to_domain: bool = True, figsize_aspect_offset: float = 0.2, suptitle_fstr: str = '{dim:} = {val:5d}', suptitle_kwargs: dict = {'fontfamily': 'monospace'}, add_legend: Optional[bool] = None, **shared_kwargs)[source]#
Plots agents in a domain, animated over time.
Features:
Plot multiple “layers” of agents onto the same axis.
Encode
hue
,size
andorientation
of all agents.Keep track of position history through an animation and draw the history as (constant or decaying) tails.
Automatically determine the domain bounds, allowing to dynamically follow the agents through the domain.
Generate marker paths ad-hoc or use pre-defined markers that are relevant in the context of visualizing agent-based models, e.g.
fish
.
Example output:
Corresponding plot configuration
The following configuration was used to generate the above example animation.
based_on: - .creator.universe - .plot.abm - .animation.ffmpeg - .animation.high_dpi select: # Test data: # xr.Datasets with data variables `x`, `y`, `orientation`, # each with `(time, agent)` dimensions. prey: abm/circle_walk_noisy predator: abm/circle_walk_noisy2 x: x y: y domain: mode: fixed # can be: fixed, follow pad: 0.1 aspect: 1 orientation: orientation frames: time to_plot: prey: marker: fish size_scale: 0.0005 # fraction of the domain a single marker takes up # Let colors encode the fish's orientation and configure the colorbar hue: orientation cmap: twilight vmin: min vmax: max label: orientation $\theta$ cbar_labels: 0: 0 1.570795: $π/2$ 3.14159: $π$ 4.712385: $3π/2$ 6.28318: $2π$ predator: # Use a larger and more predator-like marker with a fixed color marker: fish2 size_scale: 0.0010 color: black # Draw a tail for the last 12 positions tail_length: 12 tail_decay: 0.2 tail_max_segment_length: 0.5 # don't draw segments longer than this tail_kwargs: color: black alpha: 0.6 # start value, is multiplied by (1 - tail_decay) each frame linewidth: 1.5 capstyle: butt zorder: -42 # Make the suptitle more subtle suptitle_fstr: "$t = {val:3d}$" suptitle_kwargs: x: 0.90 ha: left fontfamily: monospace fontsize: medium
The used dummy data (
circle_walk…
) is anxarray.Dataset
with data variablesx
,y
,orientation
, each one spanning dimensionstime
andagents
. Data variables do not have coordinates in this case, but it would be possible to supply some.Development roadmap
The following extensions of this plot function are planned:
Subplot support, allowing to manually distribute to_plot entries onto individual subplots.
Faceting support, allowing to automatically distribute all data layers onto rows and columns and thus performing a dimensionality reduction on them.
- Parameters
data (Dict[str, Union[xarray.Dataset, xarray.DataArray]]) – A dict holding the data that is to be plotted.
hlpr (PlotHelper) – The plot helper instance.
to_plot (Dict[str, dict]) – Individual plot specifications. Each entry refers to one “layer” of agents being plotted and its key needs to match the corresponding entry in
data
. Seedraw_agents()
for available arguments. Note that theshared_kwargs
also end up in the entries here.frames (str, optional) – Which data dimension to use for the animation.
frames_isel (Union[int, slice], optional) – An index-selector that is applied on the
frames
dimension (without dropping empty dimensions resulting from this operation). Scalar values will be wrapped into a list of size one.domain (Union[str, dict, Tuple[float, float, float, float]], optional) – Specification of the domain on which the agents are plotted. If a 4-tuple is given, it defines the position of the fixed
(left, right, bottom, top)
borders of the domain; a 2-tuple will be interpreted as(0, right, 0, top)
. If a string is given, it determines the mode by which the domain is determined. It can befixed
(determine bounds from all agent positions, then keep them constant) orfollow
(domain dynamically follows agents, keeping them centered). If a dict is given, it is passed to_set_domain()
, and offers more options likepad
oraspect
.adjust_figsize_to_domain (bool, optional) – If True, will adjust the figure size to bring it closer to the aspect ratio of the domain, thus reducing whitespace.
figsize_aspect_offset (float, optional) – A constant offset that is added to the aspect ratio of the domain to arrive at the target aspect ratio of the figure used for
adjust_figsize_to_domain
.suptitle_fstr (str, optional) – The format string to use for the figure’s super-title. If empty or None, no suptitle is added. The format string can include the following keys:
dim
(frames dimension name),val
(current coordinate value, will be an index if no coordinates are available),coords
(a dict containing all layers’ iterator states), andframe_no
(enumerates the frame number).suptitle_kwargs (dict, optional) – Passed to
suptitle()
.add_legend (bool, optional) – Whether to add a legend. ⚠️ This is currently experimental and does not work as expected.
**shared_kwargs – Shared keyword arguments for all plot specifications. Whatever is specified here is used as a basis for each individual layer in
to_plot
, i.e. updated by the entries into_plot
. Seedraw_agents()
for available arguments.
utopya.eval.plots.attractor module#
This module provides plotting functions to visualize the attractive set of a dynamical system.
Todo
Migrate these to the more generic DAG-based interface.
- utopya.eval.plots.attractor.bifurcation_diagram(dm: utopya.eval.datamanager.DataManager, *, hlpr: utopya.eval.plothelper.PlotHelper, mv_data: xarray.core.dataset.Dataset, dim: Optional[str] = None, dims: Optional[Tuple[str, str]] = None, analysis_steps: Sequence[Union[str, Tuple[str, str]]], custom_analysis_funcs: Optional[Dict[str, Callable]] = None, analysis_kwargs: Optional[dict] = None, visualization_kwargs: Optional[dict] = None, to_plot: Optional[dict] = None, **kwargs) None [source]#
- Plots a bifurcation diagram for one or two parameter dimensions
(arguments
dim
ordims
).
- Parameters
dm (DataManager) – The data manager from which to retrieve the data
hlpr (PlotHelper) – The PlotHelper that instantiates the figure and takes care of plot aesthetics (labels, title, …) and saving
mv_data (xarray.Dataset) – The extracted multidimensional dataset
dim (str, optional) – The required parameter dimension of the 1d bifurcation diagram.
dims (str, optional) – The required parameter dimensions (x, y) of the 2d-bifurcation diagram.
analysis_steps (Sequence) –
The analysis steps that are to be made until one is conclusive. Applied per universe.
- If seq of str: The str will also be used as attractor key for
plotting if the test is conclusive.
- If seq of Tuple(str, str): The first str defines the attractor
key for plotting, the second str is a key within custom_analysis_funcs.
Default analysis_funcs are:
endpoint: utopya.dataprocessing.find_endpoint
fixpoint: utopya.dataprocessing.find_fixpoint
multistability: utdp.find_multistability
oscillation: utdp.find_oscillation
scatter: resolve_scatter
custom_analysis_funcs (dict) – A collection of custom analysis functions that will overwrite the default analysis funcs (recursive update).
analysis_kwargs (dict, optional) – The entries need to match the analysis_steps. The subentry (dict) is passed on to the analysis function.
visualization_kwargs (dict, optional) – The entries need to match the analysis_steps. The subentry (dict) is used to configure a rectangle to visualize the conclusive analysis step. Is passed to matplotlib.patches.rectangle. xy, width, height, and angle are ignored and set automatically. Required in 2d bifurcation diagram.
to_plot (dict, optional) –
The configuration for the data to plot. The entries of this key need to match the data_vars selected in mv_data. It is used to visualize the state of the attractor additionally to the visualization kwargs. Only for 1d-bifurcation diagram. sub_keys:
label
(str, optional): label in plotplot_kwargs
(dict, optional): passed to scatter for everyuniverse
- color (str, recommended): unique color for every
data_variable accross universes
**kwargs –
Collection of optional dicts passed to different functions
- plot_coords_kwargs (dict): Passed to ax.scatter to mark the
universe’s center in the bifurcation diagram
- rectangle_map_kwargs (dict): Passed to
utopya.eval.plots._utils.calc_pxmap_rectangles
legend_kwargs (dict): Passed to ax.legend
utopya.eval.plots.ca module#
This module provides plotting functions to visualize cellular automata.
- utopya.eval.plots.ca._prepare_hexgrid_data(data: Union[numpy.ndarray, xarray.core.dataarray.DataArray], *, x: Optional[str] = None, y: Optional[str] = None) Tuple[xarray.core.dataarray.DataArray, str, str] [source]#
Prepares data for
imshow_hexagonal()
by checking the given data and specified dimension names are consistent.
- utopya.eval.plots.ca._flatten_hexgrid_data(data: xarray.core.dataarray.DataArray) numpy.ndarray [source]#
Flattens hexgrid data in a specific way.
For consistency, this function should be used when calling
set_array()
on collections that represent hexagonal grid data.
- utopya.eval.plots.ca._plot_ca_property(prop_name: str, *, hlpr: utopya.eval.plothelper.PlotHelper, data: xarray.core.dataarray.DataArray, default_imshow_kwargs: dict, imshow_hexagonal_extra_kwargs: Optional[dict] = None, default_cbar_kwargs: Optional[dict] = None, grid_structure: Optional[str] = None, limits: Optional[Tuple[float, float]] = None, vmin: Optional[float] = None, vmax: Optional[float] = None, cmap: Optional[Union[dict, str]] = None, norm: Optional[Union[dict, str]] = None, add_colorbar: bool = True, set_axis_off: bool = True, title: Optional[str] = None, imshow_kwargs: Optional[dict] = None, cbar_labels: Optional[dict] = None, cbar_label_kwargs: Optional[dict] = None, cbar_tick_params: Optional[dict] = None, no_cbar_markings: bool = False, **cbar_kwargs) matplotlib.image.AxesImage [source]#
Helper function, used in
caplot()
andstate()
to plot a property on the given axis. Returns the created axes image object.Note
The arguments here are those within the individual entries of the
to_plot
argument for the above plotting functions.- Parameters
prop_name (str) – The property to plot
hlpr (PlotHelper) – The plot helper
data (xarray.DataArray) – The array-like data to plot as an image
default_imshow_kwargs (dict) – Default arguments for the imshow call, updated with individually-specified
imshow_kwargs
.imshow_hexagonal_extra_kwargs (dict) – Default arguments for hexagonal grids, ignored otherwise. This updates the
default_imshow_kwargs
and is in turn updated with individually-specifiedimshow_kwargs
.default_cbar_kwargs (dict) – Default arguments for the colorbar creation, updated with
cbar_kwargs
.grid_structure (str, optional) – Can be used to explicitly set the grid structure in cases where
data.attrs['grid_structure']
is not available or holds an invalid entry. This decides whether to usematplotlib.axes.Axes.imshow()
orimshow_hexagonal()
. Note that thegrid_properties
need to be passed via theimshow_kwargs
argument below.limits (Tuple[float, float], optional) – The data limits to use in the form
(vmin, vmax)
. Individual entries can also be None. Deprecated! Usevmin
andvmax
instead.vmin (float, optional) – The lower limit to use for the colorbar range.
vmax (float, optional) – The upper limit to use for the colorbar range.
cmap (Union[str, dict], optional) – The colormap to use. If a dict is given, defines a (discrete)
ListedColormap
from the values. Handled byColorManager
.norm (Union[str, dict], optional) – The normalization function to use. Handled by
ColorManager
.add_colorbar (bool, optional) – If false, will not draw a colorbar. Default is true.
set_axis_off (bool, optional) – If true (default), will set the axis to invisible.
title (str, optional) – The subplot figure title
imshow_kwargs (dict, optional) – Depending on grid structure, is passed on either to
imshow()
or toimshow_hexagonal()
.cbar_labels (dict, optional) – Passed to
ColorManager
to set up the label names alongside the givencmap
andnorm
.cbar_label_kwargs (dict, optional) – Passed to
create_cbar()
for controlling the aesthetics of colorbar labels.cbar_tick_params (dict, optional) – Passed to
create_cbar()
for controlling the aesthetics of colorbar ticks.no_cbar_markings (bool, optional) – Whether to suppress colorbar markings (ticks and tick labels).
**cbar_kwargs – Passed to
create_cbar()
- Returns
The created axes image representing the CA property.
- Return type
- Raises
ValueError – on invalid grid structure; supported structures are
square
andhexagonal
- utopya.eval.plots.ca.imshow_hexagonal(data: Union[xarray.core.dataarray.DataArray, numpy.ndarray], *, ax: Optional[matplotlib.axes._axes.Axes] = None, x: Optional[str] = None, y: Optional[str] = None, grid_properties: dict = {}, update_grid_properties: dict = {}, grid_properties_keys: dict = {}, extent: Optional[tuple] = None, scale: float = 1.01, draw_centers: bool = False, draw_center_radius: float = 0.1, draw_center_kwargs: dict = {}, hide_ticks: Optional[bool] = None, cmap: Optional[str] = None, norm: Optional[str] = None, vmin: Optional[float] = None, vmax: Optional[float] = None, collection_kwargs: dict = {}, **im_kwargs) matplotlib.image.AxesImage [source]#
Visualizes data using a grid of hexagons (⬢ or ⬣).
Owing to the many ways in which a hexagonal grid can be visualized, this function requires more information than
imshow()
. These so called grid properties need to be passed via thegrid_properties
argument or directly alongside the data viadata.attrs
(forDataArray
).The following grid properties are available:
- coordinate_mode (str):
In which way the data is stored. Currently only supports
offset
mode, i.e. with offset row and column coordinates. Coordinates of individual cells need not be given, nor can they be given: Assuming a regular hexagonal grid, all coordinates and sizes are completely deduced from the shape of the given data and the other grid parameters likepointy_top
andoffset_mode
.- pointy_top (bool):
Whether the hexagons have a pointy top (⬢) or a flat top (⬣). More precisely, with a pointy top, there is only a single vertex at the top and bottom of the hexagon (i.e. along the
y
dimension and the top/bottom of the resulting plot).- offset_mode (str):
Whether
even
orodd
rows or columns are offset towards higher values. In other words: For pointy tops, offset every second row toward the right. For flat tops, offset every second column towards the top. Offset distance is half a cell’s width and half a cell’s height, respectively.- space_size (Tuple[float, float], optional):
The size of the space in
(width, height)
that the hexagonal grid cells cover. If given, will make the assumption that the available number of hexagons in each dimension reach from one end of the space to the other, even if that means that the hexagons become distorted along the dimensions. If not given, will assume regular hexagons and use arbitrary units to cover the space; these hexagons will not be distorted.- space_offset (Tuple[float, float], optional):
Translates the space by
(offset_x, offset_y)
. Also applies to the case wherespace_size
was not given. Effectively, this refers to the coordinates of the bottom left-hand corner of the space.- space_boundary (str, optional):
Whether the space (regardless of explicitly given or deduced) describes the
outer
orinner
boundary of the hexagonal grid. Theouter
boundary (default) goes through the outermost vertices of the outermost cells. Theinner
boundary goes through some hexagon center, cutting off pointy tops and protruding parts of the hexagons such that the whole space is covered by hexagonal cells.
For example, grid properties may look like this:
grid_properties: # -- Required: coordinate_mode: offset pointy_top: true offset_mode: even # -- Optional: space_size: [8, 8] space_offset: [-4, -4] space_boundary: outer
With some 2D dummy grid data of shape
(21, 24)
, the corresponding output would be as follows. The darker cells denote the boundary and the corners; the lighter cells correspond to a “vertical” line in the third column of the grid.By setting the space boundary parameter to
inner
, the domain size remains the same, but the boundary cells are partially cut off:Removing all optional parameters, specifically the
space_size
, the size of the domain is arbitrary, so no labels are drawn. In addition, we can also mark the hexagon centers:Changing to flat tops and
odd
offset mode results in a figure with a different aspect ratio, while the hexagons remain regular.When specifying the domain size again, the hexagons need to be scaled non-uniformly to cover the domain:
Hint
For an excellent introduction to hexagonal grid representations, see this article.
See also
caplot()
integrates this function.Hexagonal grids documents usage and shows more examples.
- Parameters
data (Union[xarray.DataArray, numpy.ndarray]) – 2D array-like data that holds the grid information that is to be plotted. If the data is given as
DataArray
, itsattrs
are used to update the givengrid_properties
.ax (matplotlib.axes.Axes, optional) – The axes to draw to; if not given, will use the current axes.
x (str, optional) – Name of the data dimension that is to be represented on the x-axis of the plot. If not given, will use the first data dimension.
y (str, optional) – Name of the data dimension that is to be represented on the x-axis of the plot. If not given, will use the second data dimension.
grid_properties (dict, optional) – The grid properties dict, which needs to specify the above properties in order to determine how to represent the data. This dict is first updated with potentially available
data.attrs
and subsequently updated with theupdate_grid_properties
.update_grid_properties (dict, optional) – Updates the grid properties, see above.
grid_properties_keys (dict, optional) – A mapping that can be used if the given data has grid properties given under different names. For instance,
{"space_size": "size"}
would read thesize
entry instead ofspace_size
.extent (tuple, optional) – A custom space extent, denoting the edges
(left, right, bottom, top)
of the domain in data units.scale (float, optional) – A scaling factor for the size of the hexagons. The default value is very slightly larger than 1 to reduce aliasing artefacts on exactly overlapping hexagon edges. Scaling is uniform.
draw_centers (bool, optional) – Whether to additionally draw the center points of all hexagons.
draw_center_radius (float, optional) – The relative radius of the center points in units of
min(cell_width, cell_height) / 2
.draw_center_kwargs (dict, optional) – Additional arguments that are passed to the
PatchCollection
used to draw the center points.hide_ticks (bool, optional) – Whether to hide the ticks and tick labels. If None, will hide ticks if no
space_size
grid property was given (in which case the units are assumed irrelevant).cmap (str, optional) – The colormap to use
norm (str, optional) – The normalization to use
vmin (float, optional) – The minimum value of the color range to use
vmax (float, optional) – The maximum value of the color range to use
collection_kwargs (dict, optional) – Passed on to the
PolyCollection
that is used to represent the hexagons.**im_kwargs – Passed on to
matplotlib.image.AxesImage
that is created from the whole axis. Can be used to setinterpolation
or similar options.
- Returns
The imshow-like object containing the hexagonal grid.
- Return type
- utopya.eval.plots.ca.caplot(*, hlpr: utopya.eval.plothelper.PlotHelper, data: dict, to_plot: Dict[str, dict], from_dataset: Optional[xarray.core.dataset.Dataset] = None, frames: str = 'time', frames_isel: Optional[Union[int, Sequence]] = None, grid_structure: Optional[str] = None, aspect: float = 1.0, aspect_pad: float = 0.1, size: Optional[float] = None, col_wrap: Union[int, str, bool] = 'auto', imshow_hexagonal_extra_kwargs: Optional[dict] = None, default_imshow_kwargs: Optional[dict] = None, default_cbar_kwargs: dict = {'aspect': 20, 'fraction': 0.04}, suptitle_fstr: str = '{} = {}', suptitle_kwargs: Optional[dict] = None)[source]#
Plots an animated series of one or many 2D Cellular Automata states.
The data used for plotting is assembled from
data
using the keys that are specified into_plot
. Alternatively, thefrom_dataset
argument can be used to pass a dataset which contains all the required data.The keys in
to_plot
should match the names of data variables. The values into_plot
specify the individual subplots’ properties like the color map that is to be used or the minimum or maximum values.For plotting square grids,
matplotlib.axes.Axes.imshow()
is used and generates output like this:For a grid with hexagonal cells,
imshow_hexagonal()
is used; more details on how the cells are mapped to the space can be found there. The output (for the same dummy data as used above) may look like this:Finally, this plot function is specialized to generate animations along the
frames
dimension of the data, e.g.time
:Requirements on the CA data
The selected data (keys in
to_plot
that correspond to DAG results indata
) should have two spatial dimensions and one data dimension that goes along theframes
dimension.All coordinates should be identical, otherwise the behavior is not defined or alignment might fail.
For hexagonal grid structure, note the requirements given in
imshow_hexagonal()
.- Parameters
hlpr (PlotHelper) – The plot helper instance
data (dict) – The selected data
Which data to plot and how. The keys of this dict refer to an item within the selected
data
or the given dataset. Each of these keys is expected to hold yet another dict, supporting the following configuration options (all optional):title
(str, optional):The title for this sub-plot.
cmap
(Union[str, list, dict], optional):Which colormap to use. This argument is handled by the
ColorManager
, providing many ways in which to define the colormap. For instance, by passing mapping from labels to colors, a discrete colormap is created: The keys will be the labels and the values will be their colors. Association happens in the order of entries, with values being inferred fromlimits
, if given. For more information and examples, see the docstring of theColorManager
.
norm
(Union[str, dict], optional):The normalization function to use, also handled by the
ColorManager
.
vmin
(float, optional):The fixed lower data limit for this property; if not given, uses auto-scaling, which may lead to jumps in the animation. Can also be
'min'
in which case the global minimum of the available data is used.
vmax
(float, optional):Same as
vmin
, but with the maximum and allowing'max'
argument for choosing the global maximum.
limits
(Union[tuple, list], optional):Deprecated! Use
vmin
andvmax
instead.
label
(str, optional):The colorbar label.
imshow_kwargs
(dict, optional):Passed on to the imshow invocation, i.e. to
imshow()
orimshow_hexagonal()
.
**kwargs
:Further arguments control the colorbar appearance, their labels, ticks, and other plot specifics. For more detailed information about available arguments, see
_plot_ca_property()
, which takes care of plotting the individualto_plot
entries.
from_dataset (xarray.Dataset, optional) – If given, will use this object instead of assembling a dataset from
data
andto_plot
keys.frames (str, optional) – Name of the animated dimension, typically the time dimension.
frames_isel (Union[int, Sequence], optional) – The index selector for the frames dimension. Can be a single integer but also a range expression.
grid_structure (str, optional) – The underlying grid structure, can be
square
,hexagonal
, ortriangular
(not implemented). If None, will try to read it from the individual properties’ data attributegrid_structure
.aspect (float, optional) – The aspect ratio (width/height) of the subplots; should match the aspect ratio of the data.
aspect_pad (float, optional) – A factor that is added to the calcuation of the subplots width. This can be used to create a horizontal padding between subplots.
size (float, optional) – The height in inches of a subplot. Is used to determine the subplot size with the width being calculated by
size * (aspect + aspect_pad)
.col_wrap (Union[int, str, bool], optional) – Controls column wrapping. If
auto
, will compute a column wrapping that leads to an (approximately) square subplots layout (not taking into account the subplots aspect ratio, only the grid layout). This will start producing a column wrapping with four or more properties to plot.default_imshow_kwargs (dict, optional) – The default parameters passed to the underlying imshow plotting function. These are updated by the values given via
to_plot
.default_cbar_kwargs (dict, optional) – The default parameters for the colorbar that is added to applicable subplots. These are updated by the parameters given under
to_plot
.suptitle_fstr (str, optional) – A format string used to create the suptitle string. Passed arguments are
frames
and the currently selected frames coordinate (not the index!). If this evaluates to False, will not create a figure suptitle.suptitle_kwargs (dict, optional) – Passed on to
fig.suptitle
.
- utopya.eval.plots.ca.state(dm: utopya.eval.datamanager.DataManager, *, uni: utopya.eval.groups.UniverseGroup, hlpr: utopya.eval.plothelper.PlotHelper, model_name: str, to_plot: dict, time_idx: int, default_imshow_kwargs: Optional[dict] = None, **_kwargs)[source]#
Plots the state of the cellular automaton as a 2D heat map. This plot function can be used for a single plot, but also supports animation.
Which properties of the state to plot can be defined in
to_plot
.- Parameters
dm (DataManager) – The DataManager that holds all loaded data
uni (UniverseGroup) – The currently selected universe, parsed by the
UniversePlotCreator
.hlpr (PlotHelper) – The plot helper
model_name (str) – The name of the model of which the data is to be plotted
to_plot (dict) –
Which data to plot and how. The keys of this dict refer to a path within the data and can include forward slashes to navigate to data of submodels. Each of these keys is expected to hold yet another dict, supporting the following configuration options (all optional):
- cmap (str or dict): The colormap to use. If it is a dict, a
discrete colormap is assumed. The keys will be the labels and the values the color. Association happens in the order of entries.
title (str): The title for this sub-plot
- limits (2-tuple, list): The fixed heat map limits of this
property; if not given, limits will be auto-scaled.
**imshow_kwargs: passed on to imshow invocation
time_idx (int) – Which time index to plot the data of. Is ignored when creating an animation.
default_imshow_kwargs (dict, optional) – The default parameters passed to the underlying imshow plotting function. These are updated by the values given via
to_plot
.
- Raises
ValueError – Shape mismatch of data selected by
to_plot
AttributeError – Got unsupported arguments (referring to the old data transformation framework)
utopya.eval.plots.distributions module#
DAG-based distribution plotting functions
- utopya.eval.plots.distributions.histogram(*, data: dict, hlpr: utopya.eval.plothelper.PlotHelper, x: str, hue: Optional[str] = None, frames: Optional[str] = None, coarsen_by: Optional[int] = None, align: str = 'edge', bin_widths: Optional[Union[str, Sequence[float]]] = None, suptitle_kwargs: Optional[dict] = None, show_histogram_info: bool = True, **bar_kwargs)[source]#
Shows a distribution as a stacked bar plot, allowing animation.
Expects as DAG result
counts
an xr.DataArray of one, two, or three dimensions. Depending on thehue
andframes
arguments, this will be represented as a stacked barplot and as an animation, respectively.- Parameters
data (dict) – The DAG results
hlpr (PlotHelper) – The PlotHelper
x (str) – The name of the dimension that represents the position of the histogram bins. By default, these are the bin centers.
hue (str, optional) – Which dimension to represent by stacking bars of different hue on top of each other
frames (str, optional) – Which dimension to represent by animation
coarsen_by (int, optional) – By which factor to coarsen the dimension specified by
x
. Uses xr.DataArray.coarsen and pads boundary values.align (str, optional) – Where to align bins. By default, uses
edge
for alignment, as this is more exact for histograms.bin_widths (Union[str, Sequence[float]], optional) – If not given, will use the difference between the
x
coordinates as bin widths, padding on the right side using the last value If a string, assume that it is a DAG result and retrieve it fromdata
. Otherwise, use it directly for thewidth
argument ofplt.bar
, i.e. assume it’s a scalar or a sequence of bin widths.suptitle_kwargs (dict, optional) – Description
show_histogram_info (bool, optional) – Whether to draw a box with information about the histogram.
**bar_kwargs – Passed on
hlpr.ax.bar
invocation
- Returns
None
- Raises
ValueError – Bad dimensionality or missing
bin_widths
DAG result
utopya.eval.plots.graph module#
This module provides graph plotting functions.
- utopya.eval.plots.graph.graph_array_from_group(graph_group: utopya.eval.groups.GraphGroup, *, graph_creation: dict = None, register_property_maps: dict = None, clear_existing_property_maps: bool = True, times: dict = None, sel: dict = None, isel: dict = None) xarray.core.dataarray.DataArray [source]#
From a
utopya.eval.groups.GraphGroup
creates axarray.DataArray
withobject
dtype, containing thenetworkx.Graph
objects created from the graph group at the specified points in the group’s coordinate space.From all coordinates provided via the selection kwargs the cartesian product is taken. Each of those points represents one entry in the returned
xarray.DataArray
. The selection kwargs ingraph_creation
are ignored silently.- Parameters
graph_group (utopya.eval.groups.GraphGroup) – The graph group to create the graph array from
graph_creation (dict, optional) – Graph creation configuration
register_property_maps (dict, optional) – Property maps to be registered before graph creation
clear_existing_property_maps (bool, optional) – Whether to remove any existing property map at first
times (dict, optional) – Equivalent to a
sel.time
entry. (Deprecated!)sel (dict, optional) – Select by value
isel (dict, optional) – Select by index
- Returns
networkx.Graph
with the respective graphgroup coordinates
- Return type
- utopya.eval.plots.graph.graph_animation_update(*, hlpr: utopya.eval.plothelper.PlotHelper, graphs: Optional[xarray.core.dataarray.DataArray] = None, graph_group=None, graph_creation: Optional[dict] = None, register_property_maps: Optional[dict] = None, clear_existing_property_maps: bool = True, positions: Optional[dict] = None, animation_kwargs: Optional[dict] = None, suptitle_kwargs: Optional[dict] = None, **drawing_kwargs)[source]#
Graph animation frame generator. Yields whenever the plot helper may grab the current frame.
If
graphs
is given, the networkx graphs in the array are used to create the frames.Otherwise, use a graph group. The frames are defined via the selectors in
animation_kwargs
. From all provided coordinates the cartesian product is taken. Each of those points defines one graph and thus one frame. The selection kwargs ingraph_creation
are ignored silently.- Parameters
hlpr (PlotHelper) – The plot helper
graphs (xarray.DataArray, optional) – Networkx graphs to draw. The array will be flattened beforehand.
graph_group (None, optional) – Required if
graphs
is None. The GraphGroup from which to generate the animation frames as specified via sel and isel inanimation_kwargs
.graph_creation (dict, optional) – Graph creation configuration. Passed to
create_graph_from_group()
ifgraph_group
is given.register_property_maps (dict, optional) – Passed to
create_graph_from_group()
ifgraph_group
is given.clear_existing_property_maps (bool, optional) – Passed to
create_graph_from_group()
ifgraph_group
is given.positions (dict, optional) – The node position configuration. If
update_positions
is True the positions are reconfigured for each frame.animation_kwargs (dict, optional) –
Animation configuration. The following arguments are allowed:
- times (dict, optional):
Deprecated: Equivaluent to a
sel.time
entry.- sel (dict, optional):
Select by value. Coordinate values (or
from_property
entry) keyed by dimension name.- isel (dict, optional):
Select by index. Coordinate indices keyed by dimension. May be given together with
sel
if no key appears in both.- update_positions (bool, optional):
Whether to reconfigure the node positions for each frame (default=False).
- update_colormapping (bool, optional):
Whether to reconfigure the nodes’ and edges’
ColorManager
for each frame (default=False). If False, the colormapping (and the colorbar) is configured with the first frame and then fixed.- skip_empty_frames (bool, optional):
Whether to skip the frames where the selected graph is missing or of a type different than
nx.Graph
(default=False). If False, such frames are empty.
suptitle_kwargs (dict, optional) – Passed on to the
PlotHelper
and itsset_suptitle
helper function. Only used in animation mode. Thetitle
can be a format string containing a placeholder with the dimension name as key for each dimension along which selection is done. The format string is updated for each frame of the animation. The default is<dim-name> = {<dim-name>}
for each dimension.**drawing_kwargs – Passed to
GraphPlot
- utopya.eval.plots.graph.draw_graph(*, hlpr: utopya.eval.plothelper.PlotHelper, data: dict, graph_group_tag: str = 'graph_group', graph: Optional[Union[networkx.classes.graph.Graph, xarray.core.dataarray.DataArray]] = None, graph_creation: Optional[dict] = None, graph_drawing: Optional[dict] = None, graph_animation: Optional[dict] = None, register_property_maps: Optional[Sequence[str]] = None, clear_existing_property_maps: bool = True, suptitle_kwargs: Optional[dict] = None)[source]#
Draws a graph either from a
GraphGroup
or directly from anetworkx.Graph
using theGraphPlot
class.If the graph object is to be created from a graph group the latter needs to be selected via the TransformationDAG. Additional property maps can also be made available for plotting, see
register_property_map
argument. Animations can be created either from a graph group by using the select interface ingraph_animation
or by passing a DataArray of networkx graphs via thegraph
argument.For more information on how to use the transformation framework, refer to the dantro documentation and its
TransformationDAG
class.For more information on how to configure the graph layout refer to the
GraphPlot
documentation.- Parameters
hlpr (PlotHelper) – The PlotHelper instance for this plot
data (dict) – Data from TransformationDAG selection
graph_group_tag (str, optional) – The TransformationDAG tag of the graph group
graph (Union[networkx.Graph, xarray.DataArray], optional) – If given, the
data
andgraph_creation
arguments are ignored and this graph is drawn directly. If a DataArray of graphs is given, the first graph is drawn for a single graph plot. In animation mode the (flattened) array represents the animation frames.graph_creation (dict, optional) – Configuration of the graph creation. Passed to
GraphGroup.create_graph
.graph_drawing (dict, optional) – Configuration of the graph layout. Passed to
GraphPlot
.graph_animation (dict, optional) –
Animation configuration. The following arguments are allowed:
- times (dict, optional):
Deprecated: Equivaluent to a
sel.time
entry.- sel (dict, optional):
Select by value. Dictionary with dimension names as keys. The values may either be coordinate values or a dict with a single
from_property
(str) entry which specifies a container within theGraphGroup
or registered external data from which the coordinates are extracted.- isel (dict, optional):
Select by index. Coordinate indices keyed by dimension. May be given together with
sel
if no key appears in both.- update_positions (bool, optional):
Whether to update the node positions for each frame by recalculating the layout with the parameters specified in graph_drawing.positions. If this parameter is not given or false, the positions are calculated once initially and then fixed.
- update_colormapping (bool, optional):
Whether to reconfigure the nodes’ and edges’
ColorManager
for each frame (default=False). If False, the colormapping (and the colorbar) is configured with the first frame and then fixed.- skip_empty_frames (bool, optional):
Whether to skip the frames where the selected graph is missing or of a type different than
networkx.Graph
(default=False). If False, such frames are empty.
register_property_maps (Sequence[str], optional) – Names of properties to be registered in the graph group before the graph creation. The property names must be valid TransformationDAG tags, i.e., be available in
data
. Note that the tags may not conflict with any valid path reachable from inside the selectedGraphGroup
.clear_existing_property_maps (bool, optional) – Whether to clear any existing property maps from the selected
GraphGroup
. This is enabled by default to reduce side effects from previous plots. Set this to False if you have property maps registered with the GraphGroup that you would like to keep.suptitle_kwargs (dict, optional) – Passed on to the PlotHelper’s
set_suptitle
helper function. Only used in animation mode. Thetitle
can be a format string containing a placeholder with the dimension name as key for each dimension along which selection is done. The format string is updated for each frame of the animation. The default is<dim-name> = {<dim-name>}
for each dimension.
- Raises
ValueError – On invalid or non-computed
TransformationDAG
tags inregister_property_maps
or invalid graph group tag.
utopya.eval.plots.snsplot module#
Implements seaborn-based plotting functions
- utopya.eval.plots.snsplot.snsplot(*, data: dict, hlpr: utopya.eval.plothelper.PlotHelper, sns_kind: str, free_indices: Tuple[str, ...], optional_free_indices: Tuple[str, ...] = (), auto_encoding: Optional[Union[bool, dict]] = None, reset_index: bool = False, to_dataframe_kwargs: Optional[dict] = None, dropna: bool = False, dropna_kwargs: Optional[dict] = None, sample: Union[bool, int] = False, sample_kwargs: Optional[dict] = None, **plot_kwargs) None [source]#
Interface to seaborn’s figure-level plot functions. Plot functions are selected via the
sns_kind
argument:relplot
:seaborn.relplot()
displot
:seaborn.displot()
catplot
:seaborn.catplot()
lmplot
:seaborn.lmplot()
clustermap
:seaborn.clustermap()
(not faceting)pairplot
:seaborn.pairplot()
(not faceting)jointplot
:seaborn.jointplot()
(not faceting)
- Parameters
data (dict) – The data transformation framework results, expecting a single entry
data
which can be apandas.DataFrame
or anxarray.DataArray
orxarray.Dataset
.hlpr (PlotHelper) – The plot helper instance
sns_kind (str) – Which seaborn plot to use, see list above.
free_indices (Tuple[str]) – Which index names not to associate with a layout encoding; seaborn uses these to calculate the distribution statistics.
optional_free_indices (Tuple[str], optional) – These indices will be added to the free indices if they are part of the data frame. Otherwise, they are silently ignored.
auto_encoding (Union[bool, dict], optional) – Auto-encoding options.
reset_index (bool, optional) – Whether to reset indices such that only the
free_indices
remain as indices and all others are converted into columns.to_dataframe_kwargs (dict, optional) – For xarray data types, this is used to convert the given data into a pandas.DataFrame.
sample (bool, optional) – If True, will sample a subset from the final dataframe, controlled by
sample_kwargs
sample_kwargs (dict, optional) – Passed to
pandas.DataFrame.sample()
.**plot_kwargs – Passed on to the selected plotting function.
utopya.eval.plots.time_series module#
A generic, DAG-supporting time series plot
- utopya.eval.plots.time_series.time_series(*, data: dict, hlpr: utopya.eval.plothelper.PlotHelper, x: str = 'time', label_fstr: str = '{:.2g}', **plot_kwargs)[source]#
This is a generic plotting function that plots one or multiple time series from the
data
tag that is selected via the DAG framework.The data needs to be an xarray object. If y is an xr.DataArray, it is assumed to be one- or two-dimensional. If is an
xarray.Dataset
, all data variables are plotted and their name is used as the label.For the x axis values, the corresponding
time
coordinates are used; these need to be part of the dataset!Note
For a more generic plot, see dantro’s
facet_grid()
, which is available under.plot.facet_grid
in utopya.- Parameters
data (dict) – The data selected by the DAG framework
hlpr (PlotHelper) – The plot helper
x (str, optional) – Name of the coordinate dimension to put on the x-axis, typically (and by default)
time
.label_fstr (str, optional) – Formatting to use for label in case of the data being an
xarray.DataArray
.**plot_kwargs – Passed on ot
matplotlib.pyplot.plot()
.