-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
offsetbox.py
1624 lines (1341 loc) · 53.4 KB
/
offsetbox.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
r"""
Container classes for `.Artist`\s.
`OffsetBox`
The base of all container artists defined in this module.
`AnchoredOffsetbox`, `AnchoredText`
Anchor and align an arbitrary `.Artist` or a text relative to the parent
axes or a specific anchor point.
`DrawingArea`
A container with fixed width and height. Children have a fixed position
inside the container and may be clipped.
`HPacker`, `VPacker`
Containers for layouting their children vertically or horizontally.
`PaddedBox`
A container to add a padding around an `.Artist`.
`TextArea`
Contains a single `.Text` instance.
"""
import functools
import numpy as np
import matplotlib as mpl
from matplotlib import _api, _docstring
import matplotlib.artist as martist
import matplotlib.path as mpath
import matplotlib.text as mtext
import matplotlib.transforms as mtransforms
from matplotlib.font_manager import FontProperties
from matplotlib.image import BboxImage
from matplotlib.patches import (
FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist)
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
DEBUG = False
def _compat_get_offset(meth):
"""
Decorator for the get_offset method of OffsetBox and subclasses, that
allows supporting both the new signature (self, bbox, renderer) and the old
signature (self, width, height, xdescent, ydescent, renderer).
"""
sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(),
lambda self, bbox, renderer: locals()]
@functools.wraps(meth)
def get_offset(self, *args, **kwargs):
params = _api.select_matching_signature(sigs, self, *args, **kwargs)
bbox = (params["bbox"] if "bbox" in params else
Bbox.from_bounds(-params["xdescent"], -params["ydescent"],
params["width"], params["height"]))
return meth(params["self"], bbox, params["renderer"])
return get_offset
@_api.deprecated("3.7", alternative='patches.bbox_artist')
def bbox_artist(*args, **kwargs):
if DEBUG:
mbbox_artist(*args, **kwargs)
# for debugging use
def _bbox_artist(*args, **kwargs):
if DEBUG:
mbbox_artist(*args, **kwargs)
def _get_packed_offsets(widths, total, sep, mode="fixed"):
r"""
Pack boxes specified by their *widths*.
For simplicity of the description, the terminology used here assumes a
horizontal layout, but the function works equally for a vertical layout.
There are three packing *mode*\s:
- 'fixed': The elements are packed tight to the left with a spacing of
*sep* in between. If *total* is *None* the returned total will be the
right edge of the last box. A non-*None* total will be passed unchecked
to the output. In particular this means that right edge of the last
box may be further to the right than the returned total.
- 'expand': Distribute the boxes with equal spacing so that the left edge
of the first box is at 0, and the right edge of the last box is at
*total*. The parameter *sep* is ignored in this mode. A total of *None*
is accepted and considered equal to 1. The total is returned unchanged
(except for the conversion *None* to 1). If the total is smaller than
the sum of the widths, the laid out boxes will overlap.
- 'equal': If *total* is given, the total space is divided in N equal
ranges and each box is left-aligned within its subspace.
Otherwise (*total* is *None*), *sep* must be provided and each box is
left-aligned in its subspace of width ``(max(widths) + sep)``. The
total width is then calculated to be ``N * (max(widths) + sep)``.
Parameters
----------
widths : list of float
Widths of boxes to be packed.
total : float or None
Intended total length. *None* if not used.
sep : float
Spacing between boxes.
mode : {'fixed', 'expand', 'equal'}
The packing mode.
Returns
-------
total : float
The total width needed to accommodate the laid out boxes.
offsets : array of float
The left offsets of the boxes.
"""
_api.check_in_list(["fixed", "expand", "equal"], mode=mode)
if mode == "fixed":
offsets_ = np.cumsum([0] + [w + sep for w in widths])
offsets = offsets_[:-1]
if total is None:
total = offsets_[-1] - sep
return total, offsets
elif mode == "expand":
# This is a bit of a hack to avoid a TypeError when *total*
# is None and used in conjugation with tight layout.
if total is None:
total = 1
if len(widths) > 1:
sep = (total - sum(widths)) / (len(widths) - 1)
else:
sep = 0
offsets_ = np.cumsum([0] + [w + sep for w in widths])
offsets = offsets_[:-1]
return total, offsets
elif mode == "equal":
maxh = max(widths)
if total is None:
if sep is None:
raise ValueError("total and sep cannot both be None when "
"using layout mode 'equal'")
total = (maxh + sep) * len(widths)
else:
sep = total / len(widths) - maxh
offsets = (maxh + sep) * np.arange(len(widths))
return total, offsets
def _get_aligned_offsets(yspans, height, align="baseline"):
"""
Align boxes each specified by their ``(y0, y1)`` spans.
For simplicity of the description, the terminology used here assumes a
horizontal layout (i.e., vertical alignment), but the function works
equally for a vertical layout.
Parameters
----------
yspans
List of (y0, y1) spans of boxes to be aligned.
height : float or None
Intended total height. If None, the maximum of the heights
(``y1 - y0``) in *yspans* is used.
align : {'baseline', 'left', 'top', 'right', 'bottom', 'center'}
The alignment anchor of the boxes.
Returns
-------
(y0, y1)
y range spanned by the packing. If a *height* was originally passed
in, then for all alignments other than "baseline", a span of ``(0,
height)`` is used without checking that it is actually large enough).
descent
The descent of the packing.
offsets
The bottom offsets of the boxes.
"""
_api.check_in_list(
["baseline", "left", "top", "right", "bottom", "center"], align=align)
if height is None:
height = max(y1 - y0 for y0, y1 in yspans)
if align == "baseline":
yspan = (min(y0 for y0, y1 in yspans), max(y1 for y0, y1 in yspans))
offsets = [0] * len(yspans)
elif align in ["left", "bottom"]:
yspan = (0, height)
offsets = [-y0 for y0, y1 in yspans]
elif align in ["right", "top"]:
yspan = (0, height)
offsets = [height - y1 for y0, y1 in yspans]
elif align == "center":
yspan = (0, height)
offsets = [(height - (y1 - y0)) * .5 - y0 for y0, y1 in yspans]
return yspan, offsets
class OffsetBox(martist.Artist):
"""
The OffsetBox is a simple container artist.
The child artists are meant to be drawn at a relative position to its
parent.
Being an artist itself, all parameters are passed on to `.Artist`.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args)
self._internal_update(kwargs)
# Clipping has not been implemented in the OffsetBox family, so
# disable the clip flag for consistency. It can always be turned back
# on to zero effect.
self.set_clip_on(False)
self._children = []
self._offset = (0, 0)
def set_figure(self, fig):
"""
Set the `.Figure` for the `.OffsetBox` and all its children.
Parameters
----------
fig : `~matplotlib.figure.Figure`
"""
super().set_figure(fig)
for c in self.get_children():
c.set_figure(fig)
@martist.Artist.axes.setter
def axes(self, ax):
# TODO deal with this better
martist.Artist.axes.fset(self, ax)
for c in self.get_children():
if c is not None:
c.axes = ax
def contains(self, mouseevent):
"""
Delegate the mouse event contains-check to the children.
As a container, the `.OffsetBox` does not respond itself to
mouseevents.
Parameters
----------
mouseevent : `~matplotlib.backend_bases.MouseEvent`
Returns
-------
contains : bool
Whether any values are within the radius.
details : dict
An artist-specific dictionary of details of the event context,
such as which points are contained in the pick radius. See the
individual Artist subclasses for details.
See Also
--------
.Artist.contains
"""
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
for c in self.get_children():
a, b = c.contains(mouseevent)
if a:
return a, b
return False, {}
def set_offset(self, xy):
"""
Set the offset.
Parameters
----------
xy : (float, float) or callable
The (x, y) coordinates of the offset in display units. These can
either be given explicitly as a tuple (x, y), or by providing a
function that converts the extent into the offset. This function
must have the signature::
def offset(width, height, xdescent, ydescent, renderer) \
-> (float, float)
"""
self._offset = xy
self.stale = True
@_compat_get_offset
def get_offset(self, bbox, renderer):
"""
Return the offset as a tuple (x, y).
The extent parameters have to be provided to handle the case where the
offset is dynamically determined by a callable (see
`~.OffsetBox.set_offset`).
Parameters
----------
bbox : `.Bbox`
renderer : `.RendererBase` subclass
"""
return (
self._offset(bbox.width, bbox.height, -bbox.x0, -bbox.y0, renderer)
if callable(self._offset)
else self._offset)
def set_width(self, width):
"""
Set the width of the box.
Parameters
----------
width : float
"""
self.width = width
self.stale = True
def set_height(self, height):
"""
Set the height of the box.
Parameters
----------
height : float
"""
self.height = height
self.stale = True
def get_visible_children(self):
r"""Return a list of the visible child `.Artist`\s."""
return [c for c in self._children if c.get_visible()]
def get_children(self):
r"""Return a list of the child `.Artist`\s."""
return self._children
def _get_bbox_and_child_offsets(self, renderer):
"""
Return the bbox of the offsetbox and the child offsets.
The bbox should satisfy ``x0 <= x1 and y0 <= y1``.
Parameters
----------
renderer : `.RendererBase` subclass
Returns
-------
bbox
list of (xoffset, yoffset) pairs
"""
raise NotImplementedError(
"get_bbox_and_offsets must be overridden in derived classes")
def get_bbox(self, renderer):
"""Return the bbox of the offsetbox, ignoring parent offsets."""
bbox, offsets = self._get_bbox_and_child_offsets(renderer)
return bbox
@_api.deprecated("3.7", alternative="get_bbox and child.get_offset")
def get_extent_offsets(self, renderer):
"""
Update offset of the children and return the extent of the box.
Parameters
----------
renderer : `.RendererBase` subclass
Returns
-------
width
height
xdescent
ydescent
list of (xoffset, yoffset) pairs
"""
bbox, offsets = self._get_bbox_and_child_offsets(renderer)
return bbox.width, bbox.height, -bbox.x0, -bbox.y0, offsets
@_api.deprecated("3.7", alternative="get_bbox")
def get_extent(self, renderer):
"""Return a tuple ``width, height, xdescent, ydescent`` of the box."""
bbox = self.get_bbox(renderer)
return bbox.width, bbox.height, -bbox.x0, -bbox.y0
def get_window_extent(self, renderer=None):
# docstring inherited
if renderer is None:
renderer = self.figure._get_renderer()
bbox = self.get_bbox(renderer)
try: # Some subclasses redefine get_offset to take no args.
px, py = self.get_offset(bbox, renderer)
except TypeError:
px, py = self.get_offset()
return bbox.translated(px, py)
def draw(self, renderer):
"""
Update the location of children if necessary and draw them
to the given *renderer*.
"""
bbox, offsets = self._get_bbox_and_child_offsets(renderer)
px, py = self.get_offset(bbox, renderer)
for c, (ox, oy) in zip(self.get_visible_children(), offsets):
c.set_offset((px + ox, py + oy))
c.draw(renderer)
_bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class PackerBase(OffsetBox):
def __init__(self, pad=0., sep=0., width=None, height=None,
align="baseline", mode="fixed", children=None):
"""
Parameters
----------
pad : float, default: 0.0
The boundary padding in points.
sep : float, default: 0.0
The spacing between items in points.
width, height : float, optional
Width and height of the container box in pixels, calculated if
*None*.
align : {'top', 'bottom', 'left', 'right', 'center', 'baseline'}, \
default: 'baseline'
Alignment of boxes.
mode : {'fixed', 'expand', 'equal'}, default: 'fixed'
The packing mode.
- 'fixed' packs the given `.Artist`\\s tight with *sep* spacing.
- 'expand' uses the maximal available space to distribute the
artists with equal spacing in between.
- 'equal': Each artist an equal fraction of the available space
and is left-aligned (or top-aligned) therein.
children : list of `.Artist`
The artists to pack.
Notes
-----
*pad* and *sep* are in points and will be scaled with the renderer
dpi, while *width* and *height* are in pixels.
"""
super().__init__()
self.height = height
self.width = width
self.sep = sep
self.pad = pad
self.mode = mode
self.align = align
self._children = children
class VPacker(PackerBase):
"""
VPacker packs its children vertically, automatically adjusting their
relative positions at draw time.
"""
def _get_bbox_and_child_offsets(self, renderer):
# docstring inherited
dpicor = renderer.points_to_pixels(1.)
pad = self.pad * dpicor
sep = self.sep * dpicor
if self.width is not None:
for c in self.get_visible_children():
if isinstance(c, PackerBase) and c.mode == "expand":
c.set_width(self.width)
bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()]
(x0, x1), xoffsets = _get_aligned_offsets(
[bbox.intervalx for bbox in bboxes], self.width, self.align)
height, yoffsets = _get_packed_offsets(
[bbox.height for bbox in bboxes], self.height, sep, self.mode)
yoffsets = height - (yoffsets + [bbox.y1 for bbox in bboxes])
ydescent = yoffsets[0]
yoffsets = yoffsets - ydescent
return (
Bbox.from_bounds(x0, -ydescent, x1 - x0, height).padded(pad),
[*zip(xoffsets, yoffsets)])
class HPacker(PackerBase):
"""
HPacker packs its children horizontally, automatically adjusting their
relative positions at draw time.
"""
def _get_bbox_and_child_offsets(self, renderer):
# docstring inherited
dpicor = renderer.points_to_pixels(1.)
pad = self.pad * dpicor
sep = self.sep * dpicor
bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()]
if not bboxes:
return Bbox.from_bounds(0, 0, 0, 0).padded(pad), []
(y0, y1), yoffsets = _get_aligned_offsets(
[bbox.intervaly for bbox in bboxes], self.height, self.align)
width, xoffsets = _get_packed_offsets(
[bbox.width for bbox in bboxes], self.width, sep, self.mode)
x0 = bboxes[0].x0
xoffsets -= ([bbox.x0 for bbox in bboxes] - x0)
return (Bbox.from_bounds(x0, y0, width, y1 - y0).padded(pad),
[*zip(xoffsets, yoffsets)])
class PaddedBox(OffsetBox):
"""
A container to add a padding around an `.Artist`.
The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize
it when rendering.
"""
@_api.make_keyword_only("3.6", name="draw_frame")
def __init__(self, child, pad=0., draw_frame=False, patch_attrs=None):
"""
Parameters
----------
child : `~matplotlib.artist.Artist`
The contained `.Artist`.
pad : float, default: 0.0
The padding in points. This will be scaled with the renderer dpi.
In contrast, *width* and *height* are in *pixels* and thus not
scaled.
draw_frame : bool
Whether to draw the contained `.FancyBboxPatch`.
patch_attrs : dict or None
Additional parameters passed to the contained `.FancyBboxPatch`.
"""
super().__init__()
self.pad = pad
self._children = [child]
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=1, # self.prop.get_size_in_points(),
snap=True,
visible=draw_frame,
boxstyle="square,pad=0",
)
if patch_attrs is not None:
self.patch.update(patch_attrs)
def _get_bbox_and_child_offsets(self, renderer):
# docstring inherited.
pad = self.pad * renderer.points_to_pixels(1.)
return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)])
def draw(self, renderer):
# docstring inherited
bbox, offsets = self._get_bbox_and_child_offsets(renderer)
px, py = self.get_offset(bbox, renderer)
for c, (ox, oy) in zip(self.get_visible_children(), offsets):
c.set_offset((px + ox, py + oy))
self.draw_frame(renderer)
for c in self.get_visible_children():
c.draw(renderer)
self.stale = False
def update_frame(self, bbox, fontsize=None):
self.patch.set_bounds(bbox.bounds)
if fontsize:
self.patch.set_mutation_scale(fontsize)
self.stale = True
def draw_frame(self, renderer):
# update the location and size of the legend
self.update_frame(self.get_window_extent(renderer))
self.patch.draw(renderer)
class DrawingArea(OffsetBox):
"""
The DrawingArea can contain any Artist as a child. The DrawingArea
has a fixed width and height. The position of children relative to
the parent is fixed. The children can be clipped at the
boundaries of the parent.
"""
def __init__(self, width, height, xdescent=0., ydescent=0., clip=False):
"""
Parameters
----------
width, height : float
Width and height of the container box.
xdescent, ydescent : float
Descent of the box in x- and y-direction.
clip : bool
Whether to clip the children to the box.
"""
super().__init__()
self.width = width
self.height = height
self.xdescent = xdescent
self.ydescent = ydescent
self._clip_children = clip
self.offset_transform = mtransforms.Affine2D()
self.dpi_transform = mtransforms.Affine2D()
@property
def clip_children(self):
"""
If the children of this DrawingArea should be clipped
by DrawingArea bounding box.
"""
return self._clip_children
@clip_children.setter
def clip_children(self, val):
self._clip_children = bool(val)
self.stale = True
def get_transform(self):
"""
Return the `~matplotlib.transforms.Transform` applied to the children.
"""
return self.dpi_transform + self.offset_transform
def set_transform(self, t):
"""
set_transform is ignored.
"""
def set_offset(self, xy):
"""
Set the offset of the container.
Parameters
----------
xy : (float, float)
The (x, y) coordinates of the offset in display units.
"""
self._offset = xy
self.offset_transform.clear()
self.offset_transform.translate(xy[0], xy[1])
self.stale = True
def get_offset(self):
"""Return offset of the container."""
return self._offset
def get_bbox(self, renderer):
# docstring inherited
dpi_cor = renderer.points_to_pixels(1.)
return Bbox.from_bounds(
-self.xdescent * dpi_cor, -self.ydescent * dpi_cor,
self.width * dpi_cor, self.height * dpi_cor)
def add_artist(self, a):
"""Add an `.Artist` to the container box."""
self._children.append(a)
if not a.is_transform_set():
a.set_transform(self.get_transform())
if self.axes is not None:
a.axes = self.axes
fig = self.figure
if fig is not None:
a.set_figure(fig)
def draw(self, renderer):
# docstring inherited
dpi_cor = renderer.points_to_pixels(1.)
self.dpi_transform.clear()
self.dpi_transform.scale(dpi_cor)
# At this point the DrawingArea has a transform
# to the display space so the path created is
# good for clipping children
tpath = mtransforms.TransformedPath(
mpath.Path([[0, 0], [0, self.height],
[self.width, self.height],
[self.width, 0]]),
self.get_transform())
for c in self._children:
if self._clip_children and not (c.clipbox or c._clippath):
c.set_clip_path(tpath)
c.draw(renderer)
_bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class TextArea(OffsetBox):
"""
The TextArea is a container artist for a single Text instance.
The text is placed at (0, 0) with baseline+left alignment, by default. The
width and height of the TextArea instance is the width and height of its
child text.
"""
@_api.make_keyword_only("3.6", name="textprops")
def __init__(self, s,
textprops=None,
multilinebaseline=False,
):
"""
Parameters
----------
s : str
The text to be displayed.
textprops : dict, default: {}
Dictionary of keyword parameters to be passed to the `.Text`
instance in the TextArea.
multilinebaseline : bool, default: False
Whether the baseline for multiline text is adjusted so that it
is (approximately) center-aligned with single-line text.
"""
if textprops is None:
textprops = {}
self._text = mtext.Text(0, 0, s, **textprops)
super().__init__()
self._children = [self._text]
self.offset_transform = mtransforms.Affine2D()
self._baseline_transform = mtransforms.Affine2D()
self._text.set_transform(self.offset_transform +
self._baseline_transform)
self._multilinebaseline = multilinebaseline
def set_text(self, s):
"""Set the text of this area as a string."""
self._text.set_text(s)
self.stale = True
def get_text(self):
"""Return the string representation of this area's text."""
return self._text.get_text()
def set_multilinebaseline(self, t):
"""
Set multilinebaseline.
If True, the baseline for multiline text is adjusted so that it is
(approximately) center-aligned with single-line text. This is used
e.g. by the legend implementation so that single-line labels are
baseline-aligned, but multiline labels are "center"-aligned with them.
"""
self._multilinebaseline = t
self.stale = True
def get_multilinebaseline(self):
"""
Get multilinebaseline.
"""
return self._multilinebaseline
def set_transform(self, t):
"""
set_transform is ignored.
"""
def set_offset(self, xy):
"""
Set the offset of the container.
Parameters
----------
xy : (float, float)
The (x, y) coordinates of the offset in display units.
"""
self._offset = xy
self.offset_transform.clear()
self.offset_transform.translate(xy[0], xy[1])
self.stale = True
def get_offset(self):
"""Return offset of the container."""
return self._offset
def get_bbox(self, renderer):
_, h_, d_ = renderer.get_text_width_height_descent(
"lp", self._text._fontproperties,
ismath="TeX" if self._text.get_usetex() else False)
bbox, info, yd = self._text._get_layout(renderer)
w, h = bbox.size
self._baseline_transform.clear()
if len(info) > 1 and self._multilinebaseline:
yd_new = 0.5 * h - 0.5 * (h_ - d_)
self._baseline_transform.translate(0, yd - yd_new)
yd = yd_new
else: # single line
h_d = max(h_ - d_, h - yd)
h = h_d + yd
ha = self._text.get_horizontalalignment()
x0 = {"left": 0, "center": -w / 2, "right": -w}[ha]
return Bbox.from_bounds(x0, -yd, w, h)
def draw(self, renderer):
# docstring inherited
self._text.draw(renderer)
_bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class AuxTransformBox(OffsetBox):
"""
Offset Box with the aux_transform. Its children will be
transformed with the aux_transform first then will be
offsetted. The absolute coordinate of the aux_transform is meaning
as it will be automatically adjust so that the left-lower corner
of the bounding box of children will be set to (0, 0) before the
offset transform.
It is similar to drawing area, except that the extent of the box
is not predetermined but calculated from the window extent of its
children. Furthermore, the extent of the children will be
calculated in the transformed coordinate.
"""
def __init__(self, aux_transform):
self.aux_transform = aux_transform
super().__init__()
self.offset_transform = mtransforms.Affine2D()
# ref_offset_transform makes offset_transform always relative to the
# lower-left corner of the bbox of its children.
self.ref_offset_transform = mtransforms.Affine2D()
def add_artist(self, a):
"""Add an `.Artist` to the container box."""
self._children.append(a)
a.set_transform(self.get_transform())
self.stale = True
def get_transform(self):
"""
Return the :class:`~matplotlib.transforms.Transform` applied
to the children
"""
return (self.aux_transform
+ self.ref_offset_transform
+ self.offset_transform)
def set_transform(self, t):
"""
set_transform is ignored.
"""
def set_offset(self, xy):
"""
Set the offset of the container.
Parameters
----------
xy : (float, float)
The (x, y) coordinates of the offset in display units.
"""
self._offset = xy
self.offset_transform.clear()
self.offset_transform.translate(xy[0], xy[1])
self.stale = True
def get_offset(self):
"""Return offset of the container."""
return self._offset
def get_bbox(self, renderer):
# clear the offset transforms
_off = self.offset_transform.get_matrix() # to be restored later
self.ref_offset_transform.clear()
self.offset_transform.clear()
# calculate the extent
bboxes = [c.get_window_extent(renderer) for c in self._children]
ub = Bbox.union(bboxes)
# adjust ref_offset_transform
self.ref_offset_transform.translate(-ub.x0, -ub.y0)
# restore offset transform
self.offset_transform.set_matrix(_off)
return Bbox.from_bounds(0, 0, ub.width, ub.height)
def draw(self, renderer):
# docstring inherited
for c in self._children:
c.draw(renderer)
_bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class AnchoredOffsetbox(OffsetBox):
"""
An offset box placed according to location *loc*.
AnchoredOffsetbox has a single child. When multiple children are needed,
use an extra OffsetBox to enclose them. By default, the offset box is
anchored against its parent axes. You may explicitly specify the
*bbox_to_anchor*.
"""
zorder = 5 # zorder of the legend
# Location codes
codes = {'upper right': 1,
'upper left': 2,
'lower left': 3,
'lower right': 4,
'right': 5,
'center left': 6,
'center right': 7,
'lower center': 8,
'upper center': 9,
'center': 10,
}
@_api.make_keyword_only("3.6", name="pad")
def __init__(self, loc,
pad=0.4, borderpad=0.5,
child=None, prop=None, frameon=True,
bbox_to_anchor=None,
bbox_transform=None,
**kwargs):
"""
Parameters
----------
loc : str
The box location. Valid locations are
'upper left', 'upper center', 'upper right',
'center left', 'center', 'center right',
'lower left', 'lower center', 'lower right'.
For backward compatibility, numeric values are accepted as well.
See the parameter *loc* of `.Legend` for details.
pad : float, default: 0.4
Padding around the child as fraction of the fontsize.
borderpad : float, default: 0.5
Padding between the offsetbox frame and the *bbox_to_anchor*.
child : `.OffsetBox`
The box that will be anchored.
prop : `.FontProperties`
This is only used as a reference for paddings. If not given,
:rc:`legend.fontsize` is used.
frameon : bool
Whether to draw a frame around the box.
bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with *loc*.
bbox_transform : None or :class:`matplotlib.transforms.Transform`
The transform for the bounding box (*bbox_to_anchor*).
**kwargs
All other parameters are passed on to `.OffsetBox`.
Notes
-----
See `.Legend` for a detailed description of the anchoring mechanism.
"""
super().__init__(**kwargs)
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
self.set_child(child)
if isinstance(loc, str):
loc = _api.check_getitem(self.codes, loc=loc)
self.loc = loc
self.borderpad = borderpad
self.pad = pad
if prop is None:
self.prop = FontProperties(size=mpl.rcParams["legend.fontsize"])
else:
self.prop = FontProperties._from_any(prop)
if isinstance(prop, dict) and "size" not in prop:
self.prop.set_size(mpl.rcParams["legend.fontsize"])
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=self.prop.get_size_in_points(),
snap=True,
visible=frameon,
boxstyle="square,pad=0",
)
def set_child(self, child):
"""Set the child to be anchored."""