Python matplotlib.patches.PathPatch() Examples

The following are 30 code examples of matplotlib.patches.PathPatch(). 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: 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: colorbar.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _add_ends(self):
        """
        Create patches from extended ends and add them to the axes.
        """

        del self.extension_patch1
        del self.extension_patch2

        path1, path2 = self.ax.get_axes_locator().get_path_ends()
        fc=mpl.rcParams['axes.facecolor']
        ec=mpl.rcParams['axes.edgecolor']
        linewidths=0.5*mpl.rcParams['axes.linewidth']
        self.extension_patch1 = PathPatch(path1,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.extension_patch2 = PathPatch(path2,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.ax.add_artist(self.extension_patch1)
        self.ax.add_artist(self.extension_patch2) 
Example #3
Source File: colorbar.py    From Computable with MIT License 6 votes vote down vote up
def _add_ends(self):
        """
        Create patches from extended ends and add them to the axes.
        """

        del self.extension_patch1
        del self.extension_patch2

        path1, path2 = self.ax.get_axes_locator().get_path_ends()
        fc=mpl.rcParams['axes.facecolor']
        ec=mpl.rcParams['axes.edgecolor']
        linewidths=0.5*mpl.rcParams['axes.linewidth']
        self.extension_patch1 = PathPatch(path1,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.extension_patch2 = PathPatch(path2,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.ax.add_artist(self.extension_patch1)
        self.ax.add_artist(self.extension_patch2) 
Example #4
Source File: colorbar.py    From Computable with MIT License 6 votes vote down vote up
def _add_ends(self):
        """
        Create patches from extended ends and add them to the axes.
        """

        del self.extension_patch1
        del self.extension_patch2

        path1, path2 = self.ax.get_axes_locator().get_path_ends()
        fc=mpl.rcParams['axes.facecolor']
        ec=mpl.rcParams['axes.edgecolor']
        linewidths=0.5*mpl.rcParams['axes.linewidth']
        self.extension_patch1 = PathPatch(path1,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.extension_patch2 = PathPatch(path2,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.ax.add_artist(self.extension_patch1)
        self.ax.add_artist(self.extension_patch2) 
Example #5
Source File: NarrowPeakTrack.py    From pyGenomeTracks with GNU General Public License v3.0 6 votes vote down vote up
def peak_plot(self, start, end, height, center=None, width_adjust=1.5):
        # uses bezier curves to plot a shape that
        # looks like a peak
        peak_width = float(end - start)
        if center is None:
            center = peak_width / 2 + start
        if width_adjust != 1:
            start -= width_adjust * peak_width / 2
            end += width_adjust * peak_width / 2
            peak_width *= width_adjust

        path_data = [
            (Path.MOVETO, (start, 0)),
            (Path.CURVE4, (start + peak_width / 2, 0)),
            (Path.CURVE4, (start + peak_width * 0.4, height)),
            (Path.CURVE4, (center, height)),
            (Path.CURVE4, (end - peak_width * 0.4, height)),
            (Path.CURVE4, (end - peak_width / 2, 0)),
            (Path.CURVE4, (end, 0))]

        codes, verts = zip(*path_data)
        path = Path(verts, codes)
        return patches.PathPatch(path) 
Example #6
Source File: show_labels.py    From 3d-vehicle-tracking with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def poly2patch(self, vertices, types, closed=False, alpha=1., color=None):
        moves = {'L': Path.LINETO,
                 'C': Path.CURVE4}
        points = [v for v in vertices]
        codes = [moves[t] for t in types]
        codes[0] = Path.MOVETO

        if closed:
            points.append(points[0])
            codes.append(Path.CLOSEPOLY)

        if color is None:
            color = random_color()

        # print(codes, points)
        return mpatches.PathPatch(
            Path(points, codes),
            facecolor=color if closed else 'none',
            edgecolor=color,  # if not closed else 'none',
            lw=1 if closed else 2 * self.scale, alpha=alpha,
            antialiased=False, snap=True) 
Example #7
Source File: show_labels.py    From 3d-vehicle-tracking with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def poly2patch(self, poly2d, closed=False, alpha=1., color=None):
        moves = {'L': Path.LINETO,
                 'C': Path.CURVE4}
        points = [p[:2] for p in poly2d]
        codes = [moves[p[2]] for p in poly2d]
        codes[0] = Path.MOVETO

        if closed:
            points.append(points[0])
            codes.append(Path.CLOSEPOLY)

        if color is None:
            color = random_color()

        # print(codes, points)
        return mpatches.PathPatch(
            Path(points, codes),
            facecolor=color if closed else 'none',
            edgecolor=color,  # if not closed else 'none',
            lw=1 if closed else 2 * self.scale, alpha=alpha,
            antialiased=False, snap=True) 
Example #8
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _add_ends(self):
        """
        Create patches from extended ends and add them to the axes.
        """

        del self.extension_patch1
        del self.extension_patch2

        path1, path2 = self.ax.get_axes_locator().get_path_ends()
        fc=mpl.rcParams['axes.facecolor']
        ec=mpl.rcParams['axes.edgecolor']
        linewidths=0.5*mpl.rcParams['axes.linewidth']
        self.extension_patch1 = PathPatch(path1,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.extension_patch2 = PathPatch(path2,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.ax.add_artist(self.extension_patch1)
        self.ax.add_artist(self.extension_patch2) 
Example #9
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _add_ends(self):
        """
        Create patches from extended ends and add them to the axes.
        """

        del self.extension_patch1
        del self.extension_patch2

        path1, path2 = self.ax.get_axes_locator().get_path_ends()
        fc=mpl.rcParams['axes.facecolor']
        ec=mpl.rcParams['axes.edgecolor']
        linewidths=0.5*mpl.rcParams['axes.linewidth']
        self.extension_patch1 = PathPatch(path1,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.extension_patch2 = PathPatch(path2,
                                          fc=fc, ec=ec, lw=linewidths,
                                          zorder=2.,
                                          transform=self.ax.transAxes,
                                          clip_on=False)
        self.ax.add_artist(self.extension_patch1)
        self.ax.add_artist(self.extension_patch2) 
Example #10
Source File: pathpatch3d.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
    '''
    Plots the string 's' on the axes 'ax', with position 'xyz', size 'size',
    and rotation angle 'angle'.  'zdir' gives the axis which is to be treated
    as the third dimension.  usetex is a boolean indicating whether the string
    should be interpreted as latex or not.  Any additional keyword arguments
    are passed on to transform_path.

    Note: zdir affects the interpretation of xyz.
    '''
    x, y, z = xyz
    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "x":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z

    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir) 
Example #11
Source File: drawing.py    From discopy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def draw_wire(axis, source, target,
              bend_out=False, bend_in=False, to_tikz=False):
    """
    Draws a wire from source to target using a Bezier curve.
    """
    mid = (target[0], source[1]) if bend_out else (source[0], target[1])
    if to_tikz == "controls":
        cmd = "\\draw {} .. controls {} .. {};\n"
        axis.append(cmd.format(*("({}, {})".format(*point)
                                 for point in [source, mid, target])))
    elif to_tikz:
        out = -90 if not bend_out or source[0] == target[0]\
            else (180 if source[0] > target[0] else 0)
        inp = 90 if not bend_in or source[0] == target[0]\
            else (180 if source[0] < target[0] else 0)
        cmd = "\\draw [out={}, in={}] {{}} to {{}};\n".format(out, inp)
        axis.append(cmd.format(*("({}, {})".format(*point)
                                 for point in [source, target])))
    else:
        path = Path([source, mid, target],
                    [Path.MOVETO, Path.CURVE3, Path.CURVE3])
        axis.add_patch(PathPatch(path, facecolor='none')) 
Example #12
Source File: PlotMatplot.py    From Grid2Op with Mozilla Public License 2.0 6 votes vote down vote up
def _draw_powerline_line(self,
                             pos_or_x, pos_or_y,
                             pos_ex_x, pos_ex_y,
                             color, line_style):
        codes = [
            Path.MOVETO,
            Path.LINETO
        ]
        verts = [
            (pos_or_x, pos_or_y),
            (pos_ex_x, pos_ex_y)
        ]
        path = Path(verts, codes)
        patch = patches.PathPatch(path,
                                  color=color,
                                  lw=self._line_color_width,
                                  ls=line_style)
        self.ax.add_patch(patch) 
Example #13
Source File: show_labels.py    From bdd100k with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def poly2patch(self, vertices, types, closed=False, alpha=1., color=None):
        moves = {'L': Path.LINETO,
                 'C': Path.CURVE4}
        points = [v for v in vertices]
        codes = [moves[t] for t in types]
        codes[0] = Path.MOVETO

        if closed:
            points.append(points[0])
            codes.append(Path.CLOSEPOLY)

        if color is None:
            color = random_color()

        # print(codes, points)
        return mpatches.PathPatch(
            Path(points, codes),
            facecolor=color if closed else 'none',
            edgecolor=color,  # if not closed else 'none',
            lw=1 if closed else 2 * self.scale, alpha=alpha,
            antialiased=False, snap=True) 
Example #14
Source File: show_labels.py    From bdd100k with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def poly2patch(self, poly2d, closed=False, alpha=1., color=None):
        moves = {'L': Path.LINETO,
                 'C': Path.CURVE4}
        points = [p[:2] for p in poly2d]
        codes = [moves[p[2]] for p in poly2d]
        codes[0] = Path.MOVETO

        if closed:
            points.append(points[0])
            if codes[-1] == 4:
                codes.append(Path.LINETO)
            else:
                codes.append(Path.CLOSEPOLY)

        if color is None:
            color = random_color()

        # print(codes, points)
        return mpatches.PathPatch(
            Path(points, codes),
            facecolor=color if closed else 'none',
            edgecolor=color,  # if not closed else 'none',
            lw=1 if closed else 2 * self.scale, alpha=alpha,
            antialiased=False, snap=True) 
Example #15
Source File: listing13_4.py    From osgeopy-code with MIT License 6 votes vote down vote up
def plot_polygon_patch(poly, color):
    """Plots a polygon as a patch."""
    # Outer clockwise path.
    coords = poly.GetGeometryRef(0).GetPoints()
    coords = order_coords(coords, True)
    codes = make_codes(len(coords))
    for i in range(1, poly.GetGeometryCount()):

        # Inner counter-clockwise paths.
        coords2 = poly.GetGeometryRef(i).GetPoints()
        coords2 = order_coords(coords2, False)
        codes2 = make_codes(len(coords2))

        # Concatenate the paths.
        coords = np.concatenate((coords, coords2))
        codes = np.concatenate((codes, codes2))

    # Add the patch to the plot
    path = Path(coords, codes)
    patch = patches.PathPatch(path, facecolor=color)
    plt.axes().add_patch(patch)

# Loop through all of the features in the countries layer and create
# patches for the polygons. 
Example #16
Source File: plots.py    From nxviz with MIT License 6 votes vote down vote up
def draw_edges(self):
        """
        Renders edges to the figure.
        """
        for i, (start, end) in enumerate(self.graph.edges()):
            start_theta = node_theta(self.nodes, start)
            end_theta = node_theta(self.nodes, end)
            verts = [
                get_cartesian(self.plot_radius, start_theta),
                (0, 0),
                get_cartesian(self.plot_radius, end_theta),
            ]
            color = self.edge_colors[i]
            codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
            lw = self.edge_widths[i]
            path = Path(verts, codes)
            patch = patches.PathPatch(
                path, lw=lw, edgecolor=color, zorder=1, **self.edgeprops
            )
            self.ax.add_patch(patch) 
Example #17
Source File: simplevectorplotter.py    From osgeopy-code with MIT License 5 votes vote down vote up
def _plot_polygon(self, data, **kwargs):
        """Plot a polygon."""
        outer = self._order_vertices(data[0], True)
        inner = [self._order_vertices(d, False) for d in data[1:]]
        vertices = np.concatenate(
            [np.asarray(outer)] + [np.asarray(i) for i in inner])
        codes = np.concatenate(
            [self._codes(outer)] + [self._codes(i) for i in inner])
        patch = PathPatch(Path(vertices, codes), **kwargs)
        plt.axes().add_patch(patch)
        return [patch] 
Example #18
Source File: simplevectorplotter.py    From osgeopy-code with MIT License 5 votes vote down vote up
def show(self, name):
        """Show the layer with the given name."""
        try:
            graphics = self._graphics[name]
            graphic_type = type(graphics[0])
            if graphic_type is mpl.lines.Line2D:
                for graphic in graphics:
                    plt.axes().add_line(graphic)
            elif graphic_type is mpl.patches.Polygon or graphic_type is mpl.patches.PathPatch:
                for graphic in graphics:
                    plt.axes().add_patch(graphic)
            else:
                raise RuntimeError('{} not supported'.format(graphic_type))
        except KeyError:
            pass 
Example #19
Source File: patheffects.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __init__(self, offset=(0, 0), **kwargs):
        """
        Parameters
        ----------
        offset : pair of floats
            The offset to apply to the path, in points.
        **kwargs :
            All keyword arguments are passed through to the
            :class:`~matplotlib.patches.PathPatch` constructor. The
            properties which cannot be overridden are "path", "clip_box"
            "transform" and "clip_path".
        """
        super().__init__(offset=offset)
        self.patch = mpatches.PathPatch([], **kwargs) 
Example #20
Source File: simplevectorplotter.py    From osgeopy-code with MIT License 5 votes vote down vote up
def _codes(self, data):
        """Get a list of codes for creating a new PathPatch."""
        codes = np.ones(len(data), dtype=np.int) * Path.LINETO
        codes[0] = Path.MOVETO
        return codes 
Example #21
Source File: patheffects.py    From neural-network-animation with MIT License 5 votes vote down vote up
def __init__(self, offset=(0, 0), **kwargs):
        """
        Parameters
        ----------
        offset : pair of floats
            The offset to apply to the path, in points.
        **kwargs :
            All keyword arguments are passed through to the
            :class:`~matplotlib.patches.PathPatch` constructor. The
            properties which cannot be overridden are "path", "clip_box"
            "transform" and "clip_path".
        """
        super(PathPatchEffect, self).__init__(offset=offset)
        self.patch = mpatches.PathPatch([], **kwargs) 
Example #22
Source File: parse_svg.py    From pylustrator with GNU General Public License v3.0 5 votes vote down vote up
def plt_draw_text(node: minidom.Element, trans: mtransforms.Transform, style: dict, ids: dict, no_draw: bool = False):
    """ draw a svg text node as a text patch element into the figure (with the given transformation and style) """
    trans = parseTransformation(node.getAttribute("transform")) + trans + plt.gca().transData
    trans = mtransforms.Affine2D([[1, 0, 0], [0, -1, 0], [0, 0, 1]]) + trans
    pos = np.array([svgUnitToMpl(node.getAttribute("x")), -svgUnitToMpl(node.getAttribute("y"))])

    style = get_inline_style(node, get_css_style(node, ids["css"], style))

    text_content = ""
    patch_list = []
    for child in node.childNodes:
        text_content += child.firstChild.nodeValue
        if 1:
            style_child = get_inline_style(child, get_css_style(child, ids["css"], style))
            pos_child = pos.copy()
            if child.getAttribute("x") != "":
                pos_child = np.array([svgUnitToMpl(child.getAttribute("x")), -svgUnitToMpl(child.getAttribute("y"))])
            if child.getAttribute("dx") != "":
                pos_child[0] += svgUnitToMpl(child.getAttribute("dx"))
            if child.getAttribute("dy") != "":
                pos_child[1] -= svgUnitToMpl(child.getAttribute("dy"))
            path1 = TextPath(pos_child,
                             child.firstChild.nodeValue,
                             prop=font_properties_from_style(style_child))
            patch = mpatches.PathPatch(path1, transform=trans)

            apply_style(style_child, patch)
            if not no_draw and not styleNoDisplay(style_child):
                plt.gca().add_patch(patch)
            if child.getAttribute("id") != "":
                ids[child.getAttribute("id")] = patch
            patch_list.append(patch)
        else:
            text = plt.text(float(child.getAttribute("x")), float(child.getAttribute("y")),
                     child.firstChild.nodeValue,
                     transform=trans)
            apply_style(style, text)

    if node.getAttribute("id") != "":
        ids[node.getAttribute("id")] = patch_list 
Example #23
Source File: test_artist.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_clipping():
    exterior = mpath.Path.unit_rectangle().deepcopy()
    exterior.vertices *= 4
    exterior.vertices -= 2
    interior = mpath.Path.unit_circle().deepcopy()
    interior.vertices = interior.vertices[::-1]
    clip_path = mpath.Path(vertices=np.concatenate([exterior.vertices,
                                                    interior.vertices]),
                           codes=np.concatenate([exterior.codes,
                                                 interior.codes]))

    star = mpath.Path.unit_regular_star(6).deepcopy()
    star.vertices *= 2.6

    ax1 = plt.subplot(121)
    col = mcollections.PathCollection([star], lw=5, edgecolor='blue',
                                      facecolor='red', alpha=0.7, hatch='*')
    col.set_clip_path(clip_path, ax1.transData)
    ax1.add_collection(col)

    ax2 = plt.subplot(122, sharex=ax1, sharey=ax1)
    patch = mpatches.PathPatch(star, lw=5, edgecolor='blue', facecolor='red',
                               alpha=0.7, hatch='*')
    patch.set_clip_path(clip_path, ax2.transData)
    ax2.add_patch(patch)

    ax1.set_xlim([-3, 3])
    ax1.set_ylim([-3, 3]) 
Example #24
Source File: test_simplification.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_simplify_curve():
    pp1 = patches.PathPatch(
        Path([(0, 0), (1, 0), (1, 1), (nan, 1), (0, 0), (2, 0), (2, 2), (0, 0)],
             [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]),
        fc="none")

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.add_patch(pp1)
    ax.set_xlim((0, 2))
    ax.set_ylim((0, 2)) 
Example #25
Source File: test_transforms.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_pathc_extents_affine(self):
        ax = plt.axes()
        offset = mtrans.Affine2D().translate(10, 10)
        pth = mpath.Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
        patch = mpatches.PathPatch(pth, transform=offset + ax.transData)
        ax.add_patch(patch)
        expeted_data_lim = np.array([[0., 0.], [10.,  10.]]) + 10
        np.testing.assert_array_almost_equal(ax.dataLim.get_points(),
                                             expeted_data_lim) 
Example #26
Source File: test_transforms.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_pathc_extents_non_affine(self):
        ax = plt.axes()
        offset = mtrans.Affine2D().translate(10, 10)
        na_offset = NonAffineForTest(mtrans.Affine2D().translate(10, 10))
        pth = mpath.Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
        patch = mpatches.PathPatch(pth, transform=offset + na_offset + ax.transData)
        ax.add_patch(patch)
        expeted_data_lim = np.array([[0., 0.], [10.,  10.]]) + 20
        np.testing.assert_array_almost_equal(ax.dataLim.get_points(),
                                             expeted_data_lim) 
Example #27
Source File: test_patches.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_patch_alpha_override():
    #: Test checks that specifying an alpha attribute for a patch or
    #: collection will override any alpha component of the facecolor
    #: or edgecolor.
    star = mpath.Path.unit_regular_star(6)
    circle = mpath.Path.unit_circle()
    # concatenate the star with an internal cutout of the circle
    verts = np.concatenate([circle.vertices, star.vertices[::-1]])
    codes = np.concatenate([circle.codes, star.codes])
    cut_star1 = mpath.Path(verts, codes)
    cut_star2 = mpath.Path(verts + 1, codes)

    ax = plt.axes()
    patch = mpatches.PathPatch(cut_star1,
                               linewidth=5, linestyle='dashdot',
                               alpha=0.25,
                               facecolor=(1, 0, 0, 0.5),
                               edgecolor=(0, 0, 1, 0.75))
    ax.add_patch(patch)

    col = mcollections.PathCollection([cut_star2],
                                      linewidth=5, linestyles='dashdot',
                                      alpha=0.25,
                                      facecolor=(1, 0, 0, 0.5),
                                      edgecolor=(0, 0, 1, 0.75))
    ax.add_collection(col)

    ax.set_xlim([-1, 2])
    ax.set_ylim([-1, 2]) 
Example #28
Source File: test_patches.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_patch_alpha_coloring():
    """
    Test checks that the patch and collection are rendered with the specified
    alpha values in their facecolor and edgecolor.
    """
    star = mpath.Path.unit_regular_star(6)
    circle = mpath.Path.unit_circle()
    # concatenate the star with an internal cutout of the circle
    verts = np.concatenate([circle.vertices, star.vertices[::-1]])
    codes = np.concatenate([circle.codes, star.codes])
    cut_star1 = mpath.Path(verts, codes)
    cut_star2 = mpath.Path(verts + 1, codes)

    ax = plt.axes()
    patch = mpatches.PathPatch(cut_star1,
                               linewidth=5, linestyle='dashdot',
                               facecolor=(1, 0, 0, 0.5),
                               edgecolor=(0, 0, 1, 0.75))
    ax.add_patch(patch)

    col = mcollections.PathCollection([cut_star2],
                                      linewidth=5, linestyles='dashdot',
                                      facecolor=(1, 0, 0, 0.5),
                                      edgecolor=(0, 0, 1, 0.75))
    ax.add_collection(col)

    ax.set_xlim([-1, 2])
    ax.set_ylim([-1, 2]) 
Example #29
Source File: test_patches.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_clip_to_bbox():
    fig = plt.figure()

    ax = fig.add_subplot(111)
    ax.set_xlim([-18, 20])
    ax.set_ylim([-150, 100])

    path = mpath.Path.unit_regular_star(8).deepcopy()
    path.vertices *= [10, 100]
    path.vertices -= [5, 25]

    path2 = mpath.Path.unit_circle().deepcopy()
    path2.vertices *= [10, 100]
    path2.vertices += [10, -25]

    combined = mpath.Path.make_compound_path(path, path2)

    patch = mpatches.PathPatch(
        combined, alpha=0.5, facecolor='coral', edgecolor='none')
    ax.add_patch(patch)

    bbox = mtrans.Bbox([[-12, -77.5], [50, -110]])
    result_path = combined.clip_to_bbox(bbox)
    result_patch = mpatches.PathPatch(
        result_path, alpha=0.5, facecolor='green', lw=4, edgecolor='black')

    ax.add_patch(result_patch) 
Example #30
Source File: Map.py    From PyMICAPS with 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()))