def test_nominal(self): fig1 = plt.figure() fig2 = plt.figure() self.assertTrue(plt.fignum_exists(fig1.number)) self.assertTrue(plt.fignum_exists(fig2.number)) dcs.close_all() self.assertFalse(plt.fignum_exists(fig1.number)) self.assertFalse(plt.fignum_exists(fig2.number))
def _Plot_3D_fired(self): try: plt.fignum_exists() xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() index_wavelength_left=(np.abs(Data.wavelength-xmin)).argmin() index_wavelength_right=(np.abs(Data.wavelength-xmax)).argmin() index_time_left=(np.abs(Data.time-ymin)).argmin() index_time_right=(np.abs(Data.time-ymax)).argmin() except: index_wavelength_left=0 index_wavelength_right=Data.wavelength[-1] index_time_left=0 index_time_right=Data.wavelength[-1] Data.Three_d = Data.TrA_Data[index_time_left:index_time_right,index_wavelength_left:index_wavelength_right] Data.Three_d_wavelength = Data.wavelength[index_wavelength_left:index_wavelength_right] Data.Three_d_time = Data.time[index_time_left:index_time_right] self.scene.mlab.clf() x = np.linspace(Data.Three_d_wavelength[0],Data.Three_d_wavelength[-1],len(Data.Three_d_wavelength)) y = np.linspace(Data.Three_d_time[0], Data.Three_d_time[-1],len(Data.Three_d_wavelength)) [xi,yi] = np.meshgrid(x,y) for i in range(len(Data.Three_d_wavelength)): repeating_wavelength = np.array(np.ones((len(Data.Three_d_time)))*Data.Three_d_wavelength[i]) vectors = np.array([Data.Three_d_time,repeating_wavelength,Data.Three_d[:,i]]) if i==0: Data.TrA_Data_gridded = vectors else: Data.TrA_Data_gridded = np.hstack((Data.TrA_Data_gridded, vectors)) zi = interpolate.griddata((Data.TrA_Data_gridded[1,:],Data.TrA_Data_gridded[0,:]),Data.TrA_Data_gridded[2,:],(xi,yi), method='linear', fill_value=0) #Sends 3D plot to mayavi in gui #uncomment for plotting actual data matrix #self.scene.mlab.surf(Data.time,Data.wavelength,Data.TrA_Data,warp_scale=-self.z_height*100) #gridded plot which gives correct view self.plot = self.scene.mlab.surf(yi,xi,zi, warp_scale=-self.z_height*100) self.scene.mlab.colorbar(orientation="vertical") self.scene.mlab.axes(nb_labels=5,) self.scene.mlab.ylabel("wavelength (nm)") self.scene.mlab.xlabel("time (ps)")
def savefig(filename, **kwargs): """ Save a figure plotted by Matplotlib. Note : This function is supposed to be used after the ``plot`` function. Otherwise it will save a blank image with no plot. Parameters ---------- filename : str The name of the image file. Extension must be specified in the file name. For example filename with `.png` extension will give a rasterized image while `.pdf` extension will give a vectorized output. kwargs : keyword arguments Keyword arguments to be passed to ``savefig`` function of ``matplotlib.pyplot``. For example use `bbox_inches='tight'` to remove the undesirable whitepace around the image. """ try: import matplotlib.pyplot as plt except ImportError: raise ImportError("Matplotlib required for savefig()") if not plt.fignum_exists(1): utils.simon("use ``plot`` function to plot the image first and " "then use ``savefig`` to save the figure.") plt.savefig(filename, **kwargs)
def gplot(xval, yval, sym=None, xr=None, yr=None, title=None, xlabel=None, \ ylabel=None, tsize=None, xsize=None, ysize=None, color=None, \ fnum=None, fname=None): # -------- defaults if sym==None : sym='k-' if xr==None : xr = min(xval), max(xval) if yr==None : yr = min(yval), max(yval) if title==None : title='' if xlabel==None : xlabel='' if ylabel==None : ylabel='' if fnum==None : fnum=0 # -------- make the figure if plt.fignum_exists(fnum): plt.close(fnum) plt.figure(fnum) plt.plot(xval,yval,sym) plt.xlim(xr) plt.ylim(yr) plt.title(title, fontsize=tsize) plt.xlabel(xlabel, fontsize=xsize) plt.ylabel(ylabel, fontsize=ysize) # -------- write to output if desired if fname!=None: if not isinstance(fname,list): fname = [fname] for ifile in fname: print("GPLOT: Writing output to " + ifile) plt.savefig(ifile) else: plt.show()
def mpl_annotate_interactive(text, ax=None, arrowprops={"facecolor":'black', "shrink":0.05}): ax = ax or pyplot.gca() fig = ax.figure coordinates = [ None, # xy None # xytext ] pause = [True,] def get_xy(event): if coordinates[0] is None: coordinates[0] = (event.x, event.y) print("xy : {}".format(coordinates[0])) else: coordinates[1] = (event.x, event.y) print("xytext : {}".format(coordinates[1])) pause[0] = False cid = fig.canvas.mpl_connect('button_press_event', get_xy) while pause[0] and pyplot.fignum_exists(fig.number): fig.canvas.get_tk_widget().update() fig.canvas.mpl_disconnect(cid) ax.annotate( text, xycoords='figure pixels', xy=coordinates[0], xytext=coordinates[1], arrowprops=arrowprops, )
def plot_process(queue, name, labels=None): """Grabs data from the queue and plots it in a named figure """ # Set up the figure and display it fig = setup_figure(name) plt.show(block=False) if labels is not None: plt.xlabel(labels[0]) plt.ylabel(labels[1]) while True: # Get all the data currently on the queue data = [] while not queue.empty(): data.append(queue.get()) # If there is no data, no need to plot, instead wait for a # while if len(data) == 0: plt.pause(0.015) continue # Check if poison pill (None) arrived or the figure was closed if None in data or not plt.fignum_exists(fig.number): # If yes, leave the process break else: # Plot the data, then wait 15ms for the plot to update for datum in data: plt.plot(*datum) plt.pause(0.015)
def make_new_fig(fnum=None, close_old=True, return_fig=False, use_max_fnum=False, **kwargs): """ Make a new figure, clearing the old one. Returns the figure after the one you've created. """ if fnum is None: fignums = get_fignums() max_fnum = max(fignums) if len(fignums) > 0 else 0 if use_max_fnum: fnum = max_fnum+1 else: for fnum in range(0, max_fnum+2): if fnum not in fignums: break if fignum_exists(fnum) and close_old: close(fnum) # Close the figure if it already exists. fig = figure(fnum, **kwargs) clf() if return_fig: return [fig, fnum+1] else: return fnum+1
def mpl_wait_for_key_press(fig=None, key="enter", close=False): # I need to use an object. The pointer to the pause list will be captured by # closer in key_press_event. When the callback will change the pause # content, the outer function will see it. With the simple pause = True # code, the inner function would have changed a local copy of pause. if fig is None: fig = pyplot.gcf() pause = [True, ] def key_press_event(event): if event.key == key: pause[0] = False cid = fig.canvas.mpl_connect('key_press_event', key_press_event) while pause[0] and pyplot.fignum_exists(fig.number): fig.canvas.get_tk_widget().update() fig.canvas.mpl_disconnect(cid) if close and pyplot.fignum_exists(fig.number): pyplot.close(fig.number)
def closeFigure(event): #remove figure from figs for figure in figs: if not plt.fignum_exists(figure[0]): #if figure id number doesn't exist, figure doesn't exist print("removing figure",figure[0]) figs.remove(figure) #remove from figure list if len(figs) == 0: raise SystemExit #exit program if all figures have been closed
def _redraw(self): if plt.isinteractive(): fig = self.kwargs["fig"] if not plt.fignum_exists(fig.number): fig.show() fig.canvas.draw() else: print("Redraw() is unsupported in non-interactive plotting mode!")
def test_filter_applyFilter(self): ppmm = self.runBefore() fake_event = matplotlib.backend_bases.MouseEvent('button_press_event', ppmm.figfilter.canvas, 636, 823) ppmm.applyFilter(fake_event) # check the figure has been closed self.assertFalse(py.fignum_exists(ppmm.figfilter.number))
def updateTimeUnit(self,event): #Verify that the data frame is not empty if self.df.empty: messagebox.showinfo('Selection Error', 'Error: Please collect data before selecting time units.') else: self.unit = self.timevar.get() self.unit_conv = self.choices[self.unit] #Change units on timestamp plots if they exist self.df['timestamp']=self.df['orig_timestamp'] * self.unit_conv #Figure two is the EvT plot: if plt.fignum_exists(2): self.EvT_plot() #Figure one is the Time Histogram if plt.fignum_exists(1): self.THist_plot()
def display(self, image): if self.imsh is None or not plt.fignum_exists(self.imsh.figure.number): self.imsh = plt.imshow(image, interpolation='nearest') self.imsh.axes.axis('off') self.imsh.axes.set_position((0, 0, 1, 1)) self.imsh.figure.canvas.draw() else: self.imsh.set_data(image) plt.pause(1e-4)
def _redraw(self): if plt.isinteractive(): fig = self.kwargs.get('fig',False) if not fig: return if not plt.fignum_exists(fig.number): fig.show() fig.canvas.draw() else: print('Redraw() is unsupported in non-interactive plotting mode!')
def animation(): for i1 in xrange(1, nanim): # remove previous highlights icontainer.ax0_hs.remove() icontainer.ax1_hs.get_sizes()[0] = 20 icontainer.ax1_hs.get_facecolor()[0,0] = 0 icontainer.ax1_hs.get_facecolor()[0,1] = 0.5 icontainer.ax1_hs.get_facecolor()[0,3] = 0.2 icontainer.ax1_hs.get_edgecolor()[0,1] = 0.5 icontainer.ax1_hs.get_edgecolor()[0,3] = 0.2 # remove previous predictive distribution axes[1].lines.remove(icontainer.prev_line) # show next sample icontainer.ax0_hs = axes[0].scatter(mu[i1], sigma[i1], 40, 'r') icontainer.ax1_hs = axes[1].scatter( ynew[i1], (0.02 + 0.02*np.random.rand())*np.max(ynewdists), 40, 'r' ) icontainer.prev_line, = axes[1].plot( xynew, ynewdists[i1], 'b', linewidth=1.5 ) # update figure fig.canvas.draw() # wait animation delay time or until animation is cancelled stop_anim.wait(anim_delay) if stop_anim.isSet(): # animation cancelled break # skip the rest if the figure does not exist anymore if not plt.fignum_exists(fig.number): return # advance stage icontainer.stage += 1 # remove highlights icontainer.ax0_hs.remove() axes[1].lines.remove(icontainer.prev_line) icontainer.ax1_hs.get_sizes()[0] = 20 icontainer.ax1_hs.get_facecolor()[0,0] = 0 icontainer.ax1_hs.get_facecolor()[0,1] = 0.5 icontainer.ax1_hs.get_facecolor()[0,3] = 0.2 icontainer.ax1_hs.get_edgecolor()[0,1] = 0.5 icontainer.ax1_hs.get_edgecolor()[0,3] = 0.2 # modify helper text htext.set_text('press any key to continue') # plot the rest of the samples i1 += 1 icontainer.ax1_hs = axes[1].scatter( ynew[i1:], (0.02 + 0.015*np.random.rand(nsamp-i1))*np.max(ynewdists), 10, color=[0,0.5,0], alpha=0.2 ) # update legend axes[1].legend( (icontainer.ax1_hs,), ('samples from the predictive distribution',), loc='upper center' ) fig.canvas.draw()
def EvT_select (self): #Verify that the data frame is not empty if self.df.empty: messagebox.showinfo('Plot Error', 'Error: No data has been collected. Can not select absent data.') elif not plt.fignum_exists(2): messagebox.showinfo('Plot Error', 'Please open the EvT plot before trying to select data.') else: plt.figure(2) plt.scatter(self.df['timestamp'],self.df['amplitude'],color=self.EvT_color_set,s=self.EvT_size_set) self.EvT_interface = PlotInterface(self.df,self.EvT_color_set,self.EvT_size_set)
def _figure_name(base_name): """Helper to compute figure name This takes in a base name an return the name of the figure to use. If gs.OVERPLOT, then this is a no-op. If not gs.OVERPLOT then append '(N)' to the end of the string until a non-existing figure is found """ if not gs.OVERPLOT: if not plt.fignum_exists(base_name): pass else: for j in itertools.count(1): numbered_template = '{} ({})'.format(base_name, j) if not plt.fignum_exists(numbered_template): base_name = numbered_template break return base_name
def test_filter_unapplyFilter(self): ppmm = self.runBefore() event_apply = matplotlib.backend_bases.MouseEvent('button_press_event', ppmm.figfilter.canvas, 636, 823) ppmm.applyFilter(event_apply) event_unapply = matplotlib.backend_bases.MouseEvent('button_press_event', ppmm.figfilter.canvas, 538, 838) ppmm.unapplyFilter(event_unapply) self.assertFalse(ppmm.opts.filterParameters['apply']) self.assertFalse(py.fignum_exists(ppmm.figfilter.number))
def run(self): while self.v.isOpen() == 'true' and plt.fignum_exists(self.g.fig.number): if self.g.isUpdated: self.v.setTime((self.g.currentX/len(self.g.data)*self.v.getDuration())) self.g.isUpdated = False else: lock.acquire() if self.g.isUpdated == False: self.g.setLine((float(self.v.getTime())/float(self.v.getDuration()))*len(self.g.data)) lock.release() time.sleep(0.1)
def showMap(self,block = False ): if not plt.fignum_exists(1): self.imgplot = plt.imshow(self.map,interpolation = 'none', cmap = 'gray_r') plt.show(block = block) plt.grid(1) plt.ion() print 'does not exist' raw_input() else: self.imgplot.set_data(self.map) plt.draw() print 'exists'
def closeFigure(event): #remove figure from figs for figure in figs: if not plt.fignum_exists(figure[0]): #if figure id number doesn't exist, figure doesn't exist print("removing figure",figure[0]) figs.remove(figure) #remove from figure list if len(figs) == 0: if sys.platform == 'darwin': #only on Macs email_data(self.csvFileName, self.coder) raise SystemExit #exit program if all figures have been closed
def redraw(self): """ Redraw plot. Use after custom user modifications of axes & fig objects """ if plt.isinteractive(): fig = self.kwargs['fig'] #Redraw figure if it was previously closed prior to updating it if not plt.fignum_exists(fig.number): fig.show() fig.canvas.draw() else: print('redraw() is unsupported in non-interactive plotting mode!')
def _wx_callback(cls,*args): out=[] for ppp in cls.autoupdate: if pl.fignum_exists(ppp.figure.number): res=ppp.update() if res: out.append(res) else: cls.autoupdate.remove(ppp) if out and hasattr(cls,'on_update'): for ppp in out: cls.on_update(ppp) wx.WakeUpIdle()
def plot_interpolated_image(num): """Select number and super_grid parameters, will plot result""" data = interpolate_to_center(num) grid = super_grid if plt.fignum_exists(num): plt.close(num) f1=plt.figure(num) ax=f1.add_subplot(111) cax1=ax.pcolormesh(super_grid[0], super_grid[1],data) f1.colorbar(cax1) plt.show() print data.shape return f1
def tilefigs(lst, geometry, ww=None, raisewindows=False, tofront=False, verbose=0): """ Tile figure windows on a specified area """ mngr = plt.get_current_fig_manager() be = matplotlib.get_backend() if ww is None: ww = monitorSizes()[-1] w = ww[2] / geometry[0] h = ww[3] / geometry[1] if verbose: print('tilefigs: ww %s, w %d h %d' % (str(ww), w, h)) for ii, f in enumerate(lst): if not plt.fignum_exists(f): continue fig = plt.figure(f) iim = ii % np.prod(geometry) ix = iim % geometry[0] iy = np.floor(float(iim) / geometry[0]) x = ww[0] + ix * w y = ww[1] + iy * h if verbose: print('ii %d: %d %d: f %d: %d %d %d %d' % (ii, ix, iy, f, x, y, w, h)) if verbose >= 2: print(' window %s' % mngr.get_window_title()) if be == 'WXAgg': fig.canvas.manager.window.SetPosition((x, y)) fig.canvas.manager.window.SetSize((w, h)) if be == 'WX': fig.canvas.manager.window.SetPosition((x, y)) fig.canvas.manager.window.SetSize((w, h)) if be == 'agg': fig.canvas.manager.window.SetPosition((x, y)) fig.canvas.manager.window.resize(w, h) if be == 'Qt4Agg' or be == 'QT4' or be == 'QT5Agg': # assume Qt canvas try: fig.canvas.manager.window.move(x, y) fig.canvas.manager.window.resize(w, h) fig.canvas.manager.window.setGeometry(x, y, w, h) # mngr.window.setGeometry(x,y,w,h) except Exception as ex: print('problem with window manager: ', ) print('backend %s' % (be,)) logging.exception(ex) if raisewindows: mngr.window.raise_() if tofront: plt.figure(f)
def EvT_select_only (self): #Verify that the data frame is not empty if self.df.empty: messagebox.showinfo('Plot Error', 'Error: No data has been collected. Can not delete absent data.') else: #If we have selected some data, delete that data if self.EvT_interface: sub = ['timestamp', 'amplitude'] mask = self.df[sub].isin(self.EvT_interface.sub_df[sub].to_dict(orient='list')).all(axis=1) self.df = self.df[mask] self.EvT_interface = None #Update the plots #Figure two is the EvT plot: if plt.fignum_exists(2): self.EvT_plot() #Figure one is the Time Histogram if plt.fignum_exists(1): self.THist_plot() #Figure zero is the Energy Histogram if plt.fignum_exists(0): self.EHist_plot()
def test_list(self): fig1 = plt.figure() fig2 = plt.figure() self.assertTrue(plt.fignum_exists(fig1.number)) self.assertTrue(plt.fignum_exists(fig2.number)) dcs.close_all([fig1]) self.assertFalse(plt.fignum_exists(fig1.number)) self.assertTrue(plt.fignum_exists(fig2.number)) plt.close(fig2) self.assertFalse(plt.fignum_exists(fig1.number)) self.assertFalse(plt.fignum_exists(fig2.number))
def animation(): for i1 in xrange(1, nanim): # remove previous lines ax0.lines.remove(icontainer.prev_line1) ax0.lines.remove(icontainer.prev_line2) # resize last scatter sample icontainer.prev_scat.get_sizes()[0] = 8 # draw next sample # first sample of sigma2 icontainer.prev_line1, = ax0.plot(tl1, [sigma[i1], sigma[i1]], "k--", linewidth=1.5) # the conditional distribution of mu given sigma2 icontainer.prev_line2, = ax0.plot(t1, sigma[i1] + condpdfs[i1] * 100, "g--", linewidth=1.5) conddist, = ax10.plot(t1, condpdfs[i1], "g--") # sample mu given sigma2 icontainer.prev_scat = ax0.scatter(mu[i1], sigma[i1], 40, color="g") # update figure fig.canvas.draw() # wait animation delay time or until animation is cancelled stop_anim.wait(anim_delay) if stop_anim.isSet(): # animation cancelled break # skip the rest if the figure does not exist anymore if not plt.fignum_exists(fig.number): return # advance stage icontainer.stage += 1 # remove previous lines ax0.lines.remove(icontainer.prev_line1) ax0.lines.remove(icontainer.prev_line2) # resize last scatter sample icontainer.prev_scat.get_sizes()[0] = 8 # remove helper text htext.set_text("press any key to continue") # remove extra legend entries icontainer.legend_h.pop(2) icontainer.legend_h.pop(1) icontainer.legend_s.pop(2) icontainer.legend_s.pop(1) ax0.legend(icontainer.legend_h, icontainer.legend_s) # plot the rest of the samples i1 += 1 if i1 < nanim: ax0.scatter(mu[i1:nanim], sigma[i1:nanim], 8, color="g") conddistlist = ax10.plot(t1, condpdfs[i1:nanim].T, "g--") fig.canvas.draw()
def _render(self, pos): if self._visualize: if self._fig is None or not plt.fignum_exists(self._fig.number): self._fig = plt.figure() plt.rcParams['legend.fontsize'] = 10 self._ax = self._fig.add_subplot(1, 1, 1) self._fig.show() self._ax.cla() self._ax.plot(self._t, np.sin(3 * self._t)) car = plt.Circle((pos, np.sin(3 * pos)), radius=0.02, fc='r') self._ax.add_artist(car) self._ax.set_ylim(-1.05, 1.05) self._fig.canvas.draw()
def descriptor(self, doc): self.fields = [ k for k, v in doc["data_keys"].items() if len(v["shape"]) == 2 or ( len(v["shape"]) == 3 and len([dim for dim in v["shape"] if dim > 0]) == 2 ) ] data_keys = doc["data_keys"] if self.aspect is None: aspects = [] for field in self.fields: aspect_ratio = data_keys[field]["shape"][0] / data_keys[field][ "shape"][1] if any(s == -1 for s in data_keys[field]["shape"]): aspects.append('auto') elif aspect_ratio > 1.25 or aspect_ratio < .75: aspects.append('auto') else: aspects.append('equal') else: aspects = [self.aspect] * len(self.fields) from xray_vision.backend.mpl.cross_section_2d import CrossSection import matplotlib.pyplot as plt # only make new figure for new data otherwise use old data for field, asp in zip(self.fields, aspects): if field in self.cs_dict and plt.fignum_exists( self.cs_dict[field]._fig.number ): continue fig = plt.figure(field) cs = CrossSection( fig, self.cmap, self.norm, self.limit_func, self.auto_redraw, self.interpolation, aspect=asp, ) cs._fig.canvas.set_window_title(field) cs._fig.show() self.cs_dict[field] = cs
def test_fignum_exists(): # pyplot figure creation, selection and closing with fignum_exists plt.figure('one') plt.figure(2) plt.figure('three') plt.figure() assert plt.fignum_exists('one') assert plt.fignum_exists(2) assert plt.fignum_exists('three') assert plt.fignum_exists(4) plt.close('one') plt.close(4) assert not plt.fignum_exists('one') assert not plt.fignum_exists(4)
def test_fignum_exists(): # pyplot figure creation, selection and closing with fignum_exists plt.figure('one') plt.figure(2) plt.figure('three') plt.figure() assert_equal(plt.fignum_exists('one'), True) assert_equal(plt.fignum_exists(2), True) assert_equal(plt.fignum_exists('three'), True) assert_equal(plt.fignum_exists(4), True) plt.close('one') plt.close(4) assert_equal(plt.fignum_exists('one'), False) assert_equal(plt.fignum_exists(4), False)
def test_log_mpl_plotly(self): assert (os.path.exists( get_event_path(self.run_path, kind=V1ArtifactKind.CHART)) is False) assert (os.path.exists( get_asset_path(self.run_path, kind=V1ArtifactKind.CHART)) is False) figure, axes = plt.figure(), plt.gca() circle1 = plt.Circle((0.2, 0.5), 0.2, color="r") circle2 = plt.Circle((0.8, 0.5), 0.2, color="g") axes.add_patch(circle1) axes.add_patch(circle2) plt.axis("scaled") plt.tight_layout() self.run.log_mpl_plotly_chart(name="figure", figure=figure, step=1) self.event_logger.flush() assert (os.path.exists( get_asset_path(self.run_path, kind=V1ArtifactKind.CHART)) is False) assert (os.path.exists( get_event_path(self.run_path, kind=V1ArtifactKind.CHART)) is True) events_file = get_event_path(self.run_path, kind=V1ArtifactKind.CHART, name="figure") assert os.path.exists(events_file) is True results = V1Events.read(kind="image", name="figure", data=events_file) assert len(results.df.values) == 1 self.run.log_mpl_plotly_chart(name="figure", figure=figure, step=2) assert plt.fignum_exists(figure.number) is False self.event_logger.flush() assert (os.path.exists( get_asset_path(self.run_path, kind=V1ArtifactKind.CHART)) is False) assert (os.path.exists( get_event_path(self.run_path, kind=V1ArtifactKind.CHART)) is True) events_file = get_event_path(self.run_path, kind=V1ArtifactKind.CHART, name="figure") assert os.path.exists(events_file) is True results = V1Events.read(kind="image", name="figure", data=events_file) assert len(results.df.values) == 2
def plotmat(self,mvlist,note=None,tit=None,supt=None, cmap='gray',ion=True,minDB=None): """ input:matrix dimension """ if minDB is None: minDB=minDBdf if ion: plt.ion() subp={1:[1,1],2:[1,2],3:[1,3],4:[2,2],5:[2,3],6:[2,3],9:[3,3],12:[4,3]} p1,p2=subp[len(mvlist)] if p1*p2!=self.axnum or self.fig is None\ or not(plt.fignum_exists(self.fig.number)): self.fig,(self.ax)=plt.subplots(p1,p2) self.axnum=p1*p2 if self.axnum==1: self.ax=np.array([self.ax]) self.ax=self.ax.reshape([-1]) for i in range(len(mvlist)): US=mvlist[i] if US is None: continue if US.dtype is torch.float32: US=US.detach().numpy() US=np.abs(US).reshape([-1,mvlist[i].shape[-1]]) if np.sum(np.abs(US))!=0: US=US/np.max(US) if note=='db': US[US<10**(minDB/20)]=10**(minDB/20) US=20*np.log10(US) vmin,vmax=[minDB,0] if note=='db' else [0,1] self.ax[i].clear() self.ax[i].imshow(US,cmap=cmap,aspect='auto',vmin=vmin,vmax=vmax) if not(tit is None): self.ax[i].set_title(tit[i]) if not(supt is None): self.fig.suptitle(supt) if ion: plt.pause(self.Tpause) return self.fig
def update_fields(self): #update fields during each loop iteration #update total sequence time pressure_df = self.pressure_table_to_df() tot_seq_hrs = pressure_df['time'].astype(float).sum() / 60 self.ui.tot_seq_time_display.setText( str(np.round(tot_seq_hrs, decimals=2))) self.ui.main_loop_counter_display.setText(str(main_i)) #update actual RH field self.ui.actual_rh_display.setText( str(np.round(self.ui.set_rh.value(), decimals=3))) #display(self.ui.set_rh.value()) #switching between pressure and valve mode if self.ui.pressure_mode.isChecked(): self.ui.set_pressure.setDisabled(False) self.ui.set_valve_position.setDisabled(True) if self.ui.valve_mode.isChecked(): self.ui.set_valve_position.setDisabled(False) self.ui.set_pressure.setDisabled(True) #control pressure if self.ui.pressure_control_on.isChecked(): pressure0 = np.random.random() + 760 master_df['pressure'].iloc[main_i] = str(pressure0) #control pop-up pressure plot if not plt.fignum_exists(2): self.ui.show_pressure_plot.setChecked(False) if self.ui.show_pressure_plot.isChecked(): if main_i % 3 == 0: self.plot_pressure() #timer which updates fields on GUI (set interval in ms) self.main_loop_delay = self.ui.set_main_loop_delay.value() #record date/time and elapsed time at each iteration master_df['date'].iloc[main_i] = time.ctime() master_df['time'].iloc[main_i] = str( np.round(time.time() - app_start_time, decimals=3))
def plot_voronoi(cells, seeds, centroids, X, Y, phi): if not plt.fignum_exists(1): plt.show() ax = plt.axes(projection='3d') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.view_init(elev=90, azim=-90) ax.plot(seeds[:,0],seeds[:,1],'.') ax.plot(centroids[:,0],centroids[:,1],'.') for cell in cells: if len(cell) >= 3: hull = ConvexHull(cell) for simplex in hull.simplices: ax.plot(cell[simplex, 0],cell[simplex,1],'k-') ax.plot_surface(X, Y, phi, cmap='viridis', edgecolor='none', alpha=0.6) # plt.show() # Use instead of draw and pause to investigate the plot plt.draw() plt.pause(0.001)
def callback(ind,altpicker): if len(ax) > 0: if not plt.fignum_exists(ax[0].figure.number): ax.pop() else: if not altpicker: ax[0].clear() plt.figure(ax[0].figure.number) if len(ax) == 0: fig = plt.figure() ax0 = fig.add_subplot(111) ax.append(ax0) if len(ind) > 0: alpha = 0.1 if altpicker else 1 drawmean = False if altpicker else True averagetrace(spks[ind],alpha=alpha,drawmean=drawmean,ax=ax[0],color='k') plt.title('N = ' + str(len(ind))) plt.draw()
def addScore(self, score): if self.score_mean == 0: self.score_mean = score self.score_mean_100 = score self.score_mean *= 0.9 self.score_mean += 0.1 * score self.mean_array += [self.score_mean] self.score_mean_100 *= 0.99 self.score_mean_100 += 0.01 * score self.mean_array_100 += [self.score_mean_100] x_array = range(len(self.mean_array)) plt.plot(x_array, self.mean_array, 'C1') plt.plot(x_array, self.mean_array_100, 'C2') plt.draw() plt.pause(0.001) return plt.fignum_exists(1)
def plot_continuous(env, steps=1000): fig = plt.figure() ax = fig.add_subplot(111) env.animate(ax) fig_num = plt.get_fignums()[0] for i in range(steps): if not plt.fignum_exists(fig_num): return False plt.title('iteration: ' + str(i)) plt.pause(0.001) # take a step env.step() # store the state for animation env.animate(ax) fig.canvas.draw() return True
def main(): # borrar siguiente linea para cerrar el programa al cerrar la grafica while not plt.fignum_exists(1): try: clusters = pd.read_csv(settings.active_clusters_csv) except: pass else: clusters["created_at"] = clusters["created_at"].apply( lambda x: (pd.to_datetime(x))) clusters["last_activity"] = clusters["last_activity"].apply( lambda x: (pd.to_datetime(x))) legends = [] for _, cluster in clusters.iterrows(): root_item = str(cluster.root_item) n = 70 if len(root_item) > n: root_item = root_item[:n + root_item[n:].find( " ")] + "\n" + root_item[n + root_item[n:].find(" ") + 1:] terms = str(cluster.terms) if len(terms) > n: terms = terms[:n + terms[n:].find(" ")] + "\n" + terms[ n + terms[n:].find(" ") + 1:] legends.append("Cluster ID: " + str(cluster.id) + "\nitems: " + str(cluster.n_items) + "\nTerms: " + terms + "\nRoot item: " + root_item + "\nRoot_user: "******"\nRoot_followers: " + str(cluster.root_followers) + "\nRoot_user_created_at: " + str(cluster.root_user_created_at) + "\nOther: " + str(cluster.other_items[:300] + "...")) plotter = ClusterPlotter() plotter.plot(x=clusters["created_at"], y=clusters["last_activity"], sizes=1 * clusters["n_items"], text=legends, plot_at=str(datetime.datetime.utcnow().strftime( "%a %b %d %H:%M:%S UTC %Y")))
def play_movie(r, r1): #just for fun fig = plt.figure() pausetime = .0001 img = None #Original assumptions #rshape: (999900, 33, 100) #r1shape: (999900, 100) #0-80 hz #-1500 to 1500 power for i, (f, f1) in enumerate(zip(r, r1)): s1 = plt.subplot(212) im = f #plt.imread(f) if img is None: img = plt.imshow(im) else: img.set_data(im) if plt.fignum_exists(fig.number): plt.xticks(range(0, 101, 20), range(i, i + 101, 20)) plt.yticks(range(0, 33, 8), range(0, 81, 20)) # Figure is still opened plt.pause(pausetime) plt.draw() s1.set_title('Spectrogram') plt.xlabel('time (ms)') plt.ylabel('frequency (Hz)') s2 = plt.subplot(211) axes = plt.gca() s2.clear() plt.xticks(range(0, 101, 20), range(i, i + 101, 20)) s2.plot(r1[i:i + 101, 1]) s2.margins(x=0, y=0) axes.set_ylim([0, 1]) s2.set_title('LFP') plt.xlabel('time (ms)') plt.ylabel('power') else: break
def descriptor(self, doc): self.fields = [ k for k, v in doc["data_keys"].items() if len(v["shape"]) == 2 or (len(v["shape"]) == 3 and len( [dim for dim in v["shape"] if dim > 0]) == 2) ] data_keys = doc["data_keys"] if self.aspect is None: aspects = [] for field in self.fields: aspect_ratio = data_keys[field]["shape"][0] / data_keys[field][ "shape"][1] if any(s == -1 for s in data_keys[field]["shape"]): aspects.append('auto') elif aspect_ratio > 1.25 or aspect_ratio < .75: aspects.append('auto') else: aspects.append('equal') else: aspects = [self.aspect] * len(self.fields) from xray_vision.backend.mpl.cross_section_2d import CrossSection import matplotlib.pyplot as plt # only make new figure for new data otherwise use old data for field, asp in zip(self.fields, aspects): if field in self.cs_dict and plt.fignum_exists( self.cs_dict[field]._fig.number): continue fig = plt.figure(field) cs = CrossSection( fig, self.cmap, self.norm, self.limit_func, self.auto_redraw, self.interpolation, aspect=asp, ) cs._fig.canvas.set_window_title(field) cs._fig.show() self.cs_dict[field] = cs
def train(self, X, Y, Xtest, Ytest, steps): st = self.plot_every iterations = [] train_acc = [] test_acc = [] train_loss = [] test_loss = [] print("Step Train", "" if Xtest is None else "Test") for step in range(st, steps + st, st): self.train_step(X, Y, st) iterations.append(step) Z, P = self.inference(X) train_acc.append(100 * (Z == Y).mean()) train_loss.append(self.loss(Y, P)) if Xtest is not None: Ztest, Ptest = self.inference(Xtest) test_acc.append(100 * (Ztest == Ytest).mean()) test_loss.append(self.loss(Ytest, Ptest)) self.plot_curves(0, "Accuracy (%)", iterations, train_acc, test_acc) self.plot_curves(1, "Loss", iterations, train_loss, test_loss) self.plot_confusion(4, "Confusion matrix (train)", Z, Y) if X.shape[1] == 2: self.plot_data(2, "Training set", X, Y) if Xtest is not None: self.plot_data(3, "Test set", Xtest, Ytest) if Xtest is None: print("{} {:.2f}%".format(step, train_acc[-1])) else: self.plot_confusion(5, "Confusion matrix (test)", Ztest, Ytest) print("{} {:.2f}% {:.2f}%".format(step, train_acc[-1], test_acc[-1])) plt.pause(0.0001) if not self.iterative or (self.draw and not plt.fignum_exists(0)): break if self.dump: with open("dump.txt", "wt") as f: for t in zip_longest(iterations, train_acc, test_acc, train_loss, test_loss): row = (x if x is not None else "" for x in t) print("{} {} {} {} {}".format(*row), file=f)
def showData(d, Type): #getData() if plt.fignum_exists(num=1): plt.close() if Type == "Graph": x = [] y = [] for z in range(0, int(len(jsonDataList[1]) / 49)): x.append(str(jsonDataList[1][z * 49])) print(jsonDataList[1][z * 49]) y.append(jsonDataList[1][d + (49 * z)]) textData = str(jsonDataList[0][d]), x, y, '\n' text.insert(END, textData) del textData plt.plot(x, y) plt.show() else: textData = str(jsonDataList[0][d]), str(jsonDataList[1][d]) + '\n' print(str(textData)) text.insert(END, textData) del textData
def closeFigure(event): #remove figure from figs for figure in figs: if not plt.fignum_exists(figure[0]): #if figure id number doesn't exist, figure doesn't exist print("removing figure",figure[0]) figs.remove(figure) #remove from figure list if len(figs) == 0: if sys.platform == 'darwin': #only on Macs #uncomment to enable email functionality #email_data(self.csvFileName, self.coder) raise SystemExit #exit program if all figures have been closed for figure in figs: #for each figure connect events figure[-1].fig.canvas.mpl_connect('button_release_event', updateDisplayByTarget) #when there's a click, update trace if needed figure[-1].fig.canvas.mpl_connect('close_event', closeFigure) #if the 'x' button is clicked, remove figure from figs list figure[-1].fig.canvas.mpl_connect('motion_notify_event', figure[-1].widgets['time_xy_sub_cursor'].mouse_move) plt.show()
def GrapheUpdate(self): x, I = loadtxt("Intensity.txt", delimiter=",", unpack=True) if plt.fignum_exists(1): plt.close() fig = plt.figure(figsize=(5, 3)) fig.canvas.manager.window.move(800, 20) fig.canvas.set_window_title('Intensity') plt.plot(x, I, linestyle='--', marker='o', color='r', markersize=6, markeredgecolor='b') plt.ylim(0, 1.6) plt.title('Fresnel diffraction', fontsize=16, weight='bold') plt.xlabel('x', fontsize=12, weight='bold') plt.ylabel('I (x)', fontsize=12, weight='bold') plt.grid() plt.show()
def freshfig(num=None, figsize=None, *args, **kwargs): """Create/clear figure. Similar to:: fig, ax = suplots(*args,**kwargs) With the modification that: - If the figure does not exist: create it. This allows for figure sizing -- even with mpl backend MacOS. - Otherwise: clear figure. Avoids closing/opening so as to keep pos and size. """ exists = plt.fignum_exists(num) fig = plt.figure(num=num, figsize=figsize) fig.clear() _, ax = plt.subplots(num=fig.number, *args, **kwargs) return fig, ax
def plotBtnClicked(self): """ Plot result outputs """ if plt.fignum_exists(1): # Do nothing if a plot is already open QtGui.QMessageBox.warning( self, 'Warning', "A plot is already open. Please close to create a new plot.", QtGui.QMessageBox.Ok) else: fig = plt.figure(1, facecolor='white', figsize=(16, 7)) if self.combo_plot.currentText() == 'Battery SoC': q = self.sim_out['q'] # Reshape q into 2d matrix (24 x 365) q2d = np.reshape(np.matrix(q[1:]), (-1, 24)).T plt.title('Battery state of charge (%)') elif self.combo_plot.currentText() == 'Generator Output': q = np.array(self.sim_out['P_gen']) / 1000 q2d = np.reshape(np.matrix(q), (-1, 24)).T plt.title('Generator Output (kW)') elif self.combo_plot.currentText() == 'Solar PV Output': q = self.sim_out['P_pv'] q2d = np.reshape(np.matrix(q), (-1, 24)).T plt.title('Solar PV Output (Wp)') elif self.combo_plot.currentText() == 'Load Demand': q = self.sim_out['P_ld'] q2d = np.reshape(np.matrix(q), (-1, 24)).T plt.title('Load Demand (W)') try: plt.ylabel('Hour of the day') plt.xlabel('Day of the year') plt.imshow(q2d, aspect='auto', cmap='jet') plt.colorbar() plt.show() except: self.main_window.show_status_message('Error opening plot...') plt.close()
def show_data(self, figure_no = None): if self.acc_analysis is None: self.extract_data() if not 'time' in self.acc_analysis or not 'gradient' in self.acc_data: print("{}: Nothing can be plotted. I'm still missing data. Run 'extract_data' first.".format(self.name)) return if 'time' in self.acc_analysis: t = self.acc_analysis['time'] xlabel = 'time [s]' else: xlabel = 'time [au]' if figure_no is None: if self.name is not None: figure_no = self.name else: figure_no = 'Acc data' if plt.fignum_exists(figure_no): plt.gcf().clear() else: plt.figure(figure_no) plt.plot(t, self.acc_data['real']['acc']) plt.xlabel(xlabel) plt.ylabel('acceleration [g]') if self.name is not None: plt.title = self.name if 'smooth' in self.acc_data: plt.plot(t, self.acc_data['smooth']['acc']) if 'peak_times' in self.acc_analysis and all(np.isfinite(self.acc_analysis.get('peak_times'))): ylim = plt.ylim() plt.autoscale(False) for time in self.acc_analysis['peak_times']: plt.plot([t[time],t[time]],[ylim[0],ylim[1]],color='black',linewidth=3) plt.autoscale(True) plt.show()
def _plotgraph(self): """ This function deals with plotting the graph. """ #delete rows in table that aren't ticked csv_table, headings = self._deleterows(self.CheckVar_graph, self.column_variables, self.csv_table) # sort csv_table into date ascending order csv_table = self._timesort(csv_table, column_index=0, delimiter='/') csv_table = np.array(csv_table) # sum the amounts with the same dates dates = np.array([]) amount = [] for i in range(len(csv_table)): if csv_table[i][0] in dates: date_loc = np.where(dates == csv_table[i][0])[0][0] amount[date_loc] += float(csv_table[i][-1].replace(',', '')) else: dates = np.append(dates, csv_table[i][0]) amount += [float(csv_table[i][-1].replace(',', ''))] # accumulative amount over time accum_amount = [] for i in range(len(amount)): accum_amount += [sum(amount[0:i + 1])] if plt.fignum_exists(1): self.__plotdates(dates, accum_amount) else: plt.figure(1) self.__plotdates(dates, accum_amount) plt.ylabel('Amount (%s)' % unichr(163)) plt.grid() plt.title('+'.join(headings)) plt.legend(loc='best') plt.show() return
def plotter(self): """Child process to plot live data.""" ys = deque([], maxlen=self.history) fig, ax = plt.subplots() plt.ion() plot, = ax.plot([]) plt.title('Robot IR Sensor Readings') while True: # If the plotting window is closed, exit. if not plt.fignum_exists(fig.number): break # Get the next sensor reading from the queue. ys.append(self.queue.get(block=True)) # Need to set both x and y data in the time series. plot.set_data(range(len(ys)), ys) # Fit the plot window to the data. ax.autoscale() ax.relim() plt.pause(0.0001)
def bodePlot(myFilter, fig_id='none', axes_hdl='none', label = '' ): w, mag, phase = myFilter.bode() if fig_id == 'none': fig_hdl, axes_hdl = plt.subplots(2, 1, sharex='col') fig_id = fig_hdl.number else: if plt.fignum_exists(fig_id): fig_hdl = plt.figure(fig_id) axes_hdl = fig_hdl.get_axes() else: fig_hdl = plt.figure(fig_id) axes_hdl = fig_hdl.subplots(2, 1, sharex='col') fig_id = fig_hdl.number (mag_ax_hdl, phase_ax_hdl) = axes_hdl plt.sca(mag_ax_hdl) plt.semilogx(w, mag, label = label) # Bode magnitude plot plt.grid(True) # plt.xlabel('Angular frequency [rad/sec]') plt.ylabel('Magnitude [dB]') plt.title('Magnitude response') if label != '' : mag_ax_hdl.legend() plt.sca(phase_ax_hdl) plt.semilogx(w, phase, label = label) # Bode phase plot plt.grid(True) plt.xlabel('Angular frequency [rad/sec]') plt.ylabel('Phase [deg]') plt.title('Phase response') if label != '' : phase_ax_hdl.legend() return fig_id, axes_hdl
def tempStats(): global fig global ax1 fig = plt.figure() if(len(temperatureArray) >= 1): plt.title(likelinessToRain(humidityArray[-1] ,temperatureArray[-1])) ax1 = fig.add_subplot(1,1,1) print(f"temperatureArray{len(temperatureArray)}") print(len(humidityArray)) temperatureArray.clear() humidityArray.clear() if plt.fignum_exists(0): print("Is running temperature") plt.close('all') else: print("Is not running") print("temperature running") ani = animation.FuncAnimation(fig, sensors, interval=1000) plt.show()
def _ShowGUI(self, label): """ Show/Hide the GUI side figure which enables changing the slice locations. The figure number is used to differenciate between GUI of different figures. Parameters ---------- label : List List of the labels of the CheckButtons. Returns ------- None. """ ### check if the figure exists. If yes, hide it if plt.fignum_exists('GUIFig_%i' % self.fignum): plt.close('GUIFig_%i' % self.fignum) ## if not, instanciate the GUISlicePlot else: self.GUI = GUISlicePlot(self)
def create_time_grid(timing=None, plot=False): '''Create time grid for simulations using the Fortran implementation of the time grid generator. Args: timing : dict Dictionary containing timing elements: 'times', 'dt_start', 'steps_per_cycle','dt_increase' As in STRAHL, the last element in each of these arrays refers to sawtooth events. plot : bool If True, plot time grid. Returns: time : array Computational time grid corresponding to :param:timing input. save : array Array of zeros and ones, where ones indicate that the time step will be stored in memory in Aurora simulations. Points corresponding to zeros will not be returned to spare memory. ''' _time, _save = _aurora.time_steps( timing['times'],timing['dt_start'],timing['steps_per_cycle'],timing['dt_increase']) # eliminate trailing 0's: idxs = np.nonzero(_time) time = _time[idxs] save = _save[idxs] > 0 if plot: #show timebase if plt.fignum_exists('Aurora time step'): plt.figure('Aurora time step').clf() f,ax = plt.subplots(num='Aurora time step') ax.set_title(r'$\#$ time steps: %d $\#$ saved steps %d'%(len(time), sum(save))) ax.semilogy(time[1:],np.diff(time),'.-',label='step') ax.semilogy(time[1:][save[1:]],np.diff(time)[save[1:]],'o',label='step') [ax.axvline(t,c='k',ls='--') for t in timing['times']] ax.set_xlim(time[0],time[-1]) return time, save
def save_zp_checkplot(exp, outdir): print('Attempting to save zeropoint check plot') if not plt.fignum_exists(1): return assert (os.path.exists(outdir)) outname = (os.path.split(exp.fname_im))[-1] outname = outname.replace('.fits', '-zp.png') outname_tmp = 'tmp.' + outname outname = os.path.join(outdir, outname) outname_tmp = os.path.join(outdir, outname_tmp) assert (not os.path.exists(outname)) assert (not os.path.exists(outname_tmp)) plt.savefig(outname_tmp, dpi=200, bbox_inches='tight') os.rename(outname_tmp, outname)
def render(self, mode='human'): if mode not in self.metadata['render.modes']: return super(TestStackEnv, self).render(mode=mode) m, n = self._obs.state n = n[0] _max = np.max(m) r = m / _max if _max != 0 else m b = 1 - r g = np.ones(r.shape) * 0.5 g[self._rew.goal_bin] += 0.1 rgb0 = np.stack([r, g, b], axis=-1) _max = np.max(n) r = n / _max if _max != 0 else n b = 1 - r g = np.ones(r.shape) * 0.5 rgb1 = np.stack([r, g, b], axis=-1) if mode == 'human': if plt is None: raise ImportError( "'render' requires matplotlib.pyplot to run in 'human' mode." ) if not (self._fig and plt.fignum_exists(self._fig.number)): width_ratio = rgb0.shape[1] // rgb1.shape[1] self._fig, self._axs = plt.subplots( 1, 2, gridspec_kw={'width_ratios': [width_ratio, 1]}) self._axs[0].cla() self._axs[0].imshow(rgb0) self._axs[1].cla() self._axs[1].imshow(rgb1) self._fig.show() elif mode == 'rgb_array': return rgb0, rgb1
def specplot(signal, fs, plotspec='b-', log=False, fighandle=None): '''Plots magnitude spectra Plots a magnitude spectrum of the waveform. You can overlay several spectra on top of one another, and specify different plot properties. Parameters ---------- signal : array The input signal. fs : scalar The sampling frequency plotspec : string A matlab (matplotlib) style string specifying the plot properties (eg., 'b-') log : bool Specfies wheter the x-axis is log or linear fighandle : Int A matplotlib figure handle to plot to ''' if fighandle is None: fighandle = 4639 # An int unlikely to have been used if pp.fignum_exists(fighandle): # MPL > 0.98.6svn pp.figure(fighandle).get_axes()[0].set_autoscale_on(False) h = pp.figure(num=fighandle) h.canvas.set_window_title('Spectrum Plot') x, y = magspec(signal, fs) if log: pp.semilogx(x, y, plotspec, figure=fighandle) else: pp.plot(x, y, plotspec, figure=fighandle) pp.xlabel('Frequency (Hz)') pp.ylabel('Magnitude (dB)') pp.show()
def plot_figures_of_merit(results): taus = np.array([a["tau"] for a in results]) params = [np.array([a["fr"] for a in results]), np.array([a["gamma"] for a in results]), np.array([a["ncc"] for a in results]), np.array([a["on_rms"] for a in results]), np.array([a["off_rms"] for a in results]) / np.array([a["init_rms"] for a in results]), np.array([a["nf"] for a in results]) / np.array([a["nbins"] for a in results]) ] labels = [r"$f_r$", r"$\Gamma$", r"$N_{cc}$", r"$\sigma_{\rm on}$", r"$\sigma_{\rm offc}/\sigma_{\rm off}$", r"$N_f / N_{\rm total}$" ] fig, axs = plt.subplots(ncols=3, nrows=2, sharex="all", figsize=(20, 6)) for y, ylab, ax in zip(params, labels, axs.flatten()): ax.plot(taus, y, marker="o") ax.set_ylabel(ylab, fontsize=20) if min(y) < 0: ax.axhline(0, lw=1, ls=":", color="k") if abs(min(y)) > 0 and abs(max(y)/min(y)) > 100: ax.set_yscale("symlog") for ax in axs.flatten()[3:]: ax.set_xlabel(r"$\rm \tau\ (ms)$", fontsize=20) ax.set_xlim(0.9*min(taus), 1.1*max(taus)) plt.subplots_adjust(hspace=0.1, wspace=0.25) plt.savefig("tauclean_fom.png", dpi=300, bbox_inches="tight") plt.close(fig) # For the purposes of testing, return whether the figure was closed successfully (implying nothing broke) return not plt.fignum_exists(fig.number)
def seedgrid(): # This function allows the user to seed the grid of live cells print('Click the cells you want to seed the grid with') # Prompt user to print('Close the window when done seeding!') # populate the grid plt.figure(0) # Initialise a figure to plot on plt.plot([1,1], alpha=0, linestyle='None') # Begin creating a blank plot plt.axis([0,25,25,0]) # Manually define the axis range to create 25 cells plt.grid(which='both') # Show the grid lines to divide plot into cells plt.xticks(np.arange(0,25,step=1)) plt.yticks(np.arange(0,25,step=1)) plt.show(block=False) # Allow code to execute while the plot is showing #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #~~~~~~~~~~~~ Create Class to obtain co-ordinates of mouse input ~~~~~~~~~~~~~~~~~~~# class SeedPoints: # Based on Event Handling documentation def __init__(self, cell, ax): # See MatPlotLib.org self.cell = cell self.xs = list(cell.get_xdata()) # Get X position of click self.ys = list(cell.get_ydata()) # Get Y position of click self.cid = cell.figure.canvas.mpl_connect('button_press_event', self) self.axs = ax # Link current axis to this instance def __call__(self, event): if event.inaxes!=self.cell.axes: return self.xs.append(event.xdata) # Extend array of X points self.ys.append(event.ydata) # Extend array of Y points self.cell.set_data(self.xs, self.ys) self.axs.scatter(int(self.xs[-1])+0.5, int(self.ys[-1])+0.5, c='lime') # Draw live cells plt.draw() #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# while plt.fignum_exists(0): # Enter a loop to allow the user to click which cells are to be ax = plt.gca() # Get reference to current plot axis cell, = ax.plot([0], [0], linestyle='None') # empty cell object seeding=SeedPoints(cell,ax) # Instantiate a new event/click plt.show() # Keep plotting until user closes window seeds=[seeding.xs[1:], seeding.ys[1:]] # Return the X and Y co-ordinates of the live cells return(seeds)