def On_button_Directory_Clicked( self, event ): """ Event Handler. """ dlg = wx.DirDialog(self, "To enable plotting, select directory where WinSpec is saving the SPE files:", style=wx.DD_DEFAULT_STYLE, defaultPath=self.DataPath ) # If the user selects OK, then we process the dialog's data. # This is done by getting the path data from the dialog - BEFORE # we destroy it. if dlg.ShowModal() == wx.ID_OK: self.DataPath = dlg.GetPath() self.SPEFiles = [] # a list of SPE files to plot self.spectra = [] self.time = [] #print 'You selected: %s\n' % self.DataPath if len( pylab.get_fignums() ) == 0 or pylab.get_fignums()[-1] != self.current_fignum: self.fig = pylab.figure() self.current_fignum = pylab.get_fignums()[-1] self.axes = self.fig.add_subplot(111) self.fig.show() if self.plotcolormap(): self.fig.canvas.draw() # Only destroy a dialog after you're done with it. dlg.Destroy()
def OnThreadUpdate(self, event): """ Event Handler. """ self.status.SetLabel('Done with acquisition #%s' % (event.data)) if len(pylab.get_fignums()) > 0 and pylab.get_fignums( )[-1] == self.current_fignum: if self.plotcolormap(): self.fig.canvas.draw()
def On_button_Directory_Clicked(self, event): dlg = wx.DirDialog( self, "To enable plotting, select directory where WinSpec is saving the SPE files:", style=wx.DD_DEFAULT_STYLE, defaultPath=self.DataPath) # If the user selects OK, then we process the dialog's data. # This is done by getting the path data from the dialog - BEFORE # we destroy it. if dlg.ShowModal() == wx.ID_OK: self.DataPath = dlg.GetPath() #print 'You selected: %s\n' % self.DataPath if len(pylab.get_fignums() ) == 0 or pylab.get_fignums()[-1] != self.current_fignum: self.fig = pylab.figure() self.current_fignum = pylab.get_fignums()[-1] self.axes = self.fig.add_subplot(111) self.fig.show() if self.plotcolormap(): self.fig.canvas.draw() # Only destroy a dialog after you're done with it. dlg.Destroy()
def multipage(filename, figs=None, dpi=200): pp = PdfPages(filename) if figs is None: figs = [plt.figure(n) for n in plt.get_fignums()] for fig in figs: fig.savefig(pp, format='pdf') pp.close()
def save_all_figs(dir = './', format=None, replace_spaces = True, echo = True): ''' Save all open Figures to disk. Parameters ------------ dir : string path to save figures into format : None, or list of strings the types of formats to save figures as. The elements of this list are passed to :matplotlib:`savefig`. This is a list so that you can save each figure in multiple formats. echo : bool True prints filenames as they are saved ''' if dir[-1] != '/': dir = dir + '/' for fignum in plb.get_fignums(): fileName = plb.figure(fignum).get_axes()[0].get_title() if replace_spaces: fileName = fileName.replace(' ','_') if fileName == '': fileName = 'unnamedPlot' if format is None: plb.savefig(dir+fileName) if echo: print((dir+fileName)) else: for fmt in format: plb.savefig(dir+fileName+'.'+fmt, format=fmt) if echo: print((dir+fileName+'.'+fmt))
def init_figure(self,openfig=True): self.handles={} for k in ['mappable','quiver','quiver_key','1d']: self.handles[k]=[] if not openfig: # check if figure exist: try: exists=self.fig.number in pl.get_fignums() except: exists=False openfig=not exists # figure: if openfig: self.fig=pl.figure(figsize=self.config['figure.figsize'], facecolor=self.config['figure.facecolor'], edgecolor=self.config['figure.edgecolor']) # main ax: self.ax=self.fig.add_axes(self.config['axes.position']) # colorbar: if self.config['colorbar.bg_position']: self.cbbg=self.fig.add_axes(self.config['colorbar.bg_position']) self.cbbg_rec=matplotlib.patches.Rectangle((0,0),1,1,**self.config['colorbar.bg']) self.cbbg.add_artist(self.cbbg_rec) self.cbbg.set(frame_on=0,xticks=[],yticks=[],visible=False) else: self.cbbg=False if self.config['colorbar.ax_position']: self.cbax=self.fig.add_axes(self.config['colorbar.ax_position']) self.cbax.set(visible=False) else: self.cbax=False
def save_all_figs(dir='./', format=None, replace_spaces=True, echo=True): ''' Save all open Figures to disk. Parameters ------------ dir : string path to save figures into format : None, or list of strings the types of formats to save figures as. The elements of this list are passed to :matplotlib:`savefig`. This is a list so that you can save each figure in multiple formats. echo : bool True prints filenames as they are saved ''' if dir[-1] != '/': dir = dir + '/' for fignum in plb.get_fignums(): fileName = plb.figure(fignum).get_axes()[0].get_title() if replace_spaces: fileName = fileName.replace(' ', '_') if fileName == '': fileName = 'unnamedPlot' if format is None: plb.savefig(dir + fileName) if echo: print((dir + fileName)) else: for fmt in format: plb.savefig(dir + fileName + '.' + fmt, format=fmt) if echo: print((dir + fileName + '.' + fmt))
def AnimatePath(self, path): """Same thing as VisualizePath, except animated from start to goal. Should help for noticing collisions between robots mid-path. """ colors = ['r-', 'g-', 'b-', 'm-', 'y-'] if not pl.get_fignums(): self.env.InitializePlot() self.prm.PlotRoadmap() print('Path length is %d', len(path)) for i in range(len(path) - 1): pl.close() self.env.InitializePlot() self.prm.PlotRoadmap() for robot in range(len(path[0])): robot_path = [] robot_path.append(path[i][robot, :]) robot_path.append(path[i + 1][robot, :]) self.prm.VisualizePath(robot_path, colors[robot]) fname = 'MRdRRT_path_' + str(i) print 'Path step #', i pl.savefig(fname) raw_input(".") # raw_input("Check paths") with open('most_recent_path.p', "wb") as f: pickle.dump(path, f) print "saved path!"
def init_figure(self, **kargs): fig = kargs.get('fig', None) # use existing fig; create a new one if True ax = kargs.get('ax', None) # use existing axes cbax = kargs.get('cbax', None) # use existing axes for colorbar if ax: fig = ax.figure self.init_handles() prev = kargs.get('prev', None) if prev: print('using prev !!') for i in ['fig', 'ax', 'cbax', 'cbbg']: setattr(self, i, getattr(prev, i)) return if isinstance(fig, pl.Figure): self.fig = fig else: openfig = fig is True if not openfig: # check if figure exist: try: exists = self.fig.number in pl.get_fignums() except: exists = False openfig = not exists # figure: if openfig: self.fig = pl.figure(figsize=self.config['figure.figsize'], facecolor=self.config['figure.facecolor'], edgecolor=self.config['figure.edgecolor']) # main ax: if ax: self.ax = ax else: self.ax = self.fig.add_axes(self.config['axes.position']) # colorbar bg: if self.config['colorbar.bg_position']: self.cbbg = self.fig.add_axes(self.config['colorbar.bg_position']) self.cbbg_rec = pl.matplotlib.patches.Rectangle( (0, 0), 1, 1, **self.config['colorbar.bg']) self.cbbg.add_artist(self.cbbg_rec) self.cbbg.set(frame_on=0, xticks=[], yticks=[], visible=False) else: self.cbbg = False # colorbar ax: if cbax: self.cbax = cbax else: if self.config['colorbar.ax_position']: self.cbax = self.fig.add_axes( self.config['colorbar.ax_position']) self.cbax.set(visible=False) else: self.cbax = False
def save_plots(pdf): "save all plots to pdf" pp = PdfPages(pdf) for i in pl.get_fignums(): pl.figure(i) pl.savefig(pp, format='pdf') pp.close() print(colors.yellow % 'saved plots to "%s"' % pdf)
def look( fig=None ): import pylab if fig is None and len( pylab.get_fignums() ): fig = pylab.gcf() if isinstance( fig, int ): fig = pylab.figure( fig ) try: fig.canvas._tkcanvas.focus_force() except: try: fig.canvas.manager.window.focus_force() # works but then removes focus from whichever part of the figure is listening to keystrokes :-( except: pass
def save_plots(pdf): "save all plots to pdf" pp = PdfPages(pdf) for i in pl.get_fignums(): pl.figure(i) pl.savefig(pp, format='pdf') pp.close() print yellow % 'saved plots to "%s"' % pdf
def multipage(filename, figs=None): pp = PdfPages(filename) if figs is None: figs = [lab.figure(n) for n in lab.get_fignums()] for fig in figs: fig.savefig(pp, format='pdf') pp.close() return
def save_plots(data, filename, noisename): basename = mass.output_basename_from_ljh_fname(data.first_good_dataset.filename) dir, fname = path.split(basename) # print("writing %d plots as png to %s"%(len(plt.get_fignums()), dir)) print("writing %d plots as pdf to %s"%(len(plt.get_fignums()), dir)) with PdfPages(path.join(dir, fname+"_all_figures.pdf")) as pdf: for i in plt.get_fignums(): print("writing plot %d of %d to pdf"%(i, len(plt.get_fignums()))) pdf.savefig(i) # print("writing plot %d of %d as png"%(i, len(plt.get_fignums()))) # plt.figure(i) # plt.savefig(path.join(dir,fname+'figure%d.png') % i, dpi=600) d = pdf.infodict() d['Title'] = filename d['Author'] = noisename d['CreationDate'] = datetime.datetime(2009, 11, 13) d['ModDate'] = datetime.datetime.today()
def superimpose( figs='all' ): import pylab if figs == 'all': figs = pylab.get_fignums() if not isinstance( figs, ( tuple, list ) ): figs = [ figs ] figs = list( figs ) for i, f in enumerate( figs ): if isinstance( f, int ): figs[ i ] = pylab.figure( f ) geom = figs[ 0 ].canvas.manager.window.geometry() for fig in figs[ 1: ]: fig.canvas.manager.window.geometry( geom )
def root_locus(Num, Den, Plot=True): plotstr = 'b' if int(matplotlib.__version__[0]) == 1 else 'C0' grid = True kvect = None xlim = None ylim = None # Convert numerator and denominator to polynomials if they aren't (nump, denp) = _TransferFunction(Num, Den) start_mat = _FindRoots(nump, denp, [1]) kvect, mymat, xlim, ylim = _gains(nump, denp, xlim, ylim) Kbreak, rBreak = _break_points(nump, denp) # Show the Plot if Plot: figure_number = pylab.get_fignums() figure_title = [ pylab.figure(numb).canvas.get_window_title() for numb in figure_number ] new_figure_name = "Root Locus" rloc_num = 1 while new_figure_name in figure_title: new_figure_name = "Root Locus " + str(rloc_num) rloc_num += 1 f = pylab.figure(new_figure_name) ax = pylab.axes() ax.plot(rBreak, np.zeros(len(rBreak)), 'x', color='red') # plot open loop poles appears in X in red poles = array(denp.r) #Making the pole point with random colors to be diffrent for x, y in zip(real(poles), imag(poles)): rgb = (np.random.rand(), np.random.rand(), np.random.rand()) ax.scatter(x, y, c=[rgb]) _DepratureAngels(f, poles) # plot open loop zeros if existed appears in O in black #just for trial reasons zeros = array(nump.r) if zeros.size > 0: ax.plot(real(zeros), imag(zeros), 'x', color='black') # Now plot the loci for index, col in enumerate(mymat.T): ax.plot(real(col), imag(col), plotstr, label='root locus') # Set up plot axes and labels if xlim: ax.set_xlim(xlim) if ylim: ax.set_ylim(ylim) ax.set_xlabel('Re') ax.set_ylabel('Im') if grid: _grid_func(f, num=nump, den=denp) elif grid: _grid_func(num=nump, den=denp) ax.axhline(0., linestyle=':', color='gray') ax.axvline(0., linestyle=':', color='gray')
def superimpose(figs='all'): import pylab if figs == 'all': figs = pylab.get_fignums() if not isinstance(figs, (tuple, list)): figs = [figs] figs = list(figs) for i, f in enumerate(figs): if isinstance(f, int): figs[i] = pylab.figure(f) geom = figs[0].canvas.manager.window.geometry() for fig in figs[1:]: fig.canvas.manager.window.geometry(geom)
def close_matching(str): """ close all pylab windows with str in the title, see also raise _matching""" (labs_nums) = zip(pl.get_figlabels(), pl.get_fignums()) closed = 0 for (lab, num) in labs_nums: if str in lab: pl.close(num) closed += 1 if closed == 0: print('No figures matching {s} found'.format(s=str))
def printer(figure='gcf', arguments='', threaded=False, file_format='pdf'): """ Quick function that saves the specified figure as a postscript and then calls the command defined by spinmob.prefs['print_command'] with this postscript file as the argument. figure='gcf' can be 'all', a number, or a list of numbers """ global _prefs if not _prefs.has_key('print_command'): print "No print command setup. Set the user variable prefs['print_command']." return if figure == 'gcf': figure = [_pylab.gcf().number] elif figure == 'all': figure = _pylab.get_fignums() if not getattr(figure, '__iter__', False): figure = [figure] print "figure numbers in queue:", figure figures = [] for n in figure: figures.append(_pylab.figure(n)) # now run the ps printing command if threaded: # store the canvas type of the last figure canvas_type = type(figures[-1].canvas) # launch the aforementioned function as a separate thread _thread.start_new_thread(_print_figures, ( figures, arguments, file_format, )) # wait until the thread is running _time.sleep(0.25) # wait until the canvas type has returned to normal t0 = _time.time() while not canvas_type == type( figures[-1].canvas) and _time.time() - t0 < 5.0: _time.sleep(0.1) if _time.time() - t0 >= 5.0: print "WARNING: Timed out waiting for canvas to return to original state!" # bring back the figure and command line _pylab.draw() _pylab_tweaks.get_pyshell() else: _print_figures(figures, arguments, file_format) _pylab.draw()
def close_matching(str): """ close all pylab windows with str in the title, see also raise _matching""" (labs_nums) = zip(pl.get_figlabels(),pl.get_fignums()) closed = 0 for (lab,num) in labs_nums: if str in lab: pl.close(num) closed += 1 if closed == 0: print('No figures matching {s} found' .format(s=str))
def close_matching(str): """ close all pylab windows with str in the title, see also raise _matching""" # coded differently as the number must be given to close. (labs_nums) = zip(pl.get_figlabels(), pl.get_fignums()) closed = 0 for (lab, num) in labs_nums: if (str == '' and str == lab) or (str != '' and str in lab): # x=input('pause') pl.close(num) closed += 1 if closed == 0: print('No figures matching "{s}" found'.format(s=str))
def init_figure(self,**kargs): fig=kargs.get('fig',None) # use existing fig; create a new one if True ax=kargs.get('ax',None) # use existing axes cbax=kargs.get('cbax',None) # use existing axes for colorbar if ax: fig=ax.figure self.init_handles() prev=kargs.get('prev',None) if prev: print('using prev !!') for i in ['fig','ax','cbax','cbbg']: setattr(self,i,getattr(prev,i)) return if isinstance(fig,pl.Figure): self.fig=fig else: openfig=fig is True if not openfig: # check if figure exist: try: exists=self.fig.number in pl.get_fignums() except: exists=False openfig=not exists # figure: if openfig: self.fig=pl.figure(figsize=self.config['figure.figsize'], facecolor=self.config['figure.facecolor'], edgecolor=self.config['figure.edgecolor']) # main ax: if ax: self.ax=ax else: self.ax=self.fig.add_axes(self.config['axes.position']) # colorbar bg: if self.config['colorbar.bg_position']: self.cbbg=self.fig.add_axes(self.config['colorbar.bg_position']) self.cbbg_rec=pl.matplotlib.patches.Rectangle((0,0),1,1,**self.config['colorbar.bg']) self.cbbg.add_artist(self.cbbg_rec) self.cbbg.set(frame_on=0,xticks=[],yticks=[],visible=False) else: self.cbbg=False # colorbar ax: if cbax: self.cbax=cbax else: if self.config['colorbar.ax_position']: self.cbax=self.fig.add_axes(self.config['colorbar.ax_position']) self.cbax.set(visible=False) else: self.cbax=False
def On_button_Start_Clicked( self, event ): """Start Computation.""" # Trigger the worker thread unless it's already busy if not self.worker: self.status.SetLabel('Starting scan.') self.worker = WorkerThread(self) self.worker.setDaemon( True ) # kill this thread if we close the main app self.worker.start() self.fig = pylab.figure() self.current_fignum = pylab.get_fignums()[-1] self.axes = self.fig.add_subplot(111) self.fig.show()
def search_handles( handles, reclevel=0 ): out = [] if reclevel >= 10: zark # allows `debug` of apparent indefinite recursion try: handles = list( handles ) except: handles = [ handles ] for h in handles: if isinstance( h, ( int, float ) ): if h == 0: h = pylab.get_fignums() elif pylab.fignum_exists( h ): h = pylab.figure( h ) while hasattr( h, 'axes' ) and h.axes is not h: h = h.axes # this was intended to grab the children of a figure, but it can also grab the parent of an AxesImage.... try: h = list( h ) except: out.append( h ) else: out.extend( search_handles( h, reclevel=reclevel+1 ) ) return out
def printer(figure='gcf', arguments='', threaded=False, file_format='pdf'): """ Quick function that saves the specified figure as a postscript and then calls the command defined by spinmob.prefs['print_command'] with this postscript file as the argument. figure='gcf' can be 'all', a number, or a list of numbers """ global _prefs if not _prefs.has_key('print_command'): print "No print command setup. Set the user variable prefs['print_command']." return if figure=='gcf': figure=[_pylab.gcf().number] elif figure=='all': figure=_pylab.get_fignums() if not getattr(figure,'__iter__',False): figure = [figure] print "figure numbers in queue:", figure figures=[] for n in figure: figures.append(_pylab.figure(n)) # now run the ps printing command if threaded: # store the canvas type of the last figure canvas_type = type(figures[-1].canvas) # launch the aforementioned function as a separate thread _thread.start_new_thread(_print_figures, (figures,arguments,file_format,)) # wait until the thread is running _time.sleep(0.25) # wait until the canvas type has returned to normal t0 = _time.time() while not canvas_type == type(figures[-1].canvas) and _time.time()-t0 < 5.0: _time.sleep(0.1) if _time.time()-t0 >= 5.0: print "WARNING: Timed out waiting for canvas to return to original state!" # bring back the figure and command line _pylab.draw() _pylab_tweaks.get_pyshell() else: _print_figures(figures, arguments, file_format) _pylab.draw()
def VisualizePath(self, path): """Plot paths of robots through environment, defined in path. """ colors = ['r-', 'g-', 'b-', 'm-', 'y-'] if not pl.get_fignums(): self.env.InitializePlot() self.prm.PlotRoadmap() for robot in range(len(path[0])): robot_path = [] for i in range(len(path)): robot_path.append(path[i][robot, :]) self.prm.VisualizePath(robot_path, colors[robot]) raw_input("Check paths")
def get_fig_nums_labs(match_str=''): """ get all figure labels if they exist, or str of the fig num if note The match_str is compared with lab just to detect no matches - all labs are returned """ fig_nums = pl.get_fignums() fig_labs = pl.get_figlabels() nums_labs = [] for num, lab in zip(fig_nums, fig_labs): if lab == '': lab = str(num) nums_labs.append(lab) # check for matches here, save duplicating code. matches = [nl for nl in nums_labs if match_str in nl] if len(matches) == 0: print('No matches to ' + match_str) return (nums_labs)
def plotWeight(field, target_fields, weight, **kwargs): if isinstance(field, FieldArray): field = field[-1] date = ephem.Date(field['DATE']) if plt.get_fignums(): plt.cla() fig, basemap = obztak.utils.ortho.makePlot(date, name='weight') index_sort = np.argsort(weight)[::-1] proj = basemap.proj(target_fields['RA'][index_sort], target_fields['DEC'][index_sort]) weight_min = np.min(weight) basemap.scatter(*proj, c=weight[index_sort], edgecolor='none', s=50, vmin=weight_min, vmax=weight_min + 300., cmap='Spectral') #cut_accomplished = np.in1d(self.target_fields['ID'], self.accomplished_field_ids) #proj = obztak.utils.ortho.safeProj(basemap, self.target_fields['RA'][cut_accomplished], self.target_fields['DEC'][cut_accomplished]) #basemap.scatter(*proj, c='0.75', edgecolor='none', s=50) """ cut_accomplished = np.in1d(self.target_fields['ID'],self.accomplished_fields['ID']) proj = obztak.utils.ortho.safeProj(basemap, self.target_fields['RA'][~cut_accomplished], self.target_fields['DEC'][~cut_accomplished]) basemap.scatter(*proj, c=np.tile(0, np.sum(np.logical_not(cut_accomplished))), edgecolor='none', s=50, vmin=0, vmax=4, cmap='summer_r') proj = obztak.utils.ortho.safeProj(basemap, self.target_fields['RA'][cut_accomplished], self.target_fields['DEC'][cut_accomplished]) basemap.scatter(*proj, c=self.target_fields['TILING'][cut_accomplished], edgecolor='none', s=50, vmin=0, vmax=4, cmap='summer_r') """ # Draw colorbar in existing axis if len(fig.axes) == 2: colorbar = plt.colorbar(cax=fig.axes[-1]) else: colorbar = plt.colorbar() colorbar.set_label('Weight') # Show the selected field proj = basemap.proj([field['RA']], [field['DEC']]) basemap.scatter(*proj, c='magenta', edgecolor='none', s=50) #plt.draw() plt.pause(0.001)
def func_on_all_figs(func, *args, **kwargs): ''' runs a function after making all open figures current. Parameters ---------- func : function function to call \*args, \*\*kwargs : pased to func Examples ---------- >>>rf.func_on_all_figs(grid,alpha=.3) ''' for fig_n in plb.get_fignums(): plb.figure(fig_n) func(*args, **kwargs) plb.draw()
def mv_ginput(self, timeout=None, wait=True): """ Moves to a location the user clicks on. """ print("Select new motor x-position in current plot by mouseclick") if not pylab.get_fignums(): upper_limit = 0 lower_limit = self.limits[0] if self.limits[1] == 0: upper_limit = 100 else: upper_limit = self.limits[1] limit_plot = [] for x in range(lower_limit, upper_limit): limit_plot.append(x) pylab.plot(limit_plot) pos = pylab.ginput(1)[0][0] self.move(pos, timeout=timeout, wait=wait)
def new(ABF, forceNewFigure=False, title=None, xlabel=None, ylabel=None): """ makes a new matplotlib figure with default dims and DPI. Also labels it with pA or mV depending on ABF. """ if len(pylab.get_fignums()) and forceNewFigure == False: #print("adding to existing figure") return pylab.figure(figsize=(8, 6)) pylab.grid(alpha=.5) pylab.title(ABF.ID) pylab.ylabel(ABF.units) pylab.xlabel("seconds") if xlabel: pylab.xlabel(xlabel) if ylabel: pylab.ylabel(ylabel) if title: pylab.title(title) annotate(ABF)
def hotfig( figs='all', align=False ): import pylab if figs == 'all': figs = pylab.get_fignums() if not isinstance( figs, ( tuple, list ) ): figs = [ figs ] figs = list( figs ) for i, f in enumerate( figs ): if isinstance( f, int ): figs[ i ] = pylab.figure( f ) if align == True: align = figs if align: superimpose( align ) def kp(event): key = event.key.lower() codes = list( '1234567890QWERTYUIOP'.lower() ) if key in codes: target = int( codes.index( key ) ) + 1 elif key == '[': target = event.canvas.figure.number - 1 elif key == ']': target = event.canvas.figure.number + 1 else: target = None if target != None and pylab.fignum_exists( target ): look( target ) for fig in figs: fig.canvas.mpl_connect( 'key_press_event', kp ) look()
def save_all_figs(dir = './', format=['eps','pdf','svg','png']): ''' Save all open Figures to disk. Parameters ------------ dir : string path to save figures into format : list of strings the types of formats to save figures as. The elements of this list are passed to :matplotlib:`savefig`. This is a list so that you can save each figure in multiple formats. ''' if dir[-1] != '/': dir = dir + '/' for fignum in plb.get_fignums(): fileName = plb.figure(fignum).get_axes()[0].get_title() if fileName == '': fileName = 'unamedPlot' for fmt in format: plb.savefig(dir+fileName+'.'+fmt, format=fmt) print (dir+fileName+'.'+fmt)
def hotfig(figs='all', align=False): import pylab if figs == 'all': figs = pylab.get_fignums() if not isinstance(figs, (tuple, list)): figs = [figs] figs = list(figs) for i, f in enumerate(figs): if isinstance(f, int): figs[i] = pylab.figure(f) if align == True: align = figs if align: superimpose(align) def kp(event): key = event.key.lower() codes = list('1234567890QWERTYUIOP'.lower()) if key in codes: target = int(codes.index(key)) + 1 elif key == '[': target = event.canvas.figure.number - 1 elif key == ']': target = event.canvas.figure.number + 1 else: target = None if target != None and pylab.fignum_exists(target): look(target) for fig in figs: fig.canvas.mpl_connect('key_press_event', kp) look()
def mv_ginput(self, timeout=None): """ Moves to a location the user clicks on. If there are existing plots, this will be the position on the most recently active plot. If there are no existing plots, an empty plot will be created with the motor's limits as the range. """ logger.info(("Select new motor x-position in current plot " "by mouseclick")) if not pylab.get_fignums(): upper_limit = 0 lower_limit = self.limits[0] if self.limits[0] == self.limits[1]: upper_limit = self.limits[0] + 100 else: upper_limit = self.limits[1] limit_plot = [] for x in range(lower_limit, upper_limit): limit_plot.append(x) pylab.plot(limit_plot) pos = pylab.ginput(1)[0][0] self.move(pos, timeout=timeout)
def get_fig(newfig=False,oplot=False,mysize=False,**kwargs): """ fig = get_fig(newfig=False,oplot=False,mysize=False,**kwargs) Generates new figure with myfig size or returns figure if it exists. """ if newfig: if mysize: fig = pylab.figure(figsize=myfigsize(),**kwargs) else: fig = pylab.figure(**kwargs) else: if pylab.get_fignums() == []: if mysize: fig = pylab.figure(figsize=myfigsize(),**kwargs) else: fig = pylab.figure(**kwargs) else: fig = pylab.gcf() if not oplot: fig.clf() return fig
def func_on_all_figs(func, *args, **kwargs): ''' runs a function after making all open figures current. useful if you need to change the properties of many open figures at once, like turn off the grid. Parameters ---------- func : function function to call \*args, \*\*kwargs : pased to func Examples ---------- >>> rf.func_on_all_figs(grid,alpha=.3) ''' for fig_n in plb.get_fignums(): fig = plb.figure(fig_n) for ax_n in fig.axes: fig.add_axes(ax_n) # trick to make axes current func(*args, **kwargs) plb.draw()
def pylab_show(self, *args, **kwargs): """this is the replacement of the :code:`pylab.show` function call it will get the lastet created figures that are not already shown and create binary objects out of them. the results is put in a list of BytesIO objects, where each BytesIO is the png (for now) representation of the image. .. warning:: This function should be personalized to get options about format and resolution, but that is not yet provided """ import pylab self.last_drawn = [] figs = list(map(pylab.figure, pylab.get_fignums())) new_figures = [fig for fig in figs if fig not in self.fig_index] self.fig_index.update(set(figs)) # fig = pylab.gcf() for fig in new_figures: file_descriptor = BytesIO() fig.savefig(file_descriptor, format='png') self.last_drawn.append(file_descriptor)
def init_figure(self, openfig=True): self.handles = {} for k in ['mappable', 'quiver', 'quiver_key', '1d']: self.handles[k] = [] if not openfig: # check if figure exist: try: exists = self.fig.number in pl.get_fignums() except: exists = False openfig = not exists # figure: if openfig: self.fig = pl.figure(figsize=self.config['figure.figsize'], facecolor=self.config['figure.facecolor'], edgecolor=self.config['figure.edgecolor']) # main ax: self.ax = self.fig.add_axes(self.config['axes.position']) # colorbar: if self.config['colorbar.bg_position']: self.cbbg = self.fig.add_axes(self.config['colorbar.bg_position']) self.cbbg_rec = matplotlib.patches.Rectangle( (0, 0), 1, 1, **self.config['colorbar.bg']) self.cbbg.add_artist(self.cbbg_rec) self.cbbg.set(frame_on=0, xticks=[], yticks=[], visible=False) else: self.cbbg = False if self.config['colorbar.ax_position']: self.cbax = self.fig.add_axes(self.config['colorbar.ax_position']) self.cbax.set(visible=False) else: self.cbax = False
rcube = (SpectralCube.read(fn) .with_spectral_unit(u.km/u.s, velocity_convention='radio') .spectral_slab(0.0*u.km/u.s, 160*u.km/u.s)) slice = pvextractor.extract_pv_slice(rcube, path) slice.writeto(fn.replace(".fits",".pvextraction_path{0}.fits".format(pathno)), clobber=True) F = aplpy.FITSFigure(slice) F.show_grayscale() F.save(fn.replace(".fits",".pvextraction_path{0}.png".format(pathno))) print fn.replace(".fits",".pvextraction_path{0}.png".format(pathno)) F.show_contour('SgrB2_a_03_7M.HNC.image.pbcor.pvextraction_path0.fits') F.save(fn.replace(".fits",".pvextraction_path{0}_contourHNCACA.png".format(pathno))) F.remove_layer('contour_set_1') F.show_contour('feathered/Feathered_HNC.pvextraction_path0.fits') F.save(fn.replace(".fits",".pvextraction_path{0}_contourHNCFeath.png".format(pathno))) for ii in pl.get_fignums(): pl.close(ii) F = aplpy.FITSFigure('SgrB2_a_03_7M.HNC.image.pbcor.max.fits') F.show_grayscale() #F.show_lines([np.array([path._coords.ra.value, path._coords.dec.value])]) xy = np.array(path.sample_points(1, wcs=rcube.wcs)) F._ax1.plot(xy[0,:], xy[1,:], color='g', linewidth=5, alpha=0.3, zorder=10) F._ax1.plot(xy[0,:], xy[1,:], color='g', linewidth=2, alpha=0.5, zorder=100) pl.draw() F.save('path_on_HNCmax.png')
Usage: - Copy script into acoular/examples/ directory - Run in terminal - Move generated *.png files to acoular/docs/source/examples/ Do not run this script in an ipython console. Copyright (c) 2018 The Acoular developers. All rights reserved. """ from glob import glob from importlib import import_module from pylab import get_fignums, figure, savefig, close for ex in glob("example*.py"): exname = ex[:-3] print('Importing %s ...' % exname) try: import_module(exname) for fn in get_fignums(): figure(fn) figname = exname + '_' + str(fn)+ '.png' print('Exporting %s ...' % figname) savefig(figname, bbox_inches='tight') close('all') except: print('---------------------------------------------') print(' Error importing %s !' % ex) print('---------------------------------------------')
def root_locus(sys, kvect=None, xlim=None, ylim=None, plotstr='b' if int(matplotlib.__version__[0]) == 1 else 'C0', Plot=True, PrintGain=True, grid=False, **kwargs): """Root locus plot Calculate the root locus by finding the roots of 1+k*TF(s) where TF is self.num(s)/self.den(s) and each k is an element of kvect. Parameters ---------- sys : LTI object Linear input/output systems (SISO only, for now) kvect : list or ndarray, optional List of gains to use in computing diagram xlim : tuple or list, optional control of x-axis range, normally with tuple (see matplotlib.axes) ylim : tuple or list, optional control of y-axis range Plot : boolean, optional (default = True) If True, plot root locus diagram. PrintGain: boolean (default = True) If True, report mouse clicks when close to the root-locus branches, calculate gain, damping and print grid: boolean (default = False) If True plot omega-damping grid. Returns ------- rlist : ndarray Computed root locations, given as a 2d array klist : ndarray or list Gains used. Same as klist keyword argument if provided. """ # Convert numerator and denominator to polynomials if they aren't (nump, denp) = _systopoly1d(sys) if kvect is None: start_mat = _RLFindRoots(nump, denp, [1]) kvect, mymat, xlim, ylim = _default_gains(nump, denp, xlim, ylim) else: start_mat = _RLFindRoots(nump, denp, [kvect[0]]) mymat = _RLFindRoots(nump, denp, kvect) mymat = _RLSortRoots(mymat) # Check for sisotool mode sisotool = False if 'sisotool' not in kwargs else True # Create the Plot if Plot: if sisotool: f = kwargs['fig'] ax = f.axes[1] else: figure_number = pylab.get_fignums() figure_title = [pylab.figure(numb).canvas.get_window_title() for numb in figure_number] new_figure_name = "Root Locus" rloc_num = 1 while new_figure_name in figure_title: new_figure_name = "Root Locus " + str(rloc_num) rloc_num += 1 f = pylab.figure(new_figure_name) ax = pylab.axes() if PrintGain and sisotool == False: f.canvas.mpl_connect( 'button_release_event', partial(_RLClickDispatcher,sys=sys, fig=f,ax_rlocus=f.axes[0],plotstr=plotstr)) elif sisotool == True: f.axes[1].plot([root.real for root in start_mat], [root.imag for root in start_mat], 'm.', marker='s', markersize=8,zorder=20,label='gain_point') f.suptitle("Clicked at: %10.4g%+10.4gj gain: %10.4g damp: %10.4g" % (start_mat[0][0].real, start_mat[0][0].imag, 1, -1 * start_mat[0][0].real / abs(start_mat[0][0])),fontsize = 12 if int(matplotlib.__version__[0]) == 1 else 10) f.canvas.mpl_connect( 'button_release_event',partial(_RLClickDispatcher,sys=sys, fig=f,ax_rlocus=f.axes[1],plotstr=plotstr, sisotool=sisotool, bode_plot_params=kwargs['bode_plot_params'],tvect=kwargs['tvect'])) # plot open loop poles poles = array(denp.r) ax.plot(real(poles), imag(poles), 'x') # plot open loop zeros zeros = array(nump.r) if zeros.size > 0: ax.plot(real(zeros), imag(zeros), 'o') # Now plot the loci for index,col in enumerate(mymat.T): ax.plot(real(col), imag(col), plotstr,label='rootlocus') # Set up plot axes and labels if xlim: ax.set_xlim(xlim) if ylim: ax.set_ylim(ylim) ax.set_xlabel('Real') ax.set_ylabel('Imaginary') if grid and sisotool: _sgrid_func(f) elif grid: _sgrid_func() else: ax.axhline(0., linestyle=':', color='k',zorder=-20) ax.axvline(0., linestyle=':', color='k') return mymat, kvect
def root_locus(sys, kvect=None, xlim=None, ylim=None, plotstr='b' if int(matplotlib.__version__[0]) == 1 else 'C0', Plot=True, PrintGain=True, grid=False, **kwargs): """Root locus plot Calculate the root locus by finding the roots of 1+k*TF(s) where TF is self.num(s)/self.den(s) and each k is an element of kvect. Parameters ---------- sys : LTI object Linear input/output systems (SISO only, for now). kvect : list or ndarray, optional List of gains to use in computing diagram. xlim : tuple or list, optional Set limits of x axis, normally with tuple (see matplotlib.axes). ylim : tuple or list, optional Set limits of y axis, normally with tuple (see matplotlib.axes). Plot : boolean, optional If True (default), plot root locus diagram. PrintGain : bool If True (default), report mouse clicks when close to the root locus branches, calculate gain, damping and print. grid : bool If True plot omega-damping grid. Default is False. Returns ------- rlist : ndarray Computed root locations, given as a 2D array klist : ndarray or list Gains used. Same as klist keyword argument if provided. """ # Convert numerator and denominator to polynomials if they aren't (nump, denp) = _systopoly1d(sys) if kvect is None: start_mat = _RLFindRoots(nump, denp, [1]) kvect, mymat, xlim, ylim = _default_gains(nump, denp, xlim, ylim) else: start_mat = _RLFindRoots(nump, denp, [kvect[0]]) mymat = _RLFindRoots(nump, denp, kvect) mymat = _RLSortRoots(mymat) # Check for sisotool mode sisotool = False if 'sisotool' not in kwargs else True # Create the Plot if Plot: if sisotool: f = kwargs['fig'] ax = f.axes[1] else: figure_number = pylab.get_fignums() figure_title = [ pylab.figure(numb).canvas.get_window_title() for numb in figure_number] new_figure_name = "Root Locus" rloc_num = 1 while new_figure_name in figure_title: new_figure_name = "Root Locus " + str(rloc_num) rloc_num += 1 f = pylab.figure(new_figure_name) ax = pylab.axes() if PrintGain and not sisotool: f.canvas.mpl_connect( 'button_release_event', partial(_RLClickDispatcher, sys=sys, fig=f, ax_rlocus=f.axes[0], plotstr=plotstr)) elif sisotool: f.axes[1].plot( [root.real for root in start_mat], [root.imag for root in start_mat], 'm.', marker='s', markersize=8, zorder=20, label='gain_point') f.suptitle( "Clicked at: %10.4g%+10.4gj gain: %10.4g damp: %10.4g" % (start_mat[0][0].real, start_mat[0][0].imag, 1, -1 * start_mat[0][0].real / abs(start_mat[0][0])), fontsize=12 if int(matplotlib.__version__[0]) == 1 else 10) f.canvas.mpl_connect( 'button_release_event', partial(_RLClickDispatcher, sys=sys, fig=f, ax_rlocus=f.axes[1], plotstr=plotstr, sisotool=sisotool, bode_plot_params=kwargs['bode_plot_params'], tvect=kwargs['tvect'])) # zoom update on xlim/ylim changed, only then data on new limits # is available, i.e., cannot combine with _RLClickDispatcher dpfun = partial( _RLZoomDispatcher, sys=sys, ax_rlocus=ax, plotstr=plotstr) # TODO: the next too lines seem to take a long time to execute # TODO: is there a way to speed them up? (RMM, 6 Jun 2019) ax.callbacks.connect('xlim_changed', dpfun) ax.callbacks.connect('ylim_changed', dpfun) # plot open loop poles poles = array(denp.r) ax.plot(real(poles), imag(poles), 'x') # plot open loop zeros zeros = array(nump.r) if zeros.size > 0: ax.plot(real(zeros), imag(zeros), 'o') # Now plot the loci for index, col in enumerate(mymat.T): ax.plot(real(col), imag(col), plotstr, label='rootlocus') # Set up plot axes and labels if xlim: ax.set_xlim(xlim) if ylim: ax.set_ylim(ylim) ax.set_xlabel('Real') ax.set_ylabel('Imaginary') if grid and sisotool: _sgrid_func(f) elif grid: _sgrid_func() else: ax.axhline(0., linestyle=':', color='k', zorder=-20) ax.axvline(0., linestyle=':', color='k') return mymat, kvect
regions = pyregion.open('../regions/maser_sourceC.reg') reg = regions[0] coordinate = coordinates.SkyCoord(*reg.coord_list, frame=reg.coord_format, unit=(u.deg, u.deg)) names = {'h2co11': 'H$_2$CO $1_{1,0}-1_{1,1}$', 'siov1': 'SiO J=1-0 v=1', 'siov2': 'SiO J=1-0 v=2', 'ch3oh44': 'CH$_3$OH $7_{0,7}-6_{1,6}$ A+', 'oh': 'OH', 'ch3oh6': 'CH$_3$OH $5(1,5)-6(0,6)++$', 'siov0_54': 'SiO J=5-4 v=0', 'siov0_10': 'SiO J=1-0 v=0', 'siov0_21': 'SiO J=2-1 v=0', } for ii in pl.get_fignums(): pl.close(ii) T,F = True,False results = {} for cubename,cubefn in [('h2co11', '../data/h2comos2_uniform_min.fits'), ('siov1', '../data/M447_SiO_v1_cube.fits'), ('siov2', '../data/M447_SiO_v2_cube.fits'), ('ch3oh44', '../data/M447_CH3OH_A+_4407_cube.fits'), ('ch3oh6', '../data/ch3ohmos2_uniform_min.fits'), #('siov0', ('siov0_54', '../../apex/merged_datasets/molecule_cubes/APEX_SiO_54_bl.fits'), ]: cube = SpectralCube.read(cubefn).with_spectral_unit(u.km/u.s) pcube = pyspeckit.Cube(cube=cube)
plt.title("chan %d, selected good pulses ene=MnKa+-20eV"%ch) plt.ylim(0,40000) # plot first 30 good traces with some condition plt.figure() inds = plt.find(np.logical_and(arr['good'],np.abs(arr['enedc']-6490)<20.))[:30] plt.plot(1e3*timebase*np.arange(nSamples),arr['traces'][inds, :].T) plt.xlabel("time (ms)") plt.ylabel("pulse fb signal") plt.grid(which="both",b="on") plt.title("chan %d, selected good pulses ene=MnKb+-20eV"%ch) plt.ylim(0,40000) if save: savedir = "%s/%s"%(dir_d,fdate) print("writing %d plots as pdf to %s"%(len(plt.get_fignums()), savedir)) with PdfPages(path.join(savedir, fdate+"_all_figures.pdf")) as pdf: for i in plt.get_fignums(): print("writing plot %d of %d to pdf"%(i, len(plt.get_fignums()))) pdf.savefig(i) import commands params = {'xtick.labelsize': 10, # x ticks 'ytick.labelsize': 10, # y ticks 'legend.fontsize': 7 } plt.rcParams.update(params) for j, ds in enumerate(data):
from astropy.table import Table, Column from astropy import wcs import pylab as pl regions = pyregion.open(paths.rpath('ch3oh_maser_spots_channellabels.reg')) cube = SpectralCube.read(paths.dpath('ch3oh_256_e2zoom_chan550to700.image.fits')) vcube = cube.with_spectral_unit(u.km/u.s, velocity_convention='radio', rest_value=6.668518*u.GHz) dx, dy = 4,4 parnames = ("height", "amplitude", "x", "y", "width_x", "width_y", "rota") tbl = Table(names=['velocity'] + [x for p in parnames for x in p,'e'+p]) for ii in pl.get_fignums(): pl.figure(ii).clf() for ii,region in enumerate(regions): channel = int(region.attr[1]['text']) x,y = cube.wcs.sub([wcs.WCSSUB_CELESTIAL]).wcs_world2pix([region.coord_list], 0)[0] # not sure why, but it looks like all the images are offset by 1 pix x = x+1 y = y+1 cutout = cube[channel, y-dy:y+dy, x-dx:x+dx].value rms = cube[channel, :20, :20].std() #params: (height, amplitude, x, y, width_x, width_y, rota)
def root_locus(sys, kvect=None, xlim=None, ylim=None, plotstr='-', Plot=True, PrintGain=True, grid=False): """Root locus plot Calculate the root locus by finding the roots of 1+k*TF(s) where TF is self.num(s)/self.den(s) and each k is an element of kvect. Parameters ---------- sys : LTI object Linear input/output systems (SISO only, for now) kvect : list or ndarray, optional List of gains to use in computing diagram xlim : tuple or list, optional control of x-axis range, normally with tuple (see matplotlib.axes) ylim : tuple or list, optional control of y-axis range Plot : boolean, optional (default = True) If True, plot root locus diagram. PrintGain: boolean (default = True) If True, report mouse clicks when close to the root-locus branches, calculate gain, damping and print grid: boolean (default = False) If True plot s-plane grid. Returns ------- rlist : ndarray Computed root locations, given as a 2d array klist : ndarray or list Gains used. Same as klist keyword argument if provided. """ # Convert numerator and denominator to polynomials if they aren't (nump, denp) = _systopoly1d(sys) if kvect is None: kvect, mymat, xlim, ylim = _default_gains(nump, denp, xlim, ylim) else: mymat = _RLFindRoots(nump, denp, kvect) mymat = _RLSortRoots(mymat) # Create the Plot if Plot: figure_number = pylab.get_fignums() figure_title = [pylab.figure(numb).canvas.get_window_title() for numb in figure_number] new_figure_name = "Root Locus" rloc_num = 1 while new_figure_name in figure_title: new_figure_name = "Root Locus " + str(rloc_num) rloc_num += 1 f = pylab.figure(new_figure_name) if PrintGain: f.canvas.mpl_connect( 'button_release_event', partial(_RLFeedbackClicks, sys=sys)) ax = pylab.axes() # plot open loop poles poles = array(denp.r) ax.plot(real(poles), imag(poles), 'x') # plot open loop zeros zeros = array(nump.r) if zeros.size > 0: ax.plot(real(zeros), imag(zeros), 'o') # Now plot the loci for col in mymat.T: ax.plot(real(col), imag(col), plotstr) # Set up plot axes and labels if xlim: ax.set_xlim(xlim) if ylim: ax.set_ylim(ylim) ax.set_xlabel('Real') ax.set_ylabel('Imaginary') if grid: _sgrid_func() return mymat, kvect
from woo.core import * from woo.dem import * from woo import log #log.setLevel("PsdSphereGenerator",log.TRACE) doMass=True pp=PsdSphereGenerator(psdPts=[(.3,.5),(.5,1.)],mass=doMass,discrete=False) m=FrictMat(density=1000) for i in range(0,100000): pp(m) kw=dict(cumulative=False) import pylab pylab.ion() pylab.plot(*pp.inputPsd(**kw),label="in",linewidth=3) pylab.plot(*pp.psd(**kw),label="out",linewidth=3) pylab.grid(True) pylab.legend(loc='best') #pylab.show() genNum=PsdSphereGenerator(psdPts=[(.3,0),(.3,.2),(.4,.9),(.5,1.)],mass=False) for i in range(0,10000): genNum(m) pylab.figure(max(pylab.get_fignums())+1); \ pylab.plot(*genNum.inputPsd(),label= 'in'); \ # plot count-based PSD pylab.plot(*genNum.psd(),label='out'); \ # mass=True is the default pylab.plot(*genNum.psd(mass=False),label='out (count)'); \ # mass=False, count-based pylab.legend(loc='best'); pylab.show()
def OnThreadUpdate( self, event ): self.status.SetLabel( 'Done with acquisition #%s' % (event.data+1) ) if len( pylab.get_fignums() ) > 0 and pylab.get_fignums()[-1] == self.current_fignum: if self.plotcolormap(): self.fig.canvas.draw()
def look( fig=None ): import pylab if fig == None and len( pylab.get_fignums() ): fig = pylab.gcf() if isinstance( fig, int ): fig = pylab.figure( fig ) fig.canvas._tkcanvas.focus_force()