ZTWHHH commited on
Commit
a8553ce
·
verified ·
1 Parent(s): d30cff8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__init__.py +10 -0
  2. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/__init__.cpython-310.pyc +0 -0
  3. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/anchored_artists.cpython-310.pyc +0 -0
  4. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_divider.cpython-310.pyc +0 -0
  5. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_grid.cpython-310.pyc +0 -0
  6. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_rgb.cpython-310.pyc +0 -0
  7. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_size.cpython-310.pyc +0 -0
  8. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/inset_locator.cpython-310.pyc +0 -0
  9. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/mpl_axes.cpython-310.pyc +0 -0
  10. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/parasite_axes.cpython-310.pyc +0 -0
  11. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/anchored_artists.py +462 -0
  12. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_divider.py +694 -0
  13. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_grid.py +563 -0
  14. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_rgb.py +157 -0
  15. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_size.py +248 -0
  16. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/inset_locator.py +561 -0
  17. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/mpl_axes.py +128 -0
  18. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py +257 -0
  19. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__init__.py +10 -0
  20. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  21. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/conftest.cpython-310.pyc +0 -0
  22. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/test_axes_grid1.cpython-310.pyc +0 -0
  23. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/conftest.py +2 -0
  24. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py +792 -0
  25. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/__init__.cpython-310.pyc +0 -0
  26. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/angle_helper.cpython-310.pyc +0 -0
  27. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axes_divider.cpython-310.pyc +0 -0
  28. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axes_grid.cpython-310.pyc +0 -0
  29. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axes_rgb.cpython-310.pyc +0 -0
  30. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axis_artist.cpython-310.pyc +0 -0
  31. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axisline_style.cpython-310.pyc +0 -0
  32. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axislines.cpython-310.pyc +0 -0
  33. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/floating_axes.cpython-310.pyc +0 -0
  34. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/grid_finder.cpython-310.pyc +0 -0
  35. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/grid_helper_curvelinear.cpython-310.pyc +0 -0
  36. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/parasite_axes.cpython-310.pyc +0 -0
  37. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  38. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/__pycache__/conftest.cpython-310.pyc +0 -0
  39. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_angle_helper.cpython-310.pyc +0 -0
  40. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_axis_artist.cpython-310.pyc +0 -0
  41. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/test_floating_axes.py +115 -0
  42. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/test_grid_helper_curvelinear.py +207 -0
  43. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__init__.py +3 -0
  44. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/__init__.cpython-310.pyc +0 -0
  45. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/art3d.cpython-310.pyc +0 -0
  46. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/axis3d.cpython-310.pyc +0 -0
  47. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/proj3d.cpython-310.pyc +0 -0
  48. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/art3d.py +1262 -0
  49. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/axes3d.py +0 -0
  50. evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/axis3d.py +760 -0
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import axes_size as Size
2
+ from .axes_divider import Divider, SubplotDivider, make_axes_locatable
3
+ from .axes_grid import AxesGrid, Grid, ImageGrid
4
+
5
+ from .parasite_axes import host_subplot, host_axes
6
+
7
+ __all__ = ["Size",
8
+ "Divider", "SubplotDivider", "make_axes_locatable",
9
+ "AxesGrid", "Grid", "ImageGrid",
10
+ "host_subplot", "host_axes"]
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (537 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/anchored_artists.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_divider.cpython-310.pyc ADDED
Binary file (22.9 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_grid.cpython-310.pyc ADDED
Binary file (17.4 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_rgb.cpython-310.pyc ADDED
Binary file (5.11 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_size.cpython-310.pyc ADDED
Binary file (8.96 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/inset_locator.cpython-310.pyc ADDED
Binary file (20.9 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/mpl_axes.cpython-310.pyc ADDED
Binary file (5.24 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/__pycache__/parasite_axes.cpython-310.pyc ADDED
Binary file (8.86 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/anchored_artists.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib import _api, transforms
2
+ from matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox,
3
+ DrawingArea, TextArea, VPacker)
4
+ from matplotlib.patches import (Rectangle, Ellipse, ArrowStyle,
5
+ FancyArrowPatch, PathPatch)
6
+ from matplotlib.text import TextPath
7
+
8
+ __all__ = ['AnchoredDrawingArea', 'AnchoredAuxTransformBox',
9
+ 'AnchoredEllipse', 'AnchoredSizeBar', 'AnchoredDirectionArrows']
10
+
11
+
12
+ class AnchoredDrawingArea(AnchoredOffsetbox):
13
+ def __init__(self, width, height, xdescent, ydescent,
14
+ loc, pad=0.4, borderpad=0.5, prop=None, frameon=True,
15
+ **kwargs):
16
+ """
17
+ An anchored container with a fixed size and fillable `.DrawingArea`.
18
+
19
+ Artists added to the *drawing_area* will have their coordinates
20
+ interpreted as pixels. Any transformations set on the artists will be
21
+ overridden.
22
+
23
+ Parameters
24
+ ----------
25
+ width, height : float
26
+ Width and height of the container, in pixels.
27
+ xdescent, ydescent : float
28
+ Descent of the container in the x- and y- direction, in pixels.
29
+ loc : str
30
+ Location of this artist. Valid locations are
31
+ 'upper left', 'upper center', 'upper right',
32
+ 'center left', 'center', 'center right',
33
+ 'lower left', 'lower center', 'lower right'.
34
+ For backward compatibility, numeric values are accepted as well.
35
+ See the parameter *loc* of `.Legend` for details.
36
+ pad : float, default: 0.4
37
+ Padding around the child objects, in fraction of the font size.
38
+ borderpad : float, default: 0.5
39
+ Border padding, in fraction of the font size.
40
+ prop : `~matplotlib.font_manager.FontProperties`, optional
41
+ Font property used as a reference for paddings.
42
+ frameon : bool, default: True
43
+ If True, draw a box around this artist.
44
+ **kwargs
45
+ Keyword arguments forwarded to `.AnchoredOffsetbox`.
46
+
47
+ Attributes
48
+ ----------
49
+ drawing_area : `~matplotlib.offsetbox.DrawingArea`
50
+ A container for artists to display.
51
+
52
+ Examples
53
+ --------
54
+ To display blue and red circles of different sizes in the upper right
55
+ of an Axes *ax*:
56
+
57
+ >>> ada = AnchoredDrawingArea(20, 20, 0, 0,
58
+ ... loc='upper right', frameon=False)
59
+ >>> ada.drawing_area.add_artist(Circle((10, 10), 10, fc="b"))
60
+ >>> ada.drawing_area.add_artist(Circle((30, 10), 5, fc="r"))
61
+ >>> ax.add_artist(ada)
62
+ """
63
+ self.da = DrawingArea(width, height, xdescent, ydescent)
64
+ self.drawing_area = self.da
65
+
66
+ super().__init__(
67
+ loc, pad=pad, borderpad=borderpad, child=self.da, prop=None,
68
+ frameon=frameon, **kwargs
69
+ )
70
+
71
+
72
+ class AnchoredAuxTransformBox(AnchoredOffsetbox):
73
+ def __init__(self, transform, loc,
74
+ pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs):
75
+ """
76
+ An anchored container with transformed coordinates.
77
+
78
+ Artists added to the *drawing_area* are scaled according to the
79
+ coordinates of the transformation used. The dimensions of this artist
80
+ will scale to contain the artists added.
81
+
82
+ Parameters
83
+ ----------
84
+ transform : `~matplotlib.transforms.Transform`
85
+ The transformation object for the coordinate system in use, i.e.,
86
+ :attr:`matplotlib.axes.Axes.transData`.
87
+ loc : str
88
+ Location of this artist. Valid locations are
89
+ 'upper left', 'upper center', 'upper right',
90
+ 'center left', 'center', 'center right',
91
+ 'lower left', 'lower center', 'lower right'.
92
+ For backward compatibility, numeric values are accepted as well.
93
+ See the parameter *loc* of `.Legend` for details.
94
+ pad : float, default: 0.4
95
+ Padding around the child objects, in fraction of the font size.
96
+ borderpad : float, default: 0.5
97
+ Border padding, in fraction of the font size.
98
+ prop : `~matplotlib.font_manager.FontProperties`, optional
99
+ Font property used as a reference for paddings.
100
+ frameon : bool, default: True
101
+ If True, draw a box around this artist.
102
+ **kwargs
103
+ Keyword arguments forwarded to `.AnchoredOffsetbox`.
104
+
105
+ Attributes
106
+ ----------
107
+ drawing_area : `~matplotlib.offsetbox.AuxTransformBox`
108
+ A container for artists to display.
109
+
110
+ Examples
111
+ --------
112
+ To display an ellipse in the upper left, with a width of 0.1 and
113
+ height of 0.4 in data coordinates:
114
+
115
+ >>> box = AnchoredAuxTransformBox(ax.transData, loc='upper left')
116
+ >>> el = Ellipse((0, 0), width=0.1, height=0.4, angle=30)
117
+ >>> box.drawing_area.add_artist(el)
118
+ >>> ax.add_artist(box)
119
+ """
120
+ self.drawing_area = AuxTransformBox(transform)
121
+
122
+ super().__init__(loc, pad=pad, borderpad=borderpad,
123
+ child=self.drawing_area, prop=prop, frameon=frameon,
124
+ **kwargs)
125
+
126
+
127
+ @_api.deprecated("3.8")
128
+ class AnchoredEllipse(AnchoredOffsetbox):
129
+ def __init__(self, transform, width, height, angle, loc,
130
+ pad=0.1, borderpad=0.1, prop=None, frameon=True, **kwargs):
131
+ """
132
+ Draw an anchored ellipse of a given size.
133
+
134
+ Parameters
135
+ ----------
136
+ transform : `~matplotlib.transforms.Transform`
137
+ The transformation object for the coordinate system in use, i.e.,
138
+ :attr:`matplotlib.axes.Axes.transData`.
139
+ width, height : float
140
+ Width and height of the ellipse, given in coordinates of
141
+ *transform*.
142
+ angle : float
143
+ Rotation of the ellipse, in degrees, anti-clockwise.
144
+ loc : str
145
+ Location of the ellipse. Valid locations are
146
+ 'upper left', 'upper center', 'upper right',
147
+ 'center left', 'center', 'center right',
148
+ 'lower left', 'lower center', 'lower right'.
149
+ For backward compatibility, numeric values are accepted as well.
150
+ See the parameter *loc* of `.Legend` for details.
151
+ pad : float, default: 0.1
152
+ Padding around the ellipse, in fraction of the font size.
153
+ borderpad : float, default: 0.1
154
+ Border padding, in fraction of the font size.
155
+ frameon : bool, default: True
156
+ If True, draw a box around the ellipse.
157
+ prop : `~matplotlib.font_manager.FontProperties`, optional
158
+ Font property used as a reference for paddings.
159
+ **kwargs
160
+ Keyword arguments forwarded to `.AnchoredOffsetbox`.
161
+
162
+ Attributes
163
+ ----------
164
+ ellipse : `~matplotlib.patches.Ellipse`
165
+ Ellipse patch drawn.
166
+ """
167
+ self._box = AuxTransformBox(transform)
168
+ self.ellipse = Ellipse((0, 0), width, height, angle=angle)
169
+ self._box.add_artist(self.ellipse)
170
+
171
+ super().__init__(loc, pad=pad, borderpad=borderpad, child=self._box,
172
+ prop=prop, frameon=frameon, **kwargs)
173
+
174
+
175
+ class AnchoredSizeBar(AnchoredOffsetbox):
176
+ def __init__(self, transform, size, label, loc,
177
+ pad=0.1, borderpad=0.1, sep=2,
178
+ frameon=True, size_vertical=0, color='black',
179
+ label_top=False, fontproperties=None, fill_bar=None,
180
+ **kwargs):
181
+ """
182
+ Draw a horizontal scale bar with a center-aligned label underneath.
183
+
184
+ Parameters
185
+ ----------
186
+ transform : `~matplotlib.transforms.Transform`
187
+ The transformation object for the coordinate system in use, i.e.,
188
+ :attr:`matplotlib.axes.Axes.transData`.
189
+ size : float
190
+ Horizontal length of the size bar, given in coordinates of
191
+ *transform*.
192
+ label : str
193
+ Label to display.
194
+ loc : str
195
+ Location of the size bar. Valid locations are
196
+ 'upper left', 'upper center', 'upper right',
197
+ 'center left', 'center', 'center right',
198
+ 'lower left', 'lower center', 'lower right'.
199
+ For backward compatibility, numeric values are accepted as well.
200
+ See the parameter *loc* of `.Legend` for details.
201
+ pad : float, default: 0.1
202
+ Padding around the label and size bar, in fraction of the font
203
+ size.
204
+ borderpad : float, default: 0.1
205
+ Border padding, in fraction of the font size.
206
+ sep : float, default: 2
207
+ Separation between the label and the size bar, in points.
208
+ frameon : bool, default: True
209
+ If True, draw a box around the horizontal bar and label.
210
+ size_vertical : float, default: 0
211
+ Vertical length of the size bar, given in coordinates of
212
+ *transform*.
213
+ color : str, default: 'black'
214
+ Color for the size bar and label.
215
+ label_top : bool, default: False
216
+ If True, the label will be over the size bar.
217
+ fontproperties : `~matplotlib.font_manager.FontProperties`, optional
218
+ Font properties for the label text.
219
+ fill_bar : bool, optional
220
+ If True and if *size_vertical* is nonzero, the size bar will
221
+ be filled in with the color specified by the size bar.
222
+ Defaults to True if *size_vertical* is greater than
223
+ zero and False otherwise.
224
+ **kwargs
225
+ Keyword arguments forwarded to `.AnchoredOffsetbox`.
226
+
227
+ Attributes
228
+ ----------
229
+ size_bar : `~matplotlib.offsetbox.AuxTransformBox`
230
+ Container for the size bar.
231
+ txt_label : `~matplotlib.offsetbox.TextArea`
232
+ Container for the label of the size bar.
233
+
234
+ Notes
235
+ -----
236
+ If *prop* is passed as a keyword argument, but *fontproperties* is
237
+ not, then *prop* is assumed to be the intended *fontproperties*.
238
+ Using both *prop* and *fontproperties* is not supported.
239
+
240
+ Examples
241
+ --------
242
+ >>> import matplotlib.pyplot as plt
243
+ >>> import numpy as np
244
+ >>> from mpl_toolkits.axes_grid1.anchored_artists import (
245
+ ... AnchoredSizeBar)
246
+ >>> fig, ax = plt.subplots()
247
+ >>> ax.imshow(np.random.random((10, 10)))
248
+ >>> bar = AnchoredSizeBar(ax.transData, 3, '3 data units', 4)
249
+ >>> ax.add_artist(bar)
250
+ >>> fig.show()
251
+
252
+ Using all the optional parameters
253
+
254
+ >>> import matplotlib.font_manager as fm
255
+ >>> fontprops = fm.FontProperties(size=14, family='monospace')
256
+ >>> bar = AnchoredSizeBar(ax.transData, 3, '3 units', 4, pad=0.5,
257
+ ... sep=5, borderpad=0.5, frameon=False,
258
+ ... size_vertical=0.5, color='white',
259
+ ... fontproperties=fontprops)
260
+ """
261
+ if fill_bar is None:
262
+ fill_bar = size_vertical > 0
263
+
264
+ self.size_bar = AuxTransformBox(transform)
265
+ self.size_bar.add_artist(Rectangle((0, 0), size, size_vertical,
266
+ fill=fill_bar, facecolor=color,
267
+ edgecolor=color))
268
+
269
+ if fontproperties is None and 'prop' in kwargs:
270
+ fontproperties = kwargs.pop('prop')
271
+
272
+ if fontproperties is None:
273
+ textprops = {'color': color}
274
+ else:
275
+ textprops = {'color': color, 'fontproperties': fontproperties}
276
+
277
+ self.txt_label = TextArea(label, textprops=textprops)
278
+
279
+ if label_top:
280
+ _box_children = [self.txt_label, self.size_bar]
281
+ else:
282
+ _box_children = [self.size_bar, self.txt_label]
283
+
284
+ self._box = VPacker(children=_box_children,
285
+ align="center",
286
+ pad=0, sep=sep)
287
+
288
+ super().__init__(loc, pad=pad, borderpad=borderpad, child=self._box,
289
+ prop=fontproperties, frameon=frameon, **kwargs)
290
+
291
+
292
+ class AnchoredDirectionArrows(AnchoredOffsetbox):
293
+ def __init__(self, transform, label_x, label_y, length=0.15,
294
+ fontsize=0.08, loc='upper left', angle=0, aspect_ratio=1,
295
+ pad=0.4, borderpad=0.4, frameon=False, color='w', alpha=1,
296
+ sep_x=0.01, sep_y=0, fontproperties=None, back_length=0.15,
297
+ head_width=10, head_length=15, tail_width=2,
298
+ text_props=None, arrow_props=None,
299
+ **kwargs):
300
+ """
301
+ Draw two perpendicular arrows to indicate directions.
302
+
303
+ Parameters
304
+ ----------
305
+ transform : `~matplotlib.transforms.Transform`
306
+ The transformation object for the coordinate system in use, i.e.,
307
+ :attr:`matplotlib.axes.Axes.transAxes`.
308
+ label_x, label_y : str
309
+ Label text for the x and y arrows
310
+ length : float, default: 0.15
311
+ Length of the arrow, given in coordinates of *transform*.
312
+ fontsize : float, default: 0.08
313
+ Size of label strings, given in coordinates of *transform*.
314
+ loc : str, default: 'upper left'
315
+ Location of the arrow. Valid locations are
316
+ 'upper left', 'upper center', 'upper right',
317
+ 'center left', 'center', 'center right',
318
+ 'lower left', 'lower center', 'lower right'.
319
+ For backward compatibility, numeric values are accepted as well.
320
+ See the parameter *loc* of `.Legend` for details.
321
+ angle : float, default: 0
322
+ The angle of the arrows in degrees.
323
+ aspect_ratio : float, default: 1
324
+ The ratio of the length of arrow_x and arrow_y.
325
+ Negative numbers can be used to change the direction.
326
+ pad : float, default: 0.4
327
+ Padding around the labels and arrows, in fraction of the font size.
328
+ borderpad : float, default: 0.4
329
+ Border padding, in fraction of the font size.
330
+ frameon : bool, default: False
331
+ If True, draw a box around the arrows and labels.
332
+ color : str, default: 'white'
333
+ Color for the arrows and labels.
334
+ alpha : float, default: 1
335
+ Alpha values of the arrows and labels
336
+ sep_x, sep_y : float, default: 0.01 and 0 respectively
337
+ Separation between the arrows and labels in coordinates of
338
+ *transform*.
339
+ fontproperties : `~matplotlib.font_manager.FontProperties`, optional
340
+ Font properties for the label text.
341
+ back_length : float, default: 0.15
342
+ Fraction of the arrow behind the arrow crossing.
343
+ head_width : float, default: 10
344
+ Width of arrow head, sent to `.ArrowStyle`.
345
+ head_length : float, default: 15
346
+ Length of arrow head, sent to `.ArrowStyle`.
347
+ tail_width : float, default: 2
348
+ Width of arrow tail, sent to `.ArrowStyle`.
349
+ text_props, arrow_props : dict
350
+ Properties of the text and arrows, passed to `.TextPath` and
351
+ `.FancyArrowPatch`.
352
+ **kwargs
353
+ Keyword arguments forwarded to `.AnchoredOffsetbox`.
354
+
355
+ Attributes
356
+ ----------
357
+ arrow_x, arrow_y : `~matplotlib.patches.FancyArrowPatch`
358
+ Arrow x and y
359
+ text_path_x, text_path_y : `~matplotlib.text.TextPath`
360
+ Path for arrow labels
361
+ p_x, p_y : `~matplotlib.patches.PathPatch`
362
+ Patch for arrow labels
363
+ box : `~matplotlib.offsetbox.AuxTransformBox`
364
+ Container for the arrows and labels.
365
+
366
+ Notes
367
+ -----
368
+ If *prop* is passed as a keyword argument, but *fontproperties* is
369
+ not, then *prop* is assumed to be the intended *fontproperties*.
370
+ Using both *prop* and *fontproperties* is not supported.
371
+
372
+ Examples
373
+ --------
374
+ >>> import matplotlib.pyplot as plt
375
+ >>> import numpy as np
376
+ >>> from mpl_toolkits.axes_grid1.anchored_artists import (
377
+ ... AnchoredDirectionArrows)
378
+ >>> fig, ax = plt.subplots()
379
+ >>> ax.imshow(np.random.random((10, 10)))
380
+ >>> arrows = AnchoredDirectionArrows(ax.transAxes, '111', '110')
381
+ >>> ax.add_artist(arrows)
382
+ >>> fig.show()
383
+
384
+ Using several of the optional parameters, creating downward pointing
385
+ arrow and high contrast text labels.
386
+
387
+ >>> import matplotlib.font_manager as fm
388
+ >>> fontprops = fm.FontProperties(family='monospace')
389
+ >>> arrows = AnchoredDirectionArrows(ax.transAxes, 'East', 'South',
390
+ ... loc='lower left', color='k',
391
+ ... aspect_ratio=-1, sep_x=0.02,
392
+ ... sep_y=-0.01,
393
+ ... text_props={'ec':'w', 'fc':'k'},
394
+ ... fontproperties=fontprops)
395
+ """
396
+ if arrow_props is None:
397
+ arrow_props = {}
398
+
399
+ if text_props is None:
400
+ text_props = {}
401
+
402
+ arrowstyle = ArrowStyle("Simple",
403
+ head_width=head_width,
404
+ head_length=head_length,
405
+ tail_width=tail_width)
406
+
407
+ if fontproperties is None and 'prop' in kwargs:
408
+ fontproperties = kwargs.pop('prop')
409
+
410
+ if 'color' not in arrow_props:
411
+ arrow_props['color'] = color
412
+
413
+ if 'alpha' not in arrow_props:
414
+ arrow_props['alpha'] = alpha
415
+
416
+ if 'color' not in text_props:
417
+ text_props['color'] = color
418
+
419
+ if 'alpha' not in text_props:
420
+ text_props['alpha'] = alpha
421
+
422
+ t_start = transform
423
+ t_end = t_start + transforms.Affine2D().rotate_deg(angle)
424
+
425
+ self.box = AuxTransformBox(t_end)
426
+
427
+ length_x = length
428
+ length_y = length*aspect_ratio
429
+
430
+ self.arrow_x = FancyArrowPatch(
431
+ (0, back_length*length_y),
432
+ (length_x, back_length*length_y),
433
+ arrowstyle=arrowstyle,
434
+ shrinkA=0.0,
435
+ shrinkB=0.0,
436
+ **arrow_props)
437
+
438
+ self.arrow_y = FancyArrowPatch(
439
+ (back_length*length_x, 0),
440
+ (back_length*length_x, length_y),
441
+ arrowstyle=arrowstyle,
442
+ shrinkA=0.0,
443
+ shrinkB=0.0,
444
+ **arrow_props)
445
+
446
+ self.box.add_artist(self.arrow_x)
447
+ self.box.add_artist(self.arrow_y)
448
+
449
+ text_path_x = TextPath((
450
+ length_x+sep_x, back_length*length_y+sep_y), label_x,
451
+ size=fontsize, prop=fontproperties)
452
+ self.p_x = PathPatch(text_path_x, transform=t_start, **text_props)
453
+ self.box.add_artist(self.p_x)
454
+
455
+ text_path_y = TextPath((
456
+ length_x*back_length+sep_x, length_y*(1-back_length)+sep_y),
457
+ label_y, size=fontsize, prop=fontproperties)
458
+ self.p_y = PathPatch(text_path_y, **text_props)
459
+ self.box.add_artist(self.p_y)
460
+
461
+ super().__init__(loc, pad=pad, borderpad=borderpad, child=self.box,
462
+ frameon=frameon, **kwargs)
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_divider.py ADDED
@@ -0,0 +1,694 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper classes to adjust the positions of multiple axes at drawing time.
3
+ """
4
+
5
+ import functools
6
+
7
+ import numpy as np
8
+
9
+ import matplotlib as mpl
10
+ from matplotlib import _api
11
+ from matplotlib.gridspec import SubplotSpec
12
+ import matplotlib.transforms as mtransforms
13
+ from . import axes_size as Size
14
+
15
+
16
+ class Divider:
17
+ """
18
+ An Axes positioning class.
19
+
20
+ The divider is initialized with lists of horizontal and vertical sizes
21
+ (:mod:`mpl_toolkits.axes_grid1.axes_size`) based on which a given
22
+ rectangular area will be divided.
23
+
24
+ The `new_locator` method then creates a callable object
25
+ that can be used as the *axes_locator* of the axes.
26
+ """
27
+
28
+ def __init__(self, fig, pos, horizontal, vertical,
29
+ aspect=None, anchor="C"):
30
+ """
31
+ Parameters
32
+ ----------
33
+ fig : Figure
34
+ pos : tuple of 4 floats
35
+ Position of the rectangle that will be divided.
36
+ horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
37
+ Sizes for horizontal division.
38
+ vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
39
+ Sizes for vertical division.
40
+ aspect : bool, optional
41
+ Whether overall rectangular area is reduced so that the relative
42
+ part of the horizontal and vertical scales have the same scale.
43
+ anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
44
+ 'NW', 'W'}, default: 'C'
45
+ Placement of the reduced rectangle, when *aspect* is True.
46
+ """
47
+
48
+ self._fig = fig
49
+ self._pos = pos
50
+ self._horizontal = horizontal
51
+ self._vertical = vertical
52
+ self._anchor = anchor
53
+ self.set_anchor(anchor)
54
+ self._aspect = aspect
55
+ self._xrefindex = 0
56
+ self._yrefindex = 0
57
+ self._locator = None
58
+
59
+ def get_horizontal_sizes(self, renderer):
60
+ return np.array([s.get_size(renderer) for s in self.get_horizontal()])
61
+
62
+ def get_vertical_sizes(self, renderer):
63
+ return np.array([s.get_size(renderer) for s in self.get_vertical()])
64
+
65
+ def set_position(self, pos):
66
+ """
67
+ Set the position of the rectangle.
68
+
69
+ Parameters
70
+ ----------
71
+ pos : tuple of 4 floats
72
+ position of the rectangle that will be divided
73
+ """
74
+ self._pos = pos
75
+
76
+ def get_position(self):
77
+ """Return the position of the rectangle."""
78
+ return self._pos
79
+
80
+ def set_anchor(self, anchor):
81
+ """
82
+ Parameters
83
+ ----------
84
+ anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
85
+ 'NW', 'W'}
86
+ Either an (*x*, *y*) pair of relative coordinates (0 is left or
87
+ bottom, 1 is right or top), 'C' (center), or a cardinal direction
88
+ ('SW', southwest, is bottom left, etc.).
89
+
90
+ See Also
91
+ --------
92
+ .Axes.set_anchor
93
+ """
94
+ if isinstance(anchor, str):
95
+ _api.check_in_list(mtransforms.Bbox.coefs, anchor=anchor)
96
+ elif not isinstance(anchor, (tuple, list)) or len(anchor) != 2:
97
+ raise TypeError("anchor must be str or 2-tuple")
98
+ self._anchor = anchor
99
+
100
+ def get_anchor(self):
101
+ """Return the anchor."""
102
+ return self._anchor
103
+
104
+ def get_subplotspec(self):
105
+ return None
106
+
107
+ def set_horizontal(self, h):
108
+ """
109
+ Parameters
110
+ ----------
111
+ h : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
112
+ sizes for horizontal division
113
+ """
114
+ self._horizontal = h
115
+
116
+ def get_horizontal(self):
117
+ """Return horizontal sizes."""
118
+ return self._horizontal
119
+
120
+ def set_vertical(self, v):
121
+ """
122
+ Parameters
123
+ ----------
124
+ v : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
125
+ sizes for vertical division
126
+ """
127
+ self._vertical = v
128
+
129
+ def get_vertical(self):
130
+ """Return vertical sizes."""
131
+ return self._vertical
132
+
133
+ def set_aspect(self, aspect=False):
134
+ """
135
+ Parameters
136
+ ----------
137
+ aspect : bool
138
+ """
139
+ self._aspect = aspect
140
+
141
+ def get_aspect(self):
142
+ """Return aspect."""
143
+ return self._aspect
144
+
145
+ def set_locator(self, _locator):
146
+ self._locator = _locator
147
+
148
+ def get_locator(self):
149
+ return self._locator
150
+
151
+ def get_position_runtime(self, ax, renderer):
152
+ if self._locator is None:
153
+ return self.get_position()
154
+ else:
155
+ return self._locator(ax, renderer).bounds
156
+
157
+ @staticmethod
158
+ def _calc_k(sizes, total):
159
+ # sizes is a (n, 2) array of (rel_size, abs_size); this method finds
160
+ # the k factor such that sum(rel_size * k + abs_size) == total.
161
+ rel_sum, abs_sum = sizes.sum(0)
162
+ return (total - abs_sum) / rel_sum if rel_sum else 0
163
+
164
+ @staticmethod
165
+ def _calc_offsets(sizes, k):
166
+ # Apply k factors to (n, 2) sizes array of (rel_size, abs_size); return
167
+ # the resulting cumulative offset positions.
168
+ return np.cumsum([0, *(sizes @ [k, 1])])
169
+
170
+ def new_locator(self, nx, ny, nx1=None, ny1=None):
171
+ """
172
+ Return an axes locator callable for the specified cell.
173
+
174
+ Parameters
175
+ ----------
176
+ nx, nx1 : int
177
+ Integers specifying the column-position of the
178
+ cell. When *nx1* is None, a single *nx*-th column is
179
+ specified. Otherwise, location of columns spanning between *nx*
180
+ to *nx1* (but excluding *nx1*-th column) is specified.
181
+ ny, ny1 : int
182
+ Same as *nx* and *nx1*, but for row positions.
183
+ """
184
+ if nx1 is None:
185
+ nx1 = nx + 1
186
+ if ny1 is None:
187
+ ny1 = ny + 1
188
+ # append_size("left") adds a new size at the beginning of the
189
+ # horizontal size lists; this shift transforms e.g.
190
+ # new_locator(nx=2, ...) into effectively new_locator(nx=3, ...). To
191
+ # take that into account, instead of recording nx, we record
192
+ # nx-self._xrefindex, where _xrefindex is shifted by 1 by each
193
+ # append_size("left"), and re-add self._xrefindex back to nx in
194
+ # _locate, when the actual axes position is computed. Ditto for y.
195
+ xref = self._xrefindex
196
+ yref = self._yrefindex
197
+ locator = functools.partial(
198
+ self._locate, nx - xref, ny - yref, nx1 - xref, ny1 - yref)
199
+ locator.get_subplotspec = self.get_subplotspec
200
+ return locator
201
+
202
+ @_api.deprecated(
203
+ "3.8", alternative="divider.new_locator(...)(ax, renderer)")
204
+ def locate(self, nx, ny, nx1=None, ny1=None, axes=None, renderer=None):
205
+ """
206
+ Implementation of ``divider.new_locator().__call__``.
207
+
208
+ Parameters
209
+ ----------
210
+ nx, nx1 : int
211
+ Integers specifying the column-position of the cell. When *nx1* is
212
+ None, a single *nx*-th column is specified. Otherwise, the
213
+ location of columns spanning between *nx* to *nx1* (but excluding
214
+ *nx1*-th column) is specified.
215
+ ny, ny1 : int
216
+ Same as *nx* and *nx1*, but for row positions.
217
+ axes
218
+ renderer
219
+ """
220
+ xref = self._xrefindex
221
+ yref = self._yrefindex
222
+ return self._locate(
223
+ nx - xref, (nx + 1 if nx1 is None else nx1) - xref,
224
+ ny - yref, (ny + 1 if ny1 is None else ny1) - yref,
225
+ axes, renderer)
226
+
227
+ def _locate(self, nx, ny, nx1, ny1, axes, renderer):
228
+ """
229
+ Implementation of ``divider.new_locator().__call__``.
230
+
231
+ The axes locator callable returned by ``new_locator()`` is created as
232
+ a `functools.partial` of this method with *nx*, *ny*, *nx1*, and *ny1*
233
+ specifying the requested cell.
234
+ """
235
+ nx += self._xrefindex
236
+ nx1 += self._xrefindex
237
+ ny += self._yrefindex
238
+ ny1 += self._yrefindex
239
+
240
+ fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
241
+ x, y, w, h = self.get_position_runtime(axes, renderer)
242
+
243
+ hsizes = self.get_horizontal_sizes(renderer)
244
+ vsizes = self.get_vertical_sizes(renderer)
245
+ k_h = self._calc_k(hsizes, fig_w * w)
246
+ k_v = self._calc_k(vsizes, fig_h * h)
247
+
248
+ if self.get_aspect():
249
+ k = min(k_h, k_v)
250
+ ox = self._calc_offsets(hsizes, k)
251
+ oy = self._calc_offsets(vsizes, k)
252
+
253
+ ww = (ox[-1] - ox[0]) / fig_w
254
+ hh = (oy[-1] - oy[0]) / fig_h
255
+ pb = mtransforms.Bbox.from_bounds(x, y, w, h)
256
+ pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
257
+ x0, y0 = pb1.anchored(self.get_anchor(), pb).p0
258
+
259
+ else:
260
+ ox = self._calc_offsets(hsizes, k_h)
261
+ oy = self._calc_offsets(vsizes, k_v)
262
+ x0, y0 = x, y
263
+
264
+ if nx1 is None:
265
+ nx1 = -1
266
+ if ny1 is None:
267
+ ny1 = -1
268
+
269
+ x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
270
+ y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
271
+
272
+ return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
273
+
274
+ def append_size(self, position, size):
275
+ _api.check_in_list(["left", "right", "bottom", "top"],
276
+ position=position)
277
+ if position == "left":
278
+ self._horizontal.insert(0, size)
279
+ self._xrefindex += 1
280
+ elif position == "right":
281
+ self._horizontal.append(size)
282
+ elif position == "bottom":
283
+ self._vertical.insert(0, size)
284
+ self._yrefindex += 1
285
+ else: # 'top'
286
+ self._vertical.append(size)
287
+
288
+ def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None):
289
+ """
290
+ Add auto-adjustable padding around *use_axes* to take their decorations
291
+ (title, labels, ticks, ticklabels) into account during layout.
292
+
293
+ Parameters
294
+ ----------
295
+ use_axes : `~matplotlib.axes.Axes` or list of `~matplotlib.axes.Axes`
296
+ The Axes whose decorations are taken into account.
297
+ pad : float, default: 0.1
298
+ Additional padding in inches.
299
+ adjust_dirs : list of {"left", "right", "bottom", "top"}, optional
300
+ The sides where padding is added; defaults to all four sides.
301
+ """
302
+ if adjust_dirs is None:
303
+ adjust_dirs = ["left", "right", "bottom", "top"]
304
+ for d in adjust_dirs:
305
+ self.append_size(d, Size._AxesDecorationsSize(use_axes, d) + pad)
306
+
307
+
308
+ @_api.deprecated("3.8")
309
+ class AxesLocator:
310
+ """
311
+ A callable object which returns the position and size of a given
312
+ `.AxesDivider` cell.
313
+ """
314
+
315
+ def __init__(self, axes_divider, nx, ny, nx1=None, ny1=None):
316
+ """
317
+ Parameters
318
+ ----------
319
+ axes_divider : `~mpl_toolkits.axes_grid1.axes_divider.AxesDivider`
320
+ nx, nx1 : int
321
+ Integers specifying the column-position of the
322
+ cell. When *nx1* is None, a single *nx*-th column is
323
+ specified. Otherwise, location of columns spanning between *nx*
324
+ to *nx1* (but excluding *nx1*-th column) is specified.
325
+ ny, ny1 : int
326
+ Same as *nx* and *nx1*, but for row positions.
327
+ """
328
+ self._axes_divider = axes_divider
329
+
330
+ _xrefindex = axes_divider._xrefindex
331
+ _yrefindex = axes_divider._yrefindex
332
+
333
+ self._nx, self._ny = nx - _xrefindex, ny - _yrefindex
334
+
335
+ if nx1 is None:
336
+ nx1 = len(self._axes_divider)
337
+ if ny1 is None:
338
+ ny1 = len(self._axes_divider[0])
339
+
340
+ self._nx1 = nx1 - _xrefindex
341
+ self._ny1 = ny1 - _yrefindex
342
+
343
+ def __call__(self, axes, renderer):
344
+
345
+ _xrefindex = self._axes_divider._xrefindex
346
+ _yrefindex = self._axes_divider._yrefindex
347
+
348
+ return self._axes_divider.locate(self._nx + _xrefindex,
349
+ self._ny + _yrefindex,
350
+ self._nx1 + _xrefindex,
351
+ self._ny1 + _yrefindex,
352
+ axes,
353
+ renderer)
354
+
355
+ def get_subplotspec(self):
356
+ return self._axes_divider.get_subplotspec()
357
+
358
+
359
+ class SubplotDivider(Divider):
360
+ """
361
+ The Divider class whose rectangle area is specified as a subplot geometry.
362
+ """
363
+
364
+ def __init__(self, fig, *args, horizontal=None, vertical=None,
365
+ aspect=None, anchor='C'):
366
+ """
367
+ Parameters
368
+ ----------
369
+ fig : `~matplotlib.figure.Figure`
370
+
371
+ *args : tuple (*nrows*, *ncols*, *index*) or int
372
+ The array of subplots in the figure has dimensions ``(nrows,
373
+ ncols)``, and *index* is the index of the subplot being created.
374
+ *index* starts at 1 in the upper left corner and increases to the
375
+ right.
376
+
377
+ If *nrows*, *ncols*, and *index* are all single digit numbers, then
378
+ *args* can be passed as a single 3-digit number (e.g. 234 for
379
+ (2, 3, 4)).
380
+ horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional
381
+ Sizes for horizontal division.
382
+ vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional
383
+ Sizes for vertical division.
384
+ aspect : bool, optional
385
+ Whether overall rectangular area is reduced so that the relative
386
+ part of the horizontal and vertical scales have the same scale.
387
+ anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
388
+ 'NW', 'W'}, default: 'C'
389
+ Placement of the reduced rectangle, when *aspect* is True.
390
+ """
391
+ self.figure = fig
392
+ super().__init__(fig, [0, 0, 1, 1],
393
+ horizontal=horizontal or [], vertical=vertical or [],
394
+ aspect=aspect, anchor=anchor)
395
+ self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
396
+
397
+ def get_position(self):
398
+ """Return the bounds of the subplot box."""
399
+ return self.get_subplotspec().get_position(self.figure).bounds
400
+
401
+ def get_subplotspec(self):
402
+ """Get the SubplotSpec instance."""
403
+ return self._subplotspec
404
+
405
+ def set_subplotspec(self, subplotspec):
406
+ """Set the SubplotSpec instance."""
407
+ self._subplotspec = subplotspec
408
+ self.set_position(subplotspec.get_position(self.figure))
409
+
410
+
411
+ class AxesDivider(Divider):
412
+ """
413
+ Divider based on the preexisting axes.
414
+ """
415
+
416
+ def __init__(self, axes, xref=None, yref=None):
417
+ """
418
+ Parameters
419
+ ----------
420
+ axes : :class:`~matplotlib.axes.Axes`
421
+ xref
422
+ yref
423
+ """
424
+ self._axes = axes
425
+ if xref is None:
426
+ self._xref = Size.AxesX(axes)
427
+ else:
428
+ self._xref = xref
429
+ if yref is None:
430
+ self._yref = Size.AxesY(axes)
431
+ else:
432
+ self._yref = yref
433
+
434
+ super().__init__(fig=axes.get_figure(), pos=None,
435
+ horizontal=[self._xref], vertical=[self._yref],
436
+ aspect=None, anchor="C")
437
+
438
+ def _get_new_axes(self, *, axes_class=None, **kwargs):
439
+ axes = self._axes
440
+ if axes_class is None:
441
+ axes_class = type(axes)
442
+ return axes_class(axes.get_figure(), axes.get_position(original=True),
443
+ **kwargs)
444
+
445
+ def new_horizontal(self, size, pad=None, pack_start=False, **kwargs):
446
+ """
447
+ Helper method for ``append_axes("left")`` and ``append_axes("right")``.
448
+
449
+ See the documentation of `append_axes` for more details.
450
+
451
+ :meta private:
452
+ """
453
+ if pad is None:
454
+ pad = mpl.rcParams["figure.subplot.wspace"] * self._xref
455
+ pos = "left" if pack_start else "right"
456
+ if pad:
457
+ if not isinstance(pad, Size._Base):
458
+ pad = Size.from_any(pad, fraction_ref=self._xref)
459
+ self.append_size(pos, pad)
460
+ if not isinstance(size, Size._Base):
461
+ size = Size.from_any(size, fraction_ref=self._xref)
462
+ self.append_size(pos, size)
463
+ locator = self.new_locator(
464
+ nx=0 if pack_start else len(self._horizontal) - 1,
465
+ ny=self._yrefindex)
466
+ ax = self._get_new_axes(**kwargs)
467
+ ax.set_axes_locator(locator)
468
+ return ax
469
+
470
+ def new_vertical(self, size, pad=None, pack_start=False, **kwargs):
471
+ """
472
+ Helper method for ``append_axes("top")`` and ``append_axes("bottom")``.
473
+
474
+ See the documentation of `append_axes` for more details.
475
+
476
+ :meta private:
477
+ """
478
+ if pad is None:
479
+ pad = mpl.rcParams["figure.subplot.hspace"] * self._yref
480
+ pos = "bottom" if pack_start else "top"
481
+ if pad:
482
+ if not isinstance(pad, Size._Base):
483
+ pad = Size.from_any(pad, fraction_ref=self._yref)
484
+ self.append_size(pos, pad)
485
+ if not isinstance(size, Size._Base):
486
+ size = Size.from_any(size, fraction_ref=self._yref)
487
+ self.append_size(pos, size)
488
+ locator = self.new_locator(
489
+ nx=self._xrefindex,
490
+ ny=0 if pack_start else len(self._vertical) - 1)
491
+ ax = self._get_new_axes(**kwargs)
492
+ ax.set_axes_locator(locator)
493
+ return ax
494
+
495
+ def append_axes(self, position, size, pad=None, *, axes_class=None,
496
+ **kwargs):
497
+ """
498
+ Add a new axes on a given side of the main axes.
499
+
500
+ Parameters
501
+ ----------
502
+ position : {"left", "right", "bottom", "top"}
503
+ Where the new axes is positioned relative to the main axes.
504
+ size : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
505
+ The axes width or height. float or str arguments are interpreted
506
+ as ``axes_size.from_any(size, AxesX(<main_axes>))`` for left or
507
+ right axes, and likewise with ``AxesY`` for bottom or top axes.
508
+ pad : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
509
+ Padding between the axes. float or str arguments are interpreted
510
+ as for *size*. Defaults to :rc:`figure.subplot.wspace` times the
511
+ main Axes width (left or right axes) or :rc:`figure.subplot.hspace`
512
+ times the main Axes height (bottom or top axes).
513
+ axes_class : subclass type of `~.axes.Axes`, optional
514
+ The type of the new axes. Defaults to the type of the main axes.
515
+ **kwargs
516
+ All extra keywords arguments are passed to the created axes.
517
+ """
518
+ create_axes, pack_start = _api.check_getitem({
519
+ "left": (self.new_horizontal, True),
520
+ "right": (self.new_horizontal, False),
521
+ "bottom": (self.new_vertical, True),
522
+ "top": (self.new_vertical, False),
523
+ }, position=position)
524
+ ax = create_axes(
525
+ size, pad, pack_start=pack_start, axes_class=axes_class, **kwargs)
526
+ self._fig.add_axes(ax)
527
+ return ax
528
+
529
+ def get_aspect(self):
530
+ if self._aspect is None:
531
+ aspect = self._axes.get_aspect()
532
+ if aspect == "auto":
533
+ return False
534
+ else:
535
+ return True
536
+ else:
537
+ return self._aspect
538
+
539
+ def get_position(self):
540
+ if self._pos is None:
541
+ bbox = self._axes.get_position(original=True)
542
+ return bbox.bounds
543
+ else:
544
+ return self._pos
545
+
546
+ def get_anchor(self):
547
+ if self._anchor is None:
548
+ return self._axes.get_anchor()
549
+ else:
550
+ return self._anchor
551
+
552
+ def get_subplotspec(self):
553
+ return self._axes.get_subplotspec()
554
+
555
+
556
+ # Helper for HBoxDivider/VBoxDivider.
557
+ # The variable names are written for a horizontal layout, but the calculations
558
+ # work identically for vertical layouts.
559
+ def _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor):
560
+
561
+ total_width = fig_w * w
562
+ max_height = fig_h * h
563
+
564
+ # Determine the k factors.
565
+ n = len(equal_heights)
566
+ eq_rels, eq_abss = equal_heights.T
567
+ sm_rels, sm_abss = summed_widths.T
568
+ A = np.diag([*eq_rels, 0])
569
+ A[:n, -1] = -1
570
+ A[-1, :-1] = sm_rels
571
+ B = [*(-eq_abss), total_width - sm_abss.sum()]
572
+ # A @ K = B: This finds factors {k_0, ..., k_{N-1}, H} so that
573
+ # eq_rel_i * k_i + eq_abs_i = H for all i: all axes have the same height
574
+ # sum(sm_rel_i * k_i + sm_abs_i) = total_width: fixed total width
575
+ # (foo_rel_i * k_i + foo_abs_i will end up being the size of foo.)
576
+ *karray, height = np.linalg.solve(A, B)
577
+ if height > max_height: # Additionally, upper-bound the height.
578
+ karray = (max_height - eq_abss) / eq_rels
579
+
580
+ # Compute the offsets corresponding to these factors.
581
+ ox = np.cumsum([0, *(sm_rels * karray + sm_abss)])
582
+ ww = (ox[-1] - ox[0]) / fig_w
583
+ h0_rel, h0_abs = equal_heights[0]
584
+ hh = (karray[0]*h0_rel + h0_abs) / fig_h
585
+ pb = mtransforms.Bbox.from_bounds(x, y, w, h)
586
+ pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
587
+ x0, y0 = pb1.anchored(anchor, pb).p0
588
+
589
+ return x0, y0, ox, hh
590
+
591
+
592
+ class HBoxDivider(SubplotDivider):
593
+ """
594
+ A `.SubplotDivider` for laying out axes horizontally, while ensuring that
595
+ they have equal heights.
596
+
597
+ Examples
598
+ --------
599
+ .. plot:: gallery/axes_grid1/demo_axes_hbox_divider.py
600
+ """
601
+
602
+ def new_locator(self, nx, nx1=None):
603
+ """
604
+ Create an axes locator callable for the specified cell.
605
+
606
+ Parameters
607
+ ----------
608
+ nx, nx1 : int
609
+ Integers specifying the column-position of the
610
+ cell. When *nx1* is None, a single *nx*-th column is
611
+ specified. Otherwise, location of columns spanning between *nx*
612
+ to *nx1* (but excluding *nx1*-th column) is specified.
613
+ """
614
+ return super().new_locator(nx, 0, nx1, 0)
615
+
616
+ def _locate(self, nx, ny, nx1, ny1, axes, renderer):
617
+ # docstring inherited
618
+ nx += self._xrefindex
619
+ nx1 += self._xrefindex
620
+ fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
621
+ x, y, w, h = self.get_position_runtime(axes, renderer)
622
+ summed_ws = self.get_horizontal_sizes(renderer)
623
+ equal_hs = self.get_vertical_sizes(renderer)
624
+ x0, y0, ox, hh = _locate(
625
+ x, y, w, h, summed_ws, equal_hs, fig_w, fig_h, self.get_anchor())
626
+ if nx1 is None:
627
+ nx1 = -1
628
+ x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
629
+ y1, h1 = y0, hh
630
+ return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
631
+
632
+
633
+ class VBoxDivider(SubplotDivider):
634
+ """
635
+ A `.SubplotDivider` for laying out axes vertically, while ensuring that
636
+ they have equal widths.
637
+ """
638
+
639
+ def new_locator(self, ny, ny1=None):
640
+ """
641
+ Create an axes locator callable for the specified cell.
642
+
643
+ Parameters
644
+ ----------
645
+ ny, ny1 : int
646
+ Integers specifying the row-position of the
647
+ cell. When *ny1* is None, a single *ny*-th row is
648
+ specified. Otherwise, location of rows spanning between *ny*
649
+ to *ny1* (but excluding *ny1*-th row) is specified.
650
+ """
651
+ return super().new_locator(0, ny, 0, ny1)
652
+
653
+ def _locate(self, nx, ny, nx1, ny1, axes, renderer):
654
+ # docstring inherited
655
+ ny += self._yrefindex
656
+ ny1 += self._yrefindex
657
+ fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
658
+ x, y, w, h = self.get_position_runtime(axes, renderer)
659
+ summed_hs = self.get_vertical_sizes(renderer)
660
+ equal_ws = self.get_horizontal_sizes(renderer)
661
+ y0, x0, oy, ww = _locate(
662
+ y, x, h, w, summed_hs, equal_ws, fig_h, fig_w, self.get_anchor())
663
+ if ny1 is None:
664
+ ny1 = -1
665
+ x1, w1 = x0, ww
666
+ y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
667
+ return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
668
+
669
+
670
+ def make_axes_locatable(axes):
671
+ divider = AxesDivider(axes)
672
+ locator = divider.new_locator(nx=0, ny=0)
673
+ axes.set_axes_locator(locator)
674
+
675
+ return divider
676
+
677
+
678
+ def make_axes_area_auto_adjustable(
679
+ ax, use_axes=None, pad=0.1, adjust_dirs=None):
680
+ """
681
+ Add auto-adjustable padding around *ax* to take its decorations (title,
682
+ labels, ticks, ticklabels) into account during layout, using
683
+ `.Divider.add_auto_adjustable_area`.
684
+
685
+ By default, padding is determined from the decorations of *ax*.
686
+ Pass *use_axes* to consider the decorations of other Axes instead.
687
+ """
688
+ if adjust_dirs is None:
689
+ adjust_dirs = ["left", "right", "bottom", "top"]
690
+ divider = make_axes_locatable(ax)
691
+ if use_axes is None:
692
+ use_axes = ax
693
+ divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad,
694
+ adjust_dirs=adjust_dirs)
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_grid.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numbers import Number
2
+ import functools
3
+ from types import MethodType
4
+
5
+ import numpy as np
6
+
7
+ from matplotlib import _api, cbook
8
+ from matplotlib.gridspec import SubplotSpec
9
+
10
+ from .axes_divider import Size, SubplotDivider, Divider
11
+ from .mpl_axes import Axes, SimpleAxisArtist
12
+
13
+
14
+ class CbarAxesBase:
15
+ def __init__(self, *args, orientation, **kwargs):
16
+ self.orientation = orientation
17
+ super().__init__(*args, **kwargs)
18
+
19
+ def colorbar(self, mappable, **kwargs):
20
+ return self.figure.colorbar(
21
+ mappable, cax=self, location=self.orientation, **kwargs)
22
+
23
+ @_api.deprecated("3.8", alternative="ax.tick_params and colorbar.set_label")
24
+ def toggle_label(self, b):
25
+ axis = self.axis[self.orientation]
26
+ axis.toggle(ticklabels=b, label=b)
27
+
28
+
29
+ _cbaraxes_class_factory = cbook._make_class_factory(CbarAxesBase, "Cbar{}")
30
+
31
+
32
+ class Grid:
33
+ """
34
+ A grid of Axes.
35
+
36
+ In Matplotlib, the Axes location (and size) is specified in normalized
37
+ figure coordinates. This may not be ideal for images that needs to be
38
+ displayed with a given aspect ratio; for example, it is difficult to
39
+ display multiple images of a same size with some fixed padding between
40
+ them. AxesGrid can be used in such case.
41
+
42
+ Attributes
43
+ ----------
44
+ axes_all : list of Axes
45
+ A flat list of Axes. Note that you can also access this directly
46
+ from the grid. The following is equivalent ::
47
+
48
+ grid[i] == grid.axes_all[i]
49
+ len(grid) == len(grid.axes_all)
50
+
51
+ axes_column : list of list of Axes
52
+ A 2D list of Axes where the first index is the column. This results
53
+ in the usage pattern ``grid.axes_column[col][row]``.
54
+ axes_row : list of list of Axes
55
+ A 2D list of Axes where the first index is the row. This results
56
+ in the usage pattern ``grid.axes_row[row][col]``.
57
+ axes_llc : Axes
58
+ The Axes in the lower left corner.
59
+ ngrids : int
60
+ Number of Axes in the grid.
61
+ """
62
+
63
+ _defaultAxesClass = Axes
64
+
65
+ def __init__(self, fig,
66
+ rect,
67
+ nrows_ncols,
68
+ ngrids=None,
69
+ direction="row",
70
+ axes_pad=0.02,
71
+ *,
72
+ share_all=False,
73
+ share_x=True,
74
+ share_y=True,
75
+ label_mode="L",
76
+ axes_class=None,
77
+ aspect=False,
78
+ ):
79
+ """
80
+ Parameters
81
+ ----------
82
+ fig : `.Figure`
83
+ The parent figure.
84
+ rect : (float, float, float, float), (int, int, int), int, or \
85
+ `~.SubplotSpec`
86
+ The axes position, as a ``(left, bottom, width, height)`` tuple,
87
+ as a three-digit subplot position code (e.g., ``(1, 2, 1)`` or
88
+ ``121``), or as a `~.SubplotSpec`.
89
+ nrows_ncols : (int, int)
90
+ Number of rows and columns in the grid.
91
+ ngrids : int or None, default: None
92
+ If not None, only the first *ngrids* axes in the grid are created.
93
+ direction : {"row", "column"}, default: "row"
94
+ Whether axes are created in row-major ("row by row") or
95
+ column-major order ("column by column"). This also affects the
96
+ order in which axes are accessed using indexing (``grid[index]``).
97
+ axes_pad : float or (float, float), default: 0.02
98
+ Padding or (horizontal padding, vertical padding) between axes, in
99
+ inches.
100
+ share_all : bool, default: False
101
+ Whether all axes share their x- and y-axis. Overrides *share_x*
102
+ and *share_y*.
103
+ share_x : bool, default: True
104
+ Whether all axes of a column share their x-axis.
105
+ share_y : bool, default: True
106
+ Whether all axes of a row share their y-axis.
107
+ label_mode : {"L", "1", "all", "keep"}, default: "L"
108
+ Determines which axes will get tick labels:
109
+
110
+ - "L": All axes on the left column get vertical tick labels;
111
+ all axes on the bottom row get horizontal tick labels.
112
+ - "1": Only the bottom left axes is labelled.
113
+ - "all": All axes are labelled.
114
+ - "keep": Do not do anything.
115
+
116
+ axes_class : subclass of `matplotlib.axes.Axes`, default: `.mpl_axes.Axes`
117
+ The type of Axes to create.
118
+ aspect : bool, default: False
119
+ Whether the axes aspect ratio follows the aspect ratio of the data
120
+ limits.
121
+ """
122
+ self._nrows, self._ncols = nrows_ncols
123
+
124
+ if ngrids is None:
125
+ ngrids = self._nrows * self._ncols
126
+ else:
127
+ if not 0 < ngrids <= self._nrows * self._ncols:
128
+ raise ValueError(
129
+ "ngrids must be positive and not larger than nrows*ncols")
130
+
131
+ self.ngrids = ngrids
132
+
133
+ self._horiz_pad_size, self._vert_pad_size = map(
134
+ Size.Fixed, np.broadcast_to(axes_pad, 2))
135
+
136
+ _api.check_in_list(["column", "row"], direction=direction)
137
+ self._direction = direction
138
+
139
+ if axes_class is None:
140
+ axes_class = self._defaultAxesClass
141
+ elif isinstance(axes_class, (list, tuple)):
142
+ cls, kwargs = axes_class
143
+ axes_class = functools.partial(cls, **kwargs)
144
+
145
+ kw = dict(horizontal=[], vertical=[], aspect=aspect)
146
+ if isinstance(rect, (Number, SubplotSpec)):
147
+ self._divider = SubplotDivider(fig, rect, **kw)
148
+ elif len(rect) == 3:
149
+ self._divider = SubplotDivider(fig, *rect, **kw)
150
+ elif len(rect) == 4:
151
+ self._divider = Divider(fig, rect, **kw)
152
+ else:
153
+ raise TypeError("Incorrect rect format")
154
+
155
+ rect = self._divider.get_position()
156
+
157
+ axes_array = np.full((self._nrows, self._ncols), None, dtype=object)
158
+ for i in range(self.ngrids):
159
+ col, row = self._get_col_row(i)
160
+ if share_all:
161
+ sharex = sharey = axes_array[0, 0]
162
+ else:
163
+ sharex = axes_array[0, col] if share_x else None
164
+ sharey = axes_array[row, 0] if share_y else None
165
+ axes_array[row, col] = axes_class(
166
+ fig, rect, sharex=sharex, sharey=sharey)
167
+ self.axes_all = axes_array.ravel(
168
+ order="C" if self._direction == "row" else "F").tolist()
169
+ self.axes_column = axes_array.T.tolist()
170
+ self.axes_row = axes_array.tolist()
171
+ self.axes_llc = self.axes_column[0][-1]
172
+
173
+ self._init_locators()
174
+
175
+ for ax in self.axes_all:
176
+ fig.add_axes(ax)
177
+
178
+ self.set_label_mode(label_mode)
179
+
180
+ def _init_locators(self):
181
+ self._divider.set_horizontal(
182
+ [Size.Scaled(1), self._horiz_pad_size] * (self._ncols-1) + [Size.Scaled(1)])
183
+ self._divider.set_vertical(
184
+ [Size.Scaled(1), self._vert_pad_size] * (self._nrows-1) + [Size.Scaled(1)])
185
+ for i in range(self.ngrids):
186
+ col, row = self._get_col_row(i)
187
+ self.axes_all[i].set_axes_locator(
188
+ self._divider.new_locator(nx=2 * col, ny=2 * (self._nrows - 1 - row)))
189
+
190
+ def _get_col_row(self, n):
191
+ if self._direction == "column":
192
+ col, row = divmod(n, self._nrows)
193
+ else:
194
+ row, col = divmod(n, self._ncols)
195
+
196
+ return col, row
197
+
198
+ # Good to propagate __len__ if we have __getitem__
199
+ def __len__(self):
200
+ return len(self.axes_all)
201
+
202
+ def __getitem__(self, i):
203
+ return self.axes_all[i]
204
+
205
+ def get_geometry(self):
206
+ """
207
+ Return the number of rows and columns of the grid as (nrows, ncols).
208
+ """
209
+ return self._nrows, self._ncols
210
+
211
+ def set_axes_pad(self, axes_pad):
212
+ """
213
+ Set the padding between the axes.
214
+
215
+ Parameters
216
+ ----------
217
+ axes_pad : (float, float)
218
+ The padding (horizontal pad, vertical pad) in inches.
219
+ """
220
+ self._horiz_pad_size.fixed_size = axes_pad[0]
221
+ self._vert_pad_size.fixed_size = axes_pad[1]
222
+
223
+ def get_axes_pad(self):
224
+ """
225
+ Return the axes padding.
226
+
227
+ Returns
228
+ -------
229
+ hpad, vpad
230
+ Padding (horizontal pad, vertical pad) in inches.
231
+ """
232
+ return (self._horiz_pad_size.fixed_size,
233
+ self._vert_pad_size.fixed_size)
234
+
235
+ def set_aspect(self, aspect):
236
+ """Set the aspect of the SubplotDivider."""
237
+ self._divider.set_aspect(aspect)
238
+
239
+ def get_aspect(self):
240
+ """Return the aspect of the SubplotDivider."""
241
+ return self._divider.get_aspect()
242
+
243
+ def set_label_mode(self, mode):
244
+ """
245
+ Define which axes have tick labels.
246
+
247
+ Parameters
248
+ ----------
249
+ mode : {"L", "1", "all", "keep"}
250
+ The label mode:
251
+
252
+ - "L": All axes on the left column get vertical tick labels;
253
+ all axes on the bottom row get horizontal tick labels.
254
+ - "1": Only the bottom left axes is labelled.
255
+ - "all": All axes are labelled.
256
+ - "keep": Do not do anything.
257
+ """
258
+ _api.check_in_list(["all", "L", "1", "keep"], mode=mode)
259
+ is_last_row, is_first_col = (
260
+ np.mgrid[:self._nrows, :self._ncols] == [[[self._nrows - 1]], [[0]]])
261
+ if mode == "all":
262
+ bottom = left = np.full((self._nrows, self._ncols), True)
263
+ elif mode == "L":
264
+ bottom = is_last_row
265
+ left = is_first_col
266
+ elif mode == "1":
267
+ bottom = left = is_last_row & is_first_col
268
+ else:
269
+ return
270
+ for i in range(self._nrows):
271
+ for j in range(self._ncols):
272
+ ax = self.axes_row[i][j]
273
+ if isinstance(ax.axis, MethodType):
274
+ bottom_axis = SimpleAxisArtist(ax.xaxis, 1, ax.spines["bottom"])
275
+ left_axis = SimpleAxisArtist(ax.yaxis, 1, ax.spines["left"])
276
+ else:
277
+ bottom_axis = ax.axis["bottom"]
278
+ left_axis = ax.axis["left"]
279
+ bottom_axis.toggle(ticklabels=bottom[i, j], label=bottom[i, j])
280
+ left_axis.toggle(ticklabels=left[i, j], label=left[i, j])
281
+
282
+ def get_divider(self):
283
+ return self._divider
284
+
285
+ def set_axes_locator(self, locator):
286
+ self._divider.set_locator(locator)
287
+
288
+ def get_axes_locator(self):
289
+ return self._divider.get_locator()
290
+
291
+
292
+ class ImageGrid(Grid):
293
+ """
294
+ A grid of Axes for Image display.
295
+
296
+ This class is a specialization of `~.axes_grid1.axes_grid.Grid` for displaying a
297
+ grid of images. In particular, it forces all axes in a column to share their x-axis
298
+ and all axes in a row to share their y-axis. It further provides helpers to add
299
+ colorbars to some or all axes.
300
+ """
301
+
302
+ def __init__(self, fig,
303
+ rect,
304
+ nrows_ncols,
305
+ ngrids=None,
306
+ direction="row",
307
+ axes_pad=0.02,
308
+ *,
309
+ share_all=False,
310
+ aspect=True,
311
+ label_mode="L",
312
+ cbar_mode=None,
313
+ cbar_location="right",
314
+ cbar_pad=None,
315
+ cbar_size="5%",
316
+ cbar_set_cax=True,
317
+ axes_class=None,
318
+ ):
319
+ """
320
+ Parameters
321
+ ----------
322
+ fig : `.Figure`
323
+ The parent figure.
324
+ rect : (float, float, float, float) or int
325
+ The axes position, as a ``(left, bottom, width, height)`` tuple or
326
+ as a three-digit subplot position code (e.g., "121").
327
+ nrows_ncols : (int, int)
328
+ Number of rows and columns in the grid.
329
+ ngrids : int or None, default: None
330
+ If not None, only the first *ngrids* axes in the grid are created.
331
+ direction : {"row", "column"}, default: "row"
332
+ Whether axes are created in row-major ("row by row") or
333
+ column-major order ("column by column"). This also affects the
334
+ order in which axes are accessed using indexing (``grid[index]``).
335
+ axes_pad : float or (float, float), default: 0.02in
336
+ Padding or (horizontal padding, vertical padding) between axes, in
337
+ inches.
338
+ share_all : bool, default: False
339
+ Whether all axes share their x- and y-axis. Note that in any case,
340
+ all axes in a column share their x-axis and all axes in a row share
341
+ their y-axis.
342
+ aspect : bool, default: True
343
+ Whether the axes aspect ratio follows the aspect ratio of the data
344
+ limits.
345
+ label_mode : {"L", "1", "all"}, default: "L"
346
+ Determines which axes will get tick labels:
347
+
348
+ - "L": All axes on the left column get vertical tick labels;
349
+ all axes on the bottom row get horizontal tick labels.
350
+ - "1": Only the bottom left axes is labelled.
351
+ - "all": all axes are labelled.
352
+
353
+ cbar_mode : {"each", "single", "edge", None}, default: None
354
+ Whether to create a colorbar for "each" axes, a "single" colorbar
355
+ for the entire grid, colorbars only for axes on the "edge"
356
+ determined by *cbar_location*, or no colorbars. The colorbars are
357
+ stored in the :attr:`cbar_axes` attribute.
358
+ cbar_location : {"left", "right", "bottom", "top"}, default: "right"
359
+ cbar_pad : float, default: None
360
+ Padding between the image axes and the colorbar axes.
361
+ cbar_size : size specification (see `.Size.from_any`), default: "5%"
362
+ Colorbar size.
363
+ cbar_set_cax : bool, default: True
364
+ If True, each axes in the grid has a *cax* attribute that is bound
365
+ to associated *cbar_axes*.
366
+ axes_class : subclass of `matplotlib.axes.Axes`, default: None
367
+ """
368
+ _api.check_in_list(["each", "single", "edge", None],
369
+ cbar_mode=cbar_mode)
370
+ _api.check_in_list(["left", "right", "bottom", "top"],
371
+ cbar_location=cbar_location)
372
+ self._colorbar_mode = cbar_mode
373
+ self._colorbar_location = cbar_location
374
+ self._colorbar_pad = cbar_pad
375
+ self._colorbar_size = cbar_size
376
+ # The colorbar axes are created in _init_locators().
377
+
378
+ super().__init__(
379
+ fig, rect, nrows_ncols, ngrids,
380
+ direction=direction, axes_pad=axes_pad,
381
+ share_all=share_all, share_x=True, share_y=True, aspect=aspect,
382
+ label_mode=label_mode, axes_class=axes_class)
383
+
384
+ for ax in self.cbar_axes:
385
+ fig.add_axes(ax)
386
+
387
+ if cbar_set_cax:
388
+ if self._colorbar_mode == "single":
389
+ for ax in self.axes_all:
390
+ ax.cax = self.cbar_axes[0]
391
+ elif self._colorbar_mode == "edge":
392
+ for index, ax in enumerate(self.axes_all):
393
+ col, row = self._get_col_row(index)
394
+ if self._colorbar_location in ("left", "right"):
395
+ ax.cax = self.cbar_axes[row]
396
+ else:
397
+ ax.cax = self.cbar_axes[col]
398
+ else:
399
+ for ax, cax in zip(self.axes_all, self.cbar_axes):
400
+ ax.cax = cax
401
+
402
+ def _init_locators(self):
403
+ # Slightly abusing this method to inject colorbar creation into init.
404
+
405
+ if self._colorbar_pad is None:
406
+ # horizontal or vertical arrangement?
407
+ if self._colorbar_location in ("left", "right"):
408
+ self._colorbar_pad = self._horiz_pad_size.fixed_size
409
+ else:
410
+ self._colorbar_pad = self._vert_pad_size.fixed_size
411
+ self.cbar_axes = [
412
+ _cbaraxes_class_factory(self._defaultAxesClass)(
413
+ self.axes_all[0].figure, self._divider.get_position(),
414
+ orientation=self._colorbar_location)
415
+ for _ in range(self.ngrids)]
416
+
417
+ cb_mode = self._colorbar_mode
418
+ cb_location = self._colorbar_location
419
+
420
+ h = []
421
+ v = []
422
+
423
+ h_ax_pos = []
424
+ h_cb_pos = []
425
+ if cb_mode == "single" and cb_location in ("left", "bottom"):
426
+ if cb_location == "left":
427
+ sz = self._nrows * Size.AxesX(self.axes_llc)
428
+ h.append(Size.from_any(self._colorbar_size, sz))
429
+ h.append(Size.from_any(self._colorbar_pad, sz))
430
+ locator = self._divider.new_locator(nx=0, ny=0, ny1=-1)
431
+ elif cb_location == "bottom":
432
+ sz = self._ncols * Size.AxesY(self.axes_llc)
433
+ v.append(Size.from_any(self._colorbar_size, sz))
434
+ v.append(Size.from_any(self._colorbar_pad, sz))
435
+ locator = self._divider.new_locator(nx=0, nx1=-1, ny=0)
436
+ for i in range(self.ngrids):
437
+ self.cbar_axes[i].set_visible(False)
438
+ self.cbar_axes[0].set_axes_locator(locator)
439
+ self.cbar_axes[0].set_visible(True)
440
+
441
+ for col, ax in enumerate(self.axes_row[0]):
442
+ if h:
443
+ h.append(self._horiz_pad_size)
444
+
445
+ if ax:
446
+ sz = Size.AxesX(ax, aspect="axes", ref_ax=self.axes_all[0])
447
+ else:
448
+ sz = Size.AxesX(self.axes_all[0],
449
+ aspect="axes", ref_ax=self.axes_all[0])
450
+
451
+ if (cb_location == "left"
452
+ and (cb_mode == "each"
453
+ or (cb_mode == "edge" and col == 0))):
454
+ h_cb_pos.append(len(h))
455
+ h.append(Size.from_any(self._colorbar_size, sz))
456
+ h.append(Size.from_any(self._colorbar_pad, sz))
457
+
458
+ h_ax_pos.append(len(h))
459
+ h.append(sz)
460
+
461
+ if (cb_location == "right"
462
+ and (cb_mode == "each"
463
+ or (cb_mode == "edge" and col == self._ncols - 1))):
464
+ h.append(Size.from_any(self._colorbar_pad, sz))
465
+ h_cb_pos.append(len(h))
466
+ h.append(Size.from_any(self._colorbar_size, sz))
467
+
468
+ v_ax_pos = []
469
+ v_cb_pos = []
470
+ for row, ax in enumerate(self.axes_column[0][::-1]):
471
+ if v:
472
+ v.append(self._vert_pad_size)
473
+
474
+ if ax:
475
+ sz = Size.AxesY(ax, aspect="axes", ref_ax=self.axes_all[0])
476
+ else:
477
+ sz = Size.AxesY(self.axes_all[0],
478
+ aspect="axes", ref_ax=self.axes_all[0])
479
+
480
+ if (cb_location == "bottom"
481
+ and (cb_mode == "each"
482
+ or (cb_mode == "edge" and row == 0))):
483
+ v_cb_pos.append(len(v))
484
+ v.append(Size.from_any(self._colorbar_size, sz))
485
+ v.append(Size.from_any(self._colorbar_pad, sz))
486
+
487
+ v_ax_pos.append(len(v))
488
+ v.append(sz)
489
+
490
+ if (cb_location == "top"
491
+ and (cb_mode == "each"
492
+ or (cb_mode == "edge" and row == self._nrows - 1))):
493
+ v.append(Size.from_any(self._colorbar_pad, sz))
494
+ v_cb_pos.append(len(v))
495
+ v.append(Size.from_any(self._colorbar_size, sz))
496
+
497
+ for i in range(self.ngrids):
498
+ col, row = self._get_col_row(i)
499
+ locator = self._divider.new_locator(nx=h_ax_pos[col],
500
+ ny=v_ax_pos[self._nrows-1-row])
501
+ self.axes_all[i].set_axes_locator(locator)
502
+
503
+ if cb_mode == "each":
504
+ if cb_location in ("right", "left"):
505
+ locator = self._divider.new_locator(
506
+ nx=h_cb_pos[col], ny=v_ax_pos[self._nrows - 1 - row])
507
+
508
+ elif cb_location in ("top", "bottom"):
509
+ locator = self._divider.new_locator(
510
+ nx=h_ax_pos[col], ny=v_cb_pos[self._nrows - 1 - row])
511
+
512
+ self.cbar_axes[i].set_axes_locator(locator)
513
+ elif cb_mode == "edge":
514
+ if (cb_location == "left" and col == 0
515
+ or cb_location == "right" and col == self._ncols - 1):
516
+ locator = self._divider.new_locator(
517
+ nx=h_cb_pos[0], ny=v_ax_pos[self._nrows - 1 - row])
518
+ self.cbar_axes[row].set_axes_locator(locator)
519
+ elif (cb_location == "bottom" and row == self._nrows - 1
520
+ or cb_location == "top" and row == 0):
521
+ locator = self._divider.new_locator(nx=h_ax_pos[col],
522
+ ny=v_cb_pos[0])
523
+ self.cbar_axes[col].set_axes_locator(locator)
524
+
525
+ if cb_mode == "single":
526
+ if cb_location == "right":
527
+ sz = self._nrows * Size.AxesX(self.axes_llc)
528
+ h.append(Size.from_any(self._colorbar_pad, sz))
529
+ h.append(Size.from_any(self._colorbar_size, sz))
530
+ locator = self._divider.new_locator(nx=-2, ny=0, ny1=-1)
531
+ elif cb_location == "top":
532
+ sz = self._ncols * Size.AxesY(self.axes_llc)
533
+ v.append(Size.from_any(self._colorbar_pad, sz))
534
+ v.append(Size.from_any(self._colorbar_size, sz))
535
+ locator = self._divider.new_locator(nx=0, nx1=-1, ny=-2)
536
+ if cb_location in ("right", "top"):
537
+ for i in range(self.ngrids):
538
+ self.cbar_axes[i].set_visible(False)
539
+ self.cbar_axes[0].set_axes_locator(locator)
540
+ self.cbar_axes[0].set_visible(True)
541
+ elif cb_mode == "each":
542
+ for i in range(self.ngrids):
543
+ self.cbar_axes[i].set_visible(True)
544
+ elif cb_mode == "edge":
545
+ if cb_location in ("right", "left"):
546
+ count = self._nrows
547
+ else:
548
+ count = self._ncols
549
+ for i in range(count):
550
+ self.cbar_axes[i].set_visible(True)
551
+ for j in range(i + 1, self.ngrids):
552
+ self.cbar_axes[j].set_visible(False)
553
+ else:
554
+ for i in range(self.ngrids):
555
+ self.cbar_axes[i].set_visible(False)
556
+ self.cbar_axes[i].set_position([1., 1., 0.001, 0.001],
557
+ which="active")
558
+
559
+ self._divider.set_horizontal(h)
560
+ self._divider.set_vertical(v)
561
+
562
+
563
+ AxesGrid = ImageGrid
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_rgb.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import MethodType
2
+
3
+ import numpy as np
4
+
5
+ from .axes_divider import make_axes_locatable, Size
6
+ from .mpl_axes import Axes, SimpleAxisArtist
7
+
8
+
9
+ def make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs):
10
+ """
11
+ Parameters
12
+ ----------
13
+ ax : `~matplotlib.axes.Axes`
14
+ Axes instance to create the RGB Axes in.
15
+ pad : float, optional
16
+ Fraction of the Axes height to pad.
17
+ axes_class : `matplotlib.axes.Axes` or None, optional
18
+ Axes class to use for the R, G, and B Axes. If None, use
19
+ the same class as *ax*.
20
+ **kwargs
21
+ Forwarded to *axes_class* init for the R, G, and B Axes.
22
+ """
23
+
24
+ divider = make_axes_locatable(ax)
25
+
26
+ pad_size = pad * Size.AxesY(ax)
27
+
28
+ xsize = ((1-2*pad)/3) * Size.AxesX(ax)
29
+ ysize = ((1-2*pad)/3) * Size.AxesY(ax)
30
+
31
+ divider.set_horizontal([Size.AxesX(ax), pad_size, xsize])
32
+ divider.set_vertical([ysize, pad_size, ysize, pad_size, ysize])
33
+
34
+ ax.set_axes_locator(divider.new_locator(0, 0, ny1=-1))
35
+
36
+ ax_rgb = []
37
+ if axes_class is None:
38
+ axes_class = type(ax)
39
+
40
+ for ny in [4, 2, 0]:
41
+ ax1 = axes_class(ax.get_figure(), ax.get_position(original=True),
42
+ sharex=ax, sharey=ax, **kwargs)
43
+ locator = divider.new_locator(nx=2, ny=ny)
44
+ ax1.set_axes_locator(locator)
45
+ for t in ax1.yaxis.get_ticklabels() + ax1.xaxis.get_ticklabels():
46
+ t.set_visible(False)
47
+ try:
48
+ for axis in ax1.axis.values():
49
+ axis.major_ticklabels.set_visible(False)
50
+ except AttributeError:
51
+ pass
52
+
53
+ ax_rgb.append(ax1)
54
+
55
+ fig = ax.get_figure()
56
+ for ax1 in ax_rgb:
57
+ fig.add_axes(ax1)
58
+
59
+ return ax_rgb
60
+
61
+
62
+ class RGBAxes:
63
+ """
64
+ 4-panel `~.Axes.imshow` (RGB, R, G, B).
65
+
66
+ Layout::
67
+
68
+ ┌───────────────┬─────┐
69
+ │ │ R │
70
+ │ ├─────┤
71
+ │ RGB │ G │
72
+ │ ├─────┤
73
+ │ │ B │
74
+ └───────────────┴─────┘
75
+
76
+ Subclasses can override the ``_defaultAxesClass`` attribute.
77
+ By default RGBAxes uses `.mpl_axes.Axes`.
78
+
79
+ Attributes
80
+ ----------
81
+ RGB : ``_defaultAxesClass``
82
+ The Axes object for the three-channel `~.Axes.imshow`.
83
+ R : ``_defaultAxesClass``
84
+ The Axes object for the red channel `~.Axes.imshow`.
85
+ G : ``_defaultAxesClass``
86
+ The Axes object for the green channel `~.Axes.imshow`.
87
+ B : ``_defaultAxesClass``
88
+ The Axes object for the blue channel `~.Axes.imshow`.
89
+ """
90
+
91
+ _defaultAxesClass = Axes
92
+
93
+ def __init__(self, *args, pad=0, **kwargs):
94
+ """
95
+ Parameters
96
+ ----------
97
+ pad : float, default: 0
98
+ Fraction of the Axes height to put as padding.
99
+ axes_class : `~matplotlib.axes.Axes`
100
+ Axes class to use. If not provided, ``_defaultAxesClass`` is used.
101
+ *args
102
+ Forwarded to *axes_class* init for the RGB Axes
103
+ **kwargs
104
+ Forwarded to *axes_class* init for the RGB, R, G, and B Axes
105
+ """
106
+ axes_class = kwargs.pop("axes_class", self._defaultAxesClass)
107
+ self.RGB = ax = axes_class(*args, **kwargs)
108
+ ax.get_figure().add_axes(ax)
109
+ self.R, self.G, self.B = make_rgb_axes(
110
+ ax, pad=pad, axes_class=axes_class, **kwargs)
111
+ # Set the line color and ticks for the axes.
112
+ for ax1 in [self.RGB, self.R, self.G, self.B]:
113
+ if isinstance(ax1.axis, MethodType):
114
+ ad = Axes.AxisDict(self)
115
+ ad.update(
116
+ bottom=SimpleAxisArtist(ax1.xaxis, 1, ax1.spines["bottom"]),
117
+ top=SimpleAxisArtist(ax1.xaxis, 2, ax1.spines["top"]),
118
+ left=SimpleAxisArtist(ax1.yaxis, 1, ax1.spines["left"]),
119
+ right=SimpleAxisArtist(ax1.yaxis, 2, ax1.spines["right"]))
120
+ else:
121
+ ad = ax1.axis
122
+ ad[:].line.set_color("w")
123
+ ad[:].major_ticks.set_markeredgecolor("w")
124
+
125
+ def imshow_rgb(self, r, g, b, **kwargs):
126
+ """
127
+ Create the four images {rgb, r, g, b}.
128
+
129
+ Parameters
130
+ ----------
131
+ r, g, b : array-like
132
+ The red, green, and blue arrays.
133
+ **kwargs
134
+ Forwarded to `~.Axes.imshow` calls for the four images.
135
+
136
+ Returns
137
+ -------
138
+ rgb : `~matplotlib.image.AxesImage`
139
+ r : `~matplotlib.image.AxesImage`
140
+ g : `~matplotlib.image.AxesImage`
141
+ b : `~matplotlib.image.AxesImage`
142
+ """
143
+ if not (r.shape == g.shape == b.shape):
144
+ raise ValueError(
145
+ f'Input shapes ({r.shape}, {g.shape}, {b.shape}) do not match')
146
+ RGB = np.dstack([r, g, b])
147
+ R = np.zeros_like(RGB)
148
+ R[:, :, 0] = r
149
+ G = np.zeros_like(RGB)
150
+ G[:, :, 1] = g
151
+ B = np.zeros_like(RGB)
152
+ B[:, :, 2] = b
153
+ im_rgb = self.RGB.imshow(RGB, **kwargs)
154
+ im_r = self.R.imshow(R, **kwargs)
155
+ im_g = self.G.imshow(G, **kwargs)
156
+ im_b = self.B.imshow(B, **kwargs)
157
+ return im_rgb, im_r, im_g, im_b
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_size.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Provides classes of simple units that will be used with `.AxesDivider`
3
+ class (or others) to determine the size of each Axes. The unit
4
+ classes define `get_size` method that returns a tuple of two floats,
5
+ meaning relative and absolute sizes, respectively.
6
+
7
+ Note that this class is nothing more than a simple tuple of two
8
+ floats. Take a look at the Divider class to see how these two
9
+ values are used.
10
+ """
11
+
12
+ from numbers import Real
13
+
14
+ from matplotlib import _api
15
+ from matplotlib.axes import Axes
16
+
17
+
18
+ class _Base:
19
+ def __rmul__(self, other):
20
+ return Fraction(other, self)
21
+
22
+ def __add__(self, other):
23
+ if isinstance(other, _Base):
24
+ return Add(self, other)
25
+ else:
26
+ return Add(self, Fixed(other))
27
+
28
+ def get_size(self, renderer):
29
+ """
30
+ Return two-float tuple with relative and absolute sizes.
31
+ """
32
+ raise NotImplementedError("Subclasses must implement")
33
+
34
+
35
+ class Add(_Base):
36
+ """
37
+ Sum of two sizes.
38
+ """
39
+
40
+ def __init__(self, a, b):
41
+ self._a = a
42
+ self._b = b
43
+
44
+ def get_size(self, renderer):
45
+ a_rel_size, a_abs_size = self._a.get_size(renderer)
46
+ b_rel_size, b_abs_size = self._b.get_size(renderer)
47
+ return a_rel_size + b_rel_size, a_abs_size + b_abs_size
48
+
49
+
50
+ class Fixed(_Base):
51
+ """
52
+ Simple fixed size with absolute part = *fixed_size* and relative part = 0.
53
+ """
54
+
55
+ def __init__(self, fixed_size):
56
+ _api.check_isinstance(Real, fixed_size=fixed_size)
57
+ self.fixed_size = fixed_size
58
+
59
+ def get_size(self, renderer):
60
+ rel_size = 0.
61
+ abs_size = self.fixed_size
62
+ return rel_size, abs_size
63
+
64
+
65
+ class Scaled(_Base):
66
+ """
67
+ Simple scaled(?) size with absolute part = 0 and
68
+ relative part = *scalable_size*.
69
+ """
70
+
71
+ def __init__(self, scalable_size):
72
+ self._scalable_size = scalable_size
73
+
74
+ def get_size(self, renderer):
75
+ rel_size = self._scalable_size
76
+ abs_size = 0.
77
+ return rel_size, abs_size
78
+
79
+ Scalable = Scaled
80
+
81
+
82
+ def _get_axes_aspect(ax):
83
+ aspect = ax.get_aspect()
84
+ if aspect == "auto":
85
+ aspect = 1.
86
+ return aspect
87
+
88
+
89
+ class AxesX(_Base):
90
+ """
91
+ Scaled size whose relative part corresponds to the data width
92
+ of the *axes* multiplied by the *aspect*.
93
+ """
94
+
95
+ def __init__(self, axes, aspect=1., ref_ax=None):
96
+ self._axes = axes
97
+ self._aspect = aspect
98
+ if aspect == "axes" and ref_ax is None:
99
+ raise ValueError("ref_ax must be set when aspect='axes'")
100
+ self._ref_ax = ref_ax
101
+
102
+ def get_size(self, renderer):
103
+ l1, l2 = self._axes.get_xlim()
104
+ if self._aspect == "axes":
105
+ ref_aspect = _get_axes_aspect(self._ref_ax)
106
+ aspect = ref_aspect / _get_axes_aspect(self._axes)
107
+ else:
108
+ aspect = self._aspect
109
+
110
+ rel_size = abs(l2-l1)*aspect
111
+ abs_size = 0.
112
+ return rel_size, abs_size
113
+
114
+
115
+ class AxesY(_Base):
116
+ """
117
+ Scaled size whose relative part corresponds to the data height
118
+ of the *axes* multiplied by the *aspect*.
119
+ """
120
+
121
+ def __init__(self, axes, aspect=1., ref_ax=None):
122
+ self._axes = axes
123
+ self._aspect = aspect
124
+ if aspect == "axes" and ref_ax is None:
125
+ raise ValueError("ref_ax must be set when aspect='axes'")
126
+ self._ref_ax = ref_ax
127
+
128
+ def get_size(self, renderer):
129
+ l1, l2 = self._axes.get_ylim()
130
+
131
+ if self._aspect == "axes":
132
+ ref_aspect = _get_axes_aspect(self._ref_ax)
133
+ aspect = _get_axes_aspect(self._axes)
134
+ else:
135
+ aspect = self._aspect
136
+
137
+ rel_size = abs(l2-l1)*aspect
138
+ abs_size = 0.
139
+ return rel_size, abs_size
140
+
141
+
142
+ class MaxExtent(_Base):
143
+ """
144
+ Size whose absolute part is either the largest width or the largest height
145
+ of the given *artist_list*.
146
+ """
147
+
148
+ def __init__(self, artist_list, w_or_h):
149
+ self._artist_list = artist_list
150
+ _api.check_in_list(["width", "height"], w_or_h=w_or_h)
151
+ self._w_or_h = w_or_h
152
+
153
+ def add_artist(self, a):
154
+ self._artist_list.append(a)
155
+
156
+ def get_size(self, renderer):
157
+ rel_size = 0.
158
+ extent_list = [
159
+ getattr(a.get_window_extent(renderer), self._w_or_h) / a.figure.dpi
160
+ for a in self._artist_list]
161
+ abs_size = max(extent_list, default=0)
162
+ return rel_size, abs_size
163
+
164
+
165
+ class MaxWidth(MaxExtent):
166
+ """
167
+ Size whose absolute part is the largest width of the given *artist_list*.
168
+ """
169
+
170
+ def __init__(self, artist_list):
171
+ super().__init__(artist_list, "width")
172
+
173
+
174
+ class MaxHeight(MaxExtent):
175
+ """
176
+ Size whose absolute part is the largest height of the given *artist_list*.
177
+ """
178
+
179
+ def __init__(self, artist_list):
180
+ super().__init__(artist_list, "height")
181
+
182
+
183
+ class Fraction(_Base):
184
+ """
185
+ An instance whose size is a *fraction* of the *ref_size*.
186
+
187
+ >>> s = Fraction(0.3, AxesX(ax))
188
+ """
189
+
190
+ def __init__(self, fraction, ref_size):
191
+ _api.check_isinstance(Real, fraction=fraction)
192
+ self._fraction_ref = ref_size
193
+ self._fraction = fraction
194
+
195
+ def get_size(self, renderer):
196
+ if self._fraction_ref is None:
197
+ return self._fraction, 0.
198
+ else:
199
+ r, a = self._fraction_ref.get_size(renderer)
200
+ rel_size = r*self._fraction
201
+ abs_size = a*self._fraction
202
+ return rel_size, abs_size
203
+
204
+
205
+ def from_any(size, fraction_ref=None):
206
+ """
207
+ Create a Fixed unit when the first argument is a float, or a
208
+ Fraction unit if that is a string that ends with %. The second
209
+ argument is only meaningful when Fraction unit is created.
210
+
211
+ >>> from mpl_toolkits.axes_grid1.axes_size import from_any
212
+ >>> a = from_any(1.2) # => Fixed(1.2)
213
+ >>> from_any("50%", a) # => Fraction(0.5, a)
214
+ """
215
+ if isinstance(size, Real):
216
+ return Fixed(size)
217
+ elif isinstance(size, str):
218
+ if size[-1] == "%":
219
+ return Fraction(float(size[:-1]) / 100, fraction_ref)
220
+ raise ValueError("Unknown format")
221
+
222
+
223
+ class _AxesDecorationsSize(_Base):
224
+ """
225
+ Fixed size, corresponding to the size of decorations on a given Axes side.
226
+ """
227
+
228
+ _get_size_map = {
229
+ "left": lambda tight_bb, axes_bb: axes_bb.xmin - tight_bb.xmin,
230
+ "right": lambda tight_bb, axes_bb: tight_bb.xmax - axes_bb.xmax,
231
+ "bottom": lambda tight_bb, axes_bb: axes_bb.ymin - tight_bb.ymin,
232
+ "top": lambda tight_bb, axes_bb: tight_bb.ymax - axes_bb.ymax,
233
+ }
234
+
235
+ def __init__(self, ax, direction):
236
+ _api.check_in_list(self._get_size_map, direction=direction)
237
+ self._direction = direction
238
+ self._ax_list = [ax] if isinstance(ax, Axes) else ax
239
+
240
+ def get_size(self, renderer):
241
+ sz = max([
242
+ self._get_size_map[self._direction](
243
+ ax.get_tightbbox(renderer, call_axes_locator=False), ax.bbox)
244
+ for ax in self._ax_list])
245
+ dpi = renderer.points_to_pixels(72)
246
+ abs_size = sz / dpi
247
+ rel_size = 0
248
+ return rel_size, abs_size
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/inset_locator.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A collection of functions and objects for creating or placing inset axes.
3
+ """
4
+
5
+ from matplotlib import _api, _docstring
6
+ from matplotlib.offsetbox import AnchoredOffsetbox
7
+ from matplotlib.patches import Patch, Rectangle
8
+ from matplotlib.path import Path
9
+ from matplotlib.transforms import Bbox, BboxTransformTo
10
+ from matplotlib.transforms import IdentityTransform, TransformedBbox
11
+
12
+ from . import axes_size as Size
13
+ from .parasite_axes import HostAxes
14
+
15
+
16
+ @_api.deprecated("3.8", alternative="Axes.inset_axes")
17
+ class InsetPosition:
18
+ @_docstring.dedent_interpd
19
+ def __init__(self, parent, lbwh):
20
+ """
21
+ An object for positioning an inset axes.
22
+
23
+ This is created by specifying the normalized coordinates in the axes,
24
+ instead of the figure.
25
+
26
+ Parameters
27
+ ----------
28
+ parent : `~matplotlib.axes.Axes`
29
+ Axes to use for normalizing coordinates.
30
+
31
+ lbwh : iterable of four floats
32
+ The left edge, bottom edge, width, and height of the inset axes, in
33
+ units of the normalized coordinate of the *parent* axes.
34
+
35
+ See Also
36
+ --------
37
+ :meth:`matplotlib.axes.Axes.set_axes_locator`
38
+
39
+ Examples
40
+ --------
41
+ The following bounds the inset axes to a box with 20%% of the parent
42
+ axes height and 40%% of the width. The size of the axes specified
43
+ ([0, 0, 1, 1]) ensures that the axes completely fills the bounding box:
44
+
45
+ >>> parent_axes = plt.gca()
46
+ >>> ax_ins = plt.axes([0, 0, 1, 1])
47
+ >>> ip = InsetPosition(parent_axes, [0.5, 0.1, 0.4, 0.2])
48
+ >>> ax_ins.set_axes_locator(ip)
49
+ """
50
+ self.parent = parent
51
+ self.lbwh = lbwh
52
+
53
+ def __call__(self, ax, renderer):
54
+ bbox_parent = self.parent.get_position(original=False)
55
+ trans = BboxTransformTo(bbox_parent)
56
+ bbox_inset = Bbox.from_bounds(*self.lbwh)
57
+ bb = TransformedBbox(bbox_inset, trans)
58
+ return bb
59
+
60
+
61
+ class AnchoredLocatorBase(AnchoredOffsetbox):
62
+ def __init__(self, bbox_to_anchor, offsetbox, loc,
63
+ borderpad=0.5, bbox_transform=None):
64
+ super().__init__(
65
+ loc, pad=0., child=None, borderpad=borderpad,
66
+ bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform
67
+ )
68
+
69
+ def draw(self, renderer):
70
+ raise RuntimeError("No draw method should be called")
71
+
72
+ def __call__(self, ax, renderer):
73
+ if renderer is None:
74
+ renderer = ax.figure._get_renderer()
75
+ self.axes = ax
76
+ bbox = self.get_window_extent(renderer)
77
+ px, py = self.get_offset(bbox.width, bbox.height, 0, 0, renderer)
78
+ bbox_canvas = Bbox.from_bounds(px, py, bbox.width, bbox.height)
79
+ tr = ax.figure.transSubfigure.inverted()
80
+ return TransformedBbox(bbox_canvas, tr)
81
+
82
+
83
+ class AnchoredSizeLocator(AnchoredLocatorBase):
84
+ def __init__(self, bbox_to_anchor, x_size, y_size, loc,
85
+ borderpad=0.5, bbox_transform=None):
86
+ super().__init__(
87
+ bbox_to_anchor, None, loc,
88
+ borderpad=borderpad, bbox_transform=bbox_transform
89
+ )
90
+
91
+ self.x_size = Size.from_any(x_size)
92
+ self.y_size = Size.from_any(y_size)
93
+
94
+ def get_bbox(self, renderer):
95
+ bbox = self.get_bbox_to_anchor()
96
+ dpi = renderer.points_to_pixels(72.)
97
+
98
+ r, a = self.x_size.get_size(renderer)
99
+ width = bbox.width * r + a * dpi
100
+ r, a = self.y_size.get_size(renderer)
101
+ height = bbox.height * r + a * dpi
102
+
103
+ fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
104
+ pad = self.pad * fontsize
105
+
106
+ return Bbox.from_bounds(0, 0, width, height).padded(pad)
107
+
108
+
109
+ class AnchoredZoomLocator(AnchoredLocatorBase):
110
+ def __init__(self, parent_axes, zoom, loc,
111
+ borderpad=0.5,
112
+ bbox_to_anchor=None,
113
+ bbox_transform=None):
114
+ self.parent_axes = parent_axes
115
+ self.zoom = zoom
116
+ if bbox_to_anchor is None:
117
+ bbox_to_anchor = parent_axes.bbox
118
+ super().__init__(
119
+ bbox_to_anchor, None, loc, borderpad=borderpad,
120
+ bbox_transform=bbox_transform)
121
+
122
+ def get_bbox(self, renderer):
123
+ bb = self.parent_axes.transData.transform_bbox(self.axes.viewLim)
124
+ fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
125
+ pad = self.pad * fontsize
126
+ return (
127
+ Bbox.from_bounds(
128
+ 0, 0, abs(bb.width * self.zoom), abs(bb.height * self.zoom))
129
+ .padded(pad))
130
+
131
+
132
+ class BboxPatch(Patch):
133
+ @_docstring.dedent_interpd
134
+ def __init__(self, bbox, **kwargs):
135
+ """
136
+ Patch showing the shape bounded by a Bbox.
137
+
138
+ Parameters
139
+ ----------
140
+ bbox : `~matplotlib.transforms.Bbox`
141
+ Bbox to use for the extents of this patch.
142
+
143
+ **kwargs
144
+ Patch properties. Valid arguments include:
145
+
146
+ %(Patch:kwdoc)s
147
+ """
148
+ if "transform" in kwargs:
149
+ raise ValueError("transform should not be set")
150
+
151
+ kwargs["transform"] = IdentityTransform()
152
+ super().__init__(**kwargs)
153
+ self.bbox = bbox
154
+
155
+ def get_path(self):
156
+ # docstring inherited
157
+ x0, y0, x1, y1 = self.bbox.extents
158
+ return Path._create_closed([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
159
+
160
+
161
+ class BboxConnector(Patch):
162
+ @staticmethod
163
+ def get_bbox_edge_pos(bbox, loc):
164
+ """
165
+ Return the ``(x, y)`` coordinates of corner *loc* of *bbox*; parameters
166
+ behave as documented for the `.BboxConnector` constructor.
167
+ """
168
+ x0, y0, x1, y1 = bbox.extents
169
+ if loc == 1:
170
+ return x1, y1
171
+ elif loc == 2:
172
+ return x0, y1
173
+ elif loc == 3:
174
+ return x0, y0
175
+ elif loc == 4:
176
+ return x1, y0
177
+
178
+ @staticmethod
179
+ def connect_bbox(bbox1, bbox2, loc1, loc2=None):
180
+ """
181
+ Construct a `.Path` connecting corner *loc1* of *bbox1* to corner
182
+ *loc2* of *bbox2*, where parameters behave as documented as for the
183
+ `.BboxConnector` constructor.
184
+ """
185
+ if isinstance(bbox1, Rectangle):
186
+ bbox1 = TransformedBbox(Bbox.unit(), bbox1.get_transform())
187
+ if isinstance(bbox2, Rectangle):
188
+ bbox2 = TransformedBbox(Bbox.unit(), bbox2.get_transform())
189
+ if loc2 is None:
190
+ loc2 = loc1
191
+ x1, y1 = BboxConnector.get_bbox_edge_pos(bbox1, loc1)
192
+ x2, y2 = BboxConnector.get_bbox_edge_pos(bbox2, loc2)
193
+ return Path([[x1, y1], [x2, y2]])
194
+
195
+ @_docstring.dedent_interpd
196
+ def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs):
197
+ """
198
+ Connect two bboxes with a straight line.
199
+
200
+ Parameters
201
+ ----------
202
+ bbox1, bbox2 : `~matplotlib.transforms.Bbox`
203
+ Bounding boxes to connect.
204
+
205
+ loc1, loc2 : {1, 2, 3, 4}
206
+ Corner of *bbox1* and *bbox2* to draw the line. Valid values are::
207
+
208
+ 'upper right' : 1,
209
+ 'upper left' : 2,
210
+ 'lower left' : 3,
211
+ 'lower right' : 4
212
+
213
+ *loc2* is optional and defaults to *loc1*.
214
+
215
+ **kwargs
216
+ Patch properties for the line drawn. Valid arguments include:
217
+
218
+ %(Patch:kwdoc)s
219
+ """
220
+ if "transform" in kwargs:
221
+ raise ValueError("transform should not be set")
222
+
223
+ kwargs["transform"] = IdentityTransform()
224
+ kwargs.setdefault(
225
+ "fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs)))
226
+ super().__init__(**kwargs)
227
+ self.bbox1 = bbox1
228
+ self.bbox2 = bbox2
229
+ self.loc1 = loc1
230
+ self.loc2 = loc2
231
+
232
+ def get_path(self):
233
+ # docstring inherited
234
+ return self.connect_bbox(self.bbox1, self.bbox2,
235
+ self.loc1, self.loc2)
236
+
237
+
238
+ class BboxConnectorPatch(BboxConnector):
239
+ @_docstring.dedent_interpd
240
+ def __init__(self, bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, **kwargs):
241
+ """
242
+ Connect two bboxes with a quadrilateral.
243
+
244
+ The quadrilateral is specified by two lines that start and end at
245
+ corners of the bboxes. The four sides of the quadrilateral are defined
246
+ by the two lines given, the line between the two corners specified in
247
+ *bbox1* and the line between the two corners specified in *bbox2*.
248
+
249
+ Parameters
250
+ ----------
251
+ bbox1, bbox2 : `~matplotlib.transforms.Bbox`
252
+ Bounding boxes to connect.
253
+
254
+ loc1a, loc2a, loc1b, loc2b : {1, 2, 3, 4}
255
+ The first line connects corners *loc1a* of *bbox1* and *loc2a* of
256
+ *bbox2*; the second line connects corners *loc1b* of *bbox1* and
257
+ *loc2b* of *bbox2*. Valid values are::
258
+
259
+ 'upper right' : 1,
260
+ 'upper left' : 2,
261
+ 'lower left' : 3,
262
+ 'lower right' : 4
263
+
264
+ **kwargs
265
+ Patch properties for the line drawn:
266
+
267
+ %(Patch:kwdoc)s
268
+ """
269
+ if "transform" in kwargs:
270
+ raise ValueError("transform should not be set")
271
+ super().__init__(bbox1, bbox2, loc1a, loc2a, **kwargs)
272
+ self.loc1b = loc1b
273
+ self.loc2b = loc2b
274
+
275
+ def get_path(self):
276
+ # docstring inherited
277
+ path1 = self.connect_bbox(self.bbox1, self.bbox2, self.loc1, self.loc2)
278
+ path2 = self.connect_bbox(self.bbox2, self.bbox1,
279
+ self.loc2b, self.loc1b)
280
+ path_merged = [*path1.vertices, *path2.vertices, path1.vertices[0]]
281
+ return Path(path_merged)
282
+
283
+
284
+ def _add_inset_axes(parent_axes, axes_class, axes_kwargs, axes_locator):
285
+ """Helper function to add an inset axes and disable navigation in it."""
286
+ if axes_class is None:
287
+ axes_class = HostAxes
288
+ if axes_kwargs is None:
289
+ axes_kwargs = {}
290
+ inset_axes = axes_class(
291
+ parent_axes.figure, parent_axes.get_position(),
292
+ **{"navigate": False, **axes_kwargs, "axes_locator": axes_locator})
293
+ return parent_axes.figure.add_axes(inset_axes)
294
+
295
+
296
+ @_docstring.dedent_interpd
297
+ def inset_axes(parent_axes, width, height, loc='upper right',
298
+ bbox_to_anchor=None, bbox_transform=None,
299
+ axes_class=None, axes_kwargs=None,
300
+ borderpad=0.5):
301
+ """
302
+ Create an inset axes with a given width and height.
303
+
304
+ Both sizes used can be specified either in inches or percentage.
305
+ For example,::
306
+
307
+ inset_axes(parent_axes, width='40%%', height='30%%', loc='lower left')
308
+
309
+ creates in inset axes in the lower left corner of *parent_axes* which spans
310
+ over 30%% in height and 40%% in width of the *parent_axes*. Since the usage
311
+ of `.inset_axes` may become slightly tricky when exceeding such standard
312
+ cases, it is recommended to read :doc:`the examples
313
+ </gallery/axes_grid1/inset_locator_demo>`.
314
+
315
+ Notes
316
+ -----
317
+ The meaning of *bbox_to_anchor* and *bbox_to_transform* is interpreted
318
+ differently from that of legend. The value of bbox_to_anchor
319
+ (or the return value of its get_points method; the default is
320
+ *parent_axes.bbox*) is transformed by the bbox_transform (the default
321
+ is Identity transform) and then interpreted as points in the pixel
322
+ coordinate (which is dpi dependent).
323
+
324
+ Thus, following three calls are identical and creates an inset axes
325
+ with respect to the *parent_axes*::
326
+
327
+ axins = inset_axes(parent_axes, "30%%", "40%%")
328
+ axins = inset_axes(parent_axes, "30%%", "40%%",
329
+ bbox_to_anchor=parent_axes.bbox)
330
+ axins = inset_axes(parent_axes, "30%%", "40%%",
331
+ bbox_to_anchor=(0, 0, 1, 1),
332
+ bbox_transform=parent_axes.transAxes)
333
+
334
+ Parameters
335
+ ----------
336
+ parent_axes : `matplotlib.axes.Axes`
337
+ Axes to place the inset axes.
338
+
339
+ width, height : float or str
340
+ Size of the inset axes to create. If a float is provided, it is
341
+ the size in inches, e.g. *width=1.3*. If a string is provided, it is
342
+ the size in relative units, e.g. *width='40%%'*. By default, i.e. if
343
+ neither *bbox_to_anchor* nor *bbox_transform* are specified, those
344
+ are relative to the parent_axes. Otherwise, they are to be understood
345
+ relative to the bounding box provided via *bbox_to_anchor*.
346
+
347
+ loc : str, default: 'upper right'
348
+ Location to place the inset axes. Valid locations are
349
+ 'upper left', 'upper center', 'upper right',
350
+ 'center left', 'center', 'center right',
351
+ 'lower left', 'lower center', 'lower right'.
352
+ For backward compatibility, numeric values are accepted as well.
353
+ See the parameter *loc* of `.Legend` for details.
354
+
355
+ bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional
356
+ Bbox that the inset axes will be anchored to. If None,
357
+ a tuple of (0, 0, 1, 1) is used if *bbox_transform* is set
358
+ to *parent_axes.transAxes* or *parent_axes.figure.transFigure*.
359
+ Otherwise, *parent_axes.bbox* is used. If a tuple, can be either
360
+ [left, bottom, width, height], or [left, bottom].
361
+ If the kwargs *width* and/or *height* are specified in relative units,
362
+ the 2-tuple [left, bottom] cannot be used. Note that,
363
+ unless *bbox_transform* is set, the units of the bounding box
364
+ are interpreted in the pixel coordinate. When using *bbox_to_anchor*
365
+ with tuple, it almost always makes sense to also specify
366
+ a *bbox_transform*. This might often be the axes transform
367
+ *parent_axes.transAxes*.
368
+
369
+ bbox_transform : `~matplotlib.transforms.Transform`, optional
370
+ Transformation for the bbox that contains the inset axes.
371
+ If None, a `.transforms.IdentityTransform` is used. The value
372
+ of *bbox_to_anchor* (or the return value of its get_points method)
373
+ is transformed by the *bbox_transform* and then interpreted
374
+ as points in the pixel coordinate (which is dpi dependent).
375
+ You may provide *bbox_to_anchor* in some normalized coordinate,
376
+ and give an appropriate transform (e.g., *parent_axes.transAxes*).
377
+
378
+ axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`
379
+ The type of the newly created inset axes.
380
+
381
+ axes_kwargs : dict, optional
382
+ Keyword arguments to pass to the constructor of the inset axes.
383
+ Valid arguments include:
384
+
385
+ %(Axes:kwdoc)s
386
+
387
+ borderpad : float, default: 0.5
388
+ Padding between inset axes and the bbox_to_anchor.
389
+ The units are axes font size, i.e. for a default font size of 10 points
390
+ *borderpad = 0.5* is equivalent to a padding of 5 points.
391
+
392
+ Returns
393
+ -------
394
+ inset_axes : *axes_class*
395
+ Inset axes object created.
396
+ """
397
+
398
+ if (bbox_transform in [parent_axes.transAxes, parent_axes.figure.transFigure]
399
+ and bbox_to_anchor is None):
400
+ _api.warn_external("Using the axes or figure transform requires a "
401
+ "bounding box in the respective coordinates. "
402
+ "Using bbox_to_anchor=(0, 0, 1, 1) now.")
403
+ bbox_to_anchor = (0, 0, 1, 1)
404
+ if bbox_to_anchor is None:
405
+ bbox_to_anchor = parent_axes.bbox
406
+ if (isinstance(bbox_to_anchor, tuple) and
407
+ (isinstance(width, str) or isinstance(height, str))):
408
+ if len(bbox_to_anchor) != 4:
409
+ raise ValueError("Using relative units for width or height "
410
+ "requires to provide a 4-tuple or a "
411
+ "`Bbox` instance to `bbox_to_anchor.")
412
+ return _add_inset_axes(
413
+ parent_axes, axes_class, axes_kwargs,
414
+ AnchoredSizeLocator(
415
+ bbox_to_anchor, width, height, loc=loc,
416
+ bbox_transform=bbox_transform, borderpad=borderpad))
417
+
418
+
419
+ @_docstring.dedent_interpd
420
+ def zoomed_inset_axes(parent_axes, zoom, loc='upper right',
421
+ bbox_to_anchor=None, bbox_transform=None,
422
+ axes_class=None, axes_kwargs=None,
423
+ borderpad=0.5):
424
+ """
425
+ Create an anchored inset axes by scaling a parent axes. For usage, also see
426
+ :doc:`the examples </gallery/axes_grid1/inset_locator_demo2>`.
427
+
428
+ Parameters
429
+ ----------
430
+ parent_axes : `~matplotlib.axes.Axes`
431
+ Axes to place the inset axes.
432
+
433
+ zoom : float
434
+ Scaling factor of the data axes. *zoom* > 1 will enlarge the
435
+ coordinates (i.e., "zoomed in"), while *zoom* < 1 will shrink the
436
+ coordinates (i.e., "zoomed out").
437
+
438
+ loc : str, default: 'upper right'
439
+ Location to place the inset axes. Valid locations are
440
+ 'upper left', 'upper center', 'upper right',
441
+ 'center left', 'center', 'center right',
442
+ 'lower left', 'lower center', 'lower right'.
443
+ For backward compatibility, numeric values are accepted as well.
444
+ See the parameter *loc* of `.Legend` for details.
445
+
446
+ bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional
447
+ Bbox that the inset axes will be anchored to. If None,
448
+ *parent_axes.bbox* is used. If a tuple, can be either
449
+ [left, bottom, width, height], or [left, bottom].
450
+ If the kwargs *width* and/or *height* are specified in relative units,
451
+ the 2-tuple [left, bottom] cannot be used. Note that
452
+ the units of the bounding box are determined through the transform
453
+ in use. When using *bbox_to_anchor* it almost always makes sense to
454
+ also specify a *bbox_transform*. This might often be the axes transform
455
+ *parent_axes.transAxes*.
456
+
457
+ bbox_transform : `~matplotlib.transforms.Transform`, optional
458
+ Transformation for the bbox that contains the inset axes.
459
+ If None, a `.transforms.IdentityTransform` is used (i.e. pixel
460
+ coordinates). This is useful when not providing any argument to
461
+ *bbox_to_anchor*. When using *bbox_to_anchor* it almost always makes
462
+ sense to also specify a *bbox_transform*. This might often be the
463
+ axes transform *parent_axes.transAxes*. Inversely, when specifying
464
+ the axes- or figure-transform here, be aware that not specifying
465
+ *bbox_to_anchor* will use *parent_axes.bbox*, the units of which are
466
+ in display (pixel) coordinates.
467
+
468
+ axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`
469
+ The type of the newly created inset axes.
470
+
471
+ axes_kwargs : dict, optional
472
+ Keyword arguments to pass to the constructor of the inset axes.
473
+ Valid arguments include:
474
+
475
+ %(Axes:kwdoc)s
476
+
477
+ borderpad : float, default: 0.5
478
+ Padding between inset axes and the bbox_to_anchor.
479
+ The units are axes font size, i.e. for a default font size of 10 points
480
+ *borderpad = 0.5* is equivalent to a padding of 5 points.
481
+
482
+ Returns
483
+ -------
484
+ inset_axes : *axes_class*
485
+ Inset axes object created.
486
+ """
487
+
488
+ return _add_inset_axes(
489
+ parent_axes, axes_class, axes_kwargs,
490
+ AnchoredZoomLocator(
491
+ parent_axes, zoom=zoom, loc=loc,
492
+ bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform,
493
+ borderpad=borderpad))
494
+
495
+
496
+ class _TransformedBboxWithCallback(TransformedBbox):
497
+ """
498
+ Variant of `.TransformBbox` which calls *callback* before returning points.
499
+
500
+ Used by `.mark_inset` to unstale the parent axes' viewlim as needed.
501
+ """
502
+
503
+ def __init__(self, *args, callback, **kwargs):
504
+ super().__init__(*args, **kwargs)
505
+ self._callback = callback
506
+
507
+ def get_points(self):
508
+ self._callback()
509
+ return super().get_points()
510
+
511
+
512
+ @_docstring.dedent_interpd
513
+ def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs):
514
+ """
515
+ Draw a box to mark the location of an area represented by an inset axes.
516
+
517
+ This function draws a box in *parent_axes* at the bounding box of
518
+ *inset_axes*, and shows a connection with the inset axes by drawing lines
519
+ at the corners, giving a "zoomed in" effect.
520
+
521
+ Parameters
522
+ ----------
523
+ parent_axes : `~matplotlib.axes.Axes`
524
+ Axes which contains the area of the inset axes.
525
+
526
+ inset_axes : `~matplotlib.axes.Axes`
527
+ The inset axes.
528
+
529
+ loc1, loc2 : {1, 2, 3, 4}
530
+ Corners to use for connecting the inset axes and the area in the
531
+ parent axes.
532
+
533
+ **kwargs
534
+ Patch properties for the lines and box drawn:
535
+
536
+ %(Patch:kwdoc)s
537
+
538
+ Returns
539
+ -------
540
+ pp : `~matplotlib.patches.Patch`
541
+ The patch drawn to represent the area of the inset axes.
542
+
543
+ p1, p2 : `~matplotlib.patches.Patch`
544
+ The patches connecting two corners of the inset axes and its area.
545
+ """
546
+ rect = _TransformedBboxWithCallback(
547
+ inset_axes.viewLim, parent_axes.transData,
548
+ callback=parent_axes._unstale_viewLim)
549
+
550
+ kwargs.setdefault("fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs)))
551
+ pp = BboxPatch(rect, **kwargs)
552
+ parent_axes.add_patch(pp)
553
+
554
+ p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs)
555
+ inset_axes.add_patch(p1)
556
+ p1.set_clip_on(False)
557
+ p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs)
558
+ inset_axes.add_patch(p2)
559
+ p2.set_clip_on(False)
560
+
561
+ return pp, p1, p2
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/mpl_axes.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.axes as maxes
2
+ from matplotlib.artist import Artist
3
+ from matplotlib.axis import XAxis, YAxis
4
+
5
+
6
+ class SimpleChainedObjects:
7
+ def __init__(self, objects):
8
+ self._objects = objects
9
+
10
+ def __getattr__(self, k):
11
+ _a = SimpleChainedObjects([getattr(a, k) for a in self._objects])
12
+ return _a
13
+
14
+ def __call__(self, *args, **kwargs):
15
+ for m in self._objects:
16
+ m(*args, **kwargs)
17
+
18
+
19
+ class Axes(maxes.Axes):
20
+
21
+ class AxisDict(dict):
22
+ def __init__(self, axes):
23
+ self.axes = axes
24
+ super().__init__()
25
+
26
+ def __getitem__(self, k):
27
+ if isinstance(k, tuple):
28
+ r = SimpleChainedObjects(
29
+ # super() within a list comprehension needs explicit args.
30
+ [super(Axes.AxisDict, self).__getitem__(k1) for k1 in k])
31
+ return r
32
+ elif isinstance(k, slice):
33
+ if k.start is None and k.stop is None and k.step is None:
34
+ return SimpleChainedObjects(list(self.values()))
35
+ else:
36
+ raise ValueError("Unsupported slice")
37
+ else:
38
+ return dict.__getitem__(self, k)
39
+
40
+ def __call__(self, *v, **kwargs):
41
+ return maxes.Axes.axis(self.axes, *v, **kwargs)
42
+
43
+ @property
44
+ def axis(self):
45
+ return self._axislines
46
+
47
+ def clear(self):
48
+ # docstring inherited
49
+ super().clear()
50
+ # Init axis artists.
51
+ self._axislines = self.AxisDict(self)
52
+ self._axislines.update(
53
+ bottom=SimpleAxisArtist(self.xaxis, 1, self.spines["bottom"]),
54
+ top=SimpleAxisArtist(self.xaxis, 2, self.spines["top"]),
55
+ left=SimpleAxisArtist(self.yaxis, 1, self.spines["left"]),
56
+ right=SimpleAxisArtist(self.yaxis, 2, self.spines["right"]))
57
+
58
+
59
+ class SimpleAxisArtist(Artist):
60
+ def __init__(self, axis, axisnum, spine):
61
+ self._axis = axis
62
+ self._axisnum = axisnum
63
+ self.line = spine
64
+
65
+ if isinstance(axis, XAxis):
66
+ self._axis_direction = ["bottom", "top"][axisnum-1]
67
+ elif isinstance(axis, YAxis):
68
+ self._axis_direction = ["left", "right"][axisnum-1]
69
+ else:
70
+ raise ValueError(
71
+ f"axis must be instance of XAxis or YAxis, but got {axis}")
72
+ super().__init__()
73
+
74
+ @property
75
+ def major_ticks(self):
76
+ tickline = "tick%dline" % self._axisnum
77
+ return SimpleChainedObjects([getattr(tick, tickline)
78
+ for tick in self._axis.get_major_ticks()])
79
+
80
+ @property
81
+ def major_ticklabels(self):
82
+ label = "label%d" % self._axisnum
83
+ return SimpleChainedObjects([getattr(tick, label)
84
+ for tick in self._axis.get_major_ticks()])
85
+
86
+ @property
87
+ def label(self):
88
+ return self._axis.label
89
+
90
+ def set_visible(self, b):
91
+ self.toggle(all=b)
92
+ self.line.set_visible(b)
93
+ self._axis.set_visible(True)
94
+ super().set_visible(b)
95
+
96
+ def set_label(self, txt):
97
+ self._axis.set_label_text(txt)
98
+
99
+ def toggle(self, all=None, ticks=None, ticklabels=None, label=None):
100
+
101
+ if all:
102
+ _ticks, _ticklabels, _label = True, True, True
103
+ elif all is not None:
104
+ _ticks, _ticklabels, _label = False, False, False
105
+ else:
106
+ _ticks, _ticklabels, _label = None, None, None
107
+
108
+ if ticks is not None:
109
+ _ticks = ticks
110
+ if ticklabels is not None:
111
+ _ticklabels = ticklabels
112
+ if label is not None:
113
+ _label = label
114
+
115
+ if _ticks is not None:
116
+ tickparam = {f"tick{self._axisnum}On": _ticks}
117
+ self._axis.set_tick_params(**tickparam)
118
+ if _ticklabels is not None:
119
+ tickparam = {f"label{self._axisnum}On": _ticklabels}
120
+ self._axis.set_tick_params(**tickparam)
121
+
122
+ if _label is not None:
123
+ pos = self._axis.get_label_position()
124
+ if (pos == self._axis_direction) and not _label:
125
+ self._axis.label.set_visible(False)
126
+ elif _label:
127
+ self._axis.label.set_visible(True)
128
+ self._axis.set_label_position(self._axis_direction)
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib import _api, cbook
2
+ import matplotlib.artist as martist
3
+ import matplotlib.transforms as mtransforms
4
+ from matplotlib.transforms import Bbox
5
+ from .mpl_axes import Axes
6
+
7
+
8
+ class ParasiteAxesBase:
9
+
10
+ def __init__(self, parent_axes, aux_transform=None,
11
+ *, viewlim_mode=None, **kwargs):
12
+ self._parent_axes = parent_axes
13
+ self.transAux = aux_transform
14
+ self.set_viewlim_mode(viewlim_mode)
15
+ kwargs["frameon"] = False
16
+ super().__init__(parent_axes.figure, parent_axes._position, **kwargs)
17
+
18
+ def clear(self):
19
+ super().clear()
20
+ martist.setp(self.get_children(), visible=False)
21
+ self._get_lines = self._parent_axes._get_lines
22
+ self._parent_axes.callbacks._connect_picklable(
23
+ "xlim_changed", self._sync_lims)
24
+ self._parent_axes.callbacks._connect_picklable(
25
+ "ylim_changed", self._sync_lims)
26
+
27
+ def pick(self, mouseevent):
28
+ # This most likely goes to Artist.pick (depending on axes_class given
29
+ # to the factory), which only handles pick events registered on the
30
+ # axes associated with each child:
31
+ super().pick(mouseevent)
32
+ # But parasite axes are additionally given pick events from their host
33
+ # axes (cf. HostAxesBase.pick), which we handle here:
34
+ for a in self.get_children():
35
+ if (hasattr(mouseevent.inaxes, "parasites")
36
+ and self in mouseevent.inaxes.parasites):
37
+ a.pick(mouseevent)
38
+
39
+ # aux_transform support
40
+
41
+ def _set_lim_and_transforms(self):
42
+ if self.transAux is not None:
43
+ self.transAxes = self._parent_axes.transAxes
44
+ self.transData = self.transAux + self._parent_axes.transData
45
+ self._xaxis_transform = mtransforms.blended_transform_factory(
46
+ self.transData, self.transAxes)
47
+ self._yaxis_transform = mtransforms.blended_transform_factory(
48
+ self.transAxes, self.transData)
49
+ else:
50
+ super()._set_lim_and_transforms()
51
+
52
+ def set_viewlim_mode(self, mode):
53
+ _api.check_in_list([None, "equal", "transform"], mode=mode)
54
+ self._viewlim_mode = mode
55
+
56
+ def get_viewlim_mode(self):
57
+ return self._viewlim_mode
58
+
59
+ def _sync_lims(self, parent):
60
+ viewlim = parent.viewLim.frozen()
61
+ mode = self.get_viewlim_mode()
62
+ if mode is None:
63
+ pass
64
+ elif mode == "equal":
65
+ self.viewLim.set(viewlim)
66
+ elif mode == "transform":
67
+ self.viewLim.set(viewlim.transformed(self.transAux.inverted()))
68
+ else:
69
+ _api.check_in_list([None, "equal", "transform"], mode=mode)
70
+
71
+ # end of aux_transform support
72
+
73
+
74
+ parasite_axes_class_factory = cbook._make_class_factory(
75
+ ParasiteAxesBase, "{}Parasite")
76
+ ParasiteAxes = parasite_axes_class_factory(Axes)
77
+
78
+
79
+ class HostAxesBase:
80
+ def __init__(self, *args, **kwargs):
81
+ self.parasites = []
82
+ super().__init__(*args, **kwargs)
83
+
84
+ def get_aux_axes(
85
+ self, tr=None, viewlim_mode="equal", axes_class=None, **kwargs):
86
+ """
87
+ Add a parasite axes to this host.
88
+
89
+ Despite this method's name, this should actually be thought of as an
90
+ ``add_parasite_axes`` method.
91
+
92
+ .. versionchanged:: 3.7
93
+ Defaults to same base axes class as host axes.
94
+
95
+ Parameters
96
+ ----------
97
+ tr : `~matplotlib.transforms.Transform` or None, default: None
98
+ If a `.Transform`, the following relation will hold:
99
+ ``parasite.transData = tr + host.transData``.
100
+ If None, the parasite's and the host's ``transData`` are unrelated.
101
+ viewlim_mode : {"equal", "transform", None}, default: "equal"
102
+ How the parasite's view limits are set: directly equal to the
103
+ parent axes ("equal"), equal after application of *tr*
104
+ ("transform"), or independently (None).
105
+ axes_class : subclass type of `~matplotlib.axes.Axes`, optional
106
+ The `~.axes.Axes` subclass that is instantiated. If None, the base
107
+ class of the host axes is used.
108
+ **kwargs
109
+ Other parameters are forwarded to the parasite axes constructor.
110
+ """
111
+ if axes_class is None:
112
+ axes_class = self._base_axes_class
113
+ parasite_axes_class = parasite_axes_class_factory(axes_class)
114
+ ax2 = parasite_axes_class(
115
+ self, tr, viewlim_mode=viewlim_mode, **kwargs)
116
+ # note that ax2.transData == tr + ax1.transData
117
+ # Anything you draw in ax2 will match the ticks and grids of ax1.
118
+ self.parasites.append(ax2)
119
+ ax2._remove_method = self.parasites.remove
120
+ return ax2
121
+
122
+ def draw(self, renderer):
123
+ orig_children_len = len(self._children)
124
+
125
+ locator = self.get_axes_locator()
126
+ if locator:
127
+ pos = locator(self, renderer)
128
+ self.set_position(pos, which="active")
129
+ self.apply_aspect(pos)
130
+ else:
131
+ self.apply_aspect()
132
+
133
+ rect = self.get_position()
134
+ for ax in self.parasites:
135
+ ax.apply_aspect(rect)
136
+ self._children.extend(ax.get_children())
137
+
138
+ super().draw(renderer)
139
+ del self._children[orig_children_len:]
140
+
141
+ def clear(self):
142
+ super().clear()
143
+ for ax in self.parasites:
144
+ ax.clear()
145
+
146
+ def pick(self, mouseevent):
147
+ super().pick(mouseevent)
148
+ # Also pass pick events on to parasite axes and, in turn, their
149
+ # children (cf. ParasiteAxesBase.pick)
150
+ for a in self.parasites:
151
+ a.pick(mouseevent)
152
+
153
+ def twinx(self, axes_class=None):
154
+ """
155
+ Create a twin of Axes with a shared x-axis but independent y-axis.
156
+
157
+ The y-axis of self will have ticks on the left and the returned axes
158
+ will have ticks on the right.
159
+ """
160
+ ax = self._add_twin_axes(axes_class, sharex=self)
161
+ self.axis["right"].set_visible(False)
162
+ ax.axis["right"].set_visible(True)
163
+ ax.axis["left", "top", "bottom"].set_visible(False)
164
+ return ax
165
+
166
+ def twiny(self, axes_class=None):
167
+ """
168
+ Create a twin of Axes with a shared y-axis but independent x-axis.
169
+
170
+ The x-axis of self will have ticks on the bottom and the returned axes
171
+ will have ticks on the top.
172
+ """
173
+ ax = self._add_twin_axes(axes_class, sharey=self)
174
+ self.axis["top"].set_visible(False)
175
+ ax.axis["top"].set_visible(True)
176
+ ax.axis["left", "right", "bottom"].set_visible(False)
177
+ return ax
178
+
179
+ def twin(self, aux_trans=None, axes_class=None):
180
+ """
181
+ Create a twin of Axes with no shared axis.
182
+
183
+ While self will have ticks on the left and bottom axis, the returned
184
+ axes will have ticks on the top and right axis.
185
+ """
186
+ if aux_trans is None:
187
+ aux_trans = mtransforms.IdentityTransform()
188
+ ax = self._add_twin_axes(
189
+ axes_class, aux_transform=aux_trans, viewlim_mode="transform")
190
+ self.axis["top", "right"].set_visible(False)
191
+ ax.axis["top", "right"].set_visible(True)
192
+ ax.axis["left", "bottom"].set_visible(False)
193
+ return ax
194
+
195
+ def _add_twin_axes(self, axes_class, **kwargs):
196
+ """
197
+ Helper for `.twinx`/`.twiny`/`.twin`.
198
+
199
+ *kwargs* are forwarded to the parasite axes constructor.
200
+ """
201
+ if axes_class is None:
202
+ axes_class = self._base_axes_class
203
+ ax = parasite_axes_class_factory(axes_class)(self, **kwargs)
204
+ self.parasites.append(ax)
205
+ ax._remove_method = self._remove_any_twin
206
+ return ax
207
+
208
+ def _remove_any_twin(self, ax):
209
+ self.parasites.remove(ax)
210
+ restore = ["top", "right"]
211
+ if ax._sharex:
212
+ restore.remove("top")
213
+ if ax._sharey:
214
+ restore.remove("right")
215
+ self.axis[tuple(restore)].set_visible(True)
216
+ self.axis[tuple(restore)].toggle(ticklabels=False, label=False)
217
+
218
+ @_api.make_keyword_only("3.8", "call_axes_locator")
219
+ def get_tightbbox(self, renderer=None, call_axes_locator=True,
220
+ bbox_extra_artists=None):
221
+ bbs = [
222
+ *[ax.get_tightbbox(renderer, call_axes_locator=call_axes_locator)
223
+ for ax in self.parasites],
224
+ super().get_tightbbox(renderer,
225
+ call_axes_locator=call_axes_locator,
226
+ bbox_extra_artists=bbox_extra_artists)]
227
+ return Bbox.union([b for b in bbs if b.width != 0 or b.height != 0])
228
+
229
+
230
+ host_axes_class_factory = host_subplot_class_factory = \
231
+ cbook._make_class_factory(HostAxesBase, "{}HostAxes", "_base_axes_class")
232
+ HostAxes = SubplotHost = host_axes_class_factory(Axes)
233
+
234
+
235
+ def host_axes(*args, axes_class=Axes, figure=None, **kwargs):
236
+ """
237
+ Create axes that can act as a hosts to parasitic axes.
238
+
239
+ Parameters
240
+ ----------
241
+ figure : `~matplotlib.figure.Figure`
242
+ Figure to which the axes will be added. Defaults to the current figure
243
+ `.pyplot.gcf()`.
244
+
245
+ *args, **kwargs
246
+ Will be passed on to the underlying `~.axes.Axes` object creation.
247
+ """
248
+ import matplotlib.pyplot as plt
249
+ host_axes_class = host_axes_class_factory(axes_class)
250
+ if figure is None:
251
+ figure = plt.gcf()
252
+ ax = host_axes_class(figure, *args, **kwargs)
253
+ figure.add_axes(ax)
254
+ return ax
255
+
256
+
257
+ host_subplot = host_axes
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+
4
+ # Check that the test directories exist
5
+ if not (Path(__file__).parent / "baseline_images").exists():
6
+ raise OSError(
7
+ 'The baseline image directory does not exist. '
8
+ 'This is most likely because the test data is not installed. '
9
+ 'You may need to install matplotlib from source to get the '
10
+ 'test data.')
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (490 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (316 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/test_axes_grid1.cpython-310.pyc ADDED
Binary file (24.3 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/conftest.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from matplotlib.testing.conftest import (mpl_test_settings, # noqa
2
+ pytest_configure, pytest_unconfigure)
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py ADDED
@@ -0,0 +1,792 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+ import io
3
+ import platform
4
+
5
+ import matplotlib as mpl
6
+ import matplotlib.pyplot as plt
7
+ import matplotlib.ticker as mticker
8
+ from matplotlib import cbook
9
+ from matplotlib.backend_bases import MouseEvent
10
+ from matplotlib.colors import LogNorm
11
+ from matplotlib.patches import Circle, Ellipse
12
+ from matplotlib.transforms import Bbox, TransformedBbox
13
+ from matplotlib.testing.decorators import (
14
+ check_figures_equal, image_comparison, remove_ticks_and_titles)
15
+
16
+ from mpl_toolkits.axes_grid1 import (
17
+ axes_size as Size,
18
+ host_subplot, make_axes_locatable,
19
+ Grid, AxesGrid, ImageGrid)
20
+ from mpl_toolkits.axes_grid1.anchored_artists import (
21
+ AnchoredAuxTransformBox, AnchoredDrawingArea, AnchoredEllipse,
22
+ AnchoredDirectionArrows, AnchoredSizeBar)
23
+ from mpl_toolkits.axes_grid1.axes_divider import (
24
+ Divider, HBoxDivider, make_axes_area_auto_adjustable, SubplotDivider,
25
+ VBoxDivider)
26
+ from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes
27
+ from mpl_toolkits.axes_grid1.inset_locator import (
28
+ zoomed_inset_axes, mark_inset, inset_axes, BboxConnectorPatch,
29
+ InsetPosition)
30
+ import mpl_toolkits.axes_grid1.mpl_axes
31
+ import pytest
32
+
33
+ import numpy as np
34
+ from numpy.testing import assert_array_equal, assert_array_almost_equal
35
+
36
+
37
+ def test_divider_append_axes():
38
+ fig, ax = plt.subplots()
39
+ divider = make_axes_locatable(ax)
40
+ axs = {
41
+ "main": ax,
42
+ "top": divider.append_axes("top", 1.2, pad=0.1, sharex=ax),
43
+ "bottom": divider.append_axes("bottom", 1.2, pad=0.1, sharex=ax),
44
+ "left": divider.append_axes("left", 1.2, pad=0.1, sharey=ax),
45
+ "right": divider.append_axes("right", 1.2, pad=0.1, sharey=ax),
46
+ }
47
+ fig.canvas.draw()
48
+ bboxes = {k: axs[k].get_window_extent() for k in axs}
49
+ dpi = fig.dpi
50
+ assert bboxes["top"].height == pytest.approx(1.2 * dpi)
51
+ assert bboxes["bottom"].height == pytest.approx(1.2 * dpi)
52
+ assert bboxes["left"].width == pytest.approx(1.2 * dpi)
53
+ assert bboxes["right"].width == pytest.approx(1.2 * dpi)
54
+ assert bboxes["top"].y0 - bboxes["main"].y1 == pytest.approx(0.1 * dpi)
55
+ assert bboxes["main"].y0 - bboxes["bottom"].y1 == pytest.approx(0.1 * dpi)
56
+ assert bboxes["main"].x0 - bboxes["left"].x1 == pytest.approx(0.1 * dpi)
57
+ assert bboxes["right"].x0 - bboxes["main"].x1 == pytest.approx(0.1 * dpi)
58
+ assert bboxes["left"].y0 == bboxes["main"].y0 == bboxes["right"].y0
59
+ assert bboxes["left"].y1 == bboxes["main"].y1 == bboxes["right"].y1
60
+ assert bboxes["top"].x0 == bboxes["main"].x0 == bboxes["bottom"].x0
61
+ assert bboxes["top"].x1 == bboxes["main"].x1 == bboxes["bottom"].x1
62
+
63
+
64
+ # Update style when regenerating the test image
65
+ @image_comparison(['twin_axes_empty_and_removed'], extensions=["png"], tol=1,
66
+ style=('classic', '_classic_test_patch'))
67
+ def test_twin_axes_empty_and_removed():
68
+ # Purely cosmetic font changes (avoid overlap)
69
+ mpl.rcParams.update(
70
+ {"font.size": 8, "xtick.labelsize": 8, "ytick.labelsize": 8})
71
+ generators = ["twinx", "twiny", "twin"]
72
+ modifiers = ["", "host invisible", "twin removed", "twin invisible",
73
+ "twin removed\nhost invisible"]
74
+ # Unmodified host subplot at the beginning for reference
75
+ h = host_subplot(len(modifiers)+1, len(generators), 2)
76
+ h.text(0.5, 0.5, "host_subplot",
77
+ horizontalalignment="center", verticalalignment="center")
78
+ # Host subplots with various modifications (twin*, visibility) applied
79
+ for i, (mod, gen) in enumerate(product(modifiers, generators),
80
+ len(generators) + 1):
81
+ h = host_subplot(len(modifiers)+1, len(generators), i)
82
+ t = getattr(h, gen)()
83
+ if "twin invisible" in mod:
84
+ t.axis[:].set_visible(False)
85
+ if "twin removed" in mod:
86
+ t.remove()
87
+ if "host invisible" in mod:
88
+ h.axis[:].set_visible(False)
89
+ h.text(0.5, 0.5, gen + ("\n" + mod if mod else ""),
90
+ horizontalalignment="center", verticalalignment="center")
91
+ plt.subplots_adjust(wspace=0.5, hspace=1)
92
+
93
+
94
+ def test_twin_axes_both_with_units():
95
+ host = host_subplot(111)
96
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
97
+ host.plot_date([0, 1, 2], [0, 1, 2], xdate=False, ydate=True)
98
+ twin = host.twinx()
99
+ twin.plot(["a", "b", "c"])
100
+ assert host.get_yticklabels()[0].get_text() == "00:00:00"
101
+ assert twin.get_yticklabels()[0].get_text() == "a"
102
+
103
+
104
+ def test_axesgrid_colorbar_log_smoketest():
105
+ fig = plt.figure()
106
+ grid = AxesGrid(fig, 111, # modified to be only subplot
107
+ nrows_ncols=(1, 1),
108
+ ngrids=1,
109
+ label_mode="L",
110
+ cbar_location="top",
111
+ cbar_mode="single",
112
+ )
113
+
114
+ Z = 10000 * np.random.rand(10, 10)
115
+ im = grid[0].imshow(Z, interpolation="nearest", norm=LogNorm())
116
+
117
+ grid.cbar_axes[0].colorbar(im)
118
+
119
+
120
+ def test_inset_colorbar_tight_layout_smoketest():
121
+ fig, ax = plt.subplots(1, 1)
122
+ pts = ax.scatter([0, 1], [0, 1], c=[1, 5])
123
+
124
+ cax = inset_axes(ax, width="3%", height="70%")
125
+ plt.colorbar(pts, cax=cax)
126
+
127
+ with pytest.warns(UserWarning, match="This figure includes Axes"):
128
+ # Will warn, but not raise an error
129
+ plt.tight_layout()
130
+
131
+
132
+ @image_comparison(['inset_locator.png'], style='default', remove_text=True)
133
+ def test_inset_locator():
134
+ fig, ax = plt.subplots(figsize=[5, 4])
135
+
136
+ # prepare the demo image
137
+ # Z is a 15x15 array
138
+ Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")
139
+ extent = (-3, 4, -4, 3)
140
+ Z2 = np.zeros((150, 150))
141
+ ny, nx = Z.shape
142
+ Z2[30:30+ny, 30:30+nx] = Z
143
+
144
+ ax.imshow(Z2, extent=extent, interpolation="nearest",
145
+ origin="lower")
146
+
147
+ axins = zoomed_inset_axes(ax, zoom=6, loc='upper right')
148
+ axins.imshow(Z2, extent=extent, interpolation="nearest",
149
+ origin="lower")
150
+ axins.yaxis.get_major_locator().set_params(nbins=7)
151
+ axins.xaxis.get_major_locator().set_params(nbins=7)
152
+ # sub region of the original image
153
+ x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
154
+ axins.set_xlim(x1, x2)
155
+ axins.set_ylim(y1, y2)
156
+
157
+ plt.xticks(visible=False)
158
+ plt.yticks(visible=False)
159
+
160
+ # draw a bbox of the region of the inset axes in the parent axes and
161
+ # connecting lines between the bbox and the inset axes area
162
+ mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
163
+
164
+ asb = AnchoredSizeBar(ax.transData,
165
+ 0.5,
166
+ '0.5',
167
+ loc='lower center',
168
+ pad=0.1, borderpad=0.5, sep=5,
169
+ frameon=False)
170
+ ax.add_artist(asb)
171
+
172
+
173
+ @image_comparison(['inset_axes.png'], style='default', remove_text=True)
174
+ def test_inset_axes():
175
+ fig, ax = plt.subplots(figsize=[5, 4])
176
+
177
+ # prepare the demo image
178
+ # Z is a 15x15 array
179
+ Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")
180
+ extent = (-3, 4, -4, 3)
181
+ Z2 = np.zeros((150, 150))
182
+ ny, nx = Z.shape
183
+ Z2[30:30+ny, 30:30+nx] = Z
184
+
185
+ ax.imshow(Z2, extent=extent, interpolation="nearest",
186
+ origin="lower")
187
+
188
+ # creating our inset axes with a bbox_transform parameter
189
+ axins = inset_axes(ax, width=1., height=1., bbox_to_anchor=(1, 1),
190
+ bbox_transform=ax.transAxes)
191
+
192
+ axins.imshow(Z2, extent=extent, interpolation="nearest",
193
+ origin="lower")
194
+ axins.yaxis.get_major_locator().set_params(nbins=7)
195
+ axins.xaxis.get_major_locator().set_params(nbins=7)
196
+ # sub region of the original image
197
+ x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
198
+ axins.set_xlim(x1, x2)
199
+ axins.set_ylim(y1, y2)
200
+
201
+ plt.xticks(visible=False)
202
+ plt.yticks(visible=False)
203
+
204
+ # draw a bbox of the region of the inset axes in the parent axes and
205
+ # connecting lines between the bbox and the inset axes area
206
+ mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
207
+
208
+ asb = AnchoredSizeBar(ax.transData,
209
+ 0.5,
210
+ '0.5',
211
+ loc='lower center',
212
+ pad=0.1, borderpad=0.5, sep=5,
213
+ frameon=False)
214
+ ax.add_artist(asb)
215
+
216
+
217
+ def test_inset_axes_complete():
218
+ dpi = 100
219
+ figsize = (6, 5)
220
+ fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
221
+ fig.subplots_adjust(.1, .1, .9, .9)
222
+
223
+ ins = inset_axes(ax, width=2., height=2., borderpad=0)
224
+ fig.canvas.draw()
225
+ assert_array_almost_equal(
226
+ ins.get_position().extents,
227
+ [(0.9*figsize[0]-2.)/figsize[0], (0.9*figsize[1]-2.)/figsize[1],
228
+ 0.9, 0.9])
229
+
230
+ ins = inset_axes(ax, width="40%", height="30%", borderpad=0)
231
+ fig.canvas.draw()
232
+ assert_array_almost_equal(
233
+ ins.get_position().extents, [.9-.8*.4, .9-.8*.3, 0.9, 0.9])
234
+
235
+ ins = inset_axes(ax, width=1., height=1.2, bbox_to_anchor=(200, 100),
236
+ loc=3, borderpad=0)
237
+ fig.canvas.draw()
238
+ assert_array_almost_equal(
239
+ ins.get_position().extents,
240
+ [200/dpi/figsize[0], 100/dpi/figsize[1],
241
+ (200/dpi+1)/figsize[0], (100/dpi+1.2)/figsize[1]])
242
+
243
+ ins1 = inset_axes(ax, width="35%", height="60%", loc=3, borderpad=1)
244
+ ins2 = inset_axes(ax, width="100%", height="100%",
245
+ bbox_to_anchor=(0, 0, .35, .60),
246
+ bbox_transform=ax.transAxes, loc=3, borderpad=1)
247
+ fig.canvas.draw()
248
+ assert_array_equal(ins1.get_position().extents,
249
+ ins2.get_position().extents)
250
+
251
+ with pytest.raises(ValueError):
252
+ ins = inset_axes(ax, width="40%", height="30%",
253
+ bbox_to_anchor=(0.4, 0.5))
254
+
255
+ with pytest.warns(UserWarning):
256
+ ins = inset_axes(ax, width="40%", height="30%",
257
+ bbox_transform=ax.transAxes)
258
+
259
+
260
+ def test_inset_axes_tight():
261
+ # gh-26287 found that inset_axes raised with bbox_inches=tight
262
+ fig, ax = plt.subplots()
263
+ inset_axes(ax, width=1.3, height=0.9)
264
+
265
+ f = io.BytesIO()
266
+ fig.savefig(f, bbox_inches="tight")
267
+
268
+
269
+ @image_comparison(['fill_facecolor.png'], remove_text=True, style='mpl20')
270
+ def test_fill_facecolor():
271
+ fig, ax = plt.subplots(1, 5)
272
+ fig.set_size_inches(5, 5)
273
+ for i in range(1, 4):
274
+ ax[i].yaxis.set_visible(False)
275
+ ax[4].yaxis.tick_right()
276
+ bbox = Bbox.from_extents(0, 0.4, 1, 0.6)
277
+
278
+ # fill with blue by setting 'fc' field
279
+ bbox1 = TransformedBbox(bbox, ax[0].transData)
280
+ bbox2 = TransformedBbox(bbox, ax[1].transData)
281
+ # set color to BboxConnectorPatch
282
+ p = BboxConnectorPatch(
283
+ bbox1, bbox2, loc1a=1, loc2a=2, loc1b=4, loc2b=3,
284
+ ec="r", fc="b")
285
+ p.set_clip_on(False)
286
+ ax[0].add_patch(p)
287
+ # set color to marked area
288
+ axins = zoomed_inset_axes(ax[0], 1, loc='upper right')
289
+ axins.set_xlim(0, 0.2)
290
+ axins.set_ylim(0, 0.2)
291
+ plt.gca().axes.xaxis.set_ticks([])
292
+ plt.gca().axes.yaxis.set_ticks([])
293
+ mark_inset(ax[0], axins, loc1=2, loc2=4, fc="b", ec="0.5")
294
+
295
+ # fill with yellow by setting 'facecolor' field
296
+ bbox3 = TransformedBbox(bbox, ax[1].transData)
297
+ bbox4 = TransformedBbox(bbox, ax[2].transData)
298
+ # set color to BboxConnectorPatch
299
+ p = BboxConnectorPatch(
300
+ bbox3, bbox4, loc1a=1, loc2a=2, loc1b=4, loc2b=3,
301
+ ec="r", facecolor="y")
302
+ p.set_clip_on(False)
303
+ ax[1].add_patch(p)
304
+ # set color to marked area
305
+ axins = zoomed_inset_axes(ax[1], 1, loc='upper right')
306
+ axins.set_xlim(0, 0.2)
307
+ axins.set_ylim(0, 0.2)
308
+ plt.gca().axes.xaxis.set_ticks([])
309
+ plt.gca().axes.yaxis.set_ticks([])
310
+ mark_inset(ax[1], axins, loc1=2, loc2=4, facecolor="y", ec="0.5")
311
+
312
+ # fill with green by setting 'color' field
313
+ bbox5 = TransformedBbox(bbox, ax[2].transData)
314
+ bbox6 = TransformedBbox(bbox, ax[3].transData)
315
+ # set color to BboxConnectorPatch
316
+ p = BboxConnectorPatch(
317
+ bbox5, bbox6, loc1a=1, loc2a=2, loc1b=4, loc2b=3,
318
+ ec="r", color="g")
319
+ p.set_clip_on(False)
320
+ ax[2].add_patch(p)
321
+ # set color to marked area
322
+ axins = zoomed_inset_axes(ax[2], 1, loc='upper right')
323
+ axins.set_xlim(0, 0.2)
324
+ axins.set_ylim(0, 0.2)
325
+ plt.gca().axes.xaxis.set_ticks([])
326
+ plt.gca().axes.yaxis.set_ticks([])
327
+ mark_inset(ax[2], axins, loc1=2, loc2=4, color="g", ec="0.5")
328
+
329
+ # fill with green but color won't show if set fill to False
330
+ bbox7 = TransformedBbox(bbox, ax[3].transData)
331
+ bbox8 = TransformedBbox(bbox, ax[4].transData)
332
+ # BboxConnectorPatch won't show green
333
+ p = BboxConnectorPatch(
334
+ bbox7, bbox8, loc1a=1, loc2a=2, loc1b=4, loc2b=3,
335
+ ec="r", fc="g", fill=False)
336
+ p.set_clip_on(False)
337
+ ax[3].add_patch(p)
338
+ # marked area won't show green
339
+ axins = zoomed_inset_axes(ax[3], 1, loc='upper right')
340
+ axins.set_xlim(0, 0.2)
341
+ axins.set_ylim(0, 0.2)
342
+ axins.xaxis.set_ticks([])
343
+ axins.yaxis.set_ticks([])
344
+ mark_inset(ax[3], axins, loc1=2, loc2=4, fc="g", ec="0.5", fill=False)
345
+
346
+
347
+ # Update style when regenerating the test image
348
+ @image_comparison(['zoomed_axes.png', 'inverted_zoomed_axes.png'],
349
+ style=('classic', '_classic_test_patch'),
350
+ tol=0.02 if platform.machine() == 'arm64' else 0)
351
+ def test_zooming_with_inverted_axes():
352
+ fig, ax = plt.subplots()
353
+ ax.plot([1, 2, 3], [1, 2, 3])
354
+ ax.axis([1, 3, 1, 3])
355
+ inset_ax = zoomed_inset_axes(ax, zoom=2.5, loc='lower right')
356
+ inset_ax.axis([1.1, 1.4, 1.1, 1.4])
357
+
358
+ fig, ax = plt.subplots()
359
+ ax.plot([1, 2, 3], [1, 2, 3])
360
+ ax.axis([3, 1, 3, 1])
361
+ inset_ax = zoomed_inset_axes(ax, zoom=2.5, loc='lower right')
362
+ inset_ax.axis([1.4, 1.1, 1.4, 1.1])
363
+
364
+
365
+ # Update style when regenerating the test image
366
+ @image_comparison(['anchored_direction_arrows.png'],
367
+ tol=0 if platform.machine() == 'x86_64' else 0.01,
368
+ style=('classic', '_classic_test_patch'))
369
+ def test_anchored_direction_arrows():
370
+ fig, ax = plt.subplots()
371
+ ax.imshow(np.zeros((10, 10)), interpolation='nearest')
372
+
373
+ simple_arrow = AnchoredDirectionArrows(ax.transAxes, 'X', 'Y')
374
+ ax.add_artist(simple_arrow)
375
+
376
+
377
+ # Update style when regenerating the test image
378
+ @image_comparison(['anchored_direction_arrows_many_args.png'],
379
+ style=('classic', '_classic_test_patch'))
380
+ def test_anchored_direction_arrows_many_args():
381
+ fig, ax = plt.subplots()
382
+ ax.imshow(np.ones((10, 10)))
383
+
384
+ direction_arrows = AnchoredDirectionArrows(
385
+ ax.transAxes, 'A', 'B', loc='upper right', color='red',
386
+ aspect_ratio=-0.5, pad=0.6, borderpad=2, frameon=True, alpha=0.7,
387
+ sep_x=-0.06, sep_y=-0.08, back_length=0.1, head_width=9,
388
+ head_length=10, tail_width=5)
389
+ ax.add_artist(direction_arrows)
390
+
391
+
392
+ def test_axes_locatable_position():
393
+ fig, ax = plt.subplots()
394
+ divider = make_axes_locatable(ax)
395
+ with mpl.rc_context({"figure.subplot.wspace": 0.02}):
396
+ cax = divider.append_axes('right', size='5%')
397
+ fig.canvas.draw()
398
+ assert np.isclose(cax.get_position(original=False).width,
399
+ 0.03621495327102808)
400
+
401
+
402
+ @image_comparison(['image_grid_each_left_label_mode_all.png'], style='mpl20',
403
+ savefig_kwarg={'bbox_inches': 'tight'})
404
+ def test_image_grid_each_left_label_mode_all():
405
+ imdata = np.arange(100).reshape((10, 10))
406
+
407
+ fig = plt.figure(1, (3, 3))
408
+ grid = ImageGrid(fig, (1, 1, 1), nrows_ncols=(3, 2), axes_pad=(0.5, 0.3),
409
+ cbar_mode="each", cbar_location="left", cbar_size="15%",
410
+ label_mode="all")
411
+ # 3-tuple rect => SubplotDivider
412
+ assert isinstance(grid.get_divider(), SubplotDivider)
413
+ assert grid.get_axes_pad() == (0.5, 0.3)
414
+ assert grid.get_aspect() # True by default for ImageGrid
415
+ for ax, cax in zip(grid, grid.cbar_axes):
416
+ im = ax.imshow(imdata, interpolation='none')
417
+ cax.colorbar(im)
418
+
419
+
420
+ @image_comparison(['image_grid_single_bottom_label_mode_1.png'], style='mpl20',
421
+ savefig_kwarg={'bbox_inches': 'tight'})
422
+ def test_image_grid_single_bottom():
423
+ imdata = np.arange(100).reshape((10, 10))
424
+
425
+ fig = plt.figure(1, (2.5, 1.5))
426
+ grid = ImageGrid(fig, (0, 0, 1, 1), nrows_ncols=(1, 3),
427
+ axes_pad=(0.2, 0.15), cbar_mode="single",
428
+ cbar_location="bottom", cbar_size="10%", label_mode="1")
429
+ # 4-tuple rect => Divider, isinstance will give True for SubplotDivider
430
+ assert type(grid.get_divider()) is Divider
431
+ for i in range(3):
432
+ im = grid[i].imshow(imdata, interpolation='none')
433
+ grid.cbar_axes[0].colorbar(im)
434
+
435
+
436
+ def test_image_grid_label_mode_invalid():
437
+ fig = plt.figure()
438
+ with pytest.raises(ValueError, match="'foo' is not a valid value for mode"):
439
+ ImageGrid(fig, (0, 0, 1, 1), (2, 1), label_mode="foo")
440
+
441
+
442
+ @image_comparison(['image_grid.png'],
443
+ remove_text=True, style='mpl20',
444
+ savefig_kwarg={'bbox_inches': 'tight'})
445
+ def test_image_grid():
446
+ # test that image grid works with bbox_inches=tight.
447
+ im = np.arange(100).reshape((10, 10))
448
+
449
+ fig = plt.figure(1, (4, 4))
450
+ grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=0.1)
451
+ assert grid.get_axes_pad() == (0.1, 0.1)
452
+ for i in range(4):
453
+ grid[i].imshow(im, interpolation='nearest')
454
+
455
+
456
+ def test_gettightbbox():
457
+ fig, ax = plt.subplots(figsize=(8, 6))
458
+
459
+ l, = ax.plot([1, 2, 3], [0, 1, 0])
460
+
461
+ ax_zoom = zoomed_inset_axes(ax, 4)
462
+ ax_zoom.plot([1, 2, 3], [0, 1, 0])
463
+
464
+ mark_inset(ax, ax_zoom, loc1=1, loc2=3, fc="none", ec='0.3')
465
+
466
+ remove_ticks_and_titles(fig)
467
+ bbox = fig.get_tightbbox(fig.canvas.get_renderer())
468
+ np.testing.assert_array_almost_equal(bbox.extents,
469
+ [-17.7, -13.9, 7.2, 5.4])
470
+
471
+
472
+ @pytest.mark.parametrize("click_on", ["big", "small"])
473
+ @pytest.mark.parametrize("big_on_axes,small_on_axes", [
474
+ ("gca", "gca"),
475
+ ("host", "host"),
476
+ ("host", "parasite"),
477
+ ("parasite", "host"),
478
+ ("parasite", "parasite")
479
+ ])
480
+ def test_picking_callbacks_overlap(big_on_axes, small_on_axes, click_on):
481
+ """Test pick events on normal, host or parasite axes."""
482
+ # Two rectangles are drawn and "clicked on", a small one and a big one
483
+ # enclosing the small one. The axis on which they are drawn as well as the
484
+ # rectangle that is clicked on are varied.
485
+ # In each case we expect that both rectangles are picked if we click on the
486
+ # small one and only the big one is picked if we click on the big one.
487
+ # Also tests picking on normal axes ("gca") as a control.
488
+ big = plt.Rectangle((0.25, 0.25), 0.5, 0.5, picker=5)
489
+ small = plt.Rectangle((0.4, 0.4), 0.2, 0.2, facecolor="r", picker=5)
490
+ # Machinery for "receiving" events
491
+ received_events = []
492
+ def on_pick(event):
493
+ received_events.append(event)
494
+ plt.gcf().canvas.mpl_connect('pick_event', on_pick)
495
+ # Shortcut
496
+ rectangles_on_axes = (big_on_axes, small_on_axes)
497
+ # Axes setup
498
+ axes = {"gca": None, "host": None, "parasite": None}
499
+ if "gca" in rectangles_on_axes:
500
+ axes["gca"] = plt.gca()
501
+ if "host" in rectangles_on_axes or "parasite" in rectangles_on_axes:
502
+ axes["host"] = host_subplot(111)
503
+ axes["parasite"] = axes["host"].twin()
504
+ # Add rectangles to axes
505
+ axes[big_on_axes].add_patch(big)
506
+ axes[small_on_axes].add_patch(small)
507
+ # Simulate picking with click mouse event
508
+ if click_on == "big":
509
+ click_axes = axes[big_on_axes]
510
+ axes_coords = (0.3, 0.3)
511
+ else:
512
+ click_axes = axes[small_on_axes]
513
+ axes_coords = (0.5, 0.5)
514
+ # In reality mouse events never happen on parasite axes, only host axes
515
+ if click_axes is axes["parasite"]:
516
+ click_axes = axes["host"]
517
+ (x, y) = click_axes.transAxes.transform(axes_coords)
518
+ m = MouseEvent("button_press_event", click_axes.figure.canvas, x, y,
519
+ button=1)
520
+ click_axes.pick(m)
521
+ # Checks
522
+ expected_n_events = 2 if click_on == "small" else 1
523
+ assert len(received_events) == expected_n_events
524
+ event_rects = [event.artist for event in received_events]
525
+ assert big in event_rects
526
+ if click_on == "small":
527
+ assert small in event_rects
528
+
529
+
530
+ @image_comparison(['anchored_artists.png'], remove_text=True, style='mpl20')
531
+ def test_anchored_artists():
532
+ fig, ax = plt.subplots(figsize=(3, 3))
533
+ ada = AnchoredDrawingArea(40, 20, 0, 0, loc='upper right', pad=0.,
534
+ frameon=False)
535
+ p1 = Circle((10, 10), 10)
536
+ ada.drawing_area.add_artist(p1)
537
+ p2 = Circle((30, 10), 5, fc="r")
538
+ ada.drawing_area.add_artist(p2)
539
+ ax.add_artist(ada)
540
+
541
+ box = AnchoredAuxTransformBox(ax.transData, loc='upper left')
542
+ el = Ellipse((0, 0), width=0.1, height=0.4, angle=30, color='cyan')
543
+ box.drawing_area.add_artist(el)
544
+ ax.add_artist(box)
545
+
546
+ # Manually construct the ellipse instead, once the deprecation elapses.
547
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
548
+ ae = AnchoredEllipse(ax.transData, width=0.1, height=0.25, angle=-60,
549
+ loc='lower left', pad=0.5, borderpad=0.4,
550
+ frameon=True)
551
+ ax.add_artist(ae)
552
+
553
+ asb = AnchoredSizeBar(ax.transData, 0.2, r"0.2 units", loc='lower right',
554
+ pad=0.3, borderpad=0.4, sep=4, fill_bar=True,
555
+ frameon=False, label_top=True, prop={'size': 20},
556
+ size_vertical=0.05, color='green')
557
+ ax.add_artist(asb)
558
+
559
+
560
+ def test_hbox_divider():
561
+ arr1 = np.arange(20).reshape((4, 5))
562
+ arr2 = np.arange(20).reshape((5, 4))
563
+
564
+ fig, (ax1, ax2) = plt.subplots(1, 2)
565
+ ax1.imshow(arr1)
566
+ ax2.imshow(arr2)
567
+
568
+ pad = 0.5 # inches.
569
+ divider = HBoxDivider(
570
+ fig, 111, # Position of combined axes.
571
+ horizontal=[Size.AxesX(ax1), Size.Fixed(pad), Size.AxesX(ax2)],
572
+ vertical=[Size.AxesY(ax1), Size.Scaled(1), Size.AxesY(ax2)])
573
+ ax1.set_axes_locator(divider.new_locator(0))
574
+ ax2.set_axes_locator(divider.new_locator(2))
575
+
576
+ fig.canvas.draw()
577
+ p1 = ax1.get_position()
578
+ p2 = ax2.get_position()
579
+ assert p1.height == p2.height
580
+ assert p2.width / p1.width == pytest.approx((4 / 5) ** 2)
581
+
582
+
583
+ def test_vbox_divider():
584
+ arr1 = np.arange(20).reshape((4, 5))
585
+ arr2 = np.arange(20).reshape((5, 4))
586
+
587
+ fig, (ax1, ax2) = plt.subplots(1, 2)
588
+ ax1.imshow(arr1)
589
+ ax2.imshow(arr2)
590
+
591
+ pad = 0.5 # inches.
592
+ divider = VBoxDivider(
593
+ fig, 111, # Position of combined axes.
594
+ horizontal=[Size.AxesX(ax1), Size.Scaled(1), Size.AxesX(ax2)],
595
+ vertical=[Size.AxesY(ax1), Size.Fixed(pad), Size.AxesY(ax2)])
596
+ ax1.set_axes_locator(divider.new_locator(0))
597
+ ax2.set_axes_locator(divider.new_locator(2))
598
+
599
+ fig.canvas.draw()
600
+ p1 = ax1.get_position()
601
+ p2 = ax2.get_position()
602
+ assert p1.width == p2.width
603
+ assert p1.height / p2.height == pytest.approx((4 / 5) ** 2)
604
+
605
+
606
+ def test_axes_class_tuple():
607
+ fig = plt.figure()
608
+ axes_class = (mpl_toolkits.axes_grid1.mpl_axes.Axes, {})
609
+ gr = AxesGrid(fig, 111, nrows_ncols=(1, 1), axes_class=axes_class)
610
+
611
+
612
+ def test_grid_axes_lists():
613
+ """Test Grid axes_all, axes_row and axes_column relationship."""
614
+ fig = plt.figure()
615
+ grid = Grid(fig, 111, (2, 3), direction="row")
616
+ assert_array_equal(grid, grid.axes_all)
617
+ assert_array_equal(grid.axes_row, np.transpose(grid.axes_column))
618
+ assert_array_equal(grid, np.ravel(grid.axes_row), "row")
619
+ assert grid.get_geometry() == (2, 3)
620
+ grid = Grid(fig, 111, (2, 3), direction="column")
621
+ assert_array_equal(grid, np.ravel(grid.axes_column), "column")
622
+
623
+
624
+ @pytest.mark.parametrize('direction', ('row', 'column'))
625
+ def test_grid_axes_position(direction):
626
+ """Test positioning of the axes in Grid."""
627
+ fig = plt.figure()
628
+ grid = Grid(fig, 111, (2, 2), direction=direction)
629
+ loc = [ax.get_axes_locator() for ax in np.ravel(grid.axes_row)]
630
+ # Test nx.
631
+ assert loc[1].args[0] > loc[0].args[0]
632
+ assert loc[0].args[0] == loc[2].args[0]
633
+ assert loc[3].args[0] == loc[1].args[0]
634
+ # Test ny.
635
+ assert loc[2].args[1] < loc[0].args[1]
636
+ assert loc[0].args[1] == loc[1].args[1]
637
+ assert loc[3].args[1] == loc[2].args[1]
638
+
639
+
640
+ @pytest.mark.parametrize('rect, ngrids, error, message', (
641
+ ((1, 1), None, TypeError, "Incorrect rect format"),
642
+ (111, -1, ValueError, "ngrids must be positive"),
643
+ (111, 7, ValueError, "ngrids must be positive"),
644
+ ))
645
+ def test_grid_errors(rect, ngrids, error, message):
646
+ fig = plt.figure()
647
+ with pytest.raises(error, match=message):
648
+ Grid(fig, rect, (2, 3), ngrids=ngrids)
649
+
650
+
651
+ @pytest.mark.parametrize('anchor, error, message', (
652
+ (None, TypeError, "anchor must be str"),
653
+ ("CC", ValueError, "'CC' is not a valid value for anchor"),
654
+ ((1, 1, 1), TypeError, "anchor must be str"),
655
+ ))
656
+ def test_divider_errors(anchor, error, message):
657
+ fig = plt.figure()
658
+ with pytest.raises(error, match=message):
659
+ Divider(fig, [0, 0, 1, 1], [Size.Fixed(1)], [Size.Fixed(1)],
660
+ anchor=anchor)
661
+
662
+
663
+ @check_figures_equal(extensions=["png"])
664
+ def test_mark_inset_unstales_viewlim(fig_test, fig_ref):
665
+ inset, full = fig_test.subplots(1, 2)
666
+ full.plot([0, 5], [0, 5])
667
+ inset.set(xlim=(1, 2), ylim=(1, 2))
668
+ # Check that mark_inset unstales full's viewLim before drawing the marks.
669
+ mark_inset(full, inset, 1, 4)
670
+
671
+ inset, full = fig_ref.subplots(1, 2)
672
+ full.plot([0, 5], [0, 5])
673
+ inset.set(xlim=(1, 2), ylim=(1, 2))
674
+ mark_inset(full, inset, 1, 4)
675
+ # Manually unstale the full's viewLim.
676
+ fig_ref.canvas.draw()
677
+
678
+
679
+ def test_auto_adjustable():
680
+ fig = plt.figure()
681
+ ax = fig.add_axes([0, 0, 1, 1])
682
+ pad = 0.1
683
+ make_axes_area_auto_adjustable(ax, pad=pad)
684
+ fig.canvas.draw()
685
+ tbb = ax.get_tightbbox()
686
+ assert tbb.x0 == pytest.approx(pad * fig.dpi)
687
+ assert tbb.x1 == pytest.approx(fig.bbox.width - pad * fig.dpi)
688
+ assert tbb.y0 == pytest.approx(pad * fig.dpi)
689
+ assert tbb.y1 == pytest.approx(fig.bbox.height - pad * fig.dpi)
690
+
691
+
692
+ # Update style when regenerating the test image
693
+ @image_comparison(['rgb_axes.png'], remove_text=True,
694
+ style=('classic', '_classic_test_patch'))
695
+ def test_rgb_axes():
696
+ fig = plt.figure()
697
+ ax = RGBAxes(fig, (0.1, 0.1, 0.8, 0.8), pad=0.1)
698
+ rng = np.random.default_rng(19680801)
699
+ r = rng.random((5, 5))
700
+ g = rng.random((5, 5))
701
+ b = rng.random((5, 5))
702
+ ax.imshow_rgb(r, g, b, interpolation='none')
703
+
704
+
705
+ # Update style when regenerating the test image
706
+ @image_comparison(['insetposition.png'], remove_text=True,
707
+ style=('classic', '_classic_test_patch'))
708
+ def test_insetposition():
709
+ fig, ax = plt.subplots(figsize=(2, 2))
710
+ ax_ins = plt.axes([0, 0, 1, 1])
711
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
712
+ ip = InsetPosition(ax, [0.2, 0.25, 0.5, 0.4])
713
+ ax_ins.set_axes_locator(ip)
714
+
715
+
716
+ # The original version of this test relied on mpl_toolkits's slightly different
717
+ # colorbar implementation; moving to matplotlib's own colorbar implementation
718
+ # caused the small image comparison error.
719
+ @image_comparison(['imagegrid_cbar_mode.png'],
720
+ remove_text=True, style='mpl20', tol=0.3)
721
+ def test_imagegrid_cbar_mode_edge():
722
+ arr = np.arange(16).reshape((4, 4))
723
+
724
+ fig = plt.figure(figsize=(18, 9))
725
+
726
+ positions = (241, 242, 243, 244, 245, 246, 247, 248)
727
+ directions = ['row']*4 + ['column']*4
728
+ cbar_locations = ['left', 'right', 'top', 'bottom']*2
729
+
730
+ for position, direction, location in zip(
731
+ positions, directions, cbar_locations):
732
+ grid = ImageGrid(fig, position,
733
+ nrows_ncols=(2, 2),
734
+ direction=direction,
735
+ cbar_location=location,
736
+ cbar_size='20%',
737
+ cbar_mode='edge')
738
+ ax1, ax2, ax3, ax4 = grid
739
+
740
+ ax1.imshow(arr, cmap='nipy_spectral')
741
+ ax2.imshow(arr.T, cmap='hot')
742
+ ax3.imshow(np.hypot(arr, arr.T), cmap='jet')
743
+ ax4.imshow(np.arctan2(arr, arr.T), cmap='hsv')
744
+
745
+ # In each row/column, the "first" colorbars must be overwritten by the
746
+ # "second" ones. To achieve this, clear out the axes first.
747
+ for ax in grid:
748
+ ax.cax.cla()
749
+ cb = ax.cax.colorbar(ax.images[0])
750
+
751
+
752
+ def test_imagegrid():
753
+ fig = plt.figure()
754
+ grid = ImageGrid(fig, 111, nrows_ncols=(1, 1))
755
+ ax = grid[0]
756
+ im = ax.imshow([[1, 2]], norm=mpl.colors.LogNorm())
757
+ cb = ax.cax.colorbar(im)
758
+ assert isinstance(cb.locator, mticker.LogLocator)
759
+
760
+
761
+ def test_removal():
762
+ import matplotlib.pyplot as plt
763
+ import mpl_toolkits.axisartist as AA
764
+ fig = plt.figure()
765
+ ax = host_subplot(111, axes_class=AA.Axes, figure=fig)
766
+ col = ax.fill_between(range(5), 0, range(5))
767
+ fig.canvas.draw()
768
+ col.remove()
769
+ fig.canvas.draw()
770
+
771
+
772
+ @image_comparison(['anchored_locator_base_call.png'], style="mpl20")
773
+ def test_anchored_locator_base_call():
774
+ fig = plt.figure(figsize=(3, 3))
775
+ fig1, fig2 = fig.subfigures(nrows=2, ncols=1)
776
+
777
+ ax = fig1.subplots()
778
+ ax.set(aspect=1, xlim=(-15, 15), ylim=(-20, 5))
779
+ ax.set(xticks=[], yticks=[])
780
+
781
+ Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")
782
+ extent = (-3, 4, -4, 3)
783
+
784
+ axins = zoomed_inset_axes(ax, zoom=2, loc="upper left")
785
+ axins.set(xticks=[], yticks=[])
786
+
787
+ axins.imshow(Z, extent=extent, origin="lower")
788
+
789
+
790
+ def test_grid_with_axes_class_not_overriding_axis():
791
+ Grid(plt.figure(), 111, (2, 2), axes_class=mpl.axes.Axes)
792
+ RGBAxes(plt.figure(), 111, axes_class=mpl.axes.Axes)
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (826 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/angle_helper.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axes_divider.cpython-310.pyc ADDED
Binary file (356 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axes_grid.cpython-310.pyc ADDED
Binary file (968 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axes_rgb.cpython-310.pyc ADDED
Binary file (874 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axis_artist.cpython-310.pyc ADDED
Binary file (34.8 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axisline_style.cpython-310.pyc ADDED
Binary file (6.9 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axislines.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/floating_axes.cpython-310.pyc ADDED
Binary file (8.89 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/grid_finder.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/grid_helper_curvelinear.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/parasite_axes.cpython-310.pyc ADDED
Binary file (417 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (490 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (316 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_angle_helper.cpython-310.pyc ADDED
Binary file (4.53 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_axis_artist.cpython-310.pyc ADDED
Binary file (3.12 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/test_floating_axes.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import matplotlib.pyplot as plt
4
+ import matplotlib.projections as mprojections
5
+ import matplotlib.transforms as mtransforms
6
+ from matplotlib.testing.decorators import image_comparison
7
+ from mpl_toolkits.axisartist.axislines import Subplot
8
+ from mpl_toolkits.axisartist.floating_axes import (
9
+ FloatingAxes, GridHelperCurveLinear)
10
+ from mpl_toolkits.axisartist.grid_finder import FixedLocator
11
+ from mpl_toolkits.axisartist import angle_helper
12
+
13
+
14
+ def test_subplot():
15
+ fig = plt.figure(figsize=(5, 5))
16
+ ax = Subplot(fig, 111)
17
+ fig.add_subplot(ax)
18
+
19
+
20
+ # Rather high tolerance to allow ongoing work with floating axes internals;
21
+ # remove when image is regenerated.
22
+ @image_comparison(['curvelinear3.png'], style='default', tol=5)
23
+ def test_curvelinear3():
24
+ fig = plt.figure(figsize=(5, 5))
25
+
26
+ tr = (mtransforms.Affine2D().scale(np.pi / 180, 1) +
27
+ mprojections.PolarAxes.PolarTransform(apply_theta_transforms=False))
28
+ grid_helper = GridHelperCurveLinear(
29
+ tr,
30
+ extremes=(0, 360, 10, 3),
31
+ grid_locator1=angle_helper.LocatorDMS(15),
32
+ grid_locator2=FixedLocator([2, 4, 6, 8, 10]),
33
+ tick_formatter1=angle_helper.FormatterDMS(),
34
+ tick_formatter2=None)
35
+ ax1 = fig.add_subplot(axes_class=FloatingAxes, grid_helper=grid_helper)
36
+
37
+ r_scale = 10
38
+ tr2 = mtransforms.Affine2D().scale(1, 1 / r_scale) + tr
39
+ grid_helper2 = GridHelperCurveLinear(
40
+ tr2,
41
+ extremes=(0, 360, 10 * r_scale, 3 * r_scale),
42
+ grid_locator2=FixedLocator([30, 60, 90]))
43
+
44
+ ax1.axis["right"] = axis = grid_helper2.new_fixed_axis("right", axes=ax1)
45
+
46
+ ax1.axis["left"].label.set_text("Test 1")
47
+ ax1.axis["right"].label.set_text("Test 2")
48
+ ax1.axis["left", "right"].set_visible(False)
49
+
50
+ axis = grid_helper.new_floating_axis(1, 7, axes=ax1,
51
+ axis_direction="bottom")
52
+ ax1.axis["z"] = axis
53
+ axis.toggle(all=True, label=True)
54
+ axis.label.set_text("z = ?")
55
+ axis.label.set_visible(True)
56
+ axis.line.set_color("0.5")
57
+
58
+ ax2 = ax1.get_aux_axes(tr)
59
+
60
+ xx, yy = [67, 90, 75, 30], [2, 5, 8, 4]
61
+ ax2.scatter(xx, yy)
62
+ l, = ax2.plot(xx, yy, "k-")
63
+ l.set_clip_path(ax1.patch)
64
+
65
+
66
+ # Rather high tolerance to allow ongoing work with floating axes internals;
67
+ # remove when image is regenerated.
68
+ @image_comparison(['curvelinear4.png'], style='default', tol=0.9)
69
+ def test_curvelinear4():
70
+ # Remove this line when this test image is regenerated.
71
+ plt.rcParams['text.kerning_factor'] = 6
72
+
73
+ fig = plt.figure(figsize=(5, 5))
74
+
75
+ tr = (mtransforms.Affine2D().scale(np.pi / 180, 1) +
76
+ mprojections.PolarAxes.PolarTransform(apply_theta_transforms=False))
77
+ grid_helper = GridHelperCurveLinear(
78
+ tr,
79
+ extremes=(120, 30, 10, 0),
80
+ grid_locator1=angle_helper.LocatorDMS(5),
81
+ grid_locator2=FixedLocator([2, 4, 6, 8, 10]),
82
+ tick_formatter1=angle_helper.FormatterDMS(),
83
+ tick_formatter2=None)
84
+ ax1 = fig.add_subplot(axes_class=FloatingAxes, grid_helper=grid_helper)
85
+ ax1.clear() # Check that clear() also restores the correct limits on ax1.
86
+
87
+ ax1.axis["left"].label.set_text("Test 1")
88
+ ax1.axis["right"].label.set_text("Test 2")
89
+ ax1.axis["top"].set_visible(False)
90
+
91
+ axis = grid_helper.new_floating_axis(1, 70, axes=ax1,
92
+ axis_direction="bottom")
93
+ ax1.axis["z"] = axis
94
+ axis.toggle(all=True, label=True)
95
+ axis.label.set_axis_direction("top")
96
+ axis.label.set_text("z = ?")
97
+ axis.label.set_visible(True)
98
+ axis.line.set_color("0.5")
99
+
100
+ ax2 = ax1.get_aux_axes(tr)
101
+
102
+ xx, yy = [67, 90, 75, 30], [2, 5, 8, 4]
103
+ ax2.scatter(xx, yy)
104
+ l, = ax2.plot(xx, yy, "k-")
105
+ l.set_clip_path(ax1.patch)
106
+
107
+
108
+ def test_axis_direction():
109
+ # Check that axis direction is propagated on a floating axis
110
+ fig = plt.figure()
111
+ ax = Subplot(fig, 111)
112
+ fig.add_subplot(ax)
113
+ ax.axis['y'] = ax.new_floating_axis(nth_coord=1, value=0,
114
+ axis_direction='left')
115
+ assert ax.axis['y']._axis_direction == 'left'
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/axisartist/tests/test_grid_helper_curvelinear.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import matplotlib.pyplot as plt
4
+ from matplotlib.path import Path
5
+ from matplotlib.projections import PolarAxes
6
+ from matplotlib.ticker import FuncFormatter
7
+ from matplotlib.transforms import Affine2D, Transform
8
+ from matplotlib.testing.decorators import image_comparison
9
+
10
+ from mpl_toolkits.axisartist import SubplotHost
11
+ from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory
12
+ from mpl_toolkits.axisartist import angle_helper
13
+ from mpl_toolkits.axisartist.axislines import Axes
14
+ from mpl_toolkits.axisartist.grid_helper_curvelinear import \
15
+ GridHelperCurveLinear
16
+
17
+
18
+ @image_comparison(['custom_transform.png'], style='default', tol=0.2)
19
+ def test_custom_transform():
20
+ class MyTransform(Transform):
21
+ input_dims = output_dims = 2
22
+
23
+ def __init__(self, resolution):
24
+ """
25
+ Resolution is the number of steps to interpolate between each input
26
+ line segment to approximate its path in transformed space.
27
+ """
28
+ Transform.__init__(self)
29
+ self._resolution = resolution
30
+
31
+ def transform(self, ll):
32
+ x, y = ll.T
33
+ return np.column_stack([x, y - x])
34
+
35
+ transform_non_affine = transform
36
+
37
+ def transform_path(self, path):
38
+ ipath = path.interpolated(self._resolution)
39
+ return Path(self.transform(ipath.vertices), ipath.codes)
40
+
41
+ transform_path_non_affine = transform_path
42
+
43
+ def inverted(self):
44
+ return MyTransformInv(self._resolution)
45
+
46
+ class MyTransformInv(Transform):
47
+ input_dims = output_dims = 2
48
+
49
+ def __init__(self, resolution):
50
+ Transform.__init__(self)
51
+ self._resolution = resolution
52
+
53
+ def transform(self, ll):
54
+ x, y = ll.T
55
+ return np.column_stack([x, y + x])
56
+
57
+ def inverted(self):
58
+ return MyTransform(self._resolution)
59
+
60
+ fig = plt.figure()
61
+
62
+ SubplotHost = host_axes_class_factory(Axes)
63
+
64
+ tr = MyTransform(1)
65
+ grid_helper = GridHelperCurveLinear(tr)
66
+ ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
67
+ fig.add_subplot(ax1)
68
+
69
+ ax2 = ax1.get_aux_axes(tr, viewlim_mode="equal")
70
+ ax2.plot([3, 6], [5.0, 10.])
71
+
72
+ ax1.set_aspect(1.)
73
+ ax1.set_xlim(0, 10)
74
+ ax1.set_ylim(0, 10)
75
+
76
+ ax1.grid(True)
77
+
78
+
79
+ @image_comparison(['polar_box.png'], style='default', tol=0.04)
80
+ def test_polar_box():
81
+ fig = plt.figure(figsize=(5, 5))
82
+
83
+ # PolarAxes.PolarTransform takes radian. However, we want our coordinate
84
+ # system in degree
85
+ tr = (Affine2D().scale(np.pi / 180., 1.) +
86
+ PolarAxes.PolarTransform(apply_theta_transforms=False))
87
+
88
+ # polar projection, which involves cycle, and also has limits in
89
+ # its coordinates, needs a special method to find the extremes
90
+ # (min, max of the coordinate within the view).
91
+ extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
92
+ lon_cycle=360,
93
+ lat_cycle=None,
94
+ lon_minmax=None,
95
+ lat_minmax=(0, np.inf))
96
+
97
+ grid_helper = GridHelperCurveLinear(
98
+ tr,
99
+ extreme_finder=extreme_finder,
100
+ grid_locator1=angle_helper.LocatorDMS(12),
101
+ tick_formatter1=angle_helper.FormatterDMS(),
102
+ tick_formatter2=FuncFormatter(lambda x, p: "eight" if x == 8 else f"{int(x)}"),
103
+ )
104
+
105
+ ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
106
+
107
+ ax1.axis["right"].major_ticklabels.set_visible(True)
108
+ ax1.axis["top"].major_ticklabels.set_visible(True)
109
+
110
+ # let right axis shows ticklabels for 1st coordinate (angle)
111
+ ax1.axis["right"].get_helper().nth_coord_ticks = 0
112
+ # let bottom axis shows ticklabels for 2nd coordinate (radius)
113
+ ax1.axis["bottom"].get_helper().nth_coord_ticks = 1
114
+
115
+ fig.add_subplot(ax1)
116
+
117
+ ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1)
118
+ axis.label.set_text("Test")
119
+ axis.label.set_visible(True)
120
+ axis.get_helper().set_extremes(2, 12)
121
+
122
+ ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1)
123
+ axis.label.set_text("Test 2")
124
+ axis.get_helper().set_extremes(-180, 90)
125
+
126
+ # A parasite axes with given transform
127
+ ax2 = ax1.get_aux_axes(tr, viewlim_mode="equal")
128
+ assert ax2.transData == tr + ax1.transData
129
+ # Anything you draw in ax2 will match the ticks and grids of ax1.
130
+ ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50))
131
+
132
+ ax1.set_aspect(1.)
133
+ ax1.set_xlim(-5, 12)
134
+ ax1.set_ylim(-5, 10)
135
+
136
+ ax1.grid(True)
137
+
138
+
139
+ # Remove tol & kerning_factor when this test image is regenerated.
140
+ @image_comparison(['axis_direction.png'], style='default', tol=0.13)
141
+ def test_axis_direction():
142
+ plt.rcParams['text.kerning_factor'] = 6
143
+
144
+ fig = plt.figure(figsize=(5, 5))
145
+
146
+ # PolarAxes.PolarTransform takes radian. However, we want our coordinate
147
+ # system in degree
148
+ tr = (Affine2D().scale(np.pi / 180., 1.) +
149
+ PolarAxes.PolarTransform(apply_theta_transforms=False))
150
+
151
+ # polar projection, which involves cycle, and also has limits in
152
+ # its coordinates, needs a special method to find the extremes
153
+ # (min, max of the coordinate within the view).
154
+
155
+ # 20, 20 : number of sampling points along x, y direction
156
+ extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
157
+ lon_cycle=360,
158
+ lat_cycle=None,
159
+ lon_minmax=None,
160
+ lat_minmax=(0, np.inf),
161
+ )
162
+
163
+ grid_locator1 = angle_helper.LocatorDMS(12)
164
+ tick_formatter1 = angle_helper.FormatterDMS()
165
+
166
+ grid_helper = GridHelperCurveLinear(tr,
167
+ extreme_finder=extreme_finder,
168
+ grid_locator1=grid_locator1,
169
+ tick_formatter1=tick_formatter1)
170
+
171
+ ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
172
+
173
+ for axis in ax1.axis.values():
174
+ axis.set_visible(False)
175
+
176
+ fig.add_subplot(ax1)
177
+
178
+ ax1.axis["lat1"] = axis = grid_helper.new_floating_axis(
179
+ 0, 130,
180
+ axes=ax1, axis_direction="left")
181
+ axis.label.set_text("Test")
182
+ axis.label.set_visible(True)
183
+ axis.get_helper().set_extremes(0.001, 10)
184
+
185
+ ax1.axis["lat2"] = axis = grid_helper.new_floating_axis(
186
+ 0, 50,
187
+ axes=ax1, axis_direction="right")
188
+ axis.label.set_text("Test")
189
+ axis.label.set_visible(True)
190
+ axis.get_helper().set_extremes(0.001, 10)
191
+
192
+ ax1.axis["lon"] = axis = grid_helper.new_floating_axis(
193
+ 1, 10,
194
+ axes=ax1, axis_direction="bottom")
195
+ axis.label.set_text("Test 2")
196
+ axis.get_helper().set_extremes(50, 130)
197
+ axis.major_ticklabels.set_axis_direction("top")
198
+ axis.label.set_axis_direction("top")
199
+
200
+ grid_helper.grid_finder.grid_locator1.set_params(nbins=5)
201
+ grid_helper.grid_finder.grid_locator2.set_params(nbins=5)
202
+
203
+ ax1.set_aspect(1.)
204
+ ax1.set_xlim(-8, 8)
205
+ ax1.set_ylim(-4, 12)
206
+
207
+ ax1.grid(True)
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .axes3d import Axes3D
2
+
3
+ __all__ = ['Axes3D']
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (241 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/art3d.cpython-310.pyc ADDED
Binary file (40.9 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/axis3d.cpython-310.pyc ADDED
Binary file (19.1 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/proj3d.cpython-310.pyc ADDED
Binary file (7.22 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/art3d.py ADDED
@@ -0,0 +1,1262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # art3d.py, original mplot3d version by John Porter
2
+ # Parts rewritten by Reinier Heeres <reinier@heeres.eu>
3
+ # Minor additions by Ben Axelrod <baxelrod@coroware.com>
4
+
5
+ """
6
+ Module containing 3D artist code and functions to convert 2D
7
+ artists into 3D versions which can be added to an Axes3D.
8
+ """
9
+
10
+ import math
11
+
12
+ import numpy as np
13
+
14
+ from contextlib import contextmanager
15
+
16
+ from matplotlib import (
17
+ artist, cbook, colors as mcolors, lines, text as mtext,
18
+ path as mpath)
19
+ from matplotlib.collections import (
20
+ Collection, LineCollection, PolyCollection, PatchCollection, PathCollection)
21
+ from matplotlib.colors import Normalize
22
+ from matplotlib.patches import Patch
23
+ from . import proj3d
24
+
25
+
26
+ def _norm_angle(a):
27
+ """Return the given angle normalized to -180 < *a* <= 180 degrees."""
28
+ a = (a + 360) % 360
29
+ if a > 180:
30
+ a = a - 360
31
+ return a
32
+
33
+
34
+ def _norm_text_angle(a):
35
+ """Return the given angle normalized to -90 < *a* <= 90 degrees."""
36
+ a = (a + 180) % 180
37
+ if a > 90:
38
+ a = a - 180
39
+ return a
40
+
41
+
42
+ def get_dir_vector(zdir):
43
+ """
44
+ Return a direction vector.
45
+
46
+ Parameters
47
+ ----------
48
+ zdir : {'x', 'y', 'z', None, 3-tuple}
49
+ The direction. Possible values are:
50
+
51
+ - 'x': equivalent to (1, 0, 0)
52
+ - 'y': equivalent to (0, 1, 0)
53
+ - 'z': equivalent to (0, 0, 1)
54
+ - *None*: equivalent to (0, 0, 0)
55
+ - an iterable (x, y, z) is converted to an array
56
+
57
+ Returns
58
+ -------
59
+ x, y, z : array
60
+ The direction vector.
61
+ """
62
+ if zdir == 'x':
63
+ return np.array((1, 0, 0))
64
+ elif zdir == 'y':
65
+ return np.array((0, 1, 0))
66
+ elif zdir == 'z':
67
+ return np.array((0, 0, 1))
68
+ elif zdir is None:
69
+ return np.array((0, 0, 0))
70
+ elif np.iterable(zdir) and len(zdir) == 3:
71
+ return np.array(zdir)
72
+ else:
73
+ raise ValueError("'x', 'y', 'z', None or vector of length 3 expected")
74
+
75
+
76
+ class Text3D(mtext.Text):
77
+ """
78
+ Text object with 3D position and direction.
79
+
80
+ Parameters
81
+ ----------
82
+ x, y, z : float
83
+ The position of the text.
84
+ text : str
85
+ The text string to display.
86
+ zdir : {'x', 'y', 'z', None, 3-tuple}
87
+ The direction of the text. See `.get_dir_vector` for a description of
88
+ the values.
89
+
90
+ Other Parameters
91
+ ----------------
92
+ **kwargs
93
+ All other parameters are passed on to `~matplotlib.text.Text`.
94
+ """
95
+
96
+ def __init__(self, x=0, y=0, z=0, text='', zdir='z', **kwargs):
97
+ mtext.Text.__init__(self, x, y, text, **kwargs)
98
+ self.set_3d_properties(z, zdir)
99
+
100
+ def get_position_3d(self):
101
+ """Return the (x, y, z) position of the text."""
102
+ return self._x, self._y, self._z
103
+
104
+ def set_position_3d(self, xyz, zdir=None):
105
+ """
106
+ Set the (*x*, *y*, *z*) position of the text.
107
+
108
+ Parameters
109
+ ----------
110
+ xyz : (float, float, float)
111
+ The position in 3D space.
112
+ zdir : {'x', 'y', 'z', None, 3-tuple}
113
+ The direction of the text. If unspecified, the *zdir* will not be
114
+ changed. See `.get_dir_vector` for a description of the values.
115
+ """
116
+ super().set_position(xyz[:2])
117
+ self.set_z(xyz[2])
118
+ if zdir is not None:
119
+ self._dir_vec = get_dir_vector(zdir)
120
+
121
+ def set_z(self, z):
122
+ """
123
+ Set the *z* position of the text.
124
+
125
+ Parameters
126
+ ----------
127
+ z : float
128
+ """
129
+ self._z = z
130
+ self.stale = True
131
+
132
+ def set_3d_properties(self, z=0, zdir='z'):
133
+ """
134
+ Set the *z* position and direction of the text.
135
+
136
+ Parameters
137
+ ----------
138
+ z : float
139
+ The z-position in 3D space.
140
+ zdir : {'x', 'y', 'z', 3-tuple}
141
+ The direction of the text. Default: 'z'.
142
+ See `.get_dir_vector` for a description of the values.
143
+ """
144
+ self._z = z
145
+ self._dir_vec = get_dir_vector(zdir)
146
+ self.stale = True
147
+
148
+ @artist.allow_rasterization
149
+ def draw(self, renderer):
150
+ position3d = np.array((self._x, self._y, self._z))
151
+ proj = proj3d._proj_trans_points(
152
+ [position3d, position3d + self._dir_vec], self.axes.M)
153
+ dx = proj[0][1] - proj[0][0]
154
+ dy = proj[1][1] - proj[1][0]
155
+ angle = math.degrees(math.atan2(dy, dx))
156
+ with cbook._setattr_cm(self, _x=proj[0][0], _y=proj[1][0],
157
+ _rotation=_norm_text_angle(angle)):
158
+ mtext.Text.draw(self, renderer)
159
+ self.stale = False
160
+
161
+ def get_tightbbox(self, renderer=None):
162
+ # Overwriting the 2d Text behavior which is not valid for 3d.
163
+ # For now, just return None to exclude from layout calculation.
164
+ return None
165
+
166
+
167
+ def text_2d_to_3d(obj, z=0, zdir='z'):
168
+ """
169
+ Convert a `.Text` to a `.Text3D` object.
170
+
171
+ Parameters
172
+ ----------
173
+ z : float
174
+ The z-position in 3D space.
175
+ zdir : {'x', 'y', 'z', 3-tuple}
176
+ The direction of the text. Default: 'z'.
177
+ See `.get_dir_vector` for a description of the values.
178
+ """
179
+ obj.__class__ = Text3D
180
+ obj.set_3d_properties(z, zdir)
181
+
182
+
183
+ class Line3D(lines.Line2D):
184
+ """
185
+ 3D line object.
186
+
187
+ .. note:: Use `get_data_3d` to obtain the data associated with the line.
188
+ `~.Line2D.get_data`, `~.Line2D.get_xdata`, and `~.Line2D.get_ydata` return
189
+ the x- and y-coordinates of the projected 2D-line, not the x- and y-data of
190
+ the 3D-line. Similarly, use `set_data_3d` to set the data, not
191
+ `~.Line2D.set_data`, `~.Line2D.set_xdata`, and `~.Line2D.set_ydata`.
192
+ """
193
+
194
+ def __init__(self, xs, ys, zs, *args, **kwargs):
195
+ """
196
+
197
+ Parameters
198
+ ----------
199
+ xs : array-like
200
+ The x-data to be plotted.
201
+ ys : array-like
202
+ The y-data to be plotted.
203
+ zs : array-like
204
+ The z-data to be plotted.
205
+ *args, **kwargs
206
+ Additional arguments are passed to `~matplotlib.lines.Line2D`.
207
+ """
208
+ super().__init__([], [], *args, **kwargs)
209
+ self.set_data_3d(xs, ys, zs)
210
+
211
+ def set_3d_properties(self, zs=0, zdir='z'):
212
+ """
213
+ Set the *z* position and direction of the line.
214
+
215
+ Parameters
216
+ ----------
217
+ zs : float or array of floats
218
+ The location along the *zdir* axis in 3D space to position the
219
+ line.
220
+ zdir : {'x', 'y', 'z'}
221
+ Plane to plot line orthogonal to. Default: 'z'.
222
+ See `.get_dir_vector` for a description of the values.
223
+ """
224
+ xs = self.get_xdata()
225
+ ys = self.get_ydata()
226
+ zs = cbook._to_unmasked_float_array(zs).ravel()
227
+ zs = np.broadcast_to(zs, len(xs))
228
+ self._verts3d = juggle_axes(xs, ys, zs, zdir)
229
+ self.stale = True
230
+
231
+ def set_data_3d(self, *args):
232
+ """
233
+ Set the x, y and z data
234
+
235
+ Parameters
236
+ ----------
237
+ x : array-like
238
+ The x-data to be plotted.
239
+ y : array-like
240
+ The y-data to be plotted.
241
+ z : array-like
242
+ The z-data to be plotted.
243
+
244
+ Notes
245
+ -----
246
+ Accepts x, y, z arguments or a single array-like (x, y, z)
247
+ """
248
+ if len(args) == 1:
249
+ args = args[0]
250
+ for name, xyz in zip('xyz', args):
251
+ if not np.iterable(xyz):
252
+ raise RuntimeError(f'{name} must be a sequence')
253
+ self._verts3d = args
254
+ self.stale = True
255
+
256
+ def get_data_3d(self):
257
+ """
258
+ Get the current data
259
+
260
+ Returns
261
+ -------
262
+ verts3d : length-3 tuple or array-like
263
+ The current data as a tuple or array-like.
264
+ """
265
+ return self._verts3d
266
+
267
+ @artist.allow_rasterization
268
+ def draw(self, renderer):
269
+ xs3d, ys3d, zs3d = self._verts3d
270
+ xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M)
271
+ self.set_data(xs, ys)
272
+ super().draw(renderer)
273
+ self.stale = False
274
+
275
+
276
+ def line_2d_to_3d(line, zs=0, zdir='z'):
277
+ """
278
+ Convert a `.Line2D` to a `.Line3D` object.
279
+
280
+ Parameters
281
+ ----------
282
+ zs : float
283
+ The location along the *zdir* axis in 3D space to position the line.
284
+ zdir : {'x', 'y', 'z'}
285
+ Plane to plot line orthogonal to. Default: 'z'.
286
+ See `.get_dir_vector` for a description of the values.
287
+ """
288
+
289
+ line.__class__ = Line3D
290
+ line.set_3d_properties(zs, zdir)
291
+
292
+
293
+ def _path_to_3d_segment(path, zs=0, zdir='z'):
294
+ """Convert a path to a 3D segment."""
295
+
296
+ zs = np.broadcast_to(zs, len(path))
297
+ pathsegs = path.iter_segments(simplify=False, curves=False)
298
+ seg = [(x, y, z) for (((x, y), code), z) in zip(pathsegs, zs)]
299
+ seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg]
300
+ return seg3d
301
+
302
+
303
+ def _paths_to_3d_segments(paths, zs=0, zdir='z'):
304
+ """Convert paths from a collection object to 3D segments."""
305
+
306
+ if not np.iterable(zs):
307
+ zs = np.broadcast_to(zs, len(paths))
308
+ else:
309
+ if len(zs) != len(paths):
310
+ raise ValueError('Number of z-coordinates does not match paths.')
311
+
312
+ segs = [_path_to_3d_segment(path, pathz, zdir)
313
+ for path, pathz in zip(paths, zs)]
314
+ return segs
315
+
316
+
317
+ def _path_to_3d_segment_with_codes(path, zs=0, zdir='z'):
318
+ """Convert a path to a 3D segment with path codes."""
319
+
320
+ zs = np.broadcast_to(zs, len(path))
321
+ pathsegs = path.iter_segments(simplify=False, curves=False)
322
+ seg_codes = [((x, y, z), code) for ((x, y), code), z in zip(pathsegs, zs)]
323
+ if seg_codes:
324
+ seg, codes = zip(*seg_codes)
325
+ seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg]
326
+ else:
327
+ seg3d = []
328
+ codes = []
329
+ return seg3d, list(codes)
330
+
331
+
332
+ def _paths_to_3d_segments_with_codes(paths, zs=0, zdir='z'):
333
+ """
334
+ Convert paths from a collection object to 3D segments with path codes.
335
+ """
336
+
337
+ zs = np.broadcast_to(zs, len(paths))
338
+ segments_codes = [_path_to_3d_segment_with_codes(path, pathz, zdir)
339
+ for path, pathz in zip(paths, zs)]
340
+ if segments_codes:
341
+ segments, codes = zip(*segments_codes)
342
+ else:
343
+ segments, codes = [], []
344
+ return list(segments), list(codes)
345
+
346
+
347
+ class Collection3D(Collection):
348
+ """A collection of 3D paths."""
349
+
350
+ def do_3d_projection(self):
351
+ """Project the points according to renderer matrix."""
352
+ xyzs_list = [proj3d.proj_transform(*vs.T, self.axes.M)
353
+ for vs, _ in self._3dverts_codes]
354
+ self._paths = [mpath.Path(np.column_stack([xs, ys]), cs)
355
+ for (xs, ys, _), (_, cs) in zip(xyzs_list, self._3dverts_codes)]
356
+ zs = np.concatenate([zs for _, _, zs in xyzs_list])
357
+ return zs.min() if len(zs) else 1e9
358
+
359
+
360
+ def collection_2d_to_3d(col, zs=0, zdir='z'):
361
+ """Convert a `.Collection` to a `.Collection3D` object."""
362
+ zs = np.broadcast_to(zs, len(col.get_paths()))
363
+ col._3dverts_codes = [
364
+ (np.column_stack(juggle_axes(
365
+ *np.column_stack([p.vertices, np.broadcast_to(z, len(p.vertices))]).T,
366
+ zdir)),
367
+ p.codes)
368
+ for p, z in zip(col.get_paths(), zs)]
369
+ col.__class__ = cbook._make_class_factory(Collection3D, "{}3D")(type(col))
370
+
371
+
372
+ class Line3DCollection(LineCollection):
373
+ """
374
+ A collection of 3D lines.
375
+ """
376
+
377
+ def set_sort_zpos(self, val):
378
+ """Set the position to use for z-sorting."""
379
+ self._sort_zpos = val
380
+ self.stale = True
381
+
382
+ def set_segments(self, segments):
383
+ """
384
+ Set 3D segments.
385
+ """
386
+ self._segments3d = segments
387
+ super().set_segments([])
388
+
389
+ def do_3d_projection(self):
390
+ """
391
+ Project the points according to renderer matrix.
392
+ """
393
+ xyslist = [proj3d._proj_trans_points(points, self.axes.M)
394
+ for points in self._segments3d]
395
+ segments_2d = [np.column_stack([xs, ys]) for xs, ys, zs in xyslist]
396
+ LineCollection.set_segments(self, segments_2d)
397
+
398
+ # FIXME
399
+ minz = 1e9
400
+ for xs, ys, zs in xyslist:
401
+ minz = min(minz, min(zs))
402
+ return minz
403
+
404
+
405
+ def line_collection_2d_to_3d(col, zs=0, zdir='z'):
406
+ """Convert a `.LineCollection` to a `.Line3DCollection` object."""
407
+ segments3d = _paths_to_3d_segments(col.get_paths(), zs, zdir)
408
+ col.__class__ = Line3DCollection
409
+ col.set_segments(segments3d)
410
+
411
+
412
+ class Patch3D(Patch):
413
+ """
414
+ 3D patch object.
415
+ """
416
+
417
+ def __init__(self, *args, zs=(), zdir='z', **kwargs):
418
+ """
419
+ Parameters
420
+ ----------
421
+ verts :
422
+ zs : float
423
+ The location along the *zdir* axis in 3D space to position the
424
+ patch.
425
+ zdir : {'x', 'y', 'z'}
426
+ Plane to plot patch orthogonal to. Default: 'z'.
427
+ See `.get_dir_vector` for a description of the values.
428
+ """
429
+ super().__init__(*args, **kwargs)
430
+ self.set_3d_properties(zs, zdir)
431
+
432
+ def set_3d_properties(self, verts, zs=0, zdir='z'):
433
+ """
434
+ Set the *z* position and direction of the patch.
435
+
436
+ Parameters
437
+ ----------
438
+ verts :
439
+ zs : float
440
+ The location along the *zdir* axis in 3D space to position the
441
+ patch.
442
+ zdir : {'x', 'y', 'z'}
443
+ Plane to plot patch orthogonal to. Default: 'z'.
444
+ See `.get_dir_vector` for a description of the values.
445
+ """
446
+ zs = np.broadcast_to(zs, len(verts))
447
+ self._segment3d = [juggle_axes(x, y, z, zdir)
448
+ for ((x, y), z) in zip(verts, zs)]
449
+
450
+ def get_path(self):
451
+ # docstring inherited
452
+ # self._path2d is not initialized until do_3d_projection
453
+ if not hasattr(self, '_path2d'):
454
+ self.axes.M = self.axes.get_proj()
455
+ self.do_3d_projection()
456
+ return self._path2d
457
+
458
+ def do_3d_projection(self):
459
+ s = self._segment3d
460
+ xs, ys, zs = zip(*s)
461
+ vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,
462
+ self.axes.M)
463
+ self._path2d = mpath.Path(np.column_stack([vxs, vys]))
464
+ return min(vzs)
465
+
466
+
467
+ class PathPatch3D(Patch3D):
468
+ """
469
+ 3D PathPatch object.
470
+ """
471
+
472
+ def __init__(self, path, *, zs=(), zdir='z', **kwargs):
473
+ """
474
+ Parameters
475
+ ----------
476
+ path :
477
+ zs : float
478
+ The location along the *zdir* axis in 3D space to position the
479
+ path patch.
480
+ zdir : {'x', 'y', 'z', 3-tuple}
481
+ Plane to plot path patch orthogonal to. Default: 'z'.
482
+ See `.get_dir_vector` for a description of the values.
483
+ """
484
+ # Not super().__init__!
485
+ Patch.__init__(self, **kwargs)
486
+ self.set_3d_properties(path, zs, zdir)
487
+
488
+ def set_3d_properties(self, path, zs=0, zdir='z'):
489
+ """
490
+ Set the *z* position and direction of the path patch.
491
+
492
+ Parameters
493
+ ----------
494
+ path :
495
+ zs : float
496
+ The location along the *zdir* axis in 3D space to position the
497
+ path patch.
498
+ zdir : {'x', 'y', 'z', 3-tuple}
499
+ Plane to plot path patch orthogonal to. Default: 'z'.
500
+ See `.get_dir_vector` for a description of the values.
501
+ """
502
+ Patch3D.set_3d_properties(self, path.vertices, zs=zs, zdir=zdir)
503
+ self._code3d = path.codes
504
+
505
+ def do_3d_projection(self):
506
+ s = self._segment3d
507
+ xs, ys, zs = zip(*s)
508
+ vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,
509
+ self.axes.M)
510
+ self._path2d = mpath.Path(np.column_stack([vxs, vys]), self._code3d)
511
+ return min(vzs)
512
+
513
+
514
+ def _get_patch_verts(patch):
515
+ """Return a list of vertices for the path of a patch."""
516
+ trans = patch.get_patch_transform()
517
+ path = patch.get_path()
518
+ polygons = path.to_polygons(trans)
519
+ return polygons[0] if len(polygons) else np.array([])
520
+
521
+
522
+ def patch_2d_to_3d(patch, z=0, zdir='z'):
523
+ """Convert a `.Patch` to a `.Patch3D` object."""
524
+ verts = _get_patch_verts(patch)
525
+ patch.__class__ = Patch3D
526
+ patch.set_3d_properties(verts, z, zdir)
527
+
528
+
529
+ def pathpatch_2d_to_3d(pathpatch, z=0, zdir='z'):
530
+ """Convert a `.PathPatch` to a `.PathPatch3D` object."""
531
+ path = pathpatch.get_path()
532
+ trans = pathpatch.get_patch_transform()
533
+
534
+ mpath = trans.transform_path(path)
535
+ pathpatch.__class__ = PathPatch3D
536
+ pathpatch.set_3d_properties(mpath, z, zdir)
537
+
538
+
539
+ class Patch3DCollection(PatchCollection):
540
+ """
541
+ A collection of 3D patches.
542
+ """
543
+
544
+ def __init__(self, *args, zs=0, zdir='z', depthshade=True, **kwargs):
545
+ """
546
+ Create a collection of flat 3D patches with its normal vector
547
+ pointed in *zdir* direction, and located at *zs* on the *zdir*
548
+ axis. 'zs' can be a scalar or an array-like of the same length as
549
+ the number of patches in the collection.
550
+
551
+ Constructor arguments are the same as for
552
+ :class:`~matplotlib.collections.PatchCollection`. In addition,
553
+ keywords *zs=0* and *zdir='z'* are available.
554
+
555
+ Also, the keyword argument *depthshade* is available to indicate
556
+ whether to shade the patches in order to give the appearance of depth
557
+ (default is *True*). This is typically desired in scatter plots.
558
+ """
559
+ self._depthshade = depthshade
560
+ super().__init__(*args, **kwargs)
561
+ self.set_3d_properties(zs, zdir)
562
+
563
+ def get_depthshade(self):
564
+ return self._depthshade
565
+
566
+ def set_depthshade(self, depthshade):
567
+ """
568
+ Set whether depth shading is performed on collection members.
569
+
570
+ Parameters
571
+ ----------
572
+ depthshade : bool
573
+ Whether to shade the patches in order to give the appearance of
574
+ depth.
575
+ """
576
+ self._depthshade = depthshade
577
+ self.stale = True
578
+
579
+ def set_sort_zpos(self, val):
580
+ """Set the position to use for z-sorting."""
581
+ self._sort_zpos = val
582
+ self.stale = True
583
+
584
+ def set_3d_properties(self, zs, zdir):
585
+ """
586
+ Set the *z* positions and direction of the patches.
587
+
588
+ Parameters
589
+ ----------
590
+ zs : float or array of floats
591
+ The location or locations to place the patches in the collection
592
+ along the *zdir* axis.
593
+ zdir : {'x', 'y', 'z'}
594
+ Plane to plot patches orthogonal to.
595
+ All patches must have the same direction.
596
+ See `.get_dir_vector` for a description of the values.
597
+ """
598
+ # Force the collection to initialize the face and edgecolors
599
+ # just in case it is a scalarmappable with a colormap.
600
+ self.update_scalarmappable()
601
+ offsets = self.get_offsets()
602
+ if len(offsets) > 0:
603
+ xs, ys = offsets.T
604
+ else:
605
+ xs = []
606
+ ys = []
607
+ self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)
608
+ self._z_markers_idx = slice(-1)
609
+ self._vzs = None
610
+ self.stale = True
611
+
612
+ def do_3d_projection(self):
613
+ xs, ys, zs = self._offsets3d
614
+ vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,
615
+ self.axes.M)
616
+ self._vzs = vzs
617
+ super().set_offsets(np.column_stack([vxs, vys]))
618
+
619
+ if vzs.size > 0:
620
+ return min(vzs)
621
+ else:
622
+ return np.nan
623
+
624
+ def _maybe_depth_shade_and_sort_colors(self, color_array):
625
+ color_array = (
626
+ _zalpha(color_array, self._vzs)
627
+ if self._vzs is not None and self._depthshade
628
+ else color_array
629
+ )
630
+ if len(color_array) > 1:
631
+ color_array = color_array[self._z_markers_idx]
632
+ return mcolors.to_rgba_array(color_array, self._alpha)
633
+
634
+ def get_facecolor(self):
635
+ return self._maybe_depth_shade_and_sort_colors(super().get_facecolor())
636
+
637
+ def get_edgecolor(self):
638
+ # We need this check here to make sure we do not double-apply the depth
639
+ # based alpha shading when the edge color is "face" which means the
640
+ # edge colour should be identical to the face colour.
641
+ if cbook._str_equal(self._edgecolors, 'face'):
642
+ return self.get_facecolor()
643
+ return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor())
644
+
645
+
646
+ class Path3DCollection(PathCollection):
647
+ """
648
+ A collection of 3D paths.
649
+ """
650
+
651
+ def __init__(self, *args, zs=0, zdir='z', depthshade=True, **kwargs):
652
+ """
653
+ Create a collection of flat 3D paths with its normal vector
654
+ pointed in *zdir* direction, and located at *zs* on the *zdir*
655
+ axis. 'zs' can be a scalar or an array-like of the same length as
656
+ the number of paths in the collection.
657
+
658
+ Constructor arguments are the same as for
659
+ :class:`~matplotlib.collections.PathCollection`. In addition,
660
+ keywords *zs=0* and *zdir='z'* are available.
661
+
662
+ Also, the keyword argument *depthshade* is available to indicate
663
+ whether to shade the patches in order to give the appearance of depth
664
+ (default is *True*). This is typically desired in scatter plots.
665
+ """
666
+ self._depthshade = depthshade
667
+ self._in_draw = False
668
+ super().__init__(*args, **kwargs)
669
+ self.set_3d_properties(zs, zdir)
670
+ self._offset_zordered = None
671
+
672
+ def draw(self, renderer):
673
+ with self._use_zordered_offset():
674
+ with cbook._setattr_cm(self, _in_draw=True):
675
+ super().draw(renderer)
676
+
677
+ def set_sort_zpos(self, val):
678
+ """Set the position to use for z-sorting."""
679
+ self._sort_zpos = val
680
+ self.stale = True
681
+
682
+ def set_3d_properties(self, zs, zdir):
683
+ """
684
+ Set the *z* positions and direction of the paths.
685
+
686
+ Parameters
687
+ ----------
688
+ zs : float or array of floats
689
+ The location or locations to place the paths in the collection
690
+ along the *zdir* axis.
691
+ zdir : {'x', 'y', 'z'}
692
+ Plane to plot paths orthogonal to.
693
+ All paths must have the same direction.
694
+ See `.get_dir_vector` for a description of the values.
695
+ """
696
+ # Force the collection to initialize the face and edgecolors
697
+ # just in case it is a scalarmappable with a colormap.
698
+ self.update_scalarmappable()
699
+ offsets = self.get_offsets()
700
+ if len(offsets) > 0:
701
+ xs, ys = offsets.T
702
+ else:
703
+ xs = []
704
+ ys = []
705
+ self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)
706
+ # In the base draw methods we access the attributes directly which
707
+ # means we cannot resolve the shuffling in the getter methods like
708
+ # we do for the edge and face colors.
709
+ #
710
+ # This means we need to carry around a cache of the unsorted sizes and
711
+ # widths (postfixed with 3d) and in `do_3d_projection` set the
712
+ # depth-sorted version of that data into the private state used by the
713
+ # base collection class in its draw method.
714
+ #
715
+ # Grab the current sizes and linewidths to preserve them.
716
+ self._sizes3d = self._sizes
717
+ self._linewidths3d = np.array(self._linewidths)
718
+ xs, ys, zs = self._offsets3d
719
+
720
+ # Sort the points based on z coordinates
721
+ # Performance optimization: Create a sorted index array and reorder
722
+ # points and point properties according to the index array
723
+ self._z_markers_idx = slice(-1)
724
+ self._vzs = None
725
+ self.stale = True
726
+
727
+ def set_sizes(self, sizes, dpi=72.0):
728
+ super().set_sizes(sizes, dpi)
729
+ if not self._in_draw:
730
+ self._sizes3d = sizes
731
+
732
+ def set_linewidth(self, lw):
733
+ super().set_linewidth(lw)
734
+ if not self._in_draw:
735
+ self._linewidths3d = np.array(self._linewidths)
736
+
737
+ def get_depthshade(self):
738
+ return self._depthshade
739
+
740
+ def set_depthshade(self, depthshade):
741
+ """
742
+ Set whether depth shading is performed on collection members.
743
+
744
+ Parameters
745
+ ----------
746
+ depthshade : bool
747
+ Whether to shade the patches in order to give the appearance of
748
+ depth.
749
+ """
750
+ self._depthshade = depthshade
751
+ self.stale = True
752
+
753
+ def do_3d_projection(self):
754
+ xs, ys, zs = self._offsets3d
755
+ vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,
756
+ self.axes.M)
757
+ # Sort the points based on z coordinates
758
+ # Performance optimization: Create a sorted index array and reorder
759
+ # points and point properties according to the index array
760
+ z_markers_idx = self._z_markers_idx = np.argsort(vzs)[::-1]
761
+ self._vzs = vzs
762
+
763
+ # we have to special case the sizes because of code in collections.py
764
+ # as the draw method does
765
+ # self.set_sizes(self._sizes, self.figure.dpi)
766
+ # so we cannot rely on doing the sorting on the way out via get_*
767
+
768
+ if len(self._sizes3d) > 1:
769
+ self._sizes = self._sizes3d[z_markers_idx]
770
+
771
+ if len(self._linewidths3d) > 1:
772
+ self._linewidths = self._linewidths3d[z_markers_idx]
773
+
774
+ PathCollection.set_offsets(self, np.column_stack((vxs, vys)))
775
+
776
+ # Re-order items
777
+ vzs = vzs[z_markers_idx]
778
+ vxs = vxs[z_markers_idx]
779
+ vys = vys[z_markers_idx]
780
+
781
+ # Store ordered offset for drawing purpose
782
+ self._offset_zordered = np.column_stack((vxs, vys))
783
+
784
+ return np.min(vzs) if vzs.size else np.nan
785
+
786
+ @contextmanager
787
+ def _use_zordered_offset(self):
788
+ if self._offset_zordered is None:
789
+ # Do nothing
790
+ yield
791
+ else:
792
+ # Swap offset with z-ordered offset
793
+ old_offset = self._offsets
794
+ super().set_offsets(self._offset_zordered)
795
+ try:
796
+ yield
797
+ finally:
798
+ self._offsets = old_offset
799
+
800
+ def _maybe_depth_shade_and_sort_colors(self, color_array):
801
+ color_array = (
802
+ _zalpha(color_array, self._vzs)
803
+ if self._vzs is not None and self._depthshade
804
+ else color_array
805
+ )
806
+ if len(color_array) > 1:
807
+ color_array = color_array[self._z_markers_idx]
808
+ return mcolors.to_rgba_array(color_array, self._alpha)
809
+
810
+ def get_facecolor(self):
811
+ return self._maybe_depth_shade_and_sort_colors(super().get_facecolor())
812
+
813
+ def get_edgecolor(self):
814
+ # We need this check here to make sure we do not double-apply the depth
815
+ # based alpha shading when the edge color is "face" which means the
816
+ # edge colour should be identical to the face colour.
817
+ if cbook._str_equal(self._edgecolors, 'face'):
818
+ return self.get_facecolor()
819
+ return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor())
820
+
821
+
822
+ def patch_collection_2d_to_3d(col, zs=0, zdir='z', depthshade=True):
823
+ """
824
+ Convert a `.PatchCollection` into a `.Patch3DCollection` object
825
+ (or a `.PathCollection` into a `.Path3DCollection` object).
826
+
827
+ Parameters
828
+ ----------
829
+ col : `~matplotlib.collections.PatchCollection` or \
830
+ `~matplotlib.collections.PathCollection`
831
+ The collection to convert.
832
+ zs : float or array of floats
833
+ The location or locations to place the patches in the collection along
834
+ the *zdir* axis. Default: 0.
835
+ zdir : {'x', 'y', 'z'}
836
+ The axis in which to place the patches. Default: "z".
837
+ See `.get_dir_vector` for a description of the values.
838
+ depthshade : bool, default: True
839
+ Whether to shade the patches to give a sense of depth.
840
+
841
+ """
842
+ if isinstance(col, PathCollection):
843
+ col.__class__ = Path3DCollection
844
+ col._offset_zordered = None
845
+ elif isinstance(col, PatchCollection):
846
+ col.__class__ = Patch3DCollection
847
+ col._depthshade = depthshade
848
+ col._in_draw = False
849
+ col.set_3d_properties(zs, zdir)
850
+
851
+
852
+ class Poly3DCollection(PolyCollection):
853
+ """
854
+ A collection of 3D polygons.
855
+
856
+ .. note::
857
+ **Filling of 3D polygons**
858
+
859
+ There is no simple definition of the enclosed surface of a 3D polygon
860
+ unless the polygon is planar.
861
+
862
+ In practice, Matplotlib fills the 2D projection of the polygon. This
863
+ gives a correct filling appearance only for planar polygons. For all
864
+ other polygons, you'll find orientations in which the edges of the
865
+ polygon intersect in the projection. This will lead to an incorrect
866
+ visualization of the 3D area.
867
+
868
+ If you need filled areas, it is recommended to create them via
869
+ `~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_trisurf`, which creates a
870
+ triangulation and thus generates consistent surfaces.
871
+ """
872
+
873
+ def __init__(self, verts, *args, zsort='average', shade=False,
874
+ lightsource=None, **kwargs):
875
+ """
876
+ Parameters
877
+ ----------
878
+ verts : list of (N, 3) array-like
879
+ The sequence of polygons [*verts0*, *verts1*, ...] where each
880
+ element *verts_i* defines the vertices of polygon *i* as a 2D
881
+ array-like of shape (N, 3).
882
+ zsort : {'average', 'min', 'max'}, default: 'average'
883
+ The calculation method for the z-order.
884
+ See `~.Poly3DCollection.set_zsort` for details.
885
+ shade : bool, default: False
886
+ Whether to shade *facecolors* and *edgecolors*. When activating
887
+ *shade*, *facecolors* and/or *edgecolors* must be provided.
888
+
889
+ .. versionadded:: 3.7
890
+
891
+ lightsource : `~matplotlib.colors.LightSource`, optional
892
+ The lightsource to use when *shade* is True.
893
+
894
+ .. versionadded:: 3.7
895
+
896
+ *args, **kwargs
897
+ All other parameters are forwarded to `.PolyCollection`.
898
+
899
+ Notes
900
+ -----
901
+ Note that this class does a bit of magic with the _facecolors
902
+ and _edgecolors properties.
903
+ """
904
+ if shade:
905
+ normals = _generate_normals(verts)
906
+ facecolors = kwargs.get('facecolors', None)
907
+ if facecolors is not None:
908
+ kwargs['facecolors'] = _shade_colors(
909
+ facecolors, normals, lightsource
910
+ )
911
+
912
+ edgecolors = kwargs.get('edgecolors', None)
913
+ if edgecolors is not None:
914
+ kwargs['edgecolors'] = _shade_colors(
915
+ edgecolors, normals, lightsource
916
+ )
917
+ if facecolors is None and edgecolors is None:
918
+ raise ValueError(
919
+ "You must provide facecolors, edgecolors, or both for "
920
+ "shade to work.")
921
+ super().__init__(verts, *args, **kwargs)
922
+ if isinstance(verts, np.ndarray):
923
+ if verts.ndim != 3:
924
+ raise ValueError('verts must be a list of (N, 3) array-like')
925
+ else:
926
+ if any(len(np.shape(vert)) != 2 for vert in verts):
927
+ raise ValueError('verts must be a list of (N, 3) array-like')
928
+ self.set_zsort(zsort)
929
+ self._codes3d = None
930
+
931
+ _zsort_functions = {
932
+ 'average': np.average,
933
+ 'min': np.min,
934
+ 'max': np.max,
935
+ }
936
+
937
+ def set_zsort(self, zsort):
938
+ """
939
+ Set the calculation method for the z-order.
940
+
941
+ Parameters
942
+ ----------
943
+ zsort : {'average', 'min', 'max'}
944
+ The function applied on the z-coordinates of the vertices in the
945
+ viewer's coordinate system, to determine the z-order.
946
+ """
947
+ self._zsortfunc = self._zsort_functions[zsort]
948
+ self._sort_zpos = None
949
+ self.stale = True
950
+
951
+ def get_vector(self, segments3d):
952
+ """Optimize points for projection."""
953
+ if len(segments3d):
954
+ xs, ys, zs = np.vstack(segments3d).T
955
+ else: # vstack can't stack zero arrays.
956
+ xs, ys, zs = [], [], []
957
+ ones = np.ones(len(xs))
958
+ self._vec = np.array([xs, ys, zs, ones])
959
+
960
+ indices = [0, *np.cumsum([len(segment) for segment in segments3d])]
961
+ self._segslices = [*map(slice, indices[:-1], indices[1:])]
962
+
963
+ def set_verts(self, verts, closed=True):
964
+ """
965
+ Set 3D vertices.
966
+
967
+ Parameters
968
+ ----------
969
+ verts : list of (N, 3) array-like
970
+ The sequence of polygons [*verts0*, *verts1*, ...] where each
971
+ element *verts_i* defines the vertices of polygon *i* as a 2D
972
+ array-like of shape (N, 3).
973
+ closed : bool, default: True
974
+ Whether the polygon should be closed by adding a CLOSEPOLY
975
+ connection at the end.
976
+ """
977
+ self.get_vector(verts)
978
+ # 2D verts will be updated at draw time
979
+ super().set_verts([], False)
980
+ self._closed = closed
981
+
982
+ def set_verts_and_codes(self, verts, codes):
983
+ """Set 3D vertices with path codes."""
984
+ # set vertices with closed=False to prevent PolyCollection from
985
+ # setting path codes
986
+ self.set_verts(verts, closed=False)
987
+ # and set our own codes instead.
988
+ self._codes3d = codes
989
+
990
+ def set_3d_properties(self):
991
+ # Force the collection to initialize the face and edgecolors
992
+ # just in case it is a scalarmappable with a colormap.
993
+ self.update_scalarmappable()
994
+ self._sort_zpos = None
995
+ self.set_zsort('average')
996
+ self._facecolor3d = PolyCollection.get_facecolor(self)
997
+ self._edgecolor3d = PolyCollection.get_edgecolor(self)
998
+ self._alpha3d = PolyCollection.get_alpha(self)
999
+ self.stale = True
1000
+
1001
+ def set_sort_zpos(self, val):
1002
+ """Set the position to use for z-sorting."""
1003
+ self._sort_zpos = val
1004
+ self.stale = True
1005
+
1006
+ def do_3d_projection(self):
1007
+ """
1008
+ Perform the 3D projection for this object.
1009
+ """
1010
+ if self._A is not None:
1011
+ # force update of color mapping because we re-order them
1012
+ # below. If we do not do this here, the 2D draw will call
1013
+ # this, but we will never port the color mapped values back
1014
+ # to the 3D versions.
1015
+ #
1016
+ # We hold the 3D versions in a fixed order (the order the user
1017
+ # passed in) and sort the 2D version by view depth.
1018
+ self.update_scalarmappable()
1019
+ if self._face_is_mapped:
1020
+ self._facecolor3d = self._facecolors
1021
+ if self._edge_is_mapped:
1022
+ self._edgecolor3d = self._edgecolors
1023
+ txs, tys, tzs = proj3d._proj_transform_vec(self._vec, self.axes.M)
1024
+ xyzlist = [(txs[sl], tys[sl], tzs[sl]) for sl in self._segslices]
1025
+
1026
+ # This extra fuss is to re-order face / edge colors
1027
+ cface = self._facecolor3d
1028
+ cedge = self._edgecolor3d
1029
+ if len(cface) != len(xyzlist):
1030
+ cface = cface.repeat(len(xyzlist), axis=0)
1031
+ if len(cedge) != len(xyzlist):
1032
+ if len(cedge) == 0:
1033
+ cedge = cface
1034
+ else:
1035
+ cedge = cedge.repeat(len(xyzlist), axis=0)
1036
+
1037
+ if xyzlist:
1038
+ # sort by depth (furthest drawn first)
1039
+ z_segments_2d = sorted(
1040
+ ((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx)
1041
+ for idx, ((xs, ys, zs), fc, ec)
1042
+ in enumerate(zip(xyzlist, cface, cedge))),
1043
+ key=lambda x: x[0], reverse=True)
1044
+
1045
+ _, segments_2d, self._facecolors2d, self._edgecolors2d, idxs = \
1046
+ zip(*z_segments_2d)
1047
+ else:
1048
+ segments_2d = []
1049
+ self._facecolors2d = np.empty((0, 4))
1050
+ self._edgecolors2d = np.empty((0, 4))
1051
+ idxs = []
1052
+
1053
+ if self._codes3d is not None:
1054
+ codes = [self._codes3d[idx] for idx in idxs]
1055
+ PolyCollection.set_verts_and_codes(self, segments_2d, codes)
1056
+ else:
1057
+ PolyCollection.set_verts(self, segments_2d, self._closed)
1058
+
1059
+ if len(self._edgecolor3d) != len(cface):
1060
+ self._edgecolors2d = self._edgecolor3d
1061
+
1062
+ # Return zorder value
1063
+ if self._sort_zpos is not None:
1064
+ zvec = np.array([[0], [0], [self._sort_zpos], [1]])
1065
+ ztrans = proj3d._proj_transform_vec(zvec, self.axes.M)
1066
+ return ztrans[2][0]
1067
+ elif tzs.size > 0:
1068
+ # FIXME: Some results still don't look quite right.
1069
+ # In particular, examine contourf3d_demo2.py
1070
+ # with az = -54 and elev = -45.
1071
+ return np.min(tzs)
1072
+ else:
1073
+ return np.nan
1074
+
1075
+ def set_facecolor(self, colors):
1076
+ # docstring inherited
1077
+ super().set_facecolor(colors)
1078
+ self._facecolor3d = PolyCollection.get_facecolor(self)
1079
+
1080
+ def set_edgecolor(self, colors):
1081
+ # docstring inherited
1082
+ super().set_edgecolor(colors)
1083
+ self._edgecolor3d = PolyCollection.get_edgecolor(self)
1084
+
1085
+ def set_alpha(self, alpha):
1086
+ # docstring inherited
1087
+ artist.Artist.set_alpha(self, alpha)
1088
+ try:
1089
+ self._facecolor3d = mcolors.to_rgba_array(
1090
+ self._facecolor3d, self._alpha)
1091
+ except (AttributeError, TypeError, IndexError):
1092
+ pass
1093
+ try:
1094
+ self._edgecolors = mcolors.to_rgba_array(
1095
+ self._edgecolor3d, self._alpha)
1096
+ except (AttributeError, TypeError, IndexError):
1097
+ pass
1098
+ self.stale = True
1099
+
1100
+ def get_facecolor(self):
1101
+ # docstring inherited
1102
+ # self._facecolors2d is not initialized until do_3d_projection
1103
+ if not hasattr(self, '_facecolors2d'):
1104
+ self.axes.M = self.axes.get_proj()
1105
+ self.do_3d_projection()
1106
+ return np.asarray(self._facecolors2d)
1107
+
1108
+ def get_edgecolor(self):
1109
+ # docstring inherited
1110
+ # self._edgecolors2d is not initialized until do_3d_projection
1111
+ if not hasattr(self, '_edgecolors2d'):
1112
+ self.axes.M = self.axes.get_proj()
1113
+ self.do_3d_projection()
1114
+ return np.asarray(self._edgecolors2d)
1115
+
1116
+
1117
+ def poly_collection_2d_to_3d(col, zs=0, zdir='z'):
1118
+ """
1119
+ Convert a `.PolyCollection` into a `.Poly3DCollection` object.
1120
+
1121
+ Parameters
1122
+ ----------
1123
+ col : `~matplotlib.collections.PolyCollection`
1124
+ The collection to convert.
1125
+ zs : float or array of floats
1126
+ The location or locations to place the polygons in the collection along
1127
+ the *zdir* axis. Default: 0.
1128
+ zdir : {'x', 'y', 'z'}
1129
+ The axis in which to place the patches. Default: 'z'.
1130
+ See `.get_dir_vector` for a description of the values.
1131
+ """
1132
+ segments_3d, codes = _paths_to_3d_segments_with_codes(
1133
+ col.get_paths(), zs, zdir)
1134
+ col.__class__ = Poly3DCollection
1135
+ col.set_verts_and_codes(segments_3d, codes)
1136
+ col.set_3d_properties()
1137
+
1138
+
1139
+ def juggle_axes(xs, ys, zs, zdir):
1140
+ """
1141
+ Reorder coordinates so that 2D *xs*, *ys* can be plotted in the plane
1142
+ orthogonal to *zdir*. *zdir* is normally 'x', 'y' or 'z'. However, if
1143
+ *zdir* starts with a '-' it is interpreted as a compensation for
1144
+ `rotate_axes`.
1145
+ """
1146
+ if zdir == 'x':
1147
+ return zs, xs, ys
1148
+ elif zdir == 'y':
1149
+ return xs, zs, ys
1150
+ elif zdir[0] == '-':
1151
+ return rotate_axes(xs, ys, zs, zdir)
1152
+ else:
1153
+ return xs, ys, zs
1154
+
1155
+
1156
+ def rotate_axes(xs, ys, zs, zdir):
1157
+ """
1158
+ Reorder coordinates so that the axes are rotated with *zdir* along
1159
+ the original z axis. Prepending the axis with a '-' does the
1160
+ inverse transform, so *zdir* can be 'x', '-x', 'y', '-y', 'z' or '-z'.
1161
+ """
1162
+ if zdir in ('x', '-y'):
1163
+ return ys, zs, xs
1164
+ elif zdir in ('-x', 'y'):
1165
+ return zs, xs, ys
1166
+ else:
1167
+ return xs, ys, zs
1168
+
1169
+
1170
+ def _zalpha(colors, zs):
1171
+ """Modify the alphas of the color list according to depth."""
1172
+ # FIXME: This only works well if the points for *zs* are well-spaced
1173
+ # in all three dimensions. Otherwise, at certain orientations,
1174
+ # the min and max zs are very close together.
1175
+ # Should really normalize against the viewing depth.
1176
+ if len(colors) == 0 or len(zs) == 0:
1177
+ return np.zeros((0, 4))
1178
+ norm = Normalize(min(zs), max(zs))
1179
+ sats = 1 - norm(zs) * 0.7
1180
+ rgba = np.broadcast_to(mcolors.to_rgba_array(colors), (len(zs), 4))
1181
+ return np.column_stack([rgba[:, :3], rgba[:, 3] * sats])
1182
+
1183
+
1184
+ def _generate_normals(polygons):
1185
+ """
1186
+ Compute the normals of a list of polygons, one normal per polygon.
1187
+
1188
+ Normals point towards the viewer for a face with its vertices in
1189
+ counterclockwise order, following the right hand rule.
1190
+
1191
+ Uses three points equally spaced around the polygon. This method assumes
1192
+ that the points are in a plane. Otherwise, more than one shade is required,
1193
+ which is not supported.
1194
+
1195
+ Parameters
1196
+ ----------
1197
+ polygons : list of (M_i, 3) array-like, or (..., M, 3) array-like
1198
+ A sequence of polygons to compute normals for, which can have
1199
+ varying numbers of vertices. If the polygons all have the same
1200
+ number of vertices and array is passed, then the operation will
1201
+ be vectorized.
1202
+
1203
+ Returns
1204
+ -------
1205
+ normals : (..., 3) array
1206
+ A normal vector estimated for the polygon.
1207
+ """
1208
+ if isinstance(polygons, np.ndarray):
1209
+ # optimization: polygons all have the same number of points, so can
1210
+ # vectorize
1211
+ n = polygons.shape[-2]
1212
+ i1, i2, i3 = 0, n//3, 2*n//3
1213
+ v1 = polygons[..., i1, :] - polygons[..., i2, :]
1214
+ v2 = polygons[..., i2, :] - polygons[..., i3, :]
1215
+ else:
1216
+ # The subtraction doesn't vectorize because polygons is jagged.
1217
+ v1 = np.empty((len(polygons), 3))
1218
+ v2 = np.empty((len(polygons), 3))
1219
+ for poly_i, ps in enumerate(polygons):
1220
+ n = len(ps)
1221
+ i1, i2, i3 = 0, n//3, 2*n//3
1222
+ v1[poly_i, :] = ps[i1, :] - ps[i2, :]
1223
+ v2[poly_i, :] = ps[i2, :] - ps[i3, :]
1224
+ return np.cross(v1, v2)
1225
+
1226
+
1227
+ def _shade_colors(color, normals, lightsource=None):
1228
+ """
1229
+ Shade *color* using normal vectors given by *normals*,
1230
+ assuming a *lightsource* (using default position if not given).
1231
+ *color* can also be an array of the same length as *normals*.
1232
+ """
1233
+ if lightsource is None:
1234
+ # chosen for backwards-compatibility
1235
+ lightsource = mcolors.LightSource(azdeg=225, altdeg=19.4712)
1236
+
1237
+ with np.errstate(invalid="ignore"):
1238
+ shade = ((normals / np.linalg.norm(normals, axis=1, keepdims=True))
1239
+ @ lightsource.direction)
1240
+ mask = ~np.isnan(shade)
1241
+
1242
+ if mask.any():
1243
+ # convert dot product to allowed shading fractions
1244
+ in_norm = mcolors.Normalize(-1, 1)
1245
+ out_norm = mcolors.Normalize(0.3, 1).inverse
1246
+
1247
+ def norm(x):
1248
+ return out_norm(in_norm(x))
1249
+
1250
+ shade[~mask] = 0
1251
+
1252
+ color = mcolors.to_rgba_array(color)
1253
+ # shape of color should be (M, 4) (where M is number of faces)
1254
+ # shape of shade should be (M,)
1255
+ # colors should have final shape of (M, 4)
1256
+ alpha = color[:, 3]
1257
+ colors = norm(shade)[:, np.newaxis] * color
1258
+ colors[:, 3] = alpha
1259
+ else:
1260
+ colors = np.asanyarray(color).copy()
1261
+
1262
+ return colors
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/axes3d.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_internvl/lib/python3.10/site-packages/mpl_toolkits/mplot3d/axis3d.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # axis3d.py, original mplot3d version by John Porter
2
+ # Created: 23 Sep 2005
3
+ # Parts rewritten by Reinier Heeres <reinier@heeres.eu>
4
+
5
+ import inspect
6
+
7
+ import numpy as np
8
+
9
+ import matplotlib as mpl
10
+ from matplotlib import (
11
+ _api, artist, lines as mlines, axis as maxis, patches as mpatches,
12
+ transforms as mtransforms, colors as mcolors)
13
+ from . import art3d, proj3d
14
+
15
+
16
+ def _move_from_center(coord, centers, deltas, axmask=(True, True, True)):
17
+ """
18
+ For each coordinate where *axmask* is True, move *coord* away from
19
+ *centers* by *deltas*.
20
+ """
21
+ coord = np.asarray(coord)
22
+ return coord + axmask * np.copysign(1, coord - centers) * deltas
23
+
24
+
25
+ def _tick_update_position(tick, tickxs, tickys, labelpos):
26
+ """Update tick line and label position and style."""
27
+
28
+ tick.label1.set_position(labelpos)
29
+ tick.label2.set_position(labelpos)
30
+ tick.tick1line.set_visible(True)
31
+ tick.tick2line.set_visible(False)
32
+ tick.tick1line.set_linestyle('-')
33
+ tick.tick1line.set_marker('')
34
+ tick.tick1line.set_data(tickxs, tickys)
35
+ tick.gridline.set_data([0], [0])
36
+
37
+
38
+ class Axis(maxis.XAxis):
39
+ """An Axis class for the 3D plots."""
40
+ # These points from the unit cube make up the x, y and z-planes
41
+ _PLANES = (
42
+ (0, 3, 7, 4), (1, 2, 6, 5), # yz planes
43
+ (0, 1, 5, 4), (3, 2, 6, 7), # xz planes
44
+ (0, 1, 2, 3), (4, 5, 6, 7), # xy planes
45
+ )
46
+
47
+ # Some properties for the axes
48
+ _AXINFO = {
49
+ 'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2)},
50
+ 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2)},
51
+ 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1)},
52
+ }
53
+
54
+ def _old_init(self, adir, v_intervalx, d_intervalx, axes, *args,
55
+ rotate_label=None, **kwargs):
56
+ return locals()
57
+
58
+ def _new_init(self, axes, *, rotate_label=None, **kwargs):
59
+ return locals()
60
+
61
+ def __init__(self, *args, **kwargs):
62
+ params = _api.select_matching_signature(
63
+ [self._old_init, self._new_init], *args, **kwargs)
64
+ if "adir" in params:
65
+ _api.warn_deprecated(
66
+ "3.6", message=f"The signature of 3D Axis constructors has "
67
+ f"changed in %(since)s; the new signature is "
68
+ f"{inspect.signature(type(self).__init__)}", pending=True)
69
+ if params["adir"] != self.axis_name:
70
+ raise ValueError(f"Cannot instantiate {type(self).__name__} "
71
+ f"with adir={params['adir']!r}")
72
+ axes = params["axes"]
73
+ rotate_label = params["rotate_label"]
74
+ args = params.get("args", ())
75
+ kwargs = params["kwargs"]
76
+
77
+ name = self.axis_name
78
+
79
+ self._label_position = 'default'
80
+ self._tick_position = 'default'
81
+
82
+ # This is a temporary member variable.
83
+ # Do not depend on this existing in future releases!
84
+ self._axinfo = self._AXINFO[name].copy()
85
+ # Common parts
86
+ self._axinfo.update({
87
+ 'label': {'va': 'center', 'ha': 'center',
88
+ 'rotation_mode': 'anchor'},
89
+ 'color': mpl.rcParams[f'axes3d.{name}axis.panecolor'],
90
+ 'tick': {
91
+ 'inward_factor': 0.2,
92
+ 'outward_factor': 0.1,
93
+ },
94
+ })
95
+
96
+ if mpl.rcParams['_internal.classic_mode']:
97
+ self._axinfo.update({
98
+ 'axisline': {'linewidth': 0.75, 'color': (0, 0, 0, 1)},
99
+ 'grid': {
100
+ 'color': (0.9, 0.9, 0.9, 1),
101
+ 'linewidth': 1.0,
102
+ 'linestyle': '-',
103
+ },
104
+ })
105
+ self._axinfo['tick'].update({
106
+ 'linewidth': {
107
+ True: mpl.rcParams['lines.linewidth'], # major
108
+ False: mpl.rcParams['lines.linewidth'], # minor
109
+ }
110
+ })
111
+ else:
112
+ self._axinfo.update({
113
+ 'axisline': {
114
+ 'linewidth': mpl.rcParams['axes.linewidth'],
115
+ 'color': mpl.rcParams['axes.edgecolor'],
116
+ },
117
+ 'grid': {
118
+ 'color': mpl.rcParams['grid.color'],
119
+ 'linewidth': mpl.rcParams['grid.linewidth'],
120
+ 'linestyle': mpl.rcParams['grid.linestyle'],
121
+ },
122
+ })
123
+ self._axinfo['tick'].update({
124
+ 'linewidth': {
125
+ True: ( # major
126
+ mpl.rcParams['xtick.major.width'] if name in 'xz'
127
+ else mpl.rcParams['ytick.major.width']),
128
+ False: ( # minor
129
+ mpl.rcParams['xtick.minor.width'] if name in 'xz'
130
+ else mpl.rcParams['ytick.minor.width']),
131
+ }
132
+ })
133
+
134
+ super().__init__(axes, *args, **kwargs)
135
+
136
+ # data and viewing intervals for this direction
137
+ if "d_intervalx" in params:
138
+ self.set_data_interval(*params["d_intervalx"])
139
+ if "v_intervalx" in params:
140
+ self.set_view_interval(*params["v_intervalx"])
141
+ self.set_rotate_label(rotate_label)
142
+ self._init3d() # Inline after init3d deprecation elapses.
143
+
144
+ __init__.__signature__ = inspect.signature(_new_init)
145
+ adir = _api.deprecated("3.6", pending=True)(
146
+ property(lambda self: self.axis_name))
147
+
148
+ def _init3d(self):
149
+ self.line = mlines.Line2D(
150
+ xdata=(0, 0), ydata=(0, 0),
151
+ linewidth=self._axinfo['axisline']['linewidth'],
152
+ color=self._axinfo['axisline']['color'],
153
+ antialiased=True)
154
+
155
+ # Store dummy data in Polygon object
156
+ self.pane = mpatches.Polygon([[0, 0], [0, 1]], closed=False)
157
+ self.set_pane_color(self._axinfo['color'])
158
+
159
+ self.axes._set_artist_props(self.line)
160
+ self.axes._set_artist_props(self.pane)
161
+ self.gridlines = art3d.Line3DCollection([])
162
+ self.axes._set_artist_props(self.gridlines)
163
+ self.axes._set_artist_props(self.label)
164
+ self.axes._set_artist_props(self.offsetText)
165
+ # Need to be able to place the label at the correct location
166
+ self.label._transform = self.axes.transData
167
+ self.offsetText._transform = self.axes.transData
168
+
169
+ @_api.deprecated("3.6", pending=True)
170
+ def init3d(self): # After deprecation elapses, inline _init3d to __init__.
171
+ self._init3d()
172
+
173
+ def get_major_ticks(self, numticks=None):
174
+ ticks = super().get_major_ticks(numticks)
175
+ for t in ticks:
176
+ for obj in [
177
+ t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]:
178
+ obj.set_transform(self.axes.transData)
179
+ return ticks
180
+
181
+ def get_minor_ticks(self, numticks=None):
182
+ ticks = super().get_minor_ticks(numticks)
183
+ for t in ticks:
184
+ for obj in [
185
+ t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]:
186
+ obj.set_transform(self.axes.transData)
187
+ return ticks
188
+
189
+ def set_ticks_position(self, position):
190
+ """
191
+ Set the ticks position.
192
+
193
+ Parameters
194
+ ----------
195
+ position : {'lower', 'upper', 'both', 'default', 'none'}
196
+ The position of the bolded axis lines, ticks, and tick labels.
197
+ """
198
+ if position in ['top', 'bottom']:
199
+ _api.warn_deprecated('3.8', name=f'{position=}',
200
+ obj_type='argument value',
201
+ alternative="'upper' or 'lower'")
202
+ return
203
+ _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'],
204
+ position=position)
205
+ self._tick_position = position
206
+
207
+ def get_ticks_position(self):
208
+ """
209
+ Get the ticks position.
210
+
211
+ Returns
212
+ -------
213
+ str : {'lower', 'upper', 'both', 'default', 'none'}
214
+ The position of the bolded axis lines, ticks, and tick labels.
215
+ """
216
+ return self._tick_position
217
+
218
+ def set_label_position(self, position):
219
+ """
220
+ Set the label position.
221
+
222
+ Parameters
223
+ ----------
224
+ position : {'lower', 'upper', 'both', 'default', 'none'}
225
+ The position of the axis label.
226
+ """
227
+ if position in ['top', 'bottom']:
228
+ _api.warn_deprecated('3.8', name=f'{position=}',
229
+ obj_type='argument value',
230
+ alternative="'upper' or 'lower'")
231
+ return
232
+ _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'],
233
+ position=position)
234
+ self._label_position = position
235
+
236
+ def get_label_position(self):
237
+ """
238
+ Get the label position.
239
+
240
+ Returns
241
+ -------
242
+ str : {'lower', 'upper', 'both', 'default', 'none'}
243
+ The position of the axis label.
244
+ """
245
+ return self._label_position
246
+
247
+ def set_pane_color(self, color, alpha=None):
248
+ """
249
+ Set pane color.
250
+
251
+ Parameters
252
+ ----------
253
+ color : :mpltype:`color`
254
+ Color for axis pane.
255
+ alpha : float, optional
256
+ Alpha value for axis pane. If None, base it on *color*.
257
+ """
258
+ color = mcolors.to_rgba(color, alpha)
259
+ self._axinfo['color'] = color
260
+ self.pane.set_edgecolor(color)
261
+ self.pane.set_facecolor(color)
262
+ self.pane.set_alpha(color[-1])
263
+ self.stale = True
264
+
265
+ def set_rotate_label(self, val):
266
+ """
267
+ Whether to rotate the axis label: True, False or None.
268
+ If set to None the label will be rotated if longer than 4 chars.
269
+ """
270
+ self._rotate_label = val
271
+ self.stale = True
272
+
273
+ def get_rotate_label(self, text):
274
+ if self._rotate_label is not None:
275
+ return self._rotate_label
276
+ else:
277
+ return len(text) > 4
278
+
279
+ def _get_coord_info(self):
280
+ mins, maxs = np.array([
281
+ self.axes.get_xbound(),
282
+ self.axes.get_ybound(),
283
+ self.axes.get_zbound(),
284
+ ]).T
285
+
286
+ # Project the bounds along the current position of the cube:
287
+ bounds = mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2]
288
+ bounds_proj = self.axes._transformed_cube(bounds)
289
+
290
+ # Determine which one of the parallel planes are higher up:
291
+ means_z0 = np.zeros(3)
292
+ means_z1 = np.zeros(3)
293
+ for i in range(3):
294
+ means_z0[i] = np.mean(bounds_proj[self._PLANES[2 * i], 2])
295
+ means_z1[i] = np.mean(bounds_proj[self._PLANES[2 * i + 1], 2])
296
+ highs = means_z0 < means_z1
297
+
298
+ # Special handling for edge-on views
299
+ equals = np.abs(means_z0 - means_z1) <= np.finfo(float).eps
300
+ if np.sum(equals) == 2:
301
+ vertical = np.where(~equals)[0][0]
302
+ if vertical == 2: # looking at XY plane
303
+ highs = np.array([True, True, highs[2]])
304
+ elif vertical == 1: # looking at XZ plane
305
+ highs = np.array([True, highs[1], False])
306
+ elif vertical == 0: # looking at YZ plane
307
+ highs = np.array([highs[0], False, False])
308
+
309
+ return mins, maxs, bounds_proj, highs
310
+
311
+ def _calc_centers_deltas(self, maxs, mins):
312
+ centers = 0.5 * (maxs + mins)
313
+ # In mpl3.8, the scale factor was 1/12. mpl3.9 changes this to
314
+ # 1/12 * 24/25 = 0.08 to compensate for the change in automargin
315
+ # behavior and keep appearance the same. The 24/25 factor is from the
316
+ # 1/48 padding added to each side of the axis in mpl3.8.
317
+ scale = 0.08
318
+ deltas = (maxs - mins) * scale
319
+ return centers, deltas
320
+
321
+ def _get_axis_line_edge_points(self, minmax, maxmin, position=None):
322
+ """Get the edge points for the black bolded axis line."""
323
+ # When changing vertical axis some of the axes has to be
324
+ # moved to the other plane so it looks the same as if the z-axis
325
+ # was the vertical axis.
326
+ mb = [minmax, maxmin] # line from origin to nearest corner to camera
327
+ mb_rev = mb[::-1]
328
+ mm = [[mb, mb_rev, mb_rev], [mb_rev, mb_rev, mb], [mb, mb, mb]]
329
+ mm = mm[self.axes._vertical_axis][self._axinfo["i"]]
330
+
331
+ juggled = self._axinfo["juggled"]
332
+ edge_point_0 = mm[0].copy() # origin point
333
+
334
+ if ((position == 'lower' and mm[1][juggled[-1]] < mm[0][juggled[-1]]) or
335
+ (position == 'upper' and mm[1][juggled[-1]] > mm[0][juggled[-1]])):
336
+ edge_point_0[juggled[-1]] = mm[1][juggled[-1]]
337
+ else:
338
+ edge_point_0[juggled[0]] = mm[1][juggled[0]]
339
+
340
+ edge_point_1 = edge_point_0.copy()
341
+ edge_point_1[juggled[1]] = mm[1][juggled[1]]
342
+
343
+ return edge_point_0, edge_point_1
344
+
345
+ def _get_all_axis_line_edge_points(self, minmax, maxmin, axis_position=None):
346
+ # Determine edge points for the axis lines
347
+ edgep1s = []
348
+ edgep2s = []
349
+ position = []
350
+ if axis_position in (None, 'default'):
351
+ edgep1, edgep2 = self._get_axis_line_edge_points(minmax, maxmin)
352
+ edgep1s = [edgep1]
353
+ edgep2s = [edgep2]
354
+ position = ['default']
355
+ else:
356
+ edgep1_l, edgep2_l = self._get_axis_line_edge_points(minmax, maxmin,
357
+ position='lower')
358
+ edgep1_u, edgep2_u = self._get_axis_line_edge_points(minmax, maxmin,
359
+ position='upper')
360
+ if axis_position in ('lower', 'both'):
361
+ edgep1s.append(edgep1_l)
362
+ edgep2s.append(edgep2_l)
363
+ position.append('lower')
364
+ if axis_position in ('upper', 'both'):
365
+ edgep1s.append(edgep1_u)
366
+ edgep2s.append(edgep2_u)
367
+ position.append('upper')
368
+ return edgep1s, edgep2s, position
369
+
370
+ def _get_tickdir(self, position):
371
+ """
372
+ Get the direction of the tick.
373
+
374
+ Parameters
375
+ ----------
376
+ position : str, optional : {'upper', 'lower', 'default'}
377
+ The position of the axis.
378
+
379
+ Returns
380
+ -------
381
+ tickdir : int
382
+ Index which indicates which coordinate the tick line will
383
+ align with.
384
+ """
385
+ _api.check_in_list(('upper', 'lower', 'default'), position=position)
386
+
387
+ # TODO: Move somewhere else where it's triggered less:
388
+ tickdirs_base = [v["tickdir"] for v in self._AXINFO.values()] # default
389
+ elev_mod = np.mod(self.axes.elev + 180, 360) - 180
390
+ azim_mod = np.mod(self.axes.azim, 360)
391
+ if position == 'upper':
392
+ if elev_mod >= 0:
393
+ tickdirs_base = [2, 2, 0]
394
+ else:
395
+ tickdirs_base = [1, 0, 0]
396
+ if 0 <= azim_mod < 180:
397
+ tickdirs_base[2] = 1
398
+ elif position == 'lower':
399
+ if elev_mod >= 0:
400
+ tickdirs_base = [1, 0, 1]
401
+ else:
402
+ tickdirs_base = [2, 2, 1]
403
+ if 0 <= azim_mod < 180:
404
+ tickdirs_base[2] = 0
405
+ info_i = [v["i"] for v in self._AXINFO.values()]
406
+
407
+ i = self._axinfo["i"]
408
+ vert_ax = self.axes._vertical_axis
409
+ j = vert_ax - 2
410
+ # default: tickdir = [[1, 2, 1], [2, 2, 0], [1, 0, 0]][vert_ax][i]
411
+ tickdir = np.roll(info_i, -j)[np.roll(tickdirs_base, j)][i]
412
+ return tickdir
413
+
414
+ def active_pane(self):
415
+ mins, maxs, tc, highs = self._get_coord_info()
416
+ info = self._axinfo
417
+ index = info['i']
418
+ if not highs[index]:
419
+ loc = mins[index]
420
+ plane = self._PLANES[2 * index]
421
+ else:
422
+ loc = maxs[index]
423
+ plane = self._PLANES[2 * index + 1]
424
+ xys = np.array([tc[p] for p in plane])
425
+ return xys, loc
426
+
427
+ def draw_pane(self, renderer):
428
+ """
429
+ Draw pane.
430
+
431
+ Parameters
432
+ ----------
433
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass
434
+ """
435
+ renderer.open_group('pane3d', gid=self.get_gid())
436
+ xys, loc = self.active_pane()
437
+ self.pane.xy = xys[:, :2]
438
+ self.pane.draw(renderer)
439
+ renderer.close_group('pane3d')
440
+
441
+ def _axmask(self):
442
+ axmask = [True, True, True]
443
+ axmask[self._axinfo["i"]] = False
444
+ return axmask
445
+
446
+ def _draw_ticks(self, renderer, edgep1, centers, deltas, highs,
447
+ deltas_per_point, pos):
448
+ ticks = self._update_ticks()
449
+ info = self._axinfo
450
+ index = info["i"]
451
+ juggled = info["juggled"]
452
+
453
+ mins, maxs, tc, highs = self._get_coord_info()
454
+ centers, deltas = self._calc_centers_deltas(maxs, mins)
455
+
456
+ # Draw ticks:
457
+ tickdir = self._get_tickdir(pos)
458
+ tickdelta = deltas[tickdir] if highs[tickdir] else -deltas[tickdir]
459
+
460
+ tick_info = info['tick']
461
+ tick_out = tick_info['outward_factor'] * tickdelta
462
+ tick_in = tick_info['inward_factor'] * tickdelta
463
+ tick_lw = tick_info['linewidth']
464
+ edgep1_tickdir = edgep1[tickdir]
465
+ out_tickdir = edgep1_tickdir + tick_out
466
+ in_tickdir = edgep1_tickdir - tick_in
467
+
468
+ default_label_offset = 8. # A rough estimate
469
+ points = deltas_per_point * deltas
470
+ for tick in ticks:
471
+ # Get tick line positions
472
+ pos = edgep1.copy()
473
+ pos[index] = tick.get_loc()
474
+ pos[tickdir] = out_tickdir
475
+ x1, y1, z1 = proj3d.proj_transform(*pos, self.axes.M)
476
+ pos[tickdir] = in_tickdir
477
+ x2, y2, z2 = proj3d.proj_transform(*pos, self.axes.M)
478
+
479
+ # Get position of label
480
+ labeldeltas = (tick.get_pad() + default_label_offset) * points
481
+
482
+ pos[tickdir] = edgep1_tickdir
483
+ pos = _move_from_center(pos, centers, labeldeltas, self._axmask())
484
+ lx, ly, lz = proj3d.proj_transform(*pos, self.axes.M)
485
+
486
+ _tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly))
487
+ tick.tick1line.set_linewidth(tick_lw[tick._major])
488
+ tick.draw(renderer)
489
+
490
+ def _draw_offset_text(self, renderer, edgep1, edgep2, labeldeltas, centers,
491
+ highs, pep, dx, dy):
492
+ # Get general axis information:
493
+ info = self._axinfo
494
+ index = info["i"]
495
+ juggled = info["juggled"]
496
+ tickdir = info["tickdir"]
497
+
498
+ # Which of the two edge points do we want to
499
+ # use for locating the offset text?
500
+ if juggled[2] == 2:
501
+ outeredgep = edgep1
502
+ outerindex = 0
503
+ else:
504
+ outeredgep = edgep2
505
+ outerindex = 1
506
+
507
+ pos = _move_from_center(outeredgep, centers, labeldeltas,
508
+ self._axmask())
509
+ olx, oly, olz = proj3d.proj_transform(*pos, self.axes.M)
510
+ self.offsetText.set_text(self.major.formatter.get_offset())
511
+ self.offsetText.set_position((olx, oly))
512
+ angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))
513
+ self.offsetText.set_rotation(angle)
514
+ # Must set rotation mode to "anchor" so that
515
+ # the alignment point is used as the "fulcrum" for rotation.
516
+ self.offsetText.set_rotation_mode('anchor')
517
+
518
+ # ----------------------------------------------------------------------
519
+ # Note: the following statement for determining the proper alignment of
520
+ # the offset text. This was determined entirely by trial-and-error
521
+ # and should not be in any way considered as "the way". There are
522
+ # still some edge cases where alignment is not quite right, but this
523
+ # seems to be more of a geometry issue (in other words, I might be
524
+ # using the wrong reference points).
525
+ #
526
+ # (TT, FF, TF, FT) are the shorthand for the tuple of
527
+ # (centpt[tickdir] <= pep[tickdir, outerindex],
528
+ # centpt[index] <= pep[index, outerindex])
529
+ #
530
+ # Three-letters (e.g., TFT, FTT) are short-hand for the array of bools
531
+ # from the variable 'highs'.
532
+ # ---------------------------------------------------------------------
533
+ centpt = proj3d.proj_transform(*centers, self.axes.M)
534
+ if centpt[tickdir] > pep[tickdir, outerindex]:
535
+ # if FT and if highs has an even number of Trues
536
+ if (centpt[index] <= pep[index, outerindex]
537
+ and np.count_nonzero(highs) % 2 == 0):
538
+ # Usually, this means align right, except for the FTT case,
539
+ # in which offset for axis 1 and 2 are aligned left.
540
+ if highs.tolist() == [False, True, True] and index in (1, 2):
541
+ align = 'left'
542
+ else:
543
+ align = 'right'
544
+ else:
545
+ # The FF case
546
+ align = 'left'
547
+ else:
548
+ # if TF and if highs has an even number of Trues
549
+ if (centpt[index] > pep[index, outerindex]
550
+ and np.count_nonzero(highs) % 2 == 0):
551
+ # Usually mean align left, except if it is axis 2
552
+ align = 'right' if index == 2 else 'left'
553
+ else:
554
+ # The TT case
555
+ align = 'right'
556
+
557
+ self.offsetText.set_va('center')
558
+ self.offsetText.set_ha(align)
559
+ self.offsetText.draw(renderer)
560
+
561
+ def _draw_labels(self, renderer, edgep1, edgep2, labeldeltas, centers, dx, dy):
562
+ label = self._axinfo["label"]
563
+
564
+ # Draw labels
565
+ lxyz = 0.5 * (edgep1 + edgep2)
566
+ lxyz = _move_from_center(lxyz, centers, labeldeltas, self._axmask())
567
+ tlx, tly, tlz = proj3d.proj_transform(*lxyz, self.axes.M)
568
+ self.label.set_position((tlx, tly))
569
+ if self.get_rotate_label(self.label.get_text()):
570
+ angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))
571
+ self.label.set_rotation(angle)
572
+ self.label.set_va(label['va'])
573
+ self.label.set_ha(label['ha'])
574
+ self.label.set_rotation_mode(label['rotation_mode'])
575
+ self.label.draw(renderer)
576
+
577
+ @artist.allow_rasterization
578
+ def draw(self, renderer):
579
+ self.label._transform = self.axes.transData
580
+ self.offsetText._transform = self.axes.transData
581
+ renderer.open_group("axis3d", gid=self.get_gid())
582
+
583
+ # Get general axis information:
584
+ mins, maxs, tc, highs = self._get_coord_info()
585
+ centers, deltas = self._calc_centers_deltas(maxs, mins)
586
+
587
+ # Calculate offset distances
588
+ # A rough estimate; points are ambiguous since 3D plots rotate
589
+ reltoinches = self.figure.dpi_scale_trans.inverted()
590
+ ax_inches = reltoinches.transform(self.axes.bbox.size)
591
+ ax_points_estimate = sum(72. * ax_inches)
592
+ deltas_per_point = 48 / ax_points_estimate
593
+ default_offset = 21.
594
+ labeldeltas = (self.labelpad + default_offset) * deltas_per_point * deltas
595
+
596
+ # Determine edge points for the axis lines
597
+ minmax = np.where(highs, maxs, mins) # "origin" point
598
+ maxmin = np.where(~highs, maxs, mins) # "opposite" corner near camera
599
+
600
+ for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points(
601
+ minmax, maxmin, self._tick_position)):
602
+ # Project the edge points along the current position
603
+ pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M)
604
+ pep = np.asarray(pep)
605
+
606
+ # The transAxes transform is used because the Text object
607
+ # rotates the text relative to the display coordinate system.
608
+ # Therefore, if we want the labels to remain parallel to the
609
+ # axis regardless of the aspect ratio, we need to convert the
610
+ # edge points of the plane to display coordinates and calculate
611
+ # an angle from that.
612
+ # TODO: Maybe Text objects should handle this themselves?
613
+ dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) -
614
+ self.axes.transAxes.transform([pep[0:2, 0]]))[0]
615
+
616
+ # Draw the lines
617
+ self.line.set_data(pep[0], pep[1])
618
+ self.line.draw(renderer)
619
+
620
+ # Draw ticks
621
+ self._draw_ticks(renderer, edgep1, centers, deltas, highs,
622
+ deltas_per_point, pos)
623
+
624
+ # Draw Offset text
625
+ self._draw_offset_text(renderer, edgep1, edgep2, labeldeltas,
626
+ centers, highs, pep, dx, dy)
627
+
628
+ for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points(
629
+ minmax, maxmin, self._label_position)):
630
+ # See comments above
631
+ pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M)
632
+ pep = np.asarray(pep)
633
+ dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) -
634
+ self.axes.transAxes.transform([pep[0:2, 0]]))[0]
635
+
636
+ # Draw labels
637
+ self._draw_labels(renderer, edgep1, edgep2, labeldeltas, centers, dx, dy)
638
+
639
+ renderer.close_group('axis3d')
640
+ self.stale = False
641
+
642
+ @artist.allow_rasterization
643
+ def draw_grid(self, renderer):
644
+ if not self.axes._draw_grid:
645
+ return
646
+
647
+ renderer.open_group("grid3d", gid=self.get_gid())
648
+
649
+ ticks = self._update_ticks()
650
+ if len(ticks):
651
+ # Get general axis information:
652
+ info = self._axinfo
653
+ index = info["i"]
654
+
655
+ mins, maxs, tc, highs = self._get_coord_info()
656
+
657
+ minmax = np.where(highs, maxs, mins)
658
+ maxmin = np.where(~highs, maxs, mins)
659
+
660
+ # Grid points where the planes meet
661
+ xyz0 = np.tile(minmax, (len(ticks), 1))
662
+ xyz0[:, index] = [tick.get_loc() for tick in ticks]
663
+
664
+ # Grid lines go from the end of one plane through the plane
665
+ # intersection (at xyz0) to the end of the other plane. The first
666
+ # point (0) differs along dimension index-2 and the last (2) along
667
+ # dimension index-1.
668
+ lines = np.stack([xyz0, xyz0, xyz0], axis=1)
669
+ lines[:, 0, index - 2] = maxmin[index - 2]
670
+ lines[:, 2, index - 1] = maxmin[index - 1]
671
+ self.gridlines.set_segments(lines)
672
+ gridinfo = info['grid']
673
+ self.gridlines.set_color(gridinfo['color'])
674
+ self.gridlines.set_linewidth(gridinfo['linewidth'])
675
+ self.gridlines.set_linestyle(gridinfo['linestyle'])
676
+ self.gridlines.do_3d_projection()
677
+ self.gridlines.draw(renderer)
678
+
679
+ renderer.close_group('grid3d')
680
+
681
+ # TODO: Get this to work (more) properly when mplot3d supports the
682
+ # transforms framework.
683
+ def get_tightbbox(self, renderer=None, *, for_layout_only=False):
684
+ # docstring inherited
685
+ if not self.get_visible():
686
+ return
687
+ # We have to directly access the internal data structures
688
+ # (and hope they are up to date) because at draw time we
689
+ # shift the ticks and their labels around in (x, y) space
690
+ # based on the projection, the current view port, and their
691
+ # position in 3D space. If we extend the transforms framework
692
+ # into 3D we would not need to do this different book keeping
693
+ # than we do in the normal axis
694
+ major_locs = self.get_majorticklocs()
695
+ minor_locs = self.get_minorticklocs()
696
+
697
+ ticks = [*self.get_minor_ticks(len(minor_locs)),
698
+ *self.get_major_ticks(len(major_locs))]
699
+ view_low, view_high = self.get_view_interval()
700
+ if view_low > view_high:
701
+ view_low, view_high = view_high, view_low
702
+ interval_t = self.get_transform().transform([view_low, view_high])
703
+
704
+ ticks_to_draw = []
705
+ for tick in ticks:
706
+ try:
707
+ loc_t = self.get_transform().transform(tick.get_loc())
708
+ except AssertionError:
709
+ # Transform.transform doesn't allow masked values but
710
+ # some scales might make them, so we need this try/except.
711
+ pass
712
+ else:
713
+ if mtransforms._interval_contains_close(interval_t, loc_t):
714
+ ticks_to_draw.append(tick)
715
+
716
+ ticks = ticks_to_draw
717
+
718
+ bb_1, bb_2 = self._get_ticklabel_bboxes(ticks, renderer)
719
+ other = []
720
+
721
+ if self.line.get_visible():
722
+ other.append(self.line.get_window_extent(renderer))
723
+ if (self.label.get_visible() and not for_layout_only and
724
+ self.label.get_text()):
725
+ other.append(self.label.get_window_extent(renderer))
726
+
727
+ return mtransforms.Bbox.union([*bb_1, *bb_2, *other])
728
+
729
+ d_interval = _api.deprecated(
730
+ "3.6", alternative="get_data_interval", pending=True)(
731
+ property(lambda self: self.get_data_interval(),
732
+ lambda self, minmax: self.set_data_interval(*minmax)))
733
+ v_interval = _api.deprecated(
734
+ "3.6", alternative="get_view_interval", pending=True)(
735
+ property(lambda self: self.get_view_interval(),
736
+ lambda self, minmax: self.set_view_interval(*minmax)))
737
+
738
+
739
+ class XAxis(Axis):
740
+ axis_name = "x"
741
+ get_view_interval, set_view_interval = maxis._make_getset_interval(
742
+ "view", "xy_viewLim", "intervalx")
743
+ get_data_interval, set_data_interval = maxis._make_getset_interval(
744
+ "data", "xy_dataLim", "intervalx")
745
+
746
+
747
+ class YAxis(Axis):
748
+ axis_name = "y"
749
+ get_view_interval, set_view_interval = maxis._make_getset_interval(
750
+ "view", "xy_viewLim", "intervaly")
751
+ get_data_interval, set_data_interval = maxis._make_getset_interval(
752
+ "data", "xy_dataLim", "intervaly")
753
+
754
+
755
+ class ZAxis(Axis):
756
+ axis_name = "z"
757
+ get_view_interval, set_view_interval = maxis._make_getset_interval(
758
+ "view", "zz_viewLim", "intervalx")
759
+ get_data_interval, set_data_interval = maxis._make_getset_interval(
760
+ "data", "zz_dataLim", "intervalx")