def makeFigure(self): self.nImages = len(self.runNames) nCols = 3 nRows = ceil(self.nImages / nCols) + 1 self.fig, self.axs = plt.subplots(nrows=nRows, ncols=nCols, figsize=(2.5 * nCols, 2 * nRows + 0.25), sharex=True, sharey=True) plt.subplots_adjust(left=0.005, right=0.995, top=0.9, bottom=0.1) axnext = plt.axes([0.9, 0.01, 0.075, 0.075]) #left, bottom, width, height bnext = plt.Button(axnext, 'Next') bnext.on_clicked(self.plotImages) savebtn = plt.axes([0.75, 0.01, 0.075, 0.075]) #left, bottom, width, height bsavebtn = plt.Button(savebtn, 'Save') bsavebtn.on_clicked(self.savePlots) self.plotImages() plt.show() #block=False)
def __init__(self, markers: Iterable[Marker]) -> None: """Creates a plot from the given markers and updates their orientation from user input.""" # Create the plot. x_min, x_max, y_min, y_max = find_limits(markers) self._fig, self._ax = plt.subplots() self._ax.set_xlim((x_min, x_max)) self._ax.set_ylim((y_min, y_max)) self._ax.set_aspect("equal") plt.subplots_adjust(bottom=0.2) self._markers = [m for m in markers] self._angles = [m.orientation for m in markers] self._arrows = create_arrows(markers, color=self.ARROW_COLOR, width=5.0) self._circles = create_circles(markers, color=self.CIRCLE_COLOR) self._selected_index = None self._ignore_next_click = False self._fig_background = None btn_ax = plt.axes([0.4, 0.02, 0.2, 0.08]) self._btn_accept = plt.Button(btn_ax, "Save") self._btn_accept.on_clicked(self.on_accept) self._accepted = False for i, (arrow, circle) in enumerate(zip(self._arrows, self._circles)): circle.__dict__["user_index"] = i circle.set_picker(True) self._ax.add_artist(circle) self._ax.add_artist(arrow) self._fig.canvas.mpl_connect("resize_event", self.store_background) self._fig.canvas.mpl_connect("scroll_event", self.store_background) self._fig.canvas.mpl_connect("motion_notify_event", self.on_mouse_move) self._fig.canvas.mpl_connect("button_press_event", self.on_click) self._fig.canvas.callbacks.connect("pick_event", self.on_pick)
def test_ui(): #plt.ion() f1 = plt.figure(figsize=(6, 4)) gs = f1.add_gridspec(2, 2) ax = f1.add_subplot(gs[0, 0]) btn = plt.Button(ax, "test") btn.on_clicked(handle_clicked)
def __init__(self, location, pltnum): self.location = location self.pltnum = pltnum self.ax = plt.axes(location) self.butt = plt.Button(self.ax, self.make_name()) self.butt.on_clicked(self.input_window) self.name = ""
def create_button(index: int, num_buttons: int, text: str, click_listener, margin=None, height=None) -> plt.Button: margin = margin or 0.01 height = height or 0.06 width = (1.0 - margin) / num_buttons - margin ax = plt.axes([margin + index * (width + margin), margin, width, height]) button = plt.Button(ax, text) button.on_clicked(click_listener) return button
def rysuj(): wykresy.clf() stez = [0] t = [0] r = [0] sp = [reg.set_point] for n in range(0, 1000): Ob.Q2 = reg.update(Ob.CA) Ob.licz(n) stez.append(Ob.CA) t.append(n * Ob.Tp) r.append(Ob.Q2) sp.append(reg.set_point) ax1 = plt.subplot2grid((2, 3), (0, 0), colspan=2) plt.plot(t, r, 'g') plt.ylabel('regulator') ax2 = plt.subplot2grid((2, 3), (1, 0), colspan=2) plt.plot(t, stez, 'r', t, sp, 'b') plt.ylabel('r-stez, b-cel') plt.ylabel('r-stez, b-cel') Q1box = plt.axes([0.7, 0.8, 0.2, 0.075]) text_boxQ1 = TextBox(Q1box, 'Q1', initial=str(Ob.Q1)) text_boxQ1.on_submit(submitQ1) Q3box = plt.axes([0.7, 0.7, 0.2, 0.075]) text_boxQ3 = TextBox(Q3box, 'Q3', initial=str(Ob.Q3)) text_boxQ3.on_submit(submitQ3) CA1box = plt.axes([0.7, 0.6, 0.2, 0.075]) text_boxCA1 = TextBox(CA1box, 'CA1', initial=str(Ob.CA1)) text_boxCA1.on_submit(submitCA1) CA2box = plt.axes([0.7, 0.5, 0.2, 0.075]) text_boxCA2 = TextBox(CA2box, 'CA2', initial=str(Ob.CA2)) text_boxCA2.on_submit(submitCA2) Pbox = plt.axes([0.7, 0.4, 0.2, 0.075]) text_boxP = TextBox(Pbox, 'KP', initial=str(reg.Kp)) text_boxP.on_submit(submitKp) Ibox = plt.axes([0.7, 0.3, 0.2, 0.075]) text_boxI = TextBox(Ibox, 'KI', initial=str(reg.Ki)) text_boxI.on_submit(submitKi) Dbox = plt.axes([0.7, 0.2, 0.2, 0.075]) text_boxD = TextBox(Dbox, 'KD', initial=str(reg.Kd)) text_boxD.on_submit(submitKd) Buttonbox = plt.axes([0.7, 0.1, 0.2, 0.075]) Button_box = plt.Button(Buttonbox, 'Rysuj') Button_box.on_clicked(submitButton) plt.show()
def _figure(self): """ Interactive determination of rotation angle. """ # Adjust the angles for rotation of of the QPD signal # create new figure and axes for adjusting the angles plot_params = {'wspace': 0.09, 'hspace': 0.08} self._set_plot_params(plot_params) figure, ax_ = plt.subplots(2, 2, sharex=True, sharey=False) ax = dict(list(zip(self._axes, ax_.flatten()))) # Create buttons for interactive correction of plateaus and assign # correct functions # See http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/ for # explanation of weird function assignment ax_button = {} for ac in self.action: ax_button[ac] \ = figure.add_axes([self.column[ac] * (self.lspace + self.width) + self.left, self.row[ac] * (self.bspace + self.height) + self.bottom, self.width, self.height]) self._button[ac] = plt.Button(ax_button[ac], self.label[ac]) def ap(event, ac=ac): self._adjust_plateaus(ac) # connect button to action, accordingly self._button[ac].on_clicked(ap) # create lines to plot the data for plot in self._axes: self._lines['left' + plot] = ax[plot].plot([0], [0], 'r', alpha=0.75)[0] self._lines['right' + plot] = ax[plot].plot([0], [0], 'g', alpha=0.75)[0] ax[plot].ticklabel_format(useOffset=False) ax[plot].grid(True) ax['3D'].set_ylabel('Force (pN)') ax['Y'].set_ylabel('Force (pN)') ax['Y'].set_xlabel('Extension (nm)') ax['Z'].set_xlabel('Extension (nm)') self.supertitle = figure.suptitle("Adjust plateaus to make them " "overlap") return figure
def __init__( self, app: "PeakFinderApp", logic: "PeakLogicFiles", xticksRaw: List[int], y: List[float], fileTitle: str, ) -> None: """Create the main output graph and make it clickable.""" self.app: "PeakFinderApp" = app self.logic: "PeakLogicFiles" = logic self.x: List[float] = list(range(len(xticksRaw))) self.y: List[float] = y self.xticks: Tuple[float, ...] = tuple(xticksRaw) self.loc: List[float] = [d + 0.5 for d in self.x] # Setup the matplotlib figure self.fig = plt.figure(1) self.ax = self.fig.add_subplot(111) self.ax.plot(self.x, self.y, "bo-", picker=True, pickradius=5) self.fig.canvas.mpl_connect("pick_event", self.onpick) self.fig.subplots_adjust(left=0.17) self.ax.set_xlabel("File") self.ax.get_xaxis().set_ticks([]) self.ax.set_ylabel("Current (A)") self.ax.ticklabel_format(style="sci", scilimits=(0, 0), axis="y") self.ax.set_title("Peak Current for {}".format(str(fileTitle))) # Track which point is selected by the user self.lastind: int = 0 # Add our data self.selected = self.ax.plot( [self.x[0]], [self.y[0]], "o", ms=12, alpha=0.4, color="yellow", visible=True, ) # Display button to fetch data self.axb = plt.axes([0.75, 0.03, 0.15, 0.05]) self.button = plt.Button(self.axb, "Results") # self.ax.plot._test = self.button # self.button.on_clicked(self.app.data_popup) # Draw the figure self.fig.canvas.draw() plt.show()
def __init__(self, plot_title, framerate, ignore_plot_warning): if framerate <= 0.0: raise AssertionError('Framerate should be bigger than 0') if not ignore_plot_warning and len(plt.get_fignums()) > 0: raise AssertionError('Using plot show output at the same time as other matplotlib plots can cause problems. ' 'To use this, clear all other figures before using plot show output or set ignore_plot_warning.') self._plot_title = plot_title self._framerate = framerate self._pause_secs = 1.0 / framerate self._fig = plt.figure() self._fig.canvas.mpl_connect('close_event', self._action_close) # Create buttons for playing menu axpause = plt.axes([0.5, 0.05, 0.43, 0.075]) bpause = plt.Button(axpause, 'Pause') bpause.on_clicked(self._action_pause) self._axpause = axpause # Create buttons for paused menu axcontinue = plt.axes([0.5, 0.05, 0.1, 0.075]) axnext = plt.axes([0.61, 0.05, 0.1, 0.075]) axnext10 = plt.axes([0.72, 0.05, 0.1, 0.075]) axnext100 = plt.axes([0.83, 0.05, 0.1, 0.075]) bcontinue = plt.Button(axcontinue, 'Play') bcontinue.on_clicked(self._action_continue) bnext = plt.Button(axnext, 'Next') bnext.on_clicked(self._action_next) bnext10 = plt.Button(axnext10, 'Next 10') bnext10.on_clicked(self._action_next_10) bnext100 = plt.Button(axnext100, 'Next 100') bnext100.on_clicked(self._action_next_100) self._axcontinue = axcontinue self._axnext = axnext self._axnext10 = axnext10 self._axnext100 = axnext100 # must keep a reference to buttons so they stay responsive self._buttons = (bcontinue, bnext, bnext10, bnext100, bpause)
def __init__(self, plot_title, framerate): if framerate <= 0.0: raise AssertionError('Framerate should be bigger than 0') self._plot_title = plot_title self._framerate = framerate self._pause_secs = 1.0 / framerate self._fig = plt.figure() self._fig.canvas.mpl_connect('close_event', self._action_close) # Create buttons for playing menu axpause = plt.axes([0.5, 0.05, 0.43, 0.075]) bpause = plt.Button(axpause, 'Pause') bpause.on_clicked(self._action_pause) self._axpause = axpause # Create buttons for paused menu axcontinue = plt.axes([0.5, 0.05, 0.1, 0.075]) axnext = plt.axes([0.61, 0.05, 0.1, 0.075]) axnext10 = plt.axes([0.72, 0.05, 0.1, 0.075]) axnext100 = plt.axes([0.83, 0.05, 0.1, 0.075]) bcontinue = plt.Button(axcontinue, 'Play') bcontinue.on_clicked(self._action_continue) bnext = plt.Button(axnext, 'Next') bnext.on_clicked(self._action_next) bnext10 = plt.Button(axnext10, 'Next 10') bnext10.on_clicked(self._action_next_10) bnext100 = plt.Button(axnext100, 'Next 100') bnext100.on_clicked(self._action_next_100) self._axcontinue = axcontinue self._axnext = axnext self._axnext10 = axnext10 self._axnext100 = axnext100 # must keep a reference to buttons so they stay responsive self._buttons = (bcontinue, bnext, bnext10, bnext100, bpause)
def plt_figures(d): plt.ion() # 8,5 => [[2,4],[2,1]], [[2,5]] # 8,5 => [[4,4],[4,1]] # 8,5 => [[4,5]] f = plt.figure("kSpecAnal", figsize=(12, 8), constrained_layout=True) gs = f.add_gridspec(nrows=16, ncols=5) d['AxLevels'] = f.add_subplot(gs[:8,:4]) d['AxFreqs'] = f.add_subplot(gs[:8,4]) d['AxFreqs'].set_xlabel("Freqs - HighSigLvl") d['AxHeatMap'] = f.add_subplot(gs[8:16,:4]) d['AxBtnLevels'] = f.add_subplot(gs[8,4]) d['AxBtnHeatMap'] = f.add_subplot(gs[9,4]) d['AxBtnMaxLvls'] = f.add_subplot(gs[10,4]) d['AxBtnMinLvls'] = f.add_subplot(gs[11,4]) d['AxBtnAvgLvls'] = f.add_subplot(gs[12,4]) d['AxBtnCurLvls'] = f.add_subplot(gs[13,4]) d['AxBtnPause'] = f.add_subplot(gs[14,4]) d['AxBtnQuit'] = f.add_subplot(gs[15,4]) d['AxFreqs'].set_xticks([]) d['AxFreqs'].set_yticks([]) d['BtnPause'] = plt.Button(d['AxBtnPause'], "Pause") d['BtnPause'].on_clicked(event_pause) d['BtnLevels'] = plt.Button(d['AxBtnLevels'], "Levels") d['BtnLevels'].on_clicked(event_levels) d['BtnHeatMap'] = plt.Button(d['AxBtnHeatMap'], "HeatMap") d['BtnHeatMap'].on_clicked(event_heatmap) d['BtnMinLvls'] = plt.Button(d['AxBtnMinLvls'], "MinLvls") d['BtnMinLvls'].on_clicked(event_minlvls) d['BtnMaxLvls'] = plt.Button(d['AxBtnMaxLvls'], "MaxLvls") d['BtnMaxLvls'].on_clicked(event_maxlvls) d['BtnAvgLvls'] = plt.Button(d['AxBtnAvgLvls'], "AvgLvls") d['BtnAvgLvls'].on_clicked(event_avglvls) d['BtnCurLvls'] = plt.Button(d['AxBtnCurLvls'], "CurLvls") d['BtnCurLvls'].on_clicked(event_curlvls) d['BtnQuit'] = plt.Button(d['AxBtnQuit'], "Quit") d['BtnQuit'].on_clicked(event_quit) f.canvas.mpl_connect('pick_event', handle_pick) update_boolbtns(d)
def button_on_clicked(event): global filename filename = CSVLoad.openFileDialogCsv() # clear arrays, so that the old values disappear global lats, lons lats, lons = [], [] global mags mags = [] global times times = [] global grid grid = VG.load_from_csv(filename) redraw_map() build_map(10) # code replication because of on_clicked event does not work otherwise ax = plt.axes([0, 0.9, 0.1, 0.1]) b = plt.Button(ax, "Load") b.on_clicked(button_on_clicked) plt.show()
def _figure(self): """ Initialize and show an interactive plot for adjusting the attachment. Adjust the plateau correction parameters interactively and set the modification accordingly. The plot is stored in self.figure. """ # create new figure and axes for adjusting the plateaus figure, ax = plt.subplots(1, 1, sharex=True, sharey=True) self._ax = ax # create buttons for interactive correction of plateaus and assign # correct functions # see http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/ for # explanation of weird function assignment ax_button = {} for ac in self.action: ax_button[ac] = figure.add_axes([ self.column[ac] * (self.lspace + self.width) + self.left, self.row[ac] * (self.bspace + self.height) + self.bottom, self.width, self.height ]) self._button[ac] = plt.Button(ax_button[ac], self.label[ac]) def ap(event, ac=ac): self._adjust_plateaus(ac) # connect button to action, accordingly self._button[ac].on_clicked(ap) # create lines to plot the plateaus self._lines['left'] = ax.plot([0], [0], 'r', alpha=0.75)[0] self._lines['right'] = ax.plot([0], [0], 'g', alpha=0.75)[0] ax.ticklabel_format(useOffset=False) ax.grid(True) self.supertitle = figure.suptitle("Adjust plateaus to make them " "overlap") return figure
def __init__(self, cell_labels): cell_mask = np.ma.masked_where(np.ones_like(cell_labels), np.ones(cell_labels.shape)) grid_sz = 7 self.fig = plt.figure() plt.subplot2grid((grid_sz,grid_sz), (0,0), colspan=grid_sz, rowspan=grid_sz-1) plt.imshow(cell_labels, cmap='jet') self.mask_im = plt.imshow(cell_mask, cmap='gray') plt.title('Click to select a cell to track') plt.axis('off') button_ax = plt.subplot2grid((grid_sz,grid_sz ), (grid_sz-1,grid_sz//2)) self.done_button = plt.Button(button_ax, 'Done') self.done_button.on_clicked(self.on_button_press) self.cid = self.fig.canvas.mpl_connect('button_press_event', self.on_mouse_click) self.cell_labels = cell_labels self.selected_cell_labels = [] self.cell_mask = None # self.fig.canvas.start_event_loop(timeout=-1) plt.show()
def __init__(self): self.shuffleboard = nt_init() self.fig, self.axs = plot_init(sec_lim, 5) self.vel_lines, self.pos_lines = line_init(self.axs) self.btn = plt.Button(plt.axes([0.9, 0, 0.1, 0.075]), 'Pause') self.btn.on_clicked(self.btn_callback) self.tbs = get_all_text_boxes(self.axs) self.vel_ntd = [] self.pos_ntd = [] for line in self.vel_lines: self.vel_ntd.append(NTData(line)) for line in self.pos_lines: self.pos_ntd.append(NTData(line)) # Have to keep this var for graph to animate self.anim = animation.FuncAnimation(self.fig, self.check_animate, interval=wait_time * 1000) self.paused = False self.time_elapsed = 0 self.has_data = False plt.show() plt.pause(0)
def plot_epochs(epochs, epoch_idx=None, picks=None, n_chunks=20, title_str='#%003i', show=True, draw_discrete=None, discrete_colors=None, block=False): """ Visualize single trials using Trellis plot. Parameters ---------- epochs : instance of pyeparse.Epochs The epochs object epoch_idx : array-like | int | None The epochs to visualize. If None, the first 20 epochs are shown. Defaults to None. n_chunks : int The number of chunks to use for display. picks : array-like | None Channels to be included. If None only good data channels are used. Defaults to None lines : array-like | list of tuple Events to draw as vertical lines title_str : None | str | list-like The string formatting to use for axes titles. If None, no titles will be shown. Defaults expand to ``#001, #002, ...``. If list-like, must be of same length as epochs.events. show : bool Whether to show the figure or not. draw_discrete : {saccades, blinks, fixations} | list-like | None | The events to draw as vertical lines. discrete_colors: : list-like | None list of str or color objects with length of discrete events drawn. block : bool Whether to halt program execution until the figure is closed. Useful for rejecting bad trials on the fly by clicking on a sub plot. Returns ------- fig : Instance of matplotlib.figure.Figure The figure. """ import matplotlib.pyplot as mpl if np.isscalar(epoch_idx): epoch_idx = [epoch_idx] if epoch_idx is None: n_events = len(epochs.events) epoch_idx = range(n_events) else: n_events = len(epoch_idx) if picks is None: picks = np.arange(len(epochs.info['data_cols'])) elif all(p in epochs.ch_names for p in picks): # epochs.data does not include time ch_names = [ ch for ch in epochs.ch_names if ch in epochs.info['data_cols'] ] picks = [ch_names.index(k) for k in picks] elif any(p not in epochs.ch_names and isinstance(p, string_types) for p in picks): wrong = [p for p in picks if p not in epochs.ch_names] raise ValueError('Some channels are not defined: ' + '; '.join(wrong)) if len(picks) < 1: raise RuntimeError('No appropriate channels found. Please' ' check your picks') if discrete_colors is not None: if len(discrete_colors) != len(epochs.events): raise ValueError('The length of `discrete_colors` must equal ' 'the number of epochs.') times = epochs.times * 1e3 n_traces = len(picks) # preallocation needed for min / max scaling n_events = len(epochs.events) epoch_idx = epoch_idx[:n_events] idx_handler = deque(create_chunks(epoch_idx, n_chunks)) # handle bads this_idx = idx_handler[0] fig, axes = _prepare_trellis(len(this_idx), max_col=5) axes_handler = deque(range(len(idx_handler))) data = np.ma.masked_invalid(epochs.data[this_idx][:, picks]) if isinstance(draw_discrete, string_types): key = dict() for k in epochs.info['discretes']: key[k.strip('_')] = k key = key[draw_discrete] discretes = [ d['stime'] * 1e3 for d in vars(epochs)[key] if d is not None ] elif draw_discrete is None: discretes = None else: discretes = draw_discrete labelfontsize = 10 for i_ax, (ii, ax, data_) in enumerate(zip(this_idx, axes, data)): ax.plot(times, data_.T, color='k') ax.axvline(0.0, color='gray') vars(ax.lines[-1])['def-col'] = 'gray' n_disc_lines = 0 if discrete_colors is not None: color = discrete_colors[ii] else: color = 'orange' if discretes is not None: if discretes[ii] is not None: for here in discretes[ii]: ax.axvline(here, color=color, linestyle='--') n_disc_lines += 1 vars(ax.lines[-1])['def-col'] = color if title_str is not None: _set_title(ax, title_str, ii) ax.set_ylim(data.min(), data.max()) if i_ax % 5: [l.set_visible(0) for l in ax.get_yticklabels()] else: [l.set_fontsize(labelfontsize) for l in ax.get_yticklabels()] if i_ax < len(this_idx) - 5: [l.set_visible(0) for l in ax.get_xticklabels()] else: [l.set_fontsize(labelfontsize) for l in ax.get_xticklabels()] labels = ax.get_xticklabels() mpl.setp(labels, rotation=45) vars(ax)[axes_handler[0]] = { 'idx': ii, 'reject': False, 'n_disc_lines': n_disc_lines } # XXX find smarter way to to tight layout for incomplete plots # fig.tight_layout() # initialize memory for this_view, this_inds in zip(axes_handler, idx_handler): if this_view > 0: # all other views than the current one for ii, ax in enumerate(axes): vars(ax)[this_view] = { 'idx': ii, 'reject': False, 'n_disc_lines': 0 } navigation = figure_nobar(figsize=(3, 1.5)) from matplotlib import gridspec gs = gridspec.GridSpec(2, 2) ax1 = mpl.subplot(gs[0, 0]) ax2 = mpl.subplot(gs[0, 1]) ax3 = mpl.subplot(gs[1, :]) params = { 'fig': fig, 'idx_handler': idx_handler, 'epochs': epochs, 'n_traces': n_traces, 'picks': picks, 'times': times, 'axes': axes, 'back': mpl.Button(ax1, 'back'), 'next': mpl.Button(ax2, 'next'), 'reject-quit': mpl.Button(ax3, 'reject-quit'), 'title_str': title_str, 'reject_idx': [], 'axes_handler': axes_handler, 'discretes': discretes, 'discrete_colors': discrete_colors, } fig.canvas.mpl_connect('button_press_event', partial(_epochs_axes_onclick, params=params)) navigation.canvas.mpl_connect( 'button_press_event', partial(_epochs_navigation_onclick, params=params)) mpl.show(block=block) if show else None return fig
def make_button(self, rect, label, on_click): button_axes = plt.axes(rect) button = plt.Button(button_axes, label) button.on_clicked(lambda _mpl_event: on_click()) self._buttons.append(button)
text = ax.text(0, largeur - 200, "") fig.canvas.draw() axbackground = fig.canvas.copy_from_bbox(ax.bbox) elif match_test.disp == 1: fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(-longueur, longueur) ax.set_ylim(-largeur, largeur) text = ax.text(0, largeur - 200, "") axbackground = fig.canvas.copy_from_bbox(ax.bbox) fig.canvas.draw() frame = 0 axButton1 = plt.axes([0.25, 0.45, 0.1, 0.1]) btn1 = plt.Button( axButton1, label='Quebec', color='lightgrey', hovercolor='greenyellow' ) #definiton du bouton(position par rapport à la figure "ax",label,couleur, couleur lorsque la souris passe au dessus) btn1.label.set_fontsize(20) #modification de la taille du label t_list = [time.time()] def t_update(t_list): t_list.append(time.time()) if len(t_list) > 30: t_list.pop(0) return (t_list) def q(): print('qq')
def select_epochs(folder, overWrite=False): # Find test set with most uniform covering of speed and environment variable. # provides then a little manual tool to change the size of the window # and its position. if not os.path.exists(folder + 'nnBehavior.mat'): raise ValueError('this file does not exist :' + folder + 'nnBehavior.mat') with tables.open_file(folder + 'nnBehavior.mat', "a") as f: children = [c.name for c in f.list_nodes("/behavior")] if overWrite == False and "trainEpochs" in children and "testEpochs" in children: return # Get info from the file speedMask = f.root.behavior.speedMask[:] positions = f.root.behavior.positions positions = np.swapaxes(positions[:, :], 1, 0) speeds = f.root.behavior.speed positionTime = f.root.behavior.position_time positionTime = np.swapaxes(positionTime[:, :], 1, 0) speeds = np.swapaxes(speeds[:, :], 1, 0) if speeds.shape[0] == positionTime.shape[0] - 1: speeds = np.append(speeds, speeds[-1]).reshape(positionTime.shape[0], speeds.shape[1]) #We extract session names: sessionNames = [ "".join([chr(c) for c in l[0][:, 0]]) for l in f.root.behavior.SessionNames[:, 0] ] if sessionNames[0] != 'Recording': IsMultiSessions = True sessionNames = [ "".join([chr(c) for c in l[0][:, 0]]) for l in f.root.behavior.SessionNames[:, 0] ] sessionStart = f.root.behavior.SessionStart[:, :][:, 0] sessionStop = f.root.behavior.SessionStop[:, :][:, 0] else: IsMultiSessions = False sessionValue = np.zeros(speedMask.shape[0]) if IsMultiSessions: for k in range(len(sessionNames)): sessionValue[ep.inEpochs( positionTime[:, 0], [sessionStart[k], sessionStop[k]])] = k # Select the representative behavior without sleeps to show epochToShow = [] if IsMultiSessions: sleep_list = [ re.search('sleep', sessionNames[x], re.IGNORECASE) for x in range(len(sessionNames)) ] id_sleep = [ x for x in range(len(sleep_list)) if sleep_list[x] != None ] if id_sleep: all_id = set(range(len(sessionNames))) id_toshow = list( all_id.difference(id_sleep)) # all except sleeps for id in id_toshow: epochToShow.extend([sessionStart[id], sessionStop[id]]) else: epochToShow.extend([ positionTime[0, 0], positionTime[-1, 0] ]) # if no sleeps, or session names, or hab take everything maskToShow = ep.inEpochsMask(positionTime[:, 0], epochToShow) behToShow = positions[maskToShow, :] timeToShow = positionTime[maskToShow, 0] sessionValue_toshow = sessionValue[maskToShow] if IsMultiSessions: SessionNames_toshow = [sessionNames[i] for i in id_toshow] ### Get times of show if IsMultiSessions: if id_sleep[0] == 0: # if sleep goes first get the end of it ids = np.where(sessionValue == id_sleep[0])[0] st = positionTime[ids[-1] + 1] for i in id_sleep[1:]: ids = np.where(sessionValue == i)[0] st = np.append( st, (positionTime[ids[0]], positionTime[ids[-1]])) if st[-1] != positionTime[-1]: st = np.append(st, positionTime[-1]) else: st = st[:-1] else: # if it starts with maze st = positionTime[0] for i in id_sleep: ids = np.where(sessionValue == i)[0] st = np.append( st, (positionTime[ids[0]], positionTime[ids[-1]])) if st[-1] != positionTime[-1]: st = np.append(st, positionTime[-1]) else: st = st[:-1] assert (st.shape[0] % 2 == 0) showtimes = tuple(zip(st[::2], st[1::2])) # Default train and test sets sizeTest = timeToShow.shape[0] // 10 testSetId = timeToShow.shape[0] - timeToShow.shape[0] // 10 bestTestSet = 0 useLossPredTrainSet = True lossPredSetId = 0 sizelossPredSet = timeToShow.shape[0] // 10 SetData = { 'sizeTest': sizeTest, 'testsetId': testSetId, 'bestTestSet': bestTestSet, 'useLossPredTrainSet': useLossPredTrainSet, 'lossPredSetId': lossPredSetId, 'sizelossPredSet': sizelossPredSet } #### Next we provide a tool to manually change the bestTest set position # as well as its size: # Cut the cmap to avoid black colors min_val, max_val = 0.3, 1.0 n = 20 cmap = plt.get_cmap("nipy_spectral") colors = cmap(np.linspace(min_val, max_val, n)) cmSessValue = mplt.colors.LinearSegmentedColormap.from_list( "mycmap", colors) colorSess = cmSessValue( np.arange(len(sessionNames)) / (len(sessionNames))) keptSession = np.zeros(len(colorSess)) + 1 # a mask for the session if IsMultiSessions: keptSession[id_sleep] = 0 fig = plt.figure() gs = plt.GridSpec(positions.shape[1] + 5, max(len(colorSess), 2), figure=fig) if IsMultiSessions: ax = [ fig.add_subplot(gs[id, :]) for id in range(positions.shape[1]) ] #ax for feature display ax[0].get_shared_x_axes().join(ax[0], ax[1]) # ax = [brokenaxes(xlims=showtimes, subplot_spec=gs[id,:]) for id in range(positions.shape[1])] #ax for feature display else: ax = [ fig.add_subplot(gs[id, :]) for id in range(positions.shape[1]) ] #ax for feature display ax[0].get_shared_x_axes().join(ax[0], ax[1]) ax += [fig.add_subplot(gs[-5, id]) for id in range(len(sessionNames))] ax += [ fig.add_subplot(gs[-4, max(len(colorSess) - 3, 1):max(len(colorSess), 2)]) ] ax += [ fig.add_subplot(gs[-4, 0:max(len(colorSess) - 4, 1)]), fig.add_subplot(gs[-3, :]) ] #loss pred training set slider ax += [fig.add_subplot(gs[-2, :]), fig.add_subplot(gs[-1, :])] #test set. if IsMultiSessions: trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs( timeToShow, SetData, keptSession, starts=sessionStart, stops=sessionStop) else: trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs( timeToShow, SetData, keptSession) ls = [] for dim in range(positions.shape[1]): l1 = ax[dim].scatter( timeToShow[ep.inEpochs(timeToShow, trainEpoch)[0]], behToShow[ep.inEpochs(timeToShow, trainEpoch)[0], dim], c="red", s=0.5) l2 = ax[dim].scatter( timeToShow[ep.inEpochs(timeToShow, testEpochs)[0]], behToShow[ep.inEpochs(timeToShow, testEpochs)[0], dim], c="black", s=0.5) if SetData['useLossPredTrainSet']: l3 = ax[dim].scatter( timeToShow[ep.inEpochs(timeToShow, lossPredSetEpochs)[0]], behToShow[ep.inEpochs(timeToShow, lossPredSetEpochs)[0], dim], c="orange", s=0.5) else: l3 = ax[dim].scatter(timeToShow[0], behToShow[0, dim], c='orange', s=0.5) ls.append([l1, l2, l3]) # display the sessions positions at the bottom: if IsMultiSessions: for idk, k in enumerate(id_toshow): if len(np.where(np.equal(sessionValue_toshow, k))[0]) > 0: ax[id].hlines(np.min(behToShow[ np.logical_not(np.isnan(behToShow[:, dim])), dim]) - np.std(behToShow[ np.logical_not(np.isnan(behToShow[:, dim])), dim]), xmin=timeToShow[np.min( np.where( np.equal(sessionValue_toshow, k)))], xmax=timeToShow[np.max( np.where( np.equal(sessionValue_toshow, k)))], color=colorSess[idk], linewidth=3.0) #TODO add histograms here... slider = plt.Slider(ax[-2], 'test starting index', 0, behToShow.shape[0] - SetData['sizeTest'], valinit=SetData['testsetId'], valstep=1) sliderSize = plt.Slider(ax[-1], 'test size', 0, behToShow.shape[0], valinit=SetData['sizeTest'], valstep=1) if SetData['useLossPredTrainSet']: buttLossPred = plt.Button(ax[-5], "lossPred", color="orange") else: buttLossPred = plt.Button(ax[-5], "lossPred", color="white") sliderLossPredTrain = plt.Slider( ax[-4], "loss network training \n set starting index", 0, behToShow.shape[0], valinit=0, valstep=1) sliderLossPredTrainSize = plt.Slider(ax[-3], "loss network training set size", 0, behToShow.shape[0], valinit=SetData['sizeTest'], valstep=1) # Next we add buttons to select the sessions we would like to keep: butts = [ plt.Button(ax[len(ax) - k - 6], sessionNames[k], color=colorSess[k]) for k in range(len(colorSess)) ] if IsMultiSessions: for id in id_sleep: ax[len(ax) - id - 6].set_axis_off() def update(val): SetData['testsetId'] = slider.val SetData['sizeTest'] = sliderSize.val SetData['lossPredSetId'] = sliderLossPredTrain.val SetData['sizelossPredSet'] = sliderLossPredTrainSize.val if IsMultiSessions: trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs( timeToShow, SetData, keptSession, starts=sessionStart, stops=sessionStop) else: trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs( timeToShow, SetData, keptSession) for dim in range(len(ls)): l1, l2, l3 = ls[dim] if isinstance(l1, list): for iaxis in range(len(l1)): l1[iaxis].set_offsets( np.transpose( np.stack([ timeToShow[ep.inEpochs( timeToShow, trainEpoch)[0]], behToShow[ ep.inEpochs(timeToShow, trainEpoch)[0], dim] ]))) l2[iaxis].set_offsets( np.transpose( np.stack([ timeToShow[ep.inEpochs( timeToShow, testEpochs)[0]], behToShow[ ep.inEpochs(timeToShow, testEpochs)[0], dim] ]))) if SetData['useLossPredTrainSet']: try: ls[dim][2][iaxis].remove() # l3[iaxis].remove() except: pass else: try: ls[dim][2][iaxis].remove() # l3[iaxis].remove() except: pass if SetData['useLossPredTrainSet']: ls[dim][2] = ax[dim].scatter( timeToShow[ep.inEpochs(timeToShow, lossPredSetEpochs)[0]], behToShow[ ep.inEpochs(timeToShow, lossPredSetEpochs)[0], dim], c="orange", s=0.5) else: l1.set_offsets( np.transpose( np.stack([ timeToShow[ep.inEpochs(timeToShow, trainEpoch)[0]], behToShow[ ep.inEpochs(timeToShow, trainEpoch)[0], dim] ]))) l2.set_offsets( np.transpose( np.stack([ timeToShow[ep.inEpochs(timeToShow, testEpochs)[0]], behToShow[ ep.inEpochs(timeToShow, testEpochs)[0], dim] ]))) if SetData['useLossPredTrainSet']: try: ls[dim][2].remove() except: pass ls[dim][2] = ax[dim].scatter( timeToShow[ep.inEpochs(timeToShow, lossPredSetEpochs)[0]], behToShow[ ep.inEpochs(timeToShow, lossPredSetEpochs)[0], dim], c="orange", s=0.5) else: try: l3.remove() except: pass fig.canvas.draw_idle() slider.on_changed(update) sliderSize.on_changed(update) sliderLossPredTrain.on_changed(update) sliderLossPredTrainSize.on_changed(update) def buttUpdate(id): def buttUpdate(val): if keptSession[id]: butts[id].color = [0, 0, 0, 0] keptSession[id] = 0 else: keptSession[id] = 1 butts[id].color = colorSess[id] update(0) return buttUpdate [b.on_clicked(buttUpdate(id)) for id, b in enumerate(butts)] def buttUpdateLossPred(val): if SetData['useLossPredTrainSet']: buttLossPred.color = [0, 0, 0, 0] SetData['useLossPredTrainSet'] = False else: SetData['useLossPredTrainSet'] = True buttLossPred.color = "orange" update(0) return SetData['useLossPredTrainSet'] buttLossPred.on_clicked(buttUpdateLossPred) suptitle_str = 'Please choose train and test sets. You can include validation set' plt.suptitle(suptitle_str, fontsize=22) plt.get_current_fig_manager().window.showMaximized() plt.show() testSetId = slider.val sizeTest = sliderSize.val lossPredSetId = sliderLossPredTrain.val sizelossPredSet = sliderLossPredTrainSize.val if IsMultiSessions: trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs( timeToShow, SetData, keptSession, starts=sessionStart, stops=sessionStop) else: trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs( timeToShow, SetData, keptSession) if "testEpochs" in children: f.remove_node("/behavior", "testEpochs") f.create_array("/behavior", "testEpochs", testEpochs) if "trainEpochs" in children: f.remove_node("/behavior", "trainEpochs") f.create_array("/behavior", "trainEpochs", trainEpoch) if "keptSession" in children: f.remove_node("/behavior", "keptSession") f.create_array("/behavior", "keptSession", keptSession) if "lossPredSetEpochs" in children: f.remove_node("/behavior", "lossPredSetEpochs") if SetData['useLossPredTrainSet']: f.create_array("/behavior", "lossPredSetEpochs", lossPredSetEpochs) else: f.create_array("/behavior", "lossPredSetEpochs", []) f.flush() #effectively write down the modification we just made fig, ax = plt.subplots() trainMask = ep.inEpochsMask(positionTime, trainEpoch)[:, 0] testMask = ep.inEpochsMask(positionTime, testEpochs)[:, 0] ax.scatter(positionTime[trainMask], positions[trainMask, 0], c="red") ax.scatter(positionTime[testMask], positions[testMask, 0], c="black") if SetData['useLossPredTrainSet']: lossPredMask = ep.inEpochsMask(positionTime, lossPredSetEpochs)[:, 0] ax.scatter(positionTime[lossPredMask], positions[lossPredMask, 0], c="orange") fig.show()
def __init__(self, doneCallback, skipCallback, dumpCallback, exitCallback, prevCallback, background, MAX_PROMINENCE=6.0, FALSE_MAXIMUM_ROW_DISTANCE = 30): self.MAX_PROMINENCE = MAX_PROMINENCE self.FALSE_MAXIMUM_ROW_DISTANCE = FALSE_MAXIMUM_ROW_DISTANCE self.doneCallback = doneCallback self.skipCallback = skipCallback self.dumpCallback = dumpCallback self.exitCallback = exitCallback self.prevCallback = prevCallback self.fig = plt.figure() self.ax = self.fig.add_subplot(111) self.background = background self.ax.set_xlabel("Time") self.ax.set_ylabel("Voltage") self.titleColor = 'black' self.ax.name = 'main' self.fig.subplots_adjust(bottom=0.27, top=0.92, left=0.08, right=0.94) # Define an axes area and draw a slider in it min_prom_slider_ax = self.fig.add_axes([0.25, 0.17, 0.65, 0.03]) self.min_prom_slider = plt.Slider(min_prom_slider_ax, 'Min. Prom.', 0.0, MAX_PROMINENCE, valinit=MAX_PROMINENCE) # Draw another slider max_prom_slider_ax = self.fig.add_axes([0.25, 0.12, 0.65, 0.03]) self.max_prom_slider = plt.Slider(max_prom_slider_ax, 'Max. Prom.', 0.0, MAX_PROMINENCE, valinit=MAX_PROMINENCE) self.min_prom_slider.on_changed(self.updateProminence) self.max_prom_slider.on_changed(self.updateProminence) self.doneButtonTitle = 'Done' doneButtonAxes = plt.axes([0.80, 0.05, 0.1, 0.045]) self.doneButton = plt.Button(doneButtonAxes, self.doneButtonTitle) self.doneButton.on_clicked(self.done) resetBtn = plt.axes([0.69, 0.05, 0.1, 0.045]) self.resetButton = plt.Button(resetBtn, 'Auto') self.resetButton.on_clicked(self.reset) skipButtonAxes = plt.axes([0.58, 0.05, 0.1, 0.045]) self.skipButton = plt.Button(skipButtonAxes, 'Skip') self.skipButton.on_clicked(self.skip) dumpButtonAxes = plt.axes([0.47, 0.05, 0.1, 0.045]) self.dumpButton = plt.Button(dumpButtonAxes, 'Dump') self.dumpButton.on_clicked(self.dump) clearButtonAxes = plt.axes([0.36, 0.05, 0.1, 0.045]) self.clearButton = plt.Button(clearButtonAxes, 'Clear') self.clearButton.on_clicked(self.clear) prevButtonAxes = plt.axes([0.25, 0.05, 0.1, 0.045]) self.prevButton = plt.Button(prevButtonAxes, 'Prev') self.prevButton.on_clicked(self.prev) exitButtonAxes = plt.axes([0.14, 0.05, 0.1, 0.045]) self.exitButton = plt.Button(exitButtonAxes, 'Exit') self.exitButton.on_clicked(self.exit) self.fig.canvas.mpl_connect('button_press_event', self.onclick)
record = "{} {} {} {}".format(date_t, date_hr, t, float(data_list[0])) print(record) record = [date_t, date_hr, t, float(data_list[0])] with open("sample.csv", "a", newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(record) if len(ysA) > 100: ysA = ysA[101:] timePoint = timePoint[101:] axes.clear() axes.set(title='PM2.5 Conc.') # 設子圖title axes.set_ylim(0, 3500) #設定y軸範圍 axes.grid(True) axes.plot(timePoint, ysA, label="PM2.5 value") axes.legend() ani = animation.FuncAnimation(fig, anima, interval=duration) rax1 = plt.axes([0.75, 0.02, 0.13, 0.15], frameon=True) #[水平 垂直 寬 高] [往右 往上] frameon 顯示 rax2 = plt.axes([0.55, 0.02, 0.13, 0.15], frameon=True) button_on = plt.Button(rax1, "ON") button_off = plt.Button(rax2, "OFF") button_on.on_clicked(send_on) button_off.on_clicked(send_off) plt.show()
def verify_linearization(self, ExampleEuclideanData, folder, overwrite=False): ## A function to verify and possibly change the linearization. # Auxiliary def try_linearization(ax, l0s): _, linearTrue = self.apply_linearization(euclidData) binIndex = [ np.where((linearTrue >= projBin[id]) * (linearTrue < projBin[id + 1]))[0] for id in range(len(projBin) - 1) ] cm = plt.get_cmap("tab20") for tpl in enumerate(binIndex): id, bId = tpl try: l0s[id].remove() except: None l0s[id] = ax[0].scatter(euclidData[bId, 0], euclidData[bId, 1], c=[cm(id)]) return l0s def b1update(n): self.nnPoints = [[0.45, 0.40], [0.45, 0.65], [0.45, 0.9], [0.7, 0.9], [0.9, 0.9], [0.9, 0.7], [0.9, 0.4]] # create the interpolating object ts = np.arange(0, stop=1, step=1 / np.array(self.nnPoints).shape[0]) itpObject = itp.make_interp_spline(ts, np.array(self.nnPoints), k=2) self.tsProj = np.arange(0, stop=1, step=1 / 100) self.mazePoints = itpObject(self.tsProj) try: self.lPoints.remove() fig.canvas.draw() except: pass self.l0s = try_linearization(ax, self.l0s) self.lPoints = ax[0].scatter(np.array(self.nnPoints)[:, 0], np.array(self.nnPoints)[:, 1], c="black") fig.canvas.draw() def b2update(n): if len(self.nnPoints) > 0: self.nnPoints = self.nnPoints[0:len(self.nnPoints) - 1] # create the interpolating object ts = np.arange(0, stop=1, step=1 / np.array(self.nnPoints).shape[0]) itpObject = itp.make_interp_spline(ts, np.array(self.nnPoints), k=2) self.tsProj = np.arange(0, stop=1, step=1 / 100) self.mazePoints = itpObject(self.tsProj) self.lPoints.remove() fig.canvas.draw() if (len(self.nnPoints) > 2): self.l0s = try_linearization(ax, self.l0s) else: self.l0s[1] = ax[0].scatter(euclidData[:, 0], euclidData[:, 1], c="blue") self.lPoints = ax[0].scatter(np.array(self.nnPoints)[:, 0], np.array(self.nnPoints)[:, 1], c="black") fig.canvas.draw() def b3update(n): if len(self.nnPoints) > 0: self.nnPoints = [] self.lPoints.remove() self.l0s[1] = ax[0].scatter(euclidData[:, 0], euclidData[:, 1], c="blue") fig.canvas.draw() def onclick(event): if event.inaxes == self.l0s[1].axes: self.nnPoints += [[event.xdata, event.ydata]] try: self.lPoints.remove() fig.canvas.draw() except: pass if (len(self.nnPoints) > 2): # create the interpolating object ts = np.arange(0, stop=1, step=1 / np.array(self.nnPoints).shape[0]) itpObject = itp.make_interp_spline(ts, np.array(self.nnPoints), k=2) self.tsProj = np.arange(0, stop=1, step=1 / 100) self.mazePoints = itpObject(self.tsProj) self.l0s = try_linearization(ax, self.l0s) else: self.l0s[1] = ax[0].scatter(euclidData[:, 0], euclidData[:, 1], c="blue") self.lPoints = ax[0].scatter(np.array(self.nnPoints)[:, 0], np.array(self.nnPoints)[:, 1], c="black") fig.canvas.draw() # Check existence of linearized data with tables.open_file(folder + 'nnBehavior.mat', "a") as f: children = [c.name for c in f.list_nodes("/behavior")] if "linearizationPoints" in children: print("Linearization points have been created before") if overwrite: f.remove_node("/behavior", "speedMask") print("Overwriting linearization") else: return # Body euclidData = ExampleEuclideanData[np.logical_not( np.isnan(np.sum(ExampleEuclideanData, axis=1))), :] #down sample a bit euclidData = euclidData[1:-1:10, :] projBin = np.arange(0, stop=1.2, step=0.2) self.l0s = [None for _ in projBin] # Figure fig = plt.figure() gs = plt.GridSpec(3, 2, figure=fig) ax = [ fig.add_subplot(gs[:, 0]), fig.add_subplot(gs[0, 1]), fig.add_subplot(gs[1, 1]), fig.add_subplot(gs[2, 1]) ] self.l0s = try_linearization(ax, self.l0s) self.lPoints = ax[0].scatter(np.array(self.nnPoints)[:, 0], np.array(self.nnPoints)[:, 1], c="black") ax[0].set_aspect(1) b1 = plt.Button(ax[1], "reset", color="grey") b1.on_clicked(b1update) b2 = plt.Button(ax[2], "remove last", color="orange") b2.on_clicked(b2update) b3 = plt.Button(ax[3], "empty", color="red") b3.on_clicked(b3update) # Next we obtain user click to create a new set of linearization points [a.set_aspect(1) for a in ax] fig.canvas.mpl_connect('button_press_event', onclick) plt.show() # create the interpolating object ts = np.arange(0, stop=1, step=1 / np.array(self.nnPoints).shape[0]) itpObject = itp.make_interp_spline(ts, np.array(self.nnPoints), k=2) self.tsProj = np.arange(0, stop=1, step=1 / 100) self.mazePoints = itpObject(self.tsProj) # plot the exact linearization variable: _, linearTrue = self.apply_linearization(euclidData) cm = plt.get_cmap("Spectral") fig, ax = plt.subplots() ax.scatter(euclidData[:, 0], euclidData[:, 1], c=cm(linearTrue)) ax.set_title("Linearization variable, Spectral colormap") plt.show() # Save f.create_array("/behavior", "linearizationPoints", self.nnPoints) f.flush() f.close()
import numpy as np arduinoSerialData = serial.Serial('/dev/ttyS8',115200) #Create Serial port object called arduinoSerialData def ppause(event): pass n=0 Datalist = np.zeros(5000) fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot(Datalist) ax.set_ylim(0,5000) axpause = plt.axes([0.7, 0.05, 0.1, 0.075]) bpause = plt.Button(axpause, 'Pause') bpause.on_clicked(ppause) while (n<=10000): if (arduinoSerialData.inWaiting()>0): myData = arduinoSerialData.readline() # print(myData) try: A1 = myData.decode('utf-8').rstrip('\r\n').split(" ")[1] Datalist = np.append(Datalist[1:], float(A1)) line.set_ydata(Datalist) except: pass plt.pause(0.05) n=n+1
sL1.on_changed(updateButton) sL2.on_changed(updateButton) sL3.on_changed(updateButton) sZ4.on_changed(updateButton) sXPOS.on_changed(updateButton) sXSC.on_changed(updateButton) sATT.on_changed(updateButton) sPHI.on_changed(updateButton) sFreq.on_changed(updateButton) sLOOP.on_changed(updateButton) sALP.on_changed(updateButton) sWb.on_changed(updateButton) # --- Buttons prFitxB = plt.axes([0.35, 0.025, 0.1, 0.04]) button5 = plt.Button(prFitxB, 'PreFit', color=axcolor, hovercolor='0.975') button5.on_clicked(preFitButton) mXaxB = plt.axes([0.25, 0.025, 0.1, 0.04]) button4 = plt.Button(mXaxB, 'MatchX', color=axcolor, hovercolor='0.975') button4.on_clicked(matchXaxis) fitDaB = plt.axes([0.15, 0.025, 0.1, 0.04]) button3 = plt.Button(fitDaB, 'Fit', color=axcolor, hovercolor='0.975') button3.on_clicked(fitcurve) updatetax = plt.axes([0.05, 0.025, 0.1, 0.04]) button2 = plt.Button(updatetax, 'Update', color=axcolor, hovercolor='0.975') button2.on_clicked(update2) fig3.show() # --- Interface End
def cb_save_reg_file(self): global final_x_res_list global final_y_res_list global x_key global y_key global mouse_key #winreg.SaveKey(mouse_key,'C:\\Users\\Keegan\\Downloads\\reg_stuff\\src\\uh.reg') encode_reg(final_x_res_list, final_y_res_list) decode_reg(x_key, x_res_list) decode_reg(y_key, y_res_list) fig.canvas.mpl_connect('pick_event', onpick) fig.canvas.mpl_connect('motion_notify_event', onmotion) fig.canvas.mpl_connect('button_release_event', onrelease) plt.rc('figure', figsize=(10, 5)) interp_and_draw(np.asarray(x_res_list), np.asarray(y_res_list)) ax_save = plt.axes([0.81, 0.05, 0.1, 0.075]) butt_save = plt.Button(ax_save, 'Save') butt_save.on_clicked(cb_save_reg_file) plt.show()
fig.delaxes(cbar) cbar = map.colorbar(cs, location='bottom', pad="5%") cbar.set_label('mm') # ------------------------------ # build map fig = plt.figure() title_string = "Earthquakes of Magnitude 2.0 or Greater\n" # title_string += "%s through %s" % (times[-1][:10], times[0][:10]) plt.title(title_string) ax1 = fig.add_subplot(111) cbar = None build_map(9) #------------------------------- # save one plot to png plt.savefig('firstImage.png') # ------------------------------ # button load file ax = plt.axes([0, 0.9, 0.1, 0.1]) b = plt.Button(ax, "Load") b.on_clicked(button_on_clicked) plt.show()