Python matplotlib.path.Path() Examples

The following are 30 code examples of matplotlib.path.Path(). 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.path , or try the search function .
Example #1
Source File: Micaps11Data.py    From PyMICAPS with GNU General Public License v2.0 10 votes vote down vote up
def ConvertPacth(self, ax, patch):
        path = patch.get_path()
        lon = []
        lat = []
        for points in path.vertices:
            x, y = points[0], points[1]
            xy_pixels = ax.transData.transform(np.vstack([x, y]).T)
            xpix, ypix = xy_pixels.T
            lon.append(xpix[0])
            lat.append(ypix[0])
        from matplotlib.path import Path
        apath = Path(list(zip(lon, lat)))
        from matplotlib import patches
        apatch = patches.PathPatch(apath, linewidth=1, facecolor='none', edgecolor='k')
        plt.gca().add_patch(apatch)
        return apatch 
Example #2
Source File: dataset.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def inside_polygon(polygon, point):
    """ check if a point is strictly inside the polygon

    :param ndarray|list polygon: polygon contour
    :param tuple|list point: sample point
    :return bool: inside

    >>> poly = [[1, 1], [1, 3], [3, 3], [3, 1]]
    >>> inside_polygon(poly, [0, 0])
    False
    >>> inside_polygon(poly, [1, 1])
    False
    >>> inside_polygon(poly, [2, 2])
    True
    """
    path = Path(polygon)
    return path.contains_points([point])[0] 
Example #3
Source File: Border.py    From PyMICAPS with GNU General Public License v2.0 6 votes vote down vote up
def readPolygon(filename):
        """
        从特定格式的文件中获取path
        :param filename: 特定的数据文件全名
        :return: path对象的一个实例
        """
        try:
            file_object = open(filename)
            all_the_text = file_object.read().strip()
            file_object.close()
            poses = re.split(r'[,]+|[\s]+', all_the_text)
            lon = [float(p) for p in poses[0::2]]
            lat = [float(p) for p in poses[1::2]]
            path = Path(zip(lon, lat))
            return path
        except Exception as err:
            print(u'【{0}】{1}-{2}'.format(filename, err, datetime.now()))
            return None 
Example #4
Source File: collections.py    From Computable with MIT License 6 votes vote down vote up
def set_verts(self, verts, closed=True):
        '''This allows one to delay initialization of the vertices.'''
        if np.ma.isMaskedArray(verts):
            verts = verts.astype(np.float_).filled(np.nan)
            # This is much faster than having Path do it one at a time.
        if closed:
            self._paths = []
            for xy in verts:
                if len(xy):
                    if np.ma.isMaskedArray(xy):
                        xy = np.ma.concatenate([xy, np.zeros((1, 2))])
                    else:
                        xy = np.asarray(xy)
                        xy = np.concatenate([xy, np.zeros((1, 2))])
                    codes = np.empty(xy.shape[0], dtype=mpath.Path.code_type)
                    codes[:] = mpath.Path.LINETO
                    codes[0] = mpath.Path.MOVETO
                    codes[-1] = mpath.Path.CLOSEPOLY
                    self._paths.append(mpath.Path(xy, codes))
                else:
                    self._paths.append(mpath.Path(xy))
        else:
            self._paths = [mpath.Path(xy) for xy in verts] 
Example #5
Source File: collections.py    From Computable with MIT License 6 votes vote down vote up
def convert_mesh_to_paths(meshWidth, meshHeight, coordinates):
        """
        Converts a given mesh into a sequence of
        :class:`matplotlib.path.Path` objects for easier rendering by
        backends that do not directly support quadmeshes.

        This function is primarily of use to backend implementers.
        """
        Path = mpath.Path

        if ma.isMaskedArray(coordinates):
            c = coordinates.data
        else:
            c = coordinates

        points = np.concatenate((
                    c[0:-1, 0:-1],
                    c[0:-1, 1:],
                    c[1:, 1:],
                    c[1:, 0:-1],
                    c[0:-1, 0:-1]
                ), axis=2)
        points = points.reshape((meshWidth * meshHeight, 5, 2))
        return [Path(x) for x in points] 
Example #6
Source File: offsetbox.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def draw(self, renderer):
        """
        Draw the children
        """

        dpi_cor = renderer.points_to_pixels(1.)
        self.dpi_transform.clear()
        self.dpi_transform.scale(dpi_cor, dpi_cor)

        # At this point the DrawingArea has a transform
        # to the display space so the path created is
        # good for clipping children
        tpath = mtransforms.TransformedPath(
            mpath.Path([[0, 0], [0, self.height],
                        [self.width, self.height],
                        [self.width, 0]]),
            self.get_transform())
        for c in self._children:
            if self._clip_children and not (c.clipbox or c._clippath):
                c.set_clip_path(tpath)
            c.draw(renderer)

        bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
        self.stale = False 
Example #7
Source File: collections.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def set_verts(self, verts, closed=True):
        '''This allows one to delay initialization of the vertices.'''
        if np.ma.isMaskedArray(verts):
            verts = verts.astype(np.float_).filled(np.nan)
            # This is much faster than having Path do it one at a time.
        if closed:
            self._paths = []
            for xy in verts:
                if len(xy):
                    if np.ma.isMaskedArray(xy):
                        xy = np.ma.concatenate([xy, np.zeros((1, 2))])
                    else:
                        xy = np.asarray(xy)
                        xy = np.concatenate([xy, np.zeros((1, 2))])
                    codes = np.empty(xy.shape[0], dtype=mpath.Path.code_type)
                    codes[:] = mpath.Path.LINETO
                    codes[0] = mpath.Path.MOVETO
                    codes[-1] = mpath.Path.CLOSEPOLY
                    self._paths.append(mpath.Path(xy, codes))
                else:
                    self._paths.append(mpath.Path(xy))
        else:
            self._paths = [mpath.Path(xy) for xy in verts] 
Example #8
Source File: collections.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def convert_mesh_to_paths(meshWidth, meshHeight, coordinates):
        """
        Converts a given mesh into a sequence of
        :class:`matplotlib.path.Path` objects for easier rendering by
        backends that do not directly support quadmeshes.

        This function is primarily of use to backend implementers.
        """
        Path = mpath.Path

        if ma.isMaskedArray(coordinates):
            c = coordinates.data
        else:
            c = coordinates

        points = np.concatenate((
                    c[0:-1, 0:-1],
                    c[0:-1, 1:],
                    c[1:, 1:],
                    c[1:, 0:-1],
                    c[0:-1, 0:-1]
                ), axis=2)
        points = points.reshape((meshWidth * meshHeight, 5, 2))
        return [Path(x) for x in points] 
Example #9
Source File: spines.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def linear_spine(cls, axes, spine_type, **kwargs):
        """
        (staticmethod) Returns a linear :class:`Spine`.
        """
        # all values of 0.999 get replaced upon call to set_bounds()
        if spine_type == 'left':
            path = mpath.Path([(0.0, 0.999), (0.0, 0.999)])
        elif spine_type == 'right':
            path = mpath.Path([(1.0, 0.999), (1.0, 0.999)])
        elif spine_type == 'bottom':
            path = mpath.Path([(0.999, 0.0), (0.999, 0.0)])
        elif spine_type == 'top':
            path = mpath.Path([(0.999, 1.0), (0.999, 1.0)])
        else:
            raise ValueError('unable to make path for spine "%s"' % spine_type)
        result = cls(axes, spine_type, path, **kwargs)
        result.set_visible(rcParams['axes.spines.{0}'.format(spine_type)])

        return result 
Example #10
Source File: ClipBorder.py    From PyMICAPS with GNU General Public License v2.0 6 votes vote down vote up
def readPath(filename, start_pos=13):
        """
        从类似第9类micaps数据中获取path
        :param start_pos: 
        :param filename: 数据文件全名
        :return: path对象的一个实例
        """
        try:
            file_object = open(filename)
            all_the_text = file_object.read()
            file_object.close()
            poses = all_the_text.strip().split()
            lon = [float(p) for p in poses[start_pos::2]]
            lat = [float(p) for p in poses[start_pos+1::2]]
            path = Path(zip(lon, lat))
            return path
        except Exception as err:
            print(u'【{0}】{1}-{2}'.format(filename, err, datetime.now()))
            return None 
Example #11
Source File: art3d.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def do_3d_projection(self, renderer):
        s = self._segment3d
        xs, ys, zs = zip(*s)
        vxs, vys,vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M)
        self._path2d = mpath.Path(zip(vxs, vys))
        # FIXME: coloring
        self._facecolor2d = self._facecolor3d
        return min(vzs) 
Example #12
Source File: ndscatter.py    From tridesclous with MIT License 5 votes vote down vote up
def inside_poly(data, vertices):
    return mpl_path(vertices).contains_points(data) 
Example #13
Source File: scene_mask.py    From kite with GNU General Public License v3.0 5 votes vote down vote up
def apply(self, displacement):
        sc = self.scene
        points = self.get_points()

        mask = num.full((sc.frame.rows, sc.frame.cols), False)
        for vertices in self.config.polygons.values():
            p = Path(vertices)
            mask |= p.contains_points(points).reshape(
                sc.frame.rows, sc.frame.cols)

        displacement[mask] = num.nan
        return displacement 
Example #14
Source File: art3d.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def do_3d_projection(self, renderer):
        s = self._segment3d
        xs, ys, zs = zip(*s)
        vxs, vys,vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M)
        self._path2d = mpath.Path(zip(vxs, vys), self._code3d)
        # FIXME: coloring
        self._facecolor2d = self._facecolor3d
        return min(vzs) 
Example #15
Source File: spines.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        assert isinstance(path, matplotlib.path.Path)
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior two ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example #16
Source File: backend_svg.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _write_svgfonts(self):
        if not rcParams['svg.fonttype'] == 'svgfont':
            return

        writer = self.writer
        writer.start(u'defs')
        for font_fname, chars in self._fonts.items():
            font = FT2Font(font_fname)
            font.set_size(72, 72)
            sfnt = font.get_sfnt()
            writer.start(u'font', id=sfnt[(1, 0, 0, 4)])
            writer.element(
                u'font-face',
                attrib={
                    u'font-family': font.family_name,
                    u'font-style': font.style_name.lower(),
                    u'units-per-em': u'72',
                    u'bbox': u' '.join(unicode(x / 64.0) for x in font.bbox)})
            for char in chars:
                glyph = font.load_char(char, flags=LOAD_NO_HINTING)
                verts, codes = font.get_path()
                path = Path(verts, codes)
                path_data = self._convert_path(path)
                # name = font.get_glyph_name(char)
                writer.element(
                    u'glyph',
                    d=path_data,
                    attrib={
                        # 'glyph-name': name,
                        u'unicode': unichr(char),
                        u'horiz-adv-x': unicode(glyph.linearHoriAdvance / 65536.0)})
            writer.end(u'font')
        writer.end(u'defs') 
Example #17
Source File: mask_utils.py    From HGL-pytorch with MIT License 5 votes vote down vote up
def make_mask(mask_size, box, polygons_list):
    """
    Mask size: int about how big mask will be
    box: [x1, y1, x2, y2, conf.]
    polygons_list: List of polygons that go inside the box
    """
    mask = np.zeros((mask_size, mask_size), dtype=np.bool)
    
    xy = np.meshgrid(_spaced_points(box[0], box[2], n=mask_size),
                     _spaced_points(box[1], box[3], n=mask_size)) 
    xy_flat = np.stack(xy, 2).reshape((-1, 2))

    for polygon in polygons_list:
        polygon_path = path.Path(polygon)
        mask |= polygon_path.contains_points(xy_flat).reshape((mask_size, mask_size))
    return mask.astype(np.float32)
#
#from matplotlib import pyplot as plt
#
#
#with open('XdtbL0dP0X0@44.json', 'r') as f:
#    metadata = json.load(f)
#from time import time
#s = time()
#for i in range(100):
#    mask = make_mask(14, metadata['boxes'][3], metadata['segms'][3])
#print("Elapsed {:3f}s".format(time()-s))
#plt.imshow(mask) 
Example #18
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def convert_mesh_to_paths(tri):
        """
        Converts a given mesh into a sequence of
        :class:`matplotlib.path.Path` objects for easier rendering by
        backends that do not directly support meshes.

        This function is primarily of use to backend implementers.
        """
        Path = mpath.Path
        triangles = tri.get_masked_triangles()
        verts = np.concatenate((tri.x[triangles][..., np.newaxis],
                                tri.y[triangles][..., np.newaxis]), axis=2)
        return [Path(x) for x in verts] 
Example #19
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, widths, heights, angles, units='points', **kwargs):
        """
        *widths*: sequence
            lengths of first axes (e.g., major axis lengths)

        *heights*: sequence
            lengths of second axes

        *angles*: sequence
            angles of first axes, degrees CCW from the X-axis

        *units*: ['points' | 'inches' | 'dots' | 'width' | 'height'
        | 'x' | 'y' | 'xy']

            units in which majors and minors are given; 'width' and
            'height' refer to the dimensions of the axes, while 'x'
            and 'y' refer to the *offsets* data units. 'xy' differs
            from all others in that the angle as plotted varies with
            the aspect ratio, and equals the specified angle only when
            the aspect ratio is unity.  Hence it behaves the same as
            the :class:`~matplotlib.patches.Ellipse` with
            axes.transData as its transform.

        Additional kwargs inherited from the base :class:`Collection`:

        %(Collection)s
        """
        Collection.__init__(self, **kwargs)
        self._widths = 0.5 * np.asarray(widths).ravel()
        self._heights = 0.5 * np.asarray(heights).ravel()
        self._angles = np.asarray(angles).ravel() * (np.pi / 180.0)
        self._units = units
        self.set_transform(transforms.IdentityTransform())
        self._transforms = []
        self._paths = [mpath.Path.unit_circle()] 
Example #20
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def set_segments(self, segments):
        if segments is None:
            return
        _segments = []

        for seg in segments:

            if not np.ma.isMaskedArray(seg):
                seg = np.asarray(seg, np.float_)
            _segments.append(seg)
        if self._uniform_offsets is not None:
            _segments = self._add_offsets(_segments)
        self._paths = [mpath.Path(seg) for seg in _segments] 
Example #21
Source File: roipoly.py    From roipoly.py with Apache License 2.0 5 votes vote down vote up
def get_mask(self, current_image):
        ny, nx = np.shape(current_image)
        poly_verts = ([(self.x[0], self.y[0])]
                      + list(zip(reversed(self.x), reversed(self.y))))
        # Create vertex coordinates for each grid cell...
        # (<0,0> is at the top left of the grid in this system)
        x, y = np.meshgrid(np.arange(nx), np.arange(ny))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x, y)).T

        roi_path = MplPath(poly_verts)
        grid = roi_path.contains_points(points).reshape((ny, nx))
        return grid 
Example #22
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, paths, sizes=None, **kwargs):
        """
        *paths* is a sequence of :class:`matplotlib.path.Path`
        instances.

        %(Collection)s
        """

        Collection.__init__(self, **kwargs)
        self.set_paths(paths)
        self._sizes = sizes 
Example #23
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _prepare_points(self):
        """Point prep for drawing and hit testing"""

        transform = self.get_transform()
        transOffset = self.get_offset_transform()
        offsets = self._offsets
        paths = self.get_paths()

        if self.have_units():
            paths = []
            for path in self.get_paths():
                vertices = path.vertices
                xs, ys = vertices[:, 0], vertices[:, 1]
                xs = self.convert_xunits(xs)
                ys = self.convert_yunits(ys)
                paths.append(mpath.Path(zip(xs, ys), path.codes))

            if offsets.size > 0:
                xs = self.convert_xunits(offsets[:, 0])
                ys = self.convert_yunits(offsets[:, 1])
                offsets = zip(xs, ys)

        offsets = np.asanyarray(offsets, np.float_)
        offsets.shape = (-1, 2)             # Make it Nx2

        if not transform.is_affine:
            paths = [transform.transform_path_non_affine(path)
                     for path in paths]
            transform = transform.get_affine()
        if not transOffset.is_affine:
            offsets = transOffset.transform_non_affine(offsets)
            # This might have changed an ndarray into a masked array.
            transOffset = transOffset.get_affine()

        if np.ma.isMaskedArray(offsets):
            offsets = offsets.filled(np.nan)
            # Changing from a masked array to nan-filled ndarray
            # is probably most efficient at this point.

        return transform, transOffset, offsets, paths 
Example #24
Source File: polar.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def transform_path_non_affine(self, path):
        vertices = path.vertices
        if len(vertices) == 2 and vertices[0, 0] == vertices[1, 0]:
            return Path(self.transform(vertices), path.codes)
        ipath = path.interpolated(path._interpolation_steps)
        return Path(self.transform(ipath.vertices), ipath.codes) 
Example #25
Source File: geo.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def transform_path_non_affine(self, path):
            vertices = path.vertices
            ipath = path.interpolated(self._resolution)
            return Path(self.transform(ipath.vertices), ipath.codes) 
Example #26
Source File: geo.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def transform_path_non_affine(self, path):
            vertices = path.vertices
            ipath = path.interpolated(self._resolution)
            return Path(self.transform(ipath.vertices), ipath.codes) 
Example #27
Source File: geo.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def transform_path_non_affine(self, path):
            vertices = path.vertices
            ipath = path.interpolated(self._resolution)
            return Path(self.transform(ipath.vertices), ipath.codes) 
Example #28
Source File: geo.py    From Computable with MIT License 5 votes vote down vote up
def transform_path_non_affine(self, path):
            vertices = path.vertices
            ipath = path.interpolated(self._resolution)
            return Path(self.transform(ipath.vertices), ipath.codes) 
Example #29
Source File: spines.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def circular_spine(cls, axes, center, radius, **kwargs):
        """
        (staticmethod) Returns a circular :class:`Spine`.
        """
        path = mpath.Path.unit_circle()
        spine_type = 'circle'
        result = cls(axes, spine_type, path, **kwargs)
        result.set_patch_circle(center, radius)
        return result 
Example #30
Source File: contour.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _make_paths(self, segs, kinds):
        if kinds is not None:
            return [mpath.Path(seg, codes=kind)
                    for seg, kind in zip(segs, kinds)]
        else:
            return [mpath.Path(seg) for seg in segs]