-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
text.py
2067 lines (1711 loc) · 69.3 KB
/
text.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
"""
Classes for including text in a figure.
"""
import functools
import logging
import math
from numbers import Real
import weakref
import numpy as np
import matplotlib as mpl
from . import _api, artist, cbook, _docstring
from .artist import Artist
from .font_manager import FontProperties
from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle
from .textpath import TextPath, TextToPath # noqa # Logically located here
from .transforms import (
Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform)
_log = logging.getLogger(__name__)
@_api.deprecated("3.6")
def get_rotation(rotation):
"""
Return *rotation* normalized to an angle between 0 and 360 degrees.
Parameters
----------
rotation : float or {None, 'horizontal', 'vertical'}
Rotation angle in degrees. *None* and 'horizontal' equal 0,
'vertical' equals 90.
Returns
-------
float
"""
try:
return float(rotation) % 360
except (ValueError, TypeError) as err:
if cbook._str_equal(rotation, 'horizontal') or rotation is None:
return 0.
elif cbook._str_equal(rotation, 'vertical'):
return 90.
else:
raise ValueError("rotation is {!r}; expected either 'horizontal', "
"'vertical', numeric value, or None"
.format(rotation)) from err
def _get_textbox(text, renderer):
"""
Calculate the bounding box of the text.
The bbox position takes text rotation into account, but the width and
height are those of the unrotated box (unlike `.Text.get_window_extent`).
"""
# TODO : This function may move into the Text class as a method. As a
# matter of fact, the information from the _get_textbox function
# should be available during the Text._get_layout() call, which is
# called within the _get_textbox. So, it would better to move this
# function as a method with some refactoring of _get_layout method.
projected_xs = []
projected_ys = []
theta = np.deg2rad(text.get_rotation())
tr = Affine2D().rotate(-theta)
_, parts, d = text._get_layout(renderer)
for t, wh, x, y in parts:
w, h = wh
xt1, yt1 = tr.transform((x, y))
yt1 -= d
xt2, yt2 = xt1 + w, yt1 + h
projected_xs.extend([xt1, xt2])
projected_ys.extend([yt1, yt2])
xt_box, yt_box = min(projected_xs), min(projected_ys)
w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box
x_box, y_box = Affine2D().rotate(theta).transform((xt_box, yt_box))
return x_box, y_box, w_box, h_box
def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi):
"""Call ``renderer.get_text_width_height_descent``, caching the results."""
# Cached based on a copy of fontprop so that later in-place mutations of
# the passed-in argument do not mess up the cache.
return _get_text_metrics_with_cache_impl(
weakref.ref(renderer), text, fontprop.copy(), ismath, dpi)
@functools.lru_cache(4096)
def _get_text_metrics_with_cache_impl(
renderer_ref, text, fontprop, ismath, dpi):
# dpi is unused, but participates in cache invalidation (via the renderer).
return renderer_ref().get_text_width_height_descent(text, fontprop, ismath)
@_docstring.interpd
@_api.define_aliases({
"color": ["c"],
"fontfamily": ["family"],
"fontproperties": ["font", "font_properties"],
"horizontalalignment": ["ha"],
"multialignment": ["ma"],
"fontname": ["name"],
"fontsize": ["size"],
"fontstretch": ["stretch"],
"fontstyle": ["style"],
"fontvariant": ["variant"],
"verticalalignment": ["va"],
"fontweight": ["weight"],
})
class Text(Artist):
"""Handle storing and drawing of text in window or data coordinates."""
zorder = 3
_charsize_cache = dict()
def __repr__(self):
return "Text(%s, %s, %s)" % (self._x, self._y, repr(self._text))
@_api.make_keyword_only("3.6", name="color")
def __init__(self,
x=0, y=0, text='',
color=None, # defaults to rc params
verticalalignment='baseline',
horizontalalignment='left',
multialignment=None,
fontproperties=None, # defaults to FontProperties()
rotation=None,
linespacing=None,
rotation_mode=None,
usetex=None, # defaults to rcParams['text.usetex']
wrap=False,
transform_rotates_text=False,
*,
parse_math=None, # defaults to rcParams['text.parse_math']
**kwargs
):
"""
Create a `.Text` instance at *x*, *y* with string *text*.
The text is aligned relative to the anchor point (*x*, *y*) according
to ``horizontalalignment`` (default: 'left') and ``verticalalignment``
(default: 'bottom'). See also
:doc:`/gallery/text_labels_and_annotations/text_alignment`.
While Text accepts the 'label' keyword argument, by default it is not
added to the handles of a legend.
Valid keyword arguments are:
%(Text:kwdoc)s
"""
super().__init__()
self._x, self._y = x, y
self._text = ''
self._reset_visual_defaults(
text=text,
color=color,
fontproperties=fontproperties,
usetex=usetex,
parse_math=parse_math,
wrap=wrap,
verticalalignment=verticalalignment,
horizontalalignment=horizontalalignment,
multialignment=multialignment,
rotation=rotation,
transform_rotates_text=transform_rotates_text,
linespacing=linespacing,
rotation_mode=rotation_mode,
)
self.update(kwargs)
def _reset_visual_defaults(
self,
text='',
color=None,
fontproperties=None,
usetex=None,
parse_math=None,
wrap=False,
verticalalignment='baseline',
horizontalalignment='left',
multialignment=None,
rotation=None,
transform_rotates_text=False,
linespacing=None,
rotation_mode=None,
):
self.set_text(text)
self.set_color(
color if color is not None else mpl.rcParams["text.color"])
self.set_fontproperties(fontproperties)
self.set_usetex(usetex)
self.set_parse_math(parse_math if parse_math is not None else
mpl.rcParams['text.parse_math'])
self.set_wrap(wrap)
self.set_verticalalignment(verticalalignment)
self.set_horizontalalignment(horizontalalignment)
self._multialignment = multialignment
self.set_rotation(rotation)
self._transform_rotates_text = transform_rotates_text
self._bbox_patch = None # a FancyBboxPatch instance
self._renderer = None
if linespacing is None:
linespacing = 1.2 # Maybe use rcParam later.
self.set_linespacing(linespacing)
self.set_rotation_mode(rotation_mode)
def update(self, kwargs):
# docstring inherited
kwargs = cbook.normalize_kwargs(kwargs, Text)
sentinel = object() # bbox can be None, so use another sentinel.
# Update fontproperties first, as it has lowest priority.
fontproperties = kwargs.pop("fontproperties", sentinel)
if fontproperties is not sentinel:
self.set_fontproperties(fontproperties)
# Update bbox last, as it depends on font properties.
bbox = kwargs.pop("bbox", sentinel)
super().update(kwargs)
if bbox is not sentinel:
self.set_bbox(bbox)
def __getstate__(self):
d = super().__getstate__()
# remove the cached _renderer (if it exists)
d['_renderer'] = None
return d
def contains(self, mouseevent):
"""
Return whether the mouse event occurred inside the axis-aligned
bounding-box of the text.
"""
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
if not self.get_visible() or self._renderer is None:
return False, {}
# Explicitly use Text.get_window_extent(self) and not
# self.get_window_extent() so that Annotation.contains does not
# accidentally cover the entire annotation bounding box.
bbox = Text.get_window_extent(self)
inside = (bbox.x0 <= mouseevent.x <= bbox.x1
and bbox.y0 <= mouseevent.y <= bbox.y1)
cattr = {}
# if the text has a surrounding patch, also check containment for it,
# and merge the results with the results for the text.
if self._bbox_patch:
patch_inside, patch_cattr = self._bbox_patch.contains(mouseevent)
inside = inside or patch_inside
cattr["bbox_patch"] = patch_cattr
return inside, cattr
def _get_xy_display(self):
"""
Get the (possibly unit converted) transformed x, y in display coords.
"""
x, y = self.get_unitless_position()
return self.get_transform().transform((x, y))
def _get_multialignment(self):
if self._multialignment is not None:
return self._multialignment
else:
return self._horizontalalignment
def _char_index_at(self, x):
"""
Calculate the index closest to the coordinate x in display space.
The position of text[index] is assumed to be the sum of the widths
of all preceding characters text[:index].
This works only on single line texts.
"""
if not self._text:
return 0
text = self._text
fontproperties = str(self._fontproperties)
if fontproperties not in Text._charsize_cache:
Text._charsize_cache[fontproperties] = dict()
charsize_cache = Text._charsize_cache[fontproperties]
for char in set(text):
if char not in charsize_cache:
self.set_text(char)
bb = self.get_window_extent()
charsize_cache[char] = bb.x1 - bb.x0
self.set_text(text)
bb = self.get_window_extent()
size_accum = np.cumsum([0] + [charsize_cache[x] for x in text])
std_x = x - bb.x0
return (np.abs(size_accum - std_x)).argmin()
def get_rotation(self):
"""Return the text angle in degrees between 0 and 360."""
if self.get_transform_rotates_text():
return self.get_transform().transform_angles(
[self._rotation], [self.get_unitless_position()]).item(0)
else:
return self._rotation
def get_transform_rotates_text(self):
"""
Return whether rotations of the transform affect the text direction.
"""
return self._transform_rotates_text
def set_rotation_mode(self, m):
"""
Set text rotation mode.
Parameters
----------
m : {None, 'default', 'anchor'}
If ``None`` or ``"default"``, the text will be first rotated, then
aligned according to their horizontal and vertical alignments. If
``"anchor"``, then alignment occurs before rotation.
"""
_api.check_in_list(["anchor", "default", None], rotation_mode=m)
self._rotation_mode = m
self.stale = True
def get_rotation_mode(self):
"""Return the text rotation mode."""
return self._rotation_mode
def update_from(self, other):
# docstring inherited
super().update_from(other)
self._color = other._color
self._multialignment = other._multialignment
self._verticalalignment = other._verticalalignment
self._horizontalalignment = other._horizontalalignment
self._fontproperties = other._fontproperties.copy()
self._usetex = other._usetex
self._rotation = other._rotation
self._transform_rotates_text = other._transform_rotates_text
self._picker = other._picker
self._linespacing = other._linespacing
self.stale = True
def _get_layout(self, renderer):
"""
Return the extent (bbox) of the text together with
multiple-alignment information. Note that it returns an extent
of a rotated text when necessary.
"""
thisx, thisy = 0.0, 0.0
lines = self._get_wrapped_text().split("\n") # Ensures lines is not empty.
ws = []
hs = []
xs = []
ys = []
# Full vertical extent of font, including ascenders and descenders:
_, lp_h, lp_d = _get_text_metrics_with_cache(
renderer, "lp", self._fontproperties,
ismath="TeX" if self.get_usetex() else False, dpi=self.figure.dpi)
min_dy = (lp_h - lp_d) * self._linespacing
for i, line in enumerate(lines):
clean_line, ismath = self._preprocess_math(line)
if clean_line:
w, h, d = _get_text_metrics_with_cache(
renderer, clean_line, self._fontproperties,
ismath=ismath, dpi=self.figure.dpi)
else:
w = h = d = 0
# For multiline text, increase the line spacing when the text
# net-height (excluding baseline) is larger than that of a "l"
# (e.g., use of superscripts), which seems what TeX does.
h = max(h, lp_h)
d = max(d, lp_d)
ws.append(w)
hs.append(h)
# Metrics of the last line that are needed later:
baseline = (h - d) - thisy
if i == 0:
# position at baseline
thisy = -(h - d)
else:
# put baseline a good distance from bottom of previous line
thisy -= max(min_dy, (h - d) * self._linespacing)
xs.append(thisx) # == 0.
ys.append(thisy)
thisy -= d
# Metrics of the last line that are needed later:
descent = d
# Bounding box definition:
width = max(ws)
xmin = 0
xmax = width
ymax = 0
ymin = ys[-1] - descent # baseline of last line minus its descent
# get the rotation matrix
M = Affine2D().rotate_deg(self.get_rotation())
# now offset the individual text lines within the box
malign = self._get_multialignment()
if malign == 'left':
offset_layout = [(x, y) for x, y in zip(xs, ys)]
elif malign == 'center':
offset_layout = [(x + width / 2 - w / 2, y)
for x, y, w in zip(xs, ys, ws)]
elif malign == 'right':
offset_layout = [(x + width - w, y)
for x, y, w in zip(xs, ys, ws)]
# the corners of the unrotated bounding box
corners_horiz = np.array(
[(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)])
# now rotate the bbox
corners_rotated = M.transform(corners_horiz)
# compute the bounds of the rotated box
xmin = corners_rotated[:, 0].min()
xmax = corners_rotated[:, 0].max()
ymin = corners_rotated[:, 1].min()
ymax = corners_rotated[:, 1].max()
width = xmax - xmin
height = ymax - ymin
# Now move the box to the target position offset the display
# bbox by alignment
halign = self._horizontalalignment
valign = self._verticalalignment
rotation_mode = self.get_rotation_mode()
if rotation_mode != "anchor":
# compute the text location in display coords and the offsets
# necessary to align the bbox with that location
if halign == 'center':
offsetx = (xmin + xmax) / 2
elif halign == 'right':
offsetx = xmax
else:
offsetx = xmin
if valign == 'center':
offsety = (ymin + ymax) / 2
elif valign == 'top':
offsety = ymax
elif valign == 'baseline':
offsety = ymin + descent
elif valign == 'center_baseline':
offsety = ymin + height - baseline / 2.0
else:
offsety = ymin
else:
xmin1, ymin1 = corners_horiz[0]
xmax1, ymax1 = corners_horiz[2]
if halign == 'center':
offsetx = (xmin1 + xmax1) / 2.0
elif halign == 'right':
offsetx = xmax1
else:
offsetx = xmin1
if valign == 'center':
offsety = (ymin1 + ymax1) / 2.0
elif valign == 'top':
offsety = ymax1
elif valign == 'baseline':
offsety = ymax1 - baseline
elif valign == 'center_baseline':
offsety = ymax1 - baseline / 2.0
else:
offsety = ymin1
offsetx, offsety = M.transform((offsetx, offsety))
xmin -= offsetx
ymin -= offsety
bbox = Bbox.from_bounds(xmin, ymin, width, height)
# now rotate the positions around the first (x, y) position
xys = M.transform(offset_layout) - (offsetx, offsety)
return bbox, list(zip(lines, zip(ws, hs), *xys.T)), descent
def set_bbox(self, rectprops):
"""
Draw a bounding box around self.
Parameters
----------
rectprops : dict with properties for `.patches.FancyBboxPatch`
The default boxstyle is 'square'. The mutation
scale of the `.patches.FancyBboxPatch` is set to the fontsize.
Examples
--------
::
t.set_bbox(dict(facecolor='red', alpha=0.5))
"""
if rectprops is not None:
props = rectprops.copy()
boxstyle = props.pop("boxstyle", None)
pad = props.pop("pad", None)
if boxstyle is None:
boxstyle = "square"
if pad is None:
pad = 4 # points
pad /= self.get_size() # to fraction of font size
else:
if pad is None:
pad = 0.3
# boxstyle could be a callable or a string
if isinstance(boxstyle, str) and "pad" not in boxstyle:
boxstyle += ",pad=%0.2f" % pad
self._bbox_patch = FancyBboxPatch(
(0, 0), 1, 1,
boxstyle=boxstyle, transform=IdentityTransform(), **props)
else:
self._bbox_patch = None
self._update_clip_properties()
def get_bbox_patch(self):
"""
Return the bbox Patch, or None if the `.patches.FancyBboxPatch`
is not made.
"""
return self._bbox_patch
def update_bbox_position_size(self, renderer):
"""
Update the location and the size of the bbox.
This method should be used when the position and size of the bbox needs
to be updated before actually drawing the bbox.
"""
if self._bbox_patch:
# don't use self.get_unitless_position here, which refers to text
# position in Text:
posx = float(self.convert_xunits(self._x))
posy = float(self.convert_yunits(self._y))
posx, posy = self.get_transform().transform((posx, posy))
x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
self._bbox_patch.set_bounds(0., 0., w_box, h_box)
self._bbox_patch.set_transform(
Affine2D()
.rotate_deg(self.get_rotation())
.translate(posx + x_box, posy + y_box))
fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
def _update_clip_properties(self):
clipprops = dict(clip_box=self.clipbox,
clip_path=self._clippath,
clip_on=self._clipon)
if self._bbox_patch:
self._bbox_patch.update(clipprops)
def set_clip_box(self, clipbox):
# docstring inherited.
super().set_clip_box(clipbox)
self._update_clip_properties()
def set_clip_path(self, path, transform=None):
# docstring inherited.
super().set_clip_path(path, transform)
self._update_clip_properties()
def set_clip_on(self, b):
# docstring inherited.
super().set_clip_on(b)
self._update_clip_properties()
def get_wrap(self):
"""Return whether the text can be wrapped."""
return self._wrap
def set_wrap(self, wrap):
"""
Set whether the text can be wrapped.
Parameters
----------
wrap : bool
Notes
-----
Wrapping does not work together with
``savefig(..., bbox_inches='tight')`` (which is also used internally
by ``%matplotlib inline`` in IPython/Jupyter). The 'tight' setting
rescales the canvas to accommodate all content and happens before
wrapping.
"""
self._wrap = wrap
def _get_wrap_line_width(self):
"""
Return the maximum line width for wrapping text based on the current
orientation.
"""
x0, y0 = self.get_transform().transform(self.get_position())
figure_box = self.get_figure().get_window_extent()
# Calculate available width based on text alignment
alignment = self.get_horizontalalignment()
self.set_rotation_mode('anchor')
rotation = self.get_rotation()
left = self._get_dist_to_box(rotation, x0, y0, figure_box)
right = self._get_dist_to_box(
(180 + rotation) % 360, x0, y0, figure_box)
if alignment == 'left':
line_width = left
elif alignment == 'right':
line_width = right
else:
line_width = 2 * min(left, right)
return line_width
def _get_dist_to_box(self, rotation, x0, y0, figure_box):
"""
Return the distance from the given points to the boundaries of a
rotated box, in pixels.
"""
if rotation > 270:
quad = rotation - 270
h1 = y0 / math.cos(math.radians(quad))
h2 = (figure_box.x1 - x0) / math.cos(math.radians(90 - quad))
elif rotation > 180:
quad = rotation - 180
h1 = x0 / math.cos(math.radians(quad))
h2 = y0 / math.cos(math.radians(90 - quad))
elif rotation > 90:
quad = rotation - 90
h1 = (figure_box.y1 - y0) / math.cos(math.radians(quad))
h2 = x0 / math.cos(math.radians(90 - quad))
else:
h1 = (figure_box.x1 - x0) / math.cos(math.radians(rotation))
h2 = (figure_box.y1 - y0) / math.cos(math.radians(90 - rotation))
return min(h1, h2)
def _get_rendered_text_width(self, text):
"""
Return the width of a given text string, in pixels.
"""
w, h, d = self._renderer.get_text_width_height_descent(
text,
self.get_fontproperties(),
False)
return math.ceil(w)
def _get_wrapped_text(self):
"""
Return a copy of the text string with new lines added so that the text
is wrapped relative to the parent figure (if `get_wrap` is True).
"""
if not self.get_wrap():
return self.get_text()
# Not fit to handle breaking up latex syntax correctly, so
# ignore latex for now.
if self.get_usetex():
return self.get_text()
# Build the line incrementally, for a more accurate measure of length
line_width = self._get_wrap_line_width()
wrapped_lines = []
# New lines in the user's text force a split
unwrapped_lines = self.get_text().split('\n')
# Now wrap each individual unwrapped line
for unwrapped_line in unwrapped_lines:
sub_words = unwrapped_line.split(' ')
# Remove items from sub_words as we go, so stop when empty
while len(sub_words) > 0:
if len(sub_words) == 1:
# Only one word, so just add it to the end
wrapped_lines.append(sub_words.pop(0))
continue
for i in range(2, len(sub_words) + 1):
# Get width of all words up to and including here
line = ' '.join(sub_words[:i])
current_width = self._get_rendered_text_width(line)
# If all these words are too wide, append all not including
# last word
if current_width > line_width:
wrapped_lines.append(' '.join(sub_words[:i - 1]))
sub_words = sub_words[i - 1:]
break
# Otherwise if all words fit in the width, append them all
elif i == len(sub_words):
wrapped_lines.append(' '.join(sub_words[:i]))
sub_words = []
break
return '\n'.join(wrapped_lines)
@artist.allow_rasterization
def draw(self, renderer):
# docstring inherited
if renderer is not None:
self._renderer = renderer
if not self.get_visible():
return
if self.get_text() == '':
return
renderer.open_group('text', self.get_gid())
with self._cm_set(text=self._get_wrapped_text()):
bbox, info, descent = self._get_layout(renderer)
trans = self.get_transform()
# don't use self.get_position here, which refers to text
# position in Text:
posx = float(self.convert_xunits(self._x))
posy = float(self.convert_yunits(self._y))
posx, posy = trans.transform((posx, posy))
if not np.isfinite(posx) or not np.isfinite(posy):
_log.warning("posx and posy should be finite values")
return
canvasw, canvash = renderer.get_canvas_width_height()
# Update the location and size of the bbox
# (`.patches.FancyBboxPatch`), and draw it.
if self._bbox_patch:
self.update_bbox_position_size(renderer)
self._bbox_patch.draw(renderer)
gc = renderer.new_gc()
gc.set_foreground(self.get_color())
gc.set_alpha(self.get_alpha())
gc.set_url(self._url)
self._set_gc_clip(gc)
angle = self.get_rotation()
for line, wh, x, y in info:
mtext = self if len(info) == 1 else None
x = x + posx
y = y + posy
if renderer.flipy():
y = canvash - y
clean_line, ismath = self._preprocess_math(line)
if self.get_path_effects():
from matplotlib.patheffects import PathEffectRenderer
textrenderer = PathEffectRenderer(
self.get_path_effects(), renderer)
else:
textrenderer = renderer
if self.get_usetex():
textrenderer.draw_tex(gc, x, y, clean_line,
self._fontproperties, angle,
mtext=mtext)
else:
textrenderer.draw_text(gc, x, y, clean_line,
self._fontproperties, angle,
ismath=ismath, mtext=mtext)
gc.restore()
renderer.close_group('text')
self.stale = False
def get_color(self):
"""Return the color of the text."""
return self._color
def get_fontproperties(self):
"""Return the `.font_manager.FontProperties`."""
return self._fontproperties
def get_fontfamily(self):
"""
Return the list of font families used for font lookup.
See Also
--------
.font_manager.FontProperties.get_family
"""
return self._fontproperties.get_family()
def get_fontname(self):
"""
Return the font name as a string.
See Also
--------
.font_manager.FontProperties.get_name
"""
return self._fontproperties.get_name()
def get_fontstyle(self):
"""
Return the font style as a string.
See Also
--------
.font_manager.FontProperties.get_style
"""
return self._fontproperties.get_style()
def get_fontsize(self):
"""
Return the font size as an integer.
See Also
--------
.font_manager.FontProperties.get_size_in_points
"""
return self._fontproperties.get_size_in_points()
def get_fontvariant(self):
"""
Return the font variant as a string.
See Also
--------
.font_manager.FontProperties.get_variant
"""
return self._fontproperties.get_variant()
def get_fontweight(self):
"""
Return the font weight as a string or a number.
See Also
--------
.font_manager.FontProperties.get_weight
"""
return self._fontproperties.get_weight()
def get_stretch(self):
"""
Return the font stretch as a string or a number.
See Also
--------
.font_manager.FontProperties.get_stretch
"""
return self._fontproperties.get_stretch()
def get_horizontalalignment(self):
"""
Return the horizontal alignment as a string. Will be one of
'left', 'center' or 'right'.
"""
return self._horizontalalignment
def get_unitless_position(self):
"""Return the (x, y) unitless position of the text."""
# This will get the position with all unit information stripped away.
# This is here for convenience since it is done in several locations.
x = float(self.convert_xunits(self._x))
y = float(self.convert_yunits(self._y))
return x, y
def get_position(self):
"""Return the (x, y) position of the text."""
# This should return the same data (possible unitized) as was
# specified with 'set_x' and 'set_y'.
return self._x, self._y
def get_text(self):
"""Return the text string."""
return self._text
def get_verticalalignment(self):
"""
Return the vertical alignment as a string. Will be one of
'top', 'center', 'bottom', 'baseline' or 'center_baseline'.
"""
return self._verticalalignment
def get_window_extent(self, renderer=None, dpi=None):
"""
Return the `.Bbox` bounding the text, in display units.
In addition to being used internally, this is useful for specifying
clickable regions in a png file on a web page.
Parameters
----------
renderer : Renderer, optional
A renderer is needed to compute the bounding box. If the artist
has already been drawn, the renderer is cached; thus, it is only
necessary to pass this argument when calling `get_window_extent`
before the first draw. In practice, it is usually easier to
trigger a draw first, e.g. by calling
`~.Figure.draw_without_rendering` or ``plt.show()``.
dpi : float, optional
The dpi value for computing the bbox, defaults to
``self.figure.dpi`` (*not* the renderer dpi); should be set e.g. if
to match regions with a figure saved with a custom dpi value.
"""
if not self.get_visible():
return Bbox.unit()
if dpi is None:
dpi = self.figure.dpi
if self.get_text() == '':
with cbook._setattr_cm(self.figure, dpi=dpi):
tx, ty = self._get_xy_display()
return Bbox.from_bounds(tx, ty, 0, 0)
if renderer is not None:
self._renderer = renderer
if self._renderer is None:
self._renderer = self.figure._get_renderer()
if self._renderer is None:
raise RuntimeError(
"Cannot get window extent of text w/o renderer. You likely "
"want to call 'figure.draw_without_rendering()' first.")
with cbook._setattr_cm(self.figure, dpi=dpi):
bbox, info, descent = self._get_layout(self._renderer)
x, y = self.get_unitless_position()
x, y = self.get_transform().transform((x, y))
bbox = bbox.translated(x, y)
return bbox
def set_backgroundcolor(self, color):
"""
Set the background color of the text by updating the bbox.
Parameters
----------
color : color
See Also
--------
.set_bbox : To change the position of the bounding box
"""
if self._bbox_patch is None:
self.set_bbox(dict(facecolor=color, edgecolor=color))
else:
self._bbox_patch.update(dict(facecolor=color))
self._update_clip_properties()
self.stale = True
def set_color(self, color):
"""
Set the foreground color of the text
Parameters
----------
color : color
"""
# "auto" is only supported by axisartist, but we can just let it error
# out at draw time for simplicity.
if not cbook._str_equal(color, "auto"):
mpl.colors._check_color_like(color=color)
self._color = color
self.stale = True
def set_horizontalalignment(self, align):