def plot_mother_lineages(cells,the_frame,mother_list,fsz): fig=plt.figure(1,frameon=True) DPI = fig.get_dpi() figxlim=fsz[0] figylim=fsz[1] figWidth=figxlim/float(DPI) figHight=figylim/float(DPI) fig.set_size_inches(figWidth,figHight) ax = plt.axes() ax.clear() ax.axis("off") ax.set_aspect('equal',adjustable='box') plt.xlim(0,figxlim) plt.ylim(0,figylim) for this_cell in cells[the_frame-1]: if(this_cell['cellID'] in mother_list): this_poly=this_cell['roiPoly'] patch = PolygonPatch(this_poly, facecolor=[0,0,0], edgecolor=[0,0,0], alpha=0.7, zorder=2) ax.add_patch(patch) else: this_poly=this_cell['roiPoly'] patch = PolygonPatch(this_poly, facecolor=[0.75,0.75,0.75], edgecolor=[0,0,0], alpha=0.7, zorder=2) ax.add_patch(patch) plt.gca().invert_yaxis() plt.tight_layout(pad=0,h_pad=0,w_pad=0) return plt
def plot_guppy_bins(self, bins=True): self.ax.cla() # clear axes # plot tank ext = [(0, 0), (0, 100), (100, 100), (100, 0)] polygon = shapely.geometry.Polygon(ext) plot_coords(self.ax, polygon.exterior) patch = PolygonPatch(polygon, facecolor=BLUE, edgecolor=BLACK, alpha=0.6, zorder=1) self.ax.add_patch(patch) # plot bins if bins: for i, p in enumerate(self.bins): patch = PolygonPatch(p, facecolor=BLACK, edgecolor=YELLOW, alpha=(1 - self.agent_view[i]), zorder=1) self.ax.add_patch(patch) # plot fishes ellipse = patches.Ellipse((self.obs_pos[0], self.obs_pos[1]), 2, 7, rad_to_deg360(self.obs_angle - pi / 2)) self.ax.add_patch(ellipse) for i in range(len(self.others)): position = (self.others[i][0], self.others[i][1]) ellipse = patches.Ellipse(position, 2, 7, rad_to_deg360(self.others_angle[i] - pi / 2)) self.ax.add_patch(ellipse) # plot legend self.ax.text(110, 100, 'angle: {:.2f}°'.format(degrees(self.obs_angle))) self.ax.text(110, 90, 'o_vector: ({:.2f},{:.2f})'.format(self.obs_ori[0], self.obs_ori[1])) self.ax.text(110, 80, 'angular turn: {:.10f}'.format(self.loc_vec[0])) self.ax.text(110, 70, 'linear speed: {:.10f}'.format(self.loc_vec[1])) # self.ax.text(110, 60, 'dist travelled: {:.10f}'.format(self.dist_difference)) pyplot.show(block=False) pyplot.pause(0.00000000000001)
def plot_floorplan(annos, polygons): """plot floorplan """ fig = plt.figure() ax = fig.add_subplot(1, 1, 1) junctions = np.array( [junc['coordinate'][:2] for junc in annos['junctions']]) for (polygon, poly_type) in polygons: polygon = Polygon(junctions[np.array(polygon)]) plot_coords(ax, polygon.exterior, alpha=0.5) if poly_type == 'outwall': patch = PolygonPatch(polygon, facecolor=semantics_cmap[poly_type], alpha=0) else: patch = PolygonPatch(polygon, facecolor=semantics_cmap[poly_type], alpha=0.5) ax.add_patch(patch) plt.axis('equal') plt.axis('off') plt.savefig('floorplan.png') plt.show()
def plot_with_feed_zones(self): """ a plotting tool for branching creatures Returns ------- """ fig = plt.figure(1, figsize=(5, 5), dpi=180) ax = fig.add_subplot(111) line = MultiLineString(self.coords) patches = [PolygonPatch(circ) for circ in self.feed_zones] for patch in patches: ax.add_patch(patch) dilated = line.buffer(self.feed_radius) patch1 = PolygonPatch(dilated, facecolor='#99ccff', edgecolor='#6699cc') ax.add_patch(patch1) for i in range(len(self.coords)): x, y = line[i].xy plt.axis('equal') ax.plot(x, y, color='#999999') plt.show()
def plot_2_pols(ax, P1, P2, initA, initB): patch1 = PolygonPatch(P1, facecolor='blue', edgecolor='#6699cc', alpha=0.5, zorder=2) patch2 = PolygonPatch(P2, facecolor='red', edgecolor='#6699cc', alpha=0.5, zorder=2) plot_coords(ax, initA.coords) plot_coords(ax, initB.coords) ax.add_patch(patch1) ax.add_patch(patch2) ax.set_title('Original') minx1, miny1, maxx1, maxy1 = P1.bounds minx2, miny2, maxx2, maxy2 = P2.bounds minx = min(int(minx1) - 1, int(minx2) - 1, int(initA.x), int(initB.x)) miny = min(int(miny1) - 1, int(miny2) - 1, int(initA.y), int(initB.y)) maxx = max(int(maxx1) + 1, int(maxx2) + 1, int(initA.x), int(initB.x)) maxy = max(int(maxy1) + 1, int(maxy2) + 1, int(initA.y), int(initB.y)) xrange = [minx, maxx] yrange = [miny, maxy] ax.set_xlim(*xrange) ax.set_xticks(range(*xrange) + [xrange[-1]]) ax.set_ylim(*yrange) ax.set_yticks(range(*yrange) + [yrange[-1]]) ax.set_aspect(1)
def PlotMaze(self): fig = plt.figure(dpi=90) ax = fig.add_subplot(111) x, y = self.maze.exterior.xy ax.plot(x, y, 'o', color='#999999', zorder=1) patch = PolygonPatch(self.maze, facecolor='#6699cc', edgecolor='#6699cc', alpha=0.5, zorder=2) ax.add_patch(patch) if self.muds: for mud in self.muds: patch = PolygonPatch(mud, facecolor='#ff3333', edgecolor='#ff3333', alpha=0.5, hatch='\\', zorder=2) ax.add_patch(patch) if self.obstacles: for obstacles in self.obstacles: patch = PolygonPatch(obstacles, facecolor='#ffaabb', edgecolor='#ffaabb', alpha=0.5, hatch='\\', zorder=2) ax.add_patch(patch) plt.show()
def plot_filled_cross_section(cross_section_polygon, water_filled_polygon): """ Plot the original cross section with the region filled with water. Parameters: ----------- cross_section_polygon: :obj:`shapely.geometry.polygon.Polygon` Polygon of cross section. water_filled_polygon: :obj:`shapely.geometry.polygon.Polygon` Polygon of water filled region. """ plt.figure() plot_ax = plt.axes() plot_ax.set_aspect('equal') # build the polygon from exterior points patch = PolygonPatch(cross_section_polygon, facecolor=[1, 1, 1], edgecolor=[0, 0, 0], alpha=0.7, zorder=2) plot_ax.add_patch(patch) patch = PolygonPatch(water_filled_polygon, facecolor=[0, 0, 0.7], edgecolor=[0, 0, 0], alpha=0.7, zorder=2) plot_ax.add_patch(patch) # use bounding box to set plot limits minx, miny, maxx, maxy = cross_section_polygon.bounds plt.xlim(minx, maxx) plt.ylim(miny, maxy) plt.show()
def drawDisjointSet(D,sinks): fig = plt.figure() ax = fig.add_subplot(111) ax.set_title('Disjoint Set of BF-WSN nodes') col = ['r','g','b','y'] D_num = np.shape(D)[0] sinks_num = np.shape(sinks)[0] for i in range(D_num): nodes_num = np.shape(D[i])[0] for j in range(nodes_num): patch = PolygonPatch(Point(D[i][j]['centre']).buffer(D[i][j]['radius']), fc=col[i], ec=col[i], alpha=0.5, zorder=1) ax.add_patch(patch) for i in range(sinks_num): patch = PolygonPatch(Point(sinks[i]).buffer(10),fc='k', ec='k', alpha=0.2, zorder=1) ax.add_patch(patch) """x1 = list(nodes[:, 0]) y1 = list(nodes[:, 1]) ax.scatter(x1, y1, s=20, color=col[i], marker='o') #for a, b in zip(x1, y1): # ax.text(a, b, (a, b), ha='center', va='bottom', fontsize=10)""" set_limits(ax, 0, 50, 0, 50) plt.savefig('Disjoint Set of BF-WSN nodes.jpg') plt.legend() plt.show()
def visualize_perspective(args): colors = np.array(colormap_255) / 255 room_path = os.path.join(args.path, args.scene, "2D_rendering", args.room, "perspecitve") for position in np.sort(os.listdir(room_path)): position_path = os.path.join(room_path, position) image = io.imread(os.path.join(position_path, "rgb_rawlight.png")) annos = json.load(os.path.join(room_path, "layout.json")) fig = plt.figure() for i, key in enumerate(['visible_mask', 'invisible_mask']): ax = fig.add_subplot(2, 1, i + 1) plt.axis('off') plt.imshow(image) for i, planes in enumerate(annos['planes']): if key == 'visible_mask': # if visible if len(planes[key]): for plane in planes[key]: polygon = Polygon([annos['junctions'][id]['coordinate'] for id in plane]) patch = PolygonPatch(polygon, facecolor=colors[i], alpha=0.5) ax.add_patch(patch) else: plane = planes['invisible_mask'] polygon = Polygon([annos['junctions'][id]['coordinate'] for id in plane]) patch = PolygonPatch(polygon, facecolor=colors[i], alpha=0.5) ax.add_patch(patch) plt.title(key) plt.show()
def display(self,show=True,overlays=None): import matplotlib.pyplot as plt from descartes.patch import PolygonPatch ax = plt.axes() x = [] y = [] for geom in self.geometry: if isinstance(geom,MultiPolygon): for geom2 in geom: try: ax.add_patch(PolygonPatch(geom2,alpha=0.5)) except: geom2 = wkt.loads(geom2.wkt) ax.add_patch(PolygonPatch(geom2,alpha=0.5)) ct = geom2.centroid x.append(ct.x) y.append(ct.y) else: ax.add_patch(PolygonPatch(geom,alpha=0.5)) ct = geom.centroid x.append(ct.x) y.append(ct.y) if overlays is not None: for geom in overlays: ax.add_patch(PolygonPatch(geom,alpha=0.5,fc='#999999')) ax.scatter(x,y,alpha=1.0) if show: plt.show()
def plot_hex_to_square_map(coef, hex_cells_dict, sq_cells_dict): t0 = datetime.datetime.now() # fig=plt.figure() # ax1=fig.add_subplot(111) for hex_id, sq_overlaps in coef.items(): fig = plt.figure() ax1 = fig.add_subplot(111) hex_cell = hex_cells_dict[hex_id] poly = hex_cell.vertices x, y = poly.exterior.xy ax1.plot(x, y, 'o', zorder=1) patch = PolygonPatch(poly, alpha=0.5, zorder=2, edgecolor='blue') ax1.add_patch(patch) print '>>> Plotting hex cell: ', hex_id for sq_cell_data in sq_overlaps: sq_cell_id = sq_cell_data[0] overlap_coef = sq_cell_data[1] sq_cell = sq_cells_dict[sq_cell_id] print('overlapping with sq_cell: ', sq_cell_id, 'with overlap coef: ', overlap_coef) poly = sq_cell.polygon x, y = poly.exterior.xy ax1.plot(x, y, 'o', zorder=1) patch = PolygonPatch(poly, alpha=0.5, zorder=2, edgecolor='red') ax1.add_patch(patch) t1 = datetime.datetime.now() print 'one hex cell overlap complete in: ', t1 - t0, ' sec\n' t0 = t1 #ax1.set_xlim(-160, 160) #ax1.set_ylim(-160, 160) #ax1.set_aspect(1) plt.show()
def drawBoroughs(self, boroughFile): sf = shp.Reader(boroughFile) for s in sf.shapeRecords(): R = 1.0 G = 1.0 B = 1.0 shape = s.shape newPoints = [] for point in shape.points: newPoints.append( transform(self.inProj, self.outProj, point[0], point[1])) #print(newPoints) nparts = len(shape.parts) if nparts == 1: #polygon = Polygon(shape.points) polygon = Polygon(newPoints) patch = PolygonPatch(polygon, facecolor=[R, G, B, 0], alpha=1.0, zorder=2) self.ax.add_patch(patch) else: for ip in range(nparts): i0 = shape.parts[ip] if ip < nparts - 1: i1 = shape.parts[ip + 1] - 1 else: i1 = len(shape.points) #polygon = Polygon(shape.points[i0:i1+1]) polygon = Polygon(newPoints[i0:i1 + 1]) patch = PolygonPatch(polygon, facecolor=[R, G, B, 0], alpha=1.0, zorder=2) self.ax.add_patch(patch)
def Get_Fields_Max_Area_2010(ujd_start, ujd_stop): flat_cols = [ '#1abc9c', '#2ecc71', '#3498db', '#9b59b6', '#34495e', '#f39c12', '#d35400', '#c0392b', '#7f8c8d' ] conn = psycopg2.connect( host='srv01050.soton.ac.uk', user='******', password='******', database='frohmaier') #Connecting to the SN Group Server Database cur = conn.cursor() cur.execute( "SELECT distinct (subtraction.ptffield), min(subtraction.ra_ul), max(subtraction.dec_ul), max(subtraction.ra_ur), max(subtraction.dec_ur), max(subtraction.ra_lr), min(subtraction.dec_lr), min(subtraction.ra_ll), min(subtraction.dec_ll) from subtraction JOIN ptffield ON subtraction.ptffield=ptffield.id where subtraction.filter='R' and (ujd>%s and ujd<%s) and height<10 and width<10 and ptffield.color_excess<0.1 and ra_ll>305 and dec_ll>-23 and dec_lr>-23 and ra_ul>305 and dec_ur<31.6 and dec_ul<31.6 GROUP BY subtraction.ptffield, ptffield.color_excess;", ( float(ujd_start), float(ujd_stop), )) #Get Everything from the Subtraction Table m = cur.fetchall() cur.close() print 'DB_Done' sub = np.array(m) #All the Subtraction Information ''' 0 ptffield, 1 ra_ul, 2 dec_ul, 3 ra_ur, 4 dec_ur, 5 ra_lr, 6 dec_lr, 7 ra_ll, 8 dec_ll, ''' # for i in range(0,len(sub)): # print (sub[:,1][i],sub[:,2][i]),(sub[:,3][i],sub[:,4][i]),(sub[:,5][i],sub[:,6][i]),(sub[:,7][i],sub[:,8][i]) # print len(sub[:,0]) #plt.subplot(111, projection="mollweide") for i in range(0, len(sub[:, 0])): area = Polygon([(np.min( (sub[:, 1][i], sub[:, 7][i])), np.max((sub[:, 2][i], sub[:, 4][i]))), (np.max((sub[:, 3][i], sub[:, 5][i])), np.max((sub[:, 2][i], sub[:, 4][i]))), (np.max((sub[:, 5][i], sub[:, 3][i])), np.min((sub[:, 8][i], sub[:, 6][i]))), (np.min((sub[:, 7][i], sub[:, 1][i])), np.min((sub[:, 8][i], sub[:, 6][i])))]) patch = PolygonPatch(area, facecolor='white', zorder=2) plt.gca().add_patch(patch) #fig = matplotlib.pyplot.gcf() #fig.set_size_inches(20,10) #plt.xlim(0,360) #plt.ylim(-35,90) #cords=Convert_2010_Coords() sima = Polygon([(305, -23), (305, 31.6), (360, 31.6), (360, -23)]) simp = PolygonPatch(sima, facecolor='k', zorder=0) plt.gca().add_patch(simp) '''
def plot_hex_to_square_map(coef,hex_cells_dict,sq_cells_dict): ''' DESCRIPTION: This function is for visualization of mapping of Hexagonal cells to the square cells, for checking the correctness of resolution of interpolation with the criteria as mentioned by Florian Sir, (one square cell not overlapping with more than three hexagon cells) USAGE: This function is called internally in main.py generate_interpolation function. INPUT: coef : the coef dictionary mapping each hexagonal cells to their correspoinding square cells hex_cells_dict : the dictionary of hexagonal cells obtained from the root file sq_cells_dict : the square cell dictionary generated by get_square_cells function above and saved in 'sq_cells_data' directory in current location OUTPUT: Currently no output from this function ''' t0=datetime.datetime.now() print '>>> Calculating the area of smallar cell for filtering' filter_hex_cells=([c.vertices.area for c in hex_cells_dict.values() if len(list(c.vertices.exterior.coords))==7]) small_wafer_area=min(filter_hex_cells) t1=datetime.datetime.now() print '>>> Area calculated %s in time: %s sec'%( small_wafer_area,t1-t0) t0=t1 for hex_id,sq_overlaps in coef.items(): hex_cell=hex_cells_dict[hex_id] poly=hex_cell.vertices #Filtering the cells in smaller region if poly.area!=small_wafer_area: continue fig=plt.figure() ax1=fig.add_subplot(111) x,y=poly.exterior.xy ax1.plot(x,y,'o',zorder=1) patch=PolygonPatch(poly,alpha=0.5,zorder=2,edgecolor='blue') ax1.add_patch(patch) print '>>> Plotting hex cell: ',hex_id for sq_cell_data in sq_overlaps: sq_cell_id=sq_cell_data[0] overlap_coef=sq_cell_data[1] sq_cell=sq_cells_dict[sq_cell_id] print ('overlapping with sq_cell: ',sq_cell_id, 'with overlap coef: ',overlap_coef) poly=sq_cell.polygon x,y=poly.exterior.xy ax1.plot(x,y,'o',zorder=1) patch=PolygonPatch(poly,alpha=0.5,zorder=2,edgecolor='red') ax1.add_patch(patch) t1=datetime.datetime.now() print 'one hex cell overlap complete in: ',t1-t0,' sec\n' plt.show()
def draw_frame(ax, state, spikes, buffers, data, times, means, covariances, gmms, helpers=None): ax.cla() ax.patch.set_color((0, 0, 0, 0.)) Ls = make_Ls() ax.add_patch( PolygonPatch(Ls, facecolor=colors["Ls"], edgecolor="none", zorder=0)) # Plot the text box textbox = make_code_textbox(buffers, state) ax.text(-3.5, 3.4, textbox, fontsize=10., fontfamily="monospace", verticalalignment='top', color=colors["code"], zorder=1) # Overlay background bkgd = Point(0, 0).buffer(5.25) - Ls ax.add_patch( PolygonPatch(bkgd, facecolor=colors["bkgd"], edgecolor='none', zorder=2)) # Draw the spike train lines = make_spike_train(ax, state, spikes, 10, bkgd) for line in lines: ax.add_patch(PolygonPatch(line, facecolor='w', edgecolor='w', zorder=3)) # Plot a contour of the KDE if helpers is None: helpers = init_kdeplot(bkgd) # Plot data points and kernel density estimate these_data = data[times < state] if len(these_data > 0): kdeplot(these_data, *helpers) ax.plot(these_data[:, 0], these_data[:, 1], 'wo', markersize=4, zorder=4) ax.add_patch( PolygonPatch(bkgd, facecolor='none', edgecolor='k', lw=6, zorder=100)) ax.set_xlim(-5.5, 5.5) ax.set_ylim(-5.5, 5.5) return helpers
def plot_boundary_juliaset(self): # determines the resolution of the boundary of the julia set # dots per unit - 50 dots per 1 units means 200 points per 4 units intval = 1 / DPU_JULIASET r_range = np.arange(-self.plot_limit, self.plot_limit + intval, intval) c_range = np.arange(-self.plot_limit, self.plot_limit + intval, intval) constant = complex(self.julia_constant.center[0], self.julia_constant.center[1]) stables = np.array([], dtype='bool') for imag in c_range: for real in r_range: stable, _ = self.juliaset_func(complex(real, imag), constant) stables = np.append(stables, stable) rows = len(r_range) cols = len(c_range) start = len(stables) stable_field = [] for _ in range(cols): start -= rows real_vals = [ 1 if val == True else 0 for val in stables[start:start + rows] ] stable_field.append(real_vals) stable_field = np.array(stable_field, dtype='int') kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) stable_boundary = convolve2d(stable_field, kernel, mode='same') self.boundary_points = np.array([], dtype='complex') for col in range(cols): for row in range(rows): if stable_boundary[col, row] in BORDER_RANGE: real_val = r_range[row] # invert cols as min imag value is highest col and vice versa imag_val = c_range[cols - 1 - col] self.boundary_points = np.append( self.boundary_points, complex(real_val, imag_val)) else: pass bnd_points = [ Point(val.real, val.imag) for val in self.boundary_points ] bnd_polygon, _ = alpha_shape(bnd_points, ALPHA) patches = [] if bnd_polygon.geom_type == 'Polygon': patches.append(PolygonPatch(bnd_polygon)) ec, lw = 'red', 2 else: for poly in bnd_polygon: patches.append(PolygonPatch(poly)) ec, lw = 'green', 1 p = PatchCollection(patches, facecolor='none', edgecolor=ec, lw=lw) self.juliaset_plot = self.ax.add_collection(p)
def draw_zone_map(ax, sf, heat={}, text=[], arrows=[]): continent = [235/256, 151/256, 78/256] ocean = (89/256, 171/256, 227/256) theta = np.linspace(0, 2*np.pi, len(text)+1).tolist() ax.set_facecolor(ocean) # colorbar if len(heat) != 0: norm = mpl.colors.Normalize(vmin=(min(heat.values())-1),vmax=max(heat.values())) #norm = mpl.colors.LogNorm(vmin=1,vmax=max(heat)) cm=plt.get_cmap('Reds') sm = plt.cm.ScalarMappable(cmap=cm, norm=norm) sm.set_array([]) plt.colorbar(sm, ticks=np.linspace((min(heat.values())-1),max(heat.values()),8), boundaries=np.arange((min(heat.values())-1)-10,max(heat.values())+10,.1)) for sr in sf.shapeRecords(): shape = sr.shape rec = sr.record loc_id = rec[shp_dic['LocationID']] zone = rec[shp_dic['zone']] if len(heat) == 0: col = continent else: if loc_id not in heat: R,G,B,A = cm(norm(0)) else: R,G,B,A = cm(norm(heat[loc_id])) col = [R,G,B] nparts = len(shape.parts) if nparts == 1: polygon = Polygon(shape.points) patch = PolygonPatch(polygon, facecolor=col, alpha=1.0, zorder=2) ax.add_patch(patch) else: for ip in range(nparts): i0 = shape.parts[ip] if ip < nparts-1: i1 = shape.parts[ip+1]-1 else: i1 = len(shape.points) polygon = Polygon(shape.points[i0:i1+1]) patch = PolygonPatch(polygon, facecolor=col, alpha=1.0, zorder=2) ax.add_patch(patch) x = (shape.bbox[0]+shape.bbox[2])/2 y = (shape.bbox[1]+shape.bbox[3])/2 if (len(text) == 0 and rec[shp_dic['Shape_Area']] > 0.0001): plt.text(x, y, str(loc_id), horizontalalignment='left', verticalalignment='left') elif len(text) != 0 and loc_id in text: ax.annotate("[{}] {}".format(loc_id, zone), xy=(x, y), xytext=(x-10000, y-100),color="white", fontsize=9,horizontalalignment='right', verticalalignment='top',bbox=dict(pad=0,fc='black',alpha=0.5))
def plot_field_sample_area(self, shape, record, polygon, crop_type): exterior_pol = Polygon(polygon.exterior.coords) sample_poly = exterior_pol.buffer(-1*self.sample_gap*self.geostep) if sample_poly.type == 'Polygon': sample_list = list(sample_poly.exterior.coords) else: exterior_pol = Polygon(polygon.exterior.coords).buffer(self.sample_gap*self.geostep) sample_poly = exterior_pol.buffer(-2*self.sample_gap*self.geostep) if sample_poly.type == 'Polygon': sample_list = list(sample_poly.exterior.coords) else: sample_list = shape.points x_sample_l = [i[0] for i in sample_list[:]] y_sample_l = [i[1] for i in sample_list[:]] print crop_type.decode('utf-8', 'ignore') self.add_field_section(self.current_field_num, crop_type, record) self.report_pdf.write(" \subsection{Field Sampling}\n\n") image_name = self.current_journal_num+"_"+self.current_field_num+'_sampling'+'.png' fig = plt.figure(1, figsize=(16,8),dpi=150) #figsize=(20,10) plt.clf() ax = fig.add_subplot(111) plot_coords(ax, polygon.exterior) patch = PolygonPatch(polygon, fc=GRAY, ec=GRAY, alpha=0.5, zorder=2) ax.add_patch(patch) patch2 = PolygonPatch(sample_poly, fc=GREEN, ec=GREEN, alpha=0.5, zorder=2) ax.add_patch(patch2) for x_sp in xrange(int(shape.bbox[0]),int(shape.bbox[2]),self.sample_gap*self.geostep): for y_sp in xrange(int(shape.bbox[1]),int(shape.bbox[3]),self.sample_gap*self.geostep): if(pnpoly(x_sample_l, y_sample_l, x_sp,y_sp)): rec_patch = patches.Rectangle((x_sp-int(self.geostep/2),y_sp-int(self.geostep/2)), self.geostep, self.geostep, fc=BLUE, ec=BLUE, alpha=0.9, zorder=2) ax.add_patch(rec_patch) #rep_pl, = ax.plot(x_sp,y_sp,'o',color=BLUE) plt.axis('equal') ax.set_title(self.current_field_num+' - ' +crop_type.decode('utf-8', 'ignore')+ ' - sample method: '+str(self.sample_gap*self.geostep)+'m grid') ax.set_xlabel('UTM meter - Easting') ax.set_ylabel('UTM meter - Northing') fig.tight_layout() plt.savefig(self.plot_folder+image_name) i = open("template/norm_figure.tex",'r') caption = "Field: "+str(self.current_field_num)+' automated sample area' data = (i.read()) % (image_name, caption, image_name[:-4]) self.report_pdf.write(data) return [x_sample_l, y_sample_l]
def plot_all_pln(ax, parent_map, ref, root): for pln in root.findall(".//PLN"): print("Processing line '%s'" % pln.attrib.get("B")) polygon = get_polygon(ref, pln) if polygon is None: continue polygon_type = int(pln.attrib.get("A")) if polygon_type == 1: # boundary patch = PolygonPatch(polygon.buffer(0), alpha=1, zorder=2, facecolor="black", linewidth=2, fill=False) elif polygon_type == 2: # treatmentzone patch = PolygonPatch([polygon], linewidth=2, facecolor="gray", alpha=0.1, hatch="...", fill=False) elif polygon_type == 3: # water patch = PolygonPatch([polygon], linewidth=2, facecolor="blue", alpha=0.1) elif polygon_type == 6: # obstacle patch = PolygonPatch(polygon.buffer(0), alpha=0.1, zorder=2, facecolor="red") elif polygon_type == 8: # other patch = PolygonPatch(polygon.buffer(0), alpha=0.1, zorder=2, facecolor="gray") elif polygon_type == 9: # mainland patch = PolygonPatch(polygon.buffer(0), alpha=0.2, zorder=2, facecolor="forestgreen", linewidth=0) elif polygon_type == 10: # headland patch = PolygonPatch(polygon.buffer(0), alpha=0.1, zorder=2, facecolor="springgreen") else: patch = PolygonPatch(polygon.buffer(0), alpha=0.1, zorder=2, facecolor="violet") ax.add_patch(patch)
def draw_frame(ax, state, spikes, data, times, means, covariances, gmms, helpers=None): ax.cla() ax.patch.set_color((0, 0, 0, 0.)) center = (-.25, -1.75) # patches = make_steam_engine(center, state) # for patch in patches: # ax.add_patch(patch) Ls = make_Ls() ax.add_patch(PolygonPatch(Ls, facecolor=colors["Ls"], edgecolor="none")) bkgd = Point(0, 0).buffer(5.25) - Ls ax.add_patch(PolygonPatch(bkgd, facecolor=colors["bkgd"], edgecolor='none')) # Draw the spike train lines = make_spike_train(ax, state, spikes, 10, bkgd) for line in lines: ax.add_patch(PolygonPatch(line, facecolor='w', edgecolor='w')) # Plot a contour of the KDE if helpers is None: helpers = init_kdeplot(bkgd) # if len(these_data > 0): # kdeplot(these_data, *helpers) for mean, covariance in zip(means, covariances): plot_gaussian_2D(mean, covariance, color=colors["gmm"]) # Plot data points these_data = data[times < 1 - state / (2 * np.pi)] ax.plot(these_data[:, 0], these_data[:, 1], 'wo', markersize=4) ax.add_patch( PolygonPatch(bkgd, facecolor='none', edgecolor='k', lw=6, zorder=100)) ax.set_xlim(-5.5, 5.5) ax.set_ylim(-5.5, 5.5) return helpers
def plotTriangles(self, tris): from matplotlib import pyplot from matplotlib.patches import Circle fig = pyplot.figure(1, dpi=90) ax = fig.add_subplot(111) ax.grid() # Draw the wafer circle = Circle( (0, 0), self.wafer_r, facecolor="#{0:0{1}X}".format(np.random.randint(0, 16777215), 6), edgecolor=BLACK, alpha=1) ax.add_patch(circle) tricenters = [tri.centroid.xy for tri in tris] x, y = list(zip(*tricenters)) ax.plot(x, y, 'bo') # Draw all the triangles for i, item in enumerate(tris): x, y = item.exterior.coords.xy ax.plot(x, y, 'k-') patch = PolygonPatch(item, facecolor="#{0:0{1}X}".format(np.random.randint(0, 16777215), 6), edgecolor=BLACK, alpha=0.5, zorder=2) ax.add_patch(patch) ax.axis('equal')
def drawRoadsBuildingsMatplotlib(polygons, G, displayRatio=1.0, edgeColorAttribute='level', edgeColorScale=9, nodeColorAttribute=None, nodeColorScale=None): fig = plt.figure() ax = fig.add_subplot(111) pos = {} for n in G.nodes(): pos[n] = (G.node[n]['longitude'], G.node[n]['latitude']) # nodes nx.draw_networkx_nodes(G, pos, node_size=0, alpha=0.8, color=colors[-1], ax=ax) # edges for i in range(0, 9): selectedEdges = [(u, v) for (u, v, d) in G.edges(data=True) if d['level'] == i] selectedColors = [colors[i] for e in selectedEdges] nx.draw_networkx_edges(G, pos, edgelist=selectedEdges, width=edgeWidth[i], edge_color=selectedColors, ax=ax) selectedEdges = [(u, v) for (u, v, d) in G.edges(data=True) if d['level'] == -1] nx.draw_networkx_edges(G, pos, edgelist=selectedEdges, width=0.8, edge_color='r', ax=ax) for feature in polygons['features']: if displayRatio < 1.0: if random.random() >= displayRatio: continue polygon = shape(feature['geometry']) patch = PolygonPatch(polygon, facecolor='#FD7400', edgecolor='#FD7400', alpha=0.5, zorder=1) ax.add_patch(patch) bounds = getBuildingsBoundaries(polygons) minx, miny, maxx, maxy = bounds ax.set_xlim(minx, maxx) ax.set_ylim(miny, maxy) plt.show()
def plot(self, type_="pose", ax=None, alpha=0.5, plot_relations=False, **kwargs): """Plot either the pose or point feasible regions. Parameters ---------- type_ : {'pose','point'} The type of feasible region to plot. """ if type_ == "pose": p = self.pose_region else: p = self.point_region if ax is None: ax = plt.gca() ax.set_xlim([self.bounds[0], self.bounds[2]]) ax.set_ylim([self.bounds[1], self.bounds[3]]) patch = PolygonPatch(p, facecolor=cnames['black'], alpha=alpha, zorder=2, **kwargs) ax.add_patch(patch) plt.show()
def plot_polygons(fig, ax, polygonsList): ''' Plot descrates.PolygonPatch from list of polygons objs for each CLASS ''' legend_patches = [] for cType in polygonsList: print('{} : {} \tcount = {}'.format(cType, CLASSES[cType], len(polygonsList[cType]))) legend_patches.append( Patch(color=COLORS[cType], label='{} ({})'.format(CLASSES[cType], len(polygonsList[cType])))) for polygon in polygonsList[cType]: mpl_poly = PolygonPatch(polygon, color=COLORS[cType], lw=0, alpha=0.7, zorder=ZORDER[cType]) ax.add_patch(mpl_poly) # ax.relim() ax.autoscale_view() ax.set_title('Objects') ax.set_xticks([]) ax.set_yticks([]) return legend_patches
def draw_polygons(polygons, ax=None, color="b", size=1.2, show_edges=False, set_range=False): ax = get_ax(ax) ax.set_aspect(1) for i in range(len(polygons)): polygon = polygons[i] #color= x, y = polygon.exterior.xy if show_edges: #plot edges of polygon ax.plot(x, y, 'o', color='#999999', zorder=1) #plot surface patch = PolygonPatch(polygon, facecolor=color, edgecolor=color, alpha=0.5, zorder=1) ax.add_patch(patch) #finalise figure properties ax.set_title('Polygon representation') if set_range: (xrange, yrange) = ut.range_from_polygons(polygons, size) ax.set_xlim(*xrange) ax.set_ylim(*yrange)
def showPoly(threshold): #this outputs blue and white polygon polygons = [] tempx = [] tempy = [] for i in roomListLocal: tempx.append(i[0]) tempy.append(i[1]) polygon = Polygon(i) polygon = polygon.buffer(threshold, resolution=16, cap_style=2, join_style=3, mitre_limit=0.1) polygons.append(polygon) u = cascaded_union(polygons) polygon = Polygon(building_metre_polygon) global newPoly newPoly = polygon.difference(u) newPoly = newPoly.buffer(threshold, resolution=16, cap_style=2, join_style=3, mitre_limit=0.1) fig = plt.figure(1, figsize=5000, dpi=1000) ax = fig.add_subplot(111) print(newPoly) #plot_coords(ax, newPoly.exterior) patch = PolygonPatch(newPoly, facecolor=v_color(newPoly), edgecolor=v_color(newPoly), alpha=0.5, zorder=2) xrange = [-10, np.max(tempx) + 10] yrange = [-10, np.max(tempy) + 10] ax.set_xlim(*xrange) ax.set_ylim(*yrange) ax.set_aspect(1) ax.add_patch(patch) ax.set_aspect(1) plt.show()
def simple_plane_plot(cells_d, fraction): t0 = datetime.datetime.now() fig = plt.figure() ax1 = fig.add_subplot(111) i = 0 period = int(1.0 / fraction) for id, cell in cells_d.items(): if (i % period == 0): poly = cell.vertices # Plot vertices # commented, save CPU time # x,y=poly.exterior.xy # ax1.plot(x,y,'o',zorder=1) patch = PolygonPatch(poly, alpha=0.5, zorder=2, edgecolor='blue') ax1.add_patch(patch) i += 1 #plt.show() #if i%100==0: # plt.savefig(str(i)+'.png') #plt.show() t1 = datetime.datetime.now() print 'Cells plotted: number=', int(fraction * len(cells_d)), ', time=', t1 - t0 ax1.set_xlim(-160, 160) ax1.set_ylim(-160, 160) ax1.set_aspect(1) plt.show()
def plot_poly(poly): fig = pyplot.figure() ax = fig.add_subplot(1,1,1) plot_coords(ax, poly.exterior) patch = PolygonPatch(poly, facecolor=v_color(poly), edgecolor=v_color(poly), alpha=0.5, zorder=2) ax.add_patch(patch) pyplot.show()
def PlotBasinsWithHillshade(DataDirectory, OutDirectory, fname_prefix, stream_order=1): """ Read in the basins and plot them over a hillshade coloured by their cluster ID """ df = pd.read_csv(OutDirectory+fname_prefix+'_profiles_clustered_SO{}.csv'.format(stream_order)) clusters = df.cluster_id.unique() # make a figure fig = plt.figure(1, facecolor='white') gs = plt.GridSpec(100,100,bottom=0.1,left=0.1,right=0.9,top=0.9) ax = fig.add_subplot(gs[5:100,5:100]) # plot the raster hs_raster = IO.ReadRasterArrayBlocks(DataDirectory+fname_prefix+'_hs.bil') extent = LSDP.GetRasterExtent(DataDirectory+fname_prefix+'_hs.bil') plt.imshow(hs_raster, cmap=cm.gray, extent=extent) means = {} for i,cl in enumerate(clusters): this_df = df[df.cluster_id == cl] # get the polygons polygons = ReadBasinPolygons(DataDirectory, OutDirectory, fname_prefix+'_basins_SO{}_CL{}'.format(stream_order,int(cl))) for p in polygons: #print(list(p.exterior.coords)) patch = PolygonPatch(p, facecolor=this_df.iloc[0]['colour'], alpha=1.0, zorder=2, lw=0.2) ax.add_patch(patch) #print(polygons) # for each plt.savefig(OutDirectory+'polygons.png', FigFormat='png', dpi=500)
def overlay_fov(self, tx=cartopy.crs.PlateCarree(), maxGate=75, rangeLimits=None, beamLimits=None, model="IS", fov_dir="front", fovColor=None, fovAlpha=0.2, fovObj=None, zorder=2, lineColor="k", lineWidth=1, ls="-"): """ Overlay radar FoV """ self.maxGate = maxGate lcolor = lineColor from numpy import transpose, ones, concatenate, vstack, shape self.hdw = pydarn.read_hdw_file(self.rad) sgate = 0 egate = self.hdw.gates if not maxGate else maxGate ebeam = self.hdw.beams if beamLimits is not None: sbeam, ebeam = beamLimits[0], beamLimits[1] else: sbeam = 0 self.rad_fov = rad_fov.CalcFov(hdw=self.hdw, ngates=egate) xyz = self.projection.transform_points(tx, self.rad_fov.lonFull, self.rad_fov.latFull) x, y = xyz[:, :, 0], xyz[:, :, 1] contour_x = concatenate((x[sbeam, sgate:egate], x[sbeam:ebeam, egate], x[ebeam, egate:sgate:-1], x[ebeam:sbeam:-1, sgate])) contour_y = concatenate((y[sbeam, sgate:egate], y[sbeam:ebeam, egate], y[ebeam, egate:sgate:-1], y[ebeam:sbeam:-1, sgate])) self.plot(contour_x, contour_y, color=lcolor, zorder=zorder, linewidth=lineWidth, ls=ls) if fovColor: contour = transpose(vstack((contour_x, contour_y))) polygon = Polygon(contour) patch = PolygonPatch(polygon, facecolor=fovColor, edgecolor=fovColor, alpha=fovAlpha, zorder=zorder) self.add_patch(patch) return