FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
matplotlib/lib/matplotlib/backend_bases.py at master · flothesof/matplotlib · GitHub
flothesof
matplotlib
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
backend_bases.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
3334 lines (2713 loc) · 108 KB
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
backend_bases.py
Copy path
File metadata and controls
3334 lines (2713 loc) · 108 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
Abstract base classes define the primitives that renderers and
graphics contexts must implement to serve as a matplotlib backend
:class:`RendererBase`
An abstract base class to handle drawing/rendering operations.
:class:`FigureCanvasBase`
The abstraction layer that separates the
:class:`matplotlib.figure.Figure` from the backend specific
details like a user interface drawing area
:class:`GraphicsContextBase`
An abstract base class that provides color, line styles, etc...
:class:`Event`
The base class for all of the matplotlib event
handling. Derived classes such as :class:`KeyEvent` and
:class:`MouseEvent` store the meta data like keys and buttons
pressed, x and y locations in pixel and
:class:`~matplotlib.axes.Axes` coordinates.
:class:`ShowBase`
The base class for the Show class of each interactive backend;
the 'show' callable is then set to Show.__call__, inherited from
ShowBase.
:class:`ToolContainerBase`
The base class for the Toolbar class of each interactive backend.
:class:`StatusbarBase`
The base class for the messaging area.
"""
from
__future__
import
(
absolute_import
,
division
,
print_function
,
unicode_literals
)
from
contextlib
import
contextmanager
from
matplotlib
.
externals
import
six
from
matplotlib
.
externals
.
six
.
moves
import
xrange
import
os
import
sys
import
warnings
import
time
import
io
import
numpy
as
np
import
matplotlib
.
cbook
as
cbook
import
matplotlib
.
colors
as
colors
import
matplotlib
.
transforms
as
transforms
import
matplotlib
.
widgets
as
widgets
#import matplotlib.path as path
from
matplotlib
import
rcParams
from
matplotlib
import
is_interactive
from
matplotlib
import
get_backend
from
matplotlib
.
_pylab_helpers
import
Gcf
from
matplotlib
.
transforms
import
Bbox
,
TransformedBbox
,
Affine2D
import
matplotlib
.
tight_bbox
as
tight_bbox
import
matplotlib
.
textpath
as
textpath
from
matplotlib
.
path
import
Path
from
matplotlib
.
cbook
import
mplDeprecation
,
warn_deprecated
import
matplotlib
.
backend_tools
as
tools
try
:
from
importlib
import
import_module
except
:
# simple python 2.6 implementation (no relative imports)
def
import_module
(
name
):
__import__
(
name
)
return
sys
.
modules
[
name
]
try
:
from
PIL
import
Image
_has_pil
=
True
del
Image
except
ImportError
:
_has_pil
=
False
_default_filetypes
=
{
'ps'
:
'Postscript'
,
'eps'
:
'Encapsulated Postscript'
,
'pdf'
:
'Portable Document Format'
,
'pgf'
:
'PGF code for LaTeX'
,
'png'
:
'Portable Network Graphics'
,
'raw'
:
'Raw RGBA bitmap'
,
'rgba'
:
'Raw RGBA bitmap'
,
'svg'
:
'Scalable Vector Graphics'
,
'svgz'
:
'Scalable Vector Graphics'
}
_default_backends
=
{
'ps'
:
'matplotlib.backends.backend_ps'
,
'eps'
:
'matplotlib.backends.backend_ps'
,
'pdf'
:
'matplotlib.backends.backend_pdf'
,
'pgf'
:
'matplotlib.backends.backend_pgf'
,
'png'
:
'matplotlib.backends.backend_agg'
,
'raw'
:
'matplotlib.backends.backend_agg'
,
'rgba'
:
'matplotlib.backends.backend_agg'
,
'svg'
:
'matplotlib.backends.backend_svg'
,
'svgz'
:
'matplotlib.backends.backend_svg'
,
}
def
register_backend
(
format
,
backend
,
description
=
None
):
"""
Register a backend for saving to a given file format.
format : str
File extention
backend : module string or canvas class
Backend for handling file output
description : str, optional
Description of the file type. Defaults to an empty string
"""
if
description
is
None
:
description
=
''
_default_backends
[
format
]
=
backend
_default_filetypes
[
format
]
=
description
def
get_registered_canvas_class
(
format
):
"""
Return the registered default canvas for given file format.
Handles deferred import of required backend.
"""
if
format
not
in
_default_backends
:
return
None
backend_class
=
_default_backends
[
format
]
if
cbook
.
is_string_like
(
backend_class
):
backend_class
=
import_module
(
backend_class
).
FigureCanvas
_default_backends
[
format
]
=
backend_class
return
backend_class
class
ShowBase
(
object
):
"""
Simple base class to generate a show() callable in backends.
Subclass must override mainloop() method.
"""
def
__call__
(
self
,
block
=
None
):
"""
Show all figures. If *block* is not None, then
it is a boolean that overrides all other factors
determining whether show blocks by calling mainloop().
The other factors are:
it does not block if run inside ipython's "%pylab" mode
it does not block in interactive mode.
"""
managers
=
Gcf
.
get_all_fig_managers
()
if
not
managers
:
return
for
manager
in
managers
:
manager
.
show
()
if
block
is
not
None
:
if
block
:
self
.
mainloop
()
return
else
:
return
# Hack: determine at runtime whether we are
# inside ipython in pylab mode.
from
matplotlib
import
pyplot
try
:
ipython_pylab
=
not
pyplot
.
show
.
_needmain
# IPython versions >= 0.10 tack the _needmain
# attribute onto pyplot.show, and always set
# it to False, when in %pylab mode.
ipython_pylab
=
ipython_pylab
and
get_backend
()
!=
'WebAgg'
# TODO: The above is a hack to get the WebAgg backend
# working with ipython's `%pylab` mode until proper
# integration is implemented.
except
AttributeError
:
ipython_pylab
=
False
# Leave the following as a separate step in case we
# want to control this behavior with an rcParam.
if
ipython_pylab
:
return
if
not
is_interactive
()
or
get_backend
()
==
'WebAgg'
:
self
.
mainloop
()
def
mainloop
(
self
):
pass
class
RendererBase
(
object
):
"""An abstract base class to handle drawing/rendering operations.
The following methods must be implemented in the backend for full
functionality (though just implementing :meth:`draw_path` alone would
give a highly capable backend):
* :meth:`draw_path`
* :meth:`draw_image`
* :meth:`draw_gouraud_triangle`
The following methods *should* be implemented in the backend for
optimization reasons:
* :meth:`draw_text`
* :meth:`draw_markers`
* :meth:`draw_path_collection`
* :meth:`draw_quad_mesh`
"""
def
__init__
(
self
):
self
.
_texmanager
=
None
self
.
_text2path
=
textpath
.
TextToPath
()
def
open_group
(
self
,
s
,
gid
=
None
):
"""
Open a grouping element with label *s*. If *gid* is given, use
*gid* as the id of the group. Is only currently used by
:mod:`~matplotlib.backends.backend_svg`.
"""
pass
def
close_group
(
self
,
s
):
"""
Close a grouping element with label *s*
Is only currently used by :mod:`~matplotlib.backends.backend_svg`
"""
pass
def
draw_path
(
self
,
gc
,
path
,
transform
,
rgbFace
=
None
):
"""
Draws a :class:`~matplotlib.path.Path` instance using the
given affine transform.
"""
raise
NotImplementedError
def
draw_markers
(
self
,
gc
,
marker_path
,
marker_trans
,
path
,
trans
,
rgbFace
=
None
):
"""
Draws a marker at each of the vertices in path. This includes
all vertices, including control points on curves. To avoid
that behavior, those vertices should be removed before calling
this function.
*gc*
the :class:`GraphicsContextBase` instance
*marker_trans*
is an affine transform applied to the marker.
*trans*
is an affine transform applied to the path.
This provides a fallback implementation of draw_markers that
makes multiple calls to :meth:`draw_path`. Some backends may
want to override this method in order to draw the marker only
once and reuse it multiple times.
"""
for
vertices
,
codes
in
path
.
iter_segments
(
trans
,
simplify
=
False
):
if
len
(
vertices
):
x
,
y
=
vertices
[
-
2
:]
self
.
draw_path
(
gc
,
marker_path
,
marker_trans
+
transforms
.
Affine2D
().
translate
(
x
,
y
),
rgbFace
)
def
draw_path_collection
(
self
,
gc
,
master_transform
,
paths
,
all_transforms
,
offsets
,
offsetTrans
,
facecolors
,
edgecolors
,
linewidths
,
linestyles
,
antialiaseds
,
urls
,
offset_position
):
"""
Draws a collection of paths selecting drawing properties from
the lists *facecolors*, *edgecolors*, *linewidths*,
*linestyles* and *antialiaseds*. *offsets* is a list of
offsets to apply to each of the paths. The offsets in
*offsets* are first transformed by *offsetTrans* before being
applied. *offset_position* may be either "screen" or "data"
depending on the space that the offsets are in.
This provides a fallback implementation of
:meth:`draw_path_collection` that makes multiple calls to
:meth:`draw_path`. Some backends may want to override this in
order to render each set of path data only once, and then
reference that path multiple times with the different offsets,
colors, styles etc. The generator methods
:meth:`_iter_collection_raw_paths` and
:meth:`_iter_collection` are provided to help with (and
standardize) the implementation across backends. It is highly
recommended to use those generators, so that changes to the
behavior of :meth:`draw_path_collection` can be made globally.
"""
path_ids
=
[]
for
path
,
transform
in
self
.
_iter_collection_raw_paths
(
master_transform
,
paths
,
all_transforms
):
path_ids
.
append
((
path
,
transforms
.
Affine2D
(
transform
)))
for
xo
,
yo
,
path_id
,
gc0
,
rgbFace
in
self
.
_iter_collection
(
gc
,
master_transform
,
all_transforms
,
path_ids
,
offsets
,
offsetTrans
,
facecolors
,
edgecolors
,
linewidths
,
linestyles
,
antialiaseds
,
urls
,
offset_position
):
path
,
transform
=
path_id
transform
=
transforms
.
Affine2D
(
transform
.
get_matrix
()).
translate
(
xo
,
yo
)
self
.
draw_path
(
gc0
,
path
,
transform
,
rgbFace
)
def
draw_quad_mesh
(
self
,
gc
,
master_transform
,
meshWidth
,
meshHeight
,
coordinates
,
offsets
,
offsetTrans
,
facecolors
,
antialiased
,
edgecolors
):
"""
This provides a fallback implementation of
:meth:`draw_quad_mesh` that generates paths and then calls
:meth:`draw_path_collection`.
"""
from
matplotlib
.
collections
import
QuadMesh
paths
=
QuadMesh
.
convert_mesh_to_paths
(
meshWidth
,
meshHeight
,
coordinates
)
if
edgecolors
is
None
:
edgecolors
=
facecolors
linewidths
=
np
.
array
([
gc
.
get_linewidth
()],
np
.
float_
)
return
self
.
draw_path_collection
(
gc
,
master_transform
,
paths
, [],
offsets
,
offsetTrans
,
facecolors
,
edgecolors
,
linewidths
, [], [
antialiased
], [
None
],
'screen'
)
def
draw_gouraud_triangle
(
self
,
gc
,
points
,
colors
,
transform
):
"""
Draw a Gouraud-shaded triangle.
*points* is a 3x2 array of (x, y) points for the triangle.
*colors* is a 3x4 array of RGBA colors for each point of the
triangle.
*transform* is an affine transform to apply to the points.
"""
raise
NotImplementedError
def
draw_gouraud_triangles
(
self
,
gc
,
triangles_array
,
colors_array
,
transform
):
"""
Draws a series of Gouraud triangles.
*points* is a Nx3x2 array of (x, y) points for the trianglex.
*colors* is a Nx3x4 array of RGBA colors for each point of the
triangles.
*transform* is an affine transform to apply to the points.
"""
transform
=
transform
.
frozen
()
for
tri
,
col
in
zip
(
triangles_array
,
colors_array
):
self
.
draw_gouraud_triangle
(
gc
,
tri
,
col
,
transform
)
def
_iter_collection_raw_paths
(
self
,
master_transform
,
paths
,
all_transforms
):
"""
This is a helper method (along with :meth:`_iter_collection`) to make
it easier to write a space-efficent :meth:`draw_path_collection`
implementation in a backend.
This method yields all of the base path/transform
combinations, given a master transform, a list of paths and
list of transforms.
The arguments should be exactly what is passed in to
:meth:`draw_path_collection`.
The backend should take each yielded path and transform and
create an object that can be referenced (reused) later.
"""
Npaths
=
len
(
paths
)
Ntransforms
=
len
(
all_transforms
)
N
=
max
(
Npaths
,
Ntransforms
)
if
Npaths
==
0
:
return
transform
=
transforms
.
IdentityTransform
()
for
i
in
xrange
(
N
):
path
=
paths
[
i
%
Npaths
]
if
Ntransforms
:
transform
=
Affine2D
(
all_transforms
[
i
%
Ntransforms
])
yield
path
,
transform
+
master_transform
def
_iter_collection_uses_per_path
(
self
,
paths
,
all_transforms
,
offsets
,
facecolors
,
edgecolors
):
"""
Compute how many times each raw path object returned by
_iter_collection_raw_paths would be used when calling
_iter_collection. This is intended for the backend to decide
on the tradeoff between using the paths in-line and storing
them once and reusing. Rounds up in case the number of uses
is not the same for every path.
"""
Npaths
=
len
(
paths
)
if
Npaths
==
0
or
(
len
(
facecolors
)
==
0
and
len
(
edgecolors
)
==
0
):
return
0
Npath_ids
=
max
(
Npaths
,
len
(
all_transforms
))
N
=
max
(
Npath_ids
,
len
(
offsets
))
return
(
N
+
Npath_ids
-
1
)
//
Npath_ids
def
_iter_collection
(
self
,
gc
,
master_transform
,
all_transforms
,
path_ids
,
offsets
,
offsetTrans
,
facecolors
,
edgecolors
,
linewidths
,
linestyles
,
antialiaseds
,
urls
,
offset_position
):
"""
This is a helper method (along with
:meth:`_iter_collection_raw_paths`) to make it easier to write
a space-efficent :meth:`draw_path_collection` implementation in a
backend.
This method yields all of the path, offset and graphics
context combinations to draw the path collection. The caller
should already have looped over the results of
:meth:`_iter_collection_raw_paths` to draw this collection.
The arguments should be the same as that passed into
:meth:`draw_path_collection`, with the exception of
*path_ids*, which is a list of arbitrary objects that the
backend will use to reference one of the paths created in the
:meth:`_iter_collection_raw_paths` stage.
Each yielded result is of the form::
xo, yo, path_id, gc, rgbFace
where *xo*, *yo* is an offset; *path_id* is one of the elements of
*path_ids*; *gc* is a graphics context and *rgbFace* is a color to
use for filling the path.
"""
Ntransforms
=
len
(
all_transforms
)
Npaths
=
len
(
path_ids
)
Noffsets
=
len
(
offsets
)
N
=
max
(
Npaths
,
Noffsets
)
Nfacecolors
=
len
(
facecolors
)
Nedgecolors
=
len
(
edgecolors
)
Nlinewidths
=
len
(
linewidths
)
Nlinestyles
=
len
(
linestyles
)
Naa
=
len
(
antialiaseds
)
Nurls
=
len
(
urls
)
if
(
Nfacecolors
==
0
and
Nedgecolors
==
0
)
or
Npaths
==
0
:
return
if
Noffsets
:
toffsets
=
offsetTrans
.
transform
(
offsets
)
gc0
=
self
.
new_gc
()
gc0
.
copy_properties
(
gc
)
if
Nfacecolors
==
0
:
rgbFace
=
None
if
Nedgecolors
==
0
:
gc0
.
set_linewidth
(
0.0
)
xo
,
yo
=
0
,
0
for
i
in
xrange
(
N
):
path_id
=
path_ids
[
i
%
Npaths
]
if
Noffsets
:
xo
,
yo
=
toffsets
[
i
%
Noffsets
]
if
offset_position
==
'data'
:
if
Ntransforms
:
transform
=
(
Affine2D
(
all_transforms
[
i
%
Ntransforms
])
+
master_transform
)
else
:
transform
=
master_transform
xo
,
yo
=
transform
.
transform_point
((
xo
,
yo
))
xp
,
yp
=
transform
.
transform_point
((
0
,
0
))
xo
=
-
(
xp
-
xo
)
yo
=
-
(
yp
-
yo
)
if
not
(
np
.
isfinite
(
xo
)
and
np
.
isfinite
(
yo
)):
continue
if
Nfacecolors
:
rgbFace
=
facecolors
[
i
%
Nfacecolors
]
if
Nedgecolors
:
if
Nlinewidths
:
gc0
.
set_linewidth
(
linewidths
[
i
%
Nlinewidths
])
if
Nlinestyles
:
gc0
.
set_dashes
(
*
linestyles
[
i
%
Nlinestyles
])
fg
=
edgecolors
[
i
%
Nedgecolors
]
if
len
(
fg
)
==
4
:
if
fg
[
3
]
==
0.0
:
gc0
.
set_linewidth
(
0
)
else
:
gc0
.
set_foreground
(
fg
)
else
:
gc0
.
set_foreground
(
fg
)
if
rgbFace
is
not
None
and
len
(
rgbFace
)
==
4
:
if
rgbFace
[
3
]
==
0
:
rgbFace
=
None
gc0
.
set_antialiased
(
antialiaseds
[
i
%
Naa
])
if
Nurls
:
gc0
.
set_url
(
urls
[
i
%
Nurls
])
yield
xo
,
yo
,
path_id
,
gc0
,
rgbFace
gc0
.
restore
()
def
get_image_magnification
(
self
):
"""
Get the factor by which to magnify images passed to :meth:`draw_image`.
Allows a backend to have images at a different resolution to other
artists.
"""
return
1.0
def
draw_image
(
self
,
gc
,
x
,
y
,
im
):
"""
Draw the image instance into the current axes;
*gc*
a GraphicsContext containing clipping information
*x*
is the distance in pixels from the left hand side of the canvas.
*y*
the distance from the origin. That is, if origin is
upper, y is the distance from top. If origin is lower, y
is the distance from bottom
*im*
the :class:`matplotlib._image.Image` instance
"""
raise
NotImplementedError
def
option_image_nocomposite
(
self
):
"""
override this method for renderers that do not necessarily always
want to rescale and composite raster images. (like SVG, PDF, or PS)
"""
return
False
def
option_scale_image
(
self
):
"""
override this method for renderers that support arbitrary
scaling of image (most of the vector backend).
"""
return
False
def
draw_tex
(
self
,
gc
,
x
,
y
,
s
,
prop
,
angle
,
ismath
=
'TeX!'
,
mtext
=
None
):
"""
"""
self
.
_draw_text_as_path
(
gc
,
x
,
y
,
s
,
prop
,
angle
,
ismath
=
"TeX"
)
def
draw_text
(
self
,
gc
,
x
,
y
,
s
,
prop
,
angle
,
ismath
=
False
,
mtext
=
None
):
"""
Draw the text instance
*gc*
the :class:`GraphicsContextBase` instance
*x*
the x location of the text in display coords
*y*
the y location of the text baseline in display coords
*s*
the text string
*prop*
a :class:`matplotlib.font_manager.FontProperties` instance
*angle*
the rotation angle in degrees
*mtext*
a :class:`matplotlib.text.Text` instance
**backend implementers note**
When you are trying to determine if you have gotten your bounding box
right (which is what enables the text layout/alignment to work
properly), it helps to change the line in text.py::
if 0: bbox_artist(self, renderer)
to if 1, and then the actual bounding box will be plotted along with
your text.
"""
self
.
_draw_text_as_path
(
gc
,
x
,
y
,
s
,
prop
,
angle
,
ismath
)
def
_get_text_path_transform
(
self
,
x
,
y
,
s
,
prop
,
angle
,
ismath
):
"""
return the text path and transform
*prop*
font property
*s*
text to be converted
*usetex*
If True, use matplotlib usetex mode.
*ismath*
If True, use mathtext parser. If "TeX", use *usetex* mode.
"""
text2path
=
self
.
_text2path
fontsize
=
self
.
points_to_pixels
(
prop
.
get_size_in_points
())
if
ismath
==
"TeX"
:
verts
,
codes
=
text2path
.
get_text_path
(
prop
,
s
,
ismath
=
False
,
usetex
=
True
)
else
:
verts
,
codes
=
text2path
.
get_text_path
(
prop
,
s
,
ismath
=
ismath
,
usetex
=
False
)
path
=
Path
(
verts
,
codes
)
angle
=
angle
/
180.
*
3.141592
if
self
.
flipy
():
transform
=
Affine2D
().
scale
(
fontsize
/
text2path
.
FONT_SCALE
,
fontsize
/
text2path
.
FONT_SCALE
)
transform
=
transform
.
rotate
(
angle
).
translate
(
x
,
self
.
height
-
y
)
else
:
transform
=
Affine2D
().
scale
(
fontsize
/
text2path
.
FONT_SCALE
,
fontsize
/
text2path
.
FONT_SCALE
)
transform
=
transform
.
rotate
(
angle
).
translate
(
x
,
y
)
return
path
,
transform
def
_draw_text_as_path
(
self
,
gc
,
x
,
y
,
s
,
prop
,
angle
,
ismath
):
"""
draw the text by converting them to paths using textpath module.
*prop*
font property
*s*
text to be converted
*usetex*
If True, use matplotlib usetex mode.
*ismath*
If True, use mathtext parser. If "TeX", use *usetex* mode.
"""
path
,
transform
=
self
.
_get_text_path_transform
(
x
,
y
,
s
,
prop
,
angle
,
ismath
)
color
=
gc
.
get_rgb
()
gc
.
set_linewidth
(
0.0
)
self
.
draw_path
(
gc
,
path
,
transform
,
rgbFace
=
color
)
def
get_text_width_height_descent
(
self
,
s
,
prop
,
ismath
):
"""
get the width and height, and the offset from the bottom to the
baseline (descent), in display coords of the string s with
:class:`~matplotlib.font_manager.FontProperties` prop
"""
if
ismath
==
'TeX'
:
# todo: handle props
size
=
prop
.
get_size_in_points
()
texmanager
=
self
.
_text2path
.
get_texmanager
()
fontsize
=
prop
.
get_size_in_points
()
w
,
h
,
d
=
texmanager
.
get_text_width_height_descent
(
s
,
fontsize
,
renderer
=
self
)
return
w
,
h
,
d
dpi
=
self
.
points_to_pixels
(
72
)
if
ismath
:
dims
=
self
.
_text2path
.
mathtext_parser
.
parse
(
s
,
dpi
,
prop
)
return
dims
[
0
:
3
]
# return width, height, descent
flags
=
self
.
_text2path
.
_get_hinting_flag
()
font
=
self
.
_text2path
.
_get_font
(
prop
)
size
=
prop
.
get_size_in_points
()
font
.
set_size
(
size
,
dpi
)
# the width and height of unrotated string
font
.
set_text
(
s
,
0.0
,
flags
=
flags
)
w
,
h
=
font
.
get_width_height
()
d
=
font
.
get_descent
()
w
/=
64.0
# convert from subpixels
h
/=
64.0
d
/=
64.0
return
w
,
h
,
d
def
flipy
(
self
):
"""
Return true if y small numbers are top for renderer Is used
for drawing text (:mod:`matplotlib.text`) and images
(:mod:`matplotlib.image`) only
"""
return
True
def
get_canvas_width_height
(
self
):
'return the canvas width and height in display coords'
return
1
,
1
def
get_texmanager
(
self
):
"""
return the :class:`matplotlib.texmanager.TexManager` instance
"""
if
self
.
_texmanager
is
None
:
from
matplotlib
.
texmanager
import
TexManager
self
.
_texmanager
=
TexManager
()
return
self
.
_texmanager
def
new_gc
(
self
):
"""
Return an instance of a :class:`GraphicsContextBase`
"""
return
GraphicsContextBase
()
def
points_to_pixels
(
self
,
points
):
"""
Convert points to display units
*points*
a float or a numpy array of float
return points converted to pixels
You need to override this function (unless your backend
doesn't have a dpi, e.g., postscript or svg). Some imaging
systems assume some value for pixels per inch::
points to pixels = points * pixels_per_inch/72.0 * dpi/72.0
"""
return
points
def
strip_math
(
self
,
s
):
return
cbook
.
strip_math
(
s
)
def
start_rasterizing
(
self
):
"""
Used in MixedModeRenderer. Switch to the raster renderer.
"""
pass
def
stop_rasterizing
(
self
):
"""
Used in MixedModeRenderer. Switch back to the vector renderer
and draw the contents of the raster renderer as an image on
the vector renderer.
"""
pass
def
start_filter
(
self
):
"""
Used in AggRenderer. Switch to a temporary renderer for image
filtering effects.
"""
pass
def
stop_filter
(
self
,
filter_func
):
"""
Used in AggRenderer. Switch back to the original renderer.
The contents of the temporary renderer is processed with the
*filter_func* and is drawn on the original renderer as an
image.
"""
pass
class
GraphicsContextBase
(
object
):
"""
An abstract base class that provides color, line styles, etc...
"""
# a mapping from dash styles to suggested offset, dash pairs
dashd
=
{
'solid'
: (
None
,
None
),
'dashed'
: (
0
, (
6.0
,
6.0
)),
'dashdot'
: (
0
, (
3.0
,
5.0
,
1.0
,
5.0
)),
'dotted'
: (
0
, (
1.0
,
3.0
)),
}
def
__init__
(
self
):
self
.
_alpha
=
1.0
self
.
_forced_alpha
=
False
# if True, _alpha overrides A from RGBA
self
.
_antialiased
=
1
# use 0,1 not True, False for extension code
self
.
_capstyle
=
'butt'
self
.
_cliprect
=
None
self
.
_clippath
=
None
self
.
_dashes
=
None
,
None
self
.
_joinstyle
=
'round'
self
.
_linestyle
=
'solid'
self
.
_linewidth
=
1
self
.
_rgb
=
(
0.0
,
0.0
,
0.0
,
1.0
)
self
.
_hatch
=
None
self
.
_url
=
None
self
.
_gid
=
None
self
.
_snap
=
None
self
.
_sketch
=
None
def
copy_properties
(
self
,
gc
):
'Copy properties from gc to self'
self
.
_alpha
=
gc
.
_alpha
self
.
_forced_alpha
=
gc
.
_forced_alpha
self
.
_antialiased
=
gc
.
_antialiased
self
.
_capstyle
=
gc
.
_capstyle
self
.
_cliprect
=
gc
.
_cliprect
self
.
_clippath
=
gc
.
_clippath
self
.
_dashes
=
gc
.
_dashes
self
.
_joinstyle
=
gc
.
_joinstyle
self
.
_linestyle
=
gc
.
_linestyle
self
.
_linewidth
=
gc
.
_linewidth
self
.
_rgb
=
gc
.
_rgb
self
.
_hatch
=
gc
.
_hatch
self
.
_url
=
gc
.
_url
self
.
_gid
=
gc
.
_gid
self
.
_snap
=
gc
.
_snap
self
.
_sketch
=
gc
.
_sketch
def
restore
(
self
):
"""
Restore the graphics context from the stack - needed only
for backends that save graphics contexts on a stack
"""
pass
def
get_alpha
(
self
):
"""
Return the alpha value used for blending - not supported on
all backends
"""
return
self
.
_alpha
def
get_antialiased
(
self
):
"Return true if the object should try to do antialiased rendering"
return
self
.
_antialiased
def
get_capstyle
(
self
):
"""
Return the capstyle as a string in ('butt', 'round', 'projecting')
"""
return
self
.
_capstyle
def
get_clip_rectangle
(
self
):
"""
Return the clip rectangle as a :class:`~matplotlib.transforms.Bbox`
instance
"""
return
self
.
_cliprect
def
get_clip_path
(
self
):
"""
Return the clip path in the form (path, transform), where path
is a :class:`~matplotlib.path.Path` instance, and transform is
an affine transform to apply to the path before clipping.
"""
if
self
.
_clippath
is
not
None
:
return
self
.
_clippath
.
get_transformed_path_and_affine
()
return
None
,
None
def
get_dashes
(
self
):
"""
Return the dash information as an offset dashlist tuple.
The dash list is a even size list that gives the ink on, ink
off in pixels.
See p107 of to PostScript `BLUEBOOK
<http://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF>`_
for more info.
Default value is None
"""
return
self
.
_dashes
def
get_forced_alpha
(
self
):
"""
Return whether the value given by get_alpha() should be used to
override any other alpha-channel values.
"""
return
self
.
_forced_alpha
def
get_joinstyle
(
self
):
"""
Return the line join style as one of ('miter', 'round', 'bevel')
"""
return
self
.
_joinstyle
def
get_linestyle
(
self
,
style
):
"""
Return the linestyle: one of ('solid', 'dashed', 'dashdot',
'dotted').
"""
return
self
.
_linestyle
def
get_linewidth
(
self
):
"""
Return the line width in points as a scalar
"""
return
self
.
_linewidth
def
get_rgb
(
self
):
"""
returns a tuple of three or four floats from 0-1.
"""
return
self
.
_rgb
def
get_url
(
self
):
"""
returns a url if one is set, None otherwise
"""
return
self
.
_url
def
get_gid
(
self
):
"""
Return the object identifier if one is set, None otherwise.
"""
return
self
.
_gid
def
get_snap
(
self
):
"""
returns the snap setting which may be:
* True: snap vertices to the nearest pixel center
* False: leave vertices as-is
* None: (auto) If the path contains only rectilinear line
segments, round to the nearest pixel center
"""
return
self
.
_snap
def
set_alpha
(
self
,
alpha
):
"""
Set the alpha value used for blending - not supported on all backends.
If ``alpha=None`` (the default), the alpha components of the
foreground and fill colors will be used to set their respective
transparencies (where applicable); otherwise, ``alpha`` will override
them.
"""
if
alpha
is
not
None
:
self
.
_alpha
=
alpha
self
.
_forced_alpha
=
True
else
:
self
.
_alpha
=
1.0
self
.
_forced_alpha
=
False
self
.
set_foreground
(
self
.
_rgb
,
isRGBA
=
True
)
def
set_antialiased
(
self
,
b
):
"""
True if object should be drawn with antialiased rendering
"""
# use 0, 1 to make life easier on extension code trying to read the gc
if
b
:
self
.
_antialiased
=
1
else
:
self
.
_antialiased
=
0
def
set_capstyle
(
self
,
cs
):
"""
Set the capstyle as a string in ('butt', 'round', 'projecting')
"""
if
cs
in
(
'butt'
,
'round'
,
'projecting'
):
self
.
_capstyle
=
cs
else
:
raise
ValueError
(
'Unrecognized cap style. Found %s'
%
cs
)
def
set_clip_rectangle
(
self
,
rectangle
):
"""
Set the clip rectangle with sequence (left, bottom, width, height)
"""
self
.
_cliprect
=
rectangle
def
set_clip_path
(
self
,
path
):
"""
Set the clip path and transformation. Path should be a
:class:`~matplotlib.transforms.TransformedPath` instance.
"""
if
path
is
not
None
and
not
isinstance
(
path
,
transforms
.
TransformedPath
):
msg
=
(
"Path should be a matplotlib.transforms.TransformedPath"
"instance."
)
raise
ValueError
(
msg
)
self
.
_clippath
=
path
def
set_dashes
(
self
,
dash_offset
,
dash_list
):
"""
Set the dash style for the gc.
*dash_offset*
is the offset (usually 0).
*dash_list*
specifies the on-off sequence as points.
``(None, None)`` specifies a solid line
"""
if
dash_list
is
not
None
:
dl
=
np
.
asarray
(
dash_list
)
if
np
.
any
(
dl
<=
0.0
):
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL