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

Skip to content

Commit c0c1768

Browse files
committed
allow slider to snap to an array of values
1 parent f70557f commit c0c1768

3 files changed

Lines changed: 29 additions & 4 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Sliders can now snap to arbitrary values
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
4+
The `~matplotlib.widgets.Slider` UI widget now accepts arrays for *valstep*.
5+
This generalizes the previous behavior by allowing the slider to snap to
6+
arbitrary values.

lib/matplotlib/tests/test_widgets.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,17 @@ def test_slider_valmin_valmax():
267267
assert slider.val == slider.valmax
268268

269269

270+
def test_slider_valstep_snapping():
271+
fig, ax = plt.subplots()
272+
slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
273+
valinit=11.4, valstep=1)
274+
assert slider.val == 11
275+
276+
slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
277+
valinit=11.4, valstep=[0, 1, 5.5, 19.7])
278+
assert slider.val == 5.5
279+
280+
270281
def test_slider_horizontal_vertical():
271282
fig, ax = plt.subplots()
272283
slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24,

lib/matplotlib/widgets.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from contextlib import ExitStack
1313
import copy
14-
from numbers import Integral
14+
from numbers import Integral, Number
1515

1616
import numpy as np
1717

@@ -295,8 +295,9 @@ def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt=None,
295295
dragging : bool, default: True
296296
If True the slider can be dragged by the mouse.
297297
298-
valstep : float, default: None
299-
If given, the slider will snap to multiples of *valstep*.
298+
valstep : float or arraylike, default: None
299+
If a float, the slider will snap to multiples of *valstep*.
300+
If an array the slider will snap to the values in the array.
300301
301302
orientation : {'horizontal', 'vertical'}, default: 'horizontal'
302303
The orientation of the slider.
@@ -401,9 +402,16 @@ def observers(self):
401402

402403
def _value_in_bounds(self, val):
403404
"""Makes sure *val* is with given bounds."""
404-
if self.valstep:
405+
if isinstance(self.valstep, Number):
405406
val = (self.valmin
406407
+ round((val - self.valmin) / self.valstep) * self.valstep)
408+
elif self.valstep is not None:
409+
valstep = np.asanyarray(self.valstep)
410+
if valstep.ndim != 1:
411+
raise ValueError(
412+
f"valstep must have 1 dimension but has {valstep.ndim}"
413+
)
414+
val = valstep[np.argmin(np.abs(valstep - val))]
407415

408416
if val <= self.valmin:
409417
if not self.closedmin:

0 commit comments

Comments
 (0)