Graph Plots


Draw Graph

The draw_graph plot function combines and extends the following four networkx plotting utilities:

It preserves the full configurability of the above functions while offering additional features, e.g. plotting directly from a GraphGroup, automatically mapping data to layout properties, or creating graph animations.

Exemplary plot configuration

Check out an exemplary single graph plot configuration for the CopyMeGraph model:

Example_graph_plot:
  based_on: .dag.graph

  select:
    graph_group: data/CopyMeGraph/g_dynamic

  # The `graph_creation` configuration is passed to  `GraphGroup.create_graph`
  graph_creation:
    at_time_idx: -1
    node_props:
      - some_state
      - some_trait
    edge_props:
      - weights

  # `graph_drawing` contains all the layout configurations
  graph_drawing:
    positions:
      model: spring     # Specify the node positioning model to be used. The
                        # spring model reduces overall edge lengths.
      k: 1              # The spring model can mainly be tweaked by changing
      iterations: 100   # the optimal edge length `k'` and the maximum number
                        # of iterations that are done.

    # Only plot a subgraph induced by a set of nodes.
    select:
      center: 0        # Do radial node selection
      radius: 2

    # The four entries below configure the layout of nodes, edges, node-labels,
    # and edge-labels. After property mapping is applied, they are passed to
    # the respective networkx plot functions.
    # Have a look at the networkx documentation for a list of additional kwargs:
    # https://networkx.github.io/documentation/stable/reference/drawing.html
    nodes:
      node_size:
        from_property: some_trait     # Map the 'some_trait' property to the
                                      # node size.
        scale_to_interval: [30, 250]  # Linearly rescale the node sizes (the
                                      # default node size is 300).
    edges:
      edge_color:
        from_property: weights        # The 'weights' are mapped to the edge
                                      # color.
      edge_cmap: magma
    node_labels:
      enabled: True                   # Labels have to be enabled explicitly.
      labels:                         # Provide a dict of custom node labels.
        0: label0
        1: label1
        2: label2
      show_only: [0, 1]
    edge_labels:
      enabled: True
      edge_labels:
        [0, 1]: label01
        [1, 3]: label13

    # Highlight some nodes and edges
    mark_nodes:
      nodelist: [1, 4, 2]
      color: 'r'
    mark_edges:
      colors:
        [0, 1]: 'r'
        [1, 2]: 'g'

Note

If you have all node_props or edge_props in one container (HDF5 dataset) respectively, there are two possibilities to make subselections in the containers:

  1. When you only use either node or edge properties, or you want to make the same subselection on both your node and your edge dataset, you can simply do a .sel: {property: my_prop}, where property is your dataset dimension, and my_prop the coordinate, or you can do the respective .isel

  2. When you need to perform different subselections on your node and edge datasets—say you want node betweenness centrality and edge weight—you need to specify them via the DAG’s select interface, and the procedure needs to include the following steps:

select:
    betw:
      path: network/vertex_metrics
      transform:
        - .sel: [!dag_prev , {property: betweenness}]
        - .squeeze: !dag_prev
          kwargs: {drop: true}
    wei: network/edge_properties
        - .sel: [!dag_prev , {property: weight}]
        - .squeeze: !dag_prev
          kwargs: {drop: true}
    graph_group: g_static
register_property_maps:
    - betw
    - wei
compute_only: [graph_group, betw, wei]
# clear_existing_property_maps: false
graph_creation:
    at_time_idx: 0
    edge_props: [wei]
    node_props: [betw]
    # sel: { time: 0 } # applied to both properties
graph_drawing:
    edges:
      edge_color: k
      width:
        from_property: wei
        scale_to_interval: [.1, 2.]
    nodes:
      node_color:
        from_property: betw

ColorManager configuration

With the ColorManager integrated in draw_graph you can conveniently configure the colormap, norm, and colorbar. The examples below are meant to give an overview of its configuration possibilities. In the examples, the node-specific arguments are used. For configuring edge-colors, replace cmap, vmin, and vmax by edge_cmap, edge_vmin, and edge_vmax. For more details, see ColorManager.

A customized discrete colormap (e.g., for visualizing categorical properties) can be created via the cmap.from_values argument. The matching colorbar labels can be defined via colorbar.labels (If the categories are [0, 1, 2, ...] one could also use the shortcut syntax, see ColorManager):

cmap:
  from_values:
    0: red
    1: green
    2: blue
colorbar:
  enabled: true  # enabled by default, if property mapping was done for the node colors
  labels:
    0: foo
    1: bar
    2: baz
  # additional colorbar styling arguments:
  shrink: .2
  aspect: 10
  orientation: horizontal

For a nonlinear color-mapping, adjust the cmap_norm:

cmap:
  name: magma
  under: black
  over: white
  bad: red
cmap_norm:
  name: LogNorm   # Can be Normalize, NoNorm, LogNorm, PowerNorm, BoundaryNorm,
                  # SymLogNorm, TwoSlopeNorm.
                  # Specify via `name` key in order to provide additional
                  # arguments if needed
vmin: 0.1
vmax: 1000
colorbar:
  enabled: true
  extend: both    # to show under/over

Hint

When using the BoundaryNorm together with one of the pre-registered colormaps (e.g., viridis), use the lut argument to resample the colormap to have lut entries in the lookup table. Set lut = <BoundaryNorm.ncolors> to use the full colormap range.

utopya.plot_funcs.dag.graph.draw_graph(*, hlpr: utopya.plotting.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 a networkx.Graph using the GraphPlot 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 in graph_animation or by passing a DataArray of networkx graphs via the graph argument.

For more information on how to use the transformation framework, refer to the dantro documentation.

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[nx.Graph, xr.DataArray], optional) – If given, the data and graph_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 withing the GraphGroup 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 nx.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 selected GraphGroup.

  • 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. The title 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 in register_property_maps or invalid graph group tag.

Detailed API Reference

This module provides graph plotting functions.

utopya.plot_funcs.dag.graph.graph_array_from_group(graph_group, *, graph_creation: Optional[dict] = None, register_property_maps: Optional[dict] = None, clear_existing_property_maps: bool = True, times: Optional[dict] = None, sel: Optional[dict] = None, isel: Optional[dict] = None) xarray.core.dataarray.DataArray[source]

From a GraphGroup creates a DataArray containing the networkx graphs 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 DataArray. The selection kwargs in graph_creation are ignored silently.

Parameters
  • graph_group – The graph group

  • 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) – Deprecated: Equivalent to a sel.time entry

  • sel (dict, optional) – Select by value

  • isel (dict, optional) – Select by index

Returns

networkx graphs with the respective graph group coordinates

Return type

xr.DataArray

utopya.plot_funcs.dag.graph.graph_animation_update(*, hlpr: utopya.plotting.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 in graph_creation are ignored silently.

Parameters
  • hlpr (PlotHelper) – The plot helper

  • graphs (xr.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 in animation_kwargs.

  • graph_creation (dict, optional) – Graph creation configuration. Passed to create_graph_from_group() if graph_group is given.

  • register_property_maps (dict, optional) – Passed to create_graph_from_group() if graph_group is given.

  • clear_existing_property_maps (bool, optional) – Passed to create_graph_from_group() if graph_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’s set_suptitle helper function. Only used in animation mode. The title 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.plot_funcs.dag.graph.draw_graph(*, hlpr: utopya.plotting.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 a networkx.Graph using the GraphPlot 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 in graph_animation or by passing a DataArray of networkx graphs via the graph argument.

For more information on how to use the transformation framework, refer to the dantro documentation.

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[nx.Graph, xr.DataArray], optional) – If given, the data and graph_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 withing the GraphGroup 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 nx.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 selected GraphGroup.

  • 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. The title 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 in register_property_maps or invalid graph group tag.

For detailed descriptions of the networkx plot functions that are used here, refer to the networkx docs.