예제 #1
0
    def _make_buttons(self, true_ax):

        self.buttons = []
        width, height, locations = self._get_Button_Locations(true_ax)

        for arm in range(self.num_arms):
            self.buttons.append(
                Button(plt.axes(locations[arm]),
                       str(arm),
                       color=self.bandit_env.COLOURS[arm],
                       hovercolor=self.bandit_env.COLOURS2[1]))

            self.buttons[-1].on_clicked(
                functools.partial(self._interactive_arm, pull=arm))

        self.buttons.append(
            Button(plt.axes(locations[-1]),
                   'TS',
                   color=self.bandit_env.COLOURS2[0],
                   hovercolor=self.bandit_env.COLOURS2[1]))

        self.buttons[-1].on_clicked(functools.partial(self._TS_arm))

        self.buttons.append(
            CheckButtons(plt.axes([0.2, 0.88, 0.12, 0.12], facecolor='w'),
                         ('Distributions', ), [self.show_dists]))
        self.buttons[-1].on_clicked(self._make_Plot)
        self.buttons.append(
            CheckButtons(plt.axes([0.5, 0.88, 0.12, 0.12], facecolor='w'),
                         ('Regret', ), [self.show_regret]))
        self.buttons[-1].on_clicked(self._make_Plot)
        return
예제 #2
0
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))
예제 #3
0
    def __init__(self, plot_3D):
        self.shark_array = []

        # array of pre-defined colors,
        # so we can draw sharks with different colors
        self.colors = ['b', 'g', 'c', 'm', 'y', 'k']

        self.arrow_length_ratio = 0.1

        # initialize the 3d scatter position plot for the auv and shark
        if plot_3D:
            self.fig = plt.figure(figsize=[13, 10])
            self.ax = self.fig.add_subplot(111, projection='3d')

            # create a dictionary for checkbox for each type of planned trajectory
            # key - the planner's name: "A *", "RRT"
            # value - three-element array
            #   1. boolean(represent wheter the label is added to the legend)
            #   2. the CheckButtons object
            #   3. color of the plot
            self.traj_checkbox_dict = {}

            # initialize the A * button
            self.traj_checkbox_dict["A *"] = [False,\
                CheckButtons(plt.axes([0.7, 0.10, 0.15, 0.05]), ["A* Trajectory"]), '#9933ff']
            # when the A* checkbox is checked, it should call self.enable_traj_plot

            # initialize the RRT button
            self.traj_checkbox_dict["RRT"] = [False,\
                CheckButtons(plt.axes([0.7, 0.05, 0.15, 0.05]),["RRT Trajectory"]), '#043d10']
            # when the RRT checkbox is checked, it should call self.enable_traj_plot

            self.particle_checkbox = CheckButtons(
                plt.axes([0.1, 0.10, 0.15, 0.05]), ["Display Particles"])
            self.display_particles = False
            self.particle_checkbox.on_clicked(self.particle_checkbox_clicked)

            self.run_sim = True

            self.end_sim_btn = Button(plt.axes([0.1, 0.8, 0.15, 0.05]),
                                      "End Simulation")
            self.end_sim_btn.on_clicked(self.end_simulation)
        else:
            # initialize the 2d graph
            self.fig_2D = plt.figure(figsize=[13, 10])
            self.ax_2D = self.fig_2D.add_subplot(111)

        # an array of the labels that will appear in the legend
        # TODO: labels and legends still have minor bugs
        self.labels = ["auv"]
예제 #4
0
 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 __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)
예제 #6
0
 def __init__(self,
              pfunc=get_secz,
              targs=[],
              date=defaultDate,
              harvard=False,
              observatory='Mount Graham'):
     self.func = pfunc
     self.f = mpl.figure(figsize=(10, 10))
     self.a = self.f.add_axes([0.30, 0.30, 0.65, 0.65],
                              projection=pfunc.func_doc)
     self.raxes = []
     self.raxes.append(self.f.add_axes([0.025, 0.90, 0.10, 0.05]))
     self.last_button_bottom = 0.90
     self.radios = []
     self.nowline = None
     self.radios.append(
         CheckButtons(self.raxes[-1], ('now', ), actives=[True]))
     self.radios[-1].labels[-1].set_color('k')
     self.radios[-1].on_clicked(self.now)
     self.line_names = {}
     self.harvard = harvard
     self.observatory = observatory
     self.date = date
     for t in targs:
         self.add_star(t)
     mpl.draw()
예제 #7
0
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()
예제 #8
0
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 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()
예제 #10
0
    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()
예제 #11
0
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
예제 #12
0
    def _recreate_show_lines_check_button(self):

        axcolor = 'lightgoldenrodyellow'
        if hasattr(self, 'rax_showlines'):
            self.rax_showlines.cla()
        self.rax_showlines = plt.axes([self.x_start__ + self.slider_length__ + self.text_length__,
                                       self.y_start__,
                                       self.button_length__,
                                       self.button_height__], facecolor=axcolor)

        visible = self.prop_ifs.get_visible()
        show_ann = self.prop_ifs.get_annotation_visible()


        labels = ('showIFS',
                 #'marks',
                 #'edges',
                 'labels')
        actives = (visible,
                   # linestyle not in ['None', None],
                   show_ann)

        self.holder_actives = dict(zip(labels, actives))

        self.w_check_components = CheckButtons(self.rax_showlines,
                    labels,
                    actives)


        self.w_check_components.on_clicked(self.update_show_components)
        return self.w_check_components
예제 #13
0
    def add_star(self, name):
        print self.observatory
        self.a = self.func(name,
                           ax=self.a,
                           harvard=self.harvard,
                           observatory=self.observatory,
                           date=self.date)
        self.a.legend_.set_visible(False)

        if len(self.raxes) == 0:
            self.raxes.append(self.f.add_axes([0.025, 0.90, 0.17, 0.05]))
            self.last_button_bottom = 0.90
        else:
            self.raxes.append(
                self.f.add_axes(
                    [0.025, self.last_button_bottom - 0.05, 0.17, 0.05]))
            self.last_button_bottom = self.last_button_bottom - 0.05

        self.line_names[name] = len(self.a.lines) - 1
        self.radios.append(
            CheckButtons(self.raxes[-1], (name, ), actives=[False]))
        self.radios[-1].labels[-1].set_color(self.a.lines[-1].get_color())
        self.radios[-1].on_clicked(self.showfunc)

        mpl.draw()
예제 #14
0
    def start_spectrum(self, *args, **kwargs):
        if self.fig_spectrum is None:
            self.fig_spectrum = plt.figure()
            self.ax_spectrum = self.fig_spectrum.add_axes([0.1, 0.1, 0.7, 0.8])

            # Widgets
            ax_hanning = self.fig_spectrum.add_axes([0.825, 0.75, 0.15, 0.15])
            self.checkbox_hanning = CheckButtons(ax_hanning, ["Hanning", "AC"],
                                                 [self.hanning, self.ac])
            self.checkbox_hanning.on_clicked(self.ask_hanning_change)

            ax_spectrum_unit = self.fig_spectrum.add_axes(
                [0.825, 0.51, 0.15, 0.25])
            self.radio_units = RadioButtons(
                ax_spectrum_unit,
                ["V^2/Hz", "V/sq(Hz)", "mV/sq(Hz)", "µV/sq(Hz)", "nV/sq(Hz)"],
            )
            self.radio_units.on_clicked(self.ask_spectrum_units_change)

            ax_restart = self.fig_spectrum.add_axes([0.825, 0.35, 0.15, 0.075])
            self.btn_restart = Button(ax_restart, label="Restart")
            self.btn_restart.on_clicked(self.clean_spectrum)

            ax_save_hold = self.fig_spectrum.add_axes(
                [0.825, 0.25, 0.15, 0.075])
            self.btn_save_hold = Button(ax_save_hold, label="Hold&Save")
            self.btn_save_hold.on_clicked(self.save_hold)

        self.clean_spectrum()
예제 #15
0
    def _recreate_show_operators_check_button(self):

        axcolor = 'lightgoldenrodyellow'
        if hasattr(self, 'rax_showlines_operator'):
            self.rax_showlines_operator.cla()
        self.rax_showlines_operator = plt.axes([self.x_start__ + self.slider_length__ \
                            + self.text_length__ + 2* self.button_length__,
                                       self.y_start__,
                                       self.button_length__,
                                       self.button_height__], facecolor=axcolor)

        visible = self.prop_ifs.holder.get_visible()
        linestyle = self.prop_ifs.holder.get_linestyle()

        labels = ('F', 'G', 'H', 'J')
        actives = (self.prop_ifs.hide_ifs, visible, linestyle
                   not in ['None', None], self.prop_ifs.show_ann)

        self.holder_actives_operator = dict(zip(labels, actives))

        self.w_check_components_operator = CheckButtons(
            self.rax_showlines_operator, labels, actives)

        self.w_check_components_operator.on_clicked(
            self.update_show_components_operator)
        return self.w_check_components_operator
예제 #16
0
파일: case.py 프로젝트: ysshah/urap
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()
예제 #17
0
    def render(self):
        print(f'drawing with {self.plotter.n} circles')
        self.fig = Figure(figsize=(13, 13), dpi=100)
        self.ax = self.fig.subplots()
        self.root.wm_title(f"Render - {base_name(args.file_name, True)}")
        canvas = FigureCanvasTkAgg(self.fig, master=self.root)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
        if not self.hide_widgets:
            rax = self.fig.add_axes([0.05, 0.0, 0.1, 0.1])
            rax.axis('off')
            self.check = CheckButtons(rax, ('hide',), (self.plotter.hide,))
            self.check.on_clicked(lambda _: self.plotter.toggle_hide())

            nax = self.fig.add_axes([0.2, 0.07, 0.7, 0.02])
            self.nslider = Slider(nax, 'n', 2, self.plotter.frames,
                                  valinit=self.plotter.n, valstep=1)
            self.nslider.on_changed(self._update_n)
            fpsax = self.fig.add_axes([0.2, 0.03, 0.7, 0.02])
            self.fpsslider = Slider(fpsax, 'fps', 1, 50,
                                    valinit=10, valstep=1)
            self.fpsslider.on_changed(self._update_fps)
        self._init_animation()
        if args.save:
            self.save(args.out)
        else:
            tkinter.mainloop()
예제 #18
0
파일: plot_sar.py 프로젝트: Altoros/plsar
    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()
예제 #19
0
    def _draw_control_panel(self):

        ax = self.controller.add_axes([0.2, 0.90, 0.5, 0.05])
        self.slider_cursor = DiscreteSlider(label='cursor', valmin=0, valmax=self.series_length - 1,
                                            ax=ax, increment=1, valinit=self.ctrl_cursor)
        self.slider_cursor.on_changed(self.controller_change_slider_cursor)

        ax = self.controller.add_axes([0.2, 0.75, 0.5, 0.05])
        self.slider_class = DiscreteSlider(label='class', valmin=0, valmax=self.class_amount - 1,
                                           ax=ax, increment=1, valinit=self.ctrl_class)
        self.slider_class.on_changed(self.controller_change_slider_class)

        ax = self.controller.add_axes([0.2, 0.60, 0.5, 0.05])
        self.slider_smooth = DiscreteSlider(label='smooth', valmin=1, valmax=self.series_length,
                                            ax=ax, increment=1, valinit=self.ctrl_smooth)
        self.slider_smooth.on_changed(self.controller_change_slider_smooth)

        ax = self.controller.add_axes([0.2, 0.45, 0.5, 0.05])
        self.slider_trajectory = DiscreteSlider(label='trajectory', valmin=1, valmax=self.series_length,
                                                ax=ax, increment=1, valinit=self.ctrl_trajectory_length)
        self.slider_trajectory.on_changed(self.controller_change_slider_trajectory)

        ax = self.controller.add_axes([0.6, 0.1, 0.3, 0.25])
        self.radiobuttons_norm = RadioButtons(ax, ('FP-FN', 'FPR-TPR', 'Recl-Prec', 'Spec-Sens'), active=0)
        self.radiobuttons_norm.on_clicked(self.controller_change_radiobuttons_norm)

        ax = self.controller.add_axes([0.3, 0.1, 0.3, 0.25])
        self.checkbutton_hold = CheckButtons(ax, labels=['Hold on Range', 'Same Ratio'], actives=[False, True])
        self.checkbutton_hold.on_clicked(self.controller_change_checkbutton_hold)
예제 #20
0
    def add_checkboxes(self):
        """
        Checkboxes offer the ability to select multiple tags such as Motion,
        Ghosting Aliasing etc, instead of one from a list of mutual exclusive
        rating options (such as Good, Bad, Error etc).

        """

        ax_checkbox = plt.axes(cfg.position_checkbox_t1_mri,
                               facecolor=cfg.color_rating_axis)
        # initially de-activating all
        check_box_status = [False] * len(self.issue_list)
        self.checkbox = CheckButtons(ax_checkbox,
                                     labels=self.issue_list,
                                     actives=check_box_status)
        self.checkbox.on_clicked(self.save_issues)
        for txt_lbl in self.checkbox.labels:
            txt_lbl.set(color=cfg.text_option_color, fontweight='normal')

        for rect in self.checkbox.rectangles:
            rect.set_width(cfg.checkbox_rect_width)
            rect.set_height(cfg.checkbox_rect_height)

        # lines is a list of n crosses, each cross (x) defined by a tuple of lines
        for x_line1, x_line2 in self.checkbox.lines:
            x_line1.set_color(cfg.checkbox_cross_color)
            x_line2.set_color(cfg.checkbox_cross_color)

        self._index_pass = cfg.defacing_default_issue_list.index(
            cfg.defacing_pass_indicator)
예제 #21
0
    def initVisibilityCheckBoxes(self):
        visibility = self.visibility
        if kElementsKey in visibility.keys():
            visibility.pop(kElementsKey)

        subAxes = plt.axes([0.81, 0.4, 0.1, 0.5], frameon=False, anchor='NW')
        self.checkBoxes = CheckButtons(subAxes, visibility.keys(),
                                       visibility.values())

        step = 0.15
        for i, (label, rectangle, lines) in enumerate(
                zip(self.checkBoxes.labels, self.checkBoxes.rectangles,
                    self.checkBoxes.lines)):
            h = 0.85 - step * i
            label.set_fontsize(11)
            rectangle.set_x(0.05)
            rectangle.set_y(h)
            rectangle.set(width=0.12, height=0.04)
            label.set_y(h + 0.02)
            label.set_x(0.2)

            lineA, lineB = lines
            lineA.set_xdata([0.05, 0.17])
            lineB.set_xdata([0.05, 0.17])
            lineA.set_ydata([h, h + 0.04])
            lineB.set_ydata([h + 0.04, h])

        self.checkBoxes.on_clicked(self.onCheckBoxCallback)
예제 #22
0
def add_log_toggler(ax, pos="leg:S+W", ylim=None):
    """Add button that toggles log. scale."""
    fig = ax.figure

    # button_ax: size and creation
    size = xFontsize(mpl.rcParams['font.size'], fig, 10, 2.5)
    size = fig.transFigure.inverted().transform(size)
    rect = [.5, .5, *size]
    button_ax = fig.add_axes(rect, frameon=False, xticks=[], yticks=[])
    # button_ax: position
    if "leg:" in pos:
        pos = pos.replace("leg:", "")
        # Continuous re-positioning:
        anchor_axes(button_ax, get_legend_bbox(ax), pos)
        # Position once-only (will scale with figure):
        # align_ax_with(button_ax, get_legend_bbox(ax)(), "NW+")
    else:
        anchor_axes(button_ax, lambda: ax.bbox, "NE")

    # Create button/checkmarks
    ax.log_toggler = CheckButtons(button_ax, ["Log scale"], [False])
    # Adjust checkmark style
    dh = .3
    for box, cross in zip(ax.log_toggler.rectangles, ax.log_toggler.lines):
        box.set_y(dh)
        box.set_height(1 - 2 * dh)
        cross[0].set_ydata([dh, 1 - dh])
        cross[1].set_ydata([dh, 1 - dh][::-1])

    # Set callback
    toggler = lambda _: toggle_scale(ax, ylim, _toggle_button=False)
    ax.log_toggler.on_clicked(toggler)
예제 #23
0
    def init(self):
        t = self.samples[self.tslice]
        self.fig, self.ax = plt.subplots()
        plt.subplots_adjust(left=0.1, bottom=0.25)
        channels = np.arange(self.nchannels)
        self.lines = [self.ax.plot(t, row)[0] for row in self.get_data()]
        self.ax.set_ylim(-self.offset / 2,
                         self.nchannels * self.offset + self.offset / 2)
        self.ax.set_yticks(channels * self.offset)
        self.ax.set_yticklabels(channels)

        ## SLIDER ##
        slider_ax = plt.axes([0.20, 0.1, 0.60, 0.03])
        self.slider = Slider(
            ax=slider_ax,
            label="Samples",
            valmin=0,
            valmax=self.nsamples,
            valinit=self.start,
            valstep=300,
            valfmt="%d",
        )
        self.slider.on_changed(self.update_slider)

        self.check_ax = plt.axes([0.01, 0.4, 0.05, 0.15])
        self.check = CheckButtons(self.check_ax, ["cmr", "bandpass"],
                                  [self.cmr, self.bandpass])
        self.check.on_clicked(self.check_clicked)

        ## FORMATTING ##
        for spine in ["top", "right"]:
            self.ax.spines[spine].set_visible(False)
        self.ax.set_xlabel("Sample")
        self.ax.set_ylabel("Channel")
예제 #24
0
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
예제 #25
0
    def plot_setup(self):
        """create the plot, add checkbuttons, legend, title, labels"""
        self.fig, self.ax = plt.subplots()
        plt.subplots_adjust(left=0.2)
        plt.grid()
        plt.title('comparison of angles')
        plt.xlabel('frame')
        plt.ylabel('angle in degree')
        custom_legend = [Line2D([0], [0], linestyle='None', color='k', marker='$A$', lw=2, label=INTERPOLATION),
                         Line2D([0], [0], linestyle='None', color='tab:gray', marker='$L$', lw=2, label=LEAPMOTION),
                         Line2D([0], [0], linestyle='None', color=COLORS[0], marker='$1$', lw=2, label='Thumb'),
                         Line2D([0], [0], linestyle='None', color=COLORS[2], marker='$2$', lw=2, label='Index'),
                         Line2D([0], [0], linestyle='None', color=COLORS[4], marker='$3$', lw=2, label='Middle'),
                         Line2D([0], [0], linestyle='None', color=COLORS[6], marker='$4$', lw=2, label='Ring'),
                         Line2D([0], [0], linestyle='None', color=COLORS[8], marker='$5$', lw=2, label='Pinky'),
                         Line2D([0], [0], linestyle=LINE_STYLES[0], color='k', lw=2, label='CMC'),
                         Line2D([0], [0], linestyle=LINE_STYLES[1], color='k', lw=2, label='MCP'),
                         Line2D([0], [0], linestyle=LINE_STYLES[2], color='k', lw=2, label='PIP'),
                         Line2D([0], [0], linestyle=LINE_STYLES[3], color='k', lw=2, label='DIP'),
                         Line2D([0], [0], linestyle='None', color='k', marker='$F$', lw=2, label=FLEXION),
                         Line2D([0], [0], linestyle='None', color='k', marker='$A$', lw=2, label=ABDUCTION),
                         Line2D([0], [0], linestyle='None', color='k', marker='$D$', lw=2, label=DEVIATION)]
        leg = self.ax.legend(handles=custom_legend)
        # change the font colors to match the line colors:
        for line, text in zip(leg.get_lines(), leg.get_texts()):
            text.set_color(line.get_color())

        """checkboxes"""
        rax_data = plt.axes([0.05, 0.7, 0.1, 0.15])
        self.checkbuttons['check_data']['buttons'] = CheckButtons(
            rax_data, self.checkbuttons['check_data']['labels'], self.checkbuttons['check_data']['status'])

        rax_finger = plt.axes([0.05, 0.5, 0.1, 0.15])
        self.checkbuttons['check_finger']['buttons'] = CheckButtons(
            rax_finger, self.checkbuttons['check_finger']['labels'], self.checkbuttons['check_finger']['status'])

        rax_joint = plt.axes([0.05, 0.3, 0.1, 0.15])
        self.checkbuttons['check_joint']['buttons'] = CheckButtons(
            rax_joint, self.checkbuttons['check_joint']['labels'], self.checkbuttons['check_joint']['status'])

        rax_rotation = plt.axes([0.05, 0.1, 0.1, 0.15])
        self.checkbuttons['check_rotation']['buttons'] = CheckButtons(
            rax_rotation, self.checkbuttons['check_rotation']['labels'], self.checkbuttons['check_rotation']['status'])

        # activate on_clicked function for all button groups
        for button_group, button_values in self.checkbuttons.items():
            button_values['buttons'].on_clicked(self.change_label)
예제 #26
0
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()
예제 #27
0
    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()
예제 #28
0
    def add_check_button(self, pos, name, options, init_vals):
        def set_options(label):
            pass

        ax = plt.axes(pos)
        setattr(self, name + '_check_button',
                CheckButtons(ax, options, init_vals))
        getattr(self, name + '_check_button').on_clicked(set_options)
예제 #29
0
def make_buttons():
    labels = ["Invert", "Bacteria area"]
    visibility = [True, True, True]
    rax = plt.axes(
        [_buttons["x"], _buttons["y"], _buttons["width"], _buttons["height"]]
    )
    check = CheckButtons(rax, labels, visibility)
    return check
예제 #30
0
 def _set_control_AS(self):
     """
     Will connect the checkbutton control panel with the plotting axis.
     """
     self.check_AS = CheckButtons(
         self.AS_widg_ax, ('all rep', 'avg', 'fill'),
         (self.plot_all_AS, self.plot_avg_AS, self.fill_between_AS))
     self.check_AS.on_clicked(self._on_click_AS)