def check_buttons(rax, labels, actives, user_callback=None):
    """
    rab = check_buttons(ax, labels, actives, user_callback=None)

Puts up check buttons (any number one selected at a time) for the strings
passed in the vector of strings "labels", in the matplotlib axes given by "ax".  
actives must be a list of Booleans, same length as labels,
indicating which buttons should start as ON.
On click, if the function user_callback is set, it will be called, with a string 
as its single parameter-- that string will be the label of the clicked button. 

You can also access which buttons are currently on through
    
    rab.get_status()
        
Or, in Julia, with the PyCall syntax

    rab[:get_status]()
    
which returns a tuple of Booleans, with true for those that are ON,
false for those that aren't.  A list of string labels can also be obtained 
through

    rab[:labels]
    
    """
    checks = Wid.CheckButtons(rax, labels, actives)
    if user_callback != None:
        checks.on_clicked(user_callback)

    return checks
예제 #2
0
 def __init__(self, function, label, coords, type=1, color=None):
     self.function = function
     self.label = label
     self.coords = coords
     self.axis = plt.axes(self.coords)
     self.checkbox = mwidgets.CheckButtons(self.axis, [self.label])    
     self.checkbox.on_clicked(self.function)
     if type == 1: # Check box this a cross
         self.checkbox.rectangles[0].set_y(0)
         self.checkbox.rectangles[0].set_x(0)
         self.checkbox.rectangles[0].set_height(1)   
         self.checkbox.rectangles[0].set_width(0.2)   
         self.checkbox.lines[0][0].set_xdata([0.0,0.2])
         self.checkbox.lines[0][0].set_ydata([0.0,1.0])
         self.checkbox.lines[0][1].set_xdata([0.0,0.2])
         self.checkbox.lines[0][1].set_ydata([1.0,0.0])
     if type == 2: # Check box with color only
         if color is None:
             color = 'lime' 
         self.checkbox.rectangles[0].set_facecolor(color)
         self.checkbox.rectangles[0].set_fill(False)
         self.checkbox.lines[0][0].set_linewidth(0)
         self.checkbox.lines[0][1].set_linewidth(0)
         self.checkbox.rectangles[0].set_y(0)
         self.checkbox.rectangles[0].set_x(0)
         self.checkbox.rectangles[0].set_height(1)   
         self.checkbox.rectangles[0].set_width(0.2)   
예제 #3
0
def _draw_proj_checkbox(event, params, draw_current_state=True):
    """Toggle options (projectors) dialog"""
    from matplotlib import widgets
    projs = params['projs']
    # turn on options dialog

    labels = [p['desc'] for p in projs]
    actives = ([p['active'] for p in projs] if draw_current_state else
               [True] * len(params['projs']))

    width = max([len(p['desc']) for p in projs]) / 6.0 + 0.5
    height = len(projs) / 6.0 + 0.5
    fig_proj = figure_nobar(figsize=(width, height))
    fig_proj.canvas.set_window_title('SSP projection vectors')
    params['fig_proj'] = fig_proj  # necessary for proper toggling
    ax_temp = fig_proj.add_axes((0, 0, 1, 1), frameon=False)

    proj_checks = widgets.CheckButtons(ax_temp, labels=labels, actives=actives)
    # change already-applied projectors to red
    for ii, p in enumerate(projs):
        if p['active'] is True:
            for x in proj_checks.lines[ii]:
                x.set_color('r')
    # make minimal size
    # pass key presses from option dialog over

    proj_checks.on_clicked(partial(_toggle_proj, params=params))
    params['proj_checks'] = proj_checks

    # this should work for non-test cases
    try:
        fig_proj.canvas.draw()
        fig_proj.show(warn=False)
    except Exception:
        pass
예제 #4
0
def build_check_buttons(fig, width):
    # Give us some room along the right
    fig.subplots_adjust(right=1 - width)
    boxax = fig.add_axes([0.99 - width, 0.8, width, 0.1])
    checks = widgets.CheckButtons(boxax, ('Radar', 'Polys', 'Tracks'),
                                  [True] * 3)
    return checks
예제 #5
0
def create_button(idx_feature):
    """ function to built button groups for one feature """
    x, y, w, h = get_loc_control(idx_feature)

    plt.text(x + w / 2,
             y + h / 2 + 0.01,
             feature_name[idx_feature],
             horizontalalignment='center',
             transform=plt.gcf().transFigure)

    ax_neg = plt.axes((x + w / 8, y, w / 4, h / 2))
    b_neg = widgets.Button(ax_neg, '-', hovercolor='0.1')
    b_neg.on_clicked(lambda event: callback.modify_along_feature(
        event, idx_feature, step_size=-1 * step_size))

    ax_pos = plt.axes((x + w * 5 / 8, y, w / 4, h / 2))
    b_pos = widgets.Button(ax_pos, '+', hovercolor='0.1')
    b_pos.on_clicked(lambda event: callback.modify_along_feature(
        event, idx_feature, step_size=+1 * step_size))

    ax_lock = plt.axes((x + w * 3 / 8, y, w / 4, h / 2))
    b_lock = widgets.CheckButtons(ax_lock, ['L'], [False])
    b_lock.on_clicked(
        lambda event: callback.set_feature_lock(event, idx_feature))
    return b_neg, b_pos, b_lock
예제 #6
0
def main(seed_pt, src_lines):
    """Main entry"""
    fig = pyplot.figure()
    ax = fig.gca(projection='3d')

    flat_src_lines = src_lines.reshape((-1, src_lines.shape[-1]))
    scale = vect_lens(flat_src_lines.max(0) - flat_src_lines.min(0))
    main_data = main_class(ax, seed_pt)
    main_data.on_redraw(plot_geometry, scale, emi_gradients, src_lines)

    # Current source line
    if SOURCE_FMT:
        main_data.update_collection(plot_source(ax, src_lines))

    main_data.do_redraw()

    # Base widget rectangle
    rect1, rect2 = split_rect([0, 0, BASE_AX_WIDTH, BASE_AX_HEIGHT],
                              AX_BTN_WIDTH)

    # Check boxes to show/hide individual elements
    rax = fig.add_axes(deflate_rect(rect1))
    labels = []
    visibility = []
    for coll in main_data.get_collections():
        labels.append(coll.get_label())
        visibility.append(coll.get_visible())
    check = widgets.CheckButtons(rax, labels, visibility)
    check.on_clicked(main_data.do_showhide)

    # Sliders
    _, rect21 = split_rect(rect2, AX_BTN_HEIGHT / 3)
    rect214, rect213 = split_rect(rect21, AX_BTN_HEIGHT / 4, True)
    rect213, _ = split_rect(rect213, AX_BTN_HEIGHT / 4, True)
    rax = fig.add_axes(deflate_rect(rect213, SLIDER_HOR_MARGIN),
                       fc='lightgray')
    slider_u = widgets.Slider(rax,
                              'U extent',
                              0,
                              10,
                              main_data.extent_uv[0],
                              dragging=False,
                              valstep=1)
    slider_u.on_changed(main_data.slider_u_changed)
    rax = fig.add_axes(deflate_rect(rect214, SLIDER_HOR_MARGIN),
                       fc='lightgray')
    slider_v = widgets.Slider(rax,
                              'V extent',
                              0,
                              10,
                              main_data.extent_uv[1],
                              dragging=False,
                              valstep=1)
    slider_v.on_changed(main_data.slider_v_changed)

    ax.set_title('Surface from normals')
    ax.legend()
    pyplot.show()
    return 0
예제 #7
0
def test_check_radio_buttons_image():
    get_ax()
    plt.subplots_adjust(left=0.3)
    rax1 = plt.axes([0.05, 0.7, 0.15, 0.15])
    rax2 = plt.axes([0.05, 0.2, 0.15, 0.15])
    widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3'))
    widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'),
                         (False, True, True))
예제 #8
0
def test_CheckButtons():
    ax = get_ax()
    check = widgets.CheckButtons(ax, ('a', 'b', 'c'), (True, False, True))
    assert check.get_status() == [True, False, True]
    check.set_active(0)
    assert check.get_status() == [False, False, True]

    cid = check.on_clicked(lambda: None)
    check.disconnect(cid)
예제 #9
0
def test_check_radio_buttons_image():
    # Remove this line when this test image is regenerated.
    plt.rcParams['text.kerning_factor'] = 6

    get_ax()
    plt.subplots_adjust(left=0.3)
    rax1 = plt.axes([0.05, 0.7, 0.15, 0.15])
    rax2 = plt.axes([0.05, 0.2, 0.15, 0.15])
    widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3'))
    widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'),
                         (False, True, True))
예제 #10
0
def test_CheckButtons():
    ax = get_ax()
    check = widgets.CheckButtons(ax, ('a', 'b', 'c'), (True, False, True))
    assert check.get_status() == [True, False, True]
    check.set_active(0)
    assert check.get_status() == [False, False, True]

    def clicked_function():
        pass

    cid = check.on_clicked(clicked_function)
    check.disconnect(cid)
예제 #11
0
def main(argv):
    """Main entry"""
    fig = pyplot.figure()
    rect = [0, AX_BTN_HEIGHT, 1, 1 - AX_BTN_HEIGHT]
    ax = fig.add_axes(deflate_rect(rect), projection='3d', adjustable='box')

    # Initial drawing
    data = main_data(ax)
    data.redraw(numpy.array(SOURCE_POLYLINE), numpy.array(TARGET_POINTS))

    set_axes_equal(ax)

    # Check boxes to show/hide individual elements
    rect = [0, 0, AX_BTN_WIDTH, AX_BTN_HEIGHT]
    rax = fig.add_axes(deflate_rect(rect))
    colls = data.get_collections()
    labels = [coll.get_label() for coll in colls]
    visibility = [coll.get_visible() for coll in colls]
    check = widgets.CheckButtons(rax, labels, visibility)
    check.on_clicked(on_clicked(data))

    # Slider to scale source lines (slider 1)
    rect = [
        AX_BTN_WIDTH, 1 * AX_BTN_HEIGHT / AX_NUM_SLIDERS, 1 - AX_BTN_WIDTH,
        AX_BTN_HEIGHT / AX_NUM_SLIDERS
    ]
    rax = pyplot.axes(deflate_rect(rect, AX_TEXT_WIDTH + AX_MARGIN))
    src_slider = widgets.Slider(rax, data.src_coll.get_label(), 0, 2, 1)
    src_slider.on_changed(
        src_changed(data, scale_changed(SOURCE_SLIDER_DIR, SOURCE_SLIDER_ORG)))

    # Slider to move target points (slider 2)
    rect = [
        AX_BTN_WIDTH, 0 * AX_BTN_HEIGHT / AX_NUM_SLIDERS, 1 - AX_BTN_WIDTH,
        AX_BTN_HEIGHT / AX_NUM_SLIDERS
    ]
    rax = pyplot.axes(deflate_rect(rect, AX_TEXT_WIDTH + AX_MARGIN))
    tgt_slider = widgets.Slider(rax, data.tgt_coll.get_label(), -2, 2, 0)
    tgt_slider.on_changed(tgt_changed(data, move_changed(TARGET_SLIDER_DIR)))

    ax.legend()
    pyplot.show()
    return 0
예제 #12
0
 def create(self, rax):
     labels = [line.get_label() for line in self.lines]
     visibility = [line.get_visible() for line in self.lines]
     return widgets.CheckButtons(rax, labels, visibility)
예제 #13
0
def plot_spectrum_map(specmap):
    """
    Plot an interactive spectrum map
    """
    fig, ax = plt.subplots(figsize=(8, 6))
    plt.subplots_adjust(bottom=0.25, left=-0.1)
    ax.set_aspect("equal")

    e0 = 0
    w0 = 0.5

    spec = specmap.spectrum

    # maximum for sliders
    emin = specmap._get_energy_of_channel(0)
    emax = specmap._get_energy_of_channel(specmap.channels)
    # maximum and minimum for specmap color map
    intmax = np.max(specmap.data.sum(axis=0))
    intmin = 0

    img = specmap._get_integrated_image(e0, w0)
    # img = imf.linscale(img, intmin, intmax)
    lim = plt.imshow(img, cmap="hot")
    lim.set_clim(intmin, intmax)
    sb_settings = {"location": 'lower right',
                   "color": 'k',
                   "length_fraction": 0.25,
                   "font_properties": {"size": 12}}
    scalebar = get_scalebar(specmap.pixelsize, specmap.pixelunit, sb_settings)
    plt.gca().add_artist(scalebar)
    scalebar.set_visible(False)

    ax.margins(x=0)

    axcolor = 'white'
    # [x, y, width, height]
    axwidth = 0.7
    axheight = 0.03
    axmax = plt.axes([0.5-axwidth/2, 0.15, axwidth, axheight],
                     facecolor=axcolor)
    axenergy = plt.axes([0.5-axwidth/2, 0.10, axwidth, axheight],
                        facecolor=axcolor)
    axwidth = plt.axes([0.5-axwidth/2, 0.05, axwidth, axheight],
                       facecolor=axcolor)

    smx = wdgts.Slider(axmax, 'Max', intmin, intmax, valinit=intmax//3,
                       valstep=1, valfmt="%d")
    sen = wdgts.Slider(axenergy, f'Energy ({specmap.energy_unit})', emin, emax,
                       valinit=e0)
    swi = wdgts.Slider(axwidth, f'Width ({specmap.energy_unit})', 0,
                       (emax-emin)/2, valinit=w0)

    # plot the spectrum on the energy axis
    _, lne = spec.plot(ax=axenergy)
    axenergy.set_ylim(0, spec.data.max()/3)
    axenergy.set_xlabel("")
    axenergy.set_ylabel("")
    lne[0].set_color("red")

    def update_im(val):
        en = sen.val
        wi = swi.val
        mx = smx.val
        mn = 0
        arr = specmap._get_integrated_image(en, wi)
        # arr = imf.linscale(arr, mn, mx)
        lim.set_data(arr)
        lim.set_clim(mn, mx)
        fig.canvas.draw_idle()

    def update_clim(val):
        mx = smx.val
        mn = 0
        lim.set_clim(mn, mx)

    smx.on_changed(update_clim)
    axmax._slider = smx
    sen.on_changed(update_im)
    axenergy._slider = sen
    swi.on_changed(update_im)
    axwidth._slider = swi

    # checkbox for scalebar
    sba = plt.axes([0.65, 0.2, 0.25, 0.25], facecolor=axcolor)
    sba.axis("off")
    sbb = wdgts.CheckButtons(sba, ('scalebar',))

    def seescalebar(label):
        yesorno = sbb.get_status()[0]
        scalebar.set_visible(yesorno)
        fig.canvas.draw_idle()

    sbb.on_clicked(seescalebar)
    sba._checkbox = sbb

    plt.show()
예제 #14
0
def build_check_buttons(fig, width):
    # Give us some room along the right
    fig.subplots_adjust(right=1 - width)
    boxax = fig.add_axes([0.99 - width, 0.8, width, 0.1])
    checks = widgets.CheckButtons(boxax, ('Auto Scale', 'Test'), [True] * 2)
    return checks
예제 #15
0
    def __init__(self):

        self.param = {
            "dust_type": "MW",
            "tau_V": 1,
            "geometry": "SHELL",
            "dust_distrib": "homogeneous",
        }

        # generate the curves and plot them
        # Use 1/microns for a better sampling
        self.x = np.arange(0.35, 10.0, 0.1) / u.micron

        self.x_Vband = 0.55

        self.fig, self.ax = plt.subplots(figsize=(15, 10))

        self.axatt = plt.subplot2grid((4, 2), (0, 0), colspan=2, rowspan=3)
        self.axFF = plt.subplot2grid((4, 2), (3, 0), colspan=1, rowspan=1)
        self.axalb = plt.subplot2grid((4, 2), (3, 1), colspan=1, rowspan=1)

        self.fig.canvas.set_window_title("widget for WG00 RT model")
        plt.subplots_adjust(bottom=0.15)
        plt.subplots_adjust(left=0.35)
        plt.subplots_adjust(hspace=0.8)

        axcolor = "lightgoldenrodyellow"

        self.rax_sketch = plt.axes([0.03, 0.68, 0.25, 0.32])
        self.rax_sketch.axis("off")

        rax = plt.axes([0.05, 0.52, 0.15, 0.15], facecolor=axcolor)
        dust_type = wgt.RadioButtons(rax, ("MW", "SMC"))
        dust_type.on_clicked(self.update_dust_type)

        rax = plt.axes([0.05, 0.335, 0.15, 0.15], facecolor=axcolor)
        geometry = wgt.RadioButtons(rax, ("SHELL", "CLOUDY", "DUSTY"))
        geometry.on_clicked(self.update_geometry)

        rax = plt.axes([0.05, 0.15, 0.15, 0.15], facecolor=axcolor)
        distrib = wgt.RadioButtons(rax, ("Homogeneous", "Clumpy"))
        distrib.on_clicked(self.update_dust_distrib)

        rax = plt.axes([0.05, 0.03, 0.12, 0.08], facecolor=axcolor)
        norm = wgt.CheckButtons(rax, (r"Normalised to A$_V$", ), (True, ))
        norm.on_clicked(self.update_norm)
        self.norm = True

        rax = plt.axes([0.3, 0.05, 0.6, 0.0275])
        tau_V = wgt.Slider(rax,
                           r"$\tau_V$",
                           0.5,
                           50,
                           valinit=self.param["tau_V"])
        tau_V.on_changed(self.update_tau_V)

        # Initialise WG00 model
        self.att_model = WG00(
            tau_V=self.param["tau_V"],
            geometry=self.param["geometry"],
            dust_type=self.param["dust_type"],
            dust_distribution=self.param["dust_distrib"],
        )

        self.update_sketch()
        self.update_att_curve()
        plt.show()
예제 #16
0
파일: xtf.py 프로젝트: johannah/pyxtf
def plot(infile):
    header, chaninfos, packets = read_XTF(infile, 'sonar')
    packets = sorted(packets, key=lambda p: p.channel_number)

    channels = [0] * len(chaninfos)
    for p in packets:
        channels[p.channel_number] += 1

    n_nonempty = len([c for c in channels if c])

    def clicked(*args):
        print 'clicked', args

    #import matplotlib; matplotlib.use('MacOSX')
    from matplotlib import pyplot as P, widgets
    P.suptitle('File: ' + infile)
    P.gcf().canvas.set_window_title("%s - xtf.py" % infile)

    buttons = []

    #first = None
    for i, (channel, packets) in enumerate(groupby(packets,
                                                   lambda p: p.channel_number)):
        traces = list(p.trace for p in islice(packets, PLOT_NTRACES))
        r = np.vstack(traces).transpose()
        print 'Plotting %d traces of channel %d (%.1fMb):' % \
            (min(channels[i], PLOT_NTRACES),
             channel + 1,
             (r.size * r.itemsize) / 10.0**6)
        print r

        ax = P.subplot(n_nonempty, 2, i*2+1) #, sharex=first, sharey=first)
        #if i == 0: first = ax

        ax.set_xlim(0, 500)
        ax.set_ylim(500, 0)

        P.title('Channel %d%s' %
                (channel + 1, ' (part)' if PLOT_NTRACES < channels[i] else ''))
        P.imshow(r, P.cm.gray)

    cbax = P.subplot(2, 2, 2)
    P.title('Choose channels:')
    w = widgets.CheckButtons(cbax, ['ch.%d, %s, traces: %d' %
                                    (c+1, CHAN_TYPES[chaninfos[c]['type_of_channel']], t)
                                    for c, t in enumerate(channels)],
                                   [t > 0 for t in channels])
    w.on_clicked(clicked)

    bax1 = P.subplot(6, 4, 15)
    b1 = widgets.Button(bax1, '<< Prev file')
    b1.on_clicked(clicked)

    bax2 = P.subplot(6, 4, 16)
    b2 = widgets.Button(bax2, 'Next file >>')
    b2.on_clicked(clicked)

    bax3 = P.subplot(6, 2, 10)
    b3 = widgets.Button(bax3, 'Save all files to SEG-Y')
    b3.on_clicked(clicked)

    bax4 = P.subplot(6, 2, 12)
    b4 = widgets.Button(bax4, 'Save all files to XTF')
    b4.on_clicked(clicked)

    P.show()
예제 #17
0
    def __init__(self):

        self.param = {
            'dust_type': 'MW',
            'tau_V': 1,
            'geometry': 'SHELL',
            'dust_distrib': 'homogeneous'
        }

        # generate the curves and plot them
        # Use 1/microns for a better sampling
        self.x = np.arange(0.35, 10.0, 0.1) / u.micron

        self.x_Vband = 0.55

        self.fig, self.ax = plt.subplots(figsize=(15, 10))

        self.axatt = plt.subplot2grid((4, 2), (0, 0), colspan=2, rowspan=3)
        self.axFF = plt.subplot2grid((4, 2), (3, 0), colspan=1, rowspan=1)
        self.axalb = plt.subplot2grid((4, 2), (3, 1), colspan=1, rowspan=1)

        self.fig.canvas.set_window_title('widget for WG00 RT model')
        plt.subplots_adjust(bottom=0.15)
        plt.subplots_adjust(left=0.35)
        plt.subplots_adjust(hspace=0.8)

        axcolor = 'lightgoldenrodyellow'

        self.rax_sketch = plt.axes([.03, .68, .25, .32])
        self.rax_sketch.axis('off')

        rax = plt.axes([0.05, 0.52, 0.15, 0.15], facecolor=axcolor)
        dust_type = wgt.RadioButtons(rax, ('MW', 'SMC'))
        dust_type.on_clicked(self.update_dust_type)

        rax = plt.axes([0.05, 0.335, 0.15, 0.15], facecolor=axcolor)
        geometry = wgt.RadioButtons(rax, ('SHELL', 'CLOUDY', 'DUSTY'))
        geometry.on_clicked(self.update_geometry)

        rax = plt.axes([0.05, 0.15, 0.15, 0.15], facecolor=axcolor)
        distrib = wgt.RadioButtons(rax, ('Homogeneous', 'Clumpy'))
        distrib.on_clicked(self.update_dust_distrib)

        rax = plt.axes([0.05, 0.03, 0.12, 0.08], facecolor=axcolor)
        norm = wgt.CheckButtons(rax, (r'Normalised to A$_V$', ), (True, ))
        norm.on_clicked(self.update_norm)
        self.norm = True

        rax = plt.axes([.3, .05, .6, .0275])
        tau_V = wgt.Slider(rax,
                           r'$\tau_V$',
                           0.5,
                           50,
                           valinit=self.param['tau_V'])
        tau_V.on_changed(self.update_tau_V)

        # Initialise WG00 model
        self.att_model = WG00(tau_V=self.param['tau_V'],
                              geometry=self.param['geometry'],
                              dust_type=self.param['dust_type'],
                              dust_distribution=self.param['dust_distrib'])

        self.update_sketch()
        self.update_att_curve()
        plt.show()
    H_val = H[RKidxs[vect_idx]]
    overTable._cells[(tab_row,
                      0)]._text.set_text(utils.format_table_number(H_val))
    stage_val = H[RKidxs[vect_idx]] + eta[RKidxs[vect_idx]]
    overTable._cells[(tab_row,
                      1)]._text.set_text(utils.format_table_number(stage_val))
    over_val = H[RKidxs[vect_idx]] + eta[RKidxs[vect_idx]] > eta[
        RKidxs[vect_idx]] + zed[RKidxs[vect_idx]]
    overTable._cells[(tab_row, 2)]._text.set_text(str(over_val))
    overTable._cells[(tab_row,
                      2)]._text.set_color(utils.format_table_color(over_val))

# add gui buttons
chk_data_ax = plt.axes([0.75, 0.25, 0.15, 0.15], facecolor=background_color)
chk_data_dict = {'show water lines': 'wl', 'show thalweg': 'tw'}
chk_data = widget.CheckButtons(chk_data_ax, chk_data_dict, (False, False))

btn_reset_ax = plt.axes([0.75, 0.1, 0.1, 0.04])
btn_reset = widget.Button(btn_reset_ax,
                          'Reset',
                          color=widget_color,
                          hovercolor='0.975')


def update(val):
    # read values from the sliders
    Qw = slide_Qw.val
    H = hydro.get_backwater_dBdx(eta, S, B, H0, Cf, Qw, nx, dx)
    Xs = hydro.find_backwaterregion(H, dx)

    # update the artists in the window
예제 #19
0
def plot_stack(stack):
    """
    Plot an image stack in an interactive way

    Parameters
    ----------
    stack : data_io.GeneralImageStack
    """
    fig, ax = plt.subplots(figsize=(8, 6))
    plt.subplots_adjust(bottom=0.25, left=-0.1)

    frammax = stack.data.shape[0]-1
    intmax = np.max(stack.data)
    intmin = np.min(stack.data)

    img = stack.data[0]
    # img = imf.linscale(img, intmin, intmax)
    lim = plt.imshow(img, cmap="Greys_r")
    lim.set_clim(intmin, intmax)
    sb_settings = {"location": 'lower right',
                   "color": 'k',
                   "length_fraction": 0.25,
                   "font_properties": {"size": 12}}
    scalebar = get_scalebar(stack.pixelsize, stack.pixelunit, sb_settings)
    plt.gca().add_artist(scalebar)
    scalebar.set_visible(False)

    ax.margins(x=0)

    axcolor = 'white'
    # [x, y, width, height]
    axwidth = 0.7
    axheight = 0.03
    axfram = plt.axes([0.5-axwidth/2, 0.15, axwidth, axheight],
                      facecolor=axcolor)
    axmax = plt.axes([0.5-axwidth/2, 0.10, axwidth, axheight],
                     facecolor=axcolor)
    axmin = plt.axes([0.5-axwidth/2, 0.05, axwidth, axheight],
                     facecolor=axcolor)

    sfam = wdgts.Slider(axfram, 'Frame', 0, frammax, valinit=0, valstep=1,
                        valfmt="%d")
    smax = wdgts.Slider(axmax, 'Max', intmin, intmax, valinit=intmax)
    smin = wdgts.Slider(axmin, 'Min', intmin, intmax, valinit=intmin)

    def update_frame(val):
        mx = smax.val
        mn = smin.val
        fram = int(sfam.val)
        arr = stack.data[fram]
        # arr = imf.linscale(arr, mn, mx)
        lim.set_data(arr)
        lim.set_clim(mn, mx)
        fig.canvas.draw_idle()

    def update_clim(val):
        mx = smax.val
        mn = smin.val
        lim.set_clim(mn, mx)

    sfam.on_changed(update_frame)
    axfram._slider = sfam
    smax.on_changed(update_clim)
    axmax._slider = axmax
    smin.on_changed(update_clim)
    axmin._slider = axmin

    # checkbox for scalebar
    sba = plt.axes([0.65, 0.2, 0.25, 0.25], facecolor=axcolor)
    sba.axis("off")
    sbb = wdgts.CheckButtons(sba, ('scalebar',))

    def seescalebar(label):
        yesorno = sbb.get_status()[0]
        scalebar.set_visible(yesorno)
        fig.canvas.draw_idle()

    sbb.on_clicked(seescalebar)
    sba._checkbox = sbb

    # button for saving frame - does not work in jupyter notebook
    # def dosaveframe(event):
    #     fname = fdo.save()
    #     if fname:
    #         plt.savefig(fname)
    #         mx = smax.val
    #         mn = smin.val
    #         fram = int(sfam.val)
    #         arr = stack.data[fram]
    #         arr = imf.linscale(arr, mn, mx)
    #         plot_image(arr, pixelsize=stack.pixelsize,
    #                    pixelunit=stack.pixelunit,
    #                    scale_bar=sbb.get_status()[0],
    #                    show_fig=False, dpi=100,
    #                    sb_settings=sb_settings,
    #                    imshow_kwargs={"cmap": "Greys_r"})
    #         fig.canvas.draw_idle()

    # savea = plt.axes([0.65, 0.8, 0.15, 0.05], facecolor=axcolor)
    # saveb = wdgts.Button(savea, "save frame", hovercolor="yellow")
    # saveb.on_clicked(dosaveframe)
    # savea._button = saveb

    plt.show()
예제 #20
0
def linearPredictionPlot(filename,
                         plot_results,
                         extension='.png',
                         folder='Figuras',
                         autosave=True,
                         overwrite=False,
                         showgrid=False):
    """Plots the results of a linear prediction plot.
    
    Parameters
    ----------
    filename : str
        File's root (must include directory and extension).
    plot_results : ivu.InstancesDict
        Fit results that allow to plot. Must include...
        ...numpy array 'fit', that holds time, data, fit and fit terms
        ...numpy.array 'raman', that holds frequencies, fit spectrum and fit 
        terms' spectrum.
    extension='.png' : str
        Image file's format.
    folder='Figuras' : str
        Folder to include in figure's filename.
    autosave=True : bool
        Says whether to save or not.
    overwrite=False : bool
        Says whether to allow overwriting or not.
    showgrid=False : bool
        Says whether to show or not the vertical grid on the time space plot.
    
    Returns
    -------
    fig : plt.Figure instance
        Figure containing the desired plot.
    legend_buttons : wid.CheckButtons
        Interactive legend. Only returned if making an interactive plot.
    save_button : wid.Button
        Interactive save button. Only returned if making an interactive plot.        
    
    Raises
    ------
    Image file. Only raised if 'autosave=True'.
    
    See also
    --------
    iva.linearPrediction
    
    """

    # First I deglose data
    fit = plot_results.fit
    raman = plot_results.raman
    Nfit_terms = fit.shape[1] - 3

    # In order to save, if needed, I will need...
    filename = os.path.splitext(filename)[0] + extension

    # Then, to plot, I first start a figure
    fig = plt.figure()
    grid = plt.GridSpec(3, 5, hspace=0.1)

    # In the upper subplot, I put the Raman-like spectrum
    ax_spectrum = plt.subplot(grid[0, :4])
    plt.plot(raman[:, 0], raman[:, 1], linewidth=2)
    lspectrum_terms = plt.plot(raman[:, 0], raman[:, 2:], linewidth=2)
    for l in lspectrum_terms:
        l.set_visible(False)
    plt.xlabel("Frecuencia (GHz)")
    plt.ylabel("Amplitud (u.a.)")
    ax_spectrum.xaxis.tick_top()
    ax_spectrum.xaxis.set_label_position('top')

    # In the lower subplot, I put the data and fit
    ax_data = plt.subplot(grid[1:, :])
    ldata, = plt.plot(fit[:, 0], fit[:, 1], 'k', linewidth=0.4)
    ax_data.autoscale(False)
    lfit, = plt.plot(fit[:, 0], fit[:, 2], linewidth=2)
    lfit_terms = plt.plot(fit[:, 0], fit[:, 3:], linewidth=2)
    for l in lfit_terms:
        l.set_visible(False)
    plt.xlabel("Tiempo (ps)")
    plt.ylabel(r"Voltaje ($\mu$V)")
    ax_data.tick_params(labelsize=12)
    if showgrid:
        ax_data.minorticks_on()
        ax_data.tick_params(axis='y', which='minor', left=False)
        ax_data.tick_params(length=5)
        ax_data.grid(axis='x', which='both')
        ldata.set_linewidth(0.6)
        lfit.set_linewidth(2.3)

    # Because it's pretty, I make an interactive legend
    ax_legend = plt.axes([0.75, 0.642, 0.155, 0.24])
    legend_buttons = wid.CheckButtons(
        ax_legend,
        ('Data', 'Ajuste',
         *['Término {:.0f}'.format(i + 1) for i in range(Nfit_terms)]),
        (True, True, *[False for i in range(Nfit_terms)]))
    legend_buttons.labels[1].set_color(lfit.get_color())
    for leg, l in zip(legend_buttons.labels[2:], lfit_terms):
        leg.set_color(l.get_color())

    # For that, I'll need a callback function
    def legend_callback(label):
        if label == 'Data':
            ldata.set_visible(not ldata.get_visible())
        elif label == 'Ajuste':
            lfit.set_visible(not lfit.get_visible())
        else:
            for i in range(Nfit_terms):
                if label == 'Término {:.0f}'.format(i + 1):
                    lfit_terms[i].set_visible(not lfit_terms[i].get_visible())
                    lspectrum_terms[i].set_visible(
                        not lspectrum_terms[i].get_visible())
        plt.draw()

    legend_buttons.on_clicked(legend_callback)

    # Since I can, I would also like an interactive 'Save' button
    save_button = interactiveSaveButton(filename,
                                        overwrite=overwrite,
                                        folder=folder,
                                        sufix='_fit')

    # Once I have all that, I'll show the plot
    plt.show()

    # Like it is shown for the first time, autosave if configured that way
    if autosave:
        save_button.ax.set_visible(False)
        ivs.saveFig(filename, overwrite=overwrite, folder=folder, sufix='_fit')
        save_button.ax.set_visible(True)

    return fig, legend_buttons, save_button
예제 #21
0
    def __init__(self, solution):
        self.solution = solution
        for s in self.solution:
            if isinstance(s, sol.Exact):
                self.exact = s

        self.figure = plt.figure(figsize=(9, 8),
                                 num="Differential Equations Assignment")

        self.x0_field = Field(self.exact.x_0, [0.06, 0.86, 0.1, 0.04], "x_0")
        self.x0_field.draw()
        self.y0_field = Field(self.exact.y_0, [0.06, 0.80, 0.1, 0.04], "y_0")
        self.y0_field.draw()
        self.xf_field = Field(self.exact.x_f, [0.06, 0.74, 0.1, 0.04], "X")
        self.xf_field.draw()
        self.n_field = Field(self.exact.n, [0.06, 0.68, 0.1, 0.04], "n")
        self.n_field.draw()
        self.n_min_field = Field(self.exact.n_min, [0.06, 0.62, 0.1, 0.04],
                                 "min_n")
        self.n_min_field.draw()
        self.n_max_field = Field(self.exact.n_max, [0.06, 0.56, 0.1, 0.04],
                                 "max_n")
        self.n_max_field.draw()
        self.button = mwidgets.Button(plt.axes([0.06, 0.5, 0.1, 0.03]),
                                      "Recalculate")
        self.button.on_clicked(self.on)

        self.axes = self.figure.add_subplot(3, 1, 1)
        self.axes.set_title("Solutions of IVP")
        self.axes.set_xlabel("Value of x")
        self.axes.set_ylabel("Value of y")
        self.axes.grid(True)

        self.rescale(self.axes, self.x0_field.val, self.xf_field.val)

        for i in self.solution:
            i.graph(self.axes)
            i.calculate_error(self.exact.y)
            #i.calculate_max_error()
        plt.legend(loc="upper left")

        # ERRORS

        self.axes_errors = self.figure.add_subplot(3, 1, 2)
        self.axes_errors.set_title("Errors of Numerical Methods")
        self.axes_errors.set_xlabel("Value of x")
        self.axes_errors.set_ylabel("Value of y")
        self.axes_errors.grid(True)

        self.rescale(self.axes_errors, self.x0_field.val, self.xf_field.val)

        for i in self.solution:
            if not isinstance(i, sol.Exact):
                i.graph_error(self.axes_errors)
        plt.legend(loc="upper left")

        self.axes_max_errors = self.figure.add_subplot(3, 1, 3)
        self.axes_max_errors.set_title("Max errors of Numerical Methods")
        self.axes_max_errors.set_xlabel("Value of n")
        self.axes_max_errors.set_ylabel("Value of Total error")
        self.axes_max_errors.grid(True)

        self.rescale(self.axes_max_errors, self.n_min_field.val,
                     self.n_max_field.val)

        n_values = np.linspace(self.n_min_field.val, self.n_max_field.val,
                               self.n_max_field.val - self.n_min_field.val + 1)
        e_total_errors = np.zeros(
            [self.n_max_field.val - self.n_min_field.val + 1])
        i_total_errors = np.zeros(
            [self.n_max_field.val - self.n_min_field.val + 1])
        r_total_errors = np.zeros(
            [self.n_max_field.val - self.n_min_field.val + 1])
        for i in range(self.n_min_field.val, self.n_max_field.val + 1):
            exact = sol.Exact(sol.function, self.x0_field.val,
                              self.y0_field.val, self.xf_field.val, i)
            euler = sol.Euler(sol.function, self.x0_field.val,
                              self.y0_field.val, self.xf_field.val, i)
            i_euler = sol.Improved_Euler(sol.function, self.x0_field.val,
                                         self.y0_field.val, self.xf_field.val,
                                         i)
            r_k = sol.Runge_Kutta(sol.function, self.x0_field.val,
                                  self.y0_field.val, self.xf_field.val, i)
            euler.calculate_error(exact.y)
            i_euler.calculate_error(exact.y)
            r_k.calculate_error(exact.y)
            e_total_errors[i - self.n_min_field.val] = max(
                np.amax(euler.err), abs(np.amin(euler.err)))
            i_total_errors[i - self.n_min_field.val] = max(
                np.amax(i_euler.err), abs(np.amin(i_euler.err)))
            r_total_errors[i - self.n_min_field.val] = max(
                np.amax(r_k.err), abs(np.amin(r_k.err)))
            del exact
            del euler
            del i_euler
            del r_k
        self.ax_max_err_0, = self.axes_max_errors.plot(n_values,
                                                       e_total_errors,
                                                       'b-',
                                                       label='Euler')
        self.ax_max_err_1, = self.axes_max_errors.plot(n_values,
                                                       i_total_errors,
                                                       'g-',
                                                       label='Improved Euler')
        self.ax_max_err_2, = self.axes_max_errors.plot(n_values,
                                                       r_total_errors,
                                                       'r-',
                                                       label='Runge-Kutta')

        plt.legend(loc="upper left")

        self.lines = []
        for i in self.solution:
            self.lines.append(i.ax)

        self.lines_err = []
        for i in self.solution:
            if not isinstance(i, sol.Exact):
                self.lines_err.append(i.ax_err)

        self.lines_max_err = []
        self.lines_max_err.append(self.ax_max_err_0)
        self.lines_max_err.append(self.ax_max_err_1)
        self.lines_max_err.append(self.ax_max_err_2)

        # Make checkbuttons with all plotted lines with correct visibility
        rax = plt.axes([0.02, 0.33, 0.16, 0.15])
        self.labels = [str(line.get_label()) for line in self.lines]
        visibility = [line.get_visible() for line in self.lines]
        check = mwidgets.CheckButtons(rax, self.labels, visibility)
        check.on_clicked(self.tick)

        self.show()
statsTable = plt.table(cellText=tabData,
                       rowLabels=statsNames,
                       colLabels=columnNames,
                       colWidths=[0.2, 0.2],
                       loc="center")
statsTable.scale(1, 1.5)  # xscale, yscale of cells
for tab_row in np.arange(1, np.size(tabData, 0) + 1):
    statsTable._cells[(tab_row, 0)]._text.set_text(
        utils.format_table_number(stats[tab_row - 1]))
    statsTable._cells[(tab_row, 1)]._text.set_text(
        utils.format_table_number(summ_stats[tab_row - 1]))

# add gui buttons
chk_conn_ax = plt.axes([0.59, 0.5, 0.175, 0.15], facecolor=background_color)
chk_conn_list = ['500-run statistics', 'run w/ slider']
chk_conn = widget.CheckButtons(chk_conn_ax, chk_conn_list, [False, True])

btn_run_ax = plt.axes([0.82, 0.575, 0.125, 0.075])
btn_run = widget.Button(btn_run_ax,
                        'Run',
                        color='lightskyblue',
                        hovercolor='0.975')

btn_reset_ax = plt.axes([0.82, 0.5, 0.1, 0.04])
btn_reset = widget.Button(btn_reset_ax,
                          'Reset',
                          color=widget_color,
                          hovercolor='0.975')

# connect widgets
slide_mu.on_changed(slider_wrapper)
예제 #23
0
def fig_track_swimming(seg_track,
                       num=20,
                       zoom=None,
                       buttons=True,
                       swim_filt=None):
    seg_track = seg_track[np.isfinite(seg_track['ground_u'].values)]

    fig = plt.figure(num)
    fig.set_size_inches((8, 9), forward=True)
    fig.clf()
    gs = gridspec.GridSpec(2, 2)

    ax = fig.add_subplot(gs[0, 0])

    segs = np.array([
        seg_track.loc[:, ['x', 'y']].values,
        seg_track.loc[:, ['x_end', 'y_end']].values
    ]).transpose(1, 0, 2)

    elapsed = seg_track.tnum_m.values - seg_track.tnum_m.values[0]

    if zoom is None:
        pad = 50.0
        zoom = [
            segs[..., 0].min() - pad, segs[..., 0].max() + pad,
            segs[..., 1].min() - pad, segs[..., 1].max() + pad
        ]
    seg_coll = collections.LineCollection(segs, array=elapsed, cmap=turbo)
    ax.add_collection(seg_coll)
    ax.axis('equal')

    plots = {}

    # Hydrodynamic surface velocity
    plots['hydro_quiver'] = ax.quiver(seg_track.x_m,
                                      seg_track.y_m,
                                      seg_track[model_u],
                                      seg_track[model_v],
                                      color='k')

    plots['groundspeed_quiver'] = ax.quiver(seg_track.x_m,
                                            seg_track.y_m,
                                            seg_track.ground_u,
                                            seg_track.ground_v,
                                            color='orange')

    plots['swim_quiver'] = ax.quiver(seg_track.x_m,
                                     seg_track.y_m,
                                     seg_track.swim_u,
                                     seg_track.swim_v,
                                     color='b')
    plots['togglers'] = [
        plots['hydro_quiver'], plots['groundspeed_quiver'],
        plots['swim_quiver']
    ]

    if buttons:
        button_ax = fig.add_axes([0.01, 0.8, 0.2, 0.12])
        button_ax.axis('off')
        plots['button_ax'] = button_ax
        plots['buttons'] = widgets.CheckButtons(button_ax,
                                                ["Hydro", "Smooth", "Swim"])

        def button_cb(arg, plots=plots):
            # Unclear why this has to be negated
            [
                t.set_visible(stat) for t, stat in zip(
                    plots['togglers'], plots['buttons'].get_status())
            ]
            plots['fig'].canvas.draw()

        plots['buttons'].on_clicked(button_cb)

    for t in plots['togglers']:
        t.set_visible(0)

    ax.plot(hydros.yap_x, hydros.yap_y, 'o', mfc='none', mec='k', zorder=-1)

    dc = dem.crop([zoom[0] - 500, zoom[1] + 500, zoom[2] - 500, zoom[3] + 500])
    dc.plot(ax=ax,
            zorder=-5,
            cmap='gray',
            clim=[-20, 10],
            interpolation='bilinear')
    dc.plot_hillshade(ax=ax,
                      z_factor=1,
                      plot_args=dict(interpolation='bilinear', zorder=-4))
    ax.axis(zoom)
    ax.axis('off')

    ax_hist = fig.add_subplot(gs[1, :])

    Uscale = 0.6
    xvals = -seg_track['swim_vrel']
    yvals = seg_track['swim_urel']

    if swim_filt is not None:
        xvals = swim_filt(xvals)
        yvals = swim_filt(yvals)

    sns.kdeplot(xvals,
                yvals,
                shade_lowest=False,
                clip=[[-Uscale, Uscale], [-Uscale, Uscale]],
                linewidths=0.5,
                levels=5,
                ax=ax_hist)

    scat = ax_hist.scatter(xvals, yvals, 8, elapsed, cmap=turbo)
    ax_hist.set_xlabel('left  ferry  right')
    ax_hist.set_ylabel('+rheo — -rheo')
    ax_hist.axis('equal')
    ax_hist.axhline(0.0, color='0.5', lw=0.5)
    ax_hist.axvline(0.0, color='0.5', lw=0.5)
    plt.colorbar(scat, ax=ax_hist, label="Elapsed time (s)")

    ax_hist.axis([-Uscale, Uscale, -Uscale, Uscale])
    fig.tight_layout()
    plots['fig'] = fig

    track_common.set_direction_labels(ax_hist)

    # Text info
    ax_txt = fig.add_subplot(gs[0, 1])
    ax_txt.axis('off')
    plots['tag'] = seg_track.id.values[0]
    txt = "Tag: %s" % (plots['tag'])
    ax_txt.text(0.05, 0.95, txt, va='top')

    plots['ax_hist'] = ax_hist

    return plots
예제 #24
0
    def __init__(
        self,
        pop_size: int = 5000,
        initial_cases: int = 1,
        hospital_beds_ratio: float = .003,
        infection_distance: np.float64 = 2.0,
        infection_time: np.uint64 = 20,
        p_infect: float = 0.3,
        p_recover: float = 0.7,
        map_size: np.float64 = 100.0,
    ) -> None:

        # Simulation starts at time t=0
        self.time: int = 0

        # Keep track of the population size for this simulation
        self.pop_size: int = pop_size
        # Also the other parameters given
        self.map_size: np.float64 = map_size
        self.infection_distance: np.float64 = infection_distance
        self.infection_time: np.uint64 = infection_time
        self.p_infect: float = p_infect
        self.p_recover: float = p_recover
        self.p_die: float = 1 - p_recover
        self.hospital_beds_ratio: float = hospital_beds_ratio

        # Position and health of everyone in the population
        self.positions: np.ndarray = \
            np.random.uniform(
                low=0.0,
                high=self.map_size,
                size=(self.pop_size,2),
            )
        self.healths: np.ndarray = \
            np.full(
                shape=(self.pop_size,),
                fill_value=Simulation.HEALTHY,
                dtype=Simulation.Health,
            )
        self.infected_duration: np.ndarray = \
            np.zeros( shape=(self.pop_size,), dtype=np.uint64 )

        # Note that we don't have to randomly draw from `self.healths`. The
        #  positions are all generated in the same way, and they're all
        #  indistinguishable from each other.
        self.healths[0:initial_cases] = Simulation.INFECTED
        self.infected_duration[0:initial_cases] = 1

        # Keep track of the statistics too
        self.infected: List[int] = []
        self.recovered: List[int] = []
        self.dead: List[int] = []
        self.new_cases: List[int] = []

        # Create the figure for plotting
        self.fig = plt.figure(figsize=(16, 9))
        # Legend
        # Keep it on the whole figure since the colors apply to everything
        self.fig.legend(handles=[
            mpatches.Patch(color='blue', label='Healthy'),
            mpatches.Patch(color='red', label='Infected'),
            mpatches.Patch(color='green', label='Recovered'),
            mpatches.Patch(color='black', label='Deceased'),
        ],
                        loc='lower left')
        # Add a grid for layout
        grid = self.fig.add_gridspec(nrows=3, ncols=4)
        # Add the map and statistics
        self.map_ax = self.fig.add_subplot(grid[0:, 1:])
        self.stats_ax = self.fig.add_subplot(grid[0, 0])
        self.traj_ax = self.fig.add_subplot(grid[1, 0])
        self.check_ax = self.fig.add_subplot(grid[2, 0], frame_on=False)
        # Add labels
        self.stats_ax.set_xlabel('Time')
        self.stats_ax.set_ylabel('Cases')
        self.traj_ax.set_xlabel('Log(Total Cases)')
        self.traj_ax.set_ylabel('Log(New Cases)')
        # Call for updates
        self.map_ani = \
            animation.FuncAnimation(
                self.fig,
                self.tick_map,
                init_func=self.init_map)
        self.stats_ani = \
            animation.FuncAnimation(
                self.fig,
                self.tick_stats)

        # Check buttons and simulation options
        self.paused: bool = False
        self.log_scale: bool = False
        self.p_movement: float = 1.0
        self.checks = widgets.CheckButtons(self.check_ax, [
            'Use Log Scale',
            'Total Social Distancing',
            'Partial Social Distancing',
            'Paused',
        ])
        self.checks.on_clicked(self.checkbox_handler)
예제 #25
0
# to avoid garbage collection
ax._widgets = []

# CREATE BUTTONS

button_width = 0.1
button_lheigh = 0.07
button_x0 = 0.05
button_y0 = 0.05

# 1. ALPHA
n_buttons = len(alpha_values)
ax_alpha = fig.add_axes(
    [button_x0, button_y0, button_width, n_buttons * button_lheigh])
alpha_buttons = w.CheckButtons(ax_alpha, [str(s) for s in alpha_values],
                               [True] + (n_buttons - 1) * [False])
ax_alpha.set_title(r'$\alpha$')
ax._widgets += [alpha_buttons]  # avoids garbage collection

# 2. vf
n_buttons = len(vf_values)
ax_vf = fig.add_axes([
    button_x0 + button_width, button_y0, button_width,
    n_buttons * button_lheigh
])
vf_buttons = w.CheckButtons(ax_vf, [str(s) for s in vf_values],
                            [True] + (n_buttons - 1) * [False])
ax_vf.set_title(r'$v_\mathrm{frag}$')
ax._widgets += [vf_buttons]  # avoids garbage collection

info_dict = {}
예제 #26
0
button_lheigh = 0.06
button_x0 = 0.02
button_y0 = 0.5
"""Panel Control"""

figB = plt.figure(figsize=(15, 6))

n_buttons_1 = len(Mp1_values)

ax_Mp1 = figB.add_axes([
    button_x0 + 0 * button_width, button_y0, button_width,
    n_buttons_1 * button_lheigh
],
                       facecolor=color)

Mp1_buttons = w.CheckButtons(ax_Mp1, [s for s in Mp1_values],
                             [False] + (n_buttons_1 - 1) * [False])
ax_Mp1.set_title(r'$M_\mathrm{p1} (M_j)$')
ax._widgets += [Mp1_buttons]
#
n_buttons = len(Mp2_values)
ax_Mp2 = figB.add_axes([
    button_x0 + 1 * button_width,
    (n_buttons_1 - n_buttons) * button_lheigh + button_y0, button_width,
    n_buttons * button_lheigh
],
                       facecolor=color)
Mp2_buttons = w.CheckButtons(ax_Mp2, [s for s in Mp2_values],
                             [False] + (n_buttons - 1) * [False])
ax_Mp2.set_title(r'$M_\mathrm{p2} (M_j)$')
ax._widgets += [Mp2_buttons]
예제 #27
0
    def run(self):
        """ runs the segment picker """
        # show the images
        self.fig, self.axes = plt.subplots(nrows=1,
                                           ncols=2,
                                           sharex=True,
                                           sharey=True,
                                           squeeze=True)
        plt.subplots_adjust(bottom=0.2)
        ax_img, ax_feat = self.axes

        imshow_args = {
            'interpolation': 'none',
            'aspect': 1,
            'cmap': plt.get_cmap('gray')
        }

        ax_img.imshow(self._frame, **imshow_args)
        ax_img.set_title('First _frame of video')
        ax_img.set_autoscale_on(False)

        ax_feat.imshow(self.features, **imshow_args)
        ax_feat.set_title('Automatic feature extraction')
        ax_feat.set_autoscale_on(False)

        # internal data
        self.active = True
        self.result = 'cancel'
        self.bounds = self._frame.shape
        self._ax_segments = [[] for _ in xrange(len(self.axes))]

        # initialize data
        if self.segments:
            segments = self.segments
            self.segments = []
            for segment in segments:
                self._add_segment(segment)

        # drawtype is 'box' or 'line' or 'none'
        useblit = graphics.backend_supports_blitting()
        self.selectors = [
            widgets.RectangleSelector(
                ax,
                self.select_callback,
                drawtype='line',
                lineprops=self.lineprops,
                useblit=useblit,
                button=[1],  # don't use middle button
                minspanx=5,
                minspany=5,
                spancoords='pixels') for ax in (ax_img, ax_feat)
        ]

        # add buttons
        ax_active = plt.axes([0.5, 0.05, 0.1, 0.075])
        check = widgets.CheckButtons(ax_active, ['active'], [self.active])
        check.on_clicked(self.clicked_check)

        ax_ok = plt.axes([0.7, 0.05, 0.1, 0.075])
        bn_ok = widgets.Button(ax_ok, 'Ok')
        bn_ok.on_clicked(self.clicked_ok)

        ax_cancel = plt.axes([0.81, 0.05, 0.1, 0.075])
        bp_cancel = widgets.Button(ax_cancel, 'Cancel')
        bp_cancel.on_clicked(self.clicked_cancel)

        self.msg()

        # initialize the interaction with the image
        self.fig.canvas.mpl_connect('button_press_event', self.click_image)

        # process result
        plt.show()
        return self.result
예제 #28
0
def interactiveLegend(ax,
                      labels=False,
                      show_default=True,
                      loc='best',
                      **kwargs):
    """Adds an interactive save button to a given figure.
    
    Parameters
    ----------
    ax : plt.Axes
        The axes to which the interactive legend should be added.
    labels=False : bool, list
        If not false, the list of string names for the different lines that 
        are plotted.
    show_default=True : bool, list
        If not bool, the list of boolean values that say whether to show at 
        first or not the different lines that are plotted.
    loc='best' : str
        A string that indicates where to add the legend on the plot area. 
        Can be 'best', 'upper right', 'upper left', 'lower right', 
        'lower left'.
    
    Returns
    -------
    buttons : wid.Button
        Interactive legend instance.
    """

    # First, get the lines that are currently plotted
    lines = ax.lines
    if labels is False:
        labels = [l.get_label() for l in lines]

    # Now, if needed, correct labels and default show parameters
    try:
        N = len(labels)
    except:
        N = 1
    if N == 1:
        labels = list(labels)
    try:
        M = len(show_default)
    except:
        M = 1
    if M != N and M == 1:
        show_default = [show_default for l in labels]

    # Choose legend location
    number = len(labels)
    height = .05 * number
    extra_y = .05 * (number - 1)
    try:
        fsize = kwargs['fontsize']
    except:
        fsize = 10
    if fsize == 10:
        width = .23
        extra_x = 0
    else:
        width = .23 * fsize / 10
        extra_x = .23 * (fsize / 10 - 1)
    try:
        x0 = kwargs.pop('x0')
    except:
        x0 = (.14, .65)
    try:
        y0 = kwargs.pop('y0')
    except:
        y0 = (.03, .81)
    if loc == 'best':
        xmin = min([min(l.get_data()[0]) for l in lines])
        xmax = max([max(l.get_data()[0]) for l in lines])
        ymin = min([min(l.get_data()[1]) for l in lines])
        ymax = max([max(l.get_data()[1]) for l in lines])
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        if abs(ymin - ylim[0]) > abs(ymax - ylim[1]):
            loc = 'lower '
        else:
            loc = 'upper '
        if abs(xmin - xlim[0]) > abs(xmax - xlim[1]):
            loc = loc + 'left'
        else:
            loc = loc + 'right'
    if loc == 'upper right':
        position = [x0[1] - extra_x, y0[1] - extra_y, width, height]
    elif loc == 'upper left':
        position = [x0[0] + extra_x, y0[1] - extra_y, width, height]
    elif loc == 'lower right':
        position = [x0[1] - extra_x, y0[0] + extra_y, width, height]
    elif loc == 'lower left':
        position = [x0[0] + extra_x, y0[0] + extra_y, width, height]
    else:
        raise ValueError("Unvalid legend location")

    # Create legend buttons
    ax_buttons = plt.axes(position)
    buttons = wid.CheckButtons(ax_buttons, labels, show_default)
    legends = buttons.labels
    for l, leg in zip(lines, legends):
        leg.set_color(l.get_color())
        leg.set(**kwargs)
    for l, sd in zip(lines, show_default):
        l.set_visible(sd)

    # Add callback function and run
    def buttons_callback(label):
        for l, leg in zip(lines, legends):
            if label == leg.get_text():
                l.set_visible(not l.get_visible())
        plt.draw()
        return

    buttons.on_clicked(buttons_callback)

    plt.show()

    return buttons
예제 #29
0
def plot_image_interactive(imgobj):
    """
    Plot an image object in an interactive way

    Parameters
    ----------
    imgobj : data_io.GeneralImage
    """
    fig, ax = plt.subplots(figsize=(8, 6))
    plt.subplots_adjust(bottom=0.25, left=-0.1)
    img = imgobj.data
    intmax = np.max(img)
    intmin = np.min(img)
    # img = imf.linscale(img, intmin, intmax)
    lim = plt.imshow(img, cmap="Greys_r")
    sb_settings = {"location": 'lower right',
                   "color": 'k',
                   "length_fraction": 0.25,
                   "font_properties": {"size": 12}}
    scalebar = get_scalebar(imgobj.pixelsize, imgobj.pixelunit, sb_settings)
    plt.gca().add_artist(scalebar)
    scalebar.set_visible(False)

    ax.margins(x=0)

    axcolor = 'white'
    # [x, y, width, height]
    axwidth = 0.7
    axheight = 0.03

    axmax = plt.axes([0.5-axwidth/2, 0.10, axwidth, axheight],
                     facecolor=axcolor)
    axmin = plt.axes([0.5-axwidth/2, 0.05, axwidth, axheight],
                     facecolor=axcolor)

    smax = wdgts.Slider(axmax, 'Max', intmin, intmax, valinit=intmax)
    smin = wdgts.Slider(axmin, 'Min', intmin, intmax, valinit=intmin)

    def update_frame(val):
        mx = smax.val
        mn = smin.val
        # arr = imgobj.data
        # arr = imf.linscale(arr, mn, mx)
        lim.set_clim(mn, mx)
        fig.canvas.draw_idle()

    smax.on_changed(update_frame)
    axmax._slider = axmax
    smin.on_changed(update_frame)
    axmin._slider = axmin

    # checkbox for scalebar
    sba = plt.axes([0.65, 0.2, 0.25, 0.25], facecolor=axcolor)
    sba.axis("off")
    sbb = wdgts.CheckButtons(sba, ('scalebar',))

    def seescalebar(label):
        yesorno = sbb.get_status()[0]
        scalebar.set_visible(yesorno)
        fig.canvas.draw_idle()

    sbb.on_clicked(seescalebar)
    sba._checkbox = sbb

    plt.show()