示例#1
0
 def plot_prior_dates(self, dwidth=30, ax=None):
     """Plot prior chronology dates in age-depth plot"""
     if ax is None:
         ax = plt.gca()
     depth, probs = self.prior_dates()
     pat = []
     for i, d in enumerate(depth):
         p = probs[i]
         z = np.array([p[:, 0],
                       dwidth * p[:, 1] / np.sum(p[:, 1])])  # Normalize
         z = z[:, z[0].argsort(
             kind='mergesort')]  # np.interp requires `xp` arg to be sorted
         zy = np.linspace(np.min(z[0]), np.max(z[0]), num=200)
         zp = np.interp(x=zy, xp=z[0], fp=z[1])
         pol = np.vstack([
             np.concatenate([d + zp, d - zp[::-1]]),
             np.concatenate([zy, zy[::-1]])
         ])
         pat.append(Polygon(pol.T))
     p = PatchCollection(pat)
     p.set_label('Prior dates')
     ax.add_collection(p)
     ax.autoscale_view()
     ax.set_ylabel('Age (cal yr BP)')
     ax.set_xlabel('Depth (cm)')
     ax.grid(True)
     return ax
示例#2
0
def draw_control_z_gate(axes, gate_pos, wire_pos1, wire_pos2, plot_params):
    """
    Draw the symbol for a controlled-Z gate.

    Args:
        axes (matplotlib.axes.Axes): axes object
        wire_pos (float): x coordinate of the gate [data units]
        y1 (float): y coordinate of the 1st qubit wire
        y2 (float): y coordinate of the 2nd qubit wire
        plot_params (dict): plot parameters
    """
    gate = PatchCollection(
        [
            Circle((gate_pos, wire_pos1),
                   plot_params['control_radius'],
                   fill=True),
            Circle((gate_pos, wire_pos2),
                   plot_params['control_radius'],
                   fill=True),
            Line2D((gate_pos, gate_pos), (wire_pos1, wire_pos2)),
        ],
        edgecolors='k',
        facecolors='k',
        linewidths=plot_params['linewidth'],
    )
    gate.set_label('CZ')
    axes.add_collection(gate)
示例#3
0
    def plot_segmentlist(self, segmentlist, y=None, collection=True,
                         label=None, rasterized=None, **kwargs):
        """Plot a :class:`~gwpy.segments.SegmentList` onto these axes

        Parameters
        ----------
        segmentlist : :class:`~gwpy.segments.SegmentList`
            list of segments to display
        y : `float`, optional
            y-axis value for new segments
        collection : `bool`, default: `True`
            add all patches as a
            :class:`~matplotlib.collections.PatchCollection`, doesn't seem
            to work for hatched rectangles
        label : `str`, optional
            custom descriptive name to print as y-axis tick label
        **kwargs
            any other keyword arguments acceptable for
            :class:`~matplotlib.patches.Rectangle`

        Returns
        -------
        collection : :class:`~matplotlib.patches.PatchCollection`
            list of :class:`~matplotlib.patches.Rectangle` patches
        """
        if y is None:
            y = self.get_next_y()
        patches = []
        for seg in segmentlist:
            patches.append(self.build_segment(seg, y, **kwargs))
        try:
            if not self.epoch:
                self.set_epoch(segmentlist[0][0])
            else:
                self.set_epoch(min(self.epoch, segmentlist[0][0]))
        except IndexError:
            pass
        if collection:
            coll = PatchCollection(patches, len(patches) != 0)
            coll.set_rasterized(rasterized)
            if label is not None:
                coll.set_label(rUNDERSCORE.sub(r'\_', str(label)))
            if collection == 'ignore':
                coll._ignore = True
            else:
                coll._ignore = False
            coll._ypos = y
            out = self.add_collection(coll)
        else:
            out = []
            for p in patches:
                p.set_label(label)
                p.set_rasterized(rasterized)
                label = ''
                out.append(self.add_patch(p))
        self.autoscale(axis='y')
        return out
示例#4
0
def draw_measure_gate(axes, gate_pos, wire_pos, plot_params):
    """
    Draw a measurement gate.

    Args:
        axes (AxesSubplot): axes object
        gate_pos (float): x coordinate of the gate [data units]
        wire_pos (float): y coordinate of the qubit wire
        plot_params (dict): plot parameters
    """
    # pylint: disable=invalid-name

    width = plot_params['mgate_width']
    height = 0.9 * width
    y_ref = wire_pos - 0.3 * height

    # Cannot use PatchCollection for the arc due to bug in matplotlib code...
    arc = Arc(
        (gate_pos, y_ref),
        width * 0.7,
        height * 0.8,
        theta1=0,
        theta2=180,
        ec='k',
        fc='w',
        zorder=5,
    )
    axes.add_patch(arc)

    patches = [
        Rectangle((gate_pos - width / 2, wire_pos - height / 2),
                  width,
                  height,
                  fill=True),
        Line2D(
            (gate_pos, gate_pos + width * 0.35),
            (y_ref, wire_pos + height * 0.35),
            color='k',
            linewidth=1,
        ),
    ]

    gate = PatchCollection(
        patches,
        edgecolors='k',
        facecolors='w',
        linewidths=plot_params['linewidth'],
        zorder=5,
    )
    gate.set_label('Measure')
    axes.add_collection(gate)
示例#5
0
    def plot_segmentlist(self,
                         segmentlist,
                         y=None,
                         collection=True,
                         label=None,
                         **kwargs):
        """Plot a :class:`~gwpy.segments.SegmentList` onto these axes

        Parameters
        ----------
        segmentlist : :class:`~gwpy.segments.SegmentList`
            list of segments to display
        y : `float`, optional
            y-axis value for new segments
        collection : `bool`, default: `True`
            add all patches as a
            :class:`~matplotlib.collections.PatchCollection`, doesn't seem
            to work for hatched rectangles
        label : `str`, optional
            custom descriptive name to print as y-axis tick label
        **kwargs
            any other keyword arguments acceptable for
            :class:`~matplotlib.patches.Rectangle`

        Returns
        -------
        collection : :class:`~matplotlib.patches.PatchCollection`
            list of :class:`~matplotlib.patches.Rectangle` patches
        """
        if y is None:
            y = len(self.collections)
        patches = []
        for seg in segmentlist:
            patches.append(self.build_segment(seg, y, **kwargs))
        try:
            if not self.epoch:
                self.set_epoch(segmentlist[0][0])
            else:
                self.set_epoch(min(self.epoch, segmentlist[0][0]))
        except IndexError:
            pass
        if collection:
            coll = PatchCollection(patches, len(patches) != 0)
            coll.set_label(rUNDERSCORE.sub(r'\_', label))
            self.add_collection(coll)
        else:
            out = []
            for p in patches:
                out.append(self.add_patch(p))
            return out
示例#6
0
def draw_x_gate(axes, gate_pos, wire_pos, plot_params):
    """
    Draws the symbol for a X/NOT gate.

    Args:
        axes (matplotlib.axes.Axes): axes object
        gate_pos (float): x coordinate of the gate [data units]
        wire_pos (float): y coordinate of the qubit wire [data units]
        plot_params (dict): plot parameters
    """
    not_radius = plot_params['not_radius']

    gate = PatchCollection([
        Circle((gate_pos, wire_pos), not_radius, fill=False),
        Line2D((gate_pos, gate_pos),
               (wire_pos - not_radius, wire_pos + not_radius))
    ],
                           edgecolors='k',
                           facecolors='w',
                           linewidths=plot_params['linewidth'])
    gate.set_label('NOT')
    axes.add_collection(gate)
示例#7
0
文件: segments.py 项目: rpfisher/gwpy
    def plot_segmentlist(self, segmentlist, y=None, collection=True,
                         label=None, rasterized=None, **kwargs):
        """Plot a `~gwpy.segments.SegmentList` onto these axes

        Parameters
        ----------
        segmentlist : `~gwpy.segments.SegmentList`
            list of segments to display
        y : `float`, optional
            y-axis value for new segments
        collection : `bool`, default: `True`
            add all patches as a
            `~matplotlib.collections.PatchCollection`, doesn't seem
            to work for hatched rectangles
        label : `str`, optional
            custom descriptive name to print as y-axis tick label
        **kwargs
            any other keyword arguments acceptable for
            `~matplotlib.patches.Rectangle`

        Returns
        -------
        collection : `~matplotlib.patches.PatchCollection`
            list of `~matplotlib.patches.Rectangle` patches
        """
        if y is None:
            y = self.get_next_y()
        patches = []
        for seg in segmentlist:
            patches.append(self.build_segment(seg, y, **kwargs))
        try:
            if not self.epoch:
                self.set_epoch(segmentlist[0][0])
            else:
                self.set_epoch(min(self.epoch, segmentlist[0][0]))
        except IndexError:
            pass
        if collection:
            coll = PatchCollection(patches, len(patches) != 0)
            coll.set_rasterized(rasterized)
            if collection == 'ignore':
                coll._ignore = True
            else:
                coll._ignore = False
            coll._ypos = y
            out = self.add_collection(coll)
            # reset label with tex-formatting now
            #   matplotlib default label is applied by add_collection
            #   so we can only replace the leading underscore after
            #   this point
            if label is None:
                label = coll.get_label()
            if rcParams['text.usetex']:
                label = rUNDERSCORE.sub(r'\_', str(label))
            coll.set_label(label)
        else:
            out = []
            for p in patches:
                p.set_label(label)
                p.set_rasterized(rasterized)
                label = ''
                out.append(self.add_patch(p))
        self.autoscale(axis='y')
        return out
示例#8
0
文件: segments.py 项目: lpsinger/gwpy
    def plot_segmentlist(self,
                         segmentlist,
                         y=None,
                         height=.8,
                         label=None,
                         collection=True,
                         rasterized=None,
                         **kwargs):
        """Plot a `~gwpy.segments.SegmentList` onto these axes

        Parameters
        ----------
        segmentlist : `~gwpy.segments.SegmentList`
            list of segments to display

        y : `float`, optional
            y-axis value for new segments

        collection : `bool`, default: `True`
            add all patches as a
            `~matplotlib.collections.PatchCollection`, doesn't seem
            to work for hatched rectangles

        label : `str`, optional
            custom descriptive name to print as y-axis tick label

        **kwargs
            any other keyword arguments acceptable for
            `~matplotlib.patches.Rectangle`

        Returns
        -------
        collection : `~matplotlib.patches.PatchCollection`
            list of `~matplotlib.patches.Rectangle` patches
        """
        # get colour
        facecolor = kwargs.pop('facecolor', kwargs.pop('color', '#629fca'))
        if is_color_like(facecolor):
            kwargs.setdefault('edgecolor', tint(facecolor, factor=.5))

        # get y
        if y is None:
            y = self.get_next_y()

        # build patches
        patches = [
            SegmentRectangle(seg,
                             y,
                             height=height,
                             facecolor=facecolor,
                             **kwargs) for seg in segmentlist
        ]

        if collection:  # map to PatchCollection
            coll = PatchCollection(patches,
                                   match_original=patches,
                                   zorder=kwargs.get('zorder', 1))
            coll.set_rasterized(rasterized)
            coll._ignore = collection == 'ignore'
            coll._ypos = y
            out = self.add_collection(coll)
            # reset label with tex-formatting now
            #   matplotlib default label is applied by add_collection
            #   so we can only replace the leading underscore after
            #   this point
            if label is None:
                label = coll.get_label()
            coll.set_label(to_string(label))
        else:
            out = []
            for patch in patches:
                patch.set_label(label)
                patch.set_rasterized(rasterized)
                label = ''
                out.append(self.add_patch(patch))
        self.autoscale(enable=None, axis='both', tight=False)
        return out
示例#9
0
    def plot_segmentlist(self, segmentlist, y=None, height=.8, label=None,
                         collection=True, rasterized=None, **kwargs):
        """Plot a `~gwpy.segments.SegmentList` onto these axes

        Parameters
        ----------
        segmentlist : `~gwpy.segments.SegmentList`
            list of segments to display

        y : `float`, optional
            y-axis value for new segments

        collection : `bool`, default: `True`
            add all patches as a
            `~matplotlib.collections.PatchCollection`, doesn't seem
            to work for hatched rectangles

        label : `str`, optional
            custom descriptive name to print as y-axis tick label

        **kwargs
            any other keyword arguments acceptable for
            `~matplotlib.patches.Rectangle`

        Returns
        -------
        collection : `~matplotlib.patches.PatchCollection`
            list of `~matplotlib.patches.Rectangle` patches
        """
        # get colour
        facecolor = kwargs.pop('facecolor', kwargs.pop('color', '#629fca'))
        if is_color_like(facecolor):
            kwargs.setdefault('edgecolor', tint(facecolor, factor=.5))

        # get y
        if y is None:
            y = self.get_next_y()

        # build patches
        patches = [SegmentRectangle(seg, y, height=height, facecolor=facecolor,
                                    **kwargs) for seg in segmentlist]

        if collection:  # map to PatchCollection
            coll = PatchCollection(patches, match_original=patches,
                                   zorder=kwargs.get('zorder', 1))
            coll.set_rasterized(rasterized)
            coll._ignore = collection == 'ignore'
            coll._ypos = y
            out = self.add_collection(coll)
            # reset label with tex-formatting now
            #   matplotlib default label is applied by add_collection
            #   so we can only replace the leading underscore after
            #   this point
            if label is None:
                label = coll.get_label()
            coll.set_label(to_string(label))
        else:
            out = []
            for patch in patches:
                patch.set_label(label)
                patch.set_rasterized(rasterized)
                label = ''
                out.append(self.add_patch(patch))
        self.autoscale(enable=None, axis='both', tight=False)
        return out
示例#10
0
def draw_networkx_edges(G, pos,
                        edgelist=None,
                        width=1.0,
                        edge_color='k',
                        style='solid',
                        alpha=None,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None,
                        ax=None,
                        arrows=True,
                        label=None,
                        **kwds):
    """Draw the edges of the graph G.

    This draws only the edges of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.

    edgelist : collection of edge tuples
       Draw only specified edges(default=G.edges())

    width : float
       Line width of edges (default =1.0)

    edge_color : color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    style : string
       Edge line style (default='solid') (solid|dashed|dotted,dashdot)

    alpha : float
       The edge transparency (default=1.0)

    edge_ cmap : Matplotlib colormap
       Colormap for mapping intensities of edges (default=None)

    edge_vmin,edge_vmax : floats
       Minimum and maximum for edge colormap scaling (default=None)

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    arrows : bool, optional (default=True)
       For directed graphs, if True draw arrowheads.

    label : [None| string]
       Label for legend

    Returns
    -------
    matplotlib.collection.LineCollection
        `LineCollection` of the edges

    Notes
    -----
    For directed graphs, "arrows" (actually just thicker stubs) are drawn
    at the head end.  Arrows can be turned off with keyword arrows=False.
    Yes, it is ugly but drawing proper arrows with Matplotlib this
    way is tricky.

    Examples
    --------
    >>> G=nx.dodecahedral_graph()
    >>> edges=nx.draw_networkx_edges(G,pos=nx.spring_layout(G))

    Also see the NetworkX drawing examples at
    http://networkx.lanl.gov/gallery.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib
        import matplotlib.pyplot as plt
        import matplotlib.patches as patches
        import matplotlib.cbook as cb
        from matplotlib.colors import colorConverter, Colormap
        from matplotlib.collections import LineCollection
        from matplotlib.collections import PatchCollection
        import numpy
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax = plt.gca()

    if edgelist is None:
        edgelist = G.edges()

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    # set edge positions
    edge_pos = numpy.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])

    if not cb.iterable(width):
        lw = (width,)
    else:
        lw = width

    if not cb.is_string_like(edge_color) \
           and cb.iterable(edge_color) \
           and len(edge_color) == len(edge_pos):
        if numpy.alltrue([cb.is_string_like(c)
                         for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple([colorConverter.to_rgba(c, alpha)
                                 for c in edge_color])
        elif numpy.alltrue([not cb.is_string_like(c)
                           for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if numpy.alltrue([cb.iterable(c) and len(c) in (3, 4)
                             for c in edge_color]):
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError('edge_color must consist of either color names or numbers')
    else:
        if cb.is_string_like(edge_color) or len(edge_color) == 1:
            edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
        else:
            raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')

    edge_collection = None

    if not arrows:
        edge_collection = LineCollection(edge_pos,
                                         colors=edge_colors,
                                         linewidths=lw,
                                         antialiaseds=(1,),
                                         linestyle=style,
                                         transOffset = ax.transData,
                                         )

        edge_collection.set_zorder(1)  # edges go behind nodes
        edge_collection.set_label(label)
        ax.add_collection(edge_collection)

        # Note: there was a bug in mpl regarding the handling of alpha values for
        # each line in a LineCollection.  It was fixed in matplotlib in r7184 and
        # r7189 (June 6 2009).  We should then not set the alpha value globally,
        # since the user can instead provide per-edge alphas now.  Only set it
        # globally if provided as a scalar.
        if cb.is_numlike(alpha):
            edge_collection.set_alpha(alpha)

        if edge_colors is None:
            if edge_cmap is not None:
                assert(isinstance(edge_cmap, Colormap))
            edge_collection.set_array(numpy.asarray(edge_color))
            edge_collection.set_cmap(edge_cmap)
            if edge_vmin is not None or edge_vmax is not None:
                edge_collection.set_clim(edge_vmin, edge_vmax)
            else:
                edge_collection.autoscale()

    arrow_collection = None

    if G.is_directed() and arrows:

        # a directed graph hack
        # draw thick line segments at head end of edge
        # waiting for someone else to implement arrows that will work
        arrow_colors = edge_colors
        arrow_patches = []
        for src, dst in edge_pos:
            x1, y1 = src
            x2, y2 = dst
            dx = x2-x1   # x offset
            dy = y2-y1   # y offset
            arrow_width = width / 20.0
            line_width = arrow_width / 20.0
            arrow_patch = patches.FancyArrow(x1, y1, dx, dy, width=line_width,
                                             length_includes_head=True, head_width=arrow_width,
                                             head_length=arrow_width)
            arrow_patches.append(arrow_patch)

        arrow_collection = PatchCollection(arrow_patches,
                                           edgecolors=arrow_colors,
                                           facecolors=arrow_colors,
                                           linewidths=lw,
                                           linestyle=style,
                                           antialiaseds=(1,),
                                           transOffset = ax.transData,
                                          )

        arrow_collection.set_zorder(1)  # edges go behind nodes
        arrow_collection.set_label(label)
        ax.add_collection(arrow_collection)

    # update view
    minx = numpy.amin(numpy.ravel(edge_pos[:, :, 0]))
    maxx = numpy.amax(numpy.ravel(edge_pos[:, :, 0]))
    miny = numpy.amin(numpy.ravel(edge_pos[:, :, 1]))
    maxy = numpy.amax(numpy.ravel(edge_pos[:, :, 1]))

    w = maxx-minx
    h = maxy-miny
    padx,  pady = 0.05*w, 0.05*h
    corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

    if arrow_collection:
        return arrow_collection
    else:
        return edge_collection
示例#11
0
文件: segments.py 项目: stefco/gwpy
    def plot_segmentlist(self, segmentlist, y=None, collection=True,
                         label=None, rasterized=None, **kwargs):
        """Plot a `~gwpy.segments.SegmentList` onto these axes

        Parameters
        ----------
        segmentlist : `~gwpy.segments.SegmentList`
            list of segments to display

        y : `float`, optional
            y-axis value for new segments

        collection : `bool`, default: `True`
            add all patches as a
            `~matplotlib.collections.PatchCollection`, doesn't seem
            to work for hatched rectangles

        label : `str`, optional
            custom descriptive name to print as y-axis tick label

        **kwargs
            any other keyword arguments acceptable for
            `~matplotlib.patches.Rectangle`

        Returns
        -------
        collection : `~matplotlib.patches.PatchCollection`
            list of `~matplotlib.patches.Rectangle` patches
        """
        if y is None:
            y = self.get_next_y()
        patches = []
        for seg in segmentlist:
            patches.append(self.build_segment(seg, y, **kwargs))
        try:
            if not self.epoch:
                self.set_epoch(segmentlist[0][0])
            else:
                self.set_epoch(min(self.epoch, segmentlist[0][0]))
        except IndexError:
            pass
        if collection:
            coll = PatchCollection(patches, match_original=patches)
            coll.set_rasterized(rasterized)
            coll._ignore = collection == 'ignore'
            coll._ypos = y
            out = self.add_collection(coll)
            # reset label with tex-formatting now
            #   matplotlib default label is applied by add_collection
            #   so we can only replace the leading underscore after
            #   this point
            if label is None:
                label = coll.get_label()
            coll.set_label(to_string(label))
        else:
            out = []
            for patch in patches:
                patch.set_label(label)
                patch.set_rasterized(rasterized)
                label = ''
                out.append(self.add_patch(patch))
        self.autoscale(axis='y')
        return out