Skip to content

๐Ÿ”จ Export

Tree Export Methods

Export Tree to list, dictionary, pandas/polars DataFrame, and various formats.

Export Tree to Method
Command Line / Print print_tree, hprint_tree, vprint_tree, iprint_tree
Generator (versatile) yield_tree, hyield_tree, vyield_tree
String tree_to_html, tree_to_newick
Dictionary tree_to_dict, tree_to_nested_dict, tree_to_nested_dict_key
DataFrame (pandas, polars) tree_to_dataframe, tree_to_polars
Dot (for .dot, .png, .svg, .jpeg, etc.) tree_to_dot
Pillow (for .png, .jpg, .jpeg, etc.) tree_to_pillow, tree_to_pillow_graph
Mermaid Markdown (for .md) tree_to_mermaid
Visualization tree_to_vis

Tree Export Customisations

While exporting to another data type, methods can take in arguments to determine what information to extract.

Method Extract node attributes Specify maximum depth Skip depth Extract leaves only Others
print_tree Yes with attr_list or all_attrs Yes No No Tree style
yield_tree No, returns node Yes No No Tree style
hprint_tree No Yes No Yes, by hiding intermediate node name Tree style, border style
hyield_tree No Yes No Yes, by hiding intermediate node name Tree style, border style
vprint_tree No Yes No Yes, by hiding intermediate node name Tree style, border style
vyield_tree No Yes No Yes, by hiding intermediate node name Tree style, border style
iprint_tree Yes with attr_list No No No Node, border, edge, font customisations
tree_to_html Yes with attr_list No No No Node, border, edge, font customisations
tree_to_newick Yes with attr_list No No Yes, by hiding intermediate node name Length separator and attribute prefix and separator
tree_to_dict Yes with attr_dict or all_attrs Yes Yes Yes with leaf_only Dict key for parent
tree_to_nested_dict Yes with attr_dict or all_attrs Yes No No Dict key for node name and node children
tree_to_nested_dict_key Yes with attr_dict or all_attrs Yes No No Dict key for node children
tree_to_dataframe Yes with attr_dict or all_attrs Yes Yes Yes with leaf_only Column name for path, node name, node parent
tree_to_polars Yes with attr_dict or all_attrs Yes Yes Yes with leaf_only Column name for path, node name, node parent
tree_to_dot No No No No Graph attributes, background, node, edge colour etc.
tree_to_pillow_graph Yes with node_content Yes No No Font (family, size, colour), background colour etc.
tree_to_pillow No Yes No No Font (family, size, colour), background colour etc.
tree_to_mermaid No Yes No No Node shape, node fill, edge arrow, edge label etc.
tree_to_vis No Yes No No Background style, node style, edge style etc.

bigtree.tree.export

tree_to_dataframe

tree_to_dataframe(
    tree,
    path_col="path",
    name_col="name",
    parent_col=None,
    attr_dict=None,
    all_attrs=False,
    max_depth=0,
    skip_depth=0,
    leaf_only=False,
)

Export tree to pandas DataFrame.

All descendants from tree will be exported, tree can be the root node or child node of tree.

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> tree.to_dataframe(name_col="name", parent_col="parent", path_col="path", attr_dict={"age": "person age"})
     path name parent  person age
0      /a    a   None          90
1    /a/b    b      a          65
2  /a/b/d    d      b          40
3  /a/b/e    e      b          35
4    /a/c    c      a          60

For a subset of a tree.

>>> b_tree = Tree(b)
>>> b_tree.to_dataframe(name_col="name", parent_col="parent", path_col="path", attr_dict={"age": "person age"})
     path name parent  person age
0    /a/b    b      a          65
1  /a/b/d    d      b          40
2  /a/b/e    e      b          35

Parameters:

Name Type Description Default
tree T

tree to be exported

required
path_col str | None

column name for node.path_name

'path'
name_col str | None

column name for node.node_name

'name'
parent_col str | None

column name for node.parent.node_name

None
attr_dict dict[str, str] | None

node attributes mapped to column name, key: node attributes, value: corresponding column in dataframe

None
all_attrs bool

indicator whether to retrieve all Node attributes, overrides attr_dict

False
max_depth int

maximum depth to export tree

0
skip_depth int

number of initial depths to skip

0
leaf_only bool

indicator to retrieve only information from leaf nodes

False

Returns:

Type Description
DataFrame

pandas DataFrame containing tree information

tree_to_polars

tree_to_polars(
    tree,
    path_col="path",
    name_col="name",
    parent_col=None,
    attr_dict=None,
    all_attrs=False,
    max_depth=0,
    skip_depth=0,
    leaf_only=False,
)

Export tree to polars DataFrame.

All descendants from tree will be exported, tree can be the root node or child node of tree.

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> tree.to_polars(name_col="name", parent_col="parent", path_col="path", attr_dict={"age": "person age"})
shape: (5, 4)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ path   โ”† name โ”† parent โ”† person age โ”‚
โ”‚ ---    โ”† ---  โ”† ---    โ”† ---        โ”‚
โ”‚ str    โ”† str  โ”† str    โ”† i64        โ”‚
โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ก
โ”‚ /a     โ”† a    โ”† null   โ”† 90         โ”‚
โ”‚ /a/b   โ”† b    โ”† a      โ”† 65         โ”‚
โ”‚ /a/b/d โ”† d    โ”† b      โ”† 40         โ”‚
โ”‚ /a/b/e โ”† e    โ”† b      โ”† 35         โ”‚
โ”‚ /a/c   โ”† c    โ”† a      โ”† 60         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

For a subset of a tree.

>>> b_tree = Tree(b)
>>> b_tree.to_polars(name_col="name", parent_col="parent", path_col="path", attr_dict={"age": "person age"})
shape: (3, 4)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ path   โ”† name โ”† parent โ”† person age โ”‚
โ”‚ ---    โ”† ---  โ”† ---    โ”† ---        โ”‚
โ”‚ str    โ”† str  โ”† str    โ”† i64        โ”‚
โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ก
โ”‚ /a/b   โ”† b    โ”† a      โ”† 65         โ”‚
โ”‚ /a/b/d โ”† d    โ”† b      โ”† 40         โ”‚
โ”‚ /a/b/e โ”† e    โ”† b      โ”† 35         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Parameters:

Name Type Description Default
tree T

tree to be exported

required
path_col str | None

column name for node.path_name

'path'
name_col str | None

column name for node.node_name

'name'
parent_col str | None

column name for node.parent.node_name

None
attr_dict dict[str, str] | None

node attributes mapped to column name, key: node attributes, value: corresponding column in dataframe

None
all_attrs bool

indicator whether to retrieve all Node attributes, overrides attr_dict

False
max_depth int

maximum depth to export tree

0
skip_depth int

number of initial depths to skip

0
leaf_only bool

indicator to retrieve only information from leaf nodes

False

Returns:

Type Description
DataFrame

polars DataFrame containing tree information

tree_to_dict

tree_to_dict(
    tree,
    name_key="name",
    parent_key=None,
    attr_dict=None,
    all_attrs=False,
    max_depth=0,
    skip_depth=0,
    leaf_only=False,
)

Export tree to dictionary.

All descendants from tree will be exported, tree can be the root node or child node of tree.

Exported dictionary will have key as node path, and node attributes as a nested dictionary.

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> tree.to_dict(name_key="name", parent_key="parent", attr_dict={"age": "person age"})
{'/a': {'name': 'a', 'parent': None, 'person age': 90}, '/a/b': {'name': 'b', 'parent': 'a', 'person age': 65}, '/a/b/d': {'name': 'd', 'parent': 'b', 'person age': 40}, '/a/b/e': {'name': 'e', 'parent': 'b', 'person age': 35}, '/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}}

For a subset of a tree

>>> c_tree = Tree(c)
>>> c_tree.to_dict(name_key="name", parent_key="parent", attr_dict={"age": "person age"})
{'/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}}

Parameters:

Name Type Description Default
tree T

tree to be exported

required
name_key str | None

dictionary key for node.node_name

'name'
parent_key str | None

dictionary key for node.parent.node_name

None
attr_dict dict[str, str] | None

node attributes mapped to dictionary key, key: node attributes, value: corresponding dictionary key

None
all_attrs bool

indicator whether to retrieve all Node attributes, overrides attr_dict

False
max_depth int

maximum depth to export tree

0
skip_depth int

number of initial depths to skip

0
leaf_only bool

indicator to retrieve only information from leaf nodes

False

Returns:

Type Description
dict[str, Any]

Dictionary containing tree information

tree_to_nested_dict

tree_to_nested_dict(
    tree,
    name_key="name",
    child_key="children",
    attr_dict=None,
    all_attrs=False,
    max_depth=0,
)

Export tree to nested dictionary.

All descendants from tree will be exported, tree can be the root node or child node of tree.

Exported dictionary will have key as node attribute names, and children as a nested recursive dictionary.

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> tree.to_nested_dict(all_attrs=True)
{'name': 'a', 'age': 90, 'children': [{'name': 'b', 'age': 65, 'children': [{'name': 'd', 'age': 40}, {'name': 'e', 'age': 35}]}, {'name': 'c', 'age': 60}]}

Parameters:

Name Type Description Default
tree T

tree to be exported

required
name_key str

dictionary key for node.node_name

'name'
child_key str

dictionary key for list of children

'children'
attr_dict dict[str, str] | None

node attributes mapped to dictionary key, key: node attributes, value: corresponding dictionary key

None
all_attrs bool

indicator whether to retrieve all Node attributes, overrides attr_dict

False
max_depth int

maximum depth to export tree

0

Returns:

Type Description
dict[str, Any]

Dictionary containing tree information

tree_to_nested_dict_key

tree_to_nested_dict_key(
    tree,
    child_key="children",
    attr_dict=None,
    all_attrs=False,
    max_depth=0,
)

Export tree to nested dictionary, where the keys are node names.

All descendants from tree will be exported, tree can be the root node or child node of tree.

Exported dictionary will have key as node names, and children as node attributes and nested recursive dictionary. If child_key is None, the children key is nested recursive dictionary of node names (there will be no attributes).

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> tree.to_nested_dict_key(all_attrs=True)
{'a': {'age': 90, 'children': {'b': {'age': 65, 'children': {'d': {'age': 40}, 'e': {'age': 35}}}, 'c': {'age': 60}}}}
>>> tree.to_nested_dict_key(child_key=None)
{'a': {'b': {'d': {}, 'e': {}}, 'c': {}}}

Parameters:

Name Type Description Default
tree T

tree to be exported

required
child_key str | None

dictionary key for children

'children'
attr_dict dict[str, str] | None

node attributes mapped to dictionary key, key: node attributes, value: corresponding dictionary key

None
all_attrs bool

indicator whether to retrieve all Node attributes, overrides attr_dict

False
max_depth int

maximum depth to export tree

0

Returns:

Type Description
dict[str, Any]

Dictionary containing tree information

iprint_tree

iprint_tree(tree, **kwargs)

Display tree interactively on jupyter notebook.

Refer to tree_to_html for full list of parameters.

Customisations that applies to whole tree include

  • Node colour, width
  • Border colour, radius, width
  • Edge colour, width
  • Font colour, title size, size

Customisations available on a per-node basis include

  • Node colour
  • Border colour, width
  • Font colour

Examples:

>>> from bigtree import Node
>>> root = Node("a", species="human")
>>> b = Node("b", age=65, species="human", parent=root)
>>> c = Node("c", age=60, species="human", parent=root)
>>> d = Node("d", age=40, species="human", parent=b)
>>> e = Node("e", age=35, species="human", parent=b)
>>> root.ishow(all_attrs=True)
<IPython.core.display.HTML object>

Parameters:

Name Type Description Default
tree T

tree to display

required
**kwargs Any

refer to tree_to_html for list of parameters

{}

tree_to_html

tree_to_html(
    tree,
    all_attrs=False,
    attr_list=None,
    node_colour="#f8f9fa",
    node_width=160,
    border_colour="#dee2e6",
    border_radius=12,
    border_width=1,
    edge_colour="#ccc",
    edge_width=1.5,
    font_colour="#333",
    font_title_size=13,
    font_size=11,
    height=500,
    width=900,
)

Get html tree diagram.

Parameters:

Name Type Description Default
tree T

tree to display

required
all_attrs bool

indicator to show all attributes, overrides attr_list

False
attr_list Iterable[str] | None

node attributes to print

None
node_colour str

fill colour of nodes, accepts hexcode (starts with #), otherwise will be interpreted as the Node attribute for node_colour

'#f8f9fa'
node_width int

node width of nodes

160
border_colour str

colour of node borders, accepts hexcode (starts with #), otherwise will be interpreted as the Node attribute for custom border_colour

'#dee2e6'
border_radius int

node radius of nodes

12
border_width float | int | str

width of node borders, accepts int/float, otherwise if it is string it will be interpreted as the Node attribute for custom border_width

1
edge_colour str

colour of edges

'#ccc'
edge_width float | int

width of edges

1.5
font_colour str

font colour, accepts hexcode (starts with #), otherwise will be interpreted as the Node attribute for custom font_colour

'#333'
font_title_size int

font size of title text in node

13
font_size int

font size of attribute text in node

11
height int

height of diagram

500
width int

width of diagram

900

Returns:

Type Description
str

HTML string to display

tree_to_dot

tree_to_dot(
    tree,
    directed=True,
    rankdir="TB",
    bg_colour=None,
    node_colour=None,
    node_shape=None,
    edge_colour=None,
    node_attr=None,
    edge_attr=None,
)

Export tree(s) to pydot.Dot object. Object can be converted to other format, such as png, dot file or dot string. Dot string can be imported to work with networkx.

Possible node attributes include style, fillcolor, shape.

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> graph = tree.to_dot(root)

Display image directly without saving (requires IPython)

>>> from IPython.display import Image, display
>>> plt = Image(graph.create_png())
>>> display(plt)
<IPython.core.display.Image object>

Export to image, dot file, etc.

>>> graph.write_png("assets/tree.png")
>>> graph.write_dot("assets/tree.dot")

Export to Dot

Export to string

>>> graph.to_string()
'strict digraph G {\nrankdir=TB;\na0 [label=a];\nb0 [label=b];\na0 -> b0;\nd0 [label=d];\nb0 -> d0;\ne0 [label=e];\nb0 -> e0;\nc0 [label=c];\na0 -> c0;\n}\n'

Defining node and edge attributes (using node attribute)

>>> class CustomNode(Node):
...     def __init__(self, name, node_shape="", edge_label="", **kwargs):
...         super().__init__(name, **kwargs)
...         self.node_shape = node_shape
...         self.edge_label = edge_label
...
...     @property
...     def edge_attr(self):
...         if self.edge_label:
...             return {"label": self.edge_label}
...         return {}
...
...     @property
...     def node_attr(self):
...         if self.node_shape:
...             return {"shape": self.node_shape}
...         return {}
>>>
>>>
>>> root = CustomNode("a", node_shape="circle")
>>> b = CustomNode("b", edge_label="child", parent=root)
>>> c = CustomNode("c", edge_label="child", parent=root)
>>> d = CustomNode("d", node_shape="square", edge_label="child", parent=b)
>>> e = CustomNode("e", node_shape="square", edge_label="child", parent=b)
>>> tree = Tree(root)
>>> graph = tree.to_dot(node_colour="gold", node_shape="diamond", node_attr="node_attr", edge_attr="edge_attr")
>>> graph.write_png("assets/export_tree_dot.png")

Export to dot

Alternative way to define node and edge attributes (using callable function)

>>> def get_node_attribute(node: Node):
...     if node.is_leaf:
...         return {"shape": "square"}
...     return {"shape": "circle"}
>>>
>>>
>>> root = CustomNode("a")
>>> b = CustomNode("b", parent=root)
>>> c = CustomNode("c", parent=root)
>>> d = CustomNode("d", parent=b)
>>> e = CustomNode("e", parent=b)
>>> tree = Tree(root)
>>> graph = tree.to_dot(node_colour="gold", node_attr=get_node_attribute)
>>> graph.write_png("assets/export_tree_dot_callable.png")

Export to dot (callable)

Parameters:

Name Type Description Default
tree T | list[T]

tree(s) to be exported

required
directed bool

indicator whether graph should be directed or undirected

True
rankdir str

layout direction, accepts 'TB' (top to bottom), 'BT' (bottom to top), 'LR' (left to right), or 'RL' (right to left)

'TB'
bg_colour str | None

background color of image

None
node_colour str | None

fill colour of nodes

None
node_shape str | None

shape of nodes. Possible node_shape include "circle", "square", "diamond", "triangle"

None
edge_colour str | None

colour of edges

None
node_attr Callable[[T], dict[str, Any]] | str | None

If string type, it refers to Node attribute for node style. If callable type, it takes in the node itself and returns the node style. This overrides node_colour and node_shape. Possible node styles include {"style": "filled", "fillcolor": "gold", "shape": "diamond"}

None
edge_attr Callable[[T], dict[str, Any]] | str | None

If string type, it refers to Node attribute for edge style. If callable type, it takes in the node itself and returns the edge style. This overrides edge_colour. Possible edge styles include

None

Returns:

Type Description
Dot

Dot object of tree

tree_to_mermaid

tree_to_mermaid(
    tree,
    title=None,
    theme=None,
    rankdir="TB",
    line_shape="basis",
    node_colour=None,
    node_border_colour=None,
    node_border_width=1,
    node_shape="rounded_edge",
    node_shape_attr=None,
    edge_arrow="normal",
    edge_arrow_attr=None,
    edge_label=None,
    node_attr=None,
    **kwargs
)

Export tree to mermaid Markdown text. Accepts additional keyword arguments as input to yield_tree.

Parameters for customisations that apply to entire flowchart include
  • Title, title
  • Theme, theme
  • Layout direction, rankdir
  • Line shape or curvature, line_shape
  • Fill colour of nodes, node_colour
  • Border colour of nodes, node_border_colour
  • Border width of nodes, node_border_width
  • Node shape, node_shape
  • Edge arrow style, edge_arrow
Parameters for customisations that apply to customised nodes
  • Fill colour of nodes, fill under node_attr
  • Border colour of nodes, stroke under node_attr
  • Border width of nodes, stroke-width under node_attr
  • Node shape, node_shape_attr
  • Edge arrow style, edge_arrow_attr
  • Edge label, edge_label

Accepted Parameter Values

Possible theme
  • default
  • neutral: great for black and white documents
  • dark: great for dark-mode
  • forest: shades of geen
  • base: theme that can be modified, use it for customisations
Possible rankdir
  • TB: top-to-bottom
  • BT: bottom-to-top
  • LR: left-to-right
  • RL: right-to-left
Possible line_shape
  • basis
  • bumpX: used in LR or RL direction
  • bumpY
  • cardinal: undirected
  • catmullRom: undirected
  • linear:
  • monotoneX: used in LR or RL direction
  • monotoneY
  • natural
  • step: used in LR or RL direction
  • stepAfter
  • stepBefore: used in LR or RL direction
Possible node_shape
  • rounded_edge: rectangular with rounded edges
  • stadium: (_) shape, rectangular with rounded ends
  • subroutine: ||_|| shape, rectangular with additional line at the ends
  • cylindrical: database node
  • circle: circular
  • asymmetric: >_| shape
  • rhombus: decision node
  • hexagon: <_> shape
  • parallelogram: /_/ shape
  • parallelogram_alt: \_\ shape, inverted parallelogram
  • trapezoid: /_\ shape
  • trapezoid_alt: \_/ shape, inverted trapezoid
  • double_circle
Possible edge_arrow
  • normal: directed arrow, shaded arrowhead
  • bold: bold directed arrow
  • dotted: dotted directed arrow
  • open: line, undirected arrow
  • bold_open: bold line
  • dotted_open: dotted line
  • invisible: no line
  • circle: directed arrow with filled circle arrowhead
  • cross: directed arrow with cross arrowhead
  • double_normal: bidirectional directed arrow
  • double_circle: bidirectional directed arrow with filled circle arrowhead
  • double_cross: bidirectional directed arrow with cross arrowhead

Refer to mermaid documentation for more information. Paste the output into any markdown file renderer to view the flowchart, alternatively visit the mermaid playground here.

Note

Advanced mermaid flowchart functionalities such as subgraphs and interactions (script, click) are not supported.

Examples:

>>> from bigtree import Tree
>>> root = Node("a", node_shape="rhombus")
>>> b = Node("b", edge_arrow="bold", edge_label="Child 1", parent=root)
>>> c = Node("c", edge_arrow="dotted", edge_label="Child 2", parent=root)
>>> d = Node("d", node_style="fill:yellow, stroke:black", parent=b)
>>> e = Node("e", parent=b)
>>> tree = Tree(root)
>>> graph = tree.to_mermaid()
>>> print(graph)
```mermaid
%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%
flowchart TB
0("a") --> 0-0("b")
0-0 --> 0-0-0("d")
0-0 --> 0-0-1("e")
0("a") --> 0-1("c")
classDef default stroke-width:1
```

Customise node shape, edge label, edge arrow, and custom node attributes

>>> graph = tree.to_mermaid(
...     title="Mermaid Diagram",
...     theme="forest",
...     node_shape_attr="node_shape",
...     edge_label="edge_label",
...     edge_arrow_attr="edge_arrow",
...     node_attr="node_style",
... )
>>> print(graph)
```mermaid
---
title: Mermaid Diagram
---
%%{ init: { 'flowchart': { 'curve': 'basis' }, 'theme': 'forest' } }%%
flowchart TB
0{"a"} ==>|Child 1| 0-0("b")
0-0 --> 0-0-0("d"):::class0-0-0
0-0 --> 0-0-1("e")
0{"a"} -.->|Child 2| 0-1("c")
classDef default stroke-width:1
classDef class0-0-0 fill:yellow, stroke:black
```

Parameters:

Name Type Description Default
tree T

tree to be exported

required
title str | None

title

None
theme str | None

theme or colour scheme

None
rankdir str

layout direction, accepts 'TB' (top to bottom), 'BT' (bottom to top), 'LR' (left to right), 'RL' (right to left)

'TB'
line_shape str

line shape or curvature

'basis'
node_colour str | None

fill colour of nodes, can be colour name or hexcode

None
node_border_colour str | None

border colour of nodes, can be colour name or hexcode

None
node_border_width float

width of node border

1
node_shape str

node shape, sets the shape of every node

'rounded_edge'
node_shape_attr Callable[[T], str] | str | None

If string type, it refers to Node attribute for node shape. If callable type, it takes in the node itself and returns the node shape. This sets the shape of custom nodes, and overrides default node_shape

None
edge_arrow str

edge arrow style from parent to itself, sets the arrow style of every edge

'normal'
edge_arrow_attr Callable[[T], str] | str | None

If string type, it refers to Node attribute for edge arrow style. If callable type, it takes in the node itself and returns the edge arrow style. This sets the edge arrow style of custom nodes from parent to itself, and overrides default edge_arrow

None
edge_label str | None

Node attribute for edge label from parent to itself

None
node_attr Callable[[T], str] | str | None

If string type, it refers to Node attribute for node style. If callable type, it takes in the node itself and returns the node style. This overrides node_colour, node_border_colour, and node_border_width

None

Returns:

Type Description
str

Mermaid string of tree

tree_to_pillow

tree_to_pillow(
    tree,
    width=0,
    height=0,
    start_pos=(10, 10),
    font_family=None,
    font_size=12,
    font_colour="black",
    bg_colour="white",
    **kwargs
)

Export tree to PIL.Image.Image object. Object can be converted to other formats, such as jpg, or png. Image will be similar format as print_tree, accepts additional keyword arguments as input to yield_tree.

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> pillow_image = tree.to_pillow()

Export to image (PNG, JPG) file, etc.

>>> pillow_image.save("assets/tree_pillow.png")
>>> pillow_image.save("assets/tree_pillow.jpg")

Export to pillow

Parameters:

Name Type Description Default
tree T

tree to be exported

required
width int

width of image, optional as width of image is calculated automatically

0
height int

height of image, optional as height of image is calculated automatically

0
start_pos tuple[int, int]

start position of text, (x-offset, y-offset)

(10, 10)
font_family str | None

file path of font family, requires .ttf file, defaults to DejaVuSans

None
font_size int

font size

12
font_colour tuple[int, int, int] | str

font colour, accepts tuple of RGB values or string

'black'
bg_colour tuple[int, int, int] | str

background of image, accepts tuple of RGB values or string

'white'

Returns:

Type Description
Image

Pillow object of tree, in condensed text format

tree_to_pillow_graph

tree_to_pillow_graph(
    tree,
    node_content="{node_name}",
    *,
    margin=None,
    height_buffer=20,
    width_buffer=10,
    font_family=None,
    font_size=12,
    font_colour="black",
    text_align="center",
    bg_colour="white",
    rect_margin=None,
    rect_fill="white",
    rect_cmap_attr=None,
    rect_outline="black",
    rect_width=1,
    **kwargs
)

Export tree to PIL.Image.Image object. Object can be converted to other formats, such as jpg, or png. Image will look like a tree/graph-like structure, accepts additional keyword arguments as input to yield_tree.

Customisations:

- To change the margin of tree within diagram, vary `margin`
- To change the margin of the text within node, vary `rect_margin`
- For more separation between nodes, change `height_buffer` and `width_buffer`

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> pillow_image = tree.to_pillow_graph(node_content="{node_name}\nAge: {age}")

Export to image (PNG, JPG) file, etc.

>>> pillow_image.save("assets/tree_pillow_graph.png")
>>> pillow_image.save("assets/tree_pillow_graph.jpg")

Export to Pillow Graph

Parameters:

Name Type Description Default
tree T

tree to be exported

required
node_content str

display text in node

'{node_name}'
margin dict[str, int] | None

margin of diagram

None
height_buffer int | float

height buffer between node layers, in pixels

20
width_buffer int | float

width buffer between sibling nodes, in pixels

10
font_family str | None

file path of font family, requires .ttf file, defaults to DejaVuSans

None
font_size int

font size

12
font_colour tuple[int, int, int] | str

font colour, accepts tuple of RGB values or string

'black'
text_align str

text align for multi-line text

'center'
bg_colour tuple[int, int, int] | str

background of image, accepts tuple of RGB values or string

'white'
rect_margin dict[str, int] | None

(for rectangle) margin of text to rectangle, in pixels

None
rect_fill tuple[int, int, int] | str | Colormap

(for rectangle) colour to use for fill

'white'
rect_cmap_attr str | None

(for rectangle) if rect_fill is a colormap, attribute of node to retrieve fill from colormap, must be a float/int attribute

None
rect_outline tuple[int, int, int] | str

(for rectangle) colour to use for outline

'black'
rect_width int

(for rectangle) line width, in pixels

1

Returns:

Type Description
Image

Pillow object of tree, in graph format

hprint_tree

hprint_tree(
    tree,
    alias="node_name",
    node_name_or_path=None,
    max_depth=0,
    intermediate_node_name=True,
    spacing=0,
    style="const",
    border_style=None,
    strip=True,
    **kwargs
)

Print tree in horizontal orientation to console, starting from tree. Accepts kwargs for print() function.

  • Able to have alias for node name if alias attribute is present, else it falls back to node_name, using alias
  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customise for maximum depth to print, using max_depth
  • Able to hide names of intermediate nodes, using intermediate_node_name
  • Able to select horizontal spacing between nodes, using spacing
  • Able to customise style, to choose from str, Iterable[str], or inherit from constants.BaseHPrintStyle, using style
  • Able to toggle border, with border style to choose from str, Iterable[str], or inherit from constants.BorderStyle, using border_style
  • Able to have constant width output string or to strip the trailing spaces, using strip

For style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (Iterable[str]): Choose own style icons, they must have the same number of characters
  • (constants.BaseHPrintStyle): ANSIHPrintStyle, ASCIIHPrintStyle, ConstHPrintStyle, ConstBoldHPrintStyle, RoundedHPrintStyle, DoubleHPrintStyle style or inherit from constants.BaseHPrintStyle

For border_style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (Iterable[str]): Choose own style icons, they must be 1 character long
  • (constants.BorderStyle): ANSIBorderStyle, ASCIIBorderStyle, ConstBorderStyle, ConstBoldBorderStyle, RoundedBorderStyle, DoubleBorderStyle style or inherit from constants.BorderStyle

Examples:

Printing tree

>>> from bigtree import Node, hprint_tree
>>> root = Node("a")
>>> b = Node("b", parent=root)
>>> c = Node("c", parent=root)
>>> d = Node("d", parent=b)
>>> e = Node("e", parent=b)
>>> hprint_tree(root)
           โ”Œโ”€ d
     โ”Œโ”€ b โ”€โ”ค
โ”€ a โ”€โ”ค     โ””โ”€ e
     โ””โ”€ c

Printing Sub-tree

>>> hprint_tree(root, node_name_or_path="b")
     โ”Œโ”€ d
โ”€ b โ”€โ”ค
     โ””โ”€ e
>>> hprint_tree(root, max_depth=2)
     โ”Œโ”€ b
โ”€ a โ”€โ”ค
     โ””โ”€ c

Available Styles

>>> hprint_tree(root, style="ansi")
           /- d
     /- b -+
- a -+     \- e
     \- c
>>> hprint_tree(root, style="ascii")
           +- d
     +- b -+
- a -+     +- e
     +- c
>>> hprint_tree(root, style="const")
           โ”Œโ”€ d
     โ”Œโ”€ b โ”€โ”ค
โ”€ a โ”€โ”ค     โ””โ”€ e
     โ””โ”€ c
>>> hprint_tree(root, style="const_bold")
           โ”โ” d
     โ”โ” b โ”โ”ซ
โ” a โ”โ”ซ     โ”—โ” e
     โ”—โ” c
>>> hprint_tree(root, style="rounded")
           โ•ญโ”€ d
     โ•ญโ”€ b โ”€โ”ค
โ”€ a โ”€โ”ค     โ•ฐโ”€ e
     โ•ฐโ”€ c
>>> hprint_tree(root, style="double")
           โ•”โ• d
     โ•”โ• b โ•โ•ฃ
โ• a โ•โ•ฃ     โ•šโ• e
     โ•šโ• c

Custom Styles

>>> from bigtree import ANSIHPrintStyle
>>> hprint_tree(root, style=ANSIHPrintStyle)
           /- d
     /- b -+
- a -+     \- e
     \- c

Border

>>> hprint_tree(root, style="rounded", border_style="rounded")
                    โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
          โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญโ”ค   d   โ”‚
         โ•ญโ”ค   b   โ”œโ”คโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚   a   โ”œโ”ค         โ•ฐโ”ค   e   โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚          โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
         โ”‚โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
         โ•ฐโ”ค   c   โ”‚
          โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Printing to a file

>>> import io
>>> output = io.StringIO()
>>> hprint_tree(root, file=output)
>>> tree_string = output.getvalue()
>>> print(tree_string)
           โ”Œโ”€ d
     โ”Œโ”€ b โ”€โ”ค
โ”€ a โ”€โ”ค     โ””โ”€ e
     โ””โ”€ c

Parameters:

Name Type Description Default
tree T

tree to print

required
alias str

node attribute to use for node name in tree as alias to node_name

'node_name'
node_name_or_path str | None

node to print from, becomes the root node of printing

None
max_depth int

maximum depth of tree to print, based on depth attribute

0
intermediate_node_name bool

indicator if intermediate nodes have node names

True
spacing int

horizontal spacing between node displays

0
style str | Iterable[str] | BaseHPrintStyle

style of print

'const'
border_style str | Iterable[str] | BorderStyle | None

style of border

None
strip bool

whether to strip results

True

hyield_tree

hyield_tree(
    tree,
    alias="node_name",
    node_name_or_path=None,
    max_depth=0,
    intermediate_node_name=True,
    spacing=0,
    style="const",
    border_style=None,
    strip=True,
)

Yield tree in horizontal orientation to console, starting from tree.

  • Able to have alias for node name if alias attribute is present, else it falls back to node_name, using alias
  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customise for maximum depth to print, using max_depth
  • Able to hide names of intermediate nodes, using intermediate_node_name
  • Able to select horizontal spacing between nodes, using spacing
  • Able to customise style, to choose from str, Iterable[str], or inherit from constants.BaseHPrintStyle, using style
  • Able to toggle border, with border style to choose from str, Iterable[str], or inherit from constants.BorderStyle, using border_style
  • Able to have constant width output string or to strip the trailing spaces, using strip

For style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (Iterable[str]): Choose own style icons, they must be 1 character long
  • (constants.BaseHPrintStyle): ANSIHPrintStyle, ASCIIHPrintStyle, ConstHPrintStyle, ConstBoldHPrintStyle, RoundedHPrintStyle, DoubleHPrintStyle style or inherit from constants.BaseHPrintStyle

For border_style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (Iterable[str]): Choose own style icons, they must be 1 character long
  • (constants.BorderStyle): ANSIBorderStyle, ASCIIBorderStyle, ConstBorderStyle, ConstBoldBorderStyle, RoundedBorderStyle, DoubleBorderStyle style or inherit from constants.BorderStyle

Examples:

Printing tree

>>> from bigtree import Node, hyield_tree
>>> root = Node("a")
>>> b = Node("b", parent=root)
>>> c = Node("c", parent=root)
>>> d = Node("d", parent=b)
>>> e = Node("e", parent=b)
>>> result = hyield_tree(root)
>>> print("\n".join(result))
           โ”Œโ”€ d
     โ”Œโ”€ b โ”€โ”ค
โ”€ a โ”€โ”ค     โ””โ”€ e
     โ””โ”€ c

Printing Sub-tree

>>> result = hyield_tree(root, node_name_or_path="b")
>>> print("\n".join(result))
     โ”Œโ”€ d
โ”€ b โ”€โ”ค
     โ””โ”€ e
>>> result = hyield_tree(root, max_depth=2)
>>> print("\n".join(result))
     โ”Œโ”€ b
โ”€ a โ”€โ”ค
     โ””โ”€ c

Available Styles

>>> result = hyield_tree(root, style="ansi")
>>> print("\n".join(result))
           /- d
     /- b -+
- a -+     \- e
     \- c
>>> result = hyield_tree(root, style="ascii")
>>> print("\n".join(result))
           +- d
     +- b -+
- a -+     +- e
     +- c
>>> result = hyield_tree(root, style="const")
>>> print("\n".join(result))
           โ”Œโ”€ d
     โ”Œโ”€ b โ”€โ”ค
โ”€ a โ”€โ”ค     โ””โ”€ e
     โ””โ”€ c
>>> result = hyield_tree(root, style="const_bold")
>>> print("\n".join(result))
           โ”โ” d
     โ”โ” b โ”โ”ซ
โ” a โ”โ”ซ     โ”—โ” e
     โ”—โ” c
>>> result = hyield_tree(root, style="rounded")
>>> print("\n".join(result))
           โ•ญโ”€ d
     โ•ญโ”€ b โ”€โ”ค
โ”€ a โ”€โ”ค     โ•ฐโ”€ e
     โ•ฐโ”€ c
>>> result = hyield_tree(root, style="double")
>>> print("\n".join(result))
           โ•”โ• d
     โ•”โ• b โ•โ•ฃ
โ• a โ•โ•ฃ     โ•šโ• e
     โ•šโ• c

Custom Styles

>>> from bigtree import ANSIHPrintStyle
>>> result = hyield_tree(root, style=ANSIHPrintStyle)
>>> print("\n".join(result))
           /- d
     /- b -+
- a -+     \- e
     \- c

Border

>>> result = hyield_tree(root, style="rounded", border_style="rounded")
>>> print("\n".join(result))
                    โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
          โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญโ”ค   d   โ”‚
         โ•ญโ”ค   b   โ”œโ”คโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚   a   โ”œโ”ค         โ•ฐโ”ค   e   โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚          โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
         โ”‚โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
         โ•ฐโ”ค   c   โ”‚
          โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Parameters:

Name Type Description Default
tree T

tree to print

required
alias str

node attribute to use for node name in tree as alias to node_name

'node_name'
node_name_or_path str | None

node to print from, becomes the root node of printing

None
max_depth int

maximum depth of tree to print, based on depth attribute

0
intermediate_node_name bool

indicator if intermediate nodes have node names

True
spacing int

horizontal spacing between node displays

0
style str | Iterable[str] | BaseHPrintStyle

style of print

'const'
border_style str | Iterable[str] | BorderStyle | None

style of border

None
strip bool

whether to strip results

True

Returns:

Type Description
list[str]

Yield tree in horizontal format

print_rich

print_rich(
    pre_str,
    fill_str,
    node_str,
    _node,
    console,
    *,
    node_format=None,
    node_format_attr=None,
    edge_format=None,
    icon_prefix_attr=None,
    icon_suffix_attr=None,
    **kwargs
)

Add rich formatting and print tree to console

Parameters:

Name Type Description Default
pre_str str

edge of tree

required
fill_str str

the empty spaces

required
node_str str

node details

required
_node T

node to print

required
console Console

rich console if exist, otherwise a console will be created

required
node_format str | None

node format, sets the node format of every node, e.g., bold magenta

None
node_format_attr str | Callable[[T], str] | None

If string type, it refers to Node attribute for node format. If callable type, it takes in the node itself and returns the format. This sets the format of custom nodes, and overrides default node_format

None
edge_format str | None

edge format, sets the edge format, e.g., bold magenta

None
icon_prefix_attr str | Callable[[T], str] | None

node icon infront of node name. Accepts emoji code (e.g., :thumbs_up:), unicode characters (e.g., ๐Ÿ˜€), or anything rich supports. If string type, it refers to Node attribute for icon. If callable type, it takes in the node itself and returns the icon

None
icon_suffix_attr str | Callable[[T], str] | None

node icon behind node name. Accepts emoji code (e.g., :thumbs_up:), unicode characters (e.g., ๐Ÿ˜€), or anything rich supports. If string type, it refers to Node attribute for icon. If callable type, it takes in the node itself and returns the icon

None

print_tree

print_tree(
    tree,
    alias="node_name",
    node_name_or_path=None,
    max_depth=0,
    all_attrs=False,
    attr_list=None,
    attr_format="{k}={v}",
    attr_sep=", ",
    attr_omit_null=False,
    attr_bracket=("[", "]"),
    style="const",
    **kwargs
)

Print tree to console, starting from tree. Accepts kwargs for print() function.

  • Able to have alias for node name if alias attribute is present, else it falls back to node_name, using alias
  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customise for maximum depth to print, using max_depth
  • Able to choose which attributes to show or show all attributes, using all_attrs and attr_list
  • For showing attributes, able to customise the format of attributes and separator of attributes
  • Able to omit showing of attributes if it is null, using attr_omit_null
  • Able to customise open and close brackets if attributes are shown, using attr_bracket
  • Able to customise style, to choose from str, list[str], or inherit from constants.BasePrintStyle, using style
  • Able to support rich format, using rich=True

For style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (list[str]): Choose own style for stem, branch, and final stem icons, they must have the same number of characters
  • (constants.BasePrintStyle): ANSIPrintStyle, ASCIIPrintStyle, ConstPrintStyle, ConstBoldPrintStyle, RoundedPrintStyle, DoublePrintStyle style or inherit from constants.BasePrintStyle

For rich format, set rich=True and refer to print_rich for the list of arguments.

Examples:

Printing tree

>>> from bigtree import Node, Tree
>>> root = Node("a", alias="alias-a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", alias="alias-c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> tree.show()
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ””โ”€โ”€ e
โ””โ”€โ”€ c

Printing alias

>>> tree.show(alias="alias")
alias-a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ””โ”€โ”€ e
โ””โ”€โ”€ alias-c

Printing Sub-tree

>>> tree.show(node_name_or_path="b")
b
โ”œโ”€โ”€ d
โ””โ”€โ”€ e
>>> tree.show(max_depth=2)
a
โ”œโ”€โ”€ b
โ””โ”€โ”€ c

Printing Attributes

>>> tree.show(attr_list=["age"])
a [age=90]
โ”œโ”€โ”€ b [age=65]
โ”‚   โ”œโ”€โ”€ d [age=40]
โ”‚   โ””โ”€โ”€ e [age=35]
โ””โ”€โ”€ c [age=60]
>>> tree.show(attr_list=["name", "age"], attr_format="{k}:{v}", attr_sep="; ")
a [name:a; age:90]
โ”œโ”€โ”€ b [name:b; age:65]
โ”‚   โ”œโ”€โ”€ d [name:d; age:40]
โ”‚   โ””โ”€โ”€ e [name:e; age:35]
โ””โ”€โ”€ c [name:c; age:60]
>>> tree.show(attr_list=["age"], attr_bracket=["*(", ")"])
a *(age=90)
โ”œโ”€โ”€ b *(age=65)
โ”‚   โ”œโ”€โ”€ d *(age=40)
โ”‚   โ””โ”€โ”€ e *(age=35)
โ””โ”€โ”€ c *(age=60)

Available Styles

>>> tree.show(style="ansi")
a
|-- b
|   |-- d
|   `-- e
`-- c
>>> tree.show(style="ascii")
a
|-- b
|   |-- d
|   +-- e
+-- c
>>> tree.show(style="const")
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ””โ”€โ”€ e
โ””โ”€โ”€ c
>>> tree.show(style="const_bold")
a
โ”ฃโ”โ” b
โ”ƒ   โ”ฃโ”โ” d
โ”ƒ   โ”—โ”โ” e
โ”—โ”โ” c
>>> tree.show(style="rounded")
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ•ฐโ”€โ”€ e
โ•ฐโ”€โ”€ c
>>> tree.show(style="double")
a
โ• โ•โ• b
โ•‘   โ• โ•โ• d
โ•‘   โ•šโ•โ• e
โ•šโ•โ• c

Custom Styles

>>> from bigtree import ANSIPrintStyle
>>> tree.show(style=ANSIPrintStyle)
a
|-- b
|   |-- d
|   `-- e
`-- c

Printing to a file

>>> import io
>>> output = io.StringIO()
>>> tree.show(file=output)
>>> tree_string = output.getvalue()
>>> print(tree_string)
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ””โ”€โ”€ e
โ””โ”€โ”€ c

Printing rich format

>>> from rich.console import Console
>>> console = Console(record=True, color_system=None)  # optional, for doctest for docstring
>>> tree.show(rich=True, node_format="bold magenta", edge_format="blue", console=console)
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ””โ”€โ”€ e
โ””โ”€โ”€ c

Parameters:

Name Type Description Default
tree T

tree to print

required
alias str

node attribute to use for node name in tree as alias to node_name

'node_name'
node_name_or_path str | None

node to print from, becomes the root node of printing

None
max_depth int

maximum depth of tree to print, based on depth attribute

0
all_attrs bool

indicator to show all attributes, overrides attr_list and attr_omit_null

False
attr_list Iterable[str] | None

node attributes to print

None
attr_format str

if attributes are displayed, the format in which to display, uses k,v to correspond to attribute name and attribute value

'{k}={v}'
attr_sep str

if attributes are displayed, the separator of attributes, defaults to comma

', '
attr_omit_null bool

indicator whether to omit showing of null attributes

False
attr_bracket tuple[str, str]

open and close bracket for all_attrs or attr_list

('[', ']')
style str | Iterable[str] | BasePrintStyle

style of print

'const'

tree_to_newick

tree_to_newick(
    tree,
    intermediate_node_name=True,
    length_attr=None,
    length_sep=SEP,
    attr_list=None,
    attr_prefix="&&NHX:",
    attr_sep=SEP,
)

Export tree to Newick notation. Useful for describing phylogenetic tree.

In the Newick Notation (or New Hampshire Notation)

  • Tree is represented in round brackets i.e., (child1,child2,child3)parent
  • If there are nested trees, they will be in nested round brackets i.e., ((grandchild1)child1,(grandchild2,grandchild3)child2)parent
  • If there is length attribute, they will be beside the name i.e., (child1:0.5,child2:0.1)parent
  • If there are other attributes, attributes are represented in square brackets i.e., (child1:0.5[S:human],child2:0.1[S:human])parent[S:parent]

Customisations include

  • Omitting names of root and intermediate nodes, default all node names are shown
  • Changing length separator to another symbol, default is :
  • Adding an attribute prefix, default is &&NHX:
  • Changing the attribute separator to another symbol, default is :

Examples:

>>> from bigtree import Node, tree_to_newick
>>> root = Node("a", species="human")
>>> b = Node("b", age=65, species="human", parent=root)
>>> c = Node("c", age=60, species="human", parent=root)
>>> d = Node("d", age=40, species="human", parent=b)
>>> e = Node("e", age=35, species="human", parent=b)
>>> root.show()
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ””โ”€โ”€ e
โ””โ”€โ”€ c
>>> tree_to_newick(root)
'((d,e)b,c)a'
>>> tree_to_newick(root, length_attr="age")
'((d:40,e:35)b:65,c:60)a'
>>> tree_to_newick(root, length_attr="age", attr_list=["species"])
'((d:40[&&NHX:species=human],e:35[&&NHX:species=human])b:65[&&NHX:species=human],c:60[&&NHX:species=human])a[&&NHX:species=human]'

Parameters:

Name Type Description Default
tree T

tree to be exported

required
intermediate_node_name bool

indicator if intermediate nodes have node names

True
length_attr str | None

node length attribute to extract to beside name

None
length_sep str | NewickCharacter

separator between node name and length, used if length_attr is non-empty

SEP
attr_list Iterable[str] | None

node attributes to extract into square bracket

None
attr_prefix str

prefix before all attributes, within square bracket, used if attr_list is non-empty

'&&NHX:'
attr_sep str | NewickCharacter

separator between attributes, within square brackets, used if attr_list is non-empty

SEP

Returns:

Type Description
str

Newick string representation of tree

vprint_tree

vprint_tree(
    tree,
    alias="node_name",
    node_name_or_path=None,
    max_depth=0,
    intermediate_node_name=True,
    spacing=2,
    style="const",
    border_style="const",
    strip=False,
    **kwargs
)

Print tree in vertical orientation to console, starting from tree. Accepts kwargs for print() function.

  • Able to have alias for node name if alias attribute is present, else it falls back to node_name, using alias
  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customise for maximum depth to print, using max_depth
  • Able to hide names of intermediate nodes, using intermediate_node_name
  • Able to select horizontal spacing between nodes, using spacing
  • Able to customise style, to choose from str, Iterable[str], or inherit from constants.BaseVPrintStyle, using style
  • Able to toggle border, with border style to choose from str, Iterable[str], or inherit from constants.BorderStyle, using border_style
  • Able to have constant width output string or to strip the trailing spaces, using strip

For style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (Iterable[str]): Choose own style icons, they must be 1 character long
  • (constants.BaseVPrintStyle): ANSIVPrintStyle, ASCIIVPrintStyle, ConstVPrintStyle, ConstBoldVPrintStyle, RoundedVPrintStyle, DoubleVPrintStyle style or inherit from constants.BaseVPrintStyle

For border_style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (Iterable[str]): Choose own style icons, they must be 1 character long
  • (constants.BorderStyle): ANSIBorderStyle, ASCIIBorderStyle, ConstBorderStyle, ConstBoldBorderStyle, RoundedBorderStyle, DoubleBorderStyle style or inherit from constants.BorderStyle

Examples:

Printing tree

>>> from bigtree import Node, vprint_tree
>>> root = Node("a")
>>> b = Node("b", parent=root)
>>> c = Node("c", parent=root)
>>> d = Node("d", parent=b)
>>> e = Node("e", parent=b)
>>> vprint_tree(root, strip=True)
        โ”Œโ”€โ”€โ”€โ”
        โ”‚ a โ”‚
        โ””โ”€โ”ฌโ”€โ”˜
     โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”
   โ”Œโ”€โ”ดโ”€โ”      โ”Œโ”€โ”ดโ”€โ”
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ””โ”€โ”ฌโ”€โ”˜      โ””โ”€โ”€โ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ d โ”‚  โ”‚ e โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜

Printing Sub-tree

>>> vprint_tree(root, node_name_or_path="b", strip=True)
   โ”Œโ”€โ”€โ”€โ”
   โ”‚ b โ”‚
   โ””โ”€โ”ฌโ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ d โ”‚  โ”‚ e โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜
>>> vprint_tree(root, max_depth=2, strip=True)
   โ”Œโ”€โ”€โ”€โ”
   โ”‚ a โ”‚
   โ””โ”€โ”ฌโ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ b โ”‚  โ”‚ c โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜

Available Styles

>>> vprint_tree(root, style="ansi", border_style="ansi", strip=True)
        `---`
        | a |
        `-+-`
     /----+-----\
   `-+-`      `-+-`
   | b |      | c |
   `-+-`      `---`
  /--+---\
`-+-`  `-+-`
| d |  | e |
`---`  `---`
>>> vprint_tree(root, style="ascii", border_style="ascii", strip=True)
        +---+
        | a |
        +-+-+
     +----+-----+
   +-+-+      +-+-+
   | b |      | c |
   +-+-+      +---+
  +--+---+
+-+-+  +-+-+
| d |  | e |
+---+  +---+
>>> vprint_tree(root, style="const", border_style="const", strip=True)
        โ”Œโ”€โ”€โ”€โ”
        โ”‚ a โ”‚
        โ””โ”€โ”ฌโ”€โ”˜
     โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”
   โ”Œโ”€โ”ดโ”€โ”      โ”Œโ”€โ”ดโ”€โ”
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ””โ”€โ”ฌโ”€โ”˜      โ””โ”€โ”€โ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ d โ”‚  โ”‚ e โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜
>>> vprint_tree(root, style="const_bold", border_style="const_bold", strip=True)
        โ”โ”โ”โ”โ”“
        โ”ƒ a โ”ƒ
        โ”—โ”โ”ณโ”โ”›
     โ”โ”โ”โ”โ”โ”ปโ”โ”โ”โ”โ”โ”“
   โ”โ”โ”ปโ”โ”“      โ”โ”โ”ปโ”โ”“
   โ”ƒ b โ”ƒ      โ”ƒ c โ”ƒ
   โ”—โ”โ”ณโ”โ”›      โ”—โ”โ”โ”โ”›
  โ”โ”โ”โ”ปโ”โ”โ”โ”“
โ”โ”โ”ปโ”โ”“  โ”โ”โ”ปโ”โ”“
โ”ƒ d โ”ƒ  โ”ƒ e โ”ƒ
โ”—โ”โ”โ”โ”›  โ”—โ”โ”โ”โ”›
>>> vprint_tree(root, style="rounded", border_style="rounded", strip=True)
        โ•ญโ”€โ”€โ”€โ•ฎ
        โ”‚ a โ”‚
        โ•ฐโ”€โ”ฌโ”€โ•ฏ
     โ•ญโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ•ฎ
   โ•ญโ”€โ”ดโ”€โ•ฎ      โ•ญโ”€โ”ดโ”€โ•ฎ
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ•ฐโ”€โ”ฌโ”€โ•ฏ      โ•ฐโ”€โ”€โ”€โ•ฏ
  โ•ญโ”€โ”€โ”ดโ”€โ”€โ”€โ•ฎ
โ•ญโ”€โ”ดโ”€โ•ฎ  โ•ญโ”€โ”ดโ”€โ•ฎ
โ”‚ d โ”‚  โ”‚ e โ”‚
โ•ฐโ”€โ”€โ”€โ•ฏ  โ•ฐโ”€โ”€โ”€โ•ฏ
>>> vprint_tree(root, style="double", border_style="double", strip=True)
        โ•”โ•โ•โ•โ•—
        โ•‘ a โ•‘
        โ•šโ•โ•ฆโ•โ•
     โ•”โ•โ•โ•โ•โ•ฉโ•โ•โ•โ•โ•โ•—
   โ•”โ•โ•ฉโ•โ•—      โ•”โ•โ•ฉโ•โ•—
   โ•‘ b โ•‘      โ•‘ c โ•‘
   โ•šโ•โ•ฆโ•โ•      โ•šโ•โ•โ•โ•
  โ•”โ•โ•โ•ฉโ•โ•โ•โ•—
โ•”โ•โ•ฉโ•โ•—  โ•”โ•โ•ฉโ•โ•—
โ•‘ d โ•‘  โ•‘ e โ•‘
โ•šโ•โ•โ•โ•  โ•šโ•โ•โ•โ•

Custom Styles

>>> from bigtree import RoundedVPrintStyle, RoundedBorderStyle
>>> vprint_tree(root, style=RoundedVPrintStyle, border_style=RoundedBorderStyle, strip=True)
        โ•ญโ”€โ”€โ”€โ•ฎ
        โ”‚ a โ”‚
        โ•ฐโ”€โ”ฌโ”€โ•ฏ
     โ•ญโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ•ฎ
   โ•ญโ”€โ”ดโ”€โ•ฎ      โ•ญโ”€โ”ดโ”€โ•ฎ
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ•ฐโ”€โ”ฌโ”€โ•ฏ      โ•ฐโ”€โ”€โ”€โ•ฏ
  โ•ญโ”€โ”€โ”ดโ”€โ”€โ”€โ•ฎ
โ•ญโ”€โ”ดโ”€โ•ฎ  โ•ญโ”€โ”ดโ”€โ•ฎ
โ”‚ d โ”‚  โ”‚ e โ”‚
โ•ฐโ”€โ”€โ”€โ•ฏ  โ•ฐโ”€โ”€โ”€โ•ฏ

Printing to a file

>>> import io
>>> output = io.StringIO()
>>> vprint_tree(root, file=output, strip=True)
>>> tree_string = output.getvalue()
>>> print(tree_string)
        โ”Œโ”€โ”€โ”€โ”
        โ”‚ a โ”‚
        โ””โ”€โ”ฌโ”€โ”˜
     โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”
   โ”Œโ”€โ”ดโ”€โ”      โ”Œโ”€โ”ดโ”€โ”
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ””โ”€โ”ฌโ”€โ”˜      โ””โ”€โ”€โ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ d โ”‚  โ”‚ e โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜

Parameters:

Name Type Description Default
tree T

tree to print

required
alias str

node attribute to use for node name in tree as alias to node_name

'node_name'
node_name_or_path str | None

node to print from, becomes the root node of printing

None
max_depth int

maximum depth of tree to print, based on depth attribute

0
intermediate_node_name bool

indicator if intermediate nodes have node names

True
spacing int

horizontal spacing between node displays

2
style str | Iterable[str] | BaseVPrintStyle

style of print

'const'
border_style str | Iterable[str] | BorderStyle | None

style of border

'const'
strip bool

whether to strip results

False

vyield_tree

vyield_tree(
    tree,
    alias="node_name",
    node_name_or_path=None,
    max_depth=0,
    intermediate_node_name=True,
    spacing=2,
    style="const",
    border_style="const",
    strip=False,
)

Yield tree in vertical orientation to console, starting from tree.

  • Able to have alias for node name if alias attribute is present, else it falls back to node_name, using alias
  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customise for maximum depth to print, using max_depth
  • Able to hide names of intermediate nodes, using intermediate_node_name
  • Able to select horizontal spacing between nodes, using spacing
  • Able to customise style, to choose from str, Iterable[str], or inherit from constants.BaseVPrintStyle, using style
  • Able to toggle border, with border style to choose from str, Iterable[str], or inherit from constants.BorderStyle, using border_style
  • Able to have constant width output string or to strip the trailing spaces, using strip

For style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (Iterable[str]): Choose own style icons, they must be 1 character long
  • (constants.BaseVPrintStyle): ANSIVPrintStyle, ASCIIVPrintStyle, ConstVPrintStyle, ConstBoldVPrintStyle, RoundedVPrintStyle, DoubleVPrintStyle style or inherit from constants.BaseVPrintStyle

For border_style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (Iterable[str]): Choose own style icons, they must be 1 character long
  • (constants.BorderStyle): ANSIBorderStyle, ASCIIBorderStyle, ConstBorderStyle, ConstBoldBorderStyle, RoundedBorderStyle, DoubleBorderStyle style or inherit from constants.BorderStyle

Examples:

Printing tree

>>> from bigtree import Node, vyield_tree
>>> root = Node("a")
>>> b = Node("b", parent=root)
>>> c = Node("c", parent=root)
>>> d = Node("d", parent=b)
>>> e = Node("e", parent=b)
>>> result = vyield_tree(root, strip=True)
>>> print("\n".join(result))
        โ”Œโ”€โ”€โ”€โ”
        โ”‚ a โ”‚
        โ””โ”€โ”ฌโ”€โ”˜
     โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”
   โ”Œโ”€โ”ดโ”€โ”      โ”Œโ”€โ”ดโ”€โ”
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ””โ”€โ”ฌโ”€โ”˜      โ””โ”€โ”€โ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ d โ”‚  โ”‚ e โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜

Printing Sub-tree

>>> result = vyield_tree(root, node_name_or_path="b", strip=True)
>>> print("\n".join(result))
   โ”Œโ”€โ”€โ”€โ”
   โ”‚ b โ”‚
   โ””โ”€โ”ฌโ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ d โ”‚  โ”‚ e โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜
>>> result = vyield_tree(root, max_depth=2, strip=True)
>>> print("\n".join(result))
   โ”Œโ”€โ”€โ”€โ”
   โ”‚ a โ”‚
   โ””โ”€โ”ฌโ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ b โ”‚  โ”‚ c โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜

Available Styles

>>> result = vyield_tree(root, style="ansi", border_style="ansi", strip=True)
>>> print("\n".join(result))
        `---`
        | a |
        `-+-`
     /----+-----\
   `-+-`      `-+-`
   | b |      | c |
   `-+-`      `---`
  /--+---\
`-+-`  `-+-`
| d |  | e |
`---`  `---`
>>> result = vyield_tree(root, style="ascii", border_style="ascii", strip=True)
>>> print("\n".join(result))
        +---+
        | a |
        +-+-+
     +----+-----+
   +-+-+      +-+-+
   | b |      | c |
   +-+-+      +---+
  +--+---+
+-+-+  +-+-+
| d |  | e |
+---+  +---+
>>> result = vyield_tree(root, style="const", border_style="const", strip=True)
>>> print("\n".join(result))
        โ”Œโ”€โ”€โ”€โ”
        โ”‚ a โ”‚
        โ””โ”€โ”ฌโ”€โ”˜
     โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”
   โ”Œโ”€โ”ดโ”€โ”      โ”Œโ”€โ”ดโ”€โ”
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ””โ”€โ”ฌโ”€โ”˜      โ””โ”€โ”€โ”€โ”˜
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”€โ”
โ”Œโ”€โ”ดโ”€โ”  โ”Œโ”€โ”ดโ”€โ”
โ”‚ d โ”‚  โ”‚ e โ”‚
โ””โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”˜
>>> result = vyield_tree(root, style="const_bold", border_style="const_bold", strip=True)
>>> print("\n".join(result))
        โ”โ”โ”โ”โ”“
        โ”ƒ a โ”ƒ
        โ”—โ”โ”ณโ”โ”›
     โ”โ”โ”โ”โ”โ”ปโ”โ”โ”โ”โ”โ”“
   โ”โ”โ”ปโ”โ”“      โ”โ”โ”ปโ”โ”“
   โ”ƒ b โ”ƒ      โ”ƒ c โ”ƒ
   โ”—โ”โ”ณโ”โ”›      โ”—โ”โ”โ”โ”›
  โ”โ”โ”โ”ปโ”โ”โ”โ”“
โ”โ”โ”ปโ”โ”“  โ”โ”โ”ปโ”โ”“
โ”ƒ d โ”ƒ  โ”ƒ e โ”ƒ
โ”—โ”โ”โ”โ”›  โ”—โ”โ”โ”โ”›
>>> result = vyield_tree(root, style="rounded", border_style="rounded", strip=True)
>>> print("\n".join(result))
        โ•ญโ”€โ”€โ”€โ•ฎ
        โ”‚ a โ”‚
        โ•ฐโ”€โ”ฌโ”€โ•ฏ
     โ•ญโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ•ฎ
   โ•ญโ”€โ”ดโ”€โ•ฎ      โ•ญโ”€โ”ดโ”€โ•ฎ
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ•ฐโ”€โ”ฌโ”€โ•ฏ      โ•ฐโ”€โ”€โ”€โ•ฏ
  โ•ญโ”€โ”€โ”ดโ”€โ”€โ”€โ•ฎ
โ•ญโ”€โ”ดโ”€โ•ฎ  โ•ญโ”€โ”ดโ”€โ•ฎ
โ”‚ d โ”‚  โ”‚ e โ”‚
โ•ฐโ”€โ”€โ”€โ•ฏ  โ•ฐโ”€โ”€โ”€โ•ฏ
>>> result = vyield_tree(root, style="double", border_style="double", strip=True)
>>> print("\n".join(result))
        โ•”โ•โ•โ•โ•—
        โ•‘ a โ•‘
        โ•šโ•โ•ฆโ•โ•
     โ•”โ•โ•โ•โ•โ•ฉโ•โ•โ•โ•โ•โ•—
   โ•”โ•โ•ฉโ•โ•—      โ•”โ•โ•ฉโ•โ•—
   โ•‘ b โ•‘      โ•‘ c โ•‘
   โ•šโ•โ•ฆโ•โ•      โ•šโ•โ•โ•โ•
  โ•”โ•โ•โ•ฉโ•โ•โ•โ•—
โ•”โ•โ•ฉโ•โ•—  โ•”โ•โ•ฉโ•โ•—
โ•‘ d โ•‘  โ•‘ e โ•‘
โ•šโ•โ•โ•โ•  โ•šโ•โ•โ•โ•

Custom Styles

>>> from bigtree import RoundedVPrintStyle, RoundedBorderStyle
>>> result = vyield_tree(root, style=RoundedVPrintStyle, border_style=RoundedBorderStyle, strip=True)
>>> print("\n".join(result))
        โ•ญโ”€โ”€โ”€โ•ฎ
        โ”‚ a โ”‚
        โ•ฐโ”€โ”ฌโ”€โ•ฏ
     โ•ญโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ•ฎ
   โ•ญโ”€โ”ดโ”€โ•ฎ      โ•ญโ”€โ”ดโ”€โ•ฎ
   โ”‚ b โ”‚      โ”‚ c โ”‚
   โ•ฐโ”€โ”ฌโ”€โ•ฏ      โ•ฐโ”€โ”€โ”€โ•ฏ
  โ•ญโ”€โ”€โ”ดโ”€โ”€โ”€โ•ฎ
โ•ญโ”€โ”ดโ”€โ•ฎ  โ•ญโ”€โ”ดโ”€โ•ฎ
โ”‚ d โ”‚  โ”‚ e โ”‚
โ•ฐโ”€โ”€โ”€โ•ฏ  โ•ฐโ”€โ”€โ”€โ•ฏ

Parameters:

Name Type Description Default
tree T

tree to print

required
alias str

node attribute to use for node name in tree as alias to node_name

'node_name'
node_name_or_path str | None

node to print from, becomes the root node of printing

None
max_depth int

maximum depth of tree to print, based on depth attribute

0
intermediate_node_name bool

indicator if intermediate nodes have node names

True
spacing int

horizontal spacing between node displays

2
style str | Iterable[str] | BaseVPrintStyle

style of print

'const'
border_style str | Iterable[str] | BorderStyle | None

style of border

'const'
strip bool

whether to strip results

False

Returns:

Type Description
list[str]

Yield tree in vertical format

yield_tree

yield_tree(
    tree, node_name_or_path=None, max_depth=0, style="const"
)

Generator method for customizing printing of tree, starting from tree.

  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customise for maximum depth to print, using max_depth
  • Able to customise style, to choose from str, list[str], or inherit from constants.BasePrintStyle, using style

For style,

  • (str): ansi, ascii, const (default), const_bold, rounded, double style
  • (list[str]): Choose own style for stem, branch, and final stem icons, they must have the same number of characters
  • (constants.BasePrintStyle): ANSIPrintStyle, ASCIIPrintStyle, ConstPrintStyle, ConstBoldPrintStyle, RoundedPrintStyle, DoublePrintStyle style or inherit from constants.BasePrintStyle

Examples:

Yield tree

>>> from bigtree import Node, yield_tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> for branch, stem, node in yield_tree(root):
...     print(f"{branch}{stem}{node.node_name}")
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ””โ”€โ”€ e
โ””โ”€โ”€ c

Yield Sub-tree

>>> for branch, stem, node in yield_tree(root, node_name_or_path="b"):
...     print(f"{branch}{stem}{node.node_name}")
b
โ”œโ”€โ”€ d
โ””โ”€โ”€ e
>>> for branch, stem, node in yield_tree(root, max_depth=2):
...     print(f"{branch}{stem}{node.node_name}")
a
โ”œโ”€โ”€ b
โ””โ”€โ”€ c

Available Styles

>>> for branch, stem, node in yield_tree(root, style="ansi"):
...     print(f"{branch}{stem}{node.node_name}")
a
|-- b
|   |-- d
|   `-- e
`-- c
>>> for branch, stem, node in yield_tree(root, style="ascii"):
...     print(f"{branch}{stem}{node.node_name}")
a
|-- b
|   |-- d
|   +-- e
+-- c
>>> for branch, stem, node in yield_tree(root, style="const"):
...     print(f"{branch}{stem}{node.node_name}")
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ””โ”€โ”€ e
โ””โ”€โ”€ c
>>> for branch, stem, node in yield_tree(root, style="const_bold"):
...     print(f"{branch}{stem}{node.node_name}")
a
โ”ฃโ”โ” b
โ”ƒ   โ”ฃโ”โ” d
โ”ƒ   โ”—โ”โ” e
โ”—โ”โ” c
>>> for branch, stem, node in yield_tree(root, style="rounded"):
...     print(f"{branch}{stem}{node.node_name}")
a
โ”œโ”€โ”€ b
โ”‚   โ”œโ”€โ”€ d
โ”‚   โ•ฐโ”€โ”€ e
โ•ฐโ”€โ”€ c
>>> for branch, stem, node in yield_tree(root, style="double"):
...     print(f"{branch}{stem}{node.node_name}")
a
โ• โ•โ• b
โ•‘   โ• โ•โ• d
โ•‘   โ•šโ•โ• e
โ•šโ•โ• c

Custom Styles

>>> from bigtree import ANSIPrintStyle
>>> for branch, stem, node in yield_tree(root, style=ANSIPrintStyle):
...     print(f"{branch}{stem}{node.node_name}")
a
|-- b
|   |-- d
|   `-- e
`-- c

Printing Attributes

>>> for branch, stem, node in yield_tree(root, style="const"):
...     print(f"{branch}{stem}{node.node_name} [age={node.age}]")
a [age=90]
โ”œโ”€โ”€ b [age=65]
โ”‚   โ”œโ”€โ”€ d [age=40]
โ”‚   โ””โ”€โ”€ e [age=35]
โ””โ”€โ”€ c [age=60]

Parameters:

Name Type Description Default
tree T

tree to print

required
node_name_or_path str | None

node to print from, becomes the root node of printing

None
max_depth int

maximum depth of tree to print, based on depth attribute

0
style str | Iterable[str] | BasePrintStyle

style of print

'const'

Returns:

Type Description
Iterable[tuple[str, str, T]]

Yields tree in format branch, stem, and node

tree_to_vis

tree_to_vis(
    tree,
    alias="node_name",
    plot_kwargs=None,
    custom_node_kwargs=None,
    node_kwargs=None,
    custom_edge_kwargs=None,
    edge_kwargs=None,
    network_kwargs=None,
    **kwargs
)

Export tree to pyvis for visualisations.

  • Able to have alias for node name if alias attribute is present, else it falls back to node_name, using alias
  • Able to control the spacing of nodes using plot_kwargs
  • Able to have generic node attributes using node_kwargs, and individualised node attributes using custom_node_kwargs
  • Able to have generic edge attributes using edge_kwargs, and individualised edge attributes using custom_edge_kwargs
  • Able to have generic network attributes using network_kwargs

Refer to pyvis documentation for more information.

Examples:

>>> from bigtree import Node, Tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree = Tree(root)
>>> net = tree.to_vis()

Export to visualisation (html) file, etc.

>>> net.save_graph("myvis.html")  # save only
>>> net.show_buttons(filter_=["physics"])
>>> net.prep_notebook()
>>> net.show("myvis.html")  # save and show
myvis.html
<IPython.lib.display.IFrame object at ...>

Parameters:

Name Type Description Default
tree T

tree to be exported

required
alias str

node attribute to use for node name in tree as alias to node_name

'node_name'
plot_kwargs dict[str, Any] | None

kwargs for reingold_tilford function to retrieve x, y coordinates

None
custom_node_kwargs dict[str, str] | None

mapping of pyvis Node kwarg to tree node attribute if present. This allows custom node attributes to be set. Possible keys include value (for node size), color (for node colour)

None
node_kwargs dict[str, Any] | None

kwargs for Node for all nodes, accepts keys: color etc.

None
custom_edge_kwargs dict[str, str] | None

mapping of pyvis Edge kwarg to tree node attribute if present. This allows custom edge attributes to be set. Possible keys include width (for edge weight)

None
edge_kwargs dict[str, Any] | None

kwargs for Edge for all edges, accept keys: weight etc.

None
network_kwargs dict[str, Any] | None

kwargs for Network, accepts keys: height, width, bgcolor, font_color, notebook, select_menu etc.

None

Returns:

Type Description
Network

pyvis object for display