def get_tree(tree1, abundance): for n in tree1.iter_leaves(): face1 = CircleFace(abundance[n.name][0], abundance[n.name][1], style='sphere') face2 = TextFace(n.name, ftype='Verdana', fsize=10, fgcolor='black', penwidth=0, fstyle='normal', tight_text=False, bold=False) face1.opacity = 0.9 n.add_face(face1, column=0) n.add_face( face2, column=0, position="branch-right") #branch-top branch-bottom branch-right tree1.ladderize() ts = TreeStyle() ts.mode = 'r' ts.scale = scale1 ts.show_leaf_name = False return tree1, ts
def treeLayout(self): # Add a tree style and a legend self.ts = TreeStyle() self.ts.show_scale = False self.ts.show_leaf_name = False self.ts.extra_branch_line_type = 0 self.ts.extra_branch_line_color = 'black' self.ts.layout_fn = self.layout self.ts.branch_vertical_margin = -10 self.ts.legend_position = 4 for name, color in zip(self.featurenames, self.colors): self.ts.legend.add_face(CircleFace(10, color), column=0) self.ts.legend.add_face(TextFace(name), column=1) if self.empty: self.ts.legend.add_face(CircleFace(10, self.colors[-1]), column=0) self.ts.legend.add_face(TextFace('none'), column=1) self.ts.legend.add_face(TextFace( datetime.now().strftime('%a, %d.%m.%Y; %H:%M:%S'), fsize=8), column=1) self.ts.legend.add_face(TextFace('Tree: ' + self.treefile, fsize=8), column=1) self.ts.legend.add_face(TextFace('Crosshits: ' + self.combo[10:], fsize=8), column=1) self.ts.legend.add_face(TextFace('Pruning: ' + self.prune, fsize=8), column=1) # Order the graphical tree output from highly branched nodes on top and less branched nodes to the bottom self.t.ladderize(1)
def layout(node): if node.is_leaf(): N = AttrFace("name", fsize=10, fgcolor="black") faces.add_face_to_node(N, node, 0) if "weight" in node.features: C = CircleFace(radius=node.weight, color="blue", style="sphere") C.opacity = 0.3 faces.add_face_to_node(C, node, 0, position="float")
def layout(node): if node.is_leaf(): longNameFace = faces.TextFace(code_name[node.name], fsize=15, fgcolor="green") faces.add_face_to_node(longNameFace, node, column=0) if "weight" in node.features: C = CircleFace(radius=node.weight, color="blue", style="sphere") C.opacity = 0.3 faces.add_face_to_node(C, node, 0, position="float")
def layout(node): # if node.is_leaf(): # # Add node name to leaf nodes # N = AttrFace("name", fsize=14, fgcolor="black") # faces.add_face_to_node(N, node, 0) if "weight" in node.features: # Creates a sphere face whose size is proportional to node's # feature "weight" C = CircleFace(radius=node.weight, color="RoyalBlue", style="sphere") # Let's make the sphere transparent C.opacity = 0.6 # And place as a float face over the tree faces.add_face_to_node(C, node, 0, position="float")
def layout(node): if node.is_leaf(): # Add node name to laef nodes N = AttrFace("name", fsize=14, fgcolor="black") faces.add_face_to_node(N, node, 0) if "weight" in node.features: # Creates a sphere face whose size is proportional to node's # feature "weight" C = CircleFace(radius=node.weight, color="RoyalBlue", style="sphere") # Let's make the sphere transparent C.opacity = 0.3 # And place as a float face over the tree faces.add_face_to_node(C, node, 0, position="float")
def layout(node): global f1_lst global f2_lst if node.is_leaf(): N = AttrFace("name", fsize=14, fgcolor="black") # can be "sci_name" faces.add_face_to_node(N, node, 0) if node.name in f1_lst: C = CircleFace(radius=5, color="darkred", style="sphere") faces.add_face_to_node(C, node, 1, position="aligned") if node.name in f2_lst: C = CircleFace(radius=5, color="RoyalBlue", style="sphere") faces.add_face_to_node(C, node, 2, position="aligned")
def render_tree(tree, mode, cluster, colourDict, width, position): duplicates = ["'EBOV|EMLab-RT|KG12||GIN|Boke|?|MinION_LQ05|2015-05-27'", "'EBOV|EMLab-RT|KG45||GIN|Boke|?|MinION_LQ10|2015-06-09'", "'EBOV|EMLab-RT|KG90||GIN|Boke|?|MinION_LQ05|2015-06-19'", "'EBOV|EMLab-RT|KG91||GIN|Boke|?|MinION_LQ05|2015-06-20'"] print('Running %s: %s cluster' %(mode, cluster)) if mode == 'small': #delete unwanted leaves keep_leaves = [] b = ["'" + clusters[cluster][0] + "'", "'" + clusters[cluster][1] + "'"] for a in tree.get_common_ancestor(b).get_leaves(): keep_leaves.append(a.name) delete_leaves = [leaf for leaf in tree.get_leaf_names() if leaf not in keep_leaves] #if cluster == 'Boke': # delete_leaves.extend(duplicates) print('Keeping %s leaves' %len(keep_leaves)) for leaf in delete_leaves: if tree.search_nodes(name=leaf)[0]: n = tree.search_nodes(name=leaf)[0] #if leaf in duplicates: # n.delete(preserve_branch_length=True) #else: n.delete() #print 'Removed %s' %(n.get_leaf_names()[0]) tree.ladderize() tree.write(outfile=sys.argv[1] + '_' + cluster + '.nwk') for n in tree.get_leaves(): display_name = n.get_leaf_names()[0][1:-1] country = metadata[display_name]['country'] instrument = metadata[display_name]['instrument'] #if cluster == 'Boke': if mode == 'big': n.add_face(MyTextFace(metadata[display_name]['short_id'], ftype="Helvetica", fsize=size[mode]), column=0, position="aligned") n.add_face(MyTextFace(metadata[display_name]['prefec'], ftype="Helvetica", fsize=size[mode]), column=1, position="aligned") n.add_face(MyTextFace(metadata[display_name]['date'], ftype="Helvetica", fsize=size[mode]), column=2, position="aligned") if country == 'GUI' or country == 'GIN': if instrument == 'MinION': C = CircleFace(radius=size[mode]/2, color=colourDict[metadata[display_name]['prefec']]) else: C = CircleFace(radius=size[mode]/2, color='#F1F1F1') elif country == 'SLE': if instrument == 'MinION': C = RectFace(width=size[mode], height=size[mode], bgcolor=colourDict[metadata[display_name]['prefec']], fgcolor='#FFFFFF') else: C = RectFace(width=size[mode], height=size[mode], bgcolor='#D3D3D3', fgcolor='#FFFFFF') elif country == 'LIB' or country == 'LBR': if instrument == 'MinION': C = RectFace(triangle=True, width=size[mode], height=size[mode], bgcolor=colourDict[metadata[display_name]['prefec']], fgcolor='#FFFFFF') else: C = RectFace(triangle=True, width=size[mode], height=size[mode], bgcolor='#939393', fgcolor='#FFFFFF') n.add_face(C, column=1, position=position) tree.render(file_name=sys.argv[1] + '_' + cluster + '.pdf', tree_style=ts, w=width)
def layout(node): if node.is_leaf(): N = AttrFace("name", fgcolor="black") faces.add_face_to_node(N, node, 0) if "weight" in node.features: # Creates a sphere face whose size is proportional to node's # feature 1/gini index circle_face = CircleFace(radius=node.weight, color="RoyalBlue", style="sphere") circle_face.hz_align = 2 circle_face.opacity = 0.3 text_face = TextFace(text=node.name) faces.add_face_to_node(circle_face, node, 0, position="float") faces.add_face_to_node(text_face, node, 0, position="float")
def get_example_tree(tree, color_dict=None, annot_dict=None, col=None): used_colours = set() for n in tree.traverse(): if n.is_leaf(): if n.name in annot_dict: n.img_style["bgcolor"] = color_dict[annot_dict[n.name]] used_colours.add(annot_dict[n.name]) ts = TreeStyle() ts.layout_fn = layout ts.show_leaf_name = False ts.mode = "c" # ts.arc_start = -180 # 0 degrees = 3 o'clock # ts.arc_span = 180 # ts.root_opening_factor = 1 # print (used_colours) for k,v in color_dict.items(): # Check that the specific colour was actually present in the tree we're annotating if k in used_colours: ts.legend.add_face(CircleFace(100, v), column=0) ts.legend.add_face(TextFace(k, fsize=50), column=1) # Add title ts.title.add_face(TextFace("Colouring tips on " + col, fsize=100), column=0) return tree, ts
def mylayout(node): # Internal Node formatting nstyle = NodeStyle() nstyle["size"] = 0 nstyle["vt_line_width"] = 2 nstyle["hz_line_width"] = 2 if node.is_leaf(): circle_face = CircleFace(10, color_dict[node.name], style='circle') faces.add_face_to_node(circle_face, node, position="branch-right", column=0) text_face = TextFace(meta_dict[node.name][0]) text_face.fgcolor = color_dict[node.name] faces.add_face_to_node(text_face, node, position="branch-right", column=1) node.set_style(nstyle) elif node.is_root(): node.dist = 0 node.set_style(nstyle) else: node.set_style(nstyle)
def traitTreeMinimal(traits, mapper): ### Take dict of traits and [R,G,B]-returning function ### Draw a tree with the continuous trait painted on via a colormapping function def rgb2hex(r, g, b): hex = "#{:02x}{:02x}{:02x}".format(r, g, b) return hex ts = TreeStyle() ts.show_leaf_name = False ts.rotation = 270 ts.complete_branch_lines_when_necessary = False #ts.optimal_scale_level = "full" ts.scale = 800 # default NodeStyle nstyle = NodeStyle() nstyle["size"] = 0 nstyle["hz_line_color"] = "grey" nstyle["vt_line_color"] = "grey" nstyle["hz_line_width"] = 3 nstyle["vt_line_width"] = 3 for n in tree.traverse(): chroma = rgb2hex(*[ int(val) for val in mapper(traits[n.ND], gamma=0.8, scaleMax=255) ]) # setup for wl2RGB nf = CircleFace(radius=10, color='none', style='circle', label=None) n.set_style(nstyle) n.add_face(nf, column=0, position='branch-top') outFile = args.output + "/test_trees/cont_trait.pdf" tree.render(outFile, tree_style=ts) print >> sys.stderr, outFile
def populate_legend(ts, nstyles): ts.legend_position = 4 all_files = os.listdir('.') for file in all_files: # find the legend.txt file # this is a hack, should implement a real solution eventually if 'legend.txt' in file: #j = 0 with open(file) as f: for line in f: line = line.strip() line_arr = line.split('\t') x = CircleFace(5, nstyles[line_arr[0]]['fgcolor']) ts.legend.add_face(x, column=0) ts.legend.add_face(TextFace(line_arr[0]), column=1) genome_list = '' for i in range(1, len(line_arr)): if i > 5: genome_list += '...' # too many genomes break if i == len( line_arr ) - 1: # last element shouldn't end with comma genome_list += line_arr[i][1:] else: genome_list += line_arr[i][1:] + ', ' ts.legend.add_face(TextFace(genome_list), column=2)
def add_pie_face(tree, ts, total_profile, group): for leaf_name in tree.iter_leaf_names(): node = tree & leaf_name profile_list = total_profile[node.name] if group is not None: profile_list_grouped = OrderedDict() for sample_name, profile in profile_list.iteritems(): if group[sample_name] not in profile_list_grouped: profile_list_grouped[group[sample_name]] = 0 profile_list_grouped[group[sample_name]] += profile profile_list = pd.Series(profile_list_grouped) col_num = len(profile_list) times = int(math.ceil(col_num / len(COLS_BREWER))) cols = (COLS_BREWER * times)[:col_num] summary = sum(profile_list) if not summary: print profile_list print profile_list_grouped continue percents = map(lambda s: s / summary * 100, profile_list) P = PieChartFace(percents=percents, width=50, height=50, colors=cols) node.add_face(P, 0, 'aligned') #ts.legend.add_face(TextFace(" "), 0) #ts.legend.add_face(TextFace(" "), 1) for ind, g in enumerate(profile_list.index): T = TextFace(' %s ' % g) ts.legend.add_face(T, ind*2%24) C = CircleFace(radius=10, color=cols[ind], style="circle") ts.legend.add_face(C, (ind*2+1)%24) ts.legend_position = 1
def legend(style, color_list): for row in color_list: style.legend.add_face(CircleFace(100, row[1]), column=0) style.legend.add_face(TextFace(" " + row[0], fgcolor="Black", fsize=35, bold=True), column=1) return style
def layout(node): global represent_lst if node.is_leaf(): N = AttrFace("name", fsize=14, fgcolor="black") # can be "sci_name" faces.add_face_to_node(N, node, 0) if node.name in represent_lst: C = CircleFace(radius=5, color="black", style="sphere") faces.add_face_to_node(C, node, 1, position="aligned")
def style_and_render_tree(self, file_types=["svg"]): from ete3 import TreeStyle, TextFace, CircleFace ts = TreeStyle() title_face = TextFace(f"{genus} {snakemake.config['species']}", fsize=20) title_face.margin_bottom = 10 ts.title.add_face(title_face, column=0) ts.branch_vertical_margin = 10 ts.show_leaf_name = True # Legend ts.legend.add_face(TextFace(""), column=1) for category in ["Allowed", "Deviations", "Filtered", "Color"]: category = TextFace(category, fsize=8, bold=True) category.margin_bottom = 2 category.margin_right = 40 ts.legend.add_face(category, column=1) for i, criteria in enumerate(CRITERIA, 2): title = criteria.replace("_", " ").title() title = TextFace(title, fsize=8, bold=True) title.margin_bottom = 2 title.margin_right = 40 cf = CircleFace(4, COLORS[criteria], style="sphere") cf.margin_bottom = 5 filtered_count = len( list(filter(None, self.failed_report.criteria == criteria)) ) filtered = TextFace(filtered_count, fsize=8) filtered.margin_bottom = 5 allowed = TextFace(self.allowed[criteria], fsize=8) allowed.margin_bottom = 5 allowed.margin_right = 25 # TODO Prevent tolerance from rendering as a float tolerance = TextFace(self.tolerance[criteria], fsize=8) tolerance.margin_bottom = 5 ts.legend.add_face(title, column=i) ts.legend.add_face(allowed, column=i) ts.legend.add_face(tolerance, column=i) ts.legend.add_face(filtered, column=i) ts.legend.add_face(cf, column=i) for f in file_types: out_tree = os.path.join(self.paths.qc, "tree.{}".format(f)) self.tree.render(out_tree, tree_style=ts)
def sel_mylayout(node): node.set_style(my_node_style) if node.is_leaf(): # add names in larger font + italics species_name = AttrFace("name", fsize=12, fstyle="italic") add_face_to_node(species_name, node, column=0, position="branch-right") # add absence/presence matrix for i, value in enumerate(getattr(node, "profile", [])): if value > 0: color = "#FF0000" else: color = "#EEEEEE" my_face = CircleFace(8, color, style="circle") my_face.margin_right = 3 my_face.margin_bottom = 3 add_face_to_node(my_face, node, position="aligned", column=i)
def get_tree_style(): ts = TreeStyle() ts.show_leaf_name = False # True ts.layout_fn = layout ts.rotation = 90 ts.branch_vertical_margin = 10 ts.show_scale = False # ts.mode = "c" ts.scale = 50 ts.title.add_face(TextFace(" ", fsize=20), column=0) # for n in t.traverse(): # nstyle = NodeStyle() # nstyle["fgcolor"] = "red" # nstyle["size"] = 15 # n.set_style(nstyle) # ts.show_leaf_name = True ts.legend.add_face(TextFace(" "), column=0) ts.legend.add_face(TextFace(" "), column=1) ts.legend.add_face(RectFace(20, 20, NO_SUPPORT_COLOR, NO_SUPPORT_COLOR), column=0) ts.legend.add_face(TextFace(" Topic with no support (u(t)=0)"), column=1) ts.legend.add_face(TextFace(" "), column=0) ts.legend.add_face(TextFace(" "), column=1) ts.legend.add_face(RectFace(20, 20, "#90ee90", "#90ee90"), column=0) ts.legend.add_face(TextFace(" Topic with minor support 0<u(t)<=0.4"), column=1) ts.legend.add_face(TextFace(" "), column=0) ts.legend.add_face(TextFace(" "), column=1) ts.legend.add_face(RectFace(20, 20, "green", "green"), column=0) ts.legend.add_face( TextFace(u" Topic with medium support 0.4<u(t)<=0.6 "), column=1) ts.legend.add_face(TextFace(" "), column=0) ts.legend.add_face(TextFace(" "), column=1) ts.legend.add_face(RectFace(20, 20, "#004000", "#004000"), column=0) ts.legend.add_face(TextFace(" Topic with high support u(t)>0.6"), column=1) ts.legend.add_face(TextFace(" "), column=0) ts.legend.add_face(TextFace(" "), column=1) ts.legend.add_face(CircleFace(10, "red"), column=0) ts.legend.add_face(TextFace(" Gap"), column=1) ts.legend.add_face(TextFace(" "), column=0) ts.legend.add_face(TextFace(" "), column=1) ts.legend.add_face(RectFace(40, 40, "#004000", "#004000"), column=0) # green # ts.legend.add_face(CircleFace(15, "green"), column=1) ts.legend.add_face(TextFace(" Head subject or offshoot"), column=1) ts.legend_position = 4 # ts.title.add_face(TextFace(" ", fsize=20), column=0) return ts
def mk_bilan_tree(tree, bilan_nodesWithTransitions, output): d_nodesWithTransitions = {} for x in bilan_nodesWithTransitions: if x in d_nodesWithTransitions: d_nodesWithTransitions[x] += 1 else: d_nodesWithTransitions[x] = 1 for n in tree.traverse(): if n.ND in d_nodesWithTransitions: n.set_style(nstyle_T2) C = CircleFace(radius=d_nodesWithTransitions[n.ND] * 2, color="RoyalBlue", style="sphere", label=str(d_nodesWithTransitions[n.ND])) C.opacity = 0.5 n.add_face(C, 0, position="float") else: n.set_style(nstyle) tree.render(output, tree_style=tree_style)
def draw(self, file, colors, color_internal_nodes=True, legend_labels=(), show_branch_support=True, show_scale=True, legend_scale=1, mode="c"): max_color = len(colors) for node in self.tree.traverse(): if not (color_internal_nodes or node.is_leaf()): continue color = colors[min(node.color, max_color - 1)] node.img_style['bgcolor'] = color ts = TreeStyle() ts.mode = mode ts.scale = self.scale # Disable the default tip names config ts.show_leaf_name = False ts.show_branch_support = show_branch_support # ts.branch_vertical_margin = 20 ts.show_scale = show_scale cur_max_color = max(v.color for v in self.tree.traverse()) current_colors = colors[0:cur_max_color + 1] for i, (label, color_) in enumerate(zip(legend_labels, current_colors)): ts.legend.add_face(CircleFace(24 * legend_scale, color_), column=0) ts.legend.add_face(CircleFace(13 * legend_scale, 'White'), column=1) ts.legend.add_face(TextFace(label, fsize=53 * legend_scale), column=2) ts.legend.add_face(CircleFace(13 * legend_scale, 'White'), column=3) # self.tree.render("ete_tree.pdf", dpi=300, tree_style=ts) self.tree.render(file, w=1000, tree_style=ts)
def style_and_render_tree(self, file_types=["svg"]): from ete3 import TreeStyle, TextFace, CircleFace ts = TreeStyle() title_face = TextFace(self.name.replace('_', ' '), fsize=20) title_face.margin_bottom = 10 ts.title.add_face(title_face, column=0) ts.branch_vertical_margin = 10 ts.show_leaf_name = False # Legend ts.legend.add_face(TextFace(""), column=1) for category in ["Allowed", "Tolerance", "Filtered", "Color"]: category = TextFace(category, fsize=8, bold=True) category.margin_bottom = 2 category.margin_right = 40 ts.legend.add_face(category, column=1) for i, criteria in enumerate(self.criteria, 2): title = criteria.replace("_", " ").title() title = TextFace(title, fsize=8, bold=True) title.margin_bottom = 2 title.margin_right = 40 cf = CircleFace(4, self.colors[criteria], style="sphere") cf.margin_bottom = 5 filtered_count = len( list(filter(None, self.failed_report.criteria == criteria))) filtered = TextFace(filtered_count, fsize=8) filtered.margin_bottom = 5 allowed = TextFace(self.allowed[criteria], fsize=8) allowed.margin_bottom = 5 allowed.margin_right = 25 tolerance = TextFace(self.tolerance[criteria], fsize=8) tolerance.margin_bottom = 5 ts.legend.add_face(title, column=i) ts.legend.add_face(allowed, column=i) ts.legend.add_face(tolerance, column=i) ts.legend.add_face(filtered, column=i) ts.legend.add_face(cf, column=i) for f in file_types: out_tree = os.path.join(self.qc_results_dir, 'tree.{}'.format(f)) self.tree.render(out_tree, tree_style=ts) self.log.info("tree.{} generated".format(f))
def layout(node): ## if node.is_leaf() and 'showname' in node.features: ## # Add node name to laef nodes ## N = AttrFace("name", fsize=14, fgcolor="black") ## faces.add_face_to_node(N, node, 0) if "Rsize" in node.features: # Creates a sphere face whose size is proportional to node's # feature "Rsize" C = CircleFace(radius=node.Rsize * 3, color="RoyalBlue", style="sphere") # make the sphere transparent C.opacity = 0.9 # And place as a float face over the tree faces.add_face_to_node(C, node, 0, position="float") if "Rpearsize" in node.features: # Creates a sphere face whose size is proportional to node's # feature "Rpearsize" C = CircleFace(radius=node.Rpearsize * 3, color="lightgreen", style="sphere") # make the sphere transparent C.opacity = 0.9 # And place as a float face over the tree faces.add_face_to_node(C, node, 0, position="float")
def my_layout(node): circle_color = 'lightgray' if colormap is None or node.name not in colormap else colormap[ node.name] text_color = 'black' if isinstance(circle_color, str): C = CircleFace(radius=max(3, 10 * scipy.sqrt(node.frequency)), color=circle_color, label={ 'text': str(node.frequency), 'color': text_color } if node.frequency > 0 else None) C.rotation = -90 C.hz_align = 1 faces.add_face_to_node(C, node, 0) else: P = PieChartFace( [100 * x / node.frequency for x in circle_color.values()], 2 * 10 * scipy.sqrt(node.frequency), 2 * 10 * scipy.sqrt(node.frequency), colors=[(color if color != 'None' else 'lightgray') for color in list(circle_color.keys())], line_color=None) T = TextFace(' '.join( [str(x) for x in list(circle_color.values())]), tight_text=True) T.hz_align = 1 T.rotation = -90 faces.add_face_to_node(P, node, 0, position='branch-right') faces.add_face_to_node(T, node, 1, position='branch-right') if idlabel: T = TextFace(node.name, tight_text=True, fsize=6) T.rotation = -90 T.hz_align = 1 faces.add_face_to_node( T, node, 1 if isinstance(circle_color, str) else 2, position='branch-right')
def layout(node): if node.is_leaf(): if node.name=="A": node.color="Blue" node.attr2="Green" elif node.name=="B": node.color="Red" node.attr2="Orange" else: node.color="Grey" node.attr2="Yellow" faces.add_face_to_node( CircleFace(radius=5, color=node.color), node, column=1) faces.add_face_to_node( RectFace(width=10, height=10, fgcolor=node.attr2, bgcolor=node.attr2), node, column=2)
def set_tree_style(): ts = TreeStyle() ts.legend.add_face(CircleFace(10, "red"), column=0) ts.legend.add_face(CircleFace(10, "lime"), column=0) ts.legend.add_face(CircleFace(10, "cyan"), column=0) ts.legend.add_face(CircleFace(10, "plum"), column=0) ts.legend.add_face(CircleFace(10, "lightsalmon"), column=0) ts.legend.add_face(CircleFace(10, "indigo"), column=0) ts.legend.add_face(CircleFace(10, "royalblue"), column=0) ts.legend.add_face(CircleFace(10, "olive"), column=0) ts.show_leaf_name = False ts.show_branch_length = False ts.show_branch_support = False ts.layout_fn = my_layout return ts
def network_size_view(tree, orthologous_groups, save_dir): # Set the size of each node for node in tree.traverse(): # Count the number of genes likely to be regulated in this node num_regulated = len([grp for grp in orthologous_groups if grp.most_likely_state_at(node.name) == '1']) nstyle = NodeStyle() nstyle['size'] = 0 node.set_style(nstyle) circle_face = CircleFace( radius=num_regulated, color='green', style='sphere', label={'text': str(num_regulated), 'color': 'black'}) node.add_face(circle_face, column=2) ts = TreeStyle() tree.render(os.path.join(save_dir, 'network_size.svg'), tree_style=ts)
def default_layout(node): """ Specifies the layout for the ete.TreeStyle object. Parameters ---------- node: ete.Tree Input node for specifying which attributes. """ if node.is_leaf(): # Add node name to leaf nodes N = AttrFace("name", fsize=14, fgcolor="black") faces.add_face_to_node(N, node, 0) if "weight" in node.features: # Creates a sphere face whose size is proportional to node's # feature "weight" C = CircleFace(radius=node.weight, color="Red", style="sphere") # Let's make the sphere transparent C.opacity = 0.5 # Rotate the faces by 90* C.rotation = 90 # And place as a float face over the tree faces.add_face_to_node(C, node, 0, position="float")
def layout(n): nstyle = NodeStyle() nstyle['shape'] = 'sphere' nstyle['size'] = 0 nstyle['fgcolor'] = 'black' nstyle["hz_line_width"] = 2 nstyle["vt_line_width"] = 2 n.set_style(nstyle) clustering = None subclustering = None if args.clusters: clustering = read_clusters(args.clusters) if args.subclusters: subclustering = read_clusters(args.subclusters) if n.is_leaf(): s = samples[n.name] if args.circular: radius=12 else: radius=4 c = CircleFace(radius=radius, color=s['prefec__colour'], style='circle') n.add_face(c, column=0) offset = 1 if not args.hide_annotations: offset += 5 tf = MyTextFace(s['id'], fsize=8, tight_text=False) n.add_face(tf, column=1, position="aligned") n.add_face(MyTextFace(s['prefec'], fsize=8, tight_text=False), column=2, position="aligned") n.add_face(MyTextFace(s['subprefec'], fsize=8, tight_text=False), column=3, position="aligned") n.add_face(MyTextFace(s['village'], fsize=8, tight_text=False), column=4, position="aligned") n.add_face(MyTextFace(s['date'], fsize=8, tight_text=False), column=5, position="aligned") if clustering: n.add_face(MyBorderFace(clustering[n.name], fsize=20, tight_text=False), column=offset, position="aligned") offset += 1 if subclustering: n.add_face(MyBorderFace(subclustering[n.name], fsize=20, tight_text=False), column=offset, position="aligned") offset += 1 if hasattr(n, 'sequence'): sf = faces.SequenceFace(n.sequence, "aa", fsize=10, fg_colors=blackcolors, bg_colors=seqcolors, col_w=11) n.add_face(sf, column=offset, position="aligned") offset += 1
def traitTree(tree, traits, mapper, outDir, floatSwitch=0): ### Take dict of traits and [R,G,B]-returning function ### Draw a tree with the continuous trait painted on via a colormapping function def rgb2hex(r, g, b): hex = "#{:02x}{:02x}{:02x}".format(r, g, b) return hex for n in tree.traverse(): if n.is_leaf(): n.set_style(nstyle_L) # a manual way to set leaf labels #n.add_face(TextFace(str(n.name)), column=0, position="aligned") else: n.set_style(nstyle) #nd = TextFace(str(n.ND)) # label with node ID # make the face if round == 0: nd = TextFace(str(int(round( traits[n.ND])))) # label with rounded continuous trait value else: nd = CircleFace( 10, color=rgb2hex(*[int(val) for val in mapper(traits[n.ND])])) #nd = TextFace(str(round(traits[n.ND], floatSwitch))) # label with rounded continuous trait value #nd.background.color = rgb2hex(*[int(val) for val in mapper(traits[n.ND], gamma=0.8, scaleMax=255)]) # setup for wl2RGB #nd.background.color = rgb2hex(*[int(val) for val in mapper(traits[n.ND])]) # setup for grayscale nd.background.color = None #nd.margin_right = 2 #nd.margin_top = 1 #nd.margin_left = 2 #nd.margin_bottom = 1 nd.border.width = None nd.hz_align = 2 #nd.inner_border.width = 1 # outline for the circle node #ol = CircleFace(11, color = "black") #ol.hz_align = 0 #n.add_face(ol, column=0, position="float-behind") #float-behind n.add_face(nd, column=0, position="float") #float # this is necessary for some reason to keep the tree from collapsing n.add_face(TextFace(" "), column=0, position="branch-bottom") outFile = outDir + "/cont_trait.pdf" tree.render(outFile, tree_style=tree_style) print >> sys.stderr, outFile
def process_tree(self, t, n): # Add faces if self.opts.attribute: values = set( [getattr(l, self.opts.attribute) for l in t.get_leaves()]) colours = get_colour_set(len(values)) colour_map = dict(zip(values, colours)) for l in t.iter_leaves(): mycolour = colour_map[getattr(l, self.opts.attribute)] if not self.dummy: # pragma: no cover l.add_face( CircleFace(radius=10, color=mycolour, style="sphere"), 0) # Apply labels if not self.dummy: # pragma: no cover for l in t.iter_leaves(): l.add_face(TextFace(getattr(l, self.opts.label)), 1) # Plot or save if self.opts.output: kw = {} if self.opts.height or self.opts.width: kw["h"] = self.opts.height kw["w"] = self.opts.width kw["units"] = self.opts.units kw["dpi"] = self.opts.dpi if self.opts.multiple: base, ext = os.path.splitext(self.opts.output) filename = base + ("_%06d" % (n)) + ext else: filename = self.opts.output if not self.dummy: t.render(filename, ultrametric, tree_style=self.ts, **kw) else: # pragma: no cover if not self.dummy: t.show(ultrametric, tree_style=self.ts) if self.opts.multiple: return None else: raise StopIteration