Draw one or multiple trees on one plot.
548212
def _draw_trees(trees, nrow=1, ncol=1, rmargin=.3, iopts=None, outdir=".",
    shfile=None, **kwargs):
    
    from jcvi.graphics.tree import draw_tree

    if shfile:
        SHs = DictFile(shfile, delimiter="\t")

    ntrees = len(trees)
    n = nrow * ncol
    for x in xrange(int(ceil(float(ntrees)/n))):
        fig = plt.figure(1, (iopts.w, iopts.h)) if iopts \
              else plt.figure(1, (5, 5))
        root = fig.add_axes([0, 0, 1, 1])

        xiv = 1. / ncol
        yiv = 1. / nrow
        xstart = list(np.arange(0, 1, xiv)) * nrow
        ystart = list(chain(*zip(*[list(np.arange(0, 1, yiv))[::-1]] * ncol)))
        for i in xrange(n*x, n*(x+1)):
            if i == ntrees:
                break
            ax = fig.add_axes([xstart[i%n], ystart[i%n], xiv, yiv])
            f = trees.keys()[i]
            tree = trees[f]
            try:
                SH = SHs[f]
            except:
                SH = None
            draw_tree(ax, tree, rmargin=rmargin, reroot=False, \
                supportcolor="r", SH=SH, **kwargs)

        root.set_xlim(0, 1)
        root.set_ylim(0, 1)
        root.set_axis_off()

        format = iopts.format if iopts else "pdf"
        dpi = iopts.dpi if iopts else 300
        if n == 1:
            image_name = f.rsplit(".", 1)[0] + "." + format
        else:
            image_name = "trees{0}.{1}".format(x, format)
        image_name = op.join(outdir, image_name)
        savefig(image_name, dpi=dpi, iopts=iopts)
        plt.clf()
720065
def plot(self, axis, ith_plot, total_plots, limits):
        
        print(self.plot_type_str.upper() + " plot")
        print("%5s %9s  %s" % ("id", " #points", "group"))

        for idx, group in enumerate(self.groups):
            print("%5s %9s  %s" % (idx + 1, len(self.groups[group]), group))

        print('')

        datasets = []
        colors = []
        minx = np.inf
        maxx = -np.inf

        for idx, group in enumerate(self.groups):
            x = date2num([logevent.datetime
                          for logevent in self.groups[group]])
            minx = min(minx, min(x))
            maxx = max(maxx, max(x))
            datasets.append(x)
            color, marker = self.color_map(group)
            colors.append(color)

        if total_plots > 1:
            # if more than one plot, move histogram to twin axis on the right
            twin_axis = axis.twinx()
            twin_axis.set_ylabel(self.ylabel)
            axis.set_zorder(twin_axis.get_zorder() + 1)  # put ax ahead of ax2
            axis.patch.set_visible(False)  # hide the 'canvas'
            axis = twin_axis

        n_bins = max(1, int((maxx - minx) * 24. * 60. * 60. / self.bucketsize))
        if n_bins > 1000:
            # warning for too many buckets
            print("warning: %i buckets, will take a while to render. "
                  "consider increasing --bucketsize." % n_bins)

        n, bins, artists = axis.hist(datasets, bins=n_bins, align='mid',
                                     log=self.logscale,
                                     histtype="barstacked"
                                     if self.barstacked else "bar",
                                     color=colors, edgecolor="none",
                                     linewidth=0, alpha=0.8, picker=True,
                                     label=map(str, self.groups.keys()))

        # scale current y-axis to match min and max values
        axis.set_ylim(np.min(n), np.max(n))

        # add meta-data for picking
        if len(self.groups) > 1:
            for g, group in enumerate(self.groups.keys()):
                for i in range(len(artists[g])):
                    artists[g][i]._mt_plot_type = self
                    artists[g][i]._mt_group = group
                    artists[g][i]._mt_n = n[g][i]
                    if self.barstacked:
                        artists[g][i]._mt_n -= (n[g - 1][i] if g > 0 else 0)

                    artists[g][i]._mt_bin = bins[i]
        else:
            for i in range(len(artists)):
                artists[i]._mt_plot_type = self
                artists[i]._mt_group = group
                artists[i]._mt_n = n[i]
                artists[i]._mt_bin = bins[i]

        return artists
1245357
def plot(self, bins=250, **kwargs):
        """"""
        # Data #
        counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
        # Linear bins in logarithmic space #
        if 'log' in kwargs.get('x_scale', ''):
            start, stop = numpy.log10(1), numpy.log10(max(counts))
            bins = list(numpy.logspace(start=start, stop=stop, num=bins))
            bins.insert(0, 0)
        # Plot #
        fig = pyplot.figure()
        pyplot.hist(counts, bins=bins, color='gray')
        axes = pyplot.gca()
        # Information #
        title = 'Distribution of the total nucleotide count in the bins'
        axes.set_title(title)
        axes.set_xlabel('Number of nucleotides in a bin')
        axes.set_ylabel('Number of bins with that many nucleotides in them')
        # Save it #
        self.save_plot(fig, axes, **kwargs)
        pyplot.close(fig)
        # For convenience #
        return self
1204111
def _generate_collection(group, ax, ctype, colors):
    ''''''
    color = TREE_COLOR[ctype]

    # generate segment collection
    collection = PolyCollection(group, closed=False, antialiaseds=True,
                                edgecolors='face', facecolors=color)

    # add it to the axes
    ax.add_collection(collection)

    # dummy plot for the legend
    if color not in colors:
        label = str(ctype).replace('NeuriteType.', '').replace('_', ' ').capitalize()
        ax.plot((0., 0.), (0., 0.), c=color, label=label)
        colors.add(color)
749994
def draw_line(
            self, x0:float, y0:float, x1:float, y1:float, *,
            stroke:Color,
            stroke_width:float=1,
            stroke_dash:typing.Sequence=None
            ) -> None:
        """"""
        pass
663835
def draw(args):
    """"""
    if len(args) != 2:
        log.error('Two arguments required: [build target] [output file]')
        app.quit(1)

    target = args[0]
    out = args[1]

    try:
        bb = Butcher()
        bb.load_graph(target)
    except error.BrokenGraph as lolno:
        log.fatal(lolno)
        app.quit(1)

    # Filter down to the target and all of its transitive dependencies.
    # TODO: make it possible to optionally draw the entire graph
    filtered_graph = bb.graph.subgraph(
        networkx.topological_sort(bb.graph, nbunch=[address.new(target)]))

    a = networkx.to_agraph(filtered_graph)
    a.draw(out, prog='dot')
    log.info('Graph written to %s', out)
657997
def draw_lines():
    
    r = numpy.random.randn(200)
    fig = pyplot.figure()
    ax = fig.add_subplot(111)
    ax.plot(r)

    ax.grid(True)

    pyplot.savefig(lines_filename)
512917
def draw(self, X, y, **kwargs):
        
        nan_col_counts = self.get_nan_col_counts()

        # the x locations for the groups
        self.ind = np.arange(len(self.features_))

        if y is None:
            self.ax.barh(self.ind - self.width / 2, nan_col_counts, self.width,
                            color=self.color, label=None)
        else:
            self.draw_stacked_bar(nan_col_counts)
813936
def plotit(self):
        '''
        
        '''
        [self._plot(i) for i in range(len(self.plots))]
21373
def _draw_polygons(self, feature, bg, colour, extent, polygons, xo, yo):
        """"""
        coords = []
        for polygon in polygons:
            coords.append([self._scale_coords(x, y, extent, xo, yo) for x, y in polygon])
        # Polygons are expensive to draw and the buildings layer is huge - so we convert to
        # lines in order to process updates fast enough to animate.
        if "type" in feature["properties"] and "building" in feature["properties"]["type"]:
            for line in coords:
                self._draw_lines_internal(line, colour, bg)
        else:
            self._screen.fill_polygon(coords, colour=colour, bg=bg)
198174
def _generate_dendro(self, current_section, spacing, offsets):
        '''
        '''
        max_dims = self._max_dims
        start_x = _spacingx(current_section, max_dims, offsets[0], spacing[0])

        for child in current_section.children:

            segments = child.points

            # number of leaves in child
            terminations = _n_terminations(child)

            # segement lengths
            seg_lengths = np.linalg.norm(np.subtract(segments[:-1, COLS.XYZ],
                                                     segments[1:, COLS.XYZ]), axis=1)

            # segment radii
            radii = np.vstack((segments[:-1, COLS.R], segments[1:, COLS.R])).T \
                if self._show_diameters else np.zeros((seg_lengths.shape[0], 2))

            y_offset = offsets[1]
            for i, slen in enumerate(seg_lengths):

                # offset update for the vertical segments
                new_offsets = _update_offsets(start_x, spacing, terminations,
                                              (offsets[0], y_offset), slen)

                # segments are drawn vertically, thus only y_offset changes from init offsets
                self._rectangles[self._n] = _vertical_segment((offsets[0], y_offset),
                                                              new_offsets, spacing, radii[i, :])
                self._n += 1
                y_offset = new_offsets[1]

            if y_offset + spacing[1] * 2 + sum(seg_lengths) > max_dims[1]:
                max_dims[1] = y_offset + spacing[1] * 2. + sum(seg_lengths)

            self._max_dims = max_dims
            # recursive call to self.
            self._generate_dendro(child, spacing, new_offsets)

            # update the starting position for the next child
            start_x += terminations * spacing[0]

            # write the horizontal lines only for bifurcations, where the are actual horizontal
            # lines and not zero ones
            if offsets[0] != new_offsets[0]:

                # horizontal segment. Thickness is either 0 if show_diameters is false
                # or 1. if show_diameters is true
                self._rectangles[self._n] = _horizontal_segment(offsets, new_offsets, spacing, 0.)
                self._n += 1
145290
def do_tree(self, line):
        """"""
        opts = self.TREE_OPTS
        line = line.split()
        _pattern = ""

        if not self.current:
            self._help_noontology()
            return

        if len(line) == 0:
            # default contextual behaviour [2016-03-01]
            line = ["classes"]

        if line[0] not in opts:
            self.help_tree()
            return

        elif line[0] == "classes":
            g = self.current['graph']
            if g.all_classes:
                g.printClassTree(showids=False, labels=False, showtype=True)
                self._print("----------------", "TIP")
            else:
                self._print("No classes available.")

        elif line[0] == "properties":
            g = self.current['graph']
            if g.all_properties:
                g.printPropertyTree(showids=False, labels=False, showtype=True)
            else:
                self._print("No properties available.")

        elif line[0] == "concepts":
            g = self.current['graph']
            if g.all_skos_concepts:
                g.printSkosTree(showids=False, labels=False, showtype=True)
            else:
                self._print("No concepts available.")

        else:  # should never arrive here
            pass
66969
def draw(self):
        """"""
        for fig in set(chain(*map(
                lambda arr: arr.psy.plotter.figs2draw, self.with_plotter))):
            self.logger.debug("Drawing figure %s", fig.number)
            fig.canvas.draw()
        for arr in self:
            if arr.psy.plotter is not None:
                arr.psy.plotter._figs2draw.clear()
        self.logger.debug("Done drawing.")
442289
def _draw_feature(self, feature, extent, colour, bg, xo, yo):
        """"""
        geometry = feature["geometry"]
        if geometry["type"] == "Polygon":
            self._draw_polygons(feature, bg, colour, extent, geometry["coordinates"], xo, yo)
        elif feature["geometry"]["type"] == "MultiPolygon":
            for multi_polygon in geometry["coordinates"]:
                self._draw_polygons(feature, bg, colour, extent, multi_polygon, xo, yo)
        elif feature["geometry"]["type"] == "LineString":
            self._draw_lines(bg, colour, extent, geometry["coordinates"], xo, yo)
        elif feature["geometry"]["type"] == "MultiLineString":
            for line in geometry["coordinates"]:
                self._draw_lines(bg, colour, extent, line, xo, yo)
        elif feature["geometry"]["type"] == "Point":
            x, y = self._scale_coords(
                geometry["coordinates"][0], geometry["coordinates"][1], extent, xo, yo)
            text = u" {} ".format(feature["properties"]["name_en"])
            self._screen.print_at(text, int(x - len(text) / 2), int(y), colour=colour, bg=bg)
345958
def plot(self):
        """"""
        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)
1223799
def plot_line(axes, fname, ltype):
    """"""
    x = np.genfromtxt(fname, unpack=True)
    axes.plot(x[0], x[1], ltype)
447254
def visualize(tree, max_level=100, node_width=10, left_padding=5):
    

    height = min(max_level, tree.height()-1)
    max_width = pow(2, height)

    per_level = 1
    in_level  = 0
    level     = 0

    for node in level_order(tree, include_all=True):

        if in_level == 0:
            print()
            print()
            print(' '*left_padding, end=' ')

        width = int(max_width*node_width/per_level)

        node_str = (str(node.data) if node else '').center(width)
        print(node_str, end=' ')

        in_level += 1

        if in_level == per_level:
            in_level   = 0
            per_level *= 2
            level     += 1

        if level > height:
            break

    print()
    print()