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

Skip to content

Commit ee8f9d0

Browse files
committed
Create example of slider snapping to values
1 parent c0c1768 commit ee8f9d0

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)