Selection

detroit.create(name: str) Selection[T]

Given the specified element name, returns a single-element selection containing a detached element of the given name in the current document. This method assumes the HTML namespace, so you must specify a namespace explicitly when creating SVG or other non-HTML elements.

Parameters:

name (str) – Tag name

Returns:

XML tree

Return type:

Selection[T]

detroit.select(node: Element) Selection

Returns a selection object given a node

Parameters:

node (etree.Element) – Node

Returns:

Selection object

Return type:

Selection

class detroit.selection.selection.Selection(groups: list[list[Element]], parents: list[Element], enter: list[EnterNode[T]] | None = None, exit: list[Element] | None = None, data: dict[Element, T] | None = None)

A selection is a set of elements from the DOM. Typically these elements are identified by selectors such as .fancy for elements with the class fancy, or div to select DIV elements.

Selection methods come in two forms, select and select_all: the former selects only the first matching element, while the latter selects all matching elements in document order. The top-level selection methods, d3.select and d3.select_all, query the entire document; the subselection methods, selection.select and selection.select_all, restrict selection to descendants of the selected elements.

By convention, selection methods that return the current selection such as selection.attr use four spaces of indent, while methods that return a new selection use only two. This helps reveal changes of context by making them stick out of the chain:

Parameters:
  • groups (list[list[etree.Element]]) – List of groups of selected nodes given its parent.

  • parents (list[etree.Element]) – List of parents related to groups.

  • enter (list[EnterNode[T]] | None) – List of placeholder nodes for each datum that had no corresponding DOM element in the selection.

  • exit (list[etree.Element] | None) – List of existing DOM elements in the selection for which no new datum was found.

  • data (dict[etree.Element, T] | None) – Association between nodes and its data

Examples

>>> body = d3.create("body")
>>> (
...     body
...     .append("svg")
...     .attr("width", 960)
...     .attr("height", 500)
...     .append("g")
...     .attr("transform", "translate(20, 20)")
...     .append("rect")
...     .attr("width", 920)
...     .attr("height", 460)
... )
Selection(
    groups=[[rect]],
    parents=[g],
)
>>> print(body.to_string())
<body>
  <svg xmlns="http://www.w3.org/2000/svg" weight="960" height="500">
    <g transform="translate(20, 20)">
      <rect width="920" height="460"/>
    </g>
  </svg>
</body>
>>> str(body)
'<body><svg xmlns="http://www.w3.org/2000/svg" weight="960" height="500"><g transform="translate(20, 20)"><rect width="920" height="460"/></g></svg></body>'
append(name: str) Selection[T]

If the specified name is a string, appends a new element of this type (tag name) as the last child of each selected element, or before the next following sibling in the update selection if this is an enter selection. The latter behavior for enter selections allows you to insert elements into the DOM in an order consistent with the new bound data; however, note that selection.order may still be required if updating elements change order (i.e., if the order of new data is inconsistent with old data).

Parameters:

name (str) – Tag name

Returns:

Selection

Return type:

Selection[T]

Examples

Simple append:

>>> svg = d3.create("svg")
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg"/>
>>> g = svg.append("g").attr("class", "labels")
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <g class="labels"/>
</svg>

Multiple append:

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> (
...     svg.select_all()
...     .data([None] * 2)
...     .enter()
...     .append("g")
...     .append("text")
... )
Selection(
    groups=[[text], [text]],
    parents=[g, g],
)
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <g>
    <text/>
  </g>
  <g>
    <text/>
  </g>
</svg>
attr(name: str, value: Callable[[T], Any] | Callable[[T, int], Any] | Callable[[T, int, list[Element]], Any] | list[Any] | Any | None = None) Selection[T]

If a value is specified, sets the attribute with the specified name to the specified value on the selected elements and returns this selection.

If the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes).

Parameters:
  • name (str) – Name of the attribute

  • value (Accessor[T, Any] | list[Any] | Any | None) – Value function or constant value. The final value is converted to a string.

Returns:

Itself

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> print(
...     svg.append("g")
...     .attr("class", "labels")
...     .attr("transform", "translate(20, 10)")
...     .to_string()
... )
<svg xmlns="http://www.w3.org/2000/svg">
  <g class="labels" transform="translate(20, 10)"/>
</svg>
call(func: Callable[[Selection], Any], *args: Any) Selection[T]

Invokes the specified function exactly once, passing in this selection along with any optional arguments. Returns this selection.

Parameters:
  • func (Callable[[Selection], Any]) – Function to call

  • args (Any) – Arguments for the function to call

Returns:

Itself

Return type:

Selection[T]

Examples

This is equivalent to invoking the function by hand but facilitates method chaining. For example, to set several styles in a reusable function:

>>> def name(selection, first, last):
...     selection.attr("first-name", first).attr("last-name", last)

Now say:

>>> d3.select_all("div").call(name, "John", "Snow")

This is roughly equivalent to:

>>> name(d3.select_all("div"), "John", "Snow")
classed(names: str, value: Callable[[T], bool] | Callable[[T, int], bool] | Callable[[T, int, list[Element]], bool] | bool | None = None) Selection[T]

Assigns or unassigns the specified CSS class names on the selected elements by setting the class attribute or modifying the class list property and returns this selection.

Parameters:
  • names (str) – Class names

  • value (Accessor[T, bool] | bool | None) – Boolean function or constant boolean where the boolean indicates if the class names must be added or removed from the class property of the node.

Returns:

Itself

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> data = ["Hello", "world"]
>>> (
...    svg.select_all()
...    .data(data)
...    .enter()
...    .append("g")
...    .classed("myclass", lambda d: d == "Hello")
... )
Selection(
    groups=[[g.myclass, g]],
    parents=[svg],
)
>>> str(svg)
'<svg xmlns="http://www.w3.org/2000/svg"><g class="myclass"/><g/></svg>'
clone(deep: bool = False) Selection[T]

Copies the selected nodes and insert them after their original siblings.

Parameters:

deep (bool) – True for deep copy

Returns:

Clone of itself

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> svg.append("g").attr("class", "tick").append("line")
Selection(
    groups=[[line]],
    parents=[g.tick],
)
>>> svg.append("g").attr("class", "tick").append("line")
Selection(
    groups=[[line]],
    parents=[g.tick],
)
>>> lines = svg.select_all(".tick line")
>>> lines
Selection(
    groups=[[line], [line]],
    parents=[g.tick, g.tick],
)
>>> lines.clone()
Selection(
    groups=[[line], [line]],
    parents=[g.tick, g.tick],
)
>>> lines = svg.select_all(".tick line")
>>> lines
Selection(
    groups=[[line, line], [line, line]],
    parents=[g.tick, g.tick],
)

You should read this as:

Selection(
    groups=[[line_a, line_a], [line_b, line_b]],
    parents=[g.tick, g.tick],
)
data(values: list[T] | Callable[[Element, T, int, list[Element]], list[T]], key: Callable[[T], float | str] | Callable[[T, int], float | str] | Callable[[T, int, list[Element]], float | str] | None = None) Selection[T]

Binds the specified list of data with the selected elements, returning a new selection that represents the update selection: the elements successfully bound to data. Also defines the enter and exit selections on the returned selection, which can be used to add or remove elements to correspond to the new data. The specified data is an array of arbitrary values (e.g., numbers or objects), or a function that returns an array of values for each group.

Parameters:
  • values (list[T] | EtreeFunction[T, list[T]]) – List of data to bind

  • key (Accessor[T, float | str] | None) – Optional accessor which returns a key value

Returns:

Itself

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> print(svg.append("g").to_repr())
Selection(
    groups=[[g]],
    parents=[svg],
    enter=None,
    exit=None,
    data={<Element g at 0x75cf61141b80>: None},
)
>>> print(svg.append("g").to_repr())
Selection(
    groups=[[g]],
    parents=[svg],
    enter=None,
    exit=None,
    data={<Element g at 0x75cf61141b80>: None, <Element g at 0x75cf611b0500>: None},
)
>>> print(svg.select_all("text").data(["Hello", "world"]).to_repr())
Selection(
    groups=[[None, None]],
    parents=[svg],
    enter=[[EnterNode(svg, Hello), EnterNode(svg, world)]],
    exit=[[]],
    data={<Element g at 0x75cf61141b80>: None, <Element g at 0x75cf611b0500>: None},
)
>>> print(svg.select_all("g").data(["Hello", "world"]).to_repr())
Selection(
    groups=[[g, g]],
    parents=[svg],
    enter=[[None, None]],
    exit=[[None, None]],
    data={<Element g at 0x75cf61141b80>: 'Hello', <Element g at 0x75cf611b0500>: 'world'},
)
datum(value: T) Selection[T]

Sets the bound data for the first selected node.

Parameters:

value (T) – Value

Returns:

Itself

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> g1 = svg.append("g").attr("class", "g1")
>>> g2 = svg.append("g").attr("class", "g2")
>>> g = svg.select_all("g")
>>> print(g.to_repr())
Selection(
    groups=[[g.g1, g.g2]],
    parents=[svg],
    enter=None,
    exit=None,
    data={<Element g at 0x7d115a460a80>: None, <Element g at 0x7d115a460640>: None},
)
>>> g.datum("Hello, world")
Selection(
    groups=[[g.g1, g.g2]],
    parents=[svg],
)
>>> print(g.to_repr())
Selection(
    groups=[[g.g1, g.g2]],
    parents=[svg],
    enter=None,
    exit=None,
    data={<Element g at 0x7d115a460a80>: 'Hello, world', <Element g at 0x7d115a460640>: None},
)
>>> g1.node()
<Element g at 0x7d115a460a80>
each(callback: Callable[[Element, T, int, list[Element]], None]) Selection[T]

Invokes the specified function for each selected element, in order, being passed the current DOM element (nodes[i]), the current datum (d), the current index (i), and the current group (nodes).

Parameters:

callback (EtreeFunction[T, None]) –

Function to call which takes as argument:

  • node (etree.Element) - the node element

  • data (T) - current data associated to the node

  • index (int) - the index of the node in its group

  • group (list[etree.Element]) - the node’s group with other nodes.

Returns:

Itself

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> (
...     svg.select_all()
...     .data(list(range(4)))
...     .enter()
...     .append("g")
...     .attr("transform", lambda d: f"scale({d})")
... )
Selection(
    groups=[[g, g, g, g]],
    parents=[svg],
)
>>> def each(node, d, i, group):
...     tag = node.tag
...     transform = node.attrib.get("transform")
...     print(f"{tag = }, {transform = }, data = {d}, {i = }, {len(group) = }")
...
>>> svg.select_all("g").each(each)
tag = 'g', transform = 'scale(0)', data = 0, i = 0, len(group) = 4
tag = 'g', transform = 'scale(1)', data = 1, i = 1, len(group) = 4
tag = 'g', transform = 'scale(2)', data = 2, i = 2, len(group) = 4
tag = 'g', transform = 'scale(3)', data = 3, i = 3, len(group) = 4
Selection(
    groups=[[g, g, g, g]],
    parents=[svg],
)
enter() Selection[T]

Returns the enter selection: placeholder nodes for each datum that had no corresponding DOM element in the selection.

Returns:

Enter selection

Return type:

Selection[T]

Examples

>>> svg = d3.create("svg")
>>> text = svg.select_all("text").data(["hello", "world"])
>>> text_enter = text.enter()
>>> text_enter
Selection(
    groups=[[EnterNode(svg, hello), EnterNode(svg, world)]],
    parents=[svg],
)
exit() Selection[T]

Returns the exit selection: existing DOM elements in the selection for which no new datum was found. (The exit selection is empty for selections not returned by selection.data.)

Returns:

Exit selection

Return type:

Selection[T]

Examples

>>> svg = d3.create("svg")
>>> text = svg.select_all("text").data(["hello", "world"])
>>> text_exit = text.exit()
>>> text_exit
Selection(
    groups=[[]],
    parents=[svg],
)
filter(match: Callable[[T], bool] | Callable[[T, int], bool] | Callable[[T, int, list[Element]], bool] | int | float | str) Selection[T]

Filters the selection, returning a new selection that contains only the elements for which the specified filter is true.

Parameters:

match (Accessor[T, bool] | int | float | str) – Constant to match or accessor which returns a boolean

Returns:

Filtered selection

Return type:

Selection[T]

Examples

>>> svg = d3.create("svg")
>>> scale = d3.scale_linear([0, 10], [0, 100])
>>> print(svg.call(d3.axis_bottom(scale).set_ticks(3)).to_string())
<svg xmlns="http://www.w3.org/2000/svg" fill="none" font-size="10" font-family="sans-serif" text-anchor="middle">
  <path class="domain" stroke="currentColor" d="M0.5,6V0.5H100.5V6"/>
  <g class="tick" opacity="1" transform="translate(0.5, 0)">
    <line stroke="currentColor" y2="6"/>
    <text fill="currentColor" y="9" dy="0.71em">0</text>
  </g>
  <g class="tick" opacity="1" transform="translate(50.5, 0)">
    <line stroke="currentColor" y2="6"/>
    <text fill="currentColor" y="9" dy="0.71em">5</text>
  </g>
  <g class="tick" opacity="1" transform="translate(100.5, 0)">
    <line stroke="currentColor" y2="6"/>
    <text fill="currentColor" y="9" dy="0.71em">10</text>
  </g>
</svg>
>>> result = svg.select_all("text").filter(lambda d, i: i % 2 != 0)
>>> result
Selection(
    groups=[[text]],
    parents=[svg],
)
>>> result.node().text
'5'
html(value: Callable[[T], Any] | Callable[[T, int], Any] | Callable[[T, int, list[Element]], Any] | Any | None = None) Selection[T]

This method has no difference with Selection.text.

Parameters:

value (Accessor[T, Any] | Any | None) – Inner HML function or constant inner HML. The final value is converted to a string.

Returns:

Itself

Return type:

Selection[T]

Examples

Direct assignment:

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> print(svg.append("text").html("Hello, world!").to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <text>Hello, world!</text>
</svg>

Through data:

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> print(
...     svg.select_all("text")
...     .data(["Hello", "world"])
...     .enter()
...     .append("text")
...     .html(lambda text, i: f"{text} - index {i}")
...     .to_string()
... )
<svg xmlns="http://www.w3.org/2000/svg">
  <text>Hello - index 0</text>
  <text>world - index 1</text>
</svg>
insert(name: str, before: str) Selection[T]

If the specified name is a string, inserts a new element of this type (tag name) before the first element matching the specified before selector for each selected element.

Parameters:
  • name (str) – Tag name

  • before (str) – Node element selection

Returns:

Selection with inserted element(s)

Return type:

Selection[T]

Examples

Since before refers to a selected tag, this method will operate multiple insertions.

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> (
...     svg.select_all("g")
...     .data([None, None])
...     .enter()
...     .append("g")
...     .append("text")
... )
Selection(
    groups=[[text], [text]],
    parents=[g, g],
)
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <g>
    <text/>
  </g>
  <g>
    <text/>
  </g>
</svg>
>>> svg.insert("circle", "text")
Selection(
    groups=[[circle], [circle]],
    parents=[g, g],
)
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <g>
    <circle/>
    <text/>
  </g>
  <g>
    <circle/>
    <text/>
  </g>
</svg>

If you prefer to insert an element at a specific location, you need to select first the specific node and then insert your element.

>>> svg = d3.create("svg")
>>> (
...     svg.select_all("g")
...     .data(["class1", "class2"])
...     .enter()
...     .append("g")
...     .append("text")
...     .attr("class", lambda d: d)
... )
Selection(
    groups=[[text.class1], [text.class2]],
    parents=[g, g],
)
>>> svg.insert("circle", ".class1")
Selection(
    groups=[[circle]],
    parents=[g],
    enter=None,
    exit=None,
    data={<Element circle at 0x7fc5753f0500>: None},
)
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <g>
    <circle/>
    <text class="class1"/>
  </g>
  <g>
    <text class="class2"/>
  </g>
</svg>
join(onenter: Callable[[Selection], Selection] | str, onupdate: Callable[[Selection], Selection] | None = None, onexit: Callable[[Selection], None] | None = None) Selection[T]

Appends, removes and reorders elements as necessary to match the data that was previously bound by selection.data, returning the merged enter and update selection. This method is a convenient alternative to the explicit general update pattern, replacing selection.enter, selection.exit, selection.append, selection.remove, and selection.order.

Parameters:
Returns:

Selection with joined elements

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> data = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
>>> svg = d3.create("svg")
>>> table = (
...     svg.append("table")
...     .select_all("tr")
...     .data(data)
...     .join("tr")
...     .select_all("td")
...     .data(lambda _, d: d)
...     .join("td")
...     .text(lambda d: str(d))
... )
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <table>
    <tr>
      <td>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
      <td>5</td>
      <td>6</td>
      <td>7</td>
    </tr>
    <tr>
      <td>8</td>
      <td>9</td>
      <td>10</td>
      <td>11</td>
    </tr>
    <tr>
      <td>12</td>
      <td>13</td>
      <td>14</td>
      <td>15</td>
    </tr>
  </table>
</svg>

Another usage could be to specify functions :

>>> data = [None] * 3
>>> svg = d3.create("svg")
>>> svg.append("circle").attr("fill", "yellow")
Selection(
    groups=[[circle]],
    parents=[svg],
)
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <circle fill="yellow"/>
</svg>
>>> (
...     svg.select_all("circle")
...     .data(data)
...     .join(
...         onenter=lambda enter: enter.append("circle").attr("fill", "green"),
...         onupdate=lambda update: update.attr("fill", "blue")
...     )
...     .attr("stroke", "black")
... )
Selection(
    groups=[[circle, circle, None]],
    parents=[svg],
)
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <circle fill="blue"/>
  <circle fill="green" stroke="black"/>
  <circle fill="green" stroke="black"/>
</svg>

In this example, the attribute fill of the existing circle was updated, by onupdate, from yellow to blue. And since data has 3 elements, onenter has generated the last circles.

merge(context: Selection) Selection[T]

Returns a new selection merging this selection with the specified other selection or transition. The returned selection has the same number of groups and the same parents as this selection. Any missing (None) elements in this selection are filled with the corresponding element, if present (not null), from the specified selection. (If the other selection has additional groups or parents, they are ignored.)

Parameters:

context (Selection) – Selection

Returns:

Merged selection

Return type:

Selection[T]

Examples

>>> svg = d3.create("svg")
>>> text = svg.select_all("text").data(["hello", "world"])
>>> text_enter = text.enter()
>>> text_enter.append("text").text(lambda text: text)
Selection(
    groups=[[text, text]],
    parents=[svg],
)
>>> print(svg.to_string())
<svg xmlns:xmlns="http://www.w3.org/2000/svg">
  <text>hello</text>
  <text>world</text>
</svg>
>>> print(text.to_repr())
Selection(
    groups=[[None, None]],
    parents=[svg],
    enter=[[EnterNode(svg, hello), EnterNode(svg, world)]],
    exit=[[]],
    data={<Element text at 0x7d28b3f08380>: 'hello', <Element text at 0x7d28b3f08140>: 'world'},
)
>>> text = text.merge(text_enter)
>>> print(text.to_repr())
Selection(
    groups=[[EnterNode(svg, hello), EnterNode(svg, world)]],
    parents=[svg],
    enter=None,
    exit=None,
    data={<Element text at 0x7d28b3f08380>: 'hello', <Element text at 0x7d28b3f08140>: 'world'},
)
node() Element

Returns the first (non-None) element in this selection.

Returns:

Node

Return type:

etree.Element

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> g = (
...     svg.select_all("g")
...     .data(list(reversed(range(10))))
...     .enter()
...     .append("g")
...     .attr("class", lambda d: f"class{d}")
... )
>>> g
Selection(
    groups=[[g.class9, g.class8, g.class7, g.class6, g.class5, g.class4, g.class3, g.class2, g.class1, g.class0]],
    parents=[svg],
)
>>> first = g.node()
>>> print(f"{first.tag}.{first.attrib.get("class")}")
g.class9
nodes() list[Element]

Returns a list of all (non-None) elements in this selection.

Returns:

List of nodes

Return type:

list[etree.Element]

Examples

>>> svg = d3.create("svg")
>>> g = (
...     svg.select_all("g")
...     .data(list(reversed(range(10))))
...     .enter()
...     .append("g")
...     .attr("class", lambda d: f"class{d}")
... )
>>> g
Selection(
    groups=[[g.class9, g.class8, g.class7, g.class6, g.class5, g.class4, g.class3, g.class2, g.class1, g.class0]],
    parents=[svg],
)
>>> [f"{node.tag}.{node.attrib.get("class")}" for node in g.nodes()]
['g.class9', 'g.class8', 'g.class7', 'g.class6', 'g.class5', 'g.class4', 'g.class3', 'g.class2', 'g.class1', 'g.class0']
order() Selection[T]

Re-inserts elements into the document such that the document order of each group matches the selection order.

Returns:

Itself

Return type:

Selection[T]

property(name: str, value: Callable[[T], Any] | Callable[[T, int], Any] | Callable[[T, int, list[Element]], Any] | list[Any] | Any | None = None) Selection[T]

This method has no difference with Selection.attr.

Parameters:
  • name (str) – Name of the property

  • value (Accessor[T, Any] | list[Any] | Any | None) – Property value function or constant property value. The final value is converted to a string.

Returns:

Itself

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> print(
...     svg.append("g")
...     .property("class", "labels")
...     .property("transform", "translate(20, 10)")
...     .to_string()
... )
<svg xmlns="http://www.w3.org/2000/svg">
  <g class="labels" transform="translate(20, 10)"/>
</svg>
remove() Selection[T]

Removes the selected elements from the document. Returns this selection (the removed elements) which are now detached from the DOM.

Returns:

Selection with removed elements

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> (
...     svg.select_all("g")
...     .data([None] * 10)
...     .enter()
...     .append("g")
...     .attr("class", "domain")
... )
Selection(
    groups=[[g.domain, g.domain, g.domain, g.domain, g.domain, g.domain, g.domain, g.domain, g.domain, g.domain]],
    parents=[svg],
)
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <g class="domain"/>
  <g class="domain"/>
  <g class="domain"/>
  <g class="domain"/>
  <g class="domain"/>
  <g class="domain"/>
  <g class="domain"/>
  <g class="domain"/>
  <g class="domain"/>
  <g class="domain"/>
</svg>
>>> svg.select_all(".domain").remove()
Selection(
    groups=[[]],
    parents=[svg],
    enter=None,
    exit=None,
    data={},
)
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg"/>
select(selection: str | None = None) Selection[T]

Selects the first element that matches the specified selection string.

Supported forms are:

  • {tag_name}{.class_name}{:last-of-type}

  • {tag_name}{[attribute_name="value"]}{:last-of-type}

The tag_name is any SVG element tag (ex: g, rect, line, …). You can chain selections by adding one space between them.

The .class_name is specified when a element is created such as:

svg.append("g").attr("class", "my_class")

In this example, the value of .class_name is .my_class.

The :last-of-type option is useful when you only need the last element.

Using [attribute_name="value"] allows you to get any element associated to a specific attribute. For instance, in the following code:

svg.append("g").attr("aria-label", "my_group")

To access this element, the value of [attribute_name="value"] must be [aria-label="my_group"].

Parameters:

selection (str | None) – Selection string

Returns:

Selection of first element

Return type:

Selection[T]

Examples

>>> svg = d3.create("svg")
>>> svg.append("g").attr("class", "ticks")
Selection(
    groups=[[g.ticks]],
    parents=[svg],
)
>>> svg.append("g").attr("class", "labels")
Selection(
    groups=[[g.labels]],
    parents=[svg],
)
>>> svg.select("g.ticks")
Selection(
    groups=[[g.ticks]],
    parents=[svg],
)
>>> svg.select("g.points")
Selection(
    groups=[[]],
    parents=[svg],
)
select_all(selection: str | None = None) Selection[T]

Selects all elements that match the specified selection string.

Supported forms are:

  • {tag_name}{.class_name}{:last-of-type}

  • {tag_name}{[attribute_name="value"]}{:last-of-type}

The tag_name is any SVG element tag (ex: g, rect, line, …). You can chain selections by adding one space between them.

The .class_name is specified when a element is created such as:

svg.append("g").attr("class", "my_class")

In this example, the value of .class_name is .my_class.

The :last-of-type option is useful when you only need the last element.

Using [attribute_name="value"] allows you to get any element associated to a specific attribute. For instance, in the following code:

svg.append("g").attr("aria-label", "my_group")

To access this element, the value of [attribute_name="value"] must be [aria-label="my_group"].

Parameters:

selection (str | None) – Selection string

Returns:

Selection of all matched elements

Return type:

Selection[T]

Examples

>>> svg = d3.create("svg")
>>> scale = d3.scale_linear([0, 10], [0, 100])
>>> print(svg.call(d3.axis_bottom(scale).set_ticks(3)).to_string())
<svg xmlns:xmlns="http://www.w3.org/2000/svg" fill="none" font-size="10" font-family="sans-serif" text-anchor="middle">
  <path class="domain" stroke="currentColor" d="M0.5,6V0.5H100.5V6"/>
  <g class="tick" opacity="1" transform="translate(0.5, 0)">
    <line stroke="currentColor" y2="6"/>
    <text fill="currentColor" y="9" dy="0.71em">0</text>
  </g>
  <g class="tick" opacity="1" transform="translate(50.5, 0)">
    <line stroke="currentColor" y2="6"/>
    <text fill="currentColor" y="9" dy="0.71em">5</text>
  </g>
  <g class="tick" opacity="1" transform="translate(100.5, 0)">
    <line stroke="currentColor" y2="6"/>
    <text fill="currentColor" y="9" dy="0.71em">10</text>
  </g>
</svg>
>>> svg.select_all("g").select_all("line")
Selection(
    groups=[[line], [line], [line]],
    parents=[g.tick, g.tick, g.tick],
)
>>> svg.select_all("line")
Selection(
    groups=[[line], [line], [line]],
    parents=[g.tick, g.tick, g.tick],
)
selection() Selection[T]

Returns the selection without any modification.

Returns:

Itself

Return type:

Selection[T]

style(name: str, value: Callable[[T], str] | Callable[[T, int], str] | Callable[[T, int, list[Element]], str] | int | float | str | None = None) Selection[T]

If a value is specified, sets the style with the specified name to the specified value on the selected elements and returns this selection.

If the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes).

Parameters:
  • name (str) – Name of the style

  • value (Accessor[T, str] | Number | str | None) – Value function or constant value.

Returns:

Itself

Return type:

Selection[T]

Examples

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> print(
...     svg.append("text")
...     .style("fill", "black")
...     .style("stroke", "none")
...     .to_string()
... )
<svg xmlns="http://www.w3.org/2000/svg">
  <text style="fill:black;stroke:none;"/>
</svg>
text(value: Callable[[T], Any] | Callable[[T, int], Any] | Callable[[T, int, list[Element]], Any] | Any | None = None) Selection[T]

If the value is a constant, then all elements are given the same text content; otherwise, if the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes).

Parameters:

value (Accessor[T, Any] | Any | None) – Text function or constant text value. The final value is converted to a string.

Returns:

Itself

Return type:

Selection[T]

Examples

Direct assignment:

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> print(svg.append("text").text("Hello, world!").to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <text>Hello, world!</text>
</svg>

Through data:

>>> import detroit as d3
>>> svg = d3.create("svg")
>>> print(
...     svg.select_all("text")
...     .data(["Hello", "world"])
...     .enter()
...     .append("text")
...     .text(lambda text, i: f"{text} - index {i}")
...     .to_string()
... )
<svg xmlns="http://www.w3.org/2000/svg">
  <text>Hello - index 0</text>
  <text>world - index 1</text>
</svg>
to_repr(show_enter: bool = True, show_exit: bool = True, show_data: bool = True) str

Represents the selection with optional parameters.

Parameters:
  • show_enter (bool) – Show enter elements associated to this selection

  • show_exit (bool) – Show exit elements associated to this selection

  • show_data (bool) – Show data associated to this selection

Returns:

String

Return type:

str

Examples

>>> svg = d3.create("svg")
>>> g = (
...     svg.select_all("g")
...     .data(list(reversed(range(10))))
...     .enter()
...     .append("g")
...     .attr("class", lambda d: f"class{d}")
... )
>>> print(g.to_repr())
Selection(
    groups=[[g.class9, g.class8, g.class7, g.class6, g.class5, g.class4, g.class3, g.class2, g.class1, g.class0]],
    parents=[svg],
    enter=None,
    exit=None,
    data={<Element g at 0x7287cf850040>: 9, <Element g at 0x7287cfa50bc0>: 8, <Element g at 0x7287cf883ac0>: 7, <Element g at 0x7287cf8837c0>:6, <Element g at 0x7287cf883e00>: 5, <Element g at 0x7287cf883a40>: 4, <Element g at 0x7287cf882fc0>: 3, <Element g at 0x7287cf883a80>: 2, <Element g at 0x7287cf880d80>: 1, <Element g at 0x7287cf881000>: 0},
)
to_string(pretty_print: bool = True) str

Convert selection to string

Parameters:

pretty_print (bool) – True to prettify output

Returns:

String

Return type:

str

Examples

>>> svg = d3.create("svg")
>>> g = (
...     svg.select_all("g")
...     .data(list(reversed(range(10))))
...     .enter()
...     .append("g")
...     .attr("class", lambda d: f"class{d}")
... )
>>> print(svg.to_string())
<svg xmlns="http://www.w3.org/2000/svg">
  <g class="class9"/>
  <g class="class8"/>
  <g class="class7"/>
  <g class="class6"/>
  <g class="class5"/>
  <g class="class4"/>
  <g class="class3"/>
  <g class="class2"/>
  <g class="class1"/>
  <g class="class0"/>
</svg>
>>> print(svg.to_string(False))
<svg xmlns="http://www.w3.org/2000/svg"><g class="class9"/><g class="class8"/><g class="class7"/><g class="class6"/><g class="class5"/><g class="class4"/><g class="class3"/><g class="class2"/><g class="class1"/><g class="class0"/></svg>
>>> svg.to_string(False) == str(svg)
True
__str__() str

Returns the SVG content. Equivalent to Selection.to_string(False).

Returns:

String

Return type:

str

__repr__() str

Represents the selection

Returns:

String

Return type:

str

Examples

>>> svg = d3.create("svg")
>>> g = (
...     svg.select_all("g")
...     .data(list(reversed(range(10))))
...     .enter()
...     .append("g")
...     .attr("class", lambda d: f"class{d}")
... )
>>> print(repr(g))
Selection(
    groups=[[g.class9, g.class8, g.class7, g.class6, g.class5, g.class4, g.class3, g.class2, g.class1, g.class0]],
    parents=[svg],
)