ZTWHHH commited on
Commit
2b816c7
·
verified ·
1 Parent(s): f5aaa3d

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_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/INSTALLER +1 -0
  2. evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/LICENSE +27 -0
  3. evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/METADATA +233 -0
  4. evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/RECORD +181 -0
  5. evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/REQUESTED +0 -0
  6. evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/WHEEL +5 -0
  7. evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/top_level.txt +1 -0
  8. evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/INSTALLER +1 -0
  9. evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/METADATA +248 -0
  10. evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/RECORD +229 -0
  11. evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/REQUESTED +0 -0
  12. evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/WHEEL +4 -0
  13. evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/licenses/LICENSE.md +21 -0
  14. evalkit_eagle/lib/python3.10/site-packages/ninja/__init__.py +60 -0
  15. evalkit_eagle/lib/python3.10/site-packages/ninja/__main__.py +6 -0
  16. evalkit_eagle/lib/python3.10/site-packages/ninja/__pycache__/__init__.cpython-310.pyc +0 -0
  17. evalkit_eagle/lib/python3.10/site-packages/ninja/__pycache__/__main__.cpython-310.pyc +0 -0
  18. evalkit_eagle/lib/python3.10/site-packages/ninja/__pycache__/_version.cpython-310.pyc +0 -0
  19. evalkit_eagle/lib/python3.10/site-packages/ninja/__pycache__/ninja_syntax.cpython-310.pyc +0 -0
  20. evalkit_eagle/lib/python3.10/site-packages/ninja/_version.py +1 -0
  21. evalkit_eagle/lib/python3.10/site-packages/ninja/_version.pyi +4 -0
  22. evalkit_eagle/lib/python3.10/site-packages/ninja/ninja_syntax.py +199 -0
  23. evalkit_eagle/lib/python3.10/site-packages/ninja/ninja_syntax.pyi +37 -0
  24. evalkit_eagle/lib/python3.10/site-packages/ninja/py.typed +0 -0
  25. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/__init__.py +98 -0
  26. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/__pycache__/__init__.cpython-310.pyc +0 -0
  27. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/__pycache__/_core.cpython-310.pyc +0 -0
  28. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/__pycache__/_misc.cpython-310.pyc +0 -0
  29. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_core.py +1946 -0
  30. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__init__.py +93 -0
  31. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/__init__.cpython-310.pyc +0 -0
  32. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/boxplot.cpython-310.pyc +0 -0
  33. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/converter.cpython-310.pyc +0 -0
  34. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/core.cpython-310.pyc +0 -0
  35. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/groupby.cpython-310.pyc +0 -0
  36. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/hist.cpython-310.pyc +0 -0
  37. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/misc.cpython-310.pyc +0 -0
  38. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/style.cpython-310.pyc +0 -0
  39. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/timeseries.cpython-310.pyc +0 -0
  40. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/tools.cpython-310.pyc +0 -0
  41. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/boxplot.py +572 -0
  42. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/converter.py +1139 -0
  43. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py +2125 -0
  44. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/groupby.py +142 -0
  45. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/hist.py +581 -0
  46. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/misc.py +481 -0
  47. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/style.py +278 -0
  48. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/timeseries.py +370 -0
  49. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/tools.py +492 -0
  50. evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_misc.py +688 -0
evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/LICENSE ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2005-2021 Fredrik Johansson and mpmath contributors
2
+
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ a. Redistributions of source code must retain the above copyright notice,
9
+ this list of conditions and the following disclaimer.
10
+ b. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+ c. Neither the name of the copyright holder nor the names of its
14
+ contributors may be used to endorse or promote products derived
15
+ from this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20
+ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
21
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26
+ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
27
+ DAMAGE.
evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/METADATA ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: mpmath
3
+ Version: 1.3.0
4
+ Summary: Python library for arbitrary-precision floating-point arithmetic
5
+ Home-page: http://mpmath.org/
6
+ Author: Fredrik Johansson
7
+ Author-email: fredrik.johansson@gmail.com
8
+ License: BSD
9
+ Project-URL: Source, https://github.com/fredrik-johansson/mpmath
10
+ Project-URL: Tracker, https://github.com/fredrik-johansson/mpmath/issues
11
+ Project-URL: Documentation, http://mpmath.org/doc/current/
12
+ Classifier: License :: OSI Approved :: BSD License
13
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 2
17
+ Classifier: Programming Language :: Python :: 2.7
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.5
20
+ Classifier: Programming Language :: Python :: 3.6
21
+ Classifier: Programming Language :: Python :: 3.7
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: Implementation :: CPython
25
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
26
+ License-File: LICENSE
27
+ Provides-Extra: develop
28
+ Requires-Dist: pytest (>=4.6) ; extra == 'develop'
29
+ Requires-Dist: pycodestyle ; extra == 'develop'
30
+ Requires-Dist: pytest-cov ; extra == 'develop'
31
+ Requires-Dist: codecov ; extra == 'develop'
32
+ Requires-Dist: wheel ; extra == 'develop'
33
+ Provides-Extra: docs
34
+ Requires-Dist: sphinx ; extra == 'docs'
35
+ Provides-Extra: gmpy
36
+ Requires-Dist: gmpy2 (>=2.1.0a4) ; (platform_python_implementation != "PyPy") and extra == 'gmpy'
37
+ Provides-Extra: tests
38
+ Requires-Dist: pytest (>=4.6) ; extra == 'tests'
39
+
40
+ mpmath
41
+ ======
42
+
43
+ |pypi version| |Build status| |Code coverage status| |Zenodo Badge|
44
+
45
+ .. |pypi version| image:: https://img.shields.io/pypi/v/mpmath.svg
46
+ :target: https://pypi.python.org/pypi/mpmath
47
+ .. |Build status| image:: https://github.com/fredrik-johansson/mpmath/workflows/test/badge.svg
48
+ :target: https://github.com/fredrik-johansson/mpmath/actions?workflow=test
49
+ .. |Code coverage status| image:: https://codecov.io/gh/fredrik-johansson/mpmath/branch/master/graph/badge.svg
50
+ :target: https://codecov.io/gh/fredrik-johansson/mpmath
51
+ .. |Zenodo Badge| image:: https://zenodo.org/badge/2934512.svg
52
+ :target: https://zenodo.org/badge/latestdoi/2934512
53
+
54
+ A Python library for arbitrary-precision floating-point arithmetic.
55
+
56
+ Website: http://mpmath.org/
57
+ Main author: Fredrik Johansson <fredrik.johansson@gmail.com>
58
+
59
+ Mpmath is free software released under the New BSD License (see the
60
+ LICENSE file for details)
61
+
62
+ 0. History and credits
63
+ ----------------------
64
+
65
+ The following people (among others) have contributed major patches
66
+ or new features to mpmath:
67
+
68
+ * Pearu Peterson <pearu.peterson@gmail.com>
69
+ * Mario Pernici <mario.pernici@mi.infn.it>
70
+ * Ondrej Certik <ondrej@certik.cz>
71
+ * Vinzent Steinberg <vinzent.steinberg@gmail.cm>
72
+ * Nimish Telang <ntelang@gmail.com>
73
+ * Mike Taschuk <mtaschuk@ece.ualberta.ca>
74
+ * Case Van Horsen <casevh@gmail.com>
75
+ * Jorn Baayen <jorn.baayen@gmail.com>
76
+ * Chris Smith <smichr@gmail.com>
77
+ * Juan Arias de Reyna <arias@us.es>
78
+ * Ioannis Tziakos <itziakos@gmail.com>
79
+ * Aaron Meurer <asmeurer@gmail.com>
80
+ * Stefan Krastanov <krastanov.stefan@gmail.com>
81
+ * Ken Allen <ken.allen@sbcglobal.net>
82
+ * Timo Hartmann <thartmann15@gmail.com>
83
+ * Sergey B Kirpichev <skirpichev@gmail.com>
84
+ * Kris Kuhlman <kristopher.kuhlman@gmail.com>
85
+ * Paul Masson <paulmasson@analyticphysics.com>
86
+ * Michael Kagalenko <michael.kagalenko@gmail.com>
87
+ * Jonathan Warner <warnerjon12@gmail.com>
88
+ * Max Gaukler <max.gaukler@fau.de>
89
+ * Guillermo Navas-Palencia <g.navas.palencia@gmail.com>
90
+ * Nike Dattani <nike@hpqc.org>
91
+
92
+ Numerous other people have contributed by reporting bugs,
93
+ requesting new features, or suggesting improvements to the
94
+ documentation.
95
+
96
+ For a detailed changelog, including individual contributions,
97
+ see the CHANGES file.
98
+
99
+ Fredrik's work on mpmath during summer 2008 was sponsored by Google
100
+ as part of the Google Summer of Code program.
101
+
102
+ Fredrik's work on mpmath during summer 2009 was sponsored by the
103
+ American Institute of Mathematics under the support of the National Science
104
+ Foundation Grant No. 0757627 (FRG: L-functions and Modular Forms).
105
+
106
+ Any opinions, findings, and conclusions or recommendations expressed in this
107
+ material are those of the author(s) and do not necessarily reflect the
108
+ views of the sponsors.
109
+
110
+ Credit also goes to:
111
+
112
+ * The authors of the GMP library and the Python wrapper
113
+ gmpy, enabling mpmath to become much faster at
114
+ high precision
115
+ * The authors of MPFR, pari/gp, MPFUN, and other arbitrary-
116
+ precision libraries, whose documentation has been helpful
117
+ for implementing many of the algorithms in mpmath
118
+ * Wikipedia contributors; Abramowitz & Stegun; Gradshteyn & Ryzhik;
119
+ Wolfram Research for MathWorld and the Wolfram Functions site.
120
+ These are the main references used for special functions
121
+ implementations.
122
+ * George Brandl for developing the Sphinx documentation tool
123
+ used to build mpmath's documentation
124
+
125
+ Release history:
126
+
127
+ * Version 1.3.0 released on March 7, 2023
128
+ * Version 1.2.0 released on February 1, 2021
129
+ * Version 1.1.0 released on December 11, 2018
130
+ * Version 1.0.0 released on September 27, 2017
131
+ * Version 0.19 released on June 10, 2014
132
+ * Version 0.18 released on December 31, 2013
133
+ * Version 0.17 released on February 1, 2011
134
+ * Version 0.16 released on September 24, 2010
135
+ * Version 0.15 released on June 6, 2010
136
+ * Version 0.14 released on February 5, 2010
137
+ * Version 0.13 released on August 13, 2009
138
+ * Version 0.12 released on June 9, 2009
139
+ * Version 0.11 released on January 26, 2009
140
+ * Version 0.10 released on October 15, 2008
141
+ * Version 0.9 released on August 23, 2008
142
+ * Version 0.8 released on April 20, 2008
143
+ * Version 0.7 released on March 12, 2008
144
+ * Version 0.6 released on January 13, 2008
145
+ * Version 0.5 released on November 24, 2007
146
+ * Version 0.4 released on November 3, 2007
147
+ * Version 0.3 released on October 5, 2007
148
+ * Version 0.2 released on October 2, 2007
149
+ * Version 0.1 released on September 27, 2007
150
+
151
+ 1. Download & installation
152
+ --------------------------
153
+
154
+ Mpmath requires Python 2.7 or 3.5 (or later versions). It has been tested
155
+ with CPython 2.7, 3.5 through 3.7 and for PyPy.
156
+
157
+ The latest release of mpmath can be downloaded from the mpmath
158
+ website and from https://github.com/fredrik-johansson/mpmath/releases
159
+
160
+ It should also be available in the Python Package Index at
161
+ https://pypi.python.org/pypi/mpmath
162
+
163
+ To install latest release of Mpmath with pip, simply run
164
+
165
+ ``pip install mpmath``
166
+
167
+ Or unpack the mpmath archive and run
168
+
169
+ ``python setup.py install``
170
+
171
+ Mpmath can also be installed using
172
+
173
+ ``python -m easy_install mpmath``
174
+
175
+ The latest development code is available from
176
+ https://github.com/fredrik-johansson/mpmath
177
+
178
+ See the main documentation for more detailed instructions.
179
+
180
+ 2. Running tests
181
+ ----------------
182
+
183
+ The unit tests in mpmath/tests/ can be run via the script
184
+ runtests.py, but it is recommended to run them with py.test
185
+ (https://pytest.org/), especially
186
+ to generate more useful reports in case there are failures.
187
+
188
+ You may also want to check out the demo scripts in the demo
189
+ directory.
190
+
191
+ The master branch is automatically tested by Travis CI.
192
+
193
+ 3. Documentation
194
+ ----------------
195
+
196
+ Documentation in reStructuredText format is available in the
197
+ doc directory included with the source package. These files
198
+ are human-readable, but can be compiled to prettier HTML using
199
+ the build.py script (requires Sphinx, http://sphinx.pocoo.org/).
200
+
201
+ See setup.txt in the documentation for more information.
202
+
203
+ The most recent documentation is also available in HTML format:
204
+
205
+ http://mpmath.org/doc/current/
206
+
207
+ 4. Known problems
208
+ -----------------
209
+
210
+ Mpmath is a work in progress. Major issues include:
211
+
212
+ * Some functions may return incorrect values when given extremely
213
+ large arguments or arguments very close to singularities.
214
+
215
+ * Directed rounding works for arithmetic operations. It is implemented
216
+ heuristically for other operations, and their results may be off by one
217
+ or two units in the last place (even if otherwise accurate).
218
+
219
+ * Some IEEE 754 features are not available. Inifinities and NaN are
220
+ partially supported; denormal rounding is currently not available
221
+ at all.
222
+
223
+ * The interface for switching precision and rounding is not finalized.
224
+ The current method is not threadsafe.
225
+
226
+ 5. Help and bug reports
227
+ -----------------------
228
+
229
+ General questions and comments can be sent to the mpmath mailinglist,
230
+ mpmath@googlegroups.com
231
+
232
+ You can also report bugs and send patches to the mpmath issue tracker,
233
+ https://github.com/fredrik-johansson/mpmath/issues
evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/RECORD ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mpmath-1.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ mpmath-1.3.0.dist-info/LICENSE,sha256=wmyugdpFCOXiSZhXd6M4IfGDIj67dNf4z7-Q_n7vL7c,1537
3
+ mpmath-1.3.0.dist-info/METADATA,sha256=RLZupES5wNGa6UgV01a_BHrmtoDBkmi1wmVofNaoFAY,8630
4
+ mpmath-1.3.0.dist-info/RECORD,,
5
+ mpmath-1.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ mpmath-1.3.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
7
+ mpmath-1.3.0.dist-info/top_level.txt,sha256=BUVWrh8EVlkOhM1n3X9S8msTaVcC-3s6Sjt60avHYus,7
8
+ mpmath/__init__.py,sha256=skFYTSwfwDBLChAV6pI3SdewgAQR3UBtyrfIK_Jdn-g,8765
9
+ mpmath/__pycache__/__init__.cpython-310.pyc,,
10
+ mpmath/__pycache__/ctx_base.cpython-310.pyc,,
11
+ mpmath/__pycache__/ctx_fp.cpython-310.pyc,,
12
+ mpmath/__pycache__/ctx_iv.cpython-310.pyc,,
13
+ mpmath/__pycache__/ctx_mp.cpython-310.pyc,,
14
+ mpmath/__pycache__/ctx_mp_python.cpython-310.pyc,,
15
+ mpmath/__pycache__/function_docs.cpython-310.pyc,,
16
+ mpmath/__pycache__/identification.cpython-310.pyc,,
17
+ mpmath/__pycache__/math2.cpython-310.pyc,,
18
+ mpmath/__pycache__/rational.cpython-310.pyc,,
19
+ mpmath/__pycache__/usertools.cpython-310.pyc,,
20
+ mpmath/__pycache__/visualization.cpython-310.pyc,,
21
+ mpmath/calculus/__init__.py,sha256=UAgCIJ1YmaeyTqpNzjBlCZGeIzLtUZMEEpl99VWNjus,162
22
+ mpmath/calculus/__pycache__/__init__.cpython-310.pyc,,
23
+ mpmath/calculus/__pycache__/approximation.cpython-310.pyc,,
24
+ mpmath/calculus/__pycache__/calculus.cpython-310.pyc,,
25
+ mpmath/calculus/__pycache__/differentiation.cpython-310.pyc,,
26
+ mpmath/calculus/__pycache__/extrapolation.cpython-310.pyc,,
27
+ mpmath/calculus/__pycache__/inverselaplace.cpython-310.pyc,,
28
+ mpmath/calculus/__pycache__/odes.cpython-310.pyc,,
29
+ mpmath/calculus/__pycache__/optimization.cpython-310.pyc,,
30
+ mpmath/calculus/__pycache__/polynomials.cpython-310.pyc,,
31
+ mpmath/calculus/__pycache__/quadrature.cpython-310.pyc,,
32
+ mpmath/calculus/approximation.py,sha256=vyzu3YI6r63Oq1KFHrQz02mGXAcH23emqNYhJuUaFZ4,8817
33
+ mpmath/calculus/calculus.py,sha256=A0gSp0hxSyEDfugJViY3CeWalF-vK701YftzrjSQzQ4,112
34
+ mpmath/calculus/differentiation.py,sha256=2L6CBj8xtX9iip98NPbKsLtwtRjxi571wYmTMHFeL90,20226
35
+ mpmath/calculus/extrapolation.py,sha256=xM0rvk2DFEF4iR1Jhl-Y3aS93iW9VVJX7y9IGpmzC-A,73306
36
+ mpmath/calculus/inverselaplace.py,sha256=5-pn8N_t0PtgBTXixsXZ4xxrihK2J5gYsVfTKfDx4gA,36056
37
+ mpmath/calculus/odes.py,sha256=gaHiw7IJjsONNTAa6izFPZpmcg9uyTp8MULnGdzTIGo,9908
38
+ mpmath/calculus/optimization.py,sha256=bKnShXElBOmVOIOlFeksDsYCp9fYSmYwKmXDt0z26MM,32856
39
+ mpmath/calculus/polynomials.py,sha256=D16BhU_SHbVi06IxNwABHR-H77IylndNsN3muPTuFYs,7877
40
+ mpmath/calculus/quadrature.py,sha256=n-avtS8E43foV-5tr5lofgOBaiMUYE8AJjQcWI9QcKk,42432
41
+ mpmath/ctx_base.py,sha256=rfjmfMyA55x8R_cWFINUwWVTElfZmyx5erKDdauSEVw,15985
42
+ mpmath/ctx_fp.py,sha256=ctUjx_NoU0iFWk05cXDYCL2ZtLZOlWs1n6Zao3pbG2g,6572
43
+ mpmath/ctx_iv.py,sha256=tqdMr-GDfkZk1EhoGeCAajy7pQv-RWtrVqhYjfI8r4g,17211
44
+ mpmath/ctx_mp.py,sha256=d3r4t7xHNqSFtmqsA9Btq1Npy3WTM-pcM2_jeCyECxY,49452
45
+ mpmath/ctx_mp_python.py,sha256=3olYWo4lk1SnQ0A_IaZ181qqG8u5pxGat_v-L4Qtn3Y,37815
46
+ mpmath/function_docs.py,sha256=g4PP8n6ILXmHcLyA50sxK6Tmp_Z4_pRN-wDErU8D1i4,283512
47
+ mpmath/functions/__init__.py,sha256=YXVdhqv-6LKm6cr5xxtTNTtuD9zDPKGQl8GmS0xz2xo,330
48
+ mpmath/functions/__pycache__/__init__.cpython-310.pyc,,
49
+ mpmath/functions/__pycache__/bessel.cpython-310.pyc,,
50
+ mpmath/functions/__pycache__/elliptic.cpython-310.pyc,,
51
+ mpmath/functions/__pycache__/expintegrals.cpython-310.pyc,,
52
+ mpmath/functions/__pycache__/factorials.cpython-310.pyc,,
53
+ mpmath/functions/__pycache__/functions.cpython-310.pyc,,
54
+ mpmath/functions/__pycache__/hypergeometric.cpython-310.pyc,,
55
+ mpmath/functions/__pycache__/orthogonal.cpython-310.pyc,,
56
+ mpmath/functions/__pycache__/qfunctions.cpython-310.pyc,,
57
+ mpmath/functions/__pycache__/rszeta.cpython-310.pyc,,
58
+ mpmath/functions/__pycache__/signals.cpython-310.pyc,,
59
+ mpmath/functions/__pycache__/theta.cpython-310.pyc,,
60
+ mpmath/functions/__pycache__/zeta.cpython-310.pyc,,
61
+ mpmath/functions/__pycache__/zetazeros.cpython-310.pyc,,
62
+ mpmath/functions/bessel.py,sha256=dUPLu8frlK-vmf3-irX_7uvwyw4xccv6EIizmIZ88kM,37938
63
+ mpmath/functions/elliptic.py,sha256=qz0yVMb4lWEeOTDL_DWz5u5awmGIPKAsuZFJXgwHJNU,42237
64
+ mpmath/functions/expintegrals.py,sha256=75X_MRdYc1F_X73bgNiOJqwRlS2hqAzcFLl3RM2tCDc,11644
65
+ mpmath/functions/factorials.py,sha256=8_6kCR7e4k1GwxiAOJu0NRadeF4jA28qx4hidhu4ILk,5273
66
+ mpmath/functions/functions.py,sha256=ub2JExvqzCWLkm5yAm72Fr6fdWmZZUknq9_3w9MEigI,18100
67
+ mpmath/functions/hypergeometric.py,sha256=Z0OMAMC4ylK42n_SnamyFVnUx6zHLyCLCoJDSZ1JrHY,51570
68
+ mpmath/functions/orthogonal.py,sha256=FabkxKfBoSseA5flWu1a3re-2BYaew9augqIsT8LaLw,16097
69
+ mpmath/functions/qfunctions.py,sha256=a3EHGKQt_jMd4x9I772Jz-TGFnGY-arWqPvZGz9QSe0,7633
70
+ mpmath/functions/rszeta.py,sha256=yuUVp4ilIyDmXyE3WTBxDDjwfEJNypJnbPS-xPH5How,46184
71
+ mpmath/functions/signals.py,sha256=ELotwQaW1CDpv-eeJzOZ5c23NhfaZcj9_Gkb3psvS0Q,703
72
+ mpmath/functions/theta.py,sha256=KggOocczoMG6_HMoal4oEP7iZ4SKOou9JFE-WzY2r3M,37320
73
+ mpmath/functions/zeta.py,sha256=ue7JY7GXA0oX8q08sQJl2CSRrZ7kOt8HsftpVjnTwrE,36410
74
+ mpmath/functions/zetazeros.py,sha256=uq6TVyZBcY2MLX7VSdVfn0TOkowBLM9fXtnySEwaNzw,30858
75
+ mpmath/identification.py,sha256=7aMdngRAaeL_MafDUNbmEIlGQSklHDZ8pmPFt-OLgkw,29253
76
+ mpmath/libmp/__init__.py,sha256=UCDjLZw4brbklaCmSixCcPdLdHkz8sF_-6F_wr0duAg,3790
77
+ mpmath/libmp/__pycache__/__init__.cpython-310.pyc,,
78
+ mpmath/libmp/__pycache__/backend.cpython-310.pyc,,
79
+ mpmath/libmp/__pycache__/gammazeta.cpython-310.pyc,,
80
+ mpmath/libmp/__pycache__/libelefun.cpython-310.pyc,,
81
+ mpmath/libmp/__pycache__/libhyper.cpython-310.pyc,,
82
+ mpmath/libmp/__pycache__/libintmath.cpython-310.pyc,,
83
+ mpmath/libmp/__pycache__/libmpc.cpython-310.pyc,,
84
+ mpmath/libmp/__pycache__/libmpf.cpython-310.pyc,,
85
+ mpmath/libmp/__pycache__/libmpi.cpython-310.pyc,,
86
+ mpmath/libmp/backend.py,sha256=26A8pUkaGov26vrrFNQVyWJ5LDtK8sl3UHrYLecaTjA,3360
87
+ mpmath/libmp/gammazeta.py,sha256=Xqdw6PMoswDaSca_sOs-IglRuk3fb8c9p43M_lbcrlc,71469
88
+ mpmath/libmp/libelefun.py,sha256=joBZP4FOdxPfieWso1LPtSr6dHydpG_LQiF_bYQYWMg,43861
89
+ mpmath/libmp/libhyper.py,sha256=J9fmdDF6u27EcssEWvBuVaAa3hFjPvPN1SgRgu1dEbc,36624
90
+ mpmath/libmp/libintmath.py,sha256=aIRT0rkUZ_sdGQf3TNCLd-pBMvtQWjssbvFLfK7U0jc,16688
91
+ mpmath/libmp/libmpc.py,sha256=KBndUjs5YVS32-Id3fflDfYgpdW1Prx6zfo8Ez5Qbrs,26875
92
+ mpmath/libmp/libmpf.py,sha256=vpP0kNVkScbCVoZogJ4Watl4I7Ce0d4dzHVjfVe57so,45021
93
+ mpmath/libmp/libmpi.py,sha256=u0I5Eiwkqa-4-dXETi5k7MuaxBeZbvCAPFtl93U9YF0,27622
94
+ mpmath/math2.py,sha256=O5Dglg81SsW0wfHDUJcXOD8-cCaLvbVIvyw0sVmRbpI,18561
95
+ mpmath/matrices/__init__.py,sha256=ETzGDciYbq9ftiKwaMbJ15EI-KNXHrzRb-ZHehhqFjs,94
96
+ mpmath/matrices/__pycache__/__init__.cpython-310.pyc,,
97
+ mpmath/matrices/__pycache__/calculus.cpython-310.pyc,,
98
+ mpmath/matrices/__pycache__/eigen.cpython-310.pyc,,
99
+ mpmath/matrices/__pycache__/eigen_symmetric.cpython-310.pyc,,
100
+ mpmath/matrices/__pycache__/linalg.cpython-310.pyc,,
101
+ mpmath/matrices/__pycache__/matrices.cpython-310.pyc,,
102
+ mpmath/matrices/calculus.py,sha256=PNRq-p2nxgT-fzC54K2depi8ddhdx6Q86G8qpUiHeUY,18609
103
+ mpmath/matrices/eigen.py,sha256=GbDXI3CixzEdXxr1G86uUWkAngAvd-05MmSQ-Tsu_5k,24394
104
+ mpmath/matrices/eigen_symmetric.py,sha256=FPKPeQr1cGYw6Y6ea32a1YdEWQDLP6JlQHEA2WfNLYg,58534
105
+ mpmath/matrices/linalg.py,sha256=04C3ijzMFom7ob5fXBCDfyPPdo3BIboIeE8x2A6vqF0,26958
106
+ mpmath/matrices/matrices.py,sha256=o78Eq62EHQnxcsR0LBoWDEGREOoN4L2iDM1q3dQrw0o,32331
107
+ mpmath/rational.py,sha256=64d56fvZXngYZT7nOAHeFRUX77eJ1A0R3rpfWBU-mSo,5976
108
+ mpmath/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
109
+ mpmath/tests/__pycache__/__init__.cpython-310.pyc,,
110
+ mpmath/tests/__pycache__/extratest_gamma.cpython-310.pyc,,
111
+ mpmath/tests/__pycache__/extratest_zeta.cpython-310.pyc,,
112
+ mpmath/tests/__pycache__/runtests.cpython-310.pyc,,
113
+ mpmath/tests/__pycache__/test_basic_ops.cpython-310.pyc,,
114
+ mpmath/tests/__pycache__/test_bitwise.cpython-310.pyc,,
115
+ mpmath/tests/__pycache__/test_calculus.cpython-310.pyc,,
116
+ mpmath/tests/__pycache__/test_compatibility.cpython-310.pyc,,
117
+ mpmath/tests/__pycache__/test_convert.cpython-310.pyc,,
118
+ mpmath/tests/__pycache__/test_diff.cpython-310.pyc,,
119
+ mpmath/tests/__pycache__/test_division.cpython-310.pyc,,
120
+ mpmath/tests/__pycache__/test_eigen.cpython-310.pyc,,
121
+ mpmath/tests/__pycache__/test_eigen_symmetric.cpython-310.pyc,,
122
+ mpmath/tests/__pycache__/test_elliptic.cpython-310.pyc,,
123
+ mpmath/tests/__pycache__/test_fp.cpython-310.pyc,,
124
+ mpmath/tests/__pycache__/test_functions.cpython-310.pyc,,
125
+ mpmath/tests/__pycache__/test_functions2.cpython-310.pyc,,
126
+ mpmath/tests/__pycache__/test_gammazeta.cpython-310.pyc,,
127
+ mpmath/tests/__pycache__/test_hp.cpython-310.pyc,,
128
+ mpmath/tests/__pycache__/test_identify.cpython-310.pyc,,
129
+ mpmath/tests/__pycache__/test_interval.cpython-310.pyc,,
130
+ mpmath/tests/__pycache__/test_levin.cpython-310.pyc,,
131
+ mpmath/tests/__pycache__/test_linalg.cpython-310.pyc,,
132
+ mpmath/tests/__pycache__/test_matrices.cpython-310.pyc,,
133
+ mpmath/tests/__pycache__/test_mpmath.cpython-310.pyc,,
134
+ mpmath/tests/__pycache__/test_ode.cpython-310.pyc,,
135
+ mpmath/tests/__pycache__/test_pickle.cpython-310.pyc,,
136
+ mpmath/tests/__pycache__/test_power.cpython-310.pyc,,
137
+ mpmath/tests/__pycache__/test_quad.cpython-310.pyc,,
138
+ mpmath/tests/__pycache__/test_rootfinding.cpython-310.pyc,,
139
+ mpmath/tests/__pycache__/test_special.cpython-310.pyc,,
140
+ mpmath/tests/__pycache__/test_str.cpython-310.pyc,,
141
+ mpmath/tests/__pycache__/test_summation.cpython-310.pyc,,
142
+ mpmath/tests/__pycache__/test_trig.cpython-310.pyc,,
143
+ mpmath/tests/__pycache__/test_visualization.cpython-310.pyc,,
144
+ mpmath/tests/__pycache__/torture.cpython-310.pyc,,
145
+ mpmath/tests/extratest_gamma.py,sha256=xidhXUelILcxtiPGoTBHjqUOKIJzEaZ_v3nntGQyWZQ,7228
146
+ mpmath/tests/extratest_zeta.py,sha256=sg10j9RhjBpV2EdUqyYhGV2ERWvM--EvwwGIz6HTmlw,1003
147
+ mpmath/tests/runtests.py,sha256=7NUV82F3K_5AhU8mCLUFf5OibtT7uloFCwPyM3l71wM,5189
148
+ mpmath/tests/test_basic_ops.py,sha256=dsB8DRG-GrPzBaZ-bIauYabaeqXbfqBo9SIP9BqcTSs,15348
149
+ mpmath/tests/test_bitwise.py,sha256=-nLYhgQbhDza3SQM63BhktYntACagqMYx9ib3dPnTKM,7686
150
+ mpmath/tests/test_calculus.py,sha256=4oxtNfMpO4RLLoOzrv7r9-h8BcqfBsJIE6UpsHe7c4w,9187
151
+ mpmath/tests/test_compatibility.py,sha256=_t3ASZ3jhfAMnN1voWX7PDNIDzn-3PokkJGIdT1x7y0,2306
152
+ mpmath/tests/test_convert.py,sha256=JPcDcTJIWh5prIxjx5DM1aNWgqlUoF2KpHvAgK3uHi4,8834
153
+ mpmath/tests/test_diff.py,sha256=qjiF8NxQ8vueuZ5ZHGPQ-kjcj_I7Jh_fEdFtaA8DzEI,2466
154
+ mpmath/tests/test_division.py,sha256=6lUeZfmaBWvvszdqlWLMHgXPjVsxvW1WZpd4-jFWCpU,5340
155
+ mpmath/tests/test_eigen.py,sha256=2mnqVATGbsJkvSVHPpitfAk881twFfb3LsO3XikV9Hs,3905
156
+ mpmath/tests/test_eigen_symmetric.py,sha256=v0VimCicIU2owASDMBaP-t-30uq-pXcsglt95KBtNO4,8778
157
+ mpmath/tests/test_elliptic.py,sha256=Kjiwq9Bb6N_OOzzWewGQ1M_PMa7vRs42V0t90gloZxo,26225
158
+ mpmath/tests/test_fp.py,sha256=AJo0FTyH4BuUnUsv176LD956om308KGYndy-b54KGxM,89997
159
+ mpmath/tests/test_functions.py,sha256=b47VywdomoOX6KmMmz9-iv2IqVIydwKSuUw2pWlFHrY,30955
160
+ mpmath/tests/test_functions2.py,sha256=vlw2RWhL1oTcifnOMDx1a_YzN96UgNNIE5STeKRv1HY,96990
161
+ mpmath/tests/test_gammazeta.py,sha256=AB34O0DV7AlEf9Z4brnCadeQU5-uAwhWRw5FZas65DA,27917
162
+ mpmath/tests/test_hp.py,sha256=6hcENu6Te2klPEiTSeLBIRPlH7PADlJwFKbx8xpnOhg,10461
163
+ mpmath/tests/test_identify.py,sha256=lGUIPfrB2paTg0cFUo64GmMzF77F9gs9FQjX7gxGHV8,692
164
+ mpmath/tests/test_interval.py,sha256=TjYd7a9ca6iRJiLjw06isLeZTuGoGAPmgleDZ0cYfJ0,17527
165
+ mpmath/tests/test_levin.py,sha256=P8M11yV1dj_gdSNv5xuwCzFiF86QyRDtPMjURy6wJ28,5090
166
+ mpmath/tests/test_linalg.py,sha256=miKEnwB8iwWV13hi1bF1cg3hgB4rTKOR0fvDVfWmXds,10440
167
+ mpmath/tests/test_matrices.py,sha256=qyA4Ml2CvNvW034lzB01G6wVgNr7UrgZqh2wkMXtpzM,7944
168
+ mpmath/tests/test_mpmath.py,sha256=LVyJUeofiaxW-zLKWVBCz59L9UQsjlW0Ts9_oBiEv_4,196
169
+ mpmath/tests/test_ode.py,sha256=zAxexBH4fnmFNO4bvEHbug1NJWC5zqfFaVDlYijowkY,1822
170
+ mpmath/tests/test_pickle.py,sha256=Y8CKmDLFsJHUqG8CDaBw5ilrPP4YT1xijVduLpQ7XFE,401
171
+ mpmath/tests/test_power.py,sha256=sz_K02SmNxpa6Kb1uJLN_N4tXTJGdQ___vPRshEN7Gk,5227
172
+ mpmath/tests/test_quad.py,sha256=49Ltft0vZ_kdKLL5s-Kj-BzAVoF5LPVEUeNUzdOkghI,3893
173
+ mpmath/tests/test_rootfinding.py,sha256=umQegEaKHmYOEl5jEyoD-VLKDtXsTJJkepKEr4c0dC0,3132
174
+ mpmath/tests/test_special.py,sha256=YbMIoMIkJEvvKYIzS0CXthJFG0--j6un7-tcE6b7FPM,2848
175
+ mpmath/tests/test_str.py,sha256=0WsGD9hMPRi8zcuYMA9Cu2mOvQiCFskPwMsMf8lBDK4,544
176
+ mpmath/tests/test_summation.py,sha256=fdNlsvRVOsbWxbhlyDLDaEO2S8kTJrRMKIvB5-aNci0,2035
177
+ mpmath/tests/test_trig.py,sha256=zPtkIEnZaThxcWur4k7BX8-2Jmj-AhO191Svv7ANYUU,4799
178
+ mpmath/tests/test_visualization.py,sha256=1PqtkoUx-WsKYgTRiu5o9pBc85kwhf1lzU2eobDQCJM,944
179
+ mpmath/tests/torture.py,sha256=LD95oES7JY2KroELK-m-jhvtbvZaKChnt0Cq7kFMNCw,7868
180
+ mpmath/usertools.py,sha256=a-TDw7XSRsPdBEffxOooDV4WDFfuXnO58P75dcAD87I,3029
181
+ mpmath/visualization.py,sha256=pnnbjcd9AhFVRBZavYX5gjx4ytK_kXoDDisYR6EpXhs,10627
evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/REQUESTED ADDED
File without changes
evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.38.4)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
evalkit_eagle/lib/python3.10/site-packages/mpmath-1.3.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ mpmath
evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/METADATA ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: narwhals
3
+ Version: 1.22.0
4
+ Summary: Extremely lightweight compatibility layer between dataframe libraries
5
+ Project-URL: Homepage, https://github.com/narwhals-dev/narwhals
6
+ Project-URL: Documentation, https://narwhals-dev.github.io/narwhals/
7
+ Project-URL: Repository, https://github.com/narwhals-dev/narwhals
8
+ Project-URL: Bug Tracker, https://github.com/narwhals-dev/narwhals/issues
9
+ Author-email: Marco Gorelli <33491632+MarcoGorelli@users.noreply.github.com>
10
+ License-File: LICENSE.md
11
+ Keywords: cudf,dask,dataframes,interoperability,modin,pandas,polars,pyarrow
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Requires-Python: >=3.8
16
+ Provides-Extra: core
17
+ Requires-Dist: duckdb; extra == 'core'
18
+ Requires-Dist: pandas; extra == 'core'
19
+ Requires-Dist: polars; extra == 'core'
20
+ Requires-Dist: pyarrow; extra == 'core'
21
+ Requires-Dist: pyarrow-stubs; extra == 'core'
22
+ Provides-Extra: cudf
23
+ Requires-Dist: cudf>=24.10.0; extra == 'cudf'
24
+ Provides-Extra: dask
25
+ Requires-Dist: dask[dataframe]>=2024.8; extra == 'dask'
26
+ Provides-Extra: dev
27
+ Requires-Dist: covdefaults; extra == 'dev'
28
+ Requires-Dist: hypothesis; extra == 'dev'
29
+ Requires-Dist: pre-commit; extra == 'dev'
30
+ Requires-Dist: pytest; extra == 'dev'
31
+ Requires-Dist: pytest-cov; extra == 'dev'
32
+ Requires-Dist: pytest-env; extra == 'dev'
33
+ Requires-Dist: pytest-randomly; extra == 'dev'
34
+ Requires-Dist: typing-extensions; extra == 'dev'
35
+ Provides-Extra: docs
36
+ Requires-Dist: black; extra == 'docs'
37
+ Requires-Dist: duckdb; extra == 'docs'
38
+ Requires-Dist: jinja2; extra == 'docs'
39
+ Requires-Dist: markdown-exec[ansi]; extra == 'docs'
40
+ Requires-Dist: mkdocs; extra == 'docs'
41
+ Requires-Dist: mkdocs-autorefs; extra == 'docs'
42
+ Requires-Dist: mkdocs-material; extra == 'docs'
43
+ Requires-Dist: mkdocstrings[python]; extra == 'docs'
44
+ Requires-Dist: pandas; extra == 'docs'
45
+ Requires-Dist: polars>=1.0.0; extra == 'docs'
46
+ Requires-Dist: pyarrow; extra == 'docs'
47
+ Provides-Extra: duckdb
48
+ Requires-Dist: duckdb>=1.0; extra == 'duckdb'
49
+ Provides-Extra: extra
50
+ Requires-Dist: scikit-learn; extra == 'extra'
51
+ Provides-Extra: ibis
52
+ Requires-Dist: ibis-framework>=6.0.0; extra == 'ibis'
53
+ Requires-Dist: packaging; extra == 'ibis'
54
+ Requires-Dist: pyarrow-hotfix; extra == 'ibis'
55
+ Requires-Dist: rich; extra == 'ibis'
56
+ Provides-Extra: modin
57
+ Requires-Dist: modin; extra == 'modin'
58
+ Provides-Extra: pandas
59
+ Requires-Dist: pandas>=0.25.3; extra == 'pandas'
60
+ Provides-Extra: polars
61
+ Requires-Dist: polars>=0.20.3; extra == 'polars'
62
+ Provides-Extra: pyarrow
63
+ Requires-Dist: pyarrow>=11.0.0; extra == 'pyarrow'
64
+ Provides-Extra: pyspark
65
+ Requires-Dist: pyspark>=3.5.0; extra == 'pyspark'
66
+ Description-Content-Type: text/markdown
67
+
68
+ # Narwhals
69
+
70
+ <h1 align="center">
71
+ <img
72
+ width="400"
73
+ alt="narwhals_small"
74
+ src="https://github.com/narwhals-dev/narwhals/assets/33491632/26be901e-5383-49f2-9fbd-5c97b7696f27">
75
+ </h1>
76
+
77
+ [![PyPI version](https://badge.fury.io/py/narwhals.svg)](https://badge.fury.io/py/narwhals)
78
+ [![Downloads](https://static.pepy.tech/badge/narwhals/month)](https://pepy.tech/project/narwhals)
79
+ [![Trusted publishing](https://img.shields.io/badge/Trusted_publishing-Provides_attestations-bright_green)](https://peps.python.org/pep-0740/)
80
+
81
+ Extremely lightweight and extensible compatibility layer between dataframe libraries!
82
+
83
+ - **Full API support**: cuDF, Modin, pandas, Polars, PyArrow
84
+ - **Lazy-only support**: Dask. Work in progress: DuckDB, Ibis, PySpark.
85
+
86
+ Seamlessly support all, without depending on any!
87
+
88
+ - ✅ **Just use** [a subset of **the Polars API**](https://narwhals-dev.github.io/narwhals/api-reference/), no need to learn anything new
89
+ - ✅ **Zero dependencies**, Narwhals only uses what
90
+ the user passes in so your library can stay lightweight
91
+ - ✅ Separate **lazy** and eager APIs, use **expressions**
92
+ - ✅ Support pandas' complicated type system and index, without
93
+ either getting in the way
94
+ - ✅ **100% branch coverage**, tested against pandas and Polars nightly builds
95
+ - ✅ **Negligible overhead**, see [overhead](https://narwhals-dev.github.io/narwhals/overhead/)
96
+ - ✅ Let your IDE help you thanks to **full static typing**, see [typing](https://narwhals-dev.github.io/narwhals/api-reference/typing/)
97
+ - ✅ **Perfect backwards compatibility policy**,
98
+ see [stable api](https://narwhals-dev.github.io/narwhals/backcompat/) for how to opt-in
99
+
100
+ Get started!
101
+
102
+ - [Read the documentation](https://narwhals-dev.github.io/narwhals/)
103
+ - [Chat with us on Discord!](https://discord.gg/V3PqtB4VA4)
104
+ - [Join our community call](https://calendar.google.com/calendar/embed?src=27ff6dc5f598c1d94c1f6e627a1aaae680e2fac88f848bda1f2c7946ae74d5ab%40group.calendar.google.com)
105
+ - [Read the contributing guide](https://github.com/narwhals-dev/narwhals/blob/main/CONTRIBUTING.md)
106
+
107
+ <details>
108
+ <summary>Table of contents</summary>
109
+
110
+ - [Narwhals](#narwhals)
111
+ - [Installation](#installation)
112
+ - [Usage](#usage)
113
+ - [Example](#example)
114
+ - [Scope](#scope)
115
+ - [Roadmap](#roadmap)
116
+ - [Used by](#used-by)
117
+ - [Sponsors and institutional partners](#sponsors-and-institutional-partners)
118
+ - [Appears on](#appears-on)
119
+ - [Why "Narwhals"?](#why-narwhals)
120
+
121
+ </details>
122
+
123
+ ## Installation
124
+
125
+ - pip (recommended, as it's the most up-to-date)
126
+ ```
127
+ pip install narwhals
128
+ ```
129
+ - conda-forge (also fine, but the latest version may take longer to appear)
130
+ ```
131
+ conda install -c conda-forge narwhals
132
+ ```
133
+
134
+ ## Usage
135
+
136
+ There are three steps to writing dataframe-agnostic code using Narwhals:
137
+
138
+ 1. use `narwhals.from_native` to wrap a pandas/Polars/Modin/cuDF/PyArrow
139
+ DataFrame/LazyFrame in a Narwhals class
140
+ 2. use the [subset of the Polars API supported by Narwhals](https://narwhals-dev.github.io/narwhals/api-reference/)
141
+ 3. use `narwhals.to_native` to return an object to the user in its original
142
+ dataframe flavour. For example:
143
+
144
+ - if you started with pandas, you'll get pandas back
145
+ - if you started with Polars, you'll get Polars back
146
+ - if you started with Modin, you'll get Modin back (and compute will be distributed)
147
+ - if you started with cuDF, you'll get cuDF back (and compute will happen on GPU)
148
+ - if you started with PyArrow, you'll get PyArrow back
149
+
150
+ <h1 align="left">
151
+ <img
152
+ width="600"
153
+ alt="narwhals_gif"
154
+ src="https://github.com/user-attachments/assets/88292d3c-6359-4155-973d-d0f8e3fbf5ac">
155
+
156
+ </h1>
157
+
158
+ ## Example
159
+
160
+ See the [tutorial](https://narwhals-dev.github.io/narwhals/basics/dataframe/) for several examples!
161
+
162
+ ## Scope
163
+
164
+ - Do you maintain a dataframe-consuming library?
165
+ - Do you have a specific Polars function in mind that you would like Narwhals to have in order to make your work easier?
166
+
167
+ If you said yes to both, we'd love to hear from you!
168
+
169
+ ## Roadmap
170
+
171
+ See [roadmap discussion on GitHub](https://github.com/narwhals-dev/narwhals/discussions/1370)
172
+ for an up-to-date plan of future work.
173
+
174
+ ## Used by
175
+
176
+ Join the party!
177
+
178
+ - [altair](https://github.com/vega/altair/)
179
+ - [hierarchicalforecast](https://github.com/Nixtla/hierarchicalforecast)
180
+ - [marimo](https://github.com/marimo-team/marimo)
181
+ - [panel-graphic-walker](https://github.com/panel-extensions/panel-graphic-walker)
182
+ - [plotly](https://plotly.com)
183
+ - [pymarginaleffects](https://github.com/vincentarelbundock/pymarginaleffects)
184
+ - [py-shiny](https://github.com/posit-dev/py-shiny)
185
+ - [rio](https://github.com/rio-labs/rio)
186
+ - [scikit-lego](https://github.com/koaning/scikit-lego)
187
+ - [scikit-playtime](https://github.com/koaning/scikit-playtime)
188
+ - [tabmat](https://github.com/Quantco/tabmat)
189
+ - [tea-tasting](https://github.com/e10v/tea-tasting)
190
+ - [timebasedcv](https://github.com/FBruzzesi/timebasedcv)
191
+ - [tubular](https://github.com/lvgig/tubular)
192
+ - [vegafusion](https://github.com/vega/vegafusion)
193
+ - [wimsey](https://github.com/benrutter/wimsey)
194
+
195
+ Feel free to add your project to the list if it's missing, and/or
196
+ [chat with us on Discord](https://discord.gg/V3PqtB4VA4) if you'd like any support.
197
+
198
+ ## Sponsors and institutional partners
199
+
200
+ Narwhals is 100% independent, community-driven, and community-owned.
201
+ We are extremely grateful to the following organisations for having
202
+ provided some funding / development time:
203
+
204
+ - [Quansight Labs](https://labs.quansight.org)
205
+ - [Quansight Futures](https://www.qi.ventures)
206
+ - [OpenTeams](https://www.openteams.com)
207
+ - [POSSEE initiative](https://possee.org)
208
+ - [BYU-Idaho](https://www.byui.edu)
209
+
210
+ If you contribute to Narwhals on your organization's time, please let us know. We'd be happy to add your employer
211
+ to this list!
212
+
213
+ ## Appears on
214
+
215
+ Narwhals has been featured in several talks, podcasts, and blog posts:
216
+
217
+ - [Talk Python to me Podcast](https://youtu.be/FSH7BZ0tuE0)
218
+ Ahoy, Narwhals are bridging the data science APIs
219
+
220
+ - [Python Bytes Podcast](https://www.youtube.com/live/N7w_ESVW40I?si=y-wN1uCsAuJOKlOT&t=382)
221
+ Episode 402, topic #2
222
+
223
+ - [Super Data Science: ML & AI Podcast](https://www.youtube.com/watch?v=TeG4U8R0U8U)
224
+ Narwhals: For Pandas-to-Polars DataFrame Compatibility
225
+
226
+ - [Sample Space Podcast | probabl](https://youtu.be/8hYdq4sWbbQ?si=WG0QP1CZ6gkFf18b)
227
+ How Narwhals has many end users ... that never use it directly. - Marco Gorelli
228
+
229
+ - [The Real Python Podcast](https://www.youtube.com/watch?v=w5DFZbFYzCM)
230
+ Narwhals: Expanding DataFrame Compatibility Between Libraries
231
+
232
+ - [Pycon Lithuania](https://www.youtube.com/watch?v=-mdx7Cn6_6E)
233
+ Marco Gorelli - DataFrame interoperatiblity - what's been achieved, and what comes next?
234
+
235
+ - [Pycon Italy](https://www.youtube.com/watch?v=3IqUli9XsmQ)
236
+ How you can write a dataframe-agnostic library - Marco Gorelli
237
+
238
+ - [Polars Blog Post](https://pola.rs/posts/lightweight_plotting/)
239
+ Polars has a new lightweight plotting backend
240
+
241
+ - [Quansight Labs blog post (w/ Scikit-Lego)](https://labs.quansight.org/blog/scikit-lego-narwhals)
242
+ How Narwhals and scikit-lego came together to achieve dataframe-agnosticism
243
+
244
+ ## Why "Narwhals"?
245
+
246
+ [Coz they are so awesome](https://youtu.be/ykwqXuMPsoc?si=A-i8LdR38teYsos4).
247
+
248
+ Thanks to [Olha Urdeichuk](https://www.fiverr.com/olhaurdeichuk) for the illustration!
evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/RECORD ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ narwhals-1.22.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ narwhals-1.22.0.dist-info/METADATA,sha256=RTaOnYBIqhL0uq_xrZru6qio-TulylU3X8ICVUYaYfU,9969
3
+ narwhals-1.22.0.dist-info/RECORD,,
4
+ narwhals-1.22.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ narwhals-1.22.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ narwhals-1.22.0.dist-info/licenses/LICENSE.md,sha256=heMD6hta6RzeBucppx59AUCgr_ukRY0ABj0bcrN3mKs,1071
7
+ narwhals/__init__.py,sha256=T2UcrSOcktvCPyXjsfTyJlvWMrd7O1ebcduD7-HxEAo,4412
8
+ narwhals/__pycache__/__init__.cpython-310.pyc,,
9
+ narwhals/__pycache__/_expression_parsing.cpython-310.pyc,,
10
+ narwhals/__pycache__/dataframe.cpython-310.pyc,,
11
+ narwhals/__pycache__/dependencies.cpython-310.pyc,,
12
+ narwhals/__pycache__/dtypes.cpython-310.pyc,,
13
+ narwhals/__pycache__/exceptions.cpython-310.pyc,,
14
+ narwhals/__pycache__/expr.cpython-310.pyc,,
15
+ narwhals/__pycache__/expr_cat.cpython-310.pyc,,
16
+ narwhals/__pycache__/expr_dt.cpython-310.pyc,,
17
+ narwhals/__pycache__/expr_list.cpython-310.pyc,,
18
+ narwhals/__pycache__/expr_name.cpython-310.pyc,,
19
+ narwhals/__pycache__/expr_str.cpython-310.pyc,,
20
+ narwhals/__pycache__/functions.cpython-310.pyc,,
21
+ narwhals/__pycache__/group_by.cpython-310.pyc,,
22
+ narwhals/__pycache__/schema.cpython-310.pyc,,
23
+ narwhals/__pycache__/selectors.cpython-310.pyc,,
24
+ narwhals/__pycache__/series.cpython-310.pyc,,
25
+ narwhals/__pycache__/series_cat.cpython-310.pyc,,
26
+ narwhals/__pycache__/series_dt.cpython-310.pyc,,
27
+ narwhals/__pycache__/series_list.cpython-310.pyc,,
28
+ narwhals/__pycache__/series_str.cpython-310.pyc,,
29
+ narwhals/__pycache__/this.cpython-310.pyc,,
30
+ narwhals/__pycache__/translate.cpython-310.pyc,,
31
+ narwhals/__pycache__/typing.cpython-310.pyc,,
32
+ narwhals/__pycache__/utils.cpython-310.pyc,,
33
+ narwhals/_arrow/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
34
+ narwhals/_arrow/__pycache__/__init__.cpython-310.pyc,,
35
+ narwhals/_arrow/__pycache__/dataframe.cpython-310.pyc,,
36
+ narwhals/_arrow/__pycache__/expr.cpython-310.pyc,,
37
+ narwhals/_arrow/__pycache__/expr_cat.cpython-310.pyc,,
38
+ narwhals/_arrow/__pycache__/expr_dt.cpython-310.pyc,,
39
+ narwhals/_arrow/__pycache__/expr_list.cpython-310.pyc,,
40
+ narwhals/_arrow/__pycache__/expr_name.cpython-310.pyc,,
41
+ narwhals/_arrow/__pycache__/expr_str.cpython-310.pyc,,
42
+ narwhals/_arrow/__pycache__/group_by.cpython-310.pyc,,
43
+ narwhals/_arrow/__pycache__/namespace.cpython-310.pyc,,
44
+ narwhals/_arrow/__pycache__/selectors.cpython-310.pyc,,
45
+ narwhals/_arrow/__pycache__/series.cpython-310.pyc,,
46
+ narwhals/_arrow/__pycache__/series_cat.cpython-310.pyc,,
47
+ narwhals/_arrow/__pycache__/series_dt.cpython-310.pyc,,
48
+ narwhals/_arrow/__pycache__/series_list.cpython-310.pyc,,
49
+ narwhals/_arrow/__pycache__/series_str.cpython-310.pyc,,
50
+ narwhals/_arrow/__pycache__/typing.cpython-310.pyc,,
51
+ narwhals/_arrow/__pycache__/utils.cpython-310.pyc,,
52
+ narwhals/_arrow/dataframe.py,sha256=3H-RoH46ORJxKG0FdE7UPrQ_nwelqugZnt9ND1K9OuU,26761
53
+ narwhals/_arrow/expr.py,sha256=4M7-FPE1iB_bKZ87vZJ9BaA8U1h4PctfiDouNg-TiYM,19652
54
+ narwhals/_arrow/expr_cat.py,sha256=QLnRqFW2ElJh2saFcLToFkfOUXlNvhvnA8hOH7BMms8,549
55
+ narwhals/_arrow/expr_dt.py,sha256=_nnStlYKXy6HX7xogQG_ve9Q6vIHuanwhOQGcKJLn-s,3873
56
+ narwhals/_arrow/expr_list.py,sha256=K-NwuAitocGsIJv1HZYqg2folNBzKPcjSNiJWEAuqC4,487
57
+ narwhals/_arrow/expr_name.py,sha256=XMnHZARU2zXUcLfGiXgM1BQvJczM3amzQ8a8TvK3Rh4,6582
58
+ narwhals/_arrow/expr_str.py,sha256=0xnAK4uiZ782pec-uUd1I6tMGCh0RaiwdNnq6ZfWGFU,2794
59
+ narwhals/_arrow/group_by.py,sha256=1dI6tECqbyc4TMqDFB4mRLGQVay6Wxfo5Oy3h4UNUYU,7661
60
+ narwhals/_arrow/namespace.py,sha256=Ft07fZs8Cz7tDnB8YTxy9ne8xL9Q0-8qx7I8w0ucL2Q,18535
61
+ narwhals/_arrow/selectors.py,sha256=vxYG05IcPBG91X09CbpVOLjaRtxlLz9LZ_nH7TtSD7A,6169
62
+ narwhals/_arrow/series.py,sha256=sb03hzp7jt7AsAnSZbe8C3M6xQUZQDfCHlpholbG4aA,42677
63
+ narwhals/_arrow/series_cat.py,sha256=mu1vExGNE-u1DRjF0vztz4ltc5tiHumuAVJWZH2H3XQ,622
64
+ narwhals/_arrow/series_dt.py,sha256=HZ9heisS2Ap1RjfPP9ftHZ6XJ528JX4TOnuO0LZnQYo,10379
65
+ narwhals/_arrow/series_list.py,sha256=RfPPtMS7SJATzy2zrCnCoE1bU4Mq8ZHlPmgLbAKb0tg,571
66
+ narwhals/_arrow/series_str.py,sha256=yPvTeqt8He3i_nCkUC_g4qHKO4EzKkxH1e8hSirvEyI,3653
67
+ narwhals/_arrow/typing.py,sha256=KlKzPc7WJwvUoPoN56HbwZF2HXRXQVC54vo3yiBmMhw,486
68
+ narwhals/_arrow/utils.py,sha256=HmLWv9MSAyglyogUxnkeOEE-LuKed90D1JtLBMeiXt8,19473
69
+ narwhals/_dask/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
70
+ narwhals/_dask/__pycache__/__init__.cpython-310.pyc,,
71
+ narwhals/_dask/__pycache__/dataframe.cpython-310.pyc,,
72
+ narwhals/_dask/__pycache__/expr.cpython-310.pyc,,
73
+ narwhals/_dask/__pycache__/expr_dt.cpython-310.pyc,,
74
+ narwhals/_dask/__pycache__/expr_name.cpython-310.pyc,,
75
+ narwhals/_dask/__pycache__/expr_str.cpython-310.pyc,,
76
+ narwhals/_dask/__pycache__/group_by.cpython-310.pyc,,
77
+ narwhals/_dask/__pycache__/namespace.cpython-310.pyc,,
78
+ narwhals/_dask/__pycache__/selectors.cpython-310.pyc,,
79
+ narwhals/_dask/__pycache__/typing.cpython-310.pyc,,
80
+ narwhals/_dask/__pycache__/utils.cpython-310.pyc,,
81
+ narwhals/_dask/dataframe.py,sha256=Yjk5_0qCzckIkn7o8GcFRTkHn6V5uxQpFvcA077-HsM,15230
82
+ narwhals/_dask/expr.py,sha256=pE7AyIARV1IGjwtQv08q2aqsayTEJsvKPjnhsWjvDBE,26292
83
+ narwhals/_dask/expr_dt.py,sha256=kaG6Y_FZm44mhAbcKY8MnwJGXkY9KqLIICfWoTIHz3Q,7704
84
+ narwhals/_dask/expr_name.py,sha256=yBmbcIIB8WSUCNJDnpT_oe8_hOphsthYQXl15dVFQ_4,6968
85
+ narwhals/_dask/expr_str.py,sha256=jv844vJ5l_8KjFRuKLm2ZZW44WY0Qnuy-pUBqml0QqQ,4064
86
+ narwhals/_dask/group_by.py,sha256=f7cHeFkEho_6EYaH6eja-wOAnnhfaWkqmhsA2IJ76cg,6884
87
+ narwhals/_dask/namespace.py,sha256=kh-wx0W6o-xMylPm5279xk3IrUAZcCPsC_cPAVuL5hU,17061
88
+ narwhals/_dask/selectors.py,sha256=DFC3RXasa3R1JwbW2dXzdsMoE2BbJjPha93A9ShYzkw,6294
89
+ narwhals/_dask/typing.py,sha256=EttI-jVIL8QTCXqwWSS6EB1pgBJiVmtuVTb5FC2HovM,418
90
+ narwhals/_dask/utils.py,sha256=Dq9z9fcWVNr2GY7iAnKt8XOj0YOrqEO3WXo8otmTy_o,6886
91
+ narwhals/_duckdb/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
92
+ narwhals/_duckdb/__pycache__/__init__.cpython-310.pyc,,
93
+ narwhals/_duckdb/__pycache__/dataframe.cpython-310.pyc,,
94
+ narwhals/_duckdb/__pycache__/expr.cpython-310.pyc,,
95
+ narwhals/_duckdb/__pycache__/expr_dt.cpython-310.pyc,,
96
+ narwhals/_duckdb/__pycache__/expr_str.cpython-310.pyc,,
97
+ narwhals/_duckdb/__pycache__/group_by.cpython-310.pyc,,
98
+ narwhals/_duckdb/__pycache__/namespace.cpython-310.pyc,,
99
+ narwhals/_duckdb/__pycache__/series.cpython-310.pyc,,
100
+ narwhals/_duckdb/__pycache__/typing.cpython-310.pyc,,
101
+ narwhals/_duckdb/__pycache__/utils.cpython-310.pyc,,
102
+ narwhals/_duckdb/dataframe.py,sha256=tqodOpMvenE0-jCCDrCa832FLXJhXIkP3MvdrqNJMDs,12089
103
+ narwhals/_duckdb/expr.py,sha256=C_ONv4jp8lbldWjuwYkQ3o-hi45imDSLhRyaVHq2JVI,18894
104
+ narwhals/_duckdb/expr_dt.py,sha256=zIhbD9OCEaWAYgI2j3yXsDTZxrZaIVuuvP0ZqCsEDMw,4375
105
+ narwhals/_duckdb/expr_str.py,sha256=EejUYC6oFNM2hpeSvQPDqL6xJ_wsTJ8Zd-Jy-UW7MwE,5171
106
+ narwhals/_duckdb/group_by.py,sha256=0mpqeMJC0tMzb3JrXCDOd5WYLUTyiZmyOrfrXHE7ZQY,1861
107
+ narwhals/_duckdb/namespace.py,sha256=z9nSSm6ytlBD7xfJkxcgoDbLMJ8BrVHDjvFTyyIWJBY,11243
108
+ narwhals/_duckdb/series.py,sha256=SZdQiou37sPMOpPyTVh30n0_t_LCug-jlYDpPAkSJJ0,1207
109
+ narwhals/_duckdb/typing.py,sha256=BGMnGXao4hInynhJXz3OVXxAQlbzr1CuIos_c2NbSqg,426
110
+ narwhals/_duckdb/utils.py,sha256=dmDgaoxHHzqble21oSh-QK41UwdZVLck9lFdpHEhI34,8097
111
+ narwhals/_expression_parsing.py,sha256=XOST86DzV5Amab50HYvUetgL3YbESuKR8Ga_PsItJvo,11655
112
+ narwhals/_ibis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
113
+ narwhals/_ibis/__pycache__/__init__.cpython-310.pyc,,
114
+ narwhals/_ibis/__pycache__/dataframe.cpython-310.pyc,,
115
+ narwhals/_ibis/__pycache__/series.cpython-310.pyc,,
116
+ narwhals/_ibis/dataframe.py,sha256=bghoz0XHiTzDxGH4ClJs3JCy3VBmY2gNspdC1eOaiWY,5150
117
+ narwhals/_ibis/series.py,sha256=Shh8sV4-pBv_k7l2DvEIIYfCZWO_s2LwzEYnNH9VPKA,1126
118
+ narwhals/_interchange/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
119
+ narwhals/_interchange/__pycache__/__init__.cpython-310.pyc,,
120
+ narwhals/_interchange/__pycache__/dataframe.cpython-310.pyc,,
121
+ narwhals/_interchange/__pycache__/series.cpython-310.pyc,,
122
+ narwhals/_interchange/dataframe.py,sha256=icevQe0Bvl1WiiP8dqXj_xtOVc9U7K-GZsEPaSzypD8,6578
123
+ narwhals/_interchange/series.py,sha256=07P5Hhv8AaljNcMOeWw_8UeAySXHB3vGH3k4SFPhXz8,1582
124
+ narwhals/_pandas_like/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
125
+ narwhals/_pandas_like/__pycache__/__init__.cpython-310.pyc,,
126
+ narwhals/_pandas_like/__pycache__/dataframe.cpython-310.pyc,,
127
+ narwhals/_pandas_like/__pycache__/expr.cpython-310.pyc,,
128
+ narwhals/_pandas_like/__pycache__/expr_cat.cpython-310.pyc,,
129
+ narwhals/_pandas_like/__pycache__/expr_dt.cpython-310.pyc,,
130
+ narwhals/_pandas_like/__pycache__/expr_list.cpython-310.pyc,,
131
+ narwhals/_pandas_like/__pycache__/expr_name.cpython-310.pyc,,
132
+ narwhals/_pandas_like/__pycache__/expr_str.cpython-310.pyc,,
133
+ narwhals/_pandas_like/__pycache__/group_by.cpython-310.pyc,,
134
+ narwhals/_pandas_like/__pycache__/namespace.cpython-310.pyc,,
135
+ narwhals/_pandas_like/__pycache__/selectors.cpython-310.pyc,,
136
+ narwhals/_pandas_like/__pycache__/series.cpython-310.pyc,,
137
+ narwhals/_pandas_like/__pycache__/series_cat.cpython-310.pyc,,
138
+ narwhals/_pandas_like/__pycache__/series_dt.cpython-310.pyc,,
139
+ narwhals/_pandas_like/__pycache__/series_list.cpython-310.pyc,,
140
+ narwhals/_pandas_like/__pycache__/series_str.cpython-310.pyc,,
141
+ narwhals/_pandas_like/__pycache__/typing.cpython-310.pyc,,
142
+ narwhals/_pandas_like/__pycache__/utils.cpython-310.pyc,,
143
+ narwhals/_pandas_like/dataframe.py,sha256=7yntBFf_tRiTRNt_h3CvupmP9VQaS18p8S-SqoGs-ng,37512
144
+ narwhals/_pandas_like/expr.py,sha256=kOMtIX2v-6nI-yOxJh83d-dii13uCafvQMFwcO9FtCE,23402
145
+ narwhals/_pandas_like/expr_cat.py,sha256=OE2ZvzK6H3jkTQwOLyoAX4g41z4Ew6xSLGU-4WpqGFw,548
146
+ narwhals/_pandas_like/expr_dt.py,sha256=gq6lZjGipgmo64RilEQvMFIeNKFxtApIY5Ml7r3VCVg,3827
147
+ narwhals/_pandas_like/expr_list.py,sha256=tkRESZTrQUEjFpuVXjRK7fUjcseNdQITMXnOen2Mo04,560
148
+ narwhals/_pandas_like/expr_name.py,sha256=R9GK8iCy4DhieFDcItP_RuenlcTm7ygbU6lGmcIA_Wk,7023
149
+ narwhals/_pandas_like/expr_str.py,sha256=zaIcL42dUoEL1vMvnrjU0jsrJreIwEJHxkRuxqpocoQ,3194
150
+ narwhals/_pandas_like/group_by.py,sha256=QINPjg8H18lA9BROWg9tBIrrki0Snxz18BAjBG-5nQE,14566
151
+ narwhals/_pandas_like/namespace.py,sha256=5m3xiglGv5NJ47LTbpG1xwFZlKqwZlqiIHIbuzskxJc,20249
152
+ narwhals/_pandas_like/selectors.py,sha256=RNjqNqwO8BnmbEmRjYyyQk8-orApDL86bBxxydTz0EU,6600
153
+ narwhals/_pandas_like/series.py,sha256=ZykiRHqygrxLrFAFkuc9UQZVCAz8c0c8SX1LSlugWmw,41227
154
+ narwhals/_pandas_like/series_cat.py,sha256=uiB4M3MWO6MgoFTOdG2u7FaKo586pi31mNYEmF_ACNI,511
155
+ narwhals/_pandas_like/series_dt.py,sha256=Y5U3d3W-6fYIXhALLobUF10aNNoLcyExTha0tmg9Mug,10002
156
+ narwhals/_pandas_like/series_list.py,sha256=9OunUA03KUcJTEpV4Jh-jm3cr2JzbtDCAe_8aE0d-IA,1891
157
+ narwhals/_pandas_like/series_str.py,sha256=vLRcqZ8j_G4xV6F7uRCGYKwwHWIgiyQZwFXECymYkaM,2923
158
+ narwhals/_pandas_like/typing.py,sha256=2Vqf5H8Hq5E__Lxy8BzpKZsT7BPJ3R9Xc9nMbrXUb-I,523
159
+ narwhals/_pandas_like/utils.py,sha256=fAEfy7pbP_NHD8RpNhgUY36an0j9XUk2HTTzYuUqy-4,33037
160
+ narwhals/_polars/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
161
+ narwhals/_polars/__pycache__/__init__.cpython-310.pyc,,
162
+ narwhals/_polars/__pycache__/dataframe.cpython-310.pyc,,
163
+ narwhals/_polars/__pycache__/expr.cpython-310.pyc,,
164
+ narwhals/_polars/__pycache__/group_by.cpython-310.pyc,,
165
+ narwhals/_polars/__pycache__/namespace.cpython-310.pyc,,
166
+ narwhals/_polars/__pycache__/series.cpython-310.pyc,,
167
+ narwhals/_polars/__pycache__/typing.cpython-310.pyc,,
168
+ narwhals/_polars/__pycache__/utils.cpython-310.pyc,,
169
+ narwhals/_polars/dataframe.py,sha256=uIEGkXudMiFfKzKhUKJjCcX2X1NZOMa6SjwqlGgImYE,17543
170
+ narwhals/_polars/expr.py,sha256=YwwKpVDN22bgBhPjW0dMn6P6VpsIqnc3LIOgRunFU-8,11333
171
+ narwhals/_polars/group_by.py,sha256=YhWfg1A_d0vAvxAZmR3uxYp6HPf1gi0Q6UAkZ4IELV8,1936
172
+ narwhals/_polars/namespace.py,sha256=RkCxwfJ0Iavsmuq9KEsk3ekNtmzoZwpYF4bnrTik-jY,9287
173
+ narwhals/_polars/series.py,sha256=YLYZn_IefIvBt1hj2LdHc3RsS4DfXiFRI8IKijcJDX8,17819
174
+ narwhals/_polars/typing.py,sha256=vK3mldNcbA69EOas5GRiRi-2XLMtOyhMigb2o2s9j-I,493
175
+ narwhals/_polars/utils.py,sha256=h3eJtFwsxoB9NPfURTNZE6mqOPCYhujym22ZK5BUpXY,7479
176
+ narwhals/_spark_like/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
177
+ narwhals/_spark_like/__pycache__/__init__.cpython-310.pyc,,
178
+ narwhals/_spark_like/__pycache__/dataframe.cpython-310.pyc,,
179
+ narwhals/_spark_like/__pycache__/expr.cpython-310.pyc,,
180
+ narwhals/_spark_like/__pycache__/expr_str.cpython-310.pyc,,
181
+ narwhals/_spark_like/__pycache__/group_by.cpython-310.pyc,,
182
+ narwhals/_spark_like/__pycache__/namespace.cpython-310.pyc,,
183
+ narwhals/_spark_like/__pycache__/typing.cpython-310.pyc,,
184
+ narwhals/_spark_like/__pycache__/utils.cpython-310.pyc,,
185
+ narwhals/_spark_like/dataframe.py,sha256=XsEMYU9LtSI7Sgk8zBDYdHQWRsV5Rz0ahD5HtT7VcvQ,9513
186
+ narwhals/_spark_like/expr.py,sha256=5E0H5PNmkdpIiFiNog2FyOMLSqgC6OQQi53iDOB8npA,16553
187
+ narwhals/_spark_like/expr_str.py,sha256=DgfaaKUz00C3W1ke2DvzTIC_Rpzx4HujI2Fw9nXgimg,4638
188
+ narwhals/_spark_like/group_by.py,sha256=utafv2Onw47txKn8JVM9Xzof5AZqPyWlDqkOUQwOpxA,5803
189
+ narwhals/_spark_like/namespace.py,sha256=JBkSTOz32uu7KhLFkeFlyUKXWr9EqvsNl5RcmPDdnoc,12635
190
+ narwhals/_spark_like/typing.py,sha256=C0D-zKcbthX2LOyKKtpxIhTSDNhPPgZvEvivL5xUiE8,439
191
+ narwhals/_spark_like/utils.py,sha256=KoHH0CFgkou4Kudjvhk1Wli-lDfCVY8eyGRDJM0wq90,5640
192
+ narwhals/dataframe.py,sha256=xbYVfJk9n3PHBRyLWzNoLqAGG_B_yUJ3DIuhVG5vzos,203929
193
+ narwhals/dependencies.py,sha256=tgRmVzOTAJKBlTulEEkdDupV51-kiog28OPZsIYRMU4,12985
194
+ narwhals/dtypes.py,sha256=Vhhy4P47DTzAUhPaFJufyM-RgSmmHEVcofHkeLDW-PA,23398
195
+ narwhals/exceptions.py,sha256=5N1ZWk6lLNzQ0At6iL5HF_0v6hszsoSXgJtZcuWsMso,2543
196
+ narwhals/expr.py,sha256=XLJ5V-XTPxF5N19D4cqwvFs_5YU6iz7sFJpUr4Jrl6A,145707
197
+ narwhals/expr_cat.py,sha256=MKEo1pmpHeQ-4V9EZ8HFDBKFpVxEdQv7e6jnFlLT4-U,2053
198
+ narwhals/expr_dt.py,sha256=9fhHuZpVWo-_LpbqiMqvW78W5WIb1yjbZ0ZpO2mL6kI,57669
199
+ narwhals/expr_list.py,sha256=of-kNzZgfzKO85A_TfcPPCwihcjf4fV5VJD0OdBQVR4,2592
200
+ narwhals/expr_name.py,sha256=w8JQsXDpwo_BCkqpWkp9ET6WBNcUMx22ig_KCcan-2Q,10580
201
+ narwhals/expr_str.py,sha256=xLwAw4aBVZjP7ZwFsIOs-gVz7nn6vVKMpScwcXAB0D8,34915
202
+ narwhals/functions.py,sha256=yXbJgh9VOSfQtKCPyiGmpaNqX7FqJuwcbKNsstY-axE,81865
203
+ narwhals/group_by.py,sha256=aZebFY1RBTY2xGZGp0yW6hhhWgTTtDXH3f8zV81eChs,7323
204
+ narwhals/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
205
+ narwhals/schema.py,sha256=xQlQVrLyG40V_1FGXjZqW1gIyZsgvMFXdcviPikC15w,2147
206
+ narwhals/selectors.py,sha256=8s7tlfbYd6xVT5O2YWljKybw8SVN8ke5CLizKAPwJec,7260
207
+ narwhals/series.py,sha256=7D4TfeM3rld5f8qPsISK163I0EABBbiRVNTKZBvq3_w,153906
208
+ narwhals/series_cat.py,sha256=JR0njE9IoIeQliTLAsZ533bm3egSgYNOCyf8wN73srM,2273
209
+ narwhals/series_dt.py,sha256=knZNa9GqsN_38ud-1JAcF_rzqupurjaUj-WVVpJsiFs,42557
210
+ narwhals/series_list.py,sha256=EwSehjYI-a5T46arEM9hhfxthuuIsEvRXIsvgBdZdC4,2170
211
+ narwhals/series_str.py,sha256=qClMzpy8LL3jTsRb1yQAHnyWaiY-xcKA9OvHXNveKYU,28113
212
+ narwhals/stable/__init__.py,sha256=b9soCkGkQzgF5jO5EdQ6IOQpnc6G6eqWmY6WwpoSjhk,85
213
+ narwhals/stable/__pycache__/__init__.cpython-310.pyc,,
214
+ narwhals/stable/v1/__init__.py,sha256=64EitAcXt4T1pfbmgRTvnqN8_ww-0yeTSZPToNPuifY,71057
215
+ narwhals/stable/v1/__pycache__/__init__.cpython-310.pyc,,
216
+ narwhals/stable/v1/__pycache__/_dtypes.cpython-310.pyc,,
217
+ narwhals/stable/v1/__pycache__/dependencies.cpython-310.pyc,,
218
+ narwhals/stable/v1/__pycache__/dtypes.cpython-310.pyc,,
219
+ narwhals/stable/v1/__pycache__/selectors.cpython-310.pyc,,
220
+ narwhals/stable/v1/__pycache__/typing.cpython-310.pyc,,
221
+ narwhals/stable/v1/_dtypes.py,sha256=v3sO0aFMGwyxL24f2RtMzygTC6L5zkHcJGVWN1oh0tk,2426
222
+ narwhals/stable/v1/dependencies.py,sha256=PqYYOP_8w0ZJraajFnpYwc_ZdURRQIcgqplKsnymL_U,2204
223
+ narwhals/stable/v1/dtypes.py,sha256=WuX-S0gB3uKoH1d2YrBpcXcl8wm02V7jLn1B1J7Kbek,1741
224
+ narwhals/stable/v1/selectors.py,sha256=lMD-tTRY_avyQrWg7Vbqafud3LD82uDaexMtgNNCtBQ,375
225
+ narwhals/stable/v1/typing.py,sha256=hJ4aJk7-3kbuHFoLdl9p8MSS_qIVJFYJD9zN7sHtVek,6829
226
+ narwhals/this.py,sha256=BbKcj0ReWqE01lznzKjuqq7otXONvjBevWWC5aJhQxs,1584
227
+ narwhals/translate.py,sha256=sUdkikXO6lvo3NkAoweWwmy2TXZllwEr8SZyEhf3sjI,35449
228
+ narwhals/typing.py,sha256=pVH7PtzzgLRoneXO2xaN-ofhpXy-2R4a5fyB80kgGUQ,9239
229
+ narwhals/utils.py,sha256=B_3E1vwZNK3aASljpzwzsGPQTnItwiKilvjzzpaWf8A,36581
evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/REQUESTED ADDED
File without changes
evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
evalkit_eagle/lib/python3.10/site-packages/narwhals-1.22.0.dist-info/licenses/LICENSE.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024, Marco Gorelli
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
evalkit_eagle/lib/python3.10/site-packages/ninja/__init__.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ import sysconfig
7
+ from collections.abc import Iterable
8
+ from typing import NoReturn
9
+
10
+ from ._version import version as __version__
11
+ from .ninja_syntax import Writer, escape, expand
12
+
13
+ __all__ = ["BIN_DIR", "DATA", "Writer", "__version__", "escape", "expand", "ninja"]
14
+
15
+
16
+ def __dir__() -> list[str]:
17
+ return __all__
18
+
19
+
20
+ def _get_ninja_dir() -> str:
21
+ ninja_exe = "ninja" + sysconfig.get_config_var("EXE")
22
+
23
+ # Default path
24
+ path = os.path.join(sysconfig.get_path("scripts"), ninja_exe)
25
+ if os.path.isfile(path):
26
+ return os.path.dirname(path)
27
+
28
+ # User path
29
+ if sys.version_info >= (3, 10):
30
+ user_scheme = sysconfig.get_preferred_scheme("user")
31
+ elif os.name == "nt":
32
+ user_scheme = "nt_user"
33
+ elif sys.platform.startswith("darwin") and getattr(sys, "_framework", None):
34
+ user_scheme = "osx_framework_user"
35
+ else:
36
+ user_scheme = "posix_user"
37
+
38
+ path = sysconfig.get_path("scripts", scheme=user_scheme)
39
+
40
+ if os.path.isfile(os.path.join(path, ninja_exe)):
41
+ return path
42
+
43
+ # Fallback to python location
44
+ path = os.path.dirname(sys.executable)
45
+ if os.path.isfile(os.path.join(path, ninja_exe)):
46
+ return path
47
+
48
+ return ""
49
+
50
+
51
+ BIN_DIR = _get_ninja_dir()
52
+
53
+
54
+ def _program(name: str, args: Iterable[str]) -> int:
55
+ cmd = os.path.join(BIN_DIR, name)
56
+ return subprocess.call([cmd, *args], close_fds=False)
57
+
58
+
59
+ def ninja() -> NoReturn:
60
+ raise SystemExit(_program('ninja', sys.argv[1:]))
evalkit_eagle/lib/python3.10/site-packages/ninja/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ninja import ninja
4
+
5
+ if __name__ == '__main__':
6
+ ninja()
evalkit_eagle/lib/python3.10/site-packages/ninja/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/ninja/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (282 Bytes). View file
 
evalkit_eagle/lib/python3.10/site-packages/ninja/__pycache__/_version.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
evalkit_eagle/lib/python3.10/site-packages/ninja/__pycache__/ninja_syntax.cpython-310.pyc ADDED
Binary file (5.96 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/ninja/_version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ version = "1.11.1.3"
evalkit_eagle/lib/python3.10/site-packages/ninja/_version.pyi ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ version: str
4
+ version_tuple: tuple[int, int, int] | tuple[int, int, int, str, str]
evalkit_eagle/lib/python3.10/site-packages/ninja/ninja_syntax.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+
3
+ # Copyright 2011 Google Inc. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """Python module for generating .ninja files.
18
+
19
+ Note that this is emphatically not a required piece of Ninja; it's
20
+ just a helpful utility for build-file-generation systems that already
21
+ use Python.
22
+ """
23
+
24
+ import re
25
+ import textwrap
26
+
27
+ def escape_path(word):
28
+ return word.replace('$ ', '$$ ').replace(' ', '$ ').replace(':', '$:')
29
+
30
+ class Writer(object):
31
+ def __init__(self, output, width=78):
32
+ self.output = output
33
+ self.width = width
34
+
35
+ def newline(self):
36
+ self.output.write('\n')
37
+
38
+ def comment(self, text):
39
+ for line in textwrap.wrap(text, self.width - 2, break_long_words=False,
40
+ break_on_hyphens=False):
41
+ self.output.write('# ' + line + '\n')
42
+
43
+ def variable(self, key, value, indent=0):
44
+ if value is None:
45
+ return
46
+ if isinstance(value, list):
47
+ value = ' '.join(filter(None, value)) # Filter out empty strings.
48
+ self._line('%s = %s' % (key, value), indent)
49
+
50
+ def pool(self, name, depth):
51
+ self._line('pool %s' % name)
52
+ self.variable('depth', depth, indent=1)
53
+
54
+ def rule(self, name, command, description=None, depfile=None,
55
+ generator=False, pool=None, restat=False, rspfile=None,
56
+ rspfile_content=None, deps=None):
57
+ self._line('rule %s' % name)
58
+ self.variable('command', command, indent=1)
59
+ if description:
60
+ self.variable('description', description, indent=1)
61
+ if depfile:
62
+ self.variable('depfile', depfile, indent=1)
63
+ if generator:
64
+ self.variable('generator', '1', indent=1)
65
+ if pool:
66
+ self.variable('pool', pool, indent=1)
67
+ if restat:
68
+ self.variable('restat', '1', indent=1)
69
+ if rspfile:
70
+ self.variable('rspfile', rspfile, indent=1)
71
+ if rspfile_content:
72
+ self.variable('rspfile_content', rspfile_content, indent=1)
73
+ if deps:
74
+ self.variable('deps', deps, indent=1)
75
+
76
+ def build(self, outputs, rule, inputs=None, implicit=None, order_only=None,
77
+ variables=None, implicit_outputs=None, pool=None, dyndep=None):
78
+ outputs = as_list(outputs)
79
+ out_outputs = [escape_path(x) for x in outputs]
80
+ all_inputs = [escape_path(x) for x in as_list(inputs)]
81
+
82
+ if implicit:
83
+ implicit = [escape_path(x) for x in as_list(implicit)]
84
+ all_inputs.append('|')
85
+ all_inputs.extend(implicit)
86
+ if order_only:
87
+ order_only = [escape_path(x) for x in as_list(order_only)]
88
+ all_inputs.append('||')
89
+ all_inputs.extend(order_only)
90
+ if implicit_outputs:
91
+ implicit_outputs = [escape_path(x)
92
+ for x in as_list(implicit_outputs)]
93
+ out_outputs.append('|')
94
+ out_outputs.extend(implicit_outputs)
95
+
96
+ self._line('build %s: %s' % (' '.join(out_outputs),
97
+ ' '.join([rule] + all_inputs)))
98
+ if pool is not None:
99
+ self._line(' pool = %s' % pool)
100
+ if dyndep is not None:
101
+ self._line(' dyndep = %s' % dyndep)
102
+
103
+ if variables:
104
+ if isinstance(variables, dict):
105
+ iterator = iter(variables.items())
106
+ else:
107
+ iterator = iter(variables)
108
+
109
+ for key, val in iterator:
110
+ self.variable(key, val, indent=1)
111
+
112
+ return outputs
113
+
114
+ def include(self, path):
115
+ self._line('include %s' % path)
116
+
117
+ def subninja(self, path):
118
+ self._line('subninja %s' % path)
119
+
120
+ def default(self, paths):
121
+ self._line('default %s' % ' '.join(as_list(paths)))
122
+
123
+ def _count_dollars_before_index(self, s, i):
124
+ """Returns the number of '$' characters right in front of s[i]."""
125
+ dollar_count = 0
126
+ dollar_index = i - 1
127
+ while dollar_index > 0 and s[dollar_index] == '$':
128
+ dollar_count += 1
129
+ dollar_index -= 1
130
+ return dollar_count
131
+
132
+ def _line(self, text, indent=0):
133
+ """Write 'text' word-wrapped at self.width characters."""
134
+ leading_space = ' ' * indent
135
+ while len(leading_space) + len(text) > self.width:
136
+ # The text is too wide; wrap if possible.
137
+
138
+ # Find the rightmost space that would obey our width constraint and
139
+ # that's not an escaped space.
140
+ available_space = self.width - len(leading_space) - len(' $')
141
+ space = available_space
142
+ while True:
143
+ space = text.rfind(' ', 0, space)
144
+ if (space < 0 or
145
+ self._count_dollars_before_index(text, space) % 2 == 0):
146
+ break
147
+
148
+ if space < 0:
149
+ # No such space; just use the first unescaped space we can find.
150
+ space = available_space - 1
151
+ while True:
152
+ space = text.find(' ', space + 1)
153
+ if (space < 0 or
154
+ self._count_dollars_before_index(text, space) % 2 == 0):
155
+ break
156
+ if space < 0:
157
+ # Give up on breaking.
158
+ break
159
+
160
+ self.output.write(leading_space + text[0:space] + ' $\n')
161
+ text = text[space+1:]
162
+
163
+ # Subsequent lines are continuations, so indent them.
164
+ leading_space = ' ' * (indent+2)
165
+
166
+ self.output.write(leading_space + text + '\n')
167
+
168
+ def close(self):
169
+ self.output.close()
170
+
171
+
172
+ def as_list(input):
173
+ if input is None:
174
+ return []
175
+ if isinstance(input, list):
176
+ return input
177
+ return [input]
178
+
179
+
180
+ def escape(string):
181
+ """Escape a string such that it can be embedded into a Ninja file without
182
+ further interpretation."""
183
+ assert '\n' not in string, 'Ninja syntax does not allow newlines'
184
+ # We only have one special metacharacter: '$'.
185
+ return string.replace('$', '$$')
186
+
187
+
188
+ def expand(string, vars, local_vars={}):
189
+ """Expand a string containing $vars as Ninja would.
190
+
191
+ Note: doesn't handle the full Ninja variable syntax, but it's enough
192
+ to make configure.py's use of it work.
193
+ """
194
+ def exp(m):
195
+ var = m.group(1)
196
+ if var == '$':
197
+ return '$'
198
+ return local_vars.get(var, vars.get(var, ''))
199
+ return re.sub(r'\$(\$|\w*)', exp, string)
evalkit_eagle/lib/python3.10/site-packages/ninja/ninja_syntax.pyi ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Mapping, Sequence
2
+ from os import PathLike
3
+
4
+ def escape_path(word: str) -> str: ...
5
+
6
+ class Writer:
7
+ output: str
8
+ width: int
9
+
10
+ def __init__(self, output: str, width: int = ...): ...
11
+ def newline(self) -> None: ...
12
+ def comment(self, text: str) -> None: ...
13
+ def variable(self, key: str, value: list[str] | str, indent: int = ...) -> None: ...
14
+ def pool(self, name: str, depth: int) -> None: ...
15
+ def rule(self, name: str, command: str, description: str | None = None,
16
+ depfile: str | None = None, generator: bool = False,
17
+ pool: str | None = None, restat: bool = False,
18
+ rspfile: str | None = None, rspfile_content: str | None = None,
19
+ deps: str | None = None) -> None:
20
+ ...
21
+
22
+ def build(self, outputs: list[str], rule: str, inputs: list[str] | None = None,
23
+ implicit: list[str] | None = None, order_only: list[str] | None = None,
24
+ variables: dict[str, str] | None = None,
25
+ implicit_outputs: list[str] | None = None,
26
+ pool: str | None = None, dyndep: str | None = None) -> None:
27
+ ...
28
+ def include(self, path: str | PathLike[str]) -> None: ...
29
+ def subninja(self, path: str | PathLike[str]) -> None: ...
30
+ def default(self, paths: Sequence[str | PathLike[str]]) -> None: ...
31
+ def close(self) -> None: ...
32
+
33
+ def as_list(input: None | list[str] | str) -> list[str]: ...
34
+
35
+ def escape(string: str) -> str: ...
36
+
37
+ def expand(string: str, vars: Mapping[str, str], local_vars: Mapping[str, str]=...) -> str: ...
evalkit_eagle/lib/python3.10/site-packages/ninja/py.typed ADDED
File without changes
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/__init__.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Plotting public API.
3
+
4
+ Authors of third-party plotting backends should implement a module with a
5
+ public ``plot(data, kind, **kwargs)``. The parameter `data` will contain
6
+ the data structure and can be a `Series` or a `DataFrame`. For example,
7
+ for ``df.plot()`` the parameter `data` will contain the DataFrame `df`.
8
+ In some cases, the data structure is transformed before being sent to
9
+ the backend (see PlotAccessor.__call__ in pandas/plotting/_core.py for
10
+ the exact transformations).
11
+
12
+ The parameter `kind` will be one of:
13
+
14
+ - line
15
+ - bar
16
+ - barh
17
+ - box
18
+ - hist
19
+ - kde
20
+ - area
21
+ - pie
22
+ - scatter
23
+ - hexbin
24
+
25
+ See the pandas API reference for documentation on each kind of plot.
26
+
27
+ Any other keyword argument is currently assumed to be backend specific,
28
+ but some parameters may be unified and added to the signature in the
29
+ future (e.g. `title` which should be useful for any backend).
30
+
31
+ Currently, all the Matplotlib functions in pandas are accessed through
32
+ the selected backend. For example, `pandas.plotting.boxplot` (equivalent
33
+ to `DataFrame.boxplot`) is also accessed in the selected backend. This
34
+ is expected to change, and the exact API is under discussion. But with
35
+ the current version, backends are expected to implement the next functions:
36
+
37
+ - plot (describe above, used for `Series.plot` and `DataFrame.plot`)
38
+ - hist_series and hist_frame (for `Series.hist` and `DataFrame.hist`)
39
+ - boxplot (`pandas.plotting.boxplot(df)` equivalent to `DataFrame.boxplot`)
40
+ - boxplot_frame and boxplot_frame_groupby
41
+ - register and deregister (register converters for the tick formats)
42
+ - Plots not called as `Series` and `DataFrame` methods:
43
+ - table
44
+ - andrews_curves
45
+ - autocorrelation_plot
46
+ - bootstrap_plot
47
+ - lag_plot
48
+ - parallel_coordinates
49
+ - radviz
50
+ - scatter_matrix
51
+
52
+ Use the code in pandas/plotting/_matplotib.py and
53
+ https://github.com/pyviz/hvplot as a reference on how to write a backend.
54
+
55
+ For the discussion about the API see
56
+ https://github.com/pandas-dev/pandas/issues/26747.
57
+ """
58
+ from pandas.plotting._core import (
59
+ PlotAccessor,
60
+ boxplot,
61
+ boxplot_frame,
62
+ boxplot_frame_groupby,
63
+ hist_frame,
64
+ hist_series,
65
+ )
66
+ from pandas.plotting._misc import (
67
+ andrews_curves,
68
+ autocorrelation_plot,
69
+ bootstrap_plot,
70
+ deregister as deregister_matplotlib_converters,
71
+ lag_plot,
72
+ parallel_coordinates,
73
+ plot_params,
74
+ radviz,
75
+ register as register_matplotlib_converters,
76
+ scatter_matrix,
77
+ table,
78
+ )
79
+
80
+ __all__ = [
81
+ "PlotAccessor",
82
+ "boxplot",
83
+ "boxplot_frame",
84
+ "boxplot_frame_groupby",
85
+ "hist_frame",
86
+ "hist_series",
87
+ "scatter_matrix",
88
+ "radviz",
89
+ "andrews_curves",
90
+ "bootstrap_plot",
91
+ "parallel_coordinates",
92
+ "lag_plot",
93
+ "autocorrelation_plot",
94
+ "table",
95
+ "plot_params",
96
+ "register_matplotlib_converters",
97
+ "deregister_matplotlib_converters",
98
+ ]
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.8 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/__pycache__/_core.cpython-310.pyc ADDED
Binary file (61.2 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/__pycache__/_misc.cpython-310.pyc ADDED
Binary file (21.2 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_core.py ADDED
@@ -0,0 +1,1946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ from typing import (
5
+ TYPE_CHECKING,
6
+ Callable,
7
+ Literal,
8
+ )
9
+
10
+ from pandas._config import get_option
11
+
12
+ from pandas.util._decorators import (
13
+ Appender,
14
+ Substitution,
15
+ )
16
+
17
+ from pandas.core.dtypes.common import (
18
+ is_integer,
19
+ is_list_like,
20
+ )
21
+ from pandas.core.dtypes.generic import (
22
+ ABCDataFrame,
23
+ ABCSeries,
24
+ )
25
+
26
+ from pandas.core.base import PandasObject
27
+
28
+ if TYPE_CHECKING:
29
+ from collections.abc import (
30
+ Hashable,
31
+ Sequence,
32
+ )
33
+ import types
34
+
35
+ from matplotlib.axes import Axes
36
+ import numpy as np
37
+
38
+ from pandas._typing import IndexLabel
39
+
40
+ from pandas import (
41
+ DataFrame,
42
+ Series,
43
+ )
44
+ from pandas.core.groupby.generic import DataFrameGroupBy
45
+
46
+
47
+ def hist_series(
48
+ self: Series,
49
+ by=None,
50
+ ax=None,
51
+ grid: bool = True,
52
+ xlabelsize: int | None = None,
53
+ xrot: float | None = None,
54
+ ylabelsize: int | None = None,
55
+ yrot: float | None = None,
56
+ figsize: tuple[int, int] | None = None,
57
+ bins: int | Sequence[int] = 10,
58
+ backend: str | None = None,
59
+ legend: bool = False,
60
+ **kwargs,
61
+ ):
62
+ """
63
+ Draw histogram of the input series using matplotlib.
64
+
65
+ Parameters
66
+ ----------
67
+ by : object, optional
68
+ If passed, then used to form histograms for separate groups.
69
+ ax : matplotlib axis object
70
+ If not passed, uses gca().
71
+ grid : bool, default True
72
+ Whether to show axis grid lines.
73
+ xlabelsize : int, default None
74
+ If specified changes the x-axis label size.
75
+ xrot : float, default None
76
+ Rotation of x axis labels.
77
+ ylabelsize : int, default None
78
+ If specified changes the y-axis label size.
79
+ yrot : float, default None
80
+ Rotation of y axis labels.
81
+ figsize : tuple, default None
82
+ Figure size in inches by default.
83
+ bins : int or sequence, default 10
84
+ Number of histogram bins to be used. If an integer is given, bins + 1
85
+ bin edges are calculated and returned. If bins is a sequence, gives
86
+ bin edges, including left edge of first bin and right edge of last
87
+ bin. In this case, bins is returned unmodified.
88
+ backend : str, default None
89
+ Backend to use instead of the backend specified in the option
90
+ ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to
91
+ specify the ``plotting.backend`` for the whole session, set
92
+ ``pd.options.plotting.backend``.
93
+ legend : bool, default False
94
+ Whether to show the legend.
95
+
96
+ **kwargs
97
+ To be passed to the actual plotting function.
98
+
99
+ Returns
100
+ -------
101
+ matplotlib.AxesSubplot
102
+ A histogram plot.
103
+
104
+ See Also
105
+ --------
106
+ matplotlib.axes.Axes.hist : Plot a histogram using matplotlib.
107
+
108
+ Examples
109
+ --------
110
+ For Series:
111
+
112
+ .. plot::
113
+ :context: close-figs
114
+
115
+ >>> lst = ['a', 'a', 'a', 'b', 'b', 'b']
116
+ >>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst)
117
+ >>> hist = ser.hist()
118
+
119
+ For Groupby:
120
+
121
+ .. plot::
122
+ :context: close-figs
123
+
124
+ >>> lst = ['a', 'a', 'a', 'b', 'b', 'b']
125
+ >>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst)
126
+ >>> hist = ser.groupby(level=0).hist()
127
+ """
128
+ plot_backend = _get_plot_backend(backend)
129
+ return plot_backend.hist_series(
130
+ self,
131
+ by=by,
132
+ ax=ax,
133
+ grid=grid,
134
+ xlabelsize=xlabelsize,
135
+ xrot=xrot,
136
+ ylabelsize=ylabelsize,
137
+ yrot=yrot,
138
+ figsize=figsize,
139
+ bins=bins,
140
+ legend=legend,
141
+ **kwargs,
142
+ )
143
+
144
+
145
+ def hist_frame(
146
+ data: DataFrame,
147
+ column: IndexLabel | None = None,
148
+ by=None,
149
+ grid: bool = True,
150
+ xlabelsize: int | None = None,
151
+ xrot: float | None = None,
152
+ ylabelsize: int | None = None,
153
+ yrot: float | None = None,
154
+ ax=None,
155
+ sharex: bool = False,
156
+ sharey: bool = False,
157
+ figsize: tuple[int, int] | None = None,
158
+ layout: tuple[int, int] | None = None,
159
+ bins: int | Sequence[int] = 10,
160
+ backend: str | None = None,
161
+ legend: bool = False,
162
+ **kwargs,
163
+ ):
164
+ """
165
+ Make a histogram of the DataFrame's columns.
166
+
167
+ A `histogram`_ is a representation of the distribution of data.
168
+ This function calls :meth:`matplotlib.pyplot.hist`, on each series in
169
+ the DataFrame, resulting in one histogram per column.
170
+
171
+ .. _histogram: https://en.wikipedia.org/wiki/Histogram
172
+
173
+ Parameters
174
+ ----------
175
+ data : DataFrame
176
+ The pandas object holding the data.
177
+ column : str or sequence, optional
178
+ If passed, will be used to limit data to a subset of columns.
179
+ by : object, optional
180
+ If passed, then used to form histograms for separate groups.
181
+ grid : bool, default True
182
+ Whether to show axis grid lines.
183
+ xlabelsize : int, default None
184
+ If specified changes the x-axis label size.
185
+ xrot : float, default None
186
+ Rotation of x axis labels. For example, a value of 90 displays the
187
+ x labels rotated 90 degrees clockwise.
188
+ ylabelsize : int, default None
189
+ If specified changes the y-axis label size.
190
+ yrot : float, default None
191
+ Rotation of y axis labels. For example, a value of 90 displays the
192
+ y labels rotated 90 degrees clockwise.
193
+ ax : Matplotlib axes object, default None
194
+ The axes to plot the histogram on.
195
+ sharex : bool, default True if ax is None else False
196
+ In case subplots=True, share x axis and set some x axis labels to
197
+ invisible; defaults to True if ax is None otherwise False if an ax
198
+ is passed in.
199
+ Note that passing in both an ax and sharex=True will alter all x axis
200
+ labels for all subplots in a figure.
201
+ sharey : bool, default False
202
+ In case subplots=True, share y axis and set some y axis labels to
203
+ invisible.
204
+ figsize : tuple, optional
205
+ The size in inches of the figure to create. Uses the value in
206
+ `matplotlib.rcParams` by default.
207
+ layout : tuple, optional
208
+ Tuple of (rows, columns) for the layout of the histograms.
209
+ bins : int or sequence, default 10
210
+ Number of histogram bins to be used. If an integer is given, bins + 1
211
+ bin edges are calculated and returned. If bins is a sequence, gives
212
+ bin edges, including left edge of first bin and right edge of last
213
+ bin. In this case, bins is returned unmodified.
214
+
215
+ backend : str, default None
216
+ Backend to use instead of the backend specified in the option
217
+ ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to
218
+ specify the ``plotting.backend`` for the whole session, set
219
+ ``pd.options.plotting.backend``.
220
+
221
+ legend : bool, default False
222
+ Whether to show the legend.
223
+
224
+ **kwargs
225
+ All other plotting keyword arguments to be passed to
226
+ :meth:`matplotlib.pyplot.hist`.
227
+
228
+ Returns
229
+ -------
230
+ matplotlib.AxesSubplot or numpy.ndarray of them
231
+
232
+ See Also
233
+ --------
234
+ matplotlib.pyplot.hist : Plot a histogram using matplotlib.
235
+
236
+ Examples
237
+ --------
238
+ This example draws a histogram based on the length and width of
239
+ some animals, displayed in three bins
240
+
241
+ .. plot::
242
+ :context: close-figs
243
+
244
+ >>> data = {'length': [1.5, 0.5, 1.2, 0.9, 3],
245
+ ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1]}
246
+ >>> index = ['pig', 'rabbit', 'duck', 'chicken', 'horse']
247
+ >>> df = pd.DataFrame(data, index=index)
248
+ >>> hist = df.hist(bins=3)
249
+ """
250
+ plot_backend = _get_plot_backend(backend)
251
+ return plot_backend.hist_frame(
252
+ data,
253
+ column=column,
254
+ by=by,
255
+ grid=grid,
256
+ xlabelsize=xlabelsize,
257
+ xrot=xrot,
258
+ ylabelsize=ylabelsize,
259
+ yrot=yrot,
260
+ ax=ax,
261
+ sharex=sharex,
262
+ sharey=sharey,
263
+ figsize=figsize,
264
+ layout=layout,
265
+ legend=legend,
266
+ bins=bins,
267
+ **kwargs,
268
+ )
269
+
270
+
271
+ _boxplot_doc = """
272
+ Make a box plot from DataFrame columns.
273
+
274
+ Make a box-and-whisker plot from DataFrame columns, optionally grouped
275
+ by some other columns. A box plot is a method for graphically depicting
276
+ groups of numerical data through their quartiles.
277
+ The box extends from the Q1 to Q3 quartile values of the data,
278
+ with a line at the median (Q2). The whiskers extend from the edges
279
+ of box to show the range of the data. By default, they extend no more than
280
+ `1.5 * IQR (IQR = Q3 - Q1)` from the edges of the box, ending at the farthest
281
+ data point within that interval. Outliers are plotted as separate dots.
282
+
283
+ For further details see
284
+ Wikipedia's entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`_.
285
+
286
+ Parameters
287
+ ----------
288
+ %(data)s\
289
+ column : str or list of str, optional
290
+ Column name or list of names, or vector.
291
+ Can be any valid input to :meth:`pandas.DataFrame.groupby`.
292
+ by : str or array-like, optional
293
+ Column in the DataFrame to :meth:`pandas.DataFrame.groupby`.
294
+ One box-plot will be done per value of columns in `by`.
295
+ ax : object of class matplotlib.axes.Axes, optional
296
+ The matplotlib axes to be used by boxplot.
297
+ fontsize : float or str
298
+ Tick label font size in points or as a string (e.g., `large`).
299
+ rot : float, default 0
300
+ The rotation angle of labels (in degrees)
301
+ with respect to the screen coordinate system.
302
+ grid : bool, default True
303
+ Setting this to True will show the grid.
304
+ figsize : A tuple (width, height) in inches
305
+ The size of the figure to create in matplotlib.
306
+ layout : tuple (rows, columns), optional
307
+ For example, (3, 5) will display the subplots
308
+ using 3 rows and 5 columns, starting from the top-left.
309
+ return_type : {'axes', 'dict', 'both'} or None, default 'axes'
310
+ The kind of object to return. The default is ``axes``.
311
+
312
+ * 'axes' returns the matplotlib axes the boxplot is drawn on.
313
+ * 'dict' returns a dictionary whose values are the matplotlib
314
+ Lines of the boxplot.
315
+ * 'both' returns a namedtuple with the axes and dict.
316
+ * when grouping with ``by``, a Series mapping columns to
317
+ ``return_type`` is returned.
318
+
319
+ If ``return_type`` is `None`, a NumPy array
320
+ of axes with the same shape as ``layout`` is returned.
321
+ %(backend)s\
322
+
323
+ **kwargs
324
+ All other plotting keyword arguments to be passed to
325
+ :func:`matplotlib.pyplot.boxplot`.
326
+
327
+ Returns
328
+ -------
329
+ result
330
+ See Notes.
331
+
332
+ See Also
333
+ --------
334
+ pandas.Series.plot.hist: Make a histogram.
335
+ matplotlib.pyplot.boxplot : Matplotlib equivalent plot.
336
+
337
+ Notes
338
+ -----
339
+ The return type depends on the `return_type` parameter:
340
+
341
+ * 'axes' : object of class matplotlib.axes.Axes
342
+ * 'dict' : dict of matplotlib.lines.Line2D objects
343
+ * 'both' : a namedtuple with structure (ax, lines)
344
+
345
+ For data grouped with ``by``, return a Series of the above or a numpy
346
+ array:
347
+
348
+ * :class:`~pandas.Series`
349
+ * :class:`~numpy.array` (for ``return_type = None``)
350
+
351
+ Use ``return_type='dict'`` when you want to tweak the appearance
352
+ of the lines after plotting. In this case a dict containing the Lines
353
+ making up the boxes, caps, fliers, medians, and whiskers is returned.
354
+
355
+ Examples
356
+ --------
357
+
358
+ Boxplots can be created for every column in the dataframe
359
+ by ``df.boxplot()`` or indicating the columns to be used:
360
+
361
+ .. plot::
362
+ :context: close-figs
363
+
364
+ >>> np.random.seed(1234)
365
+ >>> df = pd.DataFrame(np.random.randn(10, 4),
366
+ ... columns=['Col1', 'Col2', 'Col3', 'Col4'])
367
+ >>> boxplot = df.boxplot(column=['Col1', 'Col2', 'Col3']) # doctest: +SKIP
368
+
369
+ Boxplots of variables distributions grouped by the values of a third
370
+ variable can be created using the option ``by``. For instance:
371
+
372
+ .. plot::
373
+ :context: close-figs
374
+
375
+ >>> df = pd.DataFrame(np.random.randn(10, 2),
376
+ ... columns=['Col1', 'Col2'])
377
+ >>> df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A',
378
+ ... 'B', 'B', 'B', 'B', 'B'])
379
+ >>> boxplot = df.boxplot(by='X')
380
+
381
+ A list of strings (i.e. ``['X', 'Y']``) can be passed to boxplot
382
+ in order to group the data by combination of the variables in the x-axis:
383
+
384
+ .. plot::
385
+ :context: close-figs
386
+
387
+ >>> df = pd.DataFrame(np.random.randn(10, 3),
388
+ ... columns=['Col1', 'Col2', 'Col3'])
389
+ >>> df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A',
390
+ ... 'B', 'B', 'B', 'B', 'B'])
391
+ >>> df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A',
392
+ ... 'B', 'A', 'B', 'A', 'B'])
393
+ >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'])
394
+
395
+ The layout of boxplot can be adjusted giving a tuple to ``layout``:
396
+
397
+ .. plot::
398
+ :context: close-figs
399
+
400
+ >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X',
401
+ ... layout=(2, 1))
402
+
403
+ Additional formatting can be done to the boxplot, like suppressing the grid
404
+ (``grid=False``), rotating the labels in the x-axis (i.e. ``rot=45``)
405
+ or changing the fontsize (i.e. ``fontsize=15``):
406
+
407
+ .. plot::
408
+ :context: close-figs
409
+
410
+ >>> boxplot = df.boxplot(grid=False, rot=45, fontsize=15) # doctest: +SKIP
411
+
412
+ The parameter ``return_type`` can be used to select the type of element
413
+ returned by `boxplot`. When ``return_type='axes'`` is selected,
414
+ the matplotlib axes on which the boxplot is drawn are returned:
415
+
416
+ >>> boxplot = df.boxplot(column=['Col1', 'Col2'], return_type='axes')
417
+ >>> type(boxplot)
418
+ <class 'matplotlib.axes._axes.Axes'>
419
+
420
+ When grouping with ``by``, a Series mapping columns to ``return_type``
421
+ is returned:
422
+
423
+ >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X',
424
+ ... return_type='axes')
425
+ >>> type(boxplot)
426
+ <class 'pandas.core.series.Series'>
427
+
428
+ If ``return_type`` is `None`, a NumPy array of axes with the same shape
429
+ as ``layout`` is returned:
430
+
431
+ >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X',
432
+ ... return_type=None)
433
+ >>> type(boxplot)
434
+ <class 'numpy.ndarray'>
435
+ """
436
+
437
+ _backend_doc = """\
438
+ backend : str, default None
439
+ Backend to use instead of the backend specified in the option
440
+ ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to
441
+ specify the ``plotting.backend`` for the whole session, set
442
+ ``pd.options.plotting.backend``.
443
+ """
444
+
445
+
446
+ _bar_or_line_doc = """
447
+ Parameters
448
+ ----------
449
+ x : label or position, optional
450
+ Allows plotting of one column versus another. If not specified,
451
+ the index of the DataFrame is used.
452
+ y : label or position, optional
453
+ Allows plotting of one column versus another. If not specified,
454
+ all numerical columns are used.
455
+ color : str, array-like, or dict, optional
456
+ The color for each of the DataFrame's columns. Possible values are:
457
+
458
+ - A single color string referred to by name, RGB or RGBA code,
459
+ for instance 'red' or '#a98d19'.
460
+
461
+ - A sequence of color strings referred to by name, RGB or RGBA
462
+ code, which will be used for each column recursively. For
463
+ instance ['green','yellow'] each column's %(kind)s will be filled in
464
+ green or yellow, alternatively. If there is only a single column to
465
+ be plotted, then only the first color from the color list will be
466
+ used.
467
+
468
+ - A dict of the form {column name : color}, so that each column will be
469
+ colored accordingly. For example, if your columns are called `a` and
470
+ `b`, then passing {'a': 'green', 'b': 'red'} will color %(kind)ss for
471
+ column `a` in green and %(kind)ss for column `b` in red.
472
+
473
+ **kwargs
474
+ Additional keyword arguments are documented in
475
+ :meth:`DataFrame.plot`.
476
+
477
+ Returns
478
+ -------
479
+ matplotlib.axes.Axes or np.ndarray of them
480
+ An ndarray is returned with one :class:`matplotlib.axes.Axes`
481
+ per column when ``subplots=True``.
482
+ """
483
+
484
+
485
+ @Substitution(data="data : DataFrame\n The data to visualize.\n", backend="")
486
+ @Appender(_boxplot_doc)
487
+ def boxplot(
488
+ data: DataFrame,
489
+ column: str | list[str] | None = None,
490
+ by: str | list[str] | None = None,
491
+ ax: Axes | None = None,
492
+ fontsize: float | str | None = None,
493
+ rot: int = 0,
494
+ grid: bool = True,
495
+ figsize: tuple[float, float] | None = None,
496
+ layout: tuple[int, int] | None = None,
497
+ return_type: str | None = None,
498
+ **kwargs,
499
+ ):
500
+ plot_backend = _get_plot_backend("matplotlib")
501
+ return plot_backend.boxplot(
502
+ data,
503
+ column=column,
504
+ by=by,
505
+ ax=ax,
506
+ fontsize=fontsize,
507
+ rot=rot,
508
+ grid=grid,
509
+ figsize=figsize,
510
+ layout=layout,
511
+ return_type=return_type,
512
+ **kwargs,
513
+ )
514
+
515
+
516
+ @Substitution(data="", backend=_backend_doc)
517
+ @Appender(_boxplot_doc)
518
+ def boxplot_frame(
519
+ self: DataFrame,
520
+ column=None,
521
+ by=None,
522
+ ax=None,
523
+ fontsize: int | None = None,
524
+ rot: int = 0,
525
+ grid: bool = True,
526
+ figsize: tuple[float, float] | None = None,
527
+ layout=None,
528
+ return_type=None,
529
+ backend=None,
530
+ **kwargs,
531
+ ):
532
+ plot_backend = _get_plot_backend(backend)
533
+ return plot_backend.boxplot_frame(
534
+ self,
535
+ column=column,
536
+ by=by,
537
+ ax=ax,
538
+ fontsize=fontsize,
539
+ rot=rot,
540
+ grid=grid,
541
+ figsize=figsize,
542
+ layout=layout,
543
+ return_type=return_type,
544
+ **kwargs,
545
+ )
546
+
547
+
548
+ def boxplot_frame_groupby(
549
+ grouped: DataFrameGroupBy,
550
+ subplots: bool = True,
551
+ column=None,
552
+ fontsize: int | None = None,
553
+ rot: int = 0,
554
+ grid: bool = True,
555
+ ax=None,
556
+ figsize: tuple[float, float] | None = None,
557
+ layout=None,
558
+ sharex: bool = False,
559
+ sharey: bool = True,
560
+ backend=None,
561
+ **kwargs,
562
+ ):
563
+ """
564
+ Make box plots from DataFrameGroupBy data.
565
+
566
+ Parameters
567
+ ----------
568
+ grouped : Grouped DataFrame
569
+ subplots : bool
570
+ * ``False`` - no subplots will be used
571
+ * ``True`` - create a subplot for each group.
572
+
573
+ column : column name or list of names, or vector
574
+ Can be any valid input to groupby.
575
+ fontsize : float or str
576
+ rot : label rotation angle
577
+ grid : Setting this to True will show the grid
578
+ ax : Matplotlib axis object, default None
579
+ figsize : A tuple (width, height) in inches
580
+ layout : tuple (optional)
581
+ The layout of the plot: (rows, columns).
582
+ sharex : bool, default False
583
+ Whether x-axes will be shared among subplots.
584
+ sharey : bool, default True
585
+ Whether y-axes will be shared among subplots.
586
+ backend : str, default None
587
+ Backend to use instead of the backend specified in the option
588
+ ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to
589
+ specify the ``plotting.backend`` for the whole session, set
590
+ ``pd.options.plotting.backend``.
591
+ **kwargs
592
+ All other plotting keyword arguments to be passed to
593
+ matplotlib's boxplot function.
594
+
595
+ Returns
596
+ -------
597
+ dict of key/value = group key/DataFrame.boxplot return value
598
+ or DataFrame.boxplot return value in case subplots=figures=False
599
+
600
+ Examples
601
+ --------
602
+ You can create boxplots for grouped data and show them as separate subplots:
603
+
604
+ .. plot::
605
+ :context: close-figs
606
+
607
+ >>> import itertools
608
+ >>> tuples = [t for t in itertools.product(range(1000), range(4))]
609
+ >>> index = pd.MultiIndex.from_tuples(tuples, names=['lvl0', 'lvl1'])
610
+ >>> data = np.random.randn(len(index), 4)
611
+ >>> df = pd.DataFrame(data, columns=list('ABCD'), index=index)
612
+ >>> grouped = df.groupby(level='lvl1')
613
+ >>> grouped.boxplot(rot=45, fontsize=12, figsize=(8, 10)) # doctest: +SKIP
614
+
615
+ The ``subplots=False`` option shows the boxplots in a single figure.
616
+
617
+ .. plot::
618
+ :context: close-figs
619
+
620
+ >>> grouped.boxplot(subplots=False, rot=45, fontsize=12) # doctest: +SKIP
621
+ """
622
+ plot_backend = _get_plot_backend(backend)
623
+ return plot_backend.boxplot_frame_groupby(
624
+ grouped,
625
+ subplots=subplots,
626
+ column=column,
627
+ fontsize=fontsize,
628
+ rot=rot,
629
+ grid=grid,
630
+ ax=ax,
631
+ figsize=figsize,
632
+ layout=layout,
633
+ sharex=sharex,
634
+ sharey=sharey,
635
+ **kwargs,
636
+ )
637
+
638
+
639
+ class PlotAccessor(PandasObject):
640
+ """
641
+ Make plots of Series or DataFrame.
642
+
643
+ Uses the backend specified by the
644
+ option ``plotting.backend``. By default, matplotlib is used.
645
+
646
+ Parameters
647
+ ----------
648
+ data : Series or DataFrame
649
+ The object for which the method is called.
650
+ x : label or position, default None
651
+ Only used if data is a DataFrame.
652
+ y : label, position or list of label, positions, default None
653
+ Allows plotting of one column versus another. Only used if data is a
654
+ DataFrame.
655
+ kind : str
656
+ The kind of plot to produce:
657
+
658
+ - 'line' : line plot (default)
659
+ - 'bar' : vertical bar plot
660
+ - 'barh' : horizontal bar plot
661
+ - 'hist' : histogram
662
+ - 'box' : boxplot
663
+ - 'kde' : Kernel Density Estimation plot
664
+ - 'density' : same as 'kde'
665
+ - 'area' : area plot
666
+ - 'pie' : pie plot
667
+ - 'scatter' : scatter plot (DataFrame only)
668
+ - 'hexbin' : hexbin plot (DataFrame only)
669
+ ax : matplotlib axes object, default None
670
+ An axes of the current figure.
671
+ subplots : bool or sequence of iterables, default False
672
+ Whether to group columns into subplots:
673
+
674
+ - ``False`` : No subplots will be used
675
+ - ``True`` : Make separate subplots for each column.
676
+ - sequence of iterables of column labels: Create a subplot for each
677
+ group of columns. For example `[('a', 'c'), ('b', 'd')]` will
678
+ create 2 subplots: one with columns 'a' and 'c', and one
679
+ with columns 'b' and 'd'. Remaining columns that aren't specified
680
+ will be plotted in additional subplots (one per column).
681
+
682
+ .. versionadded:: 1.5.0
683
+
684
+ sharex : bool, default True if ax is None else False
685
+ In case ``subplots=True``, share x axis and set some x axis labels
686
+ to invisible; defaults to True if ax is None otherwise False if
687
+ an ax is passed in; Be aware, that passing in both an ax and
688
+ ``sharex=True`` will alter all x axis labels for all axis in a figure.
689
+ sharey : bool, default False
690
+ In case ``subplots=True``, share y axis and set some y axis labels to invisible.
691
+ layout : tuple, optional
692
+ (rows, columns) for the layout of subplots.
693
+ figsize : a tuple (width, height) in inches
694
+ Size of a figure object.
695
+ use_index : bool, default True
696
+ Use index as ticks for x axis.
697
+ title : str or list
698
+ Title to use for the plot. If a string is passed, print the string
699
+ at the top of the figure. If a list is passed and `subplots` is
700
+ True, print each item in the list above the corresponding subplot.
701
+ grid : bool, default None (matlab style default)
702
+ Axis grid lines.
703
+ legend : bool or {'reverse'}
704
+ Place legend on axis subplots.
705
+ style : list or dict
706
+ The matplotlib line style per column.
707
+ logx : bool or 'sym', default False
708
+ Use log scaling or symlog scaling on x axis.
709
+
710
+ logy : bool or 'sym' default False
711
+ Use log scaling or symlog scaling on y axis.
712
+
713
+ loglog : bool or 'sym', default False
714
+ Use log scaling or symlog scaling on both x and y axes.
715
+
716
+ xticks : sequence
717
+ Values to use for the xticks.
718
+ yticks : sequence
719
+ Values to use for the yticks.
720
+ xlim : 2-tuple/list
721
+ Set the x limits of the current axes.
722
+ ylim : 2-tuple/list
723
+ Set the y limits of the current axes.
724
+ xlabel : label, optional
725
+ Name to use for the xlabel on x-axis. Default uses index name as xlabel, or the
726
+ x-column name for planar plots.
727
+
728
+ .. versionchanged:: 2.0.0
729
+
730
+ Now applicable to histograms.
731
+
732
+ ylabel : label, optional
733
+ Name to use for the ylabel on y-axis. Default will show no ylabel, or the
734
+ y-column name for planar plots.
735
+
736
+ .. versionchanged:: 2.0.0
737
+
738
+ Now applicable to histograms.
739
+
740
+ rot : float, default None
741
+ Rotation for ticks (xticks for vertical, yticks for horizontal
742
+ plots).
743
+ fontsize : float, default None
744
+ Font size for xticks and yticks.
745
+ colormap : str or matplotlib colormap object, default None
746
+ Colormap to select colors from. If string, load colormap with that
747
+ name from matplotlib.
748
+ colorbar : bool, optional
749
+ If True, plot colorbar (only relevant for 'scatter' and 'hexbin'
750
+ plots).
751
+ position : float
752
+ Specify relative alignments for bar plot layout.
753
+ From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5
754
+ (center).
755
+ table : bool, Series or DataFrame, default False
756
+ If True, draw a table using the data in the DataFrame and the data
757
+ will be transposed to meet matplotlib's default layout.
758
+ If a Series or DataFrame is passed, use passed data to draw a
759
+ table.
760
+ yerr : DataFrame, Series, array-like, dict and str
761
+ See :ref:`Plotting with Error Bars <visualization.errorbars>` for
762
+ detail.
763
+ xerr : DataFrame, Series, array-like, dict and str
764
+ Equivalent to yerr.
765
+ stacked : bool, default False in line and bar plots, and True in area plot
766
+ If True, create stacked plot.
767
+ secondary_y : bool or sequence, default False
768
+ Whether to plot on the secondary y-axis if a list/tuple, which
769
+ columns to plot on secondary y-axis.
770
+ mark_right : bool, default True
771
+ When using a secondary_y axis, automatically mark the column
772
+ labels with "(right)" in the legend.
773
+ include_bool : bool, default is False
774
+ If True, boolean values can be plotted.
775
+ backend : str, default None
776
+ Backend to use instead of the backend specified in the option
777
+ ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to
778
+ specify the ``plotting.backend`` for the whole session, set
779
+ ``pd.options.plotting.backend``.
780
+ **kwargs
781
+ Options to pass to matplotlib plotting method.
782
+
783
+ Returns
784
+ -------
785
+ :class:`matplotlib.axes.Axes` or numpy.ndarray of them
786
+ If the backend is not the default matplotlib one, the return value
787
+ will be the object returned by the backend.
788
+
789
+ Notes
790
+ -----
791
+ - See matplotlib documentation online for more on this subject
792
+ - If `kind` = 'bar' or 'barh', you can specify relative alignments
793
+ for bar plot layout by `position` keyword.
794
+ From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5
795
+ (center)
796
+
797
+ Examples
798
+ --------
799
+ For Series:
800
+
801
+ .. plot::
802
+ :context: close-figs
803
+
804
+ >>> ser = pd.Series([1, 2, 3, 3])
805
+ >>> plot = ser.plot(kind='hist', title="My plot")
806
+
807
+ For DataFrame:
808
+
809
+ .. plot::
810
+ :context: close-figs
811
+
812
+ >>> df = pd.DataFrame({'length': [1.5, 0.5, 1.2, 0.9, 3],
813
+ ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1]},
814
+ ... index=['pig', 'rabbit', 'duck', 'chicken', 'horse'])
815
+ >>> plot = df.plot(title="DataFrame Plot")
816
+
817
+ For SeriesGroupBy:
818
+
819
+ .. plot::
820
+ :context: close-figs
821
+
822
+ >>> lst = [-1, -2, -3, 1, 2, 3]
823
+ >>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst)
824
+ >>> plot = ser.groupby(lambda x: x > 0).plot(title="SeriesGroupBy Plot")
825
+
826
+ For DataFrameGroupBy:
827
+
828
+ .. plot::
829
+ :context: close-figs
830
+
831
+ >>> df = pd.DataFrame({"col1" : [1, 2, 3, 4],
832
+ ... "col2" : ["A", "B", "A", "B"]})
833
+ >>> plot = df.groupby("col2").plot(kind="bar", title="DataFrameGroupBy Plot")
834
+ """
835
+
836
+ _common_kinds = ("line", "bar", "barh", "kde", "density", "area", "hist", "box")
837
+ _series_kinds = ("pie",)
838
+ _dataframe_kinds = ("scatter", "hexbin")
839
+ _kind_aliases = {"density": "kde"}
840
+ _all_kinds = _common_kinds + _series_kinds + _dataframe_kinds
841
+
842
+ def __init__(self, data: Series | DataFrame) -> None:
843
+ self._parent = data
844
+
845
+ @staticmethod
846
+ def _get_call_args(backend_name: str, data: Series | DataFrame, args, kwargs):
847
+ """
848
+ This function makes calls to this accessor `__call__` method compatible
849
+ with the previous `SeriesPlotMethods.__call__` and
850
+ `DataFramePlotMethods.__call__`. Those had slightly different
851
+ signatures, since `DataFramePlotMethods` accepted `x` and `y`
852
+ parameters.
853
+ """
854
+ if isinstance(data, ABCSeries):
855
+ arg_def = [
856
+ ("kind", "line"),
857
+ ("ax", None),
858
+ ("figsize", None),
859
+ ("use_index", True),
860
+ ("title", None),
861
+ ("grid", None),
862
+ ("legend", False),
863
+ ("style", None),
864
+ ("logx", False),
865
+ ("logy", False),
866
+ ("loglog", False),
867
+ ("xticks", None),
868
+ ("yticks", None),
869
+ ("xlim", None),
870
+ ("ylim", None),
871
+ ("rot", None),
872
+ ("fontsize", None),
873
+ ("colormap", None),
874
+ ("table", False),
875
+ ("yerr", None),
876
+ ("xerr", None),
877
+ ("label", None),
878
+ ("secondary_y", False),
879
+ ("xlabel", None),
880
+ ("ylabel", None),
881
+ ]
882
+ elif isinstance(data, ABCDataFrame):
883
+ arg_def = [
884
+ ("x", None),
885
+ ("y", None),
886
+ ("kind", "line"),
887
+ ("ax", None),
888
+ ("subplots", False),
889
+ ("sharex", None),
890
+ ("sharey", False),
891
+ ("layout", None),
892
+ ("figsize", None),
893
+ ("use_index", True),
894
+ ("title", None),
895
+ ("grid", None),
896
+ ("legend", True),
897
+ ("style", None),
898
+ ("logx", False),
899
+ ("logy", False),
900
+ ("loglog", False),
901
+ ("xticks", None),
902
+ ("yticks", None),
903
+ ("xlim", None),
904
+ ("ylim", None),
905
+ ("rot", None),
906
+ ("fontsize", None),
907
+ ("colormap", None),
908
+ ("table", False),
909
+ ("yerr", None),
910
+ ("xerr", None),
911
+ ("secondary_y", False),
912
+ ("xlabel", None),
913
+ ("ylabel", None),
914
+ ]
915
+ else:
916
+ raise TypeError(
917
+ f"Called plot accessor for type {type(data).__name__}, "
918
+ "expected Series or DataFrame"
919
+ )
920
+
921
+ if args and isinstance(data, ABCSeries):
922
+ positional_args = str(args)[1:-1]
923
+ keyword_args = ", ".join(
924
+ [f"{name}={repr(value)}" for (name, _), value in zip(arg_def, args)]
925
+ )
926
+ msg = (
927
+ "`Series.plot()` should not be called with positional "
928
+ "arguments, only keyword arguments. The order of "
929
+ "positional arguments will change in the future. "
930
+ f"Use `Series.plot({keyword_args})` instead of "
931
+ f"`Series.plot({positional_args})`."
932
+ )
933
+ raise TypeError(msg)
934
+
935
+ pos_args = {name: value for (name, _), value in zip(arg_def, args)}
936
+ if backend_name == "pandas.plotting._matplotlib":
937
+ kwargs = dict(arg_def, **pos_args, **kwargs)
938
+ else:
939
+ kwargs = dict(pos_args, **kwargs)
940
+
941
+ x = kwargs.pop("x", None)
942
+ y = kwargs.pop("y", None)
943
+ kind = kwargs.pop("kind", "line")
944
+ return x, y, kind, kwargs
945
+
946
+ def __call__(self, *args, **kwargs):
947
+ plot_backend = _get_plot_backend(kwargs.pop("backend", None))
948
+
949
+ x, y, kind, kwargs = self._get_call_args(
950
+ plot_backend.__name__, self._parent, args, kwargs
951
+ )
952
+
953
+ kind = self._kind_aliases.get(kind, kind)
954
+
955
+ # when using another backend, get out of the way
956
+ if plot_backend.__name__ != "pandas.plotting._matplotlib":
957
+ return plot_backend.plot(self._parent, x=x, y=y, kind=kind, **kwargs)
958
+
959
+ if kind not in self._all_kinds:
960
+ raise ValueError(
961
+ f"{kind} is not a valid plot kind "
962
+ f"Valid plot kinds: {self._all_kinds}"
963
+ )
964
+
965
+ # The original data structured can be transformed before passed to the
966
+ # backend. For example, for DataFrame is common to set the index as the
967
+ # `x` parameter, and return a Series with the parameter `y` as values.
968
+ data = self._parent.copy()
969
+
970
+ if isinstance(data, ABCSeries):
971
+ kwargs["reuse_plot"] = True
972
+
973
+ if kind in self._dataframe_kinds:
974
+ if isinstance(data, ABCDataFrame):
975
+ return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs)
976
+ else:
977
+ raise ValueError(f"plot kind {kind} can only be used for data frames")
978
+ elif kind in self._series_kinds:
979
+ if isinstance(data, ABCDataFrame):
980
+ if y is None and kwargs.get("subplots") is False:
981
+ raise ValueError(
982
+ f"{kind} requires either y column or 'subplots=True'"
983
+ )
984
+ if y is not None:
985
+ if is_integer(y) and not data.columns._holds_integer():
986
+ y = data.columns[y]
987
+ # converted to series actually. copy to not modify
988
+ data = data[y].copy()
989
+ data.index.name = y
990
+ elif isinstance(data, ABCDataFrame):
991
+ data_cols = data.columns
992
+ if x is not None:
993
+ if is_integer(x) and not data.columns._holds_integer():
994
+ x = data_cols[x]
995
+ elif not isinstance(data[x], ABCSeries):
996
+ raise ValueError("x must be a label or position")
997
+ data = data.set_index(x)
998
+ if y is not None:
999
+ # check if we have y as int or list of ints
1000
+ int_ylist = is_list_like(y) and all(is_integer(c) for c in y)
1001
+ int_y_arg = is_integer(y) or int_ylist
1002
+ if int_y_arg and not data.columns._holds_integer():
1003
+ y = data_cols[y]
1004
+
1005
+ label_kw = kwargs["label"] if "label" in kwargs else False
1006
+ for kw in ["xerr", "yerr"]:
1007
+ if kw in kwargs and (
1008
+ isinstance(kwargs[kw], str) or is_integer(kwargs[kw])
1009
+ ):
1010
+ try:
1011
+ kwargs[kw] = data[kwargs[kw]]
1012
+ except (IndexError, KeyError, TypeError):
1013
+ pass
1014
+
1015
+ # don't overwrite
1016
+ data = data[y].copy()
1017
+
1018
+ if isinstance(data, ABCSeries):
1019
+ label_name = label_kw or y
1020
+ data.name = label_name
1021
+ else:
1022
+ match = is_list_like(label_kw) and len(label_kw) == len(y)
1023
+ if label_kw and not match:
1024
+ raise ValueError(
1025
+ "label should be list-like and same length as y"
1026
+ )
1027
+ label_name = label_kw or data.columns
1028
+ data.columns = label_name
1029
+
1030
+ return plot_backend.plot(data, kind=kind, **kwargs)
1031
+
1032
+ __call__.__doc__ = __doc__
1033
+
1034
+ @Appender(
1035
+ """
1036
+ See Also
1037
+ --------
1038
+ matplotlib.pyplot.plot : Plot y versus x as lines and/or markers.
1039
+
1040
+ Examples
1041
+ --------
1042
+
1043
+ .. plot::
1044
+ :context: close-figs
1045
+
1046
+ >>> s = pd.Series([1, 3, 2])
1047
+ >>> s.plot.line() # doctest: +SKIP
1048
+
1049
+ .. plot::
1050
+ :context: close-figs
1051
+
1052
+ The following example shows the populations for some animals
1053
+ over the years.
1054
+
1055
+ >>> df = pd.DataFrame({
1056
+ ... 'pig': [20, 18, 489, 675, 1776],
1057
+ ... 'horse': [4, 25, 281, 600, 1900]
1058
+ ... }, index=[1990, 1997, 2003, 2009, 2014])
1059
+ >>> lines = df.plot.line()
1060
+
1061
+ .. plot::
1062
+ :context: close-figs
1063
+
1064
+ An example with subplots, so an array of axes is returned.
1065
+
1066
+ >>> axes = df.plot.line(subplots=True)
1067
+ >>> type(axes)
1068
+ <class 'numpy.ndarray'>
1069
+
1070
+ .. plot::
1071
+ :context: close-figs
1072
+
1073
+ Let's repeat the same example, but specifying colors for
1074
+ each column (in this case, for each animal).
1075
+
1076
+ >>> axes = df.plot.line(
1077
+ ... subplots=True, color={"pig": "pink", "horse": "#742802"}
1078
+ ... )
1079
+
1080
+ .. plot::
1081
+ :context: close-figs
1082
+
1083
+ The following example shows the relationship between both
1084
+ populations.
1085
+
1086
+ >>> lines = df.plot.line(x='pig', y='horse')
1087
+ """
1088
+ )
1089
+ @Substitution(kind="line")
1090
+ @Appender(_bar_or_line_doc)
1091
+ def line(
1092
+ self, x: Hashable | None = None, y: Hashable | None = None, **kwargs
1093
+ ) -> PlotAccessor:
1094
+ """
1095
+ Plot Series or DataFrame as lines.
1096
+
1097
+ This function is useful to plot lines using DataFrame's values
1098
+ as coordinates.
1099
+ """
1100
+ return self(kind="line", x=x, y=y, **kwargs)
1101
+
1102
+ @Appender(
1103
+ """
1104
+ See Also
1105
+ --------
1106
+ DataFrame.plot.barh : Horizontal bar plot.
1107
+ DataFrame.plot : Make plots of a DataFrame.
1108
+ matplotlib.pyplot.bar : Make a bar plot with matplotlib.
1109
+
1110
+ Examples
1111
+ --------
1112
+ Basic plot.
1113
+
1114
+ .. plot::
1115
+ :context: close-figs
1116
+
1117
+ >>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
1118
+ >>> ax = df.plot.bar(x='lab', y='val', rot=0)
1119
+
1120
+ Plot a whole dataframe to a bar plot. Each column is assigned a
1121
+ distinct color, and each row is nested in a group along the
1122
+ horizontal axis.
1123
+
1124
+ .. plot::
1125
+ :context: close-figs
1126
+
1127
+ >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
1128
+ >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
1129
+ >>> index = ['snail', 'pig', 'elephant',
1130
+ ... 'rabbit', 'giraffe', 'coyote', 'horse']
1131
+ >>> df = pd.DataFrame({'speed': speed,
1132
+ ... 'lifespan': lifespan}, index=index)
1133
+ >>> ax = df.plot.bar(rot=0)
1134
+
1135
+ Plot stacked bar charts for the DataFrame
1136
+
1137
+ .. plot::
1138
+ :context: close-figs
1139
+
1140
+ >>> ax = df.plot.bar(stacked=True)
1141
+
1142
+ Instead of nesting, the figure can be split by column with
1143
+ ``subplots=True``. In this case, a :class:`numpy.ndarray` of
1144
+ :class:`matplotlib.axes.Axes` are returned.
1145
+
1146
+ .. plot::
1147
+ :context: close-figs
1148
+
1149
+ >>> axes = df.plot.bar(rot=0, subplots=True)
1150
+ >>> axes[1].legend(loc=2) # doctest: +SKIP
1151
+
1152
+ If you don't like the default colours, you can specify how you'd
1153
+ like each column to be colored.
1154
+
1155
+ .. plot::
1156
+ :context: close-figs
1157
+
1158
+ >>> axes = df.plot.bar(
1159
+ ... rot=0, subplots=True, color={"speed": "red", "lifespan": "green"}
1160
+ ... )
1161
+ >>> axes[1].legend(loc=2) # doctest: +SKIP
1162
+
1163
+ Plot a single column.
1164
+
1165
+ .. plot::
1166
+ :context: close-figs
1167
+
1168
+ >>> ax = df.plot.bar(y='speed', rot=0)
1169
+
1170
+ Plot only selected categories for the DataFrame.
1171
+
1172
+ .. plot::
1173
+ :context: close-figs
1174
+
1175
+ >>> ax = df.plot.bar(x='lifespan', rot=0)
1176
+ """
1177
+ )
1178
+ @Substitution(kind="bar")
1179
+ @Appender(_bar_or_line_doc)
1180
+ def bar( # pylint: disable=disallowed-name
1181
+ self, x: Hashable | None = None, y: Hashable | None = None, **kwargs
1182
+ ) -> PlotAccessor:
1183
+ """
1184
+ Vertical bar plot.
1185
+
1186
+ A bar plot is a plot that presents categorical data with
1187
+ rectangular bars with lengths proportional to the values that they
1188
+ represent. A bar plot shows comparisons among discrete categories. One
1189
+ axis of the plot shows the specific categories being compared, and the
1190
+ other axis represents a measured value.
1191
+ """
1192
+ return self(kind="bar", x=x, y=y, **kwargs)
1193
+
1194
+ @Appender(
1195
+ """
1196
+ See Also
1197
+ --------
1198
+ DataFrame.plot.bar: Vertical bar plot.
1199
+ DataFrame.plot : Make plots of DataFrame using matplotlib.
1200
+ matplotlib.axes.Axes.bar : Plot a vertical bar plot using matplotlib.
1201
+
1202
+ Examples
1203
+ --------
1204
+ Basic example
1205
+
1206
+ .. plot::
1207
+ :context: close-figs
1208
+
1209
+ >>> df = pd.DataFrame({'lab': ['A', 'B', 'C'], 'val': [10, 30, 20]})
1210
+ >>> ax = df.plot.barh(x='lab', y='val')
1211
+
1212
+ Plot a whole DataFrame to a horizontal bar plot
1213
+
1214
+ .. plot::
1215
+ :context: close-figs
1216
+
1217
+ >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
1218
+ >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
1219
+ >>> index = ['snail', 'pig', 'elephant',
1220
+ ... 'rabbit', 'giraffe', 'coyote', 'horse']
1221
+ >>> df = pd.DataFrame({'speed': speed,
1222
+ ... 'lifespan': lifespan}, index=index)
1223
+ >>> ax = df.plot.barh()
1224
+
1225
+ Plot stacked barh charts for the DataFrame
1226
+
1227
+ .. plot::
1228
+ :context: close-figs
1229
+
1230
+ >>> ax = df.plot.barh(stacked=True)
1231
+
1232
+ We can specify colors for each column
1233
+
1234
+ .. plot::
1235
+ :context: close-figs
1236
+
1237
+ >>> ax = df.plot.barh(color={"speed": "red", "lifespan": "green"})
1238
+
1239
+ Plot a column of the DataFrame to a horizontal bar plot
1240
+
1241
+ .. plot::
1242
+ :context: close-figs
1243
+
1244
+ >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
1245
+ >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
1246
+ >>> index = ['snail', 'pig', 'elephant',
1247
+ ... 'rabbit', 'giraffe', 'coyote', 'horse']
1248
+ >>> df = pd.DataFrame({'speed': speed,
1249
+ ... 'lifespan': lifespan}, index=index)
1250
+ >>> ax = df.plot.barh(y='speed')
1251
+
1252
+ Plot DataFrame versus the desired column
1253
+
1254
+ .. plot::
1255
+ :context: close-figs
1256
+
1257
+ >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
1258
+ >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
1259
+ >>> index = ['snail', 'pig', 'elephant',
1260
+ ... 'rabbit', 'giraffe', 'coyote', 'horse']
1261
+ >>> df = pd.DataFrame({'speed': speed,
1262
+ ... 'lifespan': lifespan}, index=index)
1263
+ >>> ax = df.plot.barh(x='lifespan')
1264
+ """
1265
+ )
1266
+ @Substitution(kind="bar")
1267
+ @Appender(_bar_or_line_doc)
1268
+ def barh(
1269
+ self, x: Hashable | None = None, y: Hashable | None = None, **kwargs
1270
+ ) -> PlotAccessor:
1271
+ """
1272
+ Make a horizontal bar plot.
1273
+
1274
+ A horizontal bar plot is a plot that presents quantitative data with
1275
+ rectangular bars with lengths proportional to the values that they
1276
+ represent. A bar plot shows comparisons among discrete categories. One
1277
+ axis of the plot shows the specific categories being compared, and the
1278
+ other axis represents a measured value.
1279
+ """
1280
+ return self(kind="barh", x=x, y=y, **kwargs)
1281
+
1282
+ def box(self, by: IndexLabel | None = None, **kwargs) -> PlotAccessor:
1283
+ r"""
1284
+ Make a box plot of the DataFrame columns.
1285
+
1286
+ A box plot is a method for graphically depicting groups of numerical
1287
+ data through their quartiles.
1288
+ The box extends from the Q1 to Q3 quartile values of the data,
1289
+ with a line at the median (Q2). The whiskers extend from the edges
1290
+ of box to show the range of the data. The position of the whiskers
1291
+ is set by default to 1.5*IQR (IQR = Q3 - Q1) from the edges of the
1292
+ box. Outlier points are those past the end of the whiskers.
1293
+
1294
+ For further details see Wikipedia's
1295
+ entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`__.
1296
+
1297
+ A consideration when using this chart is that the box and the whiskers
1298
+ can overlap, which is very common when plotting small sets of data.
1299
+
1300
+ Parameters
1301
+ ----------
1302
+ by : str or sequence
1303
+ Column in the DataFrame to group by.
1304
+
1305
+ .. versionchanged:: 1.4.0
1306
+
1307
+ Previously, `by` is silently ignore and makes no groupings
1308
+
1309
+ **kwargs
1310
+ Additional keywords are documented in
1311
+ :meth:`DataFrame.plot`.
1312
+
1313
+ Returns
1314
+ -------
1315
+ :class:`matplotlib.axes.Axes` or numpy.ndarray of them
1316
+
1317
+ See Also
1318
+ --------
1319
+ DataFrame.boxplot: Another method to draw a box plot.
1320
+ Series.plot.box: Draw a box plot from a Series object.
1321
+ matplotlib.pyplot.boxplot: Draw a box plot in matplotlib.
1322
+
1323
+ Examples
1324
+ --------
1325
+ Draw a box plot from a DataFrame with four columns of randomly
1326
+ generated data.
1327
+
1328
+ .. plot::
1329
+ :context: close-figs
1330
+
1331
+ >>> data = np.random.randn(25, 4)
1332
+ >>> df = pd.DataFrame(data, columns=list('ABCD'))
1333
+ >>> ax = df.plot.box()
1334
+
1335
+ You can also generate groupings if you specify the `by` parameter (which
1336
+ can take a column name, or a list or tuple of column names):
1337
+
1338
+ .. versionchanged:: 1.4.0
1339
+
1340
+ .. plot::
1341
+ :context: close-figs
1342
+
1343
+ >>> age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85]
1344
+ >>> df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list})
1345
+ >>> ax = df.plot.box(column="age", by="gender", figsize=(10, 8))
1346
+ """
1347
+ return self(kind="box", by=by, **kwargs)
1348
+
1349
+ def hist(
1350
+ self, by: IndexLabel | None = None, bins: int = 10, **kwargs
1351
+ ) -> PlotAccessor:
1352
+ """
1353
+ Draw one histogram of the DataFrame's columns.
1354
+
1355
+ A histogram is a representation of the distribution of data.
1356
+ This function groups the values of all given Series in the DataFrame
1357
+ into bins and draws all bins in one :class:`matplotlib.axes.Axes`.
1358
+ This is useful when the DataFrame's Series are in a similar scale.
1359
+
1360
+ Parameters
1361
+ ----------
1362
+ by : str or sequence, optional
1363
+ Column in the DataFrame to group by.
1364
+
1365
+ .. versionchanged:: 1.4.0
1366
+
1367
+ Previously, `by` is silently ignore and makes no groupings
1368
+
1369
+ bins : int, default 10
1370
+ Number of histogram bins to be used.
1371
+ **kwargs
1372
+ Additional keyword arguments are documented in
1373
+ :meth:`DataFrame.plot`.
1374
+
1375
+ Returns
1376
+ -------
1377
+ class:`matplotlib.AxesSubplot`
1378
+ Return a histogram plot.
1379
+
1380
+ See Also
1381
+ --------
1382
+ DataFrame.hist : Draw histograms per DataFrame's Series.
1383
+ Series.hist : Draw a histogram with Series' data.
1384
+
1385
+ Examples
1386
+ --------
1387
+ When we roll a die 6000 times, we expect to get each value around 1000
1388
+ times. But when we roll two dice and sum the result, the distribution
1389
+ is going to be quite different. A histogram illustrates those
1390
+ distributions.
1391
+
1392
+ .. plot::
1393
+ :context: close-figs
1394
+
1395
+ >>> df = pd.DataFrame(np.random.randint(1, 7, 6000), columns=['one'])
1396
+ >>> df['two'] = df['one'] + np.random.randint(1, 7, 6000)
1397
+ >>> ax = df.plot.hist(bins=12, alpha=0.5)
1398
+
1399
+ A grouped histogram can be generated by providing the parameter `by` (which
1400
+ can be a column name, or a list of column names):
1401
+
1402
+ .. plot::
1403
+ :context: close-figs
1404
+
1405
+ >>> age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85]
1406
+ >>> df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list})
1407
+ >>> ax = df.plot.hist(column=["age"], by="gender", figsize=(10, 8))
1408
+ """
1409
+ return self(kind="hist", by=by, bins=bins, **kwargs)
1410
+
1411
+ def kde(
1412
+ self,
1413
+ bw_method: Literal["scott", "silverman"] | float | Callable | None = None,
1414
+ ind: np.ndarray | int | None = None,
1415
+ **kwargs,
1416
+ ) -> PlotAccessor:
1417
+ """
1418
+ Generate Kernel Density Estimate plot using Gaussian kernels.
1419
+
1420
+ In statistics, `kernel density estimation`_ (KDE) is a non-parametric
1421
+ way to estimate the probability density function (PDF) of a random
1422
+ variable. This function uses Gaussian kernels and includes automatic
1423
+ bandwidth determination.
1424
+
1425
+ .. _kernel density estimation:
1426
+ https://en.wikipedia.org/wiki/Kernel_density_estimation
1427
+
1428
+ Parameters
1429
+ ----------
1430
+ bw_method : str, scalar or callable, optional
1431
+ The method used to calculate the estimator bandwidth. This can be
1432
+ 'scott', 'silverman', a scalar constant or a callable.
1433
+ If None (default), 'scott' is used.
1434
+ See :class:`scipy.stats.gaussian_kde` for more information.
1435
+ ind : NumPy array or int, optional
1436
+ Evaluation points for the estimated PDF. If None (default),
1437
+ 1000 equally spaced points are used. If `ind` is a NumPy array, the
1438
+ KDE is evaluated at the points passed. If `ind` is an integer,
1439
+ `ind` number of equally spaced points are used.
1440
+ **kwargs
1441
+ Additional keyword arguments are documented in
1442
+ :meth:`DataFrame.plot`.
1443
+
1444
+ Returns
1445
+ -------
1446
+ matplotlib.axes.Axes or numpy.ndarray of them
1447
+
1448
+ See Also
1449
+ --------
1450
+ scipy.stats.gaussian_kde : Representation of a kernel-density
1451
+ estimate using Gaussian kernels. This is the function used
1452
+ internally to estimate the PDF.
1453
+
1454
+ Examples
1455
+ --------
1456
+ Given a Series of points randomly sampled from an unknown
1457
+ distribution, estimate its PDF using KDE with automatic
1458
+ bandwidth determination and plot the results, evaluating them at
1459
+ 1000 equally spaced points (default):
1460
+
1461
+ .. plot::
1462
+ :context: close-figs
1463
+
1464
+ >>> s = pd.Series([1, 2, 2.5, 3, 3.5, 4, 5])
1465
+ >>> ax = s.plot.kde()
1466
+
1467
+ A scalar bandwidth can be specified. Using a small bandwidth value can
1468
+ lead to over-fitting, while using a large bandwidth value may result
1469
+ in under-fitting:
1470
+
1471
+ .. plot::
1472
+ :context: close-figs
1473
+
1474
+ >>> ax = s.plot.kde(bw_method=0.3)
1475
+
1476
+ .. plot::
1477
+ :context: close-figs
1478
+
1479
+ >>> ax = s.plot.kde(bw_method=3)
1480
+
1481
+ Finally, the `ind` parameter determines the evaluation points for the
1482
+ plot of the estimated PDF:
1483
+
1484
+ .. plot::
1485
+ :context: close-figs
1486
+
1487
+ >>> ax = s.plot.kde(ind=[1, 2, 3, 4, 5])
1488
+
1489
+ For DataFrame, it works in the same way:
1490
+
1491
+ .. plot::
1492
+ :context: close-figs
1493
+
1494
+ >>> df = pd.DataFrame({
1495
+ ... 'x': [1, 2, 2.5, 3, 3.5, 4, 5],
1496
+ ... 'y': [4, 4, 4.5, 5, 5.5, 6, 6],
1497
+ ... })
1498
+ >>> ax = df.plot.kde()
1499
+
1500
+ A scalar bandwidth can be specified. Using a small bandwidth value can
1501
+ lead to over-fitting, while using a large bandwidth value may result
1502
+ in under-fitting:
1503
+
1504
+ .. plot::
1505
+ :context: close-figs
1506
+
1507
+ >>> ax = df.plot.kde(bw_method=0.3)
1508
+
1509
+ .. plot::
1510
+ :context: close-figs
1511
+
1512
+ >>> ax = df.plot.kde(bw_method=3)
1513
+
1514
+ Finally, the `ind` parameter determines the evaluation points for the
1515
+ plot of the estimated PDF:
1516
+
1517
+ .. plot::
1518
+ :context: close-figs
1519
+
1520
+ >>> ax = df.plot.kde(ind=[1, 2, 3, 4, 5, 6])
1521
+ """
1522
+ return self(kind="kde", bw_method=bw_method, ind=ind, **kwargs)
1523
+
1524
+ density = kde
1525
+
1526
+ def area(
1527
+ self,
1528
+ x: Hashable | None = None,
1529
+ y: Hashable | None = None,
1530
+ stacked: bool = True,
1531
+ **kwargs,
1532
+ ) -> PlotAccessor:
1533
+ """
1534
+ Draw a stacked area plot.
1535
+
1536
+ An area plot displays quantitative data visually.
1537
+ This function wraps the matplotlib area function.
1538
+
1539
+ Parameters
1540
+ ----------
1541
+ x : label or position, optional
1542
+ Coordinates for the X axis. By default uses the index.
1543
+ y : label or position, optional
1544
+ Column to plot. By default uses all columns.
1545
+ stacked : bool, default True
1546
+ Area plots are stacked by default. Set to False to create a
1547
+ unstacked plot.
1548
+ **kwargs
1549
+ Additional keyword arguments are documented in
1550
+ :meth:`DataFrame.plot`.
1551
+
1552
+ Returns
1553
+ -------
1554
+ matplotlib.axes.Axes or numpy.ndarray
1555
+ Area plot, or array of area plots if subplots is True.
1556
+
1557
+ See Also
1558
+ --------
1559
+ DataFrame.plot : Make plots of DataFrame using matplotlib / pylab.
1560
+
1561
+ Examples
1562
+ --------
1563
+ Draw an area plot based on basic business metrics:
1564
+
1565
+ .. plot::
1566
+ :context: close-figs
1567
+
1568
+ >>> df = pd.DataFrame({
1569
+ ... 'sales': [3, 2, 3, 9, 10, 6],
1570
+ ... 'signups': [5, 5, 6, 12, 14, 13],
1571
+ ... 'visits': [20, 42, 28, 62, 81, 50],
1572
+ ... }, index=pd.date_range(start='2018/01/01', end='2018/07/01',
1573
+ ... freq='ME'))
1574
+ >>> ax = df.plot.area()
1575
+
1576
+ Area plots are stacked by default. To produce an unstacked plot,
1577
+ pass ``stacked=False``:
1578
+
1579
+ .. plot::
1580
+ :context: close-figs
1581
+
1582
+ >>> ax = df.plot.area(stacked=False)
1583
+
1584
+ Draw an area plot for a single column:
1585
+
1586
+ .. plot::
1587
+ :context: close-figs
1588
+
1589
+ >>> ax = df.plot.area(y='sales')
1590
+
1591
+ Draw with a different `x`:
1592
+
1593
+ .. plot::
1594
+ :context: close-figs
1595
+
1596
+ >>> df = pd.DataFrame({
1597
+ ... 'sales': [3, 2, 3],
1598
+ ... 'visits': [20, 42, 28],
1599
+ ... 'day': [1, 2, 3],
1600
+ ... })
1601
+ >>> ax = df.plot.area(x='day')
1602
+ """
1603
+ return self(kind="area", x=x, y=y, stacked=stacked, **kwargs)
1604
+
1605
+ def pie(self, **kwargs) -> PlotAccessor:
1606
+ """
1607
+ Generate a pie plot.
1608
+
1609
+ A pie plot is a proportional representation of the numerical data in a
1610
+ column. This function wraps :meth:`matplotlib.pyplot.pie` for the
1611
+ specified column. If no column reference is passed and
1612
+ ``subplots=True`` a pie plot is drawn for each numerical column
1613
+ independently.
1614
+
1615
+ Parameters
1616
+ ----------
1617
+ y : int or label, optional
1618
+ Label or position of the column to plot.
1619
+ If not provided, ``subplots=True`` argument must be passed.
1620
+ **kwargs
1621
+ Keyword arguments to pass on to :meth:`DataFrame.plot`.
1622
+
1623
+ Returns
1624
+ -------
1625
+ matplotlib.axes.Axes or np.ndarray of them
1626
+ A NumPy array is returned when `subplots` is True.
1627
+
1628
+ See Also
1629
+ --------
1630
+ Series.plot.pie : Generate a pie plot for a Series.
1631
+ DataFrame.plot : Make plots of a DataFrame.
1632
+
1633
+ Examples
1634
+ --------
1635
+ In the example below we have a DataFrame with the information about
1636
+ planet's mass and radius. We pass the 'mass' column to the
1637
+ pie function to get a pie plot.
1638
+
1639
+ .. plot::
1640
+ :context: close-figs
1641
+
1642
+ >>> df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
1643
+ ... 'radius': [2439.7, 6051.8, 6378.1]},
1644
+ ... index=['Mercury', 'Venus', 'Earth'])
1645
+ >>> plot = df.plot.pie(y='mass', figsize=(5, 5))
1646
+
1647
+ .. plot::
1648
+ :context: close-figs
1649
+
1650
+ >>> plot = df.plot.pie(subplots=True, figsize=(11, 6))
1651
+ """
1652
+ if (
1653
+ isinstance(self._parent, ABCDataFrame)
1654
+ and kwargs.get("y", None) is None
1655
+ and not kwargs.get("subplots", False)
1656
+ ):
1657
+ raise ValueError("pie requires either y column or 'subplots=True'")
1658
+ return self(kind="pie", **kwargs)
1659
+
1660
+ def scatter(
1661
+ self,
1662
+ x: Hashable,
1663
+ y: Hashable,
1664
+ s: Hashable | Sequence[Hashable] | None = None,
1665
+ c: Hashable | Sequence[Hashable] | None = None,
1666
+ **kwargs,
1667
+ ) -> PlotAccessor:
1668
+ """
1669
+ Create a scatter plot with varying marker point size and color.
1670
+
1671
+ The coordinates of each point are defined by two dataframe columns and
1672
+ filled circles are used to represent each point. This kind of plot is
1673
+ useful to see complex correlations between two variables. Points could
1674
+ be for instance natural 2D coordinates like longitude and latitude in
1675
+ a map or, in general, any pair of metrics that can be plotted against
1676
+ each other.
1677
+
1678
+ Parameters
1679
+ ----------
1680
+ x : int or str
1681
+ The column name or column position to be used as horizontal
1682
+ coordinates for each point.
1683
+ y : int or str
1684
+ The column name or column position to be used as vertical
1685
+ coordinates for each point.
1686
+ s : str, scalar or array-like, optional
1687
+ The size of each point. Possible values are:
1688
+
1689
+ - A string with the name of the column to be used for marker's size.
1690
+
1691
+ - A single scalar so all points have the same size.
1692
+
1693
+ - A sequence of scalars, which will be used for each point's size
1694
+ recursively. For instance, when passing [2,14] all points size
1695
+ will be either 2 or 14, alternatively.
1696
+
1697
+ c : str, int or array-like, optional
1698
+ The color of each point. Possible values are:
1699
+
1700
+ - A single color string referred to by name, RGB or RGBA code,
1701
+ for instance 'red' or '#a98d19'.
1702
+
1703
+ - A sequence of color strings referred to by name, RGB or RGBA
1704
+ code, which will be used for each point's color recursively. For
1705
+ instance ['green','yellow'] all points will be filled in green or
1706
+ yellow, alternatively.
1707
+
1708
+ - A column name or position whose values will be used to color the
1709
+ marker points according to a colormap.
1710
+
1711
+ **kwargs
1712
+ Keyword arguments to pass on to :meth:`DataFrame.plot`.
1713
+
1714
+ Returns
1715
+ -------
1716
+ :class:`matplotlib.axes.Axes` or numpy.ndarray of them
1717
+
1718
+ See Also
1719
+ --------
1720
+ matplotlib.pyplot.scatter : Scatter plot using multiple input data
1721
+ formats.
1722
+
1723
+ Examples
1724
+ --------
1725
+ Let's see how to draw a scatter plot using coordinates from the values
1726
+ in a DataFrame's columns.
1727
+
1728
+ .. plot::
1729
+ :context: close-figs
1730
+
1731
+ >>> df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
1732
+ ... [6.4, 3.2, 1], [5.9, 3.0, 2]],
1733
+ ... columns=['length', 'width', 'species'])
1734
+ >>> ax1 = df.plot.scatter(x='length',
1735
+ ... y='width',
1736
+ ... c='DarkBlue')
1737
+
1738
+ And now with the color determined by a column as well.
1739
+
1740
+ .. plot::
1741
+ :context: close-figs
1742
+
1743
+ >>> ax2 = df.plot.scatter(x='length',
1744
+ ... y='width',
1745
+ ... c='species',
1746
+ ... colormap='viridis')
1747
+ """
1748
+ return self(kind="scatter", x=x, y=y, s=s, c=c, **kwargs)
1749
+
1750
+ def hexbin(
1751
+ self,
1752
+ x: Hashable,
1753
+ y: Hashable,
1754
+ C: Hashable | None = None,
1755
+ reduce_C_function: Callable | None = None,
1756
+ gridsize: int | tuple[int, int] | None = None,
1757
+ **kwargs,
1758
+ ) -> PlotAccessor:
1759
+ """
1760
+ Generate a hexagonal binning plot.
1761
+
1762
+ Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None`
1763
+ (the default), this is a histogram of the number of occurrences
1764
+ of the observations at ``(x[i], y[i])``.
1765
+
1766
+ If `C` is specified, specifies values at given coordinates
1767
+ ``(x[i], y[i])``. These values are accumulated for each hexagonal
1768
+ bin and then reduced according to `reduce_C_function`,
1769
+ having as default the NumPy's mean function (:meth:`numpy.mean`).
1770
+ (If `C` is specified, it must also be a 1-D sequence
1771
+ of the same length as `x` and `y`, or a column label.)
1772
+
1773
+ Parameters
1774
+ ----------
1775
+ x : int or str
1776
+ The column label or position for x points.
1777
+ y : int or str
1778
+ The column label or position for y points.
1779
+ C : int or str, optional
1780
+ The column label or position for the value of `(x, y)` point.
1781
+ reduce_C_function : callable, default `np.mean`
1782
+ Function of one argument that reduces all the values in a bin to
1783
+ a single number (e.g. `np.mean`, `np.max`, `np.sum`, `np.std`).
1784
+ gridsize : int or tuple of (int, int), default 100
1785
+ The number of hexagons in the x-direction.
1786
+ The corresponding number of hexagons in the y-direction is
1787
+ chosen in a way that the hexagons are approximately regular.
1788
+ Alternatively, gridsize can be a tuple with two elements
1789
+ specifying the number of hexagons in the x-direction and the
1790
+ y-direction.
1791
+ **kwargs
1792
+ Additional keyword arguments are documented in
1793
+ :meth:`DataFrame.plot`.
1794
+
1795
+ Returns
1796
+ -------
1797
+ matplotlib.AxesSubplot
1798
+ The matplotlib ``Axes`` on which the hexbin is plotted.
1799
+
1800
+ See Also
1801
+ --------
1802
+ DataFrame.plot : Make plots of a DataFrame.
1803
+ matplotlib.pyplot.hexbin : Hexagonal binning plot using matplotlib,
1804
+ the matplotlib function that is used under the hood.
1805
+
1806
+ Examples
1807
+ --------
1808
+ The following examples are generated with random data from
1809
+ a normal distribution.
1810
+
1811
+ .. plot::
1812
+ :context: close-figs
1813
+
1814
+ >>> n = 10000
1815
+ >>> df = pd.DataFrame({'x': np.random.randn(n),
1816
+ ... 'y': np.random.randn(n)})
1817
+ >>> ax = df.plot.hexbin(x='x', y='y', gridsize=20)
1818
+
1819
+ The next example uses `C` and `np.sum` as `reduce_C_function`.
1820
+ Note that `'observations'` values ranges from 1 to 5 but the result
1821
+ plot shows values up to more than 25. This is because of the
1822
+ `reduce_C_function`.
1823
+
1824
+ .. plot::
1825
+ :context: close-figs
1826
+
1827
+ >>> n = 500
1828
+ >>> df = pd.DataFrame({
1829
+ ... 'coord_x': np.random.uniform(-3, 3, size=n),
1830
+ ... 'coord_y': np.random.uniform(30, 50, size=n),
1831
+ ... 'observations': np.random.randint(1,5, size=n)
1832
+ ... })
1833
+ >>> ax = df.plot.hexbin(x='coord_x',
1834
+ ... y='coord_y',
1835
+ ... C='observations',
1836
+ ... reduce_C_function=np.sum,
1837
+ ... gridsize=10,
1838
+ ... cmap="viridis")
1839
+ """
1840
+ if reduce_C_function is not None:
1841
+ kwargs["reduce_C_function"] = reduce_C_function
1842
+ if gridsize is not None:
1843
+ kwargs["gridsize"] = gridsize
1844
+
1845
+ return self(kind="hexbin", x=x, y=y, C=C, **kwargs)
1846
+
1847
+
1848
+ _backends: dict[str, types.ModuleType] = {}
1849
+
1850
+
1851
+ def _load_backend(backend: str) -> types.ModuleType:
1852
+ """
1853
+ Load a pandas plotting backend.
1854
+
1855
+ Parameters
1856
+ ----------
1857
+ backend : str
1858
+ The identifier for the backend. Either an entrypoint item registered
1859
+ with importlib.metadata, "matplotlib", or a module name.
1860
+
1861
+ Returns
1862
+ -------
1863
+ types.ModuleType
1864
+ The imported backend.
1865
+ """
1866
+ from importlib.metadata import entry_points
1867
+
1868
+ if backend == "matplotlib":
1869
+ # Because matplotlib is an optional dependency and first-party backend,
1870
+ # we need to attempt an import here to raise an ImportError if needed.
1871
+ try:
1872
+ module = importlib.import_module("pandas.plotting._matplotlib")
1873
+ except ImportError:
1874
+ raise ImportError(
1875
+ "matplotlib is required for plotting when the "
1876
+ 'default backend "matplotlib" is selected.'
1877
+ ) from None
1878
+ return module
1879
+
1880
+ found_backend = False
1881
+
1882
+ eps = entry_points()
1883
+ key = "pandas_plotting_backends"
1884
+ # entry_points lost dict API ~ PY 3.10
1885
+ # https://github.com/python/importlib_metadata/issues/298
1886
+ if hasattr(eps, "select"):
1887
+ entry = eps.select(group=key)
1888
+ else:
1889
+ # Argument 2 to "get" of "dict" has incompatible type "Tuple[]";
1890
+ # expected "EntryPoints" [arg-type]
1891
+ entry = eps.get(key, ()) # type: ignore[arg-type]
1892
+ for entry_point in entry:
1893
+ found_backend = entry_point.name == backend
1894
+ if found_backend:
1895
+ module = entry_point.load()
1896
+ break
1897
+
1898
+ if not found_backend:
1899
+ # Fall back to unregistered, module name approach.
1900
+ try:
1901
+ module = importlib.import_module(backend)
1902
+ found_backend = True
1903
+ except ImportError:
1904
+ # We re-raise later on.
1905
+ pass
1906
+
1907
+ if found_backend:
1908
+ if hasattr(module, "plot"):
1909
+ # Validate that the interface is implemented when the option is set,
1910
+ # rather than at plot time.
1911
+ return module
1912
+
1913
+ raise ValueError(
1914
+ f"Could not find plotting backend '{backend}'. Ensure that you've "
1915
+ f"installed the package providing the '{backend}' entrypoint, or that "
1916
+ "the package has a top-level `.plot` method."
1917
+ )
1918
+
1919
+
1920
+ def _get_plot_backend(backend: str | None = None):
1921
+ """
1922
+ Return the plotting backend to use (e.g. `pandas.plotting._matplotlib`).
1923
+
1924
+ The plotting system of pandas uses matplotlib by default, but the idea here
1925
+ is that it can also work with other third-party backends. This function
1926
+ returns the module which provides a top-level `.plot` method that will
1927
+ actually do the plotting. The backend is specified from a string, which
1928
+ either comes from the keyword argument `backend`, or, if not specified, from
1929
+ the option `pandas.options.plotting.backend`. All the rest of the code in
1930
+ this file uses the backend specified there for the plotting.
1931
+
1932
+ The backend is imported lazily, as matplotlib is a soft dependency, and
1933
+ pandas can be used without it being installed.
1934
+
1935
+ Notes
1936
+ -----
1937
+ Modifies `_backends` with imported backend as a side effect.
1938
+ """
1939
+ backend_str: str = backend or get_option("plotting.backend")
1940
+
1941
+ if backend_str in _backends:
1942
+ return _backends[backend_str]
1943
+
1944
+ module = _load_backend(backend_str)
1945
+ _backends[backend_str] = module
1946
+ return module
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__init__.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from pandas.plotting._matplotlib.boxplot import (
6
+ BoxPlot,
7
+ boxplot,
8
+ boxplot_frame,
9
+ boxplot_frame_groupby,
10
+ )
11
+ from pandas.plotting._matplotlib.converter import (
12
+ deregister,
13
+ register,
14
+ )
15
+ from pandas.plotting._matplotlib.core import (
16
+ AreaPlot,
17
+ BarhPlot,
18
+ BarPlot,
19
+ HexBinPlot,
20
+ LinePlot,
21
+ PiePlot,
22
+ ScatterPlot,
23
+ )
24
+ from pandas.plotting._matplotlib.hist import (
25
+ HistPlot,
26
+ KdePlot,
27
+ hist_frame,
28
+ hist_series,
29
+ )
30
+ from pandas.plotting._matplotlib.misc import (
31
+ andrews_curves,
32
+ autocorrelation_plot,
33
+ bootstrap_plot,
34
+ lag_plot,
35
+ parallel_coordinates,
36
+ radviz,
37
+ scatter_matrix,
38
+ )
39
+ from pandas.plotting._matplotlib.tools import table
40
+
41
+ if TYPE_CHECKING:
42
+ from pandas.plotting._matplotlib.core import MPLPlot
43
+
44
+ PLOT_CLASSES: dict[str, type[MPLPlot]] = {
45
+ "line": LinePlot,
46
+ "bar": BarPlot,
47
+ "barh": BarhPlot,
48
+ "box": BoxPlot,
49
+ "hist": HistPlot,
50
+ "kde": KdePlot,
51
+ "area": AreaPlot,
52
+ "pie": PiePlot,
53
+ "scatter": ScatterPlot,
54
+ "hexbin": HexBinPlot,
55
+ }
56
+
57
+
58
+ def plot(data, kind, **kwargs):
59
+ # Importing pyplot at the top of the file (before the converters are
60
+ # registered) causes problems in matplotlib 2 (converters seem to not
61
+ # work)
62
+ import matplotlib.pyplot as plt
63
+
64
+ if kwargs.pop("reuse_plot", False):
65
+ ax = kwargs.get("ax")
66
+ if ax is None and len(plt.get_fignums()) > 0:
67
+ with plt.rc_context():
68
+ ax = plt.gca()
69
+ kwargs["ax"] = getattr(ax, "left_ax", ax)
70
+ plot_obj = PLOT_CLASSES[kind](data, **kwargs)
71
+ plot_obj.generate()
72
+ plot_obj.draw()
73
+ return plot_obj.result
74
+
75
+
76
+ __all__ = [
77
+ "plot",
78
+ "hist_series",
79
+ "hist_frame",
80
+ "boxplot",
81
+ "boxplot_frame",
82
+ "boxplot_frame_groupby",
83
+ "table",
84
+ "andrews_curves",
85
+ "autocorrelation_plot",
86
+ "bootstrap_plot",
87
+ "lag_plot",
88
+ "parallel_coordinates",
89
+ "radviz",
90
+ "scatter_matrix",
91
+ "register",
92
+ "deregister",
93
+ ]
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.87 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/boxplot.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/converter.cpython-310.pyc ADDED
Binary file (29.1 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/core.cpython-310.pyc ADDED
Binary file (50.1 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/groupby.cpython-310.pyc ADDED
Binary file (4.34 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/hist.cpython-310.pyc ADDED
Binary file (12.8 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/misc.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/style.cpython-310.pyc ADDED
Binary file (8.81 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/timeseries.cpython-310.pyc ADDED
Binary file (8.04 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/tools.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/boxplot.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import (
4
+ TYPE_CHECKING,
5
+ Literal,
6
+ NamedTuple,
7
+ )
8
+ import warnings
9
+
10
+ from matplotlib.artist import setp
11
+ import numpy as np
12
+
13
+ from pandas._libs import lib
14
+ from pandas.util._decorators import cache_readonly
15
+ from pandas.util._exceptions import find_stack_level
16
+
17
+ from pandas.core.dtypes.common import is_dict_like
18
+ from pandas.core.dtypes.generic import ABCSeries
19
+ from pandas.core.dtypes.missing import remove_na_arraylike
20
+
21
+ import pandas as pd
22
+ import pandas.core.common as com
23
+
24
+ from pandas.io.formats.printing import pprint_thing
25
+ from pandas.plotting._matplotlib.core import (
26
+ LinePlot,
27
+ MPLPlot,
28
+ )
29
+ from pandas.plotting._matplotlib.groupby import create_iter_data_given_by
30
+ from pandas.plotting._matplotlib.style import get_standard_colors
31
+ from pandas.plotting._matplotlib.tools import (
32
+ create_subplots,
33
+ flatten_axes,
34
+ maybe_adjust_figure,
35
+ )
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Collection
39
+
40
+ from matplotlib.axes import Axes
41
+ from matplotlib.figure import Figure
42
+ from matplotlib.lines import Line2D
43
+
44
+ from pandas._typing import MatplotlibColor
45
+
46
+
47
+ def _set_ticklabels(ax: Axes, labels: list[str], is_vertical: bool, **kwargs) -> None:
48
+ """Set the tick labels of a given axis.
49
+
50
+ Due to https://github.com/matplotlib/matplotlib/pull/17266, we need to handle the
51
+ case of repeated ticks (due to `FixedLocator`) and thus we duplicate the number of
52
+ labels.
53
+ """
54
+ ticks = ax.get_xticks() if is_vertical else ax.get_yticks()
55
+ if len(ticks) != len(labels):
56
+ i, remainder = divmod(len(ticks), len(labels))
57
+ assert remainder == 0, remainder
58
+ labels *= i
59
+ if is_vertical:
60
+ ax.set_xticklabels(labels, **kwargs)
61
+ else:
62
+ ax.set_yticklabels(labels, **kwargs)
63
+
64
+
65
+ class BoxPlot(LinePlot):
66
+ @property
67
+ def _kind(self) -> Literal["box"]:
68
+ return "box"
69
+
70
+ _layout_type = "horizontal"
71
+
72
+ _valid_return_types = (None, "axes", "dict", "both")
73
+
74
+ class BP(NamedTuple):
75
+ # namedtuple to hold results
76
+ ax: Axes
77
+ lines: dict[str, list[Line2D]]
78
+
79
+ def __init__(self, data, return_type: str = "axes", **kwargs) -> None:
80
+ if return_type not in self._valid_return_types:
81
+ raise ValueError("return_type must be {None, 'axes', 'dict', 'both'}")
82
+
83
+ self.return_type = return_type
84
+ # Do not call LinePlot.__init__ which may fill nan
85
+ MPLPlot.__init__(self, data, **kwargs) # pylint: disable=non-parent-init-called
86
+
87
+ if self.subplots:
88
+ # Disable label ax sharing. Otherwise, all subplots shows last
89
+ # column label
90
+ if self.orientation == "vertical":
91
+ self.sharex = False
92
+ else:
93
+ self.sharey = False
94
+
95
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
96
+ @classmethod
97
+ def _plot( # type: ignore[override]
98
+ cls, ax: Axes, y: np.ndarray, column_num=None, return_type: str = "axes", **kwds
99
+ ):
100
+ ys: np.ndarray | list[np.ndarray]
101
+ if y.ndim == 2:
102
+ ys = [remove_na_arraylike(v) for v in y]
103
+ # Boxplot fails with empty arrays, so need to add a NaN
104
+ # if any cols are empty
105
+ # GH 8181
106
+ ys = [v if v.size > 0 else np.array([np.nan]) for v in ys]
107
+ else:
108
+ ys = remove_na_arraylike(y)
109
+ bp = ax.boxplot(ys, **kwds)
110
+
111
+ if return_type == "dict":
112
+ return bp, bp
113
+ elif return_type == "both":
114
+ return cls.BP(ax=ax, lines=bp), bp
115
+ else:
116
+ return ax, bp
117
+
118
+ def _validate_color_args(self, color, colormap):
119
+ if color is lib.no_default:
120
+ return None
121
+
122
+ if colormap is not None:
123
+ warnings.warn(
124
+ "'color' and 'colormap' cannot be used "
125
+ "simultaneously. Using 'color'",
126
+ stacklevel=find_stack_level(),
127
+ )
128
+
129
+ if isinstance(color, dict):
130
+ valid_keys = ["boxes", "whiskers", "medians", "caps"]
131
+ for key in color:
132
+ if key not in valid_keys:
133
+ raise ValueError(
134
+ f"color dict contains invalid key '{key}'. "
135
+ f"The key must be either {valid_keys}"
136
+ )
137
+ return color
138
+
139
+ @cache_readonly
140
+ def _color_attrs(self):
141
+ # get standard colors for default
142
+ # use 2 colors by default, for box/whisker and median
143
+ # flier colors isn't needed here
144
+ # because it can be specified by ``sym`` kw
145
+ return get_standard_colors(num_colors=3, colormap=self.colormap, color=None)
146
+
147
+ @cache_readonly
148
+ def _boxes_c(self):
149
+ return self._color_attrs[0]
150
+
151
+ @cache_readonly
152
+ def _whiskers_c(self):
153
+ return self._color_attrs[0]
154
+
155
+ @cache_readonly
156
+ def _medians_c(self):
157
+ return self._color_attrs[2]
158
+
159
+ @cache_readonly
160
+ def _caps_c(self):
161
+ return self._color_attrs[0]
162
+
163
+ def _get_colors(
164
+ self,
165
+ num_colors=None,
166
+ color_kwds: dict[str, MatplotlibColor]
167
+ | MatplotlibColor
168
+ | Collection[MatplotlibColor]
169
+ | None = "color",
170
+ ) -> None:
171
+ pass
172
+
173
+ def maybe_color_bp(self, bp) -> None:
174
+ if isinstance(self.color, dict):
175
+ boxes = self.color.get("boxes", self._boxes_c)
176
+ whiskers = self.color.get("whiskers", self._whiskers_c)
177
+ medians = self.color.get("medians", self._medians_c)
178
+ caps = self.color.get("caps", self._caps_c)
179
+ else:
180
+ # Other types are forwarded to matplotlib
181
+ # If None, use default colors
182
+ boxes = self.color or self._boxes_c
183
+ whiskers = self.color or self._whiskers_c
184
+ medians = self.color or self._medians_c
185
+ caps = self.color or self._caps_c
186
+
187
+ color_tup = (boxes, whiskers, medians, caps)
188
+ maybe_color_bp(bp, color_tup=color_tup, **self.kwds)
189
+
190
+ def _make_plot(self, fig: Figure) -> None:
191
+ if self.subplots:
192
+ self._return_obj = pd.Series(dtype=object)
193
+
194
+ # Re-create iterated data if `by` is assigned by users
195
+ data = (
196
+ create_iter_data_given_by(self.data, self._kind)
197
+ if self.by is not None
198
+ else self.data
199
+ )
200
+
201
+ # error: Argument "data" to "_iter_data" of "MPLPlot" has
202
+ # incompatible type "object"; expected "DataFrame |
203
+ # dict[Hashable, Series | DataFrame]"
204
+ for i, (label, y) in enumerate(self._iter_data(data=data)): # type: ignore[arg-type]
205
+ ax = self._get_ax(i)
206
+ kwds = self.kwds.copy()
207
+
208
+ # When by is applied, show title for subplots to know which group it is
209
+ # just like df.boxplot, and need to apply T on y to provide right input
210
+ if self.by is not None:
211
+ y = y.T
212
+ ax.set_title(pprint_thing(label))
213
+
214
+ # When `by` is assigned, the ticklabels will become unique grouped
215
+ # values, instead of label which is used as subtitle in this case.
216
+ # error: "Index" has no attribute "levels"; maybe "nlevels"?
217
+ levels = self.data.columns.levels # type: ignore[attr-defined]
218
+ ticklabels = [pprint_thing(col) for col in levels[0]]
219
+ else:
220
+ ticklabels = [pprint_thing(label)]
221
+
222
+ ret, bp = self._plot(
223
+ ax, y, column_num=i, return_type=self.return_type, **kwds
224
+ )
225
+ self.maybe_color_bp(bp)
226
+ self._return_obj[label] = ret
227
+ _set_ticklabels(
228
+ ax=ax, labels=ticklabels, is_vertical=self.orientation == "vertical"
229
+ )
230
+ else:
231
+ y = self.data.values.T
232
+ ax = self._get_ax(0)
233
+ kwds = self.kwds.copy()
234
+
235
+ ret, bp = self._plot(
236
+ ax, y, column_num=0, return_type=self.return_type, **kwds
237
+ )
238
+ self.maybe_color_bp(bp)
239
+ self._return_obj = ret
240
+
241
+ labels = [pprint_thing(left) for left in self.data.columns]
242
+ if not self.use_index:
243
+ labels = [pprint_thing(key) for key in range(len(labels))]
244
+ _set_ticklabels(
245
+ ax=ax, labels=labels, is_vertical=self.orientation == "vertical"
246
+ )
247
+
248
+ def _make_legend(self) -> None:
249
+ pass
250
+
251
+ def _post_plot_logic(self, ax: Axes, data) -> None:
252
+ # GH 45465: make sure that the boxplot doesn't ignore xlabel/ylabel
253
+ if self.xlabel:
254
+ ax.set_xlabel(pprint_thing(self.xlabel))
255
+ if self.ylabel:
256
+ ax.set_ylabel(pprint_thing(self.ylabel))
257
+
258
+ @property
259
+ def orientation(self) -> Literal["horizontal", "vertical"]:
260
+ if self.kwds.get("vert", True):
261
+ return "vertical"
262
+ else:
263
+ return "horizontal"
264
+
265
+ @property
266
+ def result(self):
267
+ if self.return_type is None:
268
+ return super().result
269
+ else:
270
+ return self._return_obj
271
+
272
+
273
+ def maybe_color_bp(bp, color_tup, **kwds) -> None:
274
+ # GH#30346, when users specifying those arguments explicitly, our defaults
275
+ # for these four kwargs should be overridden; if not, use Pandas settings
276
+ if not kwds.get("boxprops"):
277
+ setp(bp["boxes"], color=color_tup[0], alpha=1)
278
+ if not kwds.get("whiskerprops"):
279
+ setp(bp["whiskers"], color=color_tup[1], alpha=1)
280
+ if not kwds.get("medianprops"):
281
+ setp(bp["medians"], color=color_tup[2], alpha=1)
282
+ if not kwds.get("capprops"):
283
+ setp(bp["caps"], color=color_tup[3], alpha=1)
284
+
285
+
286
+ def _grouped_plot_by_column(
287
+ plotf,
288
+ data,
289
+ columns=None,
290
+ by=None,
291
+ numeric_only: bool = True,
292
+ grid: bool = False,
293
+ figsize: tuple[float, float] | None = None,
294
+ ax=None,
295
+ layout=None,
296
+ return_type=None,
297
+ **kwargs,
298
+ ):
299
+ grouped = data.groupby(by, observed=False)
300
+ if columns is None:
301
+ if not isinstance(by, (list, tuple)):
302
+ by = [by]
303
+ columns = data._get_numeric_data().columns.difference(by)
304
+ naxes = len(columns)
305
+ fig, axes = create_subplots(
306
+ naxes=naxes,
307
+ sharex=kwargs.pop("sharex", True),
308
+ sharey=kwargs.pop("sharey", True),
309
+ figsize=figsize,
310
+ ax=ax,
311
+ layout=layout,
312
+ )
313
+
314
+ _axes = flatten_axes(axes)
315
+
316
+ # GH 45465: move the "by" label based on "vert"
317
+ xlabel, ylabel = kwargs.pop("xlabel", None), kwargs.pop("ylabel", None)
318
+ if kwargs.get("vert", True):
319
+ xlabel = xlabel or by
320
+ else:
321
+ ylabel = ylabel or by
322
+
323
+ ax_values = []
324
+
325
+ for i, col in enumerate(columns):
326
+ ax = _axes[i]
327
+ gp_col = grouped[col]
328
+ keys, values = zip(*gp_col)
329
+ re_plotf = plotf(keys, values, ax, xlabel=xlabel, ylabel=ylabel, **kwargs)
330
+ ax.set_title(col)
331
+ ax_values.append(re_plotf)
332
+ ax.grid(grid)
333
+
334
+ result = pd.Series(ax_values, index=columns, copy=False)
335
+
336
+ # Return axes in multiplot case, maybe revisit later # 985
337
+ if return_type is None:
338
+ result = axes
339
+
340
+ byline = by[0] if len(by) == 1 else by
341
+ fig.suptitle(f"Boxplot grouped by {byline}")
342
+ maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)
343
+
344
+ return result
345
+
346
+
347
+ def boxplot(
348
+ data,
349
+ column=None,
350
+ by=None,
351
+ ax=None,
352
+ fontsize: int | None = None,
353
+ rot: int = 0,
354
+ grid: bool = True,
355
+ figsize: tuple[float, float] | None = None,
356
+ layout=None,
357
+ return_type=None,
358
+ **kwds,
359
+ ):
360
+ import matplotlib.pyplot as plt
361
+
362
+ # validate return_type:
363
+ if return_type not in BoxPlot._valid_return_types:
364
+ raise ValueError("return_type must be {'axes', 'dict', 'both'}")
365
+
366
+ if isinstance(data, ABCSeries):
367
+ data = data.to_frame("x")
368
+ column = "x"
369
+
370
+ def _get_colors():
371
+ # num_colors=3 is required as method maybe_color_bp takes the colors
372
+ # in positions 0 and 2.
373
+ # if colors not provided, use same defaults as DataFrame.plot.box
374
+ result = get_standard_colors(num_colors=3)
375
+ result = np.take(result, [0, 0, 2])
376
+ result = np.append(result, "k")
377
+
378
+ colors = kwds.pop("color", None)
379
+ if colors:
380
+ if is_dict_like(colors):
381
+ # replace colors in result array with user-specified colors
382
+ # taken from the colors dict parameter
383
+ # "boxes" value placed in position 0, "whiskers" in 1, etc.
384
+ valid_keys = ["boxes", "whiskers", "medians", "caps"]
385
+ key_to_index = dict(zip(valid_keys, range(4)))
386
+ for key, value in colors.items():
387
+ if key in valid_keys:
388
+ result[key_to_index[key]] = value
389
+ else:
390
+ raise ValueError(
391
+ f"color dict contains invalid key '{key}'. "
392
+ f"The key must be either {valid_keys}"
393
+ )
394
+ else:
395
+ result.fill(colors)
396
+
397
+ return result
398
+
399
+ def plot_group(keys, values, ax: Axes, **kwds):
400
+ # GH 45465: xlabel/ylabel need to be popped out before plotting happens
401
+ xlabel, ylabel = kwds.pop("xlabel", None), kwds.pop("ylabel", None)
402
+ if xlabel:
403
+ ax.set_xlabel(pprint_thing(xlabel))
404
+ if ylabel:
405
+ ax.set_ylabel(pprint_thing(ylabel))
406
+
407
+ keys = [pprint_thing(x) for x in keys]
408
+ values = [np.asarray(remove_na_arraylike(v), dtype=object) for v in values]
409
+ bp = ax.boxplot(values, **kwds)
410
+ if fontsize is not None:
411
+ ax.tick_params(axis="both", labelsize=fontsize)
412
+
413
+ # GH 45465: x/y are flipped when "vert" changes
414
+ _set_ticklabels(
415
+ ax=ax, labels=keys, is_vertical=kwds.get("vert", True), rotation=rot
416
+ )
417
+ maybe_color_bp(bp, color_tup=colors, **kwds)
418
+
419
+ # Return axes in multiplot case, maybe revisit later # 985
420
+ if return_type == "dict":
421
+ return bp
422
+ elif return_type == "both":
423
+ return BoxPlot.BP(ax=ax, lines=bp)
424
+ else:
425
+ return ax
426
+
427
+ colors = _get_colors()
428
+ if column is None:
429
+ columns = None
430
+ elif isinstance(column, (list, tuple)):
431
+ columns = column
432
+ else:
433
+ columns = [column]
434
+
435
+ if by is not None:
436
+ # Prefer array return type for 2-D plots to match the subplot layout
437
+ # https://github.com/pandas-dev/pandas/pull/12216#issuecomment-241175580
438
+ result = _grouped_plot_by_column(
439
+ plot_group,
440
+ data,
441
+ columns=columns,
442
+ by=by,
443
+ grid=grid,
444
+ figsize=figsize,
445
+ ax=ax,
446
+ layout=layout,
447
+ return_type=return_type,
448
+ **kwds,
449
+ )
450
+ else:
451
+ if return_type is None:
452
+ return_type = "axes"
453
+ if layout is not None:
454
+ raise ValueError("The 'layout' keyword is not supported when 'by' is None")
455
+
456
+ if ax is None:
457
+ rc = {"figure.figsize": figsize} if figsize is not None else {}
458
+ with plt.rc_context(rc):
459
+ ax = plt.gca()
460
+ data = data._get_numeric_data()
461
+ naxes = len(data.columns)
462
+ if naxes == 0:
463
+ raise ValueError(
464
+ "boxplot method requires numerical columns, nothing to plot."
465
+ )
466
+ if columns is None:
467
+ columns = data.columns
468
+ else:
469
+ data = data[columns]
470
+
471
+ result = plot_group(columns, data.values.T, ax, **kwds)
472
+ ax.grid(grid)
473
+
474
+ return result
475
+
476
+
477
+ def boxplot_frame(
478
+ self,
479
+ column=None,
480
+ by=None,
481
+ ax=None,
482
+ fontsize: int | None = None,
483
+ rot: int = 0,
484
+ grid: bool = True,
485
+ figsize: tuple[float, float] | None = None,
486
+ layout=None,
487
+ return_type=None,
488
+ **kwds,
489
+ ):
490
+ import matplotlib.pyplot as plt
491
+
492
+ ax = boxplot(
493
+ self,
494
+ column=column,
495
+ by=by,
496
+ ax=ax,
497
+ fontsize=fontsize,
498
+ grid=grid,
499
+ rot=rot,
500
+ figsize=figsize,
501
+ layout=layout,
502
+ return_type=return_type,
503
+ **kwds,
504
+ )
505
+ plt.draw_if_interactive()
506
+ return ax
507
+
508
+
509
+ def boxplot_frame_groupby(
510
+ grouped,
511
+ subplots: bool = True,
512
+ column=None,
513
+ fontsize: int | None = None,
514
+ rot: int = 0,
515
+ grid: bool = True,
516
+ ax=None,
517
+ figsize: tuple[float, float] | None = None,
518
+ layout=None,
519
+ sharex: bool = False,
520
+ sharey: bool = True,
521
+ **kwds,
522
+ ):
523
+ if subplots is True:
524
+ naxes = len(grouped)
525
+ fig, axes = create_subplots(
526
+ naxes=naxes,
527
+ squeeze=False,
528
+ ax=ax,
529
+ sharex=sharex,
530
+ sharey=sharey,
531
+ figsize=figsize,
532
+ layout=layout,
533
+ )
534
+ axes = flatten_axes(axes)
535
+
536
+ ret = pd.Series(dtype=object)
537
+
538
+ for (key, group), ax in zip(grouped, axes):
539
+ d = group.boxplot(
540
+ ax=ax, column=column, fontsize=fontsize, rot=rot, grid=grid, **kwds
541
+ )
542
+ ax.set_title(pprint_thing(key))
543
+ ret.loc[key] = d
544
+ maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)
545
+ else:
546
+ keys, frames = zip(*grouped)
547
+ if grouped.axis == 0:
548
+ df = pd.concat(frames, keys=keys, axis=1)
549
+ elif len(frames) > 1:
550
+ df = frames[0].join(frames[1::])
551
+ else:
552
+ df = frames[0]
553
+
554
+ # GH 16748, DataFrameGroupby fails when subplots=False and `column` argument
555
+ # is assigned, and in this case, since `df` here becomes MI after groupby,
556
+ # so we need to couple the keys (grouped values) and column (original df
557
+ # column) together to search for subset to plot
558
+ if column is not None:
559
+ column = com.convert_to_list_like(column)
560
+ multi_key = pd.MultiIndex.from_product([keys, column])
561
+ column = list(multi_key.values)
562
+ ret = df.boxplot(
563
+ column=column,
564
+ fontsize=fontsize,
565
+ rot=rot,
566
+ grid=grid,
567
+ ax=ax,
568
+ figsize=figsize,
569
+ layout=layout,
570
+ **kwds,
571
+ )
572
+ return ret
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/converter.py ADDED
@@ -0,0 +1,1139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import datetime as pydt
5
+ from datetime import (
6
+ datetime,
7
+ timedelta,
8
+ tzinfo,
9
+ )
10
+ import functools
11
+ from typing import (
12
+ TYPE_CHECKING,
13
+ Any,
14
+ cast,
15
+ )
16
+ import warnings
17
+
18
+ import matplotlib.dates as mdates
19
+ from matplotlib.ticker import (
20
+ AutoLocator,
21
+ Formatter,
22
+ Locator,
23
+ )
24
+ from matplotlib.transforms import nonsingular
25
+ import matplotlib.units as munits
26
+ import numpy as np
27
+
28
+ from pandas._libs import lib
29
+ from pandas._libs.tslibs import (
30
+ Timestamp,
31
+ to_offset,
32
+ )
33
+ from pandas._libs.tslibs.dtypes import (
34
+ FreqGroup,
35
+ periods_per_day,
36
+ )
37
+ from pandas._typing import (
38
+ F,
39
+ npt,
40
+ )
41
+
42
+ from pandas.core.dtypes.common import (
43
+ is_float,
44
+ is_float_dtype,
45
+ is_integer,
46
+ is_integer_dtype,
47
+ is_nested_list_like,
48
+ )
49
+
50
+ from pandas import (
51
+ Index,
52
+ Series,
53
+ get_option,
54
+ )
55
+ import pandas.core.common as com
56
+ from pandas.core.indexes.datetimes import date_range
57
+ from pandas.core.indexes.period import (
58
+ Period,
59
+ PeriodIndex,
60
+ period_range,
61
+ )
62
+ import pandas.core.tools.datetimes as tools
63
+
64
+ if TYPE_CHECKING:
65
+ from collections.abc import Generator
66
+
67
+ from matplotlib.axis import Axis
68
+
69
+ from pandas._libs.tslibs.offsets import BaseOffset
70
+
71
+
72
+ _mpl_units = {} # Cache for units overwritten by us
73
+
74
+
75
+ def get_pairs():
76
+ pairs = [
77
+ (Timestamp, DatetimeConverter),
78
+ (Period, PeriodConverter),
79
+ (pydt.datetime, DatetimeConverter),
80
+ (pydt.date, DatetimeConverter),
81
+ (pydt.time, TimeConverter),
82
+ (np.datetime64, DatetimeConverter),
83
+ ]
84
+ return pairs
85
+
86
+
87
+ def register_pandas_matplotlib_converters(func: F) -> F:
88
+ """
89
+ Decorator applying pandas_converters.
90
+ """
91
+
92
+ @functools.wraps(func)
93
+ def wrapper(*args, **kwargs):
94
+ with pandas_converters():
95
+ return func(*args, **kwargs)
96
+
97
+ return cast(F, wrapper)
98
+
99
+
100
+ @contextlib.contextmanager
101
+ def pandas_converters() -> Generator[None, None, None]:
102
+ """
103
+ Context manager registering pandas' converters for a plot.
104
+
105
+ See Also
106
+ --------
107
+ register_pandas_matplotlib_converters : Decorator that applies this.
108
+ """
109
+ value = get_option("plotting.matplotlib.register_converters")
110
+
111
+ if value:
112
+ # register for True or "auto"
113
+ register()
114
+ try:
115
+ yield
116
+ finally:
117
+ if value == "auto":
118
+ # only deregister for "auto"
119
+ deregister()
120
+
121
+
122
+ def register() -> None:
123
+ pairs = get_pairs()
124
+ for type_, cls in pairs:
125
+ # Cache previous converter if present
126
+ if type_ in munits.registry and not isinstance(munits.registry[type_], cls):
127
+ previous = munits.registry[type_]
128
+ _mpl_units[type_] = previous
129
+ # Replace with pandas converter
130
+ munits.registry[type_] = cls()
131
+
132
+
133
+ def deregister() -> None:
134
+ # Renamed in pandas.plotting.__init__
135
+ for type_, cls in get_pairs():
136
+ # We use type to catch our classes directly, no inheritance
137
+ if type(munits.registry.get(type_)) is cls:
138
+ munits.registry.pop(type_)
139
+
140
+ # restore the old keys
141
+ for unit, formatter in _mpl_units.items():
142
+ if type(formatter) not in {DatetimeConverter, PeriodConverter, TimeConverter}:
143
+ # make it idempotent by excluding ours.
144
+ munits.registry[unit] = formatter
145
+
146
+
147
+ def _to_ordinalf(tm: pydt.time) -> float:
148
+ tot_sec = tm.hour * 3600 + tm.minute * 60 + tm.second + tm.microsecond / 10**6
149
+ return tot_sec
150
+
151
+
152
+ def time2num(d):
153
+ if isinstance(d, str):
154
+ parsed = Timestamp(d)
155
+ return _to_ordinalf(parsed.time())
156
+ if isinstance(d, pydt.time):
157
+ return _to_ordinalf(d)
158
+ return d
159
+
160
+
161
+ class TimeConverter(munits.ConversionInterface):
162
+ @staticmethod
163
+ def convert(value, unit, axis):
164
+ valid_types = (str, pydt.time)
165
+ if isinstance(value, valid_types) or is_integer(value) or is_float(value):
166
+ return time2num(value)
167
+ if isinstance(value, Index):
168
+ return value.map(time2num)
169
+ if isinstance(value, (list, tuple, np.ndarray, Index)):
170
+ return [time2num(x) for x in value]
171
+ return value
172
+
173
+ @staticmethod
174
+ def axisinfo(unit, axis) -> munits.AxisInfo | None:
175
+ if unit != "time":
176
+ return None
177
+
178
+ majloc = AutoLocator()
179
+ majfmt = TimeFormatter(majloc)
180
+ return munits.AxisInfo(majloc=majloc, majfmt=majfmt, label="time")
181
+
182
+ @staticmethod
183
+ def default_units(x, axis) -> str:
184
+ return "time"
185
+
186
+
187
+ # time formatter
188
+ class TimeFormatter(Formatter):
189
+ def __init__(self, locs) -> None:
190
+ self.locs = locs
191
+
192
+ def __call__(self, x, pos: int | None = 0) -> str:
193
+ """
194
+ Return the time of day as a formatted string.
195
+
196
+ Parameters
197
+ ----------
198
+ x : float
199
+ The time of day specified as seconds since 00:00 (midnight),
200
+ with up to microsecond precision.
201
+ pos
202
+ Unused
203
+
204
+ Returns
205
+ -------
206
+ str
207
+ A string in HH:MM:SS.mmmuuu format. Microseconds,
208
+ milliseconds and seconds are only displayed if non-zero.
209
+ """
210
+ fmt = "%H:%M:%S.%f"
211
+ s = int(x)
212
+ msus = round((x - s) * 10**6)
213
+ ms = msus // 1000
214
+ us = msus % 1000
215
+ m, s = divmod(s, 60)
216
+ h, m = divmod(m, 60)
217
+ _, h = divmod(h, 24)
218
+ if us != 0:
219
+ return pydt.time(h, m, s, msus).strftime(fmt)
220
+ elif ms != 0:
221
+ return pydt.time(h, m, s, msus).strftime(fmt)[:-3]
222
+ elif s != 0:
223
+ return pydt.time(h, m, s).strftime("%H:%M:%S")
224
+
225
+ return pydt.time(h, m).strftime("%H:%M")
226
+
227
+
228
+ # Period Conversion
229
+
230
+
231
+ class PeriodConverter(mdates.DateConverter):
232
+ @staticmethod
233
+ def convert(values, units, axis):
234
+ if is_nested_list_like(values):
235
+ values = [PeriodConverter._convert_1d(v, units, axis) for v in values]
236
+ else:
237
+ values = PeriodConverter._convert_1d(values, units, axis)
238
+ return values
239
+
240
+ @staticmethod
241
+ def _convert_1d(values, units, axis):
242
+ if not hasattr(axis, "freq"):
243
+ raise TypeError("Axis must have `freq` set to convert to Periods")
244
+ valid_types = (str, datetime, Period, pydt.date, pydt.time, np.datetime64)
245
+ with warnings.catch_warnings():
246
+ warnings.filterwarnings(
247
+ "ignore", "Period with BDay freq is deprecated", category=FutureWarning
248
+ )
249
+ warnings.filterwarnings(
250
+ "ignore", r"PeriodDtype\[B\] is deprecated", category=FutureWarning
251
+ )
252
+ if (
253
+ isinstance(values, valid_types)
254
+ or is_integer(values)
255
+ or is_float(values)
256
+ ):
257
+ return get_datevalue(values, axis.freq)
258
+ elif isinstance(values, PeriodIndex):
259
+ return values.asfreq(axis.freq).asi8
260
+ elif isinstance(values, Index):
261
+ return values.map(lambda x: get_datevalue(x, axis.freq))
262
+ elif lib.infer_dtype(values, skipna=False) == "period":
263
+ # https://github.com/pandas-dev/pandas/issues/24304
264
+ # convert ndarray[period] -> PeriodIndex
265
+ return PeriodIndex(values, freq=axis.freq).asi8
266
+ elif isinstance(values, (list, tuple, np.ndarray, Index)):
267
+ return [get_datevalue(x, axis.freq) for x in values]
268
+ return values
269
+
270
+
271
+ def get_datevalue(date, freq):
272
+ if isinstance(date, Period):
273
+ return date.asfreq(freq).ordinal
274
+ elif isinstance(date, (str, datetime, pydt.date, pydt.time, np.datetime64)):
275
+ return Period(date, freq).ordinal
276
+ elif (
277
+ is_integer(date)
278
+ or is_float(date)
279
+ or (isinstance(date, (np.ndarray, Index)) and (date.size == 1))
280
+ ):
281
+ return date
282
+ elif date is None:
283
+ return None
284
+ raise ValueError(f"Unrecognizable date '{date}'")
285
+
286
+
287
+ # Datetime Conversion
288
+ class DatetimeConverter(mdates.DateConverter):
289
+ @staticmethod
290
+ def convert(values, unit, axis):
291
+ # values might be a 1-d array, or a list-like of arrays.
292
+ if is_nested_list_like(values):
293
+ values = [DatetimeConverter._convert_1d(v, unit, axis) for v in values]
294
+ else:
295
+ values = DatetimeConverter._convert_1d(values, unit, axis)
296
+ return values
297
+
298
+ @staticmethod
299
+ def _convert_1d(values, unit, axis):
300
+ def try_parse(values):
301
+ try:
302
+ return mdates.date2num(tools.to_datetime(values))
303
+ except Exception:
304
+ return values
305
+
306
+ if isinstance(values, (datetime, pydt.date, np.datetime64, pydt.time)):
307
+ return mdates.date2num(values)
308
+ elif is_integer(values) or is_float(values):
309
+ return values
310
+ elif isinstance(values, str):
311
+ return try_parse(values)
312
+ elif isinstance(values, (list, tuple, np.ndarray, Index, Series)):
313
+ if isinstance(values, Series):
314
+ # https://github.com/matplotlib/matplotlib/issues/11391
315
+ # Series was skipped. Convert to DatetimeIndex to get asi8
316
+ values = Index(values)
317
+ if isinstance(values, Index):
318
+ values = values.values
319
+ if not isinstance(values, np.ndarray):
320
+ values = com.asarray_tuplesafe(values)
321
+
322
+ if is_integer_dtype(values) or is_float_dtype(values):
323
+ return values
324
+
325
+ try:
326
+ values = tools.to_datetime(values)
327
+ except Exception:
328
+ pass
329
+
330
+ values = mdates.date2num(values)
331
+
332
+ return values
333
+
334
+ @staticmethod
335
+ def axisinfo(unit: tzinfo | None, axis) -> munits.AxisInfo:
336
+ """
337
+ Return the :class:`~matplotlib.units.AxisInfo` for *unit*.
338
+
339
+ *unit* is a tzinfo instance or None.
340
+ The *axis* argument is required but not used.
341
+ """
342
+ tz = unit
343
+
344
+ majloc = PandasAutoDateLocator(tz=tz)
345
+ majfmt = PandasAutoDateFormatter(majloc, tz=tz)
346
+ datemin = pydt.date(2000, 1, 1)
347
+ datemax = pydt.date(2010, 1, 1)
348
+
349
+ return munits.AxisInfo(
350
+ majloc=majloc, majfmt=majfmt, label="", default_limits=(datemin, datemax)
351
+ )
352
+
353
+
354
+ class PandasAutoDateFormatter(mdates.AutoDateFormatter):
355
+ def __init__(self, locator, tz=None, defaultfmt: str = "%Y-%m-%d") -> None:
356
+ mdates.AutoDateFormatter.__init__(self, locator, tz, defaultfmt)
357
+
358
+
359
+ class PandasAutoDateLocator(mdates.AutoDateLocator):
360
+ def get_locator(self, dmin, dmax):
361
+ """Pick the best locator based on a distance."""
362
+ tot_sec = (dmax - dmin).total_seconds()
363
+
364
+ if abs(tot_sec) < self.minticks:
365
+ self._freq = -1
366
+ locator = MilliSecondLocator(self.tz)
367
+ locator.set_axis(self.axis)
368
+
369
+ # error: Item "None" of "Axis | _DummyAxis | _AxisWrapper | None"
370
+ # has no attribute "get_data_interval"
371
+ locator.axis.set_view_interval( # type: ignore[union-attr]
372
+ *self.axis.get_view_interval() # type: ignore[union-attr]
373
+ )
374
+ locator.axis.set_data_interval( # type: ignore[union-attr]
375
+ *self.axis.get_data_interval() # type: ignore[union-attr]
376
+ )
377
+ return locator
378
+
379
+ return mdates.AutoDateLocator.get_locator(self, dmin, dmax)
380
+
381
+ def _get_unit(self):
382
+ return MilliSecondLocator.get_unit_generic(self._freq)
383
+
384
+
385
+ class MilliSecondLocator(mdates.DateLocator):
386
+ UNIT = 1.0 / (24 * 3600 * 1000)
387
+
388
+ def __init__(self, tz) -> None:
389
+ mdates.DateLocator.__init__(self, tz)
390
+ self._interval = 1.0
391
+
392
+ def _get_unit(self):
393
+ return self.get_unit_generic(-1)
394
+
395
+ @staticmethod
396
+ def get_unit_generic(freq):
397
+ unit = mdates.RRuleLocator.get_unit_generic(freq)
398
+ if unit < 0:
399
+ return MilliSecondLocator.UNIT
400
+ return unit
401
+
402
+ def __call__(self):
403
+ # if no data have been set, this will tank with a ValueError
404
+ try:
405
+ dmin, dmax = self.viewlim_to_dt()
406
+ except ValueError:
407
+ return []
408
+
409
+ # We need to cap at the endpoints of valid datetime
410
+ nmax, nmin = mdates.date2num((dmax, dmin))
411
+
412
+ num = (nmax - nmin) * 86400 * 1000
413
+ max_millis_ticks = 6
414
+ for interval in [1, 10, 50, 100, 200, 500]:
415
+ if num <= interval * (max_millis_ticks - 1):
416
+ self._interval = interval
417
+ break
418
+ # We went through the whole loop without breaking, default to 1
419
+ self._interval = 1000.0
420
+
421
+ estimate = (nmax - nmin) / (self._get_unit() * self._get_interval())
422
+
423
+ if estimate > self.MAXTICKS * 2:
424
+ raise RuntimeError(
425
+ "MillisecondLocator estimated to generate "
426
+ f"{estimate:d} ticks from {dmin} to {dmax}: exceeds Locator.MAXTICKS"
427
+ f"* 2 ({self.MAXTICKS * 2:d}) "
428
+ )
429
+
430
+ interval = self._get_interval()
431
+ freq = f"{interval}ms"
432
+ tz = self.tz.tzname(None)
433
+ st = dmin.replace(tzinfo=None)
434
+ ed = dmin.replace(tzinfo=None)
435
+ all_dates = date_range(start=st, end=ed, freq=freq, tz=tz).astype(object)
436
+
437
+ try:
438
+ if len(all_dates) > 0:
439
+ locs = self.raise_if_exceeds(mdates.date2num(all_dates))
440
+ return locs
441
+ except Exception: # pragma: no cover
442
+ pass
443
+
444
+ lims = mdates.date2num([dmin, dmax])
445
+ return lims
446
+
447
+ def _get_interval(self):
448
+ return self._interval
449
+
450
+ def autoscale(self):
451
+ """
452
+ Set the view limits to include the data range.
453
+ """
454
+ # We need to cap at the endpoints of valid datetime
455
+ dmin, dmax = self.datalim_to_dt()
456
+
457
+ vmin = mdates.date2num(dmin)
458
+ vmax = mdates.date2num(dmax)
459
+
460
+ return self.nonsingular(vmin, vmax)
461
+
462
+
463
+ def _from_ordinal(x, tz: tzinfo | None = None) -> datetime:
464
+ ix = int(x)
465
+ dt = datetime.fromordinal(ix)
466
+ remainder = float(x) - ix
467
+ hour, remainder = divmod(24 * remainder, 1)
468
+ minute, remainder = divmod(60 * remainder, 1)
469
+ second, remainder = divmod(60 * remainder, 1)
470
+ microsecond = int(1_000_000 * remainder)
471
+ if microsecond < 10:
472
+ microsecond = 0 # compensate for rounding errors
473
+ dt = datetime(
474
+ dt.year, dt.month, dt.day, int(hour), int(minute), int(second), microsecond
475
+ )
476
+ if tz is not None:
477
+ dt = dt.astimezone(tz)
478
+
479
+ if microsecond > 999990: # compensate for rounding errors
480
+ dt += timedelta(microseconds=1_000_000 - microsecond)
481
+
482
+ return dt
483
+
484
+
485
+ # Fixed frequency dynamic tick locators and formatters
486
+
487
+ # -------------------------------------------------------------------------
488
+ # --- Locators ---
489
+ # -------------------------------------------------------------------------
490
+
491
+
492
+ def _get_default_annual_spacing(nyears) -> tuple[int, int]:
493
+ """
494
+ Returns a default spacing between consecutive ticks for annual data.
495
+ """
496
+ if nyears < 11:
497
+ (min_spacing, maj_spacing) = (1, 1)
498
+ elif nyears < 20:
499
+ (min_spacing, maj_spacing) = (1, 2)
500
+ elif nyears < 50:
501
+ (min_spacing, maj_spacing) = (1, 5)
502
+ elif nyears < 100:
503
+ (min_spacing, maj_spacing) = (5, 10)
504
+ elif nyears < 200:
505
+ (min_spacing, maj_spacing) = (5, 25)
506
+ elif nyears < 600:
507
+ (min_spacing, maj_spacing) = (10, 50)
508
+ else:
509
+ factor = nyears // 1000 + 1
510
+ (min_spacing, maj_spacing) = (factor * 20, factor * 100)
511
+ return (min_spacing, maj_spacing)
512
+
513
+
514
+ def _period_break(dates: PeriodIndex, period: str) -> npt.NDArray[np.intp]:
515
+ """
516
+ Returns the indices where the given period changes.
517
+
518
+ Parameters
519
+ ----------
520
+ dates : PeriodIndex
521
+ Array of intervals to monitor.
522
+ period : str
523
+ Name of the period to monitor.
524
+ """
525
+ mask = _period_break_mask(dates, period)
526
+ return np.nonzero(mask)[0]
527
+
528
+
529
+ def _period_break_mask(dates: PeriodIndex, period: str) -> npt.NDArray[np.bool_]:
530
+ current = getattr(dates, period)
531
+ previous = getattr(dates - 1 * dates.freq, period)
532
+ return current != previous
533
+
534
+
535
+ def has_level_label(label_flags: npt.NDArray[np.intp], vmin: float) -> bool:
536
+ """
537
+ Returns true if the ``label_flags`` indicate there is at least one label
538
+ for this level.
539
+
540
+ if the minimum view limit is not an exact integer, then the first tick
541
+ label won't be shown, so we must adjust for that.
542
+ """
543
+ if label_flags.size == 0 or (
544
+ label_flags.size == 1 and label_flags[0] == 0 and vmin % 1 > 0.0
545
+ ):
546
+ return False
547
+ else:
548
+ return True
549
+
550
+
551
+ def _get_periods_per_ymd(freq: BaseOffset) -> tuple[int, int, int]:
552
+ # error: "BaseOffset" has no attribute "_period_dtype_code"
553
+ dtype_code = freq._period_dtype_code # type: ignore[attr-defined]
554
+ freq_group = FreqGroup.from_period_dtype_code(dtype_code)
555
+
556
+ ppd = -1 # placeholder for above-day freqs
557
+
558
+ if dtype_code >= FreqGroup.FR_HR.value:
559
+ # error: "BaseOffset" has no attribute "_creso"
560
+ ppd = periods_per_day(freq._creso) # type: ignore[attr-defined]
561
+ ppm = 28 * ppd
562
+ ppy = 365 * ppd
563
+ elif freq_group == FreqGroup.FR_BUS:
564
+ ppm = 19
565
+ ppy = 261
566
+ elif freq_group == FreqGroup.FR_DAY:
567
+ ppm = 28
568
+ ppy = 365
569
+ elif freq_group == FreqGroup.FR_WK:
570
+ ppm = 3
571
+ ppy = 52
572
+ elif freq_group == FreqGroup.FR_MTH:
573
+ ppm = 1
574
+ ppy = 12
575
+ elif freq_group == FreqGroup.FR_QTR:
576
+ ppm = -1 # placerholder
577
+ ppy = 4
578
+ elif freq_group == FreqGroup.FR_ANN:
579
+ ppm = -1 # placeholder
580
+ ppy = 1
581
+ else:
582
+ raise NotImplementedError(f"Unsupported frequency: {dtype_code}")
583
+
584
+ return ppd, ppm, ppy
585
+
586
+
587
+ @functools.cache
588
+ def _daily_finder(vmin: float, vmax: float, freq: BaseOffset) -> np.ndarray:
589
+ # error: "BaseOffset" has no attribute "_period_dtype_code"
590
+ dtype_code = freq._period_dtype_code # type: ignore[attr-defined]
591
+
592
+ periodsperday, periodspermonth, periodsperyear = _get_periods_per_ymd(freq)
593
+
594
+ # save this for later usage
595
+ vmin_orig = vmin
596
+ (vmin, vmax) = (int(vmin), int(vmax))
597
+ span = vmax - vmin + 1
598
+
599
+ with warnings.catch_warnings():
600
+ warnings.filterwarnings(
601
+ "ignore", "Period with BDay freq is deprecated", category=FutureWarning
602
+ )
603
+ warnings.filterwarnings(
604
+ "ignore", r"PeriodDtype\[B\] is deprecated", category=FutureWarning
605
+ )
606
+ dates_ = period_range(
607
+ start=Period(ordinal=vmin, freq=freq),
608
+ end=Period(ordinal=vmax, freq=freq),
609
+ freq=freq,
610
+ )
611
+
612
+ # Initialize the output
613
+ info = np.zeros(
614
+ span, dtype=[("val", np.int64), ("maj", bool), ("min", bool), ("fmt", "|S20")]
615
+ )
616
+ info["val"][:] = dates_.asi8
617
+ info["fmt"][:] = ""
618
+ info["maj"][[0, -1]] = True
619
+ # .. and set some shortcuts
620
+ info_maj = info["maj"]
621
+ info_min = info["min"]
622
+ info_fmt = info["fmt"]
623
+
624
+ def first_label(label_flags):
625
+ if (label_flags[0] == 0) and (label_flags.size > 1) and ((vmin_orig % 1) > 0.0):
626
+ return label_flags[1]
627
+ else:
628
+ return label_flags[0]
629
+
630
+ # Case 1. Less than a month
631
+ if span <= periodspermonth:
632
+ day_start = _period_break(dates_, "day")
633
+ month_start = _period_break(dates_, "month")
634
+ year_start = _period_break(dates_, "year")
635
+
636
+ def _hour_finder(label_interval: int, force_year_start: bool) -> None:
637
+ target = dates_.hour
638
+ mask = _period_break_mask(dates_, "hour")
639
+ info_maj[day_start] = True
640
+ info_min[mask & (target % label_interval == 0)] = True
641
+ info_fmt[mask & (target % label_interval == 0)] = "%H:%M"
642
+ info_fmt[day_start] = "%H:%M\n%d-%b"
643
+ info_fmt[year_start] = "%H:%M\n%d-%b\n%Y"
644
+ if force_year_start and not has_level_label(year_start, vmin_orig):
645
+ info_fmt[first_label(day_start)] = "%H:%M\n%d-%b\n%Y"
646
+
647
+ def _minute_finder(label_interval: int) -> None:
648
+ target = dates_.minute
649
+ hour_start = _period_break(dates_, "hour")
650
+ mask = _period_break_mask(dates_, "minute")
651
+ info_maj[hour_start] = True
652
+ info_min[mask & (target % label_interval == 0)] = True
653
+ info_fmt[mask & (target % label_interval == 0)] = "%H:%M"
654
+ info_fmt[day_start] = "%H:%M\n%d-%b"
655
+ info_fmt[year_start] = "%H:%M\n%d-%b\n%Y"
656
+
657
+ def _second_finder(label_interval: int) -> None:
658
+ target = dates_.second
659
+ minute_start = _period_break(dates_, "minute")
660
+ mask = _period_break_mask(dates_, "second")
661
+ info_maj[minute_start] = True
662
+ info_min[mask & (target % label_interval == 0)] = True
663
+ info_fmt[mask & (target % label_interval == 0)] = "%H:%M:%S"
664
+ info_fmt[day_start] = "%H:%M:%S\n%d-%b"
665
+ info_fmt[year_start] = "%H:%M:%S\n%d-%b\n%Y"
666
+
667
+ if span < periodsperday / 12000:
668
+ _second_finder(1)
669
+ elif span < periodsperday / 6000:
670
+ _second_finder(2)
671
+ elif span < periodsperday / 2400:
672
+ _second_finder(5)
673
+ elif span < periodsperday / 1200:
674
+ _second_finder(10)
675
+ elif span < periodsperday / 800:
676
+ _second_finder(15)
677
+ elif span < periodsperday / 400:
678
+ _second_finder(30)
679
+ elif span < periodsperday / 150:
680
+ _minute_finder(1)
681
+ elif span < periodsperday / 70:
682
+ _minute_finder(2)
683
+ elif span < periodsperday / 24:
684
+ _minute_finder(5)
685
+ elif span < periodsperday / 12:
686
+ _minute_finder(15)
687
+ elif span < periodsperday / 6:
688
+ _minute_finder(30)
689
+ elif span < periodsperday / 2.5:
690
+ _hour_finder(1, False)
691
+ elif span < periodsperday / 1.5:
692
+ _hour_finder(2, False)
693
+ elif span < periodsperday * 1.25:
694
+ _hour_finder(3, False)
695
+ elif span < periodsperday * 2.5:
696
+ _hour_finder(6, True)
697
+ elif span < periodsperday * 4:
698
+ _hour_finder(12, True)
699
+ else:
700
+ info_maj[month_start] = True
701
+ info_min[day_start] = True
702
+ info_fmt[day_start] = "%d"
703
+ info_fmt[month_start] = "%d\n%b"
704
+ info_fmt[year_start] = "%d\n%b\n%Y"
705
+ if not has_level_label(year_start, vmin_orig):
706
+ if not has_level_label(month_start, vmin_orig):
707
+ info_fmt[first_label(day_start)] = "%d\n%b\n%Y"
708
+ else:
709
+ info_fmt[first_label(month_start)] = "%d\n%b\n%Y"
710
+
711
+ # Case 2. Less than three months
712
+ elif span <= periodsperyear // 4:
713
+ month_start = _period_break(dates_, "month")
714
+ info_maj[month_start] = True
715
+ if dtype_code < FreqGroup.FR_HR.value:
716
+ info["min"] = True
717
+ else:
718
+ day_start = _period_break(dates_, "day")
719
+ info["min"][day_start] = True
720
+ week_start = _period_break(dates_, "week")
721
+ year_start = _period_break(dates_, "year")
722
+ info_fmt[week_start] = "%d"
723
+ info_fmt[month_start] = "\n\n%b"
724
+ info_fmt[year_start] = "\n\n%b\n%Y"
725
+ if not has_level_label(year_start, vmin_orig):
726
+ if not has_level_label(month_start, vmin_orig):
727
+ info_fmt[first_label(week_start)] = "\n\n%b\n%Y"
728
+ else:
729
+ info_fmt[first_label(month_start)] = "\n\n%b\n%Y"
730
+ # Case 3. Less than 14 months ...............
731
+ elif span <= 1.15 * periodsperyear:
732
+ year_start = _period_break(dates_, "year")
733
+ month_start = _period_break(dates_, "month")
734
+ week_start = _period_break(dates_, "week")
735
+ info_maj[month_start] = True
736
+ info_min[week_start] = True
737
+ info_min[year_start] = False
738
+ info_min[month_start] = False
739
+ info_fmt[month_start] = "%b"
740
+ info_fmt[year_start] = "%b\n%Y"
741
+ if not has_level_label(year_start, vmin_orig):
742
+ info_fmt[first_label(month_start)] = "%b\n%Y"
743
+ # Case 4. Less than 2.5 years ...............
744
+ elif span <= 2.5 * periodsperyear:
745
+ year_start = _period_break(dates_, "year")
746
+ quarter_start = _period_break(dates_, "quarter")
747
+ month_start = _period_break(dates_, "month")
748
+ info_maj[quarter_start] = True
749
+ info_min[month_start] = True
750
+ info_fmt[quarter_start] = "%b"
751
+ info_fmt[year_start] = "%b\n%Y"
752
+ # Case 4. Less than 4 years .................
753
+ elif span <= 4 * periodsperyear:
754
+ year_start = _period_break(dates_, "year")
755
+ month_start = _period_break(dates_, "month")
756
+ info_maj[year_start] = True
757
+ info_min[month_start] = True
758
+ info_min[year_start] = False
759
+
760
+ month_break = dates_[month_start].month
761
+ jan_or_jul = month_start[(month_break == 1) | (month_break == 7)]
762
+ info_fmt[jan_or_jul] = "%b"
763
+ info_fmt[year_start] = "%b\n%Y"
764
+ # Case 5. Less than 11 years ................
765
+ elif span <= 11 * periodsperyear:
766
+ year_start = _period_break(dates_, "year")
767
+ quarter_start = _period_break(dates_, "quarter")
768
+ info_maj[year_start] = True
769
+ info_min[quarter_start] = True
770
+ info_min[year_start] = False
771
+ info_fmt[year_start] = "%Y"
772
+ # Case 6. More than 12 years ................
773
+ else:
774
+ year_start = _period_break(dates_, "year")
775
+ year_break = dates_[year_start].year
776
+ nyears = span / periodsperyear
777
+ (min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
778
+ major_idx = year_start[(year_break % maj_anndef == 0)]
779
+ info_maj[major_idx] = True
780
+ minor_idx = year_start[(year_break % min_anndef == 0)]
781
+ info_min[minor_idx] = True
782
+ info_fmt[major_idx] = "%Y"
783
+
784
+ return info
785
+
786
+
787
+ @functools.cache
788
+ def _monthly_finder(vmin: float, vmax: float, freq: BaseOffset) -> np.ndarray:
789
+ _, _, periodsperyear = _get_periods_per_ymd(freq)
790
+
791
+ vmin_orig = vmin
792
+ (vmin, vmax) = (int(vmin), int(vmax))
793
+ span = vmax - vmin + 1
794
+
795
+ # Initialize the output
796
+ info = np.zeros(
797
+ span, dtype=[("val", int), ("maj", bool), ("min", bool), ("fmt", "|S8")]
798
+ )
799
+ info["val"] = np.arange(vmin, vmax + 1)
800
+ dates_ = info["val"]
801
+ info["fmt"] = ""
802
+ year_start = (dates_ % 12 == 0).nonzero()[0]
803
+ info_maj = info["maj"]
804
+ info_fmt = info["fmt"]
805
+
806
+ if span <= 1.15 * periodsperyear:
807
+ info_maj[year_start] = True
808
+ info["min"] = True
809
+
810
+ info_fmt[:] = "%b"
811
+ info_fmt[year_start] = "%b\n%Y"
812
+
813
+ if not has_level_label(year_start, vmin_orig):
814
+ if dates_.size > 1:
815
+ idx = 1
816
+ else:
817
+ idx = 0
818
+ info_fmt[idx] = "%b\n%Y"
819
+
820
+ elif span <= 2.5 * periodsperyear:
821
+ quarter_start = (dates_ % 3 == 0).nonzero()
822
+ info_maj[year_start] = True
823
+ # TODO: Check the following : is it really info['fmt'] ?
824
+ # 2023-09-15 this is reached in test_finder_monthly
825
+ info["fmt"][quarter_start] = True
826
+ info["min"] = True
827
+
828
+ info_fmt[quarter_start] = "%b"
829
+ info_fmt[year_start] = "%b\n%Y"
830
+
831
+ elif span <= 4 * periodsperyear:
832
+ info_maj[year_start] = True
833
+ info["min"] = True
834
+
835
+ jan_or_jul = (dates_ % 12 == 0) | (dates_ % 12 == 6)
836
+ info_fmt[jan_or_jul] = "%b"
837
+ info_fmt[year_start] = "%b\n%Y"
838
+
839
+ elif span <= 11 * periodsperyear:
840
+ quarter_start = (dates_ % 3 == 0).nonzero()
841
+ info_maj[year_start] = True
842
+ info["min"][quarter_start] = True
843
+
844
+ info_fmt[year_start] = "%Y"
845
+
846
+ else:
847
+ nyears = span / periodsperyear
848
+ (min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
849
+ years = dates_[year_start] // 12 + 1
850
+ major_idx = year_start[(years % maj_anndef == 0)]
851
+ info_maj[major_idx] = True
852
+ info["min"][year_start[(years % min_anndef == 0)]] = True
853
+
854
+ info_fmt[major_idx] = "%Y"
855
+
856
+ return info
857
+
858
+
859
+ @functools.cache
860
+ def _quarterly_finder(vmin: float, vmax: float, freq: BaseOffset) -> np.ndarray:
861
+ _, _, periodsperyear = _get_periods_per_ymd(freq)
862
+ vmin_orig = vmin
863
+ (vmin, vmax) = (int(vmin), int(vmax))
864
+ span = vmax - vmin + 1
865
+
866
+ info = np.zeros(
867
+ span, dtype=[("val", int), ("maj", bool), ("min", bool), ("fmt", "|S8")]
868
+ )
869
+ info["val"] = np.arange(vmin, vmax + 1)
870
+ info["fmt"] = ""
871
+ dates_ = info["val"]
872
+ info_maj = info["maj"]
873
+ info_fmt = info["fmt"]
874
+ year_start = (dates_ % 4 == 0).nonzero()[0]
875
+
876
+ if span <= 3.5 * periodsperyear:
877
+ info_maj[year_start] = True
878
+ info["min"] = True
879
+
880
+ info_fmt[:] = "Q%q"
881
+ info_fmt[year_start] = "Q%q\n%F"
882
+ if not has_level_label(year_start, vmin_orig):
883
+ if dates_.size > 1:
884
+ idx = 1
885
+ else:
886
+ idx = 0
887
+ info_fmt[idx] = "Q%q\n%F"
888
+
889
+ elif span <= 11 * periodsperyear:
890
+ info_maj[year_start] = True
891
+ info["min"] = True
892
+ info_fmt[year_start] = "%F"
893
+
894
+ else:
895
+ # https://github.com/pandas-dev/pandas/pull/47602
896
+ years = dates_[year_start] // 4 + 1970
897
+ nyears = span / periodsperyear
898
+ (min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
899
+ major_idx = year_start[(years % maj_anndef == 0)]
900
+ info_maj[major_idx] = True
901
+ info["min"][year_start[(years % min_anndef == 0)]] = True
902
+ info_fmt[major_idx] = "%F"
903
+
904
+ return info
905
+
906
+
907
+ @functools.cache
908
+ def _annual_finder(vmin: float, vmax: float, freq: BaseOffset) -> np.ndarray:
909
+ # Note: small difference here vs other finders in adding 1 to vmax
910
+ (vmin, vmax) = (int(vmin), int(vmax + 1))
911
+ span = vmax - vmin + 1
912
+
913
+ info = np.zeros(
914
+ span, dtype=[("val", int), ("maj", bool), ("min", bool), ("fmt", "|S8")]
915
+ )
916
+ info["val"] = np.arange(vmin, vmax + 1)
917
+ info["fmt"] = ""
918
+ dates_ = info["val"]
919
+
920
+ (min_anndef, maj_anndef) = _get_default_annual_spacing(span)
921
+ major_idx = dates_ % maj_anndef == 0
922
+ minor_idx = dates_ % min_anndef == 0
923
+ info["maj"][major_idx] = True
924
+ info["min"][minor_idx] = True
925
+ info["fmt"][major_idx] = "%Y"
926
+
927
+ return info
928
+
929
+
930
+ def get_finder(freq: BaseOffset):
931
+ # error: "BaseOffset" has no attribute "_period_dtype_code"
932
+ dtype_code = freq._period_dtype_code # type: ignore[attr-defined]
933
+ fgroup = FreqGroup.from_period_dtype_code(dtype_code)
934
+
935
+ if fgroup == FreqGroup.FR_ANN:
936
+ return _annual_finder
937
+ elif fgroup == FreqGroup.FR_QTR:
938
+ return _quarterly_finder
939
+ elif fgroup == FreqGroup.FR_MTH:
940
+ return _monthly_finder
941
+ elif (dtype_code >= FreqGroup.FR_BUS.value) or fgroup == FreqGroup.FR_WK:
942
+ return _daily_finder
943
+ else: # pragma: no cover
944
+ raise NotImplementedError(f"Unsupported frequency: {dtype_code}")
945
+
946
+
947
+ class TimeSeries_DateLocator(Locator):
948
+ """
949
+ Locates the ticks along an axis controlled by a :class:`Series`.
950
+
951
+ Parameters
952
+ ----------
953
+ freq : BaseOffset
954
+ Valid frequency specifier.
955
+ minor_locator : {False, True}, optional
956
+ Whether the locator is for minor ticks (True) or not.
957
+ dynamic_mode : {True, False}, optional
958
+ Whether the locator should work in dynamic mode.
959
+ base : {int}, optional
960
+ quarter : {int}, optional
961
+ month : {int}, optional
962
+ day : {int}, optional
963
+ """
964
+
965
+ axis: Axis
966
+
967
+ def __init__(
968
+ self,
969
+ freq: BaseOffset,
970
+ minor_locator: bool = False,
971
+ dynamic_mode: bool = True,
972
+ base: int = 1,
973
+ quarter: int = 1,
974
+ month: int = 1,
975
+ day: int = 1,
976
+ plot_obj=None,
977
+ ) -> None:
978
+ freq = to_offset(freq, is_period=True)
979
+ self.freq = freq
980
+ self.base = base
981
+ (self.quarter, self.month, self.day) = (quarter, month, day)
982
+ self.isminor = minor_locator
983
+ self.isdynamic = dynamic_mode
984
+ self.offset = 0
985
+ self.plot_obj = plot_obj
986
+ self.finder = get_finder(freq)
987
+
988
+ def _get_default_locs(self, vmin, vmax):
989
+ """Returns the default locations of ticks."""
990
+ locator = self.finder(vmin, vmax, self.freq)
991
+
992
+ if self.isminor:
993
+ return np.compress(locator["min"], locator["val"])
994
+ return np.compress(locator["maj"], locator["val"])
995
+
996
+ def __call__(self):
997
+ """Return the locations of the ticks."""
998
+ # axis calls Locator.set_axis inside set_m<xxxx>_formatter
999
+
1000
+ vi = tuple(self.axis.get_view_interval())
1001
+ vmin, vmax = vi
1002
+ if vmax < vmin:
1003
+ vmin, vmax = vmax, vmin
1004
+ if self.isdynamic:
1005
+ locs = self._get_default_locs(vmin, vmax)
1006
+ else: # pragma: no cover
1007
+ base = self.base
1008
+ (d, m) = divmod(vmin, base)
1009
+ vmin = (d + 1) * base
1010
+ # error: No overload variant of "range" matches argument types "float",
1011
+ # "float", "int"
1012
+ locs = list(range(vmin, vmax + 1, base)) # type: ignore[call-overload]
1013
+ return locs
1014
+
1015
+ def autoscale(self):
1016
+ """
1017
+ Sets the view limits to the nearest multiples of base that contain the
1018
+ data.
1019
+ """
1020
+ # requires matplotlib >= 0.98.0
1021
+ (vmin, vmax) = self.axis.get_data_interval()
1022
+
1023
+ locs = self._get_default_locs(vmin, vmax)
1024
+ (vmin, vmax) = locs[[0, -1]]
1025
+ if vmin == vmax:
1026
+ vmin -= 1
1027
+ vmax += 1
1028
+ return nonsingular(vmin, vmax)
1029
+
1030
+
1031
+ # -------------------------------------------------------------------------
1032
+ # --- Formatter ---
1033
+ # -------------------------------------------------------------------------
1034
+
1035
+
1036
+ class TimeSeries_DateFormatter(Formatter):
1037
+ """
1038
+ Formats the ticks along an axis controlled by a :class:`PeriodIndex`.
1039
+
1040
+ Parameters
1041
+ ----------
1042
+ freq : BaseOffset
1043
+ Valid frequency specifier.
1044
+ minor_locator : bool, default False
1045
+ Whether the current formatter should apply to minor ticks (True) or
1046
+ major ticks (False).
1047
+ dynamic_mode : bool, default True
1048
+ Whether the formatter works in dynamic mode or not.
1049
+ """
1050
+
1051
+ axis: Axis
1052
+
1053
+ def __init__(
1054
+ self,
1055
+ freq: BaseOffset,
1056
+ minor_locator: bool = False,
1057
+ dynamic_mode: bool = True,
1058
+ plot_obj=None,
1059
+ ) -> None:
1060
+ freq = to_offset(freq, is_period=True)
1061
+ self.format = None
1062
+ self.freq = freq
1063
+ self.locs: list[Any] = [] # unused, for matplotlib compat
1064
+ self.formatdict: dict[Any, Any] | None = None
1065
+ self.isminor = minor_locator
1066
+ self.isdynamic = dynamic_mode
1067
+ self.offset = 0
1068
+ self.plot_obj = plot_obj
1069
+ self.finder = get_finder(freq)
1070
+
1071
+ def _set_default_format(self, vmin, vmax):
1072
+ """Returns the default ticks spacing."""
1073
+ info = self.finder(vmin, vmax, self.freq)
1074
+
1075
+ if self.isminor:
1076
+ format = np.compress(info["min"] & np.logical_not(info["maj"]), info)
1077
+ else:
1078
+ format = np.compress(info["maj"], info)
1079
+ self.formatdict = {x: f for (x, _, _, f) in format}
1080
+ return self.formatdict
1081
+
1082
+ def set_locs(self, locs) -> None:
1083
+ """Sets the locations of the ticks"""
1084
+ # don't actually use the locs. This is just needed to work with
1085
+ # matplotlib. Force to use vmin, vmax
1086
+
1087
+ self.locs = locs
1088
+
1089
+ (vmin, vmax) = tuple(self.axis.get_view_interval())
1090
+ if vmax < vmin:
1091
+ (vmin, vmax) = (vmax, vmin)
1092
+ self._set_default_format(vmin, vmax)
1093
+
1094
+ def __call__(self, x, pos: int | None = 0) -> str:
1095
+ if self.formatdict is None:
1096
+ return ""
1097
+ else:
1098
+ fmt = self.formatdict.pop(x, "")
1099
+ if isinstance(fmt, np.bytes_):
1100
+ fmt = fmt.decode("utf-8")
1101
+ with warnings.catch_warnings():
1102
+ warnings.filterwarnings(
1103
+ "ignore",
1104
+ "Period with BDay freq is deprecated",
1105
+ category=FutureWarning,
1106
+ )
1107
+ period = Period(ordinal=int(x), freq=self.freq)
1108
+ assert isinstance(period, Period)
1109
+ return period.strftime(fmt)
1110
+
1111
+
1112
+ class TimeSeries_TimedeltaFormatter(Formatter):
1113
+ """
1114
+ Formats the ticks along an axis controlled by a :class:`TimedeltaIndex`.
1115
+ """
1116
+
1117
+ axis: Axis
1118
+
1119
+ @staticmethod
1120
+ def format_timedelta_ticks(x, pos, n_decimals: int) -> str:
1121
+ """
1122
+ Convert seconds to 'D days HH:MM:SS.F'
1123
+ """
1124
+ s, ns = divmod(x, 10**9) # TODO(non-nano): this looks like it assumes ns
1125
+ m, s = divmod(s, 60)
1126
+ h, m = divmod(m, 60)
1127
+ d, h = divmod(h, 24)
1128
+ decimals = int(ns * 10 ** (n_decimals - 9))
1129
+ s = f"{int(h):02d}:{int(m):02d}:{int(s):02d}"
1130
+ if n_decimals > 0:
1131
+ s += f".{decimals:0{n_decimals}d}"
1132
+ if d != 0:
1133
+ s = f"{int(d):d} days {s}"
1134
+ return s
1135
+
1136
+ def __call__(self, x, pos: int | None = 0) -> str:
1137
+ (vmin, vmax) = tuple(self.axis.get_view_interval())
1138
+ n_decimals = min(int(np.ceil(np.log10(100 * 10**9 / abs(vmax - vmin)))), 9)
1139
+ return self.format_timedelta_ticks(x, pos, n_decimals)
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py ADDED
@@ -0,0 +1,2125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import (
4
+ ABC,
5
+ abstractmethod,
6
+ )
7
+ from collections.abc import (
8
+ Hashable,
9
+ Iterable,
10
+ Iterator,
11
+ Sequence,
12
+ )
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ Literal,
17
+ cast,
18
+ final,
19
+ )
20
+ import warnings
21
+
22
+ import matplotlib as mpl
23
+ import numpy as np
24
+
25
+ from pandas._libs import lib
26
+ from pandas.errors import AbstractMethodError
27
+ from pandas.util._decorators import cache_readonly
28
+ from pandas.util._exceptions import find_stack_level
29
+
30
+ from pandas.core.dtypes.common import (
31
+ is_any_real_numeric_dtype,
32
+ is_bool,
33
+ is_float,
34
+ is_float_dtype,
35
+ is_hashable,
36
+ is_integer,
37
+ is_integer_dtype,
38
+ is_iterator,
39
+ is_list_like,
40
+ is_number,
41
+ is_numeric_dtype,
42
+ )
43
+ from pandas.core.dtypes.dtypes import (
44
+ CategoricalDtype,
45
+ ExtensionDtype,
46
+ )
47
+ from pandas.core.dtypes.generic import (
48
+ ABCDataFrame,
49
+ ABCDatetimeIndex,
50
+ ABCIndex,
51
+ ABCMultiIndex,
52
+ ABCPeriodIndex,
53
+ ABCSeries,
54
+ )
55
+ from pandas.core.dtypes.missing import isna
56
+
57
+ import pandas.core.common as com
58
+ from pandas.core.frame import DataFrame
59
+ from pandas.util.version import Version
60
+
61
+ from pandas.io.formats.printing import pprint_thing
62
+ from pandas.plotting._matplotlib import tools
63
+ from pandas.plotting._matplotlib.converter import register_pandas_matplotlib_converters
64
+ from pandas.plotting._matplotlib.groupby import reconstruct_data_with_by
65
+ from pandas.plotting._matplotlib.misc import unpack_single_str_list
66
+ from pandas.plotting._matplotlib.style import get_standard_colors
67
+ from pandas.plotting._matplotlib.timeseries import (
68
+ decorate_axes,
69
+ format_dateaxis,
70
+ maybe_convert_index,
71
+ maybe_resample,
72
+ use_dynamic_x,
73
+ )
74
+ from pandas.plotting._matplotlib.tools import (
75
+ create_subplots,
76
+ flatten_axes,
77
+ format_date_labels,
78
+ get_all_lines,
79
+ get_xlim,
80
+ handle_shared_axes,
81
+ )
82
+
83
+ if TYPE_CHECKING:
84
+ from matplotlib.artist import Artist
85
+ from matplotlib.axes import Axes
86
+ from matplotlib.axis import Axis
87
+ from matplotlib.figure import Figure
88
+
89
+ from pandas._typing import (
90
+ IndexLabel,
91
+ NDFrameT,
92
+ PlottingOrientation,
93
+ npt,
94
+ )
95
+
96
+ from pandas import Series
97
+
98
+
99
+ def _color_in_style(style: str) -> bool:
100
+ """
101
+ Check if there is a color letter in the style string.
102
+ """
103
+ from matplotlib.colors import BASE_COLORS
104
+
105
+ return not set(BASE_COLORS).isdisjoint(style)
106
+
107
+
108
+ class MPLPlot(ABC):
109
+ """
110
+ Base class for assembling a pandas plot using matplotlib
111
+
112
+ Parameters
113
+ ----------
114
+ data :
115
+
116
+ """
117
+
118
+ @property
119
+ @abstractmethod
120
+ def _kind(self) -> str:
121
+ """Specify kind str. Must be overridden in child class"""
122
+ raise NotImplementedError
123
+
124
+ _layout_type = "vertical"
125
+ _default_rot = 0
126
+
127
+ @property
128
+ def orientation(self) -> str | None:
129
+ return None
130
+
131
+ data: DataFrame
132
+
133
+ def __init__(
134
+ self,
135
+ data,
136
+ kind=None,
137
+ by: IndexLabel | None = None,
138
+ subplots: bool | Sequence[Sequence[str]] = False,
139
+ sharex: bool | None = None,
140
+ sharey: bool = False,
141
+ use_index: bool = True,
142
+ figsize: tuple[float, float] | None = None,
143
+ grid=None,
144
+ legend: bool | str = True,
145
+ rot=None,
146
+ ax=None,
147
+ fig=None,
148
+ title=None,
149
+ xlim=None,
150
+ ylim=None,
151
+ xticks=None,
152
+ yticks=None,
153
+ xlabel: Hashable | None = None,
154
+ ylabel: Hashable | None = None,
155
+ fontsize: int | None = None,
156
+ secondary_y: bool | tuple | list | np.ndarray = False,
157
+ colormap=None,
158
+ table: bool = False,
159
+ layout=None,
160
+ include_bool: bool = False,
161
+ column: IndexLabel | None = None,
162
+ *,
163
+ logx: bool | None | Literal["sym"] = False,
164
+ logy: bool | None | Literal["sym"] = False,
165
+ loglog: bool | None | Literal["sym"] = False,
166
+ mark_right: bool = True,
167
+ stacked: bool = False,
168
+ label: Hashable | None = None,
169
+ style=None,
170
+ **kwds,
171
+ ) -> None:
172
+ import matplotlib.pyplot as plt
173
+
174
+ # if users assign an empty list or tuple, raise `ValueError`
175
+ # similar to current `df.box` and `df.hist` APIs.
176
+ if by in ([], ()):
177
+ raise ValueError("No group keys passed!")
178
+ self.by = com.maybe_make_list(by)
179
+
180
+ # Assign the rest of columns into self.columns if by is explicitly defined
181
+ # while column is not, only need `columns` in hist/box plot when it's DF
182
+ # TODO: Might deprecate `column` argument in future PR (#28373)
183
+ if isinstance(data, DataFrame):
184
+ if column:
185
+ self.columns = com.maybe_make_list(column)
186
+ elif self.by is None:
187
+ self.columns = [
188
+ col for col in data.columns if is_numeric_dtype(data[col])
189
+ ]
190
+ else:
191
+ self.columns = [
192
+ col
193
+ for col in data.columns
194
+ if col not in self.by and is_numeric_dtype(data[col])
195
+ ]
196
+
197
+ # For `hist` plot, need to get grouped original data before `self.data` is
198
+ # updated later
199
+ if self.by is not None and self._kind == "hist":
200
+ self._grouped = data.groupby(unpack_single_str_list(self.by))
201
+
202
+ self.kind = kind
203
+
204
+ self.subplots = type(self)._validate_subplots_kwarg(
205
+ subplots, data, kind=self._kind
206
+ )
207
+
208
+ self.sharex = type(self)._validate_sharex(sharex, ax, by)
209
+ self.sharey = sharey
210
+ self.figsize = figsize
211
+ self.layout = layout
212
+
213
+ self.xticks = xticks
214
+ self.yticks = yticks
215
+ self.xlim = xlim
216
+ self.ylim = ylim
217
+ self.title = title
218
+ self.use_index = use_index
219
+ self.xlabel = xlabel
220
+ self.ylabel = ylabel
221
+
222
+ self.fontsize = fontsize
223
+
224
+ if rot is not None:
225
+ self.rot = rot
226
+ # need to know for format_date_labels since it's rotated to 30 by
227
+ # default
228
+ self._rot_set = True
229
+ else:
230
+ self._rot_set = False
231
+ self.rot = self._default_rot
232
+
233
+ if grid is None:
234
+ grid = False if secondary_y else plt.rcParams["axes.grid"]
235
+
236
+ self.grid = grid
237
+ self.legend = legend
238
+ self.legend_handles: list[Artist] = []
239
+ self.legend_labels: list[Hashable] = []
240
+
241
+ self.logx = type(self)._validate_log_kwd("logx", logx)
242
+ self.logy = type(self)._validate_log_kwd("logy", logy)
243
+ self.loglog = type(self)._validate_log_kwd("loglog", loglog)
244
+ self.label = label
245
+ self.style = style
246
+ self.mark_right = mark_right
247
+ self.stacked = stacked
248
+
249
+ # ax may be an Axes object or (if self.subplots) an ndarray of
250
+ # Axes objects
251
+ self.ax = ax
252
+ # TODO: deprecate fig keyword as it is ignored, not passed in tests
253
+ # as of 2023-11-05
254
+
255
+ # parse errorbar input if given
256
+ xerr = kwds.pop("xerr", None)
257
+ yerr = kwds.pop("yerr", None)
258
+ nseries = self._get_nseries(data)
259
+ xerr, data = type(self)._parse_errorbars("xerr", xerr, data, nseries)
260
+ yerr, data = type(self)._parse_errorbars("yerr", yerr, data, nseries)
261
+ self.errors = {"xerr": xerr, "yerr": yerr}
262
+ self.data = data
263
+
264
+ if not isinstance(secondary_y, (bool, tuple, list, np.ndarray, ABCIndex)):
265
+ secondary_y = [secondary_y]
266
+ self.secondary_y = secondary_y
267
+
268
+ # ugly TypeError if user passes matplotlib's `cmap` name.
269
+ # Probably better to accept either.
270
+ if "cmap" in kwds and colormap:
271
+ raise TypeError("Only specify one of `cmap` and `colormap`.")
272
+ if "cmap" in kwds:
273
+ self.colormap = kwds.pop("cmap")
274
+ else:
275
+ self.colormap = colormap
276
+
277
+ self.table = table
278
+ self.include_bool = include_bool
279
+
280
+ self.kwds = kwds
281
+
282
+ color = kwds.pop("color", lib.no_default)
283
+ self.color = self._validate_color_args(color, self.colormap)
284
+ assert "color" not in self.kwds
285
+
286
+ self.data = self._ensure_frame(self.data)
287
+
288
+ @final
289
+ @staticmethod
290
+ def _validate_sharex(sharex: bool | None, ax, by) -> bool:
291
+ if sharex is None:
292
+ # if by is defined, subplots are used and sharex should be False
293
+ if ax is None and by is None: # pylint: disable=simplifiable-if-statement
294
+ sharex = True
295
+ else:
296
+ # if we get an axis, the users should do the visibility
297
+ # setting...
298
+ sharex = False
299
+ elif not is_bool(sharex):
300
+ raise TypeError("sharex must be a bool or None")
301
+ return bool(sharex)
302
+
303
+ @classmethod
304
+ def _validate_log_kwd(
305
+ cls,
306
+ kwd: str,
307
+ value: bool | None | Literal["sym"],
308
+ ) -> bool | None | Literal["sym"]:
309
+ if (
310
+ value is None
311
+ or isinstance(value, bool)
312
+ or (isinstance(value, str) and value == "sym")
313
+ ):
314
+ return value
315
+ raise ValueError(
316
+ f"keyword '{kwd}' should be bool, None, or 'sym', not '{value}'"
317
+ )
318
+
319
+ @final
320
+ @staticmethod
321
+ def _validate_subplots_kwarg(
322
+ subplots: bool | Sequence[Sequence[str]], data: Series | DataFrame, kind: str
323
+ ) -> bool | list[tuple[int, ...]]:
324
+ """
325
+ Validate the subplots parameter
326
+
327
+ - check type and content
328
+ - check for duplicate columns
329
+ - check for invalid column names
330
+ - convert column names into indices
331
+ - add missing columns in a group of their own
332
+ See comments in code below for more details.
333
+
334
+ Parameters
335
+ ----------
336
+ subplots : subplots parameters as passed to PlotAccessor
337
+
338
+ Returns
339
+ -------
340
+ validated subplots : a bool or a list of tuples of column indices. Columns
341
+ in the same tuple will be grouped together in the resulting plot.
342
+ """
343
+
344
+ if isinstance(subplots, bool):
345
+ return subplots
346
+ elif not isinstance(subplots, Iterable):
347
+ raise ValueError("subplots should be a bool or an iterable")
348
+
349
+ supported_kinds = (
350
+ "line",
351
+ "bar",
352
+ "barh",
353
+ "hist",
354
+ "kde",
355
+ "density",
356
+ "area",
357
+ "pie",
358
+ )
359
+ if kind not in supported_kinds:
360
+ raise ValueError(
361
+ "When subplots is an iterable, kind must be "
362
+ f"one of {', '.join(supported_kinds)}. Got {kind}."
363
+ )
364
+
365
+ if isinstance(data, ABCSeries):
366
+ raise NotImplementedError(
367
+ "An iterable subplots for a Series is not supported."
368
+ )
369
+
370
+ columns = data.columns
371
+ if isinstance(columns, ABCMultiIndex):
372
+ raise NotImplementedError(
373
+ "An iterable subplots for a DataFrame with a MultiIndex column "
374
+ "is not supported."
375
+ )
376
+
377
+ if columns.nunique() != len(columns):
378
+ raise NotImplementedError(
379
+ "An iterable subplots for a DataFrame with non-unique column "
380
+ "labels is not supported."
381
+ )
382
+
383
+ # subplots is a list of tuples where each tuple is a group of
384
+ # columns to be grouped together (one ax per group).
385
+ # we consolidate the subplots list such that:
386
+ # - the tuples contain indices instead of column names
387
+ # - the columns that aren't yet in the list are added in a group
388
+ # of their own.
389
+ # For example with columns from a to g, and
390
+ # subplots = [(a, c), (b, f, e)],
391
+ # we end up with [(ai, ci), (bi, fi, ei), (di,), (gi,)]
392
+ # This way, we can handle self.subplots in a homogeneous manner
393
+ # later.
394
+ # TODO: also accept indices instead of just names?
395
+
396
+ out = []
397
+ seen_columns: set[Hashable] = set()
398
+ for group in subplots:
399
+ if not is_list_like(group):
400
+ raise ValueError(
401
+ "When subplots is an iterable, each entry "
402
+ "should be a list/tuple of column names."
403
+ )
404
+ idx_locs = columns.get_indexer_for(group)
405
+ if (idx_locs == -1).any():
406
+ bad_labels = np.extract(idx_locs == -1, group)
407
+ raise ValueError(
408
+ f"Column label(s) {list(bad_labels)} not found in the DataFrame."
409
+ )
410
+ unique_columns = set(group)
411
+ duplicates = seen_columns.intersection(unique_columns)
412
+ if duplicates:
413
+ raise ValueError(
414
+ "Each column should be in only one subplot. "
415
+ f"Columns {duplicates} were found in multiple subplots."
416
+ )
417
+ seen_columns = seen_columns.union(unique_columns)
418
+ out.append(tuple(idx_locs))
419
+
420
+ unseen_columns = columns.difference(seen_columns)
421
+ for column in unseen_columns:
422
+ idx_loc = columns.get_loc(column)
423
+ out.append((idx_loc,))
424
+ return out
425
+
426
+ def _validate_color_args(self, color, colormap):
427
+ if color is lib.no_default:
428
+ # It was not provided by the user
429
+ if "colors" in self.kwds and colormap is not None:
430
+ warnings.warn(
431
+ "'color' and 'colormap' cannot be used simultaneously. "
432
+ "Using 'color'",
433
+ stacklevel=find_stack_level(),
434
+ )
435
+ return None
436
+ if self.nseries == 1 and color is not None and not is_list_like(color):
437
+ # support series.plot(color='green')
438
+ color = [color]
439
+
440
+ if isinstance(color, tuple) and self.nseries == 1 and len(color) in (3, 4):
441
+ # support RGB and RGBA tuples in series plot
442
+ color = [color]
443
+
444
+ if colormap is not None:
445
+ warnings.warn(
446
+ "'color' and 'colormap' cannot be used simultaneously. Using 'color'",
447
+ stacklevel=find_stack_level(),
448
+ )
449
+
450
+ if self.style is not None:
451
+ if is_list_like(self.style):
452
+ styles = self.style
453
+ else:
454
+ styles = [self.style]
455
+ # need only a single match
456
+ for s in styles:
457
+ if _color_in_style(s):
458
+ raise ValueError(
459
+ "Cannot pass 'style' string with a color symbol and "
460
+ "'color' keyword argument. Please use one or the "
461
+ "other or pass 'style' without a color symbol"
462
+ )
463
+ return color
464
+
465
+ @final
466
+ @staticmethod
467
+ def _iter_data(
468
+ data: DataFrame | dict[Hashable, Series | DataFrame]
469
+ ) -> Iterator[tuple[Hashable, np.ndarray]]:
470
+ for col, values in data.items():
471
+ # This was originally written to use values.values before EAs
472
+ # were implemented; adding np.asarray(...) to keep consistent
473
+ # typing.
474
+ yield col, np.asarray(values.values)
475
+
476
+ def _get_nseries(self, data: Series | DataFrame) -> int:
477
+ # When `by` is explicitly assigned, grouped data size will be defined, and
478
+ # this will determine number of subplots to have, aka `self.nseries`
479
+ if data.ndim == 1:
480
+ return 1
481
+ elif self.by is not None and self._kind == "hist":
482
+ return len(self._grouped)
483
+ elif self.by is not None and self._kind == "box":
484
+ return len(self.columns)
485
+ else:
486
+ return data.shape[1]
487
+
488
+ @final
489
+ @property
490
+ def nseries(self) -> int:
491
+ return self._get_nseries(self.data)
492
+
493
+ @final
494
+ def draw(self) -> None:
495
+ self.plt.draw_if_interactive()
496
+
497
+ @final
498
+ def generate(self) -> None:
499
+ self._compute_plot_data()
500
+ fig = self.fig
501
+ self._make_plot(fig)
502
+ self._add_table()
503
+ self._make_legend()
504
+ self._adorn_subplots(fig)
505
+
506
+ for ax in self.axes:
507
+ self._post_plot_logic_common(ax)
508
+ self._post_plot_logic(ax, self.data)
509
+
510
+ @final
511
+ @staticmethod
512
+ def _has_plotted_object(ax: Axes) -> bool:
513
+ """check whether ax has data"""
514
+ return len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0
515
+
516
+ @final
517
+ def _maybe_right_yaxis(self, ax: Axes, axes_num: int) -> Axes:
518
+ if not self.on_right(axes_num):
519
+ # secondary axes may be passed via ax kw
520
+ return self._get_ax_layer(ax)
521
+
522
+ if hasattr(ax, "right_ax"):
523
+ # if it has right_ax property, ``ax`` must be left axes
524
+ return ax.right_ax
525
+ elif hasattr(ax, "left_ax"):
526
+ # if it has left_ax property, ``ax`` must be right axes
527
+ return ax
528
+ else:
529
+ # otherwise, create twin axes
530
+ orig_ax, new_ax = ax, ax.twinx()
531
+ # TODO: use Matplotlib public API when available
532
+ new_ax._get_lines = orig_ax._get_lines # type: ignore[attr-defined]
533
+ # TODO #54485
534
+ new_ax._get_patches_for_fill = ( # type: ignore[attr-defined]
535
+ orig_ax._get_patches_for_fill # type: ignore[attr-defined]
536
+ )
537
+ # TODO #54485
538
+ orig_ax.right_ax, new_ax.left_ax = ( # type: ignore[attr-defined]
539
+ new_ax,
540
+ orig_ax,
541
+ )
542
+
543
+ if not self._has_plotted_object(orig_ax): # no data on left y
544
+ orig_ax.get_yaxis().set_visible(False)
545
+
546
+ if self.logy is True or self.loglog is True:
547
+ new_ax.set_yscale("log")
548
+ elif self.logy == "sym" or self.loglog == "sym":
549
+ new_ax.set_yscale("symlog")
550
+ return new_ax
551
+
552
+ @final
553
+ @cache_readonly
554
+ def fig(self) -> Figure:
555
+ return self._axes_and_fig[1]
556
+
557
+ @final
558
+ @cache_readonly
559
+ # TODO: can we annotate this as both a Sequence[Axes] and ndarray[object]?
560
+ def axes(self) -> Sequence[Axes]:
561
+ return self._axes_and_fig[0]
562
+
563
+ @final
564
+ @cache_readonly
565
+ def _axes_and_fig(self) -> tuple[Sequence[Axes], Figure]:
566
+ if self.subplots:
567
+ naxes = (
568
+ self.nseries if isinstance(self.subplots, bool) else len(self.subplots)
569
+ )
570
+ fig, axes = create_subplots(
571
+ naxes=naxes,
572
+ sharex=self.sharex,
573
+ sharey=self.sharey,
574
+ figsize=self.figsize,
575
+ ax=self.ax,
576
+ layout=self.layout,
577
+ layout_type=self._layout_type,
578
+ )
579
+ elif self.ax is None:
580
+ fig = self.plt.figure(figsize=self.figsize)
581
+ axes = fig.add_subplot(111)
582
+ else:
583
+ fig = self.ax.get_figure()
584
+ if self.figsize is not None:
585
+ fig.set_size_inches(self.figsize)
586
+ axes = self.ax
587
+
588
+ axes = flatten_axes(axes)
589
+
590
+ if self.logx is True or self.loglog is True:
591
+ [a.set_xscale("log") for a in axes]
592
+ elif self.logx == "sym" or self.loglog == "sym":
593
+ [a.set_xscale("symlog") for a in axes]
594
+
595
+ if self.logy is True or self.loglog is True:
596
+ [a.set_yscale("log") for a in axes]
597
+ elif self.logy == "sym" or self.loglog == "sym":
598
+ [a.set_yscale("symlog") for a in axes]
599
+
600
+ axes_seq = cast(Sequence["Axes"], axes)
601
+ return axes_seq, fig
602
+
603
+ @property
604
+ def result(self):
605
+ """
606
+ Return result axes
607
+ """
608
+ if self.subplots:
609
+ if self.layout is not None and not is_list_like(self.ax):
610
+ # error: "Sequence[Any]" has no attribute "reshape"
611
+ return self.axes.reshape(*self.layout) # type: ignore[attr-defined]
612
+ else:
613
+ return self.axes
614
+ else:
615
+ sec_true = isinstance(self.secondary_y, bool) and self.secondary_y
616
+ # error: Argument 1 to "len" has incompatible type "Union[bool,
617
+ # Tuple[Any, ...], List[Any], ndarray[Any, Any]]"; expected "Sized"
618
+ all_sec = (
619
+ is_list_like(self.secondary_y)
620
+ and len(self.secondary_y) == self.nseries # type: ignore[arg-type]
621
+ )
622
+ if sec_true or all_sec:
623
+ # if all data is plotted on secondary, return right axes
624
+ return self._get_ax_layer(self.axes[0], primary=False)
625
+ else:
626
+ return self.axes[0]
627
+
628
+ @final
629
+ @staticmethod
630
+ def _convert_to_ndarray(data):
631
+ # GH31357: categorical columns are processed separately
632
+ if isinstance(data.dtype, CategoricalDtype):
633
+ return data
634
+
635
+ # GH32073: cast to float if values contain nulled integers
636
+ if (is_integer_dtype(data.dtype) or is_float_dtype(data.dtype)) and isinstance(
637
+ data.dtype, ExtensionDtype
638
+ ):
639
+ return data.to_numpy(dtype="float", na_value=np.nan)
640
+
641
+ # GH25587: cast ExtensionArray of pandas (IntegerArray, etc.) to
642
+ # np.ndarray before plot.
643
+ if len(data) > 0:
644
+ return np.asarray(data)
645
+
646
+ return data
647
+
648
+ @final
649
+ def _ensure_frame(self, data) -> DataFrame:
650
+ if isinstance(data, ABCSeries):
651
+ label = self.label
652
+ if label is None and data.name is None:
653
+ label = ""
654
+ if label is None:
655
+ # We'll end up with columns of [0] instead of [None]
656
+ data = data.to_frame()
657
+ else:
658
+ data = data.to_frame(name=label)
659
+ elif self._kind in ("hist", "box"):
660
+ cols = self.columns if self.by is None else self.columns + self.by
661
+ data = data.loc[:, cols]
662
+ return data
663
+
664
+ @final
665
+ def _compute_plot_data(self) -> None:
666
+ data = self.data
667
+
668
+ # GH15079 reconstruct data if by is defined
669
+ if self.by is not None:
670
+ self.subplots = True
671
+ data = reconstruct_data_with_by(self.data, by=self.by, cols=self.columns)
672
+
673
+ # GH16953, infer_objects is needed as fallback, for ``Series``
674
+ # with ``dtype == object``
675
+ data = data.infer_objects(copy=False)
676
+ include_type = [np.number, "datetime", "datetimetz", "timedelta"]
677
+
678
+ # GH23719, allow plotting boolean
679
+ if self.include_bool is True:
680
+ include_type.append(np.bool_)
681
+
682
+ # GH22799, exclude datetime-like type for boxplot
683
+ exclude_type = None
684
+ if self._kind == "box":
685
+ # TODO: change after solving issue 27881
686
+ include_type = [np.number]
687
+ exclude_type = ["timedelta"]
688
+
689
+ # GH 18755, include object and category type for scatter plot
690
+ if self._kind == "scatter":
691
+ include_type.extend(["object", "category", "string"])
692
+
693
+ numeric_data = data.select_dtypes(include=include_type, exclude=exclude_type)
694
+
695
+ is_empty = numeric_data.shape[-1] == 0
696
+ # no non-numeric frames or series allowed
697
+ if is_empty:
698
+ raise TypeError("no numeric data to plot")
699
+
700
+ self.data = numeric_data.apply(type(self)._convert_to_ndarray)
701
+
702
+ def _make_plot(self, fig: Figure) -> None:
703
+ raise AbstractMethodError(self)
704
+
705
+ @final
706
+ def _add_table(self) -> None:
707
+ if self.table is False:
708
+ return
709
+ elif self.table is True:
710
+ data = self.data.transpose()
711
+ else:
712
+ data = self.table
713
+ ax = self._get_ax(0)
714
+ tools.table(ax, data)
715
+
716
+ @final
717
+ def _post_plot_logic_common(self, ax: Axes) -> None:
718
+ """Common post process for each axes"""
719
+ if self.orientation == "vertical" or self.orientation is None:
720
+ type(self)._apply_axis_properties(
721
+ ax.xaxis, rot=self.rot, fontsize=self.fontsize
722
+ )
723
+ type(self)._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)
724
+
725
+ if hasattr(ax, "right_ax"):
726
+ type(self)._apply_axis_properties(
727
+ ax.right_ax.yaxis, fontsize=self.fontsize
728
+ )
729
+
730
+ elif self.orientation == "horizontal":
731
+ type(self)._apply_axis_properties(
732
+ ax.yaxis, rot=self.rot, fontsize=self.fontsize
733
+ )
734
+ type(self)._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)
735
+
736
+ if hasattr(ax, "right_ax"):
737
+ type(self)._apply_axis_properties(
738
+ ax.right_ax.yaxis, fontsize=self.fontsize
739
+ )
740
+ else: # pragma no cover
741
+ raise ValueError
742
+
743
+ @abstractmethod
744
+ def _post_plot_logic(self, ax: Axes, data) -> None:
745
+ """Post process for each axes. Overridden in child classes"""
746
+
747
+ @final
748
+ def _adorn_subplots(self, fig: Figure) -> None:
749
+ """Common post process unrelated to data"""
750
+ if len(self.axes) > 0:
751
+ all_axes = self._get_subplots(fig)
752
+ nrows, ncols = self._get_axes_layout(fig)
753
+ handle_shared_axes(
754
+ axarr=all_axes,
755
+ nplots=len(all_axes),
756
+ naxes=nrows * ncols,
757
+ nrows=nrows,
758
+ ncols=ncols,
759
+ sharex=self.sharex,
760
+ sharey=self.sharey,
761
+ )
762
+
763
+ for ax in self.axes:
764
+ ax = getattr(ax, "right_ax", ax)
765
+ if self.yticks is not None:
766
+ ax.set_yticks(self.yticks)
767
+
768
+ if self.xticks is not None:
769
+ ax.set_xticks(self.xticks)
770
+
771
+ if self.ylim is not None:
772
+ ax.set_ylim(self.ylim)
773
+
774
+ if self.xlim is not None:
775
+ ax.set_xlim(self.xlim)
776
+
777
+ # GH9093, currently Pandas does not show ylabel, so if users provide
778
+ # ylabel will set it as ylabel in the plot.
779
+ if self.ylabel is not None:
780
+ ax.set_ylabel(pprint_thing(self.ylabel))
781
+
782
+ ax.grid(self.grid)
783
+
784
+ if self.title:
785
+ if self.subplots:
786
+ if is_list_like(self.title):
787
+ if len(self.title) != self.nseries:
788
+ raise ValueError(
789
+ "The length of `title` must equal the number "
790
+ "of columns if using `title` of type `list` "
791
+ "and `subplots=True`.\n"
792
+ f"length of title = {len(self.title)}\n"
793
+ f"number of columns = {self.nseries}"
794
+ )
795
+
796
+ for ax, title in zip(self.axes, self.title):
797
+ ax.set_title(title)
798
+ else:
799
+ fig.suptitle(self.title)
800
+ else:
801
+ if is_list_like(self.title):
802
+ msg = (
803
+ "Using `title` of type `list` is not supported "
804
+ "unless `subplots=True` is passed"
805
+ )
806
+ raise ValueError(msg)
807
+ self.axes[0].set_title(self.title)
808
+
809
+ @final
810
+ @staticmethod
811
+ def _apply_axis_properties(
812
+ axis: Axis, rot=None, fontsize: int | None = None
813
+ ) -> None:
814
+ """
815
+ Tick creation within matplotlib is reasonably expensive and is
816
+ internally deferred until accessed as Ticks are created/destroyed
817
+ multiple times per draw. It's therefore beneficial for us to avoid
818
+ accessing unless we will act on the Tick.
819
+ """
820
+ if rot is not None or fontsize is not None:
821
+ # rot=0 is a valid setting, hence the explicit None check
822
+ labels = axis.get_majorticklabels() + axis.get_minorticklabels()
823
+ for label in labels:
824
+ if rot is not None:
825
+ label.set_rotation(rot)
826
+ if fontsize is not None:
827
+ label.set_fontsize(fontsize)
828
+
829
+ @final
830
+ @property
831
+ def legend_title(self) -> str | None:
832
+ if not isinstance(self.data.columns, ABCMultiIndex):
833
+ name = self.data.columns.name
834
+ if name is not None:
835
+ name = pprint_thing(name)
836
+ return name
837
+ else:
838
+ stringified = map(pprint_thing, self.data.columns.names)
839
+ return ",".join(stringified)
840
+
841
+ @final
842
+ def _mark_right_label(self, label: str, index: int) -> str:
843
+ """
844
+ Append ``(right)`` to the label of a line if it's plotted on the right axis.
845
+
846
+ Note that ``(right)`` is only appended when ``subplots=False``.
847
+ """
848
+ if not self.subplots and self.mark_right and self.on_right(index):
849
+ label += " (right)"
850
+ return label
851
+
852
+ @final
853
+ def _append_legend_handles_labels(self, handle: Artist, label: str) -> None:
854
+ """
855
+ Append current handle and label to ``legend_handles`` and ``legend_labels``.
856
+
857
+ These will be used to make the legend.
858
+ """
859
+ self.legend_handles.append(handle)
860
+ self.legend_labels.append(label)
861
+
862
+ def _make_legend(self) -> None:
863
+ ax, leg = self._get_ax_legend(self.axes[0])
864
+
865
+ handles = []
866
+ labels = []
867
+ title = ""
868
+
869
+ if not self.subplots:
870
+ if leg is not None:
871
+ title = leg.get_title().get_text()
872
+ # Replace leg.legend_handles because it misses marker info
873
+ if Version(mpl.__version__) < Version("3.7"):
874
+ handles = leg.legendHandles
875
+ else:
876
+ handles = leg.legend_handles
877
+ labels = [x.get_text() for x in leg.get_texts()]
878
+
879
+ if self.legend:
880
+ if self.legend == "reverse":
881
+ handles += reversed(self.legend_handles)
882
+ labels += reversed(self.legend_labels)
883
+ else:
884
+ handles += self.legend_handles
885
+ labels += self.legend_labels
886
+
887
+ if self.legend_title is not None:
888
+ title = self.legend_title
889
+
890
+ if len(handles) > 0:
891
+ ax.legend(handles, labels, loc="best", title=title)
892
+
893
+ elif self.subplots and self.legend:
894
+ for ax in self.axes:
895
+ if ax.get_visible():
896
+ with warnings.catch_warnings():
897
+ warnings.filterwarnings(
898
+ "ignore",
899
+ "No artists with labels found to put in legend.",
900
+ UserWarning,
901
+ )
902
+ ax.legend(loc="best")
903
+
904
+ @final
905
+ @staticmethod
906
+ def _get_ax_legend(ax: Axes):
907
+ """
908
+ Take in axes and return ax and legend under different scenarios
909
+ """
910
+ leg = ax.get_legend()
911
+
912
+ other_ax = getattr(ax, "left_ax", None) or getattr(ax, "right_ax", None)
913
+ other_leg = None
914
+ if other_ax is not None:
915
+ other_leg = other_ax.get_legend()
916
+ if leg is None and other_leg is not None:
917
+ leg = other_leg
918
+ ax = other_ax
919
+ return ax, leg
920
+
921
+ @final
922
+ @cache_readonly
923
+ def plt(self):
924
+ import matplotlib.pyplot as plt
925
+
926
+ return plt
927
+
928
+ _need_to_set_index = False
929
+
930
+ @final
931
+ def _get_xticks(self):
932
+ index = self.data.index
933
+ is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time")
934
+
935
+ # TODO: be stricter about x?
936
+ x: list[int] | np.ndarray
937
+ if self.use_index:
938
+ if isinstance(index, ABCPeriodIndex):
939
+ # test_mixed_freq_irreg_period
940
+ x = index.to_timestamp()._mpl_repr()
941
+ # TODO: why do we need to do to_timestamp() here but not other
942
+ # places where we call mpl_repr?
943
+ elif is_any_real_numeric_dtype(index.dtype):
944
+ # Matplotlib supports numeric values or datetime objects as
945
+ # xaxis values. Taking LBYL approach here, by the time
946
+ # matplotlib raises exception when using non numeric/datetime
947
+ # values for xaxis, several actions are already taken by plt.
948
+ x = index._mpl_repr()
949
+ elif isinstance(index, ABCDatetimeIndex) or is_datetype:
950
+ x = index._mpl_repr()
951
+ else:
952
+ self._need_to_set_index = True
953
+ x = list(range(len(index)))
954
+ else:
955
+ x = list(range(len(index)))
956
+
957
+ return x
958
+
959
+ @classmethod
960
+ @register_pandas_matplotlib_converters
961
+ def _plot(
962
+ cls, ax: Axes, x, y: np.ndarray, style=None, is_errorbar: bool = False, **kwds
963
+ ):
964
+ mask = isna(y)
965
+ if mask.any():
966
+ y = np.ma.array(y)
967
+ y = np.ma.masked_where(mask, y)
968
+
969
+ if isinstance(x, ABCIndex):
970
+ x = x._mpl_repr()
971
+
972
+ if is_errorbar:
973
+ if "xerr" in kwds:
974
+ kwds["xerr"] = np.array(kwds.get("xerr"))
975
+ if "yerr" in kwds:
976
+ kwds["yerr"] = np.array(kwds.get("yerr"))
977
+ return ax.errorbar(x, y, **kwds)
978
+ else:
979
+ # prevent style kwarg from going to errorbar, where it is unsupported
980
+ args = (x, y, style) if style is not None else (x, y)
981
+ return ax.plot(*args, **kwds)
982
+
983
+ def _get_custom_index_name(self):
984
+ """Specify whether xlabel/ylabel should be used to override index name"""
985
+ return self.xlabel
986
+
987
+ @final
988
+ def _get_index_name(self) -> str | None:
989
+ if isinstance(self.data.index, ABCMultiIndex):
990
+ name = self.data.index.names
991
+ if com.any_not_none(*name):
992
+ name = ",".join([pprint_thing(x) for x in name])
993
+ else:
994
+ name = None
995
+ else:
996
+ name = self.data.index.name
997
+ if name is not None:
998
+ name = pprint_thing(name)
999
+
1000
+ # GH 45145, override the default axis label if one is provided.
1001
+ index_name = self._get_custom_index_name()
1002
+ if index_name is not None:
1003
+ name = pprint_thing(index_name)
1004
+
1005
+ return name
1006
+
1007
+ @final
1008
+ @classmethod
1009
+ def _get_ax_layer(cls, ax, primary: bool = True):
1010
+ """get left (primary) or right (secondary) axes"""
1011
+ if primary:
1012
+ return getattr(ax, "left_ax", ax)
1013
+ else:
1014
+ return getattr(ax, "right_ax", ax)
1015
+
1016
+ @final
1017
+ def _col_idx_to_axis_idx(self, col_idx: int) -> int:
1018
+ """Return the index of the axis where the column at col_idx should be plotted"""
1019
+ if isinstance(self.subplots, list):
1020
+ # Subplots is a list: some columns will be grouped together in the same ax
1021
+ return next(
1022
+ group_idx
1023
+ for (group_idx, group) in enumerate(self.subplots)
1024
+ if col_idx in group
1025
+ )
1026
+ else:
1027
+ # subplots is True: one ax per column
1028
+ return col_idx
1029
+
1030
+ @final
1031
+ def _get_ax(self, i: int):
1032
+ # get the twinx ax if appropriate
1033
+ if self.subplots:
1034
+ i = self._col_idx_to_axis_idx(i)
1035
+ ax = self.axes[i]
1036
+ ax = self._maybe_right_yaxis(ax, i)
1037
+ # error: Unsupported target for indexed assignment ("Sequence[Any]")
1038
+ self.axes[i] = ax # type: ignore[index]
1039
+ else:
1040
+ ax = self.axes[0]
1041
+ ax = self._maybe_right_yaxis(ax, i)
1042
+
1043
+ ax.get_yaxis().set_visible(True)
1044
+ return ax
1045
+
1046
+ @final
1047
+ def on_right(self, i: int):
1048
+ if isinstance(self.secondary_y, bool):
1049
+ return self.secondary_y
1050
+
1051
+ if isinstance(self.secondary_y, (tuple, list, np.ndarray, ABCIndex)):
1052
+ return self.data.columns[i] in self.secondary_y
1053
+
1054
+ @final
1055
+ def _apply_style_colors(
1056
+ self, colors, kwds: dict[str, Any], col_num: int, label: str
1057
+ ):
1058
+ """
1059
+ Manage style and color based on column number and its label.
1060
+ Returns tuple of appropriate style and kwds which "color" may be added.
1061
+ """
1062
+ style = None
1063
+ if self.style is not None:
1064
+ if isinstance(self.style, list):
1065
+ try:
1066
+ style = self.style[col_num]
1067
+ except IndexError:
1068
+ pass
1069
+ elif isinstance(self.style, dict):
1070
+ style = self.style.get(label, style)
1071
+ else:
1072
+ style = self.style
1073
+
1074
+ has_color = "color" in kwds or self.colormap is not None
1075
+ nocolor_style = style is None or not _color_in_style(style)
1076
+ if (has_color or self.subplots) and nocolor_style:
1077
+ if isinstance(colors, dict):
1078
+ kwds["color"] = colors[label]
1079
+ else:
1080
+ kwds["color"] = colors[col_num % len(colors)]
1081
+ return style, kwds
1082
+
1083
+ def _get_colors(
1084
+ self,
1085
+ num_colors: int | None = None,
1086
+ color_kwds: str = "color",
1087
+ ):
1088
+ if num_colors is None:
1089
+ num_colors = self.nseries
1090
+ if color_kwds == "color":
1091
+ color = self.color
1092
+ else:
1093
+ color = self.kwds.get(color_kwds)
1094
+ return get_standard_colors(
1095
+ num_colors=num_colors,
1096
+ colormap=self.colormap,
1097
+ color=color,
1098
+ )
1099
+
1100
+ # TODO: tighter typing for first return?
1101
+ @final
1102
+ @staticmethod
1103
+ def _parse_errorbars(
1104
+ label: str, err, data: NDFrameT, nseries: int
1105
+ ) -> tuple[Any, NDFrameT]:
1106
+ """
1107
+ Look for error keyword arguments and return the actual errorbar data
1108
+ or return the error DataFrame/dict
1109
+
1110
+ Error bars can be specified in several ways:
1111
+ Series: the user provides a pandas.Series object of the same
1112
+ length as the data
1113
+ ndarray: provides a np.ndarray of the same length as the data
1114
+ DataFrame/dict: error values are paired with keys matching the
1115
+ key in the plotted DataFrame
1116
+ str: the name of the column within the plotted DataFrame
1117
+
1118
+ Asymmetrical error bars are also supported, however raw error values
1119
+ must be provided in this case. For a ``N`` length :class:`Series`, a
1120
+ ``2xN`` array should be provided indicating lower and upper (or left
1121
+ and right) errors. For a ``MxN`` :class:`DataFrame`, asymmetrical errors
1122
+ should be in a ``Mx2xN`` array.
1123
+ """
1124
+ if err is None:
1125
+ return None, data
1126
+
1127
+ def match_labels(data, e):
1128
+ e = e.reindex(data.index)
1129
+ return e
1130
+
1131
+ # key-matched DataFrame
1132
+ if isinstance(err, ABCDataFrame):
1133
+ err = match_labels(data, err)
1134
+ # key-matched dict
1135
+ elif isinstance(err, dict):
1136
+ pass
1137
+
1138
+ # Series of error values
1139
+ elif isinstance(err, ABCSeries):
1140
+ # broadcast error series across data
1141
+ err = match_labels(data, err)
1142
+ err = np.atleast_2d(err)
1143
+ err = np.tile(err, (nseries, 1))
1144
+
1145
+ # errors are a column in the dataframe
1146
+ elif isinstance(err, str):
1147
+ evalues = data[err].values
1148
+ data = data[data.columns.drop(err)]
1149
+ err = np.atleast_2d(evalues)
1150
+ err = np.tile(err, (nseries, 1))
1151
+
1152
+ elif is_list_like(err):
1153
+ if is_iterator(err):
1154
+ err = np.atleast_2d(list(err))
1155
+ else:
1156
+ # raw error values
1157
+ err = np.atleast_2d(err)
1158
+
1159
+ err_shape = err.shape
1160
+
1161
+ # asymmetrical error bars
1162
+ if isinstance(data, ABCSeries) and err_shape[0] == 2:
1163
+ err = np.expand_dims(err, 0)
1164
+ err_shape = err.shape
1165
+ if err_shape[2] != len(data):
1166
+ raise ValueError(
1167
+ "Asymmetrical error bars should be provided "
1168
+ f"with the shape (2, {len(data)})"
1169
+ )
1170
+ elif isinstance(data, ABCDataFrame) and err.ndim == 3:
1171
+ if (
1172
+ (err_shape[0] != nseries)
1173
+ or (err_shape[1] != 2)
1174
+ or (err_shape[2] != len(data))
1175
+ ):
1176
+ raise ValueError(
1177
+ "Asymmetrical error bars should be provided "
1178
+ f"with the shape ({nseries}, 2, {len(data)})"
1179
+ )
1180
+
1181
+ # broadcast errors to each data series
1182
+ if len(err) == 1:
1183
+ err = np.tile(err, (nseries, 1))
1184
+
1185
+ elif is_number(err):
1186
+ err = np.tile(
1187
+ [err],
1188
+ (nseries, len(data)),
1189
+ )
1190
+
1191
+ else:
1192
+ msg = f"No valid {label} detected"
1193
+ raise ValueError(msg)
1194
+
1195
+ return err, data
1196
+
1197
+ @final
1198
+ def _get_errorbars(
1199
+ self, label=None, index=None, xerr: bool = True, yerr: bool = True
1200
+ ) -> dict[str, Any]:
1201
+ errors = {}
1202
+
1203
+ for kw, flag in zip(["xerr", "yerr"], [xerr, yerr]):
1204
+ if flag:
1205
+ err = self.errors[kw]
1206
+ # user provided label-matched dataframe of errors
1207
+ if isinstance(err, (ABCDataFrame, dict)):
1208
+ if label is not None and label in err.keys():
1209
+ err = err[label]
1210
+ else:
1211
+ err = None
1212
+ elif index is not None and err is not None:
1213
+ err = err[index]
1214
+
1215
+ if err is not None:
1216
+ errors[kw] = err
1217
+ return errors
1218
+
1219
+ @final
1220
+ def _get_subplots(self, fig: Figure):
1221
+ if Version(mpl.__version__) < Version("3.8"):
1222
+ from matplotlib.axes import Subplot as Klass
1223
+ else:
1224
+ from matplotlib.axes import Axes as Klass
1225
+
1226
+ return [
1227
+ ax
1228
+ for ax in fig.get_axes()
1229
+ if (isinstance(ax, Klass) and ax.get_subplotspec() is not None)
1230
+ ]
1231
+
1232
+ @final
1233
+ def _get_axes_layout(self, fig: Figure) -> tuple[int, int]:
1234
+ axes = self._get_subplots(fig)
1235
+ x_set = set()
1236
+ y_set = set()
1237
+ for ax in axes:
1238
+ # check axes coordinates to estimate layout
1239
+ points = ax.get_position().get_points()
1240
+ x_set.add(points[0][0])
1241
+ y_set.add(points[0][1])
1242
+ return (len(y_set), len(x_set))
1243
+
1244
+
1245
+ class PlanePlot(MPLPlot, ABC):
1246
+ """
1247
+ Abstract class for plotting on plane, currently scatter and hexbin.
1248
+ """
1249
+
1250
+ _layout_type = "single"
1251
+
1252
+ def __init__(self, data, x, y, **kwargs) -> None:
1253
+ MPLPlot.__init__(self, data, **kwargs)
1254
+ if x is None or y is None:
1255
+ raise ValueError(self._kind + " requires an x and y column")
1256
+ if is_integer(x) and not self.data.columns._holds_integer():
1257
+ x = self.data.columns[x]
1258
+ if is_integer(y) and not self.data.columns._holds_integer():
1259
+ y = self.data.columns[y]
1260
+
1261
+ self.x = x
1262
+ self.y = y
1263
+
1264
+ @final
1265
+ def _get_nseries(self, data: Series | DataFrame) -> int:
1266
+ return 1
1267
+
1268
+ @final
1269
+ def _post_plot_logic(self, ax: Axes, data) -> None:
1270
+ x, y = self.x, self.y
1271
+ xlabel = self.xlabel if self.xlabel is not None else pprint_thing(x)
1272
+ ylabel = self.ylabel if self.ylabel is not None else pprint_thing(y)
1273
+ # error: Argument 1 to "set_xlabel" of "_AxesBase" has incompatible
1274
+ # type "Hashable"; expected "str"
1275
+ ax.set_xlabel(xlabel) # type: ignore[arg-type]
1276
+ ax.set_ylabel(ylabel) # type: ignore[arg-type]
1277
+
1278
+ @final
1279
+ def _plot_colorbar(self, ax: Axes, *, fig: Figure, **kwds):
1280
+ # Addresses issues #10611 and #10678:
1281
+ # When plotting scatterplots and hexbinplots in IPython
1282
+ # inline backend the colorbar axis height tends not to
1283
+ # exactly match the parent axis height.
1284
+ # The difference is due to small fractional differences
1285
+ # in floating points with similar representation.
1286
+ # To deal with this, this method forces the colorbar
1287
+ # height to take the height of the parent axes.
1288
+ # For a more detailed description of the issue
1289
+ # see the following link:
1290
+ # https://github.com/ipython/ipython/issues/11215
1291
+
1292
+ # GH33389, if ax is used multiple times, we should always
1293
+ # use the last one which contains the latest information
1294
+ # about the ax
1295
+ img = ax.collections[-1]
1296
+ return fig.colorbar(img, ax=ax, **kwds)
1297
+
1298
+
1299
+ class ScatterPlot(PlanePlot):
1300
+ @property
1301
+ def _kind(self) -> Literal["scatter"]:
1302
+ return "scatter"
1303
+
1304
+ def __init__(
1305
+ self,
1306
+ data,
1307
+ x,
1308
+ y,
1309
+ s=None,
1310
+ c=None,
1311
+ *,
1312
+ colorbar: bool | lib.NoDefault = lib.no_default,
1313
+ norm=None,
1314
+ **kwargs,
1315
+ ) -> None:
1316
+ if s is None:
1317
+ # hide the matplotlib default for size, in case we want to change
1318
+ # the handling of this argument later
1319
+ s = 20
1320
+ elif is_hashable(s) and s in data.columns:
1321
+ s = data[s]
1322
+ self.s = s
1323
+
1324
+ self.colorbar = colorbar
1325
+ self.norm = norm
1326
+
1327
+ super().__init__(data, x, y, **kwargs)
1328
+ if is_integer(c) and not self.data.columns._holds_integer():
1329
+ c = self.data.columns[c]
1330
+ self.c = c
1331
+
1332
+ def _make_plot(self, fig: Figure) -> None:
1333
+ x, y, c, data = self.x, self.y, self.c, self.data
1334
+ ax = self.axes[0]
1335
+
1336
+ c_is_column = is_hashable(c) and c in self.data.columns
1337
+
1338
+ color_by_categorical = c_is_column and isinstance(
1339
+ self.data[c].dtype, CategoricalDtype
1340
+ )
1341
+
1342
+ color = self.color
1343
+ c_values = self._get_c_values(color, color_by_categorical, c_is_column)
1344
+ norm, cmap = self._get_norm_and_cmap(c_values, color_by_categorical)
1345
+ cb = self._get_colorbar(c_values, c_is_column)
1346
+
1347
+ if self.legend:
1348
+ label = self.label
1349
+ else:
1350
+ label = None
1351
+ scatter = ax.scatter(
1352
+ data[x].values,
1353
+ data[y].values,
1354
+ c=c_values,
1355
+ label=label,
1356
+ cmap=cmap,
1357
+ norm=norm,
1358
+ s=self.s,
1359
+ **self.kwds,
1360
+ )
1361
+ if cb:
1362
+ cbar_label = c if c_is_column else ""
1363
+ cbar = self._plot_colorbar(ax, fig=fig, label=cbar_label)
1364
+ if color_by_categorical:
1365
+ n_cats = len(self.data[c].cat.categories)
1366
+ cbar.set_ticks(np.linspace(0.5, n_cats - 0.5, n_cats))
1367
+ cbar.ax.set_yticklabels(self.data[c].cat.categories)
1368
+
1369
+ if label is not None:
1370
+ self._append_legend_handles_labels(
1371
+ # error: Argument 2 to "_append_legend_handles_labels" of
1372
+ # "MPLPlot" has incompatible type "Hashable"; expected "str"
1373
+ scatter,
1374
+ label, # type: ignore[arg-type]
1375
+ )
1376
+
1377
+ errors_x = self._get_errorbars(label=x, index=0, yerr=False)
1378
+ errors_y = self._get_errorbars(label=y, index=0, xerr=False)
1379
+ if len(errors_x) > 0 or len(errors_y) > 0:
1380
+ err_kwds = dict(errors_x, **errors_y)
1381
+ err_kwds["ecolor"] = scatter.get_facecolor()[0]
1382
+ ax.errorbar(data[x].values, data[y].values, linestyle="none", **err_kwds)
1383
+
1384
+ def _get_c_values(self, color, color_by_categorical: bool, c_is_column: bool):
1385
+ c = self.c
1386
+ if c is not None and color is not None:
1387
+ raise TypeError("Specify exactly one of `c` and `color`")
1388
+ if c is None and color is None:
1389
+ c_values = self.plt.rcParams["patch.facecolor"]
1390
+ elif color is not None:
1391
+ c_values = color
1392
+ elif color_by_categorical:
1393
+ c_values = self.data[c].cat.codes
1394
+ elif c_is_column:
1395
+ c_values = self.data[c].values
1396
+ else:
1397
+ c_values = c
1398
+ return c_values
1399
+
1400
+ def _get_norm_and_cmap(self, c_values, color_by_categorical: bool):
1401
+ c = self.c
1402
+ if self.colormap is not None:
1403
+ cmap = mpl.colormaps.get_cmap(self.colormap)
1404
+ # cmap is only used if c_values are integers, otherwise UserWarning.
1405
+ # GH-53908: additionally call isinstance() because is_integer_dtype
1406
+ # returns True for "b" (meaning "blue" and not int8 in this context)
1407
+ elif not isinstance(c_values, str) and is_integer_dtype(c_values):
1408
+ # pandas uses colormap, matplotlib uses cmap.
1409
+ cmap = mpl.colormaps["Greys"]
1410
+ else:
1411
+ cmap = None
1412
+
1413
+ if color_by_categorical and cmap is not None:
1414
+ from matplotlib import colors
1415
+
1416
+ n_cats = len(self.data[c].cat.categories)
1417
+ cmap = colors.ListedColormap([cmap(i) for i in range(cmap.N)])
1418
+ bounds = np.linspace(0, n_cats, n_cats + 1)
1419
+ norm = colors.BoundaryNorm(bounds, cmap.N)
1420
+ # TODO: warn that we are ignoring self.norm if user specified it?
1421
+ # Doesn't happen in any tests 2023-11-09
1422
+ else:
1423
+ norm = self.norm
1424
+ return norm, cmap
1425
+
1426
+ def _get_colorbar(self, c_values, c_is_column: bool) -> bool:
1427
+ # plot colorbar if
1428
+ # 1. colormap is assigned, and
1429
+ # 2.`c` is a column containing only numeric values
1430
+ plot_colorbar = self.colormap or c_is_column
1431
+ cb = self.colorbar
1432
+ if cb is lib.no_default:
1433
+ return is_numeric_dtype(c_values) and plot_colorbar
1434
+ return cb
1435
+
1436
+
1437
+ class HexBinPlot(PlanePlot):
1438
+ @property
1439
+ def _kind(self) -> Literal["hexbin"]:
1440
+ return "hexbin"
1441
+
1442
+ def __init__(self, data, x, y, C=None, *, colorbar: bool = True, **kwargs) -> None:
1443
+ super().__init__(data, x, y, **kwargs)
1444
+ if is_integer(C) and not self.data.columns._holds_integer():
1445
+ C = self.data.columns[C]
1446
+ self.C = C
1447
+
1448
+ self.colorbar = colorbar
1449
+
1450
+ # Scatter plot allows to plot objects data
1451
+ if len(self.data[self.x]._get_numeric_data()) == 0:
1452
+ raise ValueError(self._kind + " requires x column to be numeric")
1453
+ if len(self.data[self.y]._get_numeric_data()) == 0:
1454
+ raise ValueError(self._kind + " requires y column to be numeric")
1455
+
1456
+ def _make_plot(self, fig: Figure) -> None:
1457
+ x, y, data, C = self.x, self.y, self.data, self.C
1458
+ ax = self.axes[0]
1459
+ # pandas uses colormap, matplotlib uses cmap.
1460
+ cmap = self.colormap or "BuGn"
1461
+ cmap = mpl.colormaps.get_cmap(cmap)
1462
+ cb = self.colorbar
1463
+
1464
+ if C is None:
1465
+ c_values = None
1466
+ else:
1467
+ c_values = data[C].values
1468
+
1469
+ ax.hexbin(data[x].values, data[y].values, C=c_values, cmap=cmap, **self.kwds)
1470
+ if cb:
1471
+ self._plot_colorbar(ax, fig=fig)
1472
+
1473
+ def _make_legend(self) -> None:
1474
+ pass
1475
+
1476
+
1477
+ class LinePlot(MPLPlot):
1478
+ _default_rot = 0
1479
+
1480
+ @property
1481
+ def orientation(self) -> PlottingOrientation:
1482
+ return "vertical"
1483
+
1484
+ @property
1485
+ def _kind(self) -> Literal["line", "area", "hist", "kde", "box"]:
1486
+ return "line"
1487
+
1488
+ def __init__(self, data, **kwargs) -> None:
1489
+ from pandas.plotting import plot_params
1490
+
1491
+ MPLPlot.__init__(self, data, **kwargs)
1492
+ if self.stacked:
1493
+ self.data = self.data.fillna(value=0)
1494
+ self.x_compat = plot_params["x_compat"]
1495
+ if "x_compat" in self.kwds:
1496
+ self.x_compat = bool(self.kwds.pop("x_compat"))
1497
+
1498
+ @final
1499
+ def _is_ts_plot(self) -> bool:
1500
+ # this is slightly deceptive
1501
+ return not self.x_compat and self.use_index and self._use_dynamic_x()
1502
+
1503
+ @final
1504
+ def _use_dynamic_x(self) -> bool:
1505
+ return use_dynamic_x(self._get_ax(0), self.data)
1506
+
1507
+ def _make_plot(self, fig: Figure) -> None:
1508
+ if self._is_ts_plot():
1509
+ data = maybe_convert_index(self._get_ax(0), self.data)
1510
+
1511
+ x = data.index # dummy, not used
1512
+ plotf = self._ts_plot
1513
+ it = data.items()
1514
+ else:
1515
+ x = self._get_xticks()
1516
+ # error: Incompatible types in assignment (expression has type
1517
+ # "Callable[[Any, Any, Any, Any, Any, Any, KwArg(Any)], Any]", variable has
1518
+ # type "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]")
1519
+ plotf = self._plot # type: ignore[assignment]
1520
+ # error: Incompatible types in assignment (expression has type
1521
+ # "Iterator[tuple[Hashable, ndarray[Any, Any]]]", variable has
1522
+ # type "Iterable[tuple[Hashable, Series]]")
1523
+ it = self._iter_data(data=self.data) # type: ignore[assignment]
1524
+
1525
+ stacking_id = self._get_stacking_id()
1526
+ is_errorbar = com.any_not_none(*self.errors.values())
1527
+
1528
+ colors = self._get_colors()
1529
+ for i, (label, y) in enumerate(it):
1530
+ ax = self._get_ax(i)
1531
+ kwds = self.kwds.copy()
1532
+ if self.color is not None:
1533
+ kwds["color"] = self.color
1534
+ style, kwds = self._apply_style_colors(
1535
+ colors,
1536
+ kwds,
1537
+ i,
1538
+ # error: Argument 4 to "_apply_style_colors" of "MPLPlot" has
1539
+ # incompatible type "Hashable"; expected "str"
1540
+ label, # type: ignore[arg-type]
1541
+ )
1542
+
1543
+ errors = self._get_errorbars(label=label, index=i)
1544
+ kwds = dict(kwds, **errors)
1545
+
1546
+ label = pprint_thing(label)
1547
+ label = self._mark_right_label(label, index=i)
1548
+ kwds["label"] = label
1549
+
1550
+ newlines = plotf(
1551
+ ax,
1552
+ x,
1553
+ y,
1554
+ style=style,
1555
+ column_num=i,
1556
+ stacking_id=stacking_id,
1557
+ is_errorbar=is_errorbar,
1558
+ **kwds,
1559
+ )
1560
+ self._append_legend_handles_labels(newlines[0], label)
1561
+
1562
+ if self._is_ts_plot():
1563
+ # reset of xlim should be used for ts data
1564
+ # TODO: GH28021, should find a way to change view limit on xaxis
1565
+ lines = get_all_lines(ax)
1566
+ left, right = get_xlim(lines)
1567
+ ax.set_xlim(left, right)
1568
+
1569
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
1570
+ @classmethod
1571
+ def _plot( # type: ignore[override]
1572
+ cls,
1573
+ ax: Axes,
1574
+ x,
1575
+ y: np.ndarray,
1576
+ style=None,
1577
+ column_num=None,
1578
+ stacking_id=None,
1579
+ **kwds,
1580
+ ):
1581
+ # column_num is used to get the target column from plotf in line and
1582
+ # area plots
1583
+ if column_num == 0:
1584
+ cls._initialize_stacker(ax, stacking_id, len(y))
1585
+ y_values = cls._get_stacked_values(ax, stacking_id, y, kwds["label"])
1586
+ lines = MPLPlot._plot(ax, x, y_values, style=style, **kwds)
1587
+ cls._update_stacker(ax, stacking_id, y)
1588
+ return lines
1589
+
1590
+ @final
1591
+ def _ts_plot(self, ax: Axes, x, data: Series, style=None, **kwds):
1592
+ # accept x to be consistent with normal plot func,
1593
+ # x is not passed to tsplot as it uses data.index as x coordinate
1594
+ # column_num must be in kwds for stacking purpose
1595
+ freq, data = maybe_resample(data, ax, kwds)
1596
+
1597
+ # Set ax with freq info
1598
+ decorate_axes(ax, freq)
1599
+ # digging deeper
1600
+ if hasattr(ax, "left_ax"):
1601
+ decorate_axes(ax.left_ax, freq)
1602
+ if hasattr(ax, "right_ax"):
1603
+ decorate_axes(ax.right_ax, freq)
1604
+ # TODO #54485
1605
+ ax._plot_data.append((data, self._kind, kwds)) # type: ignore[attr-defined]
1606
+
1607
+ lines = self._plot(ax, data.index, np.asarray(data.values), style=style, **kwds)
1608
+ # set date formatter, locators and rescale limits
1609
+ # TODO #54485
1610
+ format_dateaxis(ax, ax.freq, data.index) # type: ignore[arg-type, attr-defined]
1611
+ return lines
1612
+
1613
+ @final
1614
+ def _get_stacking_id(self) -> int | None:
1615
+ if self.stacked:
1616
+ return id(self.data)
1617
+ else:
1618
+ return None
1619
+
1620
+ @final
1621
+ @classmethod
1622
+ def _initialize_stacker(cls, ax: Axes, stacking_id, n: int) -> None:
1623
+ if stacking_id is None:
1624
+ return
1625
+ if not hasattr(ax, "_stacker_pos_prior"):
1626
+ # TODO #54485
1627
+ ax._stacker_pos_prior = {} # type: ignore[attr-defined]
1628
+ if not hasattr(ax, "_stacker_neg_prior"):
1629
+ # TODO #54485
1630
+ ax._stacker_neg_prior = {} # type: ignore[attr-defined]
1631
+ # TODO #54485
1632
+ ax._stacker_pos_prior[stacking_id] = np.zeros(n) # type: ignore[attr-defined]
1633
+ # TODO #54485
1634
+ ax._stacker_neg_prior[stacking_id] = np.zeros(n) # type: ignore[attr-defined]
1635
+
1636
+ @final
1637
+ @classmethod
1638
+ def _get_stacked_values(
1639
+ cls, ax: Axes, stacking_id: int | None, values: np.ndarray, label
1640
+ ) -> np.ndarray:
1641
+ if stacking_id is None:
1642
+ return values
1643
+ if not hasattr(ax, "_stacker_pos_prior"):
1644
+ # stacker may not be initialized for subplots
1645
+ cls._initialize_stacker(ax, stacking_id, len(values))
1646
+
1647
+ if (values >= 0).all():
1648
+ # TODO #54485
1649
+ return (
1650
+ ax._stacker_pos_prior[stacking_id] # type: ignore[attr-defined]
1651
+ + values
1652
+ )
1653
+ elif (values <= 0).all():
1654
+ # TODO #54485
1655
+ return (
1656
+ ax._stacker_neg_prior[stacking_id] # type: ignore[attr-defined]
1657
+ + values
1658
+ )
1659
+
1660
+ raise ValueError(
1661
+ "When stacked is True, each column must be either "
1662
+ "all positive or all negative. "
1663
+ f"Column '{label}' contains both positive and negative values"
1664
+ )
1665
+
1666
+ @final
1667
+ @classmethod
1668
+ def _update_stacker(cls, ax: Axes, stacking_id: int | None, values) -> None:
1669
+ if stacking_id is None:
1670
+ return
1671
+ if (values >= 0).all():
1672
+ # TODO #54485
1673
+ ax._stacker_pos_prior[stacking_id] += values # type: ignore[attr-defined]
1674
+ elif (values <= 0).all():
1675
+ # TODO #54485
1676
+ ax._stacker_neg_prior[stacking_id] += values # type: ignore[attr-defined]
1677
+
1678
+ def _post_plot_logic(self, ax: Axes, data) -> None:
1679
+ from matplotlib.ticker import FixedLocator
1680
+
1681
+ def get_label(i):
1682
+ if is_float(i) and i.is_integer():
1683
+ i = int(i)
1684
+ try:
1685
+ return pprint_thing(data.index[i])
1686
+ except Exception:
1687
+ return ""
1688
+
1689
+ if self._need_to_set_index:
1690
+ xticks = ax.get_xticks()
1691
+ xticklabels = [get_label(x) for x in xticks]
1692
+ # error: Argument 1 to "FixedLocator" has incompatible type "ndarray[Any,
1693
+ # Any]"; expected "Sequence[float]"
1694
+ ax.xaxis.set_major_locator(FixedLocator(xticks)) # type: ignore[arg-type]
1695
+ ax.set_xticklabels(xticklabels)
1696
+
1697
+ # If the index is an irregular time series, then by default
1698
+ # we rotate the tick labels. The exception is if there are
1699
+ # subplots which don't share their x-axes, in which we case
1700
+ # we don't rotate the ticklabels as by default the subplots
1701
+ # would be too close together.
1702
+ condition = (
1703
+ not self._use_dynamic_x()
1704
+ and (data.index._is_all_dates and self.use_index)
1705
+ and (not self.subplots or (self.subplots and self.sharex))
1706
+ )
1707
+
1708
+ index_name = self._get_index_name()
1709
+
1710
+ if condition:
1711
+ # irregular TS rotated 30 deg. by default
1712
+ # probably a better place to check / set this.
1713
+ if not self._rot_set:
1714
+ self.rot = 30
1715
+ format_date_labels(ax, rot=self.rot)
1716
+
1717
+ if index_name is not None and self.use_index:
1718
+ ax.set_xlabel(index_name)
1719
+
1720
+
1721
+ class AreaPlot(LinePlot):
1722
+ @property
1723
+ def _kind(self) -> Literal["area"]:
1724
+ return "area"
1725
+
1726
+ def __init__(self, data, **kwargs) -> None:
1727
+ kwargs.setdefault("stacked", True)
1728
+ with warnings.catch_warnings():
1729
+ warnings.filterwarnings(
1730
+ "ignore",
1731
+ "Downcasting object dtype arrays",
1732
+ category=FutureWarning,
1733
+ )
1734
+ data = data.fillna(value=0)
1735
+ LinePlot.__init__(self, data, **kwargs)
1736
+
1737
+ if not self.stacked:
1738
+ # use smaller alpha to distinguish overlap
1739
+ self.kwds.setdefault("alpha", 0.5)
1740
+
1741
+ if self.logy or self.loglog:
1742
+ raise ValueError("Log-y scales are not supported in area plot")
1743
+
1744
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
1745
+ @classmethod
1746
+ def _plot( # type: ignore[override]
1747
+ cls,
1748
+ ax: Axes,
1749
+ x,
1750
+ y: np.ndarray,
1751
+ style=None,
1752
+ column_num=None,
1753
+ stacking_id=None,
1754
+ is_errorbar: bool = False,
1755
+ **kwds,
1756
+ ):
1757
+ if column_num == 0:
1758
+ cls._initialize_stacker(ax, stacking_id, len(y))
1759
+ y_values = cls._get_stacked_values(ax, stacking_id, y, kwds["label"])
1760
+
1761
+ # need to remove label, because subplots uses mpl legend as it is
1762
+ line_kwds = kwds.copy()
1763
+ line_kwds.pop("label")
1764
+ lines = MPLPlot._plot(ax, x, y_values, style=style, **line_kwds)
1765
+
1766
+ # get data from the line to get coordinates for fill_between
1767
+ xdata, y_values = lines[0].get_data(orig=False)
1768
+
1769
+ # unable to use ``_get_stacked_values`` here to get starting point
1770
+ if stacking_id is None:
1771
+ start = np.zeros(len(y))
1772
+ elif (y >= 0).all():
1773
+ # TODO #54485
1774
+ start = ax._stacker_pos_prior[stacking_id] # type: ignore[attr-defined]
1775
+ elif (y <= 0).all():
1776
+ # TODO #54485
1777
+ start = ax._stacker_neg_prior[stacking_id] # type: ignore[attr-defined]
1778
+ else:
1779
+ start = np.zeros(len(y))
1780
+
1781
+ if "color" not in kwds:
1782
+ kwds["color"] = lines[0].get_color()
1783
+
1784
+ rect = ax.fill_between(xdata, start, y_values, **kwds)
1785
+ cls._update_stacker(ax, stacking_id, y)
1786
+
1787
+ # LinePlot expects list of artists
1788
+ res = [rect]
1789
+ return res
1790
+
1791
+ def _post_plot_logic(self, ax: Axes, data) -> None:
1792
+ LinePlot._post_plot_logic(self, ax, data)
1793
+
1794
+ is_shared_y = len(list(ax.get_shared_y_axes())) > 0
1795
+ # do not override the default axis behaviour in case of shared y axes
1796
+ if self.ylim is None and not is_shared_y:
1797
+ if (data >= 0).all().all():
1798
+ ax.set_ylim(0, None)
1799
+ elif (data <= 0).all().all():
1800
+ ax.set_ylim(None, 0)
1801
+
1802
+
1803
+ class BarPlot(MPLPlot):
1804
+ @property
1805
+ def _kind(self) -> Literal["bar", "barh"]:
1806
+ return "bar"
1807
+
1808
+ _default_rot = 90
1809
+
1810
+ @property
1811
+ def orientation(self) -> PlottingOrientation:
1812
+ return "vertical"
1813
+
1814
+ def __init__(
1815
+ self,
1816
+ data,
1817
+ *,
1818
+ align="center",
1819
+ bottom=0,
1820
+ left=0,
1821
+ width=0.5,
1822
+ position=0.5,
1823
+ log=False,
1824
+ **kwargs,
1825
+ ) -> None:
1826
+ # we have to treat a series differently than a
1827
+ # 1-column DataFrame w.r.t. color handling
1828
+ self._is_series = isinstance(data, ABCSeries)
1829
+ self.bar_width = width
1830
+ self._align = align
1831
+ self._position = position
1832
+ self.tick_pos = np.arange(len(data))
1833
+
1834
+ if is_list_like(bottom):
1835
+ bottom = np.array(bottom)
1836
+ if is_list_like(left):
1837
+ left = np.array(left)
1838
+ self.bottom = bottom
1839
+ self.left = left
1840
+
1841
+ self.log = log
1842
+
1843
+ MPLPlot.__init__(self, data, **kwargs)
1844
+
1845
+ @cache_readonly
1846
+ def ax_pos(self) -> np.ndarray:
1847
+ return self.tick_pos - self.tickoffset
1848
+
1849
+ @cache_readonly
1850
+ def tickoffset(self):
1851
+ if self.stacked or self.subplots:
1852
+ return self.bar_width * self._position
1853
+ elif self._align == "edge":
1854
+ w = self.bar_width / self.nseries
1855
+ return self.bar_width * (self._position - 0.5) + w * 0.5
1856
+ else:
1857
+ return self.bar_width * self._position
1858
+
1859
+ @cache_readonly
1860
+ def lim_offset(self):
1861
+ if self.stacked or self.subplots:
1862
+ if self._align == "edge":
1863
+ return self.bar_width / 2
1864
+ else:
1865
+ return 0
1866
+ elif self._align == "edge":
1867
+ w = self.bar_width / self.nseries
1868
+ return w * 0.5
1869
+ else:
1870
+ return 0
1871
+
1872
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
1873
+ @classmethod
1874
+ def _plot( # type: ignore[override]
1875
+ cls,
1876
+ ax: Axes,
1877
+ x,
1878
+ y: np.ndarray,
1879
+ w,
1880
+ start: int | npt.NDArray[np.intp] = 0,
1881
+ log: bool = False,
1882
+ **kwds,
1883
+ ):
1884
+ return ax.bar(x, y, w, bottom=start, log=log, **kwds)
1885
+
1886
+ @property
1887
+ def _start_base(self):
1888
+ return self.bottom
1889
+
1890
+ def _make_plot(self, fig: Figure) -> None:
1891
+ colors = self._get_colors()
1892
+ ncolors = len(colors)
1893
+
1894
+ pos_prior = neg_prior = np.zeros(len(self.data))
1895
+ K = self.nseries
1896
+
1897
+ data = self.data.fillna(0)
1898
+ for i, (label, y) in enumerate(self._iter_data(data=data)):
1899
+ ax = self._get_ax(i)
1900
+ kwds = self.kwds.copy()
1901
+ if self._is_series:
1902
+ kwds["color"] = colors
1903
+ elif isinstance(colors, dict):
1904
+ kwds["color"] = colors[label]
1905
+ else:
1906
+ kwds["color"] = colors[i % ncolors]
1907
+
1908
+ errors = self._get_errorbars(label=label, index=i)
1909
+ kwds = dict(kwds, **errors)
1910
+
1911
+ label = pprint_thing(label)
1912
+ label = self._mark_right_label(label, index=i)
1913
+
1914
+ if (("yerr" in kwds) or ("xerr" in kwds)) and (kwds.get("ecolor") is None):
1915
+ kwds["ecolor"] = mpl.rcParams["xtick.color"]
1916
+
1917
+ start = 0
1918
+ if self.log and (y >= 1).all():
1919
+ start = 1
1920
+ start = start + self._start_base
1921
+
1922
+ kwds["align"] = self._align
1923
+ if self.subplots:
1924
+ w = self.bar_width / 2
1925
+ rect = self._plot(
1926
+ ax,
1927
+ self.ax_pos + w,
1928
+ y,
1929
+ self.bar_width,
1930
+ start=start,
1931
+ label=label,
1932
+ log=self.log,
1933
+ **kwds,
1934
+ )
1935
+ ax.set_title(label)
1936
+ elif self.stacked:
1937
+ mask = y > 0
1938
+ start = np.where(mask, pos_prior, neg_prior) + self._start_base
1939
+ w = self.bar_width / 2
1940
+ rect = self._plot(
1941
+ ax,
1942
+ self.ax_pos + w,
1943
+ y,
1944
+ self.bar_width,
1945
+ start=start,
1946
+ label=label,
1947
+ log=self.log,
1948
+ **kwds,
1949
+ )
1950
+ pos_prior = pos_prior + np.where(mask, y, 0)
1951
+ neg_prior = neg_prior + np.where(mask, 0, y)
1952
+ else:
1953
+ w = self.bar_width / K
1954
+ rect = self._plot(
1955
+ ax,
1956
+ self.ax_pos + (i + 0.5) * w,
1957
+ y,
1958
+ w,
1959
+ start=start,
1960
+ label=label,
1961
+ log=self.log,
1962
+ **kwds,
1963
+ )
1964
+ self._append_legend_handles_labels(rect, label)
1965
+
1966
+ def _post_plot_logic(self, ax: Axes, data) -> None:
1967
+ if self.use_index:
1968
+ str_index = [pprint_thing(key) for key in data.index]
1969
+ else:
1970
+ str_index = [pprint_thing(key) for key in range(data.shape[0])]
1971
+
1972
+ s_edge = self.ax_pos[0] - 0.25 + self.lim_offset
1973
+ e_edge = self.ax_pos[-1] + 0.25 + self.bar_width + self.lim_offset
1974
+
1975
+ self._decorate_ticks(ax, self._get_index_name(), str_index, s_edge, e_edge)
1976
+
1977
+ def _decorate_ticks(
1978
+ self,
1979
+ ax: Axes,
1980
+ name: str | None,
1981
+ ticklabels: list[str],
1982
+ start_edge: float,
1983
+ end_edge: float,
1984
+ ) -> None:
1985
+ ax.set_xlim((start_edge, end_edge))
1986
+
1987
+ if self.xticks is not None:
1988
+ ax.set_xticks(np.array(self.xticks))
1989
+ else:
1990
+ ax.set_xticks(self.tick_pos)
1991
+ ax.set_xticklabels(ticklabels)
1992
+
1993
+ if name is not None and self.use_index:
1994
+ ax.set_xlabel(name)
1995
+
1996
+
1997
+ class BarhPlot(BarPlot):
1998
+ @property
1999
+ def _kind(self) -> Literal["barh"]:
2000
+ return "barh"
2001
+
2002
+ _default_rot = 0
2003
+
2004
+ @property
2005
+ def orientation(self) -> Literal["horizontal"]:
2006
+ return "horizontal"
2007
+
2008
+ @property
2009
+ def _start_base(self):
2010
+ return self.left
2011
+
2012
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
2013
+ @classmethod
2014
+ def _plot( # type: ignore[override]
2015
+ cls,
2016
+ ax: Axes,
2017
+ x,
2018
+ y: np.ndarray,
2019
+ w,
2020
+ start: int | npt.NDArray[np.intp] = 0,
2021
+ log: bool = False,
2022
+ **kwds,
2023
+ ):
2024
+ return ax.barh(x, y, w, left=start, log=log, **kwds)
2025
+
2026
+ def _get_custom_index_name(self):
2027
+ return self.ylabel
2028
+
2029
+ def _decorate_ticks(
2030
+ self,
2031
+ ax: Axes,
2032
+ name: str | None,
2033
+ ticklabels: list[str],
2034
+ start_edge: float,
2035
+ end_edge: float,
2036
+ ) -> None:
2037
+ # horizontal bars
2038
+ ax.set_ylim((start_edge, end_edge))
2039
+ ax.set_yticks(self.tick_pos)
2040
+ ax.set_yticklabels(ticklabels)
2041
+ if name is not None and self.use_index:
2042
+ ax.set_ylabel(name)
2043
+ # error: Argument 1 to "set_xlabel" of "_AxesBase" has incompatible type
2044
+ # "Hashable | None"; expected "str"
2045
+ ax.set_xlabel(self.xlabel) # type: ignore[arg-type]
2046
+
2047
+
2048
+ class PiePlot(MPLPlot):
2049
+ @property
2050
+ def _kind(self) -> Literal["pie"]:
2051
+ return "pie"
2052
+
2053
+ _layout_type = "horizontal"
2054
+
2055
+ def __init__(self, data, kind=None, **kwargs) -> None:
2056
+ data = data.fillna(value=0)
2057
+ if (data < 0).any().any():
2058
+ raise ValueError(f"{self._kind} plot doesn't allow negative values")
2059
+ MPLPlot.__init__(self, data, kind=kind, **kwargs)
2060
+
2061
+ @classmethod
2062
+ def _validate_log_kwd(
2063
+ cls,
2064
+ kwd: str,
2065
+ value: bool | None | Literal["sym"],
2066
+ ) -> bool | None | Literal["sym"]:
2067
+ super()._validate_log_kwd(kwd=kwd, value=value)
2068
+ if value is not False:
2069
+ warnings.warn(
2070
+ f"PiePlot ignores the '{kwd}' keyword",
2071
+ UserWarning,
2072
+ stacklevel=find_stack_level(),
2073
+ )
2074
+ return False
2075
+
2076
+ def _validate_color_args(self, color, colormap) -> None:
2077
+ # TODO: warn if color is passed and ignored?
2078
+ return None
2079
+
2080
+ def _make_plot(self, fig: Figure) -> None:
2081
+ colors = self._get_colors(num_colors=len(self.data), color_kwds="colors")
2082
+ self.kwds.setdefault("colors", colors)
2083
+
2084
+ for i, (label, y) in enumerate(self._iter_data(data=self.data)):
2085
+ ax = self._get_ax(i)
2086
+ if label is not None:
2087
+ label = pprint_thing(label)
2088
+ ax.set_ylabel(label)
2089
+
2090
+ kwds = self.kwds.copy()
2091
+
2092
+ def blank_labeler(label, value):
2093
+ if value == 0:
2094
+ return ""
2095
+ else:
2096
+ return label
2097
+
2098
+ idx = [pprint_thing(v) for v in self.data.index]
2099
+ labels = kwds.pop("labels", idx)
2100
+ # labels is used for each wedge's labels
2101
+ # Blank out labels for values of 0 so they don't overlap
2102
+ # with nonzero wedges
2103
+ if labels is not None:
2104
+ blabels = [blank_labeler(left, value) for left, value in zip(labels, y)]
2105
+ else:
2106
+ blabels = None
2107
+ results = ax.pie(y, labels=blabels, **kwds)
2108
+
2109
+ if kwds.get("autopct", None) is not None:
2110
+ patches, texts, autotexts = results
2111
+ else:
2112
+ patches, texts = results
2113
+ autotexts = []
2114
+
2115
+ if self.fontsize is not None:
2116
+ for t in texts + autotexts:
2117
+ t.set_fontsize(self.fontsize)
2118
+
2119
+ # leglabels is used for legend labels
2120
+ leglabels = labels if labels is not None else idx
2121
+ for _patch, _leglabel in zip(patches, leglabels):
2122
+ self._append_legend_handles_labels(_patch, _leglabel)
2123
+
2124
+ def _post_plot_logic(self, ax: Axes, data) -> None:
2125
+ pass
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/groupby.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+
7
+ from pandas.core.dtypes.missing import remove_na_arraylike
8
+
9
+ from pandas import (
10
+ MultiIndex,
11
+ concat,
12
+ )
13
+
14
+ from pandas.plotting._matplotlib.misc import unpack_single_str_list
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Hashable
18
+
19
+ from pandas._typing import IndexLabel
20
+
21
+ from pandas import (
22
+ DataFrame,
23
+ Series,
24
+ )
25
+
26
+
27
+ def create_iter_data_given_by(
28
+ data: DataFrame, kind: str = "hist"
29
+ ) -> dict[Hashable, DataFrame | Series]:
30
+ """
31
+ Create data for iteration given `by` is assigned or not, and it is only
32
+ used in both hist and boxplot.
33
+
34
+ If `by` is assigned, return a dictionary of DataFrames in which the key of
35
+ dictionary is the values in groups.
36
+ If `by` is not assigned, return input as is, and this preserves current
37
+ status of iter_data.
38
+
39
+ Parameters
40
+ ----------
41
+ data : reformatted grouped data from `_compute_plot_data` method.
42
+ kind : str, plot kind. This function is only used for `hist` and `box` plots.
43
+
44
+ Returns
45
+ -------
46
+ iter_data : DataFrame or Dictionary of DataFrames
47
+
48
+ Examples
49
+ --------
50
+ If `by` is assigned:
51
+
52
+ >>> import numpy as np
53
+ >>> tuples = [('h1', 'a'), ('h1', 'b'), ('h2', 'a'), ('h2', 'b')]
54
+ >>> mi = pd.MultiIndex.from_tuples(tuples)
55
+ >>> value = [[1, 3, np.nan, np.nan],
56
+ ... [3, 4, np.nan, np.nan], [np.nan, np.nan, 5, 6]]
57
+ >>> data = pd.DataFrame(value, columns=mi)
58
+ >>> create_iter_data_given_by(data)
59
+ {'h1': h1
60
+ a b
61
+ 0 1.0 3.0
62
+ 1 3.0 4.0
63
+ 2 NaN NaN, 'h2': h2
64
+ a b
65
+ 0 NaN NaN
66
+ 1 NaN NaN
67
+ 2 5.0 6.0}
68
+ """
69
+
70
+ # For `hist` plot, before transformation, the values in level 0 are values
71
+ # in groups and subplot titles, and later used for column subselection and
72
+ # iteration; For `box` plot, values in level 1 are column names to show,
73
+ # and are used for iteration and as subplots titles.
74
+ if kind == "hist":
75
+ level = 0
76
+ else:
77
+ level = 1
78
+
79
+ # Select sub-columns based on the value of level of MI, and if `by` is
80
+ # assigned, data must be a MI DataFrame
81
+ assert isinstance(data.columns, MultiIndex)
82
+ return {
83
+ col: data.loc[:, data.columns.get_level_values(level) == col]
84
+ for col in data.columns.levels[level]
85
+ }
86
+
87
+
88
+ def reconstruct_data_with_by(
89
+ data: DataFrame, by: IndexLabel, cols: IndexLabel
90
+ ) -> DataFrame:
91
+ """
92
+ Internal function to group data, and reassign multiindex column names onto the
93
+ result in order to let grouped data be used in _compute_plot_data method.
94
+
95
+ Parameters
96
+ ----------
97
+ data : Original DataFrame to plot
98
+ by : grouped `by` parameter selected by users
99
+ cols : columns of data set (excluding columns used in `by`)
100
+
101
+ Returns
102
+ -------
103
+ Output is the reconstructed DataFrame with MultiIndex columns. The first level
104
+ of MI is unique values of groups, and second level of MI is the columns
105
+ selected by users.
106
+
107
+ Examples
108
+ --------
109
+ >>> d = {'h': ['h1', 'h1', 'h2'], 'a': [1, 3, 5], 'b': [3, 4, 6]}
110
+ >>> df = pd.DataFrame(d)
111
+ >>> reconstruct_data_with_by(df, by='h', cols=['a', 'b'])
112
+ h1 h2
113
+ a b a b
114
+ 0 1.0 3.0 NaN NaN
115
+ 1 3.0 4.0 NaN NaN
116
+ 2 NaN NaN 5.0 6.0
117
+ """
118
+ by_modified = unpack_single_str_list(by)
119
+ grouped = data.groupby(by_modified)
120
+
121
+ data_list = []
122
+ for key, group in grouped:
123
+ # error: List item 1 has incompatible type "Union[Hashable,
124
+ # Sequence[Hashable]]"; expected "Iterable[Hashable]"
125
+ columns = MultiIndex.from_product([[key], cols]) # type: ignore[list-item]
126
+ sub_group = group[cols]
127
+ sub_group.columns = columns
128
+ data_list.append(sub_group)
129
+
130
+ data = concat(data_list, axis=1)
131
+ return data
132
+
133
+
134
+ def reformat_hist_y_given_by(y: np.ndarray, by: IndexLabel | None) -> np.ndarray:
135
+ """Internal function to reformat y given `by` is applied or not for hist plot.
136
+
137
+ If by is None, input y is 1-d with NaN removed; and if by is not None, groupby
138
+ will take place and input y is multi-dimensional array.
139
+ """
140
+ if by is not None and len(y.shape) > 1:
141
+ return np.array([remove_na_arraylike(col) for col in y.T]).T
142
+ return remove_na_arraylike(y)
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/hist.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import (
4
+ TYPE_CHECKING,
5
+ Any,
6
+ Literal,
7
+ final,
8
+ )
9
+
10
+ import numpy as np
11
+
12
+ from pandas.core.dtypes.common import (
13
+ is_integer,
14
+ is_list_like,
15
+ )
16
+ from pandas.core.dtypes.generic import (
17
+ ABCDataFrame,
18
+ ABCIndex,
19
+ )
20
+ from pandas.core.dtypes.missing import (
21
+ isna,
22
+ remove_na_arraylike,
23
+ )
24
+
25
+ from pandas.io.formats.printing import pprint_thing
26
+ from pandas.plotting._matplotlib.core import (
27
+ LinePlot,
28
+ MPLPlot,
29
+ )
30
+ from pandas.plotting._matplotlib.groupby import (
31
+ create_iter_data_given_by,
32
+ reformat_hist_y_given_by,
33
+ )
34
+ from pandas.plotting._matplotlib.misc import unpack_single_str_list
35
+ from pandas.plotting._matplotlib.tools import (
36
+ create_subplots,
37
+ flatten_axes,
38
+ maybe_adjust_figure,
39
+ set_ticks_props,
40
+ )
41
+
42
+ if TYPE_CHECKING:
43
+ from matplotlib.axes import Axes
44
+ from matplotlib.figure import Figure
45
+
46
+ from pandas._typing import PlottingOrientation
47
+
48
+ from pandas import (
49
+ DataFrame,
50
+ Series,
51
+ )
52
+
53
+
54
+ class HistPlot(LinePlot):
55
+ @property
56
+ def _kind(self) -> Literal["hist", "kde"]:
57
+ return "hist"
58
+
59
+ def __init__(
60
+ self,
61
+ data,
62
+ bins: int | np.ndarray | list[np.ndarray] = 10,
63
+ bottom: int | np.ndarray = 0,
64
+ *,
65
+ range=None,
66
+ weights=None,
67
+ **kwargs,
68
+ ) -> None:
69
+ if is_list_like(bottom):
70
+ bottom = np.array(bottom)
71
+ self.bottom = bottom
72
+
73
+ self._bin_range = range
74
+ self.weights = weights
75
+
76
+ self.xlabel = kwargs.get("xlabel")
77
+ self.ylabel = kwargs.get("ylabel")
78
+ # Do not call LinePlot.__init__ which may fill nan
79
+ MPLPlot.__init__(self, data, **kwargs) # pylint: disable=non-parent-init-called
80
+
81
+ self.bins = self._adjust_bins(bins)
82
+
83
+ def _adjust_bins(self, bins: int | np.ndarray | list[np.ndarray]):
84
+ if is_integer(bins):
85
+ if self.by is not None:
86
+ by_modified = unpack_single_str_list(self.by)
87
+ grouped = self.data.groupby(by_modified)[self.columns]
88
+ bins = [self._calculate_bins(group, bins) for key, group in grouped]
89
+ else:
90
+ bins = self._calculate_bins(self.data, bins)
91
+ return bins
92
+
93
+ def _calculate_bins(self, data: Series | DataFrame, bins) -> np.ndarray:
94
+ """Calculate bins given data"""
95
+ nd_values = data.infer_objects(copy=False)._get_numeric_data()
96
+ values = np.ravel(nd_values)
97
+ values = values[~isna(values)]
98
+
99
+ hist, bins = np.histogram(values, bins=bins, range=self._bin_range)
100
+ return bins
101
+
102
+ # error: Signature of "_plot" incompatible with supertype "LinePlot"
103
+ @classmethod
104
+ def _plot( # type: ignore[override]
105
+ cls,
106
+ ax: Axes,
107
+ y: np.ndarray,
108
+ style=None,
109
+ bottom: int | np.ndarray = 0,
110
+ column_num: int = 0,
111
+ stacking_id=None,
112
+ *,
113
+ bins,
114
+ **kwds,
115
+ ):
116
+ if column_num == 0:
117
+ cls._initialize_stacker(ax, stacking_id, len(bins) - 1)
118
+
119
+ base = np.zeros(len(bins) - 1)
120
+ bottom = bottom + cls._get_stacked_values(ax, stacking_id, base, kwds["label"])
121
+ # ignore style
122
+ n, bins, patches = ax.hist(y, bins=bins, bottom=bottom, **kwds)
123
+ cls._update_stacker(ax, stacking_id, n)
124
+ return patches
125
+
126
+ def _make_plot(self, fig: Figure) -> None:
127
+ colors = self._get_colors()
128
+ stacking_id = self._get_stacking_id()
129
+
130
+ # Re-create iterated data if `by` is assigned by users
131
+ data = (
132
+ create_iter_data_given_by(self.data, self._kind)
133
+ if self.by is not None
134
+ else self.data
135
+ )
136
+
137
+ # error: Argument "data" to "_iter_data" of "MPLPlot" has incompatible
138
+ # type "object"; expected "DataFrame | dict[Hashable, Series | DataFrame]"
139
+ for i, (label, y) in enumerate(self._iter_data(data=data)): # type: ignore[arg-type]
140
+ ax = self._get_ax(i)
141
+
142
+ kwds = self.kwds.copy()
143
+ if self.color is not None:
144
+ kwds["color"] = self.color
145
+
146
+ label = pprint_thing(label)
147
+ label = self._mark_right_label(label, index=i)
148
+ kwds["label"] = label
149
+
150
+ style, kwds = self._apply_style_colors(colors, kwds, i, label)
151
+ if style is not None:
152
+ kwds["style"] = style
153
+
154
+ self._make_plot_keywords(kwds, y)
155
+
156
+ # the bins is multi-dimension array now and each plot need only 1-d and
157
+ # when by is applied, label should be columns that are grouped
158
+ if self.by is not None:
159
+ kwds["bins"] = kwds["bins"][i]
160
+ kwds["label"] = self.columns
161
+ kwds.pop("color")
162
+
163
+ if self.weights is not None:
164
+ kwds["weights"] = type(self)._get_column_weights(self.weights, i, y)
165
+
166
+ y = reformat_hist_y_given_by(y, self.by)
167
+
168
+ artists = self._plot(ax, y, column_num=i, stacking_id=stacking_id, **kwds)
169
+
170
+ # when by is applied, show title for subplots to know which group it is
171
+ if self.by is not None:
172
+ ax.set_title(pprint_thing(label))
173
+
174
+ self._append_legend_handles_labels(artists[0], label)
175
+
176
+ def _make_plot_keywords(self, kwds: dict[str, Any], y: np.ndarray) -> None:
177
+ """merge BoxPlot/KdePlot properties to passed kwds"""
178
+ # y is required for KdePlot
179
+ kwds["bottom"] = self.bottom
180
+ kwds["bins"] = self.bins
181
+
182
+ @final
183
+ @staticmethod
184
+ def _get_column_weights(weights, i: int, y):
185
+ # We allow weights to be a multi-dimensional array, e.g. a (10, 2) array,
186
+ # and each sub-array (10,) will be called in each iteration. If users only
187
+ # provide 1D array, we assume the same weights is used for all iterations
188
+ if weights is not None:
189
+ if np.ndim(weights) != 1 and np.shape(weights)[-1] != 1:
190
+ try:
191
+ weights = weights[:, i]
192
+ except IndexError as err:
193
+ raise ValueError(
194
+ "weights must have the same shape as data, "
195
+ "or be a single column"
196
+ ) from err
197
+ weights = weights[~isna(y)]
198
+ return weights
199
+
200
+ def _post_plot_logic(self, ax: Axes, data) -> None:
201
+ if self.orientation == "horizontal":
202
+ # error: Argument 1 to "set_xlabel" of "_AxesBase" has incompatible
203
+ # type "Hashable"; expected "str"
204
+ ax.set_xlabel(
205
+ "Frequency"
206
+ if self.xlabel is None
207
+ else self.xlabel # type: ignore[arg-type]
208
+ )
209
+ ax.set_ylabel(self.ylabel) # type: ignore[arg-type]
210
+ else:
211
+ ax.set_xlabel(self.xlabel) # type: ignore[arg-type]
212
+ ax.set_ylabel(
213
+ "Frequency"
214
+ if self.ylabel is None
215
+ else self.ylabel # type: ignore[arg-type]
216
+ )
217
+
218
+ @property
219
+ def orientation(self) -> PlottingOrientation:
220
+ if self.kwds.get("orientation", None) == "horizontal":
221
+ return "horizontal"
222
+ else:
223
+ return "vertical"
224
+
225
+
226
+ class KdePlot(HistPlot):
227
+ @property
228
+ def _kind(self) -> Literal["kde"]:
229
+ return "kde"
230
+
231
+ @property
232
+ def orientation(self) -> Literal["vertical"]:
233
+ return "vertical"
234
+
235
+ def __init__(
236
+ self, data, bw_method=None, ind=None, *, weights=None, **kwargs
237
+ ) -> None:
238
+ # Do not call LinePlot.__init__ which may fill nan
239
+ MPLPlot.__init__(self, data, **kwargs) # pylint: disable=non-parent-init-called
240
+ self.bw_method = bw_method
241
+ self.ind = ind
242
+ self.weights = weights
243
+
244
+ @staticmethod
245
+ def _get_ind(y: np.ndarray, ind):
246
+ if ind is None:
247
+ # np.nanmax() and np.nanmin() ignores the missing values
248
+ sample_range = np.nanmax(y) - np.nanmin(y)
249
+ ind = np.linspace(
250
+ np.nanmin(y) - 0.5 * sample_range,
251
+ np.nanmax(y) + 0.5 * sample_range,
252
+ 1000,
253
+ )
254
+ elif is_integer(ind):
255
+ sample_range = np.nanmax(y) - np.nanmin(y)
256
+ ind = np.linspace(
257
+ np.nanmin(y) - 0.5 * sample_range,
258
+ np.nanmax(y) + 0.5 * sample_range,
259
+ ind,
260
+ )
261
+ return ind
262
+
263
+ @classmethod
264
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
265
+ def _plot( # type: ignore[override]
266
+ cls,
267
+ ax: Axes,
268
+ y: np.ndarray,
269
+ style=None,
270
+ bw_method=None,
271
+ ind=None,
272
+ column_num=None,
273
+ stacking_id: int | None = None,
274
+ **kwds,
275
+ ):
276
+ from scipy.stats import gaussian_kde
277
+
278
+ y = remove_na_arraylike(y)
279
+ gkde = gaussian_kde(y, bw_method=bw_method)
280
+
281
+ y = gkde.evaluate(ind)
282
+ lines = MPLPlot._plot(ax, ind, y, style=style, **kwds)
283
+ return lines
284
+
285
+ def _make_plot_keywords(self, kwds: dict[str, Any], y: np.ndarray) -> None:
286
+ kwds["bw_method"] = self.bw_method
287
+ kwds["ind"] = type(self)._get_ind(y, ind=self.ind)
288
+
289
+ def _post_plot_logic(self, ax: Axes, data) -> None:
290
+ ax.set_ylabel("Density")
291
+
292
+
293
+ def _grouped_plot(
294
+ plotf,
295
+ data: Series | DataFrame,
296
+ column=None,
297
+ by=None,
298
+ numeric_only: bool = True,
299
+ figsize: tuple[float, float] | None = None,
300
+ sharex: bool = True,
301
+ sharey: bool = True,
302
+ layout=None,
303
+ rot: float = 0,
304
+ ax=None,
305
+ **kwargs,
306
+ ):
307
+ # error: Non-overlapping equality check (left operand type: "Optional[Tuple[float,
308
+ # float]]", right operand type: "Literal['default']")
309
+ if figsize == "default": # type: ignore[comparison-overlap]
310
+ # allowed to specify mpl default with 'default'
311
+ raise ValueError(
312
+ "figsize='default' is no longer supported. "
313
+ "Specify figure size by tuple instead"
314
+ )
315
+
316
+ grouped = data.groupby(by)
317
+ if column is not None:
318
+ grouped = grouped[column]
319
+
320
+ naxes = len(grouped)
321
+ fig, axes = create_subplots(
322
+ naxes=naxes, figsize=figsize, sharex=sharex, sharey=sharey, ax=ax, layout=layout
323
+ )
324
+
325
+ _axes = flatten_axes(axes)
326
+
327
+ for i, (key, group) in enumerate(grouped):
328
+ ax = _axes[i]
329
+ if numeric_only and isinstance(group, ABCDataFrame):
330
+ group = group._get_numeric_data()
331
+ plotf(group, ax, **kwargs)
332
+ ax.set_title(pprint_thing(key))
333
+
334
+ return fig, axes
335
+
336
+
337
+ def _grouped_hist(
338
+ data: Series | DataFrame,
339
+ column=None,
340
+ by=None,
341
+ ax=None,
342
+ bins: int = 50,
343
+ figsize: tuple[float, float] | None = None,
344
+ layout=None,
345
+ sharex: bool = False,
346
+ sharey: bool = False,
347
+ rot: float = 90,
348
+ grid: bool = True,
349
+ xlabelsize: int | None = None,
350
+ xrot=None,
351
+ ylabelsize: int | None = None,
352
+ yrot=None,
353
+ legend: bool = False,
354
+ **kwargs,
355
+ ):
356
+ """
357
+ Grouped histogram
358
+
359
+ Parameters
360
+ ----------
361
+ data : Series/DataFrame
362
+ column : object, optional
363
+ by : object, optional
364
+ ax : axes, optional
365
+ bins : int, default 50
366
+ figsize : tuple, optional
367
+ layout : optional
368
+ sharex : bool, default False
369
+ sharey : bool, default False
370
+ rot : float, default 90
371
+ grid : bool, default True
372
+ legend: : bool, default False
373
+ kwargs : dict, keyword arguments passed to matplotlib.Axes.hist
374
+
375
+ Returns
376
+ -------
377
+ collection of Matplotlib Axes
378
+ """
379
+ if legend:
380
+ assert "label" not in kwargs
381
+ if data.ndim == 1:
382
+ kwargs["label"] = data.name
383
+ elif column is None:
384
+ kwargs["label"] = data.columns
385
+ else:
386
+ kwargs["label"] = column
387
+
388
+ def plot_group(group, ax) -> None:
389
+ ax.hist(group.dropna().values, bins=bins, **kwargs)
390
+ if legend:
391
+ ax.legend()
392
+
393
+ if xrot is None:
394
+ xrot = rot
395
+
396
+ fig, axes = _grouped_plot(
397
+ plot_group,
398
+ data,
399
+ column=column,
400
+ by=by,
401
+ sharex=sharex,
402
+ sharey=sharey,
403
+ ax=ax,
404
+ figsize=figsize,
405
+ layout=layout,
406
+ rot=rot,
407
+ )
408
+
409
+ set_ticks_props(
410
+ axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot
411
+ )
412
+
413
+ maybe_adjust_figure(
414
+ fig, bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3
415
+ )
416
+ return axes
417
+
418
+
419
+ def hist_series(
420
+ self: Series,
421
+ by=None,
422
+ ax=None,
423
+ grid: bool = True,
424
+ xlabelsize: int | None = None,
425
+ xrot=None,
426
+ ylabelsize: int | None = None,
427
+ yrot=None,
428
+ figsize: tuple[float, float] | None = None,
429
+ bins: int = 10,
430
+ legend: bool = False,
431
+ **kwds,
432
+ ):
433
+ import matplotlib.pyplot as plt
434
+
435
+ if legend and "label" in kwds:
436
+ raise ValueError("Cannot use both legend and label")
437
+
438
+ if by is None:
439
+ if kwds.get("layout", None) is not None:
440
+ raise ValueError("The 'layout' keyword is not supported when 'by' is None")
441
+ # hack until the plotting interface is a bit more unified
442
+ fig = kwds.pop(
443
+ "figure", plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize)
444
+ )
445
+ if figsize is not None and tuple(figsize) != tuple(fig.get_size_inches()):
446
+ fig.set_size_inches(*figsize, forward=True)
447
+ if ax is None:
448
+ ax = fig.gca()
449
+ elif ax.get_figure() != fig:
450
+ raise AssertionError("passed axis not bound to passed figure")
451
+ values = self.dropna().values
452
+ if legend:
453
+ kwds["label"] = self.name
454
+ ax.hist(values, bins=bins, **kwds)
455
+ if legend:
456
+ ax.legend()
457
+ ax.grid(grid)
458
+ axes = np.array([ax])
459
+
460
+ # error: Argument 1 to "set_ticks_props" has incompatible type "ndarray[Any,
461
+ # dtype[Any]]"; expected "Axes | Sequence[Axes]"
462
+ set_ticks_props(
463
+ axes, # type: ignore[arg-type]
464
+ xlabelsize=xlabelsize,
465
+ xrot=xrot,
466
+ ylabelsize=ylabelsize,
467
+ yrot=yrot,
468
+ )
469
+
470
+ else:
471
+ if "figure" in kwds:
472
+ raise ValueError(
473
+ "Cannot pass 'figure' when using the "
474
+ "'by' argument, since a new 'Figure' instance will be created"
475
+ )
476
+ axes = _grouped_hist(
477
+ self,
478
+ by=by,
479
+ ax=ax,
480
+ grid=grid,
481
+ figsize=figsize,
482
+ bins=bins,
483
+ xlabelsize=xlabelsize,
484
+ xrot=xrot,
485
+ ylabelsize=ylabelsize,
486
+ yrot=yrot,
487
+ legend=legend,
488
+ **kwds,
489
+ )
490
+
491
+ if hasattr(axes, "ndim"):
492
+ if axes.ndim == 1 and len(axes) == 1:
493
+ return axes[0]
494
+ return axes
495
+
496
+
497
+ def hist_frame(
498
+ data: DataFrame,
499
+ column=None,
500
+ by=None,
501
+ grid: bool = True,
502
+ xlabelsize: int | None = None,
503
+ xrot=None,
504
+ ylabelsize: int | None = None,
505
+ yrot=None,
506
+ ax=None,
507
+ sharex: bool = False,
508
+ sharey: bool = False,
509
+ figsize: tuple[float, float] | None = None,
510
+ layout=None,
511
+ bins: int = 10,
512
+ legend: bool = False,
513
+ **kwds,
514
+ ):
515
+ if legend and "label" in kwds:
516
+ raise ValueError("Cannot use both legend and label")
517
+ if by is not None:
518
+ axes = _grouped_hist(
519
+ data,
520
+ column=column,
521
+ by=by,
522
+ ax=ax,
523
+ grid=grid,
524
+ figsize=figsize,
525
+ sharex=sharex,
526
+ sharey=sharey,
527
+ layout=layout,
528
+ bins=bins,
529
+ xlabelsize=xlabelsize,
530
+ xrot=xrot,
531
+ ylabelsize=ylabelsize,
532
+ yrot=yrot,
533
+ legend=legend,
534
+ **kwds,
535
+ )
536
+ return axes
537
+
538
+ if column is not None:
539
+ if not isinstance(column, (list, np.ndarray, ABCIndex)):
540
+ column = [column]
541
+ data = data[column]
542
+ # GH32590
543
+ data = data.select_dtypes(
544
+ include=(np.number, "datetime64", "datetimetz"), exclude="timedelta"
545
+ )
546
+ naxes = len(data.columns)
547
+
548
+ if naxes == 0:
549
+ raise ValueError(
550
+ "hist method requires numerical or datetime columns, nothing to plot."
551
+ )
552
+
553
+ fig, axes = create_subplots(
554
+ naxes=naxes,
555
+ ax=ax,
556
+ squeeze=False,
557
+ sharex=sharex,
558
+ sharey=sharey,
559
+ figsize=figsize,
560
+ layout=layout,
561
+ )
562
+ _axes = flatten_axes(axes)
563
+
564
+ can_set_label = "label" not in kwds
565
+
566
+ for i, col in enumerate(data.columns):
567
+ ax = _axes[i]
568
+ if legend and can_set_label:
569
+ kwds["label"] = col
570
+ ax.hist(data[col].dropna().values, bins=bins, **kwds)
571
+ ax.set_title(col)
572
+ ax.grid(grid)
573
+ if legend:
574
+ ax.legend()
575
+
576
+ set_ticks_props(
577
+ axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot
578
+ )
579
+ maybe_adjust_figure(fig, wspace=0.3, hspace=0.3)
580
+
581
+ return axes
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/misc.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ from typing import TYPE_CHECKING
5
+
6
+ from matplotlib import patches
7
+ import matplotlib.lines as mlines
8
+ import numpy as np
9
+
10
+ from pandas.core.dtypes.missing import notna
11
+
12
+ from pandas.io.formats.printing import pprint_thing
13
+ from pandas.plotting._matplotlib.style import get_standard_colors
14
+ from pandas.plotting._matplotlib.tools import (
15
+ create_subplots,
16
+ do_adjust_figure,
17
+ maybe_adjust_figure,
18
+ set_ticks_props,
19
+ )
20
+
21
+ if TYPE_CHECKING:
22
+ from collections.abc import Hashable
23
+
24
+ from matplotlib.axes import Axes
25
+ from matplotlib.figure import Figure
26
+
27
+ from pandas import (
28
+ DataFrame,
29
+ Index,
30
+ Series,
31
+ )
32
+
33
+
34
+ def scatter_matrix(
35
+ frame: DataFrame,
36
+ alpha: float = 0.5,
37
+ figsize: tuple[float, float] | None = None,
38
+ ax=None,
39
+ grid: bool = False,
40
+ diagonal: str = "hist",
41
+ marker: str = ".",
42
+ density_kwds=None,
43
+ hist_kwds=None,
44
+ range_padding: float = 0.05,
45
+ **kwds,
46
+ ):
47
+ df = frame._get_numeric_data()
48
+ n = df.columns.size
49
+ naxes = n * n
50
+ fig, axes = create_subplots(naxes=naxes, figsize=figsize, ax=ax, squeeze=False)
51
+
52
+ # no gaps between subplots
53
+ maybe_adjust_figure(fig, wspace=0, hspace=0)
54
+
55
+ mask = notna(df)
56
+
57
+ marker = _get_marker_compat(marker)
58
+
59
+ hist_kwds = hist_kwds or {}
60
+ density_kwds = density_kwds or {}
61
+
62
+ # GH 14855
63
+ kwds.setdefault("edgecolors", "none")
64
+
65
+ boundaries_list = []
66
+ for a in df.columns:
67
+ values = df[a].values[mask[a].values]
68
+ rmin_, rmax_ = np.min(values), np.max(values)
69
+ rdelta_ext = (rmax_ - rmin_) * range_padding / 2
70
+ boundaries_list.append((rmin_ - rdelta_ext, rmax_ + rdelta_ext))
71
+
72
+ for i, a in enumerate(df.columns):
73
+ for j, b in enumerate(df.columns):
74
+ ax = axes[i, j]
75
+
76
+ if i == j:
77
+ values = df[a].values[mask[a].values]
78
+
79
+ # Deal with the diagonal by drawing a histogram there.
80
+ if diagonal == "hist":
81
+ ax.hist(values, **hist_kwds)
82
+
83
+ elif diagonal in ("kde", "density"):
84
+ from scipy.stats import gaussian_kde
85
+
86
+ y = values
87
+ gkde = gaussian_kde(y)
88
+ ind = np.linspace(y.min(), y.max(), 1000)
89
+ ax.plot(ind, gkde.evaluate(ind), **density_kwds)
90
+
91
+ ax.set_xlim(boundaries_list[i])
92
+
93
+ else:
94
+ common = (mask[a] & mask[b]).values
95
+
96
+ ax.scatter(
97
+ df[b][common], df[a][common], marker=marker, alpha=alpha, **kwds
98
+ )
99
+
100
+ ax.set_xlim(boundaries_list[j])
101
+ ax.set_ylim(boundaries_list[i])
102
+
103
+ ax.set_xlabel(b)
104
+ ax.set_ylabel(a)
105
+
106
+ if j != 0:
107
+ ax.yaxis.set_visible(False)
108
+ if i != n - 1:
109
+ ax.xaxis.set_visible(False)
110
+
111
+ if len(df.columns) > 1:
112
+ lim1 = boundaries_list[0]
113
+ locs = axes[0][1].yaxis.get_majorticklocs()
114
+ locs = locs[(lim1[0] <= locs) & (locs <= lim1[1])]
115
+ adj = (locs - lim1[0]) / (lim1[1] - lim1[0])
116
+
117
+ lim0 = axes[0][0].get_ylim()
118
+ adj = adj * (lim0[1] - lim0[0]) + lim0[0]
119
+ axes[0][0].yaxis.set_ticks(adj)
120
+
121
+ if np.all(locs == locs.astype(int)):
122
+ # if all ticks are int
123
+ locs = locs.astype(int)
124
+ axes[0][0].yaxis.set_ticklabels(locs)
125
+
126
+ set_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0)
127
+
128
+ return axes
129
+
130
+
131
+ def _get_marker_compat(marker):
132
+ if marker not in mlines.lineMarkers:
133
+ return "o"
134
+ return marker
135
+
136
+
137
+ def radviz(
138
+ frame: DataFrame,
139
+ class_column,
140
+ ax: Axes | None = None,
141
+ color=None,
142
+ colormap=None,
143
+ **kwds,
144
+ ) -> Axes:
145
+ import matplotlib.pyplot as plt
146
+
147
+ def normalize(series):
148
+ a = min(series)
149
+ b = max(series)
150
+ return (series - a) / (b - a)
151
+
152
+ n = len(frame)
153
+ classes = frame[class_column].drop_duplicates()
154
+ class_col = frame[class_column]
155
+ df = frame.drop(class_column, axis=1).apply(normalize)
156
+
157
+ if ax is None:
158
+ ax = plt.gca()
159
+ ax.set_xlim(-1, 1)
160
+ ax.set_ylim(-1, 1)
161
+
162
+ to_plot: dict[Hashable, list[list]] = {}
163
+ colors = get_standard_colors(
164
+ num_colors=len(classes), colormap=colormap, color_type="random", color=color
165
+ )
166
+
167
+ for kls in classes:
168
+ to_plot[kls] = [[], []]
169
+
170
+ m = len(frame.columns) - 1
171
+ s = np.array(
172
+ [(np.cos(t), np.sin(t)) for t in [2 * np.pi * (i / m) for i in range(m)]]
173
+ )
174
+
175
+ for i in range(n):
176
+ row = df.iloc[i].values
177
+ row_ = np.repeat(np.expand_dims(row, axis=1), 2, axis=1)
178
+ y = (s * row_).sum(axis=0) / row.sum()
179
+ kls = class_col.iat[i]
180
+ to_plot[kls][0].append(y[0])
181
+ to_plot[kls][1].append(y[1])
182
+
183
+ for i, kls in enumerate(classes):
184
+ ax.scatter(
185
+ to_plot[kls][0],
186
+ to_plot[kls][1],
187
+ color=colors[i],
188
+ label=pprint_thing(kls),
189
+ **kwds,
190
+ )
191
+ ax.legend()
192
+
193
+ ax.add_patch(patches.Circle((0.0, 0.0), radius=1.0, facecolor="none"))
194
+
195
+ for xy, name in zip(s, df.columns):
196
+ ax.add_patch(patches.Circle(xy, radius=0.025, facecolor="gray"))
197
+
198
+ if xy[0] < 0.0 and xy[1] < 0.0:
199
+ ax.text(
200
+ xy[0] - 0.025, xy[1] - 0.025, name, ha="right", va="top", size="small"
201
+ )
202
+ elif xy[0] < 0.0 <= xy[1]:
203
+ ax.text(
204
+ xy[0] - 0.025,
205
+ xy[1] + 0.025,
206
+ name,
207
+ ha="right",
208
+ va="bottom",
209
+ size="small",
210
+ )
211
+ elif xy[1] < 0.0 <= xy[0]:
212
+ ax.text(
213
+ xy[0] + 0.025, xy[1] - 0.025, name, ha="left", va="top", size="small"
214
+ )
215
+ elif xy[0] >= 0.0 and xy[1] >= 0.0:
216
+ ax.text(
217
+ xy[0] + 0.025, xy[1] + 0.025, name, ha="left", va="bottom", size="small"
218
+ )
219
+
220
+ ax.axis("equal")
221
+ return ax
222
+
223
+
224
+ def andrews_curves(
225
+ frame: DataFrame,
226
+ class_column,
227
+ ax: Axes | None = None,
228
+ samples: int = 200,
229
+ color=None,
230
+ colormap=None,
231
+ **kwds,
232
+ ) -> Axes:
233
+ import matplotlib.pyplot as plt
234
+
235
+ def function(amplitudes):
236
+ def f(t):
237
+ x1 = amplitudes[0]
238
+ result = x1 / np.sqrt(2.0)
239
+
240
+ # Take the rest of the coefficients and resize them
241
+ # appropriately. Take a copy of amplitudes as otherwise numpy
242
+ # deletes the element from amplitudes itself.
243
+ coeffs = np.delete(np.copy(amplitudes), 0)
244
+ coeffs = np.resize(coeffs, (int((coeffs.size + 1) / 2), 2))
245
+
246
+ # Generate the harmonics and arguments for the sin and cos
247
+ # functions.
248
+ harmonics = np.arange(0, coeffs.shape[0]) + 1
249
+ trig_args = np.outer(harmonics, t)
250
+
251
+ result += np.sum(
252
+ coeffs[:, 0, np.newaxis] * np.sin(trig_args)
253
+ + coeffs[:, 1, np.newaxis] * np.cos(trig_args),
254
+ axis=0,
255
+ )
256
+ return result
257
+
258
+ return f
259
+
260
+ n = len(frame)
261
+ class_col = frame[class_column]
262
+ classes = frame[class_column].drop_duplicates()
263
+ df = frame.drop(class_column, axis=1)
264
+ t = np.linspace(-np.pi, np.pi, samples)
265
+ used_legends: set[str] = set()
266
+
267
+ color_values = get_standard_colors(
268
+ num_colors=len(classes), colormap=colormap, color_type="random", color=color
269
+ )
270
+ colors = dict(zip(classes, color_values))
271
+ if ax is None:
272
+ ax = plt.gca()
273
+ ax.set_xlim(-np.pi, np.pi)
274
+ for i in range(n):
275
+ row = df.iloc[i].values
276
+ f = function(row)
277
+ y = f(t)
278
+ kls = class_col.iat[i]
279
+ label = pprint_thing(kls)
280
+ if label not in used_legends:
281
+ used_legends.add(label)
282
+ ax.plot(t, y, color=colors[kls], label=label, **kwds)
283
+ else:
284
+ ax.plot(t, y, color=colors[kls], **kwds)
285
+
286
+ ax.legend(loc="upper right")
287
+ ax.grid()
288
+ return ax
289
+
290
+
291
+ def bootstrap_plot(
292
+ series: Series,
293
+ fig: Figure | None = None,
294
+ size: int = 50,
295
+ samples: int = 500,
296
+ **kwds,
297
+ ) -> Figure:
298
+ import matplotlib.pyplot as plt
299
+
300
+ # TODO: is the failure mentioned below still relevant?
301
+ # random.sample(ndarray, int) fails on python 3.3, sigh
302
+ data = list(series.values)
303
+ samplings = [random.sample(data, size) for _ in range(samples)]
304
+
305
+ means = np.array([np.mean(sampling) for sampling in samplings])
306
+ medians = np.array([np.median(sampling) for sampling in samplings])
307
+ midranges = np.array(
308
+ [(min(sampling) + max(sampling)) * 0.5 for sampling in samplings]
309
+ )
310
+ if fig is None:
311
+ fig = plt.figure()
312
+ x = list(range(samples))
313
+ axes = []
314
+ ax1 = fig.add_subplot(2, 3, 1)
315
+ ax1.set_xlabel("Sample")
316
+ axes.append(ax1)
317
+ ax1.plot(x, means, **kwds)
318
+ ax2 = fig.add_subplot(2, 3, 2)
319
+ ax2.set_xlabel("Sample")
320
+ axes.append(ax2)
321
+ ax2.plot(x, medians, **kwds)
322
+ ax3 = fig.add_subplot(2, 3, 3)
323
+ ax3.set_xlabel("Sample")
324
+ axes.append(ax3)
325
+ ax3.plot(x, midranges, **kwds)
326
+ ax4 = fig.add_subplot(2, 3, 4)
327
+ ax4.set_xlabel("Mean")
328
+ axes.append(ax4)
329
+ ax4.hist(means, **kwds)
330
+ ax5 = fig.add_subplot(2, 3, 5)
331
+ ax5.set_xlabel("Median")
332
+ axes.append(ax5)
333
+ ax5.hist(medians, **kwds)
334
+ ax6 = fig.add_subplot(2, 3, 6)
335
+ ax6.set_xlabel("Midrange")
336
+ axes.append(ax6)
337
+ ax6.hist(midranges, **kwds)
338
+ for axis in axes:
339
+ plt.setp(axis.get_xticklabels(), fontsize=8)
340
+ plt.setp(axis.get_yticklabels(), fontsize=8)
341
+ if do_adjust_figure(fig):
342
+ plt.tight_layout()
343
+ return fig
344
+
345
+
346
+ def parallel_coordinates(
347
+ frame: DataFrame,
348
+ class_column,
349
+ cols=None,
350
+ ax: Axes | None = None,
351
+ color=None,
352
+ use_columns: bool = False,
353
+ xticks=None,
354
+ colormap=None,
355
+ axvlines: bool = True,
356
+ axvlines_kwds=None,
357
+ sort_labels: bool = False,
358
+ **kwds,
359
+ ) -> Axes:
360
+ import matplotlib.pyplot as plt
361
+
362
+ if axvlines_kwds is None:
363
+ axvlines_kwds = {"linewidth": 1, "color": "black"}
364
+
365
+ n = len(frame)
366
+ classes = frame[class_column].drop_duplicates()
367
+ class_col = frame[class_column]
368
+
369
+ if cols is None:
370
+ df = frame.drop(class_column, axis=1)
371
+ else:
372
+ df = frame[cols]
373
+
374
+ used_legends: set[str] = set()
375
+
376
+ ncols = len(df.columns)
377
+
378
+ # determine values to use for xticks
379
+ x: list[int] | Index
380
+ if use_columns is True:
381
+ if not np.all(np.isreal(list(df.columns))):
382
+ raise ValueError("Columns must be numeric to be used as xticks")
383
+ x = df.columns
384
+ elif xticks is not None:
385
+ if not np.all(np.isreal(xticks)):
386
+ raise ValueError("xticks specified must be numeric")
387
+ if len(xticks) != ncols:
388
+ raise ValueError("Length of xticks must match number of columns")
389
+ x = xticks
390
+ else:
391
+ x = list(range(ncols))
392
+
393
+ if ax is None:
394
+ ax = plt.gca()
395
+
396
+ color_values = get_standard_colors(
397
+ num_colors=len(classes), colormap=colormap, color_type="random", color=color
398
+ )
399
+
400
+ if sort_labels:
401
+ classes = sorted(classes)
402
+ color_values = sorted(color_values)
403
+ colors = dict(zip(classes, color_values))
404
+
405
+ for i in range(n):
406
+ y = df.iloc[i].values
407
+ kls = class_col.iat[i]
408
+ label = pprint_thing(kls)
409
+ if label not in used_legends:
410
+ used_legends.add(label)
411
+ ax.plot(x, y, color=colors[kls], label=label, **kwds)
412
+ else:
413
+ ax.plot(x, y, color=colors[kls], **kwds)
414
+
415
+ if axvlines:
416
+ for i in x:
417
+ ax.axvline(i, **axvlines_kwds)
418
+
419
+ ax.set_xticks(x)
420
+ ax.set_xticklabels(df.columns)
421
+ ax.set_xlim(x[0], x[-1])
422
+ ax.legend(loc="upper right")
423
+ ax.grid()
424
+ return ax
425
+
426
+
427
+ def lag_plot(series: Series, lag: int = 1, ax: Axes | None = None, **kwds) -> Axes:
428
+ # workaround because `c='b'` is hardcoded in matplotlib's scatter method
429
+ import matplotlib.pyplot as plt
430
+
431
+ kwds.setdefault("c", plt.rcParams["patch.facecolor"])
432
+
433
+ data = series.values
434
+ y1 = data[:-lag]
435
+ y2 = data[lag:]
436
+ if ax is None:
437
+ ax = plt.gca()
438
+ ax.set_xlabel("y(t)")
439
+ ax.set_ylabel(f"y(t + {lag})")
440
+ ax.scatter(y1, y2, **kwds)
441
+ return ax
442
+
443
+
444
+ def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwds) -> Axes:
445
+ import matplotlib.pyplot as plt
446
+
447
+ n = len(series)
448
+ data = np.asarray(series)
449
+ if ax is None:
450
+ ax = plt.gca()
451
+ ax.set_xlim(1, n)
452
+ ax.set_ylim(-1.0, 1.0)
453
+ mean = np.mean(data)
454
+ c0 = np.sum((data - mean) ** 2) / n
455
+
456
+ def r(h):
457
+ return ((data[: n - h] - mean) * (data[h:] - mean)).sum() / n / c0
458
+
459
+ x = np.arange(n) + 1
460
+ y = [r(loc) for loc in x]
461
+ z95 = 1.959963984540054
462
+ z99 = 2.5758293035489004
463
+ ax.axhline(y=z99 / np.sqrt(n), linestyle="--", color="grey")
464
+ ax.axhline(y=z95 / np.sqrt(n), color="grey")
465
+ ax.axhline(y=0.0, color="black")
466
+ ax.axhline(y=-z95 / np.sqrt(n), color="grey")
467
+ ax.axhline(y=-z99 / np.sqrt(n), linestyle="--", color="grey")
468
+ ax.set_xlabel("Lag")
469
+ ax.set_ylabel("Autocorrelation")
470
+ ax.plot(x, y, **kwds)
471
+ if "label" in kwds:
472
+ ax.legend()
473
+ ax.grid()
474
+ return ax
475
+
476
+
477
+ def unpack_single_str_list(keys):
478
+ # GH 42795
479
+ if isinstance(keys, list) and len(keys) == 1:
480
+ keys = keys[0]
481
+ return keys
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/style.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import (
4
+ Collection,
5
+ Iterator,
6
+ )
7
+ import itertools
8
+ from typing import (
9
+ TYPE_CHECKING,
10
+ cast,
11
+ )
12
+ import warnings
13
+
14
+ import matplotlib as mpl
15
+ import matplotlib.colors
16
+ import numpy as np
17
+
18
+ from pandas._typing import MatplotlibColor as Color
19
+ from pandas.util._exceptions import find_stack_level
20
+
21
+ from pandas.core.dtypes.common import is_list_like
22
+
23
+ import pandas.core.common as com
24
+
25
+ if TYPE_CHECKING:
26
+ from matplotlib.colors import Colormap
27
+
28
+
29
+ def get_standard_colors(
30
+ num_colors: int,
31
+ colormap: Colormap | None = None,
32
+ color_type: str = "default",
33
+ color: dict[str, Color] | Color | Collection[Color] | None = None,
34
+ ):
35
+ """
36
+ Get standard colors based on `colormap`, `color_type` or `color` inputs.
37
+
38
+ Parameters
39
+ ----------
40
+ num_colors : int
41
+ Minimum number of colors to be returned.
42
+ Ignored if `color` is a dictionary.
43
+ colormap : :py:class:`matplotlib.colors.Colormap`, optional
44
+ Matplotlib colormap.
45
+ When provided, the resulting colors will be derived from the colormap.
46
+ color_type : {"default", "random"}, optional
47
+ Type of colors to derive. Used if provided `color` and `colormap` are None.
48
+ Ignored if either `color` or `colormap` are not None.
49
+ color : dict or str or sequence, optional
50
+ Color(s) to be used for deriving sequence of colors.
51
+ Can be either be a dictionary, or a single color (single color string,
52
+ or sequence of floats representing a single color),
53
+ or a sequence of colors.
54
+
55
+ Returns
56
+ -------
57
+ dict or list
58
+ Standard colors. Can either be a mapping if `color` was a dictionary,
59
+ or a list of colors with a length of `num_colors` or more.
60
+
61
+ Warns
62
+ -----
63
+ UserWarning
64
+ If both `colormap` and `color` are provided.
65
+ Parameter `color` will override.
66
+ """
67
+ if isinstance(color, dict):
68
+ return color
69
+
70
+ colors = _derive_colors(
71
+ color=color,
72
+ colormap=colormap,
73
+ color_type=color_type,
74
+ num_colors=num_colors,
75
+ )
76
+
77
+ return list(_cycle_colors(colors, num_colors=num_colors))
78
+
79
+
80
+ def _derive_colors(
81
+ *,
82
+ color: Color | Collection[Color] | None,
83
+ colormap: str | Colormap | None,
84
+ color_type: str,
85
+ num_colors: int,
86
+ ) -> list[Color]:
87
+ """
88
+ Derive colors from either `colormap`, `color_type` or `color` inputs.
89
+
90
+ Get a list of colors either from `colormap`, or from `color`,
91
+ or from `color_type` (if both `colormap` and `color` are None).
92
+
93
+ Parameters
94
+ ----------
95
+ color : str or sequence, optional
96
+ Color(s) to be used for deriving sequence of colors.
97
+ Can be either be a single color (single color string, or sequence of floats
98
+ representing a single color), or a sequence of colors.
99
+ colormap : :py:class:`matplotlib.colors.Colormap`, optional
100
+ Matplotlib colormap.
101
+ When provided, the resulting colors will be derived from the colormap.
102
+ color_type : {"default", "random"}, optional
103
+ Type of colors to derive. Used if provided `color` and `colormap` are None.
104
+ Ignored if either `color` or `colormap`` are not None.
105
+ num_colors : int
106
+ Number of colors to be extracted.
107
+
108
+ Returns
109
+ -------
110
+ list
111
+ List of colors extracted.
112
+
113
+ Warns
114
+ -----
115
+ UserWarning
116
+ If both `colormap` and `color` are provided.
117
+ Parameter `color` will override.
118
+ """
119
+ if color is None and colormap is not None:
120
+ return _get_colors_from_colormap(colormap, num_colors=num_colors)
121
+ elif color is not None:
122
+ if colormap is not None:
123
+ warnings.warn(
124
+ "'color' and 'colormap' cannot be used simultaneously. Using 'color'",
125
+ stacklevel=find_stack_level(),
126
+ )
127
+ return _get_colors_from_color(color)
128
+ else:
129
+ return _get_colors_from_color_type(color_type, num_colors=num_colors)
130
+
131
+
132
+ def _cycle_colors(colors: list[Color], num_colors: int) -> Iterator[Color]:
133
+ """Cycle colors until achieving max of `num_colors` or length of `colors`.
134
+
135
+ Extra colors will be ignored by matplotlib if there are more colors
136
+ than needed and nothing needs to be done here.
137
+ """
138
+ max_colors = max(num_colors, len(colors))
139
+ yield from itertools.islice(itertools.cycle(colors), max_colors)
140
+
141
+
142
+ def _get_colors_from_colormap(
143
+ colormap: str | Colormap,
144
+ num_colors: int,
145
+ ) -> list[Color]:
146
+ """Get colors from colormap."""
147
+ cmap = _get_cmap_instance(colormap)
148
+ return [cmap(num) for num in np.linspace(0, 1, num=num_colors)]
149
+
150
+
151
+ def _get_cmap_instance(colormap: str | Colormap) -> Colormap:
152
+ """Get instance of matplotlib colormap."""
153
+ if isinstance(colormap, str):
154
+ cmap = colormap
155
+ colormap = mpl.colormaps[colormap]
156
+ if colormap is None:
157
+ raise ValueError(f"Colormap {cmap} is not recognized")
158
+ return colormap
159
+
160
+
161
+ def _get_colors_from_color(
162
+ color: Color | Collection[Color],
163
+ ) -> list[Color]:
164
+ """Get colors from user input color."""
165
+ if len(color) == 0:
166
+ raise ValueError(f"Invalid color argument: {color}")
167
+
168
+ if _is_single_color(color):
169
+ color = cast(Color, color)
170
+ return [color]
171
+
172
+ color = cast(Collection[Color], color)
173
+ return list(_gen_list_of_colors_from_iterable(color))
174
+
175
+
176
+ def _is_single_color(color: Color | Collection[Color]) -> bool:
177
+ """Check if `color` is a single color, not a sequence of colors.
178
+
179
+ Single color is of these kinds:
180
+ - Named color "red", "C0", "firebrick"
181
+ - Alias "g"
182
+ - Sequence of floats, such as (0.1, 0.2, 0.3) or (0.1, 0.2, 0.3, 0.4).
183
+
184
+ See Also
185
+ --------
186
+ _is_single_string_color
187
+ """
188
+ if isinstance(color, str) and _is_single_string_color(color):
189
+ # GH #36972
190
+ return True
191
+
192
+ if _is_floats_color(color):
193
+ return True
194
+
195
+ return False
196
+
197
+
198
+ def _gen_list_of_colors_from_iterable(color: Collection[Color]) -> Iterator[Color]:
199
+ """
200
+ Yield colors from string of several letters or from collection of colors.
201
+ """
202
+ for x in color:
203
+ if _is_single_color(x):
204
+ yield x
205
+ else:
206
+ raise ValueError(f"Invalid color {x}")
207
+
208
+
209
+ def _is_floats_color(color: Color | Collection[Color]) -> bool:
210
+ """Check if color comprises a sequence of floats representing color."""
211
+ return bool(
212
+ is_list_like(color)
213
+ and (len(color) == 3 or len(color) == 4)
214
+ and all(isinstance(x, (int, float)) for x in color)
215
+ )
216
+
217
+
218
+ def _get_colors_from_color_type(color_type: str, num_colors: int) -> list[Color]:
219
+ """Get colors from user input color type."""
220
+ if color_type == "default":
221
+ return _get_default_colors(num_colors)
222
+ elif color_type == "random":
223
+ return _get_random_colors(num_colors)
224
+ else:
225
+ raise ValueError("color_type must be either 'default' or 'random'")
226
+
227
+
228
+ def _get_default_colors(num_colors: int) -> list[Color]:
229
+ """Get `num_colors` of default colors from matplotlib rc params."""
230
+ import matplotlib.pyplot as plt
231
+
232
+ colors = [c["color"] for c in plt.rcParams["axes.prop_cycle"]]
233
+ return colors[0:num_colors]
234
+
235
+
236
+ def _get_random_colors(num_colors: int) -> list[Color]:
237
+ """Get `num_colors` of random colors."""
238
+ return [_random_color(num) for num in range(num_colors)]
239
+
240
+
241
+ def _random_color(column: int) -> list[float]:
242
+ """Get a random color represented as a list of length 3"""
243
+ # GH17525 use common._random_state to avoid resetting the seed
244
+ rs = com.random_state(column)
245
+ return rs.rand(3).tolist()
246
+
247
+
248
+ def _is_single_string_color(color: Color) -> bool:
249
+ """Check if `color` is a single string color.
250
+
251
+ Examples of single string colors:
252
+ - 'r'
253
+ - 'g'
254
+ - 'red'
255
+ - 'green'
256
+ - 'C3'
257
+ - 'firebrick'
258
+
259
+ Parameters
260
+ ----------
261
+ color : Color
262
+ Color string or sequence of floats.
263
+
264
+ Returns
265
+ -------
266
+ bool
267
+ True if `color` looks like a valid color.
268
+ False otherwise.
269
+ """
270
+ conv = matplotlib.colors.ColorConverter()
271
+ try:
272
+ # error: Argument 1 to "to_rgba" of "ColorConverter" has incompatible type
273
+ # "str | Sequence[float]"; expected "tuple[float, float, float] | ..."
274
+ conv.to_rgba(color) # type: ignore[arg-type]
275
+ except ValueError:
276
+ return False
277
+ else:
278
+ return True
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/timeseries.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO: Use the fact that axis can have units to simplify the process
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ from typing import (
7
+ TYPE_CHECKING,
8
+ Any,
9
+ cast,
10
+ )
11
+ import warnings
12
+
13
+ import numpy as np
14
+
15
+ from pandas._libs.tslibs import (
16
+ BaseOffset,
17
+ Period,
18
+ to_offset,
19
+ )
20
+ from pandas._libs.tslibs.dtypes import (
21
+ OFFSET_TO_PERIOD_FREQSTR,
22
+ FreqGroup,
23
+ )
24
+
25
+ from pandas.core.dtypes.generic import (
26
+ ABCDatetimeIndex,
27
+ ABCPeriodIndex,
28
+ ABCTimedeltaIndex,
29
+ )
30
+
31
+ from pandas.io.formats.printing import pprint_thing
32
+ from pandas.plotting._matplotlib.converter import (
33
+ TimeSeries_DateFormatter,
34
+ TimeSeries_DateLocator,
35
+ TimeSeries_TimedeltaFormatter,
36
+ )
37
+ from pandas.tseries.frequencies import (
38
+ get_period_alias,
39
+ is_subperiod,
40
+ is_superperiod,
41
+ )
42
+
43
+ if TYPE_CHECKING:
44
+ from datetime import timedelta
45
+
46
+ from matplotlib.axes import Axes
47
+
48
+ from pandas._typing import NDFrameT
49
+
50
+ from pandas import (
51
+ DataFrame,
52
+ DatetimeIndex,
53
+ Index,
54
+ PeriodIndex,
55
+ Series,
56
+ )
57
+
58
+ # ---------------------------------------------------------------------
59
+ # Plotting functions and monkey patches
60
+
61
+
62
+ def maybe_resample(series: Series, ax: Axes, kwargs: dict[str, Any]):
63
+ # resample against axes freq if necessary
64
+
65
+ if "how" in kwargs:
66
+ raise ValueError(
67
+ "'how' is not a valid keyword for plotting functions. If plotting "
68
+ "multiple objects on shared axes, resample manually first."
69
+ )
70
+
71
+ freq, ax_freq = _get_freq(ax, series)
72
+
73
+ if freq is None: # pragma: no cover
74
+ raise ValueError("Cannot use dynamic axis without frequency info")
75
+
76
+ # Convert DatetimeIndex to PeriodIndex
77
+ if isinstance(series.index, ABCDatetimeIndex):
78
+ series = series.to_period(freq=freq)
79
+
80
+ if ax_freq is not None and freq != ax_freq:
81
+ if is_superperiod(freq, ax_freq): # upsample input
82
+ series = series.copy()
83
+ # error: "Index" has no attribute "asfreq"
84
+ series.index = series.index.asfreq( # type: ignore[attr-defined]
85
+ ax_freq, how="s"
86
+ )
87
+ freq = ax_freq
88
+ elif _is_sup(freq, ax_freq): # one is weekly
89
+ # Resampling with PeriodDtype is deprecated, so we convert to
90
+ # DatetimeIndex, resample, then convert back.
91
+ ser_ts = series.to_timestamp()
92
+ ser_d = ser_ts.resample("D").last().dropna()
93
+ ser_freq = ser_d.resample(ax_freq).last().dropna()
94
+ series = ser_freq.to_period(ax_freq)
95
+ freq = ax_freq
96
+ elif is_subperiod(freq, ax_freq) or _is_sub(freq, ax_freq):
97
+ _upsample_others(ax, freq, kwargs)
98
+ else: # pragma: no cover
99
+ raise ValueError("Incompatible frequency conversion")
100
+ return freq, series
101
+
102
+
103
+ def _is_sub(f1: str, f2: str) -> bool:
104
+ return (f1.startswith("W") and is_subperiod("D", f2)) or (
105
+ f2.startswith("W") and is_subperiod(f1, "D")
106
+ )
107
+
108
+
109
+ def _is_sup(f1: str, f2: str) -> bool:
110
+ return (f1.startswith("W") and is_superperiod("D", f2)) or (
111
+ f2.startswith("W") and is_superperiod(f1, "D")
112
+ )
113
+
114
+
115
+ def _upsample_others(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None:
116
+ legend = ax.get_legend()
117
+ lines, labels = _replot_ax(ax, freq)
118
+ _replot_ax(ax, freq)
119
+
120
+ other_ax = None
121
+ if hasattr(ax, "left_ax"):
122
+ other_ax = ax.left_ax
123
+ if hasattr(ax, "right_ax"):
124
+ other_ax = ax.right_ax
125
+
126
+ if other_ax is not None:
127
+ rlines, rlabels = _replot_ax(other_ax, freq)
128
+ lines.extend(rlines)
129
+ labels.extend(rlabels)
130
+
131
+ if legend is not None and kwargs.get("legend", True) and len(lines) > 0:
132
+ title: str | None = legend.get_title().get_text()
133
+ if title == "None":
134
+ title = None
135
+ ax.legend(lines, labels, loc="best", title=title)
136
+
137
+
138
+ def _replot_ax(ax: Axes, freq: BaseOffset):
139
+ data = getattr(ax, "_plot_data", None)
140
+
141
+ # clear current axes and data
142
+ # TODO #54485
143
+ ax._plot_data = [] # type: ignore[attr-defined]
144
+ ax.clear()
145
+
146
+ decorate_axes(ax, freq)
147
+
148
+ lines = []
149
+ labels = []
150
+ if data is not None:
151
+ for series, plotf, kwds in data:
152
+ series = series.copy()
153
+ idx = series.index.asfreq(freq, how="S")
154
+ series.index = idx
155
+ # TODO #54485
156
+ ax._plot_data.append((series, plotf, kwds)) # type: ignore[attr-defined]
157
+
158
+ # for tsplot
159
+ if isinstance(plotf, str):
160
+ from pandas.plotting._matplotlib import PLOT_CLASSES
161
+
162
+ plotf = PLOT_CLASSES[plotf]._plot
163
+
164
+ lines.append(plotf(ax, series.index._mpl_repr(), series.values, **kwds)[0])
165
+ labels.append(pprint_thing(series.name))
166
+
167
+ return lines, labels
168
+
169
+
170
+ def decorate_axes(ax: Axes, freq: BaseOffset) -> None:
171
+ """Initialize axes for time-series plotting"""
172
+ if not hasattr(ax, "_plot_data"):
173
+ # TODO #54485
174
+ ax._plot_data = [] # type: ignore[attr-defined]
175
+
176
+ # TODO #54485
177
+ ax.freq = freq # type: ignore[attr-defined]
178
+ xaxis = ax.get_xaxis()
179
+ # TODO #54485
180
+ xaxis.freq = freq # type: ignore[attr-defined]
181
+
182
+
183
+ def _get_ax_freq(ax: Axes):
184
+ """
185
+ Get the freq attribute of the ax object if set.
186
+ Also checks shared axes (eg when using secondary yaxis, sharex=True
187
+ or twinx)
188
+ """
189
+ ax_freq = getattr(ax, "freq", None)
190
+ if ax_freq is None:
191
+ # check for left/right ax in case of secondary yaxis
192
+ if hasattr(ax, "left_ax"):
193
+ ax_freq = getattr(ax.left_ax, "freq", None)
194
+ elif hasattr(ax, "right_ax"):
195
+ ax_freq = getattr(ax.right_ax, "freq", None)
196
+ if ax_freq is None:
197
+ # check if a shared ax (sharex/twinx) has already freq set
198
+ shared_axes = ax.get_shared_x_axes().get_siblings(ax)
199
+ if len(shared_axes) > 1:
200
+ for shared_ax in shared_axes:
201
+ ax_freq = getattr(shared_ax, "freq", None)
202
+ if ax_freq is not None:
203
+ break
204
+ return ax_freq
205
+
206
+
207
+ def _get_period_alias(freq: timedelta | BaseOffset | str) -> str | None:
208
+ if isinstance(freq, BaseOffset):
209
+ freqstr = freq.name
210
+ else:
211
+ freqstr = to_offset(freq, is_period=True).rule_code
212
+
213
+ return get_period_alias(freqstr)
214
+
215
+
216
+ def _get_freq(ax: Axes, series: Series):
217
+ # get frequency from data
218
+ freq = getattr(series.index, "freq", None)
219
+ if freq is None:
220
+ freq = getattr(series.index, "inferred_freq", None)
221
+ freq = to_offset(freq, is_period=True)
222
+
223
+ ax_freq = _get_ax_freq(ax)
224
+
225
+ # use axes freq if no data freq
226
+ if freq is None:
227
+ freq = ax_freq
228
+
229
+ # get the period frequency
230
+ freq = _get_period_alias(freq)
231
+ return freq, ax_freq
232
+
233
+
234
+ def use_dynamic_x(ax: Axes, data: DataFrame | Series) -> bool:
235
+ freq = _get_index_freq(data.index)
236
+ ax_freq = _get_ax_freq(ax)
237
+
238
+ if freq is None: # convert irregular if axes has freq info
239
+ freq = ax_freq
240
+ # do not use tsplot if irregular was plotted first
241
+ elif (ax_freq is None) and (len(ax.get_lines()) > 0):
242
+ return False
243
+
244
+ if freq is None:
245
+ return False
246
+
247
+ freq_str = _get_period_alias(freq)
248
+
249
+ if freq_str is None:
250
+ return False
251
+
252
+ # FIXME: hack this for 0.10.1, creating more technical debt...sigh
253
+ if isinstance(data.index, ABCDatetimeIndex):
254
+ # error: "BaseOffset" has no attribute "_period_dtype_code"
255
+ freq_str = OFFSET_TO_PERIOD_FREQSTR.get(freq_str, freq_str)
256
+ base = to_offset(
257
+ freq_str, is_period=True
258
+ )._period_dtype_code # type: ignore[attr-defined]
259
+ x = data.index
260
+ if base <= FreqGroup.FR_DAY.value:
261
+ return x[:1].is_normalized
262
+ period = Period(x[0], freq_str)
263
+ assert isinstance(period, Period)
264
+ return period.to_timestamp().tz_localize(x.tz) == x[0]
265
+ return True
266
+
267
+
268
+ def _get_index_freq(index: Index) -> BaseOffset | None:
269
+ freq = getattr(index, "freq", None)
270
+ if freq is None:
271
+ freq = getattr(index, "inferred_freq", None)
272
+ if freq == "B":
273
+ # error: "Index" has no attribute "dayofweek"
274
+ weekdays = np.unique(index.dayofweek) # type: ignore[attr-defined]
275
+ if (5 in weekdays) or (6 in weekdays):
276
+ freq = None
277
+
278
+ freq = to_offset(freq)
279
+ return freq
280
+
281
+
282
+ def maybe_convert_index(ax: Axes, data: NDFrameT) -> NDFrameT:
283
+ # tsplot converts automatically, but don't want to convert index
284
+ # over and over for DataFrames
285
+ if isinstance(data.index, (ABCDatetimeIndex, ABCPeriodIndex)):
286
+ freq: str | BaseOffset | None = data.index.freq
287
+
288
+ if freq is None:
289
+ # We only get here for DatetimeIndex
290
+ data.index = cast("DatetimeIndex", data.index)
291
+ freq = data.index.inferred_freq
292
+ freq = to_offset(freq)
293
+
294
+ if freq is None:
295
+ freq = _get_ax_freq(ax)
296
+
297
+ if freq is None:
298
+ raise ValueError("Could not get frequency alias for plotting")
299
+
300
+ freq_str = _get_period_alias(freq)
301
+
302
+ with warnings.catch_warnings():
303
+ # suppress Period[B] deprecation warning
304
+ # TODO: need to find an alternative to this before the deprecation
305
+ # is enforced!
306
+ warnings.filterwarnings(
307
+ "ignore",
308
+ r"PeriodDtype\[B\] is deprecated",
309
+ category=FutureWarning,
310
+ )
311
+
312
+ if isinstance(data.index, ABCDatetimeIndex):
313
+ data = data.tz_localize(None).to_period(freq=freq_str)
314
+ elif isinstance(data.index, ABCPeriodIndex):
315
+ data.index = data.index.asfreq(freq=freq_str)
316
+ return data
317
+
318
+
319
+ # Patch methods for subplot.
320
+
321
+
322
+ def _format_coord(freq, t, y) -> str:
323
+ time_period = Period(ordinal=int(t), freq=freq)
324
+ return f"t = {time_period} y = {y:8f}"
325
+
326
+
327
+ def format_dateaxis(
328
+ subplot, freq: BaseOffset, index: DatetimeIndex | PeriodIndex
329
+ ) -> None:
330
+ """
331
+ Pretty-formats the date axis (x-axis).
332
+
333
+ Major and minor ticks are automatically set for the frequency of the
334
+ current underlying series. As the dynamic mode is activated by
335
+ default, changing the limits of the x axis will intelligently change
336
+ the positions of the ticks.
337
+ """
338
+ from matplotlib import pylab
339
+
340
+ # handle index specific formatting
341
+ # Note: DatetimeIndex does not use this
342
+ # interface. DatetimeIndex uses matplotlib.date directly
343
+ if isinstance(index, ABCPeriodIndex):
344
+ majlocator = TimeSeries_DateLocator(
345
+ freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot
346
+ )
347
+ minlocator = TimeSeries_DateLocator(
348
+ freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot
349
+ )
350
+ subplot.xaxis.set_major_locator(majlocator)
351
+ subplot.xaxis.set_minor_locator(minlocator)
352
+
353
+ majformatter = TimeSeries_DateFormatter(
354
+ freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot
355
+ )
356
+ minformatter = TimeSeries_DateFormatter(
357
+ freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot
358
+ )
359
+ subplot.xaxis.set_major_formatter(majformatter)
360
+ subplot.xaxis.set_minor_formatter(minformatter)
361
+
362
+ # x and y coord info
363
+ subplot.format_coord = functools.partial(_format_coord, freq)
364
+
365
+ elif isinstance(index, ABCTimedeltaIndex):
366
+ subplot.xaxis.set_major_formatter(TimeSeries_TimedeltaFormatter())
367
+ else:
368
+ raise TypeError("index type not supported")
369
+
370
+ pylab.draw_if_interactive()
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_matplotlib/tools.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # being a bit too dynamic
2
+ from __future__ import annotations
3
+
4
+ from math import ceil
5
+ from typing import TYPE_CHECKING
6
+ import warnings
7
+
8
+ from matplotlib import ticker
9
+ import matplotlib.table
10
+ import numpy as np
11
+
12
+ from pandas.util._exceptions import find_stack_level
13
+
14
+ from pandas.core.dtypes.common import is_list_like
15
+ from pandas.core.dtypes.generic import (
16
+ ABCDataFrame,
17
+ ABCIndex,
18
+ ABCSeries,
19
+ )
20
+
21
+ if TYPE_CHECKING:
22
+ from collections.abc import (
23
+ Iterable,
24
+ Sequence,
25
+ )
26
+
27
+ from matplotlib.axes import Axes
28
+ from matplotlib.axis import Axis
29
+ from matplotlib.figure import Figure
30
+ from matplotlib.lines import Line2D
31
+ from matplotlib.table import Table
32
+
33
+ from pandas import (
34
+ DataFrame,
35
+ Series,
36
+ )
37
+
38
+
39
+ def do_adjust_figure(fig: Figure) -> bool:
40
+ """Whether fig has constrained_layout enabled."""
41
+ if not hasattr(fig, "get_constrained_layout"):
42
+ return False
43
+ return not fig.get_constrained_layout()
44
+
45
+
46
+ def maybe_adjust_figure(fig: Figure, *args, **kwargs) -> None:
47
+ """Call fig.subplots_adjust unless fig has constrained_layout enabled."""
48
+ if do_adjust_figure(fig):
49
+ fig.subplots_adjust(*args, **kwargs)
50
+
51
+
52
+ def format_date_labels(ax: Axes, rot) -> None:
53
+ # mini version of autofmt_xdate
54
+ for label in ax.get_xticklabels():
55
+ label.set_horizontalalignment("right")
56
+ label.set_rotation(rot)
57
+ fig = ax.get_figure()
58
+ if fig is not None:
59
+ # should always be a Figure but can technically be None
60
+ maybe_adjust_figure(fig, bottom=0.2)
61
+
62
+
63
+ def table(
64
+ ax, data: DataFrame | Series, rowLabels=None, colLabels=None, **kwargs
65
+ ) -> Table:
66
+ if isinstance(data, ABCSeries):
67
+ data = data.to_frame()
68
+ elif isinstance(data, ABCDataFrame):
69
+ pass
70
+ else:
71
+ raise ValueError("Input data must be DataFrame or Series")
72
+
73
+ if rowLabels is None:
74
+ rowLabels = data.index
75
+
76
+ if colLabels is None:
77
+ colLabels = data.columns
78
+
79
+ cellText = data.values
80
+
81
+ # error: Argument "cellText" to "table" has incompatible type "ndarray[Any,
82
+ # Any]"; expected "Sequence[Sequence[str]] | None"
83
+ return matplotlib.table.table(
84
+ ax,
85
+ cellText=cellText, # type: ignore[arg-type]
86
+ rowLabels=rowLabels,
87
+ colLabels=colLabels,
88
+ **kwargs,
89
+ )
90
+
91
+
92
+ def _get_layout(
93
+ nplots: int,
94
+ layout: tuple[int, int] | None = None,
95
+ layout_type: str = "box",
96
+ ) -> tuple[int, int]:
97
+ if layout is not None:
98
+ if not isinstance(layout, (tuple, list)) or len(layout) != 2:
99
+ raise ValueError("Layout must be a tuple of (rows, columns)")
100
+
101
+ nrows, ncols = layout
102
+
103
+ if nrows == -1 and ncols > 0:
104
+ layout = nrows, ncols = (ceil(nplots / ncols), ncols)
105
+ elif ncols == -1 and nrows > 0:
106
+ layout = nrows, ncols = (nrows, ceil(nplots / nrows))
107
+ elif ncols <= 0 and nrows <= 0:
108
+ msg = "At least one dimension of layout must be positive"
109
+ raise ValueError(msg)
110
+
111
+ if nrows * ncols < nplots:
112
+ raise ValueError(
113
+ f"Layout of {nrows}x{ncols} must be larger than required size {nplots}"
114
+ )
115
+
116
+ return layout
117
+
118
+ if layout_type == "single":
119
+ return (1, 1)
120
+ elif layout_type == "horizontal":
121
+ return (1, nplots)
122
+ elif layout_type == "vertical":
123
+ return (nplots, 1)
124
+
125
+ layouts = {1: (1, 1), 2: (1, 2), 3: (2, 2), 4: (2, 2)}
126
+ try:
127
+ return layouts[nplots]
128
+ except KeyError:
129
+ k = 1
130
+ while k**2 < nplots:
131
+ k += 1
132
+
133
+ if (k - 1) * k >= nplots:
134
+ return k, (k - 1)
135
+ else:
136
+ return k, k
137
+
138
+
139
+ # copied from matplotlib/pyplot.py and modified for pandas.plotting
140
+
141
+
142
+ def create_subplots(
143
+ naxes: int,
144
+ sharex: bool = False,
145
+ sharey: bool = False,
146
+ squeeze: bool = True,
147
+ subplot_kw=None,
148
+ ax=None,
149
+ layout=None,
150
+ layout_type: str = "box",
151
+ **fig_kw,
152
+ ):
153
+ """
154
+ Create a figure with a set of subplots already made.
155
+
156
+ This utility wrapper makes it convenient to create common layouts of
157
+ subplots, including the enclosing figure object, in a single call.
158
+
159
+ Parameters
160
+ ----------
161
+ naxes : int
162
+ Number of required axes. Exceeded axes are set invisible. Default is
163
+ nrows * ncols.
164
+
165
+ sharex : bool
166
+ If True, the X axis will be shared amongst all subplots.
167
+
168
+ sharey : bool
169
+ If True, the Y axis will be shared amongst all subplots.
170
+
171
+ squeeze : bool
172
+
173
+ If True, extra dimensions are squeezed out from the returned axis object:
174
+ - if only one subplot is constructed (nrows=ncols=1), the resulting
175
+ single Axis object is returned as a scalar.
176
+ - for Nx1 or 1xN subplots, the returned object is a 1-d numpy object
177
+ array of Axis objects are returned as numpy 1-d arrays.
178
+ - for NxM subplots with N>1 and M>1 are returned as a 2d array.
179
+
180
+ If False, no squeezing is done: the returned axis object is always
181
+ a 2-d array containing Axis instances, even if it ends up being 1x1.
182
+
183
+ subplot_kw : dict
184
+ Dict with keywords passed to the add_subplot() call used to create each
185
+ subplots.
186
+
187
+ ax : Matplotlib axis object, optional
188
+
189
+ layout : tuple
190
+ Number of rows and columns of the subplot grid.
191
+ If not specified, calculated from naxes and layout_type
192
+
193
+ layout_type : {'box', 'horizontal', 'vertical'}, default 'box'
194
+ Specify how to layout the subplot grid.
195
+
196
+ fig_kw : Other keyword arguments to be passed to the figure() call.
197
+ Note that all keywords not recognized above will be
198
+ automatically included here.
199
+
200
+ Returns
201
+ -------
202
+ fig, ax : tuple
203
+ - fig is the Matplotlib Figure object
204
+ - ax can be either a single axis object or an array of axis objects if
205
+ more than one subplot was created. The dimensions of the resulting array
206
+ can be controlled with the squeeze keyword, see above.
207
+
208
+ Examples
209
+ --------
210
+ x = np.linspace(0, 2*np.pi, 400)
211
+ y = np.sin(x**2)
212
+
213
+ # Just a figure and one subplot
214
+ f, ax = plt.subplots()
215
+ ax.plot(x, y)
216
+ ax.set_title('Simple plot')
217
+
218
+ # Two subplots, unpack the output array immediately
219
+ f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
220
+ ax1.plot(x, y)
221
+ ax1.set_title('Sharing Y axis')
222
+ ax2.scatter(x, y)
223
+
224
+ # Four polar axes
225
+ plt.subplots(2, 2, subplot_kw=dict(polar=True))
226
+ """
227
+ import matplotlib.pyplot as plt
228
+
229
+ if subplot_kw is None:
230
+ subplot_kw = {}
231
+
232
+ if ax is None:
233
+ fig = plt.figure(**fig_kw)
234
+ else:
235
+ if is_list_like(ax):
236
+ if squeeze:
237
+ ax = flatten_axes(ax)
238
+ if layout is not None:
239
+ warnings.warn(
240
+ "When passing multiple axes, layout keyword is ignored.",
241
+ UserWarning,
242
+ stacklevel=find_stack_level(),
243
+ )
244
+ if sharex or sharey:
245
+ warnings.warn(
246
+ "When passing multiple axes, sharex and sharey "
247
+ "are ignored. These settings must be specified when creating axes.",
248
+ UserWarning,
249
+ stacklevel=find_stack_level(),
250
+ )
251
+ if ax.size == naxes:
252
+ fig = ax.flat[0].get_figure()
253
+ return fig, ax
254
+ else:
255
+ raise ValueError(
256
+ f"The number of passed axes must be {naxes}, the "
257
+ "same as the output plot"
258
+ )
259
+
260
+ fig = ax.get_figure()
261
+ # if ax is passed and a number of subplots is 1, return ax as it is
262
+ if naxes == 1:
263
+ if squeeze:
264
+ return fig, ax
265
+ else:
266
+ return fig, flatten_axes(ax)
267
+ else:
268
+ warnings.warn(
269
+ "To output multiple subplots, the figure containing "
270
+ "the passed axes is being cleared.",
271
+ UserWarning,
272
+ stacklevel=find_stack_level(),
273
+ )
274
+ fig.clear()
275
+
276
+ nrows, ncols = _get_layout(naxes, layout=layout, layout_type=layout_type)
277
+ nplots = nrows * ncols
278
+
279
+ # Create empty object array to hold all axes. It's easiest to make it 1-d
280
+ # so we can just append subplots upon creation, and then
281
+ axarr = np.empty(nplots, dtype=object)
282
+
283
+ # Create first subplot separately, so we can share it if requested
284
+ ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)
285
+
286
+ if sharex:
287
+ subplot_kw["sharex"] = ax0
288
+ if sharey:
289
+ subplot_kw["sharey"] = ax0
290
+ axarr[0] = ax0
291
+
292
+ # Note off-by-one counting because add_subplot uses the MATLAB 1-based
293
+ # convention.
294
+ for i in range(1, nplots):
295
+ kwds = subplot_kw.copy()
296
+ # Set sharex and sharey to None for blank/dummy axes, these can
297
+ # interfere with proper axis limits on the visible axes if
298
+ # they share axes e.g. issue #7528
299
+ if i >= naxes:
300
+ kwds["sharex"] = None
301
+ kwds["sharey"] = None
302
+ ax = fig.add_subplot(nrows, ncols, i + 1, **kwds)
303
+ axarr[i] = ax
304
+
305
+ if naxes != nplots:
306
+ for ax in axarr[naxes:]:
307
+ ax.set_visible(False)
308
+
309
+ handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
310
+
311
+ if squeeze:
312
+ # Reshape the array to have the final desired dimension (nrow,ncol),
313
+ # though discarding unneeded dimensions that equal 1. If we only have
314
+ # one subplot, just return it instead of a 1-element array.
315
+ if nplots == 1:
316
+ axes = axarr[0]
317
+ else:
318
+ axes = axarr.reshape(nrows, ncols).squeeze()
319
+ else:
320
+ # returned axis array will be always 2-d, even if nrows=ncols=1
321
+ axes = axarr.reshape(nrows, ncols)
322
+
323
+ return fig, axes
324
+
325
+
326
+ def _remove_labels_from_axis(axis: Axis) -> None:
327
+ for t in axis.get_majorticklabels():
328
+ t.set_visible(False)
329
+
330
+ # set_visible will not be effective if
331
+ # minor axis has NullLocator and NullFormatter (default)
332
+ if isinstance(axis.get_minor_locator(), ticker.NullLocator):
333
+ axis.set_minor_locator(ticker.AutoLocator())
334
+ if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
335
+ axis.set_minor_formatter(ticker.FormatStrFormatter(""))
336
+ for t in axis.get_minorticklabels():
337
+ t.set_visible(False)
338
+
339
+ axis.get_label().set_visible(False)
340
+
341
+
342
+ def _has_externally_shared_axis(ax1: Axes, compare_axis: str) -> bool:
343
+ """
344
+ Return whether an axis is externally shared.
345
+
346
+ Parameters
347
+ ----------
348
+ ax1 : matplotlib.axes.Axes
349
+ Axis to query.
350
+ compare_axis : str
351
+ `"x"` or `"y"` according to whether the X-axis or Y-axis is being
352
+ compared.
353
+
354
+ Returns
355
+ -------
356
+ bool
357
+ `True` if the axis is externally shared. Otherwise `False`.
358
+
359
+ Notes
360
+ -----
361
+ If two axes with different positions are sharing an axis, they can be
362
+ referred to as *externally* sharing the common axis.
363
+
364
+ If two axes sharing an axis also have the same position, they can be
365
+ referred to as *internally* sharing the common axis (a.k.a twinning).
366
+
367
+ _handle_shared_axes() is only interested in axes externally sharing an
368
+ axis, regardless of whether either of the axes is also internally sharing
369
+ with a third axis.
370
+ """
371
+ if compare_axis == "x":
372
+ axes = ax1.get_shared_x_axes()
373
+ elif compare_axis == "y":
374
+ axes = ax1.get_shared_y_axes()
375
+ else:
376
+ raise ValueError(
377
+ "_has_externally_shared_axis() needs 'x' or 'y' as a second parameter"
378
+ )
379
+
380
+ axes_siblings = axes.get_siblings(ax1)
381
+
382
+ # Retain ax1 and any of its siblings which aren't in the same position as it
383
+ ax1_points = ax1.get_position().get_points()
384
+
385
+ for ax2 in axes_siblings:
386
+ if not np.array_equal(ax1_points, ax2.get_position().get_points()):
387
+ return True
388
+
389
+ return False
390
+
391
+
392
+ def handle_shared_axes(
393
+ axarr: Iterable[Axes],
394
+ nplots: int,
395
+ naxes: int,
396
+ nrows: int,
397
+ ncols: int,
398
+ sharex: bool,
399
+ sharey: bool,
400
+ ) -> None:
401
+ if nplots > 1:
402
+ row_num = lambda x: x.get_subplotspec().rowspan.start
403
+ col_num = lambda x: x.get_subplotspec().colspan.start
404
+
405
+ is_first_col = lambda x: x.get_subplotspec().is_first_col()
406
+
407
+ if nrows > 1:
408
+ try:
409
+ # first find out the ax layout,
410
+ # so that we can correctly handle 'gaps"
411
+ layout = np.zeros((nrows + 1, ncols + 1), dtype=np.bool_)
412
+ for ax in axarr:
413
+ layout[row_num(ax), col_num(ax)] = ax.get_visible()
414
+
415
+ for ax in axarr:
416
+ # only the last row of subplots should get x labels -> all
417
+ # other off layout handles the case that the subplot is
418
+ # the last in the column, because below is no subplot/gap.
419
+ if not layout[row_num(ax) + 1, col_num(ax)]:
420
+ continue
421
+ if sharex or _has_externally_shared_axis(ax, "x"):
422
+ _remove_labels_from_axis(ax.xaxis)
423
+
424
+ except IndexError:
425
+ # if gridspec is used, ax.rowNum and ax.colNum may different
426
+ # from layout shape. in this case, use last_row logic
427
+ is_last_row = lambda x: x.get_subplotspec().is_last_row()
428
+ for ax in axarr:
429
+ if is_last_row(ax):
430
+ continue
431
+ if sharex or _has_externally_shared_axis(ax, "x"):
432
+ _remove_labels_from_axis(ax.xaxis)
433
+
434
+ if ncols > 1:
435
+ for ax in axarr:
436
+ # only the first column should get y labels -> set all other to
437
+ # off as we only have labels in the first column and we always
438
+ # have a subplot there, we can skip the layout test
439
+ if is_first_col(ax):
440
+ continue
441
+ if sharey or _has_externally_shared_axis(ax, "y"):
442
+ _remove_labels_from_axis(ax.yaxis)
443
+
444
+
445
+ def flatten_axes(axes: Axes | Sequence[Axes]) -> np.ndarray:
446
+ if not is_list_like(axes):
447
+ return np.array([axes])
448
+ elif isinstance(axes, (np.ndarray, ABCIndex)):
449
+ return np.asarray(axes).ravel()
450
+ return np.array(axes)
451
+
452
+
453
+ def set_ticks_props(
454
+ axes: Axes | Sequence[Axes],
455
+ xlabelsize: int | None = None,
456
+ xrot=None,
457
+ ylabelsize: int | None = None,
458
+ yrot=None,
459
+ ):
460
+ import matplotlib.pyplot as plt
461
+
462
+ for ax in flatten_axes(axes):
463
+ if xlabelsize is not None:
464
+ plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)
465
+ if xrot is not None:
466
+ plt.setp(ax.get_xticklabels(), rotation=xrot)
467
+ if ylabelsize is not None:
468
+ plt.setp(ax.get_yticklabels(), fontsize=ylabelsize)
469
+ if yrot is not None:
470
+ plt.setp(ax.get_yticklabels(), rotation=yrot)
471
+ return axes
472
+
473
+
474
+ def get_all_lines(ax: Axes) -> list[Line2D]:
475
+ lines = ax.get_lines()
476
+
477
+ if hasattr(ax, "right_ax"):
478
+ lines += ax.right_ax.get_lines()
479
+
480
+ if hasattr(ax, "left_ax"):
481
+ lines += ax.left_ax.get_lines()
482
+
483
+ return lines
484
+
485
+
486
+ def get_xlim(lines: Iterable[Line2D]) -> tuple[float, float]:
487
+ left, right = np.inf, -np.inf
488
+ for line in lines:
489
+ x = line.get_xdata(orig=False)
490
+ left = min(np.nanmin(x), left)
491
+ right = max(np.nanmax(x), right)
492
+ return left, right
evalkit_eagle/lib/python3.10/site-packages/pandas/plotting/_misc.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from contextlib import contextmanager
4
+ from typing import (
5
+ TYPE_CHECKING,
6
+ Any,
7
+ )
8
+
9
+ from pandas.plotting._core import _get_plot_backend
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import (
13
+ Generator,
14
+ Mapping,
15
+ )
16
+
17
+ from matplotlib.axes import Axes
18
+ from matplotlib.colors import Colormap
19
+ from matplotlib.figure import Figure
20
+ from matplotlib.table import Table
21
+ import numpy as np
22
+
23
+ from pandas import (
24
+ DataFrame,
25
+ Series,
26
+ )
27
+
28
+
29
+ def table(ax: Axes, data: DataFrame | Series, **kwargs) -> Table:
30
+ """
31
+ Helper function to convert DataFrame and Series to matplotlib.table.
32
+
33
+ Parameters
34
+ ----------
35
+ ax : Matplotlib axes object
36
+ data : DataFrame or Series
37
+ Data for table contents.
38
+ **kwargs
39
+ Keyword arguments to be passed to matplotlib.table.table.
40
+ If `rowLabels` or `colLabels` is not specified, data index or column
41
+ name will be used.
42
+
43
+ Returns
44
+ -------
45
+ matplotlib table object
46
+
47
+ Examples
48
+ --------
49
+
50
+ .. plot::
51
+ :context: close-figs
52
+
53
+ >>> import matplotlib.pyplot as plt
54
+ >>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
55
+ >>> fix, ax = plt.subplots()
56
+ >>> ax.axis('off')
57
+ (0.0, 1.0, 0.0, 1.0)
58
+ >>> table = pd.plotting.table(ax, df, loc='center',
59
+ ... cellLoc='center', colWidths=list([.2, .2]))
60
+ """
61
+ plot_backend = _get_plot_backend("matplotlib")
62
+ return plot_backend.table(
63
+ ax=ax, data=data, rowLabels=None, colLabels=None, **kwargs
64
+ )
65
+
66
+
67
+ def register() -> None:
68
+ """
69
+ Register pandas formatters and converters with matplotlib.
70
+
71
+ This function modifies the global ``matplotlib.units.registry``
72
+ dictionary. pandas adds custom converters for
73
+
74
+ * pd.Timestamp
75
+ * pd.Period
76
+ * np.datetime64
77
+ * datetime.datetime
78
+ * datetime.date
79
+ * datetime.time
80
+
81
+ See Also
82
+ --------
83
+ deregister_matplotlib_converters : Remove pandas formatters and converters.
84
+
85
+ Examples
86
+ --------
87
+ .. plot::
88
+ :context: close-figs
89
+
90
+ The following line is done automatically by pandas so
91
+ the plot can be rendered:
92
+
93
+ >>> pd.plotting.register_matplotlib_converters()
94
+
95
+ >>> df = pd.DataFrame({'ts': pd.period_range('2020', periods=2, freq='M'),
96
+ ... 'y': [1, 2]
97
+ ... })
98
+ >>> plot = df.plot.line(x='ts', y='y')
99
+
100
+ Unsetting the register manually an error will be raised:
101
+
102
+ >>> pd.set_option("plotting.matplotlib.register_converters",
103
+ ... False) # doctest: +SKIP
104
+ >>> df.plot.line(x='ts', y='y') # doctest: +SKIP
105
+ Traceback (most recent call last):
106
+ TypeError: float() argument must be a string or a real number, not 'Period'
107
+ """
108
+ plot_backend = _get_plot_backend("matplotlib")
109
+ plot_backend.register()
110
+
111
+
112
+ def deregister() -> None:
113
+ """
114
+ Remove pandas formatters and converters.
115
+
116
+ Removes the custom converters added by :func:`register`. This
117
+ attempts to set the state of the registry back to the state before
118
+ pandas registered its own units. Converters for pandas' own types like
119
+ Timestamp and Period are removed completely. Converters for types
120
+ pandas overwrites, like ``datetime.datetime``, are restored to their
121
+ original value.
122
+
123
+ See Also
124
+ --------
125
+ register_matplotlib_converters : Register pandas formatters and converters
126
+ with matplotlib.
127
+
128
+ Examples
129
+ --------
130
+ .. plot::
131
+ :context: close-figs
132
+
133
+ The following line is done automatically by pandas so
134
+ the plot can be rendered:
135
+
136
+ >>> pd.plotting.register_matplotlib_converters()
137
+
138
+ >>> df = pd.DataFrame({'ts': pd.period_range('2020', periods=2, freq='M'),
139
+ ... 'y': [1, 2]
140
+ ... })
141
+ >>> plot = df.plot.line(x='ts', y='y')
142
+
143
+ Unsetting the register manually an error will be raised:
144
+
145
+ >>> pd.set_option("plotting.matplotlib.register_converters",
146
+ ... False) # doctest: +SKIP
147
+ >>> df.plot.line(x='ts', y='y') # doctest: +SKIP
148
+ Traceback (most recent call last):
149
+ TypeError: float() argument must be a string or a real number, not 'Period'
150
+ """
151
+ plot_backend = _get_plot_backend("matplotlib")
152
+ plot_backend.deregister()
153
+
154
+
155
+ def scatter_matrix(
156
+ frame: DataFrame,
157
+ alpha: float = 0.5,
158
+ figsize: tuple[float, float] | None = None,
159
+ ax: Axes | None = None,
160
+ grid: bool = False,
161
+ diagonal: str = "hist",
162
+ marker: str = ".",
163
+ density_kwds: Mapping[str, Any] | None = None,
164
+ hist_kwds: Mapping[str, Any] | None = None,
165
+ range_padding: float = 0.05,
166
+ **kwargs,
167
+ ) -> np.ndarray:
168
+ """
169
+ Draw a matrix of scatter plots.
170
+
171
+ Parameters
172
+ ----------
173
+ frame : DataFrame
174
+ alpha : float, optional
175
+ Amount of transparency applied.
176
+ figsize : (float,float), optional
177
+ A tuple (width, height) in inches.
178
+ ax : Matplotlib axis object, optional
179
+ grid : bool, optional
180
+ Setting this to True will show the grid.
181
+ diagonal : {'hist', 'kde'}
182
+ Pick between 'kde' and 'hist' for either Kernel Density Estimation or
183
+ Histogram plot in the diagonal.
184
+ marker : str, optional
185
+ Matplotlib marker type, default '.'.
186
+ density_kwds : keywords
187
+ Keyword arguments to be passed to kernel density estimate plot.
188
+ hist_kwds : keywords
189
+ Keyword arguments to be passed to hist function.
190
+ range_padding : float, default 0.05
191
+ Relative extension of axis range in x and y with respect to
192
+ (x_max - x_min) or (y_max - y_min).
193
+ **kwargs
194
+ Keyword arguments to be passed to scatter function.
195
+
196
+ Returns
197
+ -------
198
+ numpy.ndarray
199
+ A matrix of scatter plots.
200
+
201
+ Examples
202
+ --------
203
+
204
+ .. plot::
205
+ :context: close-figs
206
+
207
+ >>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
208
+ >>> pd.plotting.scatter_matrix(df, alpha=0.2)
209
+ array([[<Axes: xlabel='A', ylabel='A'>, <Axes: xlabel='B', ylabel='A'>,
210
+ <Axes: xlabel='C', ylabel='A'>, <Axes: xlabel='D', ylabel='A'>],
211
+ [<Axes: xlabel='A', ylabel='B'>, <Axes: xlabel='B', ylabel='B'>,
212
+ <Axes: xlabel='C', ylabel='B'>, <Axes: xlabel='D', ylabel='B'>],
213
+ [<Axes: xlabel='A', ylabel='C'>, <Axes: xlabel='B', ylabel='C'>,
214
+ <Axes: xlabel='C', ylabel='C'>, <Axes: xlabel='D', ylabel='C'>],
215
+ [<Axes: xlabel='A', ylabel='D'>, <Axes: xlabel='B', ylabel='D'>,
216
+ <Axes: xlabel='C', ylabel='D'>, <Axes: xlabel='D', ylabel='D'>]],
217
+ dtype=object)
218
+ """
219
+ plot_backend = _get_plot_backend("matplotlib")
220
+ return plot_backend.scatter_matrix(
221
+ frame=frame,
222
+ alpha=alpha,
223
+ figsize=figsize,
224
+ ax=ax,
225
+ grid=grid,
226
+ diagonal=diagonal,
227
+ marker=marker,
228
+ density_kwds=density_kwds,
229
+ hist_kwds=hist_kwds,
230
+ range_padding=range_padding,
231
+ **kwargs,
232
+ )
233
+
234
+
235
+ def radviz(
236
+ frame: DataFrame,
237
+ class_column: str,
238
+ ax: Axes | None = None,
239
+ color: list[str] | tuple[str, ...] | None = None,
240
+ colormap: Colormap | str | None = None,
241
+ **kwds,
242
+ ) -> Axes:
243
+ """
244
+ Plot a multidimensional dataset in 2D.
245
+
246
+ Each Series in the DataFrame is represented as a evenly distributed
247
+ slice on a circle. Each data point is rendered in the circle according to
248
+ the value on each Series. Highly correlated `Series` in the `DataFrame`
249
+ are placed closer on the unit circle.
250
+
251
+ RadViz allow to project a N-dimensional data set into a 2D space where the
252
+ influence of each dimension can be interpreted as a balance between the
253
+ influence of all dimensions.
254
+
255
+ More info available at the `original article
256
+ <https://doi.org/10.1145/331770.331775>`_
257
+ describing RadViz.
258
+
259
+ Parameters
260
+ ----------
261
+ frame : `DataFrame`
262
+ Object holding the data.
263
+ class_column : str
264
+ Column name containing the name of the data point category.
265
+ ax : :class:`matplotlib.axes.Axes`, optional
266
+ A plot instance to which to add the information.
267
+ color : list[str] or tuple[str], optional
268
+ Assign a color to each category. Example: ['blue', 'green'].
269
+ colormap : str or :class:`matplotlib.colors.Colormap`, default None
270
+ Colormap to select colors from. If string, load colormap with that
271
+ name from matplotlib.
272
+ **kwds
273
+ Options to pass to matplotlib scatter plotting method.
274
+
275
+ Returns
276
+ -------
277
+ :class:`matplotlib.axes.Axes`
278
+
279
+ See Also
280
+ --------
281
+ pandas.plotting.andrews_curves : Plot clustering visualization.
282
+
283
+ Examples
284
+ --------
285
+
286
+ .. plot::
287
+ :context: close-figs
288
+
289
+ >>> df = pd.DataFrame(
290
+ ... {
291
+ ... 'SepalLength': [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6],
292
+ ... 'SepalWidth': [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6],
293
+ ... 'PetalLength': [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0],
294
+ ... 'PetalWidth': [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2],
295
+ ... 'Category': [
296
+ ... 'virginica',
297
+ ... 'virginica',
298
+ ... 'setosa',
299
+ ... 'virginica',
300
+ ... 'virginica',
301
+ ... 'versicolor',
302
+ ... 'versicolor',
303
+ ... 'setosa',
304
+ ... 'virginica',
305
+ ... 'setosa'
306
+ ... ]
307
+ ... }
308
+ ... )
309
+ >>> pd.plotting.radviz(df, 'Category') # doctest: +SKIP
310
+ """
311
+ plot_backend = _get_plot_backend("matplotlib")
312
+ return plot_backend.radviz(
313
+ frame=frame,
314
+ class_column=class_column,
315
+ ax=ax,
316
+ color=color,
317
+ colormap=colormap,
318
+ **kwds,
319
+ )
320
+
321
+
322
+ def andrews_curves(
323
+ frame: DataFrame,
324
+ class_column: str,
325
+ ax: Axes | None = None,
326
+ samples: int = 200,
327
+ color: list[str] | tuple[str, ...] | None = None,
328
+ colormap: Colormap | str | None = None,
329
+ **kwargs,
330
+ ) -> Axes:
331
+ """
332
+ Generate a matplotlib plot for visualizing clusters of multivariate data.
333
+
334
+ Andrews curves have the functional form:
335
+
336
+ .. math::
337
+ f(t) = \\frac{x_1}{\\sqrt{2}} + x_2 \\sin(t) + x_3 \\cos(t) +
338
+ x_4 \\sin(2t) + x_5 \\cos(2t) + \\cdots
339
+
340
+ Where :math:`x` coefficients correspond to the values of each dimension
341
+ and :math:`t` is linearly spaced between :math:`-\\pi` and :math:`+\\pi`.
342
+ Each row of frame then corresponds to a single curve.
343
+
344
+ Parameters
345
+ ----------
346
+ frame : DataFrame
347
+ Data to be plotted, preferably normalized to (0.0, 1.0).
348
+ class_column : label
349
+ Name of the column containing class names.
350
+ ax : axes object, default None
351
+ Axes to use.
352
+ samples : int
353
+ Number of points to plot in each curve.
354
+ color : str, list[str] or tuple[str], optional
355
+ Colors to use for the different classes. Colors can be strings
356
+ or 3-element floating point RGB values.
357
+ colormap : str or matplotlib colormap object, default None
358
+ Colormap to select colors from. If a string, load colormap with that
359
+ name from matplotlib.
360
+ **kwargs
361
+ Options to pass to matplotlib plotting method.
362
+
363
+ Returns
364
+ -------
365
+ :class:`matplotlib.axes.Axes`
366
+
367
+ Examples
368
+ --------
369
+
370
+ .. plot::
371
+ :context: close-figs
372
+
373
+ >>> df = pd.read_csv(
374
+ ... 'https://raw.githubusercontent.com/pandas-dev/'
375
+ ... 'pandas/main/pandas/tests/io/data/csv/iris.csv'
376
+ ... )
377
+ >>> pd.plotting.andrews_curves(df, 'Name') # doctest: +SKIP
378
+ """
379
+ plot_backend = _get_plot_backend("matplotlib")
380
+ return plot_backend.andrews_curves(
381
+ frame=frame,
382
+ class_column=class_column,
383
+ ax=ax,
384
+ samples=samples,
385
+ color=color,
386
+ colormap=colormap,
387
+ **kwargs,
388
+ )
389
+
390
+
391
+ def bootstrap_plot(
392
+ series: Series,
393
+ fig: Figure | None = None,
394
+ size: int = 50,
395
+ samples: int = 500,
396
+ **kwds,
397
+ ) -> Figure:
398
+ """
399
+ Bootstrap plot on mean, median and mid-range statistics.
400
+
401
+ The bootstrap plot is used to estimate the uncertainty of a statistic
402
+ by relying on random sampling with replacement [1]_. This function will
403
+ generate bootstrapping plots for mean, median and mid-range statistics
404
+ for the given number of samples of the given size.
405
+
406
+ .. [1] "Bootstrapping (statistics)" in \
407
+ https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29
408
+
409
+ Parameters
410
+ ----------
411
+ series : pandas.Series
412
+ Series from where to get the samplings for the bootstrapping.
413
+ fig : matplotlib.figure.Figure, default None
414
+ If given, it will use the `fig` reference for plotting instead of
415
+ creating a new one with default parameters.
416
+ size : int, default 50
417
+ Number of data points to consider during each sampling. It must be
418
+ less than or equal to the length of the `series`.
419
+ samples : int, default 500
420
+ Number of times the bootstrap procedure is performed.
421
+ **kwds
422
+ Options to pass to matplotlib plotting method.
423
+
424
+ Returns
425
+ -------
426
+ matplotlib.figure.Figure
427
+ Matplotlib figure.
428
+
429
+ See Also
430
+ --------
431
+ pandas.DataFrame.plot : Basic plotting for DataFrame objects.
432
+ pandas.Series.plot : Basic plotting for Series objects.
433
+
434
+ Examples
435
+ --------
436
+ This example draws a basic bootstrap plot for a Series.
437
+
438
+ .. plot::
439
+ :context: close-figs
440
+
441
+ >>> s = pd.Series(np.random.uniform(size=100))
442
+ >>> pd.plotting.bootstrap_plot(s) # doctest: +SKIP
443
+ <Figure size 640x480 with 6 Axes>
444
+ """
445
+ plot_backend = _get_plot_backend("matplotlib")
446
+ return plot_backend.bootstrap_plot(
447
+ series=series, fig=fig, size=size, samples=samples, **kwds
448
+ )
449
+
450
+
451
+ def parallel_coordinates(
452
+ frame: DataFrame,
453
+ class_column: str,
454
+ cols: list[str] | None = None,
455
+ ax: Axes | None = None,
456
+ color: list[str] | tuple[str, ...] | None = None,
457
+ use_columns: bool = False,
458
+ xticks: list | tuple | None = None,
459
+ colormap: Colormap | str | None = None,
460
+ axvlines: bool = True,
461
+ axvlines_kwds: Mapping[str, Any] | None = None,
462
+ sort_labels: bool = False,
463
+ **kwargs,
464
+ ) -> Axes:
465
+ """
466
+ Parallel coordinates plotting.
467
+
468
+ Parameters
469
+ ----------
470
+ frame : DataFrame
471
+ class_column : str
472
+ Column name containing class names.
473
+ cols : list, optional
474
+ A list of column names to use.
475
+ ax : matplotlib.axis, optional
476
+ Matplotlib axis object.
477
+ color : list or tuple, optional
478
+ Colors to use for the different classes.
479
+ use_columns : bool, optional
480
+ If true, columns will be used as xticks.
481
+ xticks : list or tuple, optional
482
+ A list of values to use for xticks.
483
+ colormap : str or matplotlib colormap, default None
484
+ Colormap to use for line colors.
485
+ axvlines : bool, optional
486
+ If true, vertical lines will be added at each xtick.
487
+ axvlines_kwds : keywords, optional
488
+ Options to be passed to axvline method for vertical lines.
489
+ sort_labels : bool, default False
490
+ Sort class_column labels, useful when assigning colors.
491
+ **kwargs
492
+ Options to pass to matplotlib plotting method.
493
+
494
+ Returns
495
+ -------
496
+ matplotlib.axes.Axes
497
+
498
+ Examples
499
+ --------
500
+
501
+ .. plot::
502
+ :context: close-figs
503
+
504
+ >>> df = pd.read_csv(
505
+ ... 'https://raw.githubusercontent.com/pandas-dev/'
506
+ ... 'pandas/main/pandas/tests/io/data/csv/iris.csv'
507
+ ... )
508
+ >>> pd.plotting.parallel_coordinates(
509
+ ... df, 'Name', color=('#556270', '#4ECDC4', '#C7F464')
510
+ ... ) # doctest: +SKIP
511
+ """
512
+ plot_backend = _get_plot_backend("matplotlib")
513
+ return plot_backend.parallel_coordinates(
514
+ frame=frame,
515
+ class_column=class_column,
516
+ cols=cols,
517
+ ax=ax,
518
+ color=color,
519
+ use_columns=use_columns,
520
+ xticks=xticks,
521
+ colormap=colormap,
522
+ axvlines=axvlines,
523
+ axvlines_kwds=axvlines_kwds,
524
+ sort_labels=sort_labels,
525
+ **kwargs,
526
+ )
527
+
528
+
529
+ def lag_plot(series: Series, lag: int = 1, ax: Axes | None = None, **kwds) -> Axes:
530
+ """
531
+ Lag plot for time series.
532
+
533
+ Parameters
534
+ ----------
535
+ series : Series
536
+ The time series to visualize.
537
+ lag : int, default 1
538
+ Lag length of the scatter plot.
539
+ ax : Matplotlib axis object, optional
540
+ The matplotlib axis object to use.
541
+ **kwds
542
+ Matplotlib scatter method keyword arguments.
543
+
544
+ Returns
545
+ -------
546
+ matplotlib.axes.Axes
547
+
548
+ Examples
549
+ --------
550
+ Lag plots are most commonly used to look for patterns in time series data.
551
+
552
+ Given the following time series
553
+
554
+ .. plot::
555
+ :context: close-figs
556
+
557
+ >>> np.random.seed(5)
558
+ >>> x = np.cumsum(np.random.normal(loc=1, scale=5, size=50))
559
+ >>> s = pd.Series(x)
560
+ >>> s.plot() # doctest: +SKIP
561
+
562
+ A lag plot with ``lag=1`` returns
563
+
564
+ .. plot::
565
+ :context: close-figs
566
+
567
+ >>> pd.plotting.lag_plot(s, lag=1)
568
+ <Axes: xlabel='y(t)', ylabel='y(t + 1)'>
569
+ """
570
+ plot_backend = _get_plot_backend("matplotlib")
571
+ return plot_backend.lag_plot(series=series, lag=lag, ax=ax, **kwds)
572
+
573
+
574
+ def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwargs) -> Axes:
575
+ """
576
+ Autocorrelation plot for time series.
577
+
578
+ Parameters
579
+ ----------
580
+ series : Series
581
+ The time series to visualize.
582
+ ax : Matplotlib axis object, optional
583
+ The matplotlib axis object to use.
584
+ **kwargs
585
+ Options to pass to matplotlib plotting method.
586
+
587
+ Returns
588
+ -------
589
+ matplotlib.axes.Axes
590
+
591
+ Examples
592
+ --------
593
+ The horizontal lines in the plot correspond to 95% and 99% confidence bands.
594
+
595
+ The dashed line is 99% confidence band.
596
+
597
+ .. plot::
598
+ :context: close-figs
599
+
600
+ >>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
601
+ >>> s = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
602
+ >>> pd.plotting.autocorrelation_plot(s) # doctest: +SKIP
603
+ """
604
+ plot_backend = _get_plot_backend("matplotlib")
605
+ return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs)
606
+
607
+
608
+ class _Options(dict):
609
+ """
610
+ Stores pandas plotting options.
611
+
612
+ Allows for parameter aliasing so you can just use parameter names that are
613
+ the same as the plot function parameters, but is stored in a canonical
614
+ format that makes it easy to breakdown into groups later.
615
+
616
+ Examples
617
+ --------
618
+
619
+ .. plot::
620
+ :context: close-figs
621
+
622
+ >>> np.random.seed(42)
623
+ >>> df = pd.DataFrame({'A': np.random.randn(10),
624
+ ... 'B': np.random.randn(10)},
625
+ ... index=pd.date_range("1/1/2000",
626
+ ... freq='4MS', periods=10))
627
+ >>> with pd.plotting.plot_params.use("x_compat", True):
628
+ ... _ = df["A"].plot(color="r")
629
+ ... _ = df["B"].plot(color="g")
630
+ """
631
+
632
+ # alias so the names are same as plotting method parameter names
633
+ _ALIASES = {"x_compat": "xaxis.compat"}
634
+ _DEFAULT_KEYS = ["xaxis.compat"]
635
+
636
+ def __init__(self, deprecated: bool = False) -> None:
637
+ self._deprecated = deprecated
638
+ super().__setitem__("xaxis.compat", False)
639
+
640
+ def __getitem__(self, key):
641
+ key = self._get_canonical_key(key)
642
+ if key not in self:
643
+ raise ValueError(f"{key} is not a valid pandas plotting option")
644
+ return super().__getitem__(key)
645
+
646
+ def __setitem__(self, key, value) -> None:
647
+ key = self._get_canonical_key(key)
648
+ super().__setitem__(key, value)
649
+
650
+ def __delitem__(self, key) -> None:
651
+ key = self._get_canonical_key(key)
652
+ if key in self._DEFAULT_KEYS:
653
+ raise ValueError(f"Cannot remove default parameter {key}")
654
+ super().__delitem__(key)
655
+
656
+ def __contains__(self, key) -> bool:
657
+ key = self._get_canonical_key(key)
658
+ return super().__contains__(key)
659
+
660
+ def reset(self) -> None:
661
+ """
662
+ Reset the option store to its initial state
663
+
664
+ Returns
665
+ -------
666
+ None
667
+ """
668
+ # error: Cannot access "__init__" directly
669
+ self.__init__() # type: ignore[misc]
670
+
671
+ def _get_canonical_key(self, key):
672
+ return self._ALIASES.get(key, key)
673
+
674
+ @contextmanager
675
+ def use(self, key, value) -> Generator[_Options, None, None]:
676
+ """
677
+ Temporarily set a parameter value using the with statement.
678
+ Aliasing allowed.
679
+ """
680
+ old_value = self[key]
681
+ try:
682
+ self[key] = value
683
+ yield self
684
+ finally:
685
+ self[key] = old_value
686
+
687
+
688
+ plot_params = _Options()