class verifier: def __init__(self, original, distorted): if (original.shape != distorted.shape): print( 'verifier.verifier: the original and distorted image arrays ' + 'must have the same dimensions.', sys.stderr) sys.exit(-1) self.orig_arr = original self.dist_arr = distorted self.total_images = original.shape[2] # Let's set up image display gear self.fig, self.ax = plt.subplots(1, 2, figsize=(10, 7)) plt.subplots_adjust(bottom=0.3) self.current_slice = 1000 self.ax[0].imshow(self.orig_arr[:, :, self.current_slice]) self.ax[1].imshow(self.dist_arr[:, :, self.current_slice]) img_no_pos = plt.axes([0.48, 0.1, 0.06, 0.1]) # x, y, w, h self.img_tbox = TextBox(img_no_pos, 'Image No.: ', initial=str(self.current_slice)) def _update(self, val): self.current_slice = int(val) self.ax[0].imshow(self.orig_arr[:, :, self.current_slice]) self.ax[1].imshow(self.dist_arr[:, :, self.current_slice]) self.fig.canvas.draw_idle() def initialize(self): self.img_tbox.on_submit(self._update)
def TryTextBox2(): #https://matplotlib.org/3.1.1/gallery/widgets/textbox.html import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import TextBox fig = plt.figure(figsize=[5, 5], constrained_layout=True) gs = GridSpec(2, 1, figure=fig) ax_plot = fig.add_subplot(gs[1, 0]) plt.subplots_adjust(bottom=0.2) t = np.arange(-2.0, 2.0, 0.001) s = t**2 initial_text = "t ** 2" l, = plt.plot(t, s, lw=2) def submit(text): t = np.arange(-2.0, 2.0, 0.001) print(text) ydata = eval(text) l.set_ydata(ydata) ax_plot.set_ylim(np.min(ydata), np.max(ydata)) plt.draw() ax_gs = fig.add_subplot(gs[0, 0]) textbox_raw_min = TextBox(ax_gs, "x min: ", initial="10") textbox_raw_min.on_submit(submit) # axbox = plt.axes([0.1, 0.05, 0.8, 0.075]) # text_box = TextBox(axbox, 'Evaluate', initial=initial_text) # text_box.on_submit(submit) plt.show() return textbox_raw_min
def show_diagram(cursor, l, n, sel_type): sql = f""" SELECT iteration, pairwise_hamming_distribution_p, wild_type_hamming_distribution_p, ideal_hamming_distribution_p FROM task2_full_v1 WHERE L={l} AND N={n} AND sel_type='{sel_type}' AND run_id=0 ORDER BY iteration """ cursor.execute(sql) rows = cursor.fetchall() hist = np.array([row[1] for row in rows]) hist2 = np.array([row[2] for row in rows]) hist3 = np.array([row[3] for row in rows]) fig, (ax1, ax2, ax3) = plt.subplots(3, 1) barcollection = ax1.bar(range(l), hist[0]) barcollection2 = ax2.bar(range(l), hist2[0]) barcollection3 = ax3.bar(range(l), hist3[0]) axcut = plt.axes([0.1, 0.9, 0.1, 0.075]) tcut = TextBox(axcut, 'Iter:', '0') axcut2 = plt.axes([0.25, 0.9, 0.1, 0.06]) bcut = Button(axcut2, 'Run') def simData(): global it while it < len(rows): if not pause: it += 1 yield it def onClick(event): bcut.label.set_text('Stop') tcut.stop_typing() global pause pause ^= True def simPoints(it): if not pause: tcut.set_val(str(it)) for i, (b, b1, b2) in enumerate(zip(barcollection, barcollection2, barcollection3)): b.set_height(hist[it, i]) b1.set_height(hist2[it, i]) b2.set_height(hist3[it, i]) # return barcollection def change_it(event): global it it = int(event) tcut.on_submit(change_it) bcut.on_clicked(onClick) fig.set_size_inches(18.5, 10.5) ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=10, repeat=True) plt.show()
def addTextBox(self, label, submitHandler, loc=(0.8, 0.0, 0.1, 0.07), **kwargs): """Add a text box to the plot. Parameters ---------- label : str Label for the button. submitHandler Submit handler to assign. loc : list(float), len 4 Left, bottom, width, height. kwargs All other arguments passed to :class:`matplotlib.widgets.TextBox`. Returns ------- matplotlotlib.widgets.TextBox """ self.checkInteractive() txtBoxAx = self.fig.add_axes(loc) txtBox = TextBox(txtBoxAx, label, **kwargs) txtBox.on_submit(lambda e: submitHandler(e, self)) self.txtBoxStore.append(txtBox) return txtBox
def _set_buttons(self, enable_reset, enable_save, enable_io): reset_button = Button(plt.axes([0.51, 0.01, 0.1, 0.035]), 'Reset') # [0.88, 0.01, 0.1, 0.035] reset_button.label.set_color('r') reset_button.label.set_fontweight('bold') reset_button.on_clicked(self._reset) if enable_reset: reset_button.set_active(True) else: reset_button.set_active(False) reset_button.ax.set_visible(False) textbox = TextBox( plt.axes([0.2, 0.06, 0.6, 0.095]), 'I/O', initial='' ) # [0.12, 0.01, 0.65, 0.06] [0.05,0.92,0.8,0.07] [0.025, 0.885, 0.75, 0.05] textbox.label.set_fontweight('bold') textbox.on_submit(self._evaluate_message) if enable_io: textbox.set_active(True) else: textbox.set_active(False) textbox.ax.set_visible(False) save_button = Button(plt.axes([0.39, 0.01, 0.1, 0.035]), 'Save') # [0.77, 0.01, 0.1, 0.035] save_button.label.set_fontweight('bold') save_button.on_clicked(self._quicksave) if enable_save: save_button.set_active(True) else: save_button.set_active(False) save_button.ax.set_visible(False) self._widgetlist[self.fignum.index(plt.gcf().number)] = (reset_button, textbox, save_button) self._textbox = textbox
class FrontEnd: def __init__(self, m): self.methods = m self.fig, self.ax = plt.subplots() plt.subplots_adjust(bottom=0.2) tbbox = plt.axes([0.1, 0.05, 0.8, 0.075]) self.tb = TextBox(tbbox, 'Шаги', initial='25') self.tb.on_submit(self.redraw) def show(self): self.redraw('25') plt.show() def redraw(self, steps_raw): # plt.xkcd() self.ax.cla() self.ax.set_xlim([0, 1]) self.ax.set_ylim([-1, 1]) try: steps = int(steps_raw) except ValueError: return for m in self.methods: s = m.ret_plot(steps) self.ax.plot(s[0], s[1], color=m.color, label=m.name) plt.draw() self.ax.legend()
def init_figure(): fig = plt.figure() for y in range(3): for x in range(3): cell = fig.add_subplot(3, 3, xy_to_row(x, y) + 1) cell.tick_params(labelbottom=False, labelleft=False) cell.tick_params(bottom=False, left=False) viewText = (xy_to_row(x, y) + 1) cell.text(0.35, 0.35, viewText, size=40, color="blue") cells.append(cell) axbox = plt.axes([0.4, 0.01, 0.4, 0.075]) global text_box text_box = TextBox(axbox, 'Trun ○ input number!') text_box.on_submit(submit) #先手の○を敵にする global nowTurn state = dizitize_state(board_status) action = np.argmax(qtable[state]) canput = put_piece(action) nowTurn = (nowTurn + 1) % 2 while canput == False: reward = -1000 action, state = q_enemy(board_status, state, action, reward, 0) canput = put_piece(action) nowTurn = (nowTurn + 1) % 2 plt.show()
def add_text_box(self, plt, rect, label, initial_value, callback): text_box = TextBox(plt.axes(rect), label, initial=initial_value, color=self.color, hovercolor=self.color) text_box.on_submit(callback) return text_box
def name_from_user(self): def submit(text): plt.close() self.name = text axbox = plt.axes([0.1, 0.05, 0.8, 0.075]) text_box = TextBox(axbox, 'Name: ', initial="") text_box.on_submit(submit) plt.show()
class AltitudeGUI(): alt = [] ts = [] def __init__(self, master): master.columnconfigure(0,weight=1) master.rowconfigure(1,weight=1) self.master = master self.master.title("Attitude Tester") self.master.geometry('800x600') self.master.attributes("-zoomed", False) self.createGraph() self.plotGraph(1) self.master.bind("<Escape>", self.end_fullscreen) def end_fullscreen(self, event=None): self.state = False sys.exit() def createGraph(self): self.frame = Frame(self.master) self.frame.grid(column=0,row=1,columnspan=4, rowspan=3, sticky=N+W+E+S) self.f = Figure( figsize=(8, 7), dpi=80 ) self.ax0 = self.f.add_axes([.05, .625, .4, .35], frameon=False, label='X Orientation') self.ax0.set_xlabel( 'Time (ms)' ) self.ax0.set_ylabel( 'Degree' ) self.ax0.grid(color='r', linestyle='-', linewidth=2) self.boxAxis = self.f.add_axes([.075, .525, .325, .025]) #self.ax0.plot(np.max(np.random.rand(100,10)*10,axis=1),"r-") self.canvas = FigureCanvasTkAgg(self.f, master=self.frame) self.canvas.draw() self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True) self.box = TextBox(boxAxis, "Altitude", initial="500") self.box.on_submit(self.plotGraph) # self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) # self.toolbar.grid(column = 0, row = 2, columnspan=2) self.toolbar.update() def plotGraph(self, val): data = [] for i in range(0,len(self.ts)): data.append(eval(val)) comms.writeData("PA:" + val) self.line, = self.ax0.plot(self.ts,data) self.line.set_color("blue") self.addAltitudeData() self.l, = self.ax0.plot(self.ts, self.alt) self.l.set_color("black") self.canvas.draw() def addAltitudeData(self): self.alt = [] self.ts = [] for i in altitudeData: self.alt.append(i[0]) self.ts.append(i[1])
def view_dep_tree(reviews: List[Text], parsed_reviews: List[List[ParsedSentence]], review_index=0, sentence_index=0): """Pass reviews to viewer...""" matplotlib.use('Qt5Agg') plt.rcParams['keymap.save'].remove('s') fig, ax = plt.subplots() # prev/next buttons plt.subplots_adjust(bottom=0.2) title_ax = plt.axes([0.05, 0.95, 0.9, 0.05]) callback = TreeViewer(reviews=reviews, parsed_reviews=parsed_reviews, ax=ax, title_ax=title_ax, fig=fig, review_index=review_index, sentence_index=sentence_index) prev_left = 0.8 next_left = 0.9 button_bottom = 0.02 button_width = 0.06 button_height = 0.04 # prev / next ax_prev = plt.axes([prev_left, button_bottom, button_width, button_height]) ax_next = plt.axes([next_left, button_bottom, button_width, button_height]) b_next = Button(ax_next, 'Next') b_prev = Button(ax_prev, 'Previous') b_next._click = callback.next_image b_next.connect_event('button_press_event', callback.button_press) # save ax_save = plt.axes([0.5, button_bottom, button_width, button_height]) b_save = Button(ax_save, 'Save') b_save.on_clicked(callback.dump_labeled_reviews) # input ax_review_index = plt.axes( [0.1, button_bottom, button_width, button_height]) text_box = TextBox(ax_review_index, 'Review.Sentence', initial='0.0') text_box.on_submit(callback.input_review_index) # Maximise the plotting window try: mng = plt.get_current_fig_manager() mng.window.showMaximized() except AttributeError as e: logging.warning(e) plt.show()
def _add_button(self, var, box): def _callback(text): try: self.__setattr__(var, float(text)) self._replot() except Exception as e: print(str(e)) tb = TextBox(plt.axes(box), var+' = ', initial=str(self.__getattribute__(var))) tb.on_submit(_callback) self.__setattr__('_tb_'+var, tb)
def addTextBox(self, label, submitHandler, loc=(0.8, 0.0, 0.1, 0.07), **kwargs): self.checkInteractive() txtBoxAx = self.fig.add_axes(loc) txtBox = TextBox(txtBoxAx, label, **kwargs) txtBox.on_submit(lambda e: submitHandler(e, self)) self.txtBoxStore.append(txtBox) return txtBox
def __init__(self, xPos, yPos): self.xPos = xPos self.yPos = yPos self.posePublisher = rospy.Publisher("robot_pose", geometry_msgs.msg.Pose2D, queue_size=10) plt.ion() fig, axes = plt.subplots(nrows=2, figsize=(5, 2)) text_box1 = TextBox(axes[0], 'X: ', initial=str(xPos)) text_box1.on_submit(lambda text: self.sendChange(float(text), None)) text_box2 = TextBox(axes[1], 'Y: ', initial=str(yPos)) text_box2.on_submit(lambda text: self.sendChange(None, float(text))) plt.show(block=True)
def set_textboxes(self): """Konfiguracja textboxy""" plt.text(0.87, 0.95, 'Ustaw prawdopodobienstwo', horizontalalignment='center', verticalalignment='center', transform=self.axes.transAxes) for i in range(10): axbox = plt.axes([0.95, 0.90 - i * 0.035, 0.03, 0.03]) text_box = TextBox(axbox, '', initial=str(self.pp_values[i]), hovercolor=self.colors[i]) text_box.on_submit(self.on_submit) self.text_boxes.append(text_box)
def initGUI(): #TextBox position variables (matplotlib.axes.Axes) RED_boxAxis = plt.axes([0.15, 0.05, 0.32, 0.05]) RED_sampleBoxAxis = plt.axes([0.15, 0.11, 0.32, 0.05]) BLUE_boxAxis = plt.axes([0.61, 0.05, 0.32, 0.05]) BLUE_sampleBoxAxis = plt.axes([0.61, 0.11, 0.32, 0.05]) meanBoxAxis = plt.axes([0.4, 0.17, 0.32, 0.05]) #Button position variables (matplotlib.axes.Axes) RED_axButton = plt.axes([0.15, 0.17, 0.15, 0.05]) BLUE_axButton = plt.axes([0.78, 0.17, 0.15, 0.05]) #buttons RED_button = Button(RED_axButton, 'Regen Red', color='red') BLUE_button = Button(BLUE_axButton, 'Regen Blue', color='blue') #TextBox text boxes RED_textBox = TextBox(RED_boxAxis, 'Modes\nRED', initial=str(classesNo[RED])) RED_textBox.label.set_wrap(True) meantextBox = TextBox(meanBoxAxis, 'Mean\nRange', initial=str(meanRange)) meantextBox.label.set_wrap(True) RED_sampletextBox = TextBox(RED_sampleBoxAxis, 'Samples\nRED', initial=str(samples[RED])) RED_sampletextBox.label.set_wrap(True) BLUE_textBox = TextBox(BLUE_boxAxis, 'Modes\nBLUE', initial=str(classesNo[BLUE])) BLUE_textBox.label.set_wrap(True) BLUE_sampletextBox = TextBox(BLUE_sampleBoxAxis, 'Samples\nBLUE', initial=str(samples[BLUE])) BLUE_sampletextBox.label.set_wrap(True) #on_submit event handlers RED_textBox.on_submit(lambda value: submitNo(RED, RED_textBox.text)) BLUE_textBox.on_submit(lambda value: submitNo(BLUE, BLUE_textBox.text)) meantextBox.on_submit(lambda value: submitMean(meantextBox.text)) RED_sampletextBox.on_submit( lambda value: submitSamples(RED, RED_sampletextBox.text)) BLUE_sampletextBox.on_submit( lambda value: submitSamples(BLUE, BLUE_sampletextBox.text)) callback = Index() RED_button.on_clicked(callback.REDregenerate) BLUE_button.on_clicked(callback.BLUEregenerate) plt.show() return callback, RED_button, BLUE_button
def initUserInterface(): RED_boxAxis = plt.axes([0.15, 0.05, 0.32, 0.05]) RED_sampleBoxAxis = plt.axes([0.15, 0.11, 0.32, 0.05]) BLUE_boxAxis = plt.axes([0.61, 0.05, 0.32, 0.05]) BLUE_sampleBoxAxis = plt.axes([0.61, 0.11, 0.32, 0.05]) meanBoxAxis = plt.axes([0.4, 0.17, 0.32, 0.05]) RED_axButton = plt.axes([0.15, 0.17, 0.15, 0.05]) BLUE_axButton = plt.axes([0.78, 0.17, 0.15, 0.05]) RED_button = Button(RED_axButton, 'Regen Red', color='red') BLUE_button = Button(BLUE_axButton, 'Regen Blue', color='blue') RED_textBox = TextBox(RED_boxAxis, 'Modes\nRED', initial=str(classesNo[RED_COLOR])) RED_textBox.label.set_wrap(True) meantextBox = TextBox(meanBoxAxis, 'Mean\nRange', initial=str(meanRange)) meantextBox.label.set_wrap(True) RED_sampletextBox = TextBox(RED_sampleBoxAxis, 'Samples\nRED', initial=str(samples[RED_COLOR])) RED_sampletextBox.label.set_wrap(True) BLUE_textBox = TextBox(BLUE_boxAxis, 'Modes\nBLUE', initial=str(classesNo[BLUE_COLOR])) BLUE_textBox.label.set_wrap(True) BLUE_sampletextBox = TextBox(BLUE_sampleBoxAxis, 'Samples\nBLUE', initial=str(samples[BLUE_COLOR])) BLUE_sampletextBox.label.set_wrap(True) RED_textBox.on_submit( lambda value: updateNewNo(RED_COLOR, RED_textBox.text)) BLUE_textBox.on_submit( lambda value: updateNewNo(BLUE_COLOR, BLUE_textBox.text)) meantextBox.on_submit(lambda value: updateNewMean(meantextBox.text)) RED_sampletextBox.on_submit( lambda value: updateNewSamples(RED_COLOR, RED_sampletextBox.text)) BLUE_sampletextBox.on_submit( lambda value: updateNewSamples(BLUE_COLOR, BLUE_sampletextBox.text)) callback = Index() RED_button.on_clicked(callback.REDregenerate) BLUE_button.on_clicked(callback.BLUEregenerate) plt.show() return callback, RED_button, BLUE_button
def view(): # fig, ax = plt.subplots() fig, ax = plt.subplots() # axes style ax.set_title('B-Spline-Curves') ax.set_xlim(1, 10) ax.set_ylim(1, 24) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.7, box.height]) # fig layout plt.text(10.3, 18, "User Tips:", fontfamily='fantasy', fontstyle='italic', fontsize='large', fontweight='roman', color='r', backgroundcolor='#87CEEB', # skyblue bbox=dict(boxstyle="round", fc='#87CEEB'), rasterized='True' ) plt.text(10.5, 11, "Add point: $Mouse-Right$\n" "Drag point: $Mouse-Left$\n" "Hide Line: h / H\nExit: q / Q\n", fontfamily='serif', fontstyle='oblique', fontsize='medium', color='#000080' ) # add new line button, input textbox and radio button addlinebtn = fig.add_axes([0.75, 0.22, 0.2, 0.075]) inputbox = fig.add_axes([0.85, 0.12, 0.1, 0.07]) rax = fig.add_axes([0.75, 0.32, 0.2, 0.12]) # button click btncallback = CreatLine(ax) binsert = Button(addlinebtn, 'New Line', color='#00BFFF') binsert.on_clicked(btncallback.createnewline) # input submit input_text = TextBox(inputbox, "Degree : ") input_text.on_submit(change_degree) input_text.set_val("3") # radio callback radio = RadioButtons(rax, ("Uniform", "Clamped")) radio.on_clicked(change_type) # add first line CreatLine(ax).createnewline(event=None) ax.legend(loc='upper left', bbox_to_anchor=(1, 1.02), fontsize='medium', shadow='True') plt.show()
def plot(self, *args, **kwargs): fig, self.ax = plt.subplots() plt.subplots_adjust(bottom=0.3) self.ax.plot(self.wavelength, self.flux, '-k', lw=4, label='Input') plt.xlabel('Wavelength') plt.ylabel('Flux') self.ax.legend(frameon=False) axbox1 = plt.axes([0.2, 0.08, 0.1, 0.075]) element_box = TextBox(axbox1, ' Element: ', initial='Fe') element_box.on_submit(self.update_element) axbox2 = plt.axes([0.6, 0.08, 0.25, 0.075]) abundance_box = TextBox(axbox2, ' Abundances: ', initial='-0.2, 0.0, 0.2') abundance_box.on_submit(self.update_abundances) plt.show()
class EditableTable(): def __init__(self, table): self.table = table self.ax = self.table.axes celld = table.get_celld() for key in celld.keys(): if key[0] > 0 and key[1] > -1: cell = celld[key] cell.set_picker(True) self.canvas = self.table.get_figure().canvas self.cid = self.canvas.mpl_connect('pick_event', self.on_pick) self.tba = self.ax.figure.add_axes([0, 0, .01, .01]) self.tba.set_visible(False) self.tb = TextBox(self.tba, '', initial="") self.cid2 = self.tb.on_submit(self.on_submit) self.currentcell = celld[(1, 0)] def on_pick(self, event): if isinstance(event.artist, CustomCell): # clear axes and delete textbox self.tba.clear() del self.tb # make textbox axes visible self.tba.set_visible(True) self.currentcell = event.artist # set position of textbox axes to the position of the current cell trans = self.ax.figure.transFigure.inverted() trans2 = self.ax.transAxes bbox = self.currentcell.get_bbox().transformed(trans2 + trans) self.tba.set_position(bbox.bounds) # create new Textbox with text of the current cell cell_text = self.currentcell.get_text().get_text() self.tb = TextBox(self.tba, '', initial=cell_text) self.cid2 = self.tb.on_submit(self.on_submit) self.canvas.draw() def on_submit(self, text): # write the text box' text back to the current cell self.currentcell.get_text().set_text(text) self.tba.set_visible(False) self.canvas.draw_idle()
def create_text_box(self, ax: Axes, label: str, get_var, set_var, data_type=float): var = str(get_var()) textbox = TextBox(ax, label, initial=var) def update_min_width(text: str): try: min_width = data_type(text) set_var(min_width) except ValueError: textbox.set_val(var) textbox.on_submit(update_min_width) self.setting_widgets.append(textbox)
def _main(initial, years): global line1 global line2 global fig global ax recalc(initial, years) fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.3) axbox1 = plt.axes([0.1, 0.15, 0.8, 0.075]) axbox2 = plt.axes([0.1, 0.05, 0.8, 0.075]) initialText = TextBox(axbox1, 'Initial Investment', initial=str(initial)) initialText.on_submit(submit_initial) yearsText = TextBox(axbox2, 'Years', initial=str(years)) yearsText.on_submit(submit_years) line1, = ax.plot(returns.index, returns, label='SP500') line2, = ax.plot(totalReturns.index, totalReturns, label='SP500 (Total Returns)') ax.set_xlabel('Date') ax.set_ylabel('Value of $%s initial investment over the course of %s years' % (initial, years)) ax.legend() plt.show()
def showUI(): global ax fig, ax = plt.subplots() callback = Index() num_text = plt.text(0, 0, str(cur_idx)) axtextbox_highlight = plt.axes([0.3, 0.05, 0.05, 0.075]) axtextbox_showlabel = plt.axes([0.4, 0.05, 0.05, 0.075]) axtextbox_merge = plt.axes([0.5, 0.05, 0.05, 0.075]) axprev = plt.axes([0.7, 0.05, 0.1, 0.075]) axnext = plt.axes([0.81, 0.05, 0.1, 0.075]) textbox_highlight = TextBox(axtextbox_highlight, 'Student #') textbox_highlight.on_submit(callback.submitHighlight) textbox_showlabel = TextBox(axtextbox_showlabel, 'Node #') textbox_showlabel.on_submit(callback.submitShowLabel) textbox_merge = TextBox(axtextbox_merge, 'Merge') textbox_merge.on_submit(callback.submitMerge) bprev = Button(axprev, 'Previous') bprev.on_clicked(callback.prev) bnext = Button(axnext, 'Next') bnext.on_clicked(callback.next) plt.sca(ax) drawGraph("new") plt.show()
def TryTextBox(): from matplotlib.widgets import TextBox fig = plt.figure(figsize=[5, 5], constrained_layout=True) gs = GridSpec(2, 1, figure=fig) ax_gs = fig.add_subplot(gs[0, 0]) textbox_raw_min = TextBox(ax_gs, "x min: ", initial="10") ax_plot = fig.add_subplot(gs[1, 0]) t = np.arange(-2.0, 2.0, 0.001) s = t**2 initial_text = "t ** 2" l, = ax_plot.plot(t, s, lw=2) def PrintASDF(text): ax_plot.set_xlim([0.5]) textbox_raw_min.on_submit(PrintASDF) return textbox_raw_min
def sap(ipAddress, port): rsa = SpectrumAnalyzer(host=ipAddress, port=port) rsa.connect() print(rsa.id) rsa.reset() rsa.write('format:data binary') rsa.write('spectrum:frequency:center {}'.format(rsa.cf)) rsa.write('spectrum:frequency:span {}'.format(rsa.span)) rsa.write('input:rlevel {}'.format(rsa.refLevel)) rsa.write('initiate:continuous on') #rsa.write('trigger:status on') #rsa.write('trigger:event:source input') #rsa.write('trigger:event:input:level -50') axcf = plt.axes([0.15, 0.90, 0.05, 0.0375]) tbcf = TextBox(axcf, 'Center Frequency (MHz)', initial=str(rsa.cf / 1e6)) tbcf.on_submit(rsa.setCenterFrequencyMHz) axspan = plt.axes([0.26, 0.90, 0.05, 0.0375]) tbspan = TextBox(axspan, 'Span (MHz)', initial=str(rsa.span / 1e6)) tbspan.on_submit(rsa.setSpanMHz) axref = plt.axes([0.42, 0.90, 0.025, 0.0375]) tbref = TextBox(axref, 'Reference Level (dBm)', initial=str(rsa.refLevel)) tbref.on_submit(rsa.setReferenceLevel) axrun = plt.axes([0.7, 0.90, 0.1, 0.0375]) axstop = plt.axes([0.81, 0.90, 0.1, 0.0375]) brun = Button(axrun, 'Run') bstop = Button(axstop, 'Stop') brun.on_clicked(rsa.run) bstop.on_clicked(rsa.stop) anispectrum = FuncAnimation(figspectrum, updatespectrum, fargs=(rsa,), init_func=displayspectrum(rsa), interval=1, blit=False) anispectrogram = FuncAnimation(figspectrogram, updatespectrogram, fargs=(rsa,), init_func=displayspectrogram(rsa), interval=50, blit=False) anispectrum3d = FuncAnimation(figspectrum3d, updatespectrum3d, fargs=(rsa,), init_func=displayspectrum3d(rsa), interval=50, blit=False) figspectrum.canvas.mpl_connect('close_event', rsa.disconnect) rsa.readyToTerminate = False tspectrum = threading.Thread(target=updatespectrumdata, args=(rsa,)) tspectrum.start() tspectrum3d = threading.Thread(target=updatespectrum3ddata, args=(rsa,50,)) tspectrum3d.start() plt.show() rsa.readyToTerminate = True try: rsa.disconnect() except: pass
def main(): mpl.rcParams['legend.fontsize'] = 10 global fig, ax fig, ax = pylab.subplots() ax = fig.gca(projection='3d') theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = r * np.sin(theta) y = r * np.cos(theta) global spir spir = Figure(x, y, z) # Оставим снизу от графика место для виджетов fig.subplots_adjust(left=0.07, right=0.95, top=0.95, bottom=0.4) # !!! Создадим ось для кнопки axes_button_add = pylab.axes([0.7, 0.05, 0.25, 0.075]) # !!! Создадим кнопку button_add = Button(axes_button_add, 'Вращать!') button_add.on_clicked(addButtonClicked) # !!! Создание осей для переключателей axes_radiobuttons = pylab.axes([0.05, 0.05, 0.2, 0.2]) # !!! Создание переключателя global radiobuttons_color radiobuttons_color = RadioButtons(axes_radiobuttons, ['X', 'Y', 'Z']) axbox = pylab.axes([0.85, 0.15, 0.1, 0.1]) text_box = TextBox(axbox, 'Введите угол в градусах') text_box.on_submit(textSubmited) ax.plot(x, y, z, label='parametric curve') ax.legend() pylab.show()
class image_browser: def __init__(self, x_test): MX = np.amax(np.abs(x_test)) self.x_test = x_test / MX self.idxB = 0 self.idxE = x_test.shape[0] self.current_slice = 0 p = self.current_slice # Let's set up image display gear self.fig, self.ax = plt.subplots(1, 1, figsize=(10, 8)) self.fig.tight_layout() plt.subplots_adjust(bottom=0.20, top=0.9) self.ax.imshow(self.x_test[self.current_slice, :, :, 0]) self.ax.set_title('Image No: ' + str(self.current_slice)) img_no_pos = plt.axes([0.48, 0.08, 0.04, 0.04]) # x, y, w, h label = 'Image No.: \nOut of ' + str(self.idxE) + ' ' self.img_tbox = TextBox(img_no_pos, label, initial=str(self.current_slice)) def _update(self, val): p = int(val) self.current_slice = p image_x = self.x_test[self.current_slice, :, :, 0] self.ax.imshow(image_x) def initialize(self): self.img_tbox.on_submit(self._update)
def create_input_boxes(): (cwedgeSize, ctheta, ckmin, cniter) = destripe_obj.get_params() dtheta_box = plt.axes([0.15, 0.03, 0.05, 0.05]) dtheta_input = TextBox(dtheta_box, 'Wedge Size: ', initial=str(cwedgeSize)) dtheta_input.on_submit(submit_dtheta) theta_box = plt.axes([0.29, 0.03, 0.05, 0.05]) theta_input = TextBox(theta_box, 'Theta: ', initial=str(ctheta)) theta_input.on_submit(submit_theta) kmin_box = plt.axes([0.42, 0.03, 0.05, 0.05]) kmin_input = TextBox(kmin_box, 'kmin: ', initial=str(ckmin)) kmin_input.on_submit(submit_kmin) niter_box = plt.axes([0.65, 0.03, 0.05, 0.05]) niter_input = TextBox(niter_box, 'Total Iterations: ', initial=str(cniter)) niter_input.on_submit(submit_niter) recon_box = plt.axes([0.72, 0.03, 0.25, 0.05]) recon_button = Button(recon_box, 'Start Reconstruction') recon_button.on_clicked(run_destripe) plt.show()
def showUI(): global fig, ax #fig, ax = plt.subplots() fig = plt.figure() refresh() callback = Index() fig.canvas.mpl_connect('button_press_event', callback.onClick) axtextbox_highlight = plt.axes([0.175, 0.05, 0.05, 0.05]) axtextbox_merge = plt.axes([0.325, 0.05, 0.05, 0.05]) axtextbox_separate = plt.axes([0.5, 0.05, 0.05, 0.05]) axundo = plt.axes([0.6, 0.05, 0.075, 0.05]) axprev = plt.axes([0.7, 0.05, 0.075, 0.05]) axnext = plt.axes([0.8, 0.05, 0.075, 0.05]) global textbox_highlight, textbox_merge, textbox_separate textbox_highlight = TextBox(axtextbox_highlight, 'Student #') textbox_highlight.label.set_fontsize(16) textbox_highlight.on_submit(callback.submitHighlight) textbox_merge = TextBox(axtextbox_merge, 'Merge (N#, N#)') textbox_merge.label.set_fontsize(16) textbox_merge.on_submit(callback.submitMerge) textbox_separate = TextBox(axtextbox_separate, 'Separate (N#, S#)') textbox_separate.label.set_fontsize(16) textbox_separate.on_submit(callback.submitSeparate) bundo = Button(axundo, 'Undo') bundo.label.set_fontsize(16) bundo.on_clicked(callback.undo) bprev = Button(axprev, 'Previous') bprev.label.set_fontsize(16) bprev.on_clicked(callback.prev) bnext = Button(axnext, 'Next') bnext.label.set_fontsize(16) bnext.on_clicked(callback.next) plt.sca(ax) drawGraph("new") plt.show()
def plotwf(numsite, numorb, plotBoth, coors, coeff): n, l, Z = setorb() rs = np.linspace(-1.5, 1.5, 60) ctrlAx = [ plt.axes([0.25, 0.1, 0.3, 0.15]), plt.axes([0.25, 0.3, 0.3, 0.15]), plt.axes([0.25, 0.5, 0.3, 0.15]) ] txtz = TextBox(ctrlAx[0], 'z=', initial=0.0) txtorb = TextBox(ctrlAx[1], 'Orb (1-10):', initial=1) txtsite = TextBox(ctrlAx[2], 'Site (1-17):', initial=1) fig, ax2 = plt.subplots(subplot_kw={"projection": "3d"}) X = np.array([[x for y in rs] for x in rs]).flatten() Y = np.array([[y for y in rs] for x in rs]).flatten() def submit(val): z = float(txtz.text) orb = int(txtorb.text) - 1 site = int(txtsite.text) - 1 ax2.clear() if plotBoth: wfs = np.array([[ wf(site, orb, numsite, numorb, n, l, Z, coors, x, y, z, coeff) for y in rs ] for x in rs]).flatten() ax2.scatter(X, Y, wfs, marker='o') ori = np.array([[ orbital(n[orb], l[orb], Z[orb], orb, coors[site], x, y, z) for y in rs ] for x in rs]).flatten() ax2.scatter(X, Y, ori, marker='.') #plt.legend() plt.title('site{}, orb{}, z={}, num of site={}, num of orb={}'.format( site, orb, z, numsite, numorb)) fig.canvas.draw_idle() txtz.on_submit(submit) txtorb.on_submit(submit) txtsite.on_submit(submit) plt.show()
Allowing text input with the Textbox widget. You can use the Textbox widget to let users provide any text that needs to be displayed, including formulas. You can use a submit button to create plots with the given input. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import TextBox fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) t = np.arange(-2.0, 2.0, 0.001) s = t ** 2 initial_text = "t ** 2" l, = plt.plot(t, s, lw=2) def submit(text): ydata = eval(text) l.set_ydata(ydata) ax.set_ylim(np.min(ydata), np.max(ydata)) plt.draw() axbox = plt.axes([0.1, 0.05, 0.8, 0.075]) text_box = TextBox(axbox, 'Evaluate', initial=initial_text) text_box.on_submit(submit) plt.show()