我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.patches.Polygon()。
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if self.dataset['type'] == 'instances': ax = plt.gca() polygons = [] color = [] for ann in anns: c = np.random.random((1, 3)).tolist()[0] if type(ann['segmentation']) == list: # polygon for seg in ann['segmentation']: poly = np.array(seg).reshape((len(seg)/2, 2)) polygons.append(Polygon(poly, True,alpha=0.4)) color.append(c) else: # mask mask = COCO.decodeMask(ann['segmentation']) img = np.ones( (mask.shape[0], mask.shape[1], 3) ) if ann['iscrowd'] == 1: color_mask = np.array([2.0,166.0,101.0])/255 if ann['iscrowd'] == 0: color_mask = np.random.random((1, 3)).tolist()[0] for i in range(3): img[:,:,i] = color_mask[i] ax.imshow(np.dstack( (img, mask*0.5) )) p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4) ax.add_collection(p) if self.dataset['type'] == 'captions': for ann in anns: print ann['caption']
def plotArc(start_angle, stop_angle, radius, width, **kwargs): """ write a docstring for this function""" numsegments = 100 theta = np.radians(np.linspace(start_angle+90, stop_angle+90, numsegments)) centerx = 0 centery = 0 x1 = -np.cos(theta) * (radius) y1 = np.sin(theta) * (radius) stack1 = np.column_stack([x1, y1]) x2 = -np.cos(theta) * (radius + width) y2 = np.sin(theta) * (radius + width) stack2 = np.column_stack([np.flip(x2, axis=0), np.flip(y2,axis=0)]) #add the first values from the first set to close the polygon np.append(stack2, [[x1[0],y1[0]]], axis=0) arcArray = np.concatenate((stack1,stack2), axis=0) return patches.Polygon(arcArray, True, **kwargs), ((x1, y1), (x2, y2))
def display(self, output_filename): fig, (ax) = plt.subplots(1, 1) data = [d.values for d in self.datasets] labels = [d.label for d in self.datasets] bp = ax.boxplot(data, labels = labels, notch = 0, sym = '+', vert = '1', whis = 1.5) plt.setp(bp['boxes'], color='black') plt.setp(bp['whiskers'], color='black') plt.setp(bp['fliers'], color='black', marker='+') for i in range(len(self.datasets)): box = bp['boxes'][i] box_x = [] box_y = [] for j in range(5): box_x.append(box.get_xdata()[j]) box_y.append(box.get_ydata()[j]) box_coords = list(zip(box_x, box_y)) box_polygon = Polygon(box_coords, facecolor = self.datasets[i].color) ax.add_patch(box_polygon) if self.title is not None: ax.set_title(self.title) x_min = np.amin([np.amin(d.values) for d in self.datasets]) x_max = np.amax([np.amax(d.values) for d in self.datasets]) ax.set_ylim(x_min - 0.05*(x_max - x_min), x_max + 0.05*(x_max - x_min)) fig.savefig(output_filename) plt.close(fig)
def __update_artist(self): # check if this is the first point of a branch if self.artist is None: self.artist = Circle([self.x[0], self.y[0]], radius=self.r[0], fill=False, lw=2, color='red') self.axes.add_artist(self.artist) elif len(self.x) == 0: self.artist.remove() self.artist = None elif len(self.x) == 1: self.artist.remove() self.artist = Circle([self.x[0], self.y[0]], radius=self.r[0], fill=False, lw=2, color='red') self.axes.add_artist(self.artist) # change from circle to polygon if more than 1 points are available elif len(self.x) == 2: self.artist.remove() branch = Branch(x=self.x, y=self.y, z=[0 for i in self.x], r=self.r) self.artist = Polygon(branch.outline, fill=False, color='red', lw=2) self.axes.add_artist(self.artist) else: assert (len(self.x) > 2) branch = Branch(x=self.x, y=self.y, z=[0 for i in self.x], r=self.r) self.artist.set_xy(branch.outline)
def plot_overlay(image_id): img = load_image(image_id) fig, ax = plt.subplots() xmax = grid_sizes.loc[image_id, 'xmax'] ymin = grid_sizes.loc[image_id, 'ymin'] ax.imshow(np.rollaxis(img, 0, 3)) # plotting, color by class type for cls in xrange(10): multi_poly = shapely.wkt.loads(train_wkt.loc[(train_wkt['cls'] == cls + 1) & (train_wkt['image_id'] == image_id), 'multi_poly_wkt'].values[0]) for poly in multi_poly: coords = convert_geo_coords_to_raster(np.array(poly.exterior), img.shape[1:], (xmax, ymin)) ax.add_patch(Polygon(coords, color=cls_colors[cls], lw=1.0, alpha=cls_alphas[cls])) plt.title(image_id) plt.show()
def _plot_displacement(ms): if not plot: ms.down return import matplotlib.pyplot as plt from matplotlib.patches import Polygon fig = plt.figure() ax = fig.gca() ms.processSources() ax.imshow(num.flipud(ms.down), aspect='equal', extent=[0, ms.frame.E.max(), 0, ms.frame.N.max()]) for src in ms.sources: for seg in src.segments: p = Polygon(seg.outline(), alpha=.8, fill=False) ax.add_artist(p) if isinstance(src, OkadaPath): nodes = num.array(src.nodes) ax.scatter(nodes[:, 0], nodes[:, 1], color='r') plt.show() fig.clear()
def plot(self, mode='image', ax=None, **kwargs): """Visualize the box on a matplotlib plot. :param mode: How should the box coordinates and angle be interpreted. - mode `'image'` corresponds to the situation where x coordinate of the box denotes the "row of an image" (ie. the Y coordinate of the plot, arranged downwards) and y coordinate of the box corresponds to the "column of an image", (ie X coordinate of the plot). In other words, box's x goes downwards and y - rightwards. - mode `'math'` corresponds to the "mathematics" situation where box's x and y correspond to the X and Y axes of the plot. :param ax: the matplotlib axis to draw on. If unspecified, the current axis is used. :param kwargs: arguments passed to the matplotlib's `Polygon` patch object. By default, fill is set to False, color to red and lw to 2. :return: The created Polygon object. """ ax = ax or plt.gca() poly = self.as_poly() if mode == 'image': poly = poly[:,[1,0]] kwargs.setdefault('fill', False) kwargs.setdefault('color', 'r') kwargs.setdefault('lw', 2) p = patches.Polygon(poly, **kwargs) ax.add_patch(p) return p
def plotTriangles(X, A, B, C): plt.hold(True) ax = plt.gca() for i in range(len(A)): poly = [X[A[i], :], X[B[i], :], X[C[i], :]] ax.add_patch(Polygon(np.array(poly), linestyle='solid', color='#00FF00', alpha=0.05))
def plot_polygon(ax, polygon): settings = dict(closed=True, facecolor="#eeeeee", linewidth=1., edgecolor="black") polygon = np.array(polygon) polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]]) patch = patches.Polygon(polygon, **settings) patchm = patches.Polygon(polygon_m, **settings) #patch.set_zorder(10) #patchm.set_zorder(10) ax.add_patch(patch) ax.add_patch(patchm) # will result in roughly nz * nr*(nr+1)/2 points
def __init__(self, domain, **params): self.domain = domain self.__dict__.update(domain_params) self.__dict__.update(params) if isinstance(domain, Polygon): self.cyl = True
def polygon_patches(self, cyl=False): poly_settings = dict(closed=True, facecolor="#eeeeee", linewidth=1., edgecolor="k") ball_settings = dict(facecolor="#aaaaaa", linewidth=1., edgecolor="k", alpha=0.5) ball_bind_zone_settings = dict(facecolor="#ffaaaa", linewidth=0., alpha=0.5) patches = [] for dom in self.domains: domp = dom.domain if isinstance(domp, Polygon): polygon = domp.nodes polygon = np.array(polygon) patches.append(mpatches.Polygon(polygon, **poly_settings)) if not cyl: polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]]) patches.append(mpatches.Polygon(polygon_m, **poly_settings)) elif isinstance(domp, Ball): xy = domp.x0[0], domp.x0[2] if dom.binding and dom.bind_type == "zone": p1 = mpatches.Circle(xy, domp.r + dom.ra, **ball_bind_zone_settings) p1.set_zorder(-100) patches.append(p1) p = mpatches.Circle(xy, domp.r, **ball_settings) p.set_zorder(200) patches.append(p) return patches
def getPolyIdxImg(corners,res,debug=False): """Returns all indices of image that lie within given polygon. Args: corners (list): List of (x,y)-coordinates of corners. res (int): Resolution of image (e.g. 512). Keyword Args: debug (bool): Print debugging messages. Returns: tuple: Tuple containing: * indX (list): List of indices inside polygon in x-direction. * indY (list): List of indices inside polygon in y-direction. """ #Convert to np array if necessary corners=np.asarray(corners) #Define polygonial patch poly = ptc.Polygon(corners,edgecolor='r',facecolor=(1,0,0,.2),) #Create grid x_int=np.arange(1,res+1,1) y_int=np.arange(1,res+1,1) g = np.meshgrid(x_int, y_int) #Zip them into coordinate tuples coords = list(zip(*(c.flat for c in g))) #Check which point is inside pts = np.vstack([p for p in coords if poly.contains_point(p, radius=0)]) indX,indY= pts[0,:],pts[1,:] return indX,indY
def plot_elements(figname="elements.png",nodesfile="nodes.txt",elementsfile="elements.txt",dlm=","): """ Plot nodes and elements of mesh. Parameters ---------- figname : str Name of output picture nodesfile : str Path of node data file elementsfile : str Path of elements conectivity file dlm : str Delimiter (i.e. ",","\t") """ NC = np.loadtxt(nodesfile, delimiter=dlm) EC = np.loadtxt(elementsfile, delimiter=dlm) f = plt.figure() ax = f.add_subplot(111) plt.hold(True) for element in EC: XX = [] for node in element: if str(node)!="nan": XX.append([NC[node-1,0],NC[node-1,1]]) p = Polygon(XX, True, fc="#00DDDD", ec="#778877") ax.add_patch(p) plt.axis('equal') plt.axis('off') plt.savefig(figname)
def draw_map(): # colour all polygons for which we have data in evaluated.json for shape, info in zip(basemap.berlin, basemap.berlin_info): if info['ORT'] in json_data: c_ort = json_data[info['ORT']] colour = get_colour(c_ort[ARGV]) else: colour = '#dddddd' patches = [Polygon(numpy.array(shape), True)] pc = PatchCollection(patches) pc.set_facecolor(colour) ax.add_collection(pc) # draw map plt.show()
def test_annotation2pltpatch(): assert list(ni.annotation2pltpatch(np.NaN)) == [] assert list(ni.annotation2pltpatch(())) == [] anno = ('point', ((1, 1), (1, 2))) pltpatches = list(ni.annotation2pltpatch(anno)) assert len(pltpatches) == 2 assert isinstance(pltpatches[0], plp.CirclePolygon) assert isinstance(pltpatches[1], plp.CirclePolygon) anno = ('circle', ((2, 2, 2),)) pltpatches = list(ni.annotation2pltpatch(anno)) assert isinstance(pltpatches[0], plp.Circle) anno = ('rect', ((1, 2, 2, 3),)) pltpatches = list(ni.annotation2pltpatch(anno)) assert isinstance(pltpatches[0], plp.Rectangle) anno = ('polyline', (((1, 2), (3, 2), (3, 4), (1, 4), (1, 2)),)) pltpatches = list(ni.annotation2pltpatch(anno)) assert isinstance(pltpatches[0], plp.Polygon) anno = ('polyline', (((0, 0), (2, 2), (2, 4)),)) pltpatches = list(ni.annotation2pltpatch(anno)) assert isinstance(pltpatches[0], plp.Polygon) with pytest.raises(ValueError) as ex: anno = ('invalid', ((1,),)) list(ni.annotation2pltpatch(anno)) assert str(ex.value).startswith('Invalid kind of annotation')
def annotation2pltpatch(annotation, **kwargs): """ Convert geometric annotation to matplotlib geometric objects (=patches) For details regarding matplotlib patches see: http://matplotlib.org/api/patches_api.html For annotation formats see: imageutil.annotation2coords :param annotation annotation: Annotation of an image region such as point, circle, rect or polyline :return: matplotlib.patches :rtype: generator over matplotlib patches """ if not annotation or isnan(annotation): return kind, geometries = annotation for geo in geometries: if kind == 'point': pltpatch = plp.CirclePolygon((geo[0], geo[1]), 1, **kwargs) elif kind == 'circle': pltpatch = plp.Circle((geo[0], geo[1]), geo[2], **kwargs) elif kind == 'rect': x, y, w, h = geo pltpatch = plp.Rectangle((x, y), w, h, **kwargs) elif kind == 'polyline': pltpatch = plp.Polygon(geo, closed=False, **kwargs) else: raise ValueError('Invalid kind of annotation: ' + kind) yield pltpatch
def polygons(latitudes, longitudes, clusters, maptype=MAPTYPE): """Plot clusters of points on map, including them in a polygon defining their convex hull. :param pandas.Series latitudes: series of sample latitudes :param pandas.Series longitudes: series of sample longitudes :param pandas.Series clusters: marker clusters, as integers :param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info :return: None """ width = SCALE * MAX_SIZE img, pixels = background_and_pixels(latitudes, longitudes, MAX_SIZE, maptype) polygons = [] for c in clusters.unique(): in_polygon = clusters == c if in_polygon.sum() < 3: print '[WARN] Cannot draw polygon for cluster {} - only {} samples.'.format(c, in_polygon.sum()) continue cluster_pixels = pixels.loc[clusters == c] polygons.append(Polygon(cluster_pixels.iloc[ConvexHull(cluster_pixels).vertices], closed=True)) plt.figure(figsize=(10, 10)) ax = plt.subplot(111) plt.imshow(np.array(img)) # Background map p = PatchCollection(polygons, cmap='jet', alpha=0.15) # Collection of polygons p.set_array(clusters.unique()) ax.add_collection(p) plt.scatter( # Scatter plot pixels['x_pixel'], pixels['y_pixel'], c=clusters, s=width / 40, linewidth=0, alpha=0.25, ) plt.gca().invert_yaxis() # Origin of map is upper left plt.axis([0, width, width, 0]) # Remove margin plt.axis('off') plt.tight_layout() plt.show()
def to_mpl_patch(self): """ This function ... :return: """ points = [] for point in self.points: points.append([point.x, point.y]) points = np.array(points) return mpl_Polygon(points, edgecolor='green', facecolor='none', lw=3, alpha=0.7) # -----------------------------------------------------------------
def plot_mesh(self): import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection fig = plt.figure() ax = fig.add_subplot(111) _x,_y = [],[] patches = [] for k,elm in enumerate(self.ec): _x,_y,_ux,_uy = [],[],[],[] for nd in elm: _x.append(self.nc[nd,0]) _y.append(self.nc[nd,1]) polygon = Polygon(zip(_x,_y), True) patches.append(polygon) pc = PatchCollection(patches, color="#25CDCD", edgecolor="#435959", alpha=0.8, lw=0.5) ax.add_collection(pc) x0,x1,y0,y1 = self._rect_region() ax.set_xlim(x0,x1) ax.set_ylim(y0,y1) #~ ax.set_title("Model %s"%(self.name)) ax.set_aspect("equal") plt.show()
def plot_model(self): """ Plot the mesh model, including bcs """ import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection fig = plt.figure() ax = fig.add_subplot(111) _x,_y = [],[] patches = [] for k,elm in enumerate(self.get_elements()): _x,_y,_ux,_uy = [],[],[],[] for nd in elm.nodes: if nd.fx != 0: self._draw_xforce(ax,nd.x,nd.y) if nd.fy != 0: self._draw_yforce(ax,nd.x,nd.y) if nd.ux == 0 and nd.uy == 0: self._draw_xyconstraint(ax,nd.x,nd.y) _x.append(nd.x) _y.append(nd.y) polygon = Polygon(zip(_x,_y), True) patches.append(polygon) pc = PatchCollection(patches, color="#7CE7FF", edgecolor="k", alpha=0.4) ax.add_collection(pc) x0,x1,y0,y1 = self.rect_region() ax.set_xlim(x0,x1) ax.set_ylim(y0,y1) ax.set_title("Model %s"%(self.name)) ax.set_aspect("equal")
def plot_esol(self,var="ux"): import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection fig = plt.figure() ax = fig.add_subplot(111) _x,_y = [],[] patches = [] for k,elm in enumerate(self.get_elements()): _x,_y,_ux,_uy = [],[],[],[] for nd in elm.nodes: _x.append(nd.x) _y.append(nd.y) polygon = Polygon(zip(_x,_y), True) patches.append(polygon) pc = PatchCollection(patches, cmap="jet", alpha=1) solutions = { "sxx": [e.sx for e in self.get_elements()], "syy": [e.sy for e in self.get_elements()], "sxy": [e.sxy for e in self.get_elements()], "exx": [e.ex for e in self.get_elements()], "eyy": [e.ey for e in self.get_elements()], "exy": [e.exy for e in self.get_elements()] } fsol = np.array(solutions.get(var.lower())) pc.set_array(fsol) ax.add_collection(pc) plt.colorbar(pc) x0,x1,y0,y1 = self.rect_region() ax.set_xlim(x0,x1) ax.set_ylim(y0,y1) ax.set_aspect("equal") ax_title = "{0} (Max:{1}, Min:{2})".format(var,fsol.max(),fsol.min()) ax.set_title(ax_title)
def __init__(self,xcoord,ycoord,**kwargs): collections.PatchCollection.__init__(self,[],**kwargs) tol = 0.02 _xdata1 = np.array([xcoord-tol,xcoord,xcoord+tol]) _ydata1 = np.array([ycoord-tol,ycoord,ycoord-tol]) _xdata2 = np.array([xcoord-tol,xcoord,xcoord-tol]) _ydata2 = np.array([ycoord-tol,ycoord,ycoord+tol]) # Polygons p1 = patches.Polygon(zip(_xdata1,_ydata1)) p1.set_color("r") p2 = patches.Polygon(zip(_xdata2,_ydata2)) #print p1,p2 #p2.set_color("g") # Set data self.set_paths((p1,p2)) self.set_color("k") #self.set_marker("-") #self.set_mfc('r') #self.set_ms(10)
def _config_axes(self, X, Y): ''' Make an axes patch and outline. ''' ax = self.ax ax.set_frame_on(False) ax.set_navigate(False) xy = self._outline(X, Y) ax.update_datalim(xy) ax.set_xlim(*ax.dataLim.intervalx) ax.set_ylim(*ax.dataLim.intervaly) if self.outline is not None: self.outline.remove() self.outline = lines.Line2D( xy[:, 0], xy[:, 1], color=mpl.rcParams['axes.edgecolor'], linewidth=mpl.rcParams['axes.linewidth']) ax.add_artist(self.outline) self.outline.set_clip_box(None) self.outline.set_clip_path(None) c = mpl.rcParams['axes.facecolor'] if self.patch is not None: self.patch.remove() self.patch = mpatches.Polygon(xy, edgecolor=c, facecolor=c, linewidth=0.01, zorder=-1) ax.add_artist(self.patch) self.update_ticks()
def tissot(self,lon_0,lat_0,radius_deg,npts,ax=None,**kwargs): """ Draw a polygon centered at ``lon_0,lat_0``. The polygon approximates a circle on the surface of the earth with radius ``radius_deg`` degrees latitude along longitude ``lon_0``, made up of ``npts`` vertices. The polygon represents a Tissot's indicatrix (http://en.wikipedia.org/wiki/Tissot's_Indicatrix), which when drawn on a map shows the distortion inherent in the map projection. .. note:: Cannot handle situations in which the polygon intersects the edge of the map projection domain, and then re-enters the domain. Extra keyword ``ax`` can be used to override the default axis instance. Other \**kwargs passed on to matplotlib.patches.Polygon. returns a matplotlib.patches.Polygon object.""" ax = kwargs.pop('ax', None) or self._check_ax() g = pyproj.Geod(a=self.rmajor,b=self.rminor) az12,az21,dist = g.inv(lon_0,lat_0,lon_0,lat_0+radius_deg) seg = [self(lon_0,lat_0+radius_deg)] delaz = 360./npts az = az12 for n in range(npts): az = az+delaz lon, lat, az21 = g.fwd(lon_0, lat_0, az, dist) x,y = self(lon,lat) # add segment if it is in the map projection region. if x < 1.e20 and y < 1.e20: seg.append((x,y)) poly = Polygon(seg,**kwargs) ax.add_patch(poly) # clip polygons for round polar plots. if self.round: poly,c = self._clipcircle(ax,poly) # set axes limits to fit map region. self.set_axes_limits(ax=ax) return poly
def _config_axes(self, X, Y): ''' Make an axes patch and outline. ''' ax = self.ax ax.set_frame_on(False) ax.set_navigate(False) xy = self._outline(X, Y) ax.update_datalim(xy) ax.set_xlim(*ax.dataLim.intervalx) ax.set_ylim(*ax.dataLim.intervaly) if self.outline is not None: self.outline.remove() self.outline = mpatches.Polygon( xy, edgecolor=mpl.rcParams['axes.edgecolor'], facecolor='none', linewidth=mpl.rcParams['axes.linewidth'], closed=True, zorder=2) ax.add_artist(self.outline) self.outline.set_clip_box(None) self.outline.set_clip_path(None) c = mpl.rcParams['axes.facecolor'] if self.patch is not None: self.patch.remove() self.patch = mpatches.Polygon(xy, edgecolor=c, facecolor=c, linewidth=0.01, zorder=-1) ax.add_artist(self.patch) self.update_ticks()
def _post_to_mask(self, rois, id): for r in rois: if 'rec' in r: x1,y1,x2,y2 = r['rec'] for x in range(self.mask.shape[0]): for y in range(self.mask.shape[1]): if (x >= x1 and x < x2) and (y >= y1 and y < y2): self.mask[x,y] = id if 'poly' in r: import matplotlib.patches as patches poly1 = patches.Polygon(r['poly'], closed=True) for i in range(self.mask.shape[0]): for j in range(self.mask.shape[1]): if poly1.get_path().contains_point((i,j)) == True: self.mask[i,j] = id
def draw_triangle(fig, ax, x1, y1, x2, y2, x3, y3, fillcolor, bordercolor): xy = [ (x1, y1), (x2, y2), (x3, y3), ] polygon = patches.Polygon( xy=xy, ls='solid', lw=1.0, ec=bordercolor, closed=True, color=fillcolor) ax.add_patch(polygon)
def _getPatches(self): return [Polygon(self._getPolygonPoints(node.size), True) for node in tree.allNodes]
def look_for_ice(planes, icebergs, k): """Retrieve, for each plane, the visible ice.""" for p in planes: if p.active(k): fov = Polygon(p.fov) p.findings = [i for i in range(icebergs.positions.shape[1]) if fov.contains(Point(icebergs.positions[0, i], icebergs.positions[1, i]))] p.scan = lmb.Scan( lmb.sensors.SquareSensor(p.fov, p.p_detect, p.lambdaB), [lmb.GaussianReport(np.random.multivariate_normal( icebergs.positions[:, i], Pz_true), p.Pz, i) for i in p.findings])
def plot_prediction_overlay(subm_name, image_id, save_file=None): subm = pd.read_csv('subm/%s.csv.gz' % subm_name) img = load_image(image_id) if save_file: fig, ax = plt.subplots(figsize=(30, 30)) else: fig, ax = plt.subplots() xmax = grid_sizes.loc[image_id, 'xmax'] ymin = grid_sizes.loc[image_id, 'ymin'] ax.imshow(np.rollaxis(img, 0, 3)) # plotting, color by class type for cls in xrange(10): multi_poly = shapely.wkt.loads(subm.loc[(subm['ClassType'] == cls + 1) & (subm['ImageId'] == image_id), 'MultipolygonWKT'].values[0]) #if cls == 3: #multi_poly = multi_poly.buffer(2e-5).buffer(-2e-5) for poly in multi_poly: coords = convert_geo_coords_to_raster(np.array(poly.exterior), img.shape[1:], (xmax, ymin)) ax.add_patch(Polygon(coords, color=cls_colors[cls], lw=1.0, alpha=cls_alphas[cls])) plt.title(subm_name) if save_file: plt.savefig(save_file) plt.close() else: plt.show()
def visualize_jackal(figure, pose, img): pyplot.cla() fig = figure ax = fig.add_subplot(111) ax.imshow(img, cmap=cm.Greys_r) ax.axis('image') if pose: meter_to_pixel = 10.6 xl = pose[0]*meter_to_pixel yl = pose[1]*meter_to_pixel dl = pose[2] ax.plot(xl, yl, 'ro', markersize=10) L1 = 0.8*meter_to_pixel L2 = 1.6*meter_to_pixel car=[(xl-L1,yl-L1), (xl-L1,yl+ L1), (xl, yl+L2), (xl+L1, yl+L1), (xl+L1,yl-L1)] polygon2 = Polygon(transform(car, [xl,yl],dl+3.14), fill = True, facecolor='blue', edgecolor='blue', lw=4, zorder=2) ax.add_patch(polygon2) ax.grid() #fig.subplots_adjust(0.003,0.062,0.97,0.94) #pyplot.show() pyplot.pause(0.01) return fig #============================== #==============================
def visualize_jackal(figure, pose): pyplot.cla() fig = figure ax = fig.add_subplot(111) if pose: xl = pose[0] yl = pose[1] dl = pose[2] ax.plot(xl, yl, 'ro', markersize=8) L1 = 0.4 L2 = 0.8 car=[(xl-L1,yl-L1), (xl-L1,yl+ L1), (xl, yl+L2), (xl+L1, yl+L1), (xl+L1,yl-L1)] Ecolor = 'Grey' polygon2 = Polygon(transform(car, [xl,yl], dl), fill = True, facecolor=Ecolor, edgecolor='black', lw=4, zorder=2) ax.add_patch(polygon2) ax.grid() ax.set_xlabel('x(m)') ax.set_ylabel('y(m)') ax.set_aspect('equal') ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) #fig.subplots_adjust(0.003,0.062,0.97,0.94) #pyplot.show() pyplot.pause(0.01) return fig #============================== #==============================
def draw_triangle(fig, ax, x1, y1, x2, y2, x3, y3, fillcolor): xy = [ (x1, y1), (x2, y2), (x3, y3), ] polygon = patches.Polygon( xy=xy, closed=True, color=fillcolor) ax.add_patch(polygon)
def on_pick(self, event): # Filter any non-Polygons (axvspan:s) or non-visible artist = event.artist if not isinstance(artist, Polygon) or not artist.get_visible(): return item = self.span2item.get(artist, None) if not item: logging.error('item for artist unexpectedly not found') return marking = self.span2marking[artist] self.sig_span_picked.emit(item, marking, event)
def map(dataframe, title = "Map", colorbarName = None): fig, ax = plt.subplots(figsize=(80,40)) m = Basemap(resolution='l', # c, l, i, h, f or None projection='robin', lon_0=0) m.drawmapboundary(fill_color='#46bcec') m.fillcontinents(color='#f2f2f2',lake_color='#46bcec') # m.drawcoastlines() plt.title(title, fontsize=50, y=1.08) m.readshapefile('visualization/World/World', 'world',drawbounds=False) df_plot = pd.DataFrame({ 'shapes': [Polygon(np.array(shape), True) for shape in m.world], 'country': [country['ISO3'] for country in m.world_info] }) df_plot = df_plot.merge(dataframe, on='country', how='left') df_plot = df_plot.dropna() cmap = plt.get_cmap('RdYlGn') pc = PatchCollection(df_plot.shapes, zorder=2) norm = Normalize() pc.set_facecolor(cmap(norm(df_plot['value'].values))) ax.add_collection(pc) mapper = matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap) mapper.set_array(df_plot['value']) cbar = plt.colorbar(mapper, shrink=0.7, label = colorbarName) fig = plt.gcf() fig.savefig("Map.jpg") plt.show()
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0]: datasetType = 'instances' elif 'caption' in anns[0]: datasetType = 'captions' if datasetType == 'instances': ax = plt.gca() polygons = [] color = [] for ann in anns: c = np.random.random((1, 3)).tolist()[0] if type(ann['segmentation']) == list: # polygon for seg in ann['segmentation']: poly = np.array(seg).reshape((len(seg)/2, 2)) polygons.append(Polygon(poly, True,alpha=0.4)) color.append(c) else: # mask t = self.imgs[ann['image_id']] if type(ann['segmentation']['counts']) == list: rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width']) else: rle = [ann['segmentation']] m = mask.decode(rle) img = np.ones( (m.shape[0], m.shape[1], 3) ) if ann['iscrowd'] == 1: color_mask = np.array([2.0,166.0,101.0])/255 if ann['iscrowd'] == 0: color_mask = np.random.random((1, 3)).tolist()[0] for i in range(3): img[:,:,i] = color_mask[i] ax.imshow(np.dstack( (img, m*0.5) )) p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4) ax.add_collection(p) elif datasetType == 'captions': for ann in anns: print ann['caption']
def plot_synteny(seq1, ind1, seq2, ind2, y1, y2, featType, matrix, cm, seqname): """This function plots all the lines for each""" myPatches = [] colormap = {"COX1": '#c0d9ef', "L": '#e8f1df', "I": '#f7dedc', "16S": '#ff2e00', "12S": '#ffc239', "cal": '#ffff54', "COX2": "#7fce66", "ND2": "#00ae60", "COX3": "#00aeec", "ND1": "#006fbb", "*": "#ffffff", "(": "#ded9c5", "Q": "#ffc294", "?": "#b5a2c4", "ND4": "#968b5a", "ND3": "#00fc65", "ND4L": "#00dcf0", "ND6": "#ff994e", "ND5": "#dc31e6", "X": "#d8d8d8", "G": "#abdce7", "CYTB": "#ff0059"} for i in range(len(seq1)): feat1 = seq1[i] feat2 = seq2[i] if feat1 != '-' and feat2 != '-': xs = [] ys = [] xs.append(ind1[i]) # top left ys.append(y1) xs.append(ind1[i] + 1) # top right ys.append(y1) xs.append(ind2[i] + 1) # bottom right ys.append(y2) xs.append(ind2[i]) #bottom left ys.append(y2) xs.append(ind1[i]) #top left ys.append(y1) alpha = 0.5 if featType in ['CDS', 'gene']: try: val = matrix[(feat1, feat2)] except: val = matrix[(feat2, feat1)] color = cm[val] alpha = color[-1] elif featType == 'rRNA': if feat1 != feat2: alpha=0 color = colormap[seqname] stack1 = np.column_stack([xs, ys]) myPatches.append(patches.Polygon(stack1, closed=True, color = color, alpha = alpha, lw=0)) return myPatches
def porestreamlines(polygon=None, rx=10., ry=10., Nx=100, Ny=100, maxvalue=None, **fields): "streamlines plot of vector field around nanopore" # interpolate on regular mesh symmetric w.r.t. center axis mesh2D = nanopores.RectangleMesh([-rx-0.1,-ry-0.1], [rx+0.1,ry+0.1], Nx, Ny) fields2 = nanopores.convert2D(mesh2D, *(fields.values())) # prepare polygon and copy to left half settings = dict(closed=True, facecolor="#eeeeee", linewidth=3., edgecolor="black") if polygon is not None: polygon = np.array(polygon) polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]]) # prepare plots Ny += 1 Nx += 1 Y, X = np.mgrid[-ry:ry:Ny*1j, -rx:rx:Nx*1j] U = np.zeros((Ny,Nx)) V = np.zeros((Ny,Nx)) formt = matplotlib.ticker.FuncFormatter(fmt) ticks = [0] + [10**n for n in range(-16, -9)] # determine uniform color range from fields (maybe round to nearest 10-power) if maxvalue is None: maxvalue = max(dolfin.norm(F.vector(), "linf") for F in fields2) #maxvalue = 10**int(np.log10(maxvalue)) for i, F in enumerate(fields2): Fstr = fields.keys()[i] fig, ax = plt.subplots(figsize=(5, 4.5), num=Fstr) # fill array with function values for y in range(Ny): for x in range(Nx): f = F(X[y][x], Y[y][x]) U[y][x] = f[0] V[y][x] = f[1] # streamplot with logarithmic scale strength = np.sqrt(U*U+V*V) norm = matplotlib.colors.SymLogNorm(linthresh=ticks[1], linscale=1.0, vmin=0., vmax=maxvalue) strm = plt.streamplot(X, Y, U, V, arrowsize=1.5, linewidth=1.5, density=1.5, cmap=cm.viridis, color=strength, norm=norm) plt.colorbar(strm.lines, ticks=ticks, format=formt) plt.xlabel('x [nm]') #, fontsize=20) plt.ylabel('z [nm]') #, fontsize=20) # plot pore polygon on top if polygon is not None: patch = patches.Polygon(polygon, **settings) patchm = patches.Polygon(polygon_m, **settings) patch.set_zorder(10) patchm.set_zorder(10) ax.add_patch(patch) ax.add_patch(patchm)
def porestreamlines(polygon=None, rx=10., ry=10., Nx=100, Ny=100, maxvalue=None, **fields): "streamlines plot of vector field around nanopore" # interpolate on regular mesh symmetric w.r.t. center axis #mesh2D = nanopores.RectangleMesh([-rx-0.1,-ry-0.1], [rx+0.1,ry+0.1], Nx, Ny) #fields2 = nanopores.convert2D(mesh2D, *(fields.values())) # prepare polygon and copy to left half settings = dict(closed=True, facecolor="#eeeeee", linewidth=3., edgecolor="black") if polygon is not None: polygon = np.array(polygon) polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]]) # prepare plots Ny += 1 Nx += 1 Y, X = np.mgrid[-ry:ry:Ny*1j, -rx:rx:Nx*1j] U = np.zeros((Ny,Nx)) V = np.zeros((Ny,Nx)) formt = matplotlib.ticker.FuncFormatter(fmt) ticks = [0] + [10**n for n in range(-16, -9)] # determine uniform color range from fields (maybe round to nearest 10-power) if maxvalue is None: maxvalue = max(dolfin.norm(F.vector(), "linf") for F in fields.values()) #maxvalue = 10**int(np.log10(maxvalue)) for i, F in enumerate(fields.values()): Fstr = fields.keys()[i] fig, ax = plt.subplots(figsize=(rx+1., ry), num=Fstr) # fill array with function values for y in range(Ny): for x in range(Nx): f = F(X[y][x], Y[y][x]) U[y][x] = f[0] V[y][x] = f[1] # streamplot with logarithmic scale strength = np.sqrt(U*U+V*V) norm = matplotlib.colors.SymLogNorm(linthresh=ticks[1], linscale=1.0, vmin=0., vmax=maxvalue) strm = plt.streamplot(X, Y, U, V, arrowsize=1., linewidth=1., density=3., cmap=cm.viridis, color=strength, norm=norm) plt.colorbar(strm.lines, ticks=ticks, format=formt) plt.xlabel('x [nm]') #, fontsize=20) plt.ylabel('z [nm]') #, fontsize=20) # plot pore polygon on top if polygon is not None: patch = patches.Polygon(polygon, **settings) patchm = patches.Polygon(polygon_m, **settings) patch.set_zorder(10) patchm.set_zorder(10) ax.add_patch(patch) ax.add_patch(patchm)
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0]: datasetType = 'instances' elif 'caption' in anns[0]: datasetType = 'captions' if datasetType == 'instances': ax = plt.gca() polygons = [] color = [] for ann in anns: c = np.random.random((1, 3)).tolist()[0] if type(ann['segmentation']) == list: # polygon for seg in ann['segmentation']: poly = np.array(seg).reshape((len(seg)/2, 2)) polygons.append(Polygon(poly, True,alpha=0.4)) color.append(c) else: # mask t = self.imgs[ann['image_id']] if type(ann['segmentation']['counts']) == list: rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width']) else: rle = [ann['segmentation']] m = mask.decode(rle) img = np.ones( (m.shape[0], m.shape[1], 3) ) if ann['iscrowd'] == 1: color_mask = np.array([2.0,166.0,101.0])/255 if ann['iscrowd'] == 0: color_mask = np.random.random((1, 3)).tolist()[0] for i in range(3): img[:,:,i] = color_mask[i] ax.imshow(np.dstack( (img, m*0.5) )) p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4) ax.add_collection(p) elif datasetType == 'captions': for ann in anns: print(ann['caption'])
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0]: datasetType = 'instances' elif 'caption' in anns[0]: datasetType = 'captions' if datasetType == 'instances': ax = plt.gca() polygons = [] color = [] for ann in anns: c = np.random.random((1, 3)).tolist()[0] if type(ann['segmentation']) == list: # polygon for seg in ann['segmentation']: poly = np.array(seg).reshape((len(seg)/2, 2)) polygons.append(Polygon(poly, True,alpha=0.4)) color.append(c) else: # mask t = self.imgs[ann['image_id']] if type(ann['segmentation']['counts']) == list: rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width']) else: rle = [ann['segmentation']] m = mask.decode(rle) img = np.ones( (m.shape[0], m.shape[1], 3) ) if ann['iscrowd'] == 1: color_mask = np.array([2.0,166.0,101.0])/255 if ann['iscrowd'] == 0: color_mask = np.random.random((1, 3)).tolist()[0] for i in range(3): img[:,:,i] = color_mask[i] ax.imshow(np.dstack( (img, m*0.5) )) p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4) ax.add_collection(p) elif datasetType == 'captions': n=0 cap= [None] * 5 for ann in anns: #print ann['caption'] if n<5: cap[n]=ann['caption'] #print cap[n] n = n + 1 print n print cap return cap