def plot_node_layout(tspnodes): ''' fig1 = plt.figure() ax1 = fig1.add_subplot(111, aspect='equal') for node in tspnodes: ax1 = plt.scatter(node.locx, node.locy, edgecolors='r', s=1600, facecolors='none') plt.show() ''' axes = pylab.axes() for node in tspnodes: if node.type == 2: circle = pylab.Circle((node.location[0], node.location[1]), radius=c.RADIUS / 2, edgecolor='cyan', facecolor='none') axes.add_patch(circle) else: circle = pylab.Circle((node.location[0], node.location[1]), radius=c.RADIUS / 2, edgecolor='r', facecolor='none') axes.add_patch(circle) pylab.axis('scaled') pylab.show() return
def draw_geo(tm, ax_xy, ax_yz, ax_xz): # March 7, 2021 # The flag_source_state variable is used to draw/erase the source geometry only once # This is necessary to speed up the animation. global flag_source_state_1 # Make this variable global so that the assigned value remains saved globally as t changes global flag_source_state_2 if 'flag_source_state_1' not in globals(): global flag_source_state # Make this variable global so that the assigned value remains saved globally as t changes flag_source_state_1 = 0 # initialize with OFF state print('Defining global flag for source geometry \n') if 'flag_source_state_2' not in globals(): global flag_source_state # Make this variable global so that the assigned value remains saved globally as t changes flag_source_state_2 = 0 # initialize with OFF state print('Defining global flag for source geometry \n') # Draw static geometry (only once) if flag_source_state_2 < 1: py.gcf().sca(ax_yz) substrate_yz = py.Rectangle((-xrange_limit*1e6, zlow_limit*1e6),2*xrange_limit*1e6, abs(zlow_limit)*1e6,fc='#d4d4d4', ec='k') py.gca().add_patch(substrate_yz) py.gcf().sca(ax_xz) substrate_xz = py.Rectangle((-xrange_limit*1e6, zlow_limit*1e6),2*xrange_limit*1e6, abs(zlow_limit)*1e6,fc='#d4d4d4', ec='k') py.gca().add_patch(substrate_xz) py.gcf().sca(ax_xy) substrate_xy = py.Rectangle((-xrange_limit*1e6, -xrange_limit*1e6),2*xrange_limit*1e6,2*xrange_limit*1e6,fc='#f9f9f9') py.gca().add_patch(substrate_xy) flag_source_state_2 = 1 # Draw source if (tm > 1) & (tm < 8) & (flag_source_state_1 < 1): patch_spot_xy = py.Circle((0, 0), 0.5*w_well*1e6, fc='#ff8c00',alpha = 0.8) # patch_spot_yz = plt.patches.Arc((0, 0), 0.5*w_well*1e6, 0.5*w_well*1e6,0, 0, 180, fc='#ff8c00',alpha = 0.8) py.gcf().sca(ax_xy) py.gca().add_patch(patch_spot_xy) # py.sca(ax_yz) # py.gca().add_patch(patch_spot_yz) flag_source_state_1 = 1 print('Drawing source\n') # Erase source (draw a white circle) if (tm > 8) & (flag_source_state_1 == 1): patch_spot = py.Circle((0, 0), 0.51*w_well*1e6, fc='#f9f9f9',alpha = 1) py.gca().add_patch(patch_spot) print('Erasing source\n') flag_source_state_1 = 0 return 0
def add_ranges(ax, chromosome, sensor=True): for i, xy in enumerate(coords): if sensor: if chromosome[i] == 0: ax.add_patch( pylab.Circle(xy, radius=3.0, alpha=0.15, fc='g', ec='none')) else: if chromosome[i] == 1: ax.add_patch(pylab.Circle(xy, radius=8.0, alpha=0.1, fc='b'))
def plotPupilOverlap(self): if self.resultPlot: self.resultPlot.setParent(None) scrnNo = self.sim.config.atmos.scrnNo self.resultPlot = OverlapWidget(scrnNo) self.ui.plotLayout.addWidget(self.resultPlot) for i in range(scrnNo): self.resultPlot.canvas.axes[i].imshow(numpy.zeros( (self.config.sim.pupilSize * 2, self.config.sim.pupilSize * 2)), origin="lower") for wfs in range(self.config.sim.nGS): if self.sim.config.wfss[ wfs].GSHeight > self.sim.config.atmos.scrnHeights[ i] or self.sim.config.wfss[wfs].GSHeight == 0: cent = (self.sim.wfss[wfs].los.getMetaPupilPos( self.sim.config.atmos.scrnHeights[i]) * self.sim.config.sim.pxlScale + self.config.sim.pupilSize) if self.sim.wfss[wfs].radii != None: radius = self.sim.wfss[wfs].radii[i] else: radius = self.config.sim.pupilSize / 2. if self.sim.config.wfss[wfs].GSHeight != 0: colour = "r" else: colour = "g" circ = pylab.Circle(cent, radius=radius, alpha=0.2, fc=colour) self.resultPlot.canvas.axes[i].add_patch(circ) self.resultPlot.canvas.axes[i].set_yticks([]) self.resultPlot.canvas.axes[i].set_xticks([]) for sci in range(self.config.sim.nSci): cent = self.sim.sciCams[sci].los.getMetaPupilPos( self.sim.config.atmos.scrnHeights[i]) cent *= self.sim.config.sim.pxlScale cent += self.config.sim.pupilSize radius = self.config.sim.pupilSize / 2. circ = pylab.Circle(cent, radius=radius, alpha=0.2, fc="y") self.resultPlot.canvas.axes[i].add_patch(circ) self.resultPlot.canvas.axes[i].set_yticks([]) self.resultPlot.canvas.axes[i].set_xticks([])
def __init__(self, size=None, position=None, lambda_=None, theta=None, sigma=None, phase=None, trim=None, contrast=0.5, width=1, hide_dot=False): if not isinstance(np, ModuleType): message = """GaborPatch can not be initialized. The Python package 'Numpy' is not installed.""" raise ImportError(message) if not isinstance(pyplot, ModuleType): message = """GaborPatch can not be initialized. The Python package 'Matplotlib' is not installed.""" raise ImportError(message) fid, filename = tempfile.mkstemp( dir=stimuli.defaults.tempdir, suffix=".png") os.close(fid) Picture.__init__(self, filename, position) size = 200 diameter = 50 line_width = 20 * width inner_diameter = 5 * (int(hide_dot)-1) fig = plt.figure(frameon=False, figsize=(1, 1)) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) pixel_map = np.zeros((size, size)) ax.imshow(pixel_map, cmap=plt.get_cmap('gray')) ax.add_patch(plt.Circle((size / 2, size / 2), diameter, color='w')) ax.add_patch(plt.Rectangle((size / 2 - line_width / 2, 0), line_width, size, color='k')) ax.add_patch(plt.Rectangle((0, size / 2 - line_width / 2), size, line_width, color='k')) ax.add_patch(plt.Circle((size / 2, size / 2), inner_diameter, color='w')) fig.canvas.draw() # Now we can save it to a numpy array. data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) #plt.show() self._pixel_array = data #save stimulus color_map = pyplot.get_cmap('gray') color_map.set_over(color="y") pyplot.imsave(fname = filename, arr = self._pixel_array, cmap = color_map, format="png", vmin=0, vmax=1) #plt.savefig(filename = filename, cmap = color_map, format="png") self._background_colour = [0, 0, 0]
def plotFieldOfView(self,quantity,AX): slicehalfwidth = self.rmax / 6.0 if quantity == 'mass': self.writeColumn('rtrunc_arcmin',(self.galaxies.r200/ self.galaxies.Da_p) * pangloss.rad2arcmin) self.writeColumn('rscale_arcmin',(self.galaxies.rs/ self.galaxies.Da_p) * pangloss.rad2arcmin) for i in range(len(self.galaxies.x)): trunc = plt.Circle([self.galaxies.x[i], self.galaxies.y[i]],radius=self.galaxies.rtrunc_arcmin[i],fill=True,fc="b",alpha=0.05) AX.add_patch(trunc) for i in range(len(self.galaxies.x)): core = plt.Circle([self.galaxies.x[i], self.galaxies.y[i]],radius=self.galaxies.rscale_arcmin[i],fill=True,fc="r",alpha=0.5) AX.add_patch(core) plt.title('Halo Mass') elif quantity == 'kappa': plt.scatter(self.galaxies.x, self.galaxies.y, c='r', marker='o', s=(self.galaxies.kappa)*30000) plt.title('Convergence') elif quantity == 'mu': plt.scatter(self.galaxies.x, self.galaxies.y, c='g', marker='o', s=((self.galaxies.mu-1.0)*3E4)) plt.title('Magnification') elif quantity == 'stellarmass': plt.scatter(self.galaxies.x, self.galaxies.y, c='y', marker='o', s=(numpy.log(self.galaxies.Mstar)/2),edgecolor = 'none' ) plt.title('Stellar Mass') elif quantity == 'light': plt.scatter(self.galaxies.x, self.galaxies.y, c='y', marker='o', s=(2**(25-self.galaxies.mag)),edgecolor = 'none' ) plt.title('Galaxy Light') else: raise "Lightcone plotting error: unknown quantity "+quantity # Lightcone boundary and centroid: circ = plt.Circle(self.xc,radius=self.rmax,fill=False,linestyle='dotted') AX.add_patch(circ) AX.plot([self.xc[0]],[self.xc[1]], c='k', marker='+',markersize=20,markeredgewidth=1) axlimits = [self.xc[0]-self.rmax-0.1,self.xc[0]+self.rmax+0.1,self.xc[1]-self.rmax-0.1,self.xc[1]+self.rmax+0.1] AX.axis(axlimits) # Show slice: plt.axvline(x=slicehalfwidth, ymin=axlimits[2], ymax=axlimits[3],color='black', ls='dotted') plt.axvline(x=-slicehalfwidth, ymin=axlimits[2], ymax=axlimits[3],color='black', ls='dotted') # Labels: plt.xlabel('x / arcmin') # plt.ylabel('y / arcmin') return
def drawCircles (axes): """ Рисование окружностей """ circle1 = pylab.Circle((0, 0), radius=0.1, fill=True) axes.add_patch (circle1) pylab.text (0, 0.2, "Circle", horizontalalignment="center") circle2 = pylab.Circle((0, 0), radius=1.5, fill=False, color="r") axes.add_patch (circle2) pylab.text (0, 1.55, "Circle", horizontalalignment="center")
def __init__(self, m, R, r=[0.0, 0.0, 0.0], v=[0.0, 0.0, 0.0]): self.m = m self.R = R self.r = np.array(r) self.v = np.array(v) self.patch = pl.Circle(self.r, self.R, fc='r') self.container = False
def button_press_callback(self, event): """Left button: add point; middle button: delete point; right button: fill polygon and stop interaction. """ if event.inaxes: x, y = event.xdata, event.ydata ax = event.inaxes if event.button == 1: # If you press the left button if self.circ == None: # if there is no line, create a line self.center = x, y self.circ = plt.Circle( (x, y), 0.5, facecolor='none', edgecolor=self.color) ax.add_artist(self.circ) # add a segment else: # if there is a line, create a segment self.circ.set_color(self.color) self.circ.set_edgecolor(self.color) self.circ.set_facecolor('none') self.circ.set_hatch('//') self.circ.set_linewidth(1) self.circ.set_alpha(1) self.disconnect() if self.completion_callback is not None: self.completion_callback() elif event.button == 3 and self.circ != None: # middle button: remove last segment self.circ.remove() self.circ = None self.fig.canvas.draw()
def __setstate__(self, d): self.im = d['im'] self.center, self.radius = d['circle'] self.color = d['color'] self.circ = plt.Circle( *d['circle'], facecolor='none', edgecolor=self.color) self.patch = None
def plot_pks(self, ax, pk_par=None, show=True, pause=None): """ ax, matplotlib axis pk_par, peakaboo peak parameter dictionary show, boolean, if not working in pylab interactive mode, set True to display image pause, if working in pylab .draw() (e.g. psuedo interactive) then set to some float value (seconds) the plot will pause for this long after drawing... """ if pk_par is not None: self.set_pk_par(pk_par) m = img[img > 0].mean() s = img[img > 0].std() ax.imshow(img, vmax=m + 5 * s, vmin=m - s, **kwargs) pos, intens = self.pk_pos() for cent in pos: circ = plt.Circle(xy=(cent[1], cent[0]), radius=3, ec='r', fc='none', lw=1) ax.add_patch(circ) if show: plt.show() elif pause is not None: plt.draw() plt.pause(pause)
def button_press_callback(self, event): """Left button: add point; middle button: delete point; right button: fill polygon and stop interaction. """ from IPython.core.debugger import Tracer Tracer()() if event.inaxes: x, y = event.xdata, event.ydata ax = event.inaxes if event.button == 1: # If you press the left button if self.circ == None: # if there is no line, create a line self.circ = plt.Circle((x, y), 0.5, facecolor='none', edgecolor='r') ax.add_artist(self.circ) # add a segment else: # if there is a line, create a segment self.circ.set_color('b') self.circ.set_alpha(0.3) self.disconnect() elif event.button == 3 and self.circ != None: # middle button: remove last segment # ax.artists.remove(self.circ) self.circ.remove() self.circ = None self.fig.canvas.draw()
def plot_part_save_inc(particles, figname, increment, xmin, xmax, ymin, ymax): #plot particles x_parts = [] y_parts = [] rad_parts = [] cir_parts = [] import pylab for i in range(len(particles)): ThisParticle = particles[i] x_parts.append(ThisParticle.xp) y_parts.append(ThisParticle.yp) rad_parts.append(ThisParticle.rad) cir_parts.append((np.pi * ThisParticle.rad**2)) circles = [] ax = pylab.axes( aspect=1 ) #Creates empty axes (aspect=1 means scale things so that circles look like circles) for i in range(len(particles)): ax.add_patch( pylab.Circle((x_parts[i], y_parts[i]), radius=rad_parts[i])) pylab.xlim(xmin - 1, xmax + 1) pylab.ylim(ymin - 1, ymax + 1) #pylab.show() plt.savefig(figname + "_" + str(increment) + '.png')
def plot(points): axes = pylab.axes() for i in points: circle = pylab.Circle(i, distance[0], alpha=.4) axes.add_patch(circle) pylab.axis('scaled')
def draw_canvas(): """ Draw an empty GFP canvas Args: Returns: ax,fig of the created canvas Note: """ #clear plot plt.clf() fig = plt.gcf().gca() ax = plt.subplot() #GFP circle1 = plt.Circle((0, 0), const.GFP_RADIUS, color='k', alpha=0.3) ax.add_artist(circle1) #patrol radius # circle1 = plt.Circle((0, 0), const.PATROL_RADIUS, color='k', alpha = 0.3) # ax.add_artist(circle1) plt.ylim((-180000, 180000)) plt.xlim((-180000, 180000)) plt.xlabel('X position (microns)') plt.ylabel('Y position (microns)') plt.legend(loc=0) ax.set_aspect('equal') return ax, fig
def plot_targets(bugsTargetXY, bugTargetTypes, booLegend=False, booShowBugs=True, booAnnotate=False, booThickPath=True): plt.clf() ax, fig = draw_canvas() for i in range(bugsTargetXY.shape[0]): thisTargetType = bugTargetTypes[i] thisTargetX = bugsTargetXY[i, 0] thisTargetY = bugsTargetXY[i, 1] #Green for guide, blue for the rest if thisTargetType == 0: c = 'g' else: c = 'b' bugShape = plt.Circle( (thisTargetX, thisTargetY), const.BUG_RADIUS, color=c, alpha=0.5, ) ax.add_artist(bugShape) plt.title('Target Positions') return ax
def generate_plot(output_file, experiments): """ Plot the experiment results on a the 2 by 2 square containing the unit circle. Show how many points fell inside v.s. outside of the circle. """ # Split the results into inside v.s. outside within = [e for e in experiments if e['x']**2 + e['y']**2 <= 1] outside = [e for e in experiments if e['x']**2 + e['y']**2 > 1] # clear things for fresh plot ax = plt.gca() ax.cla() # Set plot bounds ax.set_xlim((-1, 1)) ax.set_ylim((-1, 1)) # plots: inside and outside the circle plt.scatter([e['x'] for e in within], [e['y'] for e in within], c="red") plt.scatter([e['x'] for e in outside], [e['y'] for e in outside], c="blue") # bounding circle c = plt.Circle((0, 0), 1, color='black', fill=False) ax.add_artist(c) # write to disk plt.savefig(output_file)
def draw_circles(points, ax, radii=3, col='r', lw=2, to_fill=False): """ Given (y,x) centroid coordinates, draws on a given Matplotlib ax, circles of a defined radius and colour. Parameters ---------- points : numpy array or list an array of (y,x) coordinates for plotting ax : Matplotlib figure axes instance e.g. from fig, ax = plt.subplots() radii : int the radius of the circle col : string a valid Matplotlib colour string or valid RGBA float values lw : int linewidth of circle to_fill : bool if True, fills the circle with same colour as given by `col`. Returns ------- Nothing """ for p in points: y, x = p c = plt.Circle((x, y), radii, color=col, linewidth=lw, fill=to_fill) ax.add_patch(c) return []
def multiple_animate_image(fig, axes, data, *args, **kwargs): # First set up the figure, the axis, and the plot element we want to animate im = [] for ii in range(len(axes)): im.append(axes[ii].imshow(data[ii][0], *args, **kwargs)) patch = axes[1].add_patch(pl.Circle((60, 60), 8, color='r', alpha=0)) def animate(jj): for ii in range(len(im)): im[ii].set_array(data[ii][jj]) fig.suptitle('%s ms' % (jj * 10)) patch.set_alpha([0, .3][(jj % 50) < 5]) pl.draw() return im # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(axes[0].get_figure(), animate, frames=len(data[0]), interval=50, blit=True) return anim
def my_circle_scatter_radii(axes, x_array, y_array, r, **kwargs): # drar neighborhood circles for (x, y) in zip(x_array, y_array): circle = pylab.Circle((x, y), radius=r, **kwargs) axes.add_patch(circle) return axes
def show(self, roi_radius=None,roi_dir=None, **kwargs): """Three subplots: PSF, raw, convolved""" import pylab as plt from matplotlib.colors import LogNorm title = kwargs.pop('title', None) if hasattr(self, 'band'): roi_radius = self.band.radius roi_dir = self.band.sd fig, axx = plt.subplots(1,3, figsize=(10,3), sharex=True, sharey=True) plt.subplots_adjust(wspace=0.05) if hasattr(self, 'psf_vals'): axx[0].imshow(self.psf_vals,interpolation='nearest') vmax = self.bg_vals.max() norm = LogNorm(vmax=vmax, vmin=vmax/1e3) marker = float(self.npix)/2 for ax,what in zip(axx[1:], (self.bg_vals, self.cvals) ): what[what==0]=vmax/1e6 ax.imshow(what.transpose()[::-1], norm=norm, interpolation='nearest') ax.axvline(marker,color='grey') ax.axhline(marker,color='grey') if roi_radius is not None: if roi_dir is None: roi_dir = self.center circle = plt.Circle(self.pix(roi_dir),roi_radius/self.pixelsize, color='grey', lw=2,fill=False) ax.add_artist(circle) axx[0].set_aspect(1.0) if title is not None: plt.suptitle(title,fontsize='small') return fig
def plot(self, ax, threed=False): rad = 0.0 if self.radius == None: if self.mass == 0: rad = 1.0 else: rad = 1.0668117883456128e-18 * self.mass else: rad = self.radius if self.radius > 0: circle = pylab.Circle((self.pos.x, self.pos.y), color=self.color, radius=rad, clip_on=False) ax.add_patch(circle) #draw object crosshairs circle_vec_left = Vector3(-1.0, 0.0, 0.0).fmul(rad).add(self.pos) circle_vec_right = Vector3(1.0, 0.0, 0.0).fmul(rad).add(self.pos) circle_vec_up = Vector3(0.0, 1.0, 0.0).fmul(rad).add(self.pos) circle_vec_down = Vector3(0.0, -1.0, 0.0).fmul(rad).add(self.pos) plot_vector_list2d([circle_vec_left, circle_vec_right], color="red") plot_vector_list2d([circle_vec_down, circle_vec_up], color=self.color) plot_vector_list2d([self.pos], marker='o', color=self.color) #draw object velocity if (self.vel.mag() > 0.0 and self.show_vel): plot_vector_arrow2d(self.pos, self.vel.fmul(400), color="blue") """
def plot_file_color(base, thin=True, start=0, size=14, save=False): conf, track, pegs = load(base) fig = pl.figure(figsize=(size, size * conf['top'] / conf['wall'])) track = track[start:] x = track[:, 0] y = track[:, 1] t = np.linspace(0, 1, x.shape[0]) points = np.array([x, y]).transpose().reshape(-1, 1, 2) segs = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segs, linewidths=0.25, cmap=pl.cm.coolwarm) lc.set_array(t) pl.gca().add_collection(lc) #pl.scatter(x, y, c=np.arange(len(x)),linestyle='-',cmap=pl.cm.coolwarm) #pl.plot(track[-1000000:,0], track[-1000000:,1], '-', linewidth=0.0125, alpha=0.8) for peg in pegs: pl.gca().add_artist( pl.Circle(peg, conf['radius'], color='k', alpha=0.3)) pl.xlim(0, conf['wall']) pl.ylim(0, conf['top']) pl.xticks([]) pl.yticks([]) pl.tight_layout() pl.show() if save: pl.savefig(base + ".png", dpi=200)
def plot_pks( img, pk=None, **kwargs): """ Plot an image with detected peaks pk, list of peak positions, [ (y0,x0), (y1,x1) ... ] where y,x is slow,fast scan coordinates if pk is None, then peaks will be detected using pk_pos script below **kwargs are the arguments passed to pk_pos, e.g. thresh, nsigs, make_sparse, sig_G """ if pk is None: pk,_ = pk_pos( img, **kwargs) assert( len(pk[0]) == 2) m = img[ img > 0].mean() s = img[img > 0].std() plt.figure(1) plt.imshow( img, vmax=m+5*s, vmin=m-s, cmap='hot', aspect='equal', interpolation='nearest') ax = plt.gca() for cent in pk: circ = plt.Circle(xy=(cent[1], cent[0]), radius=3, ec='Deeppink', fc='none', lw=1) ax.add_patch(circ) plt.show()
def show_barlines(page): import pylab for i, barlines in enumerate(page.barlines): sd = page.staves.staff_dist[i] for j, barline_range in enumerate(barlines): barline_x = int(barline_range.mean()) staff_y = page.staves.staff_y(i, barline_x) repeats = page.repeats[i][j] if repeats: # Draw thick bar pylab.fill_between([barline_x - sd / 4, barline_x + sd / 4], staff_y - sd * 2, staff_y + sd * 2, color='g') for letter, sign in (('L', -1), ('R', +1)): if letter in repeats: # Draw thin bar bar_x = barline_x + sign * sd / 2 pylab.plot([bar_x, bar_x], [staff_y - sd * 2, staff_y + sd * 2], color='g') for y in (-1, +1): circ = pylab.Circle( (bar_x + sign * sd / 2, staff_y + y * sd / 2), sd / 4, color='g') pylab.gcf().gca().add_artist(circ) else: pylab.plot([barline_x, barline_x], [staff_y - sd * 2, staff_y + sd * 2], color='g')
def showMap(center, radius, CEP, DRMS): pl.figure('Global Map') pl.plot(center[0], center[1], 'ro') cir1 = pl.Circle(center, radius, alpha=.2, fc='r') #cir2 = pl.Circle(center,CEP,alpha =.4,ec="r", fc='r') cir3 = pl.Circle(center, DRMS, ec="r", color='w') pl.gca().add_patch(cir3) pl.gca().add_patch(cir1) #pl.gca().add_patch(cir2) for i in range(len(lat_data)): pl.plot(lat_data[i], lng_data[i], 'bo') pl.grid() # pl.xlim(30.0611,30.062) pl.xlabel('Latitude') # pl.ylim(31.497,31.5) pl.ylabel('Longitude ')
def plot_part_save(particles, figname): #plot particles x_parts = [] y_parts = [] rad_parts = [] cir_parts = [] for i in range(len(particles)): ThisParticle = particles[i] x_parts.append(ThisParticle.xp) y_parts.append(ThisParticle.yp) rad_parts.append(ThisParticle.rad) cir_parts.append((np.pi * ThisParticle.rad**2)) fig, ax = plt.subplots(1, 1) #ax = subplot(aspect='equal') #circles(x_parts,y_parts,rad_parts) import pylab circles = [] ax = pylab.axes( aspect=1 ) #Creates empty axes (aspect=1 means scale things so that circles look like circles) for i in range(len(particles)): ax.add_patch( pylab.Circle((x_parts[i], y_parts[i]), radius=rad_parts[i])) pylab.xlim(-0.5, 0.5) pylab.ylim(-0.5, 0.5) #pylab.show() plt.savefig(figname + '.png')
def draw_grid(self, colors: Dict[Point, str] = None): if colors is None: colors = {} fig, ax = plt.subplots() circles = [] plt.grid() lines = [] for connection in self.connections: lines.append([connection[0].coords(), connection[1].coords()]) lc = mc.LineCollection(lines, colors=["grey"], linewidths=1) for point, color in colors.items(): circles.append(plt.Circle(point.coords(), 0.3, color=color, fill=True)) ax.add_collection(lc) for circle in circles: ax.add_patch(circle) ax.invert_yaxis() c = np.array(["black"]) ax.margins(0.1) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.ylim([-1, self.y + 1]) plt.xlim([-1, self.x + 1]) plt.draw() plt.waitforbuttonpress(0)
def draw_sphere(sphere: Sphere, color='b', alpha=0.5): sphere = pylab.Circle(sphere.center, sphere.r, fill=False, color=color, alpha=alpha) pylab.gca().add_patch(sphere)
def show_vals(self, vals=None, ax=None, roi_radius=5, roi_dir=None, colorbar=True, npix=None, **kw): """Make a display. vals : 2-d array of float generated by the fill method; expect to be npix x npix npix : [int | None] if int, override self.npix to for central npix x npix """ import pylab as plt if ax is None: fig,ax=plt.subplots() if vals is None: vals = self.cvals if npix is not None and npix!=self.npix: delta = (self.npix-npix)/2 assert delta>0, 'npix not >= self.npix' tvals = vals[delta:delta+npix, delta:delta+npix] else: npix=self.npix; tvals = vals if roi_radius is not None: if roi_dir is None: roi_dir = self.center circle = plt.Circle(self.pix(roi_dir),roi_radius/self.pixelsize, color='grey', lw=2,fill=False) ax.add_artist(circle) v = ax.imshow( tvals.transpose()[::-1], interpolation='nearest', **kw) marker = float(npix)/2 ax.axvline(marker,color='k') ax.axhline(marker,color='k') if colorbar: cb = plt.colorbar(v, shrink=0.8) def scale(x, factor=1.0): return x*factor/self.pixelsize+self.npix/2. r = np.arange(-8,9,4) ax.set_xticks(scale(r)) ax.set_xticklabels(map(lambda x:'%.0f'%x ,r)) ax.set_yticks(scale(r, -1)) ax.set_yticklabels(map(lambda x:'%.0f'%x ,r)) return ax.figure