Exemplo n.º 1
0
    def _create_sliders(self):
        """ Create sliders that allow the user to scroll the axes. """
        # Create sliders for scrollable axes
        # Position at top of the graph - numbers below are positionings relative
        # to the figure: [left, bottom, width, height]
        x_slider = plt.axes([0.2, 0.95, 0.6, 0.015])
        x_slider_pos = widgets.Slider(
            x_slider, 'Position of x-axis\n/ ' + self.labels.x_units,
            self.data_stats.x_min + self.data_stats.x_delta,
            self.data_stats.x_max - self.data_stats.x_delta)
        x_slider_pos.valtext.set_visible(False)

        y_slider = plt.axes([0.2, 0.9, 0.6, 0.015])
        y_slider_pos = widgets.Slider(
            y_slider, 'Position of y-axis\n/ ' + self.labels.y_units,
            self.data_stats.y_min + self.data_stats.y_delta,
            self.data_stats.y_max - self.data_stats.y_delta)
        y_slider_pos.valtext.set_visible(False)

        def update(val):
            """ Update the axes on slider change """
            # Determine new positions
            self.pos = self._ViewportPosition(x=x_slider_pos.val,
                                              y=y_slider_pos.val)
            self._set_axes_limits()
            self._redraw()

        # Listeners for slider changes
        x_slider_pos.on_changed(update)
        y_slider_pos.on_changed(update)
Exemplo n.º 2
0
def interact():

    ax = plt.subplot(111)
    plt.subplots_adjust(bottom=.25)

    t = np.arange(0, 1, .001)
    a0, f0 = 5, 3
    s = a0 * np.sin(2 * np.pi * f0 * t)
    l = plt.plot(t, s)[0]

    plt.axis([0, 1, -10, 10])
    axfreq = plt.axes([.25, .05, .65, .03])
    axamp = plt.axes([.25, .1, .65, .03])
    sfreq = wg.Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
    samp = wg.Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)

    def update(val):
        amp = samp.val
        freq = sfreq.val
        l.set_ydata(amp * np.sin(2 * np.pi * freq * t))
        plt.draw()

    sfreq.on_changed(update)
    samp.on_changed(update)
    plt.savefig("interact.pdf")
    plt.clf()
Exemplo n.º 3
0
def test_slider_horizontal_vertical():
    fig, ax = plt.subplots()
    slider = widgets.Slider(ax=ax,
                            label='',
                            valmin=0,
                            valmax=24,
                            valinit=12,
                            orientation='horizontal')
    slider.set_val(10)
    assert slider.val == 10
    # check the dimension of the slider patch in axes units
    box = slider.poly.get_extents().transformed(ax.transAxes.inverted())
    assert_allclose(box.bounds, [0, 0, 10 / 24, 1])

    fig, ax = plt.subplots()
    slider = widgets.Slider(ax=ax,
                            label='',
                            valmin=0,
                            valmax=24,
                            valinit=12,
                            orientation='vertical')
    slider.set_val(10)
    assert slider.val == 10
    # check the dimension of the slider patch in axes units
    box = slider.poly.get_extents().transformed(ax.transAxes.inverted())
    assert_allclose(box.bounds, [0, 0, 1, 10 / 24])
Exemplo n.º 4
0
def problem6():
    ax = plt.subplot(111)
    plt.subplots_adjust(bottom=.25)
    t = np.arange(0, 1.01, .01)
    a = 5.
    f = 3.
    p = 0.
    fc = lambda a, f, p, t: a * np.sin(2 * np.pi * f * (t - p))
    l = plt.plot(t, fc(a, f, p, t))[0]
    axfreq = plt.axes([.25, .05, .65, .03])
    axamp = plt.axes([.25, .1, .65, .03])
    axph = plt.axes([.25, .15, .65, .03])
    sfreq = wg.Slider(axfreq, "Freq", .1, 30., valinit=f)
    samp = wg.Slider(axamp, "Amp", .1, 10., valinit=a)
    sph = wg.Slider(axph, "Phase", 0, 2 * np.pi, valinit=p)

    def update(val):
        a = samp.val
        f = sfreq.val
        p = sph.val
        l.set_ydata(fc(a, f, p, t))
        plt.draw()

    sfreq.on_changed(update)
    samp.on_changed(update)
    sph.on_changed(update)
    plt.show()
Exemplo n.º 5
0
    def add_param_sliders(self):
        """
        Add sliders to the figure to allow the models parameters to be set.
        """
        offset = 0.0
        self.param_sliders = dict()
        #import pdb; pdb.set_trace()
        for param, default_param in self.parameters.items():
            offset += 0.035
            sax = self.ipp_fig.add_axes([0.825, 0.865 - offset, 0.125, 0.025],
                                        axisbg=AXCOLOUR)
            default_param = default_param[0]
            param_range = self.model.trait[param].trait.inits.kwd.get(
                'range', None)
            if param_range:
                self.param_sliders[param] = widgets.Slider(
                    sax,
                    param,
                    param_range.lo,
                    param_range.hi,
                    valinit=default_param)
            else:
                self.param_sliders[param] = widgets.Slider(
                    sax, param, -1.0, 1.0, valinit=default_param)

            self.param_sliders[param].on_changed(self.update_parameters)
Exemplo n.º 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
Exemplo n.º 7
0
def test_slider_valstep_snapping():
    fig, ax = plt.subplots()
    slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                            valinit=11.4, valstep=1)
    assert slider.val == 11

    slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                            valinit=11.4, valstep=[0, 1, 5.5, 19.7])
    assert slider.val == 5.5
Exemplo n.º 8
0
def test_slider_slidermin_slidermax_invalid():
    fig, ax = plt.subplots()
    # test min/max with floats
    with pytest.raises(ValueError):
        widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                       slidermin=10.0)
    with pytest.raises(ValueError):
        widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                       slidermax=10.0)
Exemplo n.º 9
0
def test_slider_valmin_valmax():
    fig, ax = plt.subplots()
    slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                            valinit=-10.0)
    assert slider.val == slider.valmin

    slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                            valinit=25.0)
    assert slider.val == slider.valmax
Exemplo n.º 10
0
def plot_line_spectrum(specline):
    """
    Plot an interactive spectrum map
    """
    axwidth = 0.7
    axheight = 0.03

    fig, ax = plt.subplots(figsize=(8, 6))
    plt.subplots_adjust(bottom=0.25, left=0.5-axwidth/2)

    e0 = 0
    w0 = 0.5

    spec = specline.spectrum

    # maximum for sliders
    emin = specline._get_energy_of_channel(0)
    emax = specline._get_energy_of_channel(specline.channels)

    prof = specline.get_profile(e0, w0)
    # img = imf.linscale(img, intmin, intmax)
    _, lpf = prof.plot(axis=ax)
    lpf = lpf[0]

    axcolor = 'white'
    # [x, y, width, height]
    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)

    sen = wdgts.Slider(axenergy, f'Energy ({specline.energy_unit})', emin,
                       emax, valinit=e0)
    swi = wdgts.Slider(axwidth, f'Width ({specline.energy_unit})', 0,
                       (emax-emin)/2, valinit=w0)
    axenergy._slider = sen
    axwidth._slider = swi

    def update_im(val):
        en = sen.val
        wi = swi.val
        arr = specline._integrate_to_line(en, wi)
        lpf.set_ydata(arr)
        fig.canvas.draw_idle()

    sen.on_changed(update_im)
    swi.on_changed(update_im)

    # 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")

    plt.show()
Exemplo n.º 11
0
   def __init__(self, normType, n, k, logAlpha, beta, imgFiles):
      
      plt.ion()
      self.figImage = plt.figure()

      # add files
      self.plots = []
      numFiles = len(imgFiles)
      cntRows = int(round(math.sqrt(0.75*numFiles), 0))
      cntCols = int(math.ceil(float(numFiles) / cntRows))
      for i in xrange(0, numFiles):
         self.plots.append(NormDisplayAxes(self.figImage, imgFiles[i], [cntCols, cntRows], \
            [i % cntCols, cntRows - (i / cntCols + 1)], [0.95/cntCols, 0.7/cntRows], normType, n, k, logAlpha, beta))
      

      #self.figImage.subplots_adjust(bottom = 0.3)
      
      self.axNormType = self.figImage.add_subplot(9, 2, 13, axisbg='lightgoldenrodyellow', adjustable='datalim')
      self.axNormType.set_position([0.1, 0.05, 0.4, 0.2])
      self.axN = self.figImage.add_subplot(9, 2, 12, axisbg='lightgoldenrodyellow', adjustable='datalim')
      self.axN.set_position([0.6, 0.2, 0.3, 0.03])
      self.axK = self.figImage.add_subplot(9, 2, 14, axisbg='lightgoldenrodyellow', adjustable='datalim')
      self.axK.set_position([0.6, 0.15, 0.3, 0.03])
      self.axAlpha = self.figImage.add_subplot(9, 2, 16, axisbg='lightgoldenrodyellow', adjustable='datalim')
      self.axAlpha.set_position([0.6, 0.1, 0.3, 0.03])
      self.axBeta = self.figImage.add_subplot(9, 2, 18, axisbg='lightgoldenrodyellow', adjustable='datalim')
      self.axBeta.set_position([0.6, 0.05, 0.3, 0.03])

      self.currentNormType = normType
      self.sliderN = widgets.Slider(self.axN, label='N', valmin=1, valmax=10, valinit=n, valfmt='%d')
      self.sliderK = widgets.Slider(self.axK, label='k', valmin=.1, valmax=10, valinit=k)
      self.sliderAlpha = widgets.Slider(self.axAlpha, label=r'$\log_{10}\alpha$', valmin=-6, valmax=1, valinit=logAlpha)
      self.sliderBeta  = widgets.Slider(self.axBeta, label=r'$\beta$', valmin=0.1, valmax=3, valinit=beta)
      self.radioNormType = widgets.RadioButtons(self.axNormType, \
                     labels = ['ResponseNorm - Across maps', 'ResponseNorm - Same map', \
                               'ContrastNorm - Across maps', 'ContrastNorm - Same map'], active = self.currentNormType)
      self.figTitle = self.figImage.suptitle("Normalization", fontsize=14)

      def radio_onClicked(msg):
         self.currentNormType = [m.get_text() for m in self.radioNormType.labels].index(msg)
         self.updateNormedImage()

      def slider_onChanged(newVal):
         self.updateNormedImage()

      self.sliderN.on_changed(slider_onChanged)
      self.sliderK.on_changed(slider_onChanged)
      self.sliderAlpha.on_changed(slider_onChanged)
      self.sliderBeta.on_changed(slider_onChanged)
      self.radioNormType.on_clicked(radio_onClicked)
      
      self.updateNormedImage()
      plt.show()
      raw_input()
Exemplo n.º 12
0
def test_slider_slidermin_slidermax():
    fig, ax = plt.subplots()
    slider_ = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                             valinit=5.0)

    slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                            valinit=1.0, slidermin=slider_)
    assert slider.val == slider_.val

    slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
                            valinit=10.0, slidermax=slider_)
    assert slider.val == slider_.val
Exemplo n.º 13
0
    def draw_plot(self):
        self.fig = plt.figure()

        gs1 = mpl.gridspec.GridSpec(self.rows, self.cols)
        gs1.update(wspace=0.025, hspace=0.025) # set the spacing between axes. 

        self.axs = []
        self.ims = []

        for r in range(0,self.rows):
            for c in range(0,self.cols):
                im_no = r*self.cols+c
                if im_no > 0:
                    self.axs.append(plt.subplot(gs1[im_no],sharex=self.axs[0],sharey=self.axs[0]))
                else:
                    self.axs.append(plt.subplot(gs1[im_no]))

                if im_no < self.im_per_frame:
                    im = self.axs[im_no].imshow(np.squeeze(self.data[0,im_no,:,:]), interpolation='none',cmap=plt.get_cmap(self.cmap))
                    self.ims.append(im)

                self.axs[im_no].axis('off')
        
        self.fig.subplots_adjust(right=0.8)
        cbar_ax = self.fig.add_axes([0.85, 0.25, 0.05, 0.5])
        self.fig.colorbar(im, cax=cbar_ax)
        
        slider_window_ax = self.fig.add_axes([0.85, 0.15, 0.10, 0.025])
        window_min = 0
        window_max = np.max(self.data)-np.min(self.data)
        self.window = window_max
        self.window_slider = widgets.Slider(slider_window_ax, label='W: ', color='black', valmin=window_min, valmax=window_max, valinit=self.window)
        self.window_slider.on_changed(lambda value: self.set_window(value))

        slider_level_ax = self.fig.add_axes([0.85, 0.10, 0.10, 0.025])
        level_max = np.max(self.data)
        level_min = np.min(self.data)
        self.level = (level_max-level_min)/2
        self.level_slider = widgets.Slider(slider_level_ax, label='L: ', color='black', valmin=level_min, valmax=level_max, valinit=self.level)
        self.level_slider.on_changed(lambda value: self.set_level(value))

        slider_f_ax = self.fig.add_axes([0.85, 0.05, 0.10, 0.025])
        self.frame_slider = widgets.Slider(slider_f_ax, label='T: ', color='black', valmin=0, valmax=self.data.shape[0]-1,valfmt=' %d',valinit=0)
        self.frame_slider.on_changed(lambda value: self.update_plot(frame=int(value)))

        self.update_contrast()
        
        self.window_level_mouse = WindowLevelMouse(self)
        
        manager = plt.get_current_fig_manager()
    def __init__(self, number_y, number_x, max_time, init_time, init_omega,
                 init_mu):  # три раза одно и то же: создаем axes слайдера, задаем сам
        # слайдер с его min, max, и начальным значением, а так же указываем функцию, которую вызываем при изменении
        self.axes_duration = plt.axes([0.03 + number_x * 0.49, 0.42 - number_y * 0.1, 0.4, 0.02])  # положение
        self.duration = wdg.Slider(self.axes_duration, valmin=0, valmax=max_time, label='t', valinit=init_time,
                                   valfmt='%1.3f')  # мин, макс, лейбл, начальное значение
        self.duration.on_changed(Solver)  # вызов функции при обновлении обновления

        self.axes_omega = plt.axes([0.03 + number_x * 0.49, 0.39 - number_y * 0.1, 0.4, 0.02])
        self.omega = wdg.Slider(self.axes_omega, valmin=-1, valmax=1, label='ω', valinit=init_omega, valfmt='%1.5f')
        self.omega.on_changed(Solver)

        self.axes_mu = plt.axes([0.03 + number_x * 0.49, 0.36 - number_y * 0.1, 0.4, 0.02])
        self.mu = wdg.Slider(self.axes_mu, valmin=0, valmax=1, label='μ', valinit=init_mu, valfmt='%1.0f')
        self.mu.on_changed(Solver)
Exemplo n.º 15
0
def main():

    file_name, interactive = lib_args.get_args()
    header, pixels = lib_fits.read_first_image(file_name)
    background, dispersion, max_x = lib_background.compute_background(pixels)

    # console output
    print('background: {:d}, dispersion: {:d}'.format(int(background),int(dispersion)))

    # graphic output
    if interactive:

        fig, axis = plt.subplots()
        imgplot = axis.imshow(pixels)

        ax_thresh = plt.axes([0.25, 0.92, 0.65, 0.03])
        s_thresh = widgets.Slider(ax_thresh, 'Threshold', 0.0, max_x, valinit=background)

        update_slider = UpdateSlider(pixels,imgplot,fig)
        s_thresh.on_changed(update_slider)
        update_slider(background)

        plt.show()

    return 0
Exemplo n.º 16
0
def main():

    file_name, interactive = lib_args.get_args()
    header, pixels = lib_fits.read_first_image(file_name)
    background, dispersion, max_x = lib_background.compute_background(pixels)
    clustering = lib_cluster.Clustering()
    clusters = clustering(pixels, background, dispersion)

    # console output
    if not interactive:

        print('{} clusters'.format(len(clusters)))

    else:
        # graphic output

        fig, axis = plt.subplots()
        imgplot = axis.imshow(pixels)

        axcolor = 'lightgoldenrodyellow'
        ax_thresh = plt.axes([0.25, 0.92, 0.65, 0.03], axisbg=axcolor)

        threshold = 6.0
        slider = widgets.Slider(ax_thresh, 'Threshold', 0.0, 5*threshold, valinit=threshold)

        update_slider = UpdateSlider(pixels, background, dispersion, imgplot, fig)
        slider.on_changed(update_slider)
        update_slider(threshold)

        plt.show()

    return 0
Exemplo n.º 17
0
    def __init__(self, imgArr):
        '''
        Plot images from a stack, use a slider to move through the stack.

        Args:
            imgArr (np.array): Size (nFrames, width, height)
        '''
        self.imgArr = imgArr
        self.nFrames = imgArr.shape[0]
        self.imgMin = np.min(imgArr.ravel())
        self.imgMax = np.max(imgArr.ravel())
        self.fig = plt.figure()
        plt.clf()
        self.axPlot = self.fig.add_subplot(111)

        im = self.axPlot.imshow(self.imgArr[0, :, :])
        im.set_clim(self.imgMin, self.imgMax)

        plt.subplots_adjust(left=0.25, bottom=0.25)
        self.axSlider = plt.axes([0.25, 0.1, 0.65, 0.03])
        self.slider = widgets.Slider(self.axSlider,
                                     'Frame',
                                     0,
                                     self.nFrames - 1,
                                     valinit=0)
        self.slider.on_changed(self.plot_frame)
        plt.show()
Exemplo n.º 18
0
def problem6():
    A = plt.imread('kvinna.jpg')
    U, S, VT = slin.svd(A, full_matrices=False)
    sigmamax = max(S)
    fig, ax_array = plt.subplots(1, 2)
    plt.subplots_adjust(bottom=0.2)

    ax_array[0].set_title('Compressed image')
    ax_array[1].set_title('Uncompressed image')
    ax_array[0].imshow(A)
    ax_array[1].imshow(A)

    slider_ax = plt.axes([0.3, 0.1, 0.4, 0.02])
    s = w.Slider(slider_ax,
                 "Sigma max",
                 0,
                 np.log10(sigmamax),
                 valinit=np.log10(310))

    def compress(val):
        maximum_sigma = 10**s.val
        s.valtext.set_text(int(maximum_sigma))
        S_nu = np.diag(S)
        S_nu[S < maximum_sigma] = 0
        A_nu = U.dot(S_nu.dot(VT))
        ax_array[0].imshow(A_nu)

    s.on_changed(compress)
    plt.show()
    def radio_action(self, file_name):
        """
        On click function for radio button
        :param file_name: name of the fits file
        """

        # Get pixels and header from a fits file
        self.pixels, _ = mylib.get_pixels("../data/%s" % (file_name))

        # Process to the fit of the background
        _, _, _, self.background, self.dispersion = mylib.modelling_parameters(
            self.pixels)

        # Remove the background
        filtered_pixels = mylib.remove_background(self.pixels, self.background,
                                                  self.dispersion)

        # Update the picture
        self.axis.cla()  # delete the previous imshow
        self.axis.imshow(filtered_pixels)
        self.axis.set_title('Use of both slider and radio button')
        self.fig.canvas.draw()  # redraw

        # Define the slider widget
        threshold_min = max(0, self.background - 6.0 * self.dispersion)
        threshold_max = self.background + 10.0 * self.dispersion
        threshold_init = self.background + 6.0 * self.dispersion
        if self.my_widget is not None:
            self.slider_axis.cla()
        self.my_widget = widgets.Slider(self.slider_axis, 'threshold', threshold_min, \
                                   threshold_max, valinit=threshold_init)
Exemplo n.º 20
0
    def plot_init_time_slider(self, init_idx=-1, ref_idx=None):
        val_step = np.min(np.diff(self.yearList))
        val_min = self.yearList[0]
        val_max = self.yearList[-1]

        self.tslider = widgets.Slider(
            self.ax_tslider,
            label='Time',
            valinit=self.yearList[init_idx],
            valmin=val_min,
            valmax=val_max,
            valstep=val_step)

        bar_width = val_step / 4.
        datex = np.array(self.yearList) - bar_width / 2.
        self.tslider.ax.bar(datex, np.ones(len(datex)), bar_width, facecolor='black', ecolor=None)
        if ref_idx is not None:
            self.tslider.ax.bar(datex[ref_idx], 1., bar_width*3, facecolor='crimson', ecolor=None)

        # xaxis tick format
        if np.floor(val_max) == np.floor(val_min):
            digit = 10.
        else:
            digit = 1.
        self.tslider.ax.set_xticks(np.round(np.linspace(val_min, val_max, num=5) * digit) / digit)
        self.tslider.ax.xaxis.set_minor_locator(ticker.MultipleLocator(1./12.))
        self.tslider.ax.set_xlim([val_min, val_max])
        self.tslider.ax.set_yticks([])
        self.tslider.valtext.set_visible(False)   #hide slider values
        return self.tslider
def decasteljau_interactive(n):
    """ Makes an interactive plot using a slider bar to show the
    Decasteljau algorithm at different times."""
    ax = plt.subplot(1, 1, 1)
    plt.subplots_adjust(bottom=0.25)
    plt.axis([-1, 1, -1, 1])
    axT = plt.axes([0.25, 0.1, 0.65, 0.03])
    sT = wg.Slider(axT, 't', 0, 1, valinit=0)
    pts = plt.ginput(n, timeout=240)
    plt.subplot(1, 1, 1)
    pts = np.array(pts)
    plt.cla()
    T0 = 0
    decasteljau_animated(pts, T0)
    plt.axis([-1, 1, -1, 1])
    plt.draw()

    def update(val):
        T = sT.val
        ax.cla()
        plt.subplot(1, 1, 1)
        decasteljau_animated(pts, T)
        plt.xlim((-1, 1))
        plt.ylim((-1, 1))
        plt.draw()

    sT.on_changed(update)
    plt.show()
Exemplo n.º 22
0
 def __init__(self):
     self.Finder = None
     self.fig, self.ax = plt.subplots()
     plt.subplots_adjust(left=0.25, bottom=0.075, top=0.975)
     self.radio_ax = plt.axes([0.05, 0.7, 0.15, 0.15])
     #self.radio_ax.set_axis_off()
     self.radio_ax.set_frame_on(False)
     self.radio_ax.set_xticks([])
     self.radio_ax.set_yticks([])
     self.open_ax = plt.axes([0.01, 0.05, 0.07, 0.075])
     self.update_ax = plt.axes([0.09, 0.05, 0.07, 0.075])
     self.save_ax = plt.axes([0.17, 0.05, 0.07, 0.075])
     self.slider_ax = plt.axes([0.35, 0.01, 0.5, 0.02])
     self.openbutton = widgets.Button(self.open_ax, 'Open')
     self.updatebutton = widgets.Button(self.update_ax, 'Update')
     self.savebutton = widgets.Button(self.save_ax, 'Save\nImage')
     self.contrastslider = widgets.Slider(self.slider_ax,
                                          'Contrast',
                                          0,
                                          1,
                                          valinit=0.8)
     self.contrastslider.on_changed(self.slider_changed)
     self.openbutton.on_clicked(self.open_button_clicked)
     self.updatebutton.on_clicked(self.update_button_clicked)
     self.savebutton.on_clicked(self.save_button_clicked)
     self.radiobuttons = None
     self.deletemap = None
     self.show_image = None
     self.npzfilepath = None
     self.mapinfofilepath = None
     self.cid = self.fig.canvas.mpl_connect('button_press_event',
                                            self.mouseclick)
     self.contrastvalue = 0.8
     plt.show()
Exemplo n.º 23
0
def A_plot_x_from_discrete_time():
    # point 1
    x0 = 0.1
    _lambda = 1.7499 # от порядка к хаосу через перемежаемость 1.75 -> 1.7499
    k = 1000
    delta = 0
    x_array = stf.iterate(_lambda, stf.logistic_map, k, delta, x0)

    # plt.plot(x_array, '.')
    # plt.grid()
    # plt.show()
    # plt.clf()
    fig = plt.figure()
    ax = fig.gca()
    the_plot, = ax.plot(x_array, ".")
    plt.ylabel("x values")
    plt.xlabel("discrete time")
    ax.legend()
    axlambd = plt.axes([0.15, 0.01, 0.65, 0.03], facecolor="b")
    lambd_slider = wgt.Slider(axlambd, "lambda", 1.748, 1.752, valinit=1.7499, valstep=0.00001, valfmt="%1.5f")


    def update_for_slider(val):
        lambd_local = lambd_slider.val
        the_plot.set_ydata(stf.iterate(lambd_local, stf.logistic_map, k, delta, x0))
        fig.canvas.draw_idle()

    lambd_slider.on_changed(update_for_slider)

    plt.show()
    return x_array, k
Exemplo n.º 24
0
    def _create_widget_layer(self):
        """Add the `matplotlib.widget.Slider` over the UX axis and make transparent."""

        # find location of start of UX elements
        ux_start, ux_end = self.pos.x0, self.pos.x0 + self.pos.width
        pad = self._padding * (ux_end - ux_start)  # figure level coordinates

        # matplotlib slider widget layered overtop of UX axis
        self._widget_axis = self.figure.add_axes([
            self.pos.x0 + pad, self.pos.y0, self.pos.width - 2 * pad,
            self.pos.height
        ])
        self._widget_axis.patch.set_alpha(0)
        for side in 'left', 'right', 'top', 'bottom':
            self._widget_axis.spines[side].set_visible(False)

        # create slider
        self.widget = widgets.Slider(self._widget_axis,
                                     self.label,
                                     *self.bounds,
                                     valinit=self.init_value)

        # adjust formatting
        self.widget.vline.set_visible(False)
        self.widget.poly.set_edgecolor('none')
        self.widget.poly.fill = False
        self.widget.label.set_position(
            [self.widget.label.get_position()[0] - pad / 2, 0.5])
        self.widget.valtext.set_position(
            [self.widget.valtext.get_position()[0] + pad / 2, 0.5])
Exemplo n.º 25
0
def build_progress_bar(fig, lastframe, height):
    # Give us some room along the bottom
    fig.subplots_adjust(bottom=2*height)
    barax = fig.add_axes([0.08, 0.005, 0.78, height])
    bar = widgets.Slider(barax, 'Time', 0, lastframe, valinit=0,
                         valfmt='%d of '+str(lastframe))
    return bar
Exemplo n.º 26
0
 def add_param_sliders(self):
     """
     Add sliders to the figure to allow the models parameters to be set.
     """
     offset = 0.0
     self.param_sliders = dict()
     # import pdb; pdb.set_trace()
     for param_name in type(self.model).declarative_attrs:
         if self.exclude_sliders is not None and param_name in self.exclude_sliders:
             continue
         param_def = getattr(type(self.model), param_name)
         if not isinstance(param_def,
                           NArray) or not param_def.dtype == numpy.float:
             continue
         param_range = param_def.domain
         if param_range is None:
             continue
         offset += 0.035
         sax = self.ipp_fig.add_axes([0.825, 0.865 - offset, 0.125, 0.025],
                                     facecolor=AXCOLOUR)
         param_value = getattr(self.model, param_name)[0]
         self.param_sliders[param_name] = widgets.Slider(
             sax,
             param_name,
             param_range.lo,
             param_range.hi,
             valinit=param_value)
         self.param_sliders[param_name].on_changed(self.update_parameters)
Exemplo n.º 27
0
    def run(self):
        """
        Start the application for drawing.

        Will pop-up a window with a place for drawing the model (below) and a
        place with the predicted (and, optionally, observed) data (top).

        Follow the instruction on the figure title.

        When done, close the window to resume program execution.
        """
        fig = self._figure_setup()
        # Sliders to control the density and the error in the data
        self.density_slider = widgets.Slider(fig.add_axes(
            [0.10, 0.01, 0.30, 0.02]),
                                             'Density',
                                             self.density_range[0],
                                             self.density_range[1],
                                             valinit=0.,
                                             valfmt='%6.0f kg/m3')
        self.error_slider = widgets.Slider(fig.add_axes(
            [0.60, 0.01, 0.30, 0.02]),
                                           'Error',
                                           0,
                                           5,
                                           valinit=self.error,
                                           valfmt='%1.2f mGal')
        # Put instructions on figure title
        self.dataax.set_title(self.instructions)
        # Markers for mouse click events
        self._ivert = None
        self._ipoly = None
        self._lastevent = None
        self._drawing = False
        self._xy = []
        self._drawing_plot = None
        # Used to blit the model plot and make
        # rendering faster
        self.background = None
        # Connect event callbacks
        self._connect()
        self._update_data()
        self._update_data_plot()
        self.canvas.draw()
        pyplot.show()
Exemplo n.º 28
0
    def add_scaling_slider(self):
        """ Add a slider to allow scaling of the offset of time-series. """
        pos_shp = [0.75, 0.02, 0.175, 0.035]
        sax = self.its_fig.add_axes(pos_shp, facecolor=AXCOLOUR)

        self.scaling_slider = widgets.Slider(sax, "Spacing", 0.0, 1.25,
                                             valinit=self.scaling,
                                             valfmt="%4.2f")
        self.scaling_slider.on_changed(self.update_scaling)
Exemplo n.º 29
0
def show(*args):
    # Expand display_options if provided
    layers = []
    for arg in args:
        if isinstance(arg, tuple):
            layers.append((arg[0], arg[1]))
        else:
            layers.append((arg, {}))

    fig = Figure((2, 3))
    x, y, z, n = create_axes(['x', 'y', 'z', 'n'])
    mx = Mark(x, 20, {'color': 'r'})
    my = Mark(y, 20, {'color': 'g'})
    mz = Mark(z, 20, {'color': 'b'})
    mn = Mark(n, 20, {'color': 'k'})

    vx = fig.add((0, 2),
                 layers[0][0],
                 mx,
                 y,
                 z, [mn],
                 display_options=layers[0][1])
    vx.add_mark(my)
    vx.add_mark(mz)
    vy = fig.add((0, 1),
                 layers[0][0],
                 my,
                 x,
                 z, [mn],
                 display_options=layers[0][1])
    vy.add_mark(mx)
    vy.add_mark(mz)
    vz = fig.add((0, 0),
                 layers[0][0],
                 mz,
                 x,
                 y, [mn],
                 display_options=layers[0][1])
    vz.add_mark(mx)
    vz.add_mark(my)

    def update(val):
        if int(val) != mn.value:
            mn.value = int(val)
            fig.propagate_changes([mn])

    slider_ax = fig.get_subplot((1, 0), (3, 1))
    slider = widgets.Slider(slider_ax, 'n', 0, layers[0][0].shape[-1])
    slider.on_changed(update)
    """
    for data, options in layers[1:]:
        vx.add_layer(data, display_options=options)
        vy.add_layer(data, display_options=options)
        vz.add_layer(data, display_options=options)
    """
    return fig, slider
Exemplo n.º 30
0
    def __init__(self, fig, fields, vmin=None, vmax=None, color_map='inferno'):
        self.fields = fields
        self.images = {}
        self.res = 64
        self.pos = int(self.res / 2)
        self.dim = 'z'

        for idx, name, field in zip(range(len(self.fields)),
                                    self.fields.keys(), self.fields.values()):
            print(field.shape)
            ax = fig.add_axes([idx * 0.45, 0.3, 0.5, 0.5])
            im = ax.imshow(field[:, :, self.pos],
                           vmin=vmin,
                           vmax=vmax,
                           cmap=color_map,
                           interpolation='nearest')
            ax.set_title(name, fontsize=30)
            ax.set_xlim(0, self.res)
            ax.set_ylim(0, self.res)
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)
            self.images[name] = im

        # Add colorbar to last axis
        divider = make_axes_locatable(ax)
        cax = divider.append_axes('right', size='5%', pad=0.1)
        fig.colorbar(im, cax=cax, orientation='vertical')

        posax = fig.add_axes([0.2, 0.0125, 0.65, 0.03])
        self.slider_pos = wgt.Slider(posax,
                                     'Position',
                                     0,
                                     self.res - 1,
                                     valinit=int(self.res / 2))

        def slider_update(val):
            pos = int(self.slider_pos.val)
            for name, im in self.images.items():
                if self.dim == 'x':
                    im.set_data(self.fields[name][pos, :, :])
                if self.dim == 'y':
                    im.set_data(self.fields[name][:, pos, :])
                if self.dim == 'z':
                    im.set_data(self.fields[name][:, :, pos])
            fig.canvas.draw_idle()

        self.slider_pos.on_changed(slider_update)

        radax = fig.add_axes([0.075, 0.075, 0.1, 0.15])
        self.radio = wgt.RadioButtons(radax, ('x', 'y', 'z'), active=2)

        def radio_update(label):
            self.dim = label
            slider_update(self.pos)

        self.radio.on_clicked(radio_update)