-
Notifications
You must be signed in to change notification settings - Fork 16
/
wxmpl.py
2029 lines (1682 loc) · 61 KB
/
wxmpl.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
# Purpose: painless matplotlib embedding for wxPython
# Author: Ken McIvor <[email protected]>
#
# Copyright 2005-2009 Illinois Institute of Technology
#
# See the file "LICENSE" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
"""
Embedding matplotlib in wxPython applications is straightforward, but the
default plotting widget lacks the capabilities necessary for interactive use.
WxMpl (wxPython+matplotlib) is a library of components that provide these
missing features in the form of a better matplolib FigureCanvas.
"""
import wx
import sys
import os.path
import weakref
import matplotlib
matplotlib.use('WXAgg')
import numpy as NumPy
from matplotlib.axes._base import _process_plot_var_args
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.backends.backend_agg import FigureCanvasAgg, RendererAgg
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure
from matplotlib.font_manager import FontProperties
from matplotlib.projections.polar import PolarAxes
from matplotlib.transforms import Bbox
__version__ = '2.0dev'
__all__ = ['PlotPanel', 'PlotFrame', 'PlotApp', 'StripCharter', 'Channel',
'FigurePrinter', 'PointEvent', 'EVT_POINT', 'SelectionEvent',
'EVT_SELECTION']
# If you are using wxGtk without libgnomeprint and want to use something other
# than `lpr' to print you will have to specify that command here.
POSTSCRIPT_PRINTING_COMMAND = 'lpr'
# Between 0.98.1 and 0.98.3rc there were some significant API changes:
# * FigureCanvasWx.draw(repaint=True) became draw(drawDC=None)
# * The following events were added:
# - figure_enter_event
# - figure_leave_event
# - axes_enter_event
# - axes_leave_event
MATPLOTLIB_0_98_3 = '0.98.3' <= matplotlib.__version__
#
# Utility functions and classes
#
def invert_point(x, y, transform):
"""
Returns a coordinate inverted by the specificed C{Transform}.
"""
return transform.inverted().transform_point((x, y))
def find_axes(canvas, x, y):
"""
Finds the C{Axes} within a matplotlib C{FigureCanvas} contains the canvas
coordinates C{(x, y)} and returns that axes and the corresponding data
coordinates C{xdata, ydata} as a 3-tuple.
If no axes contains the specified point a 3-tuple of C{None} is returned.
"""
evt = matplotlib.backend_bases.MouseEvent('', canvas, x, y)
axes = None
for a in canvas.get_figure().get_axes():
if a.in_axes(evt):
if axes is None:
axes = a
else:
return None, None, None
if axes is None:
return None, None, None
xdata, ydata = invert_point(x, y, axes.transData)
return axes, xdata, ydata
def get_bbox_lims(bbox):
"""
Returns the boundaries of the X and Y intervals of a C{Bbox}.
"""
p0 = bbox.min
p1 = bbox.max
return (p0[0], p1[0]), (p0[1], p1[1])
def find_selected_axes(canvas, x1, y1, x2, y2):
"""
Finds the C{Axes} within a matplotlib C{FigureCanvas} that overlaps with a
canvas area from C{(x1, y1)} to C{(x1, y1)}. That axes and the
corresponding X and Y axes ranges are returned as a 3-tuple.
If no axes overlaps with the specified area, or more than one axes
overlaps, a 3-tuple of C{None}s is returned.
"""
axes = None
bbox = Bbox.from_extents(x1, y1, x2, y2)
for a in canvas.get_figure().get_axes():
if bbox.overlaps(a.bbox):
if axes is None:
axes = a
else:
return None, None, None
if axes is None:
return None, None, None
x1, y1, x2, y2 = limit_selection(bbox, axes)
xrange, yrange = get_bbox_lims(
Bbox.from_extents(x1, y1, x2, y2).inverse_transformed(axes.transData))
return axes, xrange, yrange
def limit_selection(bbox, axes):
"""
Finds the region of a selection C{bbox} which overlaps with the supplied
C{axes} and returns it as the 4-tuple C{(xmin, ymin, xmax, ymax)}.
"""
bxr, byr = get_bbox_lims(bbox)
axr, ayr = get_bbox_lims(axes.bbox)
xmin = max(bxr[0], axr[0])
xmax = min(bxr[1], axr[1])
ymin = max(byr[0], ayr[0])
ymax = min(byr[1], ayr[1])
return xmin, ymin, xmax, ymax
def format_coord(axes, xdata, ydata):
"""
A C{None}-safe version of {Axes.format_coord()}.
"""
if xdata is None or ydata is None:
return ''
return axes.format_coord(xdata, ydata)
def toplevel_parent_of_window(window):
"""
Returns the first top-level parent of a wx.Window
"""
topwin = window
while not isinstance(topwin, wx.TopLevelWindow):
topwin = topwin.GetParent()
return topwin
class AxesLimits:
"""
Alters the X and Y limits of C{Axes} objects while maintaining a history of
the changes.
"""
def __init__(self, autoscaleUnzoom):
self.autoscaleUnzoom = autoscaleUnzoom
self.history = weakref.WeakKeyDictionary()
def setAutoscaleUnzoom(self, state):
"""
Enable or disable autoscaling the axes as a result of zooming all the
way back out.
"""
self.limits.setAutoscaleUnzoom(state)
def _get_history(self, axes):
"""
Returns the history list of X and Y limits associated with C{axes}.
"""
return self.history.setdefault(axes, [])
def zoomed(self, axes):
"""
Returns a boolean indicating whether C{axes} has had its limits
altered.
"""
return not (not self._get_history(axes))
def set(self, axes, xrange, yrange):
"""
Changes the X and Y limits of C{axes} to C{xrange} and {yrange}
respectively. A boolean indicating whether or not the
axes should be redraw is returned, because polar axes cannot have
their limits changed sensibly.
"""
if not axes.can_zoom():
return False
# The axes limits must be converted to tuples because MPL 0.98.1
# returns the underlying array objects
oldRange = tuple(axes.get_xlim()), tuple(axes.get_ylim())
history = self._get_history(axes)
history.append(oldRange)
axes.set_xlim(xrange)
axes.set_ylim(yrange)
return True
def restore(self, axes):
"""
Changes the X and Y limits of C{axes} to their previous values. A
boolean indicating whether or not the axes should be redraw is
returned.
"""
history = self._get_history(axes)
if not history:
return False
xrange, yrange = history.pop()
if self.autoscaleUnzoom and not len(history):
axes.autoscale_view()
else:
axes.set_xlim(xrange)
axes.set_ylim(yrange)
return True
#
# Director of the matplotlib canvas
#
class PlotPanelDirector:
"""
Encapsulates all of the user-interaction logic required by the
C{PlotPanel}, following the Humble Dialog Box pattern proposed by Michael
Feathers:
U{http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf}
"""
# TODO: add a programmatic interface to zooming and user interactions
# TODO: full support for MPL events
def __init__(self, view, zoom=True, selection=True, rightClickUnzoom=True,
autoscaleUnzoom=True):
"""
Create a new director for the C{PlotPanel} C{view}. The keyword
arguments C{zoom} and C{selection} have the same meanings as for
C{PlotPanel}.
"""
self.view = view
self.zoomEnabled = zoom
self.selectionEnabled = selection
self.rightClickUnzoom = rightClickUnzoom
self.limits = AxesLimits(autoscaleUnzoom)
self.leftButtonPoint = None
def setSelection(self, state):
"""
Enable or disable left-click area selection.
"""
self.selectionEnabled = state
def setZoomEnabled(self, state):
"""
Enable or disable zooming as a result of left-click area selection.
"""
self.zoomEnabled = state
def setAutoscaleUnzoom(self, state):
"""
Enable or disable autoscaling the axes as a result of zooming all the
way back out.
"""
self.limits.setAutoscaleUnzoom(state)
def setRightClickUnzoom(self, state):
"""
Enable or disable unzooming as a result of right-clicking.
"""
self.rightClickUnzoom = state
def canDraw(self):
"""
Indicates if plot may be not redrawn due to the presence of a selection
box.
"""
return self.leftButtonPoint is None
def zoomed(self, axes):
"""
Returns a boolean indicating whether or not the plot has been zoomed in
as a result of a left-click area selection.
"""
return self.limits.zoomed(axes)
def keyDown(self, evt):
"""
Handles wxPython key-press events. These events are currently skipped.
"""
evt.Skip()
def keyUp(self, evt):
"""
Handles wxPython key-release events. These events are currently
skipped.
"""
evt.Skip()
def leftButtonDown(self, evt, x, y):
"""
Handles wxPython left-click events.
"""
self.leftButtonPoint = (x, y)
view = self.view
axes, xdata, ydata = find_axes(view, x, y)
if axes is not None and self.selectionEnabled and axes.can_zoom():
view.cursor.setCross()
view.crosshairs.clear()
def leftButtonUp(self, evt, x, y):
"""
Handles wxPython left-click-release events.
"""
if self.leftButtonPoint is None:
return
view = self.view
axes, xdata, ydata = find_axes(view, x, y)
x0, y0 = self.leftButtonPoint
self.leftButtonPoint = None
view.rubberband.clear()
if x0 == x:
if y0 == y and axes is not None:
view.notify_point(axes, x, y)
view.crosshairs.set(x, y)
return
elif y0 == y:
return
xdata = ydata = None
axes, xrange, yrange = find_selected_axes(view, x0, y0, x, y)
if axes is not None:
xdata, ydata = invert_point(x, y, axes.transData)
if self.zoomEnabled:
if self.limits.set(axes, xrange, yrange):
self.view.draw()
else:
bbox = Bbox.from_extents(x0, y0, x, y)
x1, y1, x2, y2 = limit_selection(bbox, axes)
self.view.notify_selection(axes, x1, y1, x2, y2)
if axes is None:
view.cursor.setNormal()
elif not axes.can_zoom():
view.cursor.setNormal()
view.location.set(format_coord(axes, xdata, ydata))
else:
view.crosshairs.set(x, y)
view.location.set(format_coord(axes, xdata, ydata))
def rightButtonDown(self, evt, x, y):
"""
Handles wxPython right-click events. These events are currently
skipped.
"""
evt.Skip()
def rightButtonUp(self, evt, x, y):
"""
Handles wxPython right-click-release events.
"""
view = self.view
axes, xdata, ydata = find_axes(view, x, y)
if (axes is not None and self.zoomEnabled and self.rightClickUnzoom
and self.limits.restore(axes)):
view.crosshairs.clear()
view.draw()
view.crosshairs.set(x, y)
def mouseMotion(self, evt, x, y):
"""
Handles wxPython mouse motion events, dispatching them based on whether
or not a selection is in process and what the cursor is over.
"""
view = self.view
axes, xdata, ydata = find_axes(view, x, y)
if self.leftButtonPoint is not None:
self.selectionMouseMotion(evt, x, y, axes, xdata, ydata)
else:
if axes is None:
self.canvasMouseMotion(evt, x, y)
elif not axes.can_zoom():
self.unzoomableAxesMouseMotion(evt, x, y, axes, xdata, ydata)
else:
self.axesMouseMotion(evt, x, y, axes, xdata, ydata)
def selectionMouseMotion(self, evt, x, y, axes, xdata, ydata):
"""
Handles wxPython mouse motion events that occur during a left-click
area selection.
"""
view = self.view
x0, y0 = self.leftButtonPoint
view.rubberband.set(x0, y0, x, y)
if axes is None:
view.location.clear()
else:
view.location.set(format_coord(axes, xdata, ydata))
def canvasMouseMotion(self, evt, x, y):
"""
Handles wxPython mouse motion events that occur over the canvas.
"""
view = self.view
view.cursor.setNormal()
view.crosshairs.clear()
view.location.clear()
def axesMouseMotion(self, evt, x, y, axes, xdata, ydata):
"""
Handles wxPython mouse motion events that occur over an axes.
"""
view = self.view
view.cursor.setCross()
view.crosshairs.set(x, y)
view.location.set(format_coord(axes, xdata, ydata))
def unzoomableAxesMouseMotion(self, evt, x, y, axes, xdata, ydata):
"""
Handles wxPython mouse motion events that occur over an axes that does
not support zooming.
"""
view = self.view
view.cursor.setNormal()
view.location.set(format_coord(axes, xdata, ydata))
#
# Components used by the PlotPanel
#
class Painter:
"""
Painters encapsulate the mechanics of drawing some value in a wxPython
window and erasing it. Subclasses override template methods to process
values and draw them.
@cvar PEN: C{wx.Pen} to use (defaults to C{wx.BLACK_PEN})
@cvar BRUSH: C{wx.Brush} to use (defaults to C{wx.TRANSPARENT_BRUSH})
@cvar FUNCTION: Logical function to use (defaults to C{wx.COPY})
@cvar FONT: C{wx.Font} to use (defaults to C{wx.NORMAL_FONT})
@cvar TEXT_FOREGROUND: C{wx.Colour} to use (defaults to C{wx.BLACK})
@cvar TEXT_BACKGROUND: C{wx.Colour} to use (defaults to C{wx.WHITE})
"""
PEN = wx.BLACK_PEN
BRUSH = wx.TRANSPARENT_BRUSH
FUNCTION = wx.COPY
FONT = wx.NORMAL_FONT
TEXT_FOREGROUND = wx.BLACK
TEXT_BACKGROUND = wx.WHITE
def __init__(self, view, enabled=True):
"""
Create a new painter attached to the wxPython window C{view}. The
keyword argument C{enabled} has the same meaning as the argument to the
C{setEnabled()} method.
"""
self.view = view
self.lastValue = None
self.enabled = enabled
def setEnabled(self, state):
"""
Enable or disable this painter. Disabled painters do not draw their
values and calls to C{set()} have no effect on them.
"""
oldState, self.enabled = self.enabled, state
if oldState and not self.enabled:
self.clear()
def set(self, *value):
"""
Update this painter's value and then draw it. Values may not be
C{None}, which is used internally to represent the absence of a current
value.
"""
if self.enabled:
value = self.formatValue(value)
self._paint(value, None)
def redraw(self, dc=None):
"""
Redraw this painter's current value.
"""
value = self.lastValue
self.lastValue = None
self._paint(value, dc)
def clear(self, dc=None):
"""
Clear the painter's current value from the screen and the painter
itself.
"""
if self.lastValue is not None:
self._paint(None, dc)
def _paint(self, value, dc):
"""
Draws a previously processed C{value} on this painter's window.
"""
if dc is None:
dc = wx.ClientDC(self.view)
dc.SetPen(self.PEN)
dc.SetBrush(self.BRUSH)
dc.SetFont(self.FONT)
dc.SetTextForeground(self.TEXT_FOREGROUND)
dc.SetTextBackground(self.TEXT_BACKGROUND)
dc.SetLogicalFunction(self.FUNCTION)
dc.BeginDrawing()
if self.lastValue is not None:
self.clearValue(dc, self.lastValue)
self.lastValue = None
if value is not None:
self.drawValue(dc, value)
self.lastValue = value
dc.EndDrawing()
def formatValue(self, value):
"""
Template method that processes the C{value} tuple passed to the
C{set()} method, returning the processed version.
"""
return value
def drawValue(self, dc, value):
"""
Template method that draws a previously processed C{value} using the
wxPython device context C{dc}. This DC has already been configured, so
calls to C{BeginDrawing()} and C{EndDrawing()} may not be made.
"""
pass
def clearValue(self, dc, value):
"""
Template method that clears a previously processed C{value} that was
previously drawn, using the wxPython device context C{dc}. This DC has
already been configured, so calls to C{BeginDrawing()} and
C{EndDrawing()} may not be made.
"""
pass
class LocationPainter(Painter):
"""
Draws a text message containing the current position of the mouse in the
lower left corner of the plot.
"""
PADDING = 2
PEN = wx.WHITE_PEN
BRUSH = wx.WHITE_BRUSH
def formatValue(self, value):
"""
Extracts a string from the 1-tuple C{value}.
"""
return value[0]
def get_XYWH(self, dc, value):
"""
Returns the upper-left coordinates C{(X, Y)} for the string C{value}
its width and height C{(W, H)}.
"""
height = dc.GetSize()[1]
w, h = dc.GetTextExtent(value)
x = self.PADDING
y = int(height - (h + self.PADDING))
return x, y, w, h
def drawValue(self, dc, value):
"""
Draws the string C{value} in the lower left corner of the plot.
"""
x, y, w, h = self.get_XYWH(dc, value)
dc.DrawText(value, x, y)
def clearValue(self, dc, value):
"""
Clears the string C{value} from the lower left corner of the plot by
painting a white rectangle over it.
"""
x, y, w, h = self.get_XYWH(dc, value)
dc.DrawRectangle(x, y, w, h)
class CrosshairPainter(Painter):
"""
Draws crosshairs through the current position of the mouse.
"""
PEN = wx.WHITE_PEN
FUNCTION = wx.XOR
def formatValue(self, value):
"""
Converts the C{(X, Y)} mouse coordinates from matplotlib to wxPython.
"""
x, y = value
return int(x), int(self.view.get_figure().bbox.height - y)
def drawValue(self, dc, value):
"""
Draws crosshairs through the C{(X, Y)} coordinates.
"""
dc.CrossHair(*value)
def clearValue(self, dc, value):
"""
Clears the crosshairs drawn through the C{(X, Y)} coordinates.
"""
dc.CrossHair(*value)
class RubberbandPainter(Painter):
"""
Draws a selection rubberband from one point to another.
"""
PEN = wx.WHITE_PEN
FUNCTION = wx.XOR
def formatValue(self, value):
"""
Converts the C{(x1, y1, x2, y2)} mouse coordinates from matplotlib to
wxPython.
"""
x1, y1, x2, y2 = value
height = self.view.get_figure().bbox.height
y1 = height - y1
y2 = height - y2
if x2 < x1: x1, x2 = x2, x1
if y2 < y1: y1, y2 = y2, y1
return [int(z) for z in (x1, y1, x2-x1, y2-y1)]
def drawValue(self, dc, value):
"""
Draws the selection rubberband around the rectangle
C{(x1, y1, x2, y2)}.
"""
dc.DrawRectangle(*value)
def clearValue(self, dc, value):
"""
Clears the selection rubberband around the rectangle
C{(x1, y1, x2, y2)}.
"""
dc.DrawRectangle(*value)
class CursorChanger:
"""
Manages the current cursor of a wxPython window, allowing it to be switched
between a normal arrow and a square cross.
"""
def __init__(self, view, enabled=True):
"""
Create a CursorChanger attached to the wxPython window C{view}. The
keyword argument C{enabled} has the same meaning as the argument to the
C{setEnabled()} method.
"""
self.view = view
self.cursor = wx.CURSOR_DEFAULT
self.enabled = enabled
def setEnabled(self, state):
"""
Enable or disable this cursor changer. When disabled, the cursor is
reset to the normal arrow and calls to the C{set()} methods have no
effect.
"""
oldState, self.enabled = self.enabled, state
if oldState and not self.enabled and self.cursor != wx.CURSOR_DEFAULT:
self.cursor = wx.CURSOR_DEFAULT
self.view.SetCursor(wx.STANDARD_CURSOR)
def setNormal(self):
"""
Change the cursor of the associated window to a normal arrow.
"""
if self.cursor != wx.CURSOR_DEFAULT and self.enabled:
self.cursor = wx.CURSOR_DEFAULT
self.view.SetCursor(wx.STANDARD_CURSOR)
def setCross(self):
"""
Change the cursor of the associated window to a square cross.
"""
if self.cursor != wx.CURSOR_CROSS and self.enabled:
self.cursor = wx.CURSOR_CROSS
self.view.SetCursor(wx.CROSS_CURSOR)
#
# Printing Framework
#
# PostScript resolutions for the various WX print qualities
PS_DPI_HIGH_QUALITY = 600
PS_DPI_MEDIUM_QUALITY = 300
PS_DPI_LOW_QUALITY = 150
PS_DPI_DRAFT_QUALITY = 72
def update_postscript_resolution(printData):
"""
Sets the default wx.PostScriptDC resolution from a wx.PrintData's quality
setting.
This is a workaround for WX ignoring the quality setting and defaulting to
72 DPI. Unfortunately wx.Printout.GetDC() returns a wx.DC object instead
of the actual class, so it's impossible to set the resolution on the DC
itself.
Even more unforuntately, printing with libgnomeprint appears to always be
stuck at 72 DPI.
"""
if not callable(getattr(wx, 'PostScriptDC_SetResolution', None)):
return
quality = printData.GetQuality()
if quality > 0:
dpi = quality
elif quality == wx.PRINT_QUALITY_HIGH:
dpi = PS_DPI_HIGH_QUALITY
elif quality == wx.PRINT_QUALITY_MEDIUM:
dpi = PS_DPI_MEDIUM_QUALITY
elif quality == wx.PRINT_QUALITY_LOW:
dpi = PS_DPI_LOW_QUALITY
elif quality == wx.PRINT_QUALITY_DRAFT:
dpi = PS_DPI_DRAFT_QUALITY
else:
dpi = PS_DPI_HIGH_QUALITY
wx.PostScriptDC_SetResolution(dpi)
class FigurePrinter:
"""
Provides a simplified interface to the wxPython printing framework that's
designed for printing matplotlib figures.
"""
def __init__(self, view, printData=None):
"""
Create a new C{FigurePrinter} associated with the wxPython widget
C{view}. The keyword argument C{printData} supplies a C{wx.PrintData}
object containing the default printer settings.
"""
self.view = view
if printData is None:
printData = wx.PrintData()
self.setPrintData(printData)
def getPrintData(self):
"""
Return the current printer settings in their C{wx.PrintData} object.
"""
return self.pData
def setPrintData(self, printData):
"""
Use the printer settings in C{printData}.
"""
self.pData = printData
update_postscript_resolution(self.pData)
def pageSetup(self):
dlg = wx.PrintDialog(self.view)
pdData = dlg.GetPrintDialogData()
pdData.SetPrintData(self.pData)
if dlg.ShowModal() == wx.ID_OK:
self.setPrintData(pdData.GetPrintData())
dlg.Destroy()
def previewFigure(self, figure, title=None):
"""
Open a "Print Preview" window for the matplotlib chart C{figure}. The
keyword argument C{title} provides the printing framework with a title
for the print job.
"""
topwin = toplevel_parent_of_window(self.view)
fpo = FigurePrintout(figure, title)
fpo4p = FigurePrintout(figure, title)
preview = wx.PrintPreview(fpo, fpo4p, self.pData)
frame = wx.PreviewFrame(preview, topwin, 'Print Preview')
if self.pData.GetOrientation() == wx.PORTRAIT:
frame.SetSize(wx.Size(450, 625))
else:
frame.SetSize(wx.Size(600, 500))
frame.Initialize()
frame.Show(True)
def printFigure(self, figure, title=None):
"""
Open a "Print" dialog to print the matplotlib chart C{figure}. The
keyword argument C{title} provides the printing framework with a title
for the print job.
"""
pdData = wx.PrintDialogData()
pdData.SetPrintData(self.pData)
printer = wx.Printer(pdData)
fpo = FigurePrintout(figure, title)
if printer.Print(self.view, fpo, True):
self.setPrintData(pdData.GetPrintData())
class FigurePrintout(wx.Printout):
"""
Render a matplotlib C{Figure} to a page or file using wxPython's printing
framework.
"""
ASPECT_RECTANGULAR = 1
ASPECT_SQUARE = 2
def __init__(self, figure, title=None, size=None, aspectRatio=None):
"""
Create a printout for the matplotlib chart C{figure}. The
keyword argument C{title} provides the printing framework with a title
for the print job. The keyword argument C{size} specifies how to scale
the figure, from 1 to 100 percent. The keyword argument C{aspectRatio}
determines whether the printed figure will be rectangular or square.
"""
self.figure = figure
figTitle = figure.gca().title.get_text()
if not figTitle:
figTitle = title or 'Matplotlib Figure'
if size is None:
size = 100
elif size < 1 or size > 100:
raise ValueError('invalid figure size')
self.size = size
if aspectRatio is None:
aspectRatio = self.ASPECT_RECTANGULAR
elif (aspectRatio != self.ASPECT_RECTANGULAR
and aspectRatio != self.ASPECT_SQUARE):
raise ValueError('invalid aspect ratio')
self.aspectRatio = aspectRatio
wx.Printout.__init__(self, figTitle)
def GetPageInfo(self):
"""
Overrides wx.Printout.GetPageInfo() to provide the printing framework
with the number of pages in this print job.
"""
return (1, 1, 1, 1)
def HasPage(self, pageNumber):
"""
Overrides wx.Printout.GetPageInfo() to tell the printing framework
of the specified page exists.
"""
return pageNumber == 1
def OnPrintPage(self, pageNumber):
"""
Overrides wx.Printout.OnPrintPage() to render the matplotlib figure to
a printing device context.
"""
# % of printable area to use
imgPercent = max(1, min(100, self.size)) / 100.0
# ratio of the figure's width to its height
if self.aspectRatio == self.ASPECT_RECTANGULAR:
aspectRatio = 1.61803399
elif self.aspectRatio == self.ASPECT_SQUARE:
aspectRatio = 1.0
else:
raise ValueError('invalid aspect ratio')
# Device context to draw the page
dc = self.GetDC()
# PPI_P: Pixels Per Inch of the Printer
wPPI_P, hPPI_P = [float(x) for x in self.GetPPIPrinter()]
PPI_P = (wPPI_P + hPPI_P)/2.0
# PPI: Pixels Per Inch of the DC
if self.IsPreview():
wPPI, hPPI = [float(x) for x in self.GetPPIScreen()]
else:
wPPI, hPPI = wPPI_P, hPPI_P
PPI = (wPPI + hPPI)/2.0
# Pg_Px: Size of the page (pixels)
wPg_Px, hPg_Px = [float(x) for x in self.GetPageSizePixels()]
# Dev_Px: Size of the DC (pixels)
wDev_Px, hDev_Px = [float(x) for x in self.GetDC().GetSize()]
# Pg: Size of the page (inches)
wPg = wPg_Px / PPI_P
hPg = hPg_Px / PPI_P
# minimum margins (inches)
wM = 0.75
hM = 0.75
# Area: printable area within the margins (inches)
wArea = wPg - 2*wM
hArea = hPg - 2*hM
# Fig: printing size of the figure
# hFig is at a maximum when wFig == wArea
max_hFig = wArea / aspectRatio
hFig = min(imgPercent * hArea, max_hFig)
wFig = aspectRatio * hFig
# scale factor = device size / page size (equals 1.0 for real printing)
S = ((wDev_Px/PPI)/wPg + (hDev_Px/PPI)/hPg)/2.0
# Fig_S: scaled printing size of the figure (inches)
# M_S: scaled minimum margins (inches)
wFig_S = S * wFig
hFig_S = S * hFig
wM_S = S * wM
hM_S = S * hM
# Fig_Dx: scaled printing size of the figure (device pixels)
# M_Dx: scaled minimum margins (device pixels)
wFig_Dx = int(S * PPI * wFig)
hFig_Dx = int(S * PPI * hFig)
wM_Dx = int(S * PPI * wM)
hM_Dx = int(S * PPI * hM)
image = self.render_figure_as_image(wFig, hFig, PPI)
if self.IsPreview():
image = image.Scale(wFig_Dx, hFig_Dx)
self.GetDC().DrawBitmap(image.ConvertToBitmap(), wM_Dx, hM_Dx, False)
return True
def render_figure_as_image(self, wFig, hFig, dpi):
"""
Renders a matplotlib figure using the Agg backend and stores the result
in a C{wx.Image}. The arguments C{wFig} and {hFig} are the width and
height of the figure, and C{dpi} is the dots-per-inch to render at.
"""
figure = self.figure
old_dpi = figure.dpi
figure.dpi = dpi
old_width = figure.get_figwidth()
figure.set_figwidth(wFig)
old_height = figure.get_figheight()
figure.set_figheight(hFig)
old_frameon = figure.frameon
figure.frameon = False
wFig_Px = int(figure.bbox.width)
hFig_Px = int(figure.bbox.height)
agg = RendererAgg(wFig_Px, hFig_Px, dpi)
figure.draw(agg)
figure.dpi = old_dpi
figure.set_figwidth(old_width)
figure.set_figheight(old_height)
figure.frameon = old_frameon
image = wx.EmptyImage(wFig_Px, hFig_Px)
image.SetData(agg.tostring_rgb())
return image
#
# wxPython event interface for the PlotPanel and PlotFrame
#
EVT_POINT_ID = wx.NewId()