Python draw tree

27 Python code examples are found related to " draw tree". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: fractal_trees.py    From advancedpython3 with GNU General Public License v3.0 8 votes vote down vote up
def draw_tree(length, width=9):
    color = 'brown'
    if length < 1:
        return
    elif length < 3:
        color = 'green'

    if width < 1:
        width = 1

    turtle.color(color)
    turtle.width(width)
    turtle.forward(length)
    turtle.left(30)
    draw_tree(length / FACTOR, width - 1)
    turtle.right(60)
    draw_tree(length / FACTOR, width - 1)
    turtle.left(30)
    turtle.color(color)
    turtle.width(width)
    turtle.backward(length) 
Example 2
Source File: __init__.py    From msldap with MIT License 6 votes vote down vote up
def draw_tree(node,
              child_iter=lambda n: n.children,
              text_str=str):
    """Support asciitree 0.2 API.

    This function solely exist to not break old code (using asciitree 0.2).
    Its use is deprecated."""
    return LeftAligned(traverse=Traversal(get_text=text_str,
                                          get_children=child_iter),
                       draw=LegacyStyle())(node) 
Example 3
Source File: scrollpanel.py    From MCEdit-Unified with ISC License 6 votes vote down vote up
def draw_tree_cell(self, surf, i, data, cell_rect, column):
        """..."""
        if self.align.lower() == 'r':
            cell_rect.right = self.right - self.margin
            if self.scrollRow.can_scroll_up() or self.scrollRow.can_scroll_down():
                cell_rect.right -= self.scrollRow.scroll_button_size
        elif self.align.lower() == 'c':
            cell_rect.left = self.centerx - (cell_rect.width / 2)
        if isinstance(data, (str, unicode)):
            self.draw_text_cell(surf, i, data, cell_rect, self.align, self.font)
        else:
            self.draw_image_cell(surf, i, data, cell_rect, column) 
Example 4
Source File: mazes.py    From receipt-printer with MIT License 6 votes vote down vote up
def draw_tree(spanning):
	# Create a big array of 0s and 1s for pypng

	pixels = []

	# Add a row of off pixels for the top
	[pixels.append([0]*bl + [1]*bl + ([0] * (img_width-2*bl))) for _ in range(bl)]

	for y in range(GRID_HEIGHT):
		# Row containing nodes
		row = [0] * bl # First column is off
		for x in range(GRID_WIDTH):
			[row.append(1) for _ in range(bl)]
			if x < GRID_WIDTH-1:
				[row.append( int(((x,y),(x+1,y)) in spanning) ) for _ in range(bl)]
		[row.append(0) for _ in range(bl)]
		[pixels.append(row) for _ in range(bl)]

		if y < GRID_HEIGHT-1:
			# Row containing vertical connections between nodes
			row = [0] * bl # First column is off
			for x in range(GRID_WIDTH):
				[row.append( int(((x,y),(x,y+1)) in spanning) ) for _ in range(bl)]
				[row.append(0) for _ in range(bl)]
			[row.append(0) for _ in range(bl)]
			[pixels.append(row) for _ in range(bl)]

	# Add a row of off pixels for the bottom
	[pixels.append(([0] * (img_width-2*bl)) + [1] * bl + [0] * bl) for _ in range(bl)]

	return pixels

# Handle arguments 
Example 5
Source File: chartparser_app.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def draw_tree(self, edge=None):
        if edge is None and self._treetoks_edge is None:
            return
        if edge is None:
            edge = self._treetoks_edge

        # If it's a new edge, then get a new list of treetoks.
        if self._treetoks_edge != edge:
            self._treetoks = [t for t in self._chart.trees(edge) if isinstance(t, Tree)]
            self._treetoks_edge = edge
            self._treetoks_index = 0

        # Make sure there's something to draw.
        if len(self._treetoks) == 0:
            return

        # Erase the old tree.
        for tag in self._tree_tags:
            self._tree_canvas.delete(tag)

        # Draw the new tree.
        tree = self._treetoks[self._treetoks_index]
        self._draw_treetok(tree, edge.start())

        # Show how many trees are available for the edge.
        self._draw_treecycle()

        # Update the scroll region.
        w = self._chart.num_leaves() * self._unitsize + 2 * ChartView._MARGIN
        h = tree.height() * (ChartView._TREE_LEVEL_SIZE + self._text_height)
        self._tree_canvas['scrollregion'] = (0, 0, w, h) 
Example 6
Source File: trees.py    From antismash with GNU Affero General Public License v3.0 6 votes vote down vote up
def draw_tree(input_number: int, output_dir: str, tag: str) -> str:
    """ Construct a PNG for display via fasttree

        Returns:
            the filename of the image generated
    """
    matplotlib.use('Agg')
    command = ["fasttree", "-quiet", "-fastest", "-noml", "trimmed_alignment%d.fasta" % input_number]
    run_result = subprocessing.execute(command)
    if not run_result.successful():
        raise RuntimeError("Fasttree failed to run successfully:", run_result.stderr)

    handle = StringIO(run_result.stdout)
    tree_filename = os.path.join(output_dir, tag + '.png')
    try:
        tree = Phylo.read(handle, 'newick')
    except NewickError:
        logging.debug('Invalid newick tree for %r', tag)
        return ''

    # enforce a minimum distance between branches
    max_size = max(tree.distance(node) for node in tree.get_terminals())
    for clade in tree.get_nonterminals() + tree.get_terminals():
        if not clade.branch_length:
            clade.branch_length = max_size / 20
        else:
            clade.branch_length = abs(clade.branch_length) + max_size / 20
    # change the colour of the query gene
    label_colors = {tag: 'green'}

    Phylo.draw(tree, do_show=False, label_colors=label_colors,
               label_func=lambda node: str(node).replace("|", " "))
    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(20, (tree.count_terminals() / 3))
    matplotlib.pyplot.axis('off')
    fig.savefig(os.path.join(output_dir, tag + '.png'), bbox_inches='tight')
    matplotlib.pyplot.close(fig)
    return tree_filename 
Example 7
Source File: fp_tree.py    From pyFP-Tree with MIT License 6 votes vote down vote up
def Draw_tree(node,prefix,isTail):#Draw a tree
	if(isTail):
		temp=prefix+"└── "+node.item
	else:
		temp=prefix+"├── "+node.item
	print temp
	for n in range(0,len(node.children)-1):
		if(isTail):
			Draw_tree(node.children[n],prefix+"    ",False)
		else:
			Draw_tree(node.children[n],prefix+"│   ",False)
	if(len(node.children)>=1):
		if(isTail):
			prefix=prefix+"    "
		else:
			prefix=prefix+"│   "
		Draw_tree(node.children[-1],prefix,True) 
Example 8
Source File: example.py    From random-forest-leaf-visualization with MIT License 6 votes vote down vote up
def draw_tree(ensemble, tree_id=0):

    plt.figure(figsize=(8,8))
    plt.subplot(211)

    tree = ensemble.estimators_[tree_id].tree_

    depths = leaf_depths(tree)
    plt.hist(depths, histtype='step', color='#9933ff', 
             bins=range(min(depths), max(depths)+1))

    plt.xlabel("Depth of leaf nodes (tree %s)" % tree_id)
    
    plt.subplot(212)
    
    samples = leaf_samples(tree)
    plt.hist(samples, histtype='step', color='#3399ff', 
             bins=range(min(samples), max(samples)+1))
    
    plt.xlabel("Number of samples in leaf nodes (tree %s)" % tree_id)
    
    plt.show() 
Example 9
Source File: human.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def draw_tree(self, origin: int):
        """

        :param origin:
        :type origin:
        :return:
        :rtype:
        """
        tree_data = self.to_tree(origin)
        tree_out = yaml.safe_dump(tree_data, default_flow_style=False)
        return tree_out 
Example 10
Source File: chartparser_app.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def draw_tree(self, edge=None):
        if edge is None and self._treetoks_edge is None: return
        if edge is None: edge = self._treetoks_edge

        # If it's a new edge, then get a new list of treetoks.
        if self._treetoks_edge != edge:
            self._treetoks = [t for t in self._chart.trees(edge)
                              if isinstance(t, Tree)]
            self._treetoks_edge = edge
            self._treetoks_index = 0

        # Make sure there's something to draw.
        if len(self._treetoks) == 0: return

        # Erase the old tree.
        for tag in self._tree_tags: self._tree_canvas.delete(tag)

        # Draw the new tree.
        tree = self._treetoks[self._treetoks_index]
        self._draw_treetok(tree, edge.start())

        # Show how many trees are available for the edge.
        self._draw_treecycle()

        # Update the scroll region.
        w = self._chart.num_leaves()*self._unitsize+2*ChartView._MARGIN
        h = tree.height() * (ChartView._TREE_LEVEL_SIZE+self._text_height)
        self._tree_canvas['scrollregion'] = (0, 0, w, h) 
Example 11
Source File: draw_tree.py    From VCTree-Scene-Graph-Generation with MIT License 6 votes vote down vote up
def draw_tree_region(tree, image, example_id):
    """
    tree: A tree structure
    image: origin image batch [batch_size, 3, IM_SIZE, IM_SIZE]
    output: a image display regions in a tree structure
    """
    sample_image = image[tree.im_idx].view(image.shape[1:]).clone()
    sample_image = (revert_normalize(sample_image) * 255).int()
    sample_image = torch.clamp(sample_image, 0, 255)
    sample_image = sample_image.permute(1,2,0).contiguous().data.cpu().numpy().astype(dtype = np.uint8)

    global tree_max_depth

    depth = min(tree.max_depth(), tree_max_depth)
    tree_img = create_tree_img(depth, 64)
    tree_img = write_cell(sample_image, tree_img, (0,0,tree_img.shape[1], tree_img.shape[0]), tree, 64)

    im = Image.fromarray(sample_image, 'RGB')
    tree_img = Image.fromarray(tree_img, 'RGB')
    im.save('./output/example/'+str(example_id)+'_origin'+'.jpg')
    tree_img.save('./output/example/'+str(example_id)+'_tree'+'.jpg')

    if example_id % 200 == 0:
        print('saved img ' + str(example_id)) 
Example 12
Source File: draw_tree.py    From VCTree-Scene-Graph-Generation with MIT License 6 votes vote down vote up
def draw_tree_region_v2(tree, image, example_id, pred_labels):
    """
    tree: A tree structure
    image: origin image batch [batch_size, 3, IM_SIZE, IM_SIZE]
    output: a image with roi bbox, the color of box correspond to the depth of roi node
    """
    sample_image = image[tree.im_idx].view(image.shape[1:]).clone()
    sample_image = (revert_normalize(sample_image) * 255).int()
    sample_image = torch.clamp(sample_image, 0, 255)
    sample_image = sample_image.permute(1,2,0).contiguous().data.cpu().numpy().astype(dtype = np.uint8)
    sample_image = Image.fromarray(sample_image, 'RGB').convert("RGBA")

    draw = ImageDraw.Draw(sample_image)
    draw_box(draw, tree, pred_labels)
    
    sample_image.save('./output/example/'+str(example_id)+'_box'+'.png')

    #print('saved img ' + str(example_id)) 
Example 13
Source File: chart.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def draw_tree(self, edge=None):
        if edge is None and self._treetoks_edge is None: return
        if edge is None: edge = self._treetoks_edge
        
        # If it's a new edge, then get a new list of treetoks.
        if self._treetoks_edge != edge:
            self._treetoks = [t for t in self._chart.trees(edge)
                              if isinstance(t, Tree)]
            self._treetoks_edge = edge
            self._treetoks_index = 0

        # Make sure there's something to draw.
        if len(self._treetoks) == 0: return

        # Erase the old tree.
        for tag in self._tree_tags: self._tree_canvas.delete(tag)

        # Draw the new tree.
        tree = self._treetoks[self._treetoks_index]
        self._draw_treetok(tree, edge.start())

        # Show how many trees are available for the edge.
        self._draw_treecycle()

        # Update the scroll region.
        w = self._chart.num_leaves()*self._unitsize+2*ChartView._MARGIN
        h = tree.height() * (ChartView._TREE_LEVEL_SIZE+self._text_height)
        self._tree_canvas['scrollregion'] = (0, 0, w, h) 
Example 14
Source File: scrollpanel.py    From GDMC with ISC License 6 votes vote down vote up
def draw_tree_cell(self, surf, i, data, cell_rect, column):
        """..."""
        if self.align.lower() == 'r':
            cell_rect.right = self.right - self.margin
            if self.scrollRow.can_scroll_up() or self.scrollRow.can_scroll_down():
                cell_rect.right -= self.scrollRow.scroll_button_size
        elif self.align.lower() == 'c':
            cell_rect.left = self.centerx - (cell_rect.width / 2)
        if type(data) in (str, unicode):
            self.draw_text_cell(surf, i, data, cell_rect, self.align, self.font)
        else:
            self.draw_image_cell(surf, i, data, cell_rect, column) 
Example 15
Source File: svm_utils.py    From ilf with Apache License 2.0 6 votes vote down vote up
def draw_wstate_tree(svm):
    import matplotlib.pyplot as plt
    import networkx as nx
    from networkx.drawing.nx_agraph import write_dot, graphviz_layout

    G = nx.DiGraph()
    pending_list = [svm.root_wstate]
    while len(pending_list):
        root = pending_list.pop()
        for trace, children in root.trace_to_children.items():
            for c in children:
                G.add_edge(repr(root), repr(c), label=trace)
                pending_list.append(c)
    # pos = nx.spring_layout(G)
    pos = graphviz_layout(G, prog='dot')
    edge_labels = nx.get_edge_attributes(G, 'label')
    nx.draw(G, pos)
    nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8)
    nx.draw_networkx_labels(G, pos, font_size=10)
    plt.show() 
Example 16
Source File: ft.py    From addons-source with GNU General Public License v2.0 6 votes vote down vote up
def draw_tree(head):
    ctx.select_font_face(font_name)
    ctx.set_font_size(base_font_size)
    ctx.set_line_width(2)
    ctx.set_line_cap(cairo.LINE_CAP_SQUARE)
    ctx.set_line_join(cairo.LINE_JOIN_MITER)
    set_line_style(ctx)
    head.draw() 
Example 17
Source File: tiny_gp_plus.py    From tiny_gp with GNU General Public License v3.0 6 votes vote down vote up
def draw_tree(self, fname, footer):
        dot = [Digraph()]
        dot[0].attr(kw='graph', label = footer)
        count = [0]
        self.draw(dot, count)
        Source(dot[0], filename = fname + ".gv", format="png").render()
        display(Image(filename = fname + ".gv.png")) 
Example 18
Source File: pgm_viz.py    From ibeis with Apache License 2.0 6 votes vote down vote up
def draw_junction_tree(model, fnum=None, **kwargs):
    import plottool_ibeis as pt
    fnum = pt.ensure_fnum(fnum)
    pt.figure(fnum=fnum)
    ax = pt.gca()
    from pgmpy.models import JunctionTree
    if not isinstance(model, JunctionTree):
        netx_graph = model.to_junction_tree()
    else:
        netx_graph = model
    # prettify nodes
    def fixtupkeys(dict_):
        return {
            ', '.join(k) if isinstance(k, tuple) else k: fixtupkeys(v)
            for k, v in dict_.items()
        }
    n = fixtupkeys(netx_graph.nodes)
    e = fixtupkeys(netx_graph.edge)
    a = fixtupkeys(netx_graph.adj)
    netx_graph.nodes = n
    netx_graph.edge = e
    netx_graph.adj = a
    #netx_graph = model.to_markov_model()
    #pos = nx.nx_agraph.pygraphviz_layout(netx_graph)
    #pos = nx.nx_agraph.graphviz_layout(netx_graph)
    pos = nx.pydot_layout(netx_graph)
    node_color = [pt.NEUTRAL] * len(pos)
    drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color,
                  node_size=2000)
    nx.draw(netx_graph, **drawkw)
    if kwargs.get('show_title', True):
        pt.set_figtitle('Junction / Clique Tree / Cluster Graph') 
Example 19
Source File: Factory.py    From parliament2 with Apache License 2.0 6 votes vote down vote up
def DrawDecisionTree(fac, datasetName, methodName):
    m = GetMethodObject(fac, datasetName, methodName)
    if m==None:
        return None
    tr = TreeReader(str(m.GetWeightFileName()))

    variables = tr.getVariables();

    def clicked(b):
        if treeSelector.value>tr.getNTrees():
            treeSelector.value = tr.getNTrees()
        clear_output()
        toJs = {
            "variables": variables,
            "tree": tr.getTree(treeSelector.value)
        }
        json_str = json.dumps(toJs)
        JPyInterface.JsDraw.Draw(json_str, "drawDecisionTree", True)

    mx = str(tr.getNTrees()-1)

    treeSelector = widgets.IntText(value=0, font_weight="bold")
    drawTree     = widgets.Button(description="Draw", font_weight="bold")
    label        = widgets.HTML("<div style='padding: 6px;font-weight:bold;color:#333;'>Decision Tree [0-"+mx+"]:</div>")

    drawTree.on_click(clicked)
    container = widgets.HBox([label,treeSelector, drawTree])
    display(container)

## This function puts the main thread to sleep until data points for tracking plots appear.
# @param m Method object
# @param sleep_time default sleeping time 
Example 20
Source File: demo_plotter.py    From momi2 with GNU General Public License v3.0 5 votes vote down vote up
def draw_tree(self, tree_color="C0", alpha=1.0):
        """Draw the demographic tree (without pulse migrations)

        :param str tree_color: Color of the tree
        :param float alpha: Transparency

        """
        # draw vertical lines
        for popname, popline in self._plot.pop_lines.items():
            x = [self.x_pos[popname]]*len(popline.points)
            t = [p.t for p in popline.points]
            xt = list(zip(x, t))

            is_ghost = [False for _ in popline.points]
            for i, p in enumerate(popline.points):
                if p.is_leaf:
                    for j in range(i):
                        is_ghost[j] = True

            for bottom, top, N, ghost in zip(
                    xt[:-1], xt[1:],
                    [p.N for p in popline.points[:-1]],
                    is_ghost):
                curr_x, curr_t = zip(bottom, top)

                if ghost:
                    linestyle = ":"
                else:
                    linestyle = "-"

                self.ax.plot(
                    curr_x, curr_t, color=tree_color,
                    linewidth=self.N_to_linewidth(N),
                    linestyle=linestyle,
                    alpha=alpha, zorder=1)

        # draw horizontal lines
        for arrow in self._plot.pop_arrows:
            if arrow.p != 1:
                continue
            self.ax.plot(
                (arrow.from_pop.x, arrow.to_pop.x),
                (arrow.t, arrow.t), color=tree_color,
                linewidth=self.N_to_linewidth(arrow.from_N),
                alpha=alpha) 
Example 21
Source File: tree.py    From Hermit with MIT License 5 votes vote down vote up
def drawTree(**p):
	if p['depth'] < p['maxdepth']:

		if p['height'] <1:return

		dep = p['depth']
		p['width'] *= p['dwidth'](dep)


		x0 = p['x']+math.cos(p['angle'])*p['trunk']
		y0 = p['y']-math.sin(p['angle'])*p['trunk']
		u.line(p['surf'],p['color'],[p['x'],p['y']],[x0,y0],p['width'])


		p['width'] *= p['dwidth'](dep)
		a1 = p['angle']-p['opening']*p['dopening'](dep)
		a2 = p['angle']+p['opening']*p['dopening'](dep)

		h1 = p['height'] * p['dheight'](dep)
		x1 = x0+math.cos(a1)*h1
		y1 = y0-math.sin(a1)*h1

		h2 = p['height'] * p['dheight'](dep)
		x2 = x0+math.cos(a2)*h2
		y2 = y0-math.sin(a2)*h2

		#u.text(p['surf'],x1,y1,str(dep),(0,150,0))
		#u.text(p['surf'],x2,y2,str(dep),(0,150,0))

		u.line(p['surf'],p['color'],[x0,y0],[x1,y1],p['width'])
		u.line(p['surf'],p['color'],[x0,y0],[x2,y2],p['width'])


		p['trunk'] *= p['dtrunk'](dep)

		p['depth'] += .5
		p['x'],p['y'],p['height'],p['angle'] = x1,y1,h1,a1-p['dangle'](dep)

		drawTree(**p)


		p['depth'] += .5
		p['x'],p['y'],p['height'],p['angle'] = x2,y2,h2,a2+p['dangle'](dep)
		drawTree(**p)
	else:
		return 
Example 22
Source File: GLViewWidget.py    From soapy with GNU General Public License v3.0 5 votes vote down vote up
def drawItemTree(self, item=None, useItemNames=False):
        if item is None:
            items = [x for x in self.items if x.parentItem() is None]
        else:
            items = item.childItems()
            items.append(item)
        items.sort(key=lambda a: a.depthValue())
        for i in items:
            if not i.visible():
                continue
            if i is item:
                try:
                    glPushAttrib(GL_ALL_ATTRIB_BITS)
                    if useItemNames:
                        glLoadName(i._id)
                        self._itemNames[i._id] = i
                    i.paint()
                except:
                    from .. import debug
                    debug.printExc()
                    msg = "Error while drawing item %s." % str(item)
                    ver = glGetString(GL_VERSION)
                    if ver is not None:
                        ver = ver.split()[0]
                        if int(ver.split(b'.')[0]) < 2:
                            print(msg + " The original exception is printed above; however, pyqtgraph requires OpenGL version 2.0 or greater for many of its 3D features and your OpenGL version is %s. Installing updated display drivers may resolve this issue." % ver)
                        else:
                            print(msg)
                    
                finally:
                    glPopAttrib()
            else:
                glMatrixMode(GL_MODELVIEW)
                glPushMatrix()
                try:
                    tr = i.transform()
                    a = np.array(tr.copyDataTo()).reshape((4,4))
                    glMultMatrixf(a.transpose())
                    self.drawItemTree(i, useItemNames=useItemNames)
                finally:
                    glMatrixMode(GL_MODELVIEW)
                    glPopMatrix() 
Example 23
Source File: AnFany_pm2.5_Tree.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 5 votes vote down vote up
def draw_tree(shujuji, result, guize, guanxi, zian=ziduan):
    # 字符串内容
    strziu = dingyistr(shujuji, result, guize, guanxi, zian)
    # 节点的位置
    weihzi = jiedian_location(guanxi)

    noyye = noye_node(guanxi)

    # 画布的设置
    huab = huabu(guanxi)[1] + 2  # 上下左右预留空间

    fig, ax = plt.subplots(figsize=(huab, huab))
    # 开始绘制
    for jj in allnodes(guanxi):
        print(jj)
        # 绘制所有的节点要展示的内容
        # 内部节点
        if jj in noyye:
            ax.text(weihzi[jj][0], weihzi[jj][1], strziu[0][jj], size=13, rotation=0.,
                    ha="center", va="center",
                    bbox=dict(boxstyle="round",
                              ec=(0.6, 0.2, 0.6),
                              fc=(0.3, 0.6, 0.3),
                              )
                    )
        # 叶子节点
        else:
            ax.text(weihzi[jj][0], weihzi[jj][1], strziu[0][jj], size=13, rotation=0.,
                    ha="center", va="center",
                    bbox=dict(boxstyle="round",
                              ec=(0.2, 0.5, 0.2),
                              fc=(0.5, 0.2, 0.5),
                              )
                    )

        # 只对内部节点绘制箭头和左右的分类规则
        if jj in noyye:
            # 添加左右箭头

            ax.annotate(' ', xy=(weihzi[jj + 'r'][0], weihzi[jj + 'r'][1]), xytext=(weihzi[jj][0], weihzi[jj][1]), ha="center", va="center",
                        arrowprops=dict(facecolor='darkred', shrink=0.128))

            ax.annotate(' ', xy=(weihzi[jj + 'l'][0], weihzi[jj + 'l'][1]), xytext=(weihzi[jj][0], weihzi[jj][1]),
                        ha="center", va="center", arrowprops=dict(facecolor='darkred', shrink=0.128))


            # 添加左右规则
            ax.text((weihzi[jj + 'l'][0] + weihzi[jj][0]) / 2, \
                    (weihzi[jj + 'l'][1] + weihzi[jj][1]) / 2 - 0.2, strziu[1][jj + 'l'], fontsize=12, color='red', weight='bold')

            ax.text((weihzi[jj + 'r'][0] + weihzi[jj][0]) / 2, \
                    (weihzi[jj + 'r'][1] + weihzi[jj][1]) / 2 - 0.2, strziu[1][jj + 'r'], fontsize=12, color='red', weight='bold')

    ax.set(xlim=(0, huab), ylim=(0, huab))

    plt.show()

# 根据不同的深度。看精确率的变化 
Example 24
Source File: twisst_node_depth.py    From twisst with GNU General Public License v3.0 5 votes vote down vote up
def drawTree(tree, leafPos = None, depthDict = None, depthRangeDict=None, extendTips=False, rootIsZero=False,
             show=True, posMethod=1, col="black",linewidth=2,alpha=1,direction="down",taxColDict=None):
    tree = tree.copy("newick")
    
    #get node depths
    for node in tree.traverse():
        if depthDict is None: node.add_feature("depth", node.get_distance(tree))
        else: node.add_feature("depth", depthDict[node.name])
    
    #extend tips to align them if needed
    if extendTips:
        maxDP = max([l.depth for l in tree.iter_leaves()])
        for l in tree.iter_leaves(): l.depth = maxDP
    
    #adjust depths so that they are aligned at zero
    if not rootIsZero:
        maxDP = max([l.depth for l in tree.iter_leaves()])
        for node in tree.traverse():
            node.depth -= maxDP
    
    #set leaf positions
    if leafPos is None:
        leafNames = [l.name for l in tree.get_leaves()]
        leafPos = dict(zip(leafNames,range(len(leafNames))))
    
    for leaf in tree.iter_leaves(): leaf.add_feature("pos", leafPos[leaf.name])
    
    #set positions for all other nodes relative to their children
    for node in tree.traverse(strategy="postorder"):
        if not node.is_leaf():
            node.add_feature("pos", getNodePos(node,method=posMethod))
        
    #draw
    for node in tree.traverse():
        if direction is "down":
            plt.setp(plt.gca(),xticks=[])
            for child in node.get_children():
                plt.plot([node.pos,child.pos],[node.depth,child.depth],color=col,linewidth=linewidth,alpha=alpha, solid_capstyle="round")
                if depthRangeDict:
                    plt.plot([node.pos]*2,depthRangeDict[node.name],color=col,linewidth=1,alpha=alpha, solid_capstyle="round")
                    plt.plot([node.pos-.1,node.pos+.1],[node.depth]*2,color=col,linewidth=1,alpha=alpha, solid_capstyle="round")
            
            if node.is_leaf(): plt.text(node.pos, node.depth - 0.1, node.name,
                                        horizontalalignment='center', verticalalignment='center',
                                        color=taxColDict[node.name] if taxColDict else "black")
        
        else:
            plt.setp(plt.gca(),yticks=[])
            for child in node.get_children():
                plt.plot([node.depth,child.depth],[node.pos,child.pos],color=col,linewidth=linewidth,alpha=alpha, solid_capstyle="round")
                if depthRangeDict:
                    plt.plot(depthRangeDict[node.name],[node.pos]*2,color=col,linewidth=1,alpha=alpha, solid_capstyle="round")
                    plt.plot([node.depth]*2,[node.pos-.1,node.pos+.1],color=col,linewidth=1,alpha=alpha, solid_capstyle="round")
            
            if node.is_leaf(): plt.text(node.depth - 0.1, node.pos, node.name,
                                        horizontalalignment='left', verticalalignment='center',
                                        color=taxColDict[node.name] if taxColDict else "black")
    
    if show: plt.show() 
Example 25
Source File: bayes.py    From ibeis with Apache License 2.0 4 votes vote down vote up
def draw_tree_model(model, **kwargs):
    import plottool_ibeis as pt
    import networkx as netx
    if not ut.get_argval('--hackjunc'):
        fnum = pt.ensure_fnum(None)
        fig = pt.figure(fnum=fnum, doclf=True)  # NOQA
        ax = pt.gca()
        #name_nodes = sorted(ut.list_getattr(model.ttype2_cpds[NAME_TTYPE], 'variable'))
        netx_graph = model.to_markov_model()
        #pos = netx.pygraphviz_layout(netx_graph)
        #pos = netx.graphviz_layout(netx_graph)
        #pos = get_hacked_pos(netx_graph, name_nodes, prog='neato')
        pos = netx.nx_pydot.pydot_layout(netx_graph)
        node_color = [pt.WHITE] * len(pos)
        drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color,
                      node_size=1100)
        netx.draw(netx_graph, **drawkw)
        if kwargs.get('show_title', True):
            pt.set_figtitle('Markov Model')

    if not ut.get_argval('--hackmarkov'):
        fnum = pt.ensure_fnum(None)
        fig = pt.figure(fnum=fnum, doclf=True)  # NOQA
        ax = pt.gca()
        netx_graph = model.to_junction_tree()
        # prettify nodes
        def fixtupkeys(dict_):
            return {
                ', '.join(k) if isinstance(k, tuple) else k: fixtupkeys(v)
                for k, v in dict_.items()
            }
        # FIXME
        n = fixtupkeys(netx_graph.node)
        e = fixtupkeys(netx_graph.edge)
        a = fixtupkeys(netx_graph.adj)
        netx_graph.nodes.update(n)
        netx_graph.edges.update(e)
        netx_graph.adj.update(a)
        #netx_graph = model.to_markov_model()
        #pos = netx.pygraphviz_layout(netx_graph)
        #pos = netx.graphviz_layout(netx_graph)
        pos = netx.nx_pydot.pydot_layout(netx_graph)
        node_color = [pt.WHITE] * len(pos)
        drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color,
                      node_size=2000)
        netx.draw(netx_graph, **drawkw)
        if kwargs.get('show_title', True):
            pt.set_figtitle('Junction/Clique Tree / Cluster Graph')