-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathMatplotlibBackend.py
More file actions
2891 lines (2700 loc) · 112 KB
/
Copy pathMatplotlibBackend.py
File metadata and controls
2891 lines (2700 loc) · 112 KB
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
#/*##########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2004-2024 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
__author__ = "V.A. Sole - ESRF"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
__doc__ = """
Matplotlib Plot backend.
"""
from matplotlib import cbook
import matplotlib
# blitting enabled by default
# it provides faster response at the cost of missing minor updates
# during movement (only the bounding box of the moving object is updated)
# For instance, when moving a marker, the label is not updated during the
# movement.
BLITTING = True
import numpy
from numpy import vstack as numpyvstack
# Problem on debian6 numpy version 1.4.1 unsigned longs give infinity
#from numpy import nanmax, nanmin
def nanmax(x):
x = numpy.asarray(x)
x = x[numpy.isfinite(x)]
if len(x):
return x.max()
else:
return 0
def nanmin(x):
x = numpy.asarray(x)
x = x[numpy.isfinite(x)]
if len(x):
return x.min()
else:
return 0
import sys
import types
# This should be independent of Qt
TK = False
if ("tk" in sys.argv) or ("Tkinter" in sys.modules) or ("tkinter" in sys.modules):
TK = True
if TK and ("PyQt5.QtCore" not in sys.modules) and ("PyQt6.QtCore" not in sys.modules) and \
("PySide6.QtCore" not in sys.modules) and ("PySide2.QtCore" not in sys.modules):
import tkinter as Tk
elif 'PySide2.QtCore' in sys.modules:
from PySide2 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
elif 'PyQt5.QtCore' in sys.modules:
from PyQt5 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
elif 'PySide6.QtCore' in sys.modules:
from PySide6 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
elif 'PyQt6.QtCore' in sys.modules:
from PyQt6 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
else:
try:
from PyQt5 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
except ImportError:
try:
from PyQt6 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
except ImportError:
from PySide6 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
if ("PyQt5.QtCore" in sys.modules) or ("PySide2.QtCore" in sys.modules):
from ._patch_matplotlib import patch_backend_qt
patch_backend_qt()
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
TK = False
QT = True
elif ("PyQt6.QtCore" in sys.modules) or ("PySide6.QtCore" in sys.modules):
from ._patch_matplotlib import patch_backend_qt
patch_backend_qt()
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
TK = False
QT = True
elif ("Tkinter" in sys.modules) or ("tkinter" in sys.modules):
TK = True
QT = False
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas
else:
QT = False
TK = False
print("Unknown backend. Defaulting to Agg")
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
try:
from .. import PlotBackend
except ImportError:
from PyMca5.PyMca import PlotBackend
from matplotlib import cm
from matplotlib.font_manager import FontProperties
try:
from matplotlib.widgets import Cursor
except Exception:
print("matplotlib.widgets Cursor not available")
from matplotlib.figure import Figure
import matplotlib.patches as patches
Rectangle = patches.Rectangle
Polygon = patches.Polygon
from matplotlib.lines import Line2D
from matplotlib.collections import PathCollection
from matplotlib.text import Text
from matplotlib.image import AxesImage, NonUniformImage
from matplotlib.colors import LinearSegmentedColormap, LogNorm, Normalize
import time
try:
from . import _utils
except ImportError:
from PyMca5.PyMcaGraph.backends import _utils
DEBUG = 0
class ModestImage(AxesImage):
pass
class MatplotlibGraph(FigureCanvas):
def __init__(self, parent=None, **kw):
#self.figure = Figure(figsize=size, dpi=dpi) #in inches
self.fig = Figure()
if TK:
self._canvas = FigureCanvas.__init__(self, self.fig, master=parent)
else:
self._originalCursorShape = QtCore.Qt.ArrowCursor
self._canvas = FigureCanvas.__init__(self, self.fig)
# get the default widget color
color = self.palette().color(self.backgroundRole())
color = "#%x" % color.rgb()
if len(color) == 9:
color = "#" + color[3:]
#self.fig.set_facecolor(color)
self.fig.set_facecolor("w")
# that's it
if 1:
#this almost works
"""
def twinx(self):
call signature::
ax = twinx()
create a twin of Axes for generating a plot with a sharex
x-axis but independent y axis. The y-axis of self will have
ticks on left and the returned axes will have ticks on the
right
ax2 = self.fig.add_axes(self.get_position(True), sharex=self,
frameon=False)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.yaxis.set_offset_position('right')
self.ax.yaxis.tick_left()
ax2.xaxis.set_visible(False)
return ax2
"""
self.ax = self.fig.add_axes([.15, .15, .75, .75], label="left")
self.ax2 = self.ax.twinx()
self.ax2.set_label("right")
# critical for picking!!!!
self.ax2.set_zorder(0)
self.ax2.set_autoscaley_on(True)
self.ax.set_zorder(1)
#this works but the figure color is left
if hasattr(self.ax, "set_facecolor"):
self.ax.set_facecolor('none')
else:
# this was deprecated in 2.0
self.ax.set_axis_bgcolor('none')
self.fig.sca(self.ax)
try:
# prevent use of offsets
self.ax.get_yaxis().get_major_formatter().set_useOffset(False)
self.ax.get_xaxis().get_major_formatter().set_useOffset(False)
except Exception:
print("Error disabling matplotlib offsets")
else:
#this almost works
self.ax2 = self.fig.add_axes([.15, .15, .75, .75],
axisbg="w",
label="right",
frameon=False)
self.ax = self.fig.add_axes(self.ax2.get_position(),
sharex=self.ax2,
label="left",
frameon=True)
self.ax2.yaxis.tick_right()
self.ax2.xaxis.set_visible(False)
self.ax2.yaxis.set_label_position('right')
self.ax2.yaxis.set_offset_position('right')
if hasattr(self.ax, "set_facecolor"):
self.ax.set_facecolor('none')
else:
# this was deprecated in 2.0
self.ax.set_axis_bgcolor('none')
# this respects aspect size
# self.ax = self.fig.add_subplot(111, aspect='equal')
# This should be independent of Qt
if QT:
FigureCanvas.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.__lastMouseClick = ["middle", time.time()]
self._zoomEnabled = False
self._zoomColor = "black"
self.__zooming = False
self.__picking = False
self._background = None
self.__markerMoving = False
self._zoomStack = []
self.xAutoScale = True
self.yAutoScale = True
#info text
self._infoText = None
#drawingmode handling
self.setDrawModeEnabled(False)
self.__drawModeList = ['line', 'hline', 'vline', 'rectangle', 'polygon']
self.__drawing = False
self._drawingPatch = None
self._drawModePatch = 'line'
#event handling
self._callback = self._dummyCallback
self._x0 = None
self._y0 = None
self._zoomRectangle = None
self.fig.canvas.mpl_connect('button_press_event',
self.onMousePressed)
self.fig.canvas.mpl_connect('button_release_event',
self.onMouseReleased)
self.fig.canvas.mpl_connect('motion_notify_event',
self.onMouseMoved)
self.fig.canvas.mpl_connect('scroll_event',
self.onMouseWheel)
self.fig.canvas.mpl_connect('pick_event',
self.onPick)
def _dummyCallback(self, ddict):
if DEBUG:
print(ddict)
def setCallback(self, callbackFuntion):
self._callback = callbackFuntion
def onPick(self, event):
# Unfortunately only the artists on the top axes
# can be picked -> A legend handling widget is
# needed
middleButton = 2
rightButton = 3
button = event.mouseevent.button
if button == middleButton:
# do nothing with the midle button
return
elif button == rightButton:
button = "right"
else:
button = "left"
if self._drawModeEnabled:
# forget about picking or zooming
# should one disconnect when setting the mode?
return
self.__picking = False
self._pickingInfo = {}
if isinstance(event.artist, Line2D) or \
isinstance(event.artist, PathCollection):
# we only handle curves and markers for the time being
self.__picking = True
artist = event.artist
label = artist.get_label()
ind = event.ind
#xdata = thisline.get_xdata()
#ydata = thisline.get_ydata()
#print('onPick line:', zip(numpy.take(xdata, ind),
# numpy.take(ydata, ind)))
self._pickingInfo['artist'] = artist
self._pickingInfo['event_ind'] = ind
if label.startswith("__MARKER__"):
label = label[10:]
self._pickingInfo['type'] = 'marker'
self._pickingInfo['label'] = label
if 'draggable' in artist._plot_options:
self._pickingInfo['draggable'] = True
else:
self._pickingInfo['draggable'] = False
if 'selectable' in artist._plot_options:
self._pickingInfo['selectable'] = True
else:
self._pickingInfo['selectable'] = False
if hasattr(artist, "_infoText"):
self._pickingInfo['infoText'] = artist._infoText
else:
self._pickingInfo['infoText'] = None
elif isinstance(event.artist, PathCollection):
# almost identical to line 2D
self._pickingInfo['type'] = 'curve'
self._pickingInfo['label'] = label
self._pickingInfo['artist'] = artist
data = artist.get_offsets()
xdata = data[:, 0]
ydata = data[:, 1]
self._pickingInfo['xdata'] = xdata[ind]
self._pickingInfo['ydata'] = ydata[ind]
self._pickingInfo['infoText'] = None
else:
# line2D
self._pickingInfo['type'] = 'curve'
self._pickingInfo['label'] = label
self._pickingInfo['artist'] = artist
xdata = artist.get_xdata()
ydata = artist.get_ydata()
self._pickingInfo['xdata'] = xdata[ind]
self._pickingInfo['ydata'] = ydata[ind]
self._pickingInfo['infoText'] = None
if self._pickingInfo['infoText'] is None:
if self._infoText is None:
self._infoText = self.ax.text(event.mouseevent.xdata,
event.mouseevent.ydata,
label)
else:
self._infoText.set_position((event.mouseevent.xdata,
event.mouseevent.ydata))
self._infoText.set_text(label)
self._pickingInfo['infoText'] = self._infoText
self._pickingInfo['infoText'].set_visible(True)
if DEBUG:
print("%s %s selected" % (self._pickingInfo['type'].upper(),
self._pickingInfo['label']))
elif isinstance(event.artist, Rectangle):
patch = event.artist
print('onPick patch:', patch.get_path())
elif isinstance(event.artist, Text):
text = event.artist
print('onPick text:', text.get_text())
elif isinstance(event.artist, AxesImage):
self.__picking = True
artist = event.artist
#print dir(artist)
self._pickingInfo['artist'] = artist
#self._pickingInfo['event_ind'] = ind
label = artist.get_label()
self._pickingInfo['type'] = 'image'
self._pickingInfo['label'] = label
self._pickingInfo['draggable'] = False
self._pickingInfo['selectable'] = False
if hasattr(artist, "_plot_options"):
if 'draggable' in artist._plot_options:
self._pickingInfo['draggable'] = True
else:
self._pickingInfo['draggable'] = False
if 'selectable' in artist._plot_options:
self._pickingInfo['selectable'] = True
else:
self._pickingInfo['selectable'] = False
else:
print("unhandled event", event.artist)
def setDrawModeEnabled(self, flag=True, shape="polygon", label=None,
color=None, **kw):
if flag:
shape = shape.lower()
if shape not in self.__drawModeList:
self._drawModeEnabled = False
raise ValueError("Unsupported shape %s" % shape)
else:
self._drawModeEnabled = True
self.setZoomModeEnabled(False)
self._drawModePatch = shape
self._drawingParameters = kw
if color is not None:
self._drawingParameters['color'] = color
self._drawingParameters['shape'] = shape
self._drawingParameters['label'] = label
else:
self._drawModeEnabled = False
def setZoomModeEnabled(self, flag=True, color=None):
if color is None:
color = self._zoomColor
if len(color) == 4:
if type(color[3]) in [type(1), numpy.uint8, numpy.int8]:
color = numpy.array(color, dtype=numpy.float64)/255.
self._zoomColor = color
if flag:
self._zoomEnabled = True
self.setDrawModeEnabled(False)
else:
self._zoomEnabled = False
def isZoomModeEnabled(self):
return self._zoomEnabled
def isDrawModeEnabled(self):
return self._drawModeEnabled
def getDrawMode(self):
if self.isDrawModeEnabled():
return self._drawingParameters
else:
return None
def onMousePressed(self, event):
if DEBUG:
print("onMousePressed, event = ",event.xdata, event.ydata)
print("Mouse button = ", event.button)
self.__time0 = -1.0
if event.inaxes != self.ax:
if DEBUG:
print("RETURNING")
return
button = event.button
leftButton = 1
middleButton = 2
rightButton = 3
self._x0 = event.xdata
self._y0 = event.ydata
if button == middleButton:
# by default, do nothing with the middle button
return
self._x0Pixel = event.x
self._y0Pixel = event.y
self._x1 = event.xdata
self._y1 = event.ydata
self._x1Pixel = event.x
self._y1Pixel = event.y
self.__movingMarker = 0
# picking handling
if self.__picking:
if DEBUG:
print("PICKING, Ignoring zoom")
self.__zooming = False
self.__drawing = False
self.__markerMoving = False
if self._pickingInfo['type'] == "marker":
if button == rightButton:
# only selection or movement
self._pickingInfo = {}
return
artist = self._pickingInfo['artist']
if button == leftButton:
if self._pickingInfo['draggable']:
self.__markerMoving = True
if self._pickingInfo['selectable']:
self.__markerMoving = False
if self.__markerMoving:
if 'xmarker' in artist._plot_options:
data = event.xdata
if not numpy.iterable(data):
data = [data, ]
artist.set_xdata(data)
elif 'ymarker' in artist._plot_options:
data = event.ydata
if not numpy.iterable(data):
data = [data, ]
artist.set_ydata(data)
else:
xData, yData = event.xdata, event.ydata
if artist._constraint is not None:
# Apply marker constraint
xData, yData = artist._constraint(xData, yData)
if not numpy.iterable(xData):
xData = [xData, ]
if not numpy.iterable(yData):
yData = [yData, ]
artist.set_xdata(xData)
artist.set_ydata(yData)
if BLITTING and hasattr(artist.figure, "canvas"):
canvas = artist.figure.canvas
axes = artist.axes
artist.set_animated(True)
canvas.draw()
self._background = canvas.copy_from_bbox(self.fig.bbox)
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
else:
self.fig.canvas.draw()
ddict = {}
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['draggable'] = self._pickingInfo['draggable']
ddict['selectable'] = self._pickingInfo['selectable']
ddict['xpixel'] = self._x0Pixel
ddict['ypixel'] = self._y0Pixel
ddict['xdata'] = artist.get_xdata()
ddict['ydata'] = artist.get_ydata()
if self.__markerMoving:
ddict['event'] = "markerMoving"
ddict['x'] = self._x0
ddict['y'] = self._y0
else:
ddict['event'] = "markerClicked"
if hasattr(ddict['xdata'], "__len__"):
ddict['x'] = ddict['xdata'][-1]
else:
ddict['x'] = ddict['xdata']
if hasattr(ddict['ydata'], "__len__"):
ddict['y'] = ddict['ydata'][-1]
else:
ddict['y'] = ddict['ydata']
if button == leftButton:
ddict['button'] = "left"
else:
ddict['button'] = "right"
self._callback(ddict)
if ddict['event'] == "markerClicked":
self.__picking = False
return
elif self._pickingInfo['type'] == "curve":
ddict = {}
ddict['event'] = "curveClicked"
#ddict['event'] = "legendClicked"
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['x'] = self._x0
ddict['y'] = self._y0
ddict['xpixel'] = self._x0Pixel
ddict['ypixel'] = self._y0Pixel
ddict['xdata'] = self._pickingInfo['xdata']
ddict['ydata'] = self._pickingInfo['ydata']
if button == leftButton:
ddict['button'] = "left"
else:
ddict['button'] = "right"
self._callback(ddict)
return
elif self._pickingInfo['type'] == "image":
artist = self._pickingInfo['artist']
ddict = {}
ddict['event'] = "imageClicked"
#ddict['event'] = "legendClicked"
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['x'] = self._x0
ddict['y'] = self._y0
ddict['xpixel'] = self._x0Pixel
ddict['ypixel'] = self._y0Pixel
xScale = artist._plot_info['xScale']
yScale = artist._plot_info['yScale']
col = (ddict['x'] - xScale[0])/float(xScale[1])
row = (ddict['y'] - yScale[0])/float(yScale[1])
ddict['row'] = int(row)
ddict['col'] = int(col)
if button == leftButton:
ddict['button'] = "left"
else:
ddict['button'] = "right"
self.__picking = False
self._callback(ddict)
if event.button == rightButton:
#right click
self.__zooming = False
if self._drawingPatch is not None:
self._emitDrawingSignal("drawingFinished")
return
self.__time0 = time.time()
self.__zooming = self._zoomEnabled
self._zoomRect = None
self._xmin, self._xmax = self.ax.get_xlim()
self._ymin, self._ymax = self.ax.get_ylim()
# deal with inverted axis
if self._xmin > self._xmax:
tmpValue = self._xmin
self._xmin = self._xmax
self._xmax = tmpValue
if self._ymin > self._ymax:
tmpValue = self._ymin
self._ymin = self._ymax
self._ymax = tmpValue
if self.ax.get_aspect() != 'auto':
self._ratio = (self._ymax - self._ymin) / (self._xmax - self._xmin)
self.__drawing = self._drawModeEnabled
if self.__drawing:
if self._drawModePatch in ['hline', 'vline']:
if self._drawingPatch is None:
self._mouseData = numpy.zeros((2,2), numpy.float32)
if self._drawModePatch == "hline":
self._mouseData[0,0] = self._xmin
self._mouseData[0,1] = self._y0
self._mouseData[1,0] = self._xmax
self._mouseData[1,1] = self._y0
else:
self._mouseData[0,0] = self._x0
self._mouseData[0,1] = self._ymin
self._mouseData[1,0] = self._x0
self._mouseData[1,1] = self._ymax
color = self._getDrawingColor()
self._drawingPatch = Polygon(self._mouseData,
closed=True,
fill=False,
color=color)
self.ax.add_patch(self._drawingPatch)
def _getDrawingColor(self):
color = "black"
if "color" in self._drawingParameters:
color = self._drawingParameters["color"]
if len(color) == 4:
if type(color[3]) in [type(1), numpy.uint8, numpy.int8]:
color = numpy.array(color, dtype=numpy.float64)/255.
return color
def onMouseMoved(self, event):
if DEBUG:
print("onMouseMoved, event = ",event.xdata, event.ydata)
if event.inaxes != self.ax:
if DEBUG:
print("RETURNING")
return
button = event.button
if button == 1:
button = "left"
elif button == 2:
button = "middle"
elif button == 3:
button = "right"
else:
button = None
#as default, export the mouse in graph coordenates
self._x1 = event.xdata
self._y1 = event.ydata
self._x1Pixel = event.x
self._y1Pixel = event.y
ddict= {'event':'mouseMoved',
'x':self._x1,
'y':self._y1,
'xpixel':self._x1Pixel,
'ypixel':self._y1Pixel,
'button':button,
}
self._callback(ddict)
if button == "middle":
return
# should this be made by Plot1D with the previous call???
# The problem is Plot1D does not know if one is zooming or drawing
if not (self.__zooming or self.__drawing or self.__picking):
# this corresponds to moving without click
marker = None
for artist in self.ax.lines:
label = artist.get_label()
if label.startswith("__MARKER__"):
#data = artist.get_xydata()[0:1]
x, y = artist.get_xydata()[-1]
pixels = self.ax.transData.transform(numpyvstack([x,y]).T)
xPixel, yPixel = pixels.T
if 'xmarker' in artist._plot_options:
if abs(xPixel-event.x) < 5:
marker = artist
elif 'ymarker' in artist._plot_options:
if abs(yPixel-event.y) < 5:
marker = artist
elif (abs(xPixel-event.x) < 5) and \
(abs(yPixel-event.y) < 5):
marker = artist
if marker is not None:
break
if QT:
oldShape = self.cursor().shape()
if oldShape not in [QtCore.Qt.SizeHorCursor,
QtCore.Qt.SizeVerCursor,
QtCore.Qt.PointingHandCursor,
QtCore.Qt.OpenHandCursor,
QtCore.Qt.SizeAllCursor]:
self._originalCursorShape = oldShape
if marker is not None:
ddict = {}
ddict['event'] = 'hover'
ddict['type'] = 'marker'
ddict['label'] = marker.get_label()[10:]
if 'draggable' in marker._plot_options:
ddict['draggable'] = True
if QT:
if 'ymarker' in artist._plot_options:
self.setCursor(QtGui.QCursor(QtCore.Qt.SizeVerCursor))
elif 'xmarker' in artist._plot_options:
self.setCursor(QtGui.QCursor(QtCore.Qt.SizeHorCursor))
else:
self.setCursor(QtGui.QCursor(QtCore.Qt.SizeAllCursor))
else:
ddict['draggable'] = False
if 'selectable' in marker._plot_options:
ddict['selectable'] = True
if QT:
self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
else:
ddict['selectable'] = False
ddict['x'] = self._x1
ddict['y'] = self._y1
ddict['xpixel'] = self._x1Pixel
ddict['ypixel'] = self._y1Pixel
self._callback(ddict)
elif QT:
if self._originalCursorShape in [QtCore.Qt.SizeHorCursor,
QtCore.Qt.SizeVerCursor,
QtCore.Qt.PointingHandCursor,
QtCore.Qt.OpenHandCursor,
QtCore.Qt.SizeAllCursor]:
self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
else:
self.setCursor(QtGui.QCursor(self._originalCursorShape))
return
if self.__picking:
if self.__markerMoving:
artist = self._pickingInfo['artist']
infoText = self._pickingInfo['infoText']
if 'xmarker' in artist._plot_options:
data = event.xdata
if not numpy.iterable(data):
data = [data, ]
artist.set_xdata(data)
ymin, ymax = self.ax.get_ylim()
delta = abs(ymax - ymin)
ymax = max(ymax, ymin) - 0.005 * delta
if infoText is not None:
infoText.set_position((event.xdata, ymax))
elif 'ymarker' in artist._plot_options:
data = event.ydata
if not numpy.iterable(data):
data = [data, ]
artist.set_ydata(data)
if infoText is not None:
infoText.set_position((event.xdata, event.ydata))
else:
xData, yData = event.xdata, event.ydata
if artist._constraint is not None:
# Apply marker constraint
xData, yData = artist._constraint(xData, yData)
if not numpy.iterable(xData):
xData = [xData, ]
if not numpy.iterable(yData):
yData = [yData, ]
artist.set_xdata(xData)
artist.set_ydata(yData)
if infoText is not None:
xtmp, ytmp = self.ax.transData.transform_point((xData,
yData))
inv = self.ax.transData.inverted()
xtmp, ytmp = inv.transform_point((xtmp, ytmp + 15))
infoText.set_position((xData, ytmp))
if BLITTING and (self._background is not None) and\
hasattr(artist.figure, "canvas"):
canvas = artist.figure.canvas
axes = artist.axes
artist.set_animated(True)
canvas.restore_region(self._background)
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
else:
self.fig.canvas.draw()
ddict = {}
ddict['event'] = "markerMoving"
ddict['button'] = "left"
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['draggable'] = self._pickingInfo['draggable']
ddict['selectable'] = self._pickingInfo['selectable']
ddict['x'] = self._x1
ddict['y'] = self._y1
ddict['xpixel'] = self._x1Pixel
ddict['ypixel'] = self._y1Pixel
ddict['xdata'] = artist.get_xdata()
ddict['ydata'] = artist.get_ydata()
self._callback(ddict)
return
if (not self.__zooming) and (not self.__drawing):
return
if self._x0 is None:
# this happened when using the middle button
return
if self.__zooming or \
(self.__drawing and (self._drawModePatch == 'rectangle')):
if self._x1 < self._xmin:
self._x1 = self._xmin
elif self._x1 > self._xmax:
self._x1 = self._xmax
if self._y1 < self._ymin:
self._y1 = self._ymin
elif self._y1 > self._ymax:
self._y1 = self._ymax
if self._x1 < self._x0:
x = self._x1
w = self._x0 - self._x1
else:
x = self._x0
w = self._x1 - self._x0
if self._y1 < self._y0:
y = self._y1
h = self._y0 - self._y1
else:
y = self._y0
h = self._y1 - self._y0
if w == 0:
return
if (not self.__drawing) and (self.ax.get_aspect() != 'auto'):
if (h / w) > self._ratio:
h = w * self._ratio
else:
w = h / self._ratio
if self._x1 > self._x0:
x = self._x0
else:
x = self._x0 - w
if self._y1 > self._y0:
y = self._y0
else:
y = self._y0 - h
if self.__zooming:
if self._zoomRectangle is None:
self._zoomRectangle = Rectangle(xy=(x,y),
width=w,
height=h,
color=self._zoomColor,
fill=False)
self.ax.add_patch(self._zoomRectangle)
else:
self._zoomRectangle.set_bounds(x, y, w, h)
#self._zoomRectangle._update_patch_transform()
if BLITTING:
artist = self._zoomRectangle
canvas = artist.figure.canvas
axes = artist.axes
artist.set_animated(True)
if self._background is None:
self._background = canvas.copy_from_bbox(self.fig.bbox)
canvas.restore_region(self._background)
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
else:
self.fig.canvas.draw()
return
else:
if self._drawingPatch is None:
color = self._getDrawingColor()
self._drawingPatch = Rectangle(xy=(x,y),
width=w,
height=h,
fill=False,
color=color)
self._drawingPatch.set_hatch('.')
self.ax.add_patch(self._drawingPatch)
else:
self._drawingPatch.set_bounds(x, y, w, h)
#self._zoomRectangle._update_patch_transform()
if self.__drawing:
if self._drawingPatch is None:
self._mouseData = numpy.zeros((2,2), numpy.float32)
self._mouseData[0,0] = self._x0
self._mouseData[0,1] = self._y0
self._mouseData[1,0] = self._x1
self._mouseData[1,1] = self._y1
color = self._getDrawingColor()
self._drawingPatch = Polygon(self._mouseData,
closed=True,
fill=False,
color=color)
self.ax.add_patch(self._drawingPatch)
elif self._drawModePatch == 'rectangle':
# already handled, just for compatibility
self._mouseData = numpy.zeros((2,2), numpy.float32)
self._mouseData[0,0] = self._x0
self._mouseData[0,1] = self._y0
self._mouseData[1,0] = self._x1
self._mouseData[1,1] = self._y1
elif self._drawModePatch == 'line':
self._mouseData[0,0] = self._x0
self._mouseData[0,1] = self._y0
self._mouseData[1,0] = self._x1
self._mouseData[1,1] = self._y1
self._drawingPatch.set_xy(self._mouseData)
elif self._drawModePatch == 'hline':
xmin, xmax = self.ax.get_xlim()
self._mouseData[0,0] = xmin
self._mouseData[0,1] = self._y1
self._mouseData[1,0] = xmax
self._mouseData[1,1] = self._y1
self._drawingPatch.set_xy(self._mouseData)
elif self._drawModePatch == 'vline':
ymin, ymax = self.ax.get_ylim()
self._mouseData[0,0] = self._x1
self._mouseData[0,1] = ymin
self._mouseData[1,0] = self._x1
self._mouseData[1,1] = ymax
self._drawingPatch.set_xy(self._mouseData)
elif self._drawModePatch == 'polygon':
self._mouseData[-1,0] = self._x1
self._mouseData[-1,1] = self._y1
self._drawingPatch.set_xy(self._mouseData)
if matplotlib.__version__.startswith('1.1.1'):
# Patch for Debian 7
# Workaround matplotlib issue with closed path
# Need to toggle closed path to rebuild points
self._drawingPatch.set_closed(False)
self._drawingPatch.set_closed(True)
self._drawingPatch.set_hatch('/')
if BLITTING:
if self._background is None:
artist = self._drawingPatch
canvas = artist.figure.canvas
axes = artist.axes
self._background = canvas.copy_from_bbox(self.fig.bbox)
artist = self._drawingPatch
canvas = artist.figure.canvas
axes = artist.axes
artist.set_animated(True)
canvas.restore_region(self._background)
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
else:
self.fig.canvas.draw()
self._emitDrawingSignal(event='drawingProgress')
def onMouseReleased(self, event):
if DEBUG:
print("onMouseReleased, event = ",event.xdata, event.ydata)
if self._infoText in self.ax.texts:
self._infoText.set_visible(False)
if self.__picking:
self.__picking = False
if self.__markerMoving:
self.__markerMoving = False
artist = self._pickingInfo['artist']
if BLITTING and hasattr(artist.figure, "canvas"):
artist.set_animated(False)
self._background = None
artist.figure.canvas.draw()
ddict = {}
ddict['event'] = "markerMoved"
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['draggable'] = self._pickingInfo['draggable']
ddict['selectable'] = self._pickingInfo['selectable']
# use this and not the current mouse position because
# it has to agree with the marker position
ddict['x'] = artist.get_xdata()
ddict['y'] = artist.get_ydata()
ddict['xdata'] = artist.get_xdata()
ddict['ydata'] = artist.get_ydata()
# matplotlib 3.7.x was giving different output than previous versions
for key in ["x", "y", "xdata", "ydata"]:
if hasattr(ddict[key], "__len__"):
if len(ddict[key]) == 1:
ddict[key] = ddict[key][0]
self._callback(ddict)
self._pickingInfo = {}
return
if not hasattr(self, "__zoomstack"):
self.__zoomstack = []