๐จ 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 |
Generator (versatile) | yield_tree , hyield_tree , vyield_tree |
String | tree_to_newick |
Dictionary | tree_to_dict , tree_to_nested_dict |
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 |
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_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_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
|
T
|
tree to be exported |
required |
path_col
|
Optional[str]
|
column name for |
'path'
|
name_col
|
Optional[str]
|
column name for |
'name'
|
parent_col
|
Optional[str]
|
column name for |
None
|
attr_dict
|
Optional[Dict[str, str]]
|
node attributes mapped to column name, key: node attributes, value: corresponding column in dataframe |
None
|
all_attrs
|
bool
|
indicator whether to retrieve all |
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_to_polars
>>> 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_polars(root, 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.
>>> tree_to_polars(b, 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
|
Optional[str]
|
column name for |
'path'
|
name_col
|
Optional[str]
|
column name for |
'name'
|
parent_col
|
Optional[str]
|
column name for |
None
|
attr_dict
|
Optional[Dict[str, str]]
|
node attributes mapped to column name, key: node attributes, value: corresponding column in dataframe |
None
|
all_attrs
|
bool
|
indicator whether to retrieve all |
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_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
|
T
|
tree to be exported |
required |
name_key
|
Optional[str]
|
dictionary key for |
'name'
|
parent_key
|
Optional[str]
|
dictionary key for |
None
|
attr_dict
|
Optional[Dict[str, str]]
|
node attributes mapped to dictionary key, key: node attributes, value: corresponding dictionary key |
None
|
all_attrs
|
bool
|
indicator whether to retrieve all |
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_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
|
T
|
tree to be exported |
required |
name_key
|
str
|
dictionary key for |
'name'
|
child_key
|
str
|
dictionary key for list of children |
'children'
|
attr_dict
|
Optional[Dict[str, str]]
|
node attributes mapped to dictionary key, key: node attributes, value: corresponding dictionary key |
None
|
all_attrs
|
bool
|
indicator whether to retrieve all |
False
|
max_depth
|
int
|
maximum depth to export tree |
0
|
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dictionary containing tree information |
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_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.
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")
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")
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tree
|
Union[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
|
Optional[str]
|
background color of image |
None
|
node_colour
|
Optional[str]
|
fill colour of nodes |
None
|
node_shape
|
Optional[str]
|
shape of nodes. Possible node_shape include "circle", "square", "diamond", "triangle" |
None
|
edge_colour
|
Optional[str]
|
colour of edges |
None
|
node_attr
|
Callable[[T], Dict[str, Any]] | Optional[str]
|
If string type, it refers to |
None
|
edge_attr
|
Callable[[T], Dict[str, Any]] | Optional[str]
|
If string type, it refers to |
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-bottomBT
: bottom-to-topLR
: left-to-rightRL
: right-to-left
Possible line_shape
basis
bumpX
: used in LR or RL directionbumpY
cardinal
: undirectedcatmullRom
: undirectedlinear
:monotoneX
: used in LR or RL directionmonotoneY
natural
step
: used in LR or RL directionstepAfter
stepBefore
: used in LR or RL direction
Possible node_shape
rounded_edge
: rectangular with rounded edgesstadium
: (_) shape, rectangular with rounded endssubroutine
: ||_|| shape, rectangular with additional line at the endscylindrical
: database nodecircle
: circularasymmetric
: >_| shaperhombus
: decision nodehexagon
: <_> shapeparallelogram
: /_/ shapeparallelogram_alt
: \_\ shape, inverted parallelogramtrapezoid
: /_\ shapetrapezoid_alt
: \_/ shape, inverted trapezoiddouble_circle
Possible edge_arrow
normal
: directed arrow, shaded arrowheadbold
: bold directed arrowdotted
: dotted directed arrowopen
: line, undirected arrowbold_open
: bold linedotted_open
: dotted lineinvisible
: no linecircle
: directed arrow with filled circle arrowheadcross
: directed arrow with cross arrowheaddouble_normal
: bidirectional directed arrowdouble_circle
: bidirectional directed arrow with filled circle arrowheaddouble_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
```
Customise node shape, edge label, edge arrow, and custom node attributes
>>> graph = tree_to_mermaid(
... root,
... 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
|
Optional[str]
|
title |
None
|
theme
|
Optional[str]
|
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
|
Optional[str]
|
fill colour of nodes, can be colour name or hexcode |
None
|
node_border_colour
|
Optional[str]
|
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] | Optional[str]
|
If string type, it refers to |
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] | Optional[str]
|
If string type, it refers to |
None
|
edge_label
|
Optional[str]
|
|
None
|
node_attr
|
Callable[[T], str] | Optional[str]
|
If string type, it refers to |
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_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.
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
|
Optional[str]
|
file path of font family, requires .ttf file, defaults to DejaVuSans |
None
|
font_size
|
int
|
font size |
12
|
font_colour
|
Union[Tuple[int, int, int], str]
|
font colour, accepts tuple of RGB values or string |
'black'
|
bg_colour
|
Union[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_to_pillow_graph
>>> 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_graph(root, 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")
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tree
|
T
|
tree to be exported |
required |
node_content
|
str
|
display text in node |
'{node_name}'
|
margin
|
Optional[Dict[str, int]]
|
margin of diagram |
None
|
height_buffer
|
Union[int, float]
|
height buffer between node layers, in pixels |
20
|
width_buffer
|
Union[int, float]
|
width buffer between sibling nodes, in pixels |
10
|
font_family
|
Optional[str]
|
file path of font family, requires .ttf file, defaults to DejaVuSans |
None
|
font_size
|
int
|
font size |
12
|
font_colour
|
Union[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
|
Union[Tuple[int, int, int], str]
|
background of image, accepts tuple of RGB values or string |
'white'
|
rect_margin
|
Optional[Dict[str, int]]
|
(for rectangle) margin of text to rectangle, in pixels |
None
|
rect_fill
|
Union[Tuple[int, int, int], str, Colormap]
|
(for rectangle) colour to use for fill |
'white'
|
rect_cmap_attr
|
Optional[str]
|
(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
|
Union[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
Available Styles
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_or_path
|
Optional[str]
|
node to print from, becomes the root node of printing |
None
|
max_depth
|
int
|
maximum depth of tree to print, based on |
0
|
intermediate_node_name
|
bool
|
indicator if intermediate nodes have node names |
True
|
spacing
|
int
|
horizontal spacing between node displays |
0
|
style
|
Union[str, Iterable[str], BaseHPrintStyle]
|
style of print |
'const'
|
border_style
|
Optional[Union[str, Iterable[str], BorderStyle]]
|
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_or_path
|
Optional[str]
|
node to print from, becomes the root node of printing |
None
|
max_depth
|
int
|
maximum depth of tree to print, based on |
0
|
intermediate_node_name
|
bool
|
indicator if intermediate nodes have node names |
True
|
spacing
|
int
|
horizontal spacing between node displays |
0
|
style
|
Union[str, Iterable[str], BaseHPrintStyle]
|
style of print |
'const'
|
border_style
|
Optional[Union[str, Iterable[str], BorderStyle]]
|
style of border |
None
|
strip
|
bool
|
whether to strip results |
True
|
Returns:
Type | Description |
---|---|
List[str]
|
Yield tree in horizontal format |
print_tree
print_tree(
tree,
alias="node_name",
node_name_or_path=None,
max_depth=0,
all_attrs=False,
attr_list=None,
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
andattr_list
- 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
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 fromconstants.BasePrintStyle
Examples:
Printing tree
>>> from bigtree import Node, print_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)
>>> print_tree(root)
a
โโโ b
โ โโโ d
โ โโโ e
โโโ c
Printing alias
>>> print_tree(root, alias="alias")
alias-a
โโโ b
โ โโโ d
โ โโโ e
โโโ alias-c
Printing Sub-tree
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
Custom Styles
>>> from bigtree import ANSIPrintStyle
>>> print_tree(root, style=ANSIPrintStyle)
a
|-- b
| |-- d
| `-- e
`-- c
Printing to a file
>>> import io
>>> output = io.StringIO()
>>> print_tree(root, file=output)
>>> tree_string = output.getvalue()
>>> print(tree_string)
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_or_path
|
Optional[str]
|
node to print from, becomes the root node of printing |
None
|
max_depth
|
int
|
maximum depth of tree to print, based on |
0
|
all_attrs
|
bool
|
indicator to show all attributes, overrides |
False
|
attr_list
|
Optional[Iterable[str]]
|
node attributes to print |
None
|
attr_omit_null
|
bool
|
indicator whether to omit showing of null attributes |
False
|
attr_bracket
|
Collection[str]
|
open and close bracket for |
('[', ']')
|
style
|
Union[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, 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
|
Optional[str]
|
node length attribute to extract to beside name |
None
|
length_sep
|
Union[str, NewickCharacter]
|
separator between node name and length, used if length_attr is non-empty |
SEP
|
attr_list
|
Optional[Iterable[str]]
|
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
|
Union[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_or_path
|
Optional[str]
|
node to print from, becomes the root node of printing |
None
|
max_depth
|
int
|
maximum depth of tree to print, based on |
0
|
intermediate_node_name
|
bool
|
indicator if intermediate nodes have node names |
True
|
spacing
|
int
|
horizontal spacing between node displays |
2
|
style
|
Union[str, Iterable[str], BaseVPrintStyle]
|
style of print |
'const'
|
border_style
|
Optional[Union[str, Iterable[str], BorderStyle]]
|
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_or_path
|
Optional[str]
|
node to print from, becomes the root node of printing |
None
|
max_depth
|
int
|
maximum depth of tree to print, based on |
0
|
intermediate_node_name
|
bool
|
indicator if intermediate nodes have node names |
True
|
spacing
|
int
|
horizontal spacing between node displays |
2
|
style
|
Union[str, Iterable[str], BaseVPrintStyle]
|
style of print |
'const'
|
border_style
|
Optional[Union[str, Iterable[str], BorderStyle]]
|
style of border |
'const'
|
strip
|
bool
|
whether to strip results |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
Yield tree in vertical format |
yield_tree
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 fromconstants.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
|
Optional[str]
|
node to print from, becomes the root node of printing |
None
|
max_depth
|
int
|
maximum depth of tree to print, based on |
0
|
style
|
Union[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 usingcustom_node_kwargs
- Able to have generic edge attributes using
edge_kwargs
, and individualised edge attributes usingcustom_edge_kwargs
- Able to have generic network attributes using
network_kwargs
Refer to pyvis documentation for more information.
Examples:
>>> from bigtree import Node, tree_to_vis
>>> 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)
>>> net = tree_to_vis(root)
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'
|
plot_kwargs
|
Optional[Dict[str, Any]]
|
kwargs for reingold_tilford function to retrieve x, y coordinates |
None
|
custom_node_kwargs
|
Optional[Dict[str, str]]
|
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
|
Optional[Dict[str, Any]]
|
kwargs for Node for all nodes, accepts keys: color etc. |
None
|
custom_edge_kwargs
|
Optional[Dict[str, str]]
|
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
|
Optional[Dict[str, Any]]
|
kwargs for Edge for all edges, accept keys: weight etc. |
None
|
network_kwargs
|
Optional[Dict[str, Any]]
|
kwargs for Network, accepts keys: height, width, bgcolor, font_color, notebook, select_menu etc. |
None
|
Returns:
Type | Description |
---|---|
Network
|
pyvis object for display |