0
# Tree Visualization
1
2
Comprehensive tree visualization system with customizable styles, faces, and layouts for creating publication-quality phylogenetic tree figures. ETE3's visual framework provides extensive control over tree appearance and annotations.
3
4
## Capabilities
5
6
### Core Visualization Classes
7
8
Main classes for tree visualization and styling.
9
10
```python { .api }
11
class TreeStyle:
12
"""
13
Global tree visualization style controlling overall appearance.
14
"""
15
16
def __init__(self):
17
"""Initialize tree style with default settings."""
18
19
# Global tree appearance properties
20
show_leaf_name: bool = True # Display leaf node names
21
show_branch_length: bool = False # Display branch lengths
22
show_branch_support: bool = False # Display support values
23
scale: float = None # Tree scale factor
24
branch_vertical_margin: float = 0 # Vertical space between branches
25
margin_left: float = 0 # Left margin
26
margin_right: float = 0 # Right margin
27
margin_top: float = 0 # Top margin
28
margin_bottom: float = 0 # Bottom margin
29
30
# Tree layout and orientation
31
mode: str = "r" # Drawing mode: "r" (rectangular), "c" (circular)
32
orientation: int = 0 # Orientation: 0, 90, 180, 270 degrees
33
arc_start: float = 0 # Start angle for circular trees (degrees)
34
arc_span: float = 360 # Angular span for circular trees (degrees)
35
rotation: float = 0 # Tree rotation angle
36
37
# Advanced layout options
38
optimal_scale_level: str = "mid" # Scale optimization level
39
force_topology: bool = False # Force topology-only layout
40
draw_guiding_lines: bool = False # Draw alignment guides
41
guiding_lines_type: int = 0 # Guide line style
42
guiding_lines_color: str = "gray" # Guide line color
43
complete_branch_lines_when_necessary: bool = True # Complete branch lines
44
45
class NodeStyle:
46
"""
47
Individual node visualization style.
48
"""
49
50
def __init__(self):
51
"""Initialize node style with default settings."""
52
53
# Node appearance
54
shape: str = "circle" # Node shape: "circle", "square", "sphere"
55
size: float = 3 # Node size in points
56
fgcolor: str = "black" # Foreground color
57
bgcolor: str = "transparent" # Background color
58
color: str = "black" # Alias for fgcolor
59
60
# Branch line styling
61
hz_line_color: str = "black" # Horizontal line color
62
vt_line_color: str = "black" # Vertical line color
63
hz_line_width: float = 1 # Horizontal line width
64
vt_line_width: float = 1 # Vertical line width
65
hz_line_type: int = 0 # Horizontal line type (0=solid, 1=dashed, 2=dotted)
66
vt_line_type: int = 0 # Vertical line type
67
68
# Node visibility and effects
69
draw_descendants: bool = True # Draw descendant branches
70
penwidth: float = 1 # Pen width for drawing
71
```
72
73
### Tree Display and Rendering
74
75
Display trees with customizable styles and export options.
76
77
```python { .api }
78
def show(self, tree_style=None, name=None):
79
"""
80
Display tree in interactive viewer.
81
82
Parameters:
83
- tree_style (TreeStyle): Global tree styling options
84
- name (str): Window name for display
85
"""
86
87
def render(self, file_name, w=None, h=None, units="px", tree_style=None, dpi=90):
88
"""
89
Render tree to image file.
90
91
Parameters:
92
- file_name (str): Output file path (supports PNG, PDF, SVG)
93
- w (int): Image width
94
- h (int): Image height
95
- units (str): Size units ("px", "mm", "in")
96
- tree_style (TreeStyle): Styling options
97
- dpi (int): Resolution for raster formats
98
99
Returns:
100
str: Path to rendered image file
101
"""
102
103
def get_ascii(self, show_internal=True, compact=False, attributes=None):
104
"""
105
Generate ASCII art representation of tree.
106
107
Parameters:
108
- show_internal (bool): Show internal node names
109
- compact (bool): Compact layout
110
- attributes (list): Node attributes to display
111
112
Returns:
113
str: ASCII tree representation
114
"""
115
```
116
117
### Face System for Annotations
118
119
Flexible annotation system using "faces" to add information to tree nodes.
120
121
```python { .api }
122
class Face:
123
"""Base class for all tree annotations."""
124
125
def __init__(self):
126
"""Initialize face with default properties."""
127
128
margin_left: float = 0
129
margin_right: float = 0
130
margin_top: float = 0
131
margin_bottom: float = 0
132
opacity: float = 1.0
133
rotation: float = 0
134
135
class TextFace(Face):
136
"""Text annotation face."""
137
138
def __init__(self, text, ftype="Verdana", fsize=10, fgcolor="black",
139
penwidth=0, fstyle="normal"):
140
"""
141
Create text face.
142
143
Parameters:
144
- text (str): Text content
145
- ftype (str): Font family
146
- fsize (int): Font size
147
- fgcolor (str): Text color
148
- penwidth (int): Text outline width
149
- fstyle (str): Font style ("normal", "bold", "italic")
150
"""
151
152
class AttrFace(TextFace):
153
"""Display node attribute as text."""
154
155
def __init__(self, attr, ftype="Verdana", fsize=10, fgcolor="black",
156
text_prefix="", text_suffix="", **kwargs):
157
"""
158
Create attribute display face.
159
160
Parameters:
161
- attr (str): Node attribute name to display
162
- text_prefix (str): Prefix text
163
- text_suffix (str): Suffix text
164
- Additional TextFace parameters
165
"""
166
167
class ImgFace(Face):
168
"""Image annotation face."""
169
170
def __init__(self, img_file, width=None, height=None, is_url=False):
171
"""
172
Create image face.
173
174
Parameters:
175
- img_file (str): Image file path or URL
176
- width (int): Image width in pixels
177
- height (int): Image height in pixels
178
- is_url (bool): Whether img_file is URL
179
"""
180
181
class CircleFace(Face):
182
"""Circle shape annotation."""
183
184
def __init__(self, radius, color, style="circle"):
185
"""
186
Create circle face.
187
188
Parameters:
189
- radius (float): Circle radius
190
- color (str): Fill color
191
- style (str): Shape style
192
"""
193
194
class RectFace(Face):
195
"""Rectangle shape annotation."""
196
197
def __init__(self, width, height, fgcolor="black", bgcolor="white",
198
label=None, label_size=10):
199
"""
200
Create rectangle face.
201
202
Parameters:
203
- width (float): Rectangle width
204
- height (float): Rectangle height
205
- fgcolor (str): Border color
206
- bgcolor (str): Fill color
207
- label (str): Optional text label
208
- label_size (int): Label font size
209
"""
210
```
211
212
### Advanced Face Types
213
214
Specialized faces for complex data visualization.
215
216
```python { .api }
217
class ProfileFace(Face):
218
"""Profile plot for numerical data."""
219
220
def __init__(self, max_v, min_v, center_v, width=200, height=40,
221
style="plot", colorscheme=None):
222
"""
223
Create profile plot face.
224
225
Parameters:
226
- max_v (float): Maximum value
227
- min_v (float): Minimum value
228
- center_v (float): Center value
229
- width (int): Plot width
230
- height (int): Plot height
231
- style (str): Plot style ("plot", "heatmap", "cbars")
232
- colorscheme (dict): Color mapping
233
"""
234
235
class SequenceFace(Face):
236
"""Sequence alignment visualization."""
237
238
def __init__(self, seq, seqtype="aa", fsize=10, codon=None):
239
"""
240
Create sequence face.
241
242
Parameters:
243
- seq (str): Sequence string
244
- seqtype (str): Sequence type ("aa", "nt")
245
- fsize (int): Font size
246
- codon (str): Codon table for translation
247
"""
248
249
class TreeFace(Face):
250
"""Embedded tree visualization."""
251
252
def __init__(self, tree, tree_style=None):
253
"""
254
Create embedded tree face.
255
256
Parameters:
257
- tree (Tree): Tree to embed
258
- tree_style (TreeStyle): Style for embedded tree
259
"""
260
261
class BarChartFace(Face):
262
"""Bar chart annotation."""
263
264
def __init__(self, values, width=200, height=100, colors=None,
265
labels=None, min_value=None, max_value=None):
266
"""
267
Create bar chart face.
268
269
Parameters:
270
- values (list): Data values
271
- width (int): Chart width
272
- height (int): Chart height
273
- colors (list): Bar colors
274
- labels (list): Value labels
275
- min_value (float): Minimum scale value
276
- max_value (float): Maximum scale value
277
"""
278
279
class PieChartFace(Face):
280
"""Pie chart annotation."""
281
282
def __init__(self, percents, width=100, height=100, colors=None, labels=None):
283
"""
284
Create pie chart face.
285
286
Parameters:
287
- percents (list): Percentage values (must sum to 100)
288
- width (int): Chart width
289
- height (int): Chart height
290
- colors (list): Slice colors
291
- labels (list): Slice labels
292
"""
293
```
294
295
### Face Positioning and Layout
296
297
Control where faces are displayed relative to tree nodes.
298
299
```python { .api }
300
def add_face(self, face, column, position="branch-right"):
301
"""
302
Add face to node at specified position.
303
304
Parameters:
305
- face (Face): Face object to add
306
- column (int): Column position (0, 1, 2, ...)
307
- position (str): Face position relative to node
308
"branch-top": Above the branch
309
"branch-bottom": Below the branch
310
"branch-right": Right of the branch (default)
311
"float": Floating position
312
"aligned": Aligned with other faces
313
"""
314
315
# Pre-defined face positions
316
FACE_POSITIONS = ["branch-top", "branch-bottom", "branch-right", "float", "aligned"]
317
```
318
319
### Color and Style Utilities
320
321
Color definitions and style utilities for visualization.
322
323
```python { .api }
324
# SVG color constants (from svg_colors module)
325
SVG_COLORS = {
326
"aliceblue": "#F0F8FF",
327
"antiquewhite": "#FAEBD7",
328
"aqua": "#00FFFF",
329
# ... (extensive color dictionary)
330
"yellow": "#FFFF00",
331
"yellowgreen": "#9ACD32"
332
}
333
334
def random_color(h=None, s=None, v=None):
335
"""
336
Generate random color in HSV space.
337
338
Parameters:
339
- h (float): Hue (0-1, None for random)
340
- s (float): Saturation (0-1, None for random)
341
- v (float): Value/brightness (0-1, None for random)
342
343
Returns:
344
str: Hex color string
345
"""
346
```
347
348
### Layout Functions
349
350
Pre-defined layout functions for common visualization patterns.
351
352
```python { .api }
353
def apply_layout_function(tree, layout_fn, *args, **kwargs):
354
"""
355
Apply layout function to tree.
356
357
Parameters:
358
- tree (Tree): Target tree
359
- layout_fn (function): Layout function to apply
360
- args, kwargs: Arguments for layout function
361
"""
362
363
# Common layout functions in layouts module
364
def basic_layout(node):
365
"""Basic node styling with names and branch lengths."""
366
367
def phylogeny_layout(node):
368
"""Phylogenetic tree layout with species information."""
369
370
def evol_layout(node):
371
"""Evolutionary analysis layout with model information."""
372
```
373
374
## Usage Examples
375
376
### Basic Tree Visualization
377
378
```python
379
from ete3 import Tree, TreeStyle, NodeStyle
380
381
# Create and display tree
382
tree = Tree("(A:1,(B:1,(E:1,D:1):0.5):0.5);")
383
384
# Show with default style
385
tree.show()
386
387
# Custom tree style
388
ts = TreeStyle()
389
ts.show_leaf_name = True
390
ts.show_branch_length = True
391
ts.show_branch_support = False
392
ts.scale = 120
393
394
tree.show(tree_style=ts)
395
```
396
397
### Node Styling
398
399
```python
400
from ete3 import Tree, NodeStyle
401
402
tree = Tree("(A:1,(B:1,(E:1,D:1):0.5):0.5);")
403
404
# Style specific nodes
405
for node in tree.traverse():
406
if node.is_leaf():
407
# Style leaf nodes
408
nstyle = NodeStyle()
409
nstyle.shape = "circle"
410
nstyle.size = 10
411
nstyle.fgcolor = "red"
412
node.set_style(nstyle)
413
else:
414
# Style internal nodes
415
nstyle = NodeStyle()
416
nstyle.shape = "square"
417
nstyle.size = 5
418
nstyle.fgcolor = "blue"
419
node.set_style(nstyle)
420
421
tree.show()
422
```
423
424
### Adding Face Annotations
425
426
```python
427
from ete3 import Tree, TextFace, AttrFace, CircleFace
428
429
tree = Tree("(A:1,(B:1,(E:1,D:1):0.5):0.5);")
430
431
# Add text annotations
432
for node in tree.traverse():
433
if node.is_leaf():
434
# Add custom text
435
text_face = TextFace(f"Leaf: {node.name}", fsize=12, fgcolor="green")
436
node.add_face(text_face, column=0, position="branch-right")
437
438
# Add attribute display
439
dist_face = AttrFace("dist", fsize=10, fgcolor="blue", text_prefix="d=")
440
node.add_face(dist_face, column=1, position="branch-right")
441
442
# Add shape annotation
443
circle_face = CircleFace(radius=5, color="red")
444
node.add_face(circle_face, column=2, position="branch-right")
445
446
tree.show()
447
```
448
449
### Advanced Visualization
450
451
```python
452
from ete3 import Tree, TreeStyle, ProfileFace, BarChartFace
453
import random
454
455
tree = Tree("(A:1,(B:1,(E:1,D:1):0.5):0.5);")
456
457
# Add profile data to nodes
458
for node in tree.traverse():
459
# Generate random profile data
460
profile_data = [random.random() for _ in range(50)]
461
profile_face = ProfileFace(
462
max_v=max(profile_data),
463
min_v=min(profile_data),
464
center_v=sum(profile_data)/len(profile_data),
465
width=200,
466
height=40
467
)
468
node.add_face(profile_face, column=0, position="aligned")
469
470
# Add bar chart for leaves
471
if node.is_leaf():
472
values = [random.randint(1, 100) for _ in range(3)]
473
bar_face = BarChartFace(
474
values=values,
475
width=100,
476
height=50,
477
colors=["red", "green", "blue"],
478
labels=["A", "B", "C"]
479
)
480
node.add_face(bar_face, column=1, position="aligned")
481
482
# Custom tree style for alignment
483
ts = TreeStyle()
484
ts.show_leaf_name = False
485
ts.draw_guiding_lines = True
486
ts.guiding_lines_color = "gray"
487
488
tree.show(tree_style=ts)
489
```
490
491
### Exporting Visualizations
492
493
```python
494
from ete3 import Tree, TreeStyle
495
496
tree = Tree("(A:1,(B:1,(E:1,D:1):0.5):0.5);")
497
498
# Setup visualization
499
ts = TreeStyle()
500
ts.show_leaf_name = True
501
ts.show_branch_length = True
502
503
# Export to different formats
504
tree.render("tree.png", tree_style=ts, dpi=300)
505
tree.render("tree.pdf", tree_style=ts, w=200, h=150, units="mm")
506
tree.render("tree.svg", tree_style=ts)
507
508
# ASCII output
509
ascii_tree = tree.get_ascii(show_internal=True, compact=False)
510
print(ascii_tree)
511
```
512
513
### Circular and Rotated Trees
514
515
```python
516
from ete3 import Tree, TreeStyle
517
518
tree = Tree("(A:1,(B:1,(E:1,D:1):0.5):0.5);")
519
520
# Circular tree
521
ts_circular = TreeStyle()
522
ts_circular.mode = "c" # Circular mode
523
ts_circular.arc_start = 0
524
ts_circular.arc_span = 270
525
tree.show(tree_style=ts_circular)
526
527
# Rotated rectangular tree
528
ts_rotated = TreeStyle()
529
ts_rotated.rotation = 90
530
ts_rotated.orientation = 1
531
tree.show(tree_style=ts_rotated)
532
```