-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
patches.py
4610 lines (3807 loc) · 156 KB
/
patches.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"""
Patches are `.Artist`\s with a face color and an edge color.
"""
import functools
import inspect
import math
from numbers import Number
import textwrap
from types import SimpleNamespace
from collections import namedtuple
from matplotlib.transforms import Affine2D
import numpy as np
import matplotlib as mpl
from . import (_api, artist, cbook, colors, _docstring, hatch as mhatch,
lines as mlines, transforms)
from .bezier import (
NonIntersectingPathException, get_cos_sin, get_intersection,
get_parallels, inside_circle, make_wedged_bezier2,
split_bezier_intersecting_with_closedpath, split_path_inout)
from .path import Path
from ._enums import JoinStyle, CapStyle
@_docstring.interpd
@_api.define_aliases({
"antialiased": ["aa"],
"edgecolor": ["ec"],
"facecolor": ["fc"],
"linestyle": ["ls"],
"linewidth": ["lw"],
})
class Patch(artist.Artist):
"""
A patch is a 2D artist with a face color and an edge color.
If any of *edgecolor*, *facecolor*, *linewidth*, or *antialiased*
are *None*, they default to their rc params setting.
"""
zorder = 1
# Whether to draw an edge by default. Set on a
# subclass-by-subclass basis.
_edge_default = False
@_api.make_keyword_only("3.6", name="edgecolor")
def __init__(self,
edgecolor=None,
facecolor=None,
color=None,
linewidth=None,
linestyle=None,
antialiased=None,
hatch=None,
fill=True,
capstyle=None,
joinstyle=None,
**kwargs):
"""
The following kwarg properties are supported
%(Patch:kwdoc)s
"""
super().__init__()
if linestyle is None:
linestyle = "solid"
if capstyle is None:
capstyle = CapStyle.butt
if joinstyle is None:
joinstyle = JoinStyle.miter
self._hatch_color = colors.to_rgba(mpl.rcParams['hatch.color'])
self._fill = True # needed for set_facecolor call
if color is not None:
if edgecolor is not None or facecolor is not None:
_api.warn_external(
"Setting the 'color' property will override "
"the edgecolor or facecolor properties.")
self.set_color(color)
else:
self.set_edgecolor(edgecolor)
self.set_facecolor(facecolor)
self._linewidth = 0
self._unscaled_dash_pattern = (0, None) # offset, dash
self._dash_pattern = (0, None) # offset, dash (scaled by linewidth)
self.set_fill(fill)
self.set_linestyle(linestyle)
self.set_linewidth(linewidth)
self.set_antialiased(antialiased)
self.set_hatch(hatch)
self.set_capstyle(capstyle)
self.set_joinstyle(joinstyle)
if len(kwargs):
self._internal_update(kwargs)
def get_verts(self):
"""
Return a copy of the vertices used in this patch.
If the patch contains Bézier curves, the curves will be interpolated by
line segments. To access the curves as curves, use `get_path`.
"""
trans = self.get_transform()
path = self.get_path()
polygons = path.to_polygons(trans)
if len(polygons):
return polygons[0]
return []
def _process_radius(self, radius):
if radius is not None:
return radius
if isinstance(self._picker, Number):
_radius = self._picker
else:
if self.get_edgecolor()[3] == 0:
_radius = 0
else:
_radius = self.get_linewidth()
return _radius
def contains(self, mouseevent, radius=None):
"""
Test whether the mouse event occurred in the patch.
Returns
-------
(bool, empty dict)
"""
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
radius = self._process_radius(radius)
codes = self.get_path().codes
if codes is not None:
vertices = self.get_path().vertices
# if the current path is concatenated by multiple sub paths.
# get the indexes of the starting code(MOVETO) of all sub paths
idxs, = np.where(codes == Path.MOVETO)
# Don't split before the first MOVETO.
idxs = idxs[1:]
subpaths = map(
Path, np.split(vertices, idxs), np.split(codes, idxs))
else:
subpaths = [self.get_path()]
inside = any(
subpath.contains_point(
(mouseevent.x, mouseevent.y), self.get_transform(), radius)
for subpath in subpaths)
return inside, {}
def contains_point(self, point, radius=None):
"""
Return whether the given point is inside the patch.
Parameters
----------
point : (float, float)
The point (x, y) to check, in target coordinates of
``self.get_transform()``. These are display coordinates for patches
that are added to a figure or axes.
radius : float, optional
Additional margin on the patch in target coordinates of
``self.get_transform()``. See `.Path.contains_point` for further
details.
Returns
-------
bool
Notes
-----
The proper use of this method depends on the transform of the patch.
Isolated patches do not have a transform. In this case, the patch
creation coordinates and the point coordinates match. The following
example checks that the center of a circle is within the circle
>>> center = 0, 0
>>> c = Circle(center, radius=1)
>>> c.contains_point(center)
True
The convention of checking against the transformed patch stems from
the fact that this method is predominantly used to check if display
coordinates (e.g. from mouse events) are within the patch. If you want
to do the above check with data coordinates, you have to properly
transform them first:
>>> center = 0, 0
>>> c = Circle(center, radius=1)
>>> plt.gca().add_patch(c)
>>> transformed_center = c.get_transform().transform(center)
>>> c.contains_point(transformed_center)
True
"""
radius = self._process_radius(radius)
return self.get_path().contains_point(point,
self.get_transform(),
radius)
def contains_points(self, points, radius=None):
"""
Return whether the given points are inside the patch.
Parameters
----------
points : (N, 2) array
The points to check, in target coordinates of
``self.get_transform()``. These are display coordinates for patches
that are added to a figure or axes. Columns contain x and y values.
radius : float, optional
Additional margin on the patch in target coordinates of
``self.get_transform()``. See `.Path.contains_point` for further
details.
Returns
-------
length-N bool array
Notes
-----
The proper use of this method depends on the transform of the patch.
See the notes on `.Patch.contains_point`.
"""
radius = self._process_radius(radius)
return self.get_path().contains_points(points,
self.get_transform(),
radius)
def update_from(self, other):
# docstring inherited.
super().update_from(other)
# For some properties we don't need or don't want to go through the
# getters/setters, so we just copy them directly.
self._edgecolor = other._edgecolor
self._facecolor = other._facecolor
self._original_edgecolor = other._original_edgecolor
self._original_facecolor = other._original_facecolor
self._fill = other._fill
self._hatch = other._hatch
self._hatch_color = other._hatch_color
self._unscaled_dash_pattern = other._unscaled_dash_pattern
self.set_linewidth(other._linewidth) # also sets scaled dashes
self.set_transform(other.get_data_transform())
# If the transform of other needs further initialization, then it will
# be the case for this artist too.
self._transformSet = other.is_transform_set()
def get_extents(self):
"""
Return the `Patch`'s axis-aligned extents as a `~.transforms.Bbox`.
"""
return self.get_path().get_extents(self.get_transform())
def get_transform(self):
"""Return the `~.transforms.Transform` applied to the `Patch`."""
return self.get_patch_transform() + artist.Artist.get_transform(self)
def get_data_transform(self):
"""
Return the `~.transforms.Transform` mapping data coordinates to
physical coordinates.
"""
return artist.Artist.get_transform(self)
def get_patch_transform(self):
"""
Return the `~.transforms.Transform` instance mapping patch coordinates
to data coordinates.
For example, one may define a patch of a circle which represents a
radius of 5 by providing coordinates for a unit circle, and a
transform which scales the coordinates (the patch coordinate) by 5.
"""
return transforms.IdentityTransform()
def get_antialiased(self):
"""Return whether antialiasing is used for drawing."""
return self._antialiased
def get_edgecolor(self):
"""Return the edge color."""
return self._edgecolor
def get_facecolor(self):
"""Return the face color."""
return self._facecolor
def get_linewidth(self):
"""Return the line width in points."""
return self._linewidth
def get_linestyle(self):
"""Return the linestyle."""
return self._linestyle
def set_antialiased(self, aa):
"""
Set whether to use antialiased rendering.
Parameters
----------
aa : bool or None
"""
if aa is None:
aa = mpl.rcParams['patch.antialiased']
self._antialiased = aa
self.stale = True
def _set_edgecolor(self, color):
set_hatch_color = True
if color is None:
if (mpl.rcParams['patch.force_edgecolor'] or
not self._fill or self._edge_default):
color = mpl.rcParams['patch.edgecolor']
else:
color = 'none'
set_hatch_color = False
self._edgecolor = colors.to_rgba(color, self._alpha)
if set_hatch_color:
self._hatch_color = self._edgecolor
self.stale = True
def set_edgecolor(self, color):
"""
Set the patch edge color.
Parameters
----------
color : color or None
"""
self._original_edgecolor = color
self._set_edgecolor(color)
def _set_facecolor(self, color):
if color is None:
color = mpl.rcParams['patch.facecolor']
alpha = self._alpha if self._fill else 0
self._facecolor = colors.to_rgba(color, alpha)
self.stale = True
def set_facecolor(self, color):
"""
Set the patch face color.
Parameters
----------
color : color or None
"""
self._original_facecolor = color
self._set_facecolor(color)
def set_color(self, c):
"""
Set both the edgecolor and the facecolor.
Parameters
----------
c : color
See Also
--------
Patch.set_facecolor, Patch.set_edgecolor
For setting the edge or face color individually.
"""
self.set_facecolor(c)
self.set_edgecolor(c)
def set_alpha(self, alpha):
# docstring inherited
super().set_alpha(alpha)
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)
# stale is already True
def set_linewidth(self, w):
"""
Set the patch linewidth in points.
Parameters
----------
w : float or None
"""
if w is None:
w = mpl.rcParams['patch.linewidth']
self._linewidth = float(w)
self._dash_pattern = mlines._scale_dashes(
*self._unscaled_dash_pattern, w)
self.stale = True
def set_linestyle(self, ls):
"""
Set the patch linestyle.
========================================== =================
linestyle description
========================================== =================
``'-'`` or ``'solid'`` solid line
``'--'`` or ``'dashed'`` dashed line
``'-.'`` or ``'dashdot'`` dash-dotted line
``':'`` or ``'dotted'`` dotted line
``'none'``, ``'None'``, ``' '``, or ``''`` draw nothing
========================================== =================
Alternatively a dash tuple of the following form can be provided::
(offset, onoffseq)
where ``onoffseq`` is an even length tuple of on and off ink in points.
Parameters
----------
ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
The line style.
"""
if ls is None:
ls = "solid"
if ls in [' ', '', 'none']:
ls = 'None'
self._linestyle = ls
self._unscaled_dash_pattern = mlines._get_dash_pattern(ls)
self._dash_pattern = mlines._scale_dashes(
*self._unscaled_dash_pattern, self._linewidth)
self.stale = True
def set_fill(self, b):
"""
Set whether to fill the patch.
Parameters
----------
b : bool
"""
self._fill = bool(b)
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)
self.stale = True
def get_fill(self):
"""Return whether the patch is filled."""
return self._fill
# Make fill a property so as to preserve the long-standing
# but somewhat inconsistent behavior in which fill was an
# attribute.
fill = property(get_fill, set_fill)
@_docstring.interpd
def set_capstyle(self, s):
"""
Set the `.CapStyle`.
The default capstyle is 'round' for `.FancyArrowPatch` and 'butt' for
all other patches.
Parameters
----------
s : `.CapStyle` or %(CapStyle)s
"""
cs = CapStyle(s)
self._capstyle = cs
self.stale = True
def get_capstyle(self):
"""Return the capstyle."""
return self._capstyle.name
@_docstring.interpd
def set_joinstyle(self, s):
"""
Set the `.JoinStyle`.
The default joinstyle is 'round' for `.FancyArrowPatch` and 'miter' for
all other patches.
Parameters
----------
s : `.JoinStyle` or %(JoinStyle)s
"""
js = JoinStyle(s)
self._joinstyle = js
self.stale = True
def get_joinstyle(self):
"""Return the joinstyle."""
return self._joinstyle.name
def set_hatch(self, hatch):
r"""
Set the hatching pattern.
*hatch* can be one of::
/ - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified
hatchings are done. If same letter repeats, it increases the
density of hatching of that pattern.
Hatching is supported in the PostScript, PDF, SVG and Agg
backends only.
Parameters
----------
hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
"""
# Use validate_hatch(list) after deprecation.
mhatch._validate_hatch_pattern(hatch)
self._hatch = hatch
self.stale = True
def get_hatch(self):
"""Return the hatching pattern."""
return self._hatch
def _draw_paths_with_artist_properties(
self, renderer, draw_path_args_list):
"""
``draw()`` helper factored out for sharing with `FancyArrowPatch`.
Configure *renderer* and the associated graphics context *gc*
from the artist properties, then repeatedly call
``renderer.draw_path(gc, *draw_path_args)`` for each tuple
*draw_path_args* in *draw_path_args_list*.
"""
renderer.open_group('patch', self.get_gid())
gc = renderer.new_gc()
gc.set_foreground(self._edgecolor, isRGBA=True)
lw = self._linewidth
if self._edgecolor[3] == 0 or self._linestyle == 'None':
lw = 0
gc.set_linewidth(lw)
gc.set_dashes(*self._dash_pattern)
gc.set_capstyle(self._capstyle)
gc.set_joinstyle(self._joinstyle)
gc.set_antialiased(self._antialiased)
self._set_gc_clip(gc)
gc.set_url(self._url)
gc.set_snap(self.get_snap())
gc.set_alpha(self._alpha)
if self._hatch:
gc.set_hatch(self._hatch)
gc.set_hatch_color(self._hatch_color)
if self.get_sketch_params() is not None:
gc.set_sketch_params(*self.get_sketch_params())
if self.get_path_effects():
from matplotlib.patheffects import PathEffectRenderer
renderer = PathEffectRenderer(self.get_path_effects(), renderer)
for draw_path_args in draw_path_args_list:
renderer.draw_path(gc, *draw_path_args)
gc.restore()
renderer.close_group('patch')
self.stale = False
@artist.allow_rasterization
def draw(self, renderer):
# docstring inherited
if not self.get_visible():
return
path = self.get_path()
transform = self.get_transform()
tpath = transform.transform_path_non_affine(path)
affine = transform.get_affine()
self._draw_paths_with_artist_properties(
renderer,
[(tpath, affine,
# Work around a bug in the PDF and SVG renderers, which
# do not draw the hatches if the facecolor is fully
# transparent, but do if it is None.
self._facecolor if self._facecolor[3] else None)])
def get_path(self):
"""Return the path of this patch."""
raise NotImplementedError('Derived must override')
def get_window_extent(self, renderer=None):
return self.get_path().get_extents(self.get_transform())
def _convert_xy_units(self, xy):
"""Convert x and y units for a tuple (x, y)."""
x = self.convert_xunits(xy[0])
y = self.convert_yunits(xy[1])
return x, y
class Shadow(Patch):
def __str__(self):
return f"Shadow({self.patch})"
@_docstring.dedent_interpd
def __init__(self, patch, ox, oy, **kwargs):
"""
Create a shadow of the given *patch*.
By default, the shadow will have the same face color as the *patch*,
but darkened.
Parameters
----------
patch : `~matplotlib.patches.Patch`
The patch to create the shadow for.
ox, oy : float
The shift of the shadow in data coordinates, scaled by a factor
of dpi/72.
**kwargs
Properties of the shadow patch. Supported keys are:
%(Patch:kwdoc)s
"""
super().__init__()
self.patch = patch
self._ox, self._oy = ox, oy
self._shadow_transform = transforms.Affine2D()
self.update_from(self.patch)
color = .3 * np.asarray(colors.to_rgb(self.patch.get_facecolor()))
self.update({'facecolor': color, 'edgecolor': color, 'alpha': 0.5,
# Place shadow patch directly behind the inherited patch.
'zorder': np.nextafter(self.patch.zorder, -np.inf),
**kwargs})
def _update_transform(self, renderer):
ox = renderer.points_to_pixels(self._ox)
oy = renderer.points_to_pixels(self._oy)
self._shadow_transform.clear().translate(ox, oy)
def get_path(self):
return self.patch.get_path()
def get_patch_transform(self):
return self.patch.get_patch_transform() + self._shadow_transform
def draw(self, renderer):
self._update_transform(renderer)
super().draw(renderer)
class Rectangle(Patch):
"""
A rectangle defined via an anchor point *xy* and its *width* and *height*.
The rectangle extends from ``xy[0]`` to ``xy[0] + width`` in x-direction
and from ``xy[1]`` to ``xy[1] + height`` in y-direction. ::
: +------------------+
: | |
: height |
: | |
: (xy)---- width -----+
One may picture *xy* as the bottom left corner, but which corner *xy* is
actually depends on the direction of the axis and the sign of *width*
and *height*; e.g. *xy* would be the bottom right corner if the x-axis
was inverted or if *width* was negative.
"""
def __str__(self):
pars = self._x0, self._y0, self._width, self._height, self.angle
fmt = "Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)"
return fmt % pars
@_docstring.dedent_interpd
@_api.make_keyword_only("3.6", name="angle")
def __init__(self, xy, width, height, angle=0.0, *,
rotation_point='xy', **kwargs):
"""
Parameters
----------
xy : (float, float)
The anchor point.
width : float
Rectangle width.
height : float
Rectangle height.
angle : float, default: 0
Rotation in degrees anti-clockwise about the rotation point.
rotation_point : {'xy', 'center', (number, number)}, default: 'xy'
If ``'xy'``, rotate around the anchor point. If ``'center'`` rotate
around the center. If 2-tuple of number, rotate around this
coordinate.
Other Parameters
----------------
**kwargs : `~matplotlib.patches.Patch` properties
%(Patch:kwdoc)s
"""
super().__init__(**kwargs)
self._x0 = xy[0]
self._y0 = xy[1]
self._width = width
self._height = height
self.angle = float(angle)
self.rotation_point = rotation_point
# Required for RectangleSelector with axes aspect ratio != 1
# The patch is defined in data coordinates and when changing the
# selector with square modifier and not in data coordinates, we need
# to correct for the aspect ratio difference between the data and
# display coordinate systems. Its value is typically provide by
# Axes._get_aspect_ratio()
self._aspect_ratio_correction = 1.0
self._convert_units() # Validate the inputs.
def get_path(self):
"""Return the vertices of the rectangle."""
return Path.unit_rectangle()
def _convert_units(self):
"""Convert bounds of the rectangle."""
x0 = self.convert_xunits(self._x0)
y0 = self.convert_yunits(self._y0)
x1 = self.convert_xunits(self._x0 + self._width)
y1 = self.convert_yunits(self._y0 + self._height)
return x0, y0, x1, y1
def get_patch_transform(self):
# Note: This cannot be called until after this has been added to
# an Axes, otherwise unit conversion will fail. This makes it very
# important to call the accessor method and not directly access the
# transformation member variable.
bbox = self.get_bbox()
if self.rotation_point == 'center':
width, height = bbox.x1 - bbox.x0, bbox.y1 - bbox.y0
rotation_point = bbox.x0 + width / 2., bbox.y0 + height / 2.
elif self.rotation_point == 'xy':
rotation_point = bbox.x0, bbox.y0
else:
rotation_point = self.rotation_point
return transforms.BboxTransformTo(bbox) \
+ transforms.Affine2D() \
.translate(-rotation_point[0], -rotation_point[1]) \
.scale(1, self._aspect_ratio_correction) \
.rotate_deg(self.angle) \
.scale(1, 1 / self._aspect_ratio_correction) \
.translate(*rotation_point)
@property
def rotation_point(self):
"""The rotation point of the patch."""
return self._rotation_point
@rotation_point.setter
def rotation_point(self, value):
if value in ['center', 'xy'] or (
isinstance(value, tuple) and len(value) == 2 and
isinstance(value[0], Number) and isinstance(value[1], Number)
):
self._rotation_point = value
else:
raise ValueError("`rotation_point` must be one of "
"{'xy', 'center', (number, number)}.")
def get_x(self):
"""Return the left coordinate of the rectangle."""
return self._x0
def get_y(self):
"""Return the bottom coordinate of the rectangle."""
return self._y0
def get_xy(self):
"""Return the left and bottom coords of the rectangle as a tuple."""
return self._x0, self._y0
def get_corners(self):
"""
Return the corners of the rectangle, moving anti-clockwise from
(x0, y0).
"""
return self.get_patch_transform().transform(
[(0, 0), (1, 0), (1, 1), (0, 1)])
def get_center(self):
"""Return the centre of the rectangle."""
return self.get_patch_transform().transform((0.5, 0.5))
def get_width(self):
"""Return the width of the rectangle."""
return self._width
def get_height(self):
"""Return the height of the rectangle."""
return self._height
def get_angle(self):
"""Get the rotation angle in degrees."""
return self.angle
def set_x(self, x):
"""Set the left coordinate of the rectangle."""
self._x0 = x
self.stale = True
def set_y(self, y):
"""Set the bottom coordinate of the rectangle."""
self._y0 = y
self.stale = True
def set_angle(self, angle):
"""
Set the rotation angle in degrees.
The rotation is performed anti-clockwise around *xy*.
"""
self.angle = angle
self.stale = True
def set_xy(self, xy):
"""
Set the left and bottom coordinates of the rectangle.
Parameters
----------
xy : (float, float)
"""
self._x0, self._y0 = xy
self.stale = True
def set_width(self, w):
"""Set the width of the rectangle."""
self._width = w
self.stale = True
def set_height(self, h):
"""Set the height of the rectangle."""
self._height = h
self.stale = True
def set_bounds(self, *args):
"""
Set the bounds of the rectangle as *left*, *bottom*, *width*, *height*.
The values may be passed as separate parameters or as a tuple::
set_bounds(left, bottom, width, height)
set_bounds((left, bottom, width, height))
.. ACCEPTS: (left, bottom, width, height)
"""
if len(args) == 1:
l, b, w, h = args[0]
else:
l, b, w, h = args
self._x0 = l
self._y0 = b
self._width = w
self._height = h
self.stale = True
def get_bbox(self):
"""Return the `.Bbox`."""
x0, y0, x1, y1 = self._convert_units()
return transforms.Bbox.from_extents(x0, y0, x1, y1)
xy = property(get_xy, set_xy)
class RegularPolygon(Patch):
"""A regular polygon patch."""
def __str__(self):
s = "RegularPolygon((%g, %g), %d, radius=%g, orientation=%g)"
return s % (self.xy[0], self.xy[1], self.numvertices, self.radius,
self.orientation)
@_docstring.dedent_interpd
@_api.make_keyword_only("3.6", name="radius")
def __init__(self, xy, numVertices, radius=5, orientation=0,
**kwargs):
"""
Parameters
----------
xy : (float, float)
The center position.
numVertices : int
The number of vertices.
radius : float
The distance from the center to each of the vertices.
orientation : float
The polygon rotation angle (in radians).
**kwargs
`Patch` properties:
%(Patch:kwdoc)s
"""
self.xy = xy
self.numvertices = numVertices
self.orientation = orientation
self.radius = radius
self._path = Path.unit_regular_polygon(numVertices)
self._patch_transform = transforms.Affine2D()
super().__init__(**kwargs)
def get_path(self):
return self._path
def get_patch_transform(self):
return self._patch_transform.clear() \
.scale(self.radius) \
.rotate(self.orientation) \
.translate(*self.xy)
class PathPatch(Patch):
"""A general polycurve path patch."""
_edge_default = True
def __str__(self):
s = "PathPatch%d((%g, %g) ...)"
return s % (len(self._path.vertices), *tuple(self._path.vertices[0]))
@_docstring.dedent_interpd
def __init__(self, path, **kwargs):
"""
*path* is a `.Path` object.
Valid keyword arguments are:
%(Patch:kwdoc)s
"""
super().__init__(**kwargs)
self._path = path
def get_path(self):
return self._path
def set_path(self, path):
self._path = path
class StepPatch(PathPatch):
"""
A path patch describing a stepwise constant function.
By default, the path is not closed and starts and stops at
baseline value.
"""
_edge_default = False
@_docstring.dedent_interpd
def __init__(self, values, edges, *,
orientation='vertical', baseline=0, **kwargs):
"""
Parameters
----------
values : array-like
The step heights.
edges : array-like
The edge positions, with ``len(edges) == len(vals) + 1``,
between which the curve takes on vals values.
orientation : {'vertical', 'horizontal'}, default: 'vertical'
The direction of the steps. Vertical means that *values* are
along the y-axis, and edges are along the x-axis.
baseline : float, array-like or None, default: 0
The bottom value of the bounding edges or when
``fill=True``, position of lower edge. If *fill* is
True or an array is passed to *baseline*, a closed
path is drawn.
Other valid keyword arguments are:
%(Patch:kwdoc)s
"""
self.orientation = orientation
self._edges = np.asarray(edges)