Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 51feb94

Browse files
committed
Create example of slider snapping to values
1 parent 413e851 commit 51feb94

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

examples/widgets/slider_snap_demo.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
==========================
3+
Slider Value Snapping Demo
4+
==========================
5+
6+
You can snap slider values to a discrete values using either the ``valstep``
7+
or ``valsnap`` arguments.
8+
9+
10+
In this exmaple the Freq slider is constrained to be multiples of pi, and the
11+
Amp slider uses the ``valsnap`` argument to more densely sample the first part
12+
of its range.
13+
"""
14+
import numpy as np
15+
import matplotlib.pyplot as plt
16+
from matplotlib.widgets import Slider, Button
17+
18+
fig, ax = plt.subplots()
19+
plt.subplots_adjust(bottom=0.25)
20+
t = np.arange(0.0, 1.0, 0.001)
21+
a0 = 5
22+
f0 = 3
23+
s = a0 * np.sin(2 * np.pi * f0 * t)
24+
l, = plt.plot(t, s, lw=2)
25+
26+
axcolor = 'lightgoldenrodyellow'
27+
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
28+
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
29+
30+
# define the values to use for snapping
31+
delta_f = np.pi
32+
allowed_amplitudes = np.concatenate([np.linspace(.1, 5, 100), [7, 8, 9, 10]])
33+
34+
# create the sliders
35+
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0, valsnap=allowed_amplitudes)
36+
sfreq = Slider(axfreq, 'Freq', 0, 10*np.pi, valinit=f0, valstep=np.pi)
37+
38+
39+
def update(val):
40+
amp = samp.val
41+
freq = sfreq.val
42+
l.set_ydata(amp*np.sin(2*np.pi*freq*t))
43+
fig.canvas.draw_idle()
44+
45+
46+
sfreq.on_changed(update)
47+
samp.on_changed(update)
48+
49+
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
50+
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
51+
52+
53+
def reset(event):
54+
sfreq.reset()
55+
samp.reset()
56+
button.on_clicked(reset)
57+
58+
59+
plt.show()

0 commit comments

Comments
 (0)