Python matplotlib.path.Path.MOVETO() Examples

The following are code examples for showing how to use matplotlib.path.Path.MOVETO(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: dyfunconn   Author: makism   File: umatrix.py    (license) View Source Project 7 votes vote down vote up
def make_hexagon():
    verts = [
        (0.5, 0.), (0.5, 1.),
        (1., 1.5),
        (1.5, 1), (1.5, 0),
        (1., -0.5),
        (0., -0.5),
    ]

    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,
             ]
    path = Path(verts, codes)

    return path 
Example 2
Project: treecat   Author: posterior   File: plotting.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def plot_chord(begin, end, spacing, color, alpha=None):
    """Plots a circular chord from begin to end.

    This assumes that the outer circle is centered at (0,0).

    Args:
        begin: A [2]-shaped numpy array.
        end: A [2]-shaped numpy array.
        spacing: A float, extra spacing around the edge of the circle.
        color: A matplotlib color spec.
        apha: A float or None.
    """
    # Adapted from https://matplotlib.org/users/path_tutorial.html
    codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
    xy = np.array([begin, begin, end, end])
    dist = ((begin - end)**2).sum()**0.5
    xy[[1, 2], :] *= 1 - 2 / 3 * dist + 1 / 6 * dist**2 - spacing
    path = Path(xy, codes)
    patch = PathPatch(
        path, facecolor='none', edgecolor=color, lw=1, alpha=alpha)
    pyplot.gca().add_patch(patch) 
Example 3
Project: PyGenAlg   Author: RaphDeau   File: main.py    (Creative Commons Attribution 4.0) View Source Project 6 votes vote down vote up
def plotIndiv(indiv, i):
    ax = eval("ax" + str(i))
    ax.cla()
    ax.set_xticks(xTicks)
    ax.set_yticks(yTicks)
    ax.grid()
    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,
             ]
    for rectVertices, color in indiv.getAllObjectRect():
        path = Path(rectVertices, codes)
        patch = patches.PathPatch(path, facecolor=color, lw=2)
        ax.add_patch(patch)
    plt.draw() 
Example 4
Project: ConceptualSpaces   Author: lbechberger   File: concept_inspector.py    (license) View Source Project 6 votes vote down vote up
def _path_for_core(cuboids, d1, d2):
    """Creates the 2d path for a complete core."""

    polygon = None    
    for cuboid in cuboids:
        p_min = cuboid[0]
        p_max = cuboid[1]
        cub = shapely.geometry.box(p_min[d1], p_min[d2], p_max[d1], p_max[d2])
        if polygon == None:
            polygon = cub
        else:
            polygon = polygon.union(cub)
    
    verts = list(polygon.exterior.coords)
    codes = [Path.LINETO] * len(verts)
    codes[0] = Path.MOVETO
    codes[-1] = Path.CLOSEPOLY
    
    path = Path(verts, codes)
    return path 
Example 5
Project: ConceptualSpaces   Author: lbechberger   File: concept_inspector.py    (license) View Source Project 6 votes vote down vote up
def _path_for_core_alpha_cut(cuboids, d1, d2, epsilon1, epsilon2):
    """Creates the 2d path for a concept's 0.5 cut."""    
    polygon = None
    for cuboid in cuboids:
        p_min = (cuboid[0][d1], cuboid[0][d2])
        p_max = (cuboid[1][d1], cuboid[1][d2])
        alphaCuboid = shapely.geometry.Polygon([[p_min[0] - epsilon1, p_min[1]], [p_min[0] - epsilon1, p_max[1]],
             [p_min[0], p_max[1] + epsilon2], [p_max[0], p_max[1] + epsilon2],
             [p_max[0] + epsilon1, p_max[1]], [p_max[0] + epsilon1, p_min[1]], 
             [p_max[0], p_min[1] - epsilon2], [p_min[0], p_min[1] - epsilon2], [p_min[0] - epsilon1, p_min[1]]])
        
        if polygon == None:
            polygon = alphaCuboid
        else:
            polygon = polygon.union(alphaCuboid)
    
    verts = list(polygon.exterior.coords)
    codes = [Path.LINETO] * len(verts)
    codes[0] = Path.MOVETO
    codes[-1] = Path.CLOSEPOLY
    
    path = Path(verts, codes)
    return path 
Example 6
Project: CAAPR   Author: Stargrazer82301   File: plot_panel.py    (license) View Source Project 6 votes vote down vote up
def redraw_overplot_on_image(self, msg=None):
        if self.primary_image_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.primary_image_patch)
        if self.start_pt == self.end_pt:
            path = Path([self.start_pt, self.start_pt + (0.5, 0.),
                         self.start_pt, self.start_pt + (-0.5, 0.), 
                         self.start_pt, self.start_pt + (0., 0.5), 
                         self.start_pt, self.start_pt + (0., -0.5), self.start_pt], 
                        [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, 
                         Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO])
        else:
            path = Path([self.start_pt, self.end_pt], [Path.MOVETO, Path.LINETO])
        self.primary_image_patch = PathPatch(path, color='magenta', lw=1)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.primary_image_patch)
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.hideshow_button.SetLabel(u"Hide") 
Example 7
Project: CAAPR   Author: Stargrazer82301   File: plot_panel.py    (license) View Source Project 6 votes vote down vote up
def redraw_overplot_on_image(self, msg=None):
        if self.primary_image_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.primary_image_patch)
        if self.start_pt == self.end_pt:
            path = Path([self.start_pt, self.start_pt + (0.5, 0.),
                         self.start_pt, self.start_pt + (-0.5, 0.), 
                         self.start_pt, self.start_pt + (0., 0.5), 
                         self.start_pt, self.start_pt + (0., -0.5), self.start_pt], 
                        [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, 
                         Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO])
        else:
            path = Path([self.start_pt, self.end_pt], [Path.MOVETO, Path.LINETO])
        self.primary_image_patch = PathPatch(path, color='magenta', lw=1)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.primary_image_patch)
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.hideshow_button.SetLabel(u"Hide") 
Example 8
Project: MicapsDataDraw   Author: flashlxy   File: maskout.py    (license) View Source Project 6 votes vote down vote up
def getPathFromShp(shpfile, region):
    try:
        sf = shapefile.Reader(shpfile)
        vertices = []  # ??????????
        codes = []  # ??????????

        for shape_rec in sf.shapeRecords():
            # if shape_rec.record[3] == region:  # ???????region?????????record[]??????????
            if shape_rec.record[4] in region or region == [100000]:  # ??????????
                pts = shape_rec.shape.points
                prt = list(shape_rec.shape.parts) + [len(pts)]
                for i in range(len(prt) - 1):
                    for j in range(prt[i], prt[i + 1]):
                        vertices.append((pts[j][0], pts[j][1]))
                    codes += [Path.MOVETO]
                    codes += [Path.LINETO] * (prt[i + 1] - prt[i] - 2)
                    codes += [Path.CLOSEPOLY]
                path = Path(vertices, codes)
        return path
    except Exception as err:
        print(err)
        return None 
Example 9
Project: MicapsDataDraw   Author: flashlxy   File: maskout.py    (license) View Source Project 6 votes vote down vote up
def shp2clip(originfig, ax, shpfile, region):
    sf = shapefile.Reader(shpfile)
    vertices = []  # ??????????
    codes = []  # ??????????
    for shape_rec in sf.shapeRecords():
        # if shape_rec.record[3] == region:  # ???????region?????????record[]??????????
        if shape_rec.record[4] in region:  # ??????????
            pts = shape_rec.shape.points
            prt = list(shape_rec.shape.parts) + [len(pts)]
            for i in range(len(prt) - 1):
                for j in range(prt[i], prt[i + 1]):
                    vertices.append((pts[j][0], pts[j][1]))
                codes += [Path.MOVETO]
                codes += [Path.LINETO] * (prt[i + 1] - prt[i] - 2)
                codes += [Path.CLOSEPOLY]
            path = Path(vertices, codes)
            # extents = path.get_extents()
            patch = PathPatch(path, transform=ax.transData, facecolor='none', edgecolor='black')
    for contour in originfig.collections:
        contour.set_clip_path(patch)
    return path, patch 
Example 10
Project: FoundryDataBrowser   Author: ScopeFoundry   File: UsefulUtils.py    (license) View Source Project 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 11
Project: hylaa   Author: stanleybak   File: plotutil.py    (license) View Source Project 6 votes vote down vote up
def add_aggregation_poly(self, poly_verts, mode_name):
        '''add a polygon that's an aggregation on the waiting list'''

        polys = self.aggregation_mode_to_polys.get(mode_name)

        if polys is None:
            _, edge_col = self.mode_colors.get_edge_face_colors(mode_name)
            edge_col = darker(edge_col)

            polys = collections.PolyCollection([], lw=4, animated=True,
                                               edgecolor=edge_col, facecolor='none')
            self.axes.add_collection(polys)
            self.aggregation_mode_to_polys[mode_name] = polys

        paths = polys.get_paths()

        codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
        paths.append(Path(poly_verts, codes)) 
Example 12
Project: hylaa   Author: stanleybak   File: plotutil.py    (license) View Source Project 6 votes vote down vote up
def add_waiting_list_poly(self, poly_verts, mode_name):
        '''add a polygon on the waiting list'''

        polys = self.waiting_list_mode_to_polys.get(mode_name)

        if polys is None:
            face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)

            polys = collections.PolyCollection([], lw=2, animated=True, alpha=0.3,
                                               edgecolor=edge_col, facecolor=face_col)
            self.axes.add_collection(polys)
            self.waiting_list_mode_to_polys[mode_name] = polys

        paths = polys.get_paths()

        codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
        paths.append(Path(poly_verts, codes)) 
Example 13
Project: greedypacker   Author: ssbothwell   File: matplotlib_demo.py    (license) View Source Project 6 votes vote down vote up
def generate_path(i: g.Item, margin: float = 0.0) -> Path:
    vertices = []
    codes = []
    codes += [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY]
    vertices += get_vertices(i, margin) + [(0, 0)]

    vertices = np.array(vertices, float) 
    return Path(vertices, codes)

#def generate_path(items: List[g.Item], margin: bool = False) -> Path:
#    vertices = []
#    codes = []
#    for i in items:
#        codes += [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY]
#        vertices += get_vertices(i, margin) + [(0, 0)]
#
#    vertices = np.array(vertices, float) 
#    return Path(vertices, codes) 
Example 14
Project: occ_grid_map   Author: ku-ya   File: ray.py    (license) View Source Project 6 votes vote down vote up
def plot(self, axes, x, y):
        low_x = x
        low_y = y
        high_x = (x+1)
        high_y = (y+1)
        verts = [
            (low_x, low_y), # left, bottom
            (low_x, high_y), # left, top
            (high_x, high_y), # right, top
            (high_x, low_y), # right, bottom
            (0., 0.), # ignored
            ]

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

        path = Path(verts, codes)
        patch = patches.PathPatch(path, facecolor='white', edgecolor='r', lw=1)
        axes.add_patch(patch) 
Example 15
Project: occ_grid_map   Author: ku-ya   File: gistfile1.py    (license) View Source Project 6 votes vote down vote up
def plot(self, axes, x, y):
        low_x = x
        low_y = y
        high_x = (x+1)
        high_y = (y+1)
        verts = [
            (low_x, low_y), # left, bottom
            (low_x, high_y), # left, top
            (high_x, high_y), # right, top
            (high_x, low_y), # right, bottom
            (0., 0.), # ignored
            ]

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

        path = Path(verts, codes)
        patch = patches.PathPatch(path, facecolor='white', edgecolor='r', lw=1)
        axes.add_patch(patch) 
Example 16
Project: faampy   Author: ncasuk   File: isopleths.py    (license) View Source Project 6 votes vote down vote up
def _make_barb(self, temperature, theta, speed, angle):
        """Add the barb to the plot at the specified location."""
        u, v = self._uv(speed, angle)
        if 0 < speed < _BARB_BINS[0]:
            # Plot the missing barbless 1-2 knots line.
            length = self._kwargs['length']
            pivot_points = dict(tip=0.0, middle=-length / 2.)
            pivot = self._kwargs.get('pivot', 'tip')
            offset = pivot_points[pivot]
            verts = [(0.0, offset), (0.0, length + offset)]
            verts = mtransforms.Affine2D().rotate(math.radians(-angle)).transform(verts)
            codes = [Path.MOVETO, Path.LINETO]
            path = Path(verts, codes)
            size = length ** 2 / 4
            xy = np.array([[temperature, theta]])
            barb = PathCollection([path], (size,), offsets=xy,
                                  transOffset=self._transform, **self._custom_kwargs)
            barb.set_transform(mtransforms.IdentityTransform())
            self.axes.add_collection(barb)
        else:
            barb = plt.barbs(temperature, theta, u, v,
                             transform=self._transform, **self._kwargs)
        return barb 
Example 17
Project: pauvre   Author: conchoecia   File: gfftools.py    (license) View Source Project 5 votes vote down vote up
def _plot_lff(panel, left_df, right_df, colorMap, y_pos, bar_thickness, text):
    """ plots a lff patch
      1__________2      ____________
      | #lff      \     \ #rff      \
      | left for   \3     \ right for \
      | forward    /     / forward   /
      5___________/4    /___________/
    """
    #if there is only one feature to plot, then just plot it

    print("plotting lff")
    verts = [(left_df['start'], y_pos + bar_thickness), #1
             (right_df['start'] - chevron_width, y_pos + bar_thickness), #2
             (left_df['stop'], y_pos + (bar_thickness/2)), #3
             (right_df['start'] - chevron_width, y_pos), #4
             (left_df['start'], y_pos), #5
             (left_df['start'], y_pos + bar_thickness), #1
             ]
    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,
             ]
    path = Path(verts, codes)
    patch = patches.PathPatch(path, lw = 0,
                 fc=colorMap[left_df['featType']] )
    text_width = left_df['width']
    if text and text_width >= min_text:
        panel = _plot_label(panel, left_df, y_pos, bar_thickness)
    elif text and text_width < min_text and text_width >= text_cutoff:
        panel = _plot_label(panel, left_df,
                            y_pos, bar_thickness,
                            rotate = True, arrow = True)

    return panel, patch 
Example 18
Project: pauvre   Author: conchoecia   File: gfftools.py    (license) View Source Project 5 votes vote down vote up
def _plot_rff(panel, left_df, right_df, colorMap, y_pos, bar_thickness, text):
    """ plots a rff patch
      ____________      1__________2
      | #lff      \     \ #rff      \
      | left for   \    6\ right for \3
      | forward    /     / forward   /
      |___________/     /5__________/4
    """
    #if there is only one feature to plot, then just plot it

    print("plotting rff")
    verts = [(right_df['start'], y_pos + bar_thickness), #1
             (right_df['stop'] - arrow_width, y_pos + bar_thickness), #2
             (right_df['stop'], y_pos + (bar_thickness/2)), #3
             (right_df['stop'] - arrow_width, y_pos), #4
             (right_df['start'], y_pos), #5
             (left_df['stop'] + chevron_width, y_pos + (bar_thickness/2)), #6
             (right_df['start'], y_pos + bar_thickness), #1
             ]
    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,
             ]
    path = Path(verts, codes)
    patch = patches.PathPatch(path, lw = 0,
                 fc=colorMap[right_df['featType']] )
    text_width = right_df['width']
    if text and text_width >= min_text:
        panel = _plot_label(panel, right_df, y_pos, bar_thickness)
    elif text and text_width < min_text and text_width >= text_cutoff:
        panel = _plot_label(panel, right_df,
                            y_pos, bar_thickness, rotate = True)
    return panel, patch 
Example 19
Project: em_examples   Author: geoscixyz   File: DCWidgetResLayer2_5D.py    (license) View Source Project 5 votes vote down vote up
def addCylinder2Mod(xc,zc,r,modd,sigCylinder):

    # Get points for cylinder outline
    cylinderPoints = getCylinderPoints(xc,zc,r)
    mod = copy.copy(modd)

    verts = []
    codes = []
    for ii in range(0,cylinderPoints.shape[0]):
        verts.append(cylinderPoints[ii,:])

        if(ii == 0):
            codes.append(Path.MOVETO)
        elif(ii == cylinderPoints.shape[0]-1):
            codes.append(Path.CLOSEPOLY)
        else:
            codes.append(Path.LINETO)

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    # #Check selected cell centers by plotting
    # # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-40,40)
    # ax.set_ylim(-35,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mod[insideInd] = sigCylinder
    return mod 
Example 20
Project: em_examples   Author: geoscixyz   File: DCWidgetResLayer2_5D.py    (license) View Source Project 5 votes vote down vote up
def addPlate2Mod(xc,zc,dx,dz,rotAng,modd,sigPlate):
    # use matplotlib paths to find CC inside of polygon
    plateCorners = getPlateCorners(xc,zc,dx,dz,rotAng)
    mod = copy.copy(modd)

    verts = [
        (plateCorners[0,:]), # left, top
        (plateCorners[1,:]), # right, top
        (plateCorners[3,:]), # right, bottom
        (plateCorners[2,:]), # left, bottom
        (plateCorners[0,:]), # left, top (closes polygon)
        ]

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

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    #Check selected cell centers by plotting
    # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-10,10)
    # ax.set_ylim(-20,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mod[insideInd] = sigPlate
    return mod 
Example 21
Project: em_examples   Author: geoscixyz   File: DCWidgetPlate_2D.py    (license) View Source Project 5 votes vote down vote up
def createPlateMod(xc, zc, dx, dz, rotAng, sigplate, sighalf):
    # use matplotlib paths to find CC inside of polygon
    plateCorners = getPlateCorners(xc,zc,dx,dz,rotAng)

    verts = [
        (plateCorners[0,:]), # left, top
        (plateCorners[1,:]), # right, top
        (plateCorners[3,:]), # right, bottom
        (plateCorners[2,:]), # left, bottom
        (plateCorners[0,:]), # left, top (closes polygon)
        ]

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

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    #Check selected cell centers by plotting
    # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-10,10)
    # ax.set_ylim(-20,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mtrue = sighalf*np.ones([mesh.nC,])
    mtrue[insideInd] = sigplate
    mtrue = np.log(mtrue)
    return mtrue 
Example 22
Project: em_examples   Author: geoscixyz   File: DCWidgetPlate2_5D.py    (license) View Source Project 5 votes vote down vote up
def createPlateMod(xc, zc, dx, dz, rotAng, sigplate, sighalf):
    # use matplotlib paths to find CC inside of polygon
    plateCorners = getPlateCorners(xc,zc,dx,dz,rotAng)

    verts = [
        (plateCorners[0,:]), # left, top
        (plateCorners[1,:]), # right, top
        (plateCorners[3,:]), # right, bottom
        (plateCorners[2,:]), # left, bottom
        (plateCorners[0,:]), # left, top (closes polygon)
        ]

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

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    #Check selected cell centers by plotting
    # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-10,10)
    # ax.set_ylim(-20,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mtrue = sighalf*np.ones([mesh.nC,])
    mtrue[insideInd] = sigplate
    mtrue = np.log(mtrue)
    return mtrue 
Example 23
Project: braindecode   Author: robintibor   File: plot.py    (license) View Source Project 5 votes vote down vote up
def _add_ears(ax, linewidth, linestyle):
    start_x = np.cos(10 * np.pi / 180.0)
    start_y = np.sin(10 * np.pi / 180.0)
    end_x = np.cos(-15 * np.pi / 180.0)
    end_y = np.sin(-15 * np.pi / 180.0)
    verts = [
        (start_x, start_y),
        (start_x + 0.05, start_y + 0.05),  # out up
        (start_x + 0.1, start_y),  # further out, back down
        (start_x + 0.11, (end_y * 0.7 + start_y * 0.3)),  # midpoint
        (end_x + 0.14, end_y),  # down out start
        (end_x + 0.05, end_y - 0.05),  # down out further
        (end_x, end_y),  # endpoint
    ]

    codes = [Path.MOVETO] + [Path.CURVE3] * (len(verts) - 1)

    path = Path(verts, codes)

    patch = patches.PathPatch(path, facecolor='none',
                              linestyle=linestyle, linewidth=linewidth)

    ax.add_patch(patch)
    verts_left = [(-x, y) for x, y in verts]
    path_left = Path(verts_left, codes)

    patch_left = patches.PathPatch(path_left, facecolor='none',
                                   linestyle=linestyle, linewidth=linewidth)

    ax.add_patch(patch_left) 
Example 24
Project: nxviz   Author: ericmjl   File: plots.py    (license) View Source Project 5 votes vote down vote up
def draw_edges(self):
        """
        Renders edges to the figure.
        """
        for i, (start, end) in enumerate(self.graph.edges()):
            start_idx = self.nodes.index(start)
            start_x = self.node_coords['x'][start_idx]
            start_y = self.node_coords['y'][start_idx]

            end_idx = self.nodes.index(end)
            end_x = self.node_coords['x'][end_idx]
            end_y = self.node_coords['y'][end_idx]

            arc_radius = abs(end_x - start_x) / 2
            # we do min(start_x, end_x) just in case start_x is greater than
            # end_x.
            middle_x = min(start_x, end_x) + arc_radius
            middle_y = arc_radius * 2

            verts = [(start_x, start_y),
                     (middle_x, middle_y),
                     (end_x, end_y)]

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

            path = Path(verts, codes)
            patch = patches.PathPatch(path, lw=1, **self.edgeprops, zorder=1)
            self.ax.add_patch(patch) 
Example 25
Project: CRIkit2   Author: CoherentRamanNIST   File: roi.py    (license) View Source Project 5 votes vote down vote up
def _verts_to_path(verts, isclose = True):
    """
    Convert vertices to paths
    """
    if not isclose:
        verts += verts[0]
    else:
        pass
    codes = [_Path.MOVETO] + [_Path.LINETO]*(len(verts)-2) + [_Path.CLOSEPOLY]
    return _Path(verts, codes) 
Example 26
Project: CRIkit2   Author: CoherentRamanNIST   File: roi.py    (license) View Source Project 5 votes vote down vote up
def verts_to_path(verts, isclosed=True):
    """
    Convert vertices to paths
    """
    if not isclosed:
        verts += [verts[0]]
    else:
        pass
    codes = [_Path.MOVETO] + [_Path.LINETO] * (len(verts)-2) + \
            [_Path.CLOSEPOLY]

    return _Path(verts, codes) 
Example 27
Project: Eins   Author: xiongbeer   File: testplot.py    (license) View Source Project 5 votes vote down vote up
def setPlot(self):
        #????
        verts = [
            (self.rX[0] - self.xOffset, self.rY[0] + self.yOffset),
            (self.rX[1] - self.xOffset, self.rY[1] + self.yOffset),
            (self.rX[1] + self.xOffset, self.rY[1] - self.yOffset),
            (self.rX[0] + self.xOffset, self.rY[0] - self.yOffset),
            (self.rX[0] - self.xOffset, self.rY[0] + self.yOffset)
        ]
        codes = [
            Path.MOVETO,
            Path.LINETO,
            Path.LINETO,
            Path.LINETO,
            Path.CLOSEPOLY,
        ]

        path = Path(verts, codes)
        patch = patches.PathPatch(path, facecolor='white', alpha = 0.3)
        self.plotLayer.add_patch(patch)

        #????
        self.plotLayer.plot([self.rX[0] - self.xOffset, self.rX[1] - self.xOffset], [self.rY[0] + self.yOffset, self.rY[1] + self.yOffset], 'w')
        self.plotLayer.plot([self.rX[0] + self.xOffset, self.rX[1] + self.xOffset], [self.rY[0] - self.yOffset, self.rY[1] - self.yOffset], 'w')

        #????
        for i in xrange(1,self.lanes+1):
             self.plotLayer.plot() 
Example 28
Project: MicapsDataDraw   Author: flashlxy   File: Map.py    (license) View Source Project 5 votes vote down vote up
def DrawShapeFile(area):
        """
        ??????shp??
        :param area: ??shp???????????????
        :return: 
        """
        try:
            shpfile = area.file
            border_shape = shapefile.Reader(shpfile)
            border = border_shape.shapes()
            for b in border:
                border_points = b.points
                path_data = []
                count = 0
                for cell in border_points:
                    if count == 0:
                        trans = (Path.MOVETO, (cell[0], cell[1]))
                        path_data += [trans]
                        cell_end = cell
                    else:
                        trans = (Path.CURVE4, (cell[0], cell[1]))
                        path_data += [trans]
                trans = (Path.CLOSEPOLY, (cell_end[0], cell_end[1]))
                path_data += [trans]

                codes, verts = zip(*path_data)
                path = Path(verts, codes)
                x, y = zip(*path.vertices)
                plt.plot(x, y, 'k-', linewidth=area.linewidth, color=area.linecolor)
        except Exception as err:
            print(u'?{0}?{1}-{2}'.format(area['file'], err, datetime.now())) 
Example 29
Project: hylaa   Author: stanleybak   File: plotutil.py    (license) View Source Project 5 votes vote down vote up
def add_inv_vio_poly(self, poly_verts):
        'add an invariant violation polygon'

        paths = self.inv_vio_polys.get_paths()

        codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
        paths.append(Path(poly_verts, codes)) 
Example 30
Project: hylaa   Author: stanleybak   File: plotutil.py    (license) View Source Project 5 votes vote down vote up
def add_reachable_poly(self, poly_verts, parent, mode_name):
        '''add a polygon which was reachable'''

        assert isinstance(parent, ContinuousPostParent)

        if len(poly_verts) <= 2:
            markers = self.parent_to_markers.get(parent)

            if markers is None:
                face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)

                markers = Line2D([], [], animated=True, ls='None', alpha=0.5, marker='o', mew=2, ms=5,
                                 mec=edge_col, mfc=face_col)
                self.axes.add_line(markers)
                self.parent_to_markers[parent] = markers

            xdata = markers.get_xdata()
            ydata = markers.get_ydata()
            xdata.append(poly_verts[0][0])
            ydata.append(poly_verts[0][1])
            markers.set_xdata(xdata)
            markers.set_ydata(ydata)
        else:
            polys = self.parent_to_polys.get(parent)

            if polys is None:
                face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)
                polys = collections.PolyCollection([], lw=2, animated=True, alpha=0.5,
                                                   edgecolor=edge_col, facecolor=face_col)
                self.axes.add_collection(polys)
                self.parent_to_polys[parent] = polys

            paths = polys.get_paths()

            codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
            paths.append(Path(poly_verts, codes)) 
Example 31
Project: c3nav   Author: c3nav   File: geometry.py    (license) View Source Project 5 votes vote down vote up
def plot_geometry(geom, title=None, bounds=None):
    fig = plt.figure()
    axes = fig.add_subplot(111)
    if bounds is None:
        bounds = geom.bounds
    axes.set_xlim(bounds[0], bounds[2])
    axes.set_ylim(bounds[1], bounds[3])
    verts = []
    codes = []
    if not isinstance(geom, (tuple, list)):
        geom = assert_multipolygon(geom)
    else:
        geom = tuple(chain(*(assert_multipolygon(g) for g in geom)))
    for polygon in geom:
        for ring in chain([polygon.exterior], polygon.interiors):
            verts.extend(ring.coords)
            codes.append(Path.MOVETO)
            codes.extend((Path.LINETO,) * len(ring.coords))
            verts.append(verts[-1])

    if title is not None:
        plt.title(title)

    path = Path(verts, codes)
    patch = PathPatch(path)
    axes.add_patch(patch)
    plt.show() 
Example 32
Project: c3nav   Author: c3nav   File: mpl.py    (license) View Source Project 5 votes vote down vote up
def linearring_to_mpl_path(linearring):
    return Path(np.array(linearring),
                (Path.MOVETO, *([Path.LINETO] * (len(linearring.coords)-2)), Path.CLOSEPOLY), readonly=True) 
Example 33
Project: la-rochelle-2017   Author: rougier   File: exercise-5-sol.py    (license) View Source Project 5 votes vote down vote up
def bezier(p0, p1, p2, p3, color='k', linewidth=1.0):
    codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
    path = Path(np.array([p0,p1,p2,p3]), codes)
    return patches.PathPatch(path, fc='none',
                             color=color, linewidth=linewidth)


# New figure with aspect = 1 
Example 34
Project: occ_grid_map   Author: ku-ya   File: ray.py    (license) View Source Project 5 votes vote down vote up
def plot(self, axes):
        for ix in range(self.aabb.low[0],self.aabb.high[0]):
            for iy in range(self.aabb.low[1], self.aabb.high[1]):
                low_x = ix
                low_y = iy
                high_x = (ix+1)
                high_y = (iy+1)
                verts = [
                    (low_x, low_y), # left, bottom
                    (low_x, high_y), # left, top
                    (high_x, high_y), # right, top
                    (high_x, low_y), # right, bottom
                    (0., 0.), # ignored
                    ]

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

                path = Path(verts, codes)
                patch = patches.PathPatch(path, facecolor='white', lw=1)
                axes.add_patch(patch)
        #axes.set_xlim((-0.5,1.5))
        #axes.set_ylim((-0.5,1.5))

# Find the distance between "frac(s)" and "1" if ds > 0, or "0" if ds < 0. 
Example 35
Project: occ_grid_map   Author: ku-ya   File: gistfile1.py    (license) View Source Project 5 votes vote down vote up
def plot(self, axes):
        for ix in range(self.aabb.low[0],self.aabb.high[0]):
            for iy in range(self.aabb.low[1], self.aabb.high[1]):
                low_x = ix
                low_y = iy
                high_x = (ix+1)
                high_y = (iy+1)
                verts = [
                    (low_x, low_y), # left, bottom
                    (low_x, high_y), # left, top
                    (high_x, high_y), # right, top
                    (high_x, low_y), # right, bottom
                    (0., 0.), # ignored
                    ]

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

                path = Path(verts, codes)
                patch = patches.PathPatch(path, facecolor='white', lw=1)
                axes.add_patch(patch)
        #axes.set_xlim((-0.5,1.5))
#        axes.set_ylim((-0.5,1.5))

# Find the distance between "frac(s)" and "1" if ds > 0, or "0" if ds < 0. 
Example 36
Project: unmixing   Author: arthur-e   File: visualize.py    (license) View Source Project 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 37
Project: em_examples   Author: geoscixyz   File: DCWidgetResLayer2_5D.py    (license) View Source Project 4 votes vote down vote up
def sumCylinderCharges(xc, zc, r, qSecondary):
    chargeRegionVerts = getCylinderPoints(xc, zc, r+0.5)

    codes = chargeRegionVerts.shape[0]*[Path.LINETO]
    codes[0] = Path.MOVETO
    codes[-1] = Path.CLOSEPOLY

    chargeRegionPath = Path(chargeRegionVerts, codes)
    CCLocs = mesh.gridCC
    chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs))

    plateChargeLocs = CCLocs[chargeRegionInsideInd]
    plateCharge = qSecondary[chargeRegionInsideInd]
    posInd = np.where(plateCharge >= 0)
    negInd = np.where(plateCharge < 0)
    qPos = Utils.mkvc(plateCharge[posInd])
    qNeg = Utils.mkvc(plateCharge[negInd])

    qPosLoc = plateChargeLocs[posInd,:][0]
    qNegLoc = plateChargeLocs[negInd,:][0]

    qPosData = np.vstack([qPosLoc[:,0], qPosLoc[:,1], qPos]).T
    qNegData = np.vstack([qNegLoc[:,0], qNegLoc[:,1], qNeg]).T

    if qNeg.shape == (0,) or qPos.shape == (0,):
        qNegAvgLoc = np.r_[-10, -10]
        qPosAvgLoc = np.r_[+10, -10]
    else:
        qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg)
        qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos)

    qPosSum = np.sum(qPos)
    qNegSum = np.sum(qNeg)

    # # Check things by plotting
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # platePatch = patches.PathPatch(platePath, facecolor='none', lw=2)
    # ax.add_patch(platePatch)
    # chargeRegionPatch = patches.PathPatch(chargeRegionPath, facecolor='none', lw=2)
    # ax.add_patch(chargeRegionPatch)
    # plt.scatter(qNegAvgLoc[0],qNegAvgLoc[1],color='b')
    # plt.scatter(qPosAvgLoc[0],qPosAvgLoc[1],color='r')
    # ax.set_xlim(-15,5)
    # ax.set_ylim(-25,-5)
    # plt.axes().set_aspect('equal')
    # plt.show()

    return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc

# The only thing we need to make it work is a 2.5D field object in SimPEG 
Example 38
Project: em_examples   Author: geoscixyz   File: DCWidgetResLayer2D.py    (license) View Source Project 4 votes vote down vote up
def sumCylinderCharges(xc, zc, r, qSecondary):
    chargeRegionVerts = getCylinderPoints(xc, zc, r+0.5)

    codes = chargeRegionVerts.shape[0]*[Path.LINETO]
    codes[0] = Path.MOVETO
    codes[-1] = Path.CLOSEPOLY

    chargeRegionPath = Path(chargeRegionVerts, codes)
    CCLocs = mesh.gridCC
    chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs))

    plateChargeLocs = CCLocs[chargeRegionInsideInd]
    plateCharge = qSecondary[chargeRegionInsideInd]
    posInd = np.where(plateCharge >= 0)
    negInd = np.where(plateCharge < 0)
    qPos = Utils.mkvc(plateCharge[posInd])
    qNeg = Utils.mkvc(plateCharge[negInd])

    qPosLoc = plateChargeLocs[posInd,:][0]
    qNegLoc = plateChargeLocs[negInd,:][0]

    qPosData = np.vstack([qPosLoc[:,0], qPosLoc[:,1], qPos]).T
    qNegData = np.vstack([qNegLoc[:,0], qNegLoc[:,1], qNeg]).T

    if qNeg.shape == (0,) or qPos.shape == (0,):
        qNegAvgLoc = np.r_[-10, -10]
        qPosAvgLoc = np.r_[+10, -10]
    else:
        qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg)
        qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos)

    qPosSum = np.sum(qPos)
    qNegSum = np.sum(qNeg)

    # # Check things by plotting
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # platePatch = patches.PathPatch(platePath, facecolor='none', lw=2)
    # ax.add_patch(platePatch)
    # chargeRegionPatch = patches.PathPatch(chargeRegionPath, facecolor='none', lw=2)
    # ax.add_patch(chargeRegionPatch)
    # plt.scatter(qNegAvgLoc[0],qNegAvgLoc[1],color='b')
    # plt.scatter(qPosAvgLoc[0],qPosAvgLoc[1],color='r')
    # ax.set_xlim(-15,5)
    # ax.set_ylim(-25,-5)
    # plt.axes().set_aspect('equal')
    # plt.show()

    return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc