Random trees

There are some simple tools in toytree, based on functions in ete3, that can be used to generate random trees which can be useful for exploring data and plotting methods.


In [1]:
import toytree
import toyplot
import numpy as np

In [3]:
## create a random tree with N tips
tre = toytree.rtree.coaltree(24)

In [5]:
## assign random edge lengths and supports to each node
for node in tre.treenode.traverse():
    node.dist = np.random.exponential(1)
    node.support = int(np.random.uniform(50, 100))

Color-mapping


In [6]:
## make a colormap
colormap = toyplot.color.brewer.map(name="Spectral", domain_min=0, domain_max=100)

In [7]:
## get node support values in plot order 
vals = np.array(tre.get_node_values("support", show_root=1, show_tips=1))
vals


Out[7]:
array([85, 52, 93, 63, 52, 66, 98, 87, 99, 95, 94, 89, 81, 60, 68, 89, 89,
       71, 80, 67, 97, 65, 96, 76, 82, 94, 83, 98, 65, 67, 75, 98, 89, 63,
       63, 75, 86, 95, 71, 55, 59, 58, 55, 73, 68, 75, 62])

In [16]:
## get colors mapped to values
colors = toyplot.color.broadcast((vals, colormap), shape=vals.shape)
colors = [toyplot.color.to_css(i) for i in colors]

Show nodes but not values (text)

Use None as the argument to get_node_values(). This allows you to still toggle whether you want the root and tip nodes to show with the following arguments to get_node_values. This argument would commonly be used if you wanted to set different node sizes or colors to represent values instead of having text show at nodes.


In [18]:
tre.draw(
    height=400, width=300,
    node_labels=tre.get_node_values(None, show_root=True, show_tips=False),
    node_colors=colors,
    node_sizes=10,
    node_style={"stroke": "black"},
    tip_labels_align=True,
    );


r0r1r2r3r4r5r6r7r8r9r10r11r12r13r14r15r16r17r18r19r20r21r22r23

Show nodes and node values

Similar to above except now enter the name of a real node "feature" into the get_node_values functions. This will return the values of the feature in node plotting order. The features "support", "dist", "name", "height", and "idx" are always available. Additional features can be added to nodes.


In [20]:
tre.draw(
    height=400, width=350,
    node_labels=tre.get_node_values("support", False, False),
    node_colors=colors,
    node_sizes=15,
    node_style={"stroke": "black"},
    use_edge_lengths=False,
    );


r0r1r2r3r4r5r6r7r8r9r10r11r12r13r14r15r16r17r18r19r20r21r22r2396659767807189896860818994959987986652639352

Show node values but not the nodes themselves


In [21]:
tre.draw(
    height=400, width=350,
    use_edge_lengths=False,
    node_labels=tre.get_node_values("support", False, False),
    node_colors=colors,
    node_sizes=0,
    node_style={"stroke": "black"},
    node_labels_style={
        "baseline-shift": "8px", 
        "-toyplot-anchor-shift": "-15px",
        "font-size": "10px"},
    );


r0r1r2r3r4r5r6r7r8r9r10r11r12r13r14r15r16r17r18r19r20r21r22r2396659767807189896860818994959987986652639352