Python matplotlib.widgets.Slider() Examples

The following are 22 code examples of matplotlib.widgets.Slider(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.widgets , or try the search function .
Example #1
Source File: mpl.py    From spotpy with MIT License 6 votes vote down vote up
def __init__(self, rect, wtype, *args, **kwargs):
        """
        Creates a matplotlib.widgets widget
        :param rect: The rectangle of the position [left, bottom, width, height] in relative figure coordinates
        :param wtype: A type from matplotlib.widgets, eg. Button, Slider, TextBox, RadioButtons
        :param args: Positional arguments passed to the widget
        :param kwargs: Keyword arguments passed to the widget and events used for the widget
                       eg. if wtype is Slider, on_changed=f can be used as keyword argument

        """
        self.ax = plt.axes(rect)
        events = {}
        for k in list(kwargs.keys()):
            if k.startswith('on_'):
                events[k] = kwargs.pop(k)
        self.object = wtype(self.ax, *args, **kwargs)
        for k in events:
            if hasattr(self.object, k):
                getattr(self.object, k)(events[k]) 
Example #2
Source File: mpl.py    From spotpy with MIT License 6 votes vote down vote up
def _make_widgets(self):
        """
        Creates the sliders
        :return:
        """
        if hasattr(self, 'sliders'):
            for s in self.sliders:
                s.ax.remove()

        sliders = []
        step = max(0.005, min(0.05, 0.8/len(self.parameter_array)))
        for i, row in enumerate(self.parameter_array):
            rect = [0.75, 0.9 - step * i, 0.2, step - 0.005]
            s = Widget(rect, Slider, row['name'], row['minbound'], row['maxbound'],
                       valinit=row['optguess'], on_changed=ValueChanger(row['name'], self.parameter_values))
            sliders.append(s)
        plt.draw()
        return sliders 
Example #3
Source File: circuit.py    From resonator_tools with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self,porttype):
		self.porttype = porttype
		self.results = []
	
#def GUIfit(porttype,f_data,z_data_raw):
#	'''
#	GUI based fitting process enabeling cutting the data and manually setting the delay
#	It employs the Matplotlib widgets
#	return f1, f2 and delay, which should be employed for the real fitting
#	'''
#	if porttype=='direct':
#		p = reflection_port(f_data=f_data,z_data_raw=z_data_raw)
#	elif porttype =='notch':
#		p = notch_port(f_data=f_data,z_data_raw=z_data_raw)
#	else:
#		warnings.warn('Not supported!')
#		return None
#	import matplotlib.pyplot as plt
#	from matplotlib.widgets import Slider, Button, RadioButtons
#	#plt.style.use('ggplot')
#	fig, axes = plt.subplots(nrows=2,ncols=2)
#	
#	return f1,f2,delay 
Example #4
Source File: pyheat.py    From pyheat with MIT License 6 votes vote down vote up
def show_heatmap(self, blocking=True, output_file=None, enable_scroll=False):
        """Method to actually display the heatmap created.

            @param blocking: When set to False makes an unblocking plot show.
            @param output_file: If not None the heatmap image is output to this
            file. Supported formats: (eps, pdf, pgf, png, ps, raw, rgba, svg,
            svgz)
            @param enable_scroll: Flag used add a scroll bar to scroll long files.
        """
        if output_file is None:
            if enable_scroll:
                # Add a new axes which will be used as scroll bar.
                axpos = plt.axes([0.12, 0.1, 0.625, 0.03])
                spos = Slider(axpos, "Scroll", 10, len(self.pyfile.lines))

                def update(val):
                    """Method to update position when slider is moved."""
                    pos = spos.val
                    self.ax.axis([0, 1, pos, pos - 10])
                    self.fig.canvas.draw_idle()

                spos.on_changed(update)
            plt.show(block=blocking)
        else:
            plt.savefig(output_file) 
Example #5
Source File: plot2d.py    From kite with GNU General Public License v3.0 5 votes vote down vote up
def interactive(self):
        """Simple interactive quadtree plot with matplot

        This is a relictic function
        """
        from matplotlib.widgets import Slider
        self._initImagePlot()

        def change_epsilon(e):
            self._quadtree.epsilon = e

        def close_figure(*args):
            self._quadtree.evChanged.unsubscribe(self._update)

        self.ax.set_position([0.05, 0.15, 0.90, 0.8])
        ax_eps = self.fig.add_axes([0.05, 0.1, 0.90, 0.03])

        self.data = self._quadtree.leaf_matrix_means
        self.title = 'Quadtree Means - Interactive'

        self._addInfoText()

        epsilon = Slider(ax_eps, 'Epsilon',
                         self._quadtree.epsilon - 1.*self._quadtree.epsilon,
                         self._quadtree.epsilon + 1.*self._quadtree.epsilon,
                         valinit=self._quadtree.epsilon, valfmt='%1.3f')

        # Catch events
        epsilon.on_changed(change_epsilon)
        self._quadtree.evChanged.subscribe(self._update)
        self.fig.canvas.mpl_connect('close_event', close_figure)

        plt.show() 
Example #6
Source File: test_widgets.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
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 
Example #7
Source File: test_widgets.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
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 
Example #8
Source File: test_widgets.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
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) 
Example #9
Source File: calibration.py    From resonator_tools with GNU General Public License v2.0 5 votes vote down vote up
def GUIbaselinefit(self):
		'''
		A GUI to help you fit the baseline
		'''
		self.__lam = 1e6
		self.__p = 0.9
		niter = 10
		self.__baseline = self._baseline_als(np.absolute(self.z_data_raw),self.__lam,self.__p,niter=niter)
		import matplotlib.pyplot as plt
		from matplotlib.widgets import Slider
		fig, (ax0,ax1) = plt.subplots(nrows=2)
		plt.suptitle('Use the sliders to make the green curve match the baseline.')
		plt.subplots_adjust(left=0.25, bottom=0.25)
		l0, = ax0.plot(np.absolute(self.z_data_raw))
		l0b, = ax0.plot(np.absolute(self.__baseline))
		l1, = ax1.plot(np.absolute(self.z_data_raw/self.__baseline))
		ax0.set_ylabel('amp, rawdata vs. baseline')
		ax1.set_ylabel('amp, corrected')
		axcolor = 'lightgoldenrodyellow'
		axSmooth = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
		axAsym = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
		axbcorr = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
		sSmooth = Slider(axSmooth, 'Smoothness', 0.1, 10., valinit=np.log10(self.__lam),valfmt='1E%f')
		sAsym = Slider(axAsym, 'Asymmetry', 1e-4,0.99999, valinit=self.__p,valfmt='%f')
		sbcorr = Slider(axbcorr, 'vertical shift',0.7,1.1,valinit=1.)
		def update(val):
			self.__lam = 10**sSmooth.val
			self.__p = sAsym.val
			self.__baseline = sbcorr.val*self._baseline_als(np.absolute(self.z_data_raw),self.__lam,self.__p,niter=niter)
			l0.set_ydata(np.absolute(self.z_data_raw))
			l0b.set_ydata(np.absolute(self.__baseline))
			l1.set_ydata(np.absolute(self.z_data_raw/self.__baseline))
			fig.canvas.draw_idle()
		sSmooth.on_changed(update)
		sAsym.on_changed(update)
		sbcorr.on_changed(update)
		plt.show()
		self.z_data_raw /= self.__baseline
		plt.close() 
Example #10
Source File: test_widgets.py    From coffeegrindsize with MIT License 5 votes vote down vote up
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 
Example #11
Source File: test_widgets.py    From coffeegrindsize with MIT License 5 votes vote down vote up
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 
Example #12
Source File: test_widgets.py    From coffeegrindsize with MIT License 5 votes vote down vote up
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) 
Example #13
Source File: energyplus_model.py    From rl-testbed-for-energyplus with MIT License 5 votes vote down vote up
def plot_progress(self):
        # Redraw all lines
        self.axprogress.lines = []
        self.axprogress.plot(self.reward, color='#1f77b4', label='Reward')
        #self.axprogress.plot(self.reward_mean, color='#ff7f0e', label='Reward (average)')
        self.axprogress.legend()
        # Redraw slider
        if self.sl_episode is None or int(round(self.sl_episode.val)) == self.num_episodes - 2:
            cur_ep = self.num_episodes - 1
        else:
            cur_ep = int(round(self.sl_episode.val))
        self.axslider.clear()
        #self.sl_episode = Slider(self.axslider, 'Episode (0..{})'.format(self.num_episodes - 1), 0, self.num_episodes - 1, valinit=self.num_episodes - 1, valfmt='%6.0f')
        self.sl_episode = Slider(self.axslider, 'Episode (0..{})'.format(self.num_episodes - 1), 0, self.num_episodes - 1, valinit=cur_ep, valfmt='%6.0f')
        self.sl_episode.on_changed(self.set_episode_num) 
Example #14
Source File: freesurfer.py    From visualqc with Apache License 2.0 5 votes vote down vote up
def add_alpha_slider(self):
        """Controls the transparency level of overlay"""

        # alpha slider
        ax_slider = plt.axes(cfg.position_slider_seg_alpha,
                             facecolor=cfg.color_slider_axis)
        self.slider = Slider(ax_slider, label='transparency',
                             valmin=0.0, valmax=1.0, valinit=0.7, valfmt='%1.2f')
        self.slider.label.set_position((0.99, 1.5))
        self.slider.on_changed(self.set_alpha_value) 
Example #15
Source File: gui_viewer.py    From image-segmentation with MIT License 5 votes vote down vote up
def create_slider(self):
        self.axcolor = 'lightgoldenrodyellow'
        ax_slider = plt.axes([0.2, 0.1, 0.65, 0.03], facecolor=self.axcolor)
        self.slider = Slider(ax_slider, 'Id', 0, self.num_images - 1, valinit=0)
        self.slider.on_changed(self.slider_callback) 
Example #16
Source File: test_widgets.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #17
Source File: test_widgets.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #18
Source File: test_widgets.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #19
Source File: energyplus_model.py    From rl-testbed-for-energyplus with MIT License 4 votes vote down vote up
def show_progress(self):
        self.monitor_file = self.log_dir + '/monitor.csv'

        # Read progress file
        if not self.read_monitor_file():
            print('Progress data is missing')
            sys.exit(1)

        # Initialize graph
        plt.rcdefaults()
        plt.rcParams['font.size'] = 6
        plt.rcParams['lines.linewidth'] = 1.0
        plt.rcParams['legend.loc'] = 'lower right'

        self.fig = plt.figure(1, figsize=(16, 10))

        # Show widgets
        axcolor = 'lightgoldenrodyellow'
        self.axprogress = self.fig.add_axes([0.15, 0.10, 0.70, 0.15], facecolor=axcolor)
        self.axslider = self.fig.add_axes([0.15, 0.04, 0.70, 0.02], facecolor=axcolor)
        axfirst = self.fig.add_axes([0.15, 0.01, 0.03, 0.02])
        axlast = self.fig.add_axes([0.82, 0.01, 0.03, 0.02])
        axprev = self.fig.add_axes([0.46, 0.01, 0.03, 0.02])
        axnext = self.fig.add_axes([0.51, 0.01, 0.03, 0.02])

        # Slider is drawn in plot_progress()

        # First/Last button
        self.button_first = Button(axfirst, 'First', color=axcolor, hovercolor='0.975')
        self.button_first.on_clicked(self.first_episode_num)
        self.button_last = Button(axlast, 'Last', color=axcolor, hovercolor='0.975')
        self.button_last.on_clicked(self.last_episode_num)

        # Next/Prev button
        self.button_prev = Button(axprev, 'Prev', color=axcolor, hovercolor='0.975')
        self.button_prev.on_clicked(self.prev_episode_num)
        self.button_next = Button(axnext, 'Next', color=axcolor, hovercolor='0.975')
        self.button_next.on_clicked(self.next_episode_num)

        # Timer
        self.timer = self.fig.canvas.new_timer(interval=1000)
        self.timer.add_callback(self.check_update)
        self.timer.start()

        # Progress data
        self.axprogress.set_xmargin(0)
        self.axprogress.set_xlabel('Episodes')
        self.axprogress.set_ylabel('Reward')
        self.axprogress.grid(True)
        self.plot_progress()

        # Plot latest episode
        self.update_episode(self.num_episodes - 1)

        plt.show() 
Example #20
Source File: ndshow.py    From polex with MIT License 4 votes vote down vote up
def matshow(data, matnames=[], dimnames=[]):
    if not isinstance(data, list):
        data = [data]

    for i in range(len(data)):
        if type(data[i]) is torch.Tensor:
            data[i] = data[i].numpy()

    ndim = max([d.ndim for d in data])

    for i in range(len(data)):
        while data[i].ndim < ndim:
            data[i] = np.expand_dims(data[i], axis=0)

    shape = []
    for dim in range(ndim - 2):
        shape.append(max(d.shape[dim] for d in data))

    figure, axes = plt.subplots(
        1, len(data), sharex=True, sharey=True, squeeze=False)

    for i in range(len(data)):
        axes[0,i].imshow(_take(data[i], [0] * (ndim-2)), 
            vmin=np.amin(data[i]), vmax=np.amax(data[i]),
            interpolation=None, origin='lower',
            extent=[0.0, data[i].shape[-1], 0.0, data[i].shape[-2]])

    for i in range(min(len(data), len(matnames))):
        axes[0,i].set_title(matnames[i])

    sliders = []
    updatefuncs = []
    bottom = np.linspace(0.0, 0.1, ndim)[1:-1]
    for i in range(len(shape)):
        sliderax = plt.axes([0.2, bottom[i], 0.6, 0.02], 
            facecolor='lightgoldenrodyellow')

        if i < len(dimnames):
            label = dimnames[i]
        else:
            label = 'Axis {}'.format(i)
        sliders.append(Slider(sliderax, label=label, 
            valmin=0, valmax=shape[i]-1, valinit=0, valstep=1))

        def update(val):
            indices = [int(slider.val) for slider in sliders]
            for j in range(axes.size):
                axes[0,j].images[0].set_array(_take(data[j], indices))
            figure.canvas.draw_idle()
        updatefuncs.append(update)

        sliders[i].on_changed(updatefuncs[i])

    plt.show() 
Example #21
Source File: animation.py    From animatplot with MIT License 4 votes vote down vote up
def timeline_slider(self, text='Time', ax=None, valfmt=None, color=None):
        """Creates a timeline slider.

        Parameters
        ----------
        text : str, optional
            The text to display for the slider. Defaults to 'Time'
        ax : matplotlib.axes.Axes, optional
            The matplotlib axes to attach the slider to.
        valfmt : str, optional
            a format specifier used to print the time
            Defaults to '%s' for datetime64, timedelta64 and '%1.2f' otherwise.
        color :
            The color of the slider.
        """
        if ax is None:
            adjust_plot = {'bottom': .2}
            rect = [.18, .05, .5, .03]

            plt.subplots_adjust(**adjust_plot)
            self.slider_ax = plt.axes(rect)
        else:
            self.slider_ax = ax

        if valfmt is None:
            if (np.issubdtype(self.timeline.t.dtype, np.datetime64)
               or np.issubdtype(self.timeline.t.dtype, np.timedelta64)):
                valfmt = '%s'
            else:
                valfmt = '%1.2f'

        if self.timeline.log:
            valfmt = '$10^{%s}$' % valfmt

        self.slider = Slider(
            self.slider_ax, text, 0, self.timeline._len-1,
            valinit=0,
            valfmt=(valfmt+self.timeline.units),
            valstep=1, color=color
        )
        self._has_slider = True

        def set_time(t):
            self.timeline.index = int(self.slider.val)
            self.slider.valtext.set_text(
                self.slider.valfmt % (self.timeline[self.timeline.index]))
            if self._pause:
                for block in self.blocks:
                    block._update(self.timeline.index)
                self.fig.canvas.draw()
        self.slider.on_changed(set_time) 
Example #22
Source File: offset_ui_tool.py    From TGC-Designer-Tools with Apache License 2.0 4 votes vote down vote up
def getManualRegistrationError(visual, heightmap, image_scale, pc):
    upper_left_enu = pc.ulENU()
    lower_right_enu = pc.lrENU()
    upper_left_latlon = pc.enuToLatLon(*upper_left_enu)
    lower_right_latlon = pc.enuToLatLon(*lower_right_enu)
    # Order is South, West, North, East
    result = OSMTGC.getOSMData(lower_right_latlon[0], upper_left_latlon[1], upper_left_latlon[0], lower_right_latlon[1])

    # TODO Scale, Sharpen, and Increase Local Constrast for these images to get potentially easier results?
    image_dict = {}
    image_dict["Visible"] = visual
    image_dict["Visible Golf"] = None
    image_dict["Heightmap"] = heightmap
    image_dict["Heightmap Golf"] = None

    fig, ax = plt.subplots()
    plt.title('Move Slider and Press Apply.  Close Window When Happy With Alignment')

    axcolor = 'green'
    plt.subplots_adjust(left=0.3, bottom=0.25)

    axx = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
    axy = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    sx = Slider(axx, 'West/East', -10.0, 10.0, valinit=0.0)
    sy = Slider(axy, 'South/North', -10.0, 10.0, valinit=0.0)

    applyax = plt.axes([0.8, 0.025, 0.1, 0.04])
    button = Button(applyax, 'Apply', color=axcolor, hovercolor='0.975')

    rax = plt.axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor)
    radio = RadioButtons(rax, image_dict.keys())
    update_image = partial(drawNewImage, ax, image_dict)
    radio.on_clicked(update_image)

    new_offset = partial(drawNewLocation, ax, image_dict, result, image_scale, radio, sx, sy, 1)
    button.on_clicked(new_offset)

    drawNewLocation(ax, image_dict, result, image_scale, radio, None, None, None, None)

    plt.show()

    return (sx.val, sy.val)