Python matplotlib.patches.Polygon() Examples

The following are 30 code examples of matplotlib.patches.Polygon(). 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. You may also want to check out all available functions/classes of the module matplotlib.patches , or try the search function .
Example #1
Source File: matplotlib.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def _measure(self, qxy, cxy, cid, fc=None, ec=None, gt=None, sc=None):
        qx, qy = qxy
        cx, cy = cxy

        # draw gate box
        self._gate(qxy, fc=fc, ec=ec, gt=gt, sc=sc)

        # add measure symbol
        arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
                          height=HIG * 0.7, theta1=0, theta2=180, fill=False,
                          ec=self._style.not_gate_lc, linewidth=2, zorder=PORDER_GATE)
        self.ax.add_patch(arc)
        self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
                     color=self._style.not_gate_lc, linewidth=2, zorder=PORDER_GATE)
        # arrow
        self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc, ls=self._style.cline)
        arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
                                     (cx + 0.20 * WID, cy + 0.35 * WID),
                                     (cx, cy)), fc=self._style.cc, ec=None)
        self.ax.add_artist(arrowhead)
        # target
        if self.cregbundle:
            self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
                         fontsize=0.8 * self._style.fs, color=self._style.tc,
                         clip_on=True, zorder=PORDER_TEXT) 
Example #2
Source File: BedTrack.py    From pyGenomeTracks with GNU General Public License v3.0 6 votes vote down vote up
def draw_gene_simple(self, ax, bed, ypos, rgb, edgecolor, linewidth):
        """
        draws an interval with direction (if given)
        """

        if bed.strand not in ['+', '-']:
            ax.add_patch(Rectangle((bed.start, ypos),
                         bed.end - bed.start, 1,
                         edgecolor=edgecolor, facecolor=rgb,
                         linewidth=linewidth))
        else:
            vertices = self._draw_arrow(bed.start, bed.end, bed.strand, ypos)
            ax.add_patch(Polygon(vertices, closed=True, fill=True,
                                 edgecolor=edgecolor,
                                 facecolor=rgb,
                                 linewidth=linewidth)) 
Example #3
Source File: test_path.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_path_clipping():
    fig = plt.figure(figsize=(6.0, 6.2))

    for i, xy in enumerate([
            [(200, 200), (200, 350), (400, 350), (400, 200)],
            [(200, 200), (200, 350), (400, 350), (400, 100)],
            [(200, 100), (200, 350), (400, 350), (400, 100)],
            [(200, 100), (200, 415), (400, 350), (400, 100)],
            [(200, 100), (200, 415), (400, 415), (400, 100)],
            [(200, 415), (400, 415), (400, 100), (200, 100)],
            [(400, 415), (400, 100), (200, 100), (200, 415)]]):
        ax = fig.add_subplot(4, 2, i)
        bbox = [0, 140, 640, 260]
        ax.set_xlim(bbox[0], bbox[0] + bbox[2])
        ax.set_ylim(bbox[1], bbox[1] + bbox[3])
        ax.add_patch(Polygon(
            xy, facecolor='none', edgecolor='red', closed=True)) 
Example #4
Source File: plate.py    From EasyPR-python with Apache License 2.0 6 votes vote down vote up
def test_plate_detect():
    print("Testing Plate Detect")

    file = cfg.DATA_DIR / 'demo' / 'test.jpg'

    src = cv2.imread(str(file))
    if cfg.VIS and 0:
        plt.imshow(cv2.cvtColor(src, cv2.COLOR_BGR2RGB))
        plt.show()
    results = plate_detect(src)
    if cfg.VIS:
        for res in results:
            print("Plate position: \n", res)
            fig = plt.figure(figsize=(10, 10))
            ax1 = fig.add_subplot(211)
            ax1.imshow(src)
            ax1.add_patch(patches.Polygon(res))
            ax2 = fig.add_subplot(212)
            vis_image = align(src, res)
            ax2.imshow(cv2.cvtColor(vis_image, cv2.COLOR_BGR2RGB))
            plt.show() 
Example #5
Source File: floating_axes.py    From Computable with MIT License 6 votes vote down vote up
def _gen_axes_patch(self):
        """
        Returns the patch used to draw the background of the axes.  It
        is also used as the clipping path for any data elements on the
        axes.

        In the standard axes, this is a rectangle, but in other
        projections it may not be.

        .. note::
            Intended to be overridden by new projection types.
        """
        import matplotlib.patches as mpatches
        grid_helper = self.get_grid_helper()
        t = grid_helper.get_boundary()
        return mpatches.Polygon(t) 
Example #6
Source File: show_labels.py    From bdd100k with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def box3d_to_lines(self, label_id, box3d, calibration, occluded):
        """generate individual bounding box from 3d label"""
        label = Label3d.from_box3d(box3d)
        edges = label.get_edges_with_visibility(calibration)

        box_color = self.get_label_color(label_id)
        alpha = 0.5 if occluded else 0.8

        lines = []
        for edge in edges['dashed']:
            lines.append(mpatches.Polygon(edge, linewidth=2 * self.scale,
                                          linestyle=(0, (2, 2)),
                                          edgecolor=box_color,
                                          facecolor='none', fill=False,
                                          alpha=alpha))
        for edge in edges['solid']:
            lines.append(mpatches.Polygon(edge, linewidth=2 * self.scale,
                                          edgecolor=box_color,
                                          facecolor='none', fill=False,
                                          alpha=alpha))

        return lines 
Example #7
Source File: graph.py    From nusa with MIT License 6 votes vote down vote up
def __init__(self,xcoord,ycoord,**kwargs):
        collections.PatchCollection.__init__(self,[],**kwargs)
        tol = 0.02
        _xdata1 = np.array([xcoord-tol,xcoord,xcoord+tol])
        _ydata1 = np.array([ycoord-tol,ycoord,ycoord-tol])
        _xdata2 = np.array([xcoord-tol,xcoord,xcoord-tol])
        _ydata2 = np.array([ycoord-tol,ycoord,ycoord+tol])
        # Polygons
        p1 = patches.Polygon(zip(_xdata1,_ydata1))
        p1.set_color("r")
        p2 = patches.Polygon(zip(_xdata2,_ydata2))
        #print p1,p2
        #p2.set_color("g")
        # Set data
        self.set_paths((p1,p2))
        self.set_color("k")
        #self.set_marker("-")
        #self.set_mfc('r')
        #self.set_ms(10) 
Example #8
Source File: geometry.py    From PassportEye with MIT License 6 votes vote down vote up
def plot(self, mode='image', ax=None, **kwargs):
        """Visualize the box on a matplotlib plot.
        :param mode: How should the box coordinates and angle be interpreted.
            - mode `'image'` corresponds to the situation where x coordinate of the box
              denotes the "row of an image" (ie. the Y coordinate of the plot, arranged downwards)
              and y coordinate of the box corresponds to the "column of an image",
              (ie X coordinate of the plot). In other words, box's x goes downwards and y - rightwards.
            - mode `'math'` corresponds to the "mathematics" situation where box's x and y correspond to the X and Y axes of the plot.
        :param ax: the matplotlib axis to draw on. If unspecified, the current axis is used.
        :param kwargs: arguments passed to the matplotlib's `Polygon` patch object. By default, fill is set to False, color to red and lw to 2.
        :return: The created Polygon object.
        """
        ax = ax or plt.gca()
        poly = self.as_poly()
        if mode == 'image':
            poly = poly[:,[1,0]]
        kwargs.setdefault('fill', False)
        kwargs.setdefault('color', 'r')
        kwargs.setdefault('lw', 2)
        p = patches.Polygon(poly, **kwargs)
        ax.add_patch(p)
        return p 
Example #9
Source File: test_source_okada.py    From kite with GNU General Public License v3.0 6 votes vote down vote up
def _plot_displacement(ms):
        if not plot:
            ms.down
            return

        import matplotlib.pyplot as plt
        from matplotlib.patches import Polygon
        fig = plt.figure()
        ax = fig.gca()
        ms.processSources()

        ax.imshow(num.flipud(ms.down), aspect='equal',
                  extent=[0, ms.frame.E.max(), 0, ms.frame.N.max()])
        for src in ms.sources:
            for seg in src.segments:
                p = Polygon(seg.outline(), alpha=.8, fill=False)
                ax.add_artist(p)
            if isinstance(src, OkadaPath):
                nodes = num.array(src.nodes)
                ax.scatter(nodes[:, 0], nodes[:, 1], color='r')
        plt.show()
        fig.clear() 
Example #10
Source File: segment.py    From COCO-Style-Dataset-Generator-GUI with Apache License 2.0 6 votes vote down vote up
def submit(self, event):

        if not self.right_click:
            print ('Right click before submit is a must!!')
        else:

            self.text+=self.radio.value_selected+'\n'+'%.2f'%self.find_poly_area()+'\n'+self.print_points()+'\n\n'
            self.right_click = False
            #print (self.points)

            self.lines, self.circles = [], []
            self.click_id = fig.canvas.mpl_connect('button_press_event', self.onclick)

            self.polys.append(Polygon(self.points_to_polygon(), closed=True, color=np.random.rand(3), alpha=0.4, fill=True))
            if self.submit_p:
                self.submit_p.remove()
            self.submit_p = PatchCollection(self.polys, cmap=matplotlib.cm.jet, alpha=0.4)
            self.ax.add_collection(self.submit_p)
            self.points = [] 
Example #11
Source File: plotter.py    From periodic-table-plotter with MIT License 6 votes vote down vote up
def single_color(self, **kwargs):
        """
        Creates a single Patch.

        +------------+
        |            |
        |            |
        |     1st    |
        |            |
        |            |
        +------------+

        """
        x1, x2 = self.x, self.x+self.dx
        y1, y2 = self.y, self.y+self.dy
        patch = Polygon([
            [x1, y1], # origin
            [x2, y1], # to bottom right
            [x2, y2], # to top right
            [x1, y2], # to top left
            [x1, y1]])# to origin
        self.patches = [patch] 
Example #12
Source File: floating_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _gen_axes_patch(self):
        """
        Returns the patch used to draw the background of the axes.  It
        is also used as the clipping path for any data elements on the
        axes.

        In the standard axes, this is a rectangle, but in other
        projections it may not be.

        .. note::
            Intended to be overridden by new projection types.
        """
        import matplotlib.patches as mpatches
        grid_helper = self.get_grid_helper()
        t = grid_helper.get_boundary()
        return mpatches.Polygon(t) 
Example #13
Source File: segment.py    From COCO-Style-Dataset-Generator-GUI with Apache License 2.0 6 votes vote down vote up
def onclick_release(self, event):

        if any([x.in_axes(event) for x in self.button_axes]) or self.selected_poly:
            return

        if hasattr(self, 'r_x') and hasattr(self, 'r_y') and None not in [self.r_x, self.r_y, event.xdata, event.ydata]:
            if np.abs(event.xdata - self.r_x)>10 and np.abs(event.ydata - self.r_y)>10: # 10 pixels limit for rectangle creation
                if len(self.points)<4:

                    self.right_click=True
                    self.fig.canvas.mpl_disconnect(self.click_id)
                    self.click_id = None
                    bbox = [np.min([event.xdata, self.r_x]), np.min([event.ydata, self.r_y]), np.max([event.xdata, self.r_x]), np.max([event.ydata, self.r_y])]
                    self.r_x = self.r_y = None

                    self.points = [bbox[0], bbox[1], bbox[0], bbox[3], bbox[2], bbox[3], bbox[2], bbox[1], bbox[0], bbox[1]]
                    self.p = PatchCollection([Polygon(self.points_to_polygon(), closed=True)], facecolor='red', linewidths=0, alpha=0.4)
                    self.ax.add_collection(self.p)
                    self.fig.canvas.draw() 
Example #14
Source File: floating_axes.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _gen_axes_patch(self):
        """
        Returns the patch used to draw the background of the axes.  It
        is also used as the clipping path for any data elements on the
        axes.

        In the standard axes, this is a rectangle, but in other
        projections it may not be.

        .. note::
            Intended to be overridden by new projection types.
        """
        import matplotlib.patches as mpatches
        grid_helper = self.get_grid_helper()
        t = grid_helper.get_boundary()
        return mpatches.Polygon(t) 
Example #15
Source File: visualize.py    From keras-ctpn with Apache License 2.0 6 votes vote down vote up
def display_polygons(image, polygons, scores=None, figsize=(16, 16), ax=None, colors=None):
    auto_show = False
    if ax is None:
        _, ax = plt.subplots(1, figsize=figsize)
        auto_show = True
    if colors is None:
        colors = random_colors(len(polygons))

    height, width = image.shape[:2]
    ax.set_ylim(height + 10, -10)
    ax.set_xlim(-10, width + 10)
    ax.axis('off')

    for i, polygon in enumerate(polygons):
        color = colors[i]
        polygon = np.reshape(polygon, (-1, 2))  # 转为[n,(x,y)]
        patch = patches.Polygon(polygon, facecolor=None, fill=False, color=color)
        ax.add_patch(patch)
        # 多边形得分
        x1, y1 = polygon[0][:]
        ax.text(x1, y1 - 1, scores[i] if scores is not None else '',
                color='w', size=11, backgroundcolor="none")
    ax.imshow(image.astype(np.uint8))
    if auto_show:
        plt.show() 
Example #16
Source File: floating_axes.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _gen_axes_patch(self):
        """
        Returns the patch used to draw the background of the axes.  It
        is also used as the clipping path for any data elements on the
        axes.

        In the standard axes, this is a rectangle, but in other
        projections it may not be.

        .. note::
            Intended to be overridden by new projection types.
        """
        import matplotlib.patches as mpatches
        grid_helper = self.get_grid_helper()
        t = grid_helper.get_boundary()
        return mpatches.Polygon(t) 
Example #17
Source File: _base.py    From neural-network-animation with MIT License 5 votes vote down vote up
def _makefill(self, x, y, kw, kwargs):
        try:
            facecolor = kw['color']
        except KeyError:
            facecolor = six.next(self.color_cycle)
        seg = mpatches.Polygon(np.hstack((x[:, np.newaxis],
                                          y[:, np.newaxis])),
                               facecolor=facecolor,
                               fill=True,
                               closed=kw['closed'])
        self.set_patchprops(seg, **kwargs)
        return seg 
Example #18
Source File: _base.py    From neural-network-animation with MIT License 5 votes vote down vote up
def _xy_from_xy(self, x, y):
        if self.axes.xaxis is not None and self.axes.yaxis is not None:
            bx = self.axes.xaxis.update_units(x)
            by = self.axes.yaxis.update_units(y)

            if self.command != 'plot':
                # the Line2D class can handle unitized data, with
                # support for post hoc unit changes etc.  Other mpl
                # artists, e.g., Polygon which _process_plot_var_args
                # also serves on calls to fill, cannot.  So this is a
                # hack to say: if you are not "plot", which is
                # creating Line2D, then convert the data now to
                # floats.  If you are plot, pass the raw data through
                # to Line2D which will handle the conversion.  So
                # polygons will not support post hoc conversions of
                # the unit type since they are not storing the orig
                # data.  Hopefully we can rationalize this at a later
                # date - JDH
                if bx:
                    x = self.axes.convert_xunits(x)
                if by:
                    y = self.axes.convert_yunits(y)

        x = np.atleast_1d(x)  # like asanyarray, but converts scalar to array
        y = np.atleast_1d(y)
        if x.shape[0] != y.shape[0]:
            raise ValueError("x and y must have same first dimension")
        if x.ndim > 2 or y.ndim > 2:
            raise ValueError("x and y can be no greater than 2-D")

        if x.ndim == 1:
            x = x[:, np.newaxis]
        if y.ndim == 1:
            y = y[:, np.newaxis]
        return x, y 
Example #19
Source File: colorbar.py    From neural-network-animation with MIT License 5 votes vote down vote up
def _config_axes(self, X, Y):
        '''
        Make an axes patch and outline.
        '''
        ax = self.ax
        ax.set_frame_on(False)
        ax.set_navigate(False)
        xy = self._outline(X, Y)
        ax.update_datalim(xy)
        ax.set_xlim(*ax.dataLim.intervalx)
        ax.set_ylim(*ax.dataLim.intervaly)
        if self.outline is not None:
            self.outline.remove()
        self.outline = mpatches.Polygon(
            xy, edgecolor=mpl.rcParams['axes.edgecolor'],
            facecolor='none',
            linewidth=mpl.rcParams['axes.linewidth'],
            closed=True,
            zorder=2)
        ax.add_artist(self.outline)
        self.outline.set_clip_box(None)
        self.outline.set_clip_path(None)
        c = mpl.rcParams['axes.facecolor']
        if self.patch is not None:
            self.patch.remove()
        self.patch = mpatches.Polygon(xy, edgecolor=c,
                                      facecolor=c,
                                      linewidth=0.01,
                                      zorder=-1)
        ax.add_artist(self.patch)

        self.update_ticks() 
Example #20
Source File: test_patches.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_Polygon_close():
    #: Github issue #1018 identified a bug in the Polygon handling
    #: of the closed attribute; the path was not getting closed
    #: when set_xy was used to set the vertices.

    # open set of vertices:
    xy = [[0, 0], [0, 1], [1, 1]]
    # closed set:
    xyclosed = xy + [[0, 0]]

    # start with open path and close it:
    p = Polygon(xy, closed=True)
    assert_array_equal(p.get_xy(), xyclosed)
    p.set_xy(xy)
    assert_array_equal(p.get_xy(), xyclosed)

    # start with closed path and open it:
    p = Polygon(xyclosed, closed=False)
    assert_array_equal(p.get_xy(), xy)
    p.set_xy(xyclosed)
    assert_array_equal(p.get_xy(), xy)

    # start with open path and leave it open:
    p = Polygon(xy, closed=False)
    assert_array_equal(p.get_xy(), xy)
    p.set_xy(xy)
    assert_array_equal(p.get_xy(), xy)

    # start with closed path and leave it closed:
    p = Polygon(xyclosed, closed=True)
    assert_array_equal(p.get_xy(), xyclosed)
    p.set_xy(xyclosed)
    assert_array_equal(p.get_xy(), xyclosed) 
Example #21
Source File: util.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def plot_polygon(ax, x, **kwargs):
    ax.add_collection(PatchCollection([patches.Polygon(x, True)], **kwargs)) 
Example #22
Source File: segment.py    From COCO-Style-Dataset-Generator-GUI with Apache License 2.0 5 votes vote down vote up
def bring_prev(self, event):

        if not self.feedback:

            poly_verts, self.objects = return_info(self.img_paths[self.index-1][:-3]+'txt')

            for num in poly_verts:
                self.existing_polys.append(Polygon(num, closed=True, alpha=0.5, facecolor='red'))

                pat = PatchCollection([Polygon(num, closed=True)], facecolor='green', linewidths=0, alpha=0.6)
                self.ax.add_collection(pat)
                self.existing_patches.append(pat) 
Example #23
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def _config_axes(self, X, Y):
        '''
        Make an axes patch and outline.
        '''
        ax = self.ax
        ax.set_frame_on(False)
        ax.set_navigate(False)
        xy = self._outline(X, Y)
        ax.update_datalim(xy)
        ax.set_xlim(*ax.dataLim.intervalx)
        ax.set_ylim(*ax.dataLim.intervaly)
        if self.outline is not None:
            self.outline.remove()
        self.outline = mpatches.Polygon(
            xy, edgecolor=mpl.rcParams['axes.edgecolor'],
            facecolor='none',
            linewidth=mpl.rcParams['axes.linewidth'],
            closed=True,
            zorder=2)
        ax.add_artist(self.outline)
        self.outline.set_clip_box(None)
        self.outline.set_clip_path(None)
        c = mpl.rcParams['axes.facecolor']
        if self.patch is not None:
            self.patch.remove()
        self.patch = mpatches.Polygon(xy, edgecolor=c,
                                      facecolor=c,
                                      linewidth=0.01,
                                      zorder=-1)
        ax.add_artist(self.patch)

        self.update_ticks() 
Example #24
Source File: map.py    From skymapper with MIT License 5 votes vote down vote up
def _setEdge(self, **kwargs):
        self._lat_range = np.linspace(-89.9999, 89.9999, self._resolution)
        self._lon_range = np.linspace(-179.9999, 179.9999, self._resolution) + self.proj.lon_0


        # styling: frame needs to be on top of everything, must be transparent
        facecolor = 'None'
        zorder = 1000
        lw = kwargs.pop('lw', 0.7)
        edgecolor = kwargs.pop('edgecolor', 'k')
        # if there is facecolor: clone the polygon and put it in as bottom layer
        facecolor_ = kwargs.pop('facecolor', '#dddddd')

        # polygon of the map edge: top, left, bottom, right
        # don't draw poles if that's a single point
        lines = []
        if not self.proj.poleIsPoint[90]:
            lines.append(self._getParallel(90))
        lines.append(self._getMeridian(self._lon_range[-1], reverse=True))
        if not self.proj.poleIsPoint[-90]:
            lines.append(self._getParallel(-90, reverse=True))
        lines.append(self._getMeridian(self._lon_range[0]))
        xy = np.concatenate(lines, axis=1).T
        self._edge = Polygon(xy, closed=True, edgecolor=edgecolor, facecolor=facecolor, lw=lw, zorder=zorder,gid="edge", **kwargs)
        self.ax.add_patch(self._edge)

        if facecolor_ is not None:
            zorder = -1000
            edgecolor = 'None'
            poly = Polygon(xy, closed=True, edgecolor=edgecolor, facecolor=facecolor_, zorder=zorder, gid="edge-background")
            self.ax.add_patch(poly) 
Example #25
Source File: map.py    From skymapper with MIT License 5 votes vote down vote up
def __init__(self, proj, ax=None, interactive=True, **kwargs):
        """Create Map with a given projection.

        A `skymapper.Map` holds a predefined projection and `matplotlib` axes
        and figures to enable plotting on the sphere with proper labeling
        and inter/extrapolations.

        It also allows for interactive and exploratory work by updateing the
        maps after pan/zoom events.

        Most of the methods are wrappers of `matplotlib` functions by the same
        names, so that one can mostly interact with a `Map` instance as one
        would do with a `matplotlib.axes`.

        For plotting purposes, it is recommended to switch `interactive` off.

        Args:
            proj: `skymapper.Projection` instance
            ax: `matplotlib.axes` instance, will be created otherwise
            interactive: if pan/zoom is enabled for map updates
            **kwargs: styling of the `matplotlib.patches.Polygon` that shows
                the outline of the map.
        """
        # store arguments to regenerate the map
        self._config = {'__init__': _parseArgs(locals())}
        self.proj = proj
        self._setFigureAx(ax, interactive=interactive)
        self._resolution = 75 # for graticules
        self._setEdge(**kwargs)
        self.ax.relim()
        self.ax.autoscale_view()
        self._setFrame() 
Example #26
Source File: test_patches.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_Polygon_close():
    #: Github issue #1018 identified a bug in the Polygon handling
    #: of the closed attribute; the path was not getting closed
    #: when set_xy was used to set the vertices.

    # open set of vertices:
    xy = [[0, 0], [0, 1], [1, 1]]
    # closed set:
    xyclosed = xy + [[0, 0]]

    # start with open path and close it:
    p = Polygon(xy, closed=True)
    assert_array_equal(p.get_xy(), xyclosed)
    p.set_xy(xy)
    assert_array_equal(p.get_xy(), xyclosed)

    # start with closed path and open it:
    p = Polygon(xyclosed, closed=False)
    assert_array_equal(p.get_xy(), xy)
    p.set_xy(xyclosed)
    assert_array_equal(p.get_xy(), xy)

    # start with open path and leave it open:
    p = Polygon(xy, closed=False)
    assert_array_equal(p.get_xy(), xy)
    p.set_xy(xy)
    assert_array_equal(p.get_xy(), xy)

    # start with closed path and leave it closed:
    p = Polygon(xyclosed, closed=True)
    assert_array_equal(p.get_xy(), xyclosed)
    p.set_xy(xyclosed)
    assert_array_equal(p.get_xy(), xyclosed) 
Example #27
Source File: _base.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _xy_from_xy(self, x, y):
        if self.axes.xaxis is not None and self.axes.yaxis is not None:
            bx = self.axes.xaxis.update_units(x)
            by = self.axes.yaxis.update_units(y)

            if self.command != 'plot':
                # the Line2D class can handle unitized data, with
                # support for post hoc unit changes etc.  Other mpl
                # artists, e.g., Polygon which _process_plot_var_args
                # also serves on calls to fill, cannot.  So this is a
                # hack to say: if you are not "plot", which is
                # creating Line2D, then convert the data now to
                # floats.  If you are plot, pass the raw data through
                # to Line2D which will handle the conversion.  So
                # polygons will not support post hoc conversions of
                # the unit type since they are not storing the orig
                # data.  Hopefully we can rationalize this at a later
                # date - JDH
                if bx:
                    x = self.axes.convert_xunits(x)
                if by:
                    y = self.axes.convert_yunits(y)

        # like asanyarray, but converts scalar to array, and doesn't change
        # existing compatible sequences
        x = _check_1d(x)
        y = _check_1d(y)
        if x.shape[0] != y.shape[0]:
            raise ValueError("x and y must have same first dimension, but "
                             "have shapes {} and {}".format(x.shape, y.shape))
        if x.ndim > 2 or y.ndim > 2:
            raise ValueError("x and y can be no greater than 2-D, but have "
                             "shapes {} and {}".format(x.shape, y.shape))

        if x.ndim == 1:
            x = x[:, np.newaxis]
        if y.ndim == 1:
            y = y[:, np.newaxis]
        return x, y 
Example #28
Source File: colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _config_axes(self, X, Y):
        '''
        Make an axes patch and outline.
        '''
        ax = self.ax
        ax.set_frame_on(False)
        ax.set_navigate(False)
        xy = self._outline(X, Y)
        ax.ignore_existing_data_limits = True
        ax.update_datalim(xy)
        ax.set_xlim(*ax.dataLim.intervalx)
        ax.set_ylim(*ax.dataLim.intervaly)
        if self.outline is not None:
            self.outline.remove()
        self.outline = mpatches.Polygon(
            xy, edgecolor=mpl.rcParams['axes.edgecolor'],
            facecolor='none',
            linewidth=mpl.rcParams['axes.linewidth'],
            closed=True,
            zorder=2)
        ax.add_artist(self.outline)
        self.outline.set_clip_box(None)
        self.outline.set_clip_path(None)
        c = mpl.rcParams['axes.facecolor']
        if self.patch is not None:
            self.patch.remove()
        self.patch = mpatches.Polygon(xy, edgecolor=c,
                                      facecolor=c,
                                      linewidth=0.01,
                                      zorder=-1)
        ax.add_artist(self.patch)

        self.update_ticks() 
Example #29
Source File: _base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def _xy_from_xy(self, x, y):
        if self.axes.xaxis is not None and self.axes.yaxis is not None:
            bx = self.axes.xaxis.update_units(x)
            by = self.axes.yaxis.update_units(y)

            if self.command != 'plot':
                # the Line2D class can handle unitized data, with
                # support for post hoc unit changes etc.  Other mpl
                # artists, e.g., Polygon which _process_plot_var_args
                # also serves on calls to fill, cannot.  So this is a
                # hack to say: if you are not "plot", which is
                # creating Line2D, then convert the data now to
                # floats.  If you are plot, pass the raw data through
                # to Line2D which will handle the conversion.  So
                # polygons will not support post hoc conversions of
                # the unit type since they are not storing the orig
                # data.  Hopefully we can rationalize this at a later
                # date - JDH
                if bx:
                    x = self.axes.convert_xunits(x)
                if by:
                    y = self.axes.convert_yunits(y)

        # like asanyarray, but converts scalar to array, and doesn't change
        # existing compatible sequences
        x = _check_1d(x)
        y = _check_1d(y)
        if x.shape[0] != y.shape[0]:
            raise ValueError("x and y must have same first dimension, but "
                             "have shapes {} and {}".format(x.shape, y.shape))
        if x.ndim > 2 or y.ndim > 2:
            raise ValueError("x and y can be no greater than 2-D, but have "
                             "shapes {} and {}".format(x.shape, y.shape))

        if x.ndim == 1:
            x = x[:, np.newaxis]
        if y.ndim == 1:
            y = y[:, np.newaxis]
        return x, y 
Example #30
Source File: LinksTrack.py    From pyGenomeTracks with GNU General Public License v3.0 5 votes vote down vote up
def plot_loops(self, ax, loop):
        """
              " <- 2
        3->  "  " <- 1
               " <- 0
            """
        width1 = loop[1] - loop[0]
        width2 = loop[3] - loop[2]
        x0 = (loop[1] + loop[2]) / 2
        y0 = loop[2] - loop[1]

        x1 = x0 + width2 / 2
        y1 = y0 + width2

        x2 = (loop[0] + loop[3]) / 2
        y2 = loop[3] - loop[0]

        x3 = x0 - width1 / 2
        y3 = y0 + width1

        if self.colormap:
            # translate score field
            # into a color
            rgb = self.colormap.to_rgba(loop[4])
        else:
            rgb = self.properties['color']

        rectangle = Polygon(np.array([[x0, y0], [x1, y1], [x2, y2], [x3, y3]]),
                            facecolor='none', edgecolor=rgb,
                            linewidth=self.line_width,
                            ls=self.properties['line_style'])
        ax.add_artist(rectangle)
        if y2 > self.max_height:
            self.max_height = y2