Python matplotlib.patches.PathPatch() Examples

The following are code examples for showing how to use matplotlib.patches.PathPatch(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: 3d-vehicle-tracking   Author: ucbdrive   File: show_labels.py    BSD 3-Clause "New" or "Revised" License 9 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 2
Project: PyMICAPS   Author: flashlxy   File: Micaps11Data.py    GNU General Public License v2.0 6 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 3
Project: TF_RL   Author: Rowing0914   File: env.py    MIT License 6 votes vote down vote up
def _visualise_setup(self):
        """ Basic setup for visualisation """
        fig = plt.figure(figsize=(10, 10))
        ax = fig.add_subplot(111)

        # convert the environment to the image
        ax.set_xlim(0.0, self.max_position)
        ax.set_ylim(0.0, self.max_position)

        # plot any walls if any
        for w in self.walls:
            patch = patches.PathPatch(w, facecolor='gray', lw=2)
            ax.add_patch(patch)

        # plot the start and goal points
        ax.scatter([self.start_position[0]], [self.start_position[1]], c='g')
        ax.scatter([self.goal_position[0]], [self.goal_position[1]], c='y')

        # Plot the dense rewards:
        for idx, mini_goal in enumerate(self.dense_goals):
            ax.scatter([mini_goal[0]], [mini_goal[1]], c='b')

        return fig, ax 
Example 4
Project: Map-Alignment-Nonrigid-Optimization-2D   Author: saeedghsh   File: plotting.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_pathes(axes, pathes):
    ''''''

    # ### plot patches with collection tool
    # patches = [mpatches.PathPatch(p) for p in pathes]
    # collection = mcollections.PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.7)
    # colors = np.linspace(0, 1, len(pathes))
    # collection.set_array(np.array(colors))
    # axes.add_collection(collection)

    ### plot patches directly
    hsv_col = np.ones( (len(pathes)+1,3) )
    hsv_col[:,0] = np.linspace(0, 1, len(pathes)+1)
    rgb_col = matplotlib.colors.hsv_to_rgb(hsv_col)
    for p,c in zip(pathes, rgb_col):
        axes.add_patch( mpatches.PathPatch(p, facecolor=c, edgecolor='none', alpha=0.5) )

    return axes 
Example 5
Project: 3d-vehicle-tracking   Author: ucbdrive   File: show_labels.py    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 6
Project: seaice   Author: Image-Py   File: result_plgs.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def showice(img, ices, areas, para):
    plt.figure('Ice Segment')
    plt.imshow(img)
    patches = []
    for xy, c in zip(ices, areas):
        path = mpath.Path(xy[:,::-1])
        patch = mpatches.PathPatch(path, lw=1)
        patches.append(patch)
        #plt.gca().add_patch(patch)

    ps = PatchCollection(patches, alpha=255, cmap=plt.cm.rainbow)
    ps.set_array(areas)
    plt.gca().add_collection(ps)
    plt.gcf().colorbar(ps, ax=plt.gca())
    plt.grid()
    myfont = fm.FontProperties(fname='C:/Windows/Fonts/msyh.ttc')
    plt.title(para['title'], fontproperties=myfont, size=24)
    plt.show() 
Example 7
Project: Computable   Author: ktraunmueller   File: colorbar.py    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 8
Project: Computable   Author: ktraunmueller   File: colorbar.py    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
Project: bdd-data   Author: ucbdrive   File: show_labels.py    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 10
Project: bdd-data   Author: ucbdrive   File: show_labels.py    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 11
Project: FoundryDataBrowser   Author: ScopeFoundry   File: UsefulUtils.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def draw_roi(x1, y1, x2, y2, **draw_params):
    codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]
    
    ax = plt.gca()

    # Form a path
    verts = [(x1, y1),
             (x1, y2),
             (x2, y2),
             (x2, y1),
             (0, 0)]
    path = Path(verts, codes)

    # Draw the BG region on the image
    patch = patches.PathPatch(path, **draw_params)
    ax.add_patch(patch) 
Example 12
Project: bezier   Author: dhermes   File: make_images.py    Apache License 2.0 6 votes vote down vote up
def add_patch(
    ax, nodes, color, with_nodes=True, alpha=0.625, node_color="black"
):
    # ``nodes`` is stored Fortran-contiguous with ``x-y`` points in each
    # column but ``Path()`` wants ``x-y`` points in each row.
    path = _path_mod.Path(nodes.T)
    patch = patches.PathPatch(path, facecolor=color, alpha=alpha)
    ax.add_patch(patch)
    if with_nodes:
        ax.plot(
            nodes[0, :],
            nodes[1, :],
            color=node_color,
            linestyle="None",
            marker="o",
        ) 
Example 13
Project: pyGenomeTracks   Author: deeptools   File: NarrowPeakTrack.py    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 14
Project: GraphicDesignPatternByPython   Author: Relph1119   File: colorbar.py    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 15
Project: python3_ios   Author: holzschu   File: pathpatch3d.py    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 16
Project: PyMICAPS   Author: flashlxy   File: Map.py    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 17
Project: PyMICAPS   Author: flashlxy   File: Map.py    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 18
Project: PyMICAPS   Author: flashlxy   File: maskout.py    GNU General Public License v2.0 5 votes vote down vote up
def shp2clip(originfig, ax, shpfile, region):
    path = getPathFromShp(shpfile=shpfile, region=region)
    patch = None
    if path:
        patch = PathPatch(path, transform=ax.transData, facecolor='none', edgecolor='black')
        for contour in originfig.collections:
            contour.set_clip_path(patch)
    return path, patch 
Example 19
Project: PyMICAPS   Author: flashlxy   File: Micaps11Data.py    GNU General Public License v2.0 5 votes vote down vote up
def GetPatches(self, paths):
        ps = []
        for path in paths:
            from matplotlib import patches
            ps.append(patches.PathPatch(path, linewidth=1, facecolor='none', edgecolor='k'))
        return ps 
Example 20
Project: OpenBTE   Author: romanodev   File: geometry2_old.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_elem(self,ne,color='gray') :

     elem = self.elems[ne]
     
     pp = []
     for e in elem:
      pp.append(self.nodes[e][:2])
     path = create_path(pp)
     patch = patches.PathPatch(path,linestyle=None,linewidth=0.0,color=color,zorder=1,joinstyle='miter',alpha=0.7)
     gca().add_patch(patch);
     ave = np.sum(np.array(pp),axis=0)/4
     ave,dummy = self.compute_general_centroid_and_side(ne)

     return ave 
Example 21
Project: OpenBTE   Author: romanodev   File: geometry2.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_elem(self,ne,color='gray') :

     elem = self.elems[ne]
     
     pp = []
     for e in elem:
      pp.append(self.nodes[e][:2])
     path = create_path(pp)
     patch = patches.PathPatch(path,linestyle=None,linewidth=0.0,color=color,zorder=1,joinstyle='miter',alpha=0.7)
     gca().add_patch(patch);
     ave = np.sum(np.array(pp),axis=0)/4
     ave,dummy = self.compute_general_centroid_and_side(ne)

     return ave 
Example 22
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: patheffects.py    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 23
Project: pyCircos   Author: ponnhide   File: pycircos.py    GNU General Public License v3.0 5 votes vote down vote up
def chord_plot(self,start_list, end_list ,top=900, bottom=0, color="#1F77B4", alpha=0.5):
        #srtart_list and end_list is composed of "locus_id", "start", "end". 
        sstart = self.theta[self.locus_dict[start_list[0]]["start"]+start_list[1]] 
        send   = self.theta[self.locus_dict[start_list[0]]["start"]+start_list[2]] 
        
        ostart = self.theta[self.locus_dict[end_list[0]]["start"]+end_list[1]] 
        oend   = self.theta[self.locus_dict[end_list[0]]["start"]+end_list[2]] 
        
        z1 = top - top * math.cos(abs((send-sstart) * 0.5)) 
        z2 = top - top * math.cos(abs((oend-ostart) * 0.5)) 
        if sstart == ostart: 
            pass 
        else:
            Path      = mpath.Path
            path_data = [(Path.MOVETO,  (sstart, top)),
                         (Path.CURVE3,  (sstart, bottom)),     
                         (Path.CURVE3,  (oend,   top)),
                         (Path.CURVE3,  ((ostart+oend)*0.5, top+z2)),
                         (Path.CURVE3,  (ostart, top)),
                         (Path.CURVE3,  (ostart, bottom)),
                         (Path.CURVE3,  (send,   top)),
                         (Path.CURVE3,  ((sstart+send)*0.5, top+z1)),
                         (Path.CURVE3,  (sstart,   top)),
                        ]
            codes, verts = list(zip(*path_data)) 
            path  = mpath.Path(verts, codes)
            patch = mpatches.PathPatch(path, facecolor=color, alpha=alpha, linewidth=0, zorder=0)
            self.ax.add_patch(patch) 
Example 24
Project: unmixing   Author: arthur-e   File: visualize.py    MIT License 5 votes vote down vote up
def plot_2d_mixing_space(self, features, hold=False):
        '''
        Draws a 2D (triangular) mixing space.
        '''
        codes = [VectorPath.MOVETO, VectorPath.LINETO, VectorPath.LINETO, VectorPath.CLOSEPOLY]
        verts = features[...,0:2].tolist()
        verts.append((0, 0)) # Dummy vertex
        path = VectorPath(verts, codes)
        patch = patches.PathPatch(path, facecolor='black', alpha=0.3, lw=0)
        plt.gca().add_patch(patch)

        if not hold:
            plt.show() 
Example 25
Project: jMetalPy   Author: jMetal   File: chord_plot.py    MIT License 5 votes vote down vote up
def draw_sector(start_angle=0, end_angle=60, radius=1.0, width=0.2, lw=2, ls='-', ax=None, fc=(1, 0, 0), ec=(0, 0, 0),
                z_order=1):
    if start_angle > end_angle:
        start_angle, end_angle = end_angle, start_angle
    start_angle *= np.pi / 180.
    end_angle *= np.pi / 180.

    # https://stackoverflow.com/questions/1734745/how-to-create-circle-with-b%C3%A9zier-curves
    opt = 4. / 3. * np.tan((end_angle - start_angle) / 4.) * radius
    inner = radius * (1 - width)

    vertsPath = [polar_to_cartesian(radius, start_angle),
                 polar_to_cartesian(radius, start_angle) + polar_to_cartesian(opt, start_angle + 0.5 * np.pi),
                 polar_to_cartesian(radius, end_angle) + polar_to_cartesian(opt, end_angle - 0.5 * np.pi),
                 polar_to_cartesian(radius, end_angle),
                 polar_to_cartesian(inner, end_angle),
                 polar_to_cartesian(inner, end_angle) + polar_to_cartesian(opt * (1 - width), end_angle - 0.5 * np.pi),
                 polar_to_cartesian(inner, start_angle) + polar_to_cartesian(opt * (1 - width),
                                                                             start_angle + 0.5 * np.pi),
                 polar_to_cartesian(inner, start_angle),
                 polar_to_cartesian(radius, start_angle)]

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

    if ax is None:
        return vertsPath, codesPaths
    else:
        path = Path(vertsPath, codesPaths)
        patch = patches.PathPatch(path, facecolor=fc, edgecolor=ec, lw=lw, linestyle=ls, zorder=z_order)
        ax.add_patch(patch)
        return (patch) 
Example 26
Project: jMetalPy   Author: jMetal   File: chord_plot.py    MIT License 5 votes vote down vote up
def draw_chord(start_angle1=0, end_angle1=60, start_angle2=180, end_angle2=240, radius=1.0, chord_width=0.7, ax=None,
               color=(1, 0, 0), z_order=1):
    if start_angle1 > end_angle1:
        start_angle1, end_angle1 = end_angle1, start_angle1
    if start_angle2 > end_angle2:
        start_angle2, end_angle2 = end_angle2, start_angle2
    start_angle1 *= np.pi / 180.
    end_angle1 *= np.pi / 180.
    start_angle2 *= np.pi / 180.
    end_angle2 *= np.pi / 180.

    optAngle1 = 4. / 3. * np.tan((end_angle1 - start_angle1) / 4.) * radius
    optAngle2 = 4. / 3. * np.tan((end_angle2 - start_angle2) / 4.) * radius
    rchord = radius * (1 - chord_width)

    vertsPath = [polar_to_cartesian(radius, start_angle1),
                 polar_to_cartesian(radius, start_angle1) + polar_to_cartesian(optAngle1, start_angle1 + 0.5 * np.pi),
                 polar_to_cartesian(radius, end_angle1) + polar_to_cartesian(optAngle1, end_angle1 - 0.5 * np.pi),
                 polar_to_cartesian(radius, end_angle1),
                 polar_to_cartesian(rchord, end_angle1), polar_to_cartesian(rchord, start_angle2),
                 polar_to_cartesian(radius, start_angle2),
                 polar_to_cartesian(radius, start_angle2) + polar_to_cartesian(optAngle2, start_angle2 + 0.5 * np.pi),
                 polar_to_cartesian(radius, end_angle2) + polar_to_cartesian(optAngle2, end_angle2 - 0.5 * np.pi),
                 polar_to_cartesian(radius, end_angle2),
                 polar_to_cartesian(rchord, end_angle2), polar_to_cartesian(rchord, start_angle1),
                 polar_to_cartesian(radius, start_angle1)]

    codesPath = [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]

    if ax == None:
        return vertsPath, codesPath
    else:
        path = Path(vertsPath, codesPath)
        patch = patches.PathPatch(path, facecolor=color + (0.5,), edgecolor=color + (0.4,), lw=2, alpha=0.5)
        ax.add_patch(patch)
        return (patch) 
Example 27
Project: ble5-nrf52-mac   Author: tomasero   File: test_transforms.py    MIT License 5 votes vote down vote up
def test_pathc_extents_non_affine(self):
        ax = plt.axes()
        offset = mtransforms.Affine2D().translate(10, 10)
        na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))
        pth = 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)
        expected_data_lim = np.array([[0., 0.], [10.,  10.]]) + 20
        assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) 
Example 28
Project: ble5-nrf52-mac   Author: tomasero   File: test_transforms.py    MIT License 5 votes vote down vote up
def test_pathc_extents_affine(self):
        ax = plt.axes()
        offset = mtransforms.Affine2D().translate(10, 10)
        pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
        patch = mpatches.PathPatch(pth, transform=offset + ax.transData)
        ax.add_patch(patch)
        expected_data_lim = np.array([[0., 0.], [10.,  10.]]) + 10
        assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) 
Example 29
Project: ble5-nrf52-mac   Author: tomasero   File: test_simplification.py    MIT License 5 votes vote down vote up
def test_simplify_curve():
    pp1 = patches.PathPatch(
        Path([(0, 0), (1, 0), (1, 1), (np.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, ax = plt.subplots()
    ax.add_patch(pp1)
    ax.set_xlim((0, 2))
    ax.set_ylim((0, 2)) 
Example 30
Project: ble5-nrf52-mac   Author: tomasero   File: test_artist.py    MIT License 5 votes vote down vote up
def test_default_edges():
    fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2)

    ax1.plot(np.arange(10), np.arange(10), 'x',
             np.arange(10) + 1, np.arange(10), 'o')
    ax2.bar(np.arange(10), np.arange(10), align='edge')
    ax3.text(0, 0, "BOX", size=24, bbox=dict(boxstyle='sawtooth'))
    ax3.set_xlim((-1, 1))
    ax3.set_ylim((-1, 1))
    pp1 = mpatches.PathPatch(
        mpath.Path([(0, 0), (1, 0), (1, 1), (0, 0)],
                   [mpath.Path.MOVETO, mpath.Path.CURVE3,
                    mpath.Path.CURVE3, mpath.Path.CLOSEPOLY]),
        fc="none", transform=ax4.transData)
    ax4.add_patch(pp1) 
Example 31
Project: ble5-nrf52-mac   Author: tomasero   File: patheffects.py    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 32
Project: Computable   Author: ktraunmueller   File: spines.py    MIT License 5 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

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

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

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

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

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

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 33
Project: TAGGS   Author: jensdebruijn   File: shapefiles.py    MIT License 5 votes vote down vote up
def create_patches(shapefile, facecolor, alpha):
    patches = []
    for path in create_paths_shapefile(shapefile):
        patch = mpatches.PathPatch(path, facecolor=facecolor, alpha=alpha, lw=2)
        patches.append(patch)
    return patches 
Example 34
Project: viznet   Author: GiggleLiu   File: edgenode.py    MIT License 5 votes vote down vote up
def mass_center(self):
        '''mass center of a node'''
        shape = self.brush.style[1]
        if isinstance(self.obj, (plt.Polygon, patches.PathPatch)):
            pos = self._clean_path.mean(axis=0)
        else:
            pos = self.position
        return Pin(pos) 
Example 35
Project: viznet   Author: GiggleLiu   File: edgenode.py    MIT License 5 votes vote down vote up
def height(self):
        shape = self.brush.style[1]
        if isinstance(self.obj, plt.Circle):
            return self.obj.radius * 2
        elif isinstance(self.obj, plt.Rectangle):
            return self.obj.get_height()
        elif isinstance(self.obj, patches.FancyBboxPatch):
            return self.obj.get_height() + 2*self.obj.get_boxstyle().pad
        elif isinstance(self.obj, (plt.Polygon, patches.PathPatch)):
            y = self.path[:,1]
            return y.max() - y.min()
        else:
            raise 
Example 36
Project: viznet   Author: GiggleLiu   File: edgenode.py    MIT License 5 votes vote down vote up
def width(self):
        shape = self.brush.style[1]
        if isinstance(self.obj, plt.Circle):
            return self.obj.radius * 2
        elif isinstance(self.obj, plt.Rectangle):
            return self.obj.get_width()
        elif isinstance(self.obj, patches.FancyBboxPatch):
            return self.obj.get_width() + 2*self.obj.get_boxstyle().pad
        elif isinstance(self.obj, (plt.Polygon, patches.PathPatch)):
            x = self.path[:,0]
            return x.max() - x.min()
        else:
            raise 
Example 37
Project: viznet   Author: GiggleLiu   File: shapes.py    MIT License 5 votes vote down vote up
def lines(xy, size, angle, roundness, props, **kwargs):
    vertices_list = props['paths']
    kwargs['facecolor'] = 'none'
    codes = []
    verts = np.zeros([0, 2])
    for iv, vertices in enumerate(np.asarray(vertices_list)):
        pp = rounded_path(affine(vertices, xy, size, angle), roundness, close=False)
        verts = np.concatenate([verts, pp.vertices], axis=0)
        if iv == 0:
            codes =  pp.codes
        else:
            codes =  np.concatenate([codes, [Path.MOVETO], pp.codes[1:]])
    c = patches.PathPatch(Path(verts, codes), **_fix(kwargs))
    return [c] 
Example 38
Project: viznet   Author: GiggleLiu   File: shapes.py    MIT License 5 votes vote down vote up
def polygon(xy, size, angle, roundness, props, **kwargs):
    vertices = props['path']
    path = rounded_path(affine(np.asarray(vertices), xy, size, angle), roundness=roundness, close=True)
    c = patches.PathPatch(path, **_fix(kwargs))
    return [c] 
Example 39
Project: viznet   Author: GiggleLiu   File: test_utils.py    MIT License 5 votes vote down vote up
def test_rounded_path():
    vertices = np.array([(0, 0), (1, 0), (1, 1), (0, 1)])
    path = shapes.rounded_path(vertices, 0.1)
    path2 = shapes.rounded_path(vertices+2, 0.1, close=True)
    pp = patches.PathPatch(path)
    pp2 = patches.PathPatch(path2)
    ax = plt.subplot(111)
    ax.add_patch(pp)
    ax.add_patch(pp2)
    plt.xlim(-1,5)
    plt.ylim(-1,5)
    plt.show() 
Example 40
Project: bezier   Author: dhermes   File: _plot_helpers.py    Apache License 2.0 5 votes vote down vote up
def add_patch(ax, color, pts_per_edge, *edges):
    """Add a polygonal surface patch to a plot.

    Args:
        ax (matplotlib.artist.Artist): A matplotlib axis.
        color (Tuple[float, float, float]): Color as RGB profile.
        pts_per_edge (int): Number of points to use in polygonal
            approximation of edge.
        edges (Tuple[~bezier.curve.Curve, ...]): Curved edges defining
            a boundary.
    """
    # pylint: disable=import-outside-toplevel
    from matplotlib import patches
    from matplotlib import path as _path_mod

    # pylint: enable=import-outside-toplevel

    s_vals = np.linspace(0.0, 1.0, pts_per_edge)
    # Evaluate points on each edge.
    all_points = []
    for edge in edges:
        points = edge.evaluate_multi(s_vals)
        # We assume the edges overlap and leave out the first point
        # in each.
        all_points.append(points[:, 1:])
    # Add first point as last point (polygon is closed).
    first_edge = all_points[0]
    all_points.append(first_edge[:, [0]])
    # Add boundary first.
    polygon = np.asfortranarray(np.hstack(all_points))
    (line,) = ax.plot(polygon[0, :], polygon[1, :], color=color)
    # Reset ``color`` in case it was ``None`` and set from color wheel.
    color = line.get_color()
    # ``polygon`` is stored Fortran-contiguous with ``x-y`` points in each
    # column but ``Path()`` wants ``x-y`` points in each row.
    path = _path_mod.Path(polygon.T)
    patch = patches.PathPatch(path, facecolor=color, alpha=0.625)
    ax.add_patch(patch) 
Example 41
Project: prob_meteogram   Author: milankl   File: lightning_bolt.py    MIT License 5 votes vote down vote up
def lightning_bolt(xy=(0.,0.),width=0.6,height=1.,rot=0.):
        
    # convert to x,y being in the middle of the droplet
    x = xy[0]-width/2
    y = xy[1]-height/2
    
    h1 = 0.7*height
    h2 = 0.55*height
    
    verts = [
    (x,y),
    (x+width/2,y+h2),
    (x,y+h2),
    (x+width/2,y+height),
    (x+width,y+height),
    (x+width/2,y+h1),
    (x+width,y+h1),
    (x,y)
    ]
    
    codes = [Path.MOVETO]+[Path.LINETO]*(len(verts)-2)+[Path.CLOSEPOLY]
    
    return Path(verts,codes)
    
    
# fig,ax = plt.subplots(1,1)
# patch = patches.PathPatch(lightning_bolt(), facecolor='yellow', lw=1)
# ax.add_patch(patch)
# 
# ax.set_xlim(-1,1)
# ax.set_ylim(-1,1)
# plt.savefig("lightning_bolt.png",dpi=300)
# plt.close(fig) 
Example 42
Project: pylustrator   Author: rgerum   File: parse_svg.py    GNU General Public License v3.0 5 votes vote down vote up
def clone_patch(patch):
    if isinstance(patch, mpatches.Rectangle):
        return mpatches.Rectangle(xy=patch.get_xy(),
                                  width=patch.get_width(),
                                  height=patch.get_height())
    if isinstance(patch, mpatches.Circle):
        return mpatches.Circle(xy=patch.get_xy(),
                               radius=patch.get_radius())
    if isinstance(patch, mpatches.Ellipse):
        return mpatches.Ellipse(xy=patch.get_xy(),
                                width=patch.get_width(),
                                height=patch.get_height())
    if isinstance(patch, mpatches.PathPatch):
        return mpatches.PathPatch(patch.get_path()) 
Example 43
Project: pylustrator   Author: rgerum   File: parse_svg.py    GNU General Public License v3.0 5 votes vote down vote up
def plt_draw_text(node, trans, style, ids, no_draw=False):
    from matplotlib.textpath import TextPath

    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 44
Project: neural-network-animation   Author: miloharper   File: test_patches.py    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 45
Project: neural-network-animation   Author: miloharper   File: test_patches.py    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 46
Project: neural-network-animation   Author: miloharper   File: test_patches.py    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 47
Project: neural-network-animation   Author: miloharper   File: test_transforms.py    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 48
Project: neural-network-animation   Author: miloharper   File: test_transforms.py    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 49
Project: neural-network-animation   Author: miloharper   File: test_simplification.py    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 50
Project: neural-network-animation   Author: miloharper   File: test_artist.py    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 51
Project: neural-network-animation   Author: miloharper   File: patheffects.py    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 52
Project: pyDNAbinding   Author: nboley   File: plot.py    GNU General Public License v2.0 5 votes vote down vote up
def PolygonPatch(polygon, **kwargs):
    """Constructs a matplotlib patch from a geometric object

    The `polygon` may be a Shapely or GeoJSON-like object with or without holes.
    The `kwargs` are those supported by the matplotlib.patches.Polygon class
    constructor. Returns an instance of matplotlib.patches.PathPatch.

    Example (using Shapely Point and a matplotlib axes):

      >>> b = Point(0, 0).buffer(1.0)
      >>> patch = PolygonPatch(b, fc='blue', ec='blue', alpha=0.5)
      >>> axis.add_patch(patch)

    """
    return PathPatch(PolygonPath(polygon), **kwargs)

#
# END copied from descartes
#
################################################################################

################################################################################
# Initialize the polygon paths for A,C,G,T
#
# Geometry taken from JTS TestBuilder Monospace font with fixed precision model
# of 1000.0
# 
Example 53
Project: GraphicDesignPatternByPython   Author: Relph1119   File: patheffects.py    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 54
Project: python3_ios   Author: holzschu   File: demo_text_path.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, path, bbox_image, **kwargs):
        mpatches.PathPatch.__init__(self, path, **kwargs)
        self._init_bbox_image(bbox_image) 
Example 55
Project: python3_ios   Author: holzschu   File: demo_text_path.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_facecolor(self, color):
        """simply ignore facecolor"""
        mpatches.PathPatch.set_facecolor(self, "none") 
Example 56
Project: python3_ios   Author: holzschu   File: demo_text_path.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw(self, renderer=None):

        # the clip path must be updated every draw. any solution? -JJ
        self.bbox_image.set_clip_path(self._path, self.get_transform())
        self.bbox_image.draw(renderer)

        mpatches.PathPatch.draw(self, renderer) 
Example 57
Project: python3_ios   Author: holzschu   File: test_transforms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pathc_extents_non_affine(self):
        ax = plt.axes()
        offset = mtransforms.Affine2D().translate(10, 10)
        na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))
        pth = 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)
        expected_data_lim = np.array([[0., 0.], [10.,  10.]]) + 20
        assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) 
Example 58
Project: python3_ios   Author: holzschu   File: test_transforms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pathc_extents_affine(self):
        ax = plt.axes()
        offset = mtransforms.Affine2D().translate(10, 10)
        pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
        patch = mpatches.PathPatch(pth, transform=offset + ax.transData)
        ax.add_patch(patch)
        expected_data_lim = np.array([[0., 0.], [10.,  10.]]) + 10
        assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) 
Example 59
Project: python3_ios   Author: holzschu   File: test_simplification.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_simplify_curve():
    pp1 = patches.PathPatch(
        Path([(0, 0), (1, 0), (1, 1), (np.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, ax = plt.subplots()
    ax.add_patch(pp1)
    ax.set_xlim((0, 2))
    ax.set_ylim((0, 2)) 
Example 60
Project: python3_ios   Author: holzschu   File: test_artist.py    BSD 3-Clause "New" or "Revised" 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 61
Project: remixt   Author: amcpherson   File: cn_plot.py    MIT License 4 votes vote down vote up
def plot_breakpoints_genome(ax, breakpoint, chromosome_info, scale_height=1.0):
    """ Plot breakpoint arcs

    Args:
        ax (matplotlib.axes.Axes): plot axes
        breakpoint (pandas.DataFrame): breakpoint
        chromosome_info (pandas.DataFrame): per chromosome start and end in plot returned from plot_cnv_genome

    """

    plot_height = ax.get_ylim()[1] * 0.8
    plot_length = ax.get_xlim()[1] - ax.get_xlim()[0]

    for side in ('1', '2'):
        
        breakpoint.set_index('chromosome_'+side, inplace=True)
        breakpoint['chromosome_start_'+side] = chromosome_info['start']
        breakpoint.reset_index(inplace=True)
        
        breakpoint['plot_position_'+side] = breakpoint['position_'+side] + breakpoint['chromosome_start_'+side]

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

    for idx, row in breakpoint.iterrows():

        pos_1, pos_2 = sorted(row[['plot_position_1', 'plot_position_2']])
        height = scale_height * 2. * plot_height * (pos_2 - pos_1) / float(plot_length)
        
        visible_1 = pos_1 >= ax.get_xlim()[0] and pos_1 <= ax.get_xlim()[1]
        visible_2 = pos_2 >= ax.get_xlim()[0] and pos_2 <= ax.get_xlim()[1]
        
        if not visible_1 and not visible_2:
            continue

        if not visible_1 or not visible_2:
            height = plot_height * 10.

        verts = [(pos_1, 0.), (pos_1, height), (pos_2, height), (pos_2, 0.)]

        path = Path(verts, codes)
        patch = patches.PathPatch(path, facecolor='none', edgecolor='#2eb036', lw=2, zorder=100)
        ax.add_patch(patch) 
Example 62
Project: LaserTOF   Author: kyleuckert   File: colorbar.py    MIT License 4 votes vote down vote up
def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        # Save, set, and restore hold state to keep pcolor from
        # clearing the axes. Ordinarily this will not be needed,
        # since the axes object should already have hold set.
        _hold = self.ax._hold
        self.ax._hold = True

        kw = {'alpha': self.alpha, }

        n_segments = len(C)

        # ensure there are sufficent hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in xrange(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]],
                           [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch, linewidth=0,
                                       antialiased=False, **kw)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
            self.ax.add_collection(self.dividers)

        self.ax._hold = _hold 
Example 63
Project: LaserTOF   Author: kyleuckert   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

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

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

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

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            msg = "'path' must be an instance of 'matplotlib.path.Path'"
            raise ValueError(msg)
        self._path = path

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

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 64
Project: LaserTOF   Author: kyleuckert   File: sankey.py    MIT License 4 votes vote down vote up
def finish(self):
        """
        Adjust the axes and return a list of information about the Sankey
        subdiagram(s).

        Return value is a list of subdiagrams represented with the following
        fields:

          ===============   ===================================================
          Field             Description
          ===============   ===================================================
          *patch*           Sankey outline (an instance of
                            :class:`~maplotlib.patches.PathPatch`)
          *flows*           values of the flows (positive for input, negative
                            for output)
          *angles*          list of angles of the arrows [deg/90]
                            For example, if the diagram has not been rotated,
                            an input to the top side will have an angle of 3
                            (DOWN), and an output from the top side will have
                            an angle of 1 (UP).  If a flow has been skipped
                            (because its magnitude is less than *tolerance*),
                            then its angle will be *None*.
          *tips*            array in which each row is an [x, y] pair
                            indicating the positions of the tips (or "dips") of
                            the flow paths
                            If the magnitude of a flow is less the *tolerance*
                            for the instance of :class:`Sankey`, the flow is
                            skipped and its tip will be at the center of the
                            diagram.
          *text*            :class:`~matplotlib.text.Text` instance for the
                            label of the diagram
          *texts*           list of :class:`~matplotlib.text.Text` instances
                            for the labels of flows
          ===============   ===================================================

        .. seealso::

            :meth:`add`
        """
        self.ax.axis([self.extent[0] - self.margin,
                      self.extent[1] + self.margin,
                      self.extent[2] - self.margin,
                      self.extent[3] + self.margin])
        self.ax.set_aspect('equal', adjustable='datalim')
        return self.diagrams 
Example 65
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: colorbar.py    MIT License 4 votes vote down vote up
def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        n_segments = len(C)

        # ensure there are sufficient hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in range(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]],
                           [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch, linewidth=0,
                                       antialiased=False, alpha=self.alpha)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(
                    self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
            self.ax.add_collection(self.dividers) 
Example 66
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

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

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

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

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

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

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 67
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: sankey.py    MIT License 4 votes vote down vote up
def finish(self):
        """
        Adjust the axes and return a list of information about the Sankey
        subdiagram(s).

        Return value is a list of subdiagrams represented with the following
        fields:

          ===============   ===================================================
          Field             Description
          ===============   ===================================================
          *patch*           Sankey outline (an instance of
                            :class:`~matplotlib.patches.PathPatch`)
          *flows*           values of the flows (positive for input, negative
                            for output)
          *angles*          list of angles of the arrows [deg/90]
                            For example, if the diagram has not been rotated,
                            an input to the top side will have an angle of 3
                            (DOWN), and an output from the top side will have
                            an angle of 1 (UP).  If a flow has been skipped
                            (because its magnitude is less than *tolerance*),
                            then its angle will be *None*.
          *tips*            array in which each row is an [x, y] pair
                            indicating the positions of the tips (or "dips") of
                            the flow paths
                            If the magnitude of a flow is less the *tolerance*
                            for the instance of :class:`Sankey`, the flow is
                            skipped and its tip will be at the center of the
                            diagram.
          *text*            :class:`~matplotlib.text.Text` instance for the
                            label of the diagram
          *texts*           list of :class:`~matplotlib.text.Text` instances
                            for the labels of flows
          ===============   ===================================================

        See Also
        --------
        Sankey.add
        """
        self.ax.axis([self.extent[0] - self.margin,
                      self.extent[1] + self.margin,
                      self.extent[2] - self.margin,
                      self.extent[3] + self.margin])
        self.ax.set_aspect('equal', adjustable='datalim')
        return self.diagrams 
Example 68
Project: Map-Alignment-Nonrigid-Optimization-2D   Author: saeedghsh   File: plotting.py    GNU General Public License v3.0 4 votes vote down vote up
def plot_tesselation_motion_heatmap(dst_image, src_img_aligned,
                                    X_aligned, X_optimized,
                                    tform_opt,
                                    plot_points=False):
    ''''''

    # motion of each triangle is the average of the motion of its vertices
    tri_motion = np.array([ np.sqrt( ((X_aligned[idx,:]-X_optimized[idx,:])**2).sum(axis=1) ).sum()
                              for idx in tform_opt._tesselation.simplices ]) / 3


    fig, axes = plt.subplots(1,2, figsize=(20,12))

    axes[0].set_title('histogram of the motion of the vertices of triangles')
    axes[0].hist(tri_motion,bins=20)

    # normalizing the motions to (0, .5) to be used for opacity of patches
    tri_motion = (tri_motion - tri_motion.min()) / ( 2* (tri_motion.max()-tri_motion.min()) )

    axes[1].set_title('based on the motion of the vertices of each triangle')
    axes[1].imshow(dst_image, origin='lower', cmap='gray', alpha=.5)
    axes[1].imshow(src_img_aligned, origin='lower', cmap='gray', alpha=.5)
    codes = (1, 2, 2, 79)
    for s_idx, idx in enumerate(tform_opt._tesselation.simplices):
        pts = X_aligned[idx,:]
        verts = (pts[0,:], pts[1,:], pts[2,:], pts[0,:])
        axes[1].add_patch( mpatches.PathPatch( mpath.Path(verts, codes),
                                            facecolor='r', edgecolor='none',#'r',
                                            alpha=tri_motion[s_idx]) )

    if plot_points:
        axes[1] = plot_point_before_after_optimization(dst_image, X_aligned, X_optimized, axes=axes[1], img_alpha=0.0)

    plt.tight_layout()
    plt.show()

    # tri_fitness = np.array([ fit_map[X_aligned[idx,1].astype(int), X_aligned[idx,0].astype(int)].sum() / 3.
    #                          for idx in tform_opt._tesselation.simplices ])
    # tri_fitness = (tri_fitness - tri_fitness.min()) / (tri_fitness.max()-tri_fitness.min())
    # axes[0].set_title('based on the fitness of the vertices of each triangle')
    # axes[0].imshow(dst_results['image'], origin='lower', cmap='gray', alpha=.5, clip_on=True)
    # axes[0].imshow(src_img_aligned, origin='lower', cmap='gray', alpha=.5, clip_on=True)
    # codes = (1, 2, 2, 79)
    # for s_idx, idx in enumerate(tform_opt._tesselation.simplices):
    #     pts = X_aligned[idx,:]
    #     verts = (pts[0,:], pts[1,:], pts[2,:], pts[0,:])
    #     axes[0].add_patch( mpatches.PathPatch( mpath.Path(verts, codes),
    #                                            facecolor='r', edgecolor='r',
    #                                            alpha=( 1-tri_fitness[s_idx])/1 ) )

################################################################################ 
Example 69
Project: TR-C2017_360Vision   Author: Lab-Work   File: tools.py    GNU General Public License v3.0 4 votes vote down vote up
def in_hull(points, hull):
    #print "Deciding if points are inside the hull..."
    import matplotlib.path as path
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    import numpy as np

    edges = []
    codes = []
    prev = hull[0][0]
    next = hull[0][1]
    edges.append(tuple(prev))
    codes.append(path.Path.MOVETO)
    edges.append(tuple(next))
    codes.append(path.Path.LINETO)
    idx = 2
    while idx < len(hull)+1:
        for edge in hull:
            pt1 = edge[0]
            pt2 = edge[1]
            
            if (pt1[0] == next[0] and
                pt1[1] == next[1] and
                (pt2[0] != prev[0] or
                 pt2[1] != prev[1])):
                prev = pt1
                next = pt2
                edges.append(tuple(next))
                codes.append(path.Path.LINETO)
                #print "break on pt2"
                break
            elif (pt2[0] == next[0] and
                  pt2[1] == next[1] and
                  (pt1[0] != prev[0] or
                   pt1[1] != prev[1])):
                prev = pt2
                next = pt1
                edges.append(tuple(next))
                codes.append(path.Path.LINETO)
                #print "break on pt1"
                break
        idx += 1

    edges.append(hull[0][0])
    codes.append(path.Path.CLOSEPOLY)
    polygon = path.Path(edges,codes)
    mask = polygon.contains_points(points)
    if False:
        mask = mask.reshape(4040,80).T
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        patch = patches.PathPatch(polygon, facecolor="orange", lw=2)
        #ax.add_patch(patch)
        ax.imshow(mask)
        ax.set_xlim(0,4040)
        ax.set_ylim(0,80)
        ax.axis("equal")
        ax.invert_yaxis
        plt.show()
    return mask 
Example 70
Project: ble5-nrf52-mac   Author: tomasero   File: colorbar.py    MIT License 4 votes vote down vote up
def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        kw = {'alpha': self.alpha, }

        n_segments = len(C)

        # ensure there are sufficient hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in range(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]],
                           [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch, linewidth=0,
                                       antialiased=False, **kw)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(
                    self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
            self.ax.add_collection(self.dividers) 
Example 71
Project: ble5-nrf52-mac   Author: tomasero   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

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

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

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

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

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

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 72
Project: ble5-nrf52-mac   Author: tomasero   File: sankey.py    MIT License 4 votes vote down vote up
def finish(self):
        """
        Adjust the axes and return a list of information about the Sankey
        subdiagram(s).

        Return value is a list of subdiagrams represented with the following
        fields:

          ===============   ===================================================
          Field             Description
          ===============   ===================================================
          *patch*           Sankey outline (an instance of
                            :class:`~maplotlib.patches.PathPatch`)
          *flows*           values of the flows (positive for input, negative
                            for output)
          *angles*          list of angles of the arrows [deg/90]
                            For example, if the diagram has not been rotated,
                            an input to the top side will have an angle of 3
                            (DOWN), and an output from the top side will have
                            an angle of 1 (UP).  If a flow has been skipped
                            (because its magnitude is less than *tolerance*),
                            then its angle will be *None*.
          *tips*            array in which each row is an [x, y] pair
                            indicating the positions of the tips (or "dips") of
                            the flow paths
                            If the magnitude of a flow is less the *tolerance*
                            for the instance of :class:`Sankey`, the flow is
                            skipped and its tip will be at the center of the
                            diagram.
          *text*            :class:`~matplotlib.text.Text` instance for the
                            label of the diagram
          *texts*           list of :class:`~matplotlib.text.Text` instances
                            for the labels of flows
          ===============   ===================================================

        .. seealso::

            :meth:`add`
        """
        self.ax.axis([self.extent[0] - self.margin,
                      self.extent[1] + self.margin,
                      self.extent[2] - self.margin,
                      self.extent[3] + self.margin])
        self.ax.set_aspect('equal', adjustable='datalim')
        return self.diagrams 
Example 73
Project: Computable   Author: ktraunmueller   File: colorbar.py    MIT License 4 votes vote down vote up
def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        # Save, set, and restore hold state to keep pcolor from
        # clearing the axes. Ordinarily this will not be needed,
        # since the axes object should already have hold set.
        _hold = self.ax.ishold()
        self.ax.hold(True)

        kw = {'alpha': self.alpha, }

        n_segments = len(C)

        # ensure there are sufficent hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in xrange(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]],
                           [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch, linewidth=0,
                                       antialiased=False, **kw)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
            self.ax.add_collection(self.dividers)

        self.ax.hold(_hold) 
Example 74
Project: Computable   Author: ktraunmueller   File: sankey.py    MIT License 4 votes vote down vote up
def finish(self):
        """
        Adjust the axes and return a list of information about the Sankey
        subdiagram(s).

        Return value is a list of subdiagrams represented with the following
        fields:

          ===============   ===================================================
          Field             Description
          ===============   ===================================================
          *patch*           Sankey outline (an instance of
                            :class:`~maplotlib.patches.PathPatch`)
          *flows*           values of the flows (positive for input, negative
                            for output)
          *angles*          list of angles of the arrows [deg/90]
                            For example, if the diagram has not been rotated,
                            an input to the top side will have an angle of 3
                            (DOWN), and an output from the top side will have
                            an angle of 1 (UP).  If a flow has been skipped
                            (because its magnitude is less than *tolerance*),
                            then its angle will be *None*.
          *tips*            array in which each row is an [x, y] pair
                            indicating the positions of the tips (or "dips") of
                            the flow paths
                            If the magnitude of a flow is less the *tolerance*
                            for the instance of :class:`Sankey`, the flow is
                            skipped and its tip will be at the center of the
                            diagram.
          *text*            :class:`~matplotlib.text.Text` instance for the
                            label of the diagram
          *texts*           list of :class:`~matplotlib.text.Text` instances
                            for the labels of flows
          ===============   ===================================================

        .. seealso::

            :meth:`add`
        """
        self.ax.axis([self.extent[0] - self.margin,
                      self.extent[1] + self.margin,
                      self.extent[2] - self.margin,
                      self.extent[3] + self.margin])
        self.ax.set_aspect('equal', adjustable='datalim')
        return self.diagrams 
Example 75
Project: neural-network-animation   Author: miloharper   File: colorbar.py    MIT License 4 votes vote down vote up
def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        # Save, set, and restore hold state to keep pcolor from
        # clearing the axes. Ordinarily this will not be needed,
        # since the axes object should already have hold set.
        _hold = self.ax.ishold()
        self.ax.hold(True)

        kw = {'alpha': self.alpha, }

        n_segments = len(C)

        # ensure there are sufficent hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in xrange(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]],
                           [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch, linewidth=0,
                                       antialiased=False, **kw)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
            self.ax.add_collection(self.dividers)

        self.ax.hold(_hold) 
Example 76
Project: neural-network-animation   Author: miloharper   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

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

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

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

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

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

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 77
Project: GraphicDesignPatternByPython   Author: Relph1119   File: colorbar.py    MIT License 4 votes vote down vote up
def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        kw = {'alpha': self.alpha, }

        n_segments = len(C)

        # ensure there are sufficient hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in range(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]],
                           [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch, linewidth=0,
                                       antialiased=False, **kw)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(
                    self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
            self.ax.add_collection(self.dividers) 
Example 78
Project: GraphicDesignPatternByPython   Author: Relph1119   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

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

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

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

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

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

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 79
Project: GraphicDesignPatternByPython   Author: Relph1119   File: sankey.py    MIT License 4 votes vote down vote up
def finish(self):
        """
        Adjust the axes and return a list of information about the Sankey
        subdiagram(s).

        Return value is a list of subdiagrams represented with the following
        fields:

          ===============   ===================================================
          Field             Description
          ===============   ===================================================
          *patch*           Sankey outline (an instance of
                            :class:`~maplotlib.patches.PathPatch`)
          *flows*           values of the flows (positive for input, negative
                            for output)
          *angles*          list of angles of the arrows [deg/90]
                            For example, if the diagram has not been rotated,
                            an input to the top side will have an angle of 3
                            (DOWN), and an output from the top side will have
                            an angle of 1 (UP).  If a flow has been skipped
                            (because its magnitude is less than *tolerance*),
                            then its angle will be *None*.
          *tips*            array in which each row is an [x, y] pair
                            indicating the positions of the tips (or "dips") of
                            the flow paths
                            If the magnitude of a flow is less the *tolerance*
                            for the instance of :class:`Sankey`, the flow is
                            skipped and its tip will be at the center of the
                            diagram.
          *text*            :class:`~matplotlib.text.Text` instance for the
                            label of the diagram
          *texts*           list of :class:`~matplotlib.text.Text` instances
                            for the labels of flows
          ===============   ===================================================

        .. seealso::

            :meth:`add`
        """
        self.ax.axis([self.extent[0] - self.margin,
                      self.extent[1] + self.margin,
                      self.extent[2] - self.margin,
                      self.extent[3] + self.margin])
        self.ax.set_aspect('equal', adjustable='datalim')
        return self.diagrams 
Example 80
Project: python3_ios   Author: holzschu   File: colorbar.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        kw = {'alpha': self.alpha, }

        n_segments = len(C)

        # ensure there are sufficient hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in range(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]],
                           [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch, linewidth=0,
                                       antialiased=False, **kw)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(
                    self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
            self.ax.add_collection(self.dividers)