我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用matplotlib.patches.PathPatch()。
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
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)
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()
def _draw_concept(concept, color, epsilons): """Paints a single concept into all four plots.""" # plot cuboids separately in 3d for cuboid in concept: x, y, z = _cuboid_data_3d(cuboid[0], cuboid[1]) this._ax_3d.plot_surface(x, y, z, color=color, rstride=1, cstride=1, alpha=this._alpha_3d) # plot overall cores in 2d for i in range(3): d1, d2 = this._current_2d_indices[i] core_path = _path_for_core(concept, d1, d2) core_patch = patches.PathPatch(core_path, facecolor=color, lw=2, alpha=this._alpha_2d) this._ax_2d[i].add_patch(core_patch) alpha_path = _path_for_core_alpha_cut(concept, d1, d2, epsilons[d1], epsilons[d2]) alpha_patch = patches.PathPatch(alpha_path, facecolor='none', edgecolor=color, linestyle='dashed') this._ax_2d[i].add_patch(alpha_patch)
def MakeChart(data, hour, coordinates, lineweights, codes): cmap = plt.cm.get_cmap('YlOrRd') fig = plt.figure(num=None, figsize=(15, 10), dpi=150, facecolor='w', edgecolor='k') ax = fig.add_subplot(111) ax.set_title('Winter Day: Hour '+str(hour), fontsize=20, fontweight='bold') for i in range(0,len(codes)): if coordinates[i] != "null": path = Path(coordinates[i], codes[i]) color = np.random.random(10) patch = patches.PathPatch(path, facecolor=cmap(data), lw=lineweights[i]) ax.add_patch(patch) ax.autoscale_view() plt.axes().set_aspect('equal', 'datalim') ################
def time_map(jsonpath, hour, lineweights): data = js.loads(open(jsonpath).read()) coordinates = getcoords(data) codes = polygonscode(coordinates) cmap = plt.cm.get_cmap('YlOrRd') fig = plt.figure(num=None, figsize=(15, 10), dpi=150, facecolor='w', edgecolor='k') ax = fig.add_subplot(111) ax.set_title('Winter Day: Hour '+str(hour), fontsize=20, fontweight='bold') for i in range(0,len(codes)): if coordinates[i] != "null": path = Path(coordinates[i], codes[i]) color = np.random.random(10) patch = patches.PathPatch(path, facecolor=cmap(data), lw=lineweights[i]) ax.add_patch(patch) ax.autoscale_view() plt.axes().set_aspect('equal', 'datalim') ################
def _render_polygon(axes, polygons, segments, facecolor, edgecolor, filled=True,alpha=1.0): vertices = [] codes = [] for polygon in polygons: vertices.extend(polygon + [(0, 0)]) codes.extend( [path.Path.MOVETO] + [path.Path.LINETO] * (len(polygon) - 1) + [path.Path.CLOSEPOLY]) if vertices and filled: axes.add_patch( patches.PathPatch(path.Path(vertices, codes), facecolor=facecolor, alpha=alpha)) linewidth = 1 if not filled: linewidth = 3 for sx, sy, tx, ty in segments: axes.plot( [sx, tx], [sy, ty], linewidth=linewidth, color=edgecolor, zorder=1)
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 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(zip(lon, lat)) from matplotlib import patches apatch = patches.PathPatch(apath, linewidth=1, facecolor='none', edgecolor='k') plt.gca().add_patch(apatch) return apatch
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 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)
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
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
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 MakeChart(data, hour, coordinates, lineweights, codes): cmap = plt.cm.get_cmap('YlOrRd') fig = plt.figure(num=None, figsize=(15, 10), dpi=150, facecolor='w', edgecolor='k') ax = fig.add_subplot(111) ax.set_title('Winter Day: Hour '+str(hour), fontsize=20, fontweight='bold') for i in range(0,len(codes)): if coordinates[i] != "null": path = Path(coordinates[i], codes[i]) color = np.random.random(10) patch = patches.PathPatch(path, facecolor=cmap(data), lw=lineweights[i]) ax.add_patch(patch) ax.autoscale_view() plt.axes().set_aspect('equal', 'datalim')
def map(jsonpath): data = js.loads(open(jsonpath).read()) coordinates = getcoords(data) codes = polygonscode(coordinates) fig = plt.figure(num=None, figsize=(15, 10), dpi=150, facecolor='w', edgecolor='k') ax = fig.add_subplot(111) for i in range(0,len(codes)): if coordinates[i] != "null": path = Path(coordinates[i], codes[i]) color = np.random.random(10) patch = patches.PathPatch(path, facecolor="black") ax.add_patch(patch) ax.autoscale_view() plt.axes().set_aspect('equal', 'datalim')
def make_patch(self): ''' Retuns a matplotlib PathPatch representing the current region. ''' path = [self.arcs[0].start_point()] for a in self.arcs: if a.direction: vertices = Path.arc(a.from_angle, a.to_angle).vertices else: vertices = Path.arc(a.to_angle, a.from_angle).vertices vertices = vertices[np.arange(len(vertices) - 1, -1, -1)] vertices = vertices * a.radius + a.center path = path + list(vertices[1:]) codes = [1] + [4] * (len(path) - 1) # NB: We could also add a CLOSEPOLY code (and a random vertex) to the end return PathPatch(Path(path, codes))
def make_patch(self): '''Currently only works if all the pieces are Arcgons. In this case returns a multiple-piece path. Otherwise throws an exception.''' paths = [p.make_patch().get_path() for p in self.pieces] vertices = np.concatenate([p.vertices for p in paths]) codes = np.concatenate([p.codes for p in paths]) return PathPatch(Path(vertices, codes))
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)
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)
def add_patch(ax, nodes, color, with_nodes=True, alpha=0.625, node_color='black'): path = _path_mod.Path(nodes) 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')
def contour(self,title='',cbartitle = '',model=[], zmax = None, zmin = None, filename = None, resolution = 1, unit_str = '', bar = True): """ Returns a figure with contourplot of 2D spatial data. Insert filename to save the figure as an image. Increase resolution to increase detail of interpolated data (<1 to decrease)""" font = {'weight' : 'medium', 'size' : 22} xi = np.linspace(min(self.data.x), max(self.data.x),len(set(self.data.x))*resolution) yi = np.linspace(min(self.data.y), max(self.data.y),len(set(self.data.y))*resolution) zi = ml.griddata(self.data.x, self.data.y, self.data.v.interpolate(), xi, yi,interp='linear') fig = plt.figure() plt.rc('font', **font) plt.title(title) plt.contour(xi, yi, zi, 15, linewidths = 0, cmap=plt.cm.bone) plt.pcolormesh(xi, yi, zi, cmap = plt.get_cmap('rainbow'),vmax = zmax, vmin = zmin) if bar: cbar = plt.colorbar(); cbar.ax.set_ylabel(cbartitle) plt.absolute_import try: vertices = [(vertex.X(), vertex.Y()) for vertex in pyliburo.py3dmodel.fetch.vertex_list_2_point_list(pyliburo.py3dmodel.fetch.topos_frm_compound(model)["vertex"])] shape = patches.PathPatch(Path(vertices), facecolor='white', lw=0) plt.gca().add_patch(shape) except TypeError: pass plt.show() try: fig.savefig(filename) except TypeError: return fig # def plot_along_line(self,X,Y, tick_list): # V = self.data.v # plt.plot(heights, SVFs_can, label='Canyon')
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()
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 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
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()
def numpy_to_pathpatch(arr): """ Returns PathPatches from nested array Parameters ---------- arr : :class:`numpy:numpy.ndarray` numpy array of Polygon/Multipolygon vertices Returns ------- array : :class:`numpy:numpy.ndarray` of matplotlib.patches.PathPatch objects """ paths = [] for item in arr: if item.ndim != 2: vert = np.vstack(item) code = np.full(vert.shape[0], 2, dtype=np.int) ind = np.cumsum([0] + [len(x) for x in item[:-1]]) code[ind] = 1 path = Path(vert, code) paths.append(patches.PathPatch(path)) else: path = Path(item, [1] + (len(item) - 1) * [2]) paths.append(patches.PathPatch(path)) return np.array(paths)
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
def draw_wastemap(binpack: g.BinManager) -> None: path = generate_path(binpack.bins[0].wastemap.freerects) return PathPatch(path, lw=2.0, fc='white', edgecolor='orange', hatch='/', label='wastemap')
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.
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.
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()
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
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
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. """ from matplotlib import patches from matplotlib import path as _path_mod 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] # NOTE: ``first_edge[[0], :]`` makes a copy while the access # below **does not** copy. See # (https://docs.scipy.org/doc/numpy-1.6.0/reference/ # arrays.indexing.html#advanced-indexing) all_points.append(first_edge[0, :].reshape((1, 2), order='F')) # Add boundary first. polygon = np.asfortranarray(np.vstack(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() path = _path_mod.Path(polygon) patch = patches.PathPatch( path, facecolor=color, alpha=0.625) ax.add_patch(patch)
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)
def cone(self, plunge, bearing, angle, segments=100, bidirectional=True, **kwargs): """ Plot a polygon of a small circle (a.k.a. a cone) with an angular radius of *angle* centered at a p/b of *plunge*, *bearing*. Additional keyword arguments are passed on to the ``PathCollection``. (e.g. to have an unfilled small small circle, pass "facecolor='none'".) Parameters ---------- plunge : number or sequence of numbers The plunge of the center of the cone in degrees. bearing : number or sequence of numbers The bearing of the center of the cone in degrees. angle : number or sequence of numbers The angular radius of the cone in degrees. segments : int, optional The number of vertices to use for the cone. Defaults to 100. bidirectional : boolean, optional Whether or not to draw two patches (the one given and its antipode) for each measurement. Defaults to True. **kwargs Additional parameters are ``matplotlib.collections.PatchCollection`` properties. Returns ------- collection : ``matplotlib.collections.PathCollection`` Notes ----- If *bidirectional* is ``True``, two circles will be plotted, even if only one of each pair is visible. This is the default behavior. """ plunge, bearing, angle = np.atleast_1d(plunge, bearing, angle) patches = [] lons, lats = stereonet_math.cone(plunge, bearing, angle, segments) codes = mpath.Path.LINETO * np.ones(segments, dtype=np.uint8) codes[0] = mpath.Path.MOVETO if bidirectional: p, b = -plunge, bearing + 180 alons, alats = stereonet_math.cone(p, b, angle, segments) codes = np.hstack([codes, codes]) lons = np.hstack([lons, alons]) lats = np.hstack([lats, alats]) for lon, lat in zip(lons, lats): xy = np.vstack([lon, lat]).T path = mpath.Path(xy, codes) patches.append(mpatches.PathPatch(path)) col = mcollections.PatchCollection(patches, **kwargs) self.add_collection(col) return col