topiary.draw

Interface for drawing phylogenetic trees and ancestor summaries.

topiary.draw.ancestor_data

Create a summary plot for an ancestor.

topiary.draw.ancestor_data.plot_ancestor_data(df_anc, alt_anc_pp=0.25, width_ratio=5, anc_name=None, anc_data_string=None, close_plot=False)

Create a summary plot for an ancestor.

Parameters:
  • df_anc (pandas.DataFrame) – ancestral data frame

  • alt_anc_pp (float, default=0.25) – cutoff (inclusive) for identifying plausible alternate states

  • width_ratio (float, default=5) – width ratio for plot

  • anc_name (str, optional) – name of ancestor (title on graph and output file {anc_name}.pdf)

  • anc_data_string (str, optional) – data to dump in subtitle

  • close_plot (bool, False) – whether or not to close plot when complete

Returns:

  • fig (matplotlib.Figure) – matplotlib figure instance

  • axes (numpy.array) – array of matplotlib axes (0 is main plot; 1 is histogram)

topiary.draw.core

Functions and classes for plotting toytree trees.

topiary.draw.core.color_to_css(color)

Take a color (as hex string, rgb tuple, rgba tuple, named color, or toyplot css) and return toyplot css.

topiary.draw.core.construct_colormap(color, prop, prop_span=None, palette=None)

Construct a toyplot color map. If value_min == value_max, the cmap will always return color_min.

Parameters:
  • color (str or tuple or dict) – set node color. If a single value, color all nodes that color. If list-like and length 2, treat as colors for minimum and maximum of a color gradient. If dict, map property keys to color values. Colors can be RGBA tuples, named colors, or hexadecimal strings. See the toyplot documentation for allowed values.

  • prop (list-like) – values of properties over which to make the color map

  • prop_span (tuple, optional) – set min/max values for property color/size calculation. First element is min, second is max. Only applicable if color and size are set to be gradients.

  • palette (toyplot.color.Palette, optional) – custom toyplot palette. if specified, use this palette rather than color to define color scheme for a color gradient. requires the property value be a float.

Returns:

  • colormap (toyplot.LinearMap) – toyplot linear colormap

  • span (list) – list of values corresponding to span. For continuous map, will be [min,max]; for discrete map will be values for each color

topiary.draw.core.construct_sizemap(size, prop, prop_span=None)

Construct a sizemap function that gives size given a property value.

Parameters:
  • size (float or tuple or dict, optional) – set node size. If a single value, make all nodes that size. If list-like and length 2, treat as sizes for minimum and maximum of a size gradient. If dict, map property keys to size values. Sizes must be float >= 0.

  • prop (list-like) – values of properties over which to make the color map

  • prop_span (tuple, optional) – set min/max values for property color/size calculation. First element is min, second is max. Only applicable if color and size are set to be gradients.

Returns:

sm – function that yields a size given the property

Return type:

function

topiary.draw.core.create_name_dict(df, tip_columns=None, separator='|', disambiguate=True)

Create a dictionary mapping between uid and pretty names extracted from tip_columns in the dataframe.

Parameters:
  • df (pandas.DataFrame) – topiary dataframe

  • tip_columns (list, optional) – columns in dataframe to use to create human-readable names for tips on tree. For example, tip_columns = ["species","nickname"] would give names like "Homo sapiens|LY96". If None, try ["species","recip_paralog"], then :code:`["species","nickname"], then ["species",f"{name[:10]}..."].

  • separator (str) – separator to use between pretty names. Cannot be “#,;:’”)(” as these are used in newick format.

  • disambiguate (bool, default=True) – if two tip labels will be the same (for example, two labels will be “Homo sapiens|LY96”), append the uid to those labels so they can be uniquely identified.

Returns:

name_dict – dict mapping between uid and pretty name

Return type:

dict

topiary.draw.core.ete3_to_toytree(T)

Generate a toytree.tree instance from an ete3.Tree instance. Copies over branch lengths, labels, and features.

Parameters:

T (ete3.Tree) – ete3.Tree to be converted

Returns:

tT – converted toytree.tree

Return type:

toytree.tree

topiary.draw.core.get_round_to(value, total_requested=2)

Figure out a natural place to round a float for creating useful but pretty strings.

Parameters:
  • value (float) – value to round

  • total_requested (int, default=3) – target number of digits for rounding. If value is 1234.23 and total_requested is 3, this would round to 1234. If total_requested is 5, this would give 1234.23.

Returns:

round_to – what number to round value to prior to string conversion

Return type:

int

topiary.draw.core.parse_position_string(position, x_offset, y_offset)

Get displacement in x and y for label placement. Displacement will be in tree coordinates.

Parameters:
  • position (str) – Allowed values are “top-left”, “top”, “top-right”, “right”, “bottom-right”, “bottom”, “bottom-left”, and “left”.

  • x_offset (float) – how far to move in x

  • t_offset (float) – how far to move in t

  • Returns

  • dx (float) – displacement in x

  • dy (float) – displacement in y

topiary.draw.core.parse_span_color(span_color, color)

Decide how to treat span_color (bs_color or pp_color), returning output that can feed into PrettyTree.draw_nodes().

Parameters:
  • span_color – putative bs_color or pp_color dictionary passed in by user

  • color – putative color passed in by user

Returns:

  • plot_nodes (bool) – whether or not we’re plotting support nodes

  • value_span (list or None) – top and bottom values for color map

  • color_span (list or None) – top and bottom colors for color map. if “color” is specified, just return this.

topiary.draw.prettytree

Class for drawing formatted phylogenetic trees using toytree.

class topiary.draw.prettytree.PrettyTree(T, name_dict=None, font_size=15, stroke_width=2, vertical_pixels_per_tip=20, aspect_ratio_parameters=(0.02, 0.47), min_height=300, height=None, width=None, padding=None, edge_style=None, tip_labels_style=None, draw_debug_points=False, **kwargs)

Bases: object

Class for drawing formatted phylogenetic trees using toytree.

Parameters:
  • T (ete3.Tree or dp.Tree or toytree.tree or newick) – tree to draw. We strongly recommend this tree have uid as its tip labels to avoid mangled trees. If you want to assign prettier names to the tips, pass in name_dict.

  • name_dict (dict, optional) – dictionary mapping strings in node.name to more useful names.

  • font_size (float, default=15) – font size (pixels)

  • stroke_width (float, default=2) – width of lines drawing tree (pixels)

  • vertical_pixels_per_tip (float, default=20) – number of pixels to assign to each tip when calculating figure height

  • aspect_ratio_parameters (tuple, default=(0.02,0.47)) – these parameters used to relate figure aspect ratio to number of taxa by the following equation: aspect_ratio_parameters[0]*num_taxa + aspect_ratio_parameters[1]

  • min_height (float, default=300) – minimum height for figure (pixels)

  • height (float, optional) – height in pixels. If specified, overrides vertical_pixels_per_tip, aspect_ratio_parameters, and min_height.

  • width (float, optional) – width in pixels. if specified, overrides aspect_ratio_parameters

  • padding (float, optional) – padding in pixels.

  • edge_style (dict, optional) – dictionary of css key/value pairs defining how the tree edge style is drawn

  • draw_debug_points (bool, default=False) – draw points on the plot that validate relative x-scale of two plot areas.

  • **kwargs (dict) – pass any other keyword arguments directly to toytree.tree.draw.

as_html()

Render the tree as an html string.

Returns:

html – tree as an html string

Return type:

str

property canvas

toyplot canvas holding tree.

property default_size

Default size for nodes.

draw_node_labels(property_labels, fmt_string=None, position='right', position_offset=None, plot_ancestors=True, plot_leaves=False, plot_root=True, text_style=None)

Draw labels on nodes on tree.

Parameters:
  • property_labels (str or list-like) – write values in property_labels to the node labels. if str, treat as a single property_label; if list-like, use each of the list entries as an individual property_label.

  • fmt_string (str, optional) –

    format for labels. If not specified, spit out as {},{},… for each property_label entry. If specified, must have one of two formats.

    • exactly the same number of unnamed fields as (i.e. “{}”) as the number of properties. For example, "{}|{}" for property_labels = ["label_a","label_b"]).

    • an arbitrary number of named fields (e.g. “{label_a}”). For example "{label_b}|{label_a}|{label_a}" for property_labels = ["label_a","label_b"].

    Mixed format strings (i.e. "{}{label_a}") are not permitted, but all other python formatting should be supported.

  • position (str, default="right") – where to put label relative to node. allowed values are: top-left”, “top”, “top-right”, “right”, “bottom-right”, “bottom”, “bottom-left”, and “left”.

  • position_offset (float, optional) – how far to displace the labels off the nodes, in px. If not specified, will be 0.75*node_size

  • plot_ancestors (bool, default=True) – draw ancestral nodes

  • plot_leaves (bool, default=False) – draw leaf nodes

  • plot_root (bool, default=True) – draw the root node

  • text_style (dict, optional) – dictionary specifying how to draw the text labels. toyplot Text documentation for description of allowable values.

draw_node_legend(label_renamer=None, max_label_len=25)

Add a node legend to the tree plot.

Parameters:
  • label_renamer (dict, optional) – dictionary where keys are property_labels for named series and values are what these should be called in the legend

  • max_label_len (int, default=15) – truncate long property names to max_label_len

draw_nodes(property_label=None, color=None, size=None, prop_span=None, plot_ancestors=True, plot_leaves=False, plot_root=True, scatter_style=None, palette=None)

Draw nodes colored and/or sized by a property loaded into the tree.

Parameters:
  • property_label (str, optional) – color/size nodes by property_label, where property_label is a feature of nodes in the toytree.tree instance.

  • color (str or tuple or dict) – set node color. If a single value, color all nodes that color. If list-like and length 2, treat as colors for minimum and maximum of a color gradient. If dict, map property keys to color values. Colors can be RGBA tuples, named colors, or hexadecimal strings. See the toyplot documentation for allowed values.

  • size (float or tuple or dict, optional) – set node size. If a single value, make all nodes that size. If list-like and length 2, treat as sizes for minimum and maximum of a size gradient. If dict, map property keys to size values. Sizes must be float >= 0.

  • prop_span (tuple, optional) – set min/max values for property color/size calculation. First element is min, second is max. Only applicable if color and size are set to be gradients.

  • plot_ancestors (bool, default=True) – draw ancestral nodes

  • plot_leaves (bool, default=False) – draw leaf nodes

  • plot_root (bool, default=True) – draw the root node

  • scatter_style (dict, optional) – dictionary specifying how to draw the nodes. valid keys are “shape”, “mstyle”,”angle”,”label”, and “lstyle”. see toyplot Markers documentation for description of values.

  • palette (toyplot.color.Palette, optional) – custom toyplot palette. if specified, use this palette rather than color_span to define color scheme.

draw_scale_bar(bar_length=0.2, units='subs/site')

Draw a scale bar on the tree plot.

Parameters:
  • bar_length (float, default=0.3) – draw a scale bar that is bar_length fraction of the total tree length. Note: this may be ignored and the bar truncated if the bar would collide with the tree.

  • units (str, default="subs/site") – name to put below the scale bar.

property legend_ax

toyplot axes holding legend.

property plotted_properties

Return list of named node series that have been plotted.

render(output_file)

Render a the tree out as a file.

Parameters:

output_file (str) – output file. should be .svg, .pdf, or .png

property tT

toytree object used to generate the plot.

property tree_ax

toyplot axes holding tree.

property tree_mark

tree object (a toyplot mark)

topiary.draw.species

Draw a species tree with tips labeled by species name.

topiary.draw.species.species_tree(species_tree, output_file=None, font_size=15, stroke_width=2, vertical_pixels_per_tip=20, min_height=300, tip_labels_align=True, return_canvas=False, **kwargs)

Draw a species tree with tips labeled by species name.

Parameters:
  • species_tree (ete3.Tree) – ete3 tree object holding a species tree

  • output_file (str, optional) – output file to write tree. If running in a notebook, will return to notebook and write to this file. If running in a notebook but not specified, do not write to a file. If not in a notebook and not specified, will write out ancestor-tree.pdf.

  • font_size (float, default=15) – font size in points for labels

  • stroke_width (int, default=2) – width of lines drawing tree (pixels)

  • vertical_pixels_per_tip (int, default=20) – number of pixels to assign to each tip when calculating figure height

  • min_height (float, default=300) – minimum height for figure (pixels)

  • tip_labels_align (bool, default=True) – align species names on the right of the plot

  • return_canvas (bool, default=False) – if True, return the canvas whether this is being called in a notebook or not. (canvas will be returned in a jupyter notebook regardless of this setting)

  • **kwargs (dict, optional) – pass any other keyword arguments directly to toytree.tree.draw

Returns:

plot – if running in jupyter notebook, return toyplot.canvas; otherwise, return None.

Return type:

toyplot.canvas or None

topiary.draw.tree

Draw a topiary tree with nodes colored by calculation outputs.

topiary.draw.tree.tree(calculation, output_file=None, bs_color={50: '#ffffff', 100: '#000000'}, pp_color={0.7: '#ffffff', 1.0: '#DC801A'}, event_color={'D': '#64007F', 'L': '#BAD316', 'T': '#407E98'}, bs_label=False, pp_label=False, event_label=False, anc_label=True, tip_columns=None, tip_name_separator='|', disambiguate_tip_names=True, node_color=None, node_size=None, font_size=15, tip_text_style=None, label_text_style=None, label_position='right', label_position_offset=None, label_color='gray', stroke_width=2, vertical_pixels_per_tip=25, min_height=300, df=None, anc_link_path=None, return_canvas=False, **kwargs)

Draw a tree with annotated with calculation outputs.

Parameters:
  • calculation (str or Supervisor) – completed calculation. Should either be a directory containing the calc (e.g. the directory with run_parameters.json, input, working, output) or a Supervisor instance with a calculation loaded.

  • output_file (str, optional) – output file to write tree.

  • bs_color (dict, default={50:"#ffffff",100:"#000000"}) – set min/max values for branch support color map. First key is min, second is max. Values are valid toyplot colors (see Notes). If given, color argument takes precedence over bs_color.

  • pp_color (dict, default={0.7:"#ffffff",1.0:"#DC801A"}) – set min/max values for posterior probability color map. First key is min, second is max. Values are valid toyplot colors (see Notes). If given, node_color argument takes precedence over pp_color.

  • event_color (dict, default={"D":"#64007F","L":"#BAD316","T":"#407E98"}) – colors for evolutionary events determined by gene/species tree reconciliation. Allowed keys are “S” (speciation), “D” (duplication), “L” (loss), and “T” (transfer). If a key is not specified, that event will not be drawn on the tree. (The default is to not show speciation). Values are any valid toyplot colors (see Notes). If given, node_color argument takes precedence over event_color.

  • bs_label (bool, default=False) – whether or not to write branch support values on the tree

  • pp_label (bool, default=False) – whether or not to write posterior probability values on the tree

  • event_label (bool, default=False) – whether or not to write events as text on the tree

  • anc_label (bool, default=True) – whether or not to write ancestor names as text on the tree

  • tip_columns (list, optional) – label the tree tips as “|”.join(tip_columns). For example, if tip_columns is [“species”,”recip_paralog”], tips will have names like ‘Homo sapiens|LY96’. If the name is not unique, the uid will be appended to the name (see disambiguate_tip_names below). If not specified, try [“species”,”recip_paralog”], [“species”,”nickname”], then, finally, [“species”,”name”].

  • tip_name_separator (str, default="|") – string to separate columns in tip names (“|” in tip_columns example above.)

  • disambiguate_tip_names (bool, default=True) – if two tip labels will be the same (for example, two labels will be “Homo sapiens|LY96”), append the uid to those labels so they can be uniquely identified.

  • node_color (str or tuple or dict, optional) – internal node color. If a single value, color all nodes that color. If list-like and length 2, treat as colors for minimum and maximum of a color gradient. If dict, map property keys to color values. This will override bs_color, pp_color, and event_color. We recommend using this to specify single colors only. Use bs_color, pp_color, and event_color to color nodes based on their properties.

  • node_size (float or tuple or dict, optional) – set node size in pixels. If a single value, make all nodes that size. If list-like and length 2, treat as sizes for minimum and maximum of a size gradient. If dict, map property keys to size values. Sizes must be float >= 0. The size map will be applied for each property individually, so this could lead to strange results if plotting branch supports and posterior probabilities simultaneously.

  • font_size (float, default=15) – font size in points for labels

  • tip_text_style (dict, optional) – dictionary of css key/value pairs for drawing tip labels. (See Notes for details.)

  • label_text_style (dict, optional) – dictionary of css key/value pairs for drawing internal nodes. (See Notes for details).

  • label_position (str, default="right") – where to put internal labels relative to node. allowed values are “top-left”, “top”, “top-right”, “right”, “bottom-right”, “bottom”, “bottom-left”, and “left”.

  • label_position_offset (float, optional) – how far to displace the internal labels off the nodes in pixels.

  • stroke_width (int, default=2) – width of lines drawing tree in pixels

  • vertical_pixels_per_tip (int, default=20) – number of pixels to assign to each tip when calculating figure height

  • min_height (float, default=300) – minimum height for figure (pixels)

  • df (pandas.DataFrame or None, default=None) – topiary dataframe (overrides whatever is in run_directory/output/dataframe.csv)

  • anc_link_path (str, optional) – if specified, format ancestors as links to ancestors in anc_link_path.

  • return_canvas (bool, default=False) – if True, return the canvas whether this is being called in a notebook or not. (canvas will be returned in a jupyter notebook regardless of this setting)

  • **kwargs (dict, optional) – pass any other keyword arguments directly to toytree.tree.draw

Notes

  • Colors can be specified as RGBA tuples, named colors, or hexadecimal strings. See the toyplot documentation for allowed values.

  • Allowed css keys are determined by toyplot. See the here for details.

Returns:

plot – if running in jupyter notebook, return toyplot.canvas; otherwise, return None.

Return type:

toyplot.canvas or None