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

Skip to content

Commit 822c3c7

Browse files
committed
Create example of slider snapping to values
1 parent 7b67892 commit 822c3c7

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

examples/widgets/slider_snap_demo.py

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

0 commit comments

Comments
 (0)