当前位置: 首页>>代码示例>>Python>>正文


Python TreeStyle.legend_position方法代码示例

本文整理汇总了Python中ete2.TreeStyle.legend_position方法的典型用法代码示例。如果您正苦于以下问题:Python TreeStyle.legend_position方法的具体用法?Python TreeStyle.legend_position怎么用?Python TreeStyle.legend_position使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ete2.TreeStyle的用法示例。


在下文中一共展示了TreeStyle.legend_position方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: draw_tree

# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import legend_position [as 别名]
def draw_tree(tree, file):
    root = tree.get_midpoint_outgroup()
    try:
      tree.set_outgroup(root)
    except:
      pass
    root = tree.get_tree_root()
    root.dist = 0
    add_sig(tree)
    ts = TreeStyle()
    ts.branch_vertical_margin = 1
    #ts.scale = 1500
    ts.show_leaf_name = False
    #ts.show_branch_support = True
    leg_file = path.join(path.expanduser('~'), 'Perl', 'Modules', 'TreeLegend.png')   
    leg_face= ImgFace(img_file=leg_file)
    leg_face.margin_left, leg_face.margin_top = 5, 5
    ts.legend.add_face(leg_face, column=1)
    ts.legend_position=1

    title_face = TextFace(text=file.split('.')[0])
    title_face.margin_left, title_face.margin_top = 10, 5
    ts.title.add_face(title_face, column=1)
    (ts.margin_left, ts.margin_right) = (5,5)
    tree.render(file, tree_style=ts, w=6000, units='mm')
开发者ID:hobrien,项目名称:Python,代码行数:27,代码来源:ColourTree.py

示例2: make_tree

# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import legend_position [as 别名]
def make_tree(treefile, image_file, clone_info):
    colour_list = ['MidnightBlue','RoyalBlue', 'LightSkyBlue', 'Aquamarine', 'SpringGreen', 'GreenYellow',\
                   'Gold','DarkOrange']
    weeks = ['16', '30', '38', '48', '59', '119', '176', '206']
    weeks = ['6', '14', '53', '92','144']
    t = Tree(treefile,format = 1)
    ts = TreeStyle()
    for i in range(5):
        ts.legend.add_face(CircleFace(20, colour_list[i]), column=0)
        ts.legend.add_face(TextFace('week' + weeks[i]), column=1)
    ts.legend_position = 2
    ts.show_leaf_name = True
    ts.branch_vertical_margin = 15
    ts.rotation = 90
    ns = NodeStyle()
    ns["size"] = 1
    ns.hz_line_width = 10
    ns.vt_line_width = 10
    edge = 0
    for node in t.traverse():
        node.name = node.name.replace("'", "")
        node.name = node.name.replace(".", ",")
        name = node.name.split(' ')[0]
        print name
        if name in clone_info.keys():
            style_node(node, colour_list[int(clone_info[name][0])-1], int(int(clone_info[name][1])/10)+5)
        if not node.is_leaf() and node.name != 'NoName':
                f = TextFace(node.name)
                f.margin_top = 2.5
                f.margin_bottom = 2.5
                f.margin_right = 2.5
                f.margin_left = 2.5
                node.add_face(f, column=0, position="branch-top")
    t.render(image_file, tree_style = ts)
开发者ID:AnnaLaddach,项目名称:MRes-project,代码行数:36,代码来源:tree_functions3.py

示例3: bar

# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import legend_position [as 别名]
            node.add_face(profileFace, 1, position = "aligned")
    
    # Add the color bar (kind of hacked in from matplotlib since there is no convenient way to get it from ETE)
    # I could generate this in situ... for now I just have a file I like and run with it.
    # This doesn't match exactlty becuase I don't have the time or motivation now to mess with QT to do it.
    # It should be pretty close though...
    from ete2 import ImgFace
    imgloc = os.path.join(locateRootDirectory(), "src", "internal", "Colormap.png")
    F1 = faces.TextFace("Minimum: %1.1f" %(matrix_min), ftype="Times", fsize=32 )
    F2 = faces.ImgFace(imgloc)
    F3 = faces.TextFace("%1.1f : Maximum" %(matrix_max), ftype="Times", fsize=32 )
    ts.legend.add_face(F1, 0)
    ts.legend.add_face(F2, 1)
    ts.legend.add_face(F3, 2)
    # Put it on the Bottom-left
    ts.legend_position = 3

if options.textfile is not None:
    fid = open(options.textfile, "r")
    # Our formatting requirements are the same as ETE's, which are:
    # 1: Tab delimited,
    # 2: #names in first row followed by titles,
    # 3: Node names in the first column followed by all the other data
    title_row = fid.readline().strip("\r\n").split("\t")
    n_titles = len(title_row)
    for idx, title in enumerate(title_row[1:]):
        coltitle = TextFace("    " + str(title) + "    ", ftype="Times", fsize=int(options.fontsize*1.2), fstyle = 'Bold')
        coltitle.hz_align = True
        # Organism name has column 0
        ts.aligned_header.add_face(coltitle, column=idx+1)
    for line in fid:
开发者ID:BioPunk,项目名称:clusterDbAnalysis,代码行数:33,代码来源:db_displayTree.py

示例4: doWork

# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import legend_position [as 别名]
def doWork(args):
	# read clustering data
	geneIdToClusterId = {}
	clusterIds  = []
	for line in open(args.cluster):
		if line[0] == '%':
			clusterId = line[1:].strip()
			clusterIds.append(clusterId)
		else:
			geneIdToClusterId[line.strip()] = clusterId

	# create colour map for clusters
	clusterIdToColour = {}
	index = 0
	for clusterId in clusterIds:
		rgb = tuple([int(c*255) for c in hsv_to_rgb(float(index)/len(clusterIds), 0.4, 1.0)])
		clusterIdToColour[clusterId] = '#%02X%02X%02X' % rgb
		index += 1

	# read tree
	tree = Tree(args.tree)

	# define node properties
	for node in tree.traverse('levelorder'):
		if node.is_leaf():
			name = node.name.replace("'", '')
			clusterId = geneIdToClusterId[name]
			node.add_feature('clusterId', clusterId)
			
			if args.label:
				node.name = ' ' + name + ' [' + clusterId + ']'
			
			ns = NodeStyle()
			ns['shape'] = 'circle'
			ns['fgcolor'] = 'black'
			ns['size'] = 4
			node.set_style(ns)
		else:
			ns = NodeStyle()
			ns['size'] = 0
			node.set_style(ns)
		
	# determine colour for each node
	assignedColor = set()
	for node in tree.traverse('levelorder'):
		if node.is_leaf() or node.is_root():
			continue
			
		# determine clusters descendent from this node
		clusterSet = set()
		for leaf in node.get_leaves():
			clusterSet.add(leaf.clusterId)
			
		# check if parent has already been assigned a colour
		bContinue = False
		parentNode = node.up
		while not parentNode.is_root():
			if parentNode in assignedColor:
				bContinue = True
				break
				
			parentNode = parentNode.up
			
		if bContinue:
			continue

		# colour node if all descendants are from the same cluster
		if len(clusterSet) == 1:
			clusters = list(clusterSet)
			ns = NodeStyle()
			ns['bgcolor'] = clusterIdToColour[clusters[0]]
			ns['size'] = 0
			node.set_style(ns)
			assignedColor.add(node)

	# create tree style for plotting consisteny index trees
	treeStyle = TreeStyle()
	treeStyle.margin_left = 10
	treeStyle.margin_right = 10
	treeStyle.margin_top = 10
	treeStyle.margin_bottom = 10
	treeStyle.guiding_lines_type = 1
	treeStyle.legend_position=1
	treeStyle.scale = 500
	
	# add legend
	rowIndex = 0
	for clusterId in sorted(clusterIdToColour.keys()):
		treeStyle.legend.add_face(CircleFace(4, clusterIdToColour[clusterId]), column=0)
		treeStyle.legend.add_face(TextFace(' ' + clusterId), column=1)
		rowIndex += 1

	tree.render(args.output, dpi=args.dpi, w = int(args.width*args.dpi + 0.5), tree_style=treeStyle)
开发者ID:dparks1134,项目名称:PETs,代码行数:95,代码来源:plotTree.py

示例5: MakePlot

# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import legend_position [as 别名]

#.........这里部分代码省略.........
		if LCA.name==t.name:
			percent_dist = percent*LCA_to_leaf_dist
			if mean_dist <= percent:
				child_node = (t&leaf_name)
			else:
				child_node = (t&nearby_names[0])#This means "go up from root" in the direction of the nearest guy
			ancestor_node = (t&child_node.name).up
		elif mean_dist <= percent:
			percent_dist = t.get_distance(LCA) + abs(percent-mean_dist)*(LCA_to_leaf_dist)/(1-mean_dist)
			child_node = (t&leaf_name)
			ancestor_node = (t&child_node.name).up
		else:
			percent_dist = t.get_distance(LCA) - abs(percent-mean_dist)*(t.get_distance(LCA))/(mean_dist)
			child_node = (t&leaf_name)
			ancestor_node = (t&child_node.name).up
		while t.get_distance(t.name, ancestor_node) > percent_dist:
			child_node = ancestor_node
			ancestor_node = (t&child_node.name).up
		insert_node(t, leaf_name+"_"+str(percent), child_node.name, percent_dist-t.get_distance(t.name, ancestor_node))

	#Set outgroup
	if outgroup in names:
		t.set_outgroup(t&outgroup) #I will need to check that this outgroup is actually one of the names...
	else:
		print("WARNING: the chosen outgroup " + outgroup + " is not in the given taxonomy: ")
		print(names)
		print("Proceeding without setting an outgroup. This may cause results to be uninterpretable.")

	#Insert hypothetical nodes
	hyp_node_names = dict()
	cutoffs = [.9,.8,.7,.6,.5,.4,.3,.2,.1]
	cutoffs = [-.5141*(val**3)+1.0932*(val**2)+0.3824*val for val in cutoffs]
	for i in range(len(org_names)):
		xi = x[i:len(x):len(org_names)]
		for j in range(1,len(cutoffs)+1):
			if xi[j]>0:
				insert_hyp_node(t, org_names[i], cutoffs[j-1],ckm_ave_train_dist, org_names)
				hyp_node_names[org_names[i]+"_"+str(cutoffs[j-1])] = [org_names[i], cutoffs[j-1], j-1] #in case there are "_" in the file names

	size_factor=250
	font_size=55

	#Now put the bubbles on the nodes
	def layout(node):
		node_style = NodeStyle()
		node_style["hz_line_width"] = 10
		node_style["vt_line_width"] = 10
		node.set_style(node_style)
		#print(node)
		if node.is_leaf():
			if node.name in org_names:
				#make reconstructed bubble
				size = x[org_names.index(node.name)]
				F = CircleFace(radius=size_factor*math.sqrt(size), color="RoyalBlue", style="sphere")
				F.border.width = None
				F.opacity = 0.6
				faces.add_face_to_node(F,node, 0, position="branch-right")
				#Denote that this was a training organism
				nameFace = AttrFace("name", fsize=font_size, fgcolor='black')
				faces.add_face_to_node(nameFace, node, 0, position="branch-right")
		elif node.name in hyp_node_names: #Otherwise it's a hypothetical node, just use recon x
			node_base_name = hyp_node_names[node.name][0]
			percent = hyp_node_names[node.name][1]
			if node_base_name in org_names:
				idx = hyp_node_names[node.name][2]
				size = x[org_names.index(node_base_name)+(idx+1)*len(org_names)]
				F = CircleFace(radius=size_factor*math.sqrt(size), color="RoyalBlue", style="sphere")
				F.border.width = None
				F.opacity = 0.6
				faces.add_face_to_node(F,node, 0, position="branch-right")
				#This is if I want the names of the hypothetical nodes to be printed as well
				#nameFace = AttrFace("name", fsize=font_size, fgcolor='black')
				#faces.add_face_to_node(nameFace, node, 0, position="branch-right")
			else:
				size=0
		else:
			size=0
	
	ts = TreeStyle()
	ts.layout_fn = layout
	ts.mode = "r"
	#ts.mode = "c"
	ts.scale = 2*1000
	ts.show_leaf_name = False
	ts.min_leaf_separation = 50
	F = CircleFace(radius=.87*size_factor, color="RoyalBlue", style="sphere")
	F.border.width = None
	F.opacity = 0.6
	ts.legend.add_face(F,0)
	ts.legend.add_face(TextFace("  Inferred relative abundance",fsize=1.5*font_size,fgcolor="Blue"),1)
	ts.legend.add_face(TextFace("  Total absolute abundance depicted " + str(sum_x)[0:8], fsize=1.5*font_size,fgcolor="Black"),1)
	ts.legend_position=4
	#t.show(tree_style=ts)
	t.render(outfile, w=550, units="mm", tree_style=ts)
	
	#Redner the XML file
	project = Phyloxml()
	phylo = phyloxml.PhyloxmlTree(newick=t.write(format=0, features=[]))
	project.add_phylogeny(phylo)
	project.export(open(outfilexml,'w'))
开发者ID:AndyGreenwell,项目名称:MetaPalette,代码行数:104,代码来源:PlotPackage.py

示例6: draw_tree

# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import legend_position [as 别名]

#.........这里部分代码省略.........
        pass

    def ly_block_alg(node):
        if node.is_leaf():
            if 'sequence' in node.features:
                seqFace = SeqMotifFace(node.sequence, [])
                # [10, 100, "[]", None, 10, "black", "rgradient:blue", "arial|8|white|domain Name"],
                motifs = []
                last_lt = None
                for c, lt in enumerate(node.sequence):
                    if lt != '-':
                        if last_lt is None:
                            last_lt = c
                        if c+1 == len(node.sequence):
                            start, end = last_lt, c
                            motifs.append([start, end, "()", 0, 12, "slategrey", "slategrey", None])
                            last_lt = None
                    elif lt == '-':
                        if last_lt is not None:
                            start, end = last_lt, c-1
                            motifs.append([start, end, "()", 0, 12, "grey", "slategrey", None])
                            last_lt = None

                seqFace = SeqMotifFace(node.sequence, motifs,
                                       intermotif_format="line",
                                       seqtail_format="line", scale_factor=ALG_SCALE)
                add_face_to_node(seqFace, node, ALG_START_COL, aligned=True)

                
    TRACKED_CLADES = ["Eukaryota", "Viridiplantae",  "Fungi",
                      "Alveolata", "Metazoa", "Stramenopiles", "Rhodophyta",
                      "Amoebozoa", "Crypthophyta", "Bacteria",
                      "Alphaproteobacteria", "Betaproteobacteria", "Cyanobacteria",
                      "Gammaproteobacteria",]
    
    # ["Opisthokonta",  "Apicomplexa"]
    
    colors = random_color(num=len(TRACKED_CLADES), s=0.45)
    lin2color = dict([(ln, colors[i]) for i, ln in enumerate(TRACKED_CLADES)])

    NAME_FACE = AttrFace('name', fsize=10, fgcolor='#444444')
        
    LABEL_START_COL = 10
    ALG_START_COL = 40
    ts = TreeStyle()
    ts.draw_aligned_faces_as_table = False
    ts.draw_guiding_lines = False
    ts.show_leaf_name = False
    ts.show_branch_support = False
    ts.scale = 160

    ts.layout_fn = [ly_basic, ly_leaf_names, ly_supports, ly_tax_labels]

    MIXED_RES = set()
    MAX_SEQ_LEN = 0
    NPR_TREES = []
    for n in tree.traverse():
        if hasattr(n, "tree_seqtype"):
            MIXED_RES.add(n.tree_seqtype)
        if hasattr(n, "tree_type"):
            NPR_TREES.append(n.tree_type)
        seq = getattr(n, "sequence", "")
        MAX_SEQ_LEN = max(len(seq), MAX_SEQ_LEN) 

    if MAX_SEQ_LEN:
        ALG_SCALE = min(1, 1000./MAX_SEQ_LEN)
        ts.layout_fn.append(ly_block_alg)
        
    if len(NPR_TREES) > 1:
        rF = RectFace(4, 4, "steelblue", "steelblue")
        rF.margin_right = 10
        rF.margin_left = 10
        ts.legend.add_face(rF, 0)
        ts.legend.add_face(TextFace(" NPR node"), 1)
        ts.legend_position = 3

    if len(MIXED_RES) > 1:
        rF = RectFace(20, 20, "#CFE6CA", "#CFE6CA")
        rF.margin_right = 10
        rF.margin_left = 10
        ts.legend.add_face(rF, 0)
        ts.legend.add_face(TextFace(" Nucleotide based alignment"), 1)
        ts.legend_position = 3
 

    try:
        tree.set_species_naming_function(spname)
        annotate_tree_with_ncbi(tree)
        a = tree.search_nodes(species='Dictyostelium discoideum')[0]
        b = tree.search_nodes(species='Chondrus crispus')[0]
        #out = tree.get_common_ancestor([a, b])
        #out = tree.search_nodes(species='Haemophilus parahaemolyticus')[0].up
        tree.set_outgroup(out)    
        tree.swap_children()
    except Exception:
        pass
    
    tree.render(outfile, tree_style=ts, w=170, units='mm', dpi=150)
    tree.render(outfile+'.svg', tree_style=ts, w=170, units='mm', dpi=150)
    tree.render(outfile+'.pdf', tree_style=ts, w=170, units='mm', dpi=150)
开发者ID:a1an77,项目名称:ete,代码行数:104,代码来源:visualize.py


注:本文中的ete2.TreeStyle.legend_position方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。