def _do_plot(self): stats = self._statistics.deserialize() metrics_to_plot = self._statistics.get_metrics_to_plot() subplots_count = len(stats) if not subplots_count: return fig, axarr = plt.subplots(subplots_count) fig.canvas.set_window_title(self._plot_title) time = range(len(stats[stats.keys()[0]])) axes_by_names = {} for i, key in enumerate(stats.keys()): axarr[i].plot(time, stats[key], label=metrics_to_plot[key].name, lw=1, color=COLORS[i]) axarr[i].set_xlabel('time (sec)') axarr[i].set_ylabel(metrics_to_plot[key].unit.name) axarr[i].legend() axes_by_names[key] = i rax = plt.axes([0.01, 0.8, 0.1, 0.1]) check_btns = CheckButtons(rax, stats.keys(), [True] * subplots_count) check_btns.on_clicked(self._get_show_hide_fn(fig, axarr, axes_by_names)) plt.subplots_adjust(left=0.2) plt.show()
def plot_hmm_path(trajectory_objs, paths, legends=[], items=[]): global colors print_n_flush("Colors are:", colors) for i, (trajectory, p) in enumerate(zip(trajectory_objs, paths)): print_n_flush("Path:", p) tr_colors = [colors[int(state)] for state in p] t = trajectory.plot2d(color=tr_colors) # t = plot_quiver2d(trajectory, color=tr_colors, path=p) too_high = [tt for tt in trajectory if tt[1] > 400] # print_n_flush( "Too high", too_high) legends.append("Trajectory%i" % i) # items.append(p) items.append(t) # gca().legend() # Let's create checkboxes rax = plt.axes([0.05, 0.4, 0.1, 0.15]) # rax = plt.gca() from matplotlib.widgets import CheckButtons check = CheckButtons(rax, legends, [True] * len(legends)) # plt.sca(axes) def func(label): widget = items[legends.index(label)] widget.set_visible(not widget.get_visible()) plt.draw() check.on_clicked(func)
def draw_plots(signals_descriptions): def on_click(label): plot = plots[label] plot.set_visible(not plot.get_visible()) signals_figure.canvas.draw() signals_figure = plt.figure('Signals') plots = {} plt.subplots_adjust(bottom=0.25) plt.subplots_adjust(left=0.2) for signal_values, signal_label, visibility, spectrum in signals_descriptions: x_points, y_points = plot_values(signal_values) line, = plt.plot(x_points, y_points) plots[signal_label] = line plt.figure(signal_label) plt.stem(*plot_values(spectrum), linefmt='b', markerfmt=' ', basefmt=' ') plt.figure('Signals') checkboxes_axes = plt.axes([0.05, 0.4, 0.12, 0.15]) checkboxes = CheckButtons( checkboxes_axes, [x.label for x in signals_descriptions], [x.visibility for x in signals_descriptions] ) checkboxes.on_clicked(on_click) plt.figlegend(list(plots.values()), [x.label for x in signals_descriptions], loc='lower center') # need to hide after figlegend to use real colors for legend for _, label, visibility, _ in signals_descriptions: plots[label].set_visible(visibility) plt.show()
def make_log_button(ax, box=[0.015, 0.05, 0.12, 0.15], ylims=None): """ Make a log button ax : the axis ylims : None or dictionary with the ylim for 'linear' and 'log' scales """ f = plt.gcf() ax_btn = f.add_axes(box, facecolor=slider_color) labels = ['log x', 'log y'] widget = CheckButtons(ax_btn, labels, [ax.get_xscale() == 'log', ax.get_yscale() == 'log']) def set_log(label): if label == 'log x': method = 'set_xscale' index = 0 if label == 'log y': method = 'set_yscale' index = 1 state = 'log' if widget.get_status()[index] else 'linear' getattr(ax, method)(state) if ylims is not None: if label == 'log y': ax.set_ylim(ylims[state]) f.canvas.draw_idle() widget.on_clicked(set_log) return widget
def setup_ui(): fig, ax = plt.subplots() plt.subplots_adjust(top=0.98, right=0.99, left=0.25, bottom=0.16) slider_axes = plt.axes([0.08, 0.04, 0.82, 0.03]) slider = Slider(slider_axes, 'Steps', STEP_MIN, STEP_MAX, valinit=STEP) def slider_listener(value): global STEP STEP = int(value) plot(ax, value) fig.canvas.draw_idle() slider.on_changed(slider_listener) checkbox_axes = plt.axes([0.01, 0.3, 0.15, 0.5]) checkbox = CheckButtons(checkbox_axes, METHODS, [method in SELECTED_METHODS for method in METHODS]) def checkbox_listener(label): method = [x for x in METHODS if x.name == label][0] if method in SELECTED_METHODS: SELECTED_METHODS.remove(method) else: SELECTED_METHODS.add(method) plot(ax, STEP) fig.canvas.draw_idle() checkbox.on_clicked(checkbox_listener) return ax, slider, checkbox
def initWindow(self): if not (self.args.placeOne and self.args.placeTwo): self.randomBB() for i in range(100): axes().set_aspect('equal', 'datalim') plt.subplot(2, 2, (1, 2)) plt.subplot(2, 2, (1, 2)).set_aspect('equal') subplots_adjust(left=0.31) subplots_adjust(bottom=-0.7) plt.title('QSR Visualisation ' + self.args.distribution[0]) axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.03, 0.4, 0.22, 0.45], fc=axcolor) checkBox = CheckButtons(rax, self.qsr_type, (False, False, False, False, False)) checkBox.on_clicked(self.EventClick) plt.subplot(2, 2, 3) plt.axis('off') plt.text(1, 1, (self.__compute_qsr(self.bb1[i], self.bb2[i])), family='serif', style='italic', ha='center') if self.qsr: self.updateWindow() plt.show()
def show_cts(filename): plt.subplots_adjust(left=0.04, top=0.99, bottom=0.03, wspace=0.12, hspace=0.23, right=0.86) record = reader.read_cts(filename, 10) with EcgInterpreter.from_record(record) as interpreter: borders = interpreter.get_global_borders() points = interpreter.get_points() measures = interpreter.get_intervals() borders = [x.sample for x in borders if x.sample > 0] onset = int(borders[0] - 0.02 * record.rate) offset = int(borders[-1] + 0.02 * record.rate) empty_count = 0 local_points = [] measurements = [] references = [] name = _record_name(filename) for i, item in enumerate(record.signals): if item is None: empty_count += 1 continue chunk = item[onset:offset] plot_index = (i - empty_count) * 2 if plot_index > 7: plot_index -= 7 plt.subplot(421 + plot_index) plt.ylabel("Lead " + _LEADS[i] + ". Voltage, mV.") plt.xlabel("Time, s.") plt.plot(chunk) measurements += _plot_borders(onset, borders) local_points += _plot_local_points(onset, points[i], chunk) references += _plot_references(name, onset, offset) legend_items = { _LABEL_MEASURES: measurements[0], _LABEL_POINTS: local_points[0] } if references: legend_items[_LABEL_REFERENCES] = references[0] plt.figlegend(legend_items.values(), legend_items.keys(), "upper right") triggers = CheckButtons(plt.axes([0.87, 0.8, 0.12, 0.10]), legend_items.keys(), [True] * len(legend_items)) def switch(label): lines = None if label == _LABEL_MEASURES: lines = measurements elif label == _LABEL_POINTS: lines = local_points elif label == _LABEL_REFERENCES: lines = references for item in lines: item.set_visible(not item.get_visible()) plt.draw() triggers.on_clicked(switch) _result_table(measures, name, ((10, 8), (10, 8), (6, 5), (12, 10)), "durations.pkl") plt.get_current_fig_manager().window.state("zoomed") plt.gcf().canvas.set_window_title("CTS-ECG: " + name) plt.show()
def build_plot(datas: List[PlotData], checkbox=True): fig, ax = plt.subplots() lines = [] for data in datas: line, = ax.plot(data.xdata, data.ydata, 'xb-', lw=2, color=data.color, label=data.label) lines.append(line) plt.subplots_adjust(left=0.2) if checkbox: def change_state(label): index = labels.index(label) lines[index].set_visible(not lines[index].get_visible()) plt.draw() rax = plt.axes([0.05, 0.4, 0.1, 0.15]) labels = [str(line.get_label()) for line in lines] visibility = [line.get_visible() for line in lines] check = CheckButtons(rax, labels, visibility) check.on_clicked(change_state) plt.show()
def plotAllFlags(): fig, ax = subplots(figsize=(16, 8)) offsets = getOffsets() start = 22 numFlags = [(flags[allChannels][:, -1] & (1 << start)) >> start] cmax = np.max(numFlags[0]) cmin = np.min(numFlags[0]) cmap = get_cmap('jet', cmax - cmin + 1) collection = RegularPolyCollection(numsides=4, rotation=np.pi / 4, sizes=(1000, ), linewidths=(1, ), offsets=offsets, transOffset=ax.transData, alpha=0.5, cmap=cmap) collection.set_clim(vmin=cmin - 0.5, vmax=cmax + 0.5) for i, w in enumerate(range(91) + range(91)): ax.annotate(str(w + 1), offsets[i], ha='center', va='center') subplots_adjust(left=0.2) ax.add_collection(collection) axis('equal') collection.set_array(numFlags[0]) cb = colorbar(collection, ticks=np.arange(cmin, cmax + 1)) rax = axes([0.05, 0.1, 0.1, 0.8]) status = [True, False, False] check = CheckButtons(rax, ('22', '23', '24'), tuple(status)) def func(label): bit = int(label) i = bit - start status[i] = not status[i] if status[i]: numFlags[0] += (flags[allChannels][:, -1] & (1 << bit)) >> bit else: numFlags[0] -= (flags[allChannels][:, -1] & (1 << bit)) >> bit cmax = np.max(numFlags[0]) cmin = np.min(numFlags[0]) cmap = get_cmap('jet', cmax - cmin + 1) ax.collections[0].set_array(numFlags[0]) ax.collections[0].set_clim(vmin=cmin - 0.5, vmax=cmax + 0.5) ax.collections[0].set_cmap(cmap) cb.set_ticks(np.arange(cmin, cmax + 1)) fig.canvas.draw() check.on_clicked(func) show()
def plot(self): print("plotting object of dimension " + str(self.decomposition.dimension)) self.make_figure() self.make_axes() self.main() self.label_axes() # I would love to move this to its own method, but I # don't think that is possible with the limiations of # matplotlib # can this be done with async?? # Create our check boxes # These four coordinates specify the position of the checkboxes rax = plt.axes([0.05, 0.4, 0.2, 0.15]) check = CheckButtons(rax, ('Vertices', 'Surface', 'Raw Surface', 'STL'), (True, True, False, False)) # Export STL button # exportstl = plt.axes([0.81, 0.01, 0.15, 0.075]) # bfvtostl = Button(exportstl,'Export STL') # if(bfvtostl.on_clicked()): # print("Export successfully") def func(label): if label == 'Vertices': # works but with hardcoded axes self.options.visibility.vertices = ( not self.options.visibility.vertices) self.ax.clear() self.replot() elif label == 'Surface': self.options.visibility.samples = ( not self.options.visibility.samples) self.ax.clear() self.replot() elif label == 'Raw Surface': self.options.visibility.raw = (not self.options.visibility.raw) self.ax.clear() self.replot() elif label == 'STL': self.fvtostl() plt.draw() check.on_clicked(func) self.apply_title() plt.show()
def build_stock_gdp(): """ Creates graphic of stock prices of 8 companies and GDP of USA >>> build_stock_gdp() """ axes = [] for comp in found_years: x = np.arange(found_years[comp], 2019) if comp == 'LGF': x = np.arange(found_years[comp], 2017) lst = [] for el in database: if database[el][1][comp] is not None: lst.append(database[el][1][comp]) y = np.array(lst) axes.extend([x, y]) lst = [] x = np.arange(1962, 2019) for el in gdp_info: if int(el) >= 1962: lst.append(gdp_info[el] / 100) y = np.array(lst) axes.extend([x, y]) fig, ax = plt.subplots() l1, = plt.plot(axes[0], axes[1], linestyle='solid') l2, = plt.plot(axes[2], axes[3], linestyle='solid') l3, = plt.plot(axes[4], axes[5], linestyle='solid') l4, = plt.plot(axes[6], axes[7], linestyle='solid') l5, = plt.plot(axes[8], axes[9], linestyle='solid') l6, = plt.plot(axes[10], axes[11], linestyle='solid') l7, = plt.plot(axes[12], axes[13], linestyle='solid') l8, = plt.plot(axes[14], axes[15], linestyle='solid') l9, = plt.plot(axes[16], axes[17], linestyle='solid') plt.subplots_adjust(left=0.3) lgnd = ax.legend(list(found_years.keys()), loc='upper center', ncol=4, fontsize='xx-small', shadow=True) lgnd.get_frame().set_facecolor('#ffb19a') rax = plt.axes([0.04, 0.5, 0.17, 0.37], facecolor='lightgoldenrodyellow') check = CheckButtons(rax, tuple(found_years.keys()), (True, True, True, True, True, True, True, True)) def func(label): for line, comp in zip([l1, l2, l3, l4, l5, l6, l7, l8], list(found_years.keys())): if label == comp: line.set_visible(not line.get_visible()) plt.draw() check.on_clicked(func) plt.show()
class PeakIdentifier: def __click_cb(self, label): self.all_names[label] = not self.all_names[label] def __init_fig__(self, data_name): self.fig = figure() self.ax = subplot(111) self.fig.subplots_adjust(left=0.3) title(_path.basename(data_name)) self.button_ax = plt.axes([0.05, 0.1, 0.15, 0.8]) self.check = CheckButtons(self.button_ax, sorted(self.all_names.keys()), [False] * len(self.all_names)) self.check.on_clicked(self.__click_cb) def __init_data__(self, data, start_i, end_i, pos, pos_s): start_i = int(start_i) end_i = int(end_i) + 1 self.start_i = start_i self.end_i = end_i self.__pos = pos self.__pos_s = pos_s self.d = end_i - start_i new_start = start_i - 10 * self.d if new_start < 0: new_start = 0 new_end = end_i + 10 * self.d if new_end >= len(data[2]): new_end = len(data[2] - 1) self.new_start = new_start self.new_end = new_end self.xs = r_[self.new_start : self.new_end] y1 = data[2][new_start:new_end] y2 = data[3][new_start:new_end] self.y = y2 - y1 def __init_plot__(self): self.ax.axvline(self.__pos, color="m", linewidth=2) self.ax.axvline(self.__pos - self.__pos_s, color="g") self.ax.axvline(self.__pos + self.__pos_s, color="g") self.ax.plot(self.xs, self.y, color="c") self.ax.set_ylim(min(self.y), max(self.y)) self.ax.set_xlim(self.new_start, self.new_end) def __init_names__(self, names): self.all_names = {} for n in names: self.all_names[n] = False def __init__(self, names, data, start_i, end_i, data_name, pos, pos_s): self.__init_names__(names) self.__init_fig__(data_name) self.__init_data__(data, start_i, end_i, pos, pos_s) self.__init_plot__() def run(self): show() close() return [k for k, v in self.all_names.items() if v]
def toggle_lines(ax=None, autoscl=True, numbering=False, txtwidth=15): """ Make checkbuttons to toggle visibility of each line in current plot. autoscl : Rescale axis limits as required by currently visible lines. numbering: Add numbering to labels. txtwidth : Wrap labels to this length. """ # Get lines and their properties if ax is None: ax = plt.gca() lines = {'handle': list(ax.get_lines())} for p in ['label', 'color', 'visible']: lines[p] = [plt.getp(x, p) for x in lines['handle']] lines = pd.DataFrame(lines) lines = lines[~lines.label.str.startswith('_')] if numbering: lines['label'] = [ str(i) + ': ' + lb for i, lb in enumerate(lines['label']) ] if txtwidth: lines['label'] = [ textwrap.fill(n, width=txtwidth) for n in lines['label'] ] # Setup buttons # When there's many, the box-sizing is awful, but difficult to fix. plt.subplots_adjust(left=0.32, right=0.97) N = len(lines) H = min(1, 0.07 * N) rax = plt.axes([0.05, 0.5 - H / 2, 0.22, H]) check = CheckButtons(rax, lines.label, lines.visible) # Adjust button style for i in range(N): check.rectangles[i].set(lw=0, facecolor=lines.color[i]) check.labels[i].set(color=lines.color[i]) # Callback def toggle_visible(label): ind = lines.label == label handle = lines[ind].handle.item() vs = not lines[ind].visible.item() handle.set_visible(vs) lines.loc[ind, 'visible'] = vs if autoscl: autoscale_based_on(ax, lines[lines.visible].handle) plt.draw() check.on_clicked(toggle_visible) # Must return (and be received) so as not to expire. return check
class AppMatplotlib(App): """ A class that uses matplotlib to display the drawing of a graph. """ def __init__(self, graph_list: List[nx.PlanarEmbedding]): App.__init__(self, graph_list) self.fig, self.ax = plt.subplots() self.fig.canvas.set_window_title('Planar graph drawing on a grid') plt.subplots_adjust(left=0, right=1, top=1, bottom=0) self.display_can_order = True self.prev_button = None self.next_button = None self.dummy_edge_button = None self.can_order_button = None self.change_graph() plt.show() plt.close() def add_widgets(self): axprev = plt.axes([0.01, 0.9, 0.1, 0.075]) axnext = plt.axes([0.12, 0.9, 0.1, 0.075]) self.prev_button = Button(axprev, "Previous") self.prev_button.on_clicked(lambda event: self.change_graph(-1)) self.next_button = Button(axnext, "Next") self.next_button.on_clicked(lambda event: self.change_graph()) axcanbox = plt.axes([0.01, 0.81, 0.1, 0.1], frameon=False) self.can_order_button = CheckButtons(axcanbox, ["Canonical order"], [self.display_can_order]) self.can_order_button.on_clicked(self.toggle_can_order) axckeckbox = plt.axes([0.01, 0.76, 0.1, 0.1], frameon=False) self.dummy_edge_button = CheckButtons(axckeckbox, ["Dummy edges"], [self.display_dummy_edges]) self.dummy_edge_button.on_clicked(self.toggle_dummy_edges) axes_text_box = plt.axes([0.01, 0.69, 0.06, 0.075], frameon=False) text_box = TextBox(axes_text_box, "", "Nodes : " + str(len(self.current_graph))) def toggle_dummy_edges(self, event=None): self.display_dummy_edges = not self.display_dummy_edges self.update_display() def toggle_can_order(self, event=None): self.display_can_order = not self.display_can_order self.update_display() def update_display(self): self.fig.clear() self.draw_graph() plt.axis('equal') # plt.gca().set_aspect('equal', adjustable='box') # plt.axis('off') self.add_widgets()
def draw_checkboxes(): global check_if, check_stat if check_if == None: rax = plt.axes([0.01, 0.8, 0.05, 0.05], title="interfaces") check_if = CheckButtons(rax, interface_list.keys(), interface_list.values()) check_if.on_clicked(partial(oncheck)) if check_stat == None: rax = plt.axes([0.01, 0.5, 0.08, 0.15], title="stats") vis = [value[1] for value in stats.values()] check_stat = CheckButtons(rax, stats.keys(), vis) check_stat.on_clicked(partial(oncheck_stats))
class fogContainerTrfcStat(MplCanvas): """ plot container traffic statistics for FOG demo""" colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'] def __init__(self, trfc_stats, n_points=15, parent=None): ''' trfc_stats: a list of multiprocessing.Value, in which each element coresponds to a container's current traffic bandwidth. ''' super().__init__(parent=parent) self.trfc_stats = trfc_stats self.n_points = n_points self.n_lines = len(trfc_stats) self.fig.subplots_adjust(left=0.35) self.ax_checkbuttom = self.fig.add_axes([0.04, 0.2, 0.17, 0.5]) self.compute_initial_figure() def compute_initial_figure(self): self.t = np.arange(0, self.n_points) self.alldata = [] self.lines = [] for i in range(self.n_lines): data = deque([0] * self.n_points, maxlen=self.n_points) ls = self.axes.plot(self.t, data, lw=1, color=fogContainerTrfcStat.colors[i], label=f'Container {i}') self.alldata.append(data) self.lines.append(ls[0]) self.labels = [str(line.get_label()) for line in self.lines] self.visibility = [line.get_visible() for line in self.lines] self.checkbuttom = CheckButtons(self.ax_checkbuttom, self.labels, self.visibility) self.checkbuttom.on_clicked(self.checkbutton_func) self.axes.set_ylim(0, 810000) self.axes.legend(loc='upper right') #'lower right' self.axes.get_xaxis().set_ticks([]) self.draw() def checkbutton_func(self, label): idx = self.labels.index(label) self.lines[idx].set_visible(not self.lines[idx].get_visible()) self.draw() def update_figure(self): #self.axes.cla() for i in range(self.n_lines): self.alldata[i].append(self.trfc_stats[i].value) self.lines[i].set_ydata(self.alldata[i]) # print(self.alldata[i]) self.draw()
def main(): fmax = 0.1 t = linspace(-fmax, fmax, num=20000) # Signals ft = f(t) # Input gt = g(t) # Tren de pulsos cuadrada fg = f(t) * g(t) # Señal muestreada sf = signal_filter(fg) # Señal recuperada con filtro # Se dibujan en la ventana fig, ax = plt.subplots(figsize=(13, 6)) l0, = ax.plot(t, ft, visible=True, lw=1, color='green', label='f(t)', dashes=[6, 2]) l1, = ax.plot(t, gt, visible=False, lw=1, color='red', label='g(t)', dashes=[6, 2]) l2, = ax.plot(t, fg, visible=False, lw=1, color='blue', label='f(t)*g(t)') l3, = ax.plot(t, sf, visible=True, lw=1, color='blue', label='Senial filtrada') lines = [l0, l1, l2, l3] # configuracion de la figura fig.canvas.set_window_title("Teorema de muestreo - %s" % (__author__)) plt.subplots_adjust(left=0.2) plt.ylim(-4, 5) plt.xlim(-fmax, fmax) plt.axhline(0, color="black") plt.axvline(0, color="black") # Se crean los chebkbuttons para las señales lines[] rax = plt.axes([0.05, 0.4, 0.1, 0.15]) labels = [str(line.get_label()) for line in lines] visibility = [line.get_visible() for line in lines] check = CheckButtons(rax, labels, visibility) def func(label): index = labels.index(label) lines[index].set_visible(not lines[index].get_visible()) plt.draw() check.on_clicked(func) plt.show()
class choose_curve (event_handler) : """ creates button to decide which curves will be visible """ def __init__ ( self , curves , name_curves = None , recenter = True , ax = None , fig = None) : """ curves: list of plot. name_curves : name_curves[i] is the name of the curve curves[i]. Must the same length as curves. recenter : recenter the graph each time we add or remove a plot. """ super().__init__(ax,fig) self.curves = curves self.name_curves = ['curve %d'%(i+1) for i in range(len(data))] \ if name_curves is None else name_curves self.recenter = recenter def add_button ( self , ax ) : #extend window to have some place to write the coordinate expand_figure ('LEFT' , 2 , ax , self.fig) ax_but = plt.axes([0.01, 0.05, 0.4, 0.8 ]) #do not show the graph of the button axis ax_but.axis('off') #add buttons self.check = CheckButtons(ax_but, self.name_curves , [True for _ in self.curves] ) #link the event handler function to the button self.check.on_clicked(self.on_click) #not usual activate because of the button so overwrite activate and activate_on_ax def activate ( self ) : self.add_button(self.ax) def activate_on_ax (self , ax) : self.add_button(ax) def on_click(self,label): #get the current curve curve = self.curves[self.name_curves.index(label)] #set it invisivle if it is visible and vice versa curve.set_visible(not curve.get_visible()) if self.recenter : # recompute the ax.dataLim self.ax.relim(visible_only=True) # update ax using the new dataLim self.ax.autoscale() #redraw graph plt.draw()
def plot_movie(dales, num_frames): n = len(fields) # number of fields to draw fig, axes = plot.subplots(1, n, sharey=True) handles = [] time_label = fig.text(0.1, 0.1, 'time') zf = dales.get_zf().value_in(units.m) ind = 0 colors = "bgrcmyk" for ax in axes: f = fields[ind] var_name, var_unit = f[0], f[1] ax = axes[ind] ax.set_xlabel(var_name) ax.set_ylabel("z") var_prof = getattr(dales.profiles, var_name).value_in(var_unit) line = ax.plot(var_prof[:], zf[:], '-', color=colors[ind], linewidth=2) handles.append((ax, line)) ind += 1 # plot.tight_layout() # draw a check box for forcing rax = plot.axes([0.25, 0.05, 0.15, 0.08]) check = CheckButtons(rax, ('Forcing', ), (False, )) check.on_clicked(checkbtn_clicked) def update_plot(lines, prof): lines[0].set_xdata(prof[:]) def update(i): if forcingFlag: tendency = numpy.zeros(dales.get_ktot()) print 'Applying forcing' for i in range(-15, 15): tendency[30 + i] = numpy.exp(-(i / 5.0)**2) dales.set_tendency_V(tendency * .2 | units.m / units.s**2) dales.set_tendency_QT(tendency * .000002 | units.mfu / units.s) t = dales.get_model_time() dales.evolve_model(t + dt) t = dales.get_model_time() print "updating with arg", i, 'time = ', t time_label.set_text('time %.2f' % t.value_in(units.s)) for f, h in zip(fields, handles): name, unit = f[0], f[1] prof = getattr(dales.profiles, name).value_in(unit) update_plot(h[1], prof) a = movie.FuncAnimation(fig, update, frames=num_frames, repeat=False) plot.show()
def plot(self, params, confidence_levels=[0.90, 0.95, 0.99], downsample=100): from plotutils import plotutils as pu from matplotlib import pyplot as plt from matplotlib.widgets import CheckButtons from itertools import cycle lines = ['solid', 'dashed', 'dashdot', 'dotted'] linecycler = cycle(lines) N = len(self._tracking_array) tracking_array = self._tracking_array param1 = tracking_array[params[0]] param2 = tracking_array[params[1]] pu.plot_greedy_kde_interval_2d(np.vstack([param1, param2]).T, [0.90,0.95,0.99]) ax = plt.gca() arrows = {} for proposal in self._proposals: ls = next(linecycler) sel = tracking_array['proposal'] == proposal accepted = tracking_array['accepted'][sel] xs = param1[sel] ys = param2[sel] x_ps = tracking_array[params[0]+'_p'][sel] y_ps = tracking_array[params[1]+'_p'][sel] dxs = x_ps - xs dys = y_ps - ys arrows[proposal] = [] for x, y, dx, dy, a in zip(xs,ys,dxs,dys,accepted): if dx != 0 or dy != 0: c = 'green' if a else 'red' arrow = ax.arrow(x, y, dx, dy, fc=c, ec=c, alpha=0.5, visible=False, linestyle=ls) arrows[proposal].append(arrow) plt.subplots_adjust(left=0.5) rax = plt.axes([0.05, 0.4, 0.4, 0.35]) check = CheckButtons(rax, self._proposals, [False for i in self._proposals]) def func(proposal): N = len(arrows[proposal]) step = int(np.floor(N/float(downsample))) step = step if step is not 0 else 1 for l in arrows[proposal][::step]: l.set_visible(not l.get_visible()) plt.draw() check.on_clicked(func) plt.show()
class Controller: ''' Display coordinate of the point if mouse hover on the plot ''' @staticmethod def decimal_quantize(value, format='.00', rounding=ROUND_HALF_UP): return float(Decimal(value).quantize(Decimal('.00'), ROUND_HALF_UP)) def __init__(self, fig, ax): self.__fig = fig self.__ax = ax self.__point_annot = self.__ax.annotate("", (0, 0), xytext=(5, 5),textcoords='offset points') self.__cursor = Cursor(ax, useblit=False, color='red', linewidth=0.5) self.__checkbox_ax = self.__fig.add_axes([0.02, 0.65, 0.1, 0.15], facecolor="lightgoldenrodyellow") self.__checkbox = CheckButtons(self.__checkbox_ax, ["curve\nfitting"], [self.__ax.get_visible()]) self.__slider_ax = self.__fig.add_axes([0.3, 0.02, 0.5, 0.02], facecolor="lightgoldenrodyellow") self.__slider = Slider(self.__slider_ax, 'facecolor alpha', np.float64(0), np.float64(255), valinit=125, valstep=5) self._xdata = 0 self._ydata = 0 self.__checkbox.on_clicked(self.check_box_click) self.__slider.on_changed(self.slider_change) self.__fig.canvas.mpl_connect("motion_notify_event", self.on_hover) def _update_point_annot(self): self.__point_annot.xy = (self._xdata, self._ydata) self.__point_annot.set_text("%r , %r" % self.__point_annot.xy) def on_hover(self, event): point_annot_vis = self.__point_annot.get_visible() if event.inaxes == self.__ax: self._xdata = self.decimal_quantize(event.xdata) self._ydata = self.decimal_quantize(event.ydata) self._update_point_annot() self.__point_annot.set_visible(True) else: if point_annot_vis: self.__point_annot.set_visible(False) self.__fig.canvas.draw_idle() def check_box_click(self, label): self.__ax.set_visible(not self.__ax.get_visible()) self.__fig.canvas.draw_idle() def slider_change(self, val): # val is numpy.float64 hex_val = '%02x' % int(val.item()) self.__ax.set_facecolor('#ffffff'+ hex_val) self.__fig.canvas.draw_idle()
def show_channel_hist(rgb_count): # takes longer time than show_dimension_plot() fig = plt.figure('channel histogram', figsize=(10, 6)) ax = plt.axes([0.1, 0.1, 0.65, 0.8]) for i, col in enumerate(('r', 'g', 'b')): ax.plot(rgb_count[i], color=col, linewidth=1) rax = plt.axes([0.78, 0.35, 0.2, 0.3]) labels = ['remove_zero', 'remove_maxval'] check = CheckButtons(rax, labels) flags = {'remove_zero': False, 'remove_maxval': False} def func(label): flags[label] = not flags[label] new_rgb_count = rgb_count.copy() if flags['remove_zero']: new_rgb_count[:, 0] = 0 if flags['remove_maxval']: new_rgb_count[:, -1] = 0 ax.cla() for i, col in enumerate(('r', 'g', 'b')): ax.plot(new_rgb_count[i], color=col, linewidth=1) ax.set_xlim([0, rgb_count.shape[1]]) ax.set_ylim([0, None]) ax.set_xlabel('pixel value') ax.set_ylabel('frequency') ax.set_title('channelwise pixel value histogram', pad=30) plt.show() check.on_clicked(func) ax.set_xlim([0, rgb_count.shape[1]]) ax.set_ylim([0, None]) ax.set_xlabel('pixel value') ax.set_ylabel('frequency') ax.set_title('channelwise pixel value histogram', pad=30) plt.show()
def labshow(labels, i=0, images=None, truth=None, test_indices=None): if images is None: images = IMAGES if truth is None: truth = LABELS if test_indices is None: test_indices = TEST test_indices = np.r_[tuple(test_indices)] gs = gridspec.GridSpec(GRID_SIZE, GRID_SIZE) fig = plt.figure() main_ax = fig.add_subplot(gs[:-1, 1:]) fig.tight_layout() img_ax = main_ax.imshow(overlay(images[test_indices[i]], labels[i], truth[test_indices[i]])) time_ax = fig.add_subplot(gs[-1, 1:-1]) time_sld = Slider(time_ax, "Frame", 0, len(test_indices) - .01, valinit=i, valfmt="%d") half = GRID_SIZE // 2 selector_ax = fig.add_subplot(gs[half-2:half, 0]) selector_chk = CheckButtons(selector_ax, ["Pred", "Truth"], [True, True]) def update(_): i = int(time_sld.val) selected = [l1.get_visible() for l1, l2 in selector_chk.lines] # checkbuttons.get_status() is supposed to exist, but doesn't? img_ax.set_data(overlay( images[test_indices[i]], labels[i] if selected[0] else None, truth[test_indices[i]] if selected[1] else None)) fig.canvas.draw_idle() time_sld.on_changed(update) selector_chk.on_clicked(update) def onkeypress(event): if event.key == "left": time_sld.set_val(max(time_sld.val - 1, time_sld.valmin)) elif event.key == "right": time_sld.set_val(min(time_sld.val + 1, time_sld.valmax)) elif event.key == "ctrl+left": time_sld.set_val(max(time_sld.val - 30, time_sld.valmin)) elif event.key == "ctrl+right": time_sld.set_val(min(time_sld.val + 30, time_sld.valmax)) elif event.key == "home": time_sld.set_val(time_sld.valmin) elif event.key == "end": time_sld.set_val(time_sld.valmax) fig.canvas.mpl_connect("key_press_event", onkeypress) plt.show()
def __init__(self, imp_obj): self.fig = pl.figure() self.tfmx = imp_obj['TimeFreqImp'] self.fvec = imp_obj['FreqVec'] self.tvec = imp_obj['TimeVec'] self.specs = imp_obj['Specs'] print(self.specs.shape) self.calibmx = imp_obj['CalibMx'] self.harms = imp_obj['Harms'] self.mode = 'mag' self.keep_prev = False self.slice_times = [] self.ax_imped = [ pl.subplot2grid((4, 8), (2, 0), colspan=7), pl.subplot2grid((4, 8), (3, 0), colspan=7) ] self.ax_tf = pl.subplot2grid((4, 8), (0, 0), rowspan=2, colspan=7) self.ax_cbar = pl.subplot2grid((4, 12), (0, 11), colspan=1, rowspan=2) # Make checkbuttons with all plotted lines with correct visibility rax = pl.subplot2grid((4, 12), (2, 11), rowspan=2, colspan=2) check = CheckButtons(rax, ['keep'], [False]) check.on_clicked(self.checkboxes) self.ax_tf.imshow( 20 * np.log10(np.abs(self.tfmx)), extent=[0, self.tvec[-1], self.fvec[0], self.fvec[-1]], aspect='auto', origin='bottom', cmap='gray') pl.colorbar(cax=self.ax_cbar, mappable=self.ax_tf.images[0]) self.fig.canvas.mpl_connect('button_press_event', self.onclick) self.fig.canvas.mpl_connect('key_press_event', self.onpress) self.temp_lines = [] self.last_tidx = 0 self.selector = SpanSelector(self.ax_tf, self.onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) self.spans = [] pl.show()
def init_ax4(): global ax4, checkService, checkPause, checkEndBen, checkDist, check ax4 = fig.add_axes([.72, .15, .08, .12]) ax4.set_xticklabels([]) ax4.set_yticklabels([]) ax4.set_xticks([]) ax4.set_yticks([]) # Define checkboxes check = CheckButtons(ax4, ('Service', 'Stepped', 'Pause', 'EndBen', 'Dist'), (checkService, checkStepped, checkPause, checkEndBen, checkDist)) # Attach checkboxes to checkbox function check.on_clicked(func)
def interactive_plot_layers(layer_info_type_list, debug_info_dict_list, plot_title="untitled"): fig, ax = plt.subplots() iters_list = np.unique( np.array([item.get('NumIters') for item in debug_info_dict_list])) handles = [] lines = [] plt.xlabel('NumIters') for (layer_name, column_to_plot) in layer_info_type_list: row_list = [ item.get(column_to_plot) for item in debug_info_dict_list if (layer_name == item.get('LayerName') and item.get(column_to_plot) != None and not np.isnan(item.get(column_to_plot))) ] if len(row_list) == 0: continue y = np.array(row_list) line, = ax.plot(iters_list[:len(y)], y, lw=2) handles.append(layer_name + '.' + column_to_plot) lines.append(line) plt.title(plot_title) plt.subplots_adjust(left=0.4) rax = plt.axes([0.05, 0.4, 0.3, 0.5]) check = CheckButtons(rax, tuple(handles), tuple([True for i in range(len(handles))])) [ rec.set_facecolor(lines[i].get_color()) for i, rec in enumerate(check.rectangles) ] def func(label): for i in range(len(handles)): if label == handles[i]: lines[i].set_visible(not lines[i].get_visible()) plt.draw() check.on_clicked(func) rax._cbutton = check
def graphIt(): print("goin") #Gets everything started by calculating the datasets before anything is graphed. euler() #Graphs the susceptible population. foxesGraph() rabbitsGraph() axcolor = 'white' rax = plt.axes([0.025, 0.7, 0.18, 0.15], axisbg=axcolor) radio = CheckButtons(rax, ('Foxes', 'Rabbits'), [True, True]) radio.on_clicked(updateLineType) ax.grid(True) ax.axhline(0, color='black', lw=2) ax.axvline(0, color='black', lw=2) plt.show()
def slider(self, N): barpos = plt.axes([0.18, 0.01, 0.70, 0.03], facecolor="gray") slider = Slider(barpos, '', 0, len(self.lista_hora) - N, valinit=0) slider.on_changed(self.bar) rax = plt.axes([0.01, 0.30, 0.12, 0.65]) check = CheckButtons( rax, ('C. Fund.', 'Arm. 1', 'Arm. 2', 'Arm. 3', 'Arm. 4', 'Arm. 5', 'Arm. 6', 'Arm. 7', 'Arm. 8', 'Arm. 9', 'Arm. 10', 'Arm. 11'), (True, True, True, True, True, True, True, True, True, True, True, True)) check.get_status() check.on_clicked(self.func) self.bar(0) plt.show()
def make_start_stop_animation(anim, box=[0.015, 0.05, 0.12, 0.1], start_animation=True): f = plt.gcf() ax_btn = f.add_axes(box, facecolor=slider_color) labels = ['anim'] widget = CheckButtons(ax_btn, labels, [start_animation]) def set_anim(label): if widget.get_status()[0]: print('on') anim.event_source.start() else: print('off') anim.event_source.stop() widget.on_clicked(set_anim) return widget
class button_manager: ''' Handles some missing features of matplotlib check buttons on init: creates button, links to button_click routine, calls call_on_click with active index and firsttime=True on click: maintains single button on state, calls call_on_click ''' #@output.capture() # debug def __init__(self, fig, dim, labels, init, call_on_click): ''' dim: (list) [leftbottom_x,bottom_y,width,height] labels: (list) for example ['1','2','3','4','5','6'] init: (list) for example [True, False, False, False, False, False] ''' self.fig = fig self.ax = plt.axes(dim) #lx,by,w,h self.init_state = init self.call_on_click = call_on_click self.button = CheckButtons(self.ax, labels, init) self.button.on_clicked(self.button_click) self.status = self.button.get_status() self.call_on_click(self.status.index(True), firsttime=True) #@output.capture() # debug def reinit(self): self.status = self.init_state self.button.set_active(self.status.index( True)) #turn off old, will trigger update and set to status #@output.capture() # debug def button_click(self, event): ''' maintains one-on state. If on-button is clicked, will process correctly ''' #new_status = self.button.get_status() #new = [self.status[i] ^ new_status[i] for i in range(len(self.status))] #newidx = new.index(True) self.button.eventson = False self.button.set_active( self.status.index(True)) #turn off old or reenable if same self.button.eventson = True self.status = self.button.get_status() self.call_on_click(self.status.index(True))
def initWindow(self): if not (self.args.placeOne and self.args.placeTwo): self.randomBB() axes().set_aspect('equal', 'datalim') plt.subplot(2, 2, (1, 2)) plt.subplot(2, 2, (1, 2)).set_aspect('equal') subplots_adjust(left=0.31) subplots_adjust(bottom=-0.7) plt.title('QSR Visualisation') axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.03, 0.4, 0.22, 0.45], axisbg=axcolor) checkBox = CheckButtons(rax, self.qsr_type,(False,False,False,False,False)) checkBox.on_clicked(self.EventClick) plt.subplot(2, 2, 3) plt.axis('off') plt.text(1, 1, (self.__compute_qsr(self.bb1, self.bb2)), family='serif', style='italic', ha='center') if self.qsr: self.updateWindow() plt.show()
def init_ax4(): global ax4, checkService, checkPause, checkEndBen, checkDist, check ax4 = fig.add_axes([0.72, 0.15, 0.08, 0.12]) ax4.set_xticklabels([]) ax4.set_yticklabels([]) ax4.set_xticks([]) ax4.set_yticks([]) # Define checkboxes check = CheckButtons( ax4, ("Service", "Stepped", "Pause", "EndBen", "Dist"), (checkService, checkStepped, checkPause, checkEndBen, checkDist), ) # Attach checkboxes to checkbox function check.on_clicked(func)
def drawParameterListControls(control_fig,viewer_fig,columns,default_values): """ Helper function for adding the check boxes for controlling the parameter list """ axcolor = 'w' char_width = max(map(lambda x:len(x),columns)) #finding the widest column title rax = plt.axes([0.05, 0.2 + 0.03*len(columns)*2 + 0.1, 0.015*char_width, 0.03*len(columns)], axisbg=axcolor,title="Parameter List") check = CheckButtons(rax, tuple(columns), ([True]*len(columns))) def parameterlistChange(label): global x_label,y_label,parameter_selection,data_dicts if(label in parameter_selection.keys()): del parameter_selection[label] else: parameter_selection[label] = default_values[columns.index(label)] redrawViewFigure(viewer_fig,data_dicts,x_label,y_label,parameter_selection) check.on_clicked(parameterlistChange) return check
class ToggleFlags: def __init__(self, args=None): self.names = [] self.args = args def add(self, name, value=False): if name in ['add', 'showat', '__init__']: return if name in self.args: value = True self.names.append(name) self.__setattr__(name, value) def showat(self, ax): v = [self.__getattribute__(name) for name in self.names] self.check = CheckButtons(ax, self.names, v) def func(label): self.__setattr__(label, not self.__getattribute__(label)) print("clicked") self.check.on_clicked(func)
def interactive_plot(plot_pairs_list, x_label, plot_title="untitled", ylim=[]): fig, ax = plt.subplots() #iters_list = np.unique(np.array([ item.get('NumIters') for item in debug_info_dict_list])) handles = [] lines = [] plt.xlabel(x_label) for x, y_pair in plot_pairs_list: y, y_label = y_pair if len(y) == 0: continue line, = ax.plot(x[:len(y)], y, lw=2) handles.append(y_label) lines.append(line) if ylim: ax.set_ylim(ylim) plt.title(plot_title) plt.subplots_adjust(left=0.4) rax = plt.axes([0.05, 0.4, 0.3, 0.5]) check = CheckButtons(rax, tuple(handles), tuple([True for i in range(len(handles))])) [ rec.set_facecolor(lines[i].get_color()) for i, rec in enumerate(check.rectangles) ] def func(label): for i in range(len(handles)): if label == handles[i]: lines[i].set_visible(not lines[i].get_visible()) plt.draw() check.on_clicked(func) rax._cbutton = check
def create_graph(self, datas, data_names): fig, ax = plt.subplots() # FPS x_step = 1 / 10 lines = [] for i, data in enumerate(datas): x = [] for _ in range(len(data)): x.append(x_step) x_step += x_step X = np.array(x) Y = np.array(data, dtype="float64") print(len(X)) print(len(Y)) i, = ax.plot(X, Y, label=data_names[i]) lines.append(i) rax = plt.axes([0.05, 0.4, 0.1, 0.15]) labels = [str(line.get_label()) for line in lines] visibility = [line.get_visible() for line in lines] check = CheckButtons(rax, labels, visibility) def change_visivility(label): index = labels.index(label) lines[index].set_visible(not lines[index].get_visible()) plt.draw() check.on_clicked(change_visivility) plt.show()
def displayResults2(self): """ show results with time slider geneNames have to be unique! """ ## ## import pylab #### from matplotlib.widgets import Slider ## mi=1 ## ma=self.results.shape[1] ## print(ma)# should be 101 ## ## figure=pylab.figure() ## ## ax=pylab.Axes(figure,[0.15, 0.1, 0.65, 0.03]) ## slider=pylab.Slider(ax=ax,label='time slider',valmin=mi,valmax=ma,valinit=1) ## ## def update(): ## pylab.plot(self.results[:,slider.val,:]) ## pylab.draw() ## ## slider.on_changed(update) ## pylab.show() import pylab import scipy from matplotlib.widgets import Slider, Button, RadioButtons, CheckButtons ## test = pylab.plot(self.results[:,-1,:]) ## pylab.show() # results is a data cube [cell, time, gene] miTime=0 maTime=self.results.shape[1]-1 ## xdata=range(self.results.shape[0]) ##ax = pylab.subplot(111) pylab.subplots_adjust(left=0.25, bottom=0.25) ## t = scipy.arange(0.0, 1.0, 0.001) ## a0 = 5 ## f0 = 3 ## s = a0*scipy.sin(2*scipy.pi*f0*t) ## plot, = pylab.plot(t,s, lw=2, color='red') selection=scipy.ones(len(self.geneNames)).astype(bool)# select all on start plots = pylab.plot(self.results[:,maTime,:]) # apperently returns a plot for each line... ## pylab.axis([0, 1, -10, 10]) axcolor = 'lightgoldenrodyellow' ## axfreq = pylab.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) ## axamp = pylab.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) ## sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0) ## samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0) ax=pylab.axes([0.15, 0.1, 0.65, 0.03]) slider=pylab.Slider(ax=ax,label='time slider',valmin=miTime,valmax=maTime,valinit=maTime) def update(val): ## amp = samp.val ## freq = sfreq.val ## l.set_ydata(amp*scipy.sin(2*scipy.pi*freq*t)) for i in range(len(plots)): plots[i].set_ydata(self.results[:,slider.val,i]) plots[i].set_visible(selection[i]) pylab.draw() ## sfreq.on_changed(update) ## samp.on_changed(update) slider.on_changed(update) resetax = pylab.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): ## sfreq.reset() ## samp.reset() slider.reset() button.on_clicked(reset) rax = pylab.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) checker=CheckButtons(rax,self.geneNames,actives=selection) def selector(val): ## print(val) ## print(scipy.array(range(len(self.geneNames)))[self.geneNames==val][0]) geneNr=scipy.array(range(len(self.geneNames)))[self.geneNames==val][0] # its retarded to check label names... but that is the way they like it.... selection[geneNr]=not(selection[geneNr]) update(slider.val) checker.on_clicked(selector) ## print(checker.eventson) ## print(checker.drawon) ## radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) ## ## rax = pylab.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) ## radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) ## def colorfunc(label): ## for i in range(len(plots)): ## plots[i].set_color(label) #### plots.set_color(label) ## pylab.draw() ## radio.on_clicked(colorfunc) pylab.show()
def scmoplot(root_path, user_ps): ps = dict(default_ps) ps.update(user_ps) ng = NameGleaner(scan=r'scan=(\d+)', x=r'x=(\d+)', y=r'y=(\d+)', averaged=r'(averaged)') tfmr = Transformer(gleaner=ng) tfmr.add(10, tfms.scale, params={'xsc': 0.1}) tfmr.add(20, tfms.flatten_saturation, params={'threshold': ps['thresh'], 'polarity': '+'}) tfmr.add(25, tfms.center) tfmr.add(30, tfms.wrapped_medfilt, params={'ks': ps['filt_ks']}) tfmr.add(40, tfms.saturation_normalize, params={'thresh': ps['thresh']}) tfmr2 = Transformer(gleaner=ng) tfmr2.add(10, tfms.scale, params={'xsc': 0.1}) tfmr2.add(30, tfms.wrapped_medfilt, params={'ks': ps['filt_ks']}) tfmr2.add(40, tfms.clean) clust = Cluster(join(root_path, 'parameters.xml')).to_dict() gx, gy = (clust['Rows'], clust['Cols']) fig, axarr = plt.subplots(ncols=gx, nrows=gy, figsize=(10, 10)) for row in axarr: for ax in row: ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) #ax.set_xlim(-ps['xlim'], ps['xlim']) #ax.set_ylim(-ps['ylim'], ps['ylim']) Hcs = [[None for i in range(gx)] for i in range(gy)] Mrs = [[None for i in range(gx)] for i in range(gy)] for f in listdir(root_path): gleaned = ng.glean(f) if gleaned['averaged']: print('Plotting %s' % f) x, y = int(gleaned['x']), int(gleaned['y']) ax = axarr[y, x] Bi, Vi = np.loadtxt(join(root_path, f), usecols=(0, 1), unpack=True, skiprows=7) B,V = tfmr((Bi,Vi),f) B2, V2 = tfmr2((Bi, Vi), f) ##data set 2 graphs lslope,rslope,tan=tfms.x0slope(B2,V2) lsat,rsat=tfms.sat_field(B2,V2) area = tfms.loop_area(B2,V2) data = ax.plot(B2,V2,'k') tanlines = ax.plot(tan[0],tan[1],'r',tan[2],tan[3],'y*',tan[4],tan[5],'b',tan[6],tan[7], 'y*') satfields = ax.plot(B2[lsat],V2[lsat],'ro',B2[rsat],V2[rsat],'go') areatext = ax.text(B2.min(),V2.max(), ("loop area: "+str(area+.0005)[0:6])) rax = plt.axes([0.05, 0.4, 0.1, 0.15]) check = CheckButtons(rax, ('data', 'tangent lines', 'saturation points', 'loop area'), (True, True, True, True)) def func(label): if label == 'data': toggle(data) elif label == 'tangent lines': toggle(tanlines) elif label == 'saturation points': toggle(satfields) elif label == 'loop area': areatext.set_visible(not areatext.get_visible()) plt.draw() check.on_clicked(func) try: Hc = tfms.Hc_of(B, V, fit_int=(ps['thresh'], ps['max'])) Hcs[y][x] = Hc Mr = tfms.Mrem_of(B, V, fit_int=(ps['thresh'], ps['max'])) Mrs[y][x] = Mr zs = np.zeros(3) ax.plot(zs, Mr, 'ro', ms=7) ax.plot(Hc, zs, 'ro', ms=7) except Exception as e: print('\t{}'.format(e)) Hcs[y][x] = 0.0 Mrs[y][x] = 0.0 plt.tight_layout(w_pad=0, h_pad=0) plt.show() Hcs = np.array([x[1] for row in Hcs for x in row]).reshape(gy, gx) Mrs = np.array([x[1] for row in Mrs for x in row]).reshape(gy, gx) gs = GridSpec(10, 10) ax0 = plt.subplot(gs[0:9, :5]) ax1 = plt.subplot(gs[9, :5]) ax2 = plt.subplot(gs[0:9, 5:]) ax3 = plt.subplot(gs[9, 5:]) fig = ax0.get_figure() fig.set_size_inches(12, 8) # Plot Hc pcolor map n = Normalize(vmin=0.0, vmax=5.0, clip=True) res = ax0.pcolor(Hcs, cmap='afmhot', norm=n, edgecolors='k') plt.colorbar(res, cax=ax1, orientation='horizontal', ticks=(0, 2.5, 5)) # Plot Mr pcolor map n = Normalize(vmin=0.0, vmax=1.0, clip=True) res = ax2.pcolor(Mrs, cmap='afmhot', norm=n, edgecolors='k') plt.colorbar(res, cax=ax3, orientation='horizontal', ticks=(0, 0.5, 1)) ax0.set_title('Hc (mT)') ax0.set_aspect('equal', adjustable='box') ax2.set_title('Mrem/Msat') ax2.set_aspect('equal', adjustable='box') plt.tight_layout() plt.show()
Bu.lines[0][0].set_ydata([CheckButtonsCrossU,CheckButtonsCrossD]) Bu.lines[0][1].set_xdata([CheckButtonsCrossL,CheckButtonsCrossR]) Bu.lines[0][1].set_ydata([CheckButtonsCrossD,CheckButtonsCrossU]) left_In = left_start bottom_In = bottom_save height_In = height_save*0.4 width_In = 0.3 axIn = plt.axes([left_In, bottom_In, width_In, height_In]) BuIn = CheckButtons(axIn, ('Interpolate',), (False,)) AdjustCheckButton(BuIn) Interpolate=False def helper_interpolate(val): global Interpolate Interpolate=not Interpolate BuIn.on_clicked(helper_interpolate) left_SLy = left_start bottom_SLy= bottom_save+1.2*height_In height_SLy= height_In width_SLy = 0.3 axSLy= plt.axes([left_SLy, bottom_SLy, width_SLy, height_SLy]) BuSLy= CheckButtons(axSLy, ('Log y',), (False,)) AdjustCheckButton(BuSLy) SLyPlot=False def helper_slyplot(val): global SLyPlot SLyPlot=not SLyPlot update(0) BuSLy.on_clicked(helper_slyplot)
#gausspl,lorenzpl,hmpl,hm2pl=plot(rx, [Gauss(x-xmed)/f0 for x in rx], 'r', rx, [Lorenz(x-xmed)/f0 for x in rx], 'b', [xmed-hw/2.,xmed+hw/2.],[0.5,0.5], 'g', [xmed-hw/2.,xmed+hw/2.],[0.5*l0/f0,0.5*l0/f0], 'g') #grid(True) #ylabel('Response') #xlabel('Frequency [THz]') subplots_adjust(bottom=0.25, right=0.95) axcolor = 'lightgoldenrodyellow' axfwhmG = axes([0.1, 0.15, 0.6, 0.03], axisbg=axcolor) fwhmG = Slider(axfwhmG, 'Gauss', 5*step, xrng/2, valinit=hw) fwhmG.on_changed(updateG) axfwhmL = axes([0.1, 0.05, 0.6, 0.03], axisbg=axcolor) fwhmL = Slider(axfwhmL, 'Lorentz', 5*step, xrng/2, valinit=hw) fwhmL.on_changed(updateL) active=[True,False,True,True] lpl.set_visible(False) cbData=CheckButtons(axes([0.78, 0.05, 0.2, 0.15]),('Gauss','Lorenz','Theory','Experiment'),active) cbData.on_clicked(changeData) show() for k in range(len(cx)) : print cx[k], cg[k], cl[k]
b_dist = Button(distance_ax, "Dist") b_dur = Button(dur_ax, "Duration") b_cal = Button(cal_ax, "Calories") b_fuel = Button(fuel_ax, "Fuel") b_reset = Button (reset_ax, "Reset") b_reclust = Button(clust_ax, "Cluster") buckets = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5,13,13.5,14,14.5] pace_buckets = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5,13,13.5,14,14.5] dur_buckets = [0.0, 5.0,10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0, 65.0, 70.0, 75.0, 80.0, 85.0, 90.0, 95.0, 100.0, 105.0] cal_buckets = [0,50,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000.0,1050,1100,1150,1200,1250,1300,1350,1400,1450,1500] fuel_buckets = [0,50,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000.0,1050,1100,1150,1200,1250,1300,1350,1400,1450,1500,1550,1600,1650,1700,1750,1800,1850,1900,1950,2000] aux_aux = figsrc.add_subplot(224) aux_aux.hist(dist, bins = buckets) title("Distance") xlabel("Distance (km)") ylabel("Number of People") b_pace.on_clicked(to_pace) b_dist.on_clicked(to_dist) b_dur.on_clicked(to_dur) b_cal.on_clicked(to_cal) b_fuel.on_clicked(to_fuel) b_reset.on_clicked(cluster_man.reset_area) b_reclust.on_clicked(cluster_man.Cluster) check.on_clicked(cluster_man) show()
def plot_data_for_station(station, available_data, event, get_data_callback, domain_bounds): """ Plots all data for a station in an interactive plot. :type station: dict :param station: A dictionary containing the keys 'id', 'latitude', 'longitude', 'elevation_in_m', and 'local_depth_in_m' describing the current station. :type available_data: dict :param available_data: The available processed and synthetic data. The raw data is always assumed to be available. :type event: dict :param event: A dictionary describing the current event. :type get_data_callback: function :param get_data_callback: Callback function returning an ObsPy Stream object. get_data_callback("raw") get_data_callback("synthetic", iteration_name) get_data_callback("processed", processing_tag) :type domain_bounds: dict :param domain_bounds: The domain bounds. """ import datetime import matplotlib.dates from matplotlib.widgets import CheckButtons from obspy.core.util.geodetics import calcVincentyInverse import textwrap # Setup the figure, the window and plot title. fig = plt.figure(figsize=(14, 9)) fig.canvas.set_window_title("Data for station %s" % station["id"]) fig.text(0.5, 0.99, "Station %s" % station["id"], verticalalignment="top", horizontalalignment="center") # Add one axis for each component. Share all axes. z_axis = fig.add_axes([0.30, 0.65, 0.68, 0.3]) n_axis = fig.add_axes([0.30, 0.35, 0.68, 0.3], sharex=z_axis, sharey=z_axis) e_axis = fig.add_axes([0.30, 0.05, 0.68, 0.3], sharex=z_axis, sharey=z_axis) axis = [z_axis, n_axis, e_axis] # Set grid, autoscale and hide all tick labels (some will be made visible # later one) for axes in axis: plt.setp(axes.get_xticklabels(), visible=False) plt.setp(axes.get_yticklabels(), visible=False) axes.grid(b=True) axes.autoscale(enable=True) axes.set_xlim(0.0, 12345.0) # Axes for the data selection check boxes. raw_check_axes = fig.add_axes([0.01, 0.8, 0.135, 0.15]) synth_check_axes = fig.add_axes([0.155, 0.8, 0.135, 0.15]) proc_check_axes = fig.add_axes([0.01, 0.5, 0.28, 0.29]) # The map axes map_axes = fig.add_axes([0.01, 0.05, 0.28, 0.40]) # Fill the check box axes. raw_check = CheckButtons(raw_check_axes, ["raw"], [True]) proc_check = CheckButtons(proc_check_axes, [ "\n".join(textwrap.wrap(_i, width=30)) for _i in available_data["processed"]], [False] * len(available_data["processed"])) synth_check = CheckButtons(synth_check_axes, available_data["synthetic"], [False] * len(available_data["synthetic"])) for check in [raw_check, proc_check, synth_check]: plt.setp(check.labels, fontsize=10) raw_check_axes.text( 0.02, 0.97, "Raw Data", transform=raw_check_axes.transAxes, verticalalignment="top", horizontalalignment="left", fontsize=10) proc_check_axes.text( 0.02, 0.97, "Processed Data", transform=proc_check_axes.transAxes, verticalalignment="top", horizontalalignment="left", fontsize=10) synth_check_axes.text( 0.02, 0.97, "Synthetic Data", transform=synth_check_axes.transAxes, verticalalignment="top", horizontalalignment="left", fontsize=10) bounds = domain_bounds["bounds"] map_object = plot_domain( bounds["minimum_latitude"], bounds["maximum_latitude"], bounds["minimum_longitude"], bounds["maximum_longitude"], bounds["boundary_width_in_degree"], rotation_axis=domain_bounds["rotation_axis"], rotation_angle_in_degree=domain_bounds["rotation_angle"], plot_simulation_domain=False, zoom=True, ax=map_axes) plot_stations_for_event(map_object=map_object, station_dict={station["id"]: station}, event_info=event) # Plot the beachball for one event. plot_events([event], map_object=map_object, beachball_size=0.05) dist = calcVincentyInverse( event["latitude"], event["longitude"], station["latitude"], station["longitude"])[0] / 1000.0 map_axes.set_title("Epicentral distance: %.1f km | Mag: %.1f %s" % (dist, event["magnitude"], event["magnitude_type"]), fontsize=10) PLOT_OBJECTS = { "raw": None, "synthetics": {}, "processed": {} } def plot(plot_type, label=None): if plot_type == "raw": st = get_data_callback("raw") PLOT_OBJECTS["raw"] = [] save_at = PLOT_OBJECTS["raw"] elif plot_type == "synthetic": st = get_data_callback("synthetic", label) PLOT_OBJECTS["synthetics"][label] = [] save_at = PLOT_OBJECTS["synthetics"][label] elif plot_type == "processed": st = get_data_callback("processed", label) PLOT_OBJECTS["processed"][label] = [] save_at = PLOT_OBJECTS["processed"][label] # Loop over all traces. for tr in st: # Normalize data. tr.data = np.require(tr.data, dtype="float32") tr.data -= tr.data.min() tr.data /= tr.data.max() tr.data -= tr.data.mean() tr.data /= np.abs(tr.data).max() * 1.1 # Figure out the correct axis. component = tr.stats.channel[-1].upper() if component == "N": axis = n_axis elif component == "E": axis = e_axis elif component == "Z": axis = z_axis else: raise NotImplementedError if plot_type == "synthetic": time_axis = matplotlib.dates.drange( event["origin_time"].datetime, (event["origin_time"] + tr.stats.delta * (tr.stats.npts)) .datetime, datetime.timedelta(seconds=tr.stats.delta)) zorder = 2 color = "red" elif plot_type == "raw": time_axis = matplotlib.dates.drange( tr.stats.starttime.datetime, (tr.stats.endtime + tr.stats.delta).datetime, datetime.timedelta(seconds=tr.stats.delta)) zorder = 0 color = "0.8" elif plot_type == "processed": time_axis = matplotlib.dates.drange( tr.stats.starttime.datetime, (tr.stats.endtime + tr.stats.delta).datetime, datetime.timedelta(seconds=tr.stats.delta)) zorder = 1 color = "0.2" else: msg = "Plot type '%s' not known" % plot_type raise ValueError(msg) save_at.append(axis.plot_date(time_axis[:len(tr.data)], tr.data, color=color, zorder=zorder, marker="", linestyle="-")) axis.set_ylim(-1.0, 1.0) axis.xaxis.set_major_formatter( matplotlib.dates.DateFormatter("%H:%M:%S")) if component == "E": try: plt.setp(axis.get_xticklabels(), visible=True) except: pass if plot_type != "raw": axis.set_xlim(time_axis[0], time_axis[-1]) # Adjust the limit only if there are no synthetics and processed if # plotting raw data. elif not PLOT_OBJECTS["synthetics"] and \ not PLOT_OBJECTS["processed"]: axis.set_xlim(time_axis[0], time_axis[-1]) for label, axis in zip(("Vertical", "North", "East"), (z_axis, n_axis, e_axis)): axis.text(0.98, 0.95, label, verticalalignment="top", horizontalalignment="right", bbox=dict(facecolor="white", alpha=0.5, pad=5), transform=axis.transAxes, fontsize=11) def _checked_raw(label): checked(label, "raw") def _checked_proc(label): checked(label, "proc") def _checked_synth(label): checked(label, "synth") def checked(label, check_box): if check_box == "raw": if PLOT_OBJECTS["raw"] is not None: for _i in PLOT_OBJECTS["raw"]: for _j in _i: _j.remove() PLOT_OBJECTS["raw"] = None else: PLOT_OBJECTS["raw"] = [] plot("raw") elif check_box == "synth": if label in PLOT_OBJECTS["synthetics"]: for _i in PLOT_OBJECTS["synthetics"][label]: for _j in _i: _j.remove() del PLOT_OBJECTS["synthetics"][label] else: PLOT_OBJECTS["synthetics"][label] = [] plot("synthetic", label=label) elif check_box == "proc": # Previously broken up. label = label.replace("\n", "") if label in PLOT_OBJECTS["processed"]: for _i in PLOT_OBJECTS["processed"][label]: for _j in _i: _j.remove() del PLOT_OBJECTS["processed"][label] else: PLOT_OBJECTS["processed"][label] = [] plot("processed", label=label) try: fig.canvas.draw() except: pass raw_check.on_clicked(_checked_raw) proc_check.on_clicked(_checked_proc) synth_check.on_clicked(_checked_synth) # Always plot the raw data by default. _checked_raw("raw") try: fig.canvas.draw() except: pass # One has call plt.show() to activate the main loop of the new figure. # Otherwise events will not work. plt.gcf().patch.set_alpha(0.0) plt.show()
class Visualizer: def __init__(self, field, fieldname, halospec=None): """Initializes a visualization instance, that is a windows with a field field is a 3D numpy array fieldname is a string with the name of the field halospec is a 2x2 array with the definition of the halo size After this call the window is shown """ self.field = field self.fieldname = fieldname # Register halo information if halospec is None: halospec = [[3, 3], [3, 3]] self.istart = halospec[0][0] self.iend = field.shape[0] - halospec[0][1] self.jstart = halospec[1][0] self.jend = field.shape[1] - halospec[1][1] self.plotHalo = True self.plotLogLog = False self.curklevel = 0 self.figure = plt.figure() # Slider slideraxes = plt.axes([0.15, 0.02, 0.5, 0.03], axisbg="lightgoldenrodyellow") self.slider = Slider(slideraxes, "K level", 0, field.shape[2] - 1, valinit=0) self.slider.valfmt = "%2d" self.slider.set_val(0) self.slider.on_changed(self.updateSlider) # CheckButton self.cbaxes = plt.axes([0.8, -0.04, 0.12, 0.15]) self.cbaxes.set_axis_off() self.cb = CheckButtons(self.cbaxes, ("Halo", "Logscale"), (self.plotHalo, self.plotLogLog)) self.cb.on_clicked(self.updateButton) # Initial plot self.fieldaxes = self.figure.add_axes([0.1, 0.15, 0.9, 0.75]) self.collection = plt.pcolor(self._getField(), axes=self.fieldaxes) self.colorbar = plt.colorbar() self.fieldaxes.set_xlim(right=self._getField().shape[1]) self.fieldaxes.set_ylim(top=self._getField().shape[0]) plt.xlabel("i") plt.ylabel("j") self.title = plt.title("%s - Level 0" % (fieldname,)) plt.show(block=False) def updateSlider(self, val): if val == self.curklevel: return self.curklevel = round(val) self.title.set_text("%s - Level %d" % (self.fieldname, self.curklevel)) # Draw new field level field = self._getField() size = field.shape[0] * field.shape[1] array = field.reshape(size) self.collection.set_array(array) self.colorbar.set_clim(vmin=field.min(), vmax=field.max()) self.collection.set_clim(vmin=field.min(), vmax=field.max()) self.colorbar.update_normal(self.collection) self.figure.canvas.draw_idle() def updateButton(self, label): if label == "Halo": self.plotHalo = not self.plotHalo if label == "Logscale": self.plotLogLog = not self.plotLogLog self.updatePlot() def updatePlot(self): # Redraw field self.collection.remove() field = self._getField() if self.plotLogLog: minvalue = field.min() norm = SymLogNorm(linthresh=1e-10) self.collection = plt.pcolor(field, axes=self.fieldaxes, norm=norm) self.colorbar.set_clim(vmin=minvalue, vmax=field.max()) else: self.collection = plt.pcolor(field, axes=self.fieldaxes) self.colorbar.set_clim(vmin=field.min(), vmax=field.max()) self.colorbar.set_norm(norm=Normalize(vmin=field.min(), vmax=field.max())) self.fieldaxes.set_xlim(right=field.shape[1]) self.fieldaxes.set_ylim(top=field.shape[0]) self.colorbar.update_normal(self.collection) self.figure.canvas.draw_idle() def _getField(self): if self.plotHalo: return np.rot90(self.field[:, :, self.curklevel]) else: return np.rot90(self.field[self.istart : self.iend, self.jstart : self.jend, self.curklevel])
for j in iterHulls[i]: if j.get_visible(): legLine.append(j) legLabel.append(j.get_label()) font=FontProperties(size='small') if (len(legLine) > 0): ax.legend(legLine, legLabel, loc=options.lpos, shadow=True, prop=font) else: ax.legend(("",),loc=options.lpos, shadow=True, prop=font) plt.draw() if not options.outfile: rax = plt.axes([0.05, 0.15, 0.15, 0.6]) check = CheckButtons(rax, ['scatter', 'all', 'config'] + itervars.keys(), (scatterPoints.get_visible(), allHull.get_visible(), options.configs) + tuple(itervarsenabled.values())) check.on_clicked(toggleHullVisibility) toggleHullVisibility("") if options.zoom: limits = options.zoom.split(","); if len(limits) != 4: print "-z parameter needs 4 comma-seperated float values!" exit(-1) ax.set_xlim(float(limits[0]), float(limits[1])) ax.set_ylim(float(limits[2]), float(limits[3])) plt.show() if options.outfile: # fig.savefig(options.outfile) # Write gnuplot script
def run_main( A, B, C, dA, dB, dC, DJ, DJK, DK, dJ, dK, ua, ub, uc, dua, dub, duc, f_lower, f_upper, T, J_max, last_times_picked_list, ): # matplotlib.use('TkAggx') global DJ_g, DJK_g, DK_g, ua_g, ub_g, uc_g, T_g, dJ_g, dK_g, f_lower_g, f_upper_g, J_max_g, triples_flag triples_flag = 0 J_max_g = J_max DJ_g = DJ DJK_g = DJK DK_g = DK ua_g = ua ub_g = ub uc_g = uc T_g = T dJ_g = dJ dK_g = dK f_lower_g = f_lower f_upper_g = f_upper global trans_1, trans_2, trans_3, peak_list trans_1 = [] trans_2 = [] trans_3 = [] peak_list = [] global picked_list picked_list = last_times_picked_list plt.close() global figure_h figure_h = plt.figure(figsize=(16.5, 4)) try: figure_h.canvas.manager.window.Move((00, 00)) except AttributeError: pass # thismanager = pl.get_current_fig_manager() # thismanager.window.SetPosition((00, 0)) # thismanager.window.wm_geometry("+00+0") int_writer(ua, ub, uc, temp=T_g, freq=(f_upper_g / 1000)) var_writer_uncert(A, B, C, DJ, DJK, DK, dJ_g, dK_g) run_SPCAT() data = cat_reader() global t global s t = [] s = [] t_b = [] s_b = [] for x in data: s.append(0.0) s.append(str(10 ** float(x[1]))) s.append(0.0) t.append(float(x[0]) - 0.0001) t.append(x[0]) t.append(float(x[0]) + 0.0001) for y in picked_list: if x[2] == y[1] and x[3] == y[2]: s_b.append(0.0) s_b.append(str(10 ** float(x[1]))) s_b.append(0.0) t_b.append(float(x[0]) - 0.0001) t_b.append(x[0]) t_b.append(float(x[0]) + 0.0001) ax = figure_h.add_subplot(212) plt.subplots_adjust(left=0.25, bottom=0.25) pl.subplots_adjust(hspace=0.0, right=0.925) a0 = 5 f0 = 3 global l, triples_plt l, = plt.plot(t, s, lw=2, color="red") triples_plt, = plt.plot([], [], "*", markersize=15, color="blue") ax.set_xlim([f_lower_g, f_upper_g]) global picked_plt, ax2 picked_plt, = plt.plot(t_b, s_b, lw=2, color="black") # plt.axis([0, 1, -10, 10]) # figure_h.canvas.mpl_connect('button_press_event', handle_mouse_press) ax2 = figure_h.add_subplot(211, sharex=ax) ax2.axes.get_xaxis().set_visible(False) global peak_list_plt, exp_plt, trans_1_plt, trans_2_plt, trans_3_plt peak_list_plt, = ax2.plot([], [], "o", color="red") trans_1_plt, = ax2.plot([], [], "s", color="cyan") trans_2_plt, = ax2.plot([], [], "s", color="magenta") trans_3_plt, = ax2.plot([], [], "s", color="yellow") ax2.set_xlim([f_lower_g, f_upper_g]) global locator locator = ax2.yaxis.get_major_locator() exp_plt, = ax2.plot([], [], lw=2, color="black") figure_h.canvas.mpl_connect("key_press_event", on_key) axcolor = "lightgoldenrodyellow" axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) axB = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axC = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) axua = plt.axes([0.935, 0.32, 0.01, 0.6], axisbg=axcolor) axub = plt.axes([0.96, 0.32, 0.01, 0.6], axisbg=axcolor) axuc = plt.axes([0.985, 0.32, 0.01, 0.6], axisbg=axcolor) # axub = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) # axuc = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) dua_2 = dua dub_2 = dub duc_2 = duc if (ua_g - dua) < 0: dua_2 = ua_g if (ub_g - dub) < 0: dub_2 = ub_g if (uc_g - duc) < 0: duc_2 = uc_g global ua_slider ua_slider = VSlider(axua, "u a", ua_g - dua_2, ua_g + dua, valinit=ua_g) ua_slider.on_changed(update) global ub_slider ub_slider = VSlider(axub, "u b", ub_g - dub_2, ub_g + dub, valinit=ub_g) ub_slider.on_changed(update) global uc_slider uc_slider = VSlider(axuc, "u c", uc_g - duc_2, uc_g + duc, valinit=uc_g) uc_slider.on_changed(update) global A_slider global B_slider global C_slider global rax rax = plt.axes([0.0, 0.5, 0.19, 0.4]) global check check = CheckButtons(rax, ("", "", "", ""), (True, False, False, False)) check.on_clicked(func) A_slider = Slider(axA, "A", A - dA, A + dA, valinit=A) B_slider = Slider(axB, "B", B - dB, B + dB, valinit=B) C_slider = Slider(axC, "C", C - dC, C + dC, valinit=C) A_slider.on_changed(update) B_slider.on_changed(update) C_slider.on_changed(update) global button global radio resetax = plt.axes([0.1, 0.025, 0.1, 0.04]) button = Button(resetax, "Reset Sliders", color=axcolor, hovercolor="0.975") button.on_clicked(reset) # rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) # radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) # radio.on_clicked(colorfunc) global text_box # global text_box2 text_box = plt.text(-1, 8, "") text_box2 = plt.text( -1, 23, "Refine Mouse Selection: Select transitions by pushing 'q' and then clicking in the predicted spectrum ", )
def display(self): """Method to create the plotting window and fill it with buttons.""" # Create matplotlib window dressing self.fig = plt.figure(figsize=(11,9), facecolor='lightgoldenrodyellow') #self.fig = plt.figure(facecolor='lightgoldenrodyellow') self.fig.canvas.set_window_title('PyPop: Visualization') self.fig.clear() # put some buttons on the figure for the plot axes buttonW = 0.055 buttonH = 0.045 # default button sizes # arguments are button left, bottom, width, height and label # check box to do log scale buttonXLog = CheckButtons(plt.axes([0.001, .3, 1.5*buttonW, 1.5*buttonH]), ['log x'], actives=[False]) self.xlog = False buttonYLog = CheckButtons(plt.axes([0.001+2.5*buttonW, .3, 1.5*buttonW, 1.5*buttonH]), ['log y'], actives=[False]) self.ylog = False # button to do plot buttonPlot = Button(plt.axes([0.001+2.0*buttonW, 0.2, 1.5*buttonW, buttonH]), 'Plot') self.fig.text(0.003, 0.98, 'PLOT SELECTION') self.fig.text(0.003, 0.95, 'X Axis') self.fig.text(0.003, 0.65, 'Y Axis') # radio buttons for x and y axis values radioXAxis = RadioButtons(plt.axes([0.001, 0.72, len(self.textlabels)*0.02, len(self.textlabels)*0.02]), self.textlabels, active=0, activecolor='blue') self.xindex = 0 radioYAxis = RadioButtons(plt.axes([0.001, 0.42, len(self.textlabels)*0.02, len(self.textlabels)*0.02]), self.textlabels, active=1, activecolor='blue') self.yindex = 1 # if radio button is clicked, change active X/Y index radioXAxis.on_clicked(self._radioXClick) radioYAxis.on_clicked(self._radioYClick) # add callback to the plot button(s?) buttonPlot.on_clicked(self._scatterplot) # callbacks for the log plot switches buttonXLog.on_clicked(self._logClick) buttonYLog.on_clicked(self._logClick) plt.show()
def animate(sources, reflect=False): fig = plt.figure() # create reflection images of sources if reflect: reflectedSources = [] for src in sources: reflSrc = deepcopy(src) reflSrc.pos = -src.pos reflectedSources.append(reflSrc) # subplot for every source lines = [] for i, src in enumerate(sources): # pressure on left y axis ax1 = fig.add_subplot(len(sources)+1, 1, i+1) ax1.set_xlim([0, xMax]) yLim = src.pAmpl * 1.3 * (1+reflect) ax1.set_ylim([-yLim, yLim]) ax1.set_ylabel('p') line_pSrc, = plt.plot([], [], 'r--', lw=1) line_pRefl, = plt.plot([], [], 'r:', lw=1) line_p, = plt.plot([], [], 'r', lw=1, label='p') ax1.legend(loc='upper left') # velocity on right y axis ax2 = ax1.twinx() ax2.set_xlim([0, xMax]) yLim = src.uAmpl * 2 * (1+reflect) ax2.set_ylim([-yLim, yLim]) ax2.set_ylabel('u') line_uSrc, = plt.plot([], [], 'b--', lw=1) line_uRefl, = plt.plot([], [], 'b:', lw=1) line_u, = plt.plot([], [], 'b', lw=1, label='u') ax2.legend(loc='upper right') ax1.set_title(src.name) lines.append([line_pSrc, line_uSrc, line_pRefl, line_uRefl, line_p, line_u]) # subplot for total pressure and velocity # pressure on left y axis ax1 = fig.add_subplot(len(sources)+1, 1, len(sources)+1) ax1.set_xlim([0, xMax]) yLim = sum([src.pAmpl for src in sources]) * 1.3 * (1+reflect) ax1.set_ylim([-yLim, yLim]) ax1.set_ylabel('p') line_p, = plt.plot([], [], 'r', lw=1, label='p') ax1.legend(loc='upper left') # velocity on right y axis ax2 = ax1.twinx() ax2.set_xlim([0, xMax]) yLim = sum([src.uAmpl for src in sources]) * 2 * (1+reflect) ax2.set_ylim([-yLim, yLim]) ax2.set_ylabel('u') line_u, = plt.plot([], [], 'b', lw=1, label='u') ax2.legend(loc='upper right') ax1.set_title('Sum of all sources') lineSum = [line_p, line_u] # interactive plots :) plt.subplots_adjust(left=0.15, top=0.9) showVelocity = [not reflect] # value in list - a hack to use nonlocal in Python 2 showPressure = [True] checkAx = plt.axes([0.05, 0.6, 0.05, 0.15]) checkButtons = CheckButtons(checkAx, ('p', 'v'), (True, showVelocity[0])) def toggleLines(label): if label == 'p': showPressure[0] = not showPressure[0] elif label == 'v': showVelocity[0] = not showVelocity[0] checkButtons.on_clicked(toggleLines) resetAnimation = [False] buttonAx = plt.axes([0.05, 0.85, 0.05, 0.04]) button = Button(buttonAx, 'Reset', hovercolor='0.975') def reset(event): resetAnimation[0] = True button.on_clicked(reset) def drawBackground(): for iSrc, src in enumerate(sources): lines[iSrc][0].set_data([src.pos, src.pos], [-src.pAmpl * 3, src.pAmpl * 3]) for line in lines[iSrc][1:]: line.set_data([], []) lineSum[0].set_data([], []) lineSum[1].set_data([], []) return tuple(itertools.chain(*lines)) + tuple(lineSum) def drawFrame(i): t = i * SPEED x = np.linspace(0, xMax, nPOINTS) pSum = np.zeros(nPOINTS) uSum = np.zeros(nPOINTS) for iSrc, src in enumerate(sources): pDirect = np.zeros(nPOINTS) uDirect = np.zeros(nPOINTS) pRefl = np.zeros(nPOINTS) uRefl = np.zeros(nPOINTS) p = np.zeros(nPOINTS) u = np.zeros(nPOINTS) for i in xrange(0, nPOINTS): pDirect[i] = src.p(pnt2x(i), t) uDirect[i] = src.u(pnt2x(i), t) if reflect: pRefl[i] = reflectedSources[iSrc].p(pnt2x(i), t) uRefl[i] = reflectedSources[iSrc].u(pnt2x(i), t) pSum[i] += (pDirect[i] + pRefl[i]) uSum[i] += (uDirect[i] + uRefl[i]) p = pDirect + pRefl u = uDirect + uRefl if showPressure[0]: lines[iSrc][0].set_data(x, pDirect) lines[iSrc][2].set_data(x, pRefl) lines[iSrc][4].set_data(x, p) else: lines[iSrc][0].set_data([], []) lines[iSrc][2].set_data([], []) lines[iSrc][4].set_data([], []) if showVelocity[0]: lines[iSrc][1].set_data(x, uDirect) lines[iSrc][3].set_data(x, uRefl) lines[iSrc][5].set_data(x, u) else: lines[iSrc][1].set_data([], []) lines[iSrc][3].set_data([], []) lines[iSrc][5].set_data([], []) if showPressure[0]: lineSum[0].set_data(x, pSum) else: lineSum[0].set_data([], []) if showVelocity[0]: lineSum[1].set_data(x, uSum) else: lineSum[1].set_data([], []) return tuple(itertools.chain(*lines)) + tuple(lineSum) def cnt(): i = 0 while True: yield i if resetAnimation[0]: i = 0 resetAnimation[0] = False else: i += 1 anim = animation.FuncAnimation(fig, drawFrame, init_func=drawBackground, frames=cnt, interval=40, blit=True, repeat=False) plt.show()
def plot_clusters_in_brain(bn,background,cluster_list,actives=[True,False,False]): if len(cluster_list)<3: print 'just '+str(len(cluster_list))+ ' cluster' colors=[[1,0,0],[0,1,0],[0,0,1]] node2voxel=bn.get_node2voxel() img=nib.load(bn.mask) imgB = nib.load(background) D=img.get_data() sh=D.shape A=bn.affine aspect1=abs(A[2,2]/A[0,0]) aspect2=abs(A[2,2]/A[1,1]) aspect3=abs(A[1,1]/A[0,0]) M=pylab.zeros((sh[0],sh[1],sh[2],3)) B=M B0=imgB.get_data().astype(numpy.float32, copy=False) #B0img.get_data().astype(numpy.float32, copy=False) B[:,:,:,0]=(B0-B0.min())/(B0.max()-B0.min()) B[:,:,:,1]=B[:,:,:,0] B[:,:,:,2]=B[:,:,:,0] M=B #M[D>0,:]=pylab.ones_like(M[D>0,:]) for ii in range(len(actives)): if actives[ii]: if len(cluster_list)>ii: for node in cluster_list[ii]: (i,j,k)=node2voxel[str(node)] M[i,j,k,:]=[B[i,j,k,l]*colors[ii][l] for l in range(3)] plt.figure() plt.subplot(221) j0 = round(M.shape[1]*0.5) lj = plt.imshow(M[:,j0,:,:].swapaxes(0,1),interpolation='None',aspect=aspect1) plt.axis([0, sh[0], 0, sh[2]]) plt.subplot(222) i0 = round(M.shape[0]*0.5) li = plt.imshow(M[i0,:,:,:].swapaxes(0,1),interpolation='None',aspect=aspect2) plt.axis([0, sh[1], 0, sh[2]]) plt.subplot(223) k0 = round(M.shape[2]*0.5) lk = plt.imshow(M[:,:,k0,:].swapaxes(0,1),interpolation='None',aspect=aspect3) plt.axis([0, sh[0], 0, sh[1]]) axcolor = 'lightgoldenrodyellow' axi = plt.axes([0.55, 0.3, 0.4, 0.03], axisbg=axcolor) axj = plt.axes([0.55, 0.2, 0.4, 0.03], axisbg=axcolor) axk = plt.axes([0.55, 0.1, 0.4, 0.03], axisbg=axcolor) si = Slider(axi, 'i', 0, sh[0]-1, valinit=i0,valfmt='%i') sj = Slider(axj, 'j', 0, sh[1]-1, valinit=j0,valfmt='%i') sk = Slider(axk, 'k', 0, sh[2]-1, valinit=k0,valfmt='%i') def update(val): i = int(si.val) j = int(sj.val) k = int(sk.val) lj.set_data(M[:,j,:,:].swapaxes(0,1)) li.set_data(M[i,:,:,:].swapaxes(0,1)) lk.set_data(M[:,:,k,:].swapaxes(0,1)) plt.draw() si.on_changed(update) sj.on_changed(update) sk.on_changed(update) rax = plt.axes([0.025, 0.5, 0.1, 0.15], axisbg=axcolor) check = CheckButtons(rax, ('0', '1', '2'), actives=actives) def showcluster(label): i0=int(si.val) j0=int(sj.val) k0=int(sk.val) M=B for node in cluster_list[int(label)]: (i,j,k)=node2voxel[str(node)] if all(M[i,j,k,:]==colors[int(label)]): M[i,j,k,:]=[1,1,1] else: M[i,j,k,:]=colors[int(label)] lj.set_data(M[:,j0,:,:].swapaxes(0,1)) li.set_data(M[i0,:,:,:].swapaxes(0,1)) lk.set_data(M[:,:,k0,:].swapaxes(0,1)) plt.draw() check.on_clicked(showcluster) return
class HilbertGUI(object): def __init__(self, config, debug=False): """ :param config: If a string, then treat it as a filename of a YAML config file; if a dictionary then treat it as the config dictionary itself. For each dictionary in `config['data']`, a new matrix, colorbar, and slider will be created using the filename and colormap specified. The matrices for the files will be plotted on the same Axes. There is no limit, but colors get complicated quickly with, say, >3 files. Example config dict:: { 'dim': 128, 'genome': 'hg19', 'chrom': 'chr10', 'data': [ {'filename': '../data/cpg-islands.hg19.chr10.bed', 'colormap': 'Blues'}, {'filename': '../data/refseq.chr10.exons.bed', 'colormap': 'Reds'} ] } Example YAML file:: dim: 128 chrom: chr10 genome: hg19 data: - filename: ../data/cpg-islands.hg19.chr10.bed colormap: Blues - filename: ../data/refseq.chr10.exons.bed colormap: Reds :param debug: If True, then print some extra debugging info :param kwargs: Additional keyword arguments are passed to HilbertMatrix (e.g., m_dim, genome, chrom) """ self.config = self._parse_config(config) self.matrix_dim = self.config['dim'] kwargs = dict( matrix_dim=self.config['dim'], genome=self.config['genome'], chrom=self.config['chrom']) self.hilberts = [] self.colormaps = [] for chunk in self.config['data']: self.hilberts.append(HilbertMatrix(chunk['filename'], **kwargs)) self.colormaps.append(getattr(matplotlib.cm, chunk['colormap'])) for h in self.hilberts: h.mask_low_values() self.debug = debug self.n = len(self.config['data']) self.fig = plt.figure(figsize=(8, 8)) def _parse_config(self, config): if isinstance(config, basestring): config = yaml.load(open(config)) self._validate_config(config) return config def _validate_config(self, config): # TODO: more work on validation assert 'data' in config def _make_main_axes(self): self.ax = plt.Axes(self.fig, (0.1, 0.1, 0.8, 0.8)) # formatting: remove ticklabels on the main axes since they're not # meaningful self.ax.set_xticks([]) self.ax.set_yticks([]) self.divider = make_axes_locatable(self.ax) self.fig.add_axes(self.ax) def _make_colorbar_axes(self): cax_total_width = 0.4 cax_total_padding = 0.8 width = cax_total_width / self.n pad = cax_total_padding / self.n self.caxes = [] for i in range(self.n): self.caxes.append( self.divider.append_axes('right', size=width, pad=pad)) def _make_alpha_slider_axes(self): # Alpha sliders. self.slider_axes = [] for i in range(self.n): self.slider_axes.append( self.divider.append_axes('bottom', size=0.1, pad=0.1)) def _make_min_slider_axes(self): return self.min_slider_ax1 = plt.Axes(self.fig, (0.7, 0.07, 0.07, 0.02)) self.min_slider_ax2 = plt.Axes(self.fig, (0.7, 0.02, 0.07, 0.02)) self.fig.add_axes(self.min_slider_ax1) self.fig.add_axes(self.min_slider_ax2) def _make_annotation_axes(self): self.annotation_ax = plt.Axes( self.fig, (0.1, 0.9, 0.8, 0.05), frame_on=False) self.annotation_ax.set_xticks([]) self.annotation_ax.set_yticks([]) # necessary to capture the canvas before drawing new things to it. # otherwise, old chrom coordinates are left on the canvas. #http://stackoverflow.com/questions/6286731/ \ #animating-matplotlib-panel-blit-leaves-old-frames-behind self.fig.canvas.draw() self.background = self.fig.canvas.copy_from_bbox( self.annotation_ax.bbox) self.current_position_label = self.annotation_ax.text( .5, .5, 'position...', horizontalalignment='center', verticalalignment='center', size=10, animated=True) self.fig.add_axes(self.annotation_ax) def _make_checkbox_axes(self): self.check_ax = plt.Axes(self.fig, (0.02, 0.02, 0.6, 0.1)) self.fig.add_axes(self.check_ax) def _make_radio_axes(self): self.radio_ax = plt.Axes(self.fig, (0.85, 0.02, 0.1, 0.1)) self.fig.add_axes(self.radio_ax) def _imshow_matrices(self): self.mappables = [] for i in range(self.n): h = self.hilberts[i] cmap = self.colormaps[i] if i == 0: picker = 5 else: picker = None self.mappables.append( self.ax.imshow( h.masked, interpolation='nearest', origin='upper', cmap=cmap, picker=picker)) # Initialize alphas for m in self.mappables: m.set_alpha(0.5) def _matrix_colorbars(self): # colorbars self.cbars = [] for i in range(self.n): m = self.mappables[i] cax = self.caxes[i] self.cbars.append(plt.colorbar(m, cax=cax)) # Tweak colorbar labels for cbar in self.cbars: for txt in cbar.ax.get_yticklabels(): txt.set_size(8) def _init_alpha_sliders(self): # Set up sliders with sensible default labels self.sliders = [] for i in range(self.n): fn = self.config['data'][i]['filename'] label = '%s: %s' % (string.letters[i], os.path.basename(fn)) slider = Slider( self.slider_axes[i], label, valmin=0, valmax=1, valinit=0.5) slider.label.set_size(10) self.sliders.append(slider) #self.slider1.poly.set_color('#7a0510') #self.slider2.poly.set_color('#08316d') def _init_min_sliders(self): return self.min_slider1 = Slider( self.min_slider_ax1, 'min', valmin=self.h1.masked.min(), valmax=self.h1.masked.max(), valinit=0) self.min_slider2 = Slider( self.min_slider_ax2, 'min', valmin=self.h2.masked.min(), valmax=self.h2.masked.max(), valinit=0) self.min_slider1.poly.set_color('#7a0510') self.min_slider2.poly.set_color('#08316d') self.min_slider1.label.set_size(10) self.min_slider2.label.set_size(10) def _init_checks(self): self.check_labels = [] self.check_display = [] for i in range(self.n): fn = self.config['data'][i]['filename'] label = '%s' % (os.path.basename(fn)) self.check_labels.append(label) self.check_display.append(self.mappables[i]) self.checks = CheckButtons(self.check_ax, self.check_labels, \ self.check_display) def _init_radio(self): # For controlling log/linear color scale self.radio = RadioButtons( self.radio_ax, labels=['log', 'linear'], active=1) def _make_connections(self): # Alpha sliders for i in range(self.n): self.sliders[i].on_changed( self._slider_callback_factory( self.mappables[i], self.cbars[i])) """ # Min sliders change thresh self.min_slider1.on_changed( self._min_slider_callback_factory( self.h1, self.mappable1, self.cbar1)) self.min_slider2.on_changed( self._min_slider_callback_factory( self.h2, self.mappable2, self.cbar2)) """ # Radio callback changes color scale self.radio.on_clicked(self._radio_callback) #Checkbox callback changes what hilberts are shown self.checks.on_clicked(self._check_callback) self.fig.canvas.mpl_connect('motion_notify_event', self._coord_tracker) self.fig.canvas.mpl_connect('pick_event', self._coord_callback) def plot(self): """ Does most of the work to set up the figure, axes, and widgets. """ # These methods construct axes in the right places self._make_main_axes() self._make_colorbar_axes() self._make_alpha_slider_axes() self._make_min_slider_axes() self._make_annotation_axes() self._make_radio_axes() self._make_checkbox_axes() # Plot the matrices and their colorbars self._imshow_matrices() self._matrix_colorbars() # Initialize the various widgets self._init_alpha_sliders() self._init_min_sliders() self._init_radio() self._init_checks() # Connect callbacks to events self._make_connections() def _coord_tracker(self, event): """ Callback that updates text based on the genomic coords of the current mouse position. """ # Restore original background self.fig.canvas.restore_region(self.background) # These will be None if the mouse is not in an Axes, so the string # should be empty. # # Also, make sure we're in the imshow Axes -- don't want crazy genomic # coords from being in the colorbar or annotation Axes x = event.xdata y = event.ydata if (x is None) or (y is None) or (event.inaxes is not self.ax): s = "" # Get matrix coords else: xi = int(round(x)) yi = int(round(y)) # If you move the mouse off the edge of the main Axes, rounding to # the nearest row or col may get you a value that's greater than # the number of rows/cols. In this case, treat it similar to being # out of the Axes, with an empty string. if (xi >= self.matrix_dim) or (yi >= self.matrix_dim): s = "" else: # Genomic coords from (x,y) s = '%s:%s-%s' % self.hilberts[0].xy2chrom(xi, yi) v = [] for letter, h in zip(string.letters, self.hilberts): v.append('%s=%s' % (letter, h.matrix[yi, xi])) s += self._xy_to_value_string(xi, yi) # Update text, redraw just the text object, and blit the background # previously saved self.current_position_label.set_text(s) self.annotation_ax.draw_artist(self.current_position_label) self.fig.canvas.blit(self.annotation_ax.bbox) def _xy_to_value_string(self, x, y): v = [] for letter, h in zip(string.letters, self.hilberts): v.append('%s=%s' % (letter, h.matrix[y, x])) return '; '.join(v) def _coord_callback(self, event): x = event.mouseevent.xdata y = event.mouseevent.ydata xi = int(round(x)) yi = int(round(y)) if self.debug: print print 'mouse x:', x, 'xi:', xi print 'mouse y:', y, 'yi:', yi s = '%s:%s-%s' % self.hilberts[0].xy2chrom(xi, yi) s += '\n' + self._xy_to_value_string(xi, yi) print s sys.stdout.flush() def _radio_callback(self, label): # Hello? Am I the 9th caller!? if label == 'log': self._log() elif label == 'linear': self._linear() else: raise ValueError("unspecified label for radio button") def _check_callback(self, label): for i in xrange(len(self.check_labels)): if label == self.check_labels[i]: self.mappables[i].set_visible(not \ self.mappables[i].get_visible()) plt.draw() def _slider_callback_factory(self, mappable, cbar): """ Given a mappable (i.e., object returned from imshow()), return a function that will modify it based on the slider's value. """ def _slider_callback(x): mappable.set_alpha(x) cbar.set_alpha(x) cbar.update_normal(mappable) return _slider_callback def _min_slider_callback_factory(self, h, mappable, cbar): def _min_slider_callback(x): h.mask_low_values(min_val=x) mappable.set_data(h.masked) return _min_slider_callback def _log(self): """ Update colomaps of the plotted images to use log-scaled color """ for i in range(self.n): norm = matplotlib.colors.LogNorm( vmin=self.hilberts[i].masked.min(), vmax=self.hilberts[i].masked.max()) self.mappables[i].set_norm(norm) self.cbars[i].set_norm(norm) self.cbars[i].update_normal(self.mappables[i]) plt.draw() def _linear(self): """ Update colormaps of the plotted images to use linear-scaled color """ for i in range(self.n): norm = matplotlib.colors.Normalize( vmin=self.hilberts[i].masked.min(), vmax=self.hilberts[i].masked.max()) self.mappables[i].set_norm(norm) self.cbars[i].set_norm(norm) self.cbars[i].update_normal(self.mappables[i]) plt.draw()
def svdplot(input_data, fmax=None, hold=0): if hold==0: pl.clf() # erase the figure, as this is a mult- axis plot else: pl.clf() # do it anyway, trying to overcome checkbuttons problem n_SV = len(input_data.svs) #for chrono in input_data.chronos: # print(peak_freq(chrono, input_data.dim1)) # define axes ax1 = pl.subplot(221) ax2 = pl.subplot(222) ax3 = pl.subplot(223) ax4 = pl.subplot(224) # allow space for check buttons pl.subplots_adjust(left=0.2, right=0.98) # setup check boxes rax = pl.axes([0.01, 0.05, 0.09, 0.9]) # CheckButtons take tuple arguments, tuples are immutable, so create lists fom svd info, and then cast as tuple button_name_list=[] button_setting_list=[] for i in range(n_SV): button_name_list.append(' '+str(i)) button_setting_list.append(False) # have first 2 SVs on as default for i in [0,1]: button_setting_list[i] = True # like "self" check = CheckButtons(rax, tuple(button_name_list), tuple(button_setting_list)) # hack to make check buttons square check_box_stretch = 7 for i in range(len(check.rectangles)): #if (1 == 0): # use this line instead of for i in... to turn off the hack check.rectangles[i].set_width(check_box_stretch*check.rectangles[i].get_height()) for j in [0,1]: # two lines of the x orig_x_data = check.lines[i][j].get_xdata() orig_y_data = check.lines[i][j].get_ydata() orig_width = orig_x_data[1]-orig_x_data[0] new_width = check_box_stretch*orig_width new_x_data = [orig_x_data[0],orig_x_data[0]+new_width] check.lines[i][j].set_data(new_x_data,orig_y_data) # plot all SVs, use button_setting_list for initial visibility # axes 1: chrono pl.axes(ax1) #pl.xlabel('Time -*-get units from Timebase-*-') pl.ylabel('chronos [a.u.]') # used to be labelled amplitude, but is not really. # you can get to the reconstructed signals via fs.signal, but chronos is better here ## python3 - all these plot_lists refactored to look nicer in python2/3 plot_list_1 = [ ax1.plot(np.arange(len(input_data.chronos[sv_i])), input_data.chronos[sv_i], visible= button_setting_list[sv_i],alpha=0.5)[0] for sv_i in range(n_SV)] #pl.xlim(min(input_data.dim1), max(input_data.dim1)) # axes 2: SVs pl.axes(ax2) sv_sv = [input_data.svs[i] for i in range(n_SV)] ax2.semilogy(np.arange(n_SV),sv_sv,'ko',markersize=3) # avoid extreme ylim ranges - start with no more than 10^3 (ymin,ymax) = ax2.get_ylim() ax2.set_ylim(max(ymin, ymax/1000), ymax) entropy = input_data.H pl.xlabel('Singular Value number') pl.ylabel('Singular Value') # pl.figtext(0.75,0.83,'1/H = %.2f' %(1./entropy),fontsize=12, color='r') # pl.figtext(0.75,0.81,'H = %.2f' %(entropy),fontsize=12, color='b') # this is done in two places - potential for inconsistency - wish I knew better -dgp # These changes make it easier to adjust the subplot layout # was pl.figtext(0.75,0.78, (relative to figure), make it relative to axes # Use kwargs so that most formatting is common to all three labels. kwargs={'fontsize':8,'transform':ax2.transAxes, 'horizontalalignment':'right', 'verticalalignment':'top'} bsl = np.array(button_setting_list) RMS_scale=np.sqrt(np.mean( (input_data.scales[:,0]*bsl)**2)) ### Note: amp is dodgy - calcualted roughly here ## reconsider how fs p is calculated! maybe factor scales in before sum ## Note also - a12 is calcuated differently here but looks OK # Also, shold update these like Dave does with Energy amp=np.sqrt(np.sum(input_data.p*bsl))*RMS_scale print("amp=%.3g:" % (amp)), energy = Energy(input_data.p,bsl) energy_label = ax2.text(0.96,0.98,'E = %.1f %%' %(100.*energy.value), color='b', **kwargs) labstr = str('tmid = {tm:.1f} ms, 1/H = {invH:.2f}, below for 0,1, '\ '?Amp = {Amp:.2g}, a12 = {a12:.2f} ' .replace(', ','\n') .format(tm=1e3*np.average(input_data.chrono_labels), invH=(1./entropy), Amp = float(np.sqrt(np.sum(input_data.p*bsl))*RMS_scale), a12 = float(np.sqrt(input_data.p[1]/input_data.p[0])))) ax2.text(0.96,0.85,labstr, color='r', **kwargs) # grid('True') plot_list_2 = [] for sv_i in range(n_SV): col = plot_list_1[sv_i].get_color() plot_list_2.append(ax2.semilogy([sv_i], [input_data.svs[sv_i]], '%so' %(col),visible= button_setting_list[sv_i], markersize=8,alpha=0.5)[0]) # axes 3: fft(chrono) pl.axes(ax3) pl.xlabel('Frequency [kHz]') pl.ylabel('Power Spectrum') pl.grid(True) # matplotlib 1.0.X wants a boolean (unquoted) nyquist_kHz = 1.e-3*0.5/np.average(np.diff(input_data.chrono_labels)) plot_list_3 = [] for sv_i in range(n_SV): col = plot_list_1[sv_i].get_color() tmp_chrono = input_data.chronos[sv_i] tmp_fft = np.fft.fft(tmp_chrono)[:len(tmp_chrono)//2] freq_array = nyquist_kHz*np.arange(len(tmp_fft))/(len(tmp_fft)-1) plot_list_3.append(ax3.plot(freq_array, abs(tmp_fft), col,visible= button_setting_list[sv_i],alpha=0.5)[0]) if fmax is None: ffact = 1e3 # seems like this routine is in kHz - where does it cvt? try: axt = eval(pyfusion.config.get('Plots','FT_Axis')) if axt[3]<2e3: ffact=1.0 # avoid a python3 issue fmax = axt[3]/ffact except: fmax = nyquist_kHz pl.xlim(0,fmax) # axes 4: topo pl.axes(ax4) pl.xlabel('Channel') pl.ylabel('Topo [a.u.]') angle_array = np.arange(n_SV+1) #channel_names = input_data.timesegment.data[input_data.diagnostic.name].ordered_channel_list #channel_names.append(channel_names[0]) #pl.xticks(angle_array,channel_names, rotation=90) plot_list_4 = [] for sv_i in range(n_SV): col = plot_list_1[sv_i].get_color() tmp_topo = join_ends(input_data.topos[sv_i]) pos,neg = posNegFill(angle_array,np.zeros(len(angle_array)),tmp_topo) ### BUG: it looks like ax4.fill doesn't work in a couple of cases, leaving sub_plot_4_list[i] as int, which raises a set_visible() bug in button_action - also has problems with draw(). other subplots all worked fine before I started with subplot 4 sub_plot_4_list = list(range(len(pos)+len(neg)+2)) for j in range(len(pos)): sub_plot_4_list[j], = ax4.fill(pos[j][0],pos[j][1],col,visible= button_setting_list[sv_i],alpha=0.5) for j in range(len(neg)): sub_plot_4_list[j+len(pos)], = ax4.fill(neg[j][0],neg[j][1],col,visible= button_setting_list[sv_i],alpha=0.5) sub_plot_4_list[len(neg)+len(pos)+0], = ax4.plot(angle_array,tmp_topo,'%so' %(col),visible= button_setting_list[sv_i],markersize=3) # show repeated val sub_plot_4_list[len(neg)+len(pos)+1], = ax4.plot([angle_array[-1]],[tmp_topo[-1]],'kx', visible= button_setting_list[sv_i],markersize=6) debug_(pyfusion.DEBUG, 2, key='svdplot') plot_list_4.append(sub_plot_4_list) def test_action(label): print(label) def button_action(label): print('action') # this is not very clear: but basically, the label is the str() of the element of plot_list_x we want to make / unmake visible visible_status = plot_list_1[int(label)].get_visible() plot_list_1[int(label)].set_visible(not visible_status) plot_list_2[int(label)].set_visible(not visible_status) plot_list_3[int(label)].set_visible(not visible_status) for i in range(len(plot_list_4[int(label)])): plot_list_4[int(label)][i].set_visible(not visible_status) # if visible_status == False, then we are adding visiblity => add to energy, vice-verca if visible_status: energy.sub(int(label)) else: energy.add(int(label)) energy_label._text='E = %.2f %%' %(100.*energy.value) pl.draw() # action when button is clicked check.on_clicked(button_action) #check.on_clicked(test_action) # show plot pl.show(block=hold)
def run_main( A, B, C, dA, dB, dC, DJ, DJK, DK, dJ, dK, ua, ub, uc, f_lower, f_upper, T, last_times_picked_list, number_of_skips, spectrum_filename=None, peaklist=None, ): # matplotlib.use('TkAggx') global DJ_g, DJK_g, DK_g, ua_g, ub_g, uc_g, T_g, dJ_g, dK_g, f_lower_g, f_upper_g DJ_g = DJ DJK_g = DJK DK_g = DK ua_g = ua ub_g = ub uc_g = uc T_g = T dJ_g = dJ dK_g = dK f_lower_g = f_lower f_upper_g = f_upper global picked_list picked_list = last_times_picked_list plt.close() global figure_h figure_h = plt.figure(figsize=(16.5, 4)) try: figure_h.canvas.manager.window.Move((00, 00)) except AttributeError: pass # thismanager = pl.get_current_fig_manager() # thismanager.window.SetPosition((00, 0)) # thismanager.window.wm_geometry("+00+0") int_writer(ua, ub, uc, temp=T_g, freq=(f_upper_g / 1000)) var_writer_uncert(A, B, C, DJ, DJK, DK, dJ_g, dK_g) run_SPCAT() data = cat_reader() global t global s t = [] s = [] t_b = [] s_b = [] for x in data: s.append(0.0) s.append(str(10 ** float(x[1]))) s.append(0.0) t.append(float(x[0]) - 0.0001) t.append(x[0]) t.append(float(x[0]) + 0.0001) for y in picked_list: if x[2] == y[1] and x[3] == y[2]: s_b.append(0.0) s_b.append(str(10 ** float(x[1]))) s_b.append(0.0) t_b.append(float(x[0]) - 0.0001) t_b.append(x[0]) t_b.append(float(x[0]) + 0.0001) ax = figure_h.add_subplot(212) plt.subplots_adjust(left=0.25, bottom=0.25) a0 = 5 f0 = 3 global l l, = plt.plot(t, s, lw=2, color="red") ax.set_xlim([f_lower_g, f_upper_g]) global picked_plt picked_plt, = plt.plot(t_b, s_b, lw=2, color="black") # plt.axis([0, 1, -10, 10]) # figure_h.canvas.mpl_connect('button_press_event', handle_mouse_press) ax2 = figure_h.add_subplot(211, sharex=ax) try: ax2.scatter(peaklist[:, 0], peaklist[:, 1], color="red") ax2.set_xlim([f_lower_g, f_upper_g]) except TypeError or IOError: pass try: fh = open(spectrum_filename) spectrum_list_F = [] spectrum_list_I = [] counter = 0 for line in fh: counter += 1 if counter % (number_of_skips + 1) == 0: spectrum_list_F.append(line.split()[0]) spectrum_list_I.append(line.split()[1]) else: pass ax2.plot(spectrum_list_F, spectrum_list_I, lw=2, color="black") ax2.set_xlim([f_lower_g, f_upper_g]) except TypeError or IOError: pass figure_h.canvas.mpl_connect("key_press_event", on_key) axcolor = "lightgoldenrodyellow" axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) axB = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axC = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) global A_slider global B_slider global C_slider global rax rax = plt.axes([0.0, 0.5, 0.19, 0.4]) global check check = CheckButtons(rax, ("", "", "", ""), (True, False, False, False)) check.on_clicked(func) A_slider = Slider(axA, "A", A - dA, A + dA, valinit=A) B_slider = Slider(axB, "B", B - dB, B + dB, valinit=B) C_slider = Slider(axC, "C", C - dC, C + dC, valinit=C) A_slider.on_changed(update) B_slider.on_changed(update) C_slider.on_changed(update) global button global radio resetax = plt.axes([0.1, 0.025, 0.1, 0.04]) button = Button(resetax, "Reset Sliders", color=axcolor, hovercolor="0.975") button.on_clicked(reset) # rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) # radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) # radio.on_clicked(colorfunc) global text_box # global text_box2 text_box = plt.text(-1, 6, "") text_box2 = plt.text( -1, 23, "Refine Mouse Selection: Select transitions by pushing 'q' and then clicking in the predicted spectrum ", ) plt.show()
def evaluateKineticsGroupValues(family, database, method, testSetLabels, plot, exactOnly=False, estimateOnly=False): """ Evaluate the kinetics group additivity values for the given reaction `family` using the specified lists of depository components `testSetLabels` as the test set. The already-loaded RMG database should be given as the `database` parameter. """ kunits = family.getRateCoefficientUnits() assert not (exactOnly and estimateOnly) print 'Categorizing reactions in test sets for {0}'.format(family.label) testSets0 = [] for testSetLabel in testSetLabels: testSet = createDataSet(testSetLabel, family, database) testSets0.append((testSetLabel, testSet)) for testSetLabel, testSet in testSets0: for index in range(len(testSet)): reaction, template, entry = testSet[index] for reactant in reaction.reactants: if isinstance(reactant, Species) and not reactant.label and len(reactant.molecule) > 0: reactant.label = reactant.molecule[0].toSMILES() for product in reaction.products: if isinstance(product, Species) and not product.label and len(product.molecule) > 0: product.label = product.molecule[0].toSMILES() # For each entry in each test set, determine the kinetics as predicted by # RMG-Py and as given by the entry in the test set # Note that this is done on a per-site basis! kineticsModels = []; kineticsData = [] testSets = [] for testSetLabel, testSet0 in testSets0: testSet = [] for index in range(len(testSet0)): reaction, template, entry = testSet0[index] krule = family.getKineticsForTemplate(template, degeneracy=1, method='rate rules') kgroup = family.getKineticsForTemplate(template, degeneracy=1, method='group additivity') kdata = convertKineticsToPerSiteBasis(reaction.kinetics, reaction.degeneracy) if exactOnly and not re.search('Exact', krule.comment): continue elif estimateOnly and not re.search('Estimated', krule.comment): continue testSet.append((reaction, template, entry, krule, kgroup, kdata)) testSets.append((testSetLabel, testSet)) # Generate parity plots at several temperatures print 'Generating parity plots for {0}'.format(family.label) import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons Tdata = [500,1000,1500,2000] if kunits == 'm^3/(mol*s)': kunits = 'cm$^3$/mol*s'; kfactor = 1.0e6 elif kunits == 's^-1': kunits = 's$^{-1}$'; kfactor = 1.0 for T in Tdata: stdev_total = 0; ci_total = 0; count_total = 0 # Initialize plot if plot == 'interactive': fig = pylab.figure(figsize=(10,8)) ax = plt.subplot(1, 1, 1) else: fig = pylab.figure(figsize=(6,5)) ax = plt.subplot(1, 1, 1) ax = plt.subplot(1, 1, 1) lines = [] legend = [] # Iterate through the test sets, plotting each for testSetLabel, testSet in testSets: kmodel = []; kdata = [] stdev = 0; ci = 0; count = 0 for reaction, template, entry, kineticsRule, kineticsGroup, kineticsData in testSet: if method == 'rate rules': kineticsModel = kineticsRule elif method == 'group additivity': kineticsModel = kineticsGroup # Honor temperature ranges when plotting data # Place a dummy value so that the points so that the # interactivity is still correct if not kineticsData.isTemperatureValid(T): kmodel.append(0.0) kdata.append(0.0) continue # Evaluate k(T) for both model and data at this temperature if isinstance(kineticsModel, ArrheniusEP): km = kineticsModel.getRateCoefficient(T, 0) * kfactor else: km = kineticsModel.getRateCoefficient(T) * kfactor kmodel.append(km) if isinstance(kineticsData, ArrheniusEP): kd = kineticsData.getRateCoefficient(T, 0) * kfactor else: kd = kineticsData.getRateCoefficient(T) * kfactor kdata.append(kd) # Evaluate variance stdev += (math.log10(km) - math.log10(kd))**2 count += 1 stdev_total += stdev count_total += count stdev = math.sqrt(stdev / (count - 1)) ci = scipy.stats.t.ppf(0.975, count - 1) * stdev assert len(kmodel) == len(testSet) assert len(kdata) == len(testSet) print "Test set {0} contained {1} rates.".format(testSetLabel, count) print 'Confidence interval at T = {0:g} K for test set "{1}" = 10^{2:g}'.format(T, testSetLabel, ci) # Add this test set to the plot lines.append(ax.loglog(kdata, kmodel, 'o', picker=5)[0]) legend.append(testSetLabel) stdev_total = math.sqrt(stdev_total / (count_total - 1)) ci_total = scipy.stats.t.ppf(0.975, count_total - 1) * stdev_total print 'Total confidence interval at T = {0:g} K for all test sets = 10^{1:g}'.format(T, ci_total) # Finish plots xlim = pylab.xlim() ylim = pylab.ylim() lim = (min(xlim[0], ylim[0])*0.1, max(xlim[1], ylim[1])*10) ax.loglog(lim, lim, '-k') ax.loglog(lim, [lim[0] * 10**ci_total, lim[1] * 10**ci_total], '--k') ax.loglog(lim, [lim[0] / 10**ci_total, lim[1] / 10**ci_total], '--k') pylab.xlabel('Actual rate coefficient ({0})'.format(kunits)) pylab.ylabel('Predicted rate coefficient ({0})'.format(kunits)) if len(testSets) > 1: pylab.legend(legend, loc=4, numpoints=1) pylab.title('%s, T = %g K' % (family.label, T)) pylab.xlim(lim) pylab.ylim(lim) plot_range = math.log10(lim[1] / lim[0]) if plot_range > 25: majorLocator = matplotlib.ticker.LogLocator(1e5) minorLocator = matplotlib.ticker.LogLocator(1e5, subs=[1, 10, 100, 1000, 10000]) elif plot_range > 20: majorLocator = matplotlib.ticker.LogLocator(1e4) minorLocator = matplotlib.ticker.LogLocator(1e4, subs=[1, 10, 100, 1000]) elif plot_range > 15: majorLocator = matplotlib.ticker.LogLocator(1e3) minorLocator = matplotlib.ticker.LogLocator(1e3, subs=[1, 10, 100]) elif plot_range > 10: majorLocator = matplotlib.ticker.LogLocator(1e2) minorLocator = matplotlib.ticker.LogLocator(1e2, subs=[1, 10]) else: majorLocator = matplotlib.ticker.LogLocator(1e1) minorLocator = None ax.xaxis.set_major_locator(majorLocator) ax.yaxis.set_major_locator(majorLocator) if minorLocator: ax.xaxis.set_minor_locator(minorLocator) ax.yaxis.set_minor_locator(minorLocator) def onpick(event): index = lines.index(event.artist) xdata = event.artist.get_xdata() ydata = event.artist.get_ydata() testSetLabel, testSet = testSets[index] for ind in event.ind: reaction, template, entry, krule, kgroup, kdata = testSet[ind] kunits = 'm^3/(mol*s)' if len(reaction.reactants) == 2 else 's^-1' print testSetLabel print 'template = [{0}]'.format(', '.join([g.label for g in template])) print 'entry = {0!r}'.format(entry) print str(reaction) print 'k_data = {0:9.2e} {1}'.format(xdata[ind], kunits) print 'k_model = {0:9.2e} {1}'.format(ydata[ind], kunits) print krule if kgroup: print kgroup print krule.comment if kgroup: print kgroup.comment print connection_id = fig.canvas.mpl_connect('pick_event', onpick) if plot == 'interactive': rax = plt.axes([0.15, 0.65, 0.2, 0.2]) check = CheckButtons(rax, legend, [True for label in legend]) def func(label): for index in range(len(lines)): if legend[index] == label: lines[index].set_visible(not lines[index].get_visible()) plt.draw() check.on_clicked(func) fig.subplots_adjust(left=0.10, bottom=0.10, right=0.97, top=0.95, wspace=0.20, hspace=0.20) else: fig.subplots_adjust(left=0.15, bottom=0.14, right=0.95, top=0.93, wspace=0.20, hspace=0.20) filename = '{0}_{1:g}'.format(family.label, T) if method == 'rate rules': filename += '_rules' elif method == 'group additivity': filename += '_groups' if exactOnly: filename += '_exact' elif estimateOnly: filename += '_estimate' pylab.savefig('{0}.pdf'.format(filename)) pylab.savefig('{0}.png'.format(filename), dpi=200) pylab.show()
valinit=model.params["phi0caret"], color='#AAAAAA') slider6.on_changed(model.on_changephi0caret) # Pressure slider slider_ax = plt.axes([0.1, 0.13, 0.5, 0.02]) slider7 = Slider(slider_ax, r"$p$", 100., 975., \ valinit=model.params["p"], color='#AAAAAA') slider7.on_changed(model.on_changep) # Visibility Buttons check_ax = plt.axes([0.66, 0.02, 0.06, 0.15]) labels = [f.label for f in model.fields[:5]] vis = [f.visibility for f in model.fields[:5]] check1 = CheckButtons(check_ax, labels, vis) check1.on_clicked(model.select_vis) check_ax = plt.axes([0.71, 0.02, 0.1, 0.15], aspect='equal') labels = [f.label for f in model.fields[5:10]] vis = [f.visibility for f in model.fields[5:10]] check2 = CheckButtons(check_ax, labels, vis) check2.on_clicked(model.select_vis) check_ax = plt.axes([0.79, 0.02, 0.1, 0.15], aspect='equal') labels = [f.label for f in model.fields[10:]] vis = [f.visibility for f in model.fields[10:]] check3 = CheckButtons(check_ax, labels, vis) check3.on_clicked(model.select_vis) plt.show()
rb1_axes = plt.axes([0.70, 0.62, 0.10, 0.15], axisbg=axcolor) radio1 = RadioButtons(rb1_axes, ('A', 'B', 'C')) def rb_1(label): print 'radio button 1' radio1.on_clicked(rb_1) rax = plt.axes([0.70, 0.3, 0.2, 0.25]) labels=['Type 1','Type 2', 'Type 4', 'Other'] check = CheckButtons(rax, (labels[0], labels[1], labels[2], labels[3]), (False, False, False, False)) def func(label): if label == labels[0]: check_text=labels[0] elif label == labels[1]: check_text=labels[1] elif label == labels[2]: check_text=labels[2] elif label == labels[3]: check_text=labels[3] print 'checked: ', check_text check.on_clicked(func) ax.text=(0.9, 0.9, 'ax.text 0.5') fig.text=(0.9, 0.9, 'fig.text 0.5') plt.show() #if __name__=='__main__':
def initialize(A,B,C,dA,dB,dC,DJ,DJK,DK,dJ,dK,ua,ub,uc,f_lower,f_upper,T,J_max,last_times_picked_list): #matplotlib.use('TkAggx') global DJ_g,DJK_g,DK_g,ua_g,ub_g,uc_g,T_g,dJ_g,dK_g,f_lower_g,f_upper_g,J_max_g J_max_g = J_max DJ_g = DJ DJK_g = DJK DK_g = DK ua_g = ua ub_g = ub uc_g = uc T_g=T dJ_g = dJ dK_g = dK f_lower_g = f_lower f_upper_g = f_upper global picked_list picked_list = last_times_picked_list plt.close() global figure_h figure_h = plt.figure(figsize=(16.5, 4)) try: figure_h.canvas.manager.window.Move((00,00)) except AttributeError: pass #thismanager = pl.get_current_fig_manager() #thismanager.window.SetPosition((00, 0)) #thismanager.window.wm_geometry("+00+0") int_writer(ua,ub,uc,temp=T_g,freq=(f_upper_g/1000)) var_writer_uncert(A,B,C,DJ,DJK,DK,dJ_g,dK_g) run_SPCAT() data = cat_reader() global t global s t = [] s = [] t_b = [] s_b = [] for x in data: s.append(0.0) s.append(str(10**float(x[1]))) s.append(0.0) t.append(float(x[0])-0.0001) t.append(x[0]) t.append(float(x[0])+0.0001) for y in picked_list: if x[2]==y[1] and x[3]==y[2]: s_b.append(0.0) s_b.append(str(10**float(x[1]))) s_b.append(0.0) t_b.append(float(x[0])-0.0001) t_b.append(x[0]) t_b.append(float(x[0])+0.0001) ax = figure_h.add_subplot(212) plt.subplots_adjust(left=0.25, bottom=0.25) pl.subplots_adjust( hspace=0.0,right=0.97 ) a0 = 5 f0 = 3 global l,triples_plt l, = plt.plot(t,s, lw=2, color='red') triples_plt, = plt.plot([],[], '*',markersize=15,color='blue') ax.set_xlim([f_lower_g,f_upper_g]) global picked_plt, ax2 picked_plt, = plt.plot(t_b,s_b,lw=2,color='black') #plt.axis([0, 1, -10, 10]) #figure_h.canvas.mpl_connect('button_press_event', handle_mouse_press) ax2 = figure_h.add_subplot(211,sharex=ax) ax2.axes.get_xaxis().set_visible(False) global peak_list_plt,exp_plt,trans_1_plt,trans_2_plt,trans_3_plt peak_list_plt, = ax2.plot([],[],'o',color='red') trans_1_plt, = ax2.plot([],[],'s',color='cyan') trans_2_plt, = ax2.plot([],[],'s',color='magenta') trans_3_plt, = ax2.plot([],[],'s',color='yellow') ax2.set_xlim([f_lower_g,f_upper_g]) global locator locator = ax2.yaxis.get_major_locator() exp_plt, = ax2.plot([],[],lw=2,color='black') global peak_1_uncertainty,peak_2_uncertainty,peak_3_uncertainty,peaklist,freq_low,freq_high figure_h.canvas.mpl_connect('key_press_event', on_key) axcolor = 'lightgoldenrodyellow' axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) axB = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axC = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) axua = plt.axes([0.03, 0.22, 0.1, 0.03], axisbg=axcolor) axub = plt.axes([0.03, 0.17, 0.1, 0.03], axisbg=axcolor) axuc = plt.axes([0.03, 0.12, 0.1, 0.03], axisbg=axcolor) #axub = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) #axuc = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) global ua_slider ua_slider = Slider(axua, 'mu a', ua_g-1, ua_g+1, valinit=ua_g) ua_slider.on_changed(update) global ub_slider ub_slider = Slider(axub, 'mu b', ub_g-1, ub_g+1, valinit=ub_g) ub_slider.on_changed(update) global uc_slider uc_slider = Slider(axuc, 'mu c', uc_g-1, uc_g+1, valinit=uc_g) uc_slider.on_changed(update) global A_slider global B_slider global C_slider global rax rax = plt.axes([0.0, 0.5, 0.19, 0.4]) global check check = CheckButtons(rax, ('','','',''), (True, False, False,False)) check.on_clicked(func) A_slider = Slider(axA, 'A', A-dA, A+dA, valinit=A) B_slider = Slider(axB, 'B', B-dB, B+dB, valinit=B) C_slider = Slider(axC, 'C', C-dC, C+dC, valinit=C) A_slider.on_changed(update) B_slider.on_changed(update) C_slider.on_changed(update) global button global radio resetax = plt.axes([0.1, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset Sliders', color=axcolor, hovercolor='0.975') button.on_clicked(reset) #rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) #radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) #radio.on_clicked(colorfunc) global text_box #global text_box2 text_box = plt.text(-1,8, "") text_box2 = plt.text(-1,23, "Refine Mouse Selection: Select transitions by pushing 'q' and then clicking in the predicted spectrum ")
class Graphics (GraphMolecule, GraphBias, GraphTrans, GraphOrbitals, GraphIVCurve): """ Manages the graphical representation of the project Attributes fig Handle to the entire figure Bias The selected bias Gate The selected gate voltage OrbitalSel The selected orbital or series of orbitals axSC Handle to the radio buttons window for the self consistency cbSC Handle to the radio buttons for the self consistency axOptions1 Handle to the checkbox window with options 1 cbOptions1 Handle to the checkboxes with options 1 axOptions2 Handle to the checkbox window with options 2 cbOptions2 Handle to the checkboxes with options 2 axGleft, axGright Handle to the slider windows for selecting the lead interaction strength sGleft, sGright Handle to the sliders for selecting the lead interaction strength axSave Handle to the save button window bSave Handle to the save button Methods init() OnPick(event) Manages the pick events OnClick(event) Manages the on click events Save() Manages the input from the save button Options1(label) Manages the input from the options 1 window Options2(label) Manages the input from the options 2 window SetMolecule(Mol) Sets the molecule class from which the graphics gets its information UpdateMolecule() Updates everything that changes when the molecule has changed UpdateConsistency(label)Updates the selected consistency method UpdateG(val) Updates the interaction strength with the leads UpdateBias(bias) Updates the selected bias UpdateHamExt() Updates everything that changes when the extended hamiltonian is changed UpdateGate(gate) Updates the selected gate voltage UpdateAtomSel(iAtom) Updates the selected atom UpdateOrbitalSel(iOrb) Updates the selected orbital UpdateSelection() Updates everything that changes after one of the selections has changed """ def __init__(self): self.Consistency = 'Not self consistent' self.Bias = 0.1 self.Gate = None self.OrbitalSel = None self.fig, (self.axBias, self.axTrans, self.axIVCurve) = plt.subplots(3,1) self.fig.patch.set_facecolor('ghostwhite') plt.subplots_adjust(left=0.3) pos = self.axBias.get_position() self.axBias.set_position ([pos.x0, 0.55, pos.width, 0.40]) self.axTrans.set_position([pos.x0, 0.05, pos.width, 0.40]) self.axIVCurve.set_position([0.05, 0.05, 0.2, 0.3]) self.axCM = self.fig.add_axes([0.94, 0.55, 0.01, 0.35]) self.fig.canvas.mpl_connect('button_press_event', self.OnClick) self.fig.canvas.mpl_connect('pick_event', self.OnPick) self.fig.canvas.mpl_connect('key_press_event', self.OnPress) self.InitMolecule() self.InitBias() self.InitTrans() self.InitOrbitals() self.InitIVCurve() self.axSC = plt.axes([0.05, 0.85, 0.15, 0.10], axisbg='white') self.cbSC = RadioButtons(self.axSC, ('Not self consistent', 'Hubbard', 'PPP')) self.cbSC.on_clicked(self.UpdateConsistency) self.axOptions1 = plt.axes([0.05, 0.7, 0.15, 0.10], axisbg='white') self.cbOptions1 = CheckButtons(self.axOptions1, ('Overlap', 'Show Local Density','Show Local Currents'), (False, False, True)) self.cbOptions1.on_clicked(self.Options1) self.axOptions2 = plt.axes([0.05, 0.5, 0.15, 0.15], axisbg='white') self.cbOptions2 = CheckButtons(self.axOptions2, ('Show Transmission', 'Show Current', 'Show DOS', 'Show Orbitals', 'Show Phase'), (True, True, False, False, False)) self.cbOptions2.on_clicked(self.Options2) c = ['seagreen', 'b', 'darkorange', 'lightsteelblue', 'm'] [rec.set_facecolor(c[i]) for i, rec in enumerate(self.cbOptions2.rectangles)] self.axGleft = plt.axes([0.05, 0.43, 0.15, 0.02], axisbg='white') self.axGright = plt.axes([0.05, 0.40, 0.15, 0.02], axisbg='white') self.sGleft = Slider(self.axGleft, 'Gl', 0.0, 1.0, valinit = gLeft) self.sGright = Slider(self.axGright, 'Gr', 0.0, 1.0, valinit = gRight) self.sGleft.on_changed(self.UpdateG) self.sGright.on_changed(self.UpdateG) self.axSave = plt.axes([0.92, 0.95, 0.07, 0.04]) self.bSave = Button(self.axSave, 'Save') self.bSave.on_clicked(self.Save) def OnPick(self, event): if isinstance(event.artist, Rectangle): self.OnPickOrbital(event) else: self.OnPickMolecule(event) def OnClick (self, event): if event.inaxes==self.axMol: if event.button==1: self.OnClickMolecule (event) elif event.button==3: self.OnClickBias (event) elif event.inaxes==self.axOrb: if event.button==1: return if event.button==3: self.OnClickTrans (event) return def Save(self, event): self.Mol.Save() def Options1(self, label): if label == 'Overlap': self.Mol.SetOverlap(self.cbOptions1.lines[0][0].get_visible()) self.UpdateMolecule() elif label == 'Show Local Density': self.DrawLocalDensity(self.cbOptions1.lines[1][0].get_visible()) elif label == 'Show Local Currents': self.DrawLocalCurrents(self.cbOptions1.lines[2][0].get_visible()) return def Options2(self, label): if label == 'Show Transmission': self.DrawTransmission() elif label == 'Show Current': self.DrawCurrent() elif label == 'Show DOS': self.DrawDOS() elif label == 'Show Orbitals': self.DrawOrbitals() self.DrawSelOrbitals() elif label == 'Show Phase': self.DrawTransmission() self.DrawSelTransmission() return def SetMolecule(self, Molecule): self.Mol = Molecule self.UpdateMolecule() def UpdateMolecule (self): self.Mol.CreateHam() self.Mol.CreateOverlap() self.Mol.CreateV() self.ChangeMolecule () self.ChangeMoleculeOrbitals () self.DrawMolecule () return self.UpdateHamExt () def UpdateConsistency(self, label): self.Consistency = label print "Consistency set to:", self.Consistency return self.UpdateHamExt () def UpdateG (self, val): print "Interaction strengths set to:", self.sGleft.val, self.sGright.val self.Mol.SetG (self.sGleft.val, self.sGright.val) return self.UpdateHamExt () def UpdateBias(self, bias): self.Bias = bias print "Bias voltage set to: ", self.Bias, "V" return self.UpdateHamExt () def UpdateHamExt (self): self.Mol.CreateHamExt (self.Bias, self.Consistency) self.Mol.CalcGamma() self.Mol.Density(self.Bias) self.Mol.Transmission() self.Mol.Current(self.Bias) self.Mol.CalcDOS() self.DrawLocalDensity () self.DrawBias () self.DrawTransmission () self.DrawDOS () self.DrawCurrent () self.DrawOrbitals () return self.UpdateSelection() def UpdateGate (self, gate): self.Gate = gate print "Gates voltage set to: ", self.Gate, "V" self.OrbitalSel = None self.AtomSel = None return self.UpdateSelection() def UpdateAtomSel(self, iAtom): self.AtomSel = iAtom if self.AtomSel == None: print "No atom selected" self.axMol.set_title('No atom selected') self.OrbitalSel = None elif isinstance(iAtom, int): print "Selected atom", self.Mol.Atom[self.AtomSel][0], "at", self.AtomSel, " Local density = ", self.Mol.LD[self.AtomSel, self.AtomSel] self.axMol.set_title('Selected atom: %c at %d. Density = %f'%(self.Mol.Atom[self.AtomSel][0],self.AtomSel, self.Mol.LD[self.AtomSel, self.AtomSel])) Orbitals = [] for i in range(self.Mol.N): Orbitals.append(np.real(self.Mol.eigvec[i][self.AtomSel]*np.conjugate(self.Mol.eigvec[i][self.AtomSel]))) self.OrbitalSel = Orbitals return self.UpdateSelection() def UpdateOrbitalSel(self, iOrbital): self.OrbitalSel = iOrbital if isinstance(self.OrbitalSel, int): print "Orbital set to:", self.OrbitalSel, "with energy", self.Mol.e_arr[self.OrbitalSel], "eV" self.AtomSel = self.Mol.eigvec[iOrbital] self.Gate = self.Mol.e_arr[self.OrbitalSel] return self.UpdateSelection() def UpdateSelection (self): self.DrawLocalCurrents () self.DrawGate() self.DrawIVCurve() self.DrawSelAtom() self.DrawSelOrbitals() self.DrawSelTransmission() return def RunSequence (self): self.fig.set_size_inches(18.5, 13.5) #default 18.5, 10.5 N=100 for i in range(N): e = self.Mol.Gates[0]+(self.Mol.Gates[-1]-self.Mol.Gates[0])/N*i self.UpdateGate(e) self.fig.savefig('Output/PN/Armchair 7,21, seq ' + str(i) + ' Energy=' + str(math.ceil(e*100)/100) + 'eV.png', dpi=self.fig.dpi) print e
redraw_curve() def updateLAG(label): global fg, ax, p1, p2, mylag, myMOCsel mylag = int(label); print('shifting MOC to lag={}'.format(mylag)) draw_pcolor(); redraw_curve() def filterpval(label): global stat_pvalfilter, cb stat_pvalfilter = not stat_pvalfilter draw_pcolor(); # update widgets fg.canvas.mpl_connect('button_press_event', onpick_xcorrBSFidx) RBlag.on_clicked(updateLAG) CBpval.on_clicked(filterpval) # ----------------------------------------------------------------------------- # moving min/max of BSFidx fg, ax = spsinv(); p00 = ax.pcolor(lat_auxgrd, zT, mxcorrBSFidx[:,:,idxlag0]) p01 = ax.plot(fminx, fminy, 'o-', prop_of_min); p02 = ax.plot(fmaxx, fmaxy, 'o-', prop_of_max); ax.legend() # ----------------------------------------------------------------------------- # movie of BSFidx over lags with max/min as dots writer = utils_plt.movie_setup() fg, ax = spsinv(); cb00 = 'dummy' with writer.saving(fg, path_figscorr+'xcorrBSFidx_201.mp4', 100): # 100 dpi
class CBox(object): """Custom checkbox.""" def __init__(self, fig, rect, labels, act=None, func=None, fargs=None): """init function Parameters: fig: a matplotlib.figure.Figure instance rect: [left, bottom, width, height] each of which in 0-to-1-fraction i.e. 0<=x<=1 labels: array of strings labels to be checked act: a len(labels) array of booleans, optional, default: None indicating whether the label is active at first if None, all labels are inactive func: function, optional, default: None if not None, function called when checkbox status changes fargs: array, optional, default: None (optional) arguments for func """ self.fig = fig self._rect = rect self._func = func self._fargs = fargs self._labels = labels self.axes = self.fig.add_axes(rect) self.axes.set_axis_bgcolor('1.00') inac = act if act is not None else (False,) * len(labels) self.cb = CheckButtons(self.axes, self._labels, inac) self.cb.on_clicked(self._onchange) def _onchange(self,label): """Actual function called when checkbox status changes.""" if self.get_visible(): if self._func is not None: if self._fargs is not None: self._func(*self._fargs) else: self._func() self.fig.canvas.draw() def get_status(self): """Get checkbox status. Returns: status status: list of booleans a len(labels) list of booleans indicating whether label is active NB: checkbox status changes even when it's not visible if a click hits the checkbox! """ stat = [] for i in self.cb.lines: stat.append(i[0].get_visible() or i[1].get_visible()) return stat def set_visible(self,b): """Set its visibility. Parameters: b: boolean """ self.axes.set_visible(b) def get_visible(self): """Get its visibility. Returns: b b: boolean """ return self.axes.get_visible()
def ishow(self): """ interactive show of trajectories Examples -------- .. plot:: :include-source: >>> from pylayers.mobility.trajectory import * >>> T=Trajectories() >>> T.loadh5() >>> T.ishow() """ fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2, left=0.3) t = np.arange(0, len(self[0].index), self[0].ts) L = Layout(self.Lfilename) fig, ax = L.showG('s', fig=fig, ax=ax) valinit = 0 lines = [] labels = [] colors = "bgrcmykw" for iT, T in enumerate(self): if T.typ == 'ag': lines.extend(ax.plot(T['x'][0:valinit],T['y'][0:valinit], 'o', color=colors[iT], visible=True)) labels.append(T.name + ':' + T.ID) else: lines.extend(ax.plot(T['x'][0], T['y'][0], '^', ms=12, color=colors[iT], visible=True)) labels.append(T.name + ':' + T.ID) t = self[0].time() # init boolean value for visible in checkbutton blabels = [True]*len(labels) ######## # slider ######## slider_ax = plt.axes([0.1, 0.1, 0.8, 0.02]) slider = Slider(slider_ax, "time", self[0].tmin, self[0].tmax, valinit=valinit, color='#AAAAAA') def update(val): if val >= 1: pval=np.where(val>t)[0] ax.set_title(str(self[0].index[pval[-1]].time())[:11].ljust(12), loc='left') for iT, T in enumerate(self): if T.typ == 'ag': lines[iT].set_xdata(T['x'][pval]) lines[iT].set_ydata(T['y'][pval]) fig.canvas.draw() slider.on_changed(update) ######## # choose ######## rax = plt.axes([0.02, 0.5, 0.3, 0.2], aspect='equal') # check (ax.object, name of the object , bool value for the obsject) check = CheckButtons(rax, labels, tuple(blabels)) def func(label): i = labels.index(label) lines[i].set_visible(not lines[i].get_visible()) fig.canvas.draw() check.on_clicked(func) fig.canvas.draw() plt.show(fig)