Python matplotlib.path() Examples

The following are 30 code examples of matplotlib.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 , or try the search function .
Example #1
Source File: backend_pdf.py    From matplotlib-4-abaqus with 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 #2
Source File: backend_pdf.py    From Computable with 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
Source File: backend_pdf.py    From Computable with 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
Source File: backend_pdf.py    From matplotlib-4-abaqus with 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 #5
Source File: backend_pdf.py    From Computable with 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 #6
Source File: backend_pdf.py    From matplotlib-4-abaqus with 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 #7
Source File: backend_wx.py    From Computable with 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
Source File: backend_macosx.py    From Computable with 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 #9
Source File: backend_wx.py    From matplotlib-4-abaqus with 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 #10
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 #11
Source File: backend_macosx.py    From matplotlib-4-abaqus with 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 #12
Source File: spines.py    From Computable 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 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 #13
Source File: backend_wx.py    From Mastering-Elasticsearch-7.0 with 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 #14
Source File: backend_wx.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw_path(self, gc, path, transform, rgbFace=None):
        gc.select()
        self.handle_clip_rectangle(gc)
        gfx_ctx = gc.gfx_ctx
        transform = transform + Affine2D().scale(1.0, -1.0).translate(0.0, self.height)
        wxpath = self.convert_path(gfx_ctx, path, transform)
        if rgbFace is not None:
            gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace)))
            gfx_ctx.DrawPath(wxpath)
        else:
            gfx_ctx.StrokePath(wxpath)
        gc.unselect() 
Example #15
Source File: backend_pdf.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def close_and_paint(self):
        """
        Return the appropriate pdf operator to close the path and
        cause it to be stroked, filled, or both.
        """
        return Op.paint_path(True, self.fillp(), self.strokep()) 
Example #16
Source File: backend_macosx.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw_path(self, gc, path, transform, rgbFace=None):
        if rgbFace is not None:
            rgbFace = tuple(rgbFace)
        linewidth = gc.get_linewidth()
        gc.draw_path(path, transform, linewidth, rgbFace) 
Example #17
Source File: backend_wx.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def convert_path(gfx_ctx, path, transform):
        wxpath = gfx_ctx.CreatePath()
        for points, code in path.iter_segments(transform):
            if code == Path.MOVETO:
                wxpath.MoveToPoint(*points)
            elif code == Path.LINETO:
                wxpath.AddLineToPoint(*points)
            elif code == Path.CURVE3:
                wxpath.AddQuadCurveToPoint(*points)
            elif code == Path.CURVE4:
                wxpath.AddCurveToPoint(*points)
            elif code == Path.CLOSEPOLY:
                wxpath.CloseSubpath()
        return wxpath 
Example #18
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 #19
Source File: backend_macosx.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
        if rgbFace is not None:
            rgbFace = tuple(rgbFace)
        linewidth = gc.get_linewidth()
        gc.draw_markers(marker_path, marker_trans, path, trans, linewidth, rgbFace) 
Example #20
Source File: geo.py    From matplotlib-4-abaqus with 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 #21
Source File: backend_pdf.py    From matplotlib-4-abaqus with 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 
Example #22
Source File: geo.py    From matplotlib-4-abaqus with 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 #23
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 #24
Source File: geo.py    From matplotlib-4-abaqus with 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 #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 __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 #27
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 #28
Source File: spines.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def arc_spine(cls, axes, spine_type, center, radius, theta1, theta2,
                  **kwargs):
        """
        (classmethod) Returns an arc :class:`Spine`.
        """
        path = mpath.Path.arc(theta1, theta2)
        result = cls(axes, spine_type, path, **kwargs)
        result.set_patch_arc(center, radius, theta1, theta2)
        return result 
Example #29
Source File: backend_wx.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def save_figure(self, *args):
        # Fetch the required filename and file type.
        filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards()
        default_file = self.canvas.get_default_filename()
        dlg = wx.FileDialog(self.canvas.GetParent(),
                            "Save to file", "", default_file, filetypes,
                            wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
        dlg.SetFilterIndex(filter_index)
        if dlg.ShowModal() == wx.ID_OK:
            dirname = dlg.GetDirectory()
            filename = dlg.GetFilename()
            DEBUG_MSG(
                'Save file dir:%s name:%s' %
                (dirname, filename), 3, self)
            format = exts[dlg.GetFilterIndex()]
            basename, ext = os.path.splitext(filename)
            if ext.startswith('.'):
                ext = ext[1:]
            if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format != ext:
                # looks like they forgot to set the image type drop
                # down, going with the extension.
                _log.warning('extension %s did not match the selected '
                             'image type %s; going with %s',
                             ext, format, ext)
                format = ext
            try:
                self.canvas.figure.savefig(
                    os.path.join(dirname, filename), format=format)
            except Exception as e:
                error_msg_wx(str(e)) 
Example #30
Source File: backend_wx.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _set_frame_icon(frame):
    # set frame icon
    bundle = wx.IconBundle()
    for image in ('matplotlib.png', 'matplotlib_large.png'):
        image = os.path.join(matplotlib.rcParams['datapath'], 'images', image)
        if not os.path.exists(image):
            continue
        icon = wx.Icon(_load_bitmap(image))
        if not icon.IsOk():
            return
        bundle.AddIcon(icon)
    frame.SetIcons(bundle)