Python matplotlib.patches 模块,FancyArrowPatch() 实例源码

我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用matplotlib.patches.FancyArrowPatch()

项目:DnaFeaturesViewer    作者:Edinburgh-Genome-Foundry    | 项目源码 | 文件源码
def plot_feature(self, ax, feature, level, linewidth=1.0):
        """Create an Arrow Matplotlib patch with the feature's coordinates.

        The Arrow points in the direction of the feature's strand.
        If the feature has no direction (strand==0), the returned patch will
        simply be a rectangle.

        The x-coordinates of the patch are determined by the feature's
        `start` and `end` while the y-coordinates are determined by the `level`
        """
        x1, x2 = feature.start, feature.end

        if feature.strand == -1:
            x1, x2 = x2, x1
        head_length = 5 if feature.strand in (-1, 1) else 0.001
        arrowstyle = mpatches.ArrowStyle.Simple(head_width=feature.thickness,
                                                tail_width=feature.thickness,
                                                head_length=head_length)
        y = self.feature_level_width * level
        patch = mpatches.FancyArrowPatch([x1, y], [x2, y],
                                         shrinkA=0.0, shrinkB=0.0,
                                         arrowstyle=arrowstyle,
                                         facecolor=feature.color, zorder=0,
                                         linewidth=feature.linewidth)
        ax.add_patch(patch)
        return patch
项目:rpl-attacks    作者:dhondta    | 项目源码 | 文件源码
def draw_dodag(path):
    """
    This function draws the DODAG (to ./results) from the list of motes (from ./simulation.csc) and the list of
     edges (from ./data/relationships.log).

    :param path: path to the experiment (including [with-|without-malicious])
    """
    pyplot.clf()
    with_malicious = (basename(normpath(path)) == 'with-malicious')
    data, results = join(path, 'data'), join(path, 'results')
    with open(join(data, 'relationships.log')) as f:
        relationships = f.read()
    # first, check if the mote relationships were recorded
    if len(relationships.strip()) == 0:
        return
    # retrieve motes and their colors
    dodag = networkx.DiGraph()
    motes = get_motes_from_simulation(join(path, 'simulation.csc'))
    dodag.add_nodes_from(motes.keys())
    colors = []
    for n, p in motes.items():
        x, y = p
        dodag.node[n]['pos'] = motes[n] = (x, -y)
        colors.append('green' if n == 0 else ('yellow' if not with_malicious or
                                              (with_malicious and 0 < n < len(motes) - 1) else 'red'))
    # retrieve edges from relationships.log
    edges = {}
    for relationship in relationships.split('\n'):
        try:
            d = match(RELATIONSHIP_REGEX, relationship.strip()).groupdict()
            if int(d['flag']) == 0:
                continue
            mote, parent = int(d['mote_id']), int(d['parent_id'])
            edges[mote] = parent
        except AttributeError:
            continue
    # now, fill in the graph with edges
    dodag.add_edges_from(edges.items())
    # finally, draw the graph
    networkx.draw(dodag, motes, node_color=colors, with_labels=True)
    pyplot.savefig(join(results, 'dodag.png'), arrow_style=FancyArrowPatch)
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def streamplot(self, x, y, u, v, *args, **kwargs):
        """
        Draws streamlines of a vector flow.
        (see matplotlib.pyplot.streamplot documentation).

        If ``latlon`` keyword is set to True, x,y are intrepreted as
        longitude and latitude in degrees.  Data and longitudes are
        automatically shifted to match map projection region for cylindrical
        and pseudocylindrical projections, and x,y are transformed to map
        projection coordinates. If ``latlon`` is False (default), x and y
        are assumed to be map projection coordinates.

        Extra keyword ``ax`` can be used to override the default axis instance.

        Other \*args and \**kwargs passed on to matplotlib.pyplot.streamplot.
        """
        if _matplotlib_version < '1.2':
            msg = dedent("""
            streamplot method requires matplotlib 1.2 or higher,
            you have %s""" % _matplotlib_version)
            raise NotImplementedError(msg)
        ax, plt = self._ax_plt_from_kw(kwargs)
        # allow callers to override the hold state by passing hold=True|False
        b = ax.ishold()
        h = kwargs.pop('hold',None)
        if h is not None:
            ax.hold(h)
        try:
            ret =  ax.streamplot(x,y,u,v,*args,**kwargs)
        except:
            ax.hold(b)
            raise
        ax.hold(b)
        if plt is not None and ret.lines.get_array() is not None:
            plt.sci(ret.lines)
        # clip for round polar plots.
        # streamplot arrows not returned in matplotlib 1.1.1, so clip all
        # FancyArrow patches attached to axes instance.
        if self. round:
            ret,c = self._clipcircle(ax,ret)
            for p in ax.patches:
                if isinstance(p,FancyArrowPatch): p.set_clip_path(c)
        # set axes limits to fit map region.
        self.set_axes_limits(ax=ax)
        return ret
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def streamplot(self, x, y, u, v, *args, **kwargs):
        """
        Draws streamlines of a vector flow.
        (see matplotlib.pyplot.streamplot documentation).

        If ``latlon`` keyword is set to True, x,y are intrepreted as
        longitude and latitude in degrees.  Data and longitudes are
        automatically shifted to match map projection region for cylindrical
        and pseudocylindrical projections, and x,y are transformed to map
        projection coordinates. If ``latlon`` is False (default), x and y
        are assumed to be map projection coordinates.

        Extra keyword ``ax`` can be used to override the default axis instance.

        Other \*args and \**kwargs passed on to matplotlib.pyplot.streamplot.
        """
        if _matplotlib_version < '1.2':
            msg = dedent("""
            streamplot method requires matplotlib 1.2 or higher,
            you have %s""" % _matplotlib_version)
            raise NotImplementedError(msg)
        ax, plt = self._ax_plt_from_kw(kwargs)
        # allow callers to override the hold state by passing hold=True|False
        b = ax.ishold()
        h = kwargs.pop('hold',None)
        if h is not None:
            ax.hold(h)
        try:
            ret =  ax.streamplot(x,y,u,v,*args,**kwargs)
        except:
            ax.hold(b)
            raise
        ax.hold(b)
        if plt is not None and ret.lines.get_array() is not None:
            plt.sci(ret.lines)
        # clip for round polar plots.
        # streamplot arrows not returned in matplotlib 1.1.1, so clip all
        # FancyArrow patches attached to axes instance.
        if self. round:
            ret,c = self._clipcircle(ax,ret)
            for p in ax.patches:
                if isinstance(p,FancyArrowPatch): p.set_clip_path(c)
        # set axes limits to fit map region.
        self.set_axes_limits(ax=ax)
        return ret
项目:Labyrinther    作者:olety    | 项目源码 | 文件源码
def _plot_moveset(self, path, bumps, **kwargs):
        if kwargs.get('omit_figures', False) and kwargs.get('ax', None):
            ax = kwargs['ax']
        else:
            f, ax = plt.subplots()
            ax.imshow(self.array_closed, cmap=cm.Greys, origin='upper', zorder=0)

        path_xs, path_ys = Labyrinth._transform_array_into_xy(path)
        bumps_xs, bumps_ys = Labyrinth._transform_array_into_xy(bumps)
        # Plotting
        if kwargs.get('plot', True):
            plots = list()
            plots.append(ax.scatter(bumps_xs, bumps_ys, color='#ff0000', s=(1800 - self.rows * self.cols * 12), alpha=0.1,
                                    marker='^',
                                    zorder=1))
            plots.append(
                ax.scatter(path_xs[0], path_ys[0], color='#ff6a00', s=(2000 - self.rows * self.cols * 15), marker='o',
                           alpha=1, zorder=2, label='start'))
            plots.append(
                ax.scatter(path_xs[-1], path_ys[-1], color='#c447e0', s=(2000 - self.rows * self.cols * 15), marker='X',
                           alpha=1, zorder=2, label='finish'))
            # Marking the goal
            ax.scatter(self.rows * 8 + 4.5, self.cols * 8 + 4.5, color='y', s=(1000 - self.rows * self.cols * 15),
                           marker='D',
                           alpha=1, zorder=2, label='goal')

            for i in range(len(path) - 2, -1, -1):
                p = FancyArrowPatch(posA=[path_xs[i], path_ys[i]], posB=[path_xs[i + 1], path_ys[i + 1]],
                                    connectionstyle='arc3, rad=0.5',
                                    arrowstyle='simple, head_width={}, head_length={}'
                                    .format(30 - (self.rows + self.cols), 25 - (self.rows + self.cols)),
                                    edgecolor='#5f5d63',
                                    facecolor='#42c8f4',
                                    zorder=2 + i)
                plots.append(ax.scatter(path_xs[i + 1], path_ys[i + 1], zorder=2 + i, color='#42c8f4'))
                ax.add_artist(p)
                plots.append(p)


            plt.axis('off')
            plt.title('Moveset')
            plt.title('{}x{}'.format(self.rows, self.cols), loc='right')
            plt.title(kwargs.get('left_title', ''), loc='left')

        return_dict = dict()
        if kwargs.get('show', False):
            plt.show()
        if kwargs.get('savefig', False) and kwargs.get('file_name', ''):
            f.savefig(kwargs['file_name'], dpi=500)
        if kwargs.get('export', False):
            return_dict['fig'] = f
            return_dict['ax'] = ax
        if kwargs.get('export_plots', False):
            return_dict['plots'] = plots
        return return_dict