forked from PlotPyStack/PythonQwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot.py
2292 lines (1790 loc) · 73.9 KB
/
plot.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
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the Qwt License
# Copyright (c) 2002 Uwe Rathmann, for the original C++ code
# Copyright (c) 2015 Pierre Raybaut, for the Python translation/optimization
# (see LICENSE file for more details)
"""
QwtPlot
-------
.. autoclass:: QwtPlot
:members:
QwtPlotItem
-----------
.. autoclass:: QwtPlotItem
:members:
"""
import math
import numpy as np
from qtpy.QtCore import QEvent, QObject, QRectF, QSize, Qt, Signal
from qtpy.QtGui import QBrush, QColor, QFont, QPainter, QPalette
from qtpy.QtWidgets import QApplication, QFrame, QSizePolicy, QWidget
from qwt.graphic import QwtGraphic
from qwt.interval import QwtInterval
from qwt.legend import QwtLegendData
from qwt.plot_canvas import QwtPlotCanvas
from qwt.scale_div import QwtScaleDiv
from qwt.scale_draw import QwtScaleDraw
from qwt.scale_engine import QwtLinearScaleEngine
from qwt.scale_map import QwtScaleMap
from qwt.scale_widget import QwtScaleWidget
from qwt.text import QwtText, QwtTextLabel
def qwtSetTabOrder(first, second, with_children):
tab_chain = [first, second]
if with_children:
children = second.findChildren(QWidget)
w = second.nextInFocusChain()
while w in children:
while w in children:
children.remove(w)
tab_chain += [w]
w = w.nextInFocusChain()
for idx in range(len(tab_chain) - 1):
w_from = tab_chain[idx]
w_to = tab_chain[idx + 1]
policy1, policy2 = w_from.focusPolicy(), w_to.focusPolicy()
proxy1, proxy2 = w_from.focusProxy(), w_to.focusProxy()
for w in (w_from, w_to):
w.setFocusPolicy(Qt.TabFocus)
w.setFocusProxy(None)
QWidget.setTabOrder(w_from, w_to)
for w, pl, px in ((w_from, policy1, proxy1), (w_to, policy2, proxy2)):
w.setFocusPolicy(pl)
w.setFocusProxy(px)
class ItemList(list):
def sortItems(self):
self.sort(key=lambda item: item.z())
def insertItem(self, obj):
self.append(obj)
self.sortItems()
def removeItem(self, obj):
self.remove(obj)
self.sortItems()
class QwtPlot_PrivateData(QObject):
def __init__(self):
QObject.__init__(self)
self.itemList = ItemList()
self.titleLabel = None
self.footerLabel = None
self.canvas = None
self.legend = None
self.layout = None
self.autoReplot = None
self.flatStyle = None
class AxisData(object):
def __init__(self):
self.isEnabled = None
self.doAutoScale = None
self.minValue = None
self.maxValue = None
self.stepSize = None
self.maxMajor = None
self.maxMinor = None
self.isValid = None
self.scaleDiv = None # QwtScaleDiv
self.scaleEngine = None # QwtScaleEngine
self.scaleWidget = None # QwtScaleWidget
self.margin = None # Margin (float) in %
class QwtPlot(QFrame):
"""
A 2-D plotting widget
QwtPlot is a widget for plotting two-dimensional graphs.
An unlimited number of plot items can be displayed on its canvas.
Plot items might be curves (:py:class:`qwt.plot_curve.QwtPlotCurve`),
markers (:py:class:`qwt.plot_marker.QwtPlotMarker`),
the grid (:py:class:`qwt.plot_grid.QwtPlotGrid`), or anything else
derived from :py:class:`QwtPlotItem`.
A plot can have up to four axes, with each plot item attached to an x- and
a y axis. The scales at the axes can be explicitly set (`QwtScaleDiv`), or
are calculated from the plot items, using algorithms (`QwtScaleEngine`)
which can be configured separately for each axis.
The following example is a good starting point to see how to set up a
plot widget::
from qtpy import QtWidgets as QW
import qwt
import numpy as np
app = QW.QApplication([])
x = np.linspace(-10, 10, 500)
plot = qwt.QwtPlot("Trigonometric functions")
plot.insertLegend(qwt.QwtLegend(), qwt.QwtPlot.BottomLegend)
qwt.QwtPlotCurve.make(x, np.cos(x), "Cosinus", plot, linecolor="red", antialiased=True)
qwt.QwtPlotCurve.make(x, np.sin(x), "Sinus", plot, linecolor="blue", antialiased=True)
plot.resize(600, 300)
plot.show()
.. image:: /_static/QwtPlot_example.png
.. py:class:: QwtPlot([title=""], [parent=None])
:param str title: Title text
:param QWidget parent: Parent widget
.. py:data:: itemAttached
A signal indicating, that an item has been attached/detached
:param plotItem: Plot item
:param on: Attached/Detached
.. py:data:: legendDataChanged
A signal with the attributes how to update
the legend entries for a plot item.
:param itemInfo: Info about a plot item, build from itemToInfo()
:param data: Attributes of the entries (usually <= 1) for the plot item.
"""
itemAttached = Signal(object, bool)
legendDataChanged = Signal(object, object)
# enum Axis
AXES = yLeft, yRight, xBottom, xTop = list(range(4))
axisCnt = len(AXES) # Not necessary but ensure compatibility with PyQwt
# enum LegendPosition
LeftLegend, RightLegend, BottomLegend, TopLegend = list(range(4))
def __init__(self, *args):
if len(args) == 0:
title, parent = "", None
elif len(args) == 1:
if isinstance(args[0], QWidget) or args[0] is None:
title = ""
(parent,) = args
else:
(title,) = args
parent = None
elif len(args) == 2:
title, parent = args
else:
raise TypeError(
"%s() takes 0, 1 or 2 argument(s) (%s given)"
% (self.__class__.__name__, len(args))
)
QFrame.__init__(self, parent)
self.__layout_state = None
self.__data = QwtPlot_PrivateData()
from qwt.plot_layout import QwtPlotLayout
self.__data.layout = QwtPlotLayout()
self.__data.autoReplot = False
self.setAutoReplot(False)
self.setPlotLayout(self.__data.layout)
# title
self.__data.titleLabel = QwtTextLabel(self)
self.__data.titleLabel.setObjectName("QwtPlotTitle")
text = QwtText(title)
text.setRenderFlags(Qt.AlignCenter | Qt.TextWordWrap)
self.__data.titleLabel.setText(text)
# footer
self.__data.footerLabel = QwtTextLabel(self)
self.__data.footerLabel.setObjectName("QwtPlotFooter")
footer = QwtText()
footer.setRenderFlags(Qt.AlignCenter | Qt.TextWordWrap)
self.__data.footerLabel.setText(footer)
# legend
self.__data.legend = None
# axis
self.__axisData = []
self.initAxesData()
# canvas
self.__data.canvas = QwtPlotCanvas(self)
self.__data.canvas.setObjectName("QwtPlotCanvas")
self.__data.canvas.installEventFilter(self)
# plot style
self.setFlatStyle(True)
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
focusChain = [
self,
self.__data.titleLabel,
self.axisWidget(self.xTop),
self.axisWidget(self.yLeft),
self.__data.canvas,
self.axisWidget(self.yRight),
self.axisWidget(self.xBottom),
self.__data.footerLabel,
]
for idx in range(len(focusChain) - 1):
qwtSetTabOrder(focusChain[idx], focusChain[idx + 1], False)
self.legendDataChanged.connect(self.updateLegendItems)
def insertItem(self, item):
"""
Insert a plot item
:param qwt.plot.QwtPlotItem item: PlotItem
.. seealso::
:py:meth:`removeItem()`
.. note::
This was a member of QwtPlotDict in older versions.
"""
self.__data.itemList.insertItem(item)
def removeItem(self, item):
"""
Remove a plot item
:param qwt.plot.QwtPlotItem item: PlotItem
.. seealso::
:py:meth:`insertItem()`
.. note::
This was a member of QwtPlotDict in older versions.
"""
self.__data.itemList.removeItem(item)
def detachItems(self, rtti=None):
"""
Detach items from the dictionary
:param rtti: In case of `QwtPlotItem.Rtti_PlotItem` or None (default) detach all items otherwise only those items of the type rtti.
:type rtti: int or None
.. note::
This was a member of QwtPlotDict in older versions.
"""
for item in self.__data.itemList[:]:
if rtti in (None, QwtPlotItem.Rtti_PlotItem) or item.rtti() == rtti:
item.attach(None)
def itemList(self, rtti=None):
"""
A list of attached plot items.
Use caution when iterating these lists, as removing/detaching an
item will invalidate the iterator. Instead you can place pointers
to objects to be removed in a removal list, and traverse that list
later.
:param int rtti: In case of `QwtPlotItem.Rtti_PlotItem` detach all items otherwise only those items of the type rtti.
:return: List of all attached plot items of a specific type. If rtti is None, return a list of all attached plot items.
.. note::
This was a member of QwtPlotDict in older versions.
"""
if rtti is None or rtti == QwtPlotItem.Rtti_PlotItem:
return self.__data.itemList
return [item for item in self.__data.itemList if item.rtti() == rtti]
def setFlatStyle(self, state):
"""
Set or reset the flatStyle option
If the flatStyle option is set, the plot will be
rendered without any margin (scales, canvas, layout).
Enabling this option makes the plot look flat and compact.
The flatStyle option is set to True by default.
:param bool state: True or False.
.. seealso::
:py:meth:`flatStyle()`
"""
def make_font(family=None, size=None, delta_size=None, weight=None):
finfo = self.fontInfo()
family = finfo.family() if family is None else family
weight = -1 if weight is None else weight
size = size if delta_size is None else finfo.pointSize() + delta_size
return QFont(family, size, weight)
if state:
# New PythonQwt-exclusive flat style
plot_title_font = make_font(size=12)
axis_title_font = make_font(size=11)
axis_label_font = make_font(size=10)
tick_lighter_factors = (150, 125, 100)
scale_margin = scale_spacing = 0
canvas_frame_style = QFrame.NoFrame
plot_layout_canvas_margin = plot_layout_spacing = 0
ticks_color = Qt.darkGray
labels_color = "#444444"
else:
# Old PyQwt / Qwt style
plot_title_font = make_font(size=14, weight=QFont.Bold)
axis_title_font = make_font(size=12, weight=QFont.Bold)
axis_label_font = make_font(size=10)
tick_lighter_factors = (100, 100, 100)
scale_margin = scale_spacing = 2
canvas_frame_style = QFrame.Panel | QFrame.Sunken
plot_layout_canvas_margin = 4
plot_layout_spacing = 5
ticks_color = labels_color = Qt.black
self.canvas().setFrameStyle(canvas_frame_style)
self.plotLayout().setCanvasMargin(plot_layout_canvas_margin)
self.plotLayout().setSpacing(plot_layout_spacing)
palette = self.palette()
palette.setColor(QPalette.WindowText, QColor(ticks_color))
palette.setColor(QPalette.Text, QColor(labels_color))
self.setPalette(palette)
for axis_id in self.AXES:
scale_widget = self.axisWidget(axis_id)
scale_draw = self.axisScaleDraw(axis_id)
scale_widget.setFont(axis_label_font)
scale_widget.setMargin(scale_margin)
scale_widget.setSpacing(scale_spacing)
scale_title = scale_widget.title()
scale_title.setFont(axis_title_font)
scale_widget.setTitle(scale_title)
for tick_type, factor in enumerate(tick_lighter_factors):
scale_draw.setTickLighterFactor(tick_type, factor)
plot_title = self.title()
plot_title.setFont(plot_title_font)
self.setTitle(plot_title)
self.__data.flatStyle = state
def flatStyle(self):
"""
:return: True if the flatStyle option is set.
.. seealso::
:py:meth:`setFlatStyle()`
"""
return self.__data.flatStyle
def initAxesData(self):
"""Initialize axes"""
self.__axisData = [AxisData() for axisId in self.AXES]
self.__axisData[self.yLeft].scaleWidget = QwtScaleWidget(
QwtScaleDraw.LeftScale, self
)
self.__axisData[self.yRight].scaleWidget = QwtScaleWidget(
QwtScaleDraw.RightScale, self
)
self.__axisData[self.xTop].scaleWidget = QwtScaleWidget(
QwtScaleDraw.TopScale, self
)
self.__axisData[self.xBottom].scaleWidget = QwtScaleWidget(
QwtScaleDraw.BottomScale, self
)
self.__axisData[self.yLeft].scaleWidget.setObjectName("QwtPlotAxisYLeft")
self.__axisData[self.yRight].scaleWidget.setObjectName("QwtPlotAxisYRight")
self.__axisData[self.xTop].scaleWidget.setObjectName("QwtPlotAxisXTop")
self.__axisData[self.xBottom].scaleWidget.setObjectName("QwtPlotAxisXBottom")
for axisId in self.AXES:
d = self.__axisData[axisId]
d.scaleEngine = QwtLinearScaleEngine()
d.scaleWidget.setTransformation(d.scaleEngine.transformation())
d.scaleWidget.setMargin(2)
text = d.scaleWidget.title()
d.scaleWidget.setTitle(text)
d.doAutoScale = True
d.margin = 0.05
d.minValue = 0.0
d.maxValue = 1000.0
d.stepSize = 0.0
d.maxMinor = 5
d.maxMajor = 8
d.isValid = False
self.__axisData[self.yLeft].isEnabled = True
self.__axisData[self.yRight].isEnabled = False
self.__axisData[self.xBottom].isEnabled = True
self.__axisData[self.xTop].isEnabled = False
def deleteAxesData(self):
# XXX Is is really necessary in Python? (pure transcription of C++)
for axisId in self.AXES:
self.__axisData[axisId].scaleEngine = None
self.__axisData[axisId] = None
def axisWidget(self, axisId):
"""
:param int axisId: Axis index
:return: Scale widget of the specified axis, or None if axisId is invalid.
"""
if self.axisValid(axisId):
return self.__axisData[axisId].scaleWidget
def setAxisScaleEngine(self, axisId, scaleEngine):
"""
Change the scale engine for an axis
:param int axisId: Axis index
:param qwt.scale_engine.QwtScaleEngine scaleEngine: Scale engine
.. seealso::
:py:meth:`axisScaleEngine()`
"""
if self.axisValid(axisId) and scaleEngine is not None:
d = self.__axisData[axisId]
d.scaleEngine = scaleEngine
self.__axisData[axisId].scaleWidget.setTransformation(
scaleEngine.transformation()
)
d.isValid = False
self.autoRefresh()
def axisScaleEngine(self, axisId):
"""
:param int axisId: Axis index
:return: Scale engine for a specific axis
.. seealso::
:py:meth:`setAxisScaleEngine()`
"""
if self.axisValid(axisId):
return self.__axisData[axisId].scaleEngine
def axisAutoScale(self, axisId):
"""
:param int axisId: Axis index
:return: True, if autoscaling is enabled
"""
if self.axisValid(axisId):
return self.__axisData[axisId].doAutoScale
def axisEnabled(self, axisId):
"""
:param int axisId: Axis index
:return: True, if a specified axis is enabled
"""
if self.axisValid(axisId):
return self.__axisData[axisId].isEnabled
def axisFont(self, axisId):
"""
:param int axisId: Axis index
:return: The font of the scale labels for a specified axis
"""
if self.axisValid(axisId):
return self.axisWidget(axisId).font()
else:
return QFont()
def axisMaxMajor(self, axisId):
"""
:param int axisId: Axis index
:return: The maximum number of major ticks for a specified axis
.. seealso::
:py:meth:`setAxisMaxMajor()`,
:py:meth:`qwt.scale_engine.QwtScaleEngine.divideScale()`
"""
if self.axisValid(axisId):
return self.__axisData[axisId].maxMajor
else:
return 0
def axisMaxMinor(self, axisId):
"""
:param int axisId: Axis index
:return: The maximum number of minor ticks for a specified axis
.. seealso::
:py:meth:`setAxisMaxMinor()`,
:py:meth:`qwt.scale_engine.QwtScaleEngine.divideScale()`
"""
if self.axisValid(axisId):
return self.__axisData[axisId].maxMinor
else:
return 0
def axisScaleDiv(self, axisId):
"""
:param int axisId: Axis index
:return: The scale division of a specified axis
axisScaleDiv(axisId).lowerBound(), axisScaleDiv(axisId).upperBound()
are the current limits of the axis scale.
.. seealso::
:py:class:`qwt.scale_div.QwtScaleDiv`,
:py:meth:`setAxisScaleDiv()`,
:py:meth:`qwt.scale_engine.QwtScaleEngine.divideScale()`
"""
return self.__axisData[axisId].scaleDiv
def axisScaleDraw(self, axisId):
"""
:param int axisId: Axis index
:return: Specified scaleDraw for axis, or NULL if axis is invalid.
"""
if self.axisValid(axisId):
return self.axisWidget(axisId).scaleDraw()
def axisStepSize(self, axisId):
"""
:param int axisId: Axis index
:return: step size parameter value
This doesn't need to be the step size of the current scale.
.. seealso::
:py:meth:`setAxisScale()`,
:py:meth:`qwt.scale_engine.QwtScaleEngine.divideScale()`
"""
if self.axisValid(axisId):
return self.__axisData[axisId].stepSize
else:
return 0
def axisMargin(self, axisId):
"""
:param int axisId: Axis index
:return: Relative margin of the axis, as a fraction of the full axis range
.. seealso::
:py:meth:`setAxisMargin()`
"""
if self.axisValid(axisId):
return self.__axisData[axisId].margin
return 0.0
def axisInterval(self, axisId):
"""
:param int axisId: Axis index
:return: The current interval of the specified axis
This is only a convenience function for axisScaleDiv(axisId).interval()
.. seealso::
:py:class:`qwt.scale_div.QwtScaleDiv`,
:py:meth:`axisScaleDiv()`
"""
if self.axisValid(axisId):
return self.axisScaleDiv(axisId).interval()
else:
return QwtInterval()
def axisTitle(self, axisId):
"""
:param int axisId: Axis index
:return: Title of a specified axis
"""
if self.axisValid(axisId):
return self.axisWidget(axisId).title()
else:
return QwtText()
def enableAxis(self, axisId, tf=True):
"""
Enable or disable a specified axis
When an axis is disabled, this only means that it is not
visible on the screen. Curves, markers and can be attached
to disabled axes, and transformation of screen coordinates
into values works as normal.
Only xBottom and yLeft are enabled by default.
:param int axisId: Axis index
:param bool tf: True (enabled) or False (disabled)
"""
if self.axisValid(axisId) and tf != self.__axisData[axisId].isEnabled:
self.__axisData[axisId].isEnabled = tf
self.updateLayout()
def invTransform(self, axisId, pos):
"""
Transform the x or y coordinate of a position in the
drawing region into a value.
:param int axisId: Axis index
:param int pos: position
.. warning::
The position can be an x or a y coordinate,
depending on the specified axis.
"""
if self.axisValid(axisId):
return self.canvasMap(axisId).invTransform(pos)
else:
return 0.0
def transform(self, axisId, value):
"""
Transform a value into a coordinate in the plotting region
:param int axisId: Axis index
:param fload value: Value
:return: X or Y coordinate in the plotting region corresponding to the value.
"""
if self.axisValid(axisId):
return self.canvasMap(axisId).transform(value)
else:
return 0.0
def setAxisFont(self, axisId, font):
"""
Change the font of an axis
:param int axisId: Axis index
:param QFont font: Font
.. warning::
This function changes the font of the tick labels,
not of the axis title.
"""
if self.axisValid(axisId):
return self.axisWidget(axisId).setFont(font)
def setAxisAutoScale(self, axisId, on=True):
"""
Enable autoscaling for a specified axis
This member function is used to switch back to autoscaling mode
after a fixed scale has been set. Autoscaling is enabled by default.
:param int axisId: Axis index
:param bool on: On/Off
.. seealso::
:py:meth:`setAxisScale()`, :py:meth:`setAxisScaleDiv()`,
:py:meth:`updateAxes()`
.. note::
The autoscaling flag has no effect until updateAxes() is executed
( called by replot() ).
"""
if self.axisValid(axisId) and self.__axisData[axisId].doAutoScale != on:
self.__axisData[axisId].doAutoScale = on
self.autoRefresh()
def setAxisScale(self, axisId, min_, max_, stepSize=0):
"""
Disable autoscaling and specify a fixed scale for a selected axis.
In updateAxes() the scale engine calculates a scale division from the
specified parameters, that will be assigned to the scale widget. So
updates of the scale widget usually happen delayed with the next replot.
:param int axisId: Axis index
:param float min_: Minimum of the scale
:param float max_: Maximum of the scale
:param float stepSize: Major step size. If <code>step == 0</code>, the step size is calculated automatically using the maxMajor setting.
.. seealso::
:py:meth:`setAxisMaxMajor()`, :py:meth:`setAxisAutoScale()`,
:py:meth:`axisStepSize()`,
:py:meth:`qwt.scale_engine.QwtScaleEngine.divideScale()`
"""
if self.axisValid(axisId):
d = self.__axisData[axisId]
d.doAutoScale = False
d.isValid = False
d.minValue = min_
d.maxValue = max_
d.stepSize = stepSize
self.autoRefresh()
def setAxisScaleDiv(self, axisId, scaleDiv):
"""
Disable autoscaling and specify a fixed scale for a selected axis.
The scale division will be stored locally only until the next call
of updateAxes(). So updates of the scale widget usually happen delayed with
the next replot.
:param int axisId: Axis index
:param qwt.scale_div.QwtScaleDiv scaleDiv: Scale division
.. seealso::
:py:meth:`setAxisScale()`, :py:meth:`setAxisAutoScale()`
"""
if self.axisValid(axisId):
d = self.__axisData[axisId]
d.doAutoScale = False
d.scaleDiv = scaleDiv
d.isValid = True
self.autoRefresh()
def setAxisScaleDraw(self, axisId, scaleDraw):
"""
Set a scale draw
:param int axisId: Axis index
:param qwt.scale_draw.QwtScaleDraw scaleDraw: Object responsible for drawing scales.
By passing scaleDraw it is possible to extend QwtScaleDraw
functionality and let it take place in QwtPlot. Please note
that scaleDraw has to be created with new and will be deleted
by the corresponding QwtScale member ( like a child object ).
.. seealso::
:py:class:`qwt.scale_draw.QwtScaleDraw`,
:py:class:`qwt.scale_widget.QwtScaleWigdet`
.. warning::
The attributes of scaleDraw will be overwritten by those of the
previous QwtScaleDraw.
"""
if self.axisValid(axisId):
self.axisWidget(axisId).setScaleDraw(scaleDraw)
self.autoRefresh()
def setAxisLabelAlignment(self, axisId, alignment):
"""
Change the alignment of the tick labels
:param int axisId: Axis index
:param Qt.Alignment alignment: Or'd Qt.AlignmentFlags
.. seealso::
:py:meth:`qwt.scale_draw.QwtScaleDraw.setLabelAlignment()`
"""
if self.axisValid(axisId):
self.axisWidget(axisId).setLabelAlignment(alignment)
def setAxisLabelRotation(self, axisId, rotation):
"""
Rotate all tick labels
:param int axisId: Axis index
:param float rotation: Angle in degrees. When changing the label rotation, the label alignment might be adjusted too.
.. seealso::
:py:meth:`setLabelRotation()`, :py:meth:`setAxisLabelAlignment()`
"""
if self.axisValid(axisId):
self.axisWidget(axisId).setLabelRotation(rotation)
def setAxisLabelAutoSize(self, axisId, state):
"""
Set tick labels automatic size option (default: on)
:param int axisId: Axis index
:param bool state: On/off
.. seealso::
:py:meth:`qwt.scale_draw.QwtScaleDraw.setLabelAutoSize()`
"""
if self.axisValid(axisId):
self.axisWidget(axisId).setLabelAutoSize(state)
def setAxisMaxMinor(self, axisId, maxMinor):
"""
Set the maximum number of minor scale intervals for a specified axis
:param int axisId: Axis index
:param int maxMinor: Maximum number of minor steps
.. seealso::
:py:meth:`axisMaxMinor()`
"""
if self.axisValid(axisId):
maxMinor = max([0, min([maxMinor, 100])])
d = self.__axisData[axisId]
if maxMinor != d.maxMinor:
d.maxMinor = maxMinor
d.isValid = False
self.autoRefresh()
def setAxisMaxMajor(self, axisId, maxMajor):
"""
Set the maximum number of major scale intervals for a specified axis
:param int axisId: Axis index
:param int maxMajor: Maximum number of major steps
.. seealso::
:py:meth:`axisMaxMajor()`
"""
if self.axisValid(axisId):
maxMajor = max([1, min([maxMajor, 10000])])
d = self.__axisData[axisId]
if maxMajor != d.maxMajor:
d.maxMajor = maxMajor
d.isValid = False
self.autoRefresh()
def setAxisMargin(self, axisId, margin):
"""
Set the relative margin of the axis, as a fraction of the full axis range
:param int axisId: Axis index
:param float margin: Relative margin (float between 0 and 1)
.. seealso::
:py:meth:`axisMargin()`
"""
if not isinstance(margin, float) or margin < 0.0 or margin > 1.0:
raise ValueError("margin must be a float between 0 and 1")
if self.axisValid(axisId):
d = self.__axisData[axisId]
if margin != d.margin:
d.margin = margin
d.isValid = False
self.autoRefresh()
def setAxisTitle(self, axisId, title):
"""
Change the title of a specified axis
:param int axisId: Axis index
:param title: axis title
:type title: qwt.text.QwtText or str
"""
if self.axisValid(axisId):
self.axisWidget(axisId).setTitle(title)
self.updateLayout()
def updateAxes(self):
"""
Rebuild the axes scales
In case of autoscaling the boundaries of a scale are calculated
from the bounding rectangles of all plot items, having the
`QwtPlotItem.AutoScale` flag enabled (`QwtScaleEngine.autoScale()`).
Then a scale division is calculated (`QwtScaleEngine.didvideScale()`)
and assigned to scale widget.
When the scale boundaries have been assigned with `setAxisScale()` a
scale division is calculated (`QwtScaleEngine.didvideScale()`)
for this interval and assigned to the scale widget.
When the scale has been set explicitly by `setAxisScaleDiv()` the
locally stored scale division gets assigned to the scale widget.
The scale widget indicates modifications by emitting a
`QwtScaleWidget.scaleDivChanged()` signal.
`updateAxes()` is usually called by `replot()`.
.. seealso::
:py:meth:`setAxisAutoScale()`, :py:meth:`setAxisScale()`,
:py:meth:`setAxisScaleDiv()`, :py:meth:`replot()`,
:py:meth:`QwtPlotItem.boundingRect()`
"""
intv = [QwtInterval() for _i in self.AXES]
itmList = self.itemList()
for item in itmList:
if not item.testItemAttribute(QwtPlotItem.AutoScale):
continue
if not item.isVisible():
continue
if self.axisAutoScale(item.xAxis()) or self.axisAutoScale(item.yAxis()):
rect = item.boundingRect()
if rect.width() >= 0.0:
intv[item.xAxis()] |= QwtInterval(rect.left(), rect.right())
if rect.height() >= 0.0:
intv[item.yAxis()] |= QwtInterval(rect.top(), rect.bottom())
for axisId in self.AXES:
d = self.__axisData[axisId]
minValue = d.minValue
maxValue = d.maxValue
stepSize = d.stepSize
if d.doAutoScale and intv[axisId].isValid():
d.isValid = False
minValue = intv[axisId].minValue()
maxValue = intv[axisId].maxValue()
minValue, maxValue, stepSize = d.scaleEngine.autoScale(
d.maxMajor, minValue, maxValue, stepSize, d.margin
)
if not d.isValid:
d.scaleDiv = d.scaleEngine.divideScale(
minValue, maxValue, d.maxMajor, d.maxMinor, stepSize
)
d.isValid = True
scaleWidget = self.axisWidget(axisId)
scaleWidget.setScaleDiv(d.scaleDiv)
# It is *really* necessary to update border dist!
# Otherwise, when tick labels are large enough, the ticks
# may not be aligned with canvas grid.
# See the following issues for more details:
# https://github.com/PlotPyStack/guiqwt/issues/57
# https://github.com/PlotPyStack/PythonQwt/issues/30
startDist, endDist = scaleWidget.getBorderDistHint()
scaleWidget.setBorderDist(startDist, endDist)
for item in itmList:
if item.testItemInterest(QwtPlotItem.ScaleInterest):
item.updateScaleDiv(
self.axisScaleDiv(item.xAxis()), self.axisScaleDiv(item.yAxis())
)
def setCanvas(self, canvas):
"""
Set the drawing canvas of the plot widget.
The default canvas is a `QwtPlotCanvas`.
:param QWidget canvas: Canvas Widget
.. seealso::
:py:meth:`canvas()`
"""
if canvas == self.__data.canvas:
return
self.__data.canvas = canvas
if canvas is not None:
canvas.setParent(self)
canvas.installEventFilter(self)
if self.isVisible():
canvas.show()