Python matplotlib.path.Path.CLOSEPOLY Examples

The following are 30 code examples of matplotlib.path.Path.CLOSEPOLY(). 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.Path , or try the search function .
Example #1
Source File: patches.py    From neural-network-animation with MIT License 6 votes vote down vote up
def transmute(self, path, mutation_size, linewidth):

            x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)

            arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
            b_plus, b_minus = make_wedged_bezier2(
                                    arrow_path,
                                    self.tail_width * mutation_size / 2.,
                                    wm=self.shrink_factor)

            patch_path = [(Path.MOVETO, b_plus[0]),
                          (Path.CURVE3, b_plus[1]),
                          (Path.CURVE3, b_plus[2]),
                          (Path.LINETO, b_minus[2]),
                          (Path.CURVE3, b_minus[1]),
                          (Path.CURVE3, b_minus[0]),
                          (Path.CLOSEPOLY, b_minus[0]),
                          ]
            path = Path([p for c, p in patch_path], [c for c, p in patch_path])

            return path, True 
Example #2
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 #3
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 #4
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 #5
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 #6
Source File: backend_cairo.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def _append_paths_slow(ctx, paths, transforms, clip=None):
    for path, transform in zip(paths, transforms):
        for points, code in path.iter_segments(
                transform, remove_nans=True, clip=clip):
            if code == Path.MOVETO:
                ctx.move_to(*points)
            elif code == Path.CLOSEPOLY:
                ctx.close_path()
            elif code == Path.LINETO:
                ctx.line_to(*points)
            elif code == Path.CURVE3:
                cur = np.asarray(ctx.get_current_point())
                a = points[:2]
                b = points[-2:]
                ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b)
            elif code == Path.CURVE4:
                ctx.curve_to(*points) 
Example #7
Source File: test_transforms.py    From ImageFusion with MIT License 6 votes vote down vote up
def test_clipping_of_log():
    # issue 804
    M,L,C = Path.MOVETO, Path.LINETO, Path.CLOSEPOLY
    points = [ (0.2, -99), (0.4, -99), (0.4, 20), (0.2, 20), (0.2, -99) ]
    codes  = [          M,          L,        L,         L,          C  ]
    path = Path(points, codes)

    # something like this happens in plotting logarithmic histograms
    trans = BlendedGenericTransform(Affine2D(),
                                    LogScale.Log10Transform('clip'))
    tpath = trans.transform_path_non_affine(path)
    result = tpath.iter_segments(trans.get_affine(),
                                 clip=(0, 0, 100, 100),
                                 simplify=False)

    tpoints, tcodes = list(zip(*result))
    # Because y coordinate -99 is outside the clip zone, the first
    # line segment is effectively removed. That means that the closepoly
    # operation must be replaced by a move to the first point.
    assert np.allclose(tcodes, [ M, M, L, L, L ]) 
Example #8
Source File: patches.py    From ImageFusion with MIT License 6 votes vote down vote up
def transmute(self, path, mutation_size, linewidth):

            x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)

            arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
            b_plus, b_minus = make_wedged_bezier2(
                                    arrow_path,
                                    self.tail_width * mutation_size / 2.,
                                    wm=self.shrink_factor)

            patch_path = [(Path.MOVETO, b_plus[0]),
                          (Path.CURVE3, b_plus[1]),
                          (Path.CURVE3, b_plus[2]),
                          (Path.LINETO, b_minus[2]),
                          (Path.CURVE3, b_minus[1]),
                          (Path.CURVE3, b_minus[0]),
                          (Path.CLOSEPOLY, b_minus[0]),
                          ]
            path = Path([p for c, p in patch_path], [c for c, p in patch_path])

            return path, True 
Example #9
Source File: inset_locator.py    From Computable with MIT License 6 votes vote down vote up
def get_path(self):
       x0, y0, x1, y1 = self.bbox.extents

       verts = [(x0, y0),
                (x1, y0),
                (x1, y1),
                (x0, y1),
                (x0, y0),
                (0,0)]

       codes = [Path.MOVETO,
                Path.LINETO,
                Path.LINETO,
                Path.LINETO,
                Path.LINETO,
                Path.CLOSEPOLY]

       return Path(verts, codes) 
Example #10
Source File: test_table.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_customcell():
    types = ('horizontal', 'vertical', 'open', 'closed', 'T', 'R', 'B', 'L')
    codes = (
        (Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, Path.MOVETO),
        (Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO),
        (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO),
        (Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY),
        (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO),
        (Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.MOVETO),
        (Path.MOVETO, Path.LINETO, Path.MOVETO, Path.MOVETO, Path.MOVETO),
        (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.LINETO),
        )

    for t, c in zip(types, codes):
        cell = CustomCell((0, 0), visible_edges=t, width=1, height=1)
        code = tuple(s for _, s in cell.get_path().iter_segments())
        assert c == code 
Example #11
Source File: test_transforms.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_clipping_of_log():
    # issue 804
    M, L, C = Path.MOVETO, Path.LINETO, Path.CLOSEPOLY
    points = [(0.2, -99), (0.4, -99), (0.4, 20), (0.2, 20), (0.2, -99)]
    codes = [M, L, L, L, C]
    path = Path(points, codes)

    # something like this happens in plotting logarithmic histograms
    trans = mtransforms.BlendedGenericTransform(mtransforms.Affine2D(),
                                            LogScale.Log10Transform('clip'))
    tpath = trans.transform_path_non_affine(path)
    result = tpath.iter_segments(trans.get_affine(),
                                 clip=(0, 0, 100, 100),
                                 simplify=False)

    tpoints, tcodes = zip(*result)
    assert_allclose(tcodes, [M, L, L, L, C]) 
Example #12
Source File: backend_cairo.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _append_paths_slow(ctx, paths, transforms, clip=None):
    for path, transform in zip(paths, transforms):
        for points, code in path.iter_segments(
                transform, remove_nans=True, clip=clip):
            if code == Path.MOVETO:
                ctx.move_to(*points)
            elif code == Path.CLOSEPOLY:
                ctx.close_path()
            elif code == Path.LINETO:
                ctx.line_to(*points)
            elif code == Path.CURVE3:
                cur = np.asarray(ctx.get_current_point())
                a = points[:2]
                b = points[-2:]
                ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b)
            elif code == Path.CURVE4:
                ctx.curve_to(*points) 
Example #13
Source File: firefox.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def svg_parse(path):
    commands = {'M': (Path.MOVETO,),
                'L': (Path.LINETO,),
                'Q': (Path.CURVE3,)*2,
                'C': (Path.CURVE4,)*3,
                'Z': (Path.CLOSEPOLY,)}
    path_re = re.compile(r'([MLHVCSQTAZ])([^MLHVCSQTAZ]+)', re.IGNORECASE)
    float_re = re.compile(r'(?:[\s,]*)([+-]?\d+(?:\.\d+)?)')
    vertices = []
    codes = []
    last = (0, 0)
    for cmd, values in path_re.findall(path):
        points = [float(v) for v in float_re.findall(values)]
        points = np.array(points).reshape((len(points)//2, 2))
        if cmd.islower():
            points += last
        cmd = cmd.capitalize()
        last = points[-1]
        codes.extend(commands[cmd])
        vertices.extend(points.tolist())
    return codes, vertices

# SVG to matplotlib 
Example #14
Source File: HumanPts.py    From CU-Net with Apache License 2.0 6 votes vote down vote up
def polygon(pts, img_shape):
    # codes = [Path.MOVETO,
    #          Path.LINETO,
    #          Path.LINETO,
    #          Path.LINETO,
    #          Path.CLOSEPOLY,
    #          ]
    x, y = np.meshgrid(np.arange(img_shape[0]), np.arange(img_shape[1]))
    x, y = x.flatten(), y.flatten()

    points = np.vstack((x, y)).T

    path = Path(pts)
    grid = path.contains_points(points)
    mask = grid.reshape((img_shape[0], img_shape[1]))
    # y, x = np.where(grid)
    return mask 
Example #15
Source File: inset_locator.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def get_path(self):
       x0, y0, x1, y1 = self.bbox.extents

       verts = [(x0, y0),
                (x1, y0),
                (x1, y1),
                (x0, y1),
                (x0, y0),
                (0,0)]

       codes = [Path.MOVETO,
                Path.LINETO,
                Path.LINETO,
                Path.LINETO,
                Path.LINETO,
                Path.CLOSEPOLY]

       return Path(verts, codes) 
Example #16
Source File: backend_cairo.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _append_paths_slow(ctx, paths, transforms, clip=None):
    for path, transform in zip(paths, transforms):
        for points, code in path.iter_segments(transform, clip=clip):
            if code == Path.MOVETO:
                ctx.move_to(*points)
            elif code == Path.CLOSEPOLY:
                ctx.close_path()
            elif code == Path.LINETO:
                ctx.line_to(*points)
            elif code == Path.CURVE3:
                cur = ctx.get_current_point()
                ctx.curve_to(
                    *np.concatenate([cur / 3 + points[:2] * 2 / 3,
                                     points[:2] * 2 / 3 + points[-2:] / 3]))
            elif code == Path.CURVE4:
                ctx.curve_to(*points) 
Example #17
Source File: test_transforms.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_clipping_of_log():
    # issue 804
    M,L,C = Path.MOVETO, Path.LINETO, Path.CLOSEPOLY
    points = [ (0.2, -99), (0.4, -99), (0.4, 20), (0.2, 20), (0.2, -99) ]
    codes  = [          M,          L,        L,         L,          C  ]
    path = Path(points, codes)

    # something like this happens in plotting logarithmic histograms
    trans = BlendedGenericTransform(Affine2D(),
                                    LogScale.Log10Transform('clip'))
    tpath = trans.transform_path_non_affine(path)
    result = tpath.iter_segments(trans.get_affine(),
                                 clip=(0, 0, 100, 100),
                                 simplify=False)

    tpoints, tcodes = list(zip(*result))
    # Because y coordinate -99 is outside the clip zone, the first
    # line segment is effectively removed. That means that the closepoly
    # operation must be replaced by a move to the first point.
    assert np.allclose(tcodes, [ M, M, L, L, L ]) 
Example #18
Source File: backend_cairo.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def _append_path(ctx, path, transform, clip=None):
    for points, code in path.iter_segments(
            transform, remove_nans=True, clip=clip):
        if code == Path.MOVETO:
            ctx.move_to(*points)
        elif code == Path.CLOSEPOLY:
           ctx.close_path()
        elif code == Path.LINETO:
            ctx.line_to(*points)
        elif code == Path.CURVE3:
            cur = np.asarray(ctx.get_current_point())
            a = points[:2]
            b = points[-2:]
            ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b)
        elif code == Path.CURVE4:
            ctx.curve_to(*points) 
Example #19
Source File: test_transforms.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_transformed_path():
    points = [(0, 0), (1, 0), (1, 1), (0, 1)]
    codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]
    path = Path(points, codes)

    trans = mtransforms.Affine2D()
    trans_path = mtransforms.TransformedPath(path, trans)
    assert_allclose(trans_path.get_fully_transformed_path().vertices, points)

    # Changing the transform should change the result.
    r2 = 1 / np.sqrt(2)
    trans.rotate(np.pi / 4)
    assert_allclose(trans_path.get_fully_transformed_path().vertices,
                    [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)],
                    atol=1e-15)

    # Changing the path does not change the result (it's cached).
    path.points = [(0, 0)] * 4
    assert_allclose(trans_path.get_fully_transformed_path().vertices,
                    [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)],
                    atol=1e-15) 
Example #20
Source File: backend_ps.py    From neural-network-animation with MIT License 5 votes vote down vote up
def _convert_path(self, path, transform, clip=False, simplify=None):
        ps = []
        last_points = None
        if clip:
            clip = (0.0, 0.0, self.width * 72.0,
                    self.height * 72.0)
        else:
            clip = None
        for points, code in path.iter_segments(transform, clip=clip,
                                               simplify=simplify):
            if code == Path.MOVETO:
                ps.append("%g %g m" % tuple(points))
            elif code == Path.CLOSEPOLY:
                ps.append("cl")
            elif last_points is None:
                # The other operations require a previous point
                raise ValueError('Path lacks initial MOVETO')
            elif code == Path.LINETO:
                ps.append("%g %g l" % tuple(points))
            elif code == Path.CURVE3:
                points = quad2cubic(*(list(last_points[-2:]) + list(points)))
                ps.append("%g %g %g %g %g %g c" %
                          tuple(points[2:]))
            elif code == Path.CURVE4:
                ps.append("%g %g %g %g %g %g c" % tuple(points))
            last_points = points

        ps = "\n".join(ps)
        return ps 
Example #21
Source File: mpl.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def linearring_to_mpl_path(linearring):
    return Path(np.array(linearring),
                (Path.MOVETO, *([Path.LINETO] * (len(linearring.coords)-2)), Path.CLOSEPOLY), readonly=True) 
Example #22
Source File: backend_cairo.py    From neural-network-animation with MIT License 5 votes vote down vote up
def convert_path(ctx, path, transform):
        for points, code in path.iter_segments(transform):
            if code == Path.MOVETO:
                ctx.move_to(*points)
            elif code == Path.CLOSEPOLY:
                ctx.close_path()
            elif code == Path.LINETO:
                ctx.line_to(*points)
            elif code == Path.CURVE3:
                ctx.curve_to(points[0], points[1],
                             points[0], points[1],
                             points[2], points[3])
            elif code == Path.CURVE4:
                ctx.curve_to(*points) 
Example #23
Source File: backend_pdf.py    From ImageFusion with MIT License 5 votes vote down vote up
def pathOperations(path, transform, clip=None, simplify=None, sketch=None):
        cmds = []
        last_points = None
        for points, code in path.iter_segments(transform, clip=clip,
                                               simplify=simplify,
                                               sketch=sketch):
            if code == Path.MOVETO:
                # This is allowed anywhere in the path
                cmds.extend(points)
                cmds.append(Op.moveto)
            elif code == Path.CLOSEPOLY:
                cmds.append(Op.closepath)
            elif last_points is None:
                # The other operations require a previous point
                raise ValueError('Path lacks initial MOVETO')
            elif code == Path.LINETO:
                cmds.extend(points)
                cmds.append(Op.lineto)
            elif code == Path.CURVE3:
                points = quad2cubic(*(list(last_points[-2:]) + list(points)))
                cmds.extend(points[2:])
                cmds.append(Op.curveto)
            elif code == Path.CURVE4:
                cmds.extend(points)
                cmds.append(Op.curveto)
            last_points = points
        return cmds 
Example #24
Source File: backend_pdf.py    From neural-network-animation with MIT License 5 votes vote down vote up
def pathOperations(path, transform, clip=None, simplify=None, sketch=None):
        cmds = []
        last_points = None
        for points, code in path.iter_segments(transform, clip=clip,
                                               simplify=simplify,
                                               sketch=sketch):
            if code == Path.MOVETO:
                # This is allowed anywhere in the path
                cmds.extend(points)
                cmds.append(Op.moveto)
            elif code == Path.CLOSEPOLY:
                cmds.append(Op.closepath)
            elif last_points is None:
                # The other operations require a previous point
                raise ValueError('Path lacks initial MOVETO')
            elif code == Path.LINETO:
                cmds.extend(points)
                cmds.append(Op.lineto)
            elif code == Path.CURVE3:
                points = quad2cubic(*(list(last_points[-2:]) + list(points)))
                cmds.extend(points[2:])
                cmds.append(Op.curveto)
            elif code == Path.CURVE4:
                cmds.extend(points)
                cmds.append(Op.curveto)
            last_points = points
        return cmds 
Example #25
Source File: patches.py    From ImageFusion with MIT License 5 votes vote down vote up
def transmute(self, x0, y0, width, height, mutation_size):

            # padding
            pad = mutation_size * self.pad

            # roudning size. Use a half of the pad if not set.
            if self.rounding_size:
                dr = mutation_size * self.rounding_size
            else:
                dr = pad / 2.

            width, height = width + 2. * pad - 2 * dr, \
                            height + 2. * pad - 2 * dr,

            x0, y0 = x0 - pad + dr, y0 - pad + dr,
            x1, y1 = x0 + width, y0 + height

            cp = [(x0, y0),
                  (x0 + dr, y0 - dr), (x1 - dr, y0 - dr), (x1, y0),
                  (x1 + dr, y0 + dr), (x1 + dr, y1 - dr), (x1, y1),
                  (x1 - dr, y1 + dr), (x0 + dr, y1 + dr), (x0, y1),
                  (x0 - dr, y1 - dr), (x0 - dr, y0 + dr), (x0, y0),
                  (x0, y0)]

            com = [Path.MOVETO,
                   Path.CURVE4, Path.CURVE4, Path.CURVE4,
                   Path.CURVE4, Path.CURVE4, Path.CURVE4,
                   Path.CURVE4, Path.CURVE4, Path.CURVE4,
                   Path.CURVE4, Path.CURVE4, Path.CURVE4,
                   Path.CLOSEPOLY]

            path = Path(cp, com)

            return path 
Example #26
Source File: patches.py    From ImageFusion with MIT License 5 votes vote down vote up
def transmute(self, x0, y0, width, height, mutation_size):
            # padding
            pad = mutation_size * self.pad

            # width and height with padding added.
            width, height = width + 2. * pad, \
                            height + 2. * pad,

            # boundary of the padded box
            x0, y0 = x0 - pad, y0 - pad,
            x1, y1 = x0 + width, y0 + height

            dx = (y1 - y0) / 2.
            dxx = dx * .5
            # adjust x0.  1.4 <- sqrt(2)
            x0 = x0 + pad / 1.4

            cp = [(x0 + dxx, y0), (x1, y0), (x1, y1), (x0 + dxx, y1),
                  (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
                  (x0 + dxx, y0 - dxx),  # arrow
                  (x0 + dxx, y0), (x0 + dxx, y0)]

            com = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
                   Path.LINETO, Path.LINETO, Path.LINETO,
                   Path.LINETO, Path.CLOSEPOLY]

            path = Path(cp, com)

            return path 
Example #27
Source File: backend_wx.py    From GraphicDesignPatternByPython 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 #28
Source File: backend_pgf.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def _print_pgf_path(self, gc, path, transform, rgbFace=None):
        f = 1. / self.dpi
        # check for clip box / ignore clip for filled paths
        bbox = gc.get_clip_rectangle() if gc else None
        if bbox and (rgbFace is None):
            p1, p2 = bbox.get_points()
            clip = (p1[0], p1[1], p2[0], p2[1])
        else:
            clip = None
        # build path
        for points, code in path.iter_segments(transform, clip=clip):
            if code == Path.MOVETO:
                x, y = tuple(points)
                writeln(self.fh,
                        r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" %
                        (f * x, f * y))
            elif code == Path.CLOSEPOLY:
                writeln(self.fh, r"\pgfpathclose")
            elif code == Path.LINETO:
                x, y = tuple(points)
                writeln(self.fh,
                        r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" %
                        (f * x, f * y))
            elif code == Path.CURVE3:
                cx, cy, px, py = tuple(points)
                coords = cx * f, cy * f, px * f, py * f
                writeln(self.fh,
                        r"\pgfpathquadraticcurveto"
                        r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
                        % coords)
            elif code == Path.CURVE4:
                c1x, c1y, c2x, c2y, px, py = tuple(points)
                coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f
                writeln(self.fh,
                        r"\pgfpathcurveto"
                        r"{\pgfqpoint{%fin}{%fin}}"
                        r"{\pgfqpoint{%fin}{%fin}}"
                        r"{\pgfqpoint{%fin}{%fin}}"
                        % coords) 
Example #29
Source File: matplotlib-chord.py    From matplotlib-chord-diagram with MIT License 5 votes vote down vote up
def IdeogramArc(start=0, end=60, radius=1.0, width=0.2, ax=None, color=(1,0,0)):
    # start, end should be in [0, 360)
    if start > end:
        start, end = end, start
    start *= np.pi/180.
    end *= np.pi/180.
    # optimal distance to the control points
    # https://stackoverflow.com/questions/1734745/how-to-create-circle-with-b%C3%A9zier-curves
    opt = 4./3. * np.tan((end-start)/ 4.) * radius
    inner = radius*(1-width)
    verts = [
        polar2xy(radius, start),
        polar2xy(radius, start) + polar2xy(opt, start+0.5*np.pi),
        polar2xy(radius, end) + polar2xy(opt, end-0.5*np.pi),
        polar2xy(radius, end),
        polar2xy(inner, end),
        polar2xy(inner, end) + polar2xy(opt*(1-width), end-0.5*np.pi),
        polar2xy(inner, start) + polar2xy(opt*(1-width), start+0.5*np.pi),
        polar2xy(inner, start),
        polar2xy(radius, start),
        ]

    codes = [Path.MOVETO,
             Path.CURVE4,
             Path.CURVE4,
             Path.CURVE4,
             Path.LINETO,
             Path.CURVE4,
             Path.CURVE4,
             Path.CURVE4,
             Path.CLOSEPOLY,
             ]

    if ax == None:
        return verts, codes
    else:
        path = Path(verts, codes)
        patch = patches.PathPatch(path, facecolor=color+(0.5,), edgecolor=color+(0.4,), lw=LW)
        ax.add_patch(patch) 
Example #30
Source File: utils.py    From lddmm-ot with MIT License 5 votes vote down vote up
def SVG_path(path, transform=None, simplify=False):
    """Construct the vertices and SVG codes for the path

    Parameters
    ----------
    path : matplotlib.Path object

    transform : matplotlib transform (optional)
        if specified, the path will be transformed before computing the output.

    Returns
    -------
    vertices : array
        The shape (M, 2) array of vertices of the Path. Note that some Path
        codes require multiple vertices, so the length of these vertices may
        be longer than the list of path codes.
    path_codes : list
        A length N list of single-character path codes, N <= M. Each code is
        a single character, in ['L','M','S','C','Z']. See the standard SVG
        path specification for a description of these.
    """
    if transform is not None:
        path = path.transformed(transform)

    vc_tuples = [(vertices if path_code != Path.CLOSEPOLY else [],
                  PATH_DICT[path_code])
                 for (vertices, path_code)
                 in path.iter_segments(simplify=simplify)]

    if not vc_tuples:
        # empty path is a special case
        return np.zeros((0, 2)), []
    else:
        vertices, codes = zip(*vc_tuples)
        vertices = np.array(list(itertools.chain(*vertices))).reshape(-1, 2)
        return vertices, list(codes)