我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用matplotlib.path()。
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")
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)
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
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
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
def end_track_positions(self): pos = np.array(self.positions) if pos.size == 0: return try: xnum = int(self.x_axis_num.text()) ynum = int(self.y_axis_num.text()) except ValueError: sys.stderr.write('Need axes numbers to be integers\n') return pos = np.append(pos, pos[-1]).reshape(-1,2) self.path_list.append(matplotlib.path.Path(pos, closed=True)) points_inside = np.array([self.path_list[-1].contains_point((p[xnum], p[ynum])) for p in self.embed]) sys.stderr.write('%d/%d frames inside ROI %d\n' % (points_inside.sum(), len(points_inside), len(self.points_inside_list))) self.points_inside_list.append(self.conversion.indices[np.where(points_inside)[0]]) self.roi_list.append( matplotlib.patches.PathPatch( self.path_list[-1], color='white', fill=False, linewidth=2., figure=self.frame.fig ) ) self.frame.fig.get_axes()[0].add_artist(self.roi_list[-1]) for p in self.click_points_list: p.remove() self.frame.canvas.draw() self.frame.canvas.mpl_disconnect(self.connect_id) self.positions = [] self.click_points_list = [] if self.roi_summary is None: self.add_roi_frame() elif self.roi_summary.text() == '': self.roi_frame.show() self.gen_roi_summary() self.add_roi_radiobutton(len(self.roi_list)-1)
def get_dasharray(obj, i=None): """Get an SVG dash array for the given matplotlib linestyle Parameters ---------- obj : matplotlib object The matplotlib line or path object, which must have a get_linestyle() method which returns a valid matplotlib line code i : integer (optional) Returns ------- dasharray : string The HTML/SVG dasharray code associated with the object. """ if obj.__dict__.get('_dashSeq', None) is not None: return ','.join(map(str, obj._dashSeq)) else: ls = obj.get_linestyle() if i is not None: ls = ls[i] dasharray = LINESTYLES.get(ls, None) if dasharray is None: warnings.warn("dash style '{0}' not understood: " "defaulting to solid.".format(ls)) dasharray = LINESTYLES['-'] return dasharray
def SVG_path(path, transform=None, simplify=False): """Construct the vertices and SVG codes for the path Parameters ---------- path : matplotlib.Path object transform : matplotlib transform (optional) if specified, the path will be transformed before computing the output. Returns ------- vertices : array The shape (M, 2) array of vertices of the Path. Note that some Path codes require multiple vertices, so the length of these vertices may be longer than the list of path codes. path_codes : list A length N list of single-character path codes, N <= M. Each code is a single character, in ['L','M','S','C','Z']. See the standard SVG path specification for a description of these. """ if transform is not None: path = path.transformed(transform) vc_tuples = [(vertices if path_code != Path.CLOSEPOLY else [], PATH_DICT[path_code]) for (vertices, path_code) in path.iter_segments(simplify=simplify)] if not vc_tuples: # empty path is a special case return np.zeros((0, 2)), [] else: vertices, codes = zip(*vc_tuples) vertices = np.array(list(itertools.chain(*vertices))).reshape(-1, 2) return vertices, list(codes)
def get_path_style(path, fill=True): """Get the style dictionary for matplotlib path objects""" style = {} style['alpha'] = path.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['edgecolor'] = color_to_hex(path.get_edgecolor()) if fill: style['facecolor'] = color_to_hex(path.get_facecolor()) else: style['facecolor'] = 'none' style['edgewidth'] = path.get_linewidth() style['dasharray'] = get_dasharray(path) style['zorder'] = path.get_zorder() return style
def DrawContourAndMark(contour, x, y, z, level, clipborder, patch, m): # ??????? ------ ?????????? if contour.contour['visible']: matplotlib.rcParams['contour.negative_linestyle'] = 'dashed' if contour.contour['colorline']: CS1 = m.contour(x, y, z, levels=level, linewidths=contour.contour['linewidth']) else: CS1 = m.contour(x, y, z, levels=level, linewidths=contour.contour['linewidth'], colors=contour.contour['linecolor']) # ????????? if contour.contourlabel['visible']: CS2 = plt.clabel(CS1, inline=1, fmt=contour.contourlabel['fmt'], inline_spacing=contour.contourlabel['inlinespacing'], fontsize=contour.contourlabel['fontsize'], colors=contour.contourlabel['fontcolor']) # ??????????? if clipborder.path is not None and clipborder.using: for collection in CS1.collections: # collection.set_clip_on(True) collection.set_clip_path(patch) for text in CS2: if not clipborder.path.contains_point(text.get_position()): text.remove() # print(CS2)
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
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) 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 = 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()))
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()))
def GetFontProperties(font): fontfile = r"C:\WINDOWS\Fonts\{0}".format(font['family']) if not os.path.exists(fontfile): fp = FontProperties(family=font['family'], weight=font['weight'], size=font['size']) else: fp = FontProperties(fname=fontfile, weight=font['weight'], size=font['size']) return fp