我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.patches.Circle()。
def redraw_overplot_on_image(self, *args): if self.star_center_patch is not None: self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_center_patch) if self.star_aperture_patch is not None: self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_aperture_patch) if self.sky_aperture_patch is not None: self.ztv_frame.primary_image_panel.axes.patches.remove(self.sky_aperture_patch) self.star_center_patch = Circle([self.xcentroid, self.ycentroid], 0.125, color=self.aprad_color) self.ztv_frame.primary_image_panel.axes.add_patch(self.star_center_patch) self.star_aperture_patch = Circle([self.xcentroid, self.ycentroid], self.aprad, color=self.aprad_color, alpha=self.alpha) self.ztv_frame.primary_image_panel.axes.add_patch(self.star_aperture_patch) self.sky_aperture_patch = Wedge([self.xcentroid, self.ycentroid], self.skyradout, 0., 360., width=self.skyradout - self.skyradin, color=self.skyrad_color, alpha=self.alpha) self.ztv_frame.primary_image_panel.axes.add_patch(self.sky_aperture_patch) self.ztv_frame.primary_image_panel.figure.canvas.draw() self.hideshow_button.SetLabel(u"Hide")
def draw_nodes(self): """ Renders nodes to the figure. """ node_r = self.nodeprops['radius'] lw = self.nodeprops['linewidth'] for i, node in enumerate(self.nodes): x = self.node_coords['x'][i] y = self.node_coords['y'][i] color = self.node_colors[i] node_patch = patches.Circle((x, y), node_r, lw=lw, color=color, zorder=2) self.ax.add_patch(node_patch) if self.node_labels: label_x = self.node_label_coords['x'][i] label_y = self.node_label_coords['y'][i] label_ha = self.node_label_aligns['has'][i] label_va = self.node_label_aligns['vas'][i] self.ax.text(s=node, x=label_x, y=label_y, ha=label_ha, va=label_va)
def drawCenterMarker(self): """Draws a yellow marker in center of the image, making it easier to find image center when selecting center of boundary.""" centerImg=[self.img.shape[0]/2.,self.img.shape[1]/2.] if len(self.centerMarker)>0: self.clearCenterMarker() else: pt=ptc.Circle(centerImg,radius=3,fill=True,color='y') self.centerMarker.append(self.ax.add_patch(pt)) self.fig.canvas.draw() return self.centerMarker
def plot(self, ax): """Plot a two-dimensional environment. Parameters ---------- ax : Axis Matplotlib axis """ if self.n_task_dims != 2: raise ValueError("Can only plot 2 dimensional environments") ax.scatter(self.x0[0], self.x0[1], c="r", s=100) ax.scatter(self.g[0], self.g[1], c="g", s=100) if self.obstacles is not None: from matplotlib.patches import Circle for obstacle in self.obstacles: ax.add_patch(Circle(obstacle, self.obstacle_dist, ec="none", color="r"))
def initialize_ax(self, ax, draw_line, with_ruler): if draw_line: circle = mpatches.Circle( (0, -self.radius), self.radius, facecolor='none', edgecolor='k') ax.add_patch(circle) ax.axis("off") if with_ruler: # only display the xaxis ticks ax.set_frame_on(False) ax.yaxis.set_visible(False) ax.xaxis.tick_bottom() else: # don't display anything ax.axis("off") ax.set_xlim(-self.radius, self.radius) ax.set_aspect("equal")
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 make_handler_map_to_scale_circles_as_in(ax, dont_resize_actively=False): fig = ax.get_figure() def axes2pt(): return np.diff( ax.transData.transform([(0,0), (1,1)]), axis=0)[0] * (72./fig.dpi) ellipses = [] if not dont_resize_actively: def update_width_height(event): dist = axes2pt() for e, radius in ellipses: e.width, e.height = 2. * radius * dist fig.canvas.mpl_connect('resize_event', update_width_height) ax.callbacks.connect('xlim_changed', update_width_height) ax.callbacks.connect('ylim_changed', update_width_height) def legend_circle_handler(legend, orig_handle, xdescent, ydescent, width, height, fontsize): w, h = 2. * orig_handle.get_radius() * axes2pt() e = Ellipse(xy=(0.5*width-0.5*xdescent, 0.5*height-0.5*ydescent), width=w, height=w) ellipses.append((e, orig_handle.get_radius())) return e return {Circle: HandlerPatch(patch_func=legend_circle_handler)}
def legend_artist(self, legend, orig_handle, fontsize, handlebox): c = orig_handle x0, y0 = handlebox.xdescent, handlebox.ydescent x1, y1 = handlebox.width, handlebox.height x = (x0+x1)/2. y = (y0+y1)/2. r = min((x1-x0)/2., (y1-y0)/2.) patch = mpatches.Circle((x, y), 2.*r, facecolor=c, alpha=0.5, lw=0, transform=handlebox.get_transform()) point = mpatches.Circle((x, y), r/2., facecolor=c, alpha=1.0, lw=0, transform=handlebox.get_transform()) handlebox.add_artist(patch) handlebox.add_artist(point) return patch,point # Parse input #Get number of euler rotations
def __init__(self, axes, sim, type_to_radius, type_to_color): assert len(type_to_radius) == len(type_to_color) particle_types_arr = sim.types self._typeToRadius = type_to_radius self._typeToColor = type_to_color self._particleCircles = [] self._sim = sim for particleType in particle_types_arr: c = Circle((0, 0, 0), type_to_radius[particleType], ) c.set_color(self._typeToColor[particleType]) self._particleCircles.append(c) axes.add_patch(c) axes.set_xlim([0, sim.domain_size[0]]) axes.set_ylim([0, sim.domain_size[1]]) axes.set_aspect('equal')
def draw_rolled_sup(ax,node,factor = 1,**kwargs): r = 0.1*factor patch = mpatches.Circle((node.x, node.y),radius = r/2.,**kwargs) ax.add_patch(patch)
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent p = Circle(xy=center, radius=width / 4.0, alpha=0.4) self.update_prop(p, orig_handle, legend) p.set_transform(trans) return [p]
def plot_labelprop_mpl(coords, communities, file_name=None, title=''): u_community = np.unique(communities) cmap = matplotlib.cm.tab20 cmap.set_over('black') ix = np.random.permutation(np.arange(coords.shape[0], dtype=int)) x = coords[ix, 0] y = coords[ix, 1] fig = matplotlib.figure.Figure(figsize=(12, 12)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.scatter(x, y, s=60, alpha=0.8, linewidth=0, color=cmap(communities[ix])) ax.tick_params(left='off', labelleft='off', bottom='off', labelbottom='off') ax.set_title(title) lbl_rects = [(Circle((0, 0), 1, color=cmap(c)), c) for c in u_community] fig.legend(*zip(*lbl_rects), **{'handler_map': {Circle: HandlerCircle()}, 'loc': 7, 'fontsize': 'large'}) if file_name: FigureCanvasAgg(fig).print_figure(file_name)
def plot_labelprop_mpl_tissues(coords, tissue_list, file_name=None, title=''): u_tissue = set(tissue_list) tissue_d = {t:i for i,t in enumerate(u_tissue)} cmap = matplotlib.cm.tab20 cmap.set_over('black') ix = np.random.permutation(np.arange(coords.shape[0], dtype=int)) x = coords[ix, 0] y = coords[ix, 1] fig = matplotlib.figure.Figure(figsize=(12, 12)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.scatter(x, y, s=60, alpha=0.8, linewidth=0, color=[cmap(tissue_d[tissue_list[i]]) for i in ix]) ax.tick_params(left='off', labelleft='off', bottom='off', labelbottom='off') ax.set_title(title) lbl_rects = [(Circle((0, 0), 1, color=cmap(tissue_d[t])), t) for t in u_tissue] fig.legend(*zip(*lbl_rects), **{'handler_map': {Circle: HandlerCircle()}, 'loc': 7, 'fontsize': 'large'}) if file_name: FigureCanvasAgg(fig).print_figure(file_name)
def venn2_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs): ''' Plots only the two circles for the corresponding Venn diagram. Useful for debugging or enhancing the basic venn diagram. parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn2() ``kwargs`` are passed as-is to matplotlib.patches.Circle. returns a list of three Circle patches. >>> c = venn2_circles((1, 2, 3)) >>> c = venn2_circles({'10': 1, '01': 2, '11': 3}) # Same effect >>> c = venn2_circles([set([1,2,3,4]), set([2,3,4,5,6])]) # Also same effect ''' if isinstance(subsets, dict): subsets = [subsets.get(t, 0) for t in ['10', '01', '11']] elif len(subsets) == 2: subsets = compute_venn2_subsets(*subsets) areas = compute_venn2_areas(subsets, normalize_to) centers, radii = solve_venn2_circles(areas) if ax is None: ax = gca() prepare_venn_axes(ax, centers, radii) result = [] for (c, r) in zip(centers, radii): circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs) ax.add_patch(circle) result.append(circle) return result
def venn3_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs): ''' Plots only the three circles for the corresponding Venn diagram. Useful for debugging or enhancing the basic venn diagram. parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn3() kwargs are passed as-is to matplotlib.patches.Circle. returns a list of three Circle patches. >>> plot = venn3_circles({'001': 10, '100': 20, '010': 21, '110': 13, '011': 14}) >>> plot = venn3_circles([set(['A','B','C']), set(['A','D','E','F']), set(['D','G','H'])]) ''' # Prepare parameters if isinstance(subsets, dict): subsets = [subsets.get(t, 0) for t in ['100', '010', '110', '001', '101', '011', '111']] elif len(subsets) == 3: subsets = compute_venn3_subsets(*subsets) areas = compute_venn3_areas(subsets, normalize_to) centers, radii = solve_venn3_circles(areas) if ax is None: ax = gca() prepare_venn_axes(ax, centers, radii) result = [] for (c, r) in zip(centers, radii): circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs) ax.add_patch(circle) result.append(circle) return result
def __init__(self, center, radius): self.center = np.asarray(center, float) self.radius = abs(radius) if (radius < -tol): raise VennRegionException("Circle with a negative radius is invalid")
def make_patch(self): ''' Returns the corresponding circular patch. >>> patch = VennCircleRegion((1, 2), 3).make_patch() >>> patch <matplotlib.patches.Circle object at ...> >>> patch.center, patch.radius (array([ 1., 2.]), 3.0) ''' return Circle(self.center, self.radius)
def plot_circle(ax, x, y, color): area = 380 circle = ax.scatter(x, y, s=area, c=color) #edgewidth = 0 #edgecolor = "k" # black #circle = ax.plot(x, y, "o", c=color, markersize=10) #circle= mpatches.Circle((x, y), radius, fc=color, ec=edgecolor, lw=edgewidth) #ax.add_patch(circle) return circle
def plot_robustness(ax, fpdata, fplabels, fpcolors): handles = OrderedDict() # for legend for data, label, color in zip(fpdata, fplabels, fpcolors): handle = [] # nice painless way to iterate array: array = np.nditer(data, flags=['multi_index']) for boolean in array: if boolean: i, j = array.multi_index x, y = X[i], Y[j] circle = plot_circle(ax, x, y, color) handle.append(circle) handles[label] = tuple(handle) # TODO: axis limits #ax.set_aspect('equal', 'datalim') #ax.autoscale_view(True,True,True) ax.set_xscale("log")#, subsx=[2,5]) ax.set_yscale("log")#, subsy=[2,5]) myhandles = [plt.Rectangle((0, 0), 1, 1, fc=col) for col in fpcolors] #ax.legend([h[0] for h in handles.values()], handles.keys(), ax.legend(myhandles, handles.keys(), #bbox_to_anchor=(0.5, 1.05), loc="lower center", borderaxespad=0.,) bbox_to_anchor=(0., 1.5), loc="upper left", borderaxespad=0.,) #handler_map={mpatches.Circle:HandlerPatch(patch_func=make_legend_ellipse)}) ax.set_xlabel("voltage bias [V]") ax.set_ylabel(r"surface charge density [q/nm$^2$]") ax.set_xlim(xlim) ax.set_ylim(ylim) # --- fixed point ---
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 drawCenter(self): """Draws a red marker at selected center on canvas.""" if len(self.centerPt)>0: self.clearCenter() pt=ptc.Circle(self.center,radius=3,fill=True,color='r') self.centerPt.append(self.ax.add_patch(pt)) self.fig.canvas.draw() return self.centerPt
def drawRadius(self): """Draws a red circle around selected center with selected radius on canvas.""" if len(self.radiusPt)>0: self.clearRadius() pt=ptc.Circle(self.center,radius=self.radius,fill=False,color='r') self.radiusPt.append(self.ax.add_patch(pt)) self.fig.canvas.draw() return self.radiusPt
def showBoundary(self,color=None,linewidth=3,ax=None): """Shows ROI in a 2D plot. If no color is specified, will use color specified in ``ROI.color``. Keyword Args: ax (matplotlib.axes): Matplotlib axes used for plotting. If not specified, will generate new one. color (str): Color of plot. linewidth (float): Linewidth of plot. Returns: matplotlib.axes: Axes used for plotting. """ if color==None: color=self.color if ax==None: fig,axes = pyfrp_plot_module.makeSubplot([1,1],titles=["boundary"],sup=self.name+" boundary") ax = axes[0] img=np.nan*np.ones((self.embryo.dataResPx,self.embryo.dataResPx)) ax.imshow(img) patch = ptc.Circle(self.center,self.radius,fill=False,linewidth=linewidth,color=color) ax.add_patch(patch) return ax
def drawPoint(self,x,y,color='r',idx=0): pt=ptc.Circle([x,y],radius=3,fill=True,color=color) self.replaceArtist(idx,self.ax.add_patch(pt)) self.canvas.draw() return pt
def drawCorner(self,corner): pt=ptc.Circle([corner[0],corner[1]],radius=3,fill=True,color=self.ROI.color) self.artists.append(self.ax.add_patch(pt)) return pt
def highlightCorner(self,corner): c=ptc.Circle([corner[0],corner[1]],radius=6,fill=False,color=self.ROI.color) self.highlighted=self.ax.add_patch(c) self.canvas.draw() return c
def drawCircle(self,center,radius,color='r',idx=1): c=ptc.Circle(center,radius=radius,fill=False,color=color) self.replaceArtist(idx,self.ax.add_patch(c)) self.canvas.draw() return c
def __call__(self, plot): from matplotlib.patches import Circle if iterable(self.radius): self.radius = plot.data.ds.quan(self.radius[0], self.radius[1]) self.radius = np.float64(self.radius.in_units(plot.xlim[0].units)) # This assures the radius has the appropriate size in # the different coordinate systems, since one cannot simply # apply a different transform for a length in the same way # you can for a coordinate. if self.coord_system == 'data' or self.coord_system == 'plot': self.radius = self.radius * self.pixel_scale(plot)[0] else: self.radius /= (plot.xlim[1]-plot.xlim[0]).v x,y = self.sanitize_coord_system(plot, self.center, coord_system=self.coord_system) cir = Circle((x, y), self.radius, transform=self.transform, **self.circle_args) xx0, xx1 = plot._axes.get_xlim() yy0, yy1 = plot._axes.get_ylim() plot._axes.add_patch(cir) if self.text is not None: label = plot._axes.text(x, y, self.text, transform=self.transform, **self.text_args) self._set_font_properties(plot, [label], **self.text_args) plot._axes.set_xlim(xx0,xx1) plot._axes.set_ylim(yy0,yy1)
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 to_mpl_patch(self): """ This function ... :return: """ return mpl_Circle((self.center.x, self.center.y), self.radius, edgecolor='green', facecolor='none', lw=3, alpha=0.7) # -----------------------------------------------------------------
def _clipcircle(self,ax,coll): c = Circle((0.5*(self.xmax+self.xmin),0.5*(self.ymax+self.ymin)), radius=0.5*(self.xmax-self.xmin),fc='none') if c not in ax.patches: p = ax.add_patch(c) p.set_clip_on(False) try: coll.set_clip_path(c) except: for item in coll: item.set_clip_path(c) return coll,c
def make_legend_circles_for(sizes, scale=1.0, **kw): return [Circle((0,0), radius=(s/scale)**0.5, **kw) for s in sizes]
def plot_circle_in_micrograph(micrograph_2d, coordinate, particle_size, filename, color = 'white'): """plot the particle circle in micrograph image Based on the coordinate of particle, plot circles of the particles in the micrograph. And save the ploted image in filename. Args: micrograph_2d: numpy.array,it is a 2D numpy array. coordinate: list, it is a 2D list, the shape is (num_particle, 2). particle_size: int, the value of the particle size filename: the filename of the image to be save. color: define the color of the circle Raises: pass """ micrograph_2d = micrograph_2d.reshape(micrograph_2d.shape[0], micrograph_2d.shape[1]) fig = plt.figure() ax = fig.add_subplot(111) plt.axis('off') plt.gray() plt.imshow(micrograph_2d) radius = particle_size/2 i = 0 while True: if i >= len(coordinate): break coordinate_x = coordinate[i][0] coordinate_y = coordinate[i][1] cir1 = Circle(xy = (coordinate_x, coordinate_y), radius = radius, alpha = 0.5, color = color, fill = False) ax.add_patch(cir1) # extract the particles i = i + 1 plt.savefig(filename)
def plotDetector(self): """ plot a detector (circle) to plt figure """ ax = plt.gca() ax.add_patch(patches.Circle((self.center[0], self.center[1]), self.radius, fill = False))
def _plot_sensors(pos_x, pos_y, sensors, ax): """Aux function""" from matplotlib.patches import Circle if sensors is True: for x, y in zip(pos_x, pos_y): ax.add_artist(Circle(xy=(x, y), radius=0.003, color='k')) else: ax.plot(pos_x, pos_y, sensors)
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'): # https://matplotlib.org/examples/color/colormaps_reference.html patches = [] for pos in var: if shape == 'c': patches.append(mpatches.Circle(pos, r)) elif shape == 'r': patches.append(mpatches.RegularPolygon(pos, 4, r)) elif shape == 's': patches.append(mpatches.RegularPolygon(pos, 6, r)) colors = np.linspace(start_color, .9, len(patches)) collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.) collection.set_array(np.array(colors)) collection.set_clim(0, 1) return collection
def plot_3d_ball_trajectory(var, filename, r=0.05): var = np.asarray(var) # Normalize directions var -= var.min(axis=0) var /= var.max(axis=0) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for x, y, z in var: p = mpatches.Circle((x, y), r, ec="none") ax.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=0, zdir="z") p = mpatches.Circle((x, z), r, ec="none") ax.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=0, zdir="y") p = mpatches.Circle((y, z), r, ec="none") ax.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=0, zdir="x") # ax.scatter(x, y, z, s=100) # ax.plot(var[:, 0], var[:, 1], zs=var[:, 2]) ax.view_init(azim=45, elev=30) ax.set_xlim3d(-0.1, 1.1) ax.set_ylim3d(-0.1, 1.1) ax.set_zlim3d(-0.1, 1.1) plt.savefig(filename, format='png', bbox_inches='tight', dpi=80) plt.close(fig) # plt.show()
def _print_junction(self): bw = self.game_params['board_width'] lw = self.game_params['lane_width'] # road marks plt.vlines(lw, -bw, -lw) plt.vlines(-lw, -bw, -lw) plt.vlines(-lw, lw, bw) plt.vlines(lw, lw, bw) plt.hlines(-lw, -bw, -lw) plt.hlines(-lw, lw, bw) plt.hlines(lw, -bw, -lw) plt.hlines(lw, lw, bw) # lane marks plt.vlines(0, -bw, -lw, linestyles='dashed') plt.vlines(0, lw, bw, linestyles='dashed') plt.hlines(0, -bw, -lw, linestyles='dashed') plt.hlines(0, lw, bw, linestyles='dashed') # stopping lines plt.hlines(-lw, 0, lw, linestyles='solid') plt.hlines(-lw-0.01, 0, lw, linestyles='solid') plt.hlines(lw, -lw, 0, linestyles='solid') plt.hlines(lw+0.01, -lw, 0, linestyles='solid') plt.vlines(-lw, -lw, 0, linestyles='solid') plt.vlines(-lw-0.01, -lw, 0, linestyles='solid') plt.vlines(lw, 0, lw, linestyles='solid') plt.vlines(lw+0.01, 0, lw, linestyles='solid') # print rails # self.ax.add_patch(Circle(xy=(lw,-lw), radius=lw/2, edgecolor='k', facecolor='none')) # self.ax.add_patch(Circle(xy=(-lw,-lw), radius=3*lw/2, edgecolor='k', facecolor='none'))
def plot_encoding(model, sess, title=None, name="encoding", datasets=("test","validation"), range_=(-4.,4.), save=True, outdir="./plots", **kwargs): """ Plotting utility to encode dataset images in (low dimensional!) latent space """ # TODO: check for 2d title = (title if title else name) for dataset_name in datasets: dataset = getattr(model.dataset, dataset_name) feed_dict = {model.x_in_test: dataset.images} encoding = sess.run(model.z_dist_info_, feed_dict=feed_dict) centers = encoding[model.latent_dist.dist_info_keys[0]] ys, xs = centers.T plt.figure() plt.title("round {}: {} in latent space".format(model.counter, dataset_name)) kwargs = {'alpha': 0.8} classes = set(dataset.labels) if classes: colormap = plt.cm.rainbow(np.linspace(0, 1, len(classes))) kwargs['c'] = [colormap[i] for i in dataset.labels] # make room for legend ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) handles = [mpatches.Circle((0,0), label=class_, color=colormap[i]) for i, class_ in enumerate(classes)] ax.legend(handles=handles, shadow=True, bbox_to_anchor=(1.05, 0.45), fancybox=True, loc='center left') plt.scatter(xs, ys, **kwargs) # map range_ to standard deviations of the target distribution stddev = model.target_dist.stddev adjusted_range = (stddev*range_[0], stddev*range_[1]) if range_: plt.xlim(adjusted_range) plt.ylim(adjusted_range) if save: title = "{}_encoding_{}_round_{}.png".format( model.datetime, dataset_name, model.counter) plt.savefig(os.path.join(outdir, title), bbox_inches="tight") plt.close()
def compute_venn3_areas(diagram_areas, normalize_to=1.0, _minimal_area=1e-6): ''' The list of venn areas is given as 7 values, corresponding to venn diagram areas in the following order: (Abc, aBc, ABc, abC, AbC, aBC, ABC) (i.e. last element corresponds to the size of intersection A&B&C). The return value is a list of areas (A_a, A_b, A_c, A_ab, A_bc, A_ac, A_abc), such that the total area of all circles is normalized to normalize_to. If the area of any circle is smaller than _minimal_area, makes it equal to _minimal_area. Assumes all input values are nonnegative (to be more precise, all areas are passed through and abs() function) >>> compute_venn3_areas((1, 1, 0, 1, 0, 0, 0)) (0.33..., 0.33..., 0.33..., 0.0, 0.0, 0.0, 0.0) >>> compute_venn3_areas((0, 0, 0, 0, 0, 0, 0)) (1e-06, 1e-06, 1e-06, 0.0, 0.0, 0.0, 0.0) >>> compute_venn3_areas((1, 1, 1, 1, 1, 1, 1), normalize_to=7) (4.0, 4.0, 4.0, 2.0, 2.0, 2.0, 1.0) >>> compute_venn3_areas((1, 2, 3, 4, 5, 6, 7), normalize_to=56/2) (16.0, 18.0, 22.0, 10.0, 13.0, 12.0, 7.0) ''' # Normalize input values to sum to 1 areas = np.array(np.abs(diagram_areas), float) total_area = np.sum(areas) if np.abs(total_area) < _minimal_area: warnings.warn("All circles have zero area") return (1e-06, 1e-06, 1e-06, 0.0, 0.0, 0.0, 0.0) else: areas = areas / total_area * normalize_to A_a = areas[0] + areas[2] + areas[4] + areas[6] if A_a < _minimal_area: warnings.warn("Circle A has zero area") A_a = _minimal_area A_b = areas[1] + areas[2] + areas[5] + areas[6] if A_b < _minimal_area: warnings.warn("Circle B has zero area") A_b = _minimal_area A_c = areas[3] + areas[4] + areas[5] + areas[6] if A_c < _minimal_area: warnings.warn("Circle C has zero area") A_c = _minimal_area # Areas of the three intersections (ab, ac, bc) A_ab, A_ac, A_bc = areas[2] + areas[6], areas[4] + areas[6], areas[5] + areas[6] return (A_a, A_b, A_c, A_ab, A_bc, A_ac, areas[6])
def plotHeadOutline(ax=None, radius=1.2): result = {} # if new axis not given, create one if ax is None: fig = plt.figure(figsize=(11,8)) result['fig'] = fig ax = fig.add_subplot(1,1,1, aspect='equal') result['ax'] = ax extent = (-0.16-radius,0.16+radius,-0.01-radius,0.20+radius) result['extent'] = extent ax.set_aspect('equal') ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) leftEar = pltPatches.Ellipse((-0.075-radius,0.0), width=0.15, height=0.4, angle=0.0, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False) ax.add_patch(leftEar) rightEar = pltPatches.Ellipse((0.075+radius,0.0), width=0.15, height=0.4, angle=0.0, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False) ax.add_patch(rightEar) result['leftEar'] = leftEar result['rightEar'] = rightEar noseLength = 0.18 noseWidth = 0.12 noseIntersect = 2.0*radius-np.sqrt(noseWidth**2+radius**2) leftNose, = ax.plot((0.0,-noseWidth), (radius+noseLength,noseIntersect), color='dimgrey', linewidth=3, zorder=10) rightNose, = ax.plot((0.0,noseWidth), (radius+noseLength,noseIntersect), color='dimgrey', linewidth=3, zorder=10) leftNose.set_solid_capstyle('round') rightNose.set_solid_capstyle('round') result['leftNose'] = leftNose result['rightNose'] = rightNose head = pltPatches.Circle((0.0,0.0), radius, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False) result['head'] = head ax.add_patch(head) ax.set_xticks([]) ax.set_yticks([]) return result
def plotHead(chanNames=('F3','F4','C3','C4','P3','P4','O1','O2'), radius=0.01, fillColor='black', lineColor='black', drawLabels=True, clip=True, fontSize=12, ax=None, **kwargs): # plot head outline and save result dict result = plotHeadOutline(ax) ax = result['ax'] # get chanNames that we have a location for chanNames = [chanName for chanName in chanNames if chanName.lower() in chanLocs3d.keys()] chanNamesLower = [chanName.lower() for chanName in chanNames] # lower case # if no valid chanNames then just draw the outline if len(chanNames) == 0: return result # get 3d cartesian coordinates for each channel xyz = np.asarray([chanLocs3d[chanName] for chanName in chanNamesLower]) # make sure coordinates have unit magnitude xyz = xyz / np.sqrt(np.sum(xyz**2, axis=1))[:,None] # rotate by pi/2 around z axis cos90 = np.cos(np.pi/2.0) rot = np.asarray(((cos90,-1.0,0.0),(1.0,cos90,0.0),(0.0,0.0,1.0))).T xyz = xyz.dot(rot) # stereographic projection x = xyz[:,0] y = xyz[:,1] z = xyz[:,2] xy = np.vstack((x/(1.0+z), y/(1.0+z))).T # list of circles and chan labels to store in result circles = [] chanLabels = [] # for each channel for chanName, coord in zip(chanNames, xy): x, y = coord c = pltPatches.Circle((x,y), radius, edgecolor=lineColor, facecolor=fillColor, linewidth=1, fill=True, zorder=100) ax.add_patch(c) circles.append(c) # draw channel labels if drawLabels: if fontSize is not None: txt = ax.text(x,y+0.081, chanName, size=fontSize, horizontalalignment='center', verticalalignment='center', zorder=100) chanLabels.append(txt) # save labels and circles in result result['chanLabels'] = chanLabels result['circles'] = circles return result