def plot(self): figure = pylab.figure() axes = figure.add_subplot(111) p = PatchCollection(self.patches, alpha=1) p.set_color(self.colors) axes.add_collection(p) pylab.show()
def update(self, frame): color = (0, 0, 0) p = PatchCollection([self.__array_polygons[frame]], alpha=.5) p.set_color(color) p.set_edgecolor([0, 0, 0]) self.__ax.add_collection(p) return
def showGrid(domain, grid, filename, numbers=False, domainColor=False): fig, ax = plt.subplots() plt.xlim(0.15, 0.85) plt.ylim(0.15, 0.65) maxGeneration = max(cell.generation for cell in grid.cells if cell.generation is not None) n = 5 getColor = lambda generation: plt.get_cmap("hsv")((generation-n)/(maxGeneration-n)) print([getColor(i) for i in range(10)]) patchesPerDomain = [[] for i in range(100)] plt.axis("off") for cell in grid.cells: patchesPerDomain[cell.domain].append(Polygon(cell.vertices)) # for (v1, v2) in zip(cell.vertices, cell.vertices[1:] + [cell.vertices[0]]): # drawLine(v1, v2, color=getColor(cell)) if numbers: plt.text(cell.pos[0]+0.007, cell.pos[1], str(cell.generation), fontsize=15, horizontalalignment="center", verticalalignment="center") for successor in cell.successors: p1 = intermediatePoint(cell.pos, successor.pos, False) p2 = intermediatePoint(cell.pos, successor.pos, True) drawArrow(p1, p2, color=getColor(successor.generation)) for (i, patchList) in enumerate(patchesPerDomain): patches = PatchCollection(patchList) if domainColor: patches.set_color(getDomainColor(i)) patches.set_alpha(0.5) else: patches.set_color(getDomainColor(1)) patches.set_alpha(0.5) ax.add_collection(patches) plt.savefig(filename, bbox_inches="tight", dpi=400)
def _create_patch(self): """Creates a matplotlib polygon patch from the Shape points. This is used when making 2d images of the Shape object. :raises ValueError: No points defined for the Shape :return: a plotable polygon shape :rtype: Matplotlib object patch """ if self.points is None: ValueError("No points defined for", self) patches = [] xylist = [] for x1, z1 in zip([row[0] for row in self.points], [row[1] for row in self.points]): xylist.append([x1, z1]) polygon = Polygon(xylist, closed=True) patches.append(polygon) p = PatchCollection(patches) if self.color is not None: p.set_facecolor(self.color) p.set_color(self.color) p.color = self.color p.edgecolor = self.color # checks to see if an alpha value is provided in the color if len(self.color) == 4: p.set_alpha = self.color[-1] self.patch = p return p
def multi_Plotter(mp, circle): cm = plt.get_cmap('RdBu') num_colours = len(mp) + 1 fig = plt.figure() ax = fig.add_subplot(111) minx, miny, maxx, maxy = circle.bounds w, h = maxx - minx, maxy - miny ax.set_xlim(minx - 0.2 * w, maxx + 0.2 * w) ax.set_ylim(miny - 0.2 * h, maxy + 0.2 * h) ax.set_aspect(1) patches = [] for i in mp: patches.append( PolygonPatch(i[0], ec='#555555', lw=0.2, alpha=1., zorder=1)) patches.append( PolygonPatch(circle, ec='#555555', lw=0.2, alpha=1., zorder=1)) ax.add_collection(PatchCollection(patches, match_original=True)) cmap = plt.get_cmap('RdYlBu') nfloors = np.random.rand(num_colours) colors = cmap(nfloors) collection = PatchCollection(patches) collection.set_color(colors) ax.add_collection(collection) ax.set_xticks([]) ax.set_yticks([]) plt.title("Shapefile polygons rendered using Shapely") plt.tight_layout() plt.show()
def plt_real(ax, intruders, moving, d_vector, j): cx = max_x/2 cy = max_y/2 patches = [] for intruder in intruders: T1, T2 = polygon_points(intruder) polygon = Polygon(np.array([[cx,cy], T1, T2]) + intruder.vector, True) patches.append(polygon) circle = plt.Circle((intruder.x, intruder.y), 4.5) ax.add_artist(circle) p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1) #colors = np.array([0.1,0.5,0.9]) #p.set_array(colors) #colors = 100 * np.random.rand(len(patches)) #colors = np.array([255,0,0]) #p.set_array(np.array(colors)) p.set_color([1, 0, 0]) ax.add_collection(p) if j<=4: ax.arrow(40, 40, moving[0], moving[1], head_width=1, length_includes_head=True, head_length=1, fc='k', ec='k') ax.arrow(40, 40, np.squeeze(d_vector)[0], np.squeeze(d_vector)[1], head_width=1, length_includes_head=True, head_length=1, fc='b', ec='b') #ax.axis('equal') ax.set_xlim(20,60) ax.set_ylim(20,60) ax.invert_yaxis()
def colored_bar(left, height, z=None, width=0.8, bottom=0, ax=None, color='b', **kwargs): ''' A bar plot colored by a scalar sequence. Author: ------- Joe Kington 2013 taken from https://stackoverflow.com/questions/16264837/how-does-one-add-a-colorbar-to-a-polar-plot-rose-diagram ''' if ax is None: ax = plt.gca() width = itertools.cycle(np.atleast_1d(width)) bottom = itertools.cycle(np.atleast_1d(bottom)) rects = [] for x, y, h, w in zip(left, bottom, height, width): rects.append(Rectangle((x, y), w, h)) coll = PatchCollection(rects, array=z, **kwargs) coll.set_color(color) ax.add_collection(coll) # ax.autoscale() return coll
def plotMesh(self, fig=None, col='xb-', fill_mat=False): """ Plot the mesh created """ for p in self.Poly: fig = p.plotMesh(fig, col) if fill_mat: patches = [] colors = [] for p in self.Poly: if p.getMaterial() is None: continue nodes = p.getNodes() verts = [n.getX() for n in nodes] patches.append(PlotPoly(verts, closed=True)) colors.append(p.getMaterial().getID()) collection = PatchCollection(patches) jet = pl.get_cmap('jet') cNorm = Normalize(vmin=0, vmax=len(self.getMaterials())) collection.set_color(jet(cNorm(colors))) ax = fig.add_subplot(111) ax.add_collection(collection) pl.gca().set_aspect('equal', adjustable='box') return fig
def add_poly_meshplot(ax: Axes, points: np.ndarray, triangles: List[Tuple[int]], values: np.ndarray, vmax: Optional[float] = None, vmin: Optional[float] = None, cmap: str = 'coolwarm', rasterized: bool = True): """ Add meshes with faces colored by the values :param Axes ax: The axis to add a meshplot to :param ndarray points: The n x 2 array of points :param list[tuple[int]]: The set of all perimeter indicies for this mesh :param ndarray values: The values to color the perimeters with """ if vmin is None: if isinstance(values, dict): vmin = np.percentile(list(values.values()), 10) else: vmin = np.percentile(list(values), 10) if vmax is None: if isinstance(values, dict): vmax = np.percentile(list(values.values()), 90) else: vmax = np.percentile(list(values), 90) cmap = mplcm.get_cmap(cmap) norm = mplcm.colors.Normalize(vmax=vmax, vmin=vmin) scores = [] patches = [] points = np.array(points) max_idx = points.shape[0] for indices in triangles: tri = [] score = [] for i in indices: if i < 0 or i > max_idx: continue tri.append(points[i, :]) score.append(values[i]) if len(tri) < 3: continue mean = np.nanmean(score) if np.isnan(mean): continue scores.append(norm(mean)) patch = Polygon(tri, closed=True, edgecolor='none') patches.append(patch) colors = cmap(scores) collection = PatchCollection(patches) ax.add_collection(collection) collection.set_color(colors) return ax
def Plot_Symmetry(mean, Fraction, color): from matplotlib.patches import Circle, Wedge from matplotlib.collections import PatchCollection theta = np.linspace(0, 2 * np.pi, 100) r = mean fig, ax = plt.subplots() origin = np.zeros(2) patches = [] theta0 = 0 thetaf = (360.0 / Fraction.shape[0]) for i in range(0, Fraction.shape[0]): wedge = Wedge(origin, Fraction[i], theta0, thetaf) patches.append(wedge) theta0 = thetaf thetaf = thetaf + (360.0 / Fraction.shape[0]) #colors = np.linspace(0,len(patches),len(patches)) p = PatchCollection(patches, alpha=0.8) p.set_color(color) ax.add_collection(p) #Circle c = Circle(origin, r, fill=False, edgecolor='gray', ls=':') p1 = PatchCollection([c], match_original=True) ax.add_collection(p1) plt.xlim(-1.0 * mean - 0.5 * mean, 1.0 * mean + 0.5 * mean) plt.ylim(-1.0 * mean - 0.5 * mean, 1.0 * mean + 0.5 * mean) ax.set_aspect(1) plt.show()
def _create_patch(self): """Creates a matplotlib polygon patch from the Shape points. This is used when making 2d images of the Shape object. Raises: ValueError: No points defined for the Shape Returns: Matplotlib object patch: a plotable polygon shape """ if self.points is None: raise ValueError("No points defined for", self) patches = [] xylist = [] for point in self.points: xylist.append([point[0], point[1]]) polygon = Polygon(xylist, closed=True) patches.append(polygon) patch = PatchCollection(patches) if self.color is not None: patch.set_facecolor(self.color) patch.set_color(self.color) patch.color = self.color patch.edgecolor = self.color # checks to see if an alpha value is provided in the color if len(self.color) == 4: patch.set_alpha = self.color[-1] self.patch = patch return patch
def get_colored_out_collection(color_out_list, general_information): patches = [] for color_out_tuple in color_out_list: cur_color_out_location = color_out_tuple[0] cur_color_out_direction = color_out_tuple[1] tmp_value_dict = {'N': 0, 'E': 0, 'S': 0, 'W': 0} tmp_value_dict[cur_color_out_direction] = 1 for_vertex_info_dict = { 'x': cur_color_out_location.x, 'y': cur_color_out_location.y, 'N': tmp_value_dict['N'], 'E': tmp_value_dict['E'], 'S': tmp_value_dict['S'], 'W': tmp_value_dict['W'] } vertex = Vertex(general_information.system_size) vertex.subtract_off_from_link(LINK_LENGTH * 0.15) vertex.estimator_fill_from_csv_row(for_vertex_info_dict) vertex.make_patches_to_plot(LINK_LENGTH, link_width_factor=0.15) for i, cur_patch in enumerate(vertex.rect_patches): if vertex.directions[i] == cur_color_out_direction: if vertex.values[i] > 0.5: patches.append(cur_patch) collection = PatchCollection(patches) collection.set_color('Orange') return collection
def main(): lat_size = Point(L, L) testing = False lattice_files = os.listdir('lattices') for cur_f in lattice_files: rect_patches = [] tri_patches = [] if '.csv' not in cur_f: continue fig, ax = adjusted_figure() if testing: plot_test_points(ax, lat_size) break full_f_name = os.path.join('lattices', cur_f) with open(full_f_name, 'r') as csv_file: reader = csv.DictReader(csv_file) for row in reader: vertex = Vertex(lat_size) vertex.fill_from_csv_row(row) vertex.make_patches_to_plot(LINK_LENGTH, link_width_factor=0.15) rect_patches += vertex.rect_patches tri_patches += vertex.tri_patches collection = PatchCollection(rect_patches) collection.set_color('grey') ax.add_collection(collection) collection = PatchCollection(tri_patches) collection.set_color('black') ax.add_collection(collection) draw_lattice_backround(L, ax) plt.axis('equal') plt.axis('off') #ax.set_aspect(1.0) ax.set_xlim([-0.5, float(L) - 0.5]) ax.set_ylim([-0.5, float(L) - 0.5]) #plt.show() full_fig_name = os.path.join('figures', 'lattices', cur_f.split('.')[0] + '.png') plt.savefig(full_fig_name, dpi=300) plt.close(fig) if testing: plt.axis('equal') plt.show()
def plot_polygons(polygons: List[Polygon]) -> None: polygon_patches = [ patches.Polygon(np.array(p.exterior.xy).transpose()) for p in polygons ] collection = PatchCollection(polygon_patches) # indigo 500 (https://www.materialui.co/colors) collection.set_color([63 / 255, 81 / 255, 181 / 255]) pyplot.gca().add_collection(collection)
def drawSensorEquivalentMap(uvzlist,labels,outname,extraText=[],cmapName='Pastel1',zran=None,labelSize=5): fig, ax = plt.subplots(1,figsize=(10, 10)) ax.set_aspect('equal') #build the hexagonal mesh patches=[] cont_patches=[] xran=[0,0] yran=[0,0] radius=8*2.54*0.5*np.sqrt(3.)/2 circleRadius=[] for i in range(len(uvzlist)): x,y,_=uvzlist[i] #u,v,_=uvzlist[i] #x,y=getXY(u,v) xran[0]=min(x-2*radius,xran[0]) xran[1]=max(x+2*radius,xran[1]) yran[0]=min(y-2*radius,yran[0]) yran[1]=max(y+2*radius,yran[1]) patches.append( RegularPolygon((x,y), numVertices=6, radius=radius, orientation=np.radians(60), alpha=0.2, edgecolor='k') ) #if v==0: circleRadius.append( np.sqrt(x*x+y*y) ) if len(labels)<i : continue label=labels[i] ax.text(x, y, label, ha='center', va='center', size=labelSize) patchColl=PatchCollection(patches) ax.add_collection(patchColl) #set the colours according to the z values norm_zvals=[uvz[2] for uvz in uvzlist] if zran: cnorm = Normalize(vmin=zran[0],vmax=zran[1]) else: cnorm = Normalize(vmin=min(norm_zvals),vmax=max(norm_zvals)) cmap = plt.get_cmap(cmapName) colors=cmap( cnorm(norm_zvals) ) patchColl.set_color(colors) for r in circleRadius: plt.Circle((0, 0), r, color='gray', ls='--', fill=False) ax.autoscale_view() ax.set_xlabel('x',fontsize=16) ax.set_ylabel('y',fontsize=16) ax.set_xlim(xran[0],xran[1]) ax.set_ylim(yran[0],yran[1]) ax.text(0.05,1.02,'CMS preliminary', transform=ax.transAxes, fontsize=16) for i in range(len(extraText)): ax.text(0.05,0.95-i*0.05,extraText[i], transform=ax.transAxes, fontsize=14) fig.savefig(outname+'.png')
def plot_2d_ff_fb(self, diagLOS, Rrng=None, Zrng=None, savefig=False): fig, ax = plt.subplots(ncols=1, figsize=(10, 8)) fig.patch.set_facecolor("white") if Rrng and Zrng: ax.set_xlim(Rrng[0], Rrng[1]) ax.set_ylim(Zrng[0], Zrng[1]) else: ax.set_xlim(1.8, 4.0) ax.set_ylim(-2.0, 2.0) cell_patches = [] ff_fb_emiss = [] for cell in self.__data2d.cells: cell_patches.append( patches.Polygon(cell.poly.exterior.coords, closed=True, zorder=1) ) ff_fb_emiss.append(cell.ff_fb_emiss["ff_fb"]) coll1 = PatchCollection(cell_patches, zorder=1) colors = plt.cm.hot(ff_fb_emiss / np.max(ff_fb_emiss)) coll1.set_color(colors) collplt = ax.add_collection(coll1) ax.set_yscale title = self.case + " Bremss. (ff+fb) 400.96 nm" ax.set_title(title) plt.gca().set_aspect("equal", adjustable="box") # ADD COLORBAR from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) cbar_ax = divider.append_axes("right", size="7%", pad=0.1) # Very ugly workaround to scale the colorbar without clobbering the patch collection plot # (https://medium.com/data-science-canvas/way-to-show-colorbar-without-calling-imshow-or-scatter) sm = plt.cm.ScalarMappable( cmap=plt.cm.hot, norm=plt.Normalize(vmin=0, vmax=np.max(ff_fb_emiss)) ) sm._A = [] cbar = fig.colorbar(sm, cax=cbar_ax) label = "$\mathrm{ph\/s^{-1}\/m^{-3}\/sr^{-1}}$" cbar.set_label(label) # ADD DIAG LOS if diagLOS: for diag in diagLOS: self.__data2d.synth_diag[diag].plot_LOS(ax, color="w", lw=1.0) # PLOT SEPARATRIX AND WALL ax.add_patch(self.__data2d.sep_poly) ax.add_patch(self.__data2d.wall_poly) if savefig: plt.savefig(title + ".png", dpi=plt.gcf().dpi)
def init_anchors(ax): anchor_coords = read.anchors()[1] anchors = [make_circ(elem, radius=0.025) for elem in anchor_coords] anch_coll = PatchCollection(anchors, alpha=0.8) anch_coll.set_color('black') anch_coll.set_visible(False) ax.add_collection(anch_coll) return anchor_coords, anch_coll
def generate_training_data(outFilePath): # Number of tracks n = 6 add_cuts = False # Create figure and axes fig, ax = plt.subplots(1) polygons = [] cuts = [] y_step = 1.0 / n height = 1.0 / (2 * n) width = 1.0 min_length = 0.2 cut_width = 0.1 cut_height = height max_cuts = 3 # Loop over data points for i in range(n): y = y_step * i x = 0 # rect = Rectangle((x, y), width, height, ) # polygons.append(rect) ncuts = np.random.randint(0, max_cuts, 1)[0] # r1 = Rectangle((x, y), xloc, height) # r2 = Rectangle((x + cut_width, y), cut_width, cut_height) cut_locs = [] # print(ncuts) for j in range(ncuts): xloc = round(np.random.sample(1)[0], 2) cut_locs.append(xloc) cut_locs.sort() for cut_loc in cut_locs: if cut_loc - x > min_length or cut_loc < cut_width: r = Rectangle((x, y), cut_loc - x, height) rc = Rectangle((cut_loc, y), cut_width, height) x = cut_loc + cut_width polygons.append(r) cuts.append(rc) if 1 - x > min_length: r = Rectangle((x, y), 1 - x, height) polygons.append(r) else: r = Rectangle((x, y), 1 - x, height) cuts.append(r) pc = PatchCollection(polygons) pc.set_color("black") ax.add_collection(pc) if add_cuts: pc = PatchCollection(cuts) pc.set_color("red") ax.add_collection(pc) plt.axis('off') # plt.show() plt.savefig(outFilePath)
def plot_simplexes_from_multiple(G_edge, dims, times): """generate plot of colorcoded simplexes by distance from boundary :param G: network which must contain distance to boundary :param xstring: :param ystring: :param dims: dictionary of simplex -> dimension :param times: dictionary of simplex -> entry time :return: """ pos = nx.get_node_attributes(G_edge, 'pos') nppos = np.array([val for k, val in pos.items()]) xmin, ymin = np.min(nppos, 0) xmax, ymax = np.max(nppos, 0) maxdist = max(list(times.values())) cmap = matplotlib.cm.get_cmap('viridis') clist = [cmap(val) for val in np.linspace(0, 1, maxdist + 1)] fig, ax = plt.subplots() for currtime in range(maxdist + 1): boundary = [k for k, val in times.items() if val == currtime] boundarytri = [k for k in boundary if dims[k] == 2] boundaryedges = [k for k in boundary if dims[k] == 1] boundaryverts = [k for k in boundary if dims[k] == 0] patches = [] if boundaryverts: points = np.array([np.array(pos[k]) for k in boundaryverts]) plt.scatter(points[:, 0], points[:, 1], s=5, alpha=0.4, c=clist[currtime]) for e in boundaryedges: verts = list(e) beg = np.array(pos[verts[0]]) end = np.array(pos[verts[1]]) line = mlines.Line2D(np.array([beg[0], end[0]]), np.array([beg[1], end[1]]), lw=1., alpha=0.4, c=clist[currtime]) ax.add_line(line) for t in boundarytri: poly = np.zeros((3, 2)) verts = list(t) for i in np.arange(3): poly[i, :] = np.array(pos[verts[i]]) triangle = Polygon(poly, True) patches.append(triangle) p = PatchCollection(patches, alpha=0.4) p.set_color(clist[currtime]) ax.add_collection(p) plt.axis([xmin, xmax, ymin, ymax]) plt.interactive(False) plt.show()
def PlotPolygons(self, polygons, alpha=0.1, color=[0, 1, 0]): patches = [] for polygon in polygons: patches.append(Polygon(polygon, True, fill=True)) # colors = 1 * color * np.ones(len(patches)) p = PatchCollection(patches, alpha=alpha, match_original=True) p.set_color(color) # p.set_array(np.array(colors)) self.ax.add_collection(p)
def random_positions(plot_radius: bool = False): fig: plt.Figure ax: plt.Axes fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.25) ax.axis('equal') axslider = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor='lightgoldenrodyellow') axbutton = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor='lightgoldenrodyellow') bnew = Button(axbutton, 'New') num_slider = Slider(axslider, 'Robots', 3, 7, valinit=3, valstep=1) # Initalize formation = regular_shape(int(num_slider.val)) positions = random_shape(len(formation)) target, radius = approximation(positions, formation) colors = get_colors(len(formation)) arr = np.arange(positions.shape[0]) srcs = ax.scatter(positions[:,0], positions[:,1], marker='o', color=colors) dsts = ax.scatter(target[:,0], target[:,1], marker='x', color=colors) def get_circles(positions: np.array, radius: float) -> List[plt.Circle]: return [plt.Circle(position, radius) for position in positions] circles = PatchCollection(get_circles(positions, radius), alpha=0.4) circles.set_color(colors) ax.add_collection(circles) def update(event): formation = regular_shape(int(num_slider.val)) positions = random_shape(len(formation)) target, radius = approximation(positions, formation) srcs.set_offsets(positions) dsts.set_offsets(target) circles.set_paths(get_circles(positions, radius)) colors = get_colors(positions.shape[0]) srcs.set_color(colors) dsts.set_color(colors) circles.set_color(colors) # Set Axis Scale points = np.concatenate([positions, target]) llim, hlim = points.min() - radius, points.max() + radius ax.set_xlim(llim, hlim) ax.set_ylim(llim, hlim) ax.autoscale_view() fig.canvas.draw_idle() bnew.on_clicked(update) num_slider.on_changed(update) ax.autoscale_view() plt.show()
def draw_curve(): x = [] y = [] f = open("results/r_%s_%s_%s/time.txt" % (v, v1, x1_0), "r") Tmin = int(f.readline()) f.close() with open("results/r_%s_%s_%s/paretopoints.csv" % (v, v1, x1_0)) as csvfile: reader = csv.DictReader(csvfile) for row in reader: x.append(float(row["x"])) y.append(float(row["y"])) new_x, new_y = zip(*sorted(zip(x, y))) new_x = [xs for xs in new_x] new_y = [ys for ys in new_y] fig, ax = plt.subplots() if len(new_x) == 2 and new_x == [0, 0] and new_y == [0, 1]: new_x = [0] new_y = [1] if cond: for i in range(len(new_y)): new_y[i] = min(new_y[i] / (1 - new_x[i]), 1) plt.plot(new_x, new_y, marker='o', color='g') if len(new_x) > 1: new_x.append(max(x)) new_y.append(0) new_x.append(min(x)) new_y.append(0) xy = np.vstack((new_x, new_y)).T polygon = [Polygon(xy, True)] p = PatchCollection(polygon, alpha=0.3) p.set_color("g") ax.add_collection(p) plt.xlabel('P$_{min=?}$ [F crashed]') if not cond: plt.ylabel('P$_{max=?}$ [F ((x = 500) \& (t $<$ %s))]' % Tmin) else: plt.ylabel('P$_{max=?}$ [F ((x = 500) \& (t $<$ %s)) $|$ F (x=500)]' % Tmin) plt.show()
def plot(self, fig = None, col = '-b',colb = '-r', fill_mat = False, e_number = False,\ n_number = False, deformed = False, deformed_factor=1.0): """ plot the mesh """ dfact = deformed_factor patches = [] colors = [] max_mat = 0 for i, e in enumerate(self.Elements): if isinstance(e, FB.StandardBoundary): col1 = colb else: col1 = col if e_number: fig,nodes = e.plot(fig, col1, number = i, deformed = deformed,\ deformed_factor=dfact) else: fig,nodes = e.plot(fig, col1, deformed = deformed,\ deformed_factor=dfact) if fill_mat and e.Ndime == 2: if not deformed: verts = [n.getX() for n in nodes] else: verts = [n.getX() + dfact * n.getU()[0:2] for n in nodes] patches.append(PlotPoly(verts, closed=True)) m_id = e.getMaterial().getID() colors.append(m_id) if m_id > max_mat: max_mat = m_id if n_number: for i, node in enumerate(self.Nodes): pl.text(node.getX()[0], node.getX()[1], str(i)) if fill_mat: collection = PatchCollection(patches) jet = pl.get_cmap('jet') cNorm = Normalize(vmin=0, vmax=max_mat) collection.set_color(jet(cNorm(colors))) ax = fig.add_subplot(111) collection.set_array(np.array(colors)) ax.add_collection(collection) # fig.colorbar(collection, ax = ax) pl.gca().set_aspect('equal', adjustable='box') return fig
def plot(self, color=None, alpha=0.4, figax=None): if figax is None: fig, ax = plt.subplot() else: fig, ax = figax # xs = [p.x() for p in self.slab_poly.points] # ys = [p.y() for p in self.slab_poly.points] slab = Polygon( np.array([(p.x(), p.y()) for p in self.slab_poly.points]), True) collec = PatchCollection(np.array([slab]), alpha=alpha) if color is None: color = np.array([random(), random(), random()]) collec.set_color(color) ax.add_collection(collec)
def plotPolygon(polygons, colors, xMin, xMax, yMin, yMax): fig, ax = plt.subplots() patches = [] for polygon in polygons: polygon = Polygon(polygon, True) patches.append(polygon) p = PatchCollection(patches, cmap=plt.cm.jet, alpha=1.0) p.set_color(colors) ax.add_collection(p) ax.set_xlim(xMin, xMax) ax.set_ylim(yMin, yMax) plt.show()
def plot_trajectory_ellipse(frame, varx="attr_VARX", vary="attr_VARY", covxy="attr_COVXY", opacity_factor=1): """ Draw the trajectory and uncertainty ellipses around teach point. 1) Scatter of points 2) Trajectory lines 3) Ellipses :param frame: Trajectory :param opacity_factor: all opacity values are multiplied by this. Useful when used to plot multiple Trajectories in an overlay plot. :return: axis """ ellipses = [] segments = [] start_point = None for i, pnt in frame.iterrows(): # The ellipse U, s, V = np.linalg.svd(np.array([[pnt[varx], pnt[covxy]], [pnt[covxy], pnt[vary]]]), full_matrices=True) w, h = s**.5 theta = np.arctan(V[1][0]/V[0][0]) # == np.arccos(-V[0][0]) ellipse = {"xy":pnt[list(frame.geo_cols)].values, "width":w, "height":h, "angle":theta} ellipses.append(Ellipse(**ellipse)) # The line segment x, y = pnt[list(frame.geo_cols)][:2] if start_point: segments.append([start_point, (x, y)]) start_point = (x, y) ax = plt.gca() ellipses = PatchCollection(ellipses) ellipses.set_facecolor('none') ellipses.set_color("green") ellipses.set_linewidth(2) ellipses.set_alpha(.4*opacity_factor) ax.add_collection(ellipses) frame.plot(kind="scatter", x=frame.geo_cols[0], y=frame.geo_cols[1], marker=".", ax=plt.gca(), alpha=opacity_factor) lines = LineCollection(segments) lines.set_color("gray") lines.set_linewidth(1) lines.set_alpha(.2*opacity_factor) ax.add_collection(lines) return ax
def draw_lattice_backround(square_lattice_size, ax): patches = [] # horizontal lines for i in range(square_lattice_size): loc = (-LINK_LENGTH/2.0, float(i) - LINE_SIZE/2.0) cur_horz_rect = Rectangle(loc, square_lattice_size, LINE_SIZE, color='k') patches.append(cur_horz_rect) # vertical lines for i in range(square_lattice_size): loc = (i - LINE_SIZE/2.0, -LINK_LENGTH/2.0) cur_vert_rect = Rectangle(loc, LINE_SIZE, square_lattice_size, color='k') patches.append(cur_vert_rect) collection = PatchCollection(patches) collection.set_color('k') ax.add_collection(collection)
def generate_image_from_cuts(cut_map, output_file, distort=False): # Number of tracks n = 6 # Create figure and axes fig, ax = plt.subplots(1) polygons = [] y_step = 1.0 / n height = 1.0 / (2 * n) min_length = 0.3 cut_width = 0.1 # Loop over data points for i in range(n): y = y_step * i x = 0 cut_locs = [] if i in cut_map: cut_locs = cut_map[i] delta_width = 0 delta_loc = 0 for cut_loc in cut_locs: if distort and (cut_loc > min_length or cut_loc < (1.0 - min_length)): # delta_width = np.random.randint(-5, 5)/100 delta_loc = np.random.randint(0, 10) / 100 cut_loc += delta_loc #if cut_loc - x > min_length or (cut_loc == cut_locs[0] and cut_loc < cut_width): r = Rectangle((x, y), cut_loc - x, height) x = cut_loc + cut_width + delta_width polygons.append(r) if 1 - x > 0: r = Rectangle((x, y), 1 - x, height) polygons.append(r) pc = PatchCollection(polygons) pc.set_color("black") ax.add_collection(pc) plt.axis('off') # plt.show() plt.savefig(output_file) plt.close(fig)
def plot_poly(contours, ax, coord_fn, color): """Plots a polygon where contours is a list of M polygons. Each polygon is an Nx2 array of its vertices. Coord_fn is meant to be the coordinate function of a georaster image.""" p = [] for i, poly in enumerate(contours): # Avoid degenerate polygons if len(poly) < 3: continue pts = np.array(poly).squeeze() try: xs, ys = coord_fn(Xpixels=list(pts[:, 0]), Ypixels=list(pts[:, 1])) except IndexError as e: print("error on translating poly {}".format(i)) p.append(Polygon(np.vstack([xs, ys]).T, facecolor='red')) col = PatchCollection(p) col.set_color(color) ax.add_collection(col) return ax
def draw(self, route=None, size=16, tight_lo=False, eqyaxi=False, save=False, filepath='./maze.png'): figsize = (size, self.shape[1] / self.shape[0] * size) plt.rcParams["figure.figsize"] = figsize plt.rcParams['lines.linewidth'] = 4 fig, ax = plt.subplots() if eqyaxi: plt.axis('equal') if tight_lo: plt.tight_layout() plt.axis('off') plt.gca().invert_yaxis() N, M = self.shape plt.plot((0, N, N, 0, 0), (0, 0, M, M, 0), 'black') walls = [] for p1, p2 in self.walls: if p1 < p2: walls.append(Maze.get_wall(p1, p2)) plt.plot(*chain(*walls)) if route is not None: plt.plot([p[0] + 0.5 for p in route], [p[1] + 0.5 for p in route], 'green') def shift(point, d): return point[0] + d, point[1] + d t = 0.2 start = patches.Rectangle(shift(self.start, t / 2), 1 - t, 1 - t) finish = patches.Rectangle(shift(self.end, t / 2), 1 - t, 1 - t) collection = PatchCollection([start, finish]) collection.set_color(['yellow', 'green']) ax.add_collection(collection) if save: plt.savefig(filepath) else: plt.show()
def animate(x, rs, label=False, lims=(12, 12), cols=[]): """ Takes an array of positions with shape = (steps, particle, coordinates) and spot size (r) and animates their trajectory. """ if not plt.get_fignums(): fig, ax = plt.subplots(figsize=(5,5)) else: ax = plt.gca() fig = plt.gcf() x = np.squeeze(x) # if there is one particle fig.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9) # use plt.Circle over ax.scatter since Circle size is in data coordinates, but # scatter marker sizes are in Figure coordinates. c = PatchCollection([plt.Circle((0, 0), r) for r in rs]) c.set_offset_position('data') c.set_offsets(x[0]) if not cols and x.shape[1] > 10: cols = ['r' if i < lims[0]/2 else 'b' for i in x[0, :, 0]] elif cols: pass else: cols = ['r' for i in x[0, :]] c.set_color(cols) ax.add_collection(c) def advance(fn): step = fn % len(x) c.set_offsets(x[step]) ax.set_title(step) for l, xy in zip(ls, x[step]): l.set_x(xy[0]) l.set_y(xy[1]) if label: ls = [plt.text(*xy, i) for i, xy in enumerate(x[0])] else: ls = [] ax.set_xlim((0, lims[0])) ax.set_ylim((0, lims[0])) ax.add_collection(c) fa = animation.FuncAnimation(fig, advance, interval=5e3//len(x)) plt.show() return fa
def plot_polygon_collection(ax, geoms, colors_or_values, plot_values, vmin=None, vmax=None, cmap=None, edgecolor='black', alpha=0.5, linewidth=1.0, **kwargs): """ Plots a collection of Polygon and MultiPolygon geometries to `ax` Parameters ---------- ax : matplotlib.axes.Axes where shapes will be plotted geoms : a sequence of `N` Polygons and/or MultiPolygons (can be mixed) colors_or_values : a sequence of `N` values or RGBA tuples It should have 1:1 correspondence with the geometries (not their components). plot_values : bool If True, `colors_or_values` is interpreted as a list of values, and will be mapped to colors using vmin/vmax/cmap (which become required). Otherwise `colors_or_values` is interpreted as a list of colors. Returns ------- collection : matplotlib.collections.Collection that was plotted """ from descartes.patch import PolygonPatch from matplotlib.collections import PatchCollection components, component_colors_or_values = _flatten_multi_geoms( geoms, colors_or_values) # PatchCollection does not accept some kwargs. if 'markersize' in kwargs: del kwargs['markersize'] collection = PatchCollection([PolygonPatch(poly) for poly in components], linewidth=linewidth, edgecolor=edgecolor, alpha=alpha, **kwargs) if plot_values: collection.set_array(np.array(component_colors_or_values)) collection.set_cmap(cmap) collection.set_clim(vmin, vmax) else: # set_color magically sets the correct combination of facecolor and # edgecolor, based on collection type. collection.set_color(component_colors_or_values) # If the user set facecolor and/or edgecolor explicitly, the previous # call to set_color might have overridden it (remember, the 'color' may # have come from plot_series, not from the user). The user should be # able to override matplotlib's default behavior, by setting them again # after set_color. if 'facecolor' in kwargs: collection.set_facecolor(kwargs['facecolor']) if edgecolor: collection.set_edgecolor(edgecolor) ax.add_collection(collection, autolim=True) ax.autoscale_view() return collection
# define a colorramp num_colors = 12 cm = plt.get_cmap('Blues') blues = [cm(1.*i/num_colors) for i in range(num_colors)] # add colorbar legend cmap = mpl.colors.ListedColormap(blues) # define the bins bounds = np.linspace(0.0, 1.0, num_colors) # read each states shapefile for key in state_codes.keys(): m.readshapefile('../input/shapefiles/pums/tl_2013_{0}_puma10'.format(key), name='state', drawbounds=True, default_encoding='latin-1') # loop through each PUMA and assign a random color from our colorramp for info, shape in zip(m.state_info, m.state): patches = [Polygon(np.array(shape), True)] pc = PatchCollection(patches, edgecolor='k', linewidths=1., zorder=2) pc.set_color(random.choice(blues)) ax.add_collection(pc) # create a second axes for the colorbar ax2 = fig.add_axes([0.82, 0.1, 0.03, 0.8]) cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, ticks=bounds, boundaries=bounds, format='%1i') cb.ax.set_yticklabels([str(round(i, 2)) for i in bounds]) plt.savefig('map.png')
else: mNormal.readshapefile('shapefiles/pums/tl_2013_{0}_puma10'.format(key),name='state', drawbounds=True) m = mNormal # loop through each PUMA and assign the correct color to its shape for info, shape in zip(m.state_info, m.state): dataForStPuma = data[key][info['PUMACE10']] # get the percentage of households with Internet access woAccess = (dataForStPuma == 3) accessPerc = 1-(sum(woAccess)/(1.0*len(dataForStPuma))) colorInd = int(round(accessPerc*num_colors)) patches = [Polygon(np.array(shape), True)] pc = PatchCollection(patches, edgecolor='k', linewidths=1., zorder=2) pc.set_color(colorGradient[colorInd]) if (state_codes[key] == "Alaska"): axAlaska.add_collection(pc) elif (state_codes[key] == "Hawaii"): axHawaii.add_collection(pc) else: ax.add_collection(pc) # add colorbar legend cmap = mpl.colors.ListedColormap(colorGradient) # define the bins and normalize bounds = np.linspace(0,100,num_colors) # create a second axes for the colorbar ax2 = fig.add_axes([0.82, 0.1, 0.03, 0.8])
cm=plt.get_cmap('hot') reds=[cm(1.0*i/num) for i in range(num-1,-1,-1)] cmap = mpl.colors.ListedColormap(reds) fig = plt.figure(figsize=(10,5)) ax = fig.add_subplot(111, axisbg='w', frame_on=False) fig.suptitle('Percentage of children without Internet access', fontsize=20) m = Basemap(width=5000000,height=3500000,resolution='l',projection='aea',lat_1=30.,lat_2=50,lon_0=-96,lat_0=38) for key in state_codes.keys(): m.readshapefile('/home/krishna/Documents/My_Docs/PBL/data/shapefiles/pums/tl_2013_{0}_puma10'.format(key), name='state', drawbounds=True) new_key = int(key) for info, shape in zip(m.state_info, m.state): id=int(info['PUMACE10']) value=noNet[(noNet['ST']==new_key) & (noNet['PUMA']==id)]['perc'] color=int(value/10) patches = [Polygon(np.array(shape), True)] pc = PatchCollection(patches, edgecolor='k', linewidths=1., zorder=2) pc.set_color(reds[color]) ax.add_collection(pc) ax2 = fig.add_axes([0.82, 0.1, 0.03, 0.8]) bounds=np.linspace(0,10,num) cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, ticks=bounds, boundaries=bounds) cb.ax.set_yticklabels([str(round(i)*10) for i in bounds]) plt.show() plt.savefig("children_without_internet_access.png")
num_colors = 12 cm = plt.get_cmap("coolwarm") blues = [cm(1.0 * i / num_colors) for i in range(num_colors)] # add colorbar legend cmap = mpl.colors.ListedColormap(blues) # read each states shapefile for key in state_codes.keys()[0 : int(sys.argv[2])]: m.readshapefile( "../shapefiles/pums/tl_2013_{0}_puma10".format(key), name="state", drawbounds=True, default_encoding="latin-1" ) # loop through each PUMA and assign a random color from our colorramp for info, shape in zip(m.state_info, m.state): idPuma = int(info.get("PUMACE10")) val = data[((data.PUMA == idPuma) & (data.ST == int(key)))]["value"] bounds = pd.Series(np.linspace(min(data.value), max(data.value), num_colors)) bins = pd.Series(np.linspace(min(data.value), max(data.value), num_colors + 1)) bucket = bounds[pd.Series(np.histogram(val, bins)[0]) == 1].index.values patches = [Polygon(np.array(shape), True)] pc = PatchCollection(patches, edgecolor="k", linewidths=1.0, zorder=2) pc.set_color(blues[bucket]) ax.add_collection(pc) # create a second axes for the colorbar ax2 = fig.add_axes([0.82, 0.1, 0.03, 0.8]) cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, ticks=bounds, boundaries=bounds, format="%1i") cb.ax.set_yticklabels([str(round(i, 2)) for i in bounds]) plt.savefig("%s.png" % sys.argv[3])
class PlotConductors(object): # Supported conductor types conductor_types = ['Box'] # Attributes template conductor_attributes = {'xcent': None, 'ycent': None, 'zcent': None, 'xsize': None, 'ysize': None, 'zsize': None, 'voltage': None, 'permeability': None, 'permittivity': None} def __init__(self, plot_axes=None, xbounds=None, zbounds=None): """ Class for plotting of conductors in 2D (XZ). Will plot conductors in simulation domain on an X vs Z plot. Bounds and scaling are automatically determined Args: plot_axes: Optional matplotlib axes object to pass for plotting. Normally the axes object is generated by PlotConductors automatically. xbounds (tuple)(xmin, xmax): Optional Set bounds in x for plotting. Normally determined from Warp values in memory. zbounds (tuple)(zmin, zmax): Optional Set bounds in z for plotting. Normally determined from Warp values in memory. """ try: self.xmin = w3d.xmmin self.xmax = w3d.xmmax self.zmin = w3d.zmmin self.zmax = w3d.zmmax except (NameError, AttributeError): try: self.xmin = xbounds[0] self.xmax = xbounds[1] self.zmin = zbounds[0] self.zmax = zbounds[1] except TypeError: raise TypeError("Must assign xbounds and zbounds") if xbounds: self.xmin = xbounds[0] self.xmax = xbounds[1] if zbounds: self.zmin = zbounds[0] self.zmax = zbounds[1] # Try to guess an ideal scaling if abs(self.xmax - self.xmin) * 1. > 10.: self.scale = 1. elif abs(self.xmax - self.xmin) * 1e3 > 1.: self.scale = 1e3 elif abs(self.xmax - self.xmin) * 1e6 > 1.: self.scale = 1e6 else: self.scale = 1e9 self.fig = None self.plot_axes = plot_axes self.legend_axes = None self.conductors = [] self.voltages = [] self.dielectrics = [] self.permittivities = [] self.conductor_patches = None self.dielectric_patches = None self.conductor_patch_colors = [] self.dielectric_patch_colors = [] self.conductor_legend_handles = [] self.dielectric_legend_handles = [] self.legend_fontsize = 5 self.legend_anchor = (2.25, 1.0) # Color options self.map = plt.cm.seismic self.positive_voltage = self.map(15) self.negative_voltage = self.map(240) self.ground_voltage = 'grey' self.variable_voltage_color = True # If true use color that varies with voltage, else fixed color for +/- def __call__(self, solver): self.solver = solver self.conductor_coordinates(solver) self.create_axes() self.conductor_collection() plt.grid() @run_once def conductor_coordinates(self, solver): """ Runs logic for finding which conductors can be plotted and run appropriate patch creation functions. Args: solver: Warp fieldsolver object containing conductors to be plotted. Returns: None """ # Iterate through all conductor lists in the solver for key in solver.installedconductorlists: # Iterate through all conductor objects for conductor in solver.installedconductorlists[key]: # Perform check to make sure this is a conductor the code knows how to handle for obj_type in self.conductor_types: if isinstance(conductor, getattr(field_solvers.generateconductors, obj_type)): if conductor.permittivity is None: self.conductors.append(self.set_rectangle_patch(conductor)) self.voltages.append(conductor.voltage) if conductor.permittivity is not None: self.dielectrics.append(self.set_rectangle_patch(conductor, dielectric=True)) self.permittivities.append(conductor.permittivity) def conductor_collection(self): # TODO: Once dielectrics register with solver add in loop to append them to dielectric array if not self.plot_axes: self.create_axes() if len(self.voltages) > 0: self.set_collection_colors(self.conductor_patch_colors, self.voltages, self.map) # Assign patches for conductors to the plot axes self.conductor_patches = PatchCollection(self.conductors) self.conductor_patches.set_color(self.conductor_patch_colors) self.plot_axes.add_collection(self.conductor_patches) if len(self.permittivities) > 0: self.set_collection_colors(self.dielectric_patch_colors, self.permittivities, plt.cm.viridis) # Assign patches for dielectrics to the plot axes self.dielectric_patches = PatchCollection(self.dielectrics) self.dielectric_patches.set_color(self.dielectric_patch_colors) self.dielectric_patches.set_hatch('//') self.plot_axes.add_collection(self.dielectric_patches) # Setup the legend and set data for legend axes self.create_legend() if len(self.voltages) > 0: cond_legend = self.legend_axes.legend(handles=self.conductor_legend_handles, bbox_to_anchor=self.legend_anchor, borderaxespad=0., fontsize=self.legend_fontsize, title='Voltage (V)') self.legend_axes.add_artist(cond_legend) if len(self.permittivities) > 0: diel_legend = self.legend_axes.legend(handles=self.dielectric_legend_handles, bbox_to_anchor=(self.legend_anchor[0] + 0.05, self.legend_anchor[1] - 0.2), borderaxespad=0., fontsize=self.legend_fontsize, title=' Relative\nPermittivity') self.legend_axes.add_artist(diel_legend) def set_collection_colors(self, color_collection, color_values, map): # Wanted color scaling to always be red for negative and blue for positive (assuming bl-r colormap) # Created custom linear scaling to using halves of color map for +/- consistently, even if only one sign present if self.variable_voltage_color: # Min/maxes for linear mapping of voltage to colormap negative_min = min(color_values) try: negative_max = max([i for i in color_values if i < 0.]) except ValueError: negative_max = 0. try: positive_min = min([i for i in color_values if i > 0.]) except ValueError: positive_min = 0. positive_max = max(color_values) # Perform mapping for voltage in color_values: if voltage < 0.: try: color = int(-115. / abs(negative_max - negative_min) * voltage - 115. / abs(negative_max - negative_min) * negative_max + 115.) except ZeroDivisionError: color = 240 color_collection.append(map(color)) elif voltage > 0.: try: color = int(-113. / (positive_max - positive_min) * voltage + 113. / (positive_max - positive_min) * positive_max + 2) except ZeroDivisionError: color = 15 color_collection.append(map(color)) elif voltage == 0.: color_collection.append('grey') else: # Just use same color for all + or - voltages for voltage in color_values: if voltage < 0.: color_collection.append(map(240)) elif voltage > 0.: color_collection.append(map(15)) elif voltage == 0.: color_collection.append('grey') def set_rectangle_patch(self, conductor, dielectric=False): """ Creates a mpl.patches.Rectangle object to represent a box in the XZ plane. Args: conductor: Warp conductor object Returns: mpl.patches.Rectangle object """ try: x = conductor.zcent y = conductor.xcent xlength = conductor.zsize ylength = conductor.xsize except: print "Conductor does not have correct attributes to plot: \n{}".format(conductor) return xcorner = x - xlength / 2. ycorner = y - ylength / 2. if dielectric: p = patches.Rectangle( (xcorner * self.scale, ycorner * self.scale), xlength * self.scale, ylength * self.scale) # fill=False, # lw=3, # color='k', # hatch='/') else: p = patches.Rectangle( (xcorner * self.scale, ycorner * self.scale), xlength * self.scale, ylength * self.scale) return p def create_axes(self): """ Sets up the plotting region. Returns: None """ fig = plt.figure(figsize=(12, 5)) gs = GridSpec(1, 2, width_ratios=[20, 1]) ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[0, 1]) ax1.set_xticks(self.solver.zmesh * 1e9) ax1.set_yticks(self.solver.xmesh * 1e9) ax1.grid() ax2.axis('off') ax1.set_xlim(self.zmin * self.scale, self.zmax * self.scale) ax1.set_ylim(self.xmin * self.scale, self.xmax * self.scale) prefix = '($mm$)' * (self.scale == 1e3) + '($\mu m$)' * (self.scale == 1e6) + \ '($nm$)' * (self.scale == 1e9) + '($m$)' * (self.scale == 1.) ax1.set_xlabel('z ' + prefix) ax1.set_ylabel('x ' + prefix) self.fig = fig self.plot_axes = ax1 self.legend_axes = ax2 @run_once def create_legend(self): voltage_sort = [] permittivity_sort = [] for voltage, color in zip(self.voltages, self.conductor_patch_colors): if voltage not in voltage_sort: legend_artist = patches.Patch(color=color, label=voltage) self.conductor_legend_handles.append(legend_artist) voltage_sort.append(voltage) for permittivity, color in zip(self.permittivities, self.dielectric_patch_colors): if permittivity not in permittivity_sort: legend_artist = patches.Patch(color=color, label=permittivity, hatch='//') self.dielectric_legend_handles.append(legend_artist) permittivity_sort.append(permittivity) self.conductor_legend_handles = [j for (i, j) in sorted(zip(voltage_sort, self.conductor_legend_handles))] self.dielectric_legend_handles = [j for (i, j) in sorted(zip(permittivity_sort, self.dielectric_legend_handles))] def set_legend_properties(self, fontsize=5, anchor=(2.25, 1.0)): """ Adjust legend fontsize and anchor position. Can be used to fit legend into plotting region. Args: fontsize: Fontsize for legend descriptors. Default value: 5. anchor (x, y): Normalized position (0, 1) for legend. Default: (2.25, 1.0) Returns: """ self.legend_fontsize = fontsize self.legend_anchor = anchor