/
widgets.py
4248 lines (3572 loc) · 152 KB
/
widgets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
GUI neutral widgets
===================
Widgets that are designed to work for any of the GUI backends.
All of these widgets require you to predefine an `~.axes.Axes`
instance and pass that as the first parameter. Matplotlib doesn't try to
be too smart with respect to layout -- you will have to figure out how
wide and tall you want your Axes to be to accommodate your widget.
"""
from contextlib import ExitStack
import copy
import itertools
from numbers import Integral, Number
from cycler import cycler
import numpy as np
import matplotlib as mpl
from . import (_api, _docstring, backend_tools, cbook, collections, colors,
text as mtext, ticker, transforms)
from .lines import Line2D
from .patches import Circle, Rectangle, Ellipse, Polygon
from .transforms import TransformedPatchPath, Affine2D
class LockDraw:
"""
Some widgets, like the cursor, draw onto the canvas, and this is not
desirable under all circumstances, like when the toolbar is in zoom-to-rect
mode and drawing a rectangle. To avoid this, a widget can acquire a
canvas' lock with ``canvas.widgetlock(widget)`` before drawing on the
canvas; this will prevent other widgets from doing so at the same time (if
they also try to acquire the lock first).
"""
def __init__(self):
self._owner = None
def __call__(self, o):
"""Reserve the lock for *o*."""
if not self.available(o):
raise ValueError('already locked')
self._owner = o
def release(self, o):
"""Release the lock from *o*."""
if not self.available(o):
raise ValueError('you do not own this lock')
self._owner = None
def available(self, o):
"""Return whether drawing is available to *o*."""
return not self.locked() or self.isowner(o)
def isowner(self, o):
"""Return whether *o* owns this lock."""
return self._owner is o
def locked(self):
"""Return whether the lock is currently held by an owner."""
return self._owner is not None
class Widget:
"""
Abstract base class for GUI neutral widgets.
"""
drawon = True
eventson = True
_active = True
def set_active(self, active):
"""Set whether the widget is active."""
self._active = active
def get_active(self):
"""Get whether the widget is active."""
return self._active
# set_active is overridden by SelectorWidgets.
active = property(get_active, set_active, doc="Is the widget active?")
def ignore(self, event):
"""
Return whether *event* should be ignored.
This method should be called at the beginning of any event callback.
"""
return not self.active
def _changed_canvas(self):
"""
Someone has switched the canvas on us!
This happens if `savefig` needs to save to a format the previous
backend did not support (e.g. saving a figure using an Agg based
backend saved to a vector format).
Returns
-------
bool
True if the canvas has been changed.
"""
return self.canvas is not self.ax.figure.canvas
class AxesWidget(Widget):
"""
Widget connected to a single `~matplotlib.axes.Axes`.
To guarantee that the widget remains responsive and not garbage-collected,
a reference to the object should be maintained by the user.
This is necessary because the callback registry
maintains only weak-refs to the functions, which are member
functions of the widget. If there are no references to the widget
object it may be garbage collected which will disconnect the callbacks.
Attributes
----------
ax : `~matplotlib.axes.Axes`
The parent Axes for the widget.
canvas : `~matplotlib.backend_bases.FigureCanvasBase`
The parent figure canvas for the widget.
active : bool
If False, the widget does not respond to events.
"""
def __init__(self, ax):
self.ax = ax
self.canvas = ax.figure.canvas
self._cids = []
def connect_event(self, event, callback):
"""
Connect a callback function with an event.
This should be used in lieu of ``figure.canvas.mpl_connect`` since this
function stores callback ids for later clean up.
"""
cid = self.canvas.mpl_connect(event, callback)
self._cids.append(cid)
def disconnect_events(self):
"""Disconnect all events created by this widget."""
for c in self._cids:
self.canvas.mpl_disconnect(c)
def _get_data_coords(self, event):
"""Return *event*'s data coordinates in this widget's Axes."""
# This method handles the possibility that event.inaxes != self.ax (which may
# occur if multiple axes are overlaid), in which case event.xdata/.ydata will
# be wrong. Note that we still special-case the common case where
# event.inaxes == self.ax and avoid re-running the inverse data transform,
# because that can introduce floating point errors for synthetic events.
return ((event.xdata, event.ydata) if event.inaxes is self.ax
else self.ax.transData.inverted().transform((event.x, event.y)))
class Button(AxesWidget):
"""
A GUI neutral button.
For the button to remain responsive you must keep a reference to it.
Call `.on_clicked` to connect to the button.
Attributes
----------
ax
The `~.axes.Axes` the button renders into.
label
A `.Text` instance.
color
The color of the button when not hovering.
hovercolor
The color of the button when hovering.
"""
def __init__(self, ax, label, image=None,
color='0.85', hovercolor='0.95', *, useblit=True):
"""
Parameters
----------
ax : `~matplotlib.axes.Axes`
The `~.axes.Axes` instance the button will be placed into.
label : str
The button text.
image : array-like or PIL Image
The image to place in the button, if not *None*. The parameter is
directly forwarded to `~.axes.Axes.imshow`.
color : color
The color of the button when not activated.
hovercolor : color
The color of the button when the mouse is over it.
useblit : bool, default: True
Use blitting for faster drawing if supported by the backend.
See the tutorial :ref:`blitting` for details.
.. versionadded:: 3.7
"""
super().__init__(ax)
if image is not None:
ax.imshow(image)
self.label = ax.text(0.5, 0.5, label,
verticalalignment='center',
horizontalalignment='center',
transform=ax.transAxes)
self._useblit = useblit and self.canvas.supports_blit
self._observers = cbook.CallbackRegistry(signals=["clicked"])
self.connect_event('button_press_event', self._click)
self.connect_event('button_release_event', self._release)
self.connect_event('motion_notify_event', self._motion)
ax.set_navigate(False)
ax.set_facecolor(color)
ax.set_xticks([])
ax.set_yticks([])
self.color = color
self.hovercolor = hovercolor
def _click(self, event):
if not self.eventson or self.ignore(event) or not self.ax.contains(event)[0]:
return
if event.canvas.mouse_grabber != self.ax:
event.canvas.grab_mouse(self.ax)
def _release(self, event):
if self.ignore(event) or event.canvas.mouse_grabber != self.ax:
return
event.canvas.release_mouse(self.ax)
if self.eventson and self.ax.contains(event)[0]:
self._observers.process('clicked', event)
def _motion(self, event):
if self.ignore(event):
return
c = self.hovercolor if self.ax.contains(event)[0] else self.color
if not colors.same_color(c, self.ax.get_facecolor()):
self.ax.set_facecolor(c)
if self.drawon:
if self._useblit:
self.ax.draw_artist(self.ax)
self.canvas.blit(self.ax.bbox)
else:
self.canvas.draw()
def on_clicked(self, func):
"""
Connect the callback function *func* to button click events.
Returns a connection id, which can be used to disconnect the callback.
"""
return self._observers.connect('clicked', lambda event: func(event))
def disconnect(self, cid):
"""Remove the callback function with connection id *cid*."""
self._observers.disconnect(cid)
class SliderBase(AxesWidget):
"""
The base class for constructing Slider widgets. Not intended for direct
usage.
For the slider to remain responsive you must maintain a reference to it.
"""
def __init__(self, ax, orientation, closedmin, closedmax,
valmin, valmax, valfmt, dragging, valstep):
if ax.name == '3d':
raise ValueError('Sliders cannot be added to 3D Axes')
super().__init__(ax)
_api.check_in_list(['horizontal', 'vertical'], orientation=orientation)
self.orientation = orientation
self.closedmin = closedmin
self.closedmax = closedmax
self.valmin = valmin
self.valmax = valmax
self.valstep = valstep
self.drag_active = False
self.valfmt = valfmt
if orientation == "vertical":
ax.set_ylim((valmin, valmax))
axis = ax.yaxis
else:
ax.set_xlim((valmin, valmax))
axis = ax.xaxis
self._fmt = axis.get_major_formatter()
if not isinstance(self._fmt, ticker.ScalarFormatter):
self._fmt = ticker.ScalarFormatter()
self._fmt.set_axis(axis)
self._fmt.set_useOffset(False) # No additive offset.
self._fmt.set_useMathText(True) # x sign before multiplicative offset.
ax.set_axis_off()
ax.set_navigate(False)
self.connect_event("button_press_event", self._update)
self.connect_event("button_release_event", self._update)
if dragging:
self.connect_event("motion_notify_event", self._update)
self._observers = cbook.CallbackRegistry(signals=["changed"])
def _stepped_value(self, val):
"""Return *val* coerced to closest number in the ``valstep`` grid."""
if isinstance(self.valstep, Number):
val = (self.valmin
+ round((val - self.valmin) / self.valstep) * self.valstep)
elif self.valstep is not None:
valstep = np.asanyarray(self.valstep)
if valstep.ndim != 1:
raise ValueError(
f"valstep must have 1 dimension but has {valstep.ndim}"
)
val = valstep[np.argmin(np.abs(valstep - val))]
return val
def disconnect(self, cid):
"""
Remove the observer with connection id *cid*.
Parameters
----------
cid : int
Connection id of the observer to be removed.
"""
self._observers.disconnect(cid)
def reset(self):
"""Reset the slider to the initial value."""
if np.any(self.val != self.valinit):
self.set_val(self.valinit)
class Slider(SliderBase):
"""
A slider representing a floating point range.
Create a slider from *valmin* to *valmax* in Axes *ax*. For the slider to
remain responsive you must maintain a reference to it. Call
:meth:`on_changed` to connect to the slider event.
Attributes
----------
val : float
Slider value.
"""
@_api.make_keyword_only("3.7", name="valinit")
def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt=None,
closedmin=True, closedmax=True, slidermin=None,
slidermax=None, dragging=True, valstep=None,
orientation='horizontal', *, initcolor='r',
track_color='lightgrey', handle_style=None, **kwargs):
"""
Parameters
----------
ax : Axes
The Axes to put the slider in.
label : str
Slider label.
valmin : float
The minimum value of the slider.
valmax : float
The maximum value of the slider.
valinit : float, default: 0.5
The slider initial position.
valfmt : str, default: None
%-format string used to format the slider value. If None, a
`.ScalarFormatter` is used instead.
closedmin : bool, default: True
Whether the slider interval is closed on the bottom.
closedmax : bool, default: True
Whether the slider interval is closed on the top.
slidermin : Slider, default: None
Do not allow the current slider to have a value less than
the value of the Slider *slidermin*.
slidermax : Slider, default: None
Do not allow the current slider to have a value greater than
the value of the Slider *slidermax*.
dragging : bool, default: True
If True the slider can be dragged by the mouse.
valstep : float or array-like, default: None
If a float, the slider will snap to multiples of *valstep*.
If an array the slider will snap to the values in the array.
orientation : {'horizontal', 'vertical'}, default: 'horizontal'
The orientation of the slider.
initcolor : color, default: 'r'
The color of the line at the *valinit* position. Set to ``'none'``
for no line.
track_color : color, default: 'lightgrey'
The color of the background track. The track is accessible for
further styling via the *track* attribute.
handle_style : dict
Properties of the slider handle. Default values are
========= ===== ======= ========================================
Key Value Default Description
========= ===== ======= ========================================
facecolor color 'white' The facecolor of the slider handle.
edgecolor color '.75' The edgecolor of the slider handle.
size int 10 The size of the slider handle in points.
========= ===== ======= ========================================
Other values will be transformed as marker{foo} and passed to the
`~.Line2D` constructor. e.g. ``handle_style = {'style'='x'}`` will
result in ``markerstyle = 'x'``.
Notes
-----
Additional kwargs are passed on to ``self.poly`` which is the
`~matplotlib.patches.Polygon` that draws the slider knob. See the
`.Polygon` documentation for valid property names (``facecolor``,
``edgecolor``, ``alpha``, etc.).
"""
super().__init__(ax, orientation, closedmin, closedmax,
valmin, valmax, valfmt, dragging, valstep)
if slidermin is not None and not hasattr(slidermin, 'val'):
raise ValueError(
f"Argument slidermin ({type(slidermin)}) has no 'val'")
if slidermax is not None and not hasattr(slidermax, 'val'):
raise ValueError(
f"Argument slidermax ({type(slidermax)}) has no 'val'")
self.slidermin = slidermin
self.slidermax = slidermax
valinit = self._value_in_bounds(valinit)
if valinit is None:
valinit = valmin
self.val = valinit
self.valinit = valinit
defaults = {'facecolor': 'white', 'edgecolor': '.75', 'size': 10}
handle_style = {} if handle_style is None else handle_style
marker_props = {
f'marker{k}': v for k, v in {**defaults, **handle_style}.items()
}
if orientation == 'vertical':
self.track = Rectangle(
(.25, 0), .5, 1,
transform=ax.transAxes,
facecolor=track_color
)
ax.add_patch(self.track)
self.poly = ax.axhspan(valmin, valinit, .25, .75, **kwargs)
# Drawing a longer line and clipping it to the track avoids
# pixelation-related asymmetries.
self.hline = ax.axhline(valinit, 0, 1, color=initcolor, lw=1,
clip_path=TransformedPatchPath(self.track))
handleXY = [[0.5], [valinit]]
else:
self.track = Rectangle(
(0, .25), 1, .5,
transform=ax.transAxes,
facecolor=track_color
)
ax.add_patch(self.track)
self.poly = ax.axvspan(valmin, valinit, .25, .75, **kwargs)
self.vline = ax.axvline(valinit, 0, 1, color=initcolor, lw=1,
clip_path=TransformedPatchPath(self.track))
handleXY = [[valinit], [0.5]]
self._handle, = ax.plot(
*handleXY,
"o",
**marker_props,
clip_on=False
)
if orientation == 'vertical':
self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes,
verticalalignment='bottom',
horizontalalignment='center')
self.valtext = ax.text(0.5, -0.02, self._format(valinit),
transform=ax.transAxes,
verticalalignment='top',
horizontalalignment='center')
else:
self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes,
verticalalignment='center',
horizontalalignment='right')
self.valtext = ax.text(1.02, 0.5, self._format(valinit),
transform=ax.transAxes,
verticalalignment='center',
horizontalalignment='left')
self.set_val(valinit)
def _value_in_bounds(self, val):
"""Makes sure *val* is with given bounds."""
val = self._stepped_value(val)
if val <= self.valmin:
if not self.closedmin:
return
val = self.valmin
elif val >= self.valmax:
if not self.closedmax:
return
val = self.valmax
if self.slidermin is not None and val <= self.slidermin.val:
if not self.closedmin:
return
val = self.slidermin.val
if self.slidermax is not None and val >= self.slidermax.val:
if not self.closedmax:
return
val = self.slidermax.val
return val
def _update(self, event):
"""Update the slider position."""
if self.ignore(event) or event.button != 1:
return
if event.name == 'button_press_event' and self.ax.contains(event)[0]:
self.drag_active = True
event.canvas.grab_mouse(self.ax)
if not self.drag_active:
return
if (event.name == 'button_release_event'
or event.name == 'button_press_event' and not self.ax.contains(event)[0]):
self.drag_active = False
event.canvas.release_mouse(self.ax)
return
xdata, ydata = self._get_data_coords(event)
val = self._value_in_bounds(
xdata if self.orientation == 'horizontal' else ydata)
if val not in [None, self.val]:
self.set_val(val)
def _format(self, val):
"""Pretty-print *val*."""
if self.valfmt is not None:
return self.valfmt % val
else:
_, s, _ = self._fmt.format_ticks([self.valmin, val, self.valmax])
# fmt.get_offset is actually the multiplicative factor, if any.
return s + self._fmt.get_offset()
def set_val(self, val):
"""
Set slider value to *val*.
Parameters
----------
val : float
"""
xy = self.poly.xy
if self.orientation == 'vertical':
xy[1] = .25, val
xy[2] = .75, val
self._handle.set_ydata([val])
else:
xy[2] = val, .75
xy[3] = val, .25
self._handle.set_xdata([val])
self.poly.xy = xy
self.valtext.set_text(self._format(val))
if self.drawon:
self.ax.figure.canvas.draw_idle()
self.val = val
if self.eventson:
self._observers.process('changed', val)
def on_changed(self, func):
"""
Connect *func* as callback function to changes of the slider value.
Parameters
----------
func : callable
Function to call when slider is changed.
The function must accept a single float as its arguments.
Returns
-------
int
Connection id (which can be used to disconnect *func*).
"""
return self._observers.connect('changed', lambda val: func(val))
class RangeSlider(SliderBase):
"""
A slider representing a range of floating point values. Defines the min and
max of the range via the *val* attribute as a tuple of (min, max).
Create a slider that defines a range contained within [*valmin*, *valmax*]
in Axes *ax*. For the slider to remain responsive you must maintain a
reference to it. Call :meth:`on_changed` to connect to the slider event.
Attributes
----------
val : tuple of float
Slider value.
"""
@_api.make_keyword_only("3.7", name="valinit")
def __init__(
self,
ax,
label,
valmin,
valmax,
valinit=None,
valfmt=None,
closedmin=True,
closedmax=True,
dragging=True,
valstep=None,
orientation="horizontal",
track_color='lightgrey',
handle_style=None,
**kwargs,
):
"""
Parameters
----------
ax : Axes
The Axes to put the slider in.
label : str
Slider label.
valmin : float
The minimum value of the slider.
valmax : float
The maximum value of the slider.
valinit : tuple of float or None, default: None
The initial positions of the slider. If None the initial positions
will be at the 25th and 75th percentiles of the range.
valfmt : str, default: None
%-format string used to format the slider values. If None, a
`.ScalarFormatter` is used instead.
closedmin : bool, default: True
Whether the slider interval is closed on the bottom.
closedmax : bool, default: True
Whether the slider interval is closed on the top.
dragging : bool, default: True
If True the slider can be dragged by the mouse.
valstep : float, default: None
If given, the slider will snap to multiples of *valstep*.
orientation : {'horizontal', 'vertical'}, default: 'horizontal'
The orientation of the slider.
track_color : color, default: 'lightgrey'
The color of the background track. The track is accessible for
further styling via the *track* attribute.
handle_style : dict
Properties of the slider handles. Default values are
========= ===== ======= =========================================
Key Value Default Description
========= ===== ======= =========================================
facecolor color 'white' The facecolor of the slider handles.
edgecolor color '.75' The edgecolor of the slider handles.
size int 10 The size of the slider handles in points.
========= ===== ======= =========================================
Other values will be transformed as marker{foo} and passed to the
`~.Line2D` constructor. e.g. ``handle_style = {'style'='x'}`` will
result in ``markerstyle = 'x'``.
Notes
-----
Additional kwargs are passed on to ``self.poly`` which is the
`~matplotlib.patches.Polygon` that draws the slider knob. See the
`.Polygon` documentation for valid property names (``facecolor``,
``edgecolor``, ``alpha``, etc.).
"""
super().__init__(ax, orientation, closedmin, closedmax,
valmin, valmax, valfmt, dragging, valstep)
# Set a value to allow _value_in_bounds() to work.
self.val = (valmin, valmax)
if valinit is None:
# Place at the 25th and 75th percentiles
extent = valmax - valmin
valinit = np.array([valmin + extent * 0.25,
valmin + extent * 0.75])
else:
valinit = self._value_in_bounds(valinit)
self.val = valinit
self.valinit = valinit
defaults = {'facecolor': 'white', 'edgecolor': '.75', 'size': 10}
handle_style = {} if handle_style is None else handle_style
marker_props = {
f'marker{k}': v for k, v in {**defaults, **handle_style}.items()
}
if orientation == "vertical":
self.track = Rectangle(
(.25, 0), .5, 2,
transform=ax.transAxes,
facecolor=track_color
)
ax.add_patch(self.track)
poly_transform = self.ax.get_yaxis_transform(which="grid")
handleXY_1 = [.5, valinit[0]]
handleXY_2 = [.5, valinit[1]]
else:
self.track = Rectangle(
(0, .25), 1, .5,
transform=ax.transAxes,
facecolor=track_color
)
ax.add_patch(self.track)
poly_transform = self.ax.get_xaxis_transform(which="grid")
handleXY_1 = [valinit[0], .5]
handleXY_2 = [valinit[1], .5]
self.poly = Polygon(np.zeros([5, 2]), **kwargs)
self._update_selection_poly(*valinit)
self.poly.set_transform(poly_transform)
self.poly.get_path()._interpolation_steps = 100
self.ax.add_patch(self.poly)
self.ax._request_autoscale_view()
self._handles = [
ax.plot(
*handleXY_1,
"o",
**marker_props,
clip_on=False
)[0],
ax.plot(
*handleXY_2,
"o",
**marker_props,
clip_on=False
)[0]
]
if orientation == "vertical":
self.label = ax.text(
0.5,
1.02,
label,
transform=ax.transAxes,
verticalalignment="bottom",
horizontalalignment="center",
)
self.valtext = ax.text(
0.5,
-0.02,
self._format(valinit),
transform=ax.transAxes,
verticalalignment="top",
horizontalalignment="center",
)
else:
self.label = ax.text(
-0.02,
0.5,
label,
transform=ax.transAxes,
verticalalignment="center",
horizontalalignment="right",
)
self.valtext = ax.text(
1.02,
0.5,
self._format(valinit),
transform=ax.transAxes,
verticalalignment="center",
horizontalalignment="left",
)
self._active_handle = None
self.set_val(valinit)
def _update_selection_poly(self, vmin, vmax):
"""
Update the vertices of the *self.poly* slider in-place
to cover the data range *vmin*, *vmax*.
"""
# The vertices are positioned
# 1 ------ 2
# | |
# 0, 4 ---- 3
verts = self.poly.xy
if self.orientation == "vertical":
verts[0] = verts[4] = .25, vmin
verts[1] = .25, vmax
verts[2] = .75, vmax
verts[3] = .75, vmin
else:
verts[0] = verts[4] = vmin, .25
verts[1] = vmin, .75
verts[2] = vmax, .75
verts[3] = vmax, .25
def _min_in_bounds(self, min):
"""Ensure the new min value is between valmin and self.val[1]."""
if min <= self.valmin:
if not self.closedmin:
return self.val[0]
min = self.valmin
if min > self.val[1]:
min = self.val[1]
return self._stepped_value(min)
def _max_in_bounds(self, max):
"""Ensure the new max value is between valmax and self.val[0]."""
if max >= self.valmax:
if not self.closedmax:
return self.val[1]
max = self.valmax
if max <= self.val[0]:
max = self.val[0]
return self._stepped_value(max)
def _value_in_bounds(self, vals):
"""Clip min, max values to the bounds."""
return (self._min_in_bounds(vals[0]), self._max_in_bounds(vals[1]))
def _update_val_from_pos(self, pos):
"""Update the slider value based on a given position."""
idx = np.argmin(np.abs(self.val - pos))
if idx == 0:
val = self._min_in_bounds(pos)
self.set_min(val)
else:
val = self._max_in_bounds(pos)
self.set_max(val)
if self._active_handle:
if self.orientation == "vertical":
self._active_handle.set_ydata([val])
else:
self._active_handle.set_xdata([val])
def _update(self, event):
"""Update the slider position."""
if self.ignore(event) or event.button != 1:
return
if event.name == "button_press_event" and self.ax.contains(event)[0]:
self.drag_active = True
event.canvas.grab_mouse(self.ax)
if not self.drag_active:
return
if (event.name == "button_release_event"
or event.name == "button_press_event" and not self.ax.contains(event)[0]):
self.drag_active = False
event.canvas.release_mouse(self.ax)
self._active_handle = None
return
# determine which handle was grabbed
xdata, ydata = self._get_data_coords(event)
handle_index = np.argmin(np.abs(
[h.get_xdata()[0] - xdata for h in self._handles]
if self.orientation == "horizontal" else
[h.get_ydata()[0] - ydata for h in self._handles]))
handle = self._handles[handle_index]
# these checks ensure smooth behavior if the handles swap which one
# has a higher value. i.e. if one is dragged over and past the other.
if handle is not self._active_handle:
self._active_handle = handle
self._update_val_from_pos(xdata if self.orientation == "horizontal" else ydata)
def _format(self, val):
"""Pretty-print *val*."""
if self.valfmt is not None:
return f"({self.valfmt % val[0]}, {self.valfmt % val[1]})"
else:
_, s1, s2, _ = self._fmt.format_ticks(
[self.valmin, *val, self.valmax]
)
# fmt.get_offset is actually the multiplicative factor, if any.
s1 += self._fmt.get_offset()
s2 += self._fmt.get_offset()
# Use f string to avoid issues with backslashes when cast to a str
return f"({s1}, {s2})"
def set_min(self, min):
"""
Set the lower value of the slider to *min*.
Parameters
----------
min : float
"""
self.set_val((min, self.val[1]))
def set_max(self, max):
"""
Set the lower value of the slider to *max*.
Parameters
----------
max : float
"""
self.set_val((self.val[0], max))
def set_val(self, val):
"""
Set slider value to *val*.
Parameters
----------
val : tuple or array-like of float
"""
val = np.sort(val)
_api.check_shape((2,), val=val)
# Reset value to allow _value_in_bounds() to work.
self.val = (self.valmin, self.valmax)
vmin, vmax = self._value_in_bounds(val)
self._update_selection_poly(vmin, vmax)
if self.orientation == "vertical":
self._handles[0].set_ydata([vmin])
self._handles[1].set_ydata([vmax])
else:
self._handles[0].set_xdata([vmin])
self._handles[1].set_xdata([vmax])
self.valtext.set_text(self._format((vmin, vmax)))
if self.drawon:
self.ax.figure.canvas.draw_idle()
self.val = (vmin, vmax)
if self.eventson:
self._observers.process("changed", (vmin, vmax))
def on_changed(self, func):
"""
Connect *func* as callback function to changes of the slider value.
Parameters
----------
func : callable
Function to call when slider is changed. The function
must accept a 2-tuple of floats as its argument.
Returns
-------
int
Connection id (which can be used to disconnect *func*).
"""
return self._observers.connect('changed', lambda val: func(val))
def _expand_text_props(props):
props = cbook.normalize_kwargs(props, mtext.Text)
return cycler(**props)() if props else itertools.repeat({})
class CheckButtons(AxesWidget):
r"""
A GUI neutral set of check buttons.
For the check buttons to remain responsive you must keep a