Selections

Selection

class graphics.Selection(context)[source]
add() → self[source]

Adds all elements in the current selection to the canvas. This should be called immediately after a selection of new elements is created. If the selection contains multiple elements, they will not necessarily be added in order.

Returns

A new instance of the current selection with animations disabled, allowing initial attributes to be configured.

remove() → self[source]

Removes all elements in the current selection from the canvas.

set(attrs, **kwargs) → self[source]

Sets one or more custom attributes on all elements in the current selection. The attributes are provided using a dictionary, where each (key, value) pair corresponds to the method and argument setting the same attribute. Keyword arguments can also be used in the same way. For example:

node.color('red').size((20, 30)).svgattr('stroke', 'blue')
# is equivalent to
node.set(color = 'red',
         size = (20, 30),
         svgattr = {
            'stroke': 'blue'
         })
Parameters
  • attrs (ElementArg[Dict[str, Any]]) – (Optional) A dictionary of custom attributes.

  • kwargs (Dict[str, Any]) – Custom attributes as keywork arguments.

visible(visible) → self[source]

Sets whether or not the elements in the current selection should be visible. This can be animated in the same way as additions and removals. However, in contrast to removing, disabling visibility will not clear attributes or affect layout.

Parameters

visible – Whether or not the elements should be visible.

eventQ(queue) → self[source]

Sets the queue onto which all events triggered by the selection should be added. Each queue handles events independently, and all queues execute in parallel. Since queues can be delayed (see pause()), this effectively enables multiple animations to run simultaneously.

The None queue is special; all events added to it will execute immediately. The default queue is named “default”.

Parameters

queue (Union[Any, None]) – The ID of the queue, which will be converted to a string, or None for the immediate queue. Defaults to “default”.

Returns

A new instance of the current selection using the specified event queue.

duration(seconds) → self[source]

Configures the duration of all animations triggered by the selection. A duration of 0 will ensure that changes occur immediately. The default duration is 0.5.

Parameters

seconds (ElementArg[Union[int, float]]) – The animation duration, in seconds.

Returns

A new instance of the current selection using the specified animation duration.

ease(ease) → self[source]

Configures the ease function used in all animations triggered by the selection. This will affect the way attributes transition from one value to another. More information is available here: https://github.com/d3/d3-ease.

Parameters

ease (ElementArg[str]) –

The name of the ease function, based on the functions found in D3. The full list is below:

”linear”, “poly”, “poly-in”, “poly-out”, “poly-in-out”, “quad”, “quad-in”, “quad-out”, “quad-in-out”, “cubic”, “cubic-in”, “cubic-out”, “cubic-in-out”, “sin”, “sin-in”, “sin-out”, “sin-in-out”, “exp”, “exp-in”, “exp-out”, “exp-in-out”, “circle”, “circle-in”, “circle-out”, “circle-in-out”, “elastic”, “elastic-in”, “elastic-out”, “elastic-in-out”, “back”, “back-in”, “back-out”, “back-in-out”, “bounce”, “bounce-in”, “bounce-out”, “bounce-in-out”.

Returns

A new instance of the current selection using the specified animation ease.

highlight(seconds) → self[source]

Returns a new selection through which all attribute changes are temporary. This is typically used to draw attention to a certain element without permanently changing its attributes.

Parameters

seconds (Optional[ElementArg[Union[int, float]]]) – The amount of time attributes should remain ‘highlighted’, in seconds, before changing back to their original values. Defaults to 0.5.

Returns

A new instance of the current selection, where all attribute changes are temporary.

data(data) → self[source]

Binds the selection to a list of data values. This will decide the arguments provided whenever an attribute is configured using a function (see ElementArg).

Parameters

data – An iterable container of values to use as the data of this selection, which should have the same length as the number of elements in the selection. Alternatively, a function (ElementFn) transforming the selection’s previous data. Use null to unbind the selection from its data, in which case the selection will fall back on its parent’s data.

Type

data: Union[Iterable[Any], ElementFn[Any]]

Raises

Exception – If the length of the data does not equal the number of elements in the selection.

Returns

A new instance of the current selection bound to the given data.

pause(seconds) → self[source]

Adds a pause to the event queue, delaying the next event by the given number of seconds.

Parameters

seconds (Union[int, float]) – The duration of the pause, in seconds.

stop(queue) → self[source]

Stops the execution of all scheduled events on the given event queue. Note that this will still be added as an event onto the current queue.

Parameters

queue (Any) – The ID of the queue to stop, which will be converted to a string.

stopall() → self[source]

Stops the execution of all scheduled events on all event queues. Note this will still be added as an event onto the current queue.

start(queue) → self[source]

Starts/resumes the execution of all scheduled events on the given event queue. Note this will still be added as an event onto the current queue.

Parameters

queue (Any) – The name of the queue to start, or an iterable container of names. Defaults to “default”.

startall() → self[source]

Starts/resumes the execution of all scheduled events on all event queues. Note that this will still be added as an event onto the current queue.

cancel(queue) → self[source]

Cancels all scheduled events on the given event queue. Note this will still be added as an event onto the current queue.

Parameters

queue (Any) – The name of the queue to cancel, or an iterable container of names. Defaults to “default”.

cancelall() → self[source]

Cancels all scheduled events on all event queues. Note that this will still be added as an event onto the current queue.

broadcast(message) → self[source]

Adds a message to the event queue, which will trigger a corresponding listener (see listen()). This can be used to detect when a queue reaches a certain point in execution, or to enable communication between a server.

Parameters

message (str) – The message.

listen(message, on_receive) → self[source]

Registers a function to listen for a specific broadcast message (see broadcast()). The function will be called when the corresponding broadcast event is processed by the event queue. If the same message is broadcast multiple times, the function will be called each time. This will also override any previous function listening for the same message.

Parameters
  • message (str) – The message to listen for.

  • on_receive (Callable) – The function to call when the message is received.

callback(on_callback) → self[source]

Adds a callback to the event queue. This is roughly equivalent to broadcasting a unique message and setting up a corresponding listener. The callback function is guaranteed to only execute once.

Parameters

on_callback (Callable) – The function to call when the callback event is processed by the event queue.

CanvasSelection

class graphics.CanvasSelection(context)[source]
node(id) → graphics.NodeSelection.NodeSelection[source]

Selects a single node by its ID.

Parameters

id (Any) – The ID of the node, which will be converted to a string.

Returns

A new selection corresponding to the given node.

nodes(ids) → graphics.NodeSelection.NodeSelection[source]

Selects multiple nodes using a list of ID values.

Parameters

ids (Iterable[Any]) – An iterable container of node IDs, which will be converted to strings.

Returns

A new selection corresponding to the given nodes.

edge(edge) → None[source]

Selects a single edge by its source, target, and optional ID. The additional ID value will distinguish edges connected to the same nodes. Once the edge has been added, source and target nodes can be provided in any order.

Parameters

edge (Tuple[Any, Any, Any]) – A (source, target) or (source, target, ID) tuple. All values will be converted to strings.

Returns

A new selection corresponding to the given edge.

edges(edges) → None[source]

Selects multiple edges using a list of source, target, and optional ID tuples.

Parameters

edges (Iterable[Union[Tuple[Any, Any], Tuple[Any, Any, Any]]]) – An iterable container of (source, target) or (source, target, ID) tuples. All values will be converted to strings.

Returns

A new selection corresponding to the given edges.

label(id) → graphics.LabelSelection.LabelSelection[source]

Selects a single label, attached to the canvas, by its ID.

Parameters

id (Any) – The ID of the label, which will be converted to a string. Defaults to “title”.

Returns

A new selection corresponding to the given label.

labels(ids) → graphics.LabelSelection.LabelSelection[source]

Selects multiple labels, attached to the canvas, using an array of ID values.

Parameters

ids (Iterable[Any]) – An iterable container of labels IDs, which will be converted to strings.

Returns

A new selection corresponding to the given labels.

size(size) → self[source]

/** Sets the width and height of the canvas. This will determine the coordinate system, and will update the width and height attributes of the main SVG element, unless otherwise specified with svgattr(). Note that size is not animated by default.

Parameters

size (ElementArg[Tuple[NumExpr, NumExpr]]) – A (width, height) tuple describing the size of the canvas.

edgelengths(length_info) → self[source]

Sets method used to calculate edge lengths. Edges can either specify individual length values (see length()), or have their lengths dynamically calculated, in which case an ‘average length’ value can be provided. More information is available here: https://github.com/tgdwyer/WebCola/wiki/link-lengths.

The default setting is: (type=”jaccard”, average length=70).

Parameters

length_info (ElementArg[Union[str, Tuple[str, NumExpr]]]) –

Either a single string describing the edge length type, or a (type, average length) tuple. The valid edge length types are:

  • ”individual”: Uses each edge’s length attribute individually.

  • ”jaccard”, “symmetric”: Dynamic calculation using an ‘average length’ value.

pan(location) → self[source]

Sets the location of the canvas camera. The canvas uses a Cartesian coordinate system with (0, 0) at the center.

Parameters

location (ElementArg[Tuple[NumExpr, NumExpr]]) – An (x, y) tuple describing the new pan location.

zoom(zoom) → self[source]

Sets the zoom level of the canvas camera. A zoom level of 2.0 will make objects appear twice as large, 0.5 will make them half as large, etc.

Parameters

zoom (ElementArg[NumExpr]) – The new zoom level.

panlimit(box) → self[source]

Restricts the movement of the canvas camera to the given bounding box, centered at (0, 0). The canvas will only be draggable when the camera is within the bounding box (i.e. the coordinates currently in view are a subset of the bounding box).

The default pan limit is: (-Infinity, Infinity).

Parameters

box (ElementArg[Tuple[NumExpr, NumExpr]]) – A (width/2, height/2) tuple describing the bounding box.

zoomlimit(limit) → self[source]

Restricts the zoom level of the canvas camera to the given range. The lower bound describes how far away the camera can zoom, while the upper bound describes the maximum enlarging zoom.

The default zoom limit is: (0.1, 10).

Parameters

limit (ElementArg[Tuple[NumExpr, NumExpr]]) – A (min, max) tuple describing the zoom limit.

zoomkey(required) → self[source]

Sets whether or not zooming requires the ctrl/cmd key to be held down. Disabled by default.

Parameters

required (ElementArg[bool]) – True if the ctrl/cmd key is required, false otherwise.

svgattr(key, value)[source]

Sets a custom SVG attribute on the canvas.

Parameters
  • key (str) – The name of the SVG attribute.

  • value (ElementArg[Union[str, int, float, None]]) – The value of the SVG attribute.

NodeSelection

class graphics.NodeSelection(context)[source]
remove() → self[source]

Removes all nodes in the current selection from the canvas. Additionally, removes any edges connected to the nodes.

label(id) → graphics.LabelSelection.LabelSelection[source]

Selects a single label, attached to the node, by its ID.

By default, each node is initialized with a “value” label, located at the center of the node and displaying its ID. Any additional labels will be automatically positioned along the boundary of the node.

Parameters

id (Any) – The ID of the label, which will be converted to a string. Defaults to “value”.

Returns

A new selection corresponding to the given label.

labels(ids) → graphics.LabelSelection.LabelSelection[source]

Selects multiple labels, attached to the node, using a list of ID values.

Parameters

ids (Iterable[Any]) – An iterable container of label IDs, which will be converted to strings.

Returns

A new selection corresponding to the given labels.

shape(shape) → self[source]

Sets the shape of the node. Note that shape cannot be animated or highlighted.

Parameters

shape (ElementArg[str]) –

One of the following strings:

  • ”circle”: Standard circular node with a single radius dimension.

  • ”rect”: Rectangular node with separate width and height dimensions, and corner rounding.

  • ”ellipse”: Elliptical node with width and height dimensions.

color(color) → self[source]

Sets the color of the node. The default color is “dark-gray”.

Parameters

color (ElementArg[str]) – A CSS color string.

size(size) → self[source]

Sets the size of the node. If the node is a circle, a single radius value is sufficient. Otherwise, a tuple containing both the horizontal and vertical radius should be provided.

Note that size can be set relative to the node’s current size using string expressions, e.g. “1.5x” for circles or (“1.5x”, “1.5y”) for rectangles and other shapes.

The default size is (12, 12).

Parameters

size (ElementArg[Union[NumExpr, Tuple[NumExpr, NumExpr]]]) – The radius of the node, or a (width/2, height/2) tuple.

pos(pos) → self[source]

Sets the position of the node. The canvas uses a Cartesian coordinate system with (0, 0) at the center.

Parameters

pos (ElementArg[Tuple[NumExpr, NumExpr]]) – An (x, y) tuple describing the new position of the node.

fixed(fixed) → self[source]

When set to true, this prevents the node from being automatically moved during the layout process. This does not affect manual dragging.

Parameters

fixed (ElementArg[bool]) – True if the position of the node should be fixed, false otherwise.

draggable(draggable) → self[source]

Sets whether or not the node can be manually dragged around.

Parameters

draggable (ElementArg[bool]) – True if the node should be draggable, false otherwise.

click(on_click) → self[source]

Registers a function to listen for node click events. This will override any previous function listening for click events on the same node.

Parameters

on_click (ElementFn) – A function taking the node’s data (see data()) and, optionally, index.

hoverin(on_hoverin) → self[source]

Registers a function to listen for node mouse-over events, triggered when the mouse enters the node. This will override any previous function listening for hover-in events on the same node.

Parameters

on_hoverin (ElementFn) – A function taking the node’s data (see data()) and, optionally, index.

hoverout(on_hoverout) → self[source]

Registers a function to listen for node mouse-over events, triggered when the mouse leaves the node. This will override any previous function listening for hover-out events on the same node.

Parameters

on_hoverout (ElementFn) – A function taking the node’s data (see data()) and, optionally, index.

svgattr(key, value)[source]

Sets a custom SVG attribute on the node’s shape.

Parameters
  • key (str) – The name of the SVG attribute.

  • value (ElementArg[Union[str, int, float, None]]) – The value of the SVG attribute.

EdgeSelection

class graphics.EdgeSelection(context)[source]
traverse(source) → self[source]

Sets the selection’s animation type such that color (color()) is animated with a traversal, and configures the node at which the traversal should begin.

If no source is given, the first node in each edge tuple used to construct the selection will be used. If the source is not connected, the edge’s actual source will be used.

Parameters

source (Optional[ElementArg[Any]) – The ID of the node at which the traversal animation should begin, which will be converted to a string.

label(id) → graphics.LabelSelection.LabelSelection[source]

Selects a single label, attached to the edge, by its ID.

Parameters

id (Any) – The ID of the label, which will be converted to a string. Defaults to “weight”.

Returns

A new selection corresponding to the given label.

labels(ids) → graphics.LabelSelection.LabelSelection[source]

Selects multiple labels, attached to the edge, using a list of ID values.

Parameters

ids (Iterable[Any]) – An iterable container of label IDs, which will be converted to strings.

Returns

A new selection corresponding to the given labels.

directed(directed) → self[source]

Sets whether or not the edge should include an arrow pointing towards its target node.

Parameters

directed (ElementArg[bool]) – True if the edge should be directed, false otherwise.

length(length) → self[source]

Sets the length of the edge. This will only take effect when edgelengths() is set to “individual”.

Parameters

length (ElementArg[NumExpr]) – The length of the edge.

thickness(thickness) → self[source]

Sets the thickness of the edge.

Parameters

thickness (ElementArg[NumExpr]) – The thickness of the edge.

color(color) → self[source]

Sets color of the edge. Note that this can be animated with a traversal animation (see traverse()). The default color is “light-gray”.

Parameters

color (ElementArg[str]) – A CSS color string.

flip(flip) → self[source]

Sets whether or not the edge should be ‘flipped’ after exceeding a certain angle, such that it is never rendered upside-down. This only applies to edges connecting two nodes.

Parameters

flip (ElementArg[bool]) – True if the edge should flip automatically, false otherwise.

curve(curve) → self[source]

Sets the curve function used to interpolate the edge’s path. The default setting is “cardinal”. More information is available here: https://github.com/d3/d3-shape#curves.

Parameters

curve (ElementArg[str]) –

The name of the curve function, based on the functions found in D3. The full list is below:

”basis”, “bundle”, “cardinal”, “catmull-rom”, “linear”, “monotone-x”, “monotone-y”, “natural”, “step”, “step-before”, “step-after”

path(path) → self[source]

Sets a custom path for the edge. The path is a list of (x, y) tuples, relative to the edge’s origin, which will automatically connect to the boundaries of the source and target nodes.

If the edge connects two nodes, (0, 0) will be the midpoint between the two nodes. If edge is a looping edge connecting one node, (0, 0) will be a point along the node’s boundary, in the direction of the edge.

Parameters

path (ElementArg[Iterable[Tuple[NumExpr, NumExpr]]]) – An iterable container of (x, y) tuples.

svgattr(key, value)[source]

Sets a custom SVG attribute on the edge’s path.

Parameters
  • key (str) – The name of the SVG attribute.

  • value (ElementArg[Union[str, int, float, None]]) – The value of the SVG attribute.

LabelSelection

class graphics.LabelSelection(context)[source]
text(text) → self[source]

Sets the text displayed by the label. The newline character (“\n”) can be used to break the text into multiple lines. Note that text cannot be animated or highlighted.

Parameters

text (ElementArg[str]) – The text displayed by the label.

align(align) → self[source]

Sets alignment of the label’s text. This will affect the direction in which text is appended, as well as its positioning relative to the label’s base position. For example, an alignment of “top-left” will ensure that the top left corner of the label is located at its base position.

A special “radial” alignment can be used to dynamically calculate the label’s alignment based on its angle() and rotate() attributes, such that text is optimally positioned around an element.

Parameters

align (ElementArg[str]) –

A string describing the alignment, typically in the form “vertical-horizontal”. The full list is below:

”top-left”, “top-middle”, “top-right”, “middle-left”, “middle”, “middle-right”, “bottom-left”, “bottom-middle”, “bottom-right”, “radial”.

pos(pos) → self[source]

Sets the position of the the label relative to its parent element. This will always involve a Cartesian coordinate system. If the parent is a node, (0, 0) will be its center. If the parent is an edge connecting two nodes, (0, 0) will be the midpoint between the two nodes. If the parent is a looping edge connecting one node, (0, 0) will be a point along the node’s boundary, in the direction of the edge.

Parameters

pos (ElementArg[Tuple[NumExpr, NumExpr]]) – An (x, y) tuple describing the position of the label.

radius(radius) → self[source]

Allows the label to be positioned using polar coordinates, together with the angle() attribute. This will specify the distance from the label’s base position (see pos()).

Parameters

radius (ElementArg[NumExpr]) – The polar radius, defined as the distance from the label’s base position.

angle(angle) → self[source]

Allows the label to be positioned using polar coordinates, together with the radius() attribute. This will specify the angle, in degrees, along a standard unit circle centered at the label’s base position (see pos()).

Additionally, this will affect the rotation of the label, if enabled (see rotate()).

Parameters

angle (ElementArg[NumExpr]) – The polar angle, in degrees, increasing counter-clockwise from the x-axis.

rotate(rotate) → self[source]

Sets whether or not the label should rotate, using its angle() attribute. The exact rotation will also depend on the label’s alignment. For example, an alignment of “top-center” together with an angle of 90 degrees will result in the text being upside-down.

Parameters

rotate (ElementArg[bool]) – Whether or not the label should rotate.

color(color) → self[source]

Sets the color of the label’s text. The default color is “gray”.

Parameters

color (ElementArg[str]) – A CSS color string.

font(font) → self[source]

Sets the font of the label’s text.

Parameters

font (ElementArg[str]) – A CSS font-family string.

size(size) → self[source]

Sets the size of the label’s text.

Parameters

size (ElementArg[NumExpr]) – The size of the label’s text, in pixels.

svgattr(key, value)[source]

Sets a custom SVG attribute on the label’s text.

Parameters
  • key (str) – The name of the SVG attribute.

  • value (ElementArg[Union[str, int, float, None]]) – The value of the SVG attribute.