pythoncolorstreeetetoolkitete3

How to color leaves on `ete3` Tree? (Python 3)


I just started using ete3 and it is awesome.

How can I color the leaves of an ete3 Tree object using a color dictionary? I made "c":None because I don't want the of c to show up.

I want to have better control of the tree render but I can't figure out exactly how to do it.

I saw that there are NodeStyle objects but I think this is for the actual nodes. It looks like this TextFace object is what I need but I don't know how to use it. All the examples are adding labels.

# Build Tree
tree = ete3.Tree( "((a,b),c);" )
# Leaf mapping
D_leaf_color = {"a":"r", "b":"g","c":None}
# Set up style for circular tree
ts = ete3.TreeStyle()
ts.mode = "c"
# Draw Tree
tree.render("tree_test.png", dpi=300, w=500, tree_style=ts)

enter image description here

I looked at this question but it was pretty confusing: How to color tree nodes with fixed set of colors?


Solution

  • I would do it like this:

    from ete3 import Tree, TextFace, TreeStyle
    
    # Build Tree
    tree = Tree( "((a,b),c);" )
    # Leaf mapping
    D_leaf_color = {"a":"red", "b":"green"}
    for node in tree.traverse():
        # Hide node circles
        node.img_style['size'] = 0
        if node.is_leaf():
            color = D_leaf_color.get(node.name, None)
            if color:
                name_face = TextFace(node.name, fgcolor=color, fsize=10)
                node.add_face(name_face, column=0, position='branch-right')
    # Set up style for circular tree
    ts = TreeStyle()
    ts.mode = "c"
    ts.scale = 10
    # Disable the default tip names config
    ts.show_leaf_name = False
    ts.show_scale = False
    # Draw Tree
    tree.render("tree_test.png", dpi=300, w=500, tree_style=ts)
    

    enter image description here