Skip to content

πŸ”¨ Export

Tree Export Methods

Export Tree to list, dictionary, and pandas DataFrame.

Export Tree to Method
Command Line / Others print_tree, yield_tree, hprint_tree, hyield_tree
String tree_to_newick
Dictionary tree_to_dict, tree_to_nested_dict
DataFrame tree_to_dataframe
Dot (for .dot, .png, .svg, .jpeg, etc.) tree_to_dot
Pillow (for .png, .jpg, .jpeg, etc.) tree_to_mermaid
Mermaid Markdown (for .md) tree_to_mermaid

Tree Export Customizations

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 with max_depth No, but can specify subtree No Tree style
yield_tree No, returns node Yes with max_depth No, but can specify subtree No Tree style
tree_to_newick Yes with attr_list No No No Length separator and attribute prefix and separator
tree_to_dict Yes with attr_dict or all_attrs Yes with max_depth Yes with skip_depth Yes with leaf_only Dict key for parent
tree_to_nested_dict Yes with attr_dict or all_attrs Yes with max_depth No No Dict key for node name and node children
tree_to_dataframe Yes with attr_dict or all_attrs Yes with max_depth Yes with skip_depth 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 No Yes, using keyword arguments similar to yield_tree No No Font (family, size, colour), background colour, etc.
tree_to_mermaid No Yes, using keyword arguments similar to yield_tree No No Node shape, node fill, edge arrow, edge label etc.

bigtree.tree.export

print_tree

print_tree(
    tree,
    node_name_or_path="",
    max_depth=0,
    all_attrs=False,
    attr_list=[],
    attr_omit_null=False,
    attr_bracket=["[", "]"],
    style="const",
    custom_style=[],
)

Print tree to console, starting from tree.

  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customize for maximum depth to print, using max_depth
  • Able to choose which attributes to show or show all attributes, using attr_name_filter and all_attrs
  • Able to omit showing of attributes if it is null, using attr_omit_null
  • Able to customize open and close brackets if attributes are shown, using attr_bracket
  • Able to customize style, to choose from ansi, ascii, const, const_bold, rounded, double, and custom style - Default style is const style - If style is set to custom, user can choose their own style for stem, branch and final stem icons - Stem, branch, and final stem symbol should have the same number of characters

Examples:

Printing tree

>>> from bigtree import Node, print_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)
>>> print_tree(root)
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   └── e
└── c

Printing Sub-tree

>>> print_tree(root, node_name_or_path="b")
b
β”œβ”€β”€ d
└── e
>>> print_tree(root, max_depth=2)
a
β”œβ”€β”€ b
└── c

Printing Attributes

>>> print_tree(root, attr_list=["age"])
a [age=90]
β”œβ”€β”€ b [age=65]
β”‚   β”œβ”€β”€ d [age=40]
β”‚   └── e [age=35]
└── c [age=60]
>>> print_tree(root, attr_list=["age"], attr_bracket=["*(", ")"])
a *(age=90)
β”œβ”€β”€ b *(age=65)
β”‚   β”œβ”€β”€ d *(age=40)
β”‚   └── e *(age=35)
└── c *(age=60)

Available Styles

>>> print_tree(root, style="ansi")
a
|-- b
|   |-- d
|   `-- e
`-- c
>>> print_tree(root, style="ascii")
a
|-- b
|   |-- d
|   +-- e
+-- c
>>> print_tree(root, style="const")
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   └── e
└── c
>>> print_tree(root, style="const_bold")
a
┣━━ b
┃   ┣━━ d
┃   ┗━━ e
┗━━ c
>>> print_tree(root, style="rounded")
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   ╰── e
╰── c
>>> print_tree(root, style="double")
a
╠══ b
β•‘   ╠══ d
β•‘   β•šβ•β• e
β•šβ•β• c

Parameters:

Name Type Description Default
tree Node

tree to print

required
node_name_or_path str

node to print from, becomes the root node of printing

''
max_depth int

maximum depth of tree to print, based on depth attribute, optional

0
all_attrs bool

indicator to show all attributes, defaults to False, overrides attr_list and attr_omit_null

False
attr_list Iterable[str]

list of node attributes to print, optional

[]
attr_omit_null bool

indicator whether to omit showing of null attributes, defaults to False

False
attr_bracket List[str]

open and close bracket for all_attrs or attr_list

['[', ']']
style str

style of print, defaults to const style

'const'
custom_style Iterable[str]

style of stem, branch and final stem, used when style is set to 'custom'

[]

yield_tree

yield_tree(
    tree,
    node_name_or_path="",
    max_depth=0,
    style="const",
    custom_style=[],
)

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 customize for maximum depth to print, using max_depth
  • Able to customize style, to choose from ansi, ascii, const, const_bold, rounded, double, and custom style - Default style is const style - If style is set to custom, user can choose their own style for stem, branch and final stem icons - Stem, branch, and final stem symbol should have the same number of characters

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

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 Node

tree to print

required
node_name_or_path str

node to print from, becomes the root node of printing, optional

''
max_depth int

maximum depth of tree to print, based on depth attribute, optional

0
style str

style of print, defaults to const

'const'
custom_style Iterable[str]

style of stem, branch and final stem, used when style is set to 'custom'

[]

hprint_tree

hprint_tree(
    tree,
    node_name_or_path="",
    max_depth=0,
    intermediate_node_name=True,
    style="const",
    custom_style=[],
)

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

  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customize for maximum depth to print, using max_depth
  • Able to customize style, to choose from ansi, ascii, const, const_bold, rounded, double, and custom style - Default style is const style - If style is set to custom, user can choose their own style icons - Style icons should have the same number of characters

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

Parameters:

Name Type Description Default
tree Node

tree to print

required
node_name_or_path str

node to print from, becomes the root node of printing

''
max_depth int

maximum depth of tree to print, based on depth attribute, optional

0
intermediate_node_name bool

indicator if intermediate nodes have node names, defaults to True

True
style str

style of print, defaults to const style

'const'
custom_style Iterable[str]

style of icons, used when style is set to 'custom'

[]

hyield_tree

hyield_tree(
    tree,
    node_name_or_path="",
    max_depth=0,
    intermediate_node_name=True,
    style="const",
    custom_style=[],
)

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

  • Able to select which node to print from, resulting in a subtree, using node_name_or_path
  • Able to customize for maximum depth to print, using max_depth
  • Able to customize style, to choose from ansi, ascii, const, const_bold, rounded, double, and custom style - Default style is const style - If style is set to custom, user can choose their own style icons - Style icons should have the same number of characters

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

>>> 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

Parameters:

Name Type Description Default
tree Node

tree to print

required
node_name_or_path str

node to print from, becomes the root node of printing

''
max_depth int

maximum depth of tree to print, based on depth attribute, optional

0
intermediate_node_name bool

indicator if intermediate nodes have node names, defaults to True

True
style str

style of print, defaults to const style

'const'
custom_style Iterable[str]

style of icons, used when style is set to 'custom'

[]

Returns:

Type Description
List[str]

(List[str])

tree_to_newick

tree_to_newick(
    tree,
    intermediate_node_name=True,
    length_attr="",
    length_sep=NewickCharacter.SEP,
    attr_list=[],
    attr_prefix="&&NHX:",
    attr_sep=NewickCharacter.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 tree, 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].

Customizations include
  • Omitting names of root and intermediate nodes, default all node names are shown.
  • Changing length separator to other symbol, default is :.
  • Adding an attribute prefix, default is &&NHX:.
  • Changing the attribute separator to other 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 Node

tree to be exported

required
intermediate_node_name bool

indicator if intermediate nodes have node names, defaults to True

True
length_attr str

node length attribute to extract to beside name, optional

''
length_sep str

separator between node name and length, used if length_attr is non-empty, defaults to ":"

SEP
attr_list Iterable[str]

list of node attributes to extract into square bracket, optional

[]
attr_prefix str

prefix before all attributes, within square bracket, used if attr_list is non-empty, defaults to "&&NHX:"

'&&NHX:'
attr_sep str

separator between attributes, within square brackets, used if attr_list is non-empty, defaults to ":"

SEP

Returns:

Type Description
str

(str)

tree_to_dict

tree_to_dict(
    tree,
    name_key="name",
    parent_key="",
    attr_dict={},
    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_to_dict
>>> 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_to_dict(root, 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

>>> tree_to_dict(c, 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 Node

tree to be exported

required
name_key str

dictionary key for node.node_name, defaults to 'name'

'name'
parent_key str

dictionary key for node.parent.node_name, optional

''
attr_dict Dict[str, str]

dictionary mapping node attributes to dictionary key, key: node attributes, value: corresponding dictionary key, optional

{}
all_attrs bool

indicator whether to retrieve all Node attributes, overrides attr_dict, defaults to False

False
max_depth int

maximum depth to export tree, optional

0
skip_depth int

number of initial depths to skip, optional

0
leaf_only bool

indicator to retrieve only information from leaf nodes

False

Returns:

Type Description
Dict[str, Any]

(Dict[str, Any])

tree_to_nested_dict

tree_to_nested_dict(
    tree,
    name_key="name",
    child_key="children",
    attr_dict={},
    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_to_nested_dict
>>> 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_to_nested_dict(root, 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 Node

tree to be exported

required
name_key str

dictionary key for node.node_name, defaults to 'name'

'name'
child_key str

dictionary key for list of children, optional

'children'
attr_dict Dict[str, str]

dictionary mapping node attributes to dictionary key, key: node attributes, value: corresponding dictionary key, optional

{}
all_attrs bool

indicator whether to retrieve all Node attributes, overrides attr_dict, defaults to False

False
max_depth int

maximum depth to export tree, optional

0

Returns:

Type Description
Dict[str, Any]

(Dict[str, Any])

tree_to_dataframe

tree_to_dataframe(
    tree,
    path_col="path",
    name_col="name",
    parent_col="",
    attr_dict={},
    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_to_dataframe
>>> 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_to_dataframe(root, 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.

>>> tree_to_dataframe(b, 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 Node

tree to be exported

required
path_col str

column name for node.path_name, defaults to 'path'

'path'
name_col str

column name for node.node_name, defaults to 'name'

'name'
parent_col str

column name for node.parent.node_name, optional

''
attr_dict Dict[str, str]

dictionary mapping node attributes to column name, key: node attributes, value: corresponding column in dataframe, optional

{}
all_attrs bool

indicator whether to retrieve all Node attributes, overrides attr_dict, defaults to False

False
max_depth int

maximum depth to export tree, optional

0
skip_depth int

number of initial depths to skip, optional

0
leaf_only bool

indicator to retrieve only information from leaf nodes

False

Returns:

Type Description
DataFrame

(pd.DataFrame)

tree_to_dot

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

Export tree or list of trees to image. Possible node attributes include style, fillcolor, shape.

Examples:

>>> from bigtree import Node, tree_to_dot
>>> 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)
>>> 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/docstr/tree.png")
>>> graph.write_dot("assets/docstr/tree.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)
>>> graph = tree_to_dot(root, 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)
>>> graph = tree_to_dot(root, 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 Node / List[Node]

tree or list of trees to be exported

required
directed bool

indicator whether graph should be directed or undirected, defaults to True

True
rankdir str

layout direction, defaults to 'TB' (top to bottom), can be 'BT' (bottom to top), 'LR' (left to right), 'RL' (right to left)

'TB'
bg_colour str

background color of image, defaults to None

''
node_colour str

fill colour of nodes, defaults to None

''
node_shape str

shape of nodes, defaults to None Possible node_shape include "circle", "square", "diamond", "triangle"

''
edge_colour str

colour of edges, defaults to None

''
node_attr str | Callable

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 and defaults to None. Possible node styles include {"style": "filled", "fillcolor": "gold", "shape": "diamond"}

''
edge_attr str | Callable

If stirng 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, and defaults to None. Possible edge styles include {"style": "bold", "label": "edge label", "color": "black"}

''

Returns:

Type Description
Dot

(pydot.Dot)

tree_to_pillow

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

Export tree to image (JPG, PNG). Image will be similar format as print_tree, accepts additional keyword arguments as input to yield_tree.

Examples:

>>> from bigtree import Node, tree_to_pillow
>>> 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)
>>> pillow_image = tree_to_pillow(root)

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

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

Parameters:

Name Type Description Default
tree Node

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), defaults to (10, 10)

(10, 10)
font_family str

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

''
font_size int

font size, defaults to 12

12
font_colour Union[Tuple[int, int, int], str]

font colour, accepts tuple of RGB values or string, defaults to black

'black'
bg_colour Union[Tuple[int, int, int], str]

background of image, accepts tuple of RGB values or string, defaults to white

'white'

Returns:

Type Description
Image

(PIL.Image.Image)

tree_to_mermaid

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

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

Parameters for customizations that applies to entire flowchart include
  • Title, title
  • 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 customizations that apply to customized 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 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_to_mermaid
>>> 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)
>>> graph = tree_to_mermaid(root)
>>> 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
```

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

>>> graph = tree_to_mermaid(root, node_shape_attr="node_shape", edge_label="edge_label", edge_arrow_attr="edge_arrow", node_attr="node_style")
>>> print(graph)
```mermaid
%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%
flowchart TB
0{"a"} ==>|Child 1| 0-0("b")
0-0:::class0-0-0 --> 0-0-0("d")
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 Node

tree to be exported

required
title str

title, defaults to None

''
rankdir str

layout direction, defaults to 'TB' (top to bottom), can be 'BT' (bottom to top), 'LR' (left to right), 'RL' (right to left)

'TB'
line_shape str

line shape or curvature, defaults to 'basis'

'basis'
node_colour str

fill colour of nodes, can be colour name or hexcode, defaults to None

''
node_border_colour str

border colour of nodes, can be colour name or hexcode, defaults to None

''
node_border_width float

width of node border, defaults to 1

1
node_shape str

node shape, sets the shape of every node, defaults to 'rounded_edge'

'rounded_edge'
node_shape_attr str | Callable

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, defaults to None

''
edge_arrow str

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

'normal'
edge_arrow_attr str | Callable

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, defaults to None

''
edge_label str

Node attribute for edge label from parent to itself, defaults to None

''
node_attr str | Callable

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, defaults to None

''

Returns:

Type Description
str

(str)