Python matplotlib.path() Examples

The following are 30 code examples for showing how to use matplotlib.path(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: Computable   Author: ktraunmueller   File: backend_pdf.py    License: MIT License 6 votes vote down vote up
def _paint_path(closep, fillp, strokep):
    """Return the PDF operator to paint a path in the following way:
    closep:  close the path before painting
    fillp:   fill the path with the fill color
    strokep: stroke the outline of the path with the line color"""
    if strokep:
        if closep:
            if fillp:
                return Op.close_fill_stroke
            else:
                return Op.close_stroke
        else:
            if fillp:
                return Op.fill_stroke
            else:
                return Op.stroke
    else:
        if fillp:
            return Op.fill
        else:
            return Op.endpath 
Example 2
Project: Computable   Author: ktraunmueller   File: backend_pdf.py    License: MIT License 6 votes vote down vote up
def writePathCollectionTemplates(self):
        for (name, path, trans, ob, joinstyle, capstyle, padding, filled,
             stroked) in self.paths:
            pathops = self.pathOperations(path, trans, simplify=False)
            bbox = path.get_extents(trans)
            if not np.all(np.isfinite(bbox.extents)):
                extents = [0, 0, 0, 0]
            else:
                bbox = bbox.padded(padding)
                extents = list(bbox.extents)
            self.beginStream(
                ob.id, None,
                {'Type': Name('XObject'), 'Subtype': Name('Form'),
                 'BBox': extents})
            self.output(GraphicsContextPdf.joinstyles[joinstyle], Op.setlinejoin)
            self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap)
            self.output(*pathops)
            self.output(Op.paint_path(False, filled, stroked))
            self.endStream() 
Example 3
Project: Computable   Author: ktraunmueller   File: backend_pdf.py    License: MIT License 6 votes vote down vote up
def clip_cmd(self, cliprect, clippath):
        """Set clip rectangle. Calls self.pop() and self.push()."""
        cmds = []
        # Pop graphics state until we hit the right one or the stack is empty
        while ((self._cliprect, self._clippath) != (cliprect, clippath)
                and self.parent is not None):
            cmds.extend(self.pop())
        # Unless we hit the right one, set the clip polygon
        if ((self._cliprect, self._clippath) != (cliprect, clippath) or
            self.parent is None):
            cmds.extend(self.push())
            if self._cliprect != cliprect:
                cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath])
            if self._clippath != clippath:
                path, affine = clippath.get_transformed_path_and_affine()
                cmds.extend(
                    PdfFile.pathOperations(path, affine, simplify=False) +
                    [Op.clip, Op.endpath])
        return cmds 
Example 4
Project: Computable   Author: ktraunmueller   File: backend_wx.py    License: MIT License 6 votes vote down vote up
def _load_bitmap(filename):
    """
    Load a bitmap file from the backends/images subdirectory in which the
    matplotlib library is installed. The filename parameter should not
    contain any path information as this is determined automatically.

    Returns a wx.Bitmap object
    """

    basedir = os.path.join(rcParams['datapath'],'images')

    bmpFilename = os.path.normpath(os.path.join(basedir, filename))
    if not os.path.exists(bmpFilename):
        raise IOError('Could not find bitmap file "%s"; dying'%bmpFilename)

    bmp = wx.Bitmap(bmpFilename)
    return bmp 
Example 5
Project: Computable   Author: ktraunmueller   File: backend_macosx.py    License: MIT License 6 votes vote down vote up
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
                             offsets, offsetTrans, facecolors, edgecolors,
                             linewidths, linestyles, antialiaseds, urls,
                             offset_position):
        if offset_position=='data':
            offset_position = True
        else:
            offset_position = False
        path_ids = []
        for path, transform in self._iter_collection_raw_paths(
            master_transform, paths, all_transforms):
            path_ids.append((path, transform))
        master_transform = master_transform.get_matrix()
        all_transforms = [t.get_matrix() for t in all_transforms]
        offsetTrans = offsetTrans.get_matrix()
        gc.draw_path_collection(master_transform, path_ids, all_transforms,
                             offsets, offsetTrans, facecolors, edgecolors,
                             linewidths, linestyles, antialiaseds,
                             offset_position) 
Example 6
Project: Computable   Author: ktraunmueller   File: spines.py    License: 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 13 get replaced upon call to set_bounds()
        if spine_type == 'left':
            path = mpath.Path([(0.0, 13), (0.0, 13)])
        elif spine_type == 'right':
            path = mpath.Path([(1.0, 13), (1.0, 13)])
        elif spine_type == 'bottom':
            path = mpath.Path([(13, 0.0), (13, 0.0)])
        elif spine_type == 'top':
            path = mpath.Path([(13, 1.0), (13, 1.0)])
        else:
            raise ValueError('unable to make path for spine "%s"' % spine_type)
        result = cls(axes, spine_type, path, **kwargs)
        return result 
Example 7
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: backend_wx.py    License: MIT License 6 votes vote down vote up
def _load_bitmap(filename):
    """
    Load a bitmap file from the backends/images subdirectory in which the
    matplotlib library is installed. The filename parameter should not
    contain any path information as this is determined automatically.

    Returns a wx.Bitmap object
    """

    basedir = os.path.join(rcParams['datapath'], 'images')

    bmpFilename = os.path.normpath(os.path.join(basedir, filename))
    if not os.path.exists(bmpFilename):
        raise IOError('Could not find bitmap file "%s"; dying' % bmpFilename)

    bmp = wx.Bitmap(bmpFilename)
    return bmp 
Example 8
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: spines.py    License: 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 9
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_pdf.py    License: MIT License 6 votes vote down vote up
def _paint_path(closep, fillp, strokep):
    """Return the PDF operator to paint a path in the following way:
    closep:  close the path before painting
    fillp:   fill the path with the fill color
    strokep: stroke the outline of the path with the line color"""
    if strokep:
        if closep:
            if fillp:
                return Op.close_fill_stroke
            else:
                return Op.close_stroke
        else:
            if fillp:
                return Op.fill_stroke
            else:
                return Op.stroke
    else:
        if fillp:
            return Op.fill
        else:
            return Op.endpath 
Example 10
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_pdf.py    License: MIT License 6 votes vote down vote up
def writePathCollectionTemplates(self):
        for (name, path, trans, ob, joinstyle, capstyle, padding, filled,
             stroked) in self.paths:
            pathops = self.pathOperations(path, trans, simplify=False)
            bbox = path.get_extents(trans)
            if not np.all(np.isfinite(bbox.extents)):
                extents = [0, 0, 0, 0]
            else:
                bbox = bbox.padded(padding)
                extents = list(bbox.extents)
            self.beginStream(
                ob.id, None,
                {'Type': Name('XObject'), 'Subtype': Name('Form'),
                 'BBox': extents})
            self.output(GraphicsContextPdf.joinstyles[joinstyle], Op.setlinejoin)
            self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap)
            self.output(*pathops)
            self.output(Op.paint_path(False, filled, stroked))
            self.endStream() 
Example 11
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_pdf.py    License: MIT License 6 votes vote down vote up
def clip_cmd(self, cliprect, clippath):
        """Set clip rectangle. Calls self.pop() and self.push()."""
        cmds = []
        # Pop graphics state until we hit the right one or the stack is empty
        while ((self._cliprect, self._clippath) != (cliprect, clippath)
                and self.parent is not None):
            cmds.extend(self.pop())
        # Unless we hit the right one, set the clip polygon
        if ((self._cliprect, self._clippath) != (cliprect, clippath) or
            self.parent is None):
            cmds.extend(self.push())
            if self._cliprect != cliprect:
                cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath])
            if self._clippath != clippath:
                path, affine = clippath.get_transformed_path_and_affine()
                cmds.extend(
                    PdfFile.pathOperations(path, affine, simplify=False) +
                    [Op.clip, Op.endpath])
        return cmds 
Example 12
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_wx.py    License: MIT License 6 votes vote down vote up
def _load_bitmap(filename):
    """
    Load a bitmap file from the backends/images subdirectory in which the
    matplotlib library is installed. The filename parameter should not
    contain any path information as this is determined automatically.

    Returns a wx.Bitmap object
    """

    basedir = os.path.join(rcParams['datapath'],'images')

    bmpFilename = os.path.normpath(os.path.join(basedir, filename))
    if not os.path.exists(bmpFilename):
        raise IOError('Could not find bitmap file "%s"; dying'%bmpFilename)

    bmp = wx.Bitmap(bmpFilename)
    return bmp 
Example 13
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_macosx.py    License: MIT License 6 votes vote down vote up
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
                             offsets, offsetTrans, facecolors, edgecolors,
                             linewidths, linestyles, antialiaseds, urls,
                             offset_position):
        if offset_position=='data':
            offset_position = True
        else:
            offset_position = False
        path_ids = []
        for path, transform in self._iter_collection_raw_paths(
            master_transform, paths, all_transforms):
            path_ids.append((path, transform))
        master_transform = master_transform.get_matrix()
        all_transforms = [t.get_matrix() for t in all_transforms]
        offsetTrans = offsetTrans.get_matrix()
        gc.draw_path_collection(master_transform, path_ids, all_transforms,
                             offsets, offsetTrans, facecolors, edgecolors,
                             linewidths, linestyles, antialiaseds,
                             offset_position) 
Example 14
Project: PyMICAPS   Author: flashlxy   File: Map.py    License: GNU General Public License v2.0 5 votes vote down vote up
def DrawContourAndMark(contour, x, y, z, level, clipborder, patch, m):

        # 是否绘制等值线 ------ 等值线和标注是一体的

        if contour.contour['visible']:

            matplotlib.rcParams['contour.negative_linestyle'] = 'dashed'
            if contour.contour['colorline']:
                CS1 = m.contour(x, y, z, levels=level, linewidths=contour.contour['linewidth'])
            else:
                CS1 = m.contour(x,
                                y,
                                z,
                                levels=level,
                                linewidths=contour.contour['linewidth'],
                                colors=contour.contour['linecolor'])

            # 是否绘制等值线标注
            CS2 = None
            if contour.contourlabel['visible']:
                CS2 = plt.clabel(CS1,
                                 inline=1,
                                 fmt=contour.contourlabel['fmt'],
                                 inline_spacing=contour.contourlabel['inlinespacing'],
                                 fontsize=contour.contourlabel['fontsize'],
                                 colors=contour.contourlabel['fontcolor'])

            # 用区域边界裁切等值线图
            if clipborder.path is not None and clipborder.using:
                for collection in CS1.collections:
                    # collection.set_clip_on(True)
                    collection.set_clip_path(patch)

                if CS2 is not None:
                    for text in CS2:
                        if not clipborder.path.contains_point(text.get_position()):
                            text.remove() 
Example 15
Project: PyMICAPS   Author: flashlxy   File: Map.py    License: GNU General Public License v2.0 5 votes vote down vote up
def DrawClipBorders(clipborders):

        # 绘制裁切区域边界并返回
        path = clipborders[0].path
        linewidth = clipborders[0].linewidth
        linecolor = clipborders[0].linecolor
        if path is not None:
            patch = patches.PathPatch(path, linewidth=linewidth, facecolor='none', edgecolor=linecolor)
            plt.gca().add_patch(patch)
        else:
            patch = None
        return patch 
Example 16
Project: PyMICAPS   Author: flashlxy   File: Map.py    License: GNU General Public License v2.0 5 votes vote down vote up
def DrawBorders(m, products):
        """
        画县市边界
        :param m: 画布对象(plt或投影后的plt)
        :param products: 产品参数
        :return: 
        """
        try:
            for area in products.map.borders:
                if not area.draw:
                    continue
                if area.filetype == 'SHP':  # shp文件
                    if m is plt:
                        # Map.DrawShapeFile(area)
                        Map.readshapefile(area.file.replace('.shp', ''),
                                          os.path.basename(area.file),
                                          color=area.linecolor,
                                          linewidth=area.linewidth)
                    else:
                        m.readshapefile(area.file.replace('.shp', ''),
                                        os.path.basename(area.file),
                                        color=area.linecolor)
                else:  # 文本文件 , 画之前 路径中的点已经被投影了
                    if area.path is None:
                        continue
                    if area.polygon == 'ON':
                        area_patch = patches.PathPatch(area.path,
                                                       linewidth=area.linewidth,
                                                       linestyle='solid',
                                                       facecolor='none',
                                                       edgecolor=area.linecolor)
                        plt.gca().add_patch(area_patch)
                    else:
                        x, y = list(zip(*area.path.vertices))
                        m.plot(x, y, 'k-', linewidth=area.linewidth, color=area.linecolor)
        except Exception as err:
            print(u'【{0}】{1}-{2}'.format(products.xmlfile, err, datetime.now())) 
Example 17
Project: PyMICAPS   Author: flashlxy   File: Map.py    License: GNU General Public License v2.0 5 votes vote down vote up
def DrawShapeFile(area):
        """
        在画布上绘制shp文件
        :param area: 包含shp文件名及线宽和线颜色的一个字典
        :return: 
        """
        try:
            shpfile = area.file
            border_shape = shapefile.Reader(shpfile)
            border = border_shape.shapes()
            for b in border:
                border_points = b.points
                path_data = []
                count = 0
                for cell in border_points:
                    if count == 0:
                        trans = (Path.MOVETO, (cell[0], cell[1]))
                        path_data += [trans]
                        cell_end = cell
                    else:
                        trans = (Path.CURVE4, (cell[0], cell[1]))
                        path_data += [trans]
                trans = (Path.CLOSEPOLY, (cell_end[0], cell_end[1]))
                path_data += [trans]

                codes, verts = list(zip(*path_data))
                path = Path(verts, codes)
                x, y = list(zip(*path.vertices))
                plt.plot(x, y, 'k-', linewidth=area.linewidth, color=area.linecolor)
        except Exception as err:
            print(u'【{0}】{1}-{2}'.format(area['file'], err, datetime.now())) 
Example 18
Project: PyMICAPS   Author: flashlxy   File: Map.py    License: GNU General Public License v2.0 5 votes vote down vote up
def GetFontProperties(font):
        fontfile = r"C:\WINDOWS\Fonts\{0}".format(font['family'])
        if not os.path.exists(fontfile):
            fp = FontProperties(family=font['family'], weight=font['weight'], size=font['size'])
        else:
            fp = FontProperties(fname=fontfile, weight=font['weight'], size=font['size'])
        return fp 
Example 19
Project: apls   Author: CosmiQ   File: apls_plots.py    License: Apache License 2.0 5 votes vote down vote up
def _ring_coding(ob):
    # The codes will be all "LINETO" commands, except for "MOVETO"s at the
    # beginning of each subpath
    n = len(ob.coords)
    codes = np.ones(n, dtype=matplotlib.path.Path.code_type) * \
        matplotlib.path.Path.LINETO
    codes[0] = matplotlib.path.Path.MOVETO
    return codes


###############################################################################
# https://sgillies.net/2010/04/06/painting-punctured-polygons-with-matplotlib.html 
Example 20
Project: apls   Author: CosmiQ   File: apls_plots.py    License: Apache License 2.0 5 votes vote down vote up
def _pathify(polygon):
    # Convert coordinates to path vertices. Objects produced by Shapely's
    # analytic methods have the proper coordinate order, no need to sort.
    vertices = np.concatenate(
        [np.asarray(polygon.exterior)]
        + [np.asarray(r) for r in polygon.interiors])
    codes = np.concatenate(
        [_ring_coding(polygon.exterior)]
        + [_ring_coding(r) for r in polygon.interiors])
    return matplotlib.path.Path(vertices, codes)
###############################################################################


############################################################################### 
Example 21
Project: Computable   Author: ktraunmueller   File: geo.py    License: MIT License 5 votes vote down vote up
def __init__(self, resolution):
            """
            Create a new Aitoff transform.  Resolution is the number of steps
            to interpolate between each input line segment to approximate its
            path in curved Aitoff space.
            """
            Transform.__init__(self)
            self._resolution = resolution 
Example 22
Project: Computable   Author: ktraunmueller   File: geo.py    License: 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 23
Project: Computable   Author: ktraunmueller   File: geo.py    License: MIT License 5 votes vote down vote up
def __init__(self, resolution):
            """
            Create a new Hammer transform.  Resolution is the number of steps
            to interpolate between each input line segment to approximate its
            path in curved Hammer space.
            """
            Transform.__init__(self)
            self._resolution = resolution 
Example 24
Project: Computable   Author: ktraunmueller   File: geo.py    License: 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 25
Project: Computable   Author: ktraunmueller   File: geo.py    License: MIT License 5 votes vote down vote up
def __init__(self, resolution):
            """
            Create a new Mollweide transform.  Resolution is the number of steps
            to interpolate between each input line segment to approximate its
            path in curved Mollweide space.
            """
            Transform.__init__(self)
            self._resolution = resolution 
Example 26
Project: Computable   Author: ktraunmueller   File: geo.py    License: MIT License 5 votes vote down vote up
def __init__(self, center_longitude, center_latitude, resolution):
            """
            Create a new Lambert transform.  Resolution is the number of steps
            to interpolate between each input line segment to approximate its
            path in curved Lambert space.
            """
            Transform.__init__(self)
            self._resolution = resolution
            self._center_longitude = center_longitude
            self._center_latitude = center_latitude 
Example 27
Project: Computable   Author: ktraunmueller   File: geo.py    License: 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
Project: Computable   Author: ktraunmueller   File: polar.py    License: 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 29
Project: Computable   Author: ktraunmueller   File: backend_pdf.py    License: MIT License 5 votes vote down vote up
def close(self):
        self.endStream()
        # Write out the various deferred objects
        self.writeFonts()
        self.writeObject(self.alphaStateObject,
                         dict([(val[0], val[1])
                               for val in self.alphaStates.itervalues()]))
        self.writeHatches()
        self.writeGouraudTriangles()
        xobjects = dict(self.images.itervalues())
        for tup in self.markers.itervalues():
            xobjects[tup[0]] = tup[1]
        for name, value in self.multi_byte_charprocs.iteritems():
            xobjects[name] = value
        for name, path, trans, ob, join, cap, padding, filled, stroked in self.paths:
            xobjects[name] = ob
        self.writeObject(self.XObjectObject, xobjects)
        self.writeImages()
        self.writeMarkers()
        self.writePathCollectionTemplates()
        self.writeObject(self.pagesObject,
                         { 'Type': Name('Pages'),
                           'Kids': self.pageList,
                           'Count': len(self.pageList) })
        self.writeInfoDict()

        # Finalize the file
        self.writeXref()
        self.writeTrailer()
        if self.passed_in_file_object:
            self.fh.flush()
        elif self.original_file_like is not None:
            self.original_file_like.write(self.fh.getvalue())
            self.fh.close()
        else:
            self.fh.close() 
Example 30
Project: Computable   Author: ktraunmueller   File: backend_pdf.py    License: MIT License 5 votes vote down vote up
def markerObject(self, path, trans, fillp, strokep, lw, joinstyle, capstyle):
        """Return name of a marker XObject representing the given path."""
        # self.markers used by markerObject, writeMarkers, close:
        # mapping from (path operations, fill?, stroke?) to
        #   [name, object reference, bounding box, linewidth]
        # This enables different draw_markers calls to share the XObject
        # if the gc is sufficiently similar: colors etc can vary, but
        # the choices of whether to fill and whether to stroke cannot.
        # We need a bounding box enclosing all of the XObject path,
        # but since line width may vary, we store the maximum of all
        # occurring line widths in self.markers.
        # close() is somewhat tightly coupled in that it expects the
        # first two components of each value in self.markers to be the
        # name and object reference.
        pathops = self.pathOperations(path, trans, simplify=False)
        key = (tuple(pathops), bool(fillp), bool(strokep), joinstyle, capstyle)
        result = self.markers.get(key)
        if result is None:
            name = Name('M%d' % len(self.markers))
            ob = self.reserveObject('marker %d' % len(self.markers))
            bbox = path.get_extents(trans)
            self.markers[key] = [name, ob, bbox, lw]
        else:
            if result[-1] < lw:
                result[-1] = lw
            name = result[0]
        return name