Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER +1 -0
- omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE +29 -0
- omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA +93 -0
- omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD +43 -0
- omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED +0 -0
- omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL +6 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/__init__.py +1486 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/_afm.py +532 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so +0 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py +120 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/_internal_utils.py +64 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/_layoutgrid.py +547 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/_text_helpers.py +74 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/_tight_bbox.py +84 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/animation.py +1790 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/axis.py +0 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/backend_managers.py +398 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/backend_tools.py +1013 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/bezier.py +594 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/collections.py +2113 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/docstring.py +4 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/font_manager.py +1553 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/fontconfig_pattern.py +20 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/hatch.py +225 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/image.py +1818 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/legend_handler.py +817 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/scale.py +748 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/stackplot.py +127 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/text.py +2067 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/textpath.py +408 -0
- omnilmm/lib/python3.10/site-packages/matplotlib/widgets.py +0 -0
- omnilmm/lib/python3.10/site-packages/pkg_resources/__init__.py +0 -0
- omnilmm/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc +3 -0
- omnilmm/lib/python3.10/site-packages/pkg_resources/api_tests.txt +424 -0
- omnilmm/lib/python3.10/site-packages/pkg_resources/py.typed +0 -0
- omnilmm/lib/python3.10/site-packages/pkg_resources/tests/__init__.py +0 -0
- omnilmm/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -990,3 +990,4 @@ omnilmm/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_host.so fil
|
|
| 990 |
omnilmm/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops_train.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 991 |
omnilmm/lib/python3.10/site-packages/pandas/core/__pycache__/frame.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 992 |
omnilmm/lib/python3.10/site-packages/pandas/tests/io/__pycache__/test_sql.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 990 |
omnilmm/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops_train.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 991 |
omnilmm/lib/python3.10/site-packages/pandas/core/__pycache__/frame.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 992 |
omnilmm/lib/python3.10/site-packages/pandas/tests/io/__pycache__/test_sql.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 993 |
+
omnilmm/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BSD 3-Clause License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2021-2024, ContourPy Developers.
|
| 4 |
+
All rights reserved.
|
| 5 |
+
|
| 6 |
+
Redistribution and use in source and binary forms, with or without
|
| 7 |
+
modification, are permitted provided that the following conditions are met:
|
| 8 |
+
|
| 9 |
+
1. Redistributions of source code must retain the above copyright notice, this
|
| 10 |
+
list of conditions and the following disclaimer.
|
| 11 |
+
|
| 12 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
| 13 |
+
this list of conditions and the following disclaimer in the documentation
|
| 14 |
+
and/or other materials provided with the distribution.
|
| 15 |
+
|
| 16 |
+
3. Neither the name of the copyright holder nor the names of its
|
| 17 |
+
contributors may be used to endorse or promote products derived from
|
| 18 |
+
this software without specific prior written permission.
|
| 19 |
+
|
| 20 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 21 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 22 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 23 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 24 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 25 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 26 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 27 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 28 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 29 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: contourpy
|
| 3 |
+
Version: 1.3.1
|
| 4 |
+
Summary: Python library for calculating contours of 2D quadrilateral grids
|
| 5 |
+
Author-Email: Ian Thomas <ianthomas23@gmail.com>
|
| 6 |
+
License: BSD 3-Clause License
|
| 7 |
+
|
| 8 |
+
Copyright (c) 2021-2024, ContourPy Developers.
|
| 9 |
+
All rights reserved.
|
| 10 |
+
|
| 11 |
+
Redistribution and use in source and binary forms, with or without
|
| 12 |
+
modification, are permitted provided that the following conditions are met:
|
| 13 |
+
|
| 14 |
+
1. Redistributions of source code must retain the above copyright notice, this
|
| 15 |
+
list of conditions and the following disclaimer.
|
| 16 |
+
|
| 17 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
| 18 |
+
this list of conditions and the following disclaimer in the documentation
|
| 19 |
+
and/or other materials provided with the distribution.
|
| 20 |
+
|
| 21 |
+
3. Neither the name of the copyright holder nor the names of its
|
| 22 |
+
contributors may be used to endorse or promote products derived from
|
| 23 |
+
this software without specific prior written permission.
|
| 24 |
+
|
| 25 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 26 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 27 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 28 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 29 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 30 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 31 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 32 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 33 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 34 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 35 |
+
|
| 36 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 37 |
+
Classifier: Intended Audience :: Developers
|
| 38 |
+
Classifier: Intended Audience :: Science/Research
|
| 39 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 40 |
+
Classifier: Programming Language :: C++
|
| 41 |
+
Classifier: Programming Language :: Python :: 3
|
| 42 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 43 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 44 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 45 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 46 |
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
| 47 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
| 48 |
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
| 49 |
+
Project-URL: Homepage, https://github.com/contourpy/contourpy
|
| 50 |
+
Project-URL: Changelog, https://contourpy.readthedocs.io/en/latest/changelog.html
|
| 51 |
+
Project-URL: Documentation, https://contourpy.readthedocs.io
|
| 52 |
+
Project-URL: Repository, https://github.com/contourpy/contourpy
|
| 53 |
+
Requires-Python: >=3.10
|
| 54 |
+
Requires-Dist: numpy>=1.23
|
| 55 |
+
Provides-Extra: docs
|
| 56 |
+
Requires-Dist: furo; extra == "docs"
|
| 57 |
+
Requires-Dist: sphinx>=7.2; extra == "docs"
|
| 58 |
+
Requires-Dist: sphinx-copybutton; extra == "docs"
|
| 59 |
+
Provides-Extra: bokeh
|
| 60 |
+
Requires-Dist: bokeh; extra == "bokeh"
|
| 61 |
+
Requires-Dist: selenium; extra == "bokeh"
|
| 62 |
+
Provides-Extra: mypy
|
| 63 |
+
Requires-Dist: contourpy[bokeh,docs]; extra == "mypy"
|
| 64 |
+
Requires-Dist: docutils-stubs; extra == "mypy"
|
| 65 |
+
Requires-Dist: mypy==1.11.1; extra == "mypy"
|
| 66 |
+
Requires-Dist: types-Pillow; extra == "mypy"
|
| 67 |
+
Provides-Extra: test
|
| 68 |
+
Requires-Dist: contourpy[test-no-images]; extra == "test"
|
| 69 |
+
Requires-Dist: matplotlib; extra == "test"
|
| 70 |
+
Requires-Dist: Pillow; extra == "test"
|
| 71 |
+
Provides-Extra: test-no-images
|
| 72 |
+
Requires-Dist: pytest; extra == "test-no-images"
|
| 73 |
+
Requires-Dist: pytest-cov; extra == "test-no-images"
|
| 74 |
+
Requires-Dist: pytest-rerunfailures; extra == "test-no-images"
|
| 75 |
+
Requires-Dist: pytest-xdist; extra == "test-no-images"
|
| 76 |
+
Requires-Dist: wurlitzer; extra == "test-no-images"
|
| 77 |
+
Description-Content-Type: text/markdown
|
| 78 |
+
|
| 79 |
+
<img alt="ContourPy" src="https://raw.githubusercontent.com/contourpy/contourpy/main/docs/_static/contourpy_logo_horiz.svg" height="90">
|
| 80 |
+
|
| 81 |
+
ContourPy is a Python library for calculating contours of 2D quadrilateral grids. It is written in C++11 and wrapped using pybind11.
|
| 82 |
+
|
| 83 |
+
It contains the 2005 and 2014 algorithms used in Matplotlib as well as a newer algorithm that includes more features and is available in both serial and multithreaded versions. It provides an easy way for Python libraries to use contouring algorithms without having to include Matplotlib as a dependency.
|
| 84 |
+
|
| 85 |
+
* **Documentation**: https://contourpy.readthedocs.io
|
| 86 |
+
* **Source code**: https://github.com/contourpy/contourpy
|
| 87 |
+
|
| 88 |
+
| | |
|
| 89 |
+
| --- | --- |
|
| 90 |
+
| Latest release | [](https://pypi.python.org/pypi/contourpy) [](https://anaconda.org/conda-forge/contourpy) |
|
| 91 |
+
| Downloads | [](https://pepy.tech/project/contourpy) |
|
| 92 |
+
| Python version | [](https://pypi.org/project/contourpy/) |
|
| 93 |
+
| Coverage | [](https://app.codecov.io/gh/contourpy/contourpy) |
|
omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
contourpy-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
contourpy-1.3.1.dist-info/LICENSE,sha256=x9ChU7_6oQQERGPrxjN5PUUXIu_TE4tf_SUntA8VBaI,1534
|
| 3 |
+
contourpy-1.3.1.dist-info/METADATA,sha256=LQNae4q9MVNwpfb0FlnTCTe2tkw22GiKEJjpks9n7jk,5423
|
| 4 |
+
contourpy-1.3.1.dist-info/RECORD,,
|
| 5 |
+
contourpy-1.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
contourpy-1.3.1.dist-info/WHEEL,sha256=sZM_NeUMz2G4fDenMf11eikcCxcLaQWiYRmjwQBavQs,137
|
| 7 |
+
contourpy/__init__.py,sha256=Vi2YbtUhM9VxYPY3PBvxfu0xZYr6fBysl5gQPJEo88k,11831
|
| 8 |
+
contourpy/__pycache__/__init__.cpython-310.pyc,,
|
| 9 |
+
contourpy/__pycache__/_version.cpython-310.pyc,,
|
| 10 |
+
contourpy/__pycache__/array.cpython-310.pyc,,
|
| 11 |
+
contourpy/__pycache__/chunk.cpython-310.pyc,,
|
| 12 |
+
contourpy/__pycache__/convert.cpython-310.pyc,,
|
| 13 |
+
contourpy/__pycache__/dechunk.cpython-310.pyc,,
|
| 14 |
+
contourpy/__pycache__/enum_util.cpython-310.pyc,,
|
| 15 |
+
contourpy/__pycache__/typecheck.cpython-310.pyc,,
|
| 16 |
+
contourpy/__pycache__/types.cpython-310.pyc,,
|
| 17 |
+
contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so,sha256=H8GWcYv0tePHkvGU0HhmBO_d_Chj3Bs_6QYgLRKjIMI,854312
|
| 18 |
+
contourpy/_contourpy.pyi,sha256=fvtccxkiZwGb6qYag7Fp4E8bsFmAIjAmobf8LNxqfgc,7122
|
| 19 |
+
contourpy/_version.py,sha256=-ypEJktJToAL9by62JJKWEzDo_KPCQtmE5kwFgX24z4,22
|
| 20 |
+
contourpy/array.py,sha256=4WwLuiZe30rizn_raymmY13OzE6hlCsDOO8kuVFOP18,8979
|
| 21 |
+
contourpy/chunk.py,sha256=8njDQqlpuD22RjaaCyA75FXQsSQDY5hZGJSrxFpvGGU,3279
|
| 22 |
+
contourpy/convert.py,sha256=mhyn7prEoWCnf0igaH-VqDwlk-CegFsZ4qOy2LL-hpU,26154
|
| 23 |
+
contourpy/dechunk.py,sha256=EgFL6hw5H54ccuof4tJ2ehdnktT7trgZjiZqppsH8QI,7756
|
| 24 |
+
contourpy/enum_util.py,sha256=o8MItJRs08oqzwPP3IwC75BBAY9Qq95saIzjkXBXwqA,1519
|
| 25 |
+
contourpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 26 |
+
contourpy/typecheck.py,sha256=t1nvvCuKMYva1Zx4fc30EpdKFcO0Enz3n_UFfXBsq9o,10747
|
| 27 |
+
contourpy/types.py,sha256=2K4T5tJpMIjYrkkg1Lqh3C2ZKlnOhnMtYmtwz92l_y8,247
|
| 28 |
+
contourpy/util/__init__.py,sha256=eVhJ_crOHL7nkG4Kb0dOo7NL4WHMy_Px665aAN_3d-8,118
|
| 29 |
+
contourpy/util/__pycache__/__init__.cpython-310.pyc,,
|
| 30 |
+
contourpy/util/__pycache__/_build_config.cpython-310.pyc,,
|
| 31 |
+
contourpy/util/__pycache__/bokeh_renderer.cpython-310.pyc,,
|
| 32 |
+
contourpy/util/__pycache__/bokeh_util.cpython-310.pyc,,
|
| 33 |
+
contourpy/util/__pycache__/data.cpython-310.pyc,,
|
| 34 |
+
contourpy/util/__pycache__/mpl_renderer.cpython-310.pyc,,
|
| 35 |
+
contourpy/util/__pycache__/mpl_util.cpython-310.pyc,,
|
| 36 |
+
contourpy/util/__pycache__/renderer.cpython-310.pyc,,
|
| 37 |
+
contourpy/util/_build_config.py,sha256=jzJKkuBQpyjnX1U_eltbhIAN_i6fbzTAQXMAP1YTlG0,1848
|
| 38 |
+
contourpy/util/bokeh_renderer.py,sha256=wNGBghEVA4x11wrSerb3dBbdRxX6E8kuoqlaKPoHTQ8,13769
|
| 39 |
+
contourpy/util/bokeh_util.py,sha256=wc-S3ewBUYWyIkEv9jkhFySIergjLQl4Z0UEVnE0HhA,2804
|
| 40 |
+
contourpy/util/data.py,sha256=-7SSGMLX_gN-1H2JzpNSEB_EcEF_uMtYdOo_ePRIcg8,2586
|
| 41 |
+
contourpy/util/mpl_renderer.py,sha256=avUxO7_MQRDQM84X5PZ9GbNtGxG0EXPSVQYV00xQMvQ,20089
|
| 42 |
+
contourpy/util/mpl_util.py,sha256=0Jz5f-aA9XMWlpO2pDnHbkVgxIiw4SY_ysxf_gACWEo,3452
|
| 43 |
+
contourpy/util/renderer.py,sha256=8CBHzPmVsFPfqsWxqrxGBhqFpJhVeFHFeDzVXAgT8Fc,5118
|
omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED
ADDED
|
File without changes
|
omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: meson
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-manylinux_2_17_x86_64
|
| 5 |
+
Tag: cp310-cp310-manylinux2014_x86_64
|
| 6 |
+
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc
ADDED
|
Binary file (55.2 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc
ADDED
|
Binary file (1.52 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc
ADDED
|
Binary file (3.98 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc
ADDED
|
Binary file (25.9 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc
ADDED
|
Binary file (11.1 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc
ADDED
|
Binary file (20.4 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc
ADDED
|
Binary file (3.8 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc
ADDED
|
Binary file (5 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc
ADDED
|
Binary file (40.3 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc
ADDED
|
Binary file (6.68 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (24.8 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/matplotlib/__init__.py
ADDED
|
@@ -0,0 +1,1486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
An object-oriented plotting library.
|
| 3 |
+
|
| 4 |
+
A procedural interface is provided by the companion pyplot module,
|
| 5 |
+
which may be imported directly, e.g.::
|
| 6 |
+
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
|
| 9 |
+
or using ipython::
|
| 10 |
+
|
| 11 |
+
ipython
|
| 12 |
+
|
| 13 |
+
at your terminal, followed by::
|
| 14 |
+
|
| 15 |
+
In [1]: %matplotlib
|
| 16 |
+
In [2]: import matplotlib.pyplot as plt
|
| 17 |
+
|
| 18 |
+
at the ipython shell prompt.
|
| 19 |
+
|
| 20 |
+
For the most part, direct use of the explicit object-oriented library is
|
| 21 |
+
encouraged when programming; the implicit pyplot interface is primarily for
|
| 22 |
+
working interactively. The exceptions to this suggestion are the pyplot
|
| 23 |
+
functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and
|
| 24 |
+
`.pyplot.savefig`, which can greatly simplify scripting. See
|
| 25 |
+
:ref:`api_interfaces` for an explanation of the tradeoffs between the implicit
|
| 26 |
+
and explicit interfaces.
|
| 27 |
+
|
| 28 |
+
Modules include:
|
| 29 |
+
|
| 30 |
+
:mod:`matplotlib.axes`
|
| 31 |
+
The `~.axes.Axes` class. Most pyplot functions are wrappers for
|
| 32 |
+
`~.axes.Axes` methods. The axes module is the highest level of OO
|
| 33 |
+
access to the library.
|
| 34 |
+
|
| 35 |
+
:mod:`matplotlib.figure`
|
| 36 |
+
The `.Figure` class.
|
| 37 |
+
|
| 38 |
+
:mod:`matplotlib.artist`
|
| 39 |
+
The `.Artist` base class for all classes that draw things.
|
| 40 |
+
|
| 41 |
+
:mod:`matplotlib.lines`
|
| 42 |
+
The `.Line2D` class for drawing lines and markers.
|
| 43 |
+
|
| 44 |
+
:mod:`matplotlib.patches`
|
| 45 |
+
Classes for drawing polygons.
|
| 46 |
+
|
| 47 |
+
:mod:`matplotlib.text`
|
| 48 |
+
The `.Text` and `.Annotation` classes.
|
| 49 |
+
|
| 50 |
+
:mod:`matplotlib.image`
|
| 51 |
+
The `.AxesImage` and `.FigureImage` classes.
|
| 52 |
+
|
| 53 |
+
:mod:`matplotlib.collections`
|
| 54 |
+
Classes for efficient drawing of groups of lines or polygons.
|
| 55 |
+
|
| 56 |
+
:mod:`matplotlib.colors`
|
| 57 |
+
Color specifications and making colormaps.
|
| 58 |
+
|
| 59 |
+
:mod:`matplotlib.cm`
|
| 60 |
+
Colormaps, and the `.ScalarMappable` mixin class for providing color
|
| 61 |
+
mapping functionality to other classes.
|
| 62 |
+
|
| 63 |
+
:mod:`matplotlib.ticker`
|
| 64 |
+
Calculation of tick mark locations and formatting of tick labels.
|
| 65 |
+
|
| 66 |
+
:mod:`matplotlib.backends`
|
| 67 |
+
A subpackage with modules for various GUI libraries and output formats.
|
| 68 |
+
|
| 69 |
+
The base matplotlib namespace includes:
|
| 70 |
+
|
| 71 |
+
`~matplotlib.rcParams`
|
| 72 |
+
Default configuration settings; their defaults may be overridden using
|
| 73 |
+
a :file:`matplotlibrc` file.
|
| 74 |
+
|
| 75 |
+
`~matplotlib.use`
|
| 76 |
+
Setting the Matplotlib backend. This should be called before any
|
| 77 |
+
figure is created, because it is not possible to switch between
|
| 78 |
+
different GUI backends after that.
|
| 79 |
+
|
| 80 |
+
The following environment variables can be used to customize the behavior:
|
| 81 |
+
|
| 82 |
+
:envvar:`MPLBACKEND`
|
| 83 |
+
This optional variable can be set to choose the Matplotlib backend. See
|
| 84 |
+
:ref:`what-is-a-backend`.
|
| 85 |
+
|
| 86 |
+
:envvar:`MPLCONFIGDIR`
|
| 87 |
+
This is the directory used to store user customizations to
|
| 88 |
+
Matplotlib, as well as some caches to improve performance. If
|
| 89 |
+
:envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib`
|
| 90 |
+
and :file:`{HOME}/.cache/matplotlib` are used on Linux, and
|
| 91 |
+
:file:`{HOME}/.matplotlib` on other platforms, if they are
|
| 92 |
+
writable. Otherwise, the Python standard library's `tempfile.gettempdir`
|
| 93 |
+
is used to find a base directory in which the :file:`matplotlib`
|
| 94 |
+
subdirectory is created.
|
| 95 |
+
|
| 96 |
+
Matplotlib was initially written by John D. Hunter (1968-2012) and is now
|
| 97 |
+
developed and maintained by a host of others.
|
| 98 |
+
|
| 99 |
+
Occasionally the internal documentation (python docstrings) will refer
|
| 100 |
+
to MATLAB®, a registered trademark of The MathWorks, Inc.
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
import atexit
|
| 105 |
+
from collections import namedtuple
|
| 106 |
+
from collections.abc import MutableMapping
|
| 107 |
+
import contextlib
|
| 108 |
+
import functools
|
| 109 |
+
import importlib
|
| 110 |
+
import inspect
|
| 111 |
+
from inspect import Parameter
|
| 112 |
+
import locale
|
| 113 |
+
import logging
|
| 114 |
+
import os
|
| 115 |
+
from pathlib import Path
|
| 116 |
+
import pprint
|
| 117 |
+
import re
|
| 118 |
+
import shutil
|
| 119 |
+
import subprocess
|
| 120 |
+
import sys
|
| 121 |
+
import tempfile
|
| 122 |
+
import warnings
|
| 123 |
+
|
| 124 |
+
import numpy
|
| 125 |
+
from packaging.version import parse as parse_version
|
| 126 |
+
|
| 127 |
+
# cbook must import matplotlib only within function
|
| 128 |
+
# definitions, so it is safe to import from it here.
|
| 129 |
+
from . import _api, _version, cbook, _docstring, rcsetup
|
| 130 |
+
from matplotlib.cbook import sanitize_sequence
|
| 131 |
+
from matplotlib._api import MatplotlibDeprecationWarning
|
| 132 |
+
from matplotlib.rcsetup import validate_backend, cycler
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
_log = logging.getLogger(__name__)
|
| 136 |
+
|
| 137 |
+
__bibtex__ = r"""@Article{Hunter:2007,
|
| 138 |
+
Author = {Hunter, J. D.},
|
| 139 |
+
Title = {Matplotlib: A 2D graphics environment},
|
| 140 |
+
Journal = {Computing in Science \& Engineering},
|
| 141 |
+
Volume = {9},
|
| 142 |
+
Number = {3},
|
| 143 |
+
Pages = {90--95},
|
| 144 |
+
abstract = {Matplotlib is a 2D graphics package used for Python
|
| 145 |
+
for application development, interactive scripting, and
|
| 146 |
+
publication-quality image generation across user
|
| 147 |
+
interfaces and operating systems.},
|
| 148 |
+
publisher = {IEEE COMPUTER SOC},
|
| 149 |
+
year = 2007
|
| 150 |
+
}"""
|
| 151 |
+
|
| 152 |
+
# modelled after sys.version_info
|
| 153 |
+
_VersionInfo = namedtuple('_VersionInfo',
|
| 154 |
+
'major, minor, micro, releaselevel, serial')
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _parse_to_version_info(version_str):
|
| 158 |
+
"""
|
| 159 |
+
Parse a version string to a namedtuple analogous to sys.version_info.
|
| 160 |
+
|
| 161 |
+
See:
|
| 162 |
+
https://packaging.pypa.io/en/latest/version.html#packaging.version.parse
|
| 163 |
+
https://docs.python.org/3/library/sys.html#sys.version_info
|
| 164 |
+
"""
|
| 165 |
+
v = parse_version(version_str)
|
| 166 |
+
if v.pre is None and v.post is None and v.dev is None:
|
| 167 |
+
return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)
|
| 168 |
+
elif v.dev is not None:
|
| 169 |
+
return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)
|
| 170 |
+
elif v.pre is not None:
|
| 171 |
+
releaselevel = {
|
| 172 |
+
'a': 'alpha',
|
| 173 |
+
'b': 'beta',
|
| 174 |
+
'rc': 'candidate'}.get(v.pre[0], 'alpha')
|
| 175 |
+
return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])
|
| 176 |
+
else:
|
| 177 |
+
# fallback for v.post: guess-next-dev scheme from setuptools_scm
|
| 178 |
+
return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _get_version():
|
| 182 |
+
"""Return the version string used for __version__."""
|
| 183 |
+
# Only shell out to a git subprocess if really needed, i.e. when we are in
|
| 184 |
+
# a matplotlib git repo but not in a shallow clone, such as those used by
|
| 185 |
+
# CI, as the latter would trigger a warning from setuptools_scm.
|
| 186 |
+
root = Path(__file__).resolve().parents[2]
|
| 187 |
+
if ((root / ".matplotlib-repo").exists()
|
| 188 |
+
and (root / ".git").exists()
|
| 189 |
+
and not (root / ".git/shallow").exists()):
|
| 190 |
+
import setuptools_scm
|
| 191 |
+
return setuptools_scm.get_version(
|
| 192 |
+
root=root,
|
| 193 |
+
version_scheme="release-branch-semver",
|
| 194 |
+
local_scheme="node-and-date",
|
| 195 |
+
fallback_version=_version.version,
|
| 196 |
+
)
|
| 197 |
+
else: # Get the version from the _version.py setuptools_scm file.
|
| 198 |
+
return _version.version
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@_api.caching_module_getattr
|
| 202 |
+
class __getattr__:
|
| 203 |
+
__version__ = property(lambda self: _get_version())
|
| 204 |
+
__version_info__ = property(
|
| 205 |
+
lambda self: _parse_to_version_info(self.__version__))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _check_versions():
|
| 209 |
+
|
| 210 |
+
# Quickfix to ensure Microsoft Visual C++ redistributable
|
| 211 |
+
# DLLs are loaded before importing kiwisolver
|
| 212 |
+
from . import ft2font
|
| 213 |
+
|
| 214 |
+
for modname, minver in [
|
| 215 |
+
("cycler", "0.10"),
|
| 216 |
+
("dateutil", "2.7"),
|
| 217 |
+
("kiwisolver", "1.0.1"),
|
| 218 |
+
("numpy", "1.20"),
|
| 219 |
+
("pyparsing", "2.3.1"),
|
| 220 |
+
]:
|
| 221 |
+
module = importlib.import_module(modname)
|
| 222 |
+
if parse_version(module.__version__) < parse_version(minver):
|
| 223 |
+
raise ImportError(f"Matplotlib requires {modname}>={minver}; "
|
| 224 |
+
f"you have {module.__version__}")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
_check_versions()
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# The decorator ensures this always returns the same handler (and it is only
|
| 231 |
+
# attached once).
|
| 232 |
+
@functools.lru_cache()
|
| 233 |
+
def _ensure_handler():
|
| 234 |
+
"""
|
| 235 |
+
The first time this function is called, attach a `StreamHandler` using the
|
| 236 |
+
same format as `logging.basicConfig` to the Matplotlib root logger.
|
| 237 |
+
|
| 238 |
+
Return this handler every time this function is called.
|
| 239 |
+
"""
|
| 240 |
+
handler = logging.StreamHandler()
|
| 241 |
+
handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
|
| 242 |
+
_log.addHandler(handler)
|
| 243 |
+
return handler
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def set_loglevel(level):
|
| 247 |
+
"""
|
| 248 |
+
Configure Matplotlib's logging levels.
|
| 249 |
+
|
| 250 |
+
Matplotlib uses the standard library `logging` framework under the root
|
| 251 |
+
logger 'matplotlib'. This is a helper function to:
|
| 252 |
+
|
| 253 |
+
- set Matplotlib's root logger level
|
| 254 |
+
- set the root logger handler's level, creating the handler
|
| 255 |
+
if it does not exist yet
|
| 256 |
+
|
| 257 |
+
Typically, one should call ``set_loglevel("info")`` or
|
| 258 |
+
``set_loglevel("debug")`` to get additional debugging information.
|
| 259 |
+
|
| 260 |
+
Users or applications that are installing their own logging handlers
|
| 261 |
+
may want to directly manipulate ``logging.getLogger('matplotlib')`` rather
|
| 262 |
+
than use this function.
|
| 263 |
+
|
| 264 |
+
Parameters
|
| 265 |
+
----------
|
| 266 |
+
level : {"notset", "debug", "info", "warning", "error", "critical"}
|
| 267 |
+
The log level of the handler.
|
| 268 |
+
|
| 269 |
+
Notes
|
| 270 |
+
-----
|
| 271 |
+
The first time this function is called, an additional handler is attached
|
| 272 |
+
to Matplotlib's root handler; this handler is reused every time and this
|
| 273 |
+
function simply manipulates the logger and handler's level.
|
| 274 |
+
|
| 275 |
+
"""
|
| 276 |
+
_log.setLevel(level.upper())
|
| 277 |
+
_ensure_handler().setLevel(level.upper())
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _logged_cached(fmt, func=None):
|
| 281 |
+
"""
|
| 282 |
+
Decorator that logs a function's return value, and memoizes that value.
|
| 283 |
+
|
| 284 |
+
After ::
|
| 285 |
+
|
| 286 |
+
@_logged_cached(fmt)
|
| 287 |
+
def func(): ...
|
| 288 |
+
|
| 289 |
+
the first call to *func* will log its return value at the DEBUG level using
|
| 290 |
+
%-format string *fmt*, and memoize it; later calls to *func* will directly
|
| 291 |
+
return that value.
|
| 292 |
+
"""
|
| 293 |
+
if func is None: # Return the actual decorator.
|
| 294 |
+
return functools.partial(_logged_cached, fmt)
|
| 295 |
+
|
| 296 |
+
called = False
|
| 297 |
+
ret = None
|
| 298 |
+
|
| 299 |
+
@functools.wraps(func)
|
| 300 |
+
def wrapper(**kwargs):
|
| 301 |
+
nonlocal called, ret
|
| 302 |
+
if not called:
|
| 303 |
+
ret = func(**kwargs)
|
| 304 |
+
called = True
|
| 305 |
+
_log.debug(fmt, ret)
|
| 306 |
+
return ret
|
| 307 |
+
|
| 308 |
+
return wrapper
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
_ExecInfo = namedtuple("_ExecInfo", "executable raw_version version")
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class ExecutableNotFoundError(FileNotFoundError):
|
| 315 |
+
"""
|
| 316 |
+
Error raised when an executable that Matplotlib optionally
|
| 317 |
+
depends on can't be found.
|
| 318 |
+
"""
|
| 319 |
+
pass
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@functools.lru_cache()
|
| 323 |
+
def _get_executable_info(name):
|
| 324 |
+
"""
|
| 325 |
+
Get the version of some executable that Matplotlib optionally depends on.
|
| 326 |
+
|
| 327 |
+
.. warning::
|
| 328 |
+
The list of executables that this function supports is set according to
|
| 329 |
+
Matplotlib's internal needs, and may change without notice.
|
| 330 |
+
|
| 331 |
+
Parameters
|
| 332 |
+
----------
|
| 333 |
+
name : str
|
| 334 |
+
The executable to query. The following values are currently supported:
|
| 335 |
+
"dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This
|
| 336 |
+
list is subject to change without notice.
|
| 337 |
+
|
| 338 |
+
Returns
|
| 339 |
+
-------
|
| 340 |
+
tuple
|
| 341 |
+
A namedtuple with fields ``executable`` (`str`) and ``version``
|
| 342 |
+
(`packaging.Version`, or ``None`` if the version cannot be determined).
|
| 343 |
+
|
| 344 |
+
Raises
|
| 345 |
+
------
|
| 346 |
+
ExecutableNotFoundError
|
| 347 |
+
If the executable is not found or older than the oldest version
|
| 348 |
+
supported by Matplotlib. For debugging purposes, it is also
|
| 349 |
+
possible to "hide" an executable from Matplotlib by adding it to the
|
| 350 |
+
:envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated
|
| 351 |
+
list), which must be set prior to any calls to this function.
|
| 352 |
+
ValueError
|
| 353 |
+
If the executable is not one that we know how to query.
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
def impl(args, regex, min_ver=None, ignore_exit_code=False):
|
| 357 |
+
# Execute the subprocess specified by args; capture stdout and stderr.
|
| 358 |
+
# Search for a regex match in the output; if the match succeeds, the
|
| 359 |
+
# first group of the match is the version.
|
| 360 |
+
# Return an _ExecInfo if the executable exists, and has a version of
|
| 361 |
+
# at least min_ver (if set); else, raise ExecutableNotFoundError.
|
| 362 |
+
try:
|
| 363 |
+
output = subprocess.check_output(
|
| 364 |
+
args, stderr=subprocess.STDOUT,
|
| 365 |
+
universal_newlines=True, errors="replace")
|
| 366 |
+
except subprocess.CalledProcessError as _cpe:
|
| 367 |
+
if ignore_exit_code:
|
| 368 |
+
output = _cpe.output
|
| 369 |
+
else:
|
| 370 |
+
raise ExecutableNotFoundError(str(_cpe)) from _cpe
|
| 371 |
+
except OSError as _ose:
|
| 372 |
+
raise ExecutableNotFoundError(str(_ose)) from _ose
|
| 373 |
+
match = re.search(regex, output)
|
| 374 |
+
if match:
|
| 375 |
+
raw_version = match.group(1)
|
| 376 |
+
version = parse_version(raw_version)
|
| 377 |
+
if min_ver is not None and version < parse_version(min_ver):
|
| 378 |
+
raise ExecutableNotFoundError(
|
| 379 |
+
f"You have {args[0]} version {version} but the minimum "
|
| 380 |
+
f"version supported by Matplotlib is {min_ver}")
|
| 381 |
+
return _ExecInfo(args[0], raw_version, version)
|
| 382 |
+
else:
|
| 383 |
+
raise ExecutableNotFoundError(
|
| 384 |
+
f"Failed to determine the version of {args[0]} from "
|
| 385 |
+
f"{' '.join(args)}, which output {output}")
|
| 386 |
+
|
| 387 |
+
if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","):
|
| 388 |
+
raise ExecutableNotFoundError(f"{name} was hidden")
|
| 389 |
+
|
| 390 |
+
if name == "dvipng":
|
| 391 |
+
return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
|
| 392 |
+
elif name == "gs":
|
| 393 |
+
execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
|
| 394 |
+
if sys.platform == "win32" else
|
| 395 |
+
["gs"])
|
| 396 |
+
for e in execs:
|
| 397 |
+
try:
|
| 398 |
+
return impl([e, "--version"], "(.*)", "9")
|
| 399 |
+
except ExecutableNotFoundError:
|
| 400 |
+
pass
|
| 401 |
+
message = "Failed to find a Ghostscript installation"
|
| 402 |
+
raise ExecutableNotFoundError(message)
|
| 403 |
+
elif name == "inkscape":
|
| 404 |
+
try:
|
| 405 |
+
# Try headless option first (needed for Inkscape version < 1.0):
|
| 406 |
+
return impl(["inkscape", "--without-gui", "-V"],
|
| 407 |
+
"Inkscape ([^ ]*)")
|
| 408 |
+
except ExecutableNotFoundError:
|
| 409 |
+
pass # Suppress exception chaining.
|
| 410 |
+
# If --without-gui is not accepted, we may be using Inkscape >= 1.0 so
|
| 411 |
+
# try without it:
|
| 412 |
+
return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")
|
| 413 |
+
elif name == "magick":
|
| 414 |
+
if sys.platform == "win32":
|
| 415 |
+
# Check the registry to avoid confusing ImageMagick's convert with
|
| 416 |
+
# Windows's builtin convert.exe.
|
| 417 |
+
import winreg
|
| 418 |
+
binpath = ""
|
| 419 |
+
for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
|
| 420 |
+
try:
|
| 421 |
+
with winreg.OpenKeyEx(
|
| 422 |
+
winreg.HKEY_LOCAL_MACHINE,
|
| 423 |
+
r"Software\Imagemagick\Current",
|
| 424 |
+
0, winreg.KEY_QUERY_VALUE | flag) as hkey:
|
| 425 |
+
binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
|
| 426 |
+
except OSError:
|
| 427 |
+
pass
|
| 428 |
+
path = None
|
| 429 |
+
if binpath:
|
| 430 |
+
for name in ["convert.exe", "magick.exe"]:
|
| 431 |
+
candidate = Path(binpath, name)
|
| 432 |
+
if candidate.exists():
|
| 433 |
+
path = str(candidate)
|
| 434 |
+
break
|
| 435 |
+
if path is None:
|
| 436 |
+
raise ExecutableNotFoundError(
|
| 437 |
+
"Failed to find an ImageMagick installation")
|
| 438 |
+
else:
|
| 439 |
+
path = "convert"
|
| 440 |
+
info = impl([path, "--version"], r"^Version: ImageMagick (\S*)")
|
| 441 |
+
if info.raw_version == "7.0.10-34":
|
| 442 |
+
# https://github.com/ImageMagick/ImageMagick/issues/2720
|
| 443 |
+
raise ExecutableNotFoundError(
|
| 444 |
+
f"You have ImageMagick {info.version}, which is unsupported")
|
| 445 |
+
return info
|
| 446 |
+
elif name == "pdftocairo":
|
| 447 |
+
return impl(["pdftocairo", "-v"], "pdftocairo version (.*)")
|
| 448 |
+
elif name == "pdftops":
|
| 449 |
+
info = impl(["pdftops", "-v"], "^pdftops version (.*)",
|
| 450 |
+
ignore_exit_code=True)
|
| 451 |
+
if info and not (
|
| 452 |
+
3 <= info.version.major or
|
| 453 |
+
# poppler version numbers.
|
| 454 |
+
parse_version("0.9") <= info.version < parse_version("1.0")):
|
| 455 |
+
raise ExecutableNotFoundError(
|
| 456 |
+
f"You have pdftops version {info.version} but the minimum "
|
| 457 |
+
f"version supported by Matplotlib is 3.0")
|
| 458 |
+
return info
|
| 459 |
+
else:
|
| 460 |
+
raise ValueError("Unknown executable: {!r}".format(name))
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
@_api.deprecated("3.6", alternative="a vendored copy of this function")
|
| 464 |
+
def checkdep_usetex(s):
|
| 465 |
+
if not s:
|
| 466 |
+
return False
|
| 467 |
+
if not shutil.which("tex"):
|
| 468 |
+
_log.warning("usetex mode requires TeX.")
|
| 469 |
+
return False
|
| 470 |
+
try:
|
| 471 |
+
_get_executable_info("dvipng")
|
| 472 |
+
except ExecutableNotFoundError:
|
| 473 |
+
_log.warning("usetex mode requires dvipng.")
|
| 474 |
+
return False
|
| 475 |
+
try:
|
| 476 |
+
_get_executable_info("gs")
|
| 477 |
+
except ExecutableNotFoundError:
|
| 478 |
+
_log.warning("usetex mode requires ghostscript.")
|
| 479 |
+
return False
|
| 480 |
+
return True
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def _get_xdg_config_dir():
|
| 484 |
+
"""
|
| 485 |
+
Return the XDG configuration directory, according to the XDG base
|
| 486 |
+
directory spec:
|
| 487 |
+
|
| 488 |
+
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
| 489 |
+
"""
|
| 490 |
+
return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def _get_xdg_cache_dir():
|
| 494 |
+
"""
|
| 495 |
+
Return the XDG cache directory, according to the XDG base directory spec:
|
| 496 |
+
|
| 497 |
+
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
| 498 |
+
"""
|
| 499 |
+
return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def _get_config_or_cache_dir(xdg_base_getter):
|
| 503 |
+
configdir = os.environ.get('MPLCONFIGDIR')
|
| 504 |
+
if configdir:
|
| 505 |
+
configdir = Path(configdir).resolve()
|
| 506 |
+
elif sys.platform.startswith(('linux', 'freebsd')):
|
| 507 |
+
# Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first,
|
| 508 |
+
# as _xdg_base_getter can throw.
|
| 509 |
+
configdir = Path(xdg_base_getter(), "matplotlib")
|
| 510 |
+
else:
|
| 511 |
+
configdir = Path.home() / ".matplotlib"
|
| 512 |
+
try:
|
| 513 |
+
configdir.mkdir(parents=True, exist_ok=True)
|
| 514 |
+
except OSError:
|
| 515 |
+
pass
|
| 516 |
+
else:
|
| 517 |
+
if os.access(str(configdir), os.W_OK) and configdir.is_dir():
|
| 518 |
+
return str(configdir)
|
| 519 |
+
# If the config or cache directory cannot be created or is not a writable
|
| 520 |
+
# directory, create a temporary one.
|
| 521 |
+
try:
|
| 522 |
+
tmpdir = tempfile.mkdtemp(prefix="matplotlib-")
|
| 523 |
+
except OSError as exc:
|
| 524 |
+
raise OSError(
|
| 525 |
+
f"Matplotlib requires access to a writable cache directory, but the "
|
| 526 |
+
f"default path ({configdir}) is not a writable directory, and a temporary "
|
| 527 |
+
f"directory could not be created; set the MPLCONFIGDIR environment "
|
| 528 |
+
f"variable to a writable directory") from exc
|
| 529 |
+
os.environ["MPLCONFIGDIR"] = tmpdir
|
| 530 |
+
atexit.register(shutil.rmtree, tmpdir)
|
| 531 |
+
_log.warning(
|
| 532 |
+
"Matplotlib created a temporary cache directory at %s because the default path "
|
| 533 |
+
"(%s) is not a writable directory; it is highly recommended to set the "
|
| 534 |
+
"MPLCONFIGDIR environment variable to a writable directory, in particular to "
|
| 535 |
+
"speed up the import of Matplotlib and to better support multiprocessing.",
|
| 536 |
+
tmpdir, configdir)
|
| 537 |
+
return tmpdir
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
@_logged_cached('CONFIGDIR=%s')
|
| 541 |
+
def get_configdir():
|
| 542 |
+
"""
|
| 543 |
+
Return the string path of the configuration directory.
|
| 544 |
+
|
| 545 |
+
The directory is chosen as follows:
|
| 546 |
+
|
| 547 |
+
1. If the MPLCONFIGDIR environment variable is supplied, choose that.
|
| 548 |
+
2. On Linux, follow the XDG specification and look first in
|
| 549 |
+
``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other
|
| 550 |
+
platforms, choose ``$HOME/.matplotlib``.
|
| 551 |
+
3. If the chosen directory exists and is writable, use that as the
|
| 552 |
+
configuration directory.
|
| 553 |
+
4. Else, create a temporary directory, and use it as the configuration
|
| 554 |
+
directory.
|
| 555 |
+
"""
|
| 556 |
+
return _get_config_or_cache_dir(_get_xdg_config_dir)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
@_logged_cached('CACHEDIR=%s')
|
| 560 |
+
def get_cachedir():
|
| 561 |
+
"""
|
| 562 |
+
Return the string path of the cache directory.
|
| 563 |
+
|
| 564 |
+
The procedure used to find the directory is the same as for
|
| 565 |
+
_get_config_dir, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead.
|
| 566 |
+
"""
|
| 567 |
+
return _get_config_or_cache_dir(_get_xdg_cache_dir)
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
@_logged_cached('matplotlib data path: %s')
|
| 571 |
+
def get_data_path():
|
| 572 |
+
"""Return the path to Matplotlib data."""
|
| 573 |
+
return str(Path(__file__).with_name("mpl-data"))
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def matplotlib_fname():
|
| 577 |
+
"""
|
| 578 |
+
Get the location of the config file.
|
| 579 |
+
|
| 580 |
+
The file location is determined in the following order
|
| 581 |
+
|
| 582 |
+
- ``$PWD/matplotlibrc``
|
| 583 |
+
- ``$MATPLOTLIBRC`` if it is not a directory
|
| 584 |
+
- ``$MATPLOTLIBRC/matplotlibrc``
|
| 585 |
+
- ``$MPLCONFIGDIR/matplotlibrc``
|
| 586 |
+
- On Linux,
|
| 587 |
+
- ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
|
| 588 |
+
is defined)
|
| 589 |
+
- or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
|
| 590 |
+
is not defined)
|
| 591 |
+
- On other platforms,
|
| 592 |
+
- ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
|
| 593 |
+
- Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
|
| 594 |
+
exist.
|
| 595 |
+
"""
|
| 596 |
+
|
| 597 |
+
def gen_candidates():
|
| 598 |
+
# rely on down-stream code to make absolute. This protects us
|
| 599 |
+
# from having to directly get the current working directory
|
| 600 |
+
# which can fail if the user has ended up with a cwd that is
|
| 601 |
+
# non-existent.
|
| 602 |
+
yield 'matplotlibrc'
|
| 603 |
+
try:
|
| 604 |
+
matplotlibrc = os.environ['MATPLOTLIBRC']
|
| 605 |
+
except KeyError:
|
| 606 |
+
pass
|
| 607 |
+
else:
|
| 608 |
+
yield matplotlibrc
|
| 609 |
+
yield os.path.join(matplotlibrc, 'matplotlibrc')
|
| 610 |
+
yield os.path.join(get_configdir(), 'matplotlibrc')
|
| 611 |
+
yield os.path.join(get_data_path(), 'matplotlibrc')
|
| 612 |
+
|
| 613 |
+
for fname in gen_candidates():
|
| 614 |
+
if os.path.exists(fname) and not os.path.isdir(fname):
|
| 615 |
+
return fname
|
| 616 |
+
|
| 617 |
+
raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
|
| 618 |
+
"install is broken")
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
# rcParams deprecated and automatically mapped to another key.
|
| 622 |
+
# Values are tuples of (version, new_name, f_old2new, f_new2old).
|
| 623 |
+
_deprecated_map = {}
|
| 624 |
+
# rcParams deprecated; some can manually be mapped to another key.
|
| 625 |
+
# Values are tuples of (version, new_name_or_None).
|
| 626 |
+
_deprecated_ignore_map = {}
|
| 627 |
+
# rcParams deprecated; can use None to suppress warnings; remain actually
|
| 628 |
+
# listed in the rcParams.
|
| 629 |
+
# Values are tuples of (version,)
|
| 630 |
+
_deprecated_remain_as_none = {}
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
@_docstring.Substitution(
|
| 634 |
+
"\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower)))
|
| 635 |
+
)
|
| 636 |
+
class RcParams(MutableMapping, dict):
|
| 637 |
+
"""
|
| 638 |
+
A dict-like key-value store for config parameters, including validation.
|
| 639 |
+
|
| 640 |
+
Validating functions are defined and associated with rc parameters in
|
| 641 |
+
:mod:`matplotlib.rcsetup`.
|
| 642 |
+
|
| 643 |
+
The list of rcParams is:
|
| 644 |
+
|
| 645 |
+
%s
|
| 646 |
+
|
| 647 |
+
See Also
|
| 648 |
+
--------
|
| 649 |
+
:ref:`customizing-with-matplotlibrc-files`
|
| 650 |
+
"""
|
| 651 |
+
|
| 652 |
+
validate = rcsetup._validators
|
| 653 |
+
|
| 654 |
+
# validate values on the way in
|
| 655 |
+
def __init__(self, *args, **kwargs):
|
| 656 |
+
self.update(*args, **kwargs)
|
| 657 |
+
|
| 658 |
+
def _set(self, key, val):
|
| 659 |
+
"""
|
| 660 |
+
Directly write data bypassing deprecation and validation logic.
|
| 661 |
+
|
| 662 |
+
Notes
|
| 663 |
+
-----
|
| 664 |
+
As end user or downstream library you almost always should use
|
| 665 |
+
``rcParams[key] = val`` and not ``_set()``.
|
| 666 |
+
|
| 667 |
+
There are only very few special cases that need direct data access.
|
| 668 |
+
These cases previously used ``dict.__setitem__(rcParams, key, val)``,
|
| 669 |
+
which is now deprecated and replaced by ``rcParams._set(key, val)``.
|
| 670 |
+
|
| 671 |
+
Even though private, we guarantee API stability for ``rcParams._set``,
|
| 672 |
+
i.e. it is subject to Matplotlib's API and deprecation policy.
|
| 673 |
+
|
| 674 |
+
:meta public:
|
| 675 |
+
"""
|
| 676 |
+
dict.__setitem__(self, key, val)
|
| 677 |
+
|
| 678 |
+
def _get(self, key):
|
| 679 |
+
"""
|
| 680 |
+
Directly read data bypassing deprecation, backend and validation
|
| 681 |
+
logic.
|
| 682 |
+
|
| 683 |
+
Notes
|
| 684 |
+
-----
|
| 685 |
+
As end user or downstream library you almost always should use
|
| 686 |
+
``val = rcParams[key]`` and not ``_get()``.
|
| 687 |
+
|
| 688 |
+
There are only very few special cases that need direct data access.
|
| 689 |
+
These cases previously used ``dict.__getitem__(rcParams, key, val)``,
|
| 690 |
+
which is now deprecated and replaced by ``rcParams._get(key)``.
|
| 691 |
+
|
| 692 |
+
Even though private, we guarantee API stability for ``rcParams._get``,
|
| 693 |
+
i.e. it is subject to Matplotlib's API and deprecation policy.
|
| 694 |
+
|
| 695 |
+
:meta public:
|
| 696 |
+
"""
|
| 697 |
+
return dict.__getitem__(self, key)
|
| 698 |
+
|
| 699 |
+
def __setitem__(self, key, val):
|
| 700 |
+
try:
|
| 701 |
+
if key in _deprecated_map:
|
| 702 |
+
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
|
| 703 |
+
_api.warn_deprecated(
|
| 704 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 705 |
+
key = alt_key
|
| 706 |
+
val = alt_val(val)
|
| 707 |
+
elif key in _deprecated_remain_as_none and val is not None:
|
| 708 |
+
version, = _deprecated_remain_as_none[key]
|
| 709 |
+
_api.warn_deprecated(version, name=key, obj_type="rcparam")
|
| 710 |
+
elif key in _deprecated_ignore_map:
|
| 711 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 712 |
+
_api.warn_deprecated(
|
| 713 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 714 |
+
return
|
| 715 |
+
elif key == 'backend':
|
| 716 |
+
if val is rcsetup._auto_backend_sentinel:
|
| 717 |
+
if 'backend' in self:
|
| 718 |
+
return
|
| 719 |
+
try:
|
| 720 |
+
cval = self.validate[key](val)
|
| 721 |
+
except ValueError as ve:
|
| 722 |
+
raise ValueError(f"Key {key}: {ve}") from None
|
| 723 |
+
self._set(key, cval)
|
| 724 |
+
except KeyError as err:
|
| 725 |
+
raise KeyError(
|
| 726 |
+
f"{key} is not a valid rc parameter (see rcParams.keys() for "
|
| 727 |
+
f"a list of valid parameters)") from err
|
| 728 |
+
|
| 729 |
+
def __getitem__(self, key):
|
| 730 |
+
if key in _deprecated_map:
|
| 731 |
+
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
|
| 732 |
+
_api.warn_deprecated(
|
| 733 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 734 |
+
return inverse_alt(self._get(alt_key))
|
| 735 |
+
|
| 736 |
+
elif key in _deprecated_ignore_map:
|
| 737 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 738 |
+
_api.warn_deprecated(
|
| 739 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 740 |
+
return self._get(alt_key) if alt_key else None
|
| 741 |
+
|
| 742 |
+
# In theory, this should only ever be used after the global rcParams
|
| 743 |
+
# has been set up, but better be safe e.g. in presence of breakpoints.
|
| 744 |
+
elif key == "backend" and self is globals().get("rcParams"):
|
| 745 |
+
val = self._get(key)
|
| 746 |
+
if val is rcsetup._auto_backend_sentinel:
|
| 747 |
+
from matplotlib import pyplot as plt
|
| 748 |
+
plt.switch_backend(rcsetup._auto_backend_sentinel)
|
| 749 |
+
|
| 750 |
+
return self._get(key)
|
| 751 |
+
|
| 752 |
+
def _get_backend_or_none(self):
|
| 753 |
+
"""Get the requested backend, if any, without triggering resolution."""
|
| 754 |
+
backend = self._get("backend")
|
| 755 |
+
return None if backend is rcsetup._auto_backend_sentinel else backend
|
| 756 |
+
|
| 757 |
+
def __repr__(self):
|
| 758 |
+
class_name = self.__class__.__name__
|
| 759 |
+
indent = len(class_name) + 1
|
| 760 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 761 |
+
repr_split = pprint.pformat(dict(self), indent=1,
|
| 762 |
+
width=80 - indent).split('\n')
|
| 763 |
+
repr_indented = ('\n' + ' ' * indent).join(repr_split)
|
| 764 |
+
return '{}({})'.format(class_name, repr_indented)
|
| 765 |
+
|
| 766 |
+
def __str__(self):
|
| 767 |
+
return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
|
| 768 |
+
|
| 769 |
+
def __iter__(self):
|
| 770 |
+
"""Yield sorted list of keys."""
|
| 771 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 772 |
+
yield from sorted(dict.__iter__(self))
|
| 773 |
+
|
| 774 |
+
def __len__(self):
|
| 775 |
+
return dict.__len__(self)
|
| 776 |
+
|
| 777 |
+
def find_all(self, pattern):
|
| 778 |
+
"""
|
| 779 |
+
Return the subset of this RcParams dictionary whose keys match,
|
| 780 |
+
using :func:`re.search`, the given ``pattern``.
|
| 781 |
+
|
| 782 |
+
.. note::
|
| 783 |
+
|
| 784 |
+
Changes to the returned dictionary are *not* propagated to
|
| 785 |
+
the parent RcParams dictionary.
|
| 786 |
+
|
| 787 |
+
"""
|
| 788 |
+
pattern_re = re.compile(pattern)
|
| 789 |
+
return RcParams((key, value)
|
| 790 |
+
for key, value in self.items()
|
| 791 |
+
if pattern_re.search(key))
|
| 792 |
+
|
| 793 |
+
def copy(self):
|
| 794 |
+
"""Copy this RcParams instance."""
|
| 795 |
+
rccopy = RcParams()
|
| 796 |
+
for k in self: # Skip deprecations and revalidation.
|
| 797 |
+
rccopy._set(k, self._get(k))
|
| 798 |
+
return rccopy
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def rc_params(fail_on_error=False):
|
| 802 |
+
"""Construct a `RcParams` instance from the default Matplotlib rc file."""
|
| 803 |
+
return rc_params_from_file(matplotlib_fname(), fail_on_error)
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
@functools.lru_cache()
|
| 807 |
+
def _get_ssl_context():
|
| 808 |
+
try:
|
| 809 |
+
import certifi
|
| 810 |
+
except ImportError:
|
| 811 |
+
_log.debug("Could not import certifi.")
|
| 812 |
+
return None
|
| 813 |
+
import ssl
|
| 814 |
+
return ssl.create_default_context(cafile=certifi.where())
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
@contextlib.contextmanager
|
| 818 |
+
def _open_file_or_url(fname):
|
| 819 |
+
if (isinstance(fname, str)
|
| 820 |
+
and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))):
|
| 821 |
+
import urllib.request
|
| 822 |
+
ssl_ctx = _get_ssl_context()
|
| 823 |
+
if ssl_ctx is None:
|
| 824 |
+
_log.debug(
|
| 825 |
+
"Could not get certifi ssl context, https may not work."
|
| 826 |
+
)
|
| 827 |
+
with urllib.request.urlopen(fname, context=ssl_ctx) as f:
|
| 828 |
+
yield (line.decode('utf-8') for line in f)
|
| 829 |
+
else:
|
| 830 |
+
fname = os.path.expanduser(fname)
|
| 831 |
+
with open(fname, encoding='utf-8') as f:
|
| 832 |
+
yield f
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):
|
| 836 |
+
"""
|
| 837 |
+
Construct a `RcParams` instance from file *fname*.
|
| 838 |
+
|
| 839 |
+
Unlike `rc_params_from_file`, the configuration class only contains the
|
| 840 |
+
parameters specified in the file (i.e. default values are not filled in).
|
| 841 |
+
|
| 842 |
+
Parameters
|
| 843 |
+
----------
|
| 844 |
+
fname : path-like
|
| 845 |
+
The loaded file.
|
| 846 |
+
transform : callable, default: the identity function
|
| 847 |
+
A function called on each individual line of the file to transform it,
|
| 848 |
+
before further parsing.
|
| 849 |
+
fail_on_error : bool, default: False
|
| 850 |
+
Whether invalid entries should result in an exception or a warning.
|
| 851 |
+
"""
|
| 852 |
+
import matplotlib as mpl
|
| 853 |
+
rc_temp = {}
|
| 854 |
+
with _open_file_or_url(fname) as fd:
|
| 855 |
+
try:
|
| 856 |
+
for line_no, line in enumerate(fd, 1):
|
| 857 |
+
line = transform(line)
|
| 858 |
+
strippedline = cbook._strip_comment(line)
|
| 859 |
+
if not strippedline:
|
| 860 |
+
continue
|
| 861 |
+
tup = strippedline.split(':', 1)
|
| 862 |
+
if len(tup) != 2:
|
| 863 |
+
_log.warning('Missing colon in file %r, line %d (%r)',
|
| 864 |
+
fname, line_no, line.rstrip('\n'))
|
| 865 |
+
continue
|
| 866 |
+
key, val = tup
|
| 867 |
+
key = key.strip()
|
| 868 |
+
val = val.strip()
|
| 869 |
+
if val.startswith('"') and val.endswith('"'):
|
| 870 |
+
val = val[1:-1] # strip double quotes
|
| 871 |
+
if key in rc_temp:
|
| 872 |
+
_log.warning('Duplicate key in file %r, line %d (%r)',
|
| 873 |
+
fname, line_no, line.rstrip('\n'))
|
| 874 |
+
rc_temp[key] = (val, line, line_no)
|
| 875 |
+
except UnicodeDecodeError:
|
| 876 |
+
_log.warning('Cannot decode configuration file %r as utf-8.',
|
| 877 |
+
fname)
|
| 878 |
+
raise
|
| 879 |
+
|
| 880 |
+
config = RcParams()
|
| 881 |
+
|
| 882 |
+
for key, (val, line, line_no) in rc_temp.items():
|
| 883 |
+
if key in rcsetup._validators:
|
| 884 |
+
if fail_on_error:
|
| 885 |
+
config[key] = val # try to convert to proper type or raise
|
| 886 |
+
else:
|
| 887 |
+
try:
|
| 888 |
+
config[key] = val # try to convert to proper type or skip
|
| 889 |
+
except Exception as msg:
|
| 890 |
+
_log.warning('Bad value in file %r, line %d (%r): %s',
|
| 891 |
+
fname, line_no, line.rstrip('\n'), msg)
|
| 892 |
+
elif key in _deprecated_ignore_map:
|
| 893 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 894 |
+
_api.warn_deprecated(
|
| 895 |
+
version, name=key, alternative=alt_key, obj_type='rcparam',
|
| 896 |
+
addendum="Please update your matplotlibrc.")
|
| 897 |
+
else:
|
| 898 |
+
# __version__ must be looked up as an attribute to trigger the
|
| 899 |
+
# module-level __getattr__.
|
| 900 |
+
version = ('main' if '.post' in mpl.__version__
|
| 901 |
+
else f'v{mpl.__version__}')
|
| 902 |
+
_log.warning("""
|
| 903 |
+
Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)
|
| 904 |
+
You probably need to get an updated matplotlibrc file from
|
| 905 |
+
https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc
|
| 906 |
+
or from the matplotlib source distribution""",
|
| 907 |
+
dict(key=key, fname=fname, line_no=line_no,
|
| 908 |
+
line=line.rstrip('\n'), version=version))
|
| 909 |
+
return config
|
| 910 |
+
|
| 911 |
+
|
| 912 |
+
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
|
| 913 |
+
"""
|
| 914 |
+
Construct a `RcParams` from file *fname*.
|
| 915 |
+
|
| 916 |
+
Parameters
|
| 917 |
+
----------
|
| 918 |
+
fname : str or path-like
|
| 919 |
+
A file with Matplotlib rc settings.
|
| 920 |
+
fail_on_error : bool
|
| 921 |
+
If True, raise an error when the parser fails to convert a parameter.
|
| 922 |
+
use_default_template : bool
|
| 923 |
+
If True, initialize with default parameters before updating with those
|
| 924 |
+
in the given file. If False, the configuration class only contains the
|
| 925 |
+
parameters specified in the file. (Useful for updating dicts.)
|
| 926 |
+
"""
|
| 927 |
+
config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)
|
| 928 |
+
|
| 929 |
+
if not use_default_template:
|
| 930 |
+
return config_from_file
|
| 931 |
+
|
| 932 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 933 |
+
config = RcParams({**rcParamsDefault, **config_from_file})
|
| 934 |
+
|
| 935 |
+
if "".join(config['text.latex.preamble']):
|
| 936 |
+
_log.info("""
|
| 937 |
+
*****************************************************************
|
| 938 |
+
You have the following UNSUPPORTED LaTeX preamble customizations:
|
| 939 |
+
%s
|
| 940 |
+
Please do not ask for support with these customizations active.
|
| 941 |
+
*****************************************************************
|
| 942 |
+
""", '\n'.join(config['text.latex.preamble']))
|
| 943 |
+
_log.debug('loaded rc file %s', fname)
|
| 944 |
+
|
| 945 |
+
return config
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
# When constructing the global instances, we need to perform certain updates
|
| 949 |
+
# by explicitly calling the superclass (dict.update, dict.items) to avoid
|
| 950 |
+
# triggering resolution of _auto_backend_sentinel.
|
| 951 |
+
rcParamsDefault = _rc_params_in_file(
|
| 952 |
+
cbook._get_data_path("matplotlibrc"),
|
| 953 |
+
# Strip leading comment.
|
| 954 |
+
transform=lambda line: line[1:] if line.startswith("#") else line,
|
| 955 |
+
fail_on_error=True)
|
| 956 |
+
dict.update(rcParamsDefault, rcsetup._hardcoded_defaults)
|
| 957 |
+
# Normally, the default matplotlibrc file contains *no* entry for backend (the
|
| 958 |
+
# corresponding line starts with ##, not #; we fill on _auto_backend_sentinel
|
| 959 |
+
# in that case. However, packagers can set a different default backend
|
| 960 |
+
# (resulting in a normal `#backend: foo` line) in which case we should *not*
|
| 961 |
+
# fill in _auto_backend_sentinel.
|
| 962 |
+
dict.setdefault(rcParamsDefault, "backend", rcsetup._auto_backend_sentinel)
|
| 963 |
+
rcParams = RcParams() # The global instance.
|
| 964 |
+
dict.update(rcParams, dict.items(rcParamsDefault))
|
| 965 |
+
dict.update(rcParams, _rc_params_in_file(matplotlib_fname()))
|
| 966 |
+
rcParamsOrig = rcParams.copy()
|
| 967 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 968 |
+
# This also checks that all rcParams are indeed listed in the template.
|
| 969 |
+
# Assigning to rcsetup.defaultParams is left only for backcompat.
|
| 970 |
+
defaultParams = rcsetup.defaultParams = {
|
| 971 |
+
# We want to resolve deprecated rcParams, but not backend...
|
| 972 |
+
key: [(rcsetup._auto_backend_sentinel if key == "backend" else
|
| 973 |
+
rcParamsDefault[key]),
|
| 974 |
+
validator]
|
| 975 |
+
for key, validator in rcsetup._validators.items()}
|
| 976 |
+
if rcParams['axes.formatter.use_locale']:
|
| 977 |
+
locale.setlocale(locale.LC_ALL, '')
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
def rc(group, **kwargs):
|
| 981 |
+
"""
|
| 982 |
+
Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,
|
| 983 |
+
for ``lines.linewidth`` the group is ``lines``, for
|
| 984 |
+
``axes.facecolor``, the group is ``axes``, and so on. Group may
|
| 985 |
+
also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
|
| 986 |
+
*kwargs* is a dictionary attribute name/value pairs, e.g.,::
|
| 987 |
+
|
| 988 |
+
rc('lines', linewidth=2, color='r')
|
| 989 |
+
|
| 990 |
+
sets the current `.rcParams` and is equivalent to::
|
| 991 |
+
|
| 992 |
+
rcParams['lines.linewidth'] = 2
|
| 993 |
+
rcParams['lines.color'] = 'r'
|
| 994 |
+
|
| 995 |
+
The following aliases are available to save typing for interactive users:
|
| 996 |
+
|
| 997 |
+
===== =================
|
| 998 |
+
Alias Property
|
| 999 |
+
===== =================
|
| 1000 |
+
'lw' 'linewidth'
|
| 1001 |
+
'ls' 'linestyle'
|
| 1002 |
+
'c' 'color'
|
| 1003 |
+
'fc' 'facecolor'
|
| 1004 |
+
'ec' 'edgecolor'
|
| 1005 |
+
'mew' 'markeredgewidth'
|
| 1006 |
+
'aa' 'antialiased'
|
| 1007 |
+
===== =================
|
| 1008 |
+
|
| 1009 |
+
Thus you could abbreviate the above call as::
|
| 1010 |
+
|
| 1011 |
+
rc('lines', lw=2, c='r')
|
| 1012 |
+
|
| 1013 |
+
Note you can use python's kwargs dictionary facility to store
|
| 1014 |
+
dictionaries of default parameters. e.g., you can customize the
|
| 1015 |
+
font rc as follows::
|
| 1016 |
+
|
| 1017 |
+
font = {'family' : 'monospace',
|
| 1018 |
+
'weight' : 'bold',
|
| 1019 |
+
'size' : 'larger'}
|
| 1020 |
+
rc('font', **font) # pass in the font dict as kwargs
|
| 1021 |
+
|
| 1022 |
+
This enables you to easily switch between several configurations. Use
|
| 1023 |
+
``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
|
| 1024 |
+
restore the default `.rcParams` after changes.
|
| 1025 |
+
|
| 1026 |
+
Notes
|
| 1027 |
+
-----
|
| 1028 |
+
Similar functionality is available by using the normal dict interface, i.e.
|
| 1029 |
+
``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
|
| 1030 |
+
does not support abbreviations or grouping).
|
| 1031 |
+
"""
|
| 1032 |
+
|
| 1033 |
+
aliases = {
|
| 1034 |
+
'lw': 'linewidth',
|
| 1035 |
+
'ls': 'linestyle',
|
| 1036 |
+
'c': 'color',
|
| 1037 |
+
'fc': 'facecolor',
|
| 1038 |
+
'ec': 'edgecolor',
|
| 1039 |
+
'mew': 'markeredgewidth',
|
| 1040 |
+
'aa': 'antialiased',
|
| 1041 |
+
}
|
| 1042 |
+
|
| 1043 |
+
if isinstance(group, str):
|
| 1044 |
+
group = (group,)
|
| 1045 |
+
for g in group:
|
| 1046 |
+
for k, v in kwargs.items():
|
| 1047 |
+
name = aliases.get(k) or k
|
| 1048 |
+
key = '%s.%s' % (g, name)
|
| 1049 |
+
try:
|
| 1050 |
+
rcParams[key] = v
|
| 1051 |
+
except KeyError as err:
|
| 1052 |
+
raise KeyError(('Unrecognized key "%s" for group "%s" and '
|
| 1053 |
+
'name "%s"') % (key, g, name)) from err
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
def rcdefaults():
|
| 1057 |
+
"""
|
| 1058 |
+
Restore the `.rcParams` from Matplotlib's internal default style.
|
| 1059 |
+
|
| 1060 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1061 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1062 |
+
|
| 1063 |
+
See Also
|
| 1064 |
+
--------
|
| 1065 |
+
matplotlib.rc_file_defaults
|
| 1066 |
+
Restore the `.rcParams` from the rc file originally loaded by
|
| 1067 |
+
Matplotlib.
|
| 1068 |
+
matplotlib.style.use
|
| 1069 |
+
Use a specific style file. Call ``style.use('default')`` to restore
|
| 1070 |
+
the default style.
|
| 1071 |
+
"""
|
| 1072 |
+
# Deprecation warnings were already handled when creating rcParamsDefault,
|
| 1073 |
+
# no need to reemit them here.
|
| 1074 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1075 |
+
from .style.core import STYLE_BLACKLIST
|
| 1076 |
+
rcParams.clear()
|
| 1077 |
+
rcParams.update({k: v for k, v in rcParamsDefault.items()
|
| 1078 |
+
if k not in STYLE_BLACKLIST})
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
def rc_file_defaults():
|
| 1082 |
+
"""
|
| 1083 |
+
Restore the `.rcParams` from the original rc file loaded by Matplotlib.
|
| 1084 |
+
|
| 1085 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1086 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1087 |
+
"""
|
| 1088 |
+
# Deprecation warnings were already handled when creating rcParamsOrig, no
|
| 1089 |
+
# need to reemit them here.
|
| 1090 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1091 |
+
from .style.core import STYLE_BLACKLIST
|
| 1092 |
+
rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
|
| 1093 |
+
if k not in STYLE_BLACKLIST})
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def rc_file(fname, *, use_default_template=True):
|
| 1097 |
+
"""
|
| 1098 |
+
Update `.rcParams` from file.
|
| 1099 |
+
|
| 1100 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1101 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1102 |
+
|
| 1103 |
+
Parameters
|
| 1104 |
+
----------
|
| 1105 |
+
fname : str or path-like
|
| 1106 |
+
A file with Matplotlib rc settings.
|
| 1107 |
+
|
| 1108 |
+
use_default_template : bool
|
| 1109 |
+
If True, initialize with default parameters before updating with those
|
| 1110 |
+
in the given file. If False, the current configuration persists
|
| 1111 |
+
and only the parameters specified in the file are updated.
|
| 1112 |
+
"""
|
| 1113 |
+
# Deprecation warnings were already handled in rc_params_from_file, no need
|
| 1114 |
+
# to reemit them here.
|
| 1115 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1116 |
+
from .style.core import STYLE_BLACKLIST
|
| 1117 |
+
rc_from_file = rc_params_from_file(
|
| 1118 |
+
fname, use_default_template=use_default_template)
|
| 1119 |
+
rcParams.update({k: rc_from_file[k] for k in rc_from_file
|
| 1120 |
+
if k not in STYLE_BLACKLIST})
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
@contextlib.contextmanager
|
| 1124 |
+
def rc_context(rc=None, fname=None):
|
| 1125 |
+
"""
|
| 1126 |
+
Return a context manager for temporarily changing rcParams.
|
| 1127 |
+
|
| 1128 |
+
The :rc:`backend` will not be reset by the context manager.
|
| 1129 |
+
|
| 1130 |
+
rcParams changed both through the context manager invocation and
|
| 1131 |
+
in the body of the context will be reset on context exit.
|
| 1132 |
+
|
| 1133 |
+
Parameters
|
| 1134 |
+
----------
|
| 1135 |
+
rc : dict
|
| 1136 |
+
The rcParams to temporarily set.
|
| 1137 |
+
fname : str or path-like
|
| 1138 |
+
A file with Matplotlib rc settings. If both *fname* and *rc* are given,
|
| 1139 |
+
settings from *rc* take precedence.
|
| 1140 |
+
|
| 1141 |
+
See Also
|
| 1142 |
+
--------
|
| 1143 |
+
:ref:`customizing-with-matplotlibrc-files`
|
| 1144 |
+
|
| 1145 |
+
Examples
|
| 1146 |
+
--------
|
| 1147 |
+
Passing explicit values via a dict::
|
| 1148 |
+
|
| 1149 |
+
with mpl.rc_context({'interactive': False}):
|
| 1150 |
+
fig, ax = plt.subplots()
|
| 1151 |
+
ax.plot(range(3), range(3))
|
| 1152 |
+
fig.savefig('example.png')
|
| 1153 |
+
plt.close(fig)
|
| 1154 |
+
|
| 1155 |
+
Loading settings from a file::
|
| 1156 |
+
|
| 1157 |
+
with mpl.rc_context(fname='print.rc'):
|
| 1158 |
+
plt.plot(x, y) # uses 'print.rc'
|
| 1159 |
+
|
| 1160 |
+
Setting in the context body::
|
| 1161 |
+
|
| 1162 |
+
with mpl.rc_context():
|
| 1163 |
+
# will be reset
|
| 1164 |
+
mpl.rcParams['lines.linewidth'] = 5
|
| 1165 |
+
plt.plot(x, y)
|
| 1166 |
+
|
| 1167 |
+
"""
|
| 1168 |
+
orig = dict(rcParams.copy())
|
| 1169 |
+
del orig['backend']
|
| 1170 |
+
try:
|
| 1171 |
+
if fname:
|
| 1172 |
+
rc_file(fname)
|
| 1173 |
+
if rc:
|
| 1174 |
+
rcParams.update(rc)
|
| 1175 |
+
yield
|
| 1176 |
+
finally:
|
| 1177 |
+
dict.update(rcParams, orig) # Revert to the original rcs.
|
| 1178 |
+
|
| 1179 |
+
|
| 1180 |
+
def use(backend, *, force=True):
|
| 1181 |
+
"""
|
| 1182 |
+
Select the backend used for rendering and GUI integration.
|
| 1183 |
+
|
| 1184 |
+
If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used
|
| 1185 |
+
and if the new backend is different than the current backend, all Figures
|
| 1186 |
+
will be closed.
|
| 1187 |
+
|
| 1188 |
+
Parameters
|
| 1189 |
+
----------
|
| 1190 |
+
backend : str
|
| 1191 |
+
The backend to switch to. This can either be one of the standard
|
| 1192 |
+
backend names, which are case-insensitive:
|
| 1193 |
+
|
| 1194 |
+
- interactive backends:
|
| 1195 |
+
GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, QtAgg,
|
| 1196 |
+
QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo
|
| 1197 |
+
|
| 1198 |
+
- non-interactive backends:
|
| 1199 |
+
agg, cairo, pdf, pgf, ps, svg, template
|
| 1200 |
+
|
| 1201 |
+
or a string of the form: ``module://my.module.name``.
|
| 1202 |
+
|
| 1203 |
+
Switching to an interactive backend is not possible if an unrelated
|
| 1204 |
+
event loop has already been started (e.g., switching to GTK3Agg if a
|
| 1205 |
+
TkAgg window has already been opened). Switching to a non-interactive
|
| 1206 |
+
backend is always possible.
|
| 1207 |
+
|
| 1208 |
+
force : bool, default: True
|
| 1209 |
+
If True (the default), raise an `ImportError` if the backend cannot be
|
| 1210 |
+
set up (either because it fails to import, or because an incompatible
|
| 1211 |
+
GUI interactive framework is already running); if False, silently
|
| 1212 |
+
ignore the failure.
|
| 1213 |
+
|
| 1214 |
+
See Also
|
| 1215 |
+
--------
|
| 1216 |
+
:ref:`backends`
|
| 1217 |
+
matplotlib.get_backend
|
| 1218 |
+
matplotlib.pyplot.switch_backend
|
| 1219 |
+
|
| 1220 |
+
"""
|
| 1221 |
+
name = validate_backend(backend)
|
| 1222 |
+
# don't (prematurely) resolve the "auto" backend setting
|
| 1223 |
+
if rcParams._get_backend_or_none() == name:
|
| 1224 |
+
# Nothing to do if the requested backend is already set
|
| 1225 |
+
pass
|
| 1226 |
+
else:
|
| 1227 |
+
# if pyplot is not already imported, do not import it. Doing
|
| 1228 |
+
# so may trigger a `plt.switch_backend` to the _default_ backend
|
| 1229 |
+
# before we get a chance to change to the one the user just requested
|
| 1230 |
+
plt = sys.modules.get('matplotlib.pyplot')
|
| 1231 |
+
# if pyplot is imported, then try to change backends
|
| 1232 |
+
if plt is not None:
|
| 1233 |
+
try:
|
| 1234 |
+
# we need this import check here to re-raise if the
|
| 1235 |
+
# user does not have the libraries to support their
|
| 1236 |
+
# chosen backend installed.
|
| 1237 |
+
plt.switch_backend(name)
|
| 1238 |
+
except ImportError:
|
| 1239 |
+
if force:
|
| 1240 |
+
raise
|
| 1241 |
+
# if we have not imported pyplot, then we can set the rcParam
|
| 1242 |
+
# value which will be respected when the user finally imports
|
| 1243 |
+
# pyplot
|
| 1244 |
+
else:
|
| 1245 |
+
rcParams['backend'] = backend
|
| 1246 |
+
# if the user has asked for a given backend, do not helpfully
|
| 1247 |
+
# fallback
|
| 1248 |
+
rcParams['backend_fallback'] = False
|
| 1249 |
+
|
| 1250 |
+
|
| 1251 |
+
if os.environ.get('MPLBACKEND'):
|
| 1252 |
+
rcParams['backend'] = os.environ.get('MPLBACKEND')
|
| 1253 |
+
|
| 1254 |
+
|
| 1255 |
+
def get_backend():
|
| 1256 |
+
"""
|
| 1257 |
+
Return the name of the current backend.
|
| 1258 |
+
|
| 1259 |
+
See Also
|
| 1260 |
+
--------
|
| 1261 |
+
matplotlib.use
|
| 1262 |
+
"""
|
| 1263 |
+
return rcParams['backend']
|
| 1264 |
+
|
| 1265 |
+
|
| 1266 |
+
def interactive(b):
|
| 1267 |
+
"""
|
| 1268 |
+
Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`).
|
| 1269 |
+
"""
|
| 1270 |
+
rcParams['interactive'] = b
|
| 1271 |
+
|
| 1272 |
+
|
| 1273 |
+
def is_interactive():
|
| 1274 |
+
"""
|
| 1275 |
+
Return whether to redraw after every plotting command.
|
| 1276 |
+
|
| 1277 |
+
.. note::
|
| 1278 |
+
|
| 1279 |
+
This function is only intended for use in backends. End users should
|
| 1280 |
+
use `.pyplot.isinteractive` instead.
|
| 1281 |
+
"""
|
| 1282 |
+
return rcParams['interactive']
|
| 1283 |
+
|
| 1284 |
+
|
| 1285 |
+
def _init_tests():
|
| 1286 |
+
# The version of FreeType to install locally for running the
|
| 1287 |
+
# tests. This must match the value in `setupext.py`
|
| 1288 |
+
LOCAL_FREETYPE_VERSION = '2.6.1'
|
| 1289 |
+
|
| 1290 |
+
from matplotlib import ft2font
|
| 1291 |
+
if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
|
| 1292 |
+
ft2font.__freetype_build_type__ != 'local'):
|
| 1293 |
+
_log.warning(
|
| 1294 |
+
f"Matplotlib is not built with the correct FreeType version to "
|
| 1295 |
+
f"run tests. Rebuild without setting system_freetype=1 in "
|
| 1296 |
+
f"mplsetup.cfg. Expect many image comparison failures below. "
|
| 1297 |
+
f"Expected freetype version {LOCAL_FREETYPE_VERSION}. "
|
| 1298 |
+
f"Found freetype version {ft2font.__freetype_version__}. "
|
| 1299 |
+
"Freetype build type is {}local".format(
|
| 1300 |
+
"" if ft2font.__freetype_build_type__ == 'local' else "not "))
|
| 1301 |
+
|
| 1302 |
+
|
| 1303 |
+
def _replacer(data, value):
|
| 1304 |
+
"""
|
| 1305 |
+
Either returns ``data[value]`` or passes ``data`` back, converts either to
|
| 1306 |
+
a sequence.
|
| 1307 |
+
"""
|
| 1308 |
+
try:
|
| 1309 |
+
# if key isn't a string don't bother
|
| 1310 |
+
if isinstance(value, str):
|
| 1311 |
+
# try to use __getitem__
|
| 1312 |
+
value = data[value]
|
| 1313 |
+
except Exception:
|
| 1314 |
+
# key does not exist, silently fall back to key
|
| 1315 |
+
pass
|
| 1316 |
+
return sanitize_sequence(value)
|
| 1317 |
+
|
| 1318 |
+
|
| 1319 |
+
def _label_from_arg(y, default_name):
|
| 1320 |
+
try:
|
| 1321 |
+
return y.name
|
| 1322 |
+
except AttributeError:
|
| 1323 |
+
if isinstance(default_name, str):
|
| 1324 |
+
return default_name
|
| 1325 |
+
return None
|
| 1326 |
+
|
| 1327 |
+
|
| 1328 |
+
def _add_data_doc(docstring, replace_names):
|
| 1329 |
+
"""
|
| 1330 |
+
Add documentation for a *data* field to the given docstring.
|
| 1331 |
+
|
| 1332 |
+
Parameters
|
| 1333 |
+
----------
|
| 1334 |
+
docstring : str
|
| 1335 |
+
The input docstring.
|
| 1336 |
+
replace_names : list of str or None
|
| 1337 |
+
The list of parameter names which arguments should be replaced by
|
| 1338 |
+
``data[name]`` (if ``data[name]`` does not throw an exception). If
|
| 1339 |
+
None, replacement is attempted for all arguments.
|
| 1340 |
+
|
| 1341 |
+
Returns
|
| 1342 |
+
-------
|
| 1343 |
+
str
|
| 1344 |
+
The augmented docstring.
|
| 1345 |
+
"""
|
| 1346 |
+
if (docstring is None
|
| 1347 |
+
or replace_names is not None and len(replace_names) == 0):
|
| 1348 |
+
return docstring
|
| 1349 |
+
docstring = inspect.cleandoc(docstring)
|
| 1350 |
+
|
| 1351 |
+
data_doc = ("""\
|
| 1352 |
+
If given, all parameters also accept a string ``s``, which is
|
| 1353 |
+
interpreted as ``data[s]`` (unless this raises an exception)."""
|
| 1354 |
+
if replace_names is None else f"""\
|
| 1355 |
+
If given, the following parameters also accept a string ``s``, which is
|
| 1356 |
+
interpreted as ``data[s]`` (unless this raises an exception):
|
| 1357 |
+
|
| 1358 |
+
{', '.join(map('*{}*'.format, replace_names))}""")
|
| 1359 |
+
# using string replacement instead of formatting has the advantages
|
| 1360 |
+
# 1) simpler indent handling
|
| 1361 |
+
# 2) prevent problems with formatting characters '{', '%' in the docstring
|
| 1362 |
+
if _log.level <= logging.DEBUG:
|
| 1363 |
+
# test_data_parameter_replacement() tests against these log messages
|
| 1364 |
+
# make sure to keep message and test in sync
|
| 1365 |
+
if "data : indexable object, optional" not in docstring:
|
| 1366 |
+
_log.debug("data parameter docstring error: no data parameter")
|
| 1367 |
+
if 'DATA_PARAMETER_PLACEHOLDER' not in docstring:
|
| 1368 |
+
_log.debug("data parameter docstring error: missing placeholder")
|
| 1369 |
+
return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc)
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
def _preprocess_data(func=None, *, replace_names=None, label_namer=None):
|
| 1373 |
+
"""
|
| 1374 |
+
A decorator to add a 'data' kwarg to a function.
|
| 1375 |
+
|
| 1376 |
+
When applied::
|
| 1377 |
+
|
| 1378 |
+
@_preprocess_data()
|
| 1379 |
+
def func(ax, *args, **kwargs): ...
|
| 1380 |
+
|
| 1381 |
+
the signature is modified to ``decorated(ax, *args, data=None, **kwargs)``
|
| 1382 |
+
with the following behavior:
|
| 1383 |
+
|
| 1384 |
+
- if called with ``data=None``, forward the other arguments to ``func``;
|
| 1385 |
+
- otherwise, *data* must be a mapping; for any argument passed in as a
|
| 1386 |
+
string ``name``, replace the argument by ``data[name]`` (if this does not
|
| 1387 |
+
throw an exception), then forward the arguments to ``func``.
|
| 1388 |
+
|
| 1389 |
+
In either case, any argument that is a `MappingView` is also converted to a
|
| 1390 |
+
list.
|
| 1391 |
+
|
| 1392 |
+
Parameters
|
| 1393 |
+
----------
|
| 1394 |
+
replace_names : list of str or None, default: None
|
| 1395 |
+
The list of parameter names for which lookup into *data* should be
|
| 1396 |
+
attempted. If None, replacement is attempted for all arguments.
|
| 1397 |
+
label_namer : str, default: None
|
| 1398 |
+
If set e.g. to "namer" (which must be a kwarg in the function's
|
| 1399 |
+
signature -- not as ``**kwargs``), if the *namer* argument passed in is
|
| 1400 |
+
a (string) key of *data* and no *label* kwarg is passed, then use the
|
| 1401 |
+
(string) value of the *namer* as *label*. ::
|
| 1402 |
+
|
| 1403 |
+
@_preprocess_data(label_namer="foo")
|
| 1404 |
+
def func(foo, label=None): ...
|
| 1405 |
+
|
| 1406 |
+
func("key", data={"key": value})
|
| 1407 |
+
# is equivalent to
|
| 1408 |
+
func.__wrapped__(value, label="key")
|
| 1409 |
+
"""
|
| 1410 |
+
|
| 1411 |
+
if func is None: # Return the actual decorator.
|
| 1412 |
+
return functools.partial(
|
| 1413 |
+
_preprocess_data,
|
| 1414 |
+
replace_names=replace_names, label_namer=label_namer)
|
| 1415 |
+
|
| 1416 |
+
sig = inspect.signature(func)
|
| 1417 |
+
varargs_name = None
|
| 1418 |
+
varkwargs_name = None
|
| 1419 |
+
arg_names = []
|
| 1420 |
+
params = list(sig.parameters.values())
|
| 1421 |
+
for p in params:
|
| 1422 |
+
if p.kind is Parameter.VAR_POSITIONAL:
|
| 1423 |
+
varargs_name = p.name
|
| 1424 |
+
elif p.kind is Parameter.VAR_KEYWORD:
|
| 1425 |
+
varkwargs_name = p.name
|
| 1426 |
+
else:
|
| 1427 |
+
arg_names.append(p.name)
|
| 1428 |
+
data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)
|
| 1429 |
+
if varkwargs_name:
|
| 1430 |
+
params.insert(-1, data_param)
|
| 1431 |
+
else:
|
| 1432 |
+
params.append(data_param)
|
| 1433 |
+
new_sig = sig.replace(parameters=params)
|
| 1434 |
+
arg_names = arg_names[1:] # remove the first "ax" / self arg
|
| 1435 |
+
|
| 1436 |
+
assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
|
| 1437 |
+
"Matplotlib internal error: invalid replace_names ({!r}) for {!r}"
|
| 1438 |
+
.format(replace_names, func.__name__))
|
| 1439 |
+
assert label_namer is None or label_namer in arg_names, (
|
| 1440 |
+
"Matplotlib internal error: invalid label_namer ({!r}) for {!r}"
|
| 1441 |
+
.format(label_namer, func.__name__))
|
| 1442 |
+
|
| 1443 |
+
@functools.wraps(func)
|
| 1444 |
+
def inner(ax, *args, data=None, **kwargs):
|
| 1445 |
+
if data is None:
|
| 1446 |
+
return func(ax, *map(sanitize_sequence, args), **kwargs)
|
| 1447 |
+
|
| 1448 |
+
bound = new_sig.bind(ax, *args, **kwargs)
|
| 1449 |
+
auto_label = (bound.arguments.get(label_namer)
|
| 1450 |
+
or bound.kwargs.get(label_namer))
|
| 1451 |
+
|
| 1452 |
+
for k, v in bound.arguments.items():
|
| 1453 |
+
if k == varkwargs_name:
|
| 1454 |
+
for k1, v1 in v.items():
|
| 1455 |
+
if replace_names is None or k1 in replace_names:
|
| 1456 |
+
v[k1] = _replacer(data, v1)
|
| 1457 |
+
elif k == varargs_name:
|
| 1458 |
+
if replace_names is None:
|
| 1459 |
+
bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)
|
| 1460 |
+
else:
|
| 1461 |
+
if replace_names is None or k in replace_names:
|
| 1462 |
+
bound.arguments[k] = _replacer(data, v)
|
| 1463 |
+
|
| 1464 |
+
new_args = bound.args
|
| 1465 |
+
new_kwargs = bound.kwargs
|
| 1466 |
+
|
| 1467 |
+
args_and_kwargs = {**bound.arguments, **bound.kwargs}
|
| 1468 |
+
if label_namer and "label" not in args_and_kwargs:
|
| 1469 |
+
new_kwargs["label"] = _label_from_arg(
|
| 1470 |
+
args_and_kwargs.get(label_namer), auto_label)
|
| 1471 |
+
|
| 1472 |
+
return func(*new_args, **new_kwargs)
|
| 1473 |
+
|
| 1474 |
+
inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)
|
| 1475 |
+
inner.__signature__ = new_sig
|
| 1476 |
+
return inner
|
| 1477 |
+
|
| 1478 |
+
|
| 1479 |
+
_log.debug('interactive is %s', is_interactive())
|
| 1480 |
+
_log.debug('platform is %s', sys.platform)
|
| 1481 |
+
|
| 1482 |
+
|
| 1483 |
+
# workaround: we must defer colormaps import to after loading rcParams, because
|
| 1484 |
+
# colormap creation depends on rcParams
|
| 1485 |
+
from matplotlib.cm import _colormaps as colormaps
|
| 1486 |
+
from matplotlib.colors import _color_sequences as color_sequences
|
omnilmm/lib/python3.10/site-packages/matplotlib/_afm.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A python interface to Adobe Font Metrics Files.
|
| 3 |
+
|
| 4 |
+
Although a number of other Python implementations exist, and may be more
|
| 5 |
+
complete than this, it was decided not to go with them because they were
|
| 6 |
+
either:
|
| 7 |
+
|
| 8 |
+
1) copyrighted or used a non-BSD compatible license
|
| 9 |
+
2) had too many dependencies and a free standing lib was needed
|
| 10 |
+
3) did more than needed and it was easier to write afresh rather than
|
| 11 |
+
figure out how to get just what was needed.
|
| 12 |
+
|
| 13 |
+
It is pretty easy to use, and has no external dependencies:
|
| 14 |
+
|
| 15 |
+
>>> import matplotlib as mpl
|
| 16 |
+
>>> from pathlib import Path
|
| 17 |
+
>>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm')
|
| 18 |
+
>>>
|
| 19 |
+
>>> from matplotlib.afm import AFM
|
| 20 |
+
>>> with afm_path.open('rb') as fh:
|
| 21 |
+
... afm = AFM(fh)
|
| 22 |
+
>>> afm.string_width_height('What the heck?')
|
| 23 |
+
(6220.0, 694)
|
| 24 |
+
>>> afm.get_fontname()
|
| 25 |
+
'Times-Roman'
|
| 26 |
+
>>> afm.get_kern_dist('A', 'f')
|
| 27 |
+
0
|
| 28 |
+
>>> afm.get_kern_dist('A', 'y')
|
| 29 |
+
-92.0
|
| 30 |
+
>>> afm.get_bbox_char('!')
|
| 31 |
+
[130, -9, 238, 676]
|
| 32 |
+
|
| 33 |
+
As in the Adobe Font Metrics File Format Specification, all dimensions
|
| 34 |
+
are given in units of 1/1000 of the scale factor (point size) of the font
|
| 35 |
+
being used.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from collections import namedtuple
|
| 39 |
+
import logging
|
| 40 |
+
import re
|
| 41 |
+
|
| 42 |
+
from ._mathtext_data import uni2type1
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
_log = logging.getLogger(__name__)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _to_int(x):
|
| 49 |
+
# Some AFM files have floats where we are expecting ints -- there is
|
| 50 |
+
# probably a better way to handle this (support floats, round rather than
|
| 51 |
+
# truncate). But I don't know what the best approach is now and this
|
| 52 |
+
# change to _to_int should at least prevent Matplotlib from crashing on
|
| 53 |
+
# these. JDH (2009-11-06)
|
| 54 |
+
return int(float(x))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _to_float(x):
|
| 58 |
+
# Some AFM files use "," instead of "." as decimal separator -- this
|
| 59 |
+
# shouldn't be ambiguous (unless someone is wicked enough to use "," as
|
| 60 |
+
# thousands separator...).
|
| 61 |
+
if isinstance(x, bytes):
|
| 62 |
+
# Encoding doesn't really matter -- if we have codepoints >127 the call
|
| 63 |
+
# to float() will error anyways.
|
| 64 |
+
x = x.decode('latin-1')
|
| 65 |
+
return float(x.replace(',', '.'))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _to_str(x):
|
| 69 |
+
return x.decode('utf8')
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _to_list_of_ints(s):
|
| 73 |
+
s = s.replace(b',', b' ')
|
| 74 |
+
return [_to_int(val) for val in s.split()]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _to_list_of_floats(s):
|
| 78 |
+
return [_to_float(val) for val in s.split()]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _to_bool(s):
|
| 82 |
+
if s.lower().strip() in (b'false', b'0', b'no'):
|
| 83 |
+
return False
|
| 84 |
+
else:
|
| 85 |
+
return True
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _parse_header(fh):
|
| 89 |
+
"""
|
| 90 |
+
Read the font metrics header (up to the char metrics) and returns
|
| 91 |
+
a dictionary mapping *key* to *val*. *val* will be converted to the
|
| 92 |
+
appropriate python type as necessary; e.g.:
|
| 93 |
+
|
| 94 |
+
* 'False'->False
|
| 95 |
+
* '0'->0
|
| 96 |
+
* '-168 -218 1000 898'-> [-168, -218, 1000, 898]
|
| 97 |
+
|
| 98 |
+
Dictionary keys are
|
| 99 |
+
|
| 100 |
+
StartFontMetrics, FontName, FullName, FamilyName, Weight,
|
| 101 |
+
ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,
|
| 102 |
+
UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,
|
| 103 |
+
XHeight, Ascender, Descender, StartCharMetrics
|
| 104 |
+
"""
|
| 105 |
+
header_converters = {
|
| 106 |
+
b'StartFontMetrics': _to_float,
|
| 107 |
+
b'FontName': _to_str,
|
| 108 |
+
b'FullName': _to_str,
|
| 109 |
+
b'FamilyName': _to_str,
|
| 110 |
+
b'Weight': _to_str,
|
| 111 |
+
b'ItalicAngle': _to_float,
|
| 112 |
+
b'IsFixedPitch': _to_bool,
|
| 113 |
+
b'FontBBox': _to_list_of_ints,
|
| 114 |
+
b'UnderlinePosition': _to_float,
|
| 115 |
+
b'UnderlineThickness': _to_float,
|
| 116 |
+
b'Version': _to_str,
|
| 117 |
+
# Some AFM files have non-ASCII characters (which are not allowed by
|
| 118 |
+
# the spec). Given that there is actually no public API to even access
|
| 119 |
+
# this field, just return it as straight bytes.
|
| 120 |
+
b'Notice': lambda x: x,
|
| 121 |
+
b'EncodingScheme': _to_str,
|
| 122 |
+
b'CapHeight': _to_float, # Is the second version a mistake, or
|
| 123 |
+
b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS
|
| 124 |
+
b'XHeight': _to_float,
|
| 125 |
+
b'Ascender': _to_float,
|
| 126 |
+
b'Descender': _to_float,
|
| 127 |
+
b'StdHW': _to_float,
|
| 128 |
+
b'StdVW': _to_float,
|
| 129 |
+
b'StartCharMetrics': _to_int,
|
| 130 |
+
b'CharacterSet': _to_str,
|
| 131 |
+
b'Characters': _to_int,
|
| 132 |
+
}
|
| 133 |
+
d = {}
|
| 134 |
+
first_line = True
|
| 135 |
+
for line in fh:
|
| 136 |
+
line = line.rstrip()
|
| 137 |
+
if line.startswith(b'Comment'):
|
| 138 |
+
continue
|
| 139 |
+
lst = line.split(b' ', 1)
|
| 140 |
+
key = lst[0]
|
| 141 |
+
if first_line:
|
| 142 |
+
# AFM spec, Section 4: The StartFontMetrics keyword
|
| 143 |
+
# [followed by a version number] must be the first line in
|
| 144 |
+
# the file, and the EndFontMetrics keyword must be the
|
| 145 |
+
# last non-empty line in the file. We just check the
|
| 146 |
+
# first header entry.
|
| 147 |
+
if key != b'StartFontMetrics':
|
| 148 |
+
raise RuntimeError('Not an AFM file')
|
| 149 |
+
first_line = False
|
| 150 |
+
if len(lst) == 2:
|
| 151 |
+
val = lst[1]
|
| 152 |
+
else:
|
| 153 |
+
val = b''
|
| 154 |
+
try:
|
| 155 |
+
converter = header_converters[key]
|
| 156 |
+
except KeyError:
|
| 157 |
+
_log.error('Found an unknown keyword in AFM header (was %r)' % key)
|
| 158 |
+
continue
|
| 159 |
+
try:
|
| 160 |
+
d[key] = converter(val)
|
| 161 |
+
except ValueError:
|
| 162 |
+
_log.error('Value error parsing header in AFM: %s, %s', key, val)
|
| 163 |
+
continue
|
| 164 |
+
if key == b'StartCharMetrics':
|
| 165 |
+
break
|
| 166 |
+
else:
|
| 167 |
+
raise RuntimeError('Bad parse')
|
| 168 |
+
return d
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
CharMetrics = namedtuple('CharMetrics', 'width, name, bbox')
|
| 172 |
+
CharMetrics.__doc__ = """
|
| 173 |
+
Represents the character metrics of a single character.
|
| 174 |
+
|
| 175 |
+
Notes
|
| 176 |
+
-----
|
| 177 |
+
The fields do currently only describe a subset of character metrics
|
| 178 |
+
information defined in the AFM standard.
|
| 179 |
+
"""
|
| 180 |
+
CharMetrics.width.__doc__ = """The character width (WX)."""
|
| 181 |
+
CharMetrics.name.__doc__ = """The character name (N)."""
|
| 182 |
+
CharMetrics.bbox.__doc__ = """
|
| 183 |
+
The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*)."""
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _parse_char_metrics(fh):
|
| 187 |
+
"""
|
| 188 |
+
Parse the given filehandle for character metrics information and return
|
| 189 |
+
the information as dicts.
|
| 190 |
+
|
| 191 |
+
It is assumed that the file cursor is on the line behind
|
| 192 |
+
'StartCharMetrics'.
|
| 193 |
+
|
| 194 |
+
Returns
|
| 195 |
+
-------
|
| 196 |
+
ascii_d : dict
|
| 197 |
+
A mapping "ASCII num of the character" to `.CharMetrics`.
|
| 198 |
+
name_d : dict
|
| 199 |
+
A mapping "character name" to `.CharMetrics`.
|
| 200 |
+
|
| 201 |
+
Notes
|
| 202 |
+
-----
|
| 203 |
+
This function is incomplete per the standard, but thus far parses
|
| 204 |
+
all the sample afm files tried.
|
| 205 |
+
"""
|
| 206 |
+
required_keys = {'C', 'WX', 'N', 'B'}
|
| 207 |
+
|
| 208 |
+
ascii_d = {}
|
| 209 |
+
name_d = {}
|
| 210 |
+
for line in fh:
|
| 211 |
+
# We are defensively letting values be utf8. The spec requires
|
| 212 |
+
# ascii, but there are non-compliant fonts in circulation
|
| 213 |
+
line = _to_str(line.rstrip()) # Convert from byte-literal
|
| 214 |
+
if line.startswith('EndCharMetrics'):
|
| 215 |
+
return ascii_d, name_d
|
| 216 |
+
# Split the metric line into a dictionary, keyed by metric identifiers
|
| 217 |
+
vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s)
|
| 218 |
+
# There may be other metrics present, but only these are needed
|
| 219 |
+
if not required_keys.issubset(vals):
|
| 220 |
+
raise RuntimeError('Bad char metrics line: %s' % line)
|
| 221 |
+
num = _to_int(vals['C'])
|
| 222 |
+
wx = _to_float(vals['WX'])
|
| 223 |
+
name = vals['N']
|
| 224 |
+
bbox = _to_list_of_floats(vals['B'])
|
| 225 |
+
bbox = list(map(int, bbox))
|
| 226 |
+
metrics = CharMetrics(wx, name, bbox)
|
| 227 |
+
# Workaround: If the character name is 'Euro', give it the
|
| 228 |
+
# corresponding character code, according to WinAnsiEncoding (see PDF
|
| 229 |
+
# Reference).
|
| 230 |
+
if name == 'Euro':
|
| 231 |
+
num = 128
|
| 232 |
+
elif name == 'minus':
|
| 233 |
+
num = ord("\N{MINUS SIGN}") # 0x2212
|
| 234 |
+
if num != -1:
|
| 235 |
+
ascii_d[num] = metrics
|
| 236 |
+
name_d[name] = metrics
|
| 237 |
+
raise RuntimeError('Bad parse')
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _parse_kern_pairs(fh):
|
| 241 |
+
"""
|
| 242 |
+
Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and
|
| 243 |
+
values are the kern pair value. For example, a kern pairs line like
|
| 244 |
+
``KPX A y -50``
|
| 245 |
+
|
| 246 |
+
will be represented as::
|
| 247 |
+
|
| 248 |
+
d[ ('A', 'y') ] = -50
|
| 249 |
+
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
line = next(fh)
|
| 253 |
+
if not line.startswith(b'StartKernPairs'):
|
| 254 |
+
raise RuntimeError('Bad start of kern pairs data: %s' % line)
|
| 255 |
+
|
| 256 |
+
d = {}
|
| 257 |
+
for line in fh:
|
| 258 |
+
line = line.rstrip()
|
| 259 |
+
if not line:
|
| 260 |
+
continue
|
| 261 |
+
if line.startswith(b'EndKernPairs'):
|
| 262 |
+
next(fh) # EndKernData
|
| 263 |
+
return d
|
| 264 |
+
vals = line.split()
|
| 265 |
+
if len(vals) != 4 or vals[0] != b'KPX':
|
| 266 |
+
raise RuntimeError('Bad kern pairs line: %s' % line)
|
| 267 |
+
c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3])
|
| 268 |
+
d[(c1, c2)] = val
|
| 269 |
+
raise RuntimeError('Bad kern pairs parse')
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
CompositePart = namedtuple('CompositePart', 'name, dx, dy')
|
| 273 |
+
CompositePart.__doc__ = """
|
| 274 |
+
Represents the information on a composite element of a composite char."""
|
| 275 |
+
CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'."""
|
| 276 |
+
CompositePart.dx.__doc__ = """x-displacement of the part from the origin."""
|
| 277 |
+
CompositePart.dy.__doc__ = """y-displacement of the part from the origin."""
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _parse_composites(fh):
|
| 281 |
+
"""
|
| 282 |
+
Parse the given filehandle for composites information return them as a
|
| 283 |
+
dict.
|
| 284 |
+
|
| 285 |
+
It is assumed that the file cursor is on the line behind 'StartComposites'.
|
| 286 |
+
|
| 287 |
+
Returns
|
| 288 |
+
-------
|
| 289 |
+
dict
|
| 290 |
+
A dict mapping composite character names to a parts list. The parts
|
| 291 |
+
list is a list of `.CompositePart` entries describing the parts of
|
| 292 |
+
the composite.
|
| 293 |
+
|
| 294 |
+
Examples
|
| 295 |
+
--------
|
| 296 |
+
A composite definition line::
|
| 297 |
+
|
| 298 |
+
CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;
|
| 299 |
+
|
| 300 |
+
will be represented as::
|
| 301 |
+
|
| 302 |
+
composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0),
|
| 303 |
+
CompositePart(name='acute', dx=160, dy=170)]
|
| 304 |
+
|
| 305 |
+
"""
|
| 306 |
+
composites = {}
|
| 307 |
+
for line in fh:
|
| 308 |
+
line = line.rstrip()
|
| 309 |
+
if not line:
|
| 310 |
+
continue
|
| 311 |
+
if line.startswith(b'EndComposites'):
|
| 312 |
+
return composites
|
| 313 |
+
vals = line.split(b';')
|
| 314 |
+
cc = vals[0].split()
|
| 315 |
+
name, _num_parts = cc[1], _to_int(cc[2])
|
| 316 |
+
pccParts = []
|
| 317 |
+
for s in vals[1:-1]:
|
| 318 |
+
pcc = s.split()
|
| 319 |
+
part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3]))
|
| 320 |
+
pccParts.append(part)
|
| 321 |
+
composites[name] = pccParts
|
| 322 |
+
|
| 323 |
+
raise RuntimeError('Bad composites parse')
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _parse_optional(fh):
|
| 327 |
+
"""
|
| 328 |
+
Parse the optional fields for kern pair data and composites.
|
| 329 |
+
|
| 330 |
+
Returns
|
| 331 |
+
-------
|
| 332 |
+
kern_data : dict
|
| 333 |
+
A dict containing kerning information. May be empty.
|
| 334 |
+
See `._parse_kern_pairs`.
|
| 335 |
+
composites : dict
|
| 336 |
+
A dict containing composite information. May be empty.
|
| 337 |
+
See `._parse_composites`.
|
| 338 |
+
"""
|
| 339 |
+
optional = {
|
| 340 |
+
b'StartKernData': _parse_kern_pairs,
|
| 341 |
+
b'StartComposites': _parse_composites,
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
d = {b'StartKernData': {},
|
| 345 |
+
b'StartComposites': {}}
|
| 346 |
+
for line in fh:
|
| 347 |
+
line = line.rstrip()
|
| 348 |
+
if not line:
|
| 349 |
+
continue
|
| 350 |
+
key = line.split()[0]
|
| 351 |
+
|
| 352 |
+
if key in optional:
|
| 353 |
+
d[key] = optional[key](fh)
|
| 354 |
+
|
| 355 |
+
return d[b'StartKernData'], d[b'StartComposites']
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class AFM:
|
| 359 |
+
|
| 360 |
+
def __init__(self, fh):
|
| 361 |
+
"""Parse the AFM file in file object *fh*."""
|
| 362 |
+
self._header = _parse_header(fh)
|
| 363 |
+
self._metrics, self._metrics_by_name = _parse_char_metrics(fh)
|
| 364 |
+
self._kern, self._composite = _parse_optional(fh)
|
| 365 |
+
|
| 366 |
+
def get_bbox_char(self, c, isord=False):
|
| 367 |
+
if not isord:
|
| 368 |
+
c = ord(c)
|
| 369 |
+
return self._metrics[c].bbox
|
| 370 |
+
|
| 371 |
+
def string_width_height(self, s):
|
| 372 |
+
"""
|
| 373 |
+
Return the string width (including kerning) and string height
|
| 374 |
+
as a (*w*, *h*) tuple.
|
| 375 |
+
"""
|
| 376 |
+
if not len(s):
|
| 377 |
+
return 0, 0
|
| 378 |
+
total_width = 0
|
| 379 |
+
namelast = None
|
| 380 |
+
miny = 1e9
|
| 381 |
+
maxy = 0
|
| 382 |
+
for c in s:
|
| 383 |
+
if c == '\n':
|
| 384 |
+
continue
|
| 385 |
+
wx, name, bbox = self._metrics[ord(c)]
|
| 386 |
+
|
| 387 |
+
total_width += wx + self._kern.get((namelast, name), 0)
|
| 388 |
+
l, b, w, h = bbox
|
| 389 |
+
miny = min(miny, b)
|
| 390 |
+
maxy = max(maxy, b + h)
|
| 391 |
+
|
| 392 |
+
namelast = name
|
| 393 |
+
|
| 394 |
+
return total_width, maxy - miny
|
| 395 |
+
|
| 396 |
+
def get_str_bbox_and_descent(self, s):
|
| 397 |
+
"""Return the string bounding box and the maximal descent."""
|
| 398 |
+
if not len(s):
|
| 399 |
+
return 0, 0, 0, 0, 0
|
| 400 |
+
total_width = 0
|
| 401 |
+
namelast = None
|
| 402 |
+
miny = 1e9
|
| 403 |
+
maxy = 0
|
| 404 |
+
left = 0
|
| 405 |
+
if not isinstance(s, str):
|
| 406 |
+
s = _to_str(s)
|
| 407 |
+
for c in s:
|
| 408 |
+
if c == '\n':
|
| 409 |
+
continue
|
| 410 |
+
name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
|
| 411 |
+
try:
|
| 412 |
+
wx, _, bbox = self._metrics_by_name[name]
|
| 413 |
+
except KeyError:
|
| 414 |
+
name = 'question'
|
| 415 |
+
wx, _, bbox = self._metrics_by_name[name]
|
| 416 |
+
total_width += wx + self._kern.get((namelast, name), 0)
|
| 417 |
+
l, b, w, h = bbox
|
| 418 |
+
left = min(left, l)
|
| 419 |
+
miny = min(miny, b)
|
| 420 |
+
maxy = max(maxy, b + h)
|
| 421 |
+
|
| 422 |
+
namelast = name
|
| 423 |
+
|
| 424 |
+
return left, miny, total_width, maxy - miny, -miny
|
| 425 |
+
|
| 426 |
+
def get_str_bbox(self, s):
|
| 427 |
+
"""Return the string bounding box."""
|
| 428 |
+
return self.get_str_bbox_and_descent(s)[:4]
|
| 429 |
+
|
| 430 |
+
def get_name_char(self, c, isord=False):
|
| 431 |
+
"""Get the name of the character, i.e., ';' is 'semicolon'."""
|
| 432 |
+
if not isord:
|
| 433 |
+
c = ord(c)
|
| 434 |
+
return self._metrics[c].name
|
| 435 |
+
|
| 436 |
+
def get_width_char(self, c, isord=False):
|
| 437 |
+
"""
|
| 438 |
+
Get the width of the character from the character metric WX field.
|
| 439 |
+
"""
|
| 440 |
+
if not isord:
|
| 441 |
+
c = ord(c)
|
| 442 |
+
return self._metrics[c].width
|
| 443 |
+
|
| 444 |
+
def get_width_from_char_name(self, name):
|
| 445 |
+
"""Get the width of the character from a type1 character name."""
|
| 446 |
+
return self._metrics_by_name[name].width
|
| 447 |
+
|
| 448 |
+
def get_height_char(self, c, isord=False):
|
| 449 |
+
"""Get the bounding box (ink) height of character *c* (space is 0)."""
|
| 450 |
+
if not isord:
|
| 451 |
+
c = ord(c)
|
| 452 |
+
return self._metrics[c].bbox[-1]
|
| 453 |
+
|
| 454 |
+
def get_kern_dist(self, c1, c2):
|
| 455 |
+
"""
|
| 456 |
+
Return the kerning pair distance (possibly 0) for chars *c1* and *c2*.
|
| 457 |
+
"""
|
| 458 |
+
name1, name2 = self.get_name_char(c1), self.get_name_char(c2)
|
| 459 |
+
return self.get_kern_dist_from_name(name1, name2)
|
| 460 |
+
|
| 461 |
+
def get_kern_dist_from_name(self, name1, name2):
|
| 462 |
+
"""
|
| 463 |
+
Return the kerning pair distance (possibly 0) for chars
|
| 464 |
+
*name1* and *name2*.
|
| 465 |
+
"""
|
| 466 |
+
return self._kern.get((name1, name2), 0)
|
| 467 |
+
|
| 468 |
+
def get_fontname(self):
|
| 469 |
+
"""Return the font name, e.g., 'Times-Roman'."""
|
| 470 |
+
return self._header[b'FontName']
|
| 471 |
+
|
| 472 |
+
@property
|
| 473 |
+
def postscript_name(self): # For consistency with FT2Font.
|
| 474 |
+
return self.get_fontname()
|
| 475 |
+
|
| 476 |
+
def get_fullname(self):
|
| 477 |
+
"""Return the font full name, e.g., 'Times-Roman'."""
|
| 478 |
+
name = self._header.get(b'FullName')
|
| 479 |
+
if name is None: # use FontName as a substitute
|
| 480 |
+
name = self._header[b'FontName']
|
| 481 |
+
return name
|
| 482 |
+
|
| 483 |
+
def get_familyname(self):
|
| 484 |
+
"""Return the font family name, e.g., 'Times'."""
|
| 485 |
+
name = self._header.get(b'FamilyName')
|
| 486 |
+
if name is not None:
|
| 487 |
+
return name
|
| 488 |
+
|
| 489 |
+
# FamilyName not specified so we'll make a guess
|
| 490 |
+
name = self.get_fullname()
|
| 491 |
+
extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
|
| 492 |
+
r'light|ultralight|extra|condensed))+$')
|
| 493 |
+
return re.sub(extras, '', name)
|
| 494 |
+
|
| 495 |
+
@property
|
| 496 |
+
def family_name(self):
|
| 497 |
+
"""The font family name, e.g., 'Times'."""
|
| 498 |
+
return self.get_familyname()
|
| 499 |
+
|
| 500 |
+
def get_weight(self):
|
| 501 |
+
"""Return the font weight, e.g., 'Bold' or 'Roman'."""
|
| 502 |
+
return self._header[b'Weight']
|
| 503 |
+
|
| 504 |
+
def get_angle(self):
|
| 505 |
+
"""Return the fontangle as float."""
|
| 506 |
+
return self._header[b'ItalicAngle']
|
| 507 |
+
|
| 508 |
+
def get_capheight(self):
|
| 509 |
+
"""Return the cap height as float."""
|
| 510 |
+
return self._header[b'CapHeight']
|
| 511 |
+
|
| 512 |
+
def get_xheight(self):
|
| 513 |
+
"""Return the xheight as float."""
|
| 514 |
+
return self._header[b'XHeight']
|
| 515 |
+
|
| 516 |
+
def get_underline_thickness(self):
|
| 517 |
+
"""Return the underline thickness as float."""
|
| 518 |
+
return self._header[b'UnderlineThickness']
|
| 519 |
+
|
| 520 |
+
def get_horizontal_stem_width(self):
|
| 521 |
+
"""
|
| 522 |
+
Return the standard horizontal stem width as float, or *None* if
|
| 523 |
+
not specified in AFM file.
|
| 524 |
+
"""
|
| 525 |
+
return self._header.get(b'StdHW', None)
|
| 526 |
+
|
| 527 |
+
def get_vertical_stem_width(self):
|
| 528 |
+
"""
|
| 529 |
+
Return the standard vertical stem width as float, or *None* if
|
| 530 |
+
not specified in AFM file.
|
| 531 |
+
"""
|
| 532 |
+
return self._header.get(b'StdVW', None)
|
omnilmm/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (30.4 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A module for parsing and generating `fontconfig patterns`_.
|
| 3 |
+
|
| 4 |
+
.. _fontconfig patterns:
|
| 5 |
+
https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
# This class logically belongs in `matplotlib.font_manager`, but placing it
|
| 9 |
+
# there would have created cyclical dependency problems, because it also needs
|
| 10 |
+
# to be available from `matplotlib.rcsetup` (for parsing matplotlibrc files).
|
| 11 |
+
|
| 12 |
+
from functools import lru_cache, partial
|
| 13 |
+
import re
|
| 14 |
+
|
| 15 |
+
from pyparsing import (
|
| 16 |
+
Group, Optional, ParseException, Regex, StringEnd, Suppress, ZeroOrMore)
|
| 17 |
+
|
| 18 |
+
from matplotlib import _api
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
_family_punc = r'\\\-:,'
|
| 22 |
+
_family_unescape = partial(re.compile(r'\\(?=[%s])' % _family_punc).sub, '')
|
| 23 |
+
_family_escape = partial(re.compile(r'(?=[%s])' % _family_punc).sub, r'\\')
|
| 24 |
+
_value_punc = r'\\=_:,'
|
| 25 |
+
_value_unescape = partial(re.compile(r'\\(?=[%s])' % _value_punc).sub, '')
|
| 26 |
+
_value_escape = partial(re.compile(r'(?=[%s])' % _value_punc).sub, r'\\')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
_CONSTANTS = {
|
| 30 |
+
'thin': ('weight', 'light'),
|
| 31 |
+
'extralight': ('weight', 'light'),
|
| 32 |
+
'ultralight': ('weight', 'light'),
|
| 33 |
+
'light': ('weight', 'light'),
|
| 34 |
+
'book': ('weight', 'book'),
|
| 35 |
+
'regular': ('weight', 'regular'),
|
| 36 |
+
'normal': ('weight', 'normal'),
|
| 37 |
+
'medium': ('weight', 'medium'),
|
| 38 |
+
'demibold': ('weight', 'demibold'),
|
| 39 |
+
'semibold': ('weight', 'semibold'),
|
| 40 |
+
'bold': ('weight', 'bold'),
|
| 41 |
+
'extrabold': ('weight', 'extra bold'),
|
| 42 |
+
'black': ('weight', 'black'),
|
| 43 |
+
'heavy': ('weight', 'heavy'),
|
| 44 |
+
'roman': ('slant', 'normal'),
|
| 45 |
+
'italic': ('slant', 'italic'),
|
| 46 |
+
'oblique': ('slant', 'oblique'),
|
| 47 |
+
'ultracondensed': ('width', 'ultra-condensed'),
|
| 48 |
+
'extracondensed': ('width', 'extra-condensed'),
|
| 49 |
+
'condensed': ('width', 'condensed'),
|
| 50 |
+
'semicondensed': ('width', 'semi-condensed'),
|
| 51 |
+
'expanded': ('width', 'expanded'),
|
| 52 |
+
'extraexpanded': ('width', 'extra-expanded'),
|
| 53 |
+
'ultraexpanded': ('width', 'ultra-expanded'),
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@lru_cache # The parser instance is a singleton.
|
| 58 |
+
def _make_fontconfig_parser():
|
| 59 |
+
def comma_separated(elem):
|
| 60 |
+
return elem + ZeroOrMore(Suppress(",") + elem)
|
| 61 |
+
|
| 62 |
+
family = Regex(r"([^%s]|(\\[%s]))*" % (_family_punc, _family_punc))
|
| 63 |
+
size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)")
|
| 64 |
+
name = Regex(r"[a-z]+")
|
| 65 |
+
value = Regex(r"([^%s]|(\\[%s]))*" % (_value_punc, _value_punc))
|
| 66 |
+
# replace trailing `| name` by oneOf(_CONSTANTS) in mpl 3.9.
|
| 67 |
+
prop = Group((name + Suppress("=") + comma_separated(value)) | name)
|
| 68 |
+
return (
|
| 69 |
+
Optional(comma_separated(family)("families"))
|
| 70 |
+
+ Optional("-" + comma_separated(size)("sizes"))
|
| 71 |
+
+ ZeroOrMore(":" + prop("properties*"))
|
| 72 |
+
+ StringEnd()
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# `parse_fontconfig_pattern` is a bottleneck during the tests because it is
|
| 77 |
+
# repeatedly called when the rcParams are reset (to validate the default
|
| 78 |
+
# fonts). In practice, the cache size doesn't grow beyond a few dozen entries
|
| 79 |
+
# during the test suite.
|
| 80 |
+
@lru_cache
|
| 81 |
+
def parse_fontconfig_pattern(pattern):
|
| 82 |
+
"""
|
| 83 |
+
Parse a fontconfig *pattern* into a dict that can initialize a
|
| 84 |
+
`.font_manager.FontProperties` object.
|
| 85 |
+
"""
|
| 86 |
+
parser = _make_fontconfig_parser()
|
| 87 |
+
try:
|
| 88 |
+
parse = parser.parseString(pattern)
|
| 89 |
+
except ParseException as err:
|
| 90 |
+
# explain becomes a plain method on pyparsing 3 (err.explain(0)).
|
| 91 |
+
raise ValueError("\n" + ParseException.explain(err, 0)) from None
|
| 92 |
+
parser.resetCache()
|
| 93 |
+
props = {}
|
| 94 |
+
if "families" in parse:
|
| 95 |
+
props["family"] = [*map(_family_unescape, parse["families"])]
|
| 96 |
+
if "sizes" in parse:
|
| 97 |
+
props["size"] = [*parse["sizes"]]
|
| 98 |
+
for prop in parse.get("properties", []):
|
| 99 |
+
if len(prop) == 1:
|
| 100 |
+
if prop[0] not in _CONSTANTS:
|
| 101 |
+
_api.warn_deprecated(
|
| 102 |
+
"3.7", message=f"Support for unknown constants "
|
| 103 |
+
f"({prop[0]!r}) is deprecated since %(since)s and "
|
| 104 |
+
f"will be removed %(removal)s.")
|
| 105 |
+
continue
|
| 106 |
+
prop = _CONSTANTS[prop[0]]
|
| 107 |
+
k, *v = prop
|
| 108 |
+
props.setdefault(k, []).extend(map(_value_unescape, v))
|
| 109 |
+
return props
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def generate_fontconfig_pattern(d):
|
| 113 |
+
"""Convert a `.FontProperties` to a fontconfig pattern string."""
|
| 114 |
+
kvs = [(k, getattr(d, f"get_{k}")())
|
| 115 |
+
for k in ["style", "variant", "weight", "stretch", "file", "size"]]
|
| 116 |
+
# Families is given first without a leading keyword. Other entries (which
|
| 117 |
+
# are necessarily scalar) are given as key=value, skipping Nones.
|
| 118 |
+
return (",".join(_family_escape(f) for f in d.get_family())
|
| 119 |
+
+ "".join(f":{k}={_value_escape(str(v))}"
|
| 120 |
+
for k, v in kvs if v is not None))
|
omnilmm/lib/python3.10/site-packages/matplotlib/_internal_utils.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Internal debugging utilities, that are not expected to be used in the rest of
|
| 3 |
+
the codebase.
|
| 4 |
+
|
| 5 |
+
WARNING: Code in this module may change without prior notice!
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from io import StringIO
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import subprocess
|
| 11 |
+
|
| 12 |
+
from matplotlib.transforms import TransformNode
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def graphviz_dump_transform(transform, dest, *, highlight=None):
|
| 16 |
+
"""
|
| 17 |
+
Generate a graphical representation of the transform tree for *transform*
|
| 18 |
+
using the :program:`dot` program (which this function depends on). The
|
| 19 |
+
output format (png, dot, etc.) is determined from the suffix of *dest*.
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
transform : `~matplotlib.transform.Transform`
|
| 24 |
+
The represented transform.
|
| 25 |
+
dest : str
|
| 26 |
+
Output filename. The extension must be one of the formats supported
|
| 27 |
+
by :program:`dot`, e.g. png, svg, dot, ...
|
| 28 |
+
(see https://www.graphviz.org/doc/info/output.html).
|
| 29 |
+
highlight : list of `~matplotlib.transform.Transform` or None
|
| 30 |
+
The transforms in the tree to be drawn in bold.
|
| 31 |
+
If *None*, *transform* is highlighted.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
if highlight is None:
|
| 35 |
+
highlight = [transform]
|
| 36 |
+
seen = set()
|
| 37 |
+
|
| 38 |
+
def recurse(root, buf):
|
| 39 |
+
if id(root) in seen:
|
| 40 |
+
return
|
| 41 |
+
seen.add(id(root))
|
| 42 |
+
props = {}
|
| 43 |
+
label = type(root).__name__
|
| 44 |
+
if root._invalid:
|
| 45 |
+
label = f'[{label}]'
|
| 46 |
+
if root in highlight:
|
| 47 |
+
props['style'] = 'bold'
|
| 48 |
+
props['shape'] = 'box'
|
| 49 |
+
props['label'] = '"%s"' % label
|
| 50 |
+
props = ' '.join(map('{0[0]}={0[1]}'.format, props.items()))
|
| 51 |
+
buf.write(f'{id(root)} [{props}];\n')
|
| 52 |
+
for key, val in vars(root).items():
|
| 53 |
+
if isinstance(val, TransformNode) and id(root) in val._parents:
|
| 54 |
+
buf.write(f'"{id(root)}" -> "{id(val)}" '
|
| 55 |
+
f'[label="{key}", fontsize=10];\n')
|
| 56 |
+
recurse(val, buf)
|
| 57 |
+
|
| 58 |
+
buf = StringIO()
|
| 59 |
+
buf.write('digraph G {\n')
|
| 60 |
+
recurse(transform, buf)
|
| 61 |
+
buf.write('}\n')
|
| 62 |
+
subprocess.run(
|
| 63 |
+
['dot', '-T', Path(dest).suffix[1:], '-o', dest],
|
| 64 |
+
input=buf.getvalue().encode('utf-8'), check=True)
|
omnilmm/lib/python3.10/site-packages/matplotlib/_layoutgrid.py
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A layoutgrid is a nrows by ncols set of boxes, meant to be used by
|
| 3 |
+
`._constrained_layout`, each box is analogous to a subplotspec element of
|
| 4 |
+
a gridspec.
|
| 5 |
+
|
| 6 |
+
Each box is defined by left[ncols], right[ncols], bottom[nrows] and top[nrows],
|
| 7 |
+
and by two editable margins for each side. The main margin gets its value
|
| 8 |
+
set by the size of ticklabels, titles, etc on each axes that is in the figure.
|
| 9 |
+
The outer margin is the padding around the axes, and space for any
|
| 10 |
+
colorbars.
|
| 11 |
+
|
| 12 |
+
The "inner" widths and heights of these boxes are then constrained to be the
|
| 13 |
+
same (relative the values of `width_ratios[ncols]` and `height_ratios[nrows]`).
|
| 14 |
+
|
| 15 |
+
The layoutgrid is then constrained to be contained within a parent layoutgrid,
|
| 16 |
+
its column(s) and row(s) specified when it is created.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import itertools
|
| 20 |
+
import kiwisolver as kiwi
|
| 21 |
+
import logging
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
import matplotlib as mpl
|
| 25 |
+
import matplotlib.patches as mpatches
|
| 26 |
+
from matplotlib.transforms import Bbox
|
| 27 |
+
|
| 28 |
+
_log = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class LayoutGrid:
|
| 32 |
+
"""
|
| 33 |
+
Analogous to a gridspec, and contained in another LayoutGrid.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self, parent=None, parent_pos=(0, 0),
|
| 37 |
+
parent_inner=False, name='', ncols=1, nrows=1,
|
| 38 |
+
h_pad=None, w_pad=None, width_ratios=None,
|
| 39 |
+
height_ratios=None):
|
| 40 |
+
Variable = kiwi.Variable
|
| 41 |
+
self.parent_pos = parent_pos
|
| 42 |
+
self.parent_inner = parent_inner
|
| 43 |
+
self.name = name + seq_id()
|
| 44 |
+
if isinstance(parent, LayoutGrid):
|
| 45 |
+
self.name = f'{parent.name}.{self.name}'
|
| 46 |
+
self.nrows = nrows
|
| 47 |
+
self.ncols = ncols
|
| 48 |
+
self.height_ratios = np.atleast_1d(height_ratios)
|
| 49 |
+
if height_ratios is None:
|
| 50 |
+
self.height_ratios = np.ones(nrows)
|
| 51 |
+
self.width_ratios = np.atleast_1d(width_ratios)
|
| 52 |
+
if width_ratios is None:
|
| 53 |
+
self.width_ratios = np.ones(ncols)
|
| 54 |
+
|
| 55 |
+
sn = self.name + '_'
|
| 56 |
+
if not isinstance(parent, LayoutGrid):
|
| 57 |
+
# parent can be a rect if not a LayoutGrid
|
| 58 |
+
# allows specifying a rectangle to contain the layout.
|
| 59 |
+
self.solver = kiwi.Solver()
|
| 60 |
+
else:
|
| 61 |
+
parent.add_child(self, *parent_pos)
|
| 62 |
+
self.solver = parent.solver
|
| 63 |
+
# keep track of artist associated w/ this layout. Can be none
|
| 64 |
+
self.artists = np.empty((nrows, ncols), dtype=object)
|
| 65 |
+
self.children = np.empty((nrows, ncols), dtype=object)
|
| 66 |
+
|
| 67 |
+
self.margins = {}
|
| 68 |
+
self.margin_vals = {}
|
| 69 |
+
# all the boxes in each column share the same left/right margins:
|
| 70 |
+
for todo in ['left', 'right', 'leftcb', 'rightcb']:
|
| 71 |
+
# track the value so we can change only if a margin is larger
|
| 72 |
+
# than the current value
|
| 73 |
+
self.margin_vals[todo] = np.zeros(ncols)
|
| 74 |
+
|
| 75 |
+
sol = self.solver
|
| 76 |
+
|
| 77 |
+
self.lefts = [Variable(f'{sn}lefts[{i}]') for i in range(ncols)]
|
| 78 |
+
self.rights = [Variable(f'{sn}rights[{i}]') for i in range(ncols)]
|
| 79 |
+
for todo in ['left', 'right', 'leftcb', 'rightcb']:
|
| 80 |
+
self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')
|
| 81 |
+
for i in range(ncols)]
|
| 82 |
+
for i in range(ncols):
|
| 83 |
+
sol.addEditVariable(self.margins[todo][i], 'strong')
|
| 84 |
+
|
| 85 |
+
for todo in ['bottom', 'top', 'bottomcb', 'topcb']:
|
| 86 |
+
self.margins[todo] = np.empty((nrows), dtype=object)
|
| 87 |
+
self.margin_vals[todo] = np.zeros(nrows)
|
| 88 |
+
|
| 89 |
+
self.bottoms = [Variable(f'{sn}bottoms[{i}]') for i in range(nrows)]
|
| 90 |
+
self.tops = [Variable(f'{sn}tops[{i}]') for i in range(nrows)]
|
| 91 |
+
for todo in ['bottom', 'top', 'bottomcb', 'topcb']:
|
| 92 |
+
self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')
|
| 93 |
+
for i in range(nrows)]
|
| 94 |
+
for i in range(nrows):
|
| 95 |
+
sol.addEditVariable(self.margins[todo][i], 'strong')
|
| 96 |
+
|
| 97 |
+
# set these margins to zero by default. They will be edited as
|
| 98 |
+
# children are filled.
|
| 99 |
+
self.reset_margins()
|
| 100 |
+
self.add_constraints(parent)
|
| 101 |
+
|
| 102 |
+
self.h_pad = h_pad
|
| 103 |
+
self.w_pad = w_pad
|
| 104 |
+
|
| 105 |
+
def __repr__(self):
|
| 106 |
+
str = f'LayoutBox: {self.name:25s} {self.nrows}x{self.ncols},\n'
|
| 107 |
+
for i in range(self.nrows):
|
| 108 |
+
for j in range(self.ncols):
|
| 109 |
+
str += f'{i}, {j}: '\
|
| 110 |
+
f'L{self.lefts[j].value():1.3f}, ' \
|
| 111 |
+
f'B{self.bottoms[i].value():1.3f}, ' \
|
| 112 |
+
f'R{self.rights[j].value():1.3f}, ' \
|
| 113 |
+
f'T{self.tops[i].value():1.3f}, ' \
|
| 114 |
+
f'ML{self.margins["left"][j].value():1.3f}, ' \
|
| 115 |
+
f'MR{self.margins["right"][j].value():1.3f}, ' \
|
| 116 |
+
f'MB{self.margins["bottom"][i].value():1.3f}, ' \
|
| 117 |
+
f'MT{self.margins["top"][i].value():1.3f}, \n'
|
| 118 |
+
return str
|
| 119 |
+
|
| 120 |
+
def reset_margins(self):
|
| 121 |
+
"""
|
| 122 |
+
Reset all the margins to zero. Must do this after changing
|
| 123 |
+
figure size, for instance, because the relative size of the
|
| 124 |
+
axes labels etc changes.
|
| 125 |
+
"""
|
| 126 |
+
for todo in ['left', 'right', 'bottom', 'top',
|
| 127 |
+
'leftcb', 'rightcb', 'bottomcb', 'topcb']:
|
| 128 |
+
self.edit_margins(todo, 0.0)
|
| 129 |
+
|
| 130 |
+
def add_constraints(self, parent):
|
| 131 |
+
# define self-consistent constraints
|
| 132 |
+
self.hard_constraints()
|
| 133 |
+
# define relationship with parent layoutgrid:
|
| 134 |
+
self.parent_constraints(parent)
|
| 135 |
+
# define relative widths of the grid cells to each other
|
| 136 |
+
# and stack horizontally and vertically.
|
| 137 |
+
self.grid_constraints()
|
| 138 |
+
|
| 139 |
+
def hard_constraints(self):
|
| 140 |
+
"""
|
| 141 |
+
These are the redundant constraints, plus ones that make the
|
| 142 |
+
rest of the code easier.
|
| 143 |
+
"""
|
| 144 |
+
for i in range(self.ncols):
|
| 145 |
+
hc = [self.rights[i] >= self.lefts[i],
|
| 146 |
+
(self.rights[i] - self.margins['right'][i] -
|
| 147 |
+
self.margins['rightcb'][i] >=
|
| 148 |
+
self.lefts[i] - self.margins['left'][i] -
|
| 149 |
+
self.margins['leftcb'][i])
|
| 150 |
+
]
|
| 151 |
+
for c in hc:
|
| 152 |
+
self.solver.addConstraint(c | 'required')
|
| 153 |
+
|
| 154 |
+
for i in range(self.nrows):
|
| 155 |
+
hc = [self.tops[i] >= self.bottoms[i],
|
| 156 |
+
(self.tops[i] - self.margins['top'][i] -
|
| 157 |
+
self.margins['topcb'][i] >=
|
| 158 |
+
self.bottoms[i] - self.margins['bottom'][i] -
|
| 159 |
+
self.margins['bottomcb'][i])
|
| 160 |
+
]
|
| 161 |
+
for c in hc:
|
| 162 |
+
self.solver.addConstraint(c | 'required')
|
| 163 |
+
|
| 164 |
+
def add_child(self, child, i=0, j=0):
|
| 165 |
+
# np.ix_ returns the cross product of i and j indices
|
| 166 |
+
self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child
|
| 167 |
+
|
| 168 |
+
def parent_constraints(self, parent):
|
| 169 |
+
# constraints that are due to the parent...
|
| 170 |
+
# i.e. the first column's left is equal to the
|
| 171 |
+
# parent's left, the last column right equal to the
|
| 172 |
+
# parent's right...
|
| 173 |
+
if not isinstance(parent, LayoutGrid):
|
| 174 |
+
# specify a rectangle in figure coordinates
|
| 175 |
+
hc = [self.lefts[0] == parent[0],
|
| 176 |
+
self.rights[-1] == parent[0] + parent[2],
|
| 177 |
+
# top and bottom reversed order...
|
| 178 |
+
self.tops[0] == parent[1] + parent[3],
|
| 179 |
+
self.bottoms[-1] == parent[1]]
|
| 180 |
+
else:
|
| 181 |
+
rows, cols = self.parent_pos
|
| 182 |
+
rows = np.atleast_1d(rows)
|
| 183 |
+
cols = np.atleast_1d(cols)
|
| 184 |
+
|
| 185 |
+
left = parent.lefts[cols[0]]
|
| 186 |
+
right = parent.rights[cols[-1]]
|
| 187 |
+
top = parent.tops[rows[0]]
|
| 188 |
+
bottom = parent.bottoms[rows[-1]]
|
| 189 |
+
if self.parent_inner:
|
| 190 |
+
# the layout grid is contained inside the inner
|
| 191 |
+
# grid of the parent.
|
| 192 |
+
left += parent.margins['left'][cols[0]]
|
| 193 |
+
left += parent.margins['leftcb'][cols[0]]
|
| 194 |
+
right -= parent.margins['right'][cols[-1]]
|
| 195 |
+
right -= parent.margins['rightcb'][cols[-1]]
|
| 196 |
+
top -= parent.margins['top'][rows[0]]
|
| 197 |
+
top -= parent.margins['topcb'][rows[0]]
|
| 198 |
+
bottom += parent.margins['bottom'][rows[-1]]
|
| 199 |
+
bottom += parent.margins['bottomcb'][rows[-1]]
|
| 200 |
+
hc = [self.lefts[0] == left,
|
| 201 |
+
self.rights[-1] == right,
|
| 202 |
+
# from top to bottom
|
| 203 |
+
self.tops[0] == top,
|
| 204 |
+
self.bottoms[-1] == bottom]
|
| 205 |
+
for c in hc:
|
| 206 |
+
self.solver.addConstraint(c | 'required')
|
| 207 |
+
|
| 208 |
+
def grid_constraints(self):
|
| 209 |
+
# constrain the ratio of the inner part of the grids
|
| 210 |
+
# to be the same (relative to width_ratios)
|
| 211 |
+
|
| 212 |
+
# constrain widths:
|
| 213 |
+
w = (self.rights[0] - self.margins['right'][0] -
|
| 214 |
+
self.margins['rightcb'][0])
|
| 215 |
+
w = (w - self.lefts[0] - self.margins['left'][0] -
|
| 216 |
+
self.margins['leftcb'][0])
|
| 217 |
+
w0 = w / self.width_ratios[0]
|
| 218 |
+
# from left to right
|
| 219 |
+
for i in range(1, self.ncols):
|
| 220 |
+
w = (self.rights[i] - self.margins['right'][i] -
|
| 221 |
+
self.margins['rightcb'][i])
|
| 222 |
+
w = (w - self.lefts[i] - self.margins['left'][i] -
|
| 223 |
+
self.margins['leftcb'][i])
|
| 224 |
+
c = (w == w0 * self.width_ratios[i])
|
| 225 |
+
self.solver.addConstraint(c | 'strong')
|
| 226 |
+
# constrain the grid cells to be directly next to each other.
|
| 227 |
+
c = (self.rights[i - 1] == self.lefts[i])
|
| 228 |
+
self.solver.addConstraint(c | 'strong')
|
| 229 |
+
|
| 230 |
+
# constrain heights:
|
| 231 |
+
h = self.tops[0] - self.margins['top'][0] - self.margins['topcb'][0]
|
| 232 |
+
h = (h - self.bottoms[0] - self.margins['bottom'][0] -
|
| 233 |
+
self.margins['bottomcb'][0])
|
| 234 |
+
h0 = h / self.height_ratios[0]
|
| 235 |
+
# from top to bottom:
|
| 236 |
+
for i in range(1, self.nrows):
|
| 237 |
+
h = (self.tops[i] - self.margins['top'][i] -
|
| 238 |
+
self.margins['topcb'][i])
|
| 239 |
+
h = (h - self.bottoms[i] - self.margins['bottom'][i] -
|
| 240 |
+
self.margins['bottomcb'][i])
|
| 241 |
+
c = (h == h0 * self.height_ratios[i])
|
| 242 |
+
self.solver.addConstraint(c | 'strong')
|
| 243 |
+
# constrain the grid cells to be directly above each other.
|
| 244 |
+
c = (self.bottoms[i - 1] == self.tops[i])
|
| 245 |
+
self.solver.addConstraint(c | 'strong')
|
| 246 |
+
|
| 247 |
+
# Margin editing: The margins are variable and meant to
|
| 248 |
+
# contain things of a fixed size like axes labels, tick labels, titles
|
| 249 |
+
# etc
|
| 250 |
+
def edit_margin(self, todo, size, cell):
|
| 251 |
+
"""
|
| 252 |
+
Change the size of the margin for one cell.
|
| 253 |
+
|
| 254 |
+
Parameters
|
| 255 |
+
----------
|
| 256 |
+
todo : string (one of 'left', 'right', 'bottom', 'top')
|
| 257 |
+
margin to alter.
|
| 258 |
+
|
| 259 |
+
size : float
|
| 260 |
+
Size of the margin. If it is larger than the existing minimum it
|
| 261 |
+
updates the margin size. Fraction of figure size.
|
| 262 |
+
|
| 263 |
+
cell : int
|
| 264 |
+
Cell column or row to edit.
|
| 265 |
+
"""
|
| 266 |
+
self.solver.suggestValue(self.margins[todo][cell], size)
|
| 267 |
+
self.margin_vals[todo][cell] = size
|
| 268 |
+
|
| 269 |
+
def edit_margin_min(self, todo, size, cell=0):
|
| 270 |
+
"""
|
| 271 |
+
Change the minimum size of the margin for one cell.
|
| 272 |
+
|
| 273 |
+
Parameters
|
| 274 |
+
----------
|
| 275 |
+
todo : string (one of 'left', 'right', 'bottom', 'top')
|
| 276 |
+
margin to alter.
|
| 277 |
+
|
| 278 |
+
size : float
|
| 279 |
+
Minimum size of the margin . If it is larger than the
|
| 280 |
+
existing minimum it updates the margin size. Fraction of
|
| 281 |
+
figure size.
|
| 282 |
+
|
| 283 |
+
cell : int
|
| 284 |
+
Cell column or row to edit.
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
if size > self.margin_vals[todo][cell]:
|
| 288 |
+
self.edit_margin(todo, size, cell)
|
| 289 |
+
|
| 290 |
+
def edit_margins(self, todo, size):
|
| 291 |
+
"""
|
| 292 |
+
Change the size of all the margin of all the cells in the layout grid.
|
| 293 |
+
|
| 294 |
+
Parameters
|
| 295 |
+
----------
|
| 296 |
+
todo : string (one of 'left', 'right', 'bottom', 'top')
|
| 297 |
+
margin to alter.
|
| 298 |
+
|
| 299 |
+
size : float
|
| 300 |
+
Size to set the margins. Fraction of figure size.
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
for i in range(len(self.margin_vals[todo])):
|
| 304 |
+
self.edit_margin(todo, size, i)
|
| 305 |
+
|
| 306 |
+
def edit_all_margins_min(self, todo, size):
|
| 307 |
+
"""
|
| 308 |
+
Change the minimum size of all the margin of all
|
| 309 |
+
the cells in the layout grid.
|
| 310 |
+
|
| 311 |
+
Parameters
|
| 312 |
+
----------
|
| 313 |
+
todo : {'left', 'right', 'bottom', 'top'}
|
| 314 |
+
The margin to alter.
|
| 315 |
+
|
| 316 |
+
size : float
|
| 317 |
+
Minimum size of the margin. If it is larger than the
|
| 318 |
+
existing minimum it updates the margin size. Fraction of
|
| 319 |
+
figure size.
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
for i in range(len(self.margin_vals[todo])):
|
| 323 |
+
self.edit_margin_min(todo, size, i)
|
| 324 |
+
|
| 325 |
+
def edit_outer_margin_mins(self, margin, ss):
|
| 326 |
+
"""
|
| 327 |
+
Edit all four margin minimums in one statement.
|
| 328 |
+
|
| 329 |
+
Parameters
|
| 330 |
+
----------
|
| 331 |
+
margin : dict
|
| 332 |
+
size of margins in a dict with keys 'left', 'right', 'bottom',
|
| 333 |
+
'top'
|
| 334 |
+
|
| 335 |
+
ss : SubplotSpec
|
| 336 |
+
defines the subplotspec these margins should be applied to
|
| 337 |
+
"""
|
| 338 |
+
|
| 339 |
+
self.edit_margin_min('left', margin['left'], ss.colspan.start)
|
| 340 |
+
self.edit_margin_min('leftcb', margin['leftcb'], ss.colspan.start)
|
| 341 |
+
self.edit_margin_min('right', margin['right'], ss.colspan.stop - 1)
|
| 342 |
+
self.edit_margin_min('rightcb', margin['rightcb'], ss.colspan.stop - 1)
|
| 343 |
+
# rows are from the top down:
|
| 344 |
+
self.edit_margin_min('top', margin['top'], ss.rowspan.start)
|
| 345 |
+
self.edit_margin_min('topcb', margin['topcb'], ss.rowspan.start)
|
| 346 |
+
self.edit_margin_min('bottom', margin['bottom'], ss.rowspan.stop - 1)
|
| 347 |
+
self.edit_margin_min('bottomcb', margin['bottomcb'],
|
| 348 |
+
ss.rowspan.stop - 1)
|
| 349 |
+
|
| 350 |
+
def get_margins(self, todo, col):
|
| 351 |
+
"""Return the margin at this position"""
|
| 352 |
+
return self.margin_vals[todo][col]
|
| 353 |
+
|
| 354 |
+
def get_outer_bbox(self, rows=0, cols=0):
|
| 355 |
+
"""
|
| 356 |
+
Return the outer bounding box of the subplot specs
|
| 357 |
+
given by rows and cols. rows and cols can be spans.
|
| 358 |
+
"""
|
| 359 |
+
rows = np.atleast_1d(rows)
|
| 360 |
+
cols = np.atleast_1d(cols)
|
| 361 |
+
|
| 362 |
+
bbox = Bbox.from_extents(
|
| 363 |
+
self.lefts[cols[0]].value(),
|
| 364 |
+
self.bottoms[rows[-1]].value(),
|
| 365 |
+
self.rights[cols[-1]].value(),
|
| 366 |
+
self.tops[rows[0]].value())
|
| 367 |
+
return bbox
|
| 368 |
+
|
| 369 |
+
def get_inner_bbox(self, rows=0, cols=0):
|
| 370 |
+
"""
|
| 371 |
+
Return the inner bounding box of the subplot specs
|
| 372 |
+
given by rows and cols. rows and cols can be spans.
|
| 373 |
+
"""
|
| 374 |
+
rows = np.atleast_1d(rows)
|
| 375 |
+
cols = np.atleast_1d(cols)
|
| 376 |
+
|
| 377 |
+
bbox = Bbox.from_extents(
|
| 378 |
+
(self.lefts[cols[0]].value() +
|
| 379 |
+
self.margins['left'][cols[0]].value() +
|
| 380 |
+
self.margins['leftcb'][cols[0]].value()),
|
| 381 |
+
(self.bottoms[rows[-1]].value() +
|
| 382 |
+
self.margins['bottom'][rows[-1]].value() +
|
| 383 |
+
self.margins['bottomcb'][rows[-1]].value()),
|
| 384 |
+
(self.rights[cols[-1]].value() -
|
| 385 |
+
self.margins['right'][cols[-1]].value() -
|
| 386 |
+
self.margins['rightcb'][cols[-1]].value()),
|
| 387 |
+
(self.tops[rows[0]].value() -
|
| 388 |
+
self.margins['top'][rows[0]].value() -
|
| 389 |
+
self.margins['topcb'][rows[0]].value())
|
| 390 |
+
)
|
| 391 |
+
return bbox
|
| 392 |
+
|
| 393 |
+
def get_bbox_for_cb(self, rows=0, cols=0):
|
| 394 |
+
"""
|
| 395 |
+
Return the bounding box that includes the
|
| 396 |
+
decorations but, *not* the colorbar...
|
| 397 |
+
"""
|
| 398 |
+
rows = np.atleast_1d(rows)
|
| 399 |
+
cols = np.atleast_1d(cols)
|
| 400 |
+
|
| 401 |
+
bbox = Bbox.from_extents(
|
| 402 |
+
(self.lefts[cols[0]].value() +
|
| 403 |
+
self.margins['leftcb'][cols[0]].value()),
|
| 404 |
+
(self.bottoms[rows[-1]].value() +
|
| 405 |
+
self.margins['bottomcb'][rows[-1]].value()),
|
| 406 |
+
(self.rights[cols[-1]].value() -
|
| 407 |
+
self.margins['rightcb'][cols[-1]].value()),
|
| 408 |
+
(self.tops[rows[0]].value() -
|
| 409 |
+
self.margins['topcb'][rows[0]].value())
|
| 410 |
+
)
|
| 411 |
+
return bbox
|
| 412 |
+
|
| 413 |
+
def get_left_margin_bbox(self, rows=0, cols=0):
|
| 414 |
+
"""
|
| 415 |
+
Return the left margin bounding box of the subplot specs
|
| 416 |
+
given by rows and cols. rows and cols can be spans.
|
| 417 |
+
"""
|
| 418 |
+
rows = np.atleast_1d(rows)
|
| 419 |
+
cols = np.atleast_1d(cols)
|
| 420 |
+
|
| 421 |
+
bbox = Bbox.from_extents(
|
| 422 |
+
(self.lefts[cols[0]].value() +
|
| 423 |
+
self.margins['leftcb'][cols[0]].value()),
|
| 424 |
+
(self.bottoms[rows[-1]].value()),
|
| 425 |
+
(self.lefts[cols[0]].value() +
|
| 426 |
+
self.margins['leftcb'][cols[0]].value() +
|
| 427 |
+
self.margins['left'][cols[0]].value()),
|
| 428 |
+
(self.tops[rows[0]].value()))
|
| 429 |
+
return bbox
|
| 430 |
+
|
| 431 |
+
def get_bottom_margin_bbox(self, rows=0, cols=0):
|
| 432 |
+
"""
|
| 433 |
+
Return the left margin bounding box of the subplot specs
|
| 434 |
+
given by rows and cols. rows and cols can be spans.
|
| 435 |
+
"""
|
| 436 |
+
rows = np.atleast_1d(rows)
|
| 437 |
+
cols = np.atleast_1d(cols)
|
| 438 |
+
|
| 439 |
+
bbox = Bbox.from_extents(
|
| 440 |
+
(self.lefts[cols[0]].value()),
|
| 441 |
+
(self.bottoms[rows[-1]].value() +
|
| 442 |
+
self.margins['bottomcb'][rows[-1]].value()),
|
| 443 |
+
(self.rights[cols[-1]].value()),
|
| 444 |
+
(self.bottoms[rows[-1]].value() +
|
| 445 |
+
self.margins['bottom'][rows[-1]].value() +
|
| 446 |
+
self.margins['bottomcb'][rows[-1]].value()
|
| 447 |
+
))
|
| 448 |
+
return bbox
|
| 449 |
+
|
| 450 |
+
def get_right_margin_bbox(self, rows=0, cols=0):
|
| 451 |
+
"""
|
| 452 |
+
Return the left margin bounding box of the subplot specs
|
| 453 |
+
given by rows and cols. rows and cols can be spans.
|
| 454 |
+
"""
|
| 455 |
+
rows = np.atleast_1d(rows)
|
| 456 |
+
cols = np.atleast_1d(cols)
|
| 457 |
+
|
| 458 |
+
bbox = Bbox.from_extents(
|
| 459 |
+
(self.rights[cols[-1]].value() -
|
| 460 |
+
self.margins['right'][cols[-1]].value() -
|
| 461 |
+
self.margins['rightcb'][cols[-1]].value()),
|
| 462 |
+
(self.bottoms[rows[-1]].value()),
|
| 463 |
+
(self.rights[cols[-1]].value() -
|
| 464 |
+
self.margins['rightcb'][cols[-1]].value()),
|
| 465 |
+
(self.tops[rows[0]].value()))
|
| 466 |
+
return bbox
|
| 467 |
+
|
| 468 |
+
def get_top_margin_bbox(self, rows=0, cols=0):
|
| 469 |
+
"""
|
| 470 |
+
Return the left margin bounding box of the subplot specs
|
| 471 |
+
given by rows and cols. rows and cols can be spans.
|
| 472 |
+
"""
|
| 473 |
+
rows = np.atleast_1d(rows)
|
| 474 |
+
cols = np.atleast_1d(cols)
|
| 475 |
+
|
| 476 |
+
bbox = Bbox.from_extents(
|
| 477 |
+
(self.lefts[cols[0]].value()),
|
| 478 |
+
(self.tops[rows[0]].value() -
|
| 479 |
+
self.margins['topcb'][rows[0]].value()),
|
| 480 |
+
(self.rights[cols[-1]].value()),
|
| 481 |
+
(self.tops[rows[0]].value() -
|
| 482 |
+
self.margins['topcb'][rows[0]].value() -
|
| 483 |
+
self.margins['top'][rows[0]].value()))
|
| 484 |
+
return bbox
|
| 485 |
+
|
| 486 |
+
def update_variables(self):
|
| 487 |
+
"""
|
| 488 |
+
Update the variables for the solver attached to this layoutgrid.
|
| 489 |
+
"""
|
| 490 |
+
self.solver.updateVariables()
|
| 491 |
+
|
| 492 |
+
_layoutboxobjnum = itertools.count()
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def seq_id():
|
| 496 |
+
"""Generate a short sequential id for layoutbox objects."""
|
| 497 |
+
return '%06d' % next(_layoutboxobjnum)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def plot_children(fig, lg=None, level=0):
|
| 501 |
+
"""Simple plotting to show where boxes are."""
|
| 502 |
+
if lg is None:
|
| 503 |
+
_layoutgrids = fig.get_layout_engine().execute(fig)
|
| 504 |
+
lg = _layoutgrids[fig]
|
| 505 |
+
colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"]
|
| 506 |
+
col = colors[level]
|
| 507 |
+
for i in range(lg.nrows):
|
| 508 |
+
for j in range(lg.ncols):
|
| 509 |
+
bb = lg.get_outer_bbox(rows=i, cols=j)
|
| 510 |
+
fig.add_artist(
|
| 511 |
+
mpatches.Rectangle(bb.p0, bb.width, bb.height, linewidth=1,
|
| 512 |
+
edgecolor='0.7', facecolor='0.7',
|
| 513 |
+
alpha=0.2, transform=fig.transFigure,
|
| 514 |
+
zorder=-3))
|
| 515 |
+
bbi = lg.get_inner_bbox(rows=i, cols=j)
|
| 516 |
+
fig.add_artist(
|
| 517 |
+
mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=2,
|
| 518 |
+
edgecolor=col, facecolor='none',
|
| 519 |
+
transform=fig.transFigure, zorder=-2))
|
| 520 |
+
|
| 521 |
+
bbi = lg.get_left_margin_bbox(rows=i, cols=j)
|
| 522 |
+
fig.add_artist(
|
| 523 |
+
mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
|
| 524 |
+
edgecolor='none', alpha=0.2,
|
| 525 |
+
facecolor=[0.5, 0.7, 0.5],
|
| 526 |
+
transform=fig.transFigure, zorder=-2))
|
| 527 |
+
bbi = lg.get_right_margin_bbox(rows=i, cols=j)
|
| 528 |
+
fig.add_artist(
|
| 529 |
+
mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
|
| 530 |
+
edgecolor='none', alpha=0.2,
|
| 531 |
+
facecolor=[0.7, 0.5, 0.5],
|
| 532 |
+
transform=fig.transFigure, zorder=-2))
|
| 533 |
+
bbi = lg.get_bottom_margin_bbox(rows=i, cols=j)
|
| 534 |
+
fig.add_artist(
|
| 535 |
+
mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
|
| 536 |
+
edgecolor='none', alpha=0.2,
|
| 537 |
+
facecolor=[0.5, 0.5, 0.7],
|
| 538 |
+
transform=fig.transFigure, zorder=-2))
|
| 539 |
+
bbi = lg.get_top_margin_bbox(rows=i, cols=j)
|
| 540 |
+
fig.add_artist(
|
| 541 |
+
mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
|
| 542 |
+
edgecolor='none', alpha=0.2,
|
| 543 |
+
facecolor=[0.7, 0.2, 0.7],
|
| 544 |
+
transform=fig.transFigure, zorder=-2))
|
| 545 |
+
for ch in lg.children.flat:
|
| 546 |
+
if ch is not None:
|
| 547 |
+
plot_children(fig, ch, level=level+1)
|
omnilmm/lib/python3.10/site-packages/matplotlib/_text_helpers.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Low-level text helper utilities.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
|
| 7 |
+
from . import _api
|
| 8 |
+
from .ft2font import KERNING_DEFAULT, LOAD_NO_HINTING
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
LayoutItem = dataclasses.make_dataclass(
|
| 12 |
+
"LayoutItem", ["ft_object", "char", "glyph_idx", "x", "prev_kern"])
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def warn_on_missing_glyph(codepoint):
|
| 16 |
+
_api.warn_external(
|
| 17 |
+
"Glyph {} ({}) missing from current font.".format(
|
| 18 |
+
codepoint,
|
| 19 |
+
chr(codepoint).encode("ascii", "namereplace").decode("ascii")))
|
| 20 |
+
block = ("Hebrew" if 0x0590 <= codepoint <= 0x05ff else
|
| 21 |
+
"Arabic" if 0x0600 <= codepoint <= 0x06ff else
|
| 22 |
+
"Devanagari" if 0x0900 <= codepoint <= 0x097f else
|
| 23 |
+
"Bengali" if 0x0980 <= codepoint <= 0x09ff else
|
| 24 |
+
"Gurmukhi" if 0x0a00 <= codepoint <= 0x0a7f else
|
| 25 |
+
"Gujarati" if 0x0a80 <= codepoint <= 0x0aff else
|
| 26 |
+
"Oriya" if 0x0b00 <= codepoint <= 0x0b7f else
|
| 27 |
+
"Tamil" if 0x0b80 <= codepoint <= 0x0bff else
|
| 28 |
+
"Telugu" if 0x0c00 <= codepoint <= 0x0c7f else
|
| 29 |
+
"Kannada" if 0x0c80 <= codepoint <= 0x0cff else
|
| 30 |
+
"Malayalam" if 0x0d00 <= codepoint <= 0x0d7f else
|
| 31 |
+
"Sinhala" if 0x0d80 <= codepoint <= 0x0dff else
|
| 32 |
+
None)
|
| 33 |
+
if block:
|
| 34 |
+
_api.warn_external(
|
| 35 |
+
f"Matplotlib currently does not support {block} natively.")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def layout(string, font, *, kern_mode=KERNING_DEFAULT):
|
| 39 |
+
"""
|
| 40 |
+
Render *string* with *font*. For each character in *string*, yield a
|
| 41 |
+
(glyph-index, x-position) pair. When such a pair is yielded, the font's
|
| 42 |
+
glyph is set to the corresponding character.
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
string : str
|
| 47 |
+
The string to be rendered.
|
| 48 |
+
font : FT2Font
|
| 49 |
+
The font.
|
| 50 |
+
kern_mode : int
|
| 51 |
+
A FreeType kerning mode.
|
| 52 |
+
|
| 53 |
+
Yields
|
| 54 |
+
------
|
| 55 |
+
glyph_index : int
|
| 56 |
+
x_position : float
|
| 57 |
+
"""
|
| 58 |
+
x = 0
|
| 59 |
+
prev_glyph_idx = None
|
| 60 |
+
char_to_font = font._get_fontmap(string)
|
| 61 |
+
base_font = font
|
| 62 |
+
for char in string:
|
| 63 |
+
# This has done the fallback logic
|
| 64 |
+
font = char_to_font.get(char, base_font)
|
| 65 |
+
glyph_idx = font.get_char_index(ord(char))
|
| 66 |
+
kern = (
|
| 67 |
+
base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64
|
| 68 |
+
if prev_glyph_idx is not None else 0.
|
| 69 |
+
)
|
| 70 |
+
x += kern
|
| 71 |
+
glyph = font.load_glyph(glyph_idx, flags=LOAD_NO_HINTING)
|
| 72 |
+
yield LayoutItem(font, char, glyph_idx, x, kern)
|
| 73 |
+
x += glyph.linearHoriAdvance / 65536
|
| 74 |
+
prev_glyph_idx = glyph_idx
|
omnilmm/lib/python3.10/site-packages/matplotlib/_tight_bbox.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Helper module for the *bbox_inches* parameter in `.Figure.savefig`.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def adjust_bbox(fig, bbox_inches, fixed_dpi=None):
|
| 9 |
+
"""
|
| 10 |
+
Temporarily adjust the figure so that only the specified area
|
| 11 |
+
(bbox_inches) is saved.
|
| 12 |
+
|
| 13 |
+
It modifies fig.bbox, fig.bbox_inches,
|
| 14 |
+
fig.transFigure._boxout, and fig.patch. While the figure size
|
| 15 |
+
changes, the scale of the original figure is conserved. A
|
| 16 |
+
function which restores the original values are returned.
|
| 17 |
+
"""
|
| 18 |
+
origBbox = fig.bbox
|
| 19 |
+
origBboxInches = fig.bbox_inches
|
| 20 |
+
_boxout = fig.transFigure._boxout
|
| 21 |
+
|
| 22 |
+
old_aspect = []
|
| 23 |
+
locator_list = []
|
| 24 |
+
sentinel = object()
|
| 25 |
+
for ax in fig.axes:
|
| 26 |
+
locator = ax.get_axes_locator()
|
| 27 |
+
if locator is not None:
|
| 28 |
+
ax.apply_aspect(locator(ax, None))
|
| 29 |
+
locator_list.append(locator)
|
| 30 |
+
current_pos = ax.get_position(original=False).frozen()
|
| 31 |
+
ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos)
|
| 32 |
+
# override the method that enforces the aspect ratio on the Axes
|
| 33 |
+
if 'apply_aspect' in ax.__dict__:
|
| 34 |
+
old_aspect.append(ax.apply_aspect)
|
| 35 |
+
else:
|
| 36 |
+
old_aspect.append(sentinel)
|
| 37 |
+
ax.apply_aspect = lambda pos=None: None
|
| 38 |
+
|
| 39 |
+
def restore_bbox():
|
| 40 |
+
for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect):
|
| 41 |
+
ax.set_axes_locator(loc)
|
| 42 |
+
if aspect is sentinel:
|
| 43 |
+
# delete our no-op function which un-hides the original method
|
| 44 |
+
del ax.apply_aspect
|
| 45 |
+
else:
|
| 46 |
+
ax.apply_aspect = aspect
|
| 47 |
+
|
| 48 |
+
fig.bbox = origBbox
|
| 49 |
+
fig.bbox_inches = origBboxInches
|
| 50 |
+
fig.transFigure._boxout = _boxout
|
| 51 |
+
fig.transFigure.invalidate()
|
| 52 |
+
fig.patch.set_bounds(0, 0, 1, 1)
|
| 53 |
+
|
| 54 |
+
if fixed_dpi is None:
|
| 55 |
+
fixed_dpi = fig.dpi
|
| 56 |
+
tr = Affine2D().scale(fixed_dpi)
|
| 57 |
+
dpi_scale = fixed_dpi / fig.dpi
|
| 58 |
+
|
| 59 |
+
fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size)
|
| 60 |
+
x0, y0 = tr.transform(bbox_inches.p0)
|
| 61 |
+
w1, h1 = fig.bbox.size * dpi_scale
|
| 62 |
+
fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
|
| 63 |
+
fig.transFigure.invalidate()
|
| 64 |
+
|
| 65 |
+
fig.bbox = TransformedBbox(fig.bbox_inches, tr)
|
| 66 |
+
|
| 67 |
+
fig.patch.set_bounds(x0 / w1, y0 / h1,
|
| 68 |
+
fig.bbox.width / w1, fig.bbox.height / h1)
|
| 69 |
+
|
| 70 |
+
return restore_bbox
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None):
|
| 74 |
+
"""
|
| 75 |
+
A function that needs to be called when figure dpi changes during the
|
| 76 |
+
drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with
|
| 77 |
+
the new dpi.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
bbox_inches, restore_bbox = bbox_inches_restore
|
| 81 |
+
restore_bbox()
|
| 82 |
+
r = adjust_bbox(fig, bbox_inches, fixed_dpi)
|
| 83 |
+
|
| 84 |
+
return bbox_inches, r
|
omnilmm/lib/python3.10/site-packages/matplotlib/animation.py
ADDED
|
@@ -0,0 +1,1790 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# TODO:
|
| 2 |
+
# * Documentation -- this will need a new section of the User's Guide.
|
| 3 |
+
# Both for Animations and just timers.
|
| 4 |
+
# - Also need to update
|
| 5 |
+
# https://scipy-cookbook.readthedocs.io/items/Matplotlib_Animations.html
|
| 6 |
+
# * Blit
|
| 7 |
+
# * Currently broken with Qt4 for widgets that don't start on screen
|
| 8 |
+
# * Still a few edge cases that aren't working correctly
|
| 9 |
+
# * Can this integrate better with existing matplotlib animation artist flag?
|
| 10 |
+
# - If animated removes from default draw(), perhaps we could use this to
|
| 11 |
+
# simplify initial draw.
|
| 12 |
+
# * Example
|
| 13 |
+
# * Frameless animation - pure procedural with no loop
|
| 14 |
+
# * Need example that uses something like inotify or subprocess
|
| 15 |
+
# * Complex syncing examples
|
| 16 |
+
# * Movies
|
| 17 |
+
# * Can blit be enabled for movies?
|
| 18 |
+
# * Need to consider event sources to allow clicking through multiple figures
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
import abc
|
| 22 |
+
import base64
|
| 23 |
+
import contextlib
|
| 24 |
+
from io import BytesIO, TextIOWrapper
|
| 25 |
+
import itertools
|
| 26 |
+
import logging
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
import shutil
|
| 29 |
+
import subprocess
|
| 30 |
+
import sys
|
| 31 |
+
from tempfile import TemporaryDirectory
|
| 32 |
+
import uuid
|
| 33 |
+
import warnings
|
| 34 |
+
|
| 35 |
+
import numpy as np
|
| 36 |
+
from PIL import Image
|
| 37 |
+
|
| 38 |
+
import matplotlib as mpl
|
| 39 |
+
from matplotlib._animation_data import (
|
| 40 |
+
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
|
| 41 |
+
from matplotlib import _api, cbook
|
| 42 |
+
import matplotlib.colors as mcolors
|
| 43 |
+
|
| 44 |
+
_log = logging.getLogger(__name__)
|
| 45 |
+
|
| 46 |
+
# Process creation flag for subprocess to prevent it raising a terminal
|
| 47 |
+
# window. See for example https://stackoverflow.com/q/24130623/
|
| 48 |
+
subprocess_creation_flags = (
|
| 49 |
+
subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0)
|
| 50 |
+
|
| 51 |
+
# Other potential writing methods:
|
| 52 |
+
# * http://pymedia.org/
|
| 53 |
+
# * libming (produces swf) python wrappers: https://github.com/libming/libming
|
| 54 |
+
# * Wrap x264 API:
|
| 55 |
+
|
| 56 |
+
# (https://stackoverflow.com/q/2940671/)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def adjusted_figsize(w, h, dpi, n):
|
| 60 |
+
"""
|
| 61 |
+
Compute figure size so that pixels are a multiple of n.
|
| 62 |
+
|
| 63 |
+
Parameters
|
| 64 |
+
----------
|
| 65 |
+
w, h : float
|
| 66 |
+
Size in inches.
|
| 67 |
+
|
| 68 |
+
dpi : float
|
| 69 |
+
The dpi.
|
| 70 |
+
|
| 71 |
+
n : int
|
| 72 |
+
The target multiple.
|
| 73 |
+
|
| 74 |
+
Returns
|
| 75 |
+
-------
|
| 76 |
+
wnew, hnew : float
|
| 77 |
+
The new figure size in inches.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
# this maybe simplified if / when we adopt consistent rounding for
|
| 81 |
+
# pixel size across the whole library
|
| 82 |
+
def correct_roundoff(x, dpi, n):
|
| 83 |
+
if int(x*dpi) % n != 0:
|
| 84 |
+
if int(np.nextafter(x, np.inf)*dpi) % n == 0:
|
| 85 |
+
x = np.nextafter(x, np.inf)
|
| 86 |
+
elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
|
| 87 |
+
x = np.nextafter(x, -np.inf)
|
| 88 |
+
return x
|
| 89 |
+
|
| 90 |
+
wnew = int(w * dpi / n) * n / dpi
|
| 91 |
+
hnew = int(h * dpi / n) * n / dpi
|
| 92 |
+
return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class MovieWriterRegistry:
|
| 96 |
+
"""Registry of available writer classes by human readable name."""
|
| 97 |
+
|
| 98 |
+
def __init__(self):
|
| 99 |
+
self._registered = dict()
|
| 100 |
+
|
| 101 |
+
def register(self, name):
|
| 102 |
+
"""
|
| 103 |
+
Decorator for registering a class under a name.
|
| 104 |
+
|
| 105 |
+
Example use::
|
| 106 |
+
|
| 107 |
+
@registry.register(name)
|
| 108 |
+
class Foo:
|
| 109 |
+
pass
|
| 110 |
+
"""
|
| 111 |
+
def wrapper(writer_cls):
|
| 112 |
+
self._registered[name] = writer_cls
|
| 113 |
+
return writer_cls
|
| 114 |
+
return wrapper
|
| 115 |
+
|
| 116 |
+
def is_available(self, name):
|
| 117 |
+
"""
|
| 118 |
+
Check if given writer is available by name.
|
| 119 |
+
|
| 120 |
+
Parameters
|
| 121 |
+
----------
|
| 122 |
+
name : str
|
| 123 |
+
|
| 124 |
+
Returns
|
| 125 |
+
-------
|
| 126 |
+
bool
|
| 127 |
+
"""
|
| 128 |
+
try:
|
| 129 |
+
cls = self._registered[name]
|
| 130 |
+
except KeyError:
|
| 131 |
+
return False
|
| 132 |
+
return cls.isAvailable()
|
| 133 |
+
|
| 134 |
+
def __iter__(self):
|
| 135 |
+
"""Iterate over names of available writer class."""
|
| 136 |
+
for name in self._registered:
|
| 137 |
+
if self.is_available(name):
|
| 138 |
+
yield name
|
| 139 |
+
|
| 140 |
+
def list(self):
|
| 141 |
+
"""Get a list of available MovieWriters."""
|
| 142 |
+
return [*self]
|
| 143 |
+
|
| 144 |
+
def __getitem__(self, name):
|
| 145 |
+
"""Get an available writer class from its name."""
|
| 146 |
+
if self.is_available(name):
|
| 147 |
+
return self._registered[name]
|
| 148 |
+
raise RuntimeError(f"Requested MovieWriter ({name}) not available")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
writers = MovieWriterRegistry()
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class AbstractMovieWriter(abc.ABC):
|
| 155 |
+
"""
|
| 156 |
+
Abstract base class for writing movies, providing a way to grab frames by
|
| 157 |
+
calling `~AbstractMovieWriter.grab_frame`.
|
| 158 |
+
|
| 159 |
+
`setup` is called to start the process and `finish` is called afterwards.
|
| 160 |
+
`saving` is provided as a context manager to facilitate this process as ::
|
| 161 |
+
|
| 162 |
+
with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
|
| 163 |
+
# Iterate over frames
|
| 164 |
+
moviewriter.grab_frame(**savefig_kwargs)
|
| 165 |
+
|
| 166 |
+
The use of the context manager ensures that `setup` and `finish` are
|
| 167 |
+
performed as necessary.
|
| 168 |
+
|
| 169 |
+
An instance of a concrete subclass of this class can be given as the
|
| 170 |
+
``writer`` argument of `Animation.save()`.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
def __init__(self, fps=5, metadata=None, codec=None, bitrate=None):
|
| 174 |
+
self.fps = fps
|
| 175 |
+
self.metadata = metadata if metadata is not None else {}
|
| 176 |
+
self.codec = (
|
| 177 |
+
mpl.rcParams['animation.codec'] if codec is None else codec)
|
| 178 |
+
self.bitrate = (
|
| 179 |
+
mpl.rcParams['animation.bitrate'] if bitrate is None else bitrate)
|
| 180 |
+
|
| 181 |
+
@abc.abstractmethod
|
| 182 |
+
def setup(self, fig, outfile, dpi=None):
|
| 183 |
+
"""
|
| 184 |
+
Setup for writing the movie file.
|
| 185 |
+
|
| 186 |
+
Parameters
|
| 187 |
+
----------
|
| 188 |
+
fig : `~matplotlib.figure.Figure`
|
| 189 |
+
The figure object that contains the information for frames.
|
| 190 |
+
outfile : str
|
| 191 |
+
The filename of the resulting movie file.
|
| 192 |
+
dpi : float, default: ``fig.dpi``
|
| 193 |
+
The DPI (or resolution) for the file. This controls the size
|
| 194 |
+
in pixels of the resulting movie file.
|
| 195 |
+
"""
|
| 196 |
+
# Check that path is valid
|
| 197 |
+
Path(outfile).parent.resolve(strict=True)
|
| 198 |
+
self.outfile = outfile
|
| 199 |
+
self.fig = fig
|
| 200 |
+
if dpi is None:
|
| 201 |
+
dpi = self.fig.dpi
|
| 202 |
+
self.dpi = dpi
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def frame_size(self):
|
| 206 |
+
"""A tuple ``(width, height)`` in pixels of a movie frame."""
|
| 207 |
+
w, h = self.fig.get_size_inches()
|
| 208 |
+
return int(w * self.dpi), int(h * self.dpi)
|
| 209 |
+
|
| 210 |
+
@abc.abstractmethod
|
| 211 |
+
def grab_frame(self, **savefig_kwargs):
|
| 212 |
+
"""
|
| 213 |
+
Grab the image information from the figure and save as a movie frame.
|
| 214 |
+
|
| 215 |
+
All keyword arguments in *savefig_kwargs* are passed on to the
|
| 216 |
+
`~.Figure.savefig` call that saves the figure.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
@abc.abstractmethod
|
| 220 |
+
def finish(self):
|
| 221 |
+
"""Finish any processing for writing the movie."""
|
| 222 |
+
|
| 223 |
+
@contextlib.contextmanager
|
| 224 |
+
def saving(self, fig, outfile, dpi, *args, **kwargs):
|
| 225 |
+
"""
|
| 226 |
+
Context manager to facilitate writing the movie file.
|
| 227 |
+
|
| 228 |
+
``*args, **kw`` are any parameters that should be passed to `setup`.
|
| 229 |
+
"""
|
| 230 |
+
# This particular sequence is what contextlib.contextmanager wants
|
| 231 |
+
self.setup(fig, outfile, dpi, *args, **kwargs)
|
| 232 |
+
try:
|
| 233 |
+
yield self
|
| 234 |
+
finally:
|
| 235 |
+
self.finish()
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class MovieWriter(AbstractMovieWriter):
|
| 239 |
+
"""
|
| 240 |
+
Base class for writing movies.
|
| 241 |
+
|
| 242 |
+
This is a base class for MovieWriter subclasses that write a movie frame
|
| 243 |
+
data to a pipe. You cannot instantiate this class directly.
|
| 244 |
+
See examples for how to use its subclasses.
|
| 245 |
+
|
| 246 |
+
Attributes
|
| 247 |
+
----------
|
| 248 |
+
frame_format : str
|
| 249 |
+
The format used in writing frame data, defaults to 'rgba'.
|
| 250 |
+
fig : `~matplotlib.figure.Figure`
|
| 251 |
+
The figure to capture data from.
|
| 252 |
+
This must be provided by the subclasses.
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
# Builtin writer subclasses additionally define the _exec_key and _args_key
|
| 256 |
+
# attributes, which indicate the rcParams entries where the path to the
|
| 257 |
+
# executable and additional command-line arguments to the executable are
|
| 258 |
+
# stored. Third-party writers cannot meaningfully set these as they cannot
|
| 259 |
+
# extend rcParams with new keys.
|
| 260 |
+
|
| 261 |
+
# Pipe-based writers only support RGBA, but file-based ones support more
|
| 262 |
+
# formats.
|
| 263 |
+
supported_formats = ["rgba"]
|
| 264 |
+
|
| 265 |
+
def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
|
| 266 |
+
metadata=None):
|
| 267 |
+
"""
|
| 268 |
+
Parameters
|
| 269 |
+
----------
|
| 270 |
+
fps : int, default: 5
|
| 271 |
+
Movie frame rate (per second).
|
| 272 |
+
codec : str or None, default: :rc:`animation.codec`
|
| 273 |
+
The codec to use.
|
| 274 |
+
bitrate : int, default: :rc:`animation.bitrate`
|
| 275 |
+
The bitrate of the movie, in kilobits per second. Higher values
|
| 276 |
+
means higher quality movies, but increase the file size. A value
|
| 277 |
+
of -1 lets the underlying movie encoder select the bitrate.
|
| 278 |
+
extra_args : list of str or None, optional
|
| 279 |
+
Extra command-line arguments passed to the underlying movie
|
| 280 |
+
encoder. The default, None, means to use
|
| 281 |
+
:rc:`animation.[name-of-encoder]_args` for the builtin writers.
|
| 282 |
+
metadata : dict[str, str], default: {}
|
| 283 |
+
A dictionary of keys and values for metadata to include in the
|
| 284 |
+
output file. Some keys that may be of use include:
|
| 285 |
+
title, artist, genre, subject, copyright, srcform, comment.
|
| 286 |
+
"""
|
| 287 |
+
if type(self) is MovieWriter:
|
| 288 |
+
# TODO MovieWriter is still an abstract class and needs to be
|
| 289 |
+
# extended with a mixin. This should be clearer in naming
|
| 290 |
+
# and description. For now, just give a reasonable error
|
| 291 |
+
# message to users.
|
| 292 |
+
raise TypeError(
|
| 293 |
+
'MovieWriter cannot be instantiated directly. Please use one '
|
| 294 |
+
'of its subclasses.')
|
| 295 |
+
|
| 296 |
+
super().__init__(fps=fps, metadata=metadata, codec=codec,
|
| 297 |
+
bitrate=bitrate)
|
| 298 |
+
self.frame_format = self.supported_formats[0]
|
| 299 |
+
self.extra_args = extra_args
|
| 300 |
+
|
| 301 |
+
def _adjust_frame_size(self):
|
| 302 |
+
if self.codec == 'h264':
|
| 303 |
+
wo, ho = self.fig.get_size_inches()
|
| 304 |
+
w, h = adjusted_figsize(wo, ho, self.dpi, 2)
|
| 305 |
+
if (wo, ho) != (w, h):
|
| 306 |
+
self.fig.set_size_inches(w, h, forward=True)
|
| 307 |
+
_log.info('figure size in inches has been adjusted '
|
| 308 |
+
'from %s x %s to %s x %s', wo, ho, w, h)
|
| 309 |
+
else:
|
| 310 |
+
w, h = self.fig.get_size_inches()
|
| 311 |
+
_log.debug('frame size in pixels is %s x %s', *self.frame_size)
|
| 312 |
+
return w, h
|
| 313 |
+
|
| 314 |
+
def setup(self, fig, outfile, dpi=None):
|
| 315 |
+
# docstring inherited
|
| 316 |
+
super().setup(fig, outfile, dpi=dpi)
|
| 317 |
+
self._w, self._h = self._adjust_frame_size()
|
| 318 |
+
# Run here so that grab_frame() can write the data to a pipe. This
|
| 319 |
+
# eliminates the need for temp files.
|
| 320 |
+
self._run()
|
| 321 |
+
|
| 322 |
+
def _run(self):
|
| 323 |
+
# Uses subprocess to call the program for assembling frames into a
|
| 324 |
+
# movie file. *args* returns the sequence of command line arguments
|
| 325 |
+
# from a few configuration options.
|
| 326 |
+
command = self._args()
|
| 327 |
+
_log.info('MovieWriter._run: running command: %s',
|
| 328 |
+
cbook._pformat_subprocess(command))
|
| 329 |
+
PIPE = subprocess.PIPE
|
| 330 |
+
self._proc = subprocess.Popen(
|
| 331 |
+
command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
|
| 332 |
+
creationflags=subprocess_creation_flags)
|
| 333 |
+
|
| 334 |
+
def finish(self):
|
| 335 |
+
"""Finish any processing for writing the movie."""
|
| 336 |
+
out, err = self._proc.communicate()
|
| 337 |
+
# Use the encoding/errors that universal_newlines would use.
|
| 338 |
+
out = TextIOWrapper(BytesIO(out)).read()
|
| 339 |
+
err = TextIOWrapper(BytesIO(err)).read()
|
| 340 |
+
if out:
|
| 341 |
+
_log.log(
|
| 342 |
+
logging.WARNING if self._proc.returncode else logging.DEBUG,
|
| 343 |
+
"MovieWriter stdout:\n%s", out)
|
| 344 |
+
if err:
|
| 345 |
+
_log.log(
|
| 346 |
+
logging.WARNING if self._proc.returncode else logging.DEBUG,
|
| 347 |
+
"MovieWriter stderr:\n%s", err)
|
| 348 |
+
if self._proc.returncode:
|
| 349 |
+
raise subprocess.CalledProcessError(
|
| 350 |
+
self._proc.returncode, self._proc.args, out, err)
|
| 351 |
+
|
| 352 |
+
def grab_frame(self, **savefig_kwargs):
|
| 353 |
+
# docstring inherited
|
| 354 |
+
_log.debug('MovieWriter.grab_frame: Grabbing frame.')
|
| 355 |
+
# Readjust the figure size in case it has been changed by the user.
|
| 356 |
+
# All frames must have the same size to save the movie correctly.
|
| 357 |
+
self.fig.set_size_inches(self._w, self._h)
|
| 358 |
+
# Save the figure data to the sink, using the frame format and dpi.
|
| 359 |
+
self.fig.savefig(self._proc.stdin, format=self.frame_format,
|
| 360 |
+
dpi=self.dpi, **savefig_kwargs)
|
| 361 |
+
|
| 362 |
+
def _args(self):
|
| 363 |
+
"""Assemble list of encoder-specific command-line arguments."""
|
| 364 |
+
return NotImplementedError("args needs to be implemented by subclass.")
|
| 365 |
+
|
| 366 |
+
@classmethod
|
| 367 |
+
def bin_path(cls):
|
| 368 |
+
"""
|
| 369 |
+
Return the binary path to the commandline tool used by a specific
|
| 370 |
+
subclass. This is a class method so that the tool can be looked for
|
| 371 |
+
before making a particular MovieWriter subclass available.
|
| 372 |
+
"""
|
| 373 |
+
return str(mpl.rcParams[cls._exec_key])
|
| 374 |
+
|
| 375 |
+
@classmethod
|
| 376 |
+
def isAvailable(cls):
|
| 377 |
+
"""Return whether a MovieWriter subclass is actually available."""
|
| 378 |
+
return shutil.which(cls.bin_path()) is not None
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
class FileMovieWriter(MovieWriter):
|
| 382 |
+
"""
|
| 383 |
+
`MovieWriter` for writing to individual files and stitching at the end.
|
| 384 |
+
|
| 385 |
+
This must be sub-classed to be useful.
|
| 386 |
+
"""
|
| 387 |
+
def __init__(self, *args, **kwargs):
|
| 388 |
+
super().__init__(*args, **kwargs)
|
| 389 |
+
self.frame_format = mpl.rcParams['animation.frame_format']
|
| 390 |
+
|
| 391 |
+
def setup(self, fig, outfile, dpi=None, frame_prefix=None):
|
| 392 |
+
"""
|
| 393 |
+
Setup for writing the movie file.
|
| 394 |
+
|
| 395 |
+
Parameters
|
| 396 |
+
----------
|
| 397 |
+
fig : `~matplotlib.figure.Figure`
|
| 398 |
+
The figure to grab the rendered frames from.
|
| 399 |
+
outfile : str
|
| 400 |
+
The filename of the resulting movie file.
|
| 401 |
+
dpi : float, default: ``fig.dpi``
|
| 402 |
+
The dpi of the output file. This, with the figure size,
|
| 403 |
+
controls the size in pixels of the resulting movie file.
|
| 404 |
+
frame_prefix : str, optional
|
| 405 |
+
The filename prefix to use for temporary files. If *None* (the
|
| 406 |
+
default), files are written to a temporary directory which is
|
| 407 |
+
deleted by `finish`; if not *None*, no temporary files are
|
| 408 |
+
deleted.
|
| 409 |
+
"""
|
| 410 |
+
# Check that path is valid
|
| 411 |
+
Path(outfile).parent.resolve(strict=True)
|
| 412 |
+
self.fig = fig
|
| 413 |
+
self.outfile = outfile
|
| 414 |
+
if dpi is None:
|
| 415 |
+
dpi = self.fig.dpi
|
| 416 |
+
self.dpi = dpi
|
| 417 |
+
self._adjust_frame_size()
|
| 418 |
+
|
| 419 |
+
if frame_prefix is None:
|
| 420 |
+
self._tmpdir = TemporaryDirectory()
|
| 421 |
+
self.temp_prefix = str(Path(self._tmpdir.name, 'tmp'))
|
| 422 |
+
else:
|
| 423 |
+
self._tmpdir = None
|
| 424 |
+
self.temp_prefix = frame_prefix
|
| 425 |
+
self._frame_counter = 0 # used for generating sequential file names
|
| 426 |
+
self._temp_paths = list()
|
| 427 |
+
self.fname_format_str = '%s%%07d.%s'
|
| 428 |
+
|
| 429 |
+
def __del__(self):
|
| 430 |
+
if hasattr(self, '_tmpdir') and self._tmpdir:
|
| 431 |
+
self._tmpdir.cleanup()
|
| 432 |
+
|
| 433 |
+
@property
|
| 434 |
+
def frame_format(self):
|
| 435 |
+
"""
|
| 436 |
+
Format (png, jpeg, etc.) to use for saving the frames, which can be
|
| 437 |
+
decided by the individual subclasses.
|
| 438 |
+
"""
|
| 439 |
+
return self._frame_format
|
| 440 |
+
|
| 441 |
+
@frame_format.setter
|
| 442 |
+
def frame_format(self, frame_format):
|
| 443 |
+
if frame_format in self.supported_formats:
|
| 444 |
+
self._frame_format = frame_format
|
| 445 |
+
else:
|
| 446 |
+
_api.warn_external(
|
| 447 |
+
f"Ignoring file format {frame_format!r} which is not "
|
| 448 |
+
f"supported by {type(self).__name__}; using "
|
| 449 |
+
f"{self.supported_formats[0]} instead.")
|
| 450 |
+
self._frame_format = self.supported_formats[0]
|
| 451 |
+
|
| 452 |
+
def _base_temp_name(self):
|
| 453 |
+
# Generates a template name (without number) given the frame format
|
| 454 |
+
# for extension and the prefix.
|
| 455 |
+
return self.fname_format_str % (self.temp_prefix, self.frame_format)
|
| 456 |
+
|
| 457 |
+
def grab_frame(self, **savefig_kwargs):
|
| 458 |
+
# docstring inherited
|
| 459 |
+
# Creates a filename for saving using basename and counter.
|
| 460 |
+
path = Path(self._base_temp_name() % self._frame_counter)
|
| 461 |
+
self._temp_paths.append(path) # Record the filename for later use.
|
| 462 |
+
self._frame_counter += 1 # Ensures each created name is unique.
|
| 463 |
+
_log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s',
|
| 464 |
+
self._frame_counter, path)
|
| 465 |
+
with open(path, 'wb') as sink: # Save figure to the sink.
|
| 466 |
+
self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi,
|
| 467 |
+
**savefig_kwargs)
|
| 468 |
+
|
| 469 |
+
def finish(self):
|
| 470 |
+
# Call run here now that all frame grabbing is done. All temp files
|
| 471 |
+
# are available to be assembled.
|
| 472 |
+
try:
|
| 473 |
+
self._run()
|
| 474 |
+
super().finish()
|
| 475 |
+
finally:
|
| 476 |
+
if self._tmpdir:
|
| 477 |
+
_log.debug(
|
| 478 |
+
'MovieWriter: clearing temporary path=%s', self._tmpdir
|
| 479 |
+
)
|
| 480 |
+
self._tmpdir.cleanup()
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
@writers.register('pillow')
|
| 484 |
+
class PillowWriter(AbstractMovieWriter):
|
| 485 |
+
@classmethod
|
| 486 |
+
def isAvailable(cls):
|
| 487 |
+
return True
|
| 488 |
+
|
| 489 |
+
def setup(self, fig, outfile, dpi=None):
|
| 490 |
+
super().setup(fig, outfile, dpi=dpi)
|
| 491 |
+
self._frames = []
|
| 492 |
+
|
| 493 |
+
def grab_frame(self, **savefig_kwargs):
|
| 494 |
+
buf = BytesIO()
|
| 495 |
+
self.fig.savefig(
|
| 496 |
+
buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
|
| 497 |
+
self._frames.append(Image.frombuffer(
|
| 498 |
+
"RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1))
|
| 499 |
+
|
| 500 |
+
def finish(self):
|
| 501 |
+
self._frames[0].save(
|
| 502 |
+
self.outfile, save_all=True, append_images=self._frames[1:],
|
| 503 |
+
duration=int(1000 / self.fps), loop=0)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
# Base class of ffmpeg information. Has the config keys and the common set
|
| 507 |
+
# of arguments that controls the *output* side of things.
|
| 508 |
+
class FFMpegBase:
|
| 509 |
+
"""
|
| 510 |
+
Mixin class for FFMpeg output.
|
| 511 |
+
|
| 512 |
+
This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter`
|
| 513 |
+
classes.
|
| 514 |
+
"""
|
| 515 |
+
|
| 516 |
+
_exec_key = 'animation.ffmpeg_path'
|
| 517 |
+
_args_key = 'animation.ffmpeg_args'
|
| 518 |
+
|
| 519 |
+
@property
|
| 520 |
+
def output_args(self):
|
| 521 |
+
args = []
|
| 522 |
+
if Path(self.outfile).suffix == '.gif':
|
| 523 |
+
self.codec = 'gif'
|
| 524 |
+
else:
|
| 525 |
+
args.extend(['-vcodec', self.codec])
|
| 526 |
+
extra_args = (self.extra_args if self.extra_args is not None
|
| 527 |
+
else mpl.rcParams[self._args_key])
|
| 528 |
+
# For h264, the default format is yuv444p, which is not compatible
|
| 529 |
+
# with quicktime (and others). Specifying yuv420p fixes playback on
|
| 530 |
+
# iOS, as well as HTML5 video in firefox and safari (on both Win and
|
| 531 |
+
# OSX). Also fixes internet explorer. This is as of 2015/10/29.
|
| 532 |
+
if self.codec == 'h264' and '-pix_fmt' not in extra_args:
|
| 533 |
+
args.extend(['-pix_fmt', 'yuv420p'])
|
| 534 |
+
# For GIF, we're telling FFMPEG to split the video stream, to generate
|
| 535 |
+
# a palette, and then use it for encoding.
|
| 536 |
+
elif self.codec == 'gif' and '-filter_complex' not in extra_args:
|
| 537 |
+
args.extend(['-filter_complex',
|
| 538 |
+
'split [a][b];[a] palettegen [p];[b][p] paletteuse'])
|
| 539 |
+
if self.bitrate > 0:
|
| 540 |
+
args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
|
| 541 |
+
args.extend(extra_args)
|
| 542 |
+
for k, v in self.metadata.items():
|
| 543 |
+
args.extend(['-metadata', '%s=%s' % (k, v)])
|
| 544 |
+
|
| 545 |
+
return args + ['-y', self.outfile]
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
# Combine FFMpeg options with pipe-based writing
|
| 549 |
+
@writers.register('ffmpeg')
|
| 550 |
+
class FFMpegWriter(FFMpegBase, MovieWriter):
|
| 551 |
+
"""
|
| 552 |
+
Pipe-based ffmpeg writer.
|
| 553 |
+
|
| 554 |
+
Frames are streamed directly to ffmpeg via a pipe and written in a single
|
| 555 |
+
pass.
|
| 556 |
+
"""
|
| 557 |
+
def _args(self):
|
| 558 |
+
# Returns the command line parameters for subprocess to use
|
| 559 |
+
# ffmpeg to create a movie using a pipe.
|
| 560 |
+
args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
|
| 561 |
+
'-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
|
| 562 |
+
'-r', str(self.fps)]
|
| 563 |
+
# Logging is quieted because subprocess.PIPE has limited buffer size.
|
| 564 |
+
# If you have a lot of frames in your animation and set logging to
|
| 565 |
+
# DEBUG, you will have a buffer overrun.
|
| 566 |
+
if _log.getEffectiveLevel() > logging.DEBUG:
|
| 567 |
+
args += ['-loglevel', 'error']
|
| 568 |
+
args += ['-i', 'pipe:'] + self.output_args
|
| 569 |
+
return args
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
# Combine FFMpeg options with temp file-based writing
|
| 573 |
+
@writers.register('ffmpeg_file')
|
| 574 |
+
class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
|
| 575 |
+
"""
|
| 576 |
+
File-based ffmpeg writer.
|
| 577 |
+
|
| 578 |
+
Frames are written to temporary files on disk and then stitched
|
| 579 |
+
together at the end.
|
| 580 |
+
"""
|
| 581 |
+
supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
|
| 582 |
+
|
| 583 |
+
def _args(self):
|
| 584 |
+
# Returns the command line parameters for subprocess to use
|
| 585 |
+
# ffmpeg to create a movie using a collection of temp images
|
| 586 |
+
args = []
|
| 587 |
+
# For raw frames, we need to explicitly tell ffmpeg the metadata.
|
| 588 |
+
if self.frame_format in {'raw', 'rgba'}:
|
| 589 |
+
args += [
|
| 590 |
+
'-f', 'image2', '-vcodec', 'rawvideo',
|
| 591 |
+
'-video_size', '%dx%d' % self.frame_size,
|
| 592 |
+
'-pixel_format', 'rgba',
|
| 593 |
+
'-framerate', str(self.fps),
|
| 594 |
+
]
|
| 595 |
+
args += ['-r', str(self.fps), '-i', self._base_temp_name(),
|
| 596 |
+
'-vframes', str(self._frame_counter)]
|
| 597 |
+
# Logging is quieted because subprocess.PIPE has limited buffer size.
|
| 598 |
+
# If you have a lot of frames in your animation and set logging to
|
| 599 |
+
# DEBUG, you will have a buffer overrun.
|
| 600 |
+
if _log.getEffectiveLevel() > logging.DEBUG:
|
| 601 |
+
args += ['-loglevel', 'error']
|
| 602 |
+
return [self.bin_path(), *args, *self.output_args]
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
# Base class for animated GIFs with ImageMagick
|
| 606 |
+
class ImageMagickBase:
|
| 607 |
+
"""
|
| 608 |
+
Mixin class for ImageMagick output.
|
| 609 |
+
|
| 610 |
+
This is a base class for the concrete `ImageMagickWriter` and
|
| 611 |
+
`ImageMagickFileWriter` classes, which define an ``input_names`` attribute
|
| 612 |
+
(or property) specifying the input names passed to ImageMagick.
|
| 613 |
+
"""
|
| 614 |
+
|
| 615 |
+
_exec_key = 'animation.convert_path'
|
| 616 |
+
_args_key = 'animation.convert_args'
|
| 617 |
+
|
| 618 |
+
@_api.deprecated("3.6")
|
| 619 |
+
@property
|
| 620 |
+
def delay(self):
|
| 621 |
+
return 100. / self.fps
|
| 622 |
+
|
| 623 |
+
@_api.deprecated("3.6")
|
| 624 |
+
@property
|
| 625 |
+
def output_args(self):
|
| 626 |
+
extra_args = (self.extra_args if self.extra_args is not None
|
| 627 |
+
else mpl.rcParams[self._args_key])
|
| 628 |
+
return [*extra_args, self.outfile]
|
| 629 |
+
|
| 630 |
+
def _args(self):
|
| 631 |
+
# ImageMagick does not recognize "raw".
|
| 632 |
+
fmt = "rgba" if self.frame_format == "raw" else self.frame_format
|
| 633 |
+
extra_args = (self.extra_args if self.extra_args is not None
|
| 634 |
+
else mpl.rcParams[self._args_key])
|
| 635 |
+
return [
|
| 636 |
+
self.bin_path(),
|
| 637 |
+
"-size", "%ix%i" % self.frame_size,
|
| 638 |
+
"-depth", "8",
|
| 639 |
+
"-delay", str(100 / self.fps),
|
| 640 |
+
"-loop", "0",
|
| 641 |
+
f"{fmt}:{self.input_names}",
|
| 642 |
+
*extra_args,
|
| 643 |
+
self.outfile,
|
| 644 |
+
]
|
| 645 |
+
|
| 646 |
+
@classmethod
|
| 647 |
+
def bin_path(cls):
|
| 648 |
+
binpath = super().bin_path()
|
| 649 |
+
if binpath == 'convert':
|
| 650 |
+
binpath = mpl._get_executable_info('magick').executable
|
| 651 |
+
return binpath
|
| 652 |
+
|
| 653 |
+
@classmethod
|
| 654 |
+
def isAvailable(cls):
|
| 655 |
+
try:
|
| 656 |
+
return super().isAvailable()
|
| 657 |
+
except mpl.ExecutableNotFoundError as _enf:
|
| 658 |
+
# May be raised by get_executable_info.
|
| 659 |
+
_log.debug('ImageMagick unavailable due to: %s', _enf)
|
| 660 |
+
return False
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
# Combine ImageMagick options with pipe-based writing
|
| 664 |
+
@writers.register('imagemagick')
|
| 665 |
+
class ImageMagickWriter(ImageMagickBase, MovieWriter):
|
| 666 |
+
"""
|
| 667 |
+
Pipe-based animated gif writer.
|
| 668 |
+
|
| 669 |
+
Frames are streamed directly to ImageMagick via a pipe and written
|
| 670 |
+
in a single pass.
|
| 671 |
+
"""
|
| 672 |
+
|
| 673 |
+
input_names = "-" # stdin
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
# Combine ImageMagick options with temp file-based writing
|
| 677 |
+
@writers.register('imagemagick_file')
|
| 678 |
+
class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
|
| 679 |
+
"""
|
| 680 |
+
File-based animated gif writer.
|
| 681 |
+
|
| 682 |
+
Frames are written to temporary files on disk and then stitched
|
| 683 |
+
together at the end.
|
| 684 |
+
"""
|
| 685 |
+
|
| 686 |
+
supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
|
| 687 |
+
input_names = property(
|
| 688 |
+
lambda self: f'{self.temp_prefix}*.{self.frame_format}')
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
# Taken directly from jakevdp's JSAnimation package at
|
| 692 |
+
# http://github.com/jakevdp/JSAnimation
|
| 693 |
+
def _included_frames(frame_count, frame_format, frame_dir):
|
| 694 |
+
return INCLUDED_FRAMES.format(Nframes=frame_count,
|
| 695 |
+
frame_dir=frame_dir,
|
| 696 |
+
frame_format=frame_format)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def _embedded_frames(frame_list, frame_format):
|
| 700 |
+
"""frame_list should be a list of base64-encoded png files"""
|
| 701 |
+
if frame_format == 'svg':
|
| 702 |
+
# Fix MIME type for svg
|
| 703 |
+
frame_format = 'svg+xml'
|
| 704 |
+
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
|
| 705 |
+
return "\n" + "".join(
|
| 706 |
+
template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
|
| 707 |
+
for i, frame_data in enumerate(frame_list))
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
@writers.register('html')
|
| 711 |
+
class HTMLWriter(FileMovieWriter):
|
| 712 |
+
"""Writer for JavaScript-based HTML movies."""
|
| 713 |
+
|
| 714 |
+
supported_formats = ['png', 'jpeg', 'tiff', 'svg']
|
| 715 |
+
|
| 716 |
+
@classmethod
|
| 717 |
+
def isAvailable(cls):
|
| 718 |
+
return True
|
| 719 |
+
|
| 720 |
+
def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
|
| 721 |
+
metadata=None, embed_frames=False, default_mode='loop',
|
| 722 |
+
embed_limit=None):
|
| 723 |
+
|
| 724 |
+
if extra_args:
|
| 725 |
+
_log.warning("HTMLWriter ignores 'extra_args'")
|
| 726 |
+
extra_args = () # Don't lookup nonexistent rcParam[args_key].
|
| 727 |
+
self.embed_frames = embed_frames
|
| 728 |
+
self.default_mode = default_mode.lower()
|
| 729 |
+
_api.check_in_list(['loop', 'once', 'reflect'],
|
| 730 |
+
default_mode=self.default_mode)
|
| 731 |
+
|
| 732 |
+
# Save embed limit, which is given in MB
|
| 733 |
+
if embed_limit is None:
|
| 734 |
+
self._bytes_limit = mpl.rcParams['animation.embed_limit']
|
| 735 |
+
else:
|
| 736 |
+
self._bytes_limit = embed_limit
|
| 737 |
+
# Convert from MB to bytes
|
| 738 |
+
self._bytes_limit *= 1024 * 1024
|
| 739 |
+
|
| 740 |
+
super().__init__(fps, codec, bitrate, extra_args, metadata)
|
| 741 |
+
|
| 742 |
+
def setup(self, fig, outfile, dpi=None, frame_dir=None):
|
| 743 |
+
outfile = Path(outfile)
|
| 744 |
+
_api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)
|
| 745 |
+
|
| 746 |
+
self._saved_frames = []
|
| 747 |
+
self._total_bytes = 0
|
| 748 |
+
self._hit_limit = False
|
| 749 |
+
|
| 750 |
+
if not self.embed_frames:
|
| 751 |
+
if frame_dir is None:
|
| 752 |
+
frame_dir = outfile.with_name(outfile.stem + '_frames')
|
| 753 |
+
frame_dir.mkdir(parents=True, exist_ok=True)
|
| 754 |
+
frame_prefix = frame_dir / 'frame'
|
| 755 |
+
else:
|
| 756 |
+
frame_prefix = None
|
| 757 |
+
|
| 758 |
+
super().setup(fig, outfile, dpi, frame_prefix)
|
| 759 |
+
self._clear_temp = False
|
| 760 |
+
|
| 761 |
+
def grab_frame(self, **savefig_kwargs):
|
| 762 |
+
if self.embed_frames:
|
| 763 |
+
# Just stop processing if we hit the limit
|
| 764 |
+
if self._hit_limit:
|
| 765 |
+
return
|
| 766 |
+
f = BytesIO()
|
| 767 |
+
self.fig.savefig(f, format=self.frame_format,
|
| 768 |
+
dpi=self.dpi, **savefig_kwargs)
|
| 769 |
+
imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
|
| 770 |
+
self._total_bytes += len(imgdata64)
|
| 771 |
+
if self._total_bytes >= self._bytes_limit:
|
| 772 |
+
_log.warning(
|
| 773 |
+
"Animation size has reached %s bytes, exceeding the limit "
|
| 774 |
+
"of %s. If you're sure you want a larger animation "
|
| 775 |
+
"embedded, set the animation.embed_limit rc parameter to "
|
| 776 |
+
"a larger value (in MB). This and further frames will be "
|
| 777 |
+
"dropped.", self._total_bytes, self._bytes_limit)
|
| 778 |
+
self._hit_limit = True
|
| 779 |
+
else:
|
| 780 |
+
self._saved_frames.append(imgdata64)
|
| 781 |
+
else:
|
| 782 |
+
return super().grab_frame(**savefig_kwargs)
|
| 783 |
+
|
| 784 |
+
def finish(self):
|
| 785 |
+
# save the frames to an html file
|
| 786 |
+
if self.embed_frames:
|
| 787 |
+
fill_frames = _embedded_frames(self._saved_frames,
|
| 788 |
+
self.frame_format)
|
| 789 |
+
frame_count = len(self._saved_frames)
|
| 790 |
+
else:
|
| 791 |
+
# temp names is filled by FileMovieWriter
|
| 792 |
+
frame_count = len(self._temp_paths)
|
| 793 |
+
fill_frames = _included_frames(
|
| 794 |
+
frame_count, self.frame_format,
|
| 795 |
+
self._temp_paths[0].parent.relative_to(self.outfile.parent))
|
| 796 |
+
mode_dict = dict(once_checked='',
|
| 797 |
+
loop_checked='',
|
| 798 |
+
reflect_checked='')
|
| 799 |
+
mode_dict[self.default_mode + '_checked'] = 'checked'
|
| 800 |
+
|
| 801 |
+
interval = 1000 // self.fps
|
| 802 |
+
|
| 803 |
+
with open(self.outfile, 'w') as of:
|
| 804 |
+
of.write(JS_INCLUDE + STYLE_INCLUDE)
|
| 805 |
+
of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
|
| 806 |
+
Nframes=frame_count,
|
| 807 |
+
fill_frames=fill_frames,
|
| 808 |
+
interval=interval,
|
| 809 |
+
**mode_dict))
|
| 810 |
+
|
| 811 |
+
# Duplicate the temporary file clean up logic from
|
| 812 |
+
# FileMovieWriter.finish. We can not call the inherited version of
|
| 813 |
+
# finish because it assumes that there is a subprocess that we either
|
| 814 |
+
# need to call to merge many frames together or that there is a
|
| 815 |
+
# subprocess call that we need to clean up.
|
| 816 |
+
if self._tmpdir:
|
| 817 |
+
_log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
|
| 818 |
+
self._tmpdir.cleanup()
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
class Animation:
|
| 822 |
+
"""
|
| 823 |
+
A base class for Animations.
|
| 824 |
+
|
| 825 |
+
This class is not usable as is, and should be subclassed to provide needed
|
| 826 |
+
behavior.
|
| 827 |
+
|
| 828 |
+
.. note::
|
| 829 |
+
|
| 830 |
+
You must store the created Animation in a variable that lives as long
|
| 831 |
+
as the animation should run. Otherwise, the Animation object will be
|
| 832 |
+
garbage-collected and the animation stops.
|
| 833 |
+
|
| 834 |
+
Parameters
|
| 835 |
+
----------
|
| 836 |
+
fig : `~matplotlib.figure.Figure`
|
| 837 |
+
The figure object used to get needed events, such as draw or resize.
|
| 838 |
+
|
| 839 |
+
event_source : object, optional
|
| 840 |
+
A class that can run a callback when desired events
|
| 841 |
+
are generated, as well as be stopped and started.
|
| 842 |
+
|
| 843 |
+
Examples include timers (see `TimedAnimation`) and file
|
| 844 |
+
system notifications.
|
| 845 |
+
|
| 846 |
+
blit : bool, default: False
|
| 847 |
+
Whether blitting is used to optimize drawing. If the backend does not
|
| 848 |
+
support blitting, then this parameter has no effect.
|
| 849 |
+
|
| 850 |
+
See Also
|
| 851 |
+
--------
|
| 852 |
+
FuncAnimation, ArtistAnimation
|
| 853 |
+
"""
|
| 854 |
+
|
| 855 |
+
def __init__(self, fig, event_source=None, blit=False):
|
| 856 |
+
self._draw_was_started = False
|
| 857 |
+
|
| 858 |
+
self._fig = fig
|
| 859 |
+
# Disables blitting for backends that don't support it. This
|
| 860 |
+
# allows users to request it if available, but still have a
|
| 861 |
+
# fallback that works if it is not.
|
| 862 |
+
self._blit = blit and fig.canvas.supports_blit
|
| 863 |
+
|
| 864 |
+
# These are the basics of the animation. The frame sequence represents
|
| 865 |
+
# information for each frame of the animation and depends on how the
|
| 866 |
+
# drawing is handled by the subclasses. The event source fires events
|
| 867 |
+
# that cause the frame sequence to be iterated.
|
| 868 |
+
self.frame_seq = self.new_frame_seq()
|
| 869 |
+
self.event_source = event_source
|
| 870 |
+
|
| 871 |
+
# Instead of starting the event source now, we connect to the figure's
|
| 872 |
+
# draw_event, so that we only start once the figure has been drawn.
|
| 873 |
+
self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
|
| 874 |
+
|
| 875 |
+
# Connect to the figure's close_event so that we don't continue to
|
| 876 |
+
# fire events and try to draw to a deleted figure.
|
| 877 |
+
self._close_id = self._fig.canvas.mpl_connect('close_event',
|
| 878 |
+
self._stop)
|
| 879 |
+
if self._blit:
|
| 880 |
+
self._setup_blit()
|
| 881 |
+
|
| 882 |
+
def __del__(self):
|
| 883 |
+
if not getattr(self, '_draw_was_started', True):
|
| 884 |
+
warnings.warn(
|
| 885 |
+
'Animation was deleted without rendering anything. This is '
|
| 886 |
+
'most likely not intended. To prevent deletion, assign the '
|
| 887 |
+
'Animation to a variable, e.g. `anim`, that exists until you '
|
| 888 |
+
'output the Animation using `plt.show()` or '
|
| 889 |
+
'`anim.save()`.'
|
| 890 |
+
)
|
| 891 |
+
|
| 892 |
+
def _start(self, *args):
|
| 893 |
+
"""
|
| 894 |
+
Starts interactive animation. Adds the draw frame command to the GUI
|
| 895 |
+
handler, calls show to start the event loop.
|
| 896 |
+
"""
|
| 897 |
+
# Do not start the event source if saving() it.
|
| 898 |
+
if self._fig.canvas.is_saving():
|
| 899 |
+
return
|
| 900 |
+
# First disconnect our draw event handler
|
| 901 |
+
self._fig.canvas.mpl_disconnect(self._first_draw_id)
|
| 902 |
+
|
| 903 |
+
# Now do any initial draw
|
| 904 |
+
self._init_draw()
|
| 905 |
+
|
| 906 |
+
# Add our callback for stepping the animation and
|
| 907 |
+
# actually start the event_source.
|
| 908 |
+
self.event_source.add_callback(self._step)
|
| 909 |
+
self.event_source.start()
|
| 910 |
+
|
| 911 |
+
def _stop(self, *args):
|
| 912 |
+
# On stop we disconnect all of our events.
|
| 913 |
+
if self._blit:
|
| 914 |
+
self._fig.canvas.mpl_disconnect(self._resize_id)
|
| 915 |
+
self._fig.canvas.mpl_disconnect(self._close_id)
|
| 916 |
+
self.event_source.remove_callback(self._step)
|
| 917 |
+
self.event_source = None
|
| 918 |
+
|
| 919 |
+
def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
|
| 920 |
+
bitrate=None, extra_args=None, metadata=None, extra_anim=None,
|
| 921 |
+
savefig_kwargs=None, *, progress_callback=None):
|
| 922 |
+
"""
|
| 923 |
+
Save the animation as a movie file by drawing every frame.
|
| 924 |
+
|
| 925 |
+
Parameters
|
| 926 |
+
----------
|
| 927 |
+
filename : str
|
| 928 |
+
The output filename, e.g., :file:`mymovie.mp4`.
|
| 929 |
+
|
| 930 |
+
writer : `MovieWriter` or str, default: :rc:`animation.writer`
|
| 931 |
+
A `MovieWriter` instance to use or a key that identifies a
|
| 932 |
+
class to use, such as 'ffmpeg'.
|
| 933 |
+
|
| 934 |
+
fps : int, optional
|
| 935 |
+
Movie frame rate (per second). If not set, the frame rate from the
|
| 936 |
+
animation's frame interval.
|
| 937 |
+
|
| 938 |
+
dpi : float, default: :rc:`savefig.dpi`
|
| 939 |
+
Controls the dots per inch for the movie frames. Together with
|
| 940 |
+
the figure's size in inches, this controls the size of the movie.
|
| 941 |
+
|
| 942 |
+
codec : str, default: :rc:`animation.codec`.
|
| 943 |
+
The video codec to use. Not all codecs are supported by a given
|
| 944 |
+
`MovieWriter`.
|
| 945 |
+
|
| 946 |
+
bitrate : int, default: :rc:`animation.bitrate`
|
| 947 |
+
The bitrate of the movie, in kilobits per second. Higher values
|
| 948 |
+
means higher quality movies, but increase the file size. A value
|
| 949 |
+
of -1 lets the underlying movie encoder select the bitrate.
|
| 950 |
+
|
| 951 |
+
extra_args : list of str or None, optional
|
| 952 |
+
Extra command-line arguments passed to the underlying movie
|
| 953 |
+
encoder. The default, None, means to use
|
| 954 |
+
:rc:`animation.[name-of-encoder]_args` for the builtin writers.
|
| 955 |
+
|
| 956 |
+
metadata : dict[str, str], default: {}
|
| 957 |
+
Dictionary of keys and values for metadata to include in
|
| 958 |
+
the output file. Some keys that may be of use include:
|
| 959 |
+
title, artist, genre, subject, copyright, srcform, comment.
|
| 960 |
+
|
| 961 |
+
extra_anim : list, default: []
|
| 962 |
+
Additional `Animation` objects that should be included
|
| 963 |
+
in the saved movie file. These need to be from the same
|
| 964 |
+
`.Figure` instance. Also, animation frames will
|
| 965 |
+
just be simply combined, so there should be a 1:1 correspondence
|
| 966 |
+
between the frames from the different animations.
|
| 967 |
+
|
| 968 |
+
savefig_kwargs : dict, default: {}
|
| 969 |
+
Keyword arguments passed to each `~.Figure.savefig` call used to
|
| 970 |
+
save the individual frames.
|
| 971 |
+
|
| 972 |
+
progress_callback : function, optional
|
| 973 |
+
A callback function that will be called for every frame to notify
|
| 974 |
+
the saving progress. It must have the signature ::
|
| 975 |
+
|
| 976 |
+
def func(current_frame: int, total_frames: int) -> Any
|
| 977 |
+
|
| 978 |
+
where *current_frame* is the current frame number and
|
| 979 |
+
*total_frames* is the total number of frames to be saved.
|
| 980 |
+
*total_frames* is set to None, if the total number of frames can
|
| 981 |
+
not be determined. Return values may exist but are ignored.
|
| 982 |
+
|
| 983 |
+
Example code to write the progress to stdout::
|
| 984 |
+
|
| 985 |
+
progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
|
| 986 |
+
|
| 987 |
+
Notes
|
| 988 |
+
-----
|
| 989 |
+
*fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
|
| 990 |
+
construct a `.MovieWriter` instance and can only be passed if
|
| 991 |
+
*writer* is a string. If they are passed as non-*None* and *writer*
|
| 992 |
+
is a `.MovieWriter`, a `RuntimeError` will be raised.
|
| 993 |
+
"""
|
| 994 |
+
|
| 995 |
+
all_anim = [self]
|
| 996 |
+
if extra_anim is not None:
|
| 997 |
+
all_anim.extend(anim for anim in extra_anim
|
| 998 |
+
if anim._fig is self._fig)
|
| 999 |
+
|
| 1000 |
+
# Disable "Animation was deleted without rendering" warning.
|
| 1001 |
+
for anim in all_anim:
|
| 1002 |
+
anim._draw_was_started = True
|
| 1003 |
+
|
| 1004 |
+
if writer is None:
|
| 1005 |
+
writer = mpl.rcParams['animation.writer']
|
| 1006 |
+
elif (not isinstance(writer, str) and
|
| 1007 |
+
any(arg is not None
|
| 1008 |
+
for arg in (fps, codec, bitrate, extra_args, metadata))):
|
| 1009 |
+
raise RuntimeError('Passing in values for arguments '
|
| 1010 |
+
'fps, codec, bitrate, extra_args, or metadata '
|
| 1011 |
+
'is not supported when writer is an existing '
|
| 1012 |
+
'MovieWriter instance. These should instead be '
|
| 1013 |
+
'passed as arguments when creating the '
|
| 1014 |
+
'MovieWriter instance.')
|
| 1015 |
+
|
| 1016 |
+
if savefig_kwargs is None:
|
| 1017 |
+
savefig_kwargs = {}
|
| 1018 |
+
else:
|
| 1019 |
+
# we are going to mutate this below
|
| 1020 |
+
savefig_kwargs = dict(savefig_kwargs)
|
| 1021 |
+
|
| 1022 |
+
if fps is None and hasattr(self, '_interval'):
|
| 1023 |
+
# Convert interval in ms to frames per second
|
| 1024 |
+
fps = 1000. / self._interval
|
| 1025 |
+
|
| 1026 |
+
# Re-use the savefig DPI for ours if none is given
|
| 1027 |
+
if dpi is None:
|
| 1028 |
+
dpi = mpl.rcParams['savefig.dpi']
|
| 1029 |
+
if dpi == 'figure':
|
| 1030 |
+
dpi = self._fig.dpi
|
| 1031 |
+
|
| 1032 |
+
writer_kwargs = {}
|
| 1033 |
+
if codec is not None:
|
| 1034 |
+
writer_kwargs['codec'] = codec
|
| 1035 |
+
if bitrate is not None:
|
| 1036 |
+
writer_kwargs['bitrate'] = bitrate
|
| 1037 |
+
if extra_args is not None:
|
| 1038 |
+
writer_kwargs['extra_args'] = extra_args
|
| 1039 |
+
if metadata is not None:
|
| 1040 |
+
writer_kwargs['metadata'] = metadata
|
| 1041 |
+
|
| 1042 |
+
# If we have the name of a writer, instantiate an instance of the
|
| 1043 |
+
# registered class.
|
| 1044 |
+
if isinstance(writer, str):
|
| 1045 |
+
try:
|
| 1046 |
+
writer_cls = writers[writer]
|
| 1047 |
+
except RuntimeError: # Raised if not available.
|
| 1048 |
+
writer_cls = PillowWriter # Always available.
|
| 1049 |
+
_log.warning("MovieWriter %s unavailable; using Pillow "
|
| 1050 |
+
"instead.", writer)
|
| 1051 |
+
writer = writer_cls(fps, **writer_kwargs)
|
| 1052 |
+
_log.info('Animation.save using %s', type(writer))
|
| 1053 |
+
|
| 1054 |
+
if 'bbox_inches' in savefig_kwargs:
|
| 1055 |
+
_log.warning("Warning: discarding the 'bbox_inches' argument in "
|
| 1056 |
+
"'savefig_kwargs' as it may cause frame size "
|
| 1057 |
+
"to vary, which is inappropriate for animation.")
|
| 1058 |
+
savefig_kwargs.pop('bbox_inches')
|
| 1059 |
+
|
| 1060 |
+
# Create a new sequence of frames for saved data. This is different
|
| 1061 |
+
# from new_frame_seq() to give the ability to save 'live' generated
|
| 1062 |
+
# frame information to be saved later.
|
| 1063 |
+
# TODO: Right now, after closing the figure, saving a movie won't work
|
| 1064 |
+
# since GUI widgets are gone. Either need to remove extra code to
|
| 1065 |
+
# allow for this non-existent use case or find a way to make it work.
|
| 1066 |
+
if mpl.rcParams['savefig.bbox'] == 'tight':
|
| 1067 |
+
_log.info("Disabling savefig.bbox = 'tight', as it may cause "
|
| 1068 |
+
"frame size to vary, which is inappropriate for "
|
| 1069 |
+
"animation.")
|
| 1070 |
+
|
| 1071 |
+
facecolor = savefig_kwargs.get('facecolor',
|
| 1072 |
+
mpl.rcParams['savefig.facecolor'])
|
| 1073 |
+
if facecolor == 'auto':
|
| 1074 |
+
facecolor = self._fig.get_facecolor()
|
| 1075 |
+
|
| 1076 |
+
def _pre_composite_to_white(color):
|
| 1077 |
+
r, g, b, a = mcolors.to_rgba(color)
|
| 1078 |
+
return a * np.array([r, g, b]) + 1 - a
|
| 1079 |
+
|
| 1080 |
+
savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor)
|
| 1081 |
+
savefig_kwargs['transparent'] = False # just to be safe!
|
| 1082 |
+
# canvas._is_saving = True makes the draw_event animation-starting
|
| 1083 |
+
# callback a no-op; canvas.manager = None prevents resizing the GUI
|
| 1084 |
+
# widget (both are likewise done in savefig()).
|
| 1085 |
+
with mpl.rc_context({'savefig.bbox': None}), \
|
| 1086 |
+
writer.saving(self._fig, filename, dpi), \
|
| 1087 |
+
cbook._setattr_cm(self._fig.canvas,
|
| 1088 |
+
_is_saving=True, manager=None):
|
| 1089 |
+
for anim in all_anim:
|
| 1090 |
+
anim._init_draw() # Clear the initial frame
|
| 1091 |
+
frame_number = 0
|
| 1092 |
+
# TODO: Currently only FuncAnimation has a save_count
|
| 1093 |
+
# attribute. Can we generalize this to all Animations?
|
| 1094 |
+
save_count_list = [getattr(a, '_save_count', None)
|
| 1095 |
+
for a in all_anim]
|
| 1096 |
+
if None in save_count_list:
|
| 1097 |
+
total_frames = None
|
| 1098 |
+
else:
|
| 1099 |
+
total_frames = sum(save_count_list)
|
| 1100 |
+
for data in zip(*[a.new_saved_frame_seq() for a in all_anim]):
|
| 1101 |
+
for anim, d in zip(all_anim, data):
|
| 1102 |
+
# TODO: See if turning off blit is really necessary
|
| 1103 |
+
anim._draw_next_frame(d, blit=False)
|
| 1104 |
+
if progress_callback is not None:
|
| 1105 |
+
progress_callback(frame_number, total_frames)
|
| 1106 |
+
frame_number += 1
|
| 1107 |
+
writer.grab_frame(**savefig_kwargs)
|
| 1108 |
+
|
| 1109 |
+
def _step(self, *args):
|
| 1110 |
+
"""
|
| 1111 |
+
Handler for getting events. By default, gets the next frame in the
|
| 1112 |
+
sequence and hands the data off to be drawn.
|
| 1113 |
+
"""
|
| 1114 |
+
# Returns True to indicate that the event source should continue to
|
| 1115 |
+
# call _step, until the frame sequence reaches the end of iteration,
|
| 1116 |
+
# at which point False will be returned.
|
| 1117 |
+
try:
|
| 1118 |
+
framedata = next(self.frame_seq)
|
| 1119 |
+
self._draw_next_frame(framedata, self._blit)
|
| 1120 |
+
return True
|
| 1121 |
+
except StopIteration:
|
| 1122 |
+
return False
|
| 1123 |
+
|
| 1124 |
+
def new_frame_seq(self):
|
| 1125 |
+
"""Return a new sequence of frame information."""
|
| 1126 |
+
# Default implementation is just an iterator over self._framedata
|
| 1127 |
+
return iter(self._framedata)
|
| 1128 |
+
|
| 1129 |
+
def new_saved_frame_seq(self):
|
| 1130 |
+
"""Return a new sequence of saved/cached frame information."""
|
| 1131 |
+
# Default is the same as the regular frame sequence
|
| 1132 |
+
return self.new_frame_seq()
|
| 1133 |
+
|
| 1134 |
+
def _draw_next_frame(self, framedata, blit):
|
| 1135 |
+
# Breaks down the drawing of the next frame into steps of pre- and
|
| 1136 |
+
# post- draw, as well as the drawing of the frame itself.
|
| 1137 |
+
self._pre_draw(framedata, blit)
|
| 1138 |
+
self._draw_frame(framedata)
|
| 1139 |
+
self._post_draw(framedata, blit)
|
| 1140 |
+
|
| 1141 |
+
def _init_draw(self):
|
| 1142 |
+
# Initial draw to clear the frame. Also used by the blitting code
|
| 1143 |
+
# when a clean base is required.
|
| 1144 |
+
self._draw_was_started = True
|
| 1145 |
+
|
| 1146 |
+
def _pre_draw(self, framedata, blit):
|
| 1147 |
+
# Perform any cleaning or whatnot before the drawing of the frame.
|
| 1148 |
+
# This default implementation allows blit to clear the frame.
|
| 1149 |
+
if blit:
|
| 1150 |
+
self._blit_clear(self._drawn_artists)
|
| 1151 |
+
|
| 1152 |
+
def _draw_frame(self, framedata):
|
| 1153 |
+
# Performs actual drawing of the frame.
|
| 1154 |
+
raise NotImplementedError('Needs to be implemented by subclasses to'
|
| 1155 |
+
' actually make an animation.')
|
| 1156 |
+
|
| 1157 |
+
def _post_draw(self, framedata, blit):
|
| 1158 |
+
# After the frame is rendered, this handles the actual flushing of
|
| 1159 |
+
# the draw, which can be a direct draw_idle() or make use of the
|
| 1160 |
+
# blitting.
|
| 1161 |
+
if blit and self._drawn_artists:
|
| 1162 |
+
self._blit_draw(self._drawn_artists)
|
| 1163 |
+
else:
|
| 1164 |
+
self._fig.canvas.draw_idle()
|
| 1165 |
+
|
| 1166 |
+
# The rest of the code in this class is to facilitate easy blitting
|
| 1167 |
+
def _blit_draw(self, artists):
|
| 1168 |
+
# Handles blitted drawing, which renders only the artists given instead
|
| 1169 |
+
# of the entire figure.
|
| 1170 |
+
updated_ax = {a.axes for a in artists}
|
| 1171 |
+
# Enumerate artists to cache Axes backgrounds. We do not draw
|
| 1172 |
+
# artists yet to not cache foreground from plots with shared axes
|
| 1173 |
+
for ax in updated_ax:
|
| 1174 |
+
# If we haven't cached the background for the current view of this
|
| 1175 |
+
# Axes object, do so now. This might not always be reliable, but
|
| 1176 |
+
# it's an attempt to automate the process.
|
| 1177 |
+
cur_view = ax._get_view()
|
| 1178 |
+
view, bg = self._blit_cache.get(ax, (object(), None))
|
| 1179 |
+
if cur_view != view:
|
| 1180 |
+
self._blit_cache[ax] = (
|
| 1181 |
+
cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox))
|
| 1182 |
+
# Make a separate pass to draw foreground.
|
| 1183 |
+
for a in artists:
|
| 1184 |
+
a.axes.draw_artist(a)
|
| 1185 |
+
# After rendering all the needed artists, blit each Axes individually.
|
| 1186 |
+
for ax in updated_ax:
|
| 1187 |
+
ax.figure.canvas.blit(ax.bbox)
|
| 1188 |
+
|
| 1189 |
+
def _blit_clear(self, artists):
|
| 1190 |
+
# Get a list of the Axes that need clearing from the artists that
|
| 1191 |
+
# have been drawn. Grab the appropriate saved background from the
|
| 1192 |
+
# cache and restore.
|
| 1193 |
+
axes = {a.axes for a in artists}
|
| 1194 |
+
for ax in axes:
|
| 1195 |
+
try:
|
| 1196 |
+
view, bg = self._blit_cache[ax]
|
| 1197 |
+
except KeyError:
|
| 1198 |
+
continue
|
| 1199 |
+
if ax._get_view() == view:
|
| 1200 |
+
ax.figure.canvas.restore_region(bg)
|
| 1201 |
+
else:
|
| 1202 |
+
self._blit_cache.pop(ax)
|
| 1203 |
+
|
| 1204 |
+
def _setup_blit(self):
|
| 1205 |
+
# Setting up the blit requires: a cache of the background for the Axes
|
| 1206 |
+
self._blit_cache = dict()
|
| 1207 |
+
self._drawn_artists = []
|
| 1208 |
+
# _post_draw needs to be called first to initialize the renderer
|
| 1209 |
+
self._post_draw(None, self._blit)
|
| 1210 |
+
# Then we need to clear the Frame for the initial draw
|
| 1211 |
+
# This is typically handled in _on_resize because QT and Tk
|
| 1212 |
+
# emit a resize event on launch, but the macosx backend does not,
|
| 1213 |
+
# thus we force it here for everyone for consistency
|
| 1214 |
+
self._init_draw()
|
| 1215 |
+
# Connect to future resize events
|
| 1216 |
+
self._resize_id = self._fig.canvas.mpl_connect('resize_event',
|
| 1217 |
+
self._on_resize)
|
| 1218 |
+
|
| 1219 |
+
def _on_resize(self, event):
|
| 1220 |
+
# On resize, we need to disable the resize event handling so we don't
|
| 1221 |
+
# get too many events. Also stop the animation events, so that
|
| 1222 |
+
# we're paused. Reset the cache and re-init. Set up an event handler
|
| 1223 |
+
# to catch once the draw has actually taken place.
|
| 1224 |
+
self._fig.canvas.mpl_disconnect(self._resize_id)
|
| 1225 |
+
self.event_source.stop()
|
| 1226 |
+
self._blit_cache.clear()
|
| 1227 |
+
self._init_draw()
|
| 1228 |
+
self._resize_id = self._fig.canvas.mpl_connect('draw_event',
|
| 1229 |
+
self._end_redraw)
|
| 1230 |
+
|
| 1231 |
+
def _end_redraw(self, event):
|
| 1232 |
+
# Now that the redraw has happened, do the post draw flushing and
|
| 1233 |
+
# blit handling. Then re-enable all of the original events.
|
| 1234 |
+
self._post_draw(None, False)
|
| 1235 |
+
self.event_source.start()
|
| 1236 |
+
self._fig.canvas.mpl_disconnect(self._resize_id)
|
| 1237 |
+
self._resize_id = self._fig.canvas.mpl_connect('resize_event',
|
| 1238 |
+
self._on_resize)
|
| 1239 |
+
|
| 1240 |
+
def to_html5_video(self, embed_limit=None):
|
| 1241 |
+
"""
|
| 1242 |
+
Convert the animation to an HTML5 ``<video>`` tag.
|
| 1243 |
+
|
| 1244 |
+
This saves the animation as an h264 video, encoded in base64
|
| 1245 |
+
directly into the HTML5 video tag. This respects :rc:`animation.writer`
|
| 1246 |
+
and :rc:`animation.bitrate`. This also makes use of the
|
| 1247 |
+
*interval* to control the speed, and uses the *repeat*
|
| 1248 |
+
parameter to decide whether to loop.
|
| 1249 |
+
|
| 1250 |
+
Parameters
|
| 1251 |
+
----------
|
| 1252 |
+
embed_limit : float, optional
|
| 1253 |
+
Limit, in MB, of the returned animation. No animation is created
|
| 1254 |
+
if the limit is exceeded.
|
| 1255 |
+
Defaults to :rc:`animation.embed_limit` = 20.0.
|
| 1256 |
+
|
| 1257 |
+
Returns
|
| 1258 |
+
-------
|
| 1259 |
+
str
|
| 1260 |
+
An HTML5 video tag with the animation embedded as base64 encoded
|
| 1261 |
+
h264 video.
|
| 1262 |
+
If the *embed_limit* is exceeded, this returns the string
|
| 1263 |
+
"Video too large to embed."
|
| 1264 |
+
"""
|
| 1265 |
+
VIDEO_TAG = r'''<video {size} {options}>
|
| 1266 |
+
<source type="video/mp4" src="data:video/mp4;base64,{video}">
|
| 1267 |
+
Your browser does not support the video tag.
|
| 1268 |
+
</video>'''
|
| 1269 |
+
# Cache the rendering of the video as HTML
|
| 1270 |
+
if not hasattr(self, '_base64_video'):
|
| 1271 |
+
# Save embed limit, which is given in MB
|
| 1272 |
+
if embed_limit is None:
|
| 1273 |
+
embed_limit = mpl.rcParams['animation.embed_limit']
|
| 1274 |
+
|
| 1275 |
+
# Convert from MB to bytes
|
| 1276 |
+
embed_limit *= 1024 * 1024
|
| 1277 |
+
|
| 1278 |
+
# Can't open a NamedTemporaryFile twice on Windows, so use a
|
| 1279 |
+
# TemporaryDirectory instead.
|
| 1280 |
+
with TemporaryDirectory() as tmpdir:
|
| 1281 |
+
path = Path(tmpdir, "temp.m4v")
|
| 1282 |
+
# We create a writer manually so that we can get the
|
| 1283 |
+
# appropriate size for the tag
|
| 1284 |
+
Writer = writers[mpl.rcParams['animation.writer']]
|
| 1285 |
+
writer = Writer(codec='h264',
|
| 1286 |
+
bitrate=mpl.rcParams['animation.bitrate'],
|
| 1287 |
+
fps=1000. / self._interval)
|
| 1288 |
+
self.save(str(path), writer=writer)
|
| 1289 |
+
# Now open and base64 encode.
|
| 1290 |
+
vid64 = base64.encodebytes(path.read_bytes())
|
| 1291 |
+
|
| 1292 |
+
vid_len = len(vid64)
|
| 1293 |
+
if vid_len >= embed_limit:
|
| 1294 |
+
_log.warning(
|
| 1295 |
+
"Animation movie is %s bytes, exceeding the limit of %s. "
|
| 1296 |
+
"If you're sure you want a large animation embedded, set "
|
| 1297 |
+
"the animation.embed_limit rc parameter to a larger value "
|
| 1298 |
+
"(in MB).", vid_len, embed_limit)
|
| 1299 |
+
else:
|
| 1300 |
+
self._base64_video = vid64.decode('ascii')
|
| 1301 |
+
self._video_size = 'width="{}" height="{}"'.format(
|
| 1302 |
+
*writer.frame_size)
|
| 1303 |
+
|
| 1304 |
+
# If we exceeded the size, this attribute won't exist
|
| 1305 |
+
if hasattr(self, '_base64_video'):
|
| 1306 |
+
# Default HTML5 options are to autoplay and display video controls
|
| 1307 |
+
options = ['controls', 'autoplay']
|
| 1308 |
+
|
| 1309 |
+
# If we're set to repeat, make it loop
|
| 1310 |
+
if getattr(self, '_repeat', False):
|
| 1311 |
+
options.append('loop')
|
| 1312 |
+
|
| 1313 |
+
return VIDEO_TAG.format(video=self._base64_video,
|
| 1314 |
+
size=self._video_size,
|
| 1315 |
+
options=' '.join(options))
|
| 1316 |
+
else:
|
| 1317 |
+
return 'Video too large to embed.'
|
| 1318 |
+
|
| 1319 |
+
def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
|
| 1320 |
+
"""
|
| 1321 |
+
Generate HTML representation of the animation.
|
| 1322 |
+
|
| 1323 |
+
Parameters
|
| 1324 |
+
----------
|
| 1325 |
+
fps : int, optional
|
| 1326 |
+
Movie frame rate (per second). If not set, the frame rate from
|
| 1327 |
+
the animation's frame interval.
|
| 1328 |
+
embed_frames : bool, optional
|
| 1329 |
+
default_mode : str, optional
|
| 1330 |
+
What to do when the animation ends. Must be one of ``{'loop',
|
| 1331 |
+
'once', 'reflect'}``. Defaults to ``'loop'`` if the *repeat*
|
| 1332 |
+
parameter is True, otherwise ``'once'``.
|
| 1333 |
+
"""
|
| 1334 |
+
if fps is None and hasattr(self, '_interval'):
|
| 1335 |
+
# Convert interval in ms to frames per second
|
| 1336 |
+
fps = 1000 / self._interval
|
| 1337 |
+
|
| 1338 |
+
# If we're not given a default mode, choose one base on the value of
|
| 1339 |
+
# the _repeat attribute
|
| 1340 |
+
if default_mode is None:
|
| 1341 |
+
default_mode = 'loop' if getattr(self, '_repeat',
|
| 1342 |
+
False) else 'once'
|
| 1343 |
+
|
| 1344 |
+
if not hasattr(self, "_html_representation"):
|
| 1345 |
+
# Can't open a NamedTemporaryFile twice on Windows, so use a
|
| 1346 |
+
# TemporaryDirectory instead.
|
| 1347 |
+
with TemporaryDirectory() as tmpdir:
|
| 1348 |
+
path = Path(tmpdir, "temp.html")
|
| 1349 |
+
writer = HTMLWriter(fps=fps,
|
| 1350 |
+
embed_frames=embed_frames,
|
| 1351 |
+
default_mode=default_mode)
|
| 1352 |
+
self.save(str(path), writer=writer)
|
| 1353 |
+
self._html_representation = path.read_text()
|
| 1354 |
+
|
| 1355 |
+
return self._html_representation
|
| 1356 |
+
|
| 1357 |
+
def _repr_html_(self):
|
| 1358 |
+
"""IPython display hook for rendering."""
|
| 1359 |
+
fmt = mpl.rcParams['animation.html']
|
| 1360 |
+
if fmt == 'html5':
|
| 1361 |
+
return self.to_html5_video()
|
| 1362 |
+
elif fmt == 'jshtml':
|
| 1363 |
+
return self.to_jshtml()
|
| 1364 |
+
|
| 1365 |
+
def pause(self):
|
| 1366 |
+
"""Pause the animation."""
|
| 1367 |
+
self.event_source.stop()
|
| 1368 |
+
if self._blit:
|
| 1369 |
+
for artist in self._drawn_artists:
|
| 1370 |
+
artist.set_animated(False)
|
| 1371 |
+
|
| 1372 |
+
def resume(self):
|
| 1373 |
+
"""Resume the animation."""
|
| 1374 |
+
self.event_source.start()
|
| 1375 |
+
if self._blit:
|
| 1376 |
+
for artist in self._drawn_artists:
|
| 1377 |
+
artist.set_animated(True)
|
| 1378 |
+
|
| 1379 |
+
|
| 1380 |
+
class TimedAnimation(Animation):
|
| 1381 |
+
"""
|
| 1382 |
+
`Animation` subclass for time-based animation.
|
| 1383 |
+
|
| 1384 |
+
A new frame is drawn every *interval* milliseconds.
|
| 1385 |
+
|
| 1386 |
+
.. note::
|
| 1387 |
+
|
| 1388 |
+
You must store the created Animation in a variable that lives as long
|
| 1389 |
+
as the animation should run. Otherwise, the Animation object will be
|
| 1390 |
+
garbage-collected and the animation stops.
|
| 1391 |
+
|
| 1392 |
+
Parameters
|
| 1393 |
+
----------
|
| 1394 |
+
fig : `~matplotlib.figure.Figure`
|
| 1395 |
+
The figure object used to get needed events, such as draw or resize.
|
| 1396 |
+
interval : int, default: 200
|
| 1397 |
+
Delay between frames in milliseconds.
|
| 1398 |
+
repeat_delay : int, default: 0
|
| 1399 |
+
The delay in milliseconds between consecutive animation runs, if
|
| 1400 |
+
*repeat* is True.
|
| 1401 |
+
repeat : bool, default: True
|
| 1402 |
+
Whether the animation repeats when the sequence of frames is completed.
|
| 1403 |
+
blit : bool, default: False
|
| 1404 |
+
Whether blitting is used to optimize drawing.
|
| 1405 |
+
"""
|
| 1406 |
+
def __init__(self, fig, interval=200, repeat_delay=0, repeat=True,
|
| 1407 |
+
event_source=None, *args, **kwargs):
|
| 1408 |
+
self._interval = interval
|
| 1409 |
+
# Undocumented support for repeat_delay = None as backcompat.
|
| 1410 |
+
self._repeat_delay = repeat_delay if repeat_delay is not None else 0
|
| 1411 |
+
self._repeat = repeat
|
| 1412 |
+
# If we're not given an event source, create a new timer. This permits
|
| 1413 |
+
# sharing timers between animation objects for syncing animations.
|
| 1414 |
+
if event_source is None:
|
| 1415 |
+
event_source = fig.canvas.new_timer(interval=self._interval)
|
| 1416 |
+
super().__init__(fig, event_source=event_source, *args, **kwargs)
|
| 1417 |
+
|
| 1418 |
+
def _step(self, *args):
|
| 1419 |
+
"""Handler for getting events."""
|
| 1420 |
+
# Extends the _step() method for the Animation class. If
|
| 1421 |
+
# Animation._step signals that it reached the end and we want to
|
| 1422 |
+
# repeat, we refresh the frame sequence and return True. If
|
| 1423 |
+
# _repeat_delay is set, change the event_source's interval to our loop
|
| 1424 |
+
# delay and set the callback to one which will then set the interval
|
| 1425 |
+
# back.
|
| 1426 |
+
still_going = super()._step(*args)
|
| 1427 |
+
if not still_going:
|
| 1428 |
+
if self._repeat:
|
| 1429 |
+
# Restart the draw loop
|
| 1430 |
+
self._init_draw()
|
| 1431 |
+
self.frame_seq = self.new_frame_seq()
|
| 1432 |
+
self.event_source.interval = self._repeat_delay
|
| 1433 |
+
return True
|
| 1434 |
+
else:
|
| 1435 |
+
# We are done with the animation. Call pause to remove
|
| 1436 |
+
# animated flags from artists that were using blitting
|
| 1437 |
+
self.pause()
|
| 1438 |
+
if self._blit:
|
| 1439 |
+
# Remove the resize callback if we were blitting
|
| 1440 |
+
self._fig.canvas.mpl_disconnect(self._resize_id)
|
| 1441 |
+
self._fig.canvas.mpl_disconnect(self._close_id)
|
| 1442 |
+
self.event_source = None
|
| 1443 |
+
return False
|
| 1444 |
+
|
| 1445 |
+
self.event_source.interval = self._interval
|
| 1446 |
+
return True
|
| 1447 |
+
|
| 1448 |
+
repeat = _api.deprecate_privatize_attribute("3.7")
|
| 1449 |
+
|
| 1450 |
+
|
| 1451 |
+
class ArtistAnimation(TimedAnimation):
|
| 1452 |
+
"""
|
| 1453 |
+
`TimedAnimation` subclass that creates an animation by using a fixed
|
| 1454 |
+
set of `.Artist` objects.
|
| 1455 |
+
|
| 1456 |
+
Before creating an instance, all plotting should have taken place
|
| 1457 |
+
and the relevant artists saved.
|
| 1458 |
+
|
| 1459 |
+
.. note::
|
| 1460 |
+
|
| 1461 |
+
You must store the created Animation in a variable that lives as long
|
| 1462 |
+
as the animation should run. Otherwise, the Animation object will be
|
| 1463 |
+
garbage-collected and the animation stops.
|
| 1464 |
+
|
| 1465 |
+
Parameters
|
| 1466 |
+
----------
|
| 1467 |
+
fig : `~matplotlib.figure.Figure`
|
| 1468 |
+
The figure object used to get needed events, such as draw or resize.
|
| 1469 |
+
artists : list
|
| 1470 |
+
Each list entry is a collection of `.Artist` objects that are made
|
| 1471 |
+
visible on the corresponding frame. Other artists are made invisible.
|
| 1472 |
+
interval : int, default: 200
|
| 1473 |
+
Delay between frames in milliseconds.
|
| 1474 |
+
repeat_delay : int, default: 0
|
| 1475 |
+
The delay in milliseconds between consecutive animation runs, if
|
| 1476 |
+
*repeat* is True.
|
| 1477 |
+
repeat : bool, default: True
|
| 1478 |
+
Whether the animation repeats when the sequence of frames is completed.
|
| 1479 |
+
blit : bool, default: False
|
| 1480 |
+
Whether blitting is used to optimize drawing.
|
| 1481 |
+
"""
|
| 1482 |
+
|
| 1483 |
+
def __init__(self, fig, artists, *args, **kwargs):
|
| 1484 |
+
# Internal list of artists drawn in the most recent frame.
|
| 1485 |
+
self._drawn_artists = []
|
| 1486 |
+
|
| 1487 |
+
# Use the list of artists as the framedata, which will be iterated
|
| 1488 |
+
# over by the machinery.
|
| 1489 |
+
self._framedata = artists
|
| 1490 |
+
super().__init__(fig, *args, **kwargs)
|
| 1491 |
+
|
| 1492 |
+
def _init_draw(self):
|
| 1493 |
+
super()._init_draw()
|
| 1494 |
+
# Make all the artists involved in *any* frame invisible
|
| 1495 |
+
figs = set()
|
| 1496 |
+
for f in self.new_frame_seq():
|
| 1497 |
+
for artist in f:
|
| 1498 |
+
artist.set_visible(False)
|
| 1499 |
+
artist.set_animated(self._blit)
|
| 1500 |
+
# Assemble a list of unique figures that need flushing
|
| 1501 |
+
if artist.get_figure() not in figs:
|
| 1502 |
+
figs.add(artist.get_figure())
|
| 1503 |
+
|
| 1504 |
+
# Flush the needed figures
|
| 1505 |
+
for fig in figs:
|
| 1506 |
+
fig.canvas.draw_idle()
|
| 1507 |
+
|
| 1508 |
+
def _pre_draw(self, framedata, blit):
|
| 1509 |
+
"""Clears artists from the last frame."""
|
| 1510 |
+
if blit:
|
| 1511 |
+
# Let blit handle clearing
|
| 1512 |
+
self._blit_clear(self._drawn_artists)
|
| 1513 |
+
else:
|
| 1514 |
+
# Otherwise, make all the artists from the previous frame invisible
|
| 1515 |
+
for artist in self._drawn_artists:
|
| 1516 |
+
artist.set_visible(False)
|
| 1517 |
+
|
| 1518 |
+
def _draw_frame(self, artists):
|
| 1519 |
+
# Save the artists that were passed in as framedata for the other
|
| 1520 |
+
# steps (esp. blitting) to use.
|
| 1521 |
+
self._drawn_artists = artists
|
| 1522 |
+
|
| 1523 |
+
# Make all the artists from the current frame visible
|
| 1524 |
+
for artist in artists:
|
| 1525 |
+
artist.set_visible(True)
|
| 1526 |
+
|
| 1527 |
+
|
| 1528 |
+
class FuncAnimation(TimedAnimation):
|
| 1529 |
+
"""
|
| 1530 |
+
`TimedAnimation` subclass that makes an animation by repeatedly calling
|
| 1531 |
+
a function *func*.
|
| 1532 |
+
|
| 1533 |
+
.. note::
|
| 1534 |
+
|
| 1535 |
+
You must store the created Animation in a variable that lives as long
|
| 1536 |
+
as the animation should run. Otherwise, the Animation object will be
|
| 1537 |
+
garbage-collected and the animation stops.
|
| 1538 |
+
|
| 1539 |
+
Parameters
|
| 1540 |
+
----------
|
| 1541 |
+
fig : `~matplotlib.figure.Figure`
|
| 1542 |
+
The figure object used to get needed events, such as draw or resize.
|
| 1543 |
+
|
| 1544 |
+
func : callable
|
| 1545 |
+
The function to call at each frame. The first argument will
|
| 1546 |
+
be the next value in *frames*. Any additional positional
|
| 1547 |
+
arguments can be supplied using `functools.partial` or via the *fargs*
|
| 1548 |
+
parameter.
|
| 1549 |
+
|
| 1550 |
+
The required signature is::
|
| 1551 |
+
|
| 1552 |
+
def func(frame, *fargs) -> iterable_of_artists
|
| 1553 |
+
|
| 1554 |
+
It is often more convenient to provide the arguments using
|
| 1555 |
+
`functools.partial`. In this way it is also possible to pass keyword
|
| 1556 |
+
arguments. To pass a function with both positional and keyword
|
| 1557 |
+
arguments, set all arguments as keyword arguments, just leaving the
|
| 1558 |
+
*frame* argument unset::
|
| 1559 |
+
|
| 1560 |
+
def func(frame, art, *, y=None):
|
| 1561 |
+
...
|
| 1562 |
+
|
| 1563 |
+
ani = FuncAnimation(fig, partial(func, art=ln, y='foo'))
|
| 1564 |
+
|
| 1565 |
+
If ``blit == True``, *func* must return an iterable of all artists
|
| 1566 |
+
that were modified or created. This information is used by the blitting
|
| 1567 |
+
algorithm to determine which parts of the figure have to be updated.
|
| 1568 |
+
The return value is unused if ``blit == False`` and may be omitted in
|
| 1569 |
+
that case.
|
| 1570 |
+
|
| 1571 |
+
frames : iterable, int, generator function, or None, optional
|
| 1572 |
+
Source of data to pass *func* and each frame of the animation
|
| 1573 |
+
|
| 1574 |
+
- If an iterable, then simply use the values provided. If the
|
| 1575 |
+
iterable has a length, it will override the *save_count* kwarg.
|
| 1576 |
+
|
| 1577 |
+
- If an integer, then equivalent to passing ``range(frames)``
|
| 1578 |
+
|
| 1579 |
+
- If a generator function, then must have the signature::
|
| 1580 |
+
|
| 1581 |
+
def gen_function() -> obj
|
| 1582 |
+
|
| 1583 |
+
- If *None*, then equivalent to passing ``itertools.count``.
|
| 1584 |
+
|
| 1585 |
+
In all of these cases, the values in *frames* is simply passed through
|
| 1586 |
+
to the user-supplied *func* and thus can be of any type.
|
| 1587 |
+
|
| 1588 |
+
init_func : callable, optional
|
| 1589 |
+
A function used to draw a clear frame. If not given, the results of
|
| 1590 |
+
drawing from the first item in the frames sequence will be used. This
|
| 1591 |
+
function will be called once before the first frame.
|
| 1592 |
+
|
| 1593 |
+
The required signature is::
|
| 1594 |
+
|
| 1595 |
+
def init_func() -> iterable_of_artists
|
| 1596 |
+
|
| 1597 |
+
If ``blit == True``, *init_func* must return an iterable of artists
|
| 1598 |
+
to be re-drawn. This information is used by the blitting algorithm to
|
| 1599 |
+
determine which parts of the figure have to be updated. The return
|
| 1600 |
+
value is unused if ``blit == False`` and may be omitted in that case.
|
| 1601 |
+
|
| 1602 |
+
fargs : tuple or None, optional
|
| 1603 |
+
Additional arguments to pass to each call to *func*. Note: the use of
|
| 1604 |
+
`functools.partial` is preferred over *fargs*. See *func* for details.
|
| 1605 |
+
|
| 1606 |
+
save_count : int, optional
|
| 1607 |
+
Fallback for the number of values from *frames* to cache. This is
|
| 1608 |
+
only used if the number of frames cannot be inferred from *frames*,
|
| 1609 |
+
i.e. when it's an iterator without length or a generator.
|
| 1610 |
+
|
| 1611 |
+
interval : int, default: 200
|
| 1612 |
+
Delay between frames in milliseconds.
|
| 1613 |
+
|
| 1614 |
+
repeat_delay : int, default: 0
|
| 1615 |
+
The delay in milliseconds between consecutive animation runs, if
|
| 1616 |
+
*repeat* is True.
|
| 1617 |
+
|
| 1618 |
+
repeat : bool, default: True
|
| 1619 |
+
Whether the animation repeats when the sequence of frames is completed.
|
| 1620 |
+
|
| 1621 |
+
blit : bool, default: False
|
| 1622 |
+
Whether blitting is used to optimize drawing. Note: when using
|
| 1623 |
+
blitting, any animated artists will be drawn according to their zorder;
|
| 1624 |
+
however, they will be drawn on top of any previous artists, regardless
|
| 1625 |
+
of their zorder.
|
| 1626 |
+
|
| 1627 |
+
cache_frame_data : bool, default: True
|
| 1628 |
+
Whether frame data is cached. Disabling cache might be helpful when
|
| 1629 |
+
frames contain large objects.
|
| 1630 |
+
"""
|
| 1631 |
+
def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
|
| 1632 |
+
save_count=None, *, cache_frame_data=True, **kwargs):
|
| 1633 |
+
if fargs:
|
| 1634 |
+
self._args = fargs
|
| 1635 |
+
else:
|
| 1636 |
+
self._args = ()
|
| 1637 |
+
self._func = func
|
| 1638 |
+
self._init_func = init_func
|
| 1639 |
+
|
| 1640 |
+
# Amount of framedata to keep around for saving movies. This is only
|
| 1641 |
+
# used if we don't know how many frames there will be: in the case
|
| 1642 |
+
# of no generator or in the case of a callable.
|
| 1643 |
+
self._save_count = save_count
|
| 1644 |
+
# Set up a function that creates a new iterable when needed. If nothing
|
| 1645 |
+
# is passed in for frames, just use itertools.count, which will just
|
| 1646 |
+
# keep counting from 0. A callable passed in for frames is assumed to
|
| 1647 |
+
# be a generator. An iterable will be used as is, and anything else
|
| 1648 |
+
# will be treated as a number of frames.
|
| 1649 |
+
if frames is None:
|
| 1650 |
+
self._iter_gen = itertools.count
|
| 1651 |
+
elif callable(frames):
|
| 1652 |
+
self._iter_gen = frames
|
| 1653 |
+
elif np.iterable(frames):
|
| 1654 |
+
if kwargs.get('repeat', True):
|
| 1655 |
+
self._tee_from = frames
|
| 1656 |
+
def iter_frames(frames=frames):
|
| 1657 |
+
this, self._tee_from = itertools.tee(self._tee_from, 2)
|
| 1658 |
+
yield from this
|
| 1659 |
+
self._iter_gen = iter_frames
|
| 1660 |
+
else:
|
| 1661 |
+
self._iter_gen = lambda: iter(frames)
|
| 1662 |
+
if hasattr(frames, '__len__'):
|
| 1663 |
+
self._save_count = len(frames)
|
| 1664 |
+
if save_count is not None:
|
| 1665 |
+
_api.warn_external(
|
| 1666 |
+
f"You passed in an explicit {save_count=} "
|
| 1667 |
+
"which is being ignored in favor of "
|
| 1668 |
+
f"{len(frames)=}."
|
| 1669 |
+
)
|
| 1670 |
+
else:
|
| 1671 |
+
self._iter_gen = lambda: iter(range(frames))
|
| 1672 |
+
self._save_count = frames
|
| 1673 |
+
if save_count is not None:
|
| 1674 |
+
_api.warn_external(
|
| 1675 |
+
f"You passed in an explicit {save_count=} which is being "
|
| 1676 |
+
f"ignored in favor of {frames=}."
|
| 1677 |
+
)
|
| 1678 |
+
if self._save_count is None and cache_frame_data:
|
| 1679 |
+
_api.warn_external(
|
| 1680 |
+
f"{frames=!r} which we can infer the length of, "
|
| 1681 |
+
"did not pass an explicit *save_count* "
|
| 1682 |
+
f"and passed {cache_frame_data=}. To avoid a possibly "
|
| 1683 |
+
"unbounded cache, frame data caching has been disabled. "
|
| 1684 |
+
"To suppress this warning either pass "
|
| 1685 |
+
"`cache_frame_data=False` or `save_count=MAX_FRAMES`."
|
| 1686 |
+
)
|
| 1687 |
+
cache_frame_data = False
|
| 1688 |
+
|
| 1689 |
+
self._cache_frame_data = cache_frame_data
|
| 1690 |
+
|
| 1691 |
+
# Needs to be initialized so the draw functions work without checking
|
| 1692 |
+
self._save_seq = []
|
| 1693 |
+
|
| 1694 |
+
super().__init__(fig, **kwargs)
|
| 1695 |
+
|
| 1696 |
+
# Need to reset the saved seq, since right now it will contain data
|
| 1697 |
+
# for a single frame from init, which is not what we want.
|
| 1698 |
+
self._save_seq = []
|
| 1699 |
+
|
| 1700 |
+
def new_frame_seq(self):
|
| 1701 |
+
# Use the generating function to generate a new frame sequence
|
| 1702 |
+
return self._iter_gen()
|
| 1703 |
+
|
| 1704 |
+
def new_saved_frame_seq(self):
|
| 1705 |
+
# Generate an iterator for the sequence of saved data. If there are
|
| 1706 |
+
# no saved frames, generate a new frame sequence and take the first
|
| 1707 |
+
# save_count entries in it.
|
| 1708 |
+
if self._save_seq:
|
| 1709 |
+
# While iterating we are going to update _save_seq
|
| 1710 |
+
# so make a copy to safely iterate over
|
| 1711 |
+
self._old_saved_seq = list(self._save_seq)
|
| 1712 |
+
return iter(self._old_saved_seq)
|
| 1713 |
+
else:
|
| 1714 |
+
if self._save_count is None:
|
| 1715 |
+
frame_seq = self.new_frame_seq()
|
| 1716 |
+
|
| 1717 |
+
def gen():
|
| 1718 |
+
try:
|
| 1719 |
+
while True:
|
| 1720 |
+
yield next(frame_seq)
|
| 1721 |
+
except StopIteration:
|
| 1722 |
+
pass
|
| 1723 |
+
return gen()
|
| 1724 |
+
else:
|
| 1725 |
+
return itertools.islice(self.new_frame_seq(), self._save_count)
|
| 1726 |
+
|
| 1727 |
+
def _init_draw(self):
|
| 1728 |
+
super()._init_draw()
|
| 1729 |
+
# Initialize the drawing either using the given init_func or by
|
| 1730 |
+
# calling the draw function with the first item of the frame sequence.
|
| 1731 |
+
# For blitting, the init_func should return a sequence of modified
|
| 1732 |
+
# artists.
|
| 1733 |
+
if self._init_func is None:
|
| 1734 |
+
try:
|
| 1735 |
+
frame_data = next(self.new_frame_seq())
|
| 1736 |
+
except StopIteration:
|
| 1737 |
+
# we can't start the iteration, it may have already been
|
| 1738 |
+
# exhausted by a previous save or just be 0 length.
|
| 1739 |
+
# warn and bail.
|
| 1740 |
+
warnings.warn(
|
| 1741 |
+
"Can not start iterating the frames for the initial draw. "
|
| 1742 |
+
"This can be caused by passing in a 0 length sequence "
|
| 1743 |
+
"for *frames*.\n\n"
|
| 1744 |
+
"If you passed *frames* as a generator "
|
| 1745 |
+
"it may be exhausted due to a previous display or save."
|
| 1746 |
+
)
|
| 1747 |
+
return
|
| 1748 |
+
self._draw_frame(frame_data)
|
| 1749 |
+
else:
|
| 1750 |
+
self._drawn_artists = self._init_func()
|
| 1751 |
+
if self._blit:
|
| 1752 |
+
if self._drawn_artists is None:
|
| 1753 |
+
raise RuntimeError('The init_func must return a '
|
| 1754 |
+
'sequence of Artist objects.')
|
| 1755 |
+
for a in self._drawn_artists:
|
| 1756 |
+
a.set_animated(self._blit)
|
| 1757 |
+
self._save_seq = []
|
| 1758 |
+
|
| 1759 |
+
def _draw_frame(self, framedata):
|
| 1760 |
+
if self._cache_frame_data:
|
| 1761 |
+
# Save the data for potential saving of movies.
|
| 1762 |
+
self._save_seq.append(framedata)
|
| 1763 |
+
self._save_seq = self._save_seq[-self._save_count:]
|
| 1764 |
+
|
| 1765 |
+
# Call the func with framedata and args. If blitting is desired,
|
| 1766 |
+
# func needs to return a sequence of any artists that were modified.
|
| 1767 |
+
self._drawn_artists = self._func(framedata, *self._args)
|
| 1768 |
+
|
| 1769 |
+
if self._blit:
|
| 1770 |
+
|
| 1771 |
+
err = RuntimeError('The animation function must return a sequence '
|
| 1772 |
+
'of Artist objects.')
|
| 1773 |
+
try:
|
| 1774 |
+
# check if a sequence
|
| 1775 |
+
iter(self._drawn_artists)
|
| 1776 |
+
except TypeError:
|
| 1777 |
+
raise err from None
|
| 1778 |
+
|
| 1779 |
+
# check each item if it's artist
|
| 1780 |
+
for i in self._drawn_artists:
|
| 1781 |
+
if not isinstance(i, mpl.artist.Artist):
|
| 1782 |
+
raise err
|
| 1783 |
+
|
| 1784 |
+
self._drawn_artists = sorted(self._drawn_artists,
|
| 1785 |
+
key=lambda x: x.get_zorder())
|
| 1786 |
+
|
| 1787 |
+
for a in self._drawn_artists:
|
| 1788 |
+
a.set_animated(self._blit)
|
| 1789 |
+
|
| 1790 |
+
save_count = _api.deprecate_privatize_attribute("3.7")
|
omnilmm/lib/python3.10/site-packages/matplotlib/axis.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
omnilmm/lib/python3.10/site-packages/matplotlib/backend_managers.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib import _api, backend_tools, cbook, widgets
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class ToolEvent:
|
| 5 |
+
"""Event for tool manipulation (add/remove)."""
|
| 6 |
+
def __init__(self, name, sender, tool, data=None):
|
| 7 |
+
self.name = name
|
| 8 |
+
self.sender = sender
|
| 9 |
+
self.tool = tool
|
| 10 |
+
self.data = data
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ToolTriggerEvent(ToolEvent):
|
| 14 |
+
"""Event to inform that a tool has been triggered."""
|
| 15 |
+
def __init__(self, name, sender, tool, canvasevent=None, data=None):
|
| 16 |
+
super().__init__(name, sender, tool, data)
|
| 17 |
+
self.canvasevent = canvasevent
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ToolManagerMessageEvent:
|
| 21 |
+
"""
|
| 22 |
+
Event carrying messages from toolmanager.
|
| 23 |
+
|
| 24 |
+
Messages usually get displayed to the user by the toolbar.
|
| 25 |
+
"""
|
| 26 |
+
def __init__(self, name, sender, message):
|
| 27 |
+
self.name = name
|
| 28 |
+
self.sender = sender
|
| 29 |
+
self.message = message
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ToolManager:
|
| 33 |
+
"""
|
| 34 |
+
Manager for actions triggered by user interactions (key press, toolbar
|
| 35 |
+
clicks, ...) on a Figure.
|
| 36 |
+
|
| 37 |
+
Attributes
|
| 38 |
+
----------
|
| 39 |
+
figure : `.Figure`
|
| 40 |
+
keypresslock : `~matplotlib.widgets.LockDraw`
|
| 41 |
+
`.LockDraw` object to know if the `canvas` key_press_event is locked.
|
| 42 |
+
messagelock : `~matplotlib.widgets.LockDraw`
|
| 43 |
+
`.LockDraw` object to know if the message is available to write.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self, figure=None):
|
| 47 |
+
|
| 48 |
+
self._key_press_handler_id = None
|
| 49 |
+
|
| 50 |
+
self._tools = {}
|
| 51 |
+
self._keys = {}
|
| 52 |
+
self._toggled = {}
|
| 53 |
+
self._callbacks = cbook.CallbackRegistry()
|
| 54 |
+
|
| 55 |
+
# to process keypress event
|
| 56 |
+
self.keypresslock = widgets.LockDraw()
|
| 57 |
+
self.messagelock = widgets.LockDraw()
|
| 58 |
+
|
| 59 |
+
self._figure = None
|
| 60 |
+
self.set_figure(figure)
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def canvas(self):
|
| 64 |
+
"""Canvas managed by FigureManager."""
|
| 65 |
+
if not self._figure:
|
| 66 |
+
return None
|
| 67 |
+
return self._figure.canvas
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def figure(self):
|
| 71 |
+
"""Figure that holds the canvas."""
|
| 72 |
+
return self._figure
|
| 73 |
+
|
| 74 |
+
@figure.setter
|
| 75 |
+
def figure(self, figure):
|
| 76 |
+
self.set_figure(figure)
|
| 77 |
+
|
| 78 |
+
def set_figure(self, figure, update_tools=True):
|
| 79 |
+
"""
|
| 80 |
+
Bind the given figure to the tools.
|
| 81 |
+
|
| 82 |
+
Parameters
|
| 83 |
+
----------
|
| 84 |
+
figure : `.Figure`
|
| 85 |
+
update_tools : bool, default: True
|
| 86 |
+
Force tools to update figure.
|
| 87 |
+
"""
|
| 88 |
+
if self._key_press_handler_id:
|
| 89 |
+
self.canvas.mpl_disconnect(self._key_press_handler_id)
|
| 90 |
+
self._figure = figure
|
| 91 |
+
if figure:
|
| 92 |
+
self._key_press_handler_id = self.canvas.mpl_connect(
|
| 93 |
+
'key_press_event', self._key_press)
|
| 94 |
+
if update_tools:
|
| 95 |
+
for tool in self._tools.values():
|
| 96 |
+
tool.figure = figure
|
| 97 |
+
|
| 98 |
+
def toolmanager_connect(self, s, func):
|
| 99 |
+
"""
|
| 100 |
+
Connect event with string *s* to *func*.
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
s : str
|
| 105 |
+
The name of the event. The following events are recognized:
|
| 106 |
+
|
| 107 |
+
- 'tool_message_event'
|
| 108 |
+
- 'tool_removed_event'
|
| 109 |
+
- 'tool_added_event'
|
| 110 |
+
|
| 111 |
+
For every tool added a new event is created
|
| 112 |
+
|
| 113 |
+
- 'tool_trigger_TOOLNAME', where TOOLNAME is the id of the tool.
|
| 114 |
+
|
| 115 |
+
func : callable
|
| 116 |
+
Callback function for the toolmanager event with signature::
|
| 117 |
+
|
| 118 |
+
def func(event: ToolEvent) -> Any
|
| 119 |
+
|
| 120 |
+
Returns
|
| 121 |
+
-------
|
| 122 |
+
cid
|
| 123 |
+
The callback id for the connection. This can be used in
|
| 124 |
+
`.toolmanager_disconnect`.
|
| 125 |
+
"""
|
| 126 |
+
return self._callbacks.connect(s, func)
|
| 127 |
+
|
| 128 |
+
def toolmanager_disconnect(self, cid):
|
| 129 |
+
"""
|
| 130 |
+
Disconnect callback id *cid*.
|
| 131 |
+
|
| 132 |
+
Example usage::
|
| 133 |
+
|
| 134 |
+
cid = toolmanager.toolmanager_connect('tool_trigger_zoom', onpress)
|
| 135 |
+
#...later
|
| 136 |
+
toolmanager.toolmanager_disconnect(cid)
|
| 137 |
+
"""
|
| 138 |
+
return self._callbacks.disconnect(cid)
|
| 139 |
+
|
| 140 |
+
def message_event(self, message, sender=None):
|
| 141 |
+
"""Emit a `ToolManagerMessageEvent`."""
|
| 142 |
+
if sender is None:
|
| 143 |
+
sender = self
|
| 144 |
+
|
| 145 |
+
s = 'tool_message_event'
|
| 146 |
+
event = ToolManagerMessageEvent(s, sender, message)
|
| 147 |
+
self._callbacks.process(s, event)
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def active_toggle(self):
|
| 151 |
+
"""Currently toggled tools."""
|
| 152 |
+
return self._toggled
|
| 153 |
+
|
| 154 |
+
def get_tool_keymap(self, name):
|
| 155 |
+
"""
|
| 156 |
+
Return the keymap associated with the specified tool.
|
| 157 |
+
|
| 158 |
+
Parameters
|
| 159 |
+
----------
|
| 160 |
+
name : str
|
| 161 |
+
Name of the Tool.
|
| 162 |
+
|
| 163 |
+
Returns
|
| 164 |
+
-------
|
| 165 |
+
list of str
|
| 166 |
+
List of keys associated with the tool.
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
keys = [k for k, i in self._keys.items() if i == name]
|
| 170 |
+
return keys
|
| 171 |
+
|
| 172 |
+
def _remove_keys(self, name):
|
| 173 |
+
for k in self.get_tool_keymap(name):
|
| 174 |
+
del self._keys[k]
|
| 175 |
+
|
| 176 |
+
def update_keymap(self, name, key):
|
| 177 |
+
"""
|
| 178 |
+
Set the keymap to associate with the specified tool.
|
| 179 |
+
|
| 180 |
+
Parameters
|
| 181 |
+
----------
|
| 182 |
+
name : str
|
| 183 |
+
Name of the Tool.
|
| 184 |
+
key : str or list of str
|
| 185 |
+
Keys to associate with the tool.
|
| 186 |
+
"""
|
| 187 |
+
if name not in self._tools:
|
| 188 |
+
raise KeyError(f'{name!r} not in Tools')
|
| 189 |
+
self._remove_keys(name)
|
| 190 |
+
if isinstance(key, str):
|
| 191 |
+
key = [key]
|
| 192 |
+
for k in key:
|
| 193 |
+
if k in self._keys:
|
| 194 |
+
_api.warn_external(
|
| 195 |
+
f'Key {k} changed from {self._keys[k]} to {name}')
|
| 196 |
+
self._keys[k] = name
|
| 197 |
+
|
| 198 |
+
def remove_tool(self, name):
|
| 199 |
+
"""
|
| 200 |
+
Remove tool named *name*.
|
| 201 |
+
|
| 202 |
+
Parameters
|
| 203 |
+
----------
|
| 204 |
+
name : str
|
| 205 |
+
Name of the tool.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
tool = self.get_tool(name)
|
| 209 |
+
destroy = _api.deprecate_method_override(
|
| 210 |
+
backend_tools.ToolBase.destroy, tool, since="3.6",
|
| 211 |
+
alternative="tool_removed_event")
|
| 212 |
+
if destroy is not None:
|
| 213 |
+
destroy()
|
| 214 |
+
|
| 215 |
+
# If it's a toggle tool and toggled, untoggle
|
| 216 |
+
if getattr(tool, 'toggled', False):
|
| 217 |
+
self.trigger_tool(tool, 'toolmanager')
|
| 218 |
+
|
| 219 |
+
self._remove_keys(name)
|
| 220 |
+
|
| 221 |
+
event = ToolEvent('tool_removed_event', self, tool)
|
| 222 |
+
self._callbacks.process(event.name, event)
|
| 223 |
+
|
| 224 |
+
del self._tools[name]
|
| 225 |
+
|
| 226 |
+
def add_tool(self, name, tool, *args, **kwargs):
|
| 227 |
+
"""
|
| 228 |
+
Add *tool* to `ToolManager`.
|
| 229 |
+
|
| 230 |
+
If successful, adds a new event ``tool_trigger_{name}`` where
|
| 231 |
+
``{name}`` is the *name* of the tool; the event is fired every time the
|
| 232 |
+
tool is triggered.
|
| 233 |
+
|
| 234 |
+
Parameters
|
| 235 |
+
----------
|
| 236 |
+
name : str
|
| 237 |
+
Name of the tool, treated as the ID, has to be unique.
|
| 238 |
+
tool : type
|
| 239 |
+
Class of the tool to be added. A subclass will be used
|
| 240 |
+
instead if one was registered for the current canvas class.
|
| 241 |
+
*args, **kwargs
|
| 242 |
+
Passed to the *tool*'s constructor.
|
| 243 |
+
|
| 244 |
+
See Also
|
| 245 |
+
--------
|
| 246 |
+
matplotlib.backend_tools.ToolBase : The base class for tools.
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
tool_cls = backend_tools._find_tool_class(type(self.canvas), tool)
|
| 250 |
+
if not tool_cls:
|
| 251 |
+
raise ValueError('Impossible to find class for %s' % str(tool))
|
| 252 |
+
|
| 253 |
+
if name in self._tools:
|
| 254 |
+
_api.warn_external('A "Tool class" with the same name already '
|
| 255 |
+
'exists, not added')
|
| 256 |
+
return self._tools[name]
|
| 257 |
+
|
| 258 |
+
tool_obj = tool_cls(self, name, *args, **kwargs)
|
| 259 |
+
self._tools[name] = tool_obj
|
| 260 |
+
|
| 261 |
+
if tool_obj.default_keymap is not None:
|
| 262 |
+
self.update_keymap(name, tool_obj.default_keymap)
|
| 263 |
+
|
| 264 |
+
# For toggle tools init the radio_group in self._toggled
|
| 265 |
+
if isinstance(tool_obj, backend_tools.ToolToggleBase):
|
| 266 |
+
# None group is not mutually exclusive, a set is used to keep track
|
| 267 |
+
# of all toggled tools in this group
|
| 268 |
+
if tool_obj.radio_group is None:
|
| 269 |
+
self._toggled.setdefault(None, set())
|
| 270 |
+
else:
|
| 271 |
+
self._toggled.setdefault(tool_obj.radio_group, None)
|
| 272 |
+
|
| 273 |
+
# If initially toggled
|
| 274 |
+
if tool_obj.toggled:
|
| 275 |
+
self._handle_toggle(tool_obj, None, None)
|
| 276 |
+
tool_obj.set_figure(self.figure)
|
| 277 |
+
|
| 278 |
+
event = ToolEvent('tool_added_event', self, tool_obj)
|
| 279 |
+
self._callbacks.process(event.name, event)
|
| 280 |
+
|
| 281 |
+
return tool_obj
|
| 282 |
+
|
| 283 |
+
def _handle_toggle(self, tool, canvasevent, data):
|
| 284 |
+
"""
|
| 285 |
+
Toggle tools, need to untoggle prior to using other Toggle tool.
|
| 286 |
+
Called from trigger_tool.
|
| 287 |
+
|
| 288 |
+
Parameters
|
| 289 |
+
----------
|
| 290 |
+
tool : `.ToolBase`
|
| 291 |
+
canvasevent : Event
|
| 292 |
+
Original Canvas event or None.
|
| 293 |
+
data : object
|
| 294 |
+
Extra data to pass to the tool when triggering.
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
radio_group = tool.radio_group
|
| 298 |
+
# radio_group None is not mutually exclusive
|
| 299 |
+
# just keep track of toggled tools in this group
|
| 300 |
+
if radio_group is None:
|
| 301 |
+
if tool.name in self._toggled[None]:
|
| 302 |
+
self._toggled[None].remove(tool.name)
|
| 303 |
+
else:
|
| 304 |
+
self._toggled[None].add(tool.name)
|
| 305 |
+
return
|
| 306 |
+
|
| 307 |
+
# If the tool already has a toggled state, untoggle it
|
| 308 |
+
if self._toggled[radio_group] == tool.name:
|
| 309 |
+
toggled = None
|
| 310 |
+
# If no tool was toggled in the radio_group
|
| 311 |
+
# toggle it
|
| 312 |
+
elif self._toggled[radio_group] is None:
|
| 313 |
+
toggled = tool.name
|
| 314 |
+
# Other tool in the radio_group is toggled
|
| 315 |
+
else:
|
| 316 |
+
# Untoggle previously toggled tool
|
| 317 |
+
self.trigger_tool(self._toggled[radio_group],
|
| 318 |
+
self,
|
| 319 |
+
canvasevent,
|
| 320 |
+
data)
|
| 321 |
+
toggled = tool.name
|
| 322 |
+
|
| 323 |
+
# Keep track of the toggled tool in the radio_group
|
| 324 |
+
self._toggled[radio_group] = toggled
|
| 325 |
+
|
| 326 |
+
def trigger_tool(self, name, sender=None, canvasevent=None, data=None):
|
| 327 |
+
"""
|
| 328 |
+
Trigger a tool and emit the ``tool_trigger_{name}`` event.
|
| 329 |
+
|
| 330 |
+
Parameters
|
| 331 |
+
----------
|
| 332 |
+
name : str
|
| 333 |
+
Name of the tool.
|
| 334 |
+
sender : object
|
| 335 |
+
Object that wishes to trigger the tool.
|
| 336 |
+
canvasevent : Event
|
| 337 |
+
Original Canvas event or None.
|
| 338 |
+
data : object
|
| 339 |
+
Extra data to pass to the tool when triggering.
|
| 340 |
+
"""
|
| 341 |
+
tool = self.get_tool(name)
|
| 342 |
+
if tool is None:
|
| 343 |
+
return
|
| 344 |
+
|
| 345 |
+
if sender is None:
|
| 346 |
+
sender = self
|
| 347 |
+
|
| 348 |
+
if isinstance(tool, backend_tools.ToolToggleBase):
|
| 349 |
+
self._handle_toggle(tool, canvasevent, data)
|
| 350 |
+
|
| 351 |
+
tool.trigger(sender, canvasevent, data) # Actually trigger Tool.
|
| 352 |
+
|
| 353 |
+
s = 'tool_trigger_%s' % name
|
| 354 |
+
event = ToolTriggerEvent(s, sender, tool, canvasevent, data)
|
| 355 |
+
self._callbacks.process(s, event)
|
| 356 |
+
|
| 357 |
+
def _key_press(self, event):
|
| 358 |
+
if event.key is None or self.keypresslock.locked():
|
| 359 |
+
return
|
| 360 |
+
|
| 361 |
+
name = self._keys.get(event.key, None)
|
| 362 |
+
if name is None:
|
| 363 |
+
return
|
| 364 |
+
self.trigger_tool(name, canvasevent=event)
|
| 365 |
+
|
| 366 |
+
@property
|
| 367 |
+
def tools(self):
|
| 368 |
+
"""A dict mapping tool name -> controlled tool."""
|
| 369 |
+
return self._tools
|
| 370 |
+
|
| 371 |
+
def get_tool(self, name, warn=True):
|
| 372 |
+
"""
|
| 373 |
+
Return the tool object with the given name.
|
| 374 |
+
|
| 375 |
+
For convenience, this passes tool objects through.
|
| 376 |
+
|
| 377 |
+
Parameters
|
| 378 |
+
----------
|
| 379 |
+
name : str or `.ToolBase`
|
| 380 |
+
Name of the tool, or the tool itself.
|
| 381 |
+
warn : bool, default: True
|
| 382 |
+
Whether a warning should be emitted it no tool with the given name
|
| 383 |
+
exists.
|
| 384 |
+
|
| 385 |
+
Returns
|
| 386 |
+
-------
|
| 387 |
+
`.ToolBase` or None
|
| 388 |
+
The tool or None if no tool with the given name exists.
|
| 389 |
+
"""
|
| 390 |
+
if (isinstance(name, backend_tools.ToolBase)
|
| 391 |
+
and name.name in self._tools):
|
| 392 |
+
return name
|
| 393 |
+
if name not in self._tools:
|
| 394 |
+
if warn:
|
| 395 |
+
_api.warn_external(
|
| 396 |
+
f"ToolManager does not control t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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Abstract base classes define the primitives for Tools.
|
| 3 |
+
These tools are used by `matplotlib.backend_managers.ToolManager`
|
| 4 |
+
|
| 5 |
+
:class:`ToolBase`
|
| 6 |
+
Simple stateless tool
|
| 7 |
+
|
| 8 |
+
:class:`ToolToggleBase`
|
| 9 |
+
Tool that has two states, only one Toggle tool can be
|
| 10 |
+
active at any given time for the same
|
| 11 |
+
`matplotlib.backend_managers.ToolManager`
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import enum
|
| 15 |
+
import functools
|
| 16 |
+
import re
|
| 17 |
+
import time
|
| 18 |
+
from types import SimpleNamespace
|
| 19 |
+
import uuid
|
| 20 |
+
from weakref import WeakKeyDictionary
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
import matplotlib as mpl
|
| 25 |
+
from matplotlib._pylab_helpers import Gcf
|
| 26 |
+
from matplotlib import _api, cbook
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Cursors(enum.IntEnum): # Must subclass int for the macOS backend.
|
| 30 |
+
"""Backend-independent cursor types."""
|
| 31 |
+
POINTER = enum.auto()
|
| 32 |
+
HAND = enum.auto()
|
| 33 |
+
SELECT_REGION = enum.auto()
|
| 34 |
+
MOVE = enum.auto()
|
| 35 |
+
WAIT = enum.auto()
|
| 36 |
+
RESIZE_HORIZONTAL = enum.auto()
|
| 37 |
+
RESIZE_VERTICAL = enum.auto()
|
| 38 |
+
cursors = Cursors # Backcompat.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# _tool_registry, _register_tool_class, and _find_tool_class implement a
|
| 42 |
+
# mechanism through which ToolManager.add_tool can determine whether a subclass
|
| 43 |
+
# of the requested tool class has been registered (either for the current
|
| 44 |
+
# canvas class or for a parent class), in which case that tool subclass will be
|
| 45 |
+
# instantiated instead. This is the mechanism used e.g. to allow different
|
| 46 |
+
# GUI backends to implement different specializations for ConfigureSubplots.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
_tool_registry = set()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _register_tool_class(canvas_cls, tool_cls=None):
|
| 53 |
+
"""Decorator registering *tool_cls* as a tool class for *canvas_cls*."""
|
| 54 |
+
if tool_cls is None:
|
| 55 |
+
return functools.partial(_register_tool_class, canvas_cls)
|
| 56 |
+
_tool_registry.add((canvas_cls, tool_cls))
|
| 57 |
+
return tool_cls
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _find_tool_class(canvas_cls, tool_cls):
|
| 61 |
+
"""Find a subclass of *tool_cls* registered for *canvas_cls*."""
|
| 62 |
+
for canvas_parent in canvas_cls.__mro__:
|
| 63 |
+
for tool_child in _api.recursive_subclasses(tool_cls):
|
| 64 |
+
if (canvas_parent, tool_child) in _tool_registry:
|
| 65 |
+
return tool_child
|
| 66 |
+
return tool_cls
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Views positions tool
|
| 70 |
+
_views_positions = 'viewpos'
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class ToolBase:
|
| 74 |
+
"""
|
| 75 |
+
Base tool class.
|
| 76 |
+
|
| 77 |
+
A base tool, only implements `trigger` method or no method at all.
|
| 78 |
+
The tool is instantiated by `matplotlib.backend_managers.ToolManager`.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
default_keymap = None
|
| 82 |
+
"""
|
| 83 |
+
Keymap to associate with this tool.
|
| 84 |
+
|
| 85 |
+
``list[str]``: List of keys that will trigger this tool when a keypress
|
| 86 |
+
event is emitted on ``self.figure.canvas``. Note that this attribute is
|
| 87 |
+
looked up on the instance, and can therefore be a property (this is used
|
| 88 |
+
e.g. by the built-in tools to load the rcParams at instantiation time).
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
description = None
|
| 92 |
+
"""
|
| 93 |
+
Description of the Tool.
|
| 94 |
+
|
| 95 |
+
`str`: Tooltip used if the Tool is included in a Toolbar.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
image = None
|
| 99 |
+
"""
|
| 100 |
+
Filename of the image.
|
| 101 |
+
|
| 102 |
+
`str`: Filename of the image to use in a Toolbar. If None, the *name* is
|
| 103 |
+
used as a label in the toolbar button.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(self, toolmanager, name):
|
| 107 |
+
self._name = name
|
| 108 |
+
self._toolmanager = toolmanager
|
| 109 |
+
self._figure = None
|
| 110 |
+
|
| 111 |
+
name = property(
|
| 112 |
+
lambda self: self._name,
|
| 113 |
+
doc="The tool id (str, must be unique among tools of a tool manager).")
|
| 114 |
+
toolmanager = property(
|
| 115 |
+
lambda self: self._toolmanager,
|
| 116 |
+
doc="The `.ToolManager` that controls this tool.")
|
| 117 |
+
canvas = property(
|
| 118 |
+
lambda self: self._figure.canvas if self._figure is not None else None,
|
| 119 |
+
doc="The canvas of the figure affected by this tool, or None.")
|
| 120 |
+
|
| 121 |
+
@property
|
| 122 |
+
def figure(self):
|
| 123 |
+
"""The Figure affected by this tool, or None."""
|
| 124 |
+
return self._figure
|
| 125 |
+
|
| 126 |
+
@figure.setter
|
| 127 |
+
def figure(self, figure):
|
| 128 |
+
self._figure = figure
|
| 129 |
+
|
| 130 |
+
set_figure = figure.fset
|
| 131 |
+
|
| 132 |
+
def _make_classic_style_pseudo_toolbar(self):
|
| 133 |
+
"""
|
| 134 |
+
Return a placeholder object with a single `canvas` attribute.
|
| 135 |
+
|
| 136 |
+
This is useful to reuse the implementations of tools already provided
|
| 137 |
+
by the classic Toolbars.
|
| 138 |
+
"""
|
| 139 |
+
return SimpleNamespace(canvas=self.canvas)
|
| 140 |
+
|
| 141 |
+
def trigger(self, sender, event, data=None):
|
| 142 |
+
"""
|
| 143 |
+
Called when this tool gets used.
|
| 144 |
+
|
| 145 |
+
This method is called by `.ToolManager.trigger_tool`.
|
| 146 |
+
|
| 147 |
+
Parameters
|
| 148 |
+
----------
|
| 149 |
+
event : `.Event`
|
| 150 |
+
The canvas event that caused this tool to be called.
|
| 151 |
+
sender : object
|
| 152 |
+
Object that requested the tool to be triggered.
|
| 153 |
+
data : object
|
| 154 |
+
Extra data.
|
| 155 |
+
"""
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
@_api.deprecated("3.6", alternative="tool_removed_event")
|
| 159 |
+
def destroy(self):
|
| 160 |
+
"""
|
| 161 |
+
Destroy the tool.
|
| 162 |
+
|
| 163 |
+
This method is called by `.ToolManager.remove_tool`.
|
| 164 |
+
"""
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class ToolToggleBase(ToolBase):
|
| 169 |
+
"""
|
| 170 |
+
Toggleable tool.
|
| 171 |
+
|
| 172 |
+
Every time it is triggered, it switches between enable and disable.
|
| 173 |
+
|
| 174 |
+
Parameters
|
| 175 |
+
----------
|
| 176 |
+
``*args``
|
| 177 |
+
Variable length argument to be used by the Tool.
|
| 178 |
+
``**kwargs``
|
| 179 |
+
`toggled` if present and True, sets the initial state of the Tool
|
| 180 |
+
Arbitrary keyword arguments to be consumed by the Tool
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
radio_group = None
|
| 184 |
+
"""
|
| 185 |
+
Attribute to group 'radio' like tools (mutually exclusive).
|
| 186 |
+
|
| 187 |
+
`str` that identifies the group or **None** if not belonging to a group.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
cursor = None
|
| 191 |
+
"""Cursor to use when the tool is active."""
|
| 192 |
+
|
| 193 |
+
default_toggled = False
|
| 194 |
+
"""Default of toggled state."""
|
| 195 |
+
|
| 196 |
+
def __init__(self, *args, **kwargs):
|
| 197 |
+
self._toggled = kwargs.pop('toggled', self.default_toggled)
|
| 198 |
+
super().__init__(*args, **kwargs)
|
| 199 |
+
|
| 200 |
+
def trigger(self, sender, event, data=None):
|
| 201 |
+
"""Calls `enable` or `disable` based on `toggled` value."""
|
| 202 |
+
if self._toggled:
|
| 203 |
+
self.disable(event)
|
| 204 |
+
else:
|
| 205 |
+
self.enable(event)
|
| 206 |
+
self._toggled = not self._toggled
|
| 207 |
+
|
| 208 |
+
def enable(self, event=None):
|
| 209 |
+
"""
|
| 210 |
+
Enable the toggle tool.
|
| 211 |
+
|
| 212 |
+
`trigger` calls this method when `toggled` is False.
|
| 213 |
+
"""
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
def disable(self, event=None):
|
| 217 |
+
"""
|
| 218 |
+
Disable the toggle tool.
|
| 219 |
+
|
| 220 |
+
`trigger` call this method when `toggled` is True.
|
| 221 |
+
|
| 222 |
+
This can happen in different circumstances.
|
| 223 |
+
|
| 224 |
+
* Click on the toolbar tool button.
|
| 225 |
+
* Call to `matplotlib.backend_managers.ToolManager.trigger_tool`.
|
| 226 |
+
* Another `ToolToggleBase` derived tool is triggered
|
| 227 |
+
(from the same `.ToolManager`).
|
| 228 |
+
"""
|
| 229 |
+
pass
|
| 230 |
+
|
| 231 |
+
@property
|
| 232 |
+
def toggled(self):
|
| 233 |
+
"""State of the toggled tool."""
|
| 234 |
+
return self._toggled
|
| 235 |
+
|
| 236 |
+
def set_figure(self, figure):
|
| 237 |
+
toggled = self.toggled
|
| 238 |
+
if toggled:
|
| 239 |
+
if self.figure:
|
| 240 |
+
self.trigger(self, None)
|
| 241 |
+
else:
|
| 242 |
+
# if no figure the internal state is not changed
|
| 243 |
+
# we change it here so next call to trigger will change it back
|
| 244 |
+
self._toggled = False
|
| 245 |
+
super().set_figure(figure)
|
| 246 |
+
if toggled:
|
| 247 |
+
if figure:
|
| 248 |
+
self.trigger(self, None)
|
| 249 |
+
else:
|
| 250 |
+
# if there is no figure, trigger won't change the internal
|
| 251 |
+
# state we change it back
|
| 252 |
+
self._toggled = True
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class ToolSetCursor(ToolBase):
|
| 256 |
+
"""
|
| 257 |
+
Change to the current cursor while inaxes.
|
| 258 |
+
|
| 259 |
+
This tool, keeps track of all `ToolToggleBase` derived tools, and updates
|
| 260 |
+
the cursor when a tool gets triggered.
|
| 261 |
+
"""
|
| 262 |
+
def __init__(self, *args, **kwargs):
|
| 263 |
+
super().__init__(*args, **kwargs)
|
| 264 |
+
self._id_drag = None
|
| 265 |
+
self._current_tool = None
|
| 266 |
+
self._default_cursor = cursors.POINTER
|
| 267 |
+
self._last_cursor = self._default_cursor
|
| 268 |
+
self.toolmanager.toolmanager_connect('tool_added_event',
|
| 269 |
+
self._add_tool_cbk)
|
| 270 |
+
# process current tools
|
| 271 |
+
for tool in self.toolmanager.tools.values():
|
| 272 |
+
self._add_tool(tool)
|
| 273 |
+
|
| 274 |
+
def set_figure(self, figure):
|
| 275 |
+
if self._id_drag:
|
| 276 |
+
self.canvas.mpl_disconnect(self._id_drag)
|
| 277 |
+
super().set_figure(figure)
|
| 278 |
+
if figure:
|
| 279 |
+
self._id_drag = self.canvas.mpl_connect(
|
| 280 |
+
'motion_notify_event', self._set_cursor_cbk)
|
| 281 |
+
|
| 282 |
+
def _tool_trigger_cbk(self, event):
|
| 283 |
+
if event.tool.toggled:
|
| 284 |
+
self._current_tool = event.tool
|
| 285 |
+
else:
|
| 286 |
+
self._current_tool = None
|
| 287 |
+
self._set_cursor_cbk(event.canvasevent)
|
| 288 |
+
|
| 289 |
+
def _add_tool(self, tool):
|
| 290 |
+
"""Set the cursor when the tool is triggered."""
|
| 291 |
+
if getattr(tool, 'cursor', None) is not None:
|
| 292 |
+
self.toolmanager.toolmanager_connect('tool_trigger_%s' % tool.name,
|
| 293 |
+
self._tool_trigger_cbk)
|
| 294 |
+
|
| 295 |
+
def _add_tool_cbk(self, event):
|
| 296 |
+
"""Process every newly added tool."""
|
| 297 |
+
if event.tool is self:
|
| 298 |
+
return
|
| 299 |
+
self._add_tool(event.tool)
|
| 300 |
+
|
| 301 |
+
def _set_cursor_cbk(self, event):
|
| 302 |
+
if not event or not self.canvas:
|
| 303 |
+
return
|
| 304 |
+
if (self._current_tool and getattr(event, "inaxes", None)
|
| 305 |
+
and event.inaxes.get_navigate()):
|
| 306 |
+
if self._last_cursor != self._current_tool.cursor:
|
| 307 |
+
self.canvas.set_cursor(self._current_tool.cursor)
|
| 308 |
+
self._last_cursor = self._current_tool.cursor
|
| 309 |
+
elif self._last_cursor != self._default_cursor:
|
| 310 |
+
self.canvas.set_cursor(self._default_cursor)
|
| 311 |
+
self._last_cursor = self._default_cursor
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class ToolCursorPosition(ToolBase):
|
| 315 |
+
"""
|
| 316 |
+
Send message with the current pointer position.
|
| 317 |
+
|
| 318 |
+
This tool runs in the background reporting the position of the cursor.
|
| 319 |
+
"""
|
| 320 |
+
def __init__(self, *args, **kwargs):
|
| 321 |
+
self._id_drag = None
|
| 322 |
+
super().__init__(*args, **kwargs)
|
| 323 |
+
|
| 324 |
+
def set_figure(self, figure):
|
| 325 |
+
if self._id_drag:
|
| 326 |
+
self.canvas.mpl_disconnect(self._id_drag)
|
| 327 |
+
super().set_figure(figure)
|
| 328 |
+
if figure:
|
| 329 |
+
self._id_drag = self.canvas.mpl_connect(
|
| 330 |
+
'motion_notify_event', self.send_message)
|
| 331 |
+
|
| 332 |
+
def send_message(self, event):
|
| 333 |
+
"""Call `matplotlib.backend_managers.ToolManager.message_event`."""
|
| 334 |
+
if self.toolmanager.messagelock.locked():
|
| 335 |
+
return
|
| 336 |
+
|
| 337 |
+
from matplotlib.backend_bases import NavigationToolbar2
|
| 338 |
+
message = NavigationToolbar2._mouse_event_to_message(event)
|
| 339 |
+
self.toolmanager.message_event(message, self)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class RubberbandBase(ToolBase):
|
| 343 |
+
"""Draw and remove a rubberband."""
|
| 344 |
+
def trigger(self, sender, event, data=None):
|
| 345 |
+
"""Call `draw_rubberband` or `remove_rubberband` based on data."""
|
| 346 |
+
if not self.figure.canvas.widgetlock.available(sender):
|
| 347 |
+
return
|
| 348 |
+
if data is not None:
|
| 349 |
+
self.draw_rubberband(*data)
|
| 350 |
+
else:
|
| 351 |
+
self.remove_rubberband()
|
| 352 |
+
|
| 353 |
+
def draw_rubberband(self, *data):
|
| 354 |
+
"""
|
| 355 |
+
Draw rubberband.
|
| 356 |
+
|
| 357 |
+
This method must get implemented per backend.
|
| 358 |
+
"""
|
| 359 |
+
raise NotImplementedError
|
| 360 |
+
|
| 361 |
+
def remove_rubberband(self):
|
| 362 |
+
"""
|
| 363 |
+
Remove rubberband.
|
| 364 |
+
|
| 365 |
+
This method should get implemented per backend.
|
| 366 |
+
"""
|
| 367 |
+
pass
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class ToolQuit(ToolBase):
|
| 371 |
+
"""Tool to call the figure manager destroy method."""
|
| 372 |
+
|
| 373 |
+
description = 'Quit the figure'
|
| 374 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.quit'])
|
| 375 |
+
|
| 376 |
+
def trigger(self, sender, event, data=None):
|
| 377 |
+
Gcf.destroy_fig(self.figure)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class ToolQuitAll(ToolBase):
|
| 381 |
+
"""Tool to call the figure manager destroy method."""
|
| 382 |
+
|
| 383 |
+
description = 'Quit all figures'
|
| 384 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all'])
|
| 385 |
+
|
| 386 |
+
def trigger(self, sender, event, data=None):
|
| 387 |
+
Gcf.destroy_all()
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class ToolGrid(ToolBase):
|
| 391 |
+
"""Tool to toggle the major grids of the figure."""
|
| 392 |
+
|
| 393 |
+
description = 'Toggle major grids'
|
| 394 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.grid'])
|
| 395 |
+
|
| 396 |
+
def trigger(self, sender, event, data=None):
|
| 397 |
+
sentinel = str(uuid.uuid4())
|
| 398 |
+
# Trigger grid switching by temporarily setting :rc:`keymap.grid`
|
| 399 |
+
# to a unique key and sending an appropriate event.
|
| 400 |
+
with cbook._setattr_cm(event, key=sentinel), \
|
| 401 |
+
mpl.rc_context({'keymap.grid': sentinel}):
|
| 402 |
+
mpl.backend_bases.key_press_handler(event, self.figure.canvas)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class ToolMinorGrid(ToolBase):
|
| 406 |
+
"""Tool to toggle the major and minor grids of the figure."""
|
| 407 |
+
|
| 408 |
+
description = 'Toggle major and minor grids'
|
| 409 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor'])
|
| 410 |
+
|
| 411 |
+
def trigger(self, sender, event, data=None):
|
| 412 |
+
sentinel = str(uuid.uuid4())
|
| 413 |
+
# Trigger grid switching by temporarily setting :rc:`keymap.grid_minor`
|
| 414 |
+
# to a unique key and sending an appropriate event.
|
| 415 |
+
with cbook._setattr_cm(event, key=sentinel), \
|
| 416 |
+
mpl.rc_context({'keymap.grid_minor': sentinel}):
|
| 417 |
+
mpl.backend_bases.key_press_handler(event, self.figure.canvas)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class ToolFullScreen(ToolBase):
|
| 421 |
+
"""Tool to toggle full screen."""
|
| 422 |
+
|
| 423 |
+
description = 'Toggle fullscreen mode'
|
| 424 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen'])
|
| 425 |
+
|
| 426 |
+
def trigger(self, sender, event, data=None):
|
| 427 |
+
self.figure.canvas.manager.full_screen_toggle()
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
class AxisScaleBase(ToolToggleBase):
|
| 431 |
+
"""Base Tool to toggle between linear and logarithmic."""
|
| 432 |
+
|
| 433 |
+
def trigger(self, sender, event, data=None):
|
| 434 |
+
if event.inaxes is None:
|
| 435 |
+
return
|
| 436 |
+
super().trigger(sender, event, data)
|
| 437 |
+
|
| 438 |
+
def enable(self, event=None):
|
| 439 |
+
self.set_scale(event.inaxes, 'log')
|
| 440 |
+
self.figure.canvas.draw_idle()
|
| 441 |
+
|
| 442 |
+
def disable(self, event=None):
|
| 443 |
+
self.set_scale(event.inaxes, 'linear')
|
| 444 |
+
self.figure.canvas.draw_idle()
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class ToolYScale(AxisScaleBase):
|
| 448 |
+
"""Tool to toggle between linear and logarithmic scales on the Y axis."""
|
| 449 |
+
|
| 450 |
+
description = 'Toggle scale Y axis'
|
| 451 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.yscale'])
|
| 452 |
+
|
| 453 |
+
def set_scale(self, ax, scale):
|
| 454 |
+
ax.set_yscale(scale)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
class ToolXScale(AxisScaleBase):
|
| 458 |
+
"""Tool to toggle between linear and logarithmic scales on the X axis."""
|
| 459 |
+
|
| 460 |
+
description = 'Toggle scale X axis'
|
| 461 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.xscale'])
|
| 462 |
+
|
| 463 |
+
def set_scale(self, ax, scale):
|
| 464 |
+
ax.set_xscale(scale)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class ToolViewsPositions(ToolBase):
|
| 468 |
+
"""
|
| 469 |
+
Auxiliary Tool to handle changes in views and positions.
|
| 470 |
+
|
| 471 |
+
Runs in the background and should get used by all the tools that
|
| 472 |
+
need to access the figure's history of views and positions, e.g.
|
| 473 |
+
|
| 474 |
+
* `ToolZoom`
|
| 475 |
+
* `ToolPan`
|
| 476 |
+
* `ToolHome`
|
| 477 |
+
* `ToolBack`
|
| 478 |
+
* `ToolForward`
|
| 479 |
+
"""
|
| 480 |
+
|
| 481 |
+
def __init__(self, *args, **kwargs):
|
| 482 |
+
self.views = WeakKeyDictionary()
|
| 483 |
+
self.positions = WeakKeyDictionary()
|
| 484 |
+
self.home_views = WeakKeyDictionary()
|
| 485 |
+
super().__init__(*args, **kwargs)
|
| 486 |
+
|
| 487 |
+
def add_figure(self, figure):
|
| 488 |
+
"""Add the current figure to the stack of views and positions."""
|
| 489 |
+
|
| 490 |
+
if figure not in self.views:
|
| 491 |
+
self.views[figure] = cbook.Stack()
|
| 492 |
+
self.positions[figure] = cbook.Stack()
|
| 493 |
+
self.home_views[figure] = WeakKeyDictionary()
|
| 494 |
+
# Define Home
|
| 495 |
+
self.push_current(figure)
|
| 496 |
+
# Make sure we add a home view for new axes as they're added
|
| 497 |
+
figure.add_axobserver(lambda fig: self.update_home_views(fig))
|
| 498 |
+
|
| 499 |
+
def clear(self, figure):
|
| 500 |
+
"""Reset the axes stack."""
|
| 501 |
+
if figure in self.views:
|
| 502 |
+
self.views[figure].clear()
|
| 503 |
+
self.positions[figure].clear()
|
| 504 |
+
self.home_views[figure].clear()
|
| 505 |
+
self.update_home_views()
|
| 506 |
+
|
| 507 |
+
def update_view(self):
|
| 508 |
+
"""
|
| 509 |
+
Update the view limits and position for each axes from the current
|
| 510 |
+
stack position. If any axes are present in the figure that aren't in
|
| 511 |
+
the current stack position, use the home view limits for those axes and
|
| 512 |
+
don't update *any* positions.
|
| 513 |
+
"""
|
| 514 |
+
|
| 515 |
+
views = self.views[self.figure]()
|
| 516 |
+
if views is None:
|
| 517 |
+
return
|
| 518 |
+
pos = self.positions[self.figure]()
|
| 519 |
+
if pos is None:
|
| 520 |
+
return
|
| 521 |
+
home_views = self.home_views[self.figure]
|
| 522 |
+
all_axes = self.figure.get_axes()
|
| 523 |
+
for a in all_axes:
|
| 524 |
+
if a in views:
|
| 525 |
+
cur_view = views[a]
|
| 526 |
+
else:
|
| 527 |
+
cur_view = home_views[a]
|
| 528 |
+
a._set_view(cur_view)
|
| 529 |
+
|
| 530 |
+
if set(all_axes).issubset(pos):
|
| 531 |
+
for a in all_axes:
|
| 532 |
+
# Restore both the original and modified positions
|
| 533 |
+
a._set_position(pos[a][0], 'original')
|
| 534 |
+
a._set_position(pos[a][1], 'active')
|
| 535 |
+
|
| 536 |
+
self.figure.canvas.draw_idle()
|
| 537 |
+
|
| 538 |
+
def push_current(self, figure=None):
|
| 539 |
+
"""
|
| 540 |
+
Push the current view limits and position onto their respective stacks.
|
| 541 |
+
"""
|
| 542 |
+
if not figure:
|
| 543 |
+
figure = self.figure
|
| 544 |
+
views = WeakKeyDictionary()
|
| 545 |
+
pos = WeakKeyDictionary()
|
| 546 |
+
for a in figure.get_axes():
|
| 547 |
+
views[a] = a._get_view()
|
| 548 |
+
pos[a] = self._axes_pos(a)
|
| 549 |
+
self.views[figure].push(views)
|
| 550 |
+
self.positions[figure].push(pos)
|
| 551 |
+
|
| 552 |
+
def _axes_pos(self, ax):
|
| 553 |
+
"""
|
| 554 |
+
Return the original and modified positions for the specified axes.
|
| 555 |
+
|
| 556 |
+
Parameters
|
| 557 |
+
----------
|
| 558 |
+
ax : matplotlib.axes.Axes
|
| 559 |
+
The `.Axes` to get the positions for.
|
| 560 |
+
|
| 561 |
+
Returns
|
| 562 |
+
-------
|
| 563 |
+
original_position, modified_position
|
| 564 |
+
A tuple of the original and modified positions.
|
| 565 |
+
"""
|
| 566 |
+
|
| 567 |
+
return (ax.get_position(True).frozen(),
|
| 568 |
+
ax.get_position().frozen())
|
| 569 |
+
|
| 570 |
+
def update_home_views(self, figure=None):
|
| 571 |
+
"""
|
| 572 |
+
Make sure that ``self.home_views`` has an entry for all axes present
|
| 573 |
+
in the figure.
|
| 574 |
+
"""
|
| 575 |
+
|
| 576 |
+
if not figure:
|
| 577 |
+
figure = self.figure
|
| 578 |
+
for a in figure.get_axes():
|
| 579 |
+
if a not in self.home_views[figure]:
|
| 580 |
+
self.home_views[figure][a] = a._get_view()
|
| 581 |
+
|
| 582 |
+
def home(self):
|
| 583 |
+
"""Recall the first view and position from the stack."""
|
| 584 |
+
self.views[self.figure].home()
|
| 585 |
+
self.positions[self.figure].home()
|
| 586 |
+
|
| 587 |
+
def back(self):
|
| 588 |
+
"""Back one step in the stack of views and positions."""
|
| 589 |
+
self.views[self.figure].back()
|
| 590 |
+
self.positions[self.figure].back()
|
| 591 |
+
|
| 592 |
+
def forward(self):
|
| 593 |
+
"""Forward one step in the stack of views and positions."""
|
| 594 |
+
self.views[self.figure].forward()
|
| 595 |
+
self.positions[self.figure].forward()
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class ViewsPositionsBase(ToolBase):
|
| 599 |
+
"""Base class for `ToolHome`, `ToolBack` and `ToolForward`."""
|
| 600 |
+
|
| 601 |
+
_on_trigger = None
|
| 602 |
+
|
| 603 |
+
def trigger(self, sender, event, data=None):
|
| 604 |
+
self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
|
| 605 |
+
getattr(self.toolmanager.get_tool(_views_positions),
|
| 606 |
+
self._on_trigger)()
|
| 607 |
+
self.toolmanager.get_tool(_views_positions).update_view()
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
class ToolHome(ViewsPositionsBase):
|
| 611 |
+
"""Restore the original view limits."""
|
| 612 |
+
|
| 613 |
+
description = 'Reset original view'
|
| 614 |
+
image = 'home'
|
| 615 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.home'])
|
| 616 |
+
_on_trigger = 'home'
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class ToolBack(ViewsPositionsBase):
|
| 620 |
+
"""Move back up the view limits stack."""
|
| 621 |
+
|
| 622 |
+
description = 'Back to previous view'
|
| 623 |
+
image = 'back'
|
| 624 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.back'])
|
| 625 |
+
_on_trigger = 'back'
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
class ToolForward(ViewsPositionsBase):
|
| 629 |
+
"""Move forward in the view lim stack."""
|
| 630 |
+
|
| 631 |
+
description = 'Forward to next view'
|
| 632 |
+
image = 'forward'
|
| 633 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.forward'])
|
| 634 |
+
_on_trigger = 'forward'
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
class ConfigureSubplotsBase(ToolBase):
|
| 638 |
+
"""Base tool for the configuration of subplots."""
|
| 639 |
+
|
| 640 |
+
description = 'Configure subplots'
|
| 641 |
+
image = 'subplots'
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
class SaveFigureBase(ToolBase):
|
| 645 |
+
"""Base tool for figure saving."""
|
| 646 |
+
|
| 647 |
+
description = 'Save the figure'
|
| 648 |
+
image = 'filesave'
|
| 649 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.save'])
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
class ZoomPanBase(ToolToggleBase):
|
| 653 |
+
"""Base class for `ToolZoom` and `ToolPan`."""
|
| 654 |
+
def __init__(self, *args):
|
| 655 |
+
super().__init__(*args)
|
| 656 |
+
self._button_pressed = None
|
| 657 |
+
self._xypress = None
|
| 658 |
+
self._idPress = None
|
| 659 |
+
self._idRelease = None
|
| 660 |
+
self._idScroll = None
|
| 661 |
+
self.base_scale = 2.
|
| 662 |
+
self.scrollthresh = .5 # .5 second scroll threshold
|
| 663 |
+
self.lastscroll = time.time()-self.scrollthresh
|
| 664 |
+
|
| 665 |
+
def enable(self, event=None):
|
| 666 |
+
"""Connect press/release events and lock the canvas."""
|
| 667 |
+
self.figure.canvas.widgetlock(self)
|
| 668 |
+
self._idPress = self.figure.canvas.mpl_connect(
|
| 669 |
+
'button_press_event', self._press)
|
| 670 |
+
self._idRelease = self.figure.canvas.mpl_connect(
|
| 671 |
+
'button_release_event', self._release)
|
| 672 |
+
self._idScroll = self.figure.canvas.mpl_connect(
|
| 673 |
+
'scroll_event', self.scroll_zoom)
|
| 674 |
+
|
| 675 |
+
def disable(self, event=None):
|
| 676 |
+
"""Release the canvas and disconnect press/release events."""
|
| 677 |
+
self._cancel_action()
|
| 678 |
+
self.figure.canvas.widgetlock.release(self)
|
| 679 |
+
self.figure.canvas.mpl_disconnect(self._idPress)
|
| 680 |
+
self.figure.canvas.mpl_disconnect(self._idRelease)
|
| 681 |
+
self.figure.canvas.mpl_disconnect(self._idScroll)
|
| 682 |
+
|
| 683 |
+
def trigger(self, sender, event, data=None):
|
| 684 |
+
self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
|
| 685 |
+
super().trigger(sender, event, data)
|
| 686 |
+
new_navigate_mode = self.name.upper() if self.toggled else None
|
| 687 |
+
for ax in self.figure.axes:
|
| 688 |
+
ax.set_navigate_mode(new_navigate_mode)
|
| 689 |
+
|
| 690 |
+
def scroll_zoom(self, event):
|
| 691 |
+
# https://gist.github.com/tacaswell/3144287
|
| 692 |
+
if event.inaxes is None:
|
| 693 |
+
return
|
| 694 |
+
|
| 695 |
+
if event.button == 'up':
|
| 696 |
+
# deal with zoom in
|
| 697 |
+
scl = self.base_scale
|
| 698 |
+
elif event.button == 'down':
|
| 699 |
+
# deal with zoom out
|
| 700 |
+
scl = 1/self.base_scale
|
| 701 |
+
else:
|
| 702 |
+
# deal with something that should never happen
|
| 703 |
+
scl = 1
|
| 704 |
+
|
| 705 |
+
ax = event.inaxes
|
| 706 |
+
ax._set_view_from_bbox([event.x, event.y, scl])
|
| 707 |
+
|
| 708 |
+
# If last scroll was done within the timing threshold, delete the
|
| 709 |
+
# previous view
|
| 710 |
+
if (time.time()-self.lastscroll) < self.scrollthresh:
|
| 711 |
+
self.toolmanager.get_tool(_views_positions).back()
|
| 712 |
+
|
| 713 |
+
self.figure.canvas.draw_idle() # force re-draw
|
| 714 |
+
|
| 715 |
+
self.lastscroll = time.time()
|
| 716 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
class ToolZoom(ZoomPanBase):
|
| 720 |
+
"""A Tool for zooming using a rectangle selector."""
|
| 721 |
+
|
| 722 |
+
description = 'Zoom to rectangle'
|
| 723 |
+
image = 'zoom_to_rect'
|
| 724 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.zoom'])
|
| 725 |
+
cursor = cursors.SELECT_REGION
|
| 726 |
+
radio_group = 'default'
|
| 727 |
+
|
| 728 |
+
def __init__(self, *args):
|
| 729 |
+
super().__init__(*args)
|
| 730 |
+
self._ids_zoom = []
|
| 731 |
+
|
| 732 |
+
def _cancel_action(self):
|
| 733 |
+
for zoom_id in self._ids_zoom:
|
| 734 |
+
self.figure.canvas.mpl_disconnect(zoom_id)
|
| 735 |
+
self.toolmanager.trigger_tool('rubberband', self)
|
| 736 |
+
self.figure.canvas.draw_idle()
|
| 737 |
+
self._xypress = None
|
| 738 |
+
self._button_pressed = None
|
| 739 |
+
self._ids_zoom = []
|
| 740 |
+
return
|
| 741 |
+
|
| 742 |
+
def _press(self, event):
|
| 743 |
+
"""Callback for mouse button presses in zoom-to-rectangle mode."""
|
| 744 |
+
|
| 745 |
+
# If we're already in the middle of a zoom, pressing another
|
| 746 |
+
# button works to "cancel"
|
| 747 |
+
if self._ids_zoom:
|
| 748 |
+
self._cancel_action()
|
| 749 |
+
|
| 750 |
+
if event.button == 1:
|
| 751 |
+
self._button_pressed = 1
|
| 752 |
+
elif event.button == 3:
|
| 753 |
+
self._button_pressed = 3
|
| 754 |
+
else:
|
| 755 |
+
self._cancel_action()
|
| 756 |
+
return
|
| 757 |
+
|
| 758 |
+
x, y = event.x, event.y
|
| 759 |
+
|
| 760 |
+
self._xypress = []
|
| 761 |
+
for i, a in enumerate(self.figure.get_axes()):
|
| 762 |
+
if (x is not None and y is not None and a.in_axes(event) and
|
| 763 |
+
a.get_navigate() and a.can_zoom()):
|
| 764 |
+
self._xypress.append((x, y, a, i, a._get_view()))
|
| 765 |
+
|
| 766 |
+
id1 = self.figure.canvas.mpl_connect(
|
| 767 |
+
'motion_notify_event', self._mouse_move)
|
| 768 |
+
id2 = self.figure.canvas.mpl_connect(
|
| 769 |
+
'key_press_event', self._switch_on_zoom_mode)
|
| 770 |
+
id3 = self.figure.canvas.mpl_connect(
|
| 771 |
+
'key_release_event', self._switch_off_zoom_mode)
|
| 772 |
+
|
| 773 |
+
self._ids_zoom = id1, id2, id3
|
| 774 |
+
self._zoom_mode = event.key
|
| 775 |
+
|
| 776 |
+
def _switch_on_zoom_mode(self, event):
|
| 777 |
+
self._zoom_mode = event.key
|
| 778 |
+
self._mouse_move(event)
|
| 779 |
+
|
| 780 |
+
def _switch_off_zoom_mode(self, event):
|
| 781 |
+
self._zoom_mode = None
|
| 782 |
+
self._mouse_move(event)
|
| 783 |
+
|
| 784 |
+
def _mouse_move(self, event):
|
| 785 |
+
"""Callback for mouse moves in zoom-to-rectangle mode."""
|
| 786 |
+
|
| 787 |
+
if self._xypress:
|
| 788 |
+
x, y = event.x, event.y
|
| 789 |
+
lastx, lasty, a, ind, view = self._xypress[0]
|
| 790 |
+
(x1, y1), (x2, y2) = np.clip(
|
| 791 |
+
[[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
|
| 792 |
+
if self._zoom_mode == "x":
|
| 793 |
+
y1, y2 = a.bbox.intervaly
|
| 794 |
+
elif self._zoom_mode == "y":
|
| 795 |
+
x1, x2 = a.bbox.intervalx
|
| 796 |
+
self.toolmanager.trigger_tool(
|
| 797 |
+
'rubberband', self, data=(x1, y1, x2, y2))
|
| 798 |
+
|
| 799 |
+
def _release(self, event):
|
| 800 |
+
"""Callback for mouse button releases in zoom-to-rectangle mode."""
|
| 801 |
+
|
| 802 |
+
for zoom_id in self._ids_zoom:
|
| 803 |
+
self.figure.canvas.mpl_disconnect(zoom_id)
|
| 804 |
+
self._ids_zoom = []
|
| 805 |
+
|
| 806 |
+
if not self._xypress:
|
| 807 |
+
self._cancel_action()
|
| 808 |
+
return
|
| 809 |
+
|
| 810 |
+
done_ax = []
|
| 811 |
+
|
| 812 |
+
for cur_xypress in self._xypress:
|
| 813 |
+
x, y = event.x, event.y
|
| 814 |
+
lastx, lasty, a, _ind, view = cur_xypress
|
| 815 |
+
# ignore singular clicks - 5 pixels is a threshold
|
| 816 |
+
if abs(x - lastx) < 5 or abs(y - lasty) < 5:
|
| 817 |
+
self._cancel_action()
|
| 818 |
+
return
|
| 819 |
+
|
| 820 |
+
# detect twinx, twiny axes and avoid double zooming
|
| 821 |
+
twinx = any(a.get_shared_x_axes().joined(a, a1) for a1 in done_ax)
|
| 822 |
+
twiny = any(a.get_shared_y_axes().joined(a, a1) for a1 in done_ax)
|
| 823 |
+
done_ax.append(a)
|
| 824 |
+
|
| 825 |
+
if self._button_pressed == 1:
|
| 826 |
+
direction = 'in'
|
| 827 |
+
elif self._button_pressed == 3:
|
| 828 |
+
direction = 'out'
|
| 829 |
+
else:
|
| 830 |
+
continue
|
| 831 |
+
|
| 832 |
+
a._set_view_from_bbox((lastx, lasty, x, y), direction,
|
| 833 |
+
self._zoom_mode, twinx, twiny)
|
| 834 |
+
|
| 835 |
+
self._zoom_mode = None
|
| 836 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 837 |
+
self._cancel_action()
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
class ToolPan(ZoomPanBase):
|
| 841 |
+
"""Pan axes with left mouse, zoom with right."""
|
| 842 |
+
|
| 843 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.pan'])
|
| 844 |
+
description = 'Pan axes with left mouse, zoom with right'
|
| 845 |
+
image = 'move'
|
| 846 |
+
cursor = cursors.MOVE
|
| 847 |
+
radio_group = 'default'
|
| 848 |
+
|
| 849 |
+
def __init__(self, *args):
|
| 850 |
+
super().__init__(*args)
|
| 851 |
+
self._id_drag = None
|
| 852 |
+
|
| 853 |
+
def _cancel_action(self):
|
| 854 |
+
self._button_pressed = None
|
| 855 |
+
self._xypress = []
|
| 856 |
+
self.figure.canvas.mpl_disconnect(self._id_drag)
|
| 857 |
+
self.toolmanager.messagelock.release(self)
|
| 858 |
+
self.figure.canvas.draw_idle()
|
| 859 |
+
|
| 860 |
+
def _press(self, event):
|
| 861 |
+
if event.button == 1:
|
| 862 |
+
self._button_pressed = 1
|
| 863 |
+
elif event.button == 3:
|
| 864 |
+
self._button_pressed = 3
|
| 865 |
+
else:
|
| 866 |
+
self._cancel_action()
|
| 867 |
+
return
|
| 868 |
+
|
| 869 |
+
x, y = event.x, event.y
|
| 870 |
+
|
| 871 |
+
self._xypress = []
|
| 872 |
+
for i, a in enumerate(self.figure.get_axes()):
|
| 873 |
+
if (x is not None and y is not None and a.in_axes(event) and
|
| 874 |
+
a.get_navigate() and a.can_pan()):
|
| 875 |
+
a.start_pan(x, y, event.button)
|
| 876 |
+
self._xypress.append((a, i))
|
| 877 |
+
self.toolmanager.messagelock(self)
|
| 878 |
+
self._id_drag = self.figure.canvas.mpl_connect(
|
| 879 |
+
'motion_notify_event', self._mouse_move)
|
| 880 |
+
|
| 881 |
+
def _release(self, event):
|
| 882 |
+
if self._button_pressed is None:
|
| 883 |
+
self._cancel_action()
|
| 884 |
+
return
|
| 885 |
+
|
| 886 |
+
self.figure.canvas.mpl_disconnect(self._id_drag)
|
| 887 |
+
self.toolmanager.messagelock.release(self)
|
| 888 |
+
|
| 889 |
+
for a, _ind in self._xypress:
|
| 890 |
+
a.end_pan()
|
| 891 |
+
if not self._xypress:
|
| 892 |
+
self._cancel_action()
|
| 893 |
+
return
|
| 894 |
+
|
| 895 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 896 |
+
self._cancel_action()
|
| 897 |
+
|
| 898 |
+
def _mouse_move(self, event):
|
| 899 |
+
for a, _ind in self._xypress:
|
| 900 |
+
# safer to use the recorded button at the _press than current
|
| 901 |
+
# button: # multiple button can get pressed during motion...
|
| 902 |
+
a.drag_pan(self._button_pressed, event.key, event.x, event.y)
|
| 903 |
+
self.toolmanager.canvas.draw_idle()
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
class ToolHelpBase(ToolBase):
|
| 907 |
+
description = 'Print tool list, shortcuts and description'
|
| 908 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.help'])
|
| 909 |
+
image = 'help'
|
| 910 |
+
|
| 911 |
+
@staticmethod
|
| 912 |
+
def format_shortcut(key_sequence):
|
| 913 |
+
"""
|
| 914 |
+
Convert a shortcut string from the notation used in rc config to the
|
| 915 |
+
standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'.
|
| 916 |
+
"""
|
| 917 |
+
return (key_sequence if len(key_sequence) == 1 else
|
| 918 |
+
re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title())
|
| 919 |
+
|
| 920 |
+
def _format_tool_keymap(self, name):
|
| 921 |
+
keymaps = self.toolmanager.get_tool_keymap(name)
|
| 922 |
+
return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
|
| 923 |
+
|
| 924 |
+
def _get_help_entries(self):
|
| 925 |
+
return [(name, self._format_tool_keymap(name), tool.description)
|
| 926 |
+
for name, tool in sorted(self.toolmanager.tools.items())
|
| 927 |
+
if tool.description]
|
| 928 |
+
|
| 929 |
+
def _get_help_text(self):
|
| 930 |
+
entries = self._get_help_entries()
|
| 931 |
+
entries = ["{}: {}\n\t{}".format(*entry) for entry in entries]
|
| 932 |
+
return "\n".join(entries)
|
| 933 |
+
|
| 934 |
+
def _get_help_html(self):
|
| 935 |
+
fmt = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>"
|
| 936 |
+
rows = [fmt.format(
|
| 937 |
+
"<b>Action</b>", "<b>Shortcuts</b>", "<b>Description</b>")]
|
| 938 |
+
rows += [fmt.format(*row) for row in self._get_help_entries()]
|
| 939 |
+
return ("<style>td {padding: 0px 4px}</style>"
|
| 940 |
+
"<table><thead>" + rows[0] + "</thead>"
|
| 941 |
+
"<tbody>".join(rows[1:]) + "</tbody></table>")
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
class ToolCopyToClipboardBase(ToolBase):
|
| 945 |
+
"""Tool to copy the figure to the clipboard."""
|
| 946 |
+
|
| 947 |
+
description = 'Copy the canvas figure to clipboard'
|
| 948 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.copy'])
|
| 949 |
+
|
| 950 |
+
def trigger(self, *args, **kwargs):
|
| 951 |
+
message = "Copy tool is not available"
|
| 952 |
+
self.toolmanager.message_event(message, self)
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
|
| 956 |
+
'zoom': ToolZoom, 'pan': ToolPan,
|
| 957 |
+
'subplots': ConfigureSubplotsBase,
|
| 958 |
+
'save': SaveFigureBase,
|
| 959 |
+
'grid': ToolGrid,
|
| 960 |
+
'grid_minor': ToolMinorGrid,
|
| 961 |
+
'fullscreen': ToolFullScreen,
|
| 962 |
+
'quit': ToolQuit,
|
| 963 |
+
'quit_all': ToolQuitAll,
|
| 964 |
+
'xscale': ToolXScale,
|
| 965 |
+
'yscale': ToolYScale,
|
| 966 |
+
'position': ToolCursorPosition,
|
| 967 |
+
_views_positions: ToolViewsPositions,
|
| 968 |
+
'cursor': ToolSetCursor,
|
| 969 |
+
'rubberband': RubberbandBase,
|
| 970 |
+
'help': ToolHelpBase,
|
| 971 |
+
'copy': ToolCopyToClipboardBase,
|
| 972 |
+
}
|
| 973 |
+
|
| 974 |
+
default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
|
| 975 |
+
['zoompan', ['pan', 'zoom', 'subplots']],
|
| 976 |
+
['io', ['save', 'help']]]
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
def add_tools_to_manager(toolmanager, tools=default_tools):
|
| 980 |
+
"""
|
| 981 |
+
Add multiple tools to a `.ToolManager`.
|
| 982 |
+
|
| 983 |
+
Parameters
|
| 984 |
+
----------
|
| 985 |
+
toolmanager : `.backend_managers.ToolManager`
|
| 986 |
+
Manager to which the tools are added.
|
| 987 |
+
tools : {str: class_like}, optional
|
| 988 |
+
The tools to add in a {name: tool} dict, see
|
| 989 |
+
`.backend_managers.ToolManager.add_tool` for more info.
|
| 990 |
+
"""
|
| 991 |
+
|
| 992 |
+
for name, tool in tools.items():
|
| 993 |
+
toolmanager.add_tool(name, tool)
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def add_tools_to_container(container, tools=default_toolbar_tools):
|
| 997 |
+
"""
|
| 998 |
+
Add multiple tools to the container.
|
| 999 |
+
|
| 1000 |
+
Parameters
|
| 1001 |
+
----------
|
| 1002 |
+
container : Container
|
| 1003 |
+
`.backend_bases.ToolContainerBase` object that will get the tools
|
| 1004 |
+
added.
|
| 1005 |
+
tools : list, optional
|
| 1006 |
+
List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
|
| 1007 |
+
where the tools ``[tool1, tool2, ...]`` will display in group1.
|
| 1008 |
+
See `.backend_bases.ToolContainerBase.add_tool` for details.
|
| 1009 |
+
"""
|
| 1010 |
+
|
| 1011 |
+
for group, grouptools in tools:
|
| 1012 |
+
for position, tool in enumerate(grouptools):
|
| 1013 |
+
container.add_tool(tool, group, position)
|
omnilmm/lib/python3.10/site-packages/matplotlib/bezier.py
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A module providing some utility functions regarding Bézier path manipulation.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
import math
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from matplotlib import _api
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# same algorithm as 3.8's math.comb
|
| 15 |
+
@np.vectorize
|
| 16 |
+
@lru_cache(maxsize=128)
|
| 17 |
+
def _comb(n, k):
|
| 18 |
+
if k > n:
|
| 19 |
+
return 0
|
| 20 |
+
k = min(k, n - k)
|
| 21 |
+
i = np.arange(1, k + 1)
|
| 22 |
+
return np.prod((n + 1 - i)/i).astype(int)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class NonIntersectingPathException(ValueError):
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# some functions
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_intersection(cx1, cy1, cos_t1, sin_t1,
|
| 33 |
+
cx2, cy2, cos_t2, sin_t2):
|
| 34 |
+
"""
|
| 35 |
+
Return the intersection between the line through (*cx1*, *cy1*) at angle
|
| 36 |
+
*t1* and the line through (*cx2*, *cy2*) at angle *t2*.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
# line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0.
|
| 40 |
+
# line1 => sin_t1 * x + cos_t1 * y = sin_t1*cx1 - cos_t1*cy1
|
| 41 |
+
|
| 42 |
+
line1_rhs = sin_t1 * cx1 - cos_t1 * cy1
|
| 43 |
+
line2_rhs = sin_t2 * cx2 - cos_t2 * cy2
|
| 44 |
+
|
| 45 |
+
# rhs matrix
|
| 46 |
+
a, b = sin_t1, -cos_t1
|
| 47 |
+
c, d = sin_t2, -cos_t2
|
| 48 |
+
|
| 49 |
+
ad_bc = a * d - b * c
|
| 50 |
+
if abs(ad_bc) < 1e-12:
|
| 51 |
+
raise ValueError("Given lines do not intersect. Please verify that "
|
| 52 |
+
"the angles are not equal or differ by 180 degrees.")
|
| 53 |
+
|
| 54 |
+
# rhs_inverse
|
| 55 |
+
a_, b_ = d, -b
|
| 56 |
+
c_, d_ = -c, a
|
| 57 |
+
a_, b_, c_, d_ = [k / ad_bc for k in [a_, b_, c_, d_]]
|
| 58 |
+
|
| 59 |
+
x = a_ * line1_rhs + b_ * line2_rhs
|
| 60 |
+
y = c_ * line1_rhs + d_ * line2_rhs
|
| 61 |
+
|
| 62 |
+
return x, y
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_normal_points(cx, cy, cos_t, sin_t, length):
|
| 66 |
+
"""
|
| 67 |
+
For a line passing through (*cx*, *cy*) and having an angle *t*, return
|
| 68 |
+
locations of the two points located along its perpendicular line at the
|
| 69 |
+
distance of *length*.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
if length == 0.:
|
| 73 |
+
return cx, cy, cx, cy
|
| 74 |
+
|
| 75 |
+
cos_t1, sin_t1 = sin_t, -cos_t
|
| 76 |
+
cos_t2, sin_t2 = -sin_t, cos_t
|
| 77 |
+
|
| 78 |
+
x1, y1 = length * cos_t1 + cx, length * sin_t1 + cy
|
| 79 |
+
x2, y2 = length * cos_t2 + cx, length * sin_t2 + cy
|
| 80 |
+
|
| 81 |
+
return x1, y1, x2, y2
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# BEZIER routines
|
| 85 |
+
|
| 86 |
+
# subdividing bezier curve
|
| 87 |
+
# http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-sub.html
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _de_casteljau1(beta, t):
|
| 91 |
+
next_beta = beta[:-1] * (1 - t) + beta[1:] * t
|
| 92 |
+
return next_beta
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def split_de_casteljau(beta, t):
|
| 96 |
+
"""
|
| 97 |
+
Split a Bézier segment defined by its control points *beta* into two
|
| 98 |
+
separate segments divided at *t* and return their control points.
|
| 99 |
+
"""
|
| 100 |
+
beta = np.asarray(beta)
|
| 101 |
+
beta_list = [beta]
|
| 102 |
+
while True:
|
| 103 |
+
beta = _de_casteljau1(beta, t)
|
| 104 |
+
beta_list.append(beta)
|
| 105 |
+
if len(beta) == 1:
|
| 106 |
+
break
|
| 107 |
+
left_beta = [beta[0] for beta in beta_list]
|
| 108 |
+
right_beta = [beta[-1] for beta in reversed(beta_list)]
|
| 109 |
+
|
| 110 |
+
return left_beta, right_beta
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def find_bezier_t_intersecting_with_closedpath(
|
| 114 |
+
bezier_point_at_t, inside_closedpath, t0=0., t1=1., tolerance=0.01):
|
| 115 |
+
"""
|
| 116 |
+
Find the intersection of the Bézier curve with a closed path.
|
| 117 |
+
|
| 118 |
+
The intersection point *t* is approximated by two parameters *t0*, *t1*
|
| 119 |
+
such that *t0* <= *t* <= *t1*.
|
| 120 |
+
|
| 121 |
+
Search starts from *t0* and *t1* and uses a simple bisecting algorithm
|
| 122 |
+
therefore one of the end points must be inside the path while the other
|
| 123 |
+
doesn't. The search stops when the distance of the points parametrized by
|
| 124 |
+
*t0* and *t1* gets smaller than the given *tolerance*.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
----------
|
| 128 |
+
bezier_point_at_t : callable
|
| 129 |
+
A function returning x, y coordinates of the Bézier at parameter *t*.
|
| 130 |
+
It must have the signature::
|
| 131 |
+
|
| 132 |
+
bezier_point_at_t(t: float) -> tuple[float, float]
|
| 133 |
+
|
| 134 |
+
inside_closedpath : callable
|
| 135 |
+
A function returning True if a given point (x, y) is inside the
|
| 136 |
+
closed path. It must have the signature::
|
| 137 |
+
|
| 138 |
+
inside_closedpath(point: tuple[float, float]) -> bool
|
| 139 |
+
|
| 140 |
+
t0, t1 : float
|
| 141 |
+
Start parameters for the search.
|
| 142 |
+
|
| 143 |
+
tolerance : float
|
| 144 |
+
Maximal allowed distance between the final points.
|
| 145 |
+
|
| 146 |
+
Returns
|
| 147 |
+
-------
|
| 148 |
+
t0, t1 : float
|
| 149 |
+
The Bézier path parameters.
|
| 150 |
+
"""
|
| 151 |
+
start = bezier_point_at_t(t0)
|
| 152 |
+
end = bezier_point_at_t(t1)
|
| 153 |
+
|
| 154 |
+
start_inside = inside_closedpath(start)
|
| 155 |
+
end_inside = inside_closedpath(end)
|
| 156 |
+
|
| 157 |
+
if start_inside == end_inside and start != end:
|
| 158 |
+
raise NonIntersectingPathException(
|
| 159 |
+
"Both points are on the same side of the closed path")
|
| 160 |
+
|
| 161 |
+
while True:
|
| 162 |
+
|
| 163 |
+
# return if the distance is smaller than the tolerance
|
| 164 |
+
if np.hypot(start[0] - end[0], start[1] - end[1]) < tolerance:
|
| 165 |
+
return t0, t1
|
| 166 |
+
|
| 167 |
+
# calculate the middle point
|
| 168 |
+
middle_t = 0.5 * (t0 + t1)
|
| 169 |
+
middle = bezier_point_at_t(middle_t)
|
| 170 |
+
middle_inside = inside_closedpath(middle)
|
| 171 |
+
|
| 172 |
+
if start_inside ^ middle_inside:
|
| 173 |
+
t1 = middle_t
|
| 174 |
+
end = middle
|
| 175 |
+
else:
|
| 176 |
+
t0 = middle_t
|
| 177 |
+
start = middle
|
| 178 |
+
start_inside = middle_inside
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class BezierSegment:
|
| 182 |
+
"""
|
| 183 |
+
A d-dimensional Bézier segment.
|
| 184 |
+
|
| 185 |
+
Parameters
|
| 186 |
+
----------
|
| 187 |
+
control_points : (N, d) array
|
| 188 |
+
Location of the *N* control points.
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
def __init__(self, control_points):
|
| 192 |
+
self._cpoints = np.asarray(control_points)
|
| 193 |
+
self._N, self._d = self._cpoints.shape
|
| 194 |
+
self._orders = np.arange(self._N)
|
| 195 |
+
coeff = [math.factorial(self._N - 1)
|
| 196 |
+
// (math.factorial(i) * math.factorial(self._N - 1 - i))
|
| 197 |
+
for i in range(self._N)]
|
| 198 |
+
self._px = (self._cpoints.T * coeff).T
|
| 199 |
+
|
| 200 |
+
def __call__(self, t):
|
| 201 |
+
"""
|
| 202 |
+
Evaluate the Bézier curve at point(s) *t* in [0, 1].
|
| 203 |
+
|
| 204 |
+
Parameters
|
| 205 |
+
----------
|
| 206 |
+
t : (k,) array-like
|
| 207 |
+
Points at which to evaluate the curve.
|
| 208 |
+
|
| 209 |
+
Returns
|
| 210 |
+
-------
|
| 211 |
+
(k, d) array
|
| 212 |
+
Value of the curve for each point in *t*.
|
| 213 |
+
"""
|
| 214 |
+
t = np.asarray(t)
|
| 215 |
+
return (np.power.outer(1 - t, self._orders[::-1])
|
| 216 |
+
* np.power.outer(t, self._orders)) @ self._px
|
| 217 |
+
|
| 218 |
+
def point_at_t(self, t):
|
| 219 |
+
"""
|
| 220 |
+
Evaluate the curve at a single point, returning a tuple of *d* floats.
|
| 221 |
+
"""
|
| 222 |
+
return tuple(self(t))
|
| 223 |
+
|
| 224 |
+
@property
|
| 225 |
+
def control_points(self):
|
| 226 |
+
"""The control points of the curve."""
|
| 227 |
+
return self._cpoints
|
| 228 |
+
|
| 229 |
+
@property
|
| 230 |
+
def dimension(self):
|
| 231 |
+
"""The dimension of the curve."""
|
| 232 |
+
return self._d
|
| 233 |
+
|
| 234 |
+
@property
|
| 235 |
+
def degree(self):
|
| 236 |
+
"""Degree of the polynomial. One less the number of control points."""
|
| 237 |
+
return self._N - 1
|
| 238 |
+
|
| 239 |
+
@property
|
| 240 |
+
def polynomial_coefficients(self):
|
| 241 |
+
r"""
|
| 242 |
+
The polynomial coefficients of the Bézier curve.
|
| 243 |
+
|
| 244 |
+
.. warning:: Follows opposite convention from `numpy.polyval`.
|
| 245 |
+
|
| 246 |
+
Returns
|
| 247 |
+
-------
|
| 248 |
+
(n+1, d) array
|
| 249 |
+
Coefficients after expanding in polynomial basis, where :math:`n`
|
| 250 |
+
is the degree of the Bézier curve and :math:`d` its dimension.
|
| 251 |
+
These are the numbers (:math:`C_j`) such that the curve can be
|
| 252 |
+
written :math:`\sum_{j=0}^n C_j t^j`.
|
| 253 |
+
|
| 254 |
+
Notes
|
| 255 |
+
-----
|
| 256 |
+
The coefficients are calculated as
|
| 257 |
+
|
| 258 |
+
.. math::
|
| 259 |
+
|
| 260 |
+
{n \choose j} \sum_{i=0}^j (-1)^{i+j} {j \choose i} P_i
|
| 261 |
+
|
| 262 |
+
where :math:`P_i` are the control points of the curve.
|
| 263 |
+
"""
|
| 264 |
+
n = self.degree
|
| 265 |
+
# matplotlib uses n <= 4. overflow plausible starting around n = 15.
|
| 266 |
+
if n > 10:
|
| 267 |
+
warnings.warn("Polynomial coefficients formula unstable for high "
|
| 268 |
+
"order Bezier curves!", RuntimeWarning)
|
| 269 |
+
P = self.control_points
|
| 270 |
+
j = np.arange(n+1)[:, None]
|
| 271 |
+
i = np.arange(n+1)[None, :] # _comb is non-zero for i <= j
|
| 272 |
+
prefactor = (-1)**(i + j) * _comb(j, i) # j on axis 0, i on axis 1
|
| 273 |
+
return _comb(n, j) * prefactor @ P # j on axis 0, self.dimension on 1
|
| 274 |
+
|
| 275 |
+
def axis_aligned_extrema(self):
|
| 276 |
+
"""
|
| 277 |
+
Return the dimension and location of the curve's interior extrema.
|
| 278 |
+
|
| 279 |
+
The extrema are the points along the curve where one of its partial
|
| 280 |
+
derivatives is zero.
|
| 281 |
+
|
| 282 |
+
Returns
|
| 283 |
+
-------
|
| 284 |
+
dims : array of int
|
| 285 |
+
Index :math:`i` of the partial derivative which is zero at each
|
| 286 |
+
interior extrema.
|
| 287 |
+
dzeros : array of float
|
| 288 |
+
Of same size as dims. The :math:`t` such that :math:`d/dx_i B(t) =
|
| 289 |
+
0`
|
| 290 |
+
"""
|
| 291 |
+
n = self.degree
|
| 292 |
+
if n <= 1:
|
| 293 |
+
return np.array([]), np.array([])
|
| 294 |
+
Cj = self.polynomial_coefficients
|
| 295 |
+
dCj = np.arange(1, n+1)[:, None] * Cj[1:]
|
| 296 |
+
dims = []
|
| 297 |
+
roots = []
|
| 298 |
+
for i, pi in enumerate(dCj.T):
|
| 299 |
+
r = np.roots(pi[::-1])
|
| 300 |
+
roots.append(r)
|
| 301 |
+
dims.append(np.full_like(r, i))
|
| 302 |
+
roots = np.concatenate(roots)
|
| 303 |
+
dims = np.concatenate(dims)
|
| 304 |
+
in_range = np.isreal(roots) & (roots >= 0) & (roots <= 1)
|
| 305 |
+
return dims[in_range], np.real(roots)[in_range]
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def split_bezier_intersecting_with_closedpath(
|
| 309 |
+
bezier, inside_closedpath, tolerance=0.01):
|
| 310 |
+
"""
|
| 311 |
+
Split a Bézier curve into two at the intersection with a closed path.
|
| 312 |
+
|
| 313 |
+
Parameters
|
| 314 |
+
----------
|
| 315 |
+
bezier : (N, 2) array-like
|
| 316 |
+
Control points of the Bézier segment. See `.BezierSegment`.
|
| 317 |
+
inside_closedpath : callable
|
| 318 |
+
A function returning True if a given point (x, y) is inside the
|
| 319 |
+
closed path. See also `.find_bezier_t_intersecting_with_closedpath`.
|
| 320 |
+
tolerance : float
|
| 321 |
+
The tolerance for the intersection. See also
|
| 322 |
+
`.find_bezier_t_intersecting_with_closedpath`.
|
| 323 |
+
|
| 324 |
+
Returns
|
| 325 |
+
-------
|
| 326 |
+
left, right
|
| 327 |
+
Lists of control points for the two Bézier segments.
|
| 328 |
+
"""
|
| 329 |
+
|
| 330 |
+
bz = BezierSegment(bezier)
|
| 331 |
+
bezier_point_at_t = bz.point_at_t
|
| 332 |
+
|
| 333 |
+
t0, t1 = find_bezier_t_intersecting_with_closedpath(
|
| 334 |
+
bezier_point_at_t, inside_closedpath, tolerance=tolerance)
|
| 335 |
+
|
| 336 |
+
_left, _right = split_de_casteljau(bezier, (t0 + t1) / 2.)
|
| 337 |
+
return _left, _right
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
# matplotlib specific
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False):
|
| 344 |
+
"""
|
| 345 |
+
Divide a path into two segments at the point where ``inside(x, y)`` becomes
|
| 346 |
+
False.
|
| 347 |
+
"""
|
| 348 |
+
from .path import Path
|
| 349 |
+
path_iter = path.iter_segments()
|
| 350 |
+
|
| 351 |
+
ctl_points, command = next(path_iter)
|
| 352 |
+
begin_inside = inside(ctl_points[-2:]) # true if begin point is inside
|
| 353 |
+
|
| 354 |
+
ctl_points_old = ctl_points
|
| 355 |
+
|
| 356 |
+
iold = 0
|
| 357 |
+
i = 1
|
| 358 |
+
|
| 359 |
+
for ctl_points, command in path_iter:
|
| 360 |
+
iold = i
|
| 361 |
+
i += len(ctl_points) // 2
|
| 362 |
+
if inside(ctl_points[-2:]) != begin_inside:
|
| 363 |
+
bezier_path = np.concatenate([ctl_points_old[-2:], ctl_points])
|
| 364 |
+
break
|
| 365 |
+
ctl_points_old = ctl_points
|
| 366 |
+
else:
|
| 367 |
+
raise ValueError("The path does not intersect with the patch")
|
| 368 |
+
|
| 369 |
+
bp = bezier_path.reshape((-1, 2))
|
| 370 |
+
left, right = split_bezier_intersecting_with_closedpath(
|
| 371 |
+
bp, inside, tolerance)
|
| 372 |
+
if len(left) == 2:
|
| 373 |
+
codes_left = [Path.LINETO]
|
| 374 |
+
codes_right = [Path.MOVETO, Path.LINETO]
|
| 375 |
+
elif len(left) == 3:
|
| 376 |
+
codes_left = [Path.CURVE3, Path.CURVE3]
|
| 377 |
+
codes_right = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
|
| 378 |
+
elif len(left) == 4:
|
| 379 |
+
codes_left = [Path.CURVE4, Path.CURVE4, Path.CURVE4]
|
| 380 |
+
codes_right = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
|
| 381 |
+
else:
|
| 382 |
+
raise AssertionError("This should never be reached")
|
| 383 |
+
|
| 384 |
+
verts_left = left[1:]
|
| 385 |
+
verts_right = right[:]
|
| 386 |
+
|
| 387 |
+
if path.codes is None:
|
| 388 |
+
path_in = Path(np.concatenate([path.vertices[:i], verts_left]))
|
| 389 |
+
path_out = Path(np.concatenate([verts_right, path.vertices[i:]]))
|
| 390 |
+
|
| 391 |
+
else:
|
| 392 |
+
path_in = Path(np.concatenate([path.vertices[:iold], verts_left]),
|
| 393 |
+
np.concatenate([path.codes[:iold], codes_left]))
|
| 394 |
+
|
| 395 |
+
path_out = Path(np.concatenate([verts_right, path.vertices[i:]]),
|
| 396 |
+
np.concatenate([codes_right, path.codes[i:]]))
|
| 397 |
+
|
| 398 |
+
if reorder_inout and not begin_inside:
|
| 399 |
+
path_in, path_out = path_out, path_in
|
| 400 |
+
|
| 401 |
+
return path_in, path_out
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def inside_circle(cx, cy, r):
|
| 405 |
+
"""
|
| 406 |
+
Return a function that checks whether a point is in a circle with center
|
| 407 |
+
(*cx*, *cy*) and radius *r*.
|
| 408 |
+
|
| 409 |
+
The returned function has the signature::
|
| 410 |
+
|
| 411 |
+
f(xy: tuple[float, float]) -> bool
|
| 412 |
+
"""
|
| 413 |
+
r2 = r ** 2
|
| 414 |
+
|
| 415 |
+
def _f(xy):
|
| 416 |
+
x, y = xy
|
| 417 |
+
return (x - cx) ** 2 + (y - cy) ** 2 < r2
|
| 418 |
+
return _f
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
# quadratic Bezier lines
|
| 422 |
+
|
| 423 |
+
def get_cos_sin(x0, y0, x1, y1):
|
| 424 |
+
dx, dy = x1 - x0, y1 - y0
|
| 425 |
+
d = (dx * dx + dy * dy) ** .5
|
| 426 |
+
# Account for divide by zero
|
| 427 |
+
if d == 0:
|
| 428 |
+
return 0.0, 0.0
|
| 429 |
+
return dx / d, dy / d
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def check_if_parallel(dx1, dy1, dx2, dy2, tolerance=1.e-5):
|
| 433 |
+
"""
|
| 434 |
+
Check if two lines are parallel.
|
| 435 |
+
|
| 436 |
+
Parameters
|
| 437 |
+
----------
|
| 438 |
+
dx1, dy1, dx2, dy2 : float
|
| 439 |
+
The gradients *dy*/*dx* of the two lines.
|
| 440 |
+
tolerance : float
|
| 441 |
+
The angular tolerance in radians up to which the lines are considered
|
| 442 |
+
parallel.
|
| 443 |
+
|
| 444 |
+
Returns
|
| 445 |
+
-------
|
| 446 |
+
is_parallel
|
| 447 |
+
- 1 if two lines are parallel in same direction.
|
| 448 |
+
- -1 if two lines are parallel in opposite direction.
|
| 449 |
+
- False otherwise.
|
| 450 |
+
"""
|
| 451 |
+
theta1 = np.arctan2(dx1, dy1)
|
| 452 |
+
theta2 = np.arctan2(dx2, dy2)
|
| 453 |
+
dtheta = abs(theta1 - theta2)
|
| 454 |
+
if dtheta < tolerance:
|
| 455 |
+
return 1
|
| 456 |
+
elif abs(dtheta - np.pi) < tolerance:
|
| 457 |
+
return -1
|
| 458 |
+
else:
|
| 459 |
+
return False
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def get_parallels(bezier2, width):
|
| 463 |
+
"""
|
| 464 |
+
Given the quadratic Bézier control points *bezier2*, returns
|
| 465 |
+
control points of quadratic Bézier lines roughly parallel to given
|
| 466 |
+
one separated by *width*.
|
| 467 |
+
"""
|
| 468 |
+
|
| 469 |
+
# The parallel Bezier lines are constructed by following ways.
|
| 470 |
+
# c1 and c2 are control points representing the start and end of the
|
| 471 |
+
# Bezier line.
|
| 472 |
+
# cm is the middle point
|
| 473 |
+
|
| 474 |
+
c1x, c1y = bezier2[0]
|
| 475 |
+
cmx, cmy = bezier2[1]
|
| 476 |
+
c2x, c2y = bezier2[2]
|
| 477 |
+
|
| 478 |
+
parallel_test = check_if_parallel(c1x - cmx, c1y - cmy,
|
| 479 |
+
cmx - c2x, cmy - c2y)
|
| 480 |
+
|
| 481 |
+
if parallel_test == -1:
|
| 482 |
+
_api.warn_external(
|
| 483 |
+
"Lines do not intersect. A straight line is used instead.")
|
| 484 |
+
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y)
|
| 485 |
+
cos_t2, sin_t2 = cos_t1, sin_t1
|
| 486 |
+
else:
|
| 487 |
+
# t1 and t2 is the angle between c1 and cm, cm, c2. They are
|
| 488 |
+
# also an angle of the tangential line of the path at c1 and c2
|
| 489 |
+
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
|
| 490 |
+
cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y)
|
| 491 |
+
|
| 492 |
+
# find c1_left, c1_right which are located along the lines
|
| 493 |
+
# through c1 and perpendicular to the tangential lines of the
|
| 494 |
+
# Bezier path at a distance of width. Same thing for c2_left and
|
| 495 |
+
# c2_right with respect to c2.
|
| 496 |
+
c1x_left, c1y_left, c1x_right, c1y_right = (
|
| 497 |
+
get_normal_points(c1x, c1y, cos_t1, sin_t1, width)
|
| 498 |
+
)
|
| 499 |
+
c2x_left, c2y_left, c2x_right, c2y_right = (
|
| 500 |
+
get_normal_points(c2x, c2y, cos_t2, sin_t2, width)
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
# find cm_left which is the intersecting point of a line through
|
| 504 |
+
# c1_left with angle t1 and a line through c2_left with angle
|
| 505 |
+
# t2. Same with cm_right.
|
| 506 |
+
try:
|
| 507 |
+
cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1,
|
| 508 |
+
sin_t1, c2x_left, c2y_left,
|
| 509 |
+
cos_t2, sin_t2)
|
| 510 |
+
cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1,
|
| 511 |
+
sin_t1, c2x_right, c2y_right,
|
| 512 |
+
cos_t2, sin_t2)
|
| 513 |
+
except ValueError:
|
| 514 |
+
# Special case straight lines, i.e., angle between two lines is
|
| 515 |
+
# less than the threshold used by get_intersection (we don't use
|
| 516 |
+
# check_if_parallel as the threshold is not the same).
|
| 517 |
+
cmx_left, cmy_left = (
|
| 518 |
+
0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left)
|
| 519 |
+
)
|
| 520 |
+
cmx_right, cmy_right = (
|
| 521 |
+
0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right)
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
# the parallel Bezier lines are created with control points of
|
| 525 |
+
# [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right]
|
| 526 |
+
path_left = [(c1x_left, c1y_left),
|
| 527 |
+
(cmx_left, cmy_left),
|
| 528 |
+
(c2x_left, c2y_left)]
|
| 529 |
+
path_right = [(c1x_right, c1y_right),
|
| 530 |
+
(cmx_right, cmy_right),
|
| 531 |
+
(c2x_right, c2y_right)]
|
| 532 |
+
|
| 533 |
+
return path_left, path_right
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y):
|
| 537 |
+
"""
|
| 538 |
+
Find control points of the Bézier curve passing through (*c1x*, *c1y*),
|
| 539 |
+
(*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1.
|
| 540 |
+
"""
|
| 541 |
+
cmx = .5 * (4 * mmx - (c1x + c2x))
|
| 542 |
+
cmy = .5 * (4 * mmy - (c1y + c2y))
|
| 543 |
+
return [(c1x, c1y), (cmx, cmy), (c2x, c2y)]
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.):
|
| 547 |
+
"""
|
| 548 |
+
Being similar to `get_parallels`, returns control points of two quadratic
|
| 549 |
+
Bézier lines having a width roughly parallel to given one separated by
|
| 550 |
+
*width*.
|
| 551 |
+
"""
|
| 552 |
+
|
| 553 |
+
# c1, cm, c2
|
| 554 |
+
c1x, c1y = bezier2[0]
|
| 555 |
+
cmx, cmy = bezier2[1]
|
| 556 |
+
c3x, c3y = bezier2[2]
|
| 557 |
+
|
| 558 |
+
# t1 and t2 is the angle between c1 and cm, cm, c3.
|
| 559 |
+
# They are also an angle of the tangential line of the path at c1 and c3
|
| 560 |
+
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
|
| 561 |
+
cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c3x, c3y)
|
| 562 |
+
|
| 563 |
+
# find c1_left, c1_right which are located along the lines
|
| 564 |
+
# through c1 and perpendicular to the tangential lines of the
|
| 565 |
+
# Bezier path at a distance of width. Same thing for c3_left and
|
| 566 |
+
# c3_right with respect to c3.
|
| 567 |
+
c1x_left, c1y_left, c1x_right, c1y_right = (
|
| 568 |
+
get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1)
|
| 569 |
+
)
|
| 570 |
+
c3x_left, c3y_left, c3x_right, c3y_right = (
|
| 571 |
+
get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2)
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
# find c12, c23 and c123 which are middle points of c1-cm, cm-c3 and
|
| 575 |
+
# c12-c23
|
| 576 |
+
c12x, c12y = (c1x + cmx) * .5, (c1y + cmy) * .5
|
| 577 |
+
c23x, c23y = (cmx + c3x) * .5, (cmy + c3y) * .5
|
| 578 |
+
c123x, c123y = (c12x + c23x) * .5, (c12y + c23y) * .5
|
| 579 |
+
|
| 580 |
+
# tangential angle of c123 (angle between c12 and c23)
|
| 581 |
+
cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y)
|
| 582 |
+
|
| 583 |
+
c123x_left, c123y_left, c123x_right, c123y_right = (
|
| 584 |
+
get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm)
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
path_left = find_control_points(c1x_left, c1y_left,
|
| 588 |
+
c123x_left, c123y_left,
|
| 589 |
+
c3x_left, c3y_left)
|
| 590 |
+
path_right = find_control_points(c1x_right, c1y_right,
|
| 591 |
+
c123x_right, c123y_right,
|
| 592 |
+
c3x_right, c3y_right)
|
| 593 |
+
|
| 594 |
+
return path_left, path_right
|
omnilmm/lib/python3.10/site-packages/matplotlib/collections.py
ADDED
|
@@ -0,0 +1,2113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Classes for the efficient drawing of large collections of objects that
|
| 3 |
+
share most properties, e.g., a large number of line segments or
|
| 4 |
+
polygons.
|
| 5 |
+
|
| 6 |
+
The classes are not meant to be as flexible as their single element
|
| 7 |
+
counterparts (e.g., you may not be able to select all line styles) but
|
| 8 |
+
they are meant to be fast for common use cases (e.g., a large set of solid
|
| 9 |
+
line segments).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import math
|
| 13 |
+
from numbers import Number
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
import matplotlib as mpl
|
| 19 |
+
from . import (_api, _path, artist, cbook, cm, colors as mcolors, _docstring,
|
| 20 |
+
hatch as mhatch, lines as mlines, path as mpath, transforms)
|
| 21 |
+
from ._enums import JoinStyle, CapStyle
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# "color" is excluded; it is a compound setter, and its docstring differs
|
| 25 |
+
# in LineCollection.
|
| 26 |
+
@_api.define_aliases({
|
| 27 |
+
"antialiased": ["antialiaseds", "aa"],
|
| 28 |
+
"edgecolor": ["edgecolors", "ec"],
|
| 29 |
+
"facecolor": ["facecolors", "fc"],
|
| 30 |
+
"linestyle": ["linestyles", "dashes", "ls"],
|
| 31 |
+
"linewidth": ["linewidths", "lw"],
|
| 32 |
+
"offset_transform": ["transOffset"],
|
| 33 |
+
})
|
| 34 |
+
class Collection(artist.Artist, cm.ScalarMappable):
|
| 35 |
+
r"""
|
| 36 |
+
Base class for Collections. Must be subclassed to be usable.
|
| 37 |
+
|
| 38 |
+
A Collection represents a sequence of `.Patch`\es that can be drawn
|
| 39 |
+
more efficiently together than individually. For example, when a single
|
| 40 |
+
path is being drawn repeatedly at different offsets, the renderer can
|
| 41 |
+
typically execute a ``draw_marker()`` call much more efficiently than a
|
| 42 |
+
series of repeated calls to ``draw_path()`` with the offsets put in
|
| 43 |
+
one-by-one.
|
| 44 |
+
|
| 45 |
+
Most properties of a collection can be configured per-element. Therefore,
|
| 46 |
+
Collections have "plural" versions of many of the properties of a `.Patch`
|
| 47 |
+
(e.g. `.Collection.get_paths` instead of `.Patch.get_path`). Exceptions are
|
| 48 |
+
the *zorder*, *hatch*, *pickradius*, *capstyle* and *joinstyle* properties,
|
| 49 |
+
which can only be set globally for the whole collection.
|
| 50 |
+
|
| 51 |
+
Besides these exceptions, all properties can be specified as single values
|
| 52 |
+
(applying to all elements) or sequences of values. The property of the
|
| 53 |
+
``i``\th element of the collection is::
|
| 54 |
+
|
| 55 |
+
prop[i % len(prop)]
|
| 56 |
+
|
| 57 |
+
Each Collection can optionally be used as its own `.ScalarMappable` by
|
| 58 |
+
passing the *norm* and *cmap* parameters to its constructor. If the
|
| 59 |
+
Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call
|
| 60 |
+
to `.Collection.set_array`), then at draw time this internal scalar
|
| 61 |
+
mappable will be used to set the ``facecolors`` and ``edgecolors``,
|
| 62 |
+
ignoring those that were manually passed in.
|
| 63 |
+
"""
|
| 64 |
+
#: Either a list of 3x3 arrays or an Nx3x3 array (representing N
|
| 65 |
+
#: transforms), suitable for the `all_transforms` argument to
|
| 66 |
+
#: `~matplotlib.backend_bases.RendererBase.draw_path_collection`;
|
| 67 |
+
#: each 3x3 array is used to initialize an
|
| 68 |
+
#: `~matplotlib.transforms.Affine2D` object.
|
| 69 |
+
#: Each kind of collection defines this based on its arguments.
|
| 70 |
+
_transforms = np.empty((0, 3, 3))
|
| 71 |
+
|
| 72 |
+
# Whether to draw an edge by default. Set on a
|
| 73 |
+
# subclass-by-subclass basis.
|
| 74 |
+
_edge_default = False
|
| 75 |
+
|
| 76 |
+
@_docstring.interpd
|
| 77 |
+
@_api.make_keyword_only("3.6", name="edgecolors")
|
| 78 |
+
def __init__(self,
|
| 79 |
+
edgecolors=None,
|
| 80 |
+
facecolors=None,
|
| 81 |
+
linewidths=None,
|
| 82 |
+
linestyles='solid',
|
| 83 |
+
capstyle=None,
|
| 84 |
+
joinstyle=None,
|
| 85 |
+
antialiaseds=None,
|
| 86 |
+
offsets=None,
|
| 87 |
+
offset_transform=None,
|
| 88 |
+
norm=None, # optional for ScalarMappable
|
| 89 |
+
cmap=None, # ditto
|
| 90 |
+
pickradius=5.0,
|
| 91 |
+
hatch=None,
|
| 92 |
+
urls=None,
|
| 93 |
+
*,
|
| 94 |
+
zorder=1,
|
| 95 |
+
**kwargs
|
| 96 |
+
):
|
| 97 |
+
"""
|
| 98 |
+
Parameters
|
| 99 |
+
----------
|
| 100 |
+
edgecolors : color or list of colors, default: :rc:`patch.edgecolor`
|
| 101 |
+
Edge color for each patch making up the collection. The special
|
| 102 |
+
value 'face' can be passed to make the edgecolor match the
|
| 103 |
+
facecolor.
|
| 104 |
+
facecolors : color or list of colors, default: :rc:`patch.facecolor`
|
| 105 |
+
Face color for each patch making up the collection.
|
| 106 |
+
linewidths : float or list of floats, default: :rc:`patch.linewidth`
|
| 107 |
+
Line width for each patch making up the collection.
|
| 108 |
+
linestyles : str or tuple or list thereof, default: 'solid'
|
| 109 |
+
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-',
|
| 110 |
+
'--', '-.', ':']. Dash tuples should be of the form::
|
| 111 |
+
|
| 112 |
+
(offset, onoffseq),
|
| 113 |
+
|
| 114 |
+
where *onoffseq* is an even length tuple of on and off ink lengths
|
| 115 |
+
in points. For examples, see
|
| 116 |
+
:doc:`/gallery/lines_bars_and_markers/linestyles`.
|
| 117 |
+
capstyle : `.CapStyle`-like, default: :rc:`patch.capstyle`
|
| 118 |
+
Style to use for capping lines for all paths in the collection.
|
| 119 |
+
Allowed values are %(CapStyle)s.
|
| 120 |
+
joinstyle : `.JoinStyle`-like, default: :rc:`patch.joinstyle`
|
| 121 |
+
Style to use for joining lines for all paths in the collection.
|
| 122 |
+
Allowed values are %(JoinStyle)s.
|
| 123 |
+
antialiaseds : bool or list of bool, default: :rc:`patch.antialiased`
|
| 124 |
+
Whether each patch in the collection should be drawn with
|
| 125 |
+
antialiasing.
|
| 126 |
+
offsets : (float, float) or list thereof, default: (0, 0)
|
| 127 |
+
A vector by which to translate each patch after rendering (default
|
| 128 |
+
is no translation). The translation is performed in screen (pixel)
|
| 129 |
+
coordinates (i.e. after the Artist's transform is applied).
|
| 130 |
+
offset_transform : `~.Transform`, default: `.IdentityTransform`
|
| 131 |
+
A single transform which will be applied to each *offsets* vector
|
| 132 |
+
before it is used.
|
| 133 |
+
cmap, norm
|
| 134 |
+
Data normalization and colormapping parameters. See
|
| 135 |
+
`.ScalarMappable` for a detailed description.
|
| 136 |
+
hatch : str, optional
|
| 137 |
+
Hatching pattern to use in filled paths, if any. Valid strings are
|
| 138 |
+
['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See
|
| 139 |
+
:doc:`/gallery/shapes_and_collections/hatch_style_reference` for
|
| 140 |
+
the meaning of each hatch type.
|
| 141 |
+
pickradius : float, default: 5.0
|
| 142 |
+
If ``pickradius <= 0``, then `.Collection.contains` will return
|
| 143 |
+
``True`` whenever the test point is inside of one of the polygons
|
| 144 |
+
formed by the control points of a Path in the Collection. On the
|
| 145 |
+
other hand, if it is greater than 0, then we instead check if the
|
| 146 |
+
test point is contained in a stroke of width ``2*pickradius``
|
| 147 |
+
following any of the Paths in the Collection.
|
| 148 |
+
urls : list of str, default: None
|
| 149 |
+
A URL for each patch to link to once drawn. Currently only works
|
| 150 |
+
for the SVG backend. See :doc:`/gallery/misc/hyperlinks_sgskip` for
|
| 151 |
+
examples.
|
| 152 |
+
zorder : float, default: 1
|
| 153 |
+
The drawing order, shared by all Patches in the Collection. See
|
| 154 |
+
:doc:`/gallery/misc/zorder_demo` for all defaults and examples.
|
| 155 |
+
"""
|
| 156 |
+
artist.Artist.__init__(self)
|
| 157 |
+
cm.ScalarMappable.__init__(self, norm, cmap)
|
| 158 |
+
# list of un-scaled dash patterns
|
| 159 |
+
# this is needed scaling the dash pattern by linewidth
|
| 160 |
+
self._us_linestyles = [(0, None)]
|
| 161 |
+
# list of dash patterns
|
| 162 |
+
self._linestyles = [(0, None)]
|
| 163 |
+
# list of unbroadcast/scaled linewidths
|
| 164 |
+
self._us_lw = [0]
|
| 165 |
+
self._linewidths = [0]
|
| 166 |
+
# Flags set by _set_mappable_flags: are colors from mapping an array?
|
| 167 |
+
self._face_is_mapped = None
|
| 168 |
+
self._edge_is_mapped = None
|
| 169 |
+
self._mapped_colors = None # calculated in update_scalarmappable
|
| 170 |
+
self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
|
| 171 |
+
self.set_facecolor(facecolors)
|
| 172 |
+
self.set_edgecolor(edgecolors)
|
| 173 |
+
self.set_linewidth(linewidths)
|
| 174 |
+
self.set_linestyle(linestyles)
|
| 175 |
+
self.set_antialiased(antialiaseds)
|
| 176 |
+
self.set_pickradius(pickradius)
|
| 177 |
+
self.set_urls(urls)
|
| 178 |
+
self.set_hatch(hatch)
|
| 179 |
+
self.set_zorder(zorder)
|
| 180 |
+
|
| 181 |
+
if capstyle:
|
| 182 |
+
self.set_capstyle(capstyle)
|
| 183 |
+
else:
|
| 184 |
+
self._capstyle = None
|
| 185 |
+
|
| 186 |
+
if joinstyle:
|
| 187 |
+
self.set_joinstyle(joinstyle)
|
| 188 |
+
else:
|
| 189 |
+
self._joinstyle = None
|
| 190 |
+
|
| 191 |
+
if offsets is not None:
|
| 192 |
+
offsets = np.asanyarray(offsets, float)
|
| 193 |
+
# Broadcast (2,) -> (1, 2) but nothing else.
|
| 194 |
+
if offsets.shape == (2,):
|
| 195 |
+
offsets = offsets[None, :]
|
| 196 |
+
|
| 197 |
+
self._offsets = offsets
|
| 198 |
+
self._offset_transform = offset_transform
|
| 199 |
+
|
| 200 |
+
self._path_effects = None
|
| 201 |
+
self._internal_update(kwargs)
|
| 202 |
+
self._paths = None
|
| 203 |
+
|
| 204 |
+
def get_paths(self):
|
| 205 |
+
return self._paths
|
| 206 |
+
|
| 207 |
+
def set_paths(self, paths):
|
| 208 |
+
raise NotImplementedError
|
| 209 |
+
|
| 210 |
+
def get_transforms(self):
|
| 211 |
+
return self._transforms
|
| 212 |
+
|
| 213 |
+
def get_offset_transform(self):
|
| 214 |
+
"""Return the `.Transform` instance used by this artist offset."""
|
| 215 |
+
if self._offset_transform is None:
|
| 216 |
+
self._offset_transform = transforms.IdentityTransform()
|
| 217 |
+
elif (not isinstance(self._offset_transform, transforms.Transform)
|
| 218 |
+
and hasattr(self._offset_transform, '_as_mpl_transform')):
|
| 219 |
+
self._offset_transform = \
|
| 220 |
+
self._offset_transform._as_mpl_transform(self.axes)
|
| 221 |
+
return self._offset_transform
|
| 222 |
+
|
| 223 |
+
@_api.rename_parameter("3.6", "transOffset", "offset_transform")
|
| 224 |
+
def set_offset_transform(self, offset_transform):
|
| 225 |
+
"""
|
| 226 |
+
Set the artist offset transform.
|
| 227 |
+
|
| 228 |
+
Parameters
|
| 229 |
+
----------
|
| 230 |
+
offset_transform : `.Transform`
|
| 231 |
+
"""
|
| 232 |
+
self._offset_transform = offset_transform
|
| 233 |
+
|
| 234 |
+
def get_datalim(self, transData):
|
| 235 |
+
# Calculate the data limits and return them as a `.Bbox`.
|
| 236 |
+
#
|
| 237 |
+
# This operation depends on the transforms for the data in the
|
| 238 |
+
# collection and whether the collection has offsets:
|
| 239 |
+
#
|
| 240 |
+
# 1. offsets = None, transform child of transData: use the paths for
|
| 241 |
+
# the automatic limits (i.e. for LineCollection in streamline).
|
| 242 |
+
# 2. offsets != None: offset_transform is child of transData:
|
| 243 |
+
#
|
| 244 |
+
# a. transform is child of transData: use the path + offset for
|
| 245 |
+
# limits (i.e for bar).
|
| 246 |
+
# b. transform is not a child of transData: just use the offsets
|
| 247 |
+
# for the limits (i.e. for scatter)
|
| 248 |
+
#
|
| 249 |
+
# 3. otherwise return a null Bbox.
|
| 250 |
+
|
| 251 |
+
transform = self.get_transform()
|
| 252 |
+
offset_trf = self.get_offset_transform()
|
| 253 |
+
if not (isinstance(offset_trf, transforms.IdentityTransform)
|
| 254 |
+
or offset_trf.contains_branch(transData)):
|
| 255 |
+
# if the offsets are in some coords other than data,
|
| 256 |
+
# then don't use them for autoscaling.
|
| 257 |
+
return transforms.Bbox.null()
|
| 258 |
+
offsets = self.get_offsets()
|
| 259 |
+
|
| 260 |
+
paths = self.get_paths()
|
| 261 |
+
if not len(paths):
|
| 262 |
+
# No paths to transform
|
| 263 |
+
return transforms.Bbox.null()
|
| 264 |
+
|
| 265 |
+
if not transform.is_affine:
|
| 266 |
+
paths = [transform.transform_path_non_affine(p) for p in paths]
|
| 267 |
+
# Don't convert transform to transform.get_affine() here because
|
| 268 |
+
# we may have transform.contains_branch(transData) but not
|
| 269 |
+
# transforms.get_affine().contains_branch(transData). But later,
|
| 270 |
+
# be careful to only apply the affine part that remains.
|
| 271 |
+
|
| 272 |
+
if any(transform.contains_branch_seperately(transData)):
|
| 273 |
+
# collections that are just in data units (like quiver)
|
| 274 |
+
# can properly have the axes limits set by their shape +
|
| 275 |
+
# offset. LineCollections that have no offsets can
|
| 276 |
+
# also use this algorithm (like streamplot).
|
| 277 |
+
if isinstance(offsets, np.ma.MaskedArray):
|
| 278 |
+
offsets = offsets.filled(np.nan)
|
| 279 |
+
# get_path_collection_extents handles nan but not masked arrays
|
| 280 |
+
return mpath.get_path_collection_extents(
|
| 281 |
+
transform.get_affine() - transData, paths,
|
| 282 |
+
self.get_transforms(),
|
| 283 |
+
offset_trf.transform_non_affine(offsets),
|
| 284 |
+
offset_trf.get_affine().frozen())
|
| 285 |
+
|
| 286 |
+
# NOTE: None is the default case where no offsets were passed in
|
| 287 |
+
if self._offsets is not None:
|
| 288 |
+
# this is for collections that have their paths (shapes)
|
| 289 |
+
# in physical, axes-relative, or figure-relative units
|
| 290 |
+
# (i.e. like scatter). We can't uniquely set limits based on
|
| 291 |
+
# those shapes, so we just set the limits based on their
|
| 292 |
+
# location.
|
| 293 |
+
offsets = (offset_trf - transData).transform(offsets)
|
| 294 |
+
# note A-B means A B^{-1}
|
| 295 |
+
offsets = np.ma.masked_invalid(offsets)
|
| 296 |
+
if not offsets.mask.all():
|
| 297 |
+
bbox = transforms.Bbox.null()
|
| 298 |
+
bbox.update_from_data_xy(offsets)
|
| 299 |
+
return bbox
|
| 300 |
+
return transforms.Bbox.null()
|
| 301 |
+
|
| 302 |
+
def get_window_extent(self, renderer=None):
|
| 303 |
+
# TODO: check to ensure that this does not fail for
|
| 304 |
+
# cases other than scatter plot legend
|
| 305 |
+
return self.get_datalim(transforms.IdentityTransform())
|
| 306 |
+
|
| 307 |
+
def _prepare_points(self):
|
| 308 |
+
# Helper for drawing and hit testing.
|
| 309 |
+
|
| 310 |
+
transform = self.get_transform()
|
| 311 |
+
offset_trf = self.get_offset_transform()
|
| 312 |
+
offsets = self.get_offsets()
|
| 313 |
+
paths = self.get_paths()
|
| 314 |
+
|
| 315 |
+
if self.have_units():
|
| 316 |
+
paths = []
|
| 317 |
+
for path in self.get_paths():
|
| 318 |
+
vertices = path.vertices
|
| 319 |
+
xs, ys = vertices[:, 0], vertices[:, 1]
|
| 320 |
+
xs = self.convert_xunits(xs)
|
| 321 |
+
ys = self.convert_yunits(ys)
|
| 322 |
+
paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes))
|
| 323 |
+
xs = self.convert_xunits(offsets[:, 0])
|
| 324 |
+
ys = self.convert_yunits(offsets[:, 1])
|
| 325 |
+
offsets = np.ma.column_stack([xs, ys])
|
| 326 |
+
|
| 327 |
+
if not transform.is_affine:
|
| 328 |
+
paths = [transform.transform_path_non_affine(path)
|
| 329 |
+
for path in paths]
|
| 330 |
+
transform = transform.get_affine()
|
| 331 |
+
if not offset_trf.is_affine:
|
| 332 |
+
offsets = offset_trf.transform_non_affine(offsets)
|
| 333 |
+
# This might have changed an ndarray into a masked array.
|
| 334 |
+
offset_trf = offset_trf.get_affine()
|
| 335 |
+
|
| 336 |
+
if isinstance(offsets, np.ma.MaskedArray):
|
| 337 |
+
offsets = offsets.filled(np.nan)
|
| 338 |
+
# Changing from a masked array to nan-filled ndarray
|
| 339 |
+
# is probably most efficient at this point.
|
| 340 |
+
|
| 341 |
+
return transform, offset_trf, offsets, paths
|
| 342 |
+
|
| 343 |
+
@artist.allow_rasterization
|
| 344 |
+
def draw(self, renderer):
|
| 345 |
+
if not self.get_visible():
|
| 346 |
+
return
|
| 347 |
+
renderer.open_group(self.__class__.__name__, self.get_gid())
|
| 348 |
+
|
| 349 |
+
self.update_scalarmappable()
|
| 350 |
+
|
| 351 |
+
transform, offset_trf, offsets, paths = self._prepare_points()
|
| 352 |
+
|
| 353 |
+
gc = renderer.new_gc()
|
| 354 |
+
self._set_gc_clip(gc)
|
| 355 |
+
gc.set_snap(self.get_snap())
|
| 356 |
+
|
| 357 |
+
if self._hatch:
|
| 358 |
+
gc.set_hatch(self._hatch)
|
| 359 |
+
gc.set_hatch_color(self._hatch_color)
|
| 360 |
+
|
| 361 |
+
if self.get_sketch_params() is not None:
|
| 362 |
+
gc.set_sketch_params(*self.get_sketch_params())
|
| 363 |
+
|
| 364 |
+
if self.get_path_effects():
|
| 365 |
+
from matplotlib.patheffects import PathEffectRenderer
|
| 366 |
+
renderer = PathEffectRenderer(self.get_path_effects(), renderer)
|
| 367 |
+
|
| 368 |
+
# If the collection is made up of a single shape/color/stroke,
|
| 369 |
+
# it can be rendered once and blitted multiple times, using
|
| 370 |
+
# `draw_markers` rather than `draw_path_collection`. This is
|
| 371 |
+
# *much* faster for Agg, and results in smaller file sizes in
|
| 372 |
+
# PDF/SVG/PS.
|
| 373 |
+
|
| 374 |
+
trans = self.get_transforms()
|
| 375 |
+
facecolors = self.get_facecolor()
|
| 376 |
+
edgecolors = self.get_edgecolor()
|
| 377 |
+
do_single_path_optimization = False
|
| 378 |
+
if (len(paths) == 1 and len(trans) <= 1 and
|
| 379 |
+
len(facecolors) == 1 and len(edgecolors) == 1 and
|
| 380 |
+
len(self._linewidths) == 1 and
|
| 381 |
+
all(ls[1] is None for ls in self._linestyles) and
|
| 382 |
+
len(self._antialiaseds) == 1 and len(self._urls) == 1 and
|
| 383 |
+
self.get_hatch() is None):
|
| 384 |
+
if len(trans):
|
| 385 |
+
combined_transform = transforms.Affine2D(trans[0]) + transform
|
| 386 |
+
else:
|
| 387 |
+
combined_transform = transform
|
| 388 |
+
extents = paths[0].get_extents(combined_transform)
|
| 389 |
+
if (extents.width < self.figure.bbox.width
|
| 390 |
+
and extents.height < self.figure.bbox.height):
|
| 391 |
+
do_single_path_optimization = True
|
| 392 |
+
|
| 393 |
+
if self._joinstyle:
|
| 394 |
+
gc.set_joinstyle(self._joinstyle)
|
| 395 |
+
|
| 396 |
+
if self._capstyle:
|
| 397 |
+
gc.set_capstyle(self._capstyle)
|
| 398 |
+
|
| 399 |
+
if do_single_path_optimization:
|
| 400 |
+
gc.set_foreground(tuple(edgecolors[0]))
|
| 401 |
+
gc.set_linewidth(self._linewidths[0])
|
| 402 |
+
gc.set_dashes(*self._linestyles[0])
|
| 403 |
+
gc.set_antialiased(self._antialiaseds[0])
|
| 404 |
+
gc.set_url(self._urls[0])
|
| 405 |
+
renderer.draw_markers(
|
| 406 |
+
gc, paths[0], combined_transform.frozen(),
|
| 407 |
+
mpath.Path(offsets), offset_trf, tuple(facecolors[0]))
|
| 408 |
+
else:
|
| 409 |
+
renderer.draw_path_collection(
|
| 410 |
+
gc, transform.frozen(), paths,
|
| 411 |
+
self.get_transforms(), offsets, offset_trf,
|
| 412 |
+
self.get_facecolor(), self.get_edgecolor(),
|
| 413 |
+
self._linewidths, self._linestyles,
|
| 414 |
+
self._antialiaseds, self._urls,
|
| 415 |
+
"screen") # offset_position, kept for backcompat.
|
| 416 |
+
|
| 417 |
+
gc.restore()
|
| 418 |
+
renderer.close_group(self.__class__.__name__)
|
| 419 |
+
self.stale = False
|
| 420 |
+
|
| 421 |
+
@_api.rename_parameter("3.6", "pr", "pickradius")
|
| 422 |
+
def set_pickradius(self, pickradius):
|
| 423 |
+
"""
|
| 424 |
+
Set the pick radius used for containment tests.
|
| 425 |
+
|
| 426 |
+
Parameters
|
| 427 |
+
----------
|
| 428 |
+
pickradius : float
|
| 429 |
+
Pick radius, in points.
|
| 430 |
+
"""
|
| 431 |
+
self._pickradius = pickradius
|
| 432 |
+
|
| 433 |
+
def get_pickradius(self):
|
| 434 |
+
return self._pickradius
|
| 435 |
+
|
| 436 |
+
def contains(self, mouseevent):
|
| 437 |
+
"""
|
| 438 |
+
Test whether the mouse event occurred in the collection.
|
| 439 |
+
|
| 440 |
+
Returns ``bool, dict(ind=itemlist)``, where every item in itemlist
|
| 441 |
+
contains the event.
|
| 442 |
+
"""
|
| 443 |
+
inside, info = self._default_contains(mouseevent)
|
| 444 |
+
if inside is not None:
|
| 445 |
+
return inside, info
|
| 446 |
+
|
| 447 |
+
if not self.get_visible():
|
| 448 |
+
return False, {}
|
| 449 |
+
|
| 450 |
+
pickradius = (
|
| 451 |
+
float(self._picker)
|
| 452 |
+
if isinstance(self._picker, Number) and
|
| 453 |
+
self._picker is not True # the bool, not just nonzero or 1
|
| 454 |
+
else self._pickradius)
|
| 455 |
+
|
| 456 |
+
if self.axes:
|
| 457 |
+
self.axes._unstale_viewLim()
|
| 458 |
+
|
| 459 |
+
transform, offset_trf, offsets, paths = self._prepare_points()
|
| 460 |
+
|
| 461 |
+
# Tests if the point is contained on one of the polygons formed
|
| 462 |
+
# by the control points of each of the paths. A point is considered
|
| 463 |
+
# "on" a path if it would lie within a stroke of width 2*pickradius
|
| 464 |
+
# following the path. If pickradius <= 0, then we instead simply check
|
| 465 |
+
# if the point is *inside* of the path instead.
|
| 466 |
+
ind = _path.point_in_path_collection(
|
| 467 |
+
mouseevent.x, mouseevent.y, pickradius,
|
| 468 |
+
transform.frozen(), paths, self.get_transforms(),
|
| 469 |
+
offsets, offset_trf, pickradius <= 0)
|
| 470 |
+
|
| 471 |
+
return len(ind) > 0, dict(ind=ind)
|
| 472 |
+
|
| 473 |
+
def set_urls(self, urls):
|
| 474 |
+
"""
|
| 475 |
+
Parameters
|
| 476 |
+
----------
|
| 477 |
+
urls : list of str or None
|
| 478 |
+
|
| 479 |
+
Notes
|
| 480 |
+
-----
|
| 481 |
+
URLs are currently only implemented by the SVG backend. They are
|
| 482 |
+
ignored by all other backends.
|
| 483 |
+
"""
|
| 484 |
+
self._urls = urls if urls is not None else [None]
|
| 485 |
+
self.stale = True
|
| 486 |
+
|
| 487 |
+
def get_urls(self):
|
| 488 |
+
"""
|
| 489 |
+
Return a list of URLs, one for each element of the collection.
|
| 490 |
+
|
| 491 |
+
The list contains *None* for elements without a URL. See
|
| 492 |
+
:doc:`/gallery/misc/hyperlinks_sgskip` for an example.
|
| 493 |
+
"""
|
| 494 |
+
return self._urls
|
| 495 |
+
|
| 496 |
+
def set_hatch(self, hatch):
|
| 497 |
+
r"""
|
| 498 |
+
Set the hatching pattern
|
| 499 |
+
|
| 500 |
+
*hatch* can be one of::
|
| 501 |
+
|
| 502 |
+
/ - diagonal hatching
|
| 503 |
+
\ - back diagonal
|
| 504 |
+
| - vertical
|
| 505 |
+
- - horizontal
|
| 506 |
+
+ - crossed
|
| 507 |
+
x - crossed diagonal
|
| 508 |
+
o - small circle
|
| 509 |
+
O - large circle
|
| 510 |
+
. - dots
|
| 511 |
+
* - stars
|
| 512 |
+
|
| 513 |
+
Letters can be combined, in which case all the specified
|
| 514 |
+
hatchings are done. If same letter repeats, it increases the
|
| 515 |
+
density of hatching of that pattern.
|
| 516 |
+
|
| 517 |
+
Hatching is supported in the PostScript, PDF, SVG and Agg
|
| 518 |
+
backends only.
|
| 519 |
+
|
| 520 |
+
Unlike other properties such as linewidth and colors, hatching
|
| 521 |
+
can only be specified for the collection as a whole, not separately
|
| 522 |
+
for each member.
|
| 523 |
+
|
| 524 |
+
Parameters
|
| 525 |
+
----------
|
| 526 |
+
hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
|
| 527 |
+
"""
|
| 528 |
+
# Use validate_hatch(list) after deprecation.
|
| 529 |
+
mhatch._validate_hatch_pattern(hatch)
|
| 530 |
+
self._hatch = hatch
|
| 531 |
+
self.stale = True
|
| 532 |
+
|
| 533 |
+
def get_hatch(self):
|
| 534 |
+
"""Return the current hatching pattern."""
|
| 535 |
+
return self._hatch
|
| 536 |
+
|
| 537 |
+
def set_offsets(self, offsets):
|
| 538 |
+
"""
|
| 539 |
+
Set the offsets for the collection.
|
| 540 |
+
|
| 541 |
+
Parameters
|
| 542 |
+
----------
|
| 543 |
+
offsets : (N, 2) or (2,) array-like
|
| 544 |
+
"""
|
| 545 |
+
offsets = np.asanyarray(offsets)
|
| 546 |
+
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
|
| 547 |
+
offsets = offsets[None, :]
|
| 548 |
+
cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray)
|
| 549 |
+
else np.column_stack)
|
| 550 |
+
self._offsets = cstack(
|
| 551 |
+
(np.asanyarray(self.convert_xunits(offsets[:, 0]), float),
|
| 552 |
+
np.asanyarray(self.convert_yunits(offsets[:, 1]), float)))
|
| 553 |
+
self.stale = True
|
| 554 |
+
|
| 555 |
+
def get_offsets(self):
|
| 556 |
+
"""Return the offsets for the collection."""
|
| 557 |
+
# Default to zeros in the no-offset (None) case
|
| 558 |
+
return np.zeros((1, 2)) if self._offsets is None else self._offsets
|
| 559 |
+
|
| 560 |
+
def _get_default_linewidth(self):
|
| 561 |
+
# This may be overridden in a subclass.
|
| 562 |
+
return mpl.rcParams['patch.linewidth'] # validated as float
|
| 563 |
+
|
| 564 |
+
def set_linewidth(self, lw):
|
| 565 |
+
"""
|
| 566 |
+
Set the linewidth(s) for the collection. *lw* can be a scalar
|
| 567 |
+
or a sequence; if it is a sequence the patches will cycle
|
| 568 |
+
through the sequence
|
| 569 |
+
|
| 570 |
+
Parameters
|
| 571 |
+
----------
|
| 572 |
+
lw : float or list of floats
|
| 573 |
+
"""
|
| 574 |
+
if lw is None:
|
| 575 |
+
lw = self._get_default_linewidth()
|
| 576 |
+
# get the un-scaled/broadcast lw
|
| 577 |
+
self._us_lw = np.atleast_1d(lw)
|
| 578 |
+
|
| 579 |
+
# scale all of the dash patterns.
|
| 580 |
+
self._linewidths, self._linestyles = self._bcast_lwls(
|
| 581 |
+
self._us_lw, self._us_linestyles)
|
| 582 |
+
self.stale = True
|
| 583 |
+
|
| 584 |
+
def set_linestyle(self, ls):
|
| 585 |
+
"""
|
| 586 |
+
Set the linestyle(s) for the collection.
|
| 587 |
+
|
| 588 |
+
=========================== =================
|
| 589 |
+
linestyle description
|
| 590 |
+
=========================== =================
|
| 591 |
+
``'-'`` or ``'solid'`` solid line
|
| 592 |
+
``'--'`` or ``'dashed'`` dashed line
|
| 593 |
+
``'-.'`` or ``'dashdot'`` dash-dotted line
|
| 594 |
+
``':'`` or ``'dotted'`` dotted line
|
| 595 |
+
=========================== =================
|
| 596 |
+
|
| 597 |
+
Alternatively a dash tuple of the following form can be provided::
|
| 598 |
+
|
| 599 |
+
(offset, onoffseq),
|
| 600 |
+
|
| 601 |
+
where ``onoffseq`` is an even length tuple of on and off ink in points.
|
| 602 |
+
|
| 603 |
+
Parameters
|
| 604 |
+
----------
|
| 605 |
+
ls : str or tuple or list thereof
|
| 606 |
+
Valid values for individual linestyles include {'-', '--', '-.',
|
| 607 |
+
':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a
|
| 608 |
+
complete description.
|
| 609 |
+
"""
|
| 610 |
+
try:
|
| 611 |
+
dashes = [mlines._get_dash_pattern(ls)]
|
| 612 |
+
except ValueError:
|
| 613 |
+
try:
|
| 614 |
+
dashes = [mlines._get_dash_pattern(x) for x in ls]
|
| 615 |
+
except ValueError as err:
|
| 616 |
+
emsg = f'Do not know how to convert {ls!r} to dashes'
|
| 617 |
+
raise ValueError(emsg) from err
|
| 618 |
+
|
| 619 |
+
# get the list of raw 'unscaled' dash patterns
|
| 620 |
+
self._us_linestyles = dashes
|
| 621 |
+
|
| 622 |
+
# broadcast and scale the lw and dash patterns
|
| 623 |
+
self._linewidths, self._linestyles = self._bcast_lwls(
|
| 624 |
+
self._us_lw, self._us_linestyles)
|
| 625 |
+
|
| 626 |
+
@_docstring.interpd
|
| 627 |
+
def set_capstyle(self, cs):
|
| 628 |
+
"""
|
| 629 |
+
Set the `.CapStyle` for the collection (for all its elements).
|
| 630 |
+
|
| 631 |
+
Parameters
|
| 632 |
+
----------
|
| 633 |
+
cs : `.CapStyle` or %(CapStyle)s
|
| 634 |
+
"""
|
| 635 |
+
self._capstyle = CapStyle(cs)
|
| 636 |
+
|
| 637 |
+
def get_capstyle(self):
|
| 638 |
+
return self._capstyle.name
|
| 639 |
+
|
| 640 |
+
@_docstring.interpd
|
| 641 |
+
def set_joinstyle(self, js):
|
| 642 |
+
"""
|
| 643 |
+
Set the `.JoinStyle` for the collection (for all its elements).
|
| 644 |
+
|
| 645 |
+
Parameters
|
| 646 |
+
----------
|
| 647 |
+
js : `.JoinStyle` or %(JoinStyle)s
|
| 648 |
+
"""
|
| 649 |
+
self._joinstyle = JoinStyle(js)
|
| 650 |
+
|
| 651 |
+
def get_joinstyle(self):
|
| 652 |
+
return self._joinstyle.name
|
| 653 |
+
|
| 654 |
+
@staticmethod
|
| 655 |
+
def _bcast_lwls(linewidths, dashes):
|
| 656 |
+
"""
|
| 657 |
+
Internal helper function to broadcast + scale ls/lw
|
| 658 |
+
|
| 659 |
+
In the collection drawing code, the linewidth and linestyle are cycled
|
| 660 |
+
through as circular buffers (via ``v[i % len(v)]``). Thus, if we are
|
| 661 |
+
going to scale the dash pattern at set time (not draw time) we need to
|
| 662 |
+
do the broadcasting now and expand both lists to be the same length.
|
| 663 |
+
|
| 664 |
+
Parameters
|
| 665 |
+
----------
|
| 666 |
+
linewidths : list
|
| 667 |
+
line widths of collection
|
| 668 |
+
dashes : list
|
| 669 |
+
dash specification (offset, (dash pattern tuple))
|
| 670 |
+
|
| 671 |
+
Returns
|
| 672 |
+
-------
|
| 673 |
+
linewidths, dashes : list
|
| 674 |
+
Will be the same length, dashes are scaled by paired linewidth
|
| 675 |
+
"""
|
| 676 |
+
if mpl.rcParams['_internal.classic_mode']:
|
| 677 |
+
return linewidths, dashes
|
| 678 |
+
# make sure they are the same length so we can zip them
|
| 679 |
+
if len(dashes) != len(linewidths):
|
| 680 |
+
l_dashes = len(dashes)
|
| 681 |
+
l_lw = len(linewidths)
|
| 682 |
+
gcd = math.gcd(l_dashes, l_lw)
|
| 683 |
+
dashes = list(dashes) * (l_lw // gcd)
|
| 684 |
+
linewidths = list(linewidths) * (l_dashes // gcd)
|
| 685 |
+
|
| 686 |
+
# scale the dash patterns
|
| 687 |
+
dashes = [mlines._scale_dashes(o, d, lw)
|
| 688 |
+
for (o, d), lw in zip(dashes, linewidths)]
|
| 689 |
+
|
| 690 |
+
return linewidths, dashes
|
| 691 |
+
|
| 692 |
+
def set_antialiased(self, aa):
|
| 693 |
+
"""
|
| 694 |
+
Set the antialiasing state for rendering.
|
| 695 |
+
|
| 696 |
+
Parameters
|
| 697 |
+
----------
|
| 698 |
+
aa : bool or list of bools
|
| 699 |
+
"""
|
| 700 |
+
if aa is None:
|
| 701 |
+
aa = self._get_default_antialiased()
|
| 702 |
+
self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
|
| 703 |
+
self.stale = True
|
| 704 |
+
|
| 705 |
+
def _get_default_antialiased(self):
|
| 706 |
+
# This may be overridden in a subclass.
|
| 707 |
+
return mpl.rcParams['patch.antialiased']
|
| 708 |
+
|
| 709 |
+
def set_color(self, c):
|
| 710 |
+
"""
|
| 711 |
+
Set both the edgecolor and the facecolor.
|
| 712 |
+
|
| 713 |
+
Parameters
|
| 714 |
+
----------
|
| 715 |
+
c : color or list of RGBA tuples
|
| 716 |
+
|
| 717 |
+
See Also
|
| 718 |
+
--------
|
| 719 |
+
Collection.set_facecolor, Collection.set_edgecolor
|
| 720 |
+
For setting the edge or face color individually.
|
| 721 |
+
"""
|
| 722 |
+
self.set_facecolor(c)
|
| 723 |
+
self.set_edgecolor(c)
|
| 724 |
+
|
| 725 |
+
def _get_default_facecolor(self):
|
| 726 |
+
# This may be overridden in a subclass.
|
| 727 |
+
return mpl.rcParams['patch.facecolor']
|
| 728 |
+
|
| 729 |
+
def _set_facecolor(self, c):
|
| 730 |
+
if c is None:
|
| 731 |
+
c = self._get_default_facecolor()
|
| 732 |
+
|
| 733 |
+
self._facecolors = mcolors.to_rgba_array(c, self._alpha)
|
| 734 |
+
self.stale = True
|
| 735 |
+
|
| 736 |
+
def set_facecolor(self, c):
|
| 737 |
+
"""
|
| 738 |
+
Set the facecolor(s) of the collection. *c* can be a color (all patches
|
| 739 |
+
have same color), or a sequence of colors; if it is a sequence the
|
| 740 |
+
patches will cycle through the sequence.
|
| 741 |
+
|
| 742 |
+
If *c* is 'none', the patch will not be filled.
|
| 743 |
+
|
| 744 |
+
Parameters
|
| 745 |
+
----------
|
| 746 |
+
c : color or list of colors
|
| 747 |
+
"""
|
| 748 |
+
if isinstance(c, str) and c.lower() in ("none", "face"):
|
| 749 |
+
c = c.lower()
|
| 750 |
+
self._original_facecolor = c
|
| 751 |
+
self._set_facecolor(c)
|
| 752 |
+
|
| 753 |
+
def get_facecolor(self):
|
| 754 |
+
return self._facecolors
|
| 755 |
+
|
| 756 |
+
def get_edgecolor(self):
|
| 757 |
+
if cbook._str_equal(self._edgecolors, 'face'):
|
| 758 |
+
return self.get_facecolor()
|
| 759 |
+
else:
|
| 760 |
+
return self._edgecolors
|
| 761 |
+
|
| 762 |
+
def _get_default_edgecolor(self):
|
| 763 |
+
# This may be overridden in a subclass.
|
| 764 |
+
return mpl.rcParams['patch.edgecolor']
|
| 765 |
+
|
| 766 |
+
def _set_edgecolor(self, c):
|
| 767 |
+
set_hatch_color = True
|
| 768 |
+
if c is None:
|
| 769 |
+
if (mpl.rcParams['patch.force_edgecolor']
|
| 770 |
+
or self._edge_default
|
| 771 |
+
or cbook._str_equal(self._original_facecolor, 'none')):
|
| 772 |
+
c = self._get_default_edgecolor()
|
| 773 |
+
else:
|
| 774 |
+
c = 'none'
|
| 775 |
+
set_hatch_color = False
|
| 776 |
+
if cbook._str_lower_equal(c, 'face'):
|
| 777 |
+
self._edgecolors = 'face'
|
| 778 |
+
self.stale = True
|
| 779 |
+
return
|
| 780 |
+
self._edgecolors = mcolors.to_rgba_array(c, self._alpha)
|
| 781 |
+
if set_hatch_color and len(self._edgecolors):
|
| 782 |
+
self._hatch_color = tuple(self._edgecolors[0])
|
| 783 |
+
self.stale = True
|
| 784 |
+
|
| 785 |
+
def set_edgecolor(self, c):
|
| 786 |
+
"""
|
| 787 |
+
Set the edgecolor(s) of the collection.
|
| 788 |
+
|
| 789 |
+
Parameters
|
| 790 |
+
----------
|
| 791 |
+
c : color or list of colors or 'face'
|
| 792 |
+
The collection edgecolor(s). If a sequence, the patches cycle
|
| 793 |
+
through it. If 'face', match the facecolor.
|
| 794 |
+
"""
|
| 795 |
+
# We pass through a default value for use in LineCollection.
|
| 796 |
+
# This allows us to maintain None as the default indicator in
|
| 797 |
+
# _original_edgecolor.
|
| 798 |
+
if isinstance(c, str) and c.lower() in ("none", "face"):
|
| 799 |
+
c = c.lower()
|
| 800 |
+
self._original_edgecolor = c
|
| 801 |
+
self._set_edgecolor(c)
|
| 802 |
+
|
| 803 |
+
def set_alpha(self, alpha):
|
| 804 |
+
"""
|
| 805 |
+
Set the transparency of the collection.
|
| 806 |
+
|
| 807 |
+
Parameters
|
| 808 |
+
----------
|
| 809 |
+
alpha : float or array of float or None
|
| 810 |
+
If not None, *alpha* values must be between 0 and 1, inclusive.
|
| 811 |
+
If an array is provided, its length must match the number of
|
| 812 |
+
elements in the collection. Masked values and nans are not
|
| 813 |
+
supported.
|
| 814 |
+
"""
|
| 815 |
+
artist.Artist._set_alpha_for_array(self, alpha)
|
| 816 |
+
self._set_facecolor(self._original_facecolor)
|
| 817 |
+
self._set_edgecolor(self._original_edgecolor)
|
| 818 |
+
|
| 819 |
+
set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__
|
| 820 |
+
|
| 821 |
+
def get_linewidth(self):
|
| 822 |
+
return self._linewidths
|
| 823 |
+
|
| 824 |
+
def get_linestyle(self):
|
| 825 |
+
return self._linestyles
|
| 826 |
+
|
| 827 |
+
def _set_mappable_flags(self):
|
| 828 |
+
"""
|
| 829 |
+
Determine whether edges and/or faces are color-mapped.
|
| 830 |
+
|
| 831 |
+
This is a helper for update_scalarmappable.
|
| 832 |
+
It sets Boolean flags '_edge_is_mapped' and '_face_is_mapped'.
|
| 833 |
+
|
| 834 |
+
Returns
|
| 835 |
+
-------
|
| 836 |
+
mapping_change : bool
|
| 837 |
+
True if either flag is True, or if a flag has changed.
|
| 838 |
+
"""
|
| 839 |
+
# The flags are initialized to None to ensure this returns True
|
| 840 |
+
# the first time it is called.
|
| 841 |
+
edge0 = self._edge_is_mapped
|
| 842 |
+
face0 = self._face_is_mapped
|
| 843 |
+
# After returning, the flags must be Booleans, not None.
|
| 844 |
+
self._edge_is_mapped = False
|
| 845 |
+
self._face_is_mapped = False
|
| 846 |
+
if self._A is not None:
|
| 847 |
+
if not cbook._str_equal(self._original_facecolor, 'none'):
|
| 848 |
+
self._face_is_mapped = True
|
| 849 |
+
if cbook._str_equal(self._original_edgecolor, 'face'):
|
| 850 |
+
self._edge_is_mapped = True
|
| 851 |
+
else:
|
| 852 |
+
if self._original_edgecolor is None:
|
| 853 |
+
self._edge_is_mapped = True
|
| 854 |
+
|
| 855 |
+
mapped = self._face_is_mapped or self._edge_is_mapped
|
| 856 |
+
changed = (edge0 is None or face0 is None
|
| 857 |
+
or self._edge_is_mapped != edge0
|
| 858 |
+
or self._face_is_mapped != face0)
|
| 859 |
+
return mapped or changed
|
| 860 |
+
|
| 861 |
+
def update_scalarmappable(self):
|
| 862 |
+
"""
|
| 863 |
+
Update colors from the scalar mappable array, if any.
|
| 864 |
+
|
| 865 |
+
Assign colors to edges and faces based on the array and/or
|
| 866 |
+
colors that were directly set, as appropriate.
|
| 867 |
+
"""
|
| 868 |
+
if not self._set_mappable_flags():
|
| 869 |
+
return
|
| 870 |
+
# Allow possibility to call 'self.set_array(None)'.
|
| 871 |
+
if self._A is not None:
|
| 872 |
+
# QuadMesh can map 2d arrays (but pcolormesh supplies 1d array)
|
| 873 |
+
if self._A.ndim > 1 and not isinstance(self, QuadMesh):
|
| 874 |
+
raise ValueError('Collections can only map rank 1 arrays')
|
| 875 |
+
if np.iterable(self._alpha):
|
| 876 |
+
if self._alpha.size != self._A.size:
|
| 877 |
+
raise ValueError(
|
| 878 |
+
f'Data array shape, {self._A.shape} '
|
| 879 |
+
'is incompatible with alpha array shape, '
|
| 880 |
+
f'{self._alpha.shape}. '
|
| 881 |
+
'This can occur with the deprecated '
|
| 882 |
+
'behavior of the "flat" shading option, '
|
| 883 |
+
'in which a row and/or column of the data '
|
| 884 |
+
'array is dropped.')
|
| 885 |
+
# pcolormesh, scatter, maybe others flatten their _A
|
| 886 |
+
self._alpha = self._alpha.reshape(self._A.shape)
|
| 887 |
+
self._mapped_colors = self.to_rgba(self._A, self._alpha)
|
| 888 |
+
|
| 889 |
+
if self._face_is_mapped:
|
| 890 |
+
self._facecolors = self._mapped_colors
|
| 891 |
+
else:
|
| 892 |
+
self._set_facecolor(self._original_facecolor)
|
| 893 |
+
if self._edge_is_mapped:
|
| 894 |
+
self._edgecolors = self._mapped_colors
|
| 895 |
+
else:
|
| 896 |
+
self._set_edgecolor(self._original_edgecolor)
|
| 897 |
+
self.stale = True
|
| 898 |
+
|
| 899 |
+
def get_fill(self):
|
| 900 |
+
"""Return whether face is colored."""
|
| 901 |
+
return not cbook._str_lower_equal(self._original_facecolor, "none")
|
| 902 |
+
|
| 903 |
+
def update_from(self, other):
|
| 904 |
+
"""Copy properties from other to self."""
|
| 905 |
+
|
| 906 |
+
artist.Artist.update_from(self, other)
|
| 907 |
+
self._antialiaseds = other._antialiaseds
|
| 908 |
+
self._mapped_colors = other._mapped_colors
|
| 909 |
+
self._edge_is_mapped = other._edge_is_mapped
|
| 910 |
+
self._original_edgecolor = other._original_edgecolor
|
| 911 |
+
self._edgecolors = other._edgecolors
|
| 912 |
+
self._face_is_mapped = other._face_is_mapped
|
| 913 |
+
self._original_facecolor = other._original_facecolor
|
| 914 |
+
self._facecolors = other._facecolors
|
| 915 |
+
self._linewidths = other._linewidths
|
| 916 |
+
self._linestyles = other._linestyles
|
| 917 |
+
self._us_linestyles = other._us_linestyles
|
| 918 |
+
self._pickradius = other._pickradius
|
| 919 |
+
self._hatch = other._hatch
|
| 920 |
+
|
| 921 |
+
# update_from for scalarmappable
|
| 922 |
+
self._A = other._A
|
| 923 |
+
self.norm = other.norm
|
| 924 |
+
self.cmap = other.cmap
|
| 925 |
+
self.stale = True
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
class _CollectionWithSizes(Collection):
|
| 929 |
+
"""
|
| 930 |
+
Base class for collections that have an array of sizes.
|
| 931 |
+
"""
|
| 932 |
+
_factor = 1.0
|
| 933 |
+
|
| 934 |
+
def get_sizes(self):
|
| 935 |
+
"""
|
| 936 |
+
Return the sizes ('areas') of the elements in the collection.
|
| 937 |
+
|
| 938 |
+
Returns
|
| 939 |
+
-------
|
| 940 |
+
array
|
| 941 |
+
The 'area' of each element.
|
| 942 |
+
"""
|
| 943 |
+
return self._sizes
|
| 944 |
+
|
| 945 |
+
def set_sizes(self, sizes, dpi=72.0):
|
| 946 |
+
"""
|
| 947 |
+
Set the sizes of each member of the collection.
|
| 948 |
+
|
| 949 |
+
Parameters
|
| 950 |
+
----------
|
| 951 |
+
sizes : `numpy.ndarray` or None
|
| 952 |
+
The size to set for each element of the collection. The
|
| 953 |
+
value is the 'area' of the element.
|
| 954 |
+
dpi : float, default: 72
|
| 955 |
+
The dpi of the canvas.
|
| 956 |
+
"""
|
| 957 |
+
if sizes is None:
|
| 958 |
+
self._sizes = np.array([])
|
| 959 |
+
self._transforms = np.empty((0, 3, 3))
|
| 960 |
+
else:
|
| 961 |
+
self._sizes = np.asarray(sizes)
|
| 962 |
+
self._transforms = np.zeros((len(self._sizes), 3, 3))
|
| 963 |
+
scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
|
| 964 |
+
self._transforms[:, 0, 0] = scale
|
| 965 |
+
self._transforms[:, 1, 1] = scale
|
| 966 |
+
self._transforms[:, 2, 2] = 1.0
|
| 967 |
+
self.stale = True
|
| 968 |
+
|
| 969 |
+
@artist.allow_rasterization
|
| 970 |
+
def draw(self, renderer):
|
| 971 |
+
self.set_sizes(self._sizes, self.figure.dpi)
|
| 972 |
+
super().draw(renderer)
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
class PathCollection(_CollectionWithSizes):
|
| 976 |
+
r"""
|
| 977 |
+
A collection of `~.path.Path`\s, as created by e.g. `~.Axes.scatter`.
|
| 978 |
+
"""
|
| 979 |
+
|
| 980 |
+
def __init__(self, paths, sizes=None, **kwargs):
|
| 981 |
+
"""
|
| 982 |
+
Parameters
|
| 983 |
+
----------
|
| 984 |
+
paths : list of `.path.Path`
|
| 985 |
+
The paths that will make up the `.Collection`.
|
| 986 |
+
sizes : array-like
|
| 987 |
+
The factor by which to scale each drawn `~.path.Path`. One unit
|
| 988 |
+
squared in the Path's data space is scaled to be ``sizes**2``
|
| 989 |
+
points when rendered.
|
| 990 |
+
**kwargs
|
| 991 |
+
Forwarded to `.Collection`.
|
| 992 |
+
"""
|
| 993 |
+
|
| 994 |
+
super().__init__(**kwargs)
|
| 995 |
+
self.set_paths(paths)
|
| 996 |
+
self.set_sizes(sizes)
|
| 997 |
+
self.stale = True
|
| 998 |
+
|
| 999 |
+
def set_paths(self, paths):
|
| 1000 |
+
self._paths = paths
|
| 1001 |
+
self.stale = True
|
| 1002 |
+
|
| 1003 |
+
def get_paths(self):
|
| 1004 |
+
return self._paths
|
| 1005 |
+
|
| 1006 |
+
def legend_elements(self, prop="colors", num="auto",
|
| 1007 |
+
fmt=None, func=lambda x: x, **kwargs):
|
| 1008 |
+
"""
|
| 1009 |
+
Create legend handles and labels for a PathCollection.
|
| 1010 |
+
|
| 1011 |
+
Each legend handle is a `.Line2D` representing the Path that was drawn,
|
| 1012 |
+
and each label is a string what each Path represents.
|
| 1013 |
+
|
| 1014 |
+
This is useful for obtaining a legend for a `~.Axes.scatter` plot;
|
| 1015 |
+
e.g.::
|
| 1016 |
+
|
| 1017 |
+
scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3])
|
| 1018 |
+
plt.legend(*scatter.legend_elements())
|
| 1019 |
+
|
| 1020 |
+
creates three legend elements, one for each color with the numerical
|
| 1021 |
+
values passed to *c* as the labels.
|
| 1022 |
+
|
| 1023 |
+
Also see the :ref:`automatedlegendcreation` example.
|
| 1024 |
+
|
| 1025 |
+
Parameters
|
| 1026 |
+
----------
|
| 1027 |
+
prop : {"colors", "sizes"}, default: "colors"
|
| 1028 |
+
If "colors", the legend handles will show the different colors of
|
| 1029 |
+
the collection. If "sizes", the legend will show the different
|
| 1030 |
+
sizes. To set both, use *kwargs* to directly edit the `.Line2D`
|
| 1031 |
+
properties.
|
| 1032 |
+
num : int, None, "auto" (default), array-like, or `~.ticker.Locator`
|
| 1033 |
+
Target number of elements to create.
|
| 1034 |
+
If None, use all unique elements of the mappable array. If an
|
| 1035 |
+
integer, target to use *num* elements in the normed range.
|
| 1036 |
+
If *"auto"*, try to determine which option better suits the nature
|
| 1037 |
+
of the data.
|
| 1038 |
+
The number of created elements may slightly deviate from *num* due
|
| 1039 |
+
to a `~.ticker.Locator` being used to find useful locations.
|
| 1040 |
+
If a list or array, use exactly those elements for the legend.
|
| 1041 |
+
Finally, a `~.ticker.Locator` can be provided.
|
| 1042 |
+
fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
|
| 1043 |
+
The format or formatter to use for the labels. If a string must be
|
| 1044 |
+
a valid input for a `.StrMethodFormatter`. If None (the default),
|
| 1045 |
+
use a `.ScalarFormatter`.
|
| 1046 |
+
func : function, default: ``lambda x: x``
|
| 1047 |
+
Function to calculate the labels. Often the size (or color)
|
| 1048 |
+
argument to `~.Axes.scatter` will have been pre-processed by the
|
| 1049 |
+
user using a function ``s = f(x)`` to make the markers visible;
|
| 1050 |
+
e.g. ``size = np.log10(x)``. Providing the inverse of this
|
| 1051 |
+
function here allows that pre-processing to be inverted, so that
|
| 1052 |
+
the legend labels have the correct values; e.g. ``func = lambda
|
| 1053 |
+
x: 10**x``.
|
| 1054 |
+
**kwargs
|
| 1055 |
+
Allowed keyword arguments are *color* and *size*. E.g. it may be
|
| 1056 |
+
useful to set the color of the markers if *prop="sizes"* is used;
|
| 1057 |
+
similarly to set the size of the markers if *prop="colors"* is
|
| 1058 |
+
used. Any further parameters are passed onto the `.Line2D`
|
| 1059 |
+
instance. This may be useful to e.g. specify a different
|
| 1060 |
+
*markeredgecolor* or *alpha* for the legend handles.
|
| 1061 |
+
|
| 1062 |
+
Returns
|
| 1063 |
+
-------
|
| 1064 |
+
handles : list of `.Line2D`
|
| 1065 |
+
Visual representation of each element of the legend.
|
| 1066 |
+
labels : list of str
|
| 1067 |
+
The string labels for elements of the legend.
|
| 1068 |
+
"""
|
| 1069 |
+
handles = []
|
| 1070 |
+
labels = []
|
| 1071 |
+
hasarray = self.get_array() is not None
|
| 1072 |
+
if fmt is None:
|
| 1073 |
+
fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
|
| 1074 |
+
elif isinstance(fmt, str):
|
| 1075 |
+
fmt = mpl.ticker.StrMethodFormatter(fmt)
|
| 1076 |
+
fmt.create_dummy_axis()
|
| 1077 |
+
|
| 1078 |
+
if prop == "colors":
|
| 1079 |
+
if not hasarray:
|
| 1080 |
+
warnings.warn("Collection without array used. Make sure to "
|
| 1081 |
+
"specify the values to be colormapped via the "
|
| 1082 |
+
"`c` argument.")
|
| 1083 |
+
return handles, labels
|
| 1084 |
+
u = np.unique(self.get_array())
|
| 1085 |
+
size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
|
| 1086 |
+
elif prop == "sizes":
|
| 1087 |
+
u = np.unique(self.get_sizes())
|
| 1088 |
+
color = kwargs.pop("color", "k")
|
| 1089 |
+
else:
|
| 1090 |
+
raise ValueError("Valid values for `prop` are 'colors' or "
|
| 1091 |
+
f"'sizes'. You supplied '{prop}' instead.")
|
| 1092 |
+
|
| 1093 |
+
fu = func(u)
|
| 1094 |
+
fmt.axis.set_view_interval(fu.min(), fu.max())
|
| 1095 |
+
fmt.axis.set_data_interval(fu.min(), fu.max())
|
| 1096 |
+
if num == "auto":
|
| 1097 |
+
num = 9
|
| 1098 |
+
if len(u) <= num:
|
| 1099 |
+
num = None
|
| 1100 |
+
if num is None:
|
| 1101 |
+
values = u
|
| 1102 |
+
label_values = func(values)
|
| 1103 |
+
else:
|
| 1104 |
+
if prop == "colors":
|
| 1105 |
+
arr = self.get_array()
|
| 1106 |
+
elif prop == "sizes":
|
| 1107 |
+
arr = self.get_sizes()
|
| 1108 |
+
if isinstance(num, mpl.ticker.Locator):
|
| 1109 |
+
loc = num
|
| 1110 |
+
elif np.iterable(num):
|
| 1111 |
+
loc = mpl.ticker.FixedLocator(num)
|
| 1112 |
+
else:
|
| 1113 |
+
num = int(num)
|
| 1114 |
+
loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
|
| 1115 |
+
steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
|
| 1116 |
+
label_values = loc.tick_values(func(arr).min(), func(arr).max())
|
| 1117 |
+
cond = ((label_values >= func(arr).min()) &
|
| 1118 |
+
(label_values <= func(arr).max()))
|
| 1119 |
+
label_values = label_values[cond]
|
| 1120 |
+
yarr = np.linspace(arr.min(), arr.max(), 256)
|
| 1121 |
+
xarr = func(yarr)
|
| 1122 |
+
ix = np.argsort(xarr)
|
| 1123 |
+
values = np.interp(label_values, xarr[ix], yarr[ix])
|
| 1124 |
+
|
| 1125 |
+
kw = {"markeredgewidth": self.get_linewidths()[0],
|
| 1126 |
+
"alpha": self.get_alpha(),
|
| 1127 |
+
**kwargs}
|
| 1128 |
+
|
| 1129 |
+
for val, lab in zip(values, label_values):
|
| 1130 |
+
if prop == "colors":
|
| 1131 |
+
color = self.cmap(self.norm(val))
|
| 1132 |
+
elif prop == "sizes":
|
| 1133 |
+
size = np.sqrt(val)
|
| 1134 |
+
if np.isclose(size, 0.0):
|
| 1135 |
+
continue
|
| 1136 |
+
h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
|
| 1137 |
+
marker=self.get_paths()[0], **kw)
|
| 1138 |
+
handles.append(h)
|
| 1139 |
+
if hasattr(fmt, "set_locs"):
|
| 1140 |
+
fmt.set_locs(label_values)
|
| 1141 |
+
l = fmt(lab)
|
| 1142 |
+
labels.append(l)
|
| 1143 |
+
|
| 1144 |
+
return handles, labels
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
class PolyCollection(_CollectionWithSizes):
|
| 1148 |
+
|
| 1149 |
+
@_api.make_keyword_only("3.6", name="closed")
|
| 1150 |
+
def __init__(self, verts, sizes=None, closed=True, **kwargs):
|
| 1151 |
+
"""
|
| 1152 |
+
Parameters
|
| 1153 |
+
----------
|
| 1154 |
+
verts : list of array-like
|
| 1155 |
+
The sequence of polygons [*verts0*, *verts1*, ...] where each
|
| 1156 |
+
element *verts_i* defines the vertices of polygon *i* as a 2D
|
| 1157 |
+
array-like of shape (M, 2).
|
| 1158 |
+
sizes : array-like, default: None
|
| 1159 |
+
Squared scaling factors for the polygons. The coordinates of each
|
| 1160 |
+
polygon *verts_i* are multiplied by the square-root of the
|
| 1161 |
+
corresponding entry in *sizes* (i.e., *sizes* specify the scaling
|
| 1162 |
+
of areas). The scaling is applied before the Artist master
|
| 1163 |
+
transform.
|
| 1164 |
+
closed : bool, default: True
|
| 1165 |
+
Whether the polygon should be closed by adding a CLOSEPOLY
|
| 1166 |
+
connection at the end.
|
| 1167 |
+
**kwargs
|
| 1168 |
+
Forwarded to `.Collection`.
|
| 1169 |
+
"""
|
| 1170 |
+
super().__init__(**kwargs)
|
| 1171 |
+
self.set_sizes(sizes)
|
| 1172 |
+
self.set_verts(verts, closed)
|
| 1173 |
+
self.stale = True
|
| 1174 |
+
|
| 1175 |
+
def set_verts(self, verts, closed=True):
|
| 1176 |
+
"""
|
| 1177 |
+
Set the vertices of the polygons.
|
| 1178 |
+
|
| 1179 |
+
Parameters
|
| 1180 |
+
----------
|
| 1181 |
+
verts : list of array-like
|
| 1182 |
+
The sequence of polygons [*verts0*, *verts1*, ...] where each
|
| 1183 |
+
element *verts_i* defines the vertices of polygon *i* as a 2D
|
| 1184 |
+
array-like of shape (M, 2).
|
| 1185 |
+
closed : bool, default: True
|
| 1186 |
+
Whether the polygon should be closed by adding a CLOSEPOLY
|
| 1187 |
+
connection at the end.
|
| 1188 |
+
"""
|
| 1189 |
+
self.stale = True
|
| 1190 |
+
if isinstance(verts, np.ma.MaskedArray):
|
| 1191 |
+
verts = verts.astype(float).filled(np.nan)
|
| 1192 |
+
|
| 1193 |
+
# No need to do anything fancy if the path isn't closed.
|
| 1194 |
+
if not closed:
|
| 1195 |
+
self._paths = [mpath.Path(xy) for xy in verts]
|
| 1196 |
+
return
|
| 1197 |
+
|
| 1198 |
+
# Fast path for arrays
|
| 1199 |
+
if isinstance(verts, np.ndarray) and len(verts.shape) == 3:
|
| 1200 |
+
verts_pad = np.concatenate((verts, verts[:, :1]), axis=1)
|
| 1201 |
+
# Creating the codes once is much faster than having Path do it
|
| 1202 |
+
# separately each time by passing closed=True.
|
| 1203 |
+
codes = np.empty(verts_pad.shape[1], dtype=mpath.Path.code_type)
|
| 1204 |
+
codes[:] = mpath.Path.LINETO
|
| 1205 |
+
codes[0] = mpath.Path.MOVETO
|
| 1206 |
+
codes[-1] = mpath.Path.CLOSEPOLY
|
| 1207 |
+
self._paths = [mpath.Path(xy, codes) for xy in verts_pad]
|
| 1208 |
+
return
|
| 1209 |
+
|
| 1210 |
+
self._paths = []
|
| 1211 |
+
for xy in verts:
|
| 1212 |
+
if len(xy):
|
| 1213 |
+
self._paths.append(mpath.Path._create_closed(xy))
|
| 1214 |
+
else:
|
| 1215 |
+
self._paths.append(mpath.Path(xy))
|
| 1216 |
+
|
| 1217 |
+
set_paths = set_verts
|
| 1218 |
+
|
| 1219 |
+
def set_verts_and_codes(self, verts, codes):
|
| 1220 |
+
"""Initialize vertices with path codes."""
|
| 1221 |
+
if len(verts) != len(codes):
|
| 1222 |
+
raise ValueError("'codes' must be a 1D list or array "
|
| 1223 |
+
"with the same length of 'verts'")
|
| 1224 |
+
self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy)
|
| 1225 |
+
for xy, cds in zip(verts, codes)]
|
| 1226 |
+
self.stale = True
|
| 1227 |
+
|
| 1228 |
+
@classmethod
|
| 1229 |
+
@_api.deprecated("3.7", alternative="fill_between")
|
| 1230 |
+
def span_where(cls, x, ymin, ymax, where, **kwargs):
|
| 1231 |
+
"""
|
| 1232 |
+
Return a `.BrokenBarHCollection` that plots horizontal bars from
|
| 1233 |
+
over the regions in *x* where *where* is True. The bars range
|
| 1234 |
+
on the y-axis from *ymin* to *ymax*
|
| 1235 |
+
|
| 1236 |
+
*kwargs* are passed on to the collection.
|
| 1237 |
+
"""
|
| 1238 |
+
xranges = []
|
| 1239 |
+
for ind0, ind1 in cbook.contiguous_regions(where):
|
| 1240 |
+
xslice = x[ind0:ind1]
|
| 1241 |
+
if not len(xslice):
|
| 1242 |
+
continue
|
| 1243 |
+
xranges.append((xslice[0], xslice[-1] - xslice[0]))
|
| 1244 |
+
return BrokenBarHCollection(xranges, [ymin, ymax - ymin], **kwargs)
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
@_api.deprecated("3.7")
|
| 1248 |
+
class BrokenBarHCollection(PolyCollection):
|
| 1249 |
+
"""
|
| 1250 |
+
A collection of horizontal bars spanning *yrange* with a sequence of
|
| 1251 |
+
*xranges*.
|
| 1252 |
+
"""
|
| 1253 |
+
def __init__(self, xranges, yrange, **kwargs):
|
| 1254 |
+
"""
|
| 1255 |
+
Parameters
|
| 1256 |
+
----------
|
| 1257 |
+
xranges : list of (float, float)
|
| 1258 |
+
The sequence of (left-edge-position, width) pairs for each bar.
|
| 1259 |
+
yrange : (float, float)
|
| 1260 |
+
The (lower-edge, height) common to all bars.
|
| 1261 |
+
**kwargs
|
| 1262 |
+
Forwarded to `.Collection`.
|
| 1263 |
+
"""
|
| 1264 |
+
ymin, ywidth = yrange
|
| 1265 |
+
ymax = ymin + ywidth
|
| 1266 |
+
verts = [[(xmin, ymin),
|
| 1267 |
+
(xmin, ymax),
|
| 1268 |
+
(xmin + xwidth, ymax),
|
| 1269 |
+
(xmin + xwidth, ymin),
|
| 1270 |
+
(xmin, ymin)] for xmin, xwidth in xranges]
|
| 1271 |
+
super().__init__(verts, **kwargs)
|
| 1272 |
+
|
| 1273 |
+
|
| 1274 |
+
class RegularPolyCollection(_CollectionWithSizes):
|
| 1275 |
+
"""A collection of n-sided regular polygons."""
|
| 1276 |
+
|
| 1277 |
+
_path_generator = mpath.Path.unit_regular_polygon
|
| 1278 |
+
_factor = np.pi ** (-1/2)
|
| 1279 |
+
|
| 1280 |
+
@_api.make_keyword_only("3.6", name="rotation")
|
| 1281 |
+
def __init__(self,
|
| 1282 |
+
numsides,
|
| 1283 |
+
rotation=0,
|
| 1284 |
+
sizes=(1,),
|
| 1285 |
+
**kwargs):
|
| 1286 |
+
"""
|
| 1287 |
+
Parameters
|
| 1288 |
+
----------
|
| 1289 |
+
numsides : int
|
| 1290 |
+
The number of sides of the polygon.
|
| 1291 |
+
rotation : float
|
| 1292 |
+
The rotation of the polygon in radians.
|
| 1293 |
+
sizes : tuple of float
|
| 1294 |
+
The area of the circle circumscribing the polygon in points^2.
|
| 1295 |
+
**kwargs
|
| 1296 |
+
Forwarded to `.Collection`.
|
| 1297 |
+
|
| 1298 |
+
Examples
|
| 1299 |
+
--------
|
| 1300 |
+
See :doc:`/gallery/event_handling/lasso_demo` for a complete example::
|
| 1301 |
+
|
| 1302 |
+
offsets = np.random.rand(20, 2)
|
| 1303 |
+
facecolors = [cm.jet(x) for x in np.random.rand(20)]
|
| 1304 |
+
|
| 1305 |
+
collection = RegularPolyCollection(
|
| 1306 |
+
numsides=5, # a pentagon
|
| 1307 |
+
rotation=0, sizes=(50,),
|
| 1308 |
+
facecolors=facecolors,
|
| 1309 |
+
edgecolors=("black",),
|
| 1310 |
+
linewidths=(1,),
|
| 1311 |
+
offsets=offsets,
|
| 1312 |
+
offset_transform=ax.transData,
|
| 1313 |
+
)
|
| 1314 |
+
"""
|
| 1315 |
+
super().__init__(**kwargs)
|
| 1316 |
+
self.set_sizes(sizes)
|
| 1317 |
+
self._numsides = numsides
|
| 1318 |
+
self._paths = [self._path_generator(numsides)]
|
| 1319 |
+
self._rotation = rotation
|
| 1320 |
+
self.set_transform(transforms.IdentityTransform())
|
| 1321 |
+
|
| 1322 |
+
def get_numsides(self):
|
| 1323 |
+
return self._numsides
|
| 1324 |
+
|
| 1325 |
+
def get_rotation(self):
|
| 1326 |
+
return self._rotation
|
| 1327 |
+
|
| 1328 |
+
@artist.allow_rasterization
|
| 1329 |
+
def draw(self, renderer):
|
| 1330 |
+
self.set_sizes(self._sizes, self.figure.dpi)
|
| 1331 |
+
self._transforms = [
|
| 1332 |
+
transforms.Affine2D(x).rotate(-self._rotation).get_matrix()
|
| 1333 |
+
for x in self._transforms
|
| 1334 |
+
]
|
| 1335 |
+
# Explicitly not super().draw, because set_sizes must be called before
|
| 1336 |
+
# updating self._transforms.
|
| 1337 |
+
Collection.draw(self, renderer)
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
class StarPolygonCollection(RegularPolyCollection):
|
| 1341 |
+
"""Draw a collection of regular stars with *numsides* points."""
|
| 1342 |
+
_path_generator = mpath.Path.unit_regular_star
|
| 1343 |
+
|
| 1344 |
+
|
| 1345 |
+
class AsteriskPolygonCollection(RegularPolyCollection):
|
| 1346 |
+
"""Draw a collection of regular asterisks with *numsides* points."""
|
| 1347 |
+
_path_generator = mpath.Path.unit_regular_asterisk
|
| 1348 |
+
|
| 1349 |
+
|
| 1350 |
+
class LineCollection(Collection):
|
| 1351 |
+
r"""
|
| 1352 |
+
Represents a sequence of `.Line2D`\s that should be drawn together.
|
| 1353 |
+
|
| 1354 |
+
This class extends `.Collection` to represent a sequence of
|
| 1355 |
+
`.Line2D`\s instead of just a sequence of `.Patch`\s.
|
| 1356 |
+
Just as in `.Collection`, each property of a *LineCollection* may be either
|
| 1357 |
+
a single value or a list of values. This list is then used cyclically for
|
| 1358 |
+
each element of the LineCollection, so the property of the ``i``\th element
|
| 1359 |
+
of the collection is::
|
| 1360 |
+
|
| 1361 |
+
prop[i % len(prop)]
|
| 1362 |
+
|
| 1363 |
+
The properties of each member of a *LineCollection* default to their values
|
| 1364 |
+
in :rc:`lines.*` instead of :rc:`patch.*`, and the property *colors* is
|
| 1365 |
+
added in place of *edgecolors*.
|
| 1366 |
+
"""
|
| 1367 |
+
|
| 1368 |
+
_edge_default = True
|
| 1369 |
+
|
| 1370 |
+
def __init__(self, segments, # Can be None.
|
| 1371 |
+
*,
|
| 1372 |
+
zorder=2, # Collection.zorder is 1
|
| 1373 |
+
**kwargs
|
| 1374 |
+
):
|
| 1375 |
+
"""
|
| 1376 |
+
Parameters
|
| 1377 |
+
----------
|
| 1378 |
+
segments : list of array-like
|
| 1379 |
+
A sequence of (*line0*, *line1*, *line2*), where::
|
| 1380 |
+
|
| 1381 |
+
linen = (x0, y0), (x1, y1), ... (xm, ym)
|
| 1382 |
+
|
| 1383 |
+
or the equivalent numpy array with two columns. Each line
|
| 1384 |
+
can have a different number of segments.
|
| 1385 |
+
linewidths : float or list of float, default: :rc:`lines.linewidth`
|
| 1386 |
+
The width of each line in points.
|
| 1387 |
+
colors : color or list of color, default: :rc:`lines.color`
|
| 1388 |
+
A sequence of RGBA tuples (e.g., arbitrary color strings, etc, not
|
| 1389 |
+
allowed).
|
| 1390 |
+
antialiaseds : bool or list of bool, default: :rc:`lines.antialiased`
|
| 1391 |
+
Whether to use antialiasing for each line.
|
| 1392 |
+
zorder : float, default: 2
|
| 1393 |
+
zorder of the lines once drawn.
|
| 1394 |
+
|
| 1395 |
+
facecolors : color or list of color, default: 'none'
|
| 1396 |
+
When setting *facecolors*, each line is interpreted as a boundary
|
| 1397 |
+
for an area, implicitly closing the path from the last point to the
|
| 1398 |
+
first point. The enclosed area is filled with *facecolor*.
|
| 1399 |
+
In order to manually specify what should count as the "interior" of
|
| 1400 |
+
each line, please use `.PathCollection` instead, where the
|
| 1401 |
+
"interior" can be specified by appropriate usage of
|
| 1402 |
+
`~.path.Path.CLOSEPOLY`.
|
| 1403 |
+
|
| 1404 |
+
**kwargs
|
| 1405 |
+
Forwarded to `.Collection`.
|
| 1406 |
+
"""
|
| 1407 |
+
# Unfortunately, mplot3d needs this explicit setting of 'facecolors'.
|
| 1408 |
+
kwargs.setdefault('facecolors', 'none')
|
| 1409 |
+
super().__init__(
|
| 1410 |
+
zorder=zorder,
|
| 1411 |
+
**kwargs)
|
| 1412 |
+
self.set_segments(segments)
|
| 1413 |
+
|
| 1414 |
+
def set_segments(self, segments):
|
| 1415 |
+
if segments is None:
|
| 1416 |
+
return
|
| 1417 |
+
|
| 1418 |
+
self._paths = [mpath.Path(seg) if isinstance(seg, np.ma.MaskedArray)
|
| 1419 |
+
else mpath.Path(np.asarray(seg, float))
|
| 1420 |
+
for seg in segments]
|
| 1421 |
+
self.stale = True
|
| 1422 |
+
|
| 1423 |
+
set_verts = set_segments # for compatibility with PolyCollection
|
| 1424 |
+
set_paths = set_segments
|
| 1425 |
+
|
| 1426 |
+
def get_segments(self):
|
| 1427 |
+
"""
|
| 1428 |
+
Returns
|
| 1429 |
+
-------
|
| 1430 |
+
list
|
| 1431 |
+
List of segments in the LineCollection. Each list item contains an
|
| 1432 |
+
array of vertices.
|
| 1433 |
+
"""
|
| 1434 |
+
segments = []
|
| 1435 |
+
|
| 1436 |
+
for path in self._paths:
|
| 1437 |
+
vertices = [
|
| 1438 |
+
vertex
|
| 1439 |
+
for vertex, _
|
| 1440 |
+
# Never simplify here, we want to get the data-space values
|
| 1441 |
+
# back and there in no way to know the "right" simplification
|
| 1442 |
+
# threshold so never try.
|
| 1443 |
+
in path.iter_segments(simplify=False)
|
| 1444 |
+
]
|
| 1445 |
+
vertices = np.asarray(vertices)
|
| 1446 |
+
segments.append(vertices)
|
| 1447 |
+
|
| 1448 |
+
return segments
|
| 1449 |
+
|
| 1450 |
+
def _get_default_linewidth(self):
|
| 1451 |
+
return mpl.rcParams['lines.linewidth']
|
| 1452 |
+
|
| 1453 |
+
def _get_default_antialiased(self):
|
| 1454 |
+
return mpl.rcParams['lines.antialiased']
|
| 1455 |
+
|
| 1456 |
+
def _get_default_edgecolor(self):
|
| 1457 |
+
return mpl.rcParams['lines.color']
|
| 1458 |
+
|
| 1459 |
+
def _get_default_facecolor(self):
|
| 1460 |
+
return 'none'
|
| 1461 |
+
|
| 1462 |
+
def set_color(self, c):
|
| 1463 |
+
"""
|
| 1464 |
+
Set the edgecolor(s) of the LineCollection.
|
| 1465 |
+
|
| 1466 |
+
Parameters
|
| 1467 |
+
----------
|
| 1468 |
+
c : color or list of colors
|
| 1469 |
+
Single color (all lines have same color), or a
|
| 1470 |
+
sequence of RGBA tuples; if it is a sequence the lines will
|
| 1471 |
+
cycle through the sequence.
|
| 1472 |
+
"""
|
| 1473 |
+
self.set_edgecolor(c)
|
| 1474 |
+
|
| 1475 |
+
set_colors = set_color
|
| 1476 |
+
|
| 1477 |
+
def get_color(self):
|
| 1478 |
+
return self._edgecolors
|
| 1479 |
+
|
| 1480 |
+
get_colors = get_color # for compatibility with old versions
|
| 1481 |
+
|
| 1482 |
+
|
| 1483 |
+
class EventCollection(LineCollection):
|
| 1484 |
+
"""
|
| 1485 |
+
A collection of locations along a single axis at which an "event" occurred.
|
| 1486 |
+
|
| 1487 |
+
The events are given by a 1-dimensional array. They do not have an
|
| 1488 |
+
amplitude and are displayed as parallel lines.
|
| 1489 |
+
"""
|
| 1490 |
+
|
| 1491 |
+
_edge_default = True
|
| 1492 |
+
|
| 1493 |
+
@_api.make_keyword_only("3.6", name="lineoffset")
|
| 1494 |
+
def __init__(self,
|
| 1495 |
+
positions, # Cannot be None.
|
| 1496 |
+
orientation='horizontal',
|
| 1497 |
+
lineoffset=0,
|
| 1498 |
+
linelength=1,
|
| 1499 |
+
linewidth=None,
|
| 1500 |
+
color=None,
|
| 1501 |
+
linestyle='solid',
|
| 1502 |
+
antialiased=None,
|
| 1503 |
+
**kwargs
|
| 1504 |
+
):
|
| 1505 |
+
"""
|
| 1506 |
+
Parameters
|
| 1507 |
+
----------
|
| 1508 |
+
positions : 1D array-like
|
| 1509 |
+
Each value is an event.
|
| 1510 |
+
orientation : {'horizontal', 'vertical'}, default: 'horizontal'
|
| 1511 |
+
The sequence of events is plotted along this direction.
|
| 1512 |
+
The marker lines of the single events are along the orthogonal
|
| 1513 |
+
direction.
|
| 1514 |
+
lineoffset : float, default: 0
|
| 1515 |
+
The offset of the center of the markers from the origin, in the
|
| 1516 |
+
direction orthogonal to *orientation*.
|
| 1517 |
+
linelength : float, default: 1
|
| 1518 |
+
The total height of the marker (i.e. the marker stretches from
|
| 1519 |
+
``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
|
| 1520 |
+
linewidth : float or list thereof, default: :rc:`lines.linewidth`
|
| 1521 |
+
The line width of the event lines, in points.
|
| 1522 |
+
color : color or list of colors, default: :rc:`lines.color`
|
| 1523 |
+
The color of the event lines.
|
| 1524 |
+
linestyle : str or tuple or list thereof, default: 'solid'
|
| 1525 |
+
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
|
| 1526 |
+
'-', '--', '-.', ':']. Dash tuples should be of the form::
|
| 1527 |
+
|
| 1528 |
+
(offset, onoffseq),
|
| 1529 |
+
|
| 1530 |
+
where *onoffseq* is an even length tuple of on and off ink
|
| 1531 |
+
in points.
|
| 1532 |
+
antialiased : bool or list thereof, default: :rc:`lines.antialiased`
|
| 1533 |
+
Whether to use antialiasing for drawing the lines.
|
| 1534 |
+
**kwargs
|
| 1535 |
+
Forwarded to `.LineCollection`.
|
| 1536 |
+
|
| 1537 |
+
Examples
|
| 1538 |
+
--------
|
| 1539 |
+
.. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
|
| 1540 |
+
"""
|
| 1541 |
+
super().__init__([],
|
| 1542 |
+
linewidths=linewidth, linestyles=linestyle,
|
| 1543 |
+
colors=color, antialiaseds=antialiased,
|
| 1544 |
+
**kwargs)
|
| 1545 |
+
self._is_horizontal = True # Initial value, may be switched below.
|
| 1546 |
+
self._linelength = linelength
|
| 1547 |
+
self._lineoffset = lineoffset
|
| 1548 |
+
self.set_orientation(orientation)
|
| 1549 |
+
self.set_positions(positions)
|
| 1550 |
+
|
| 1551 |
+
def get_positions(self):
|
| 1552 |
+
"""
|
| 1553 |
+
Return an array containing the floating-point values of the positions.
|
| 1554 |
+
"""
|
| 1555 |
+
pos = 0 if self.is_horizontal() else 1
|
| 1556 |
+
return [segment[0, pos] for segment in self.get_segments()]
|
| 1557 |
+
|
| 1558 |
+
def set_positions(self, positions):
|
| 1559 |
+
"""Set the positions of the events."""
|
| 1560 |
+
if positions is None:
|
| 1561 |
+
positions = []
|
| 1562 |
+
if np.ndim(positions) != 1:
|
| 1563 |
+
raise ValueError('positions must be one-dimensional')
|
| 1564 |
+
lineoffset = self.get_lineoffset()
|
| 1565 |
+
linelength = self.get_linelength()
|
| 1566 |
+
pos_idx = 0 if self.is_horizontal() else 1
|
| 1567 |
+
segments = np.empty((len(positions), 2, 2))
|
| 1568 |
+
segments[:, :, pos_idx] = np.sort(positions)[:, None]
|
| 1569 |
+
segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2
|
| 1570 |
+
segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2
|
| 1571 |
+
self.set_segments(segments)
|
| 1572 |
+
|
| 1573 |
+
def add_positions(self, position):
|
| 1574 |
+
"""Add one or more events at the specified positions."""
|
| 1575 |
+
if position is None or (hasattr(position, 'len') and
|
| 1576 |
+
len(position) == 0):
|
| 1577 |
+
return
|
| 1578 |
+
positions = self.get_positions()
|
| 1579 |
+
positions = np.hstack([positions, np.asanyarray(position)])
|
| 1580 |
+
self.set_positions(positions)
|
| 1581 |
+
extend_positions = append_positions = add_positions
|
| 1582 |
+
|
| 1583 |
+
def is_horizontal(self):
|
| 1584 |
+
"""True if the eventcollection is horizontal, False if vertical."""
|
| 1585 |
+
return self._is_horizontal
|
| 1586 |
+
|
| 1587 |
+
def get_orientation(self):
|
| 1588 |
+
"""
|
| 1589 |
+
Return the orientation of the event line ('horizontal' or 'vertical').
|
| 1590 |
+
"""
|
| 1591 |
+
return 'horizontal' if self.is_horizontal() else 'vertical'
|
| 1592 |
+
|
| 1593 |
+
def switch_orientation(self):
|
| 1594 |
+
"""
|
| 1595 |
+
Switch the orientation of the event line, either from vertical to
|
| 1596 |
+
horizontal or vice versus.
|
| 1597 |
+
"""
|
| 1598 |
+
segments = self.get_segments()
|
| 1599 |
+
for i, segment in enumerate(segments):
|
| 1600 |
+
segments[i] = np.fliplr(segment)
|
| 1601 |
+
self.set_segments(segments)
|
| 1602 |
+
self._is_horizontal = not self.is_horizontal()
|
| 1603 |
+
self.stale = True
|
| 1604 |
+
|
| 1605 |
+
def set_orientation(self, orientation):
|
| 1606 |
+
"""
|
| 1607 |
+
Set the orientation of the event line.
|
| 1608 |
+
|
| 1609 |
+
Parameters
|
| 1610 |
+
----------
|
| 1611 |
+
orientation : {'horizontal', 'vertical'}
|
| 1612 |
+
"""
|
| 1613 |
+
is_horizontal = _api.check_getitem(
|
| 1614 |
+
{"horizontal": True, "vertical": False},
|
| 1615 |
+
orientation=orientation)
|
| 1616 |
+
if is_horizontal == self.is_horizontal():
|
| 1617 |
+
return
|
| 1618 |
+
self.switch_orientation()
|
| 1619 |
+
|
| 1620 |
+
def get_linelength(self):
|
| 1621 |
+
"""Return the length of the lines used to mark each event."""
|
| 1622 |
+
return self._linelength
|
| 1623 |
+
|
| 1624 |
+
def set_linelength(self, linelength):
|
| 1625 |
+
"""Set the length of the lines used to mark each event."""
|
| 1626 |
+
if linelength == self.get_linelength():
|
| 1627 |
+
return
|
| 1628 |
+
lineoffset = self.get_lineoffset()
|
| 1629 |
+
segments = self.get_segments()
|
| 1630 |
+
pos = 1 if self.is_horizontal() else 0
|
| 1631 |
+
for segment in segments:
|
| 1632 |
+
segment[0, pos] = lineoffset + linelength / 2.
|
| 1633 |
+
segment[1, pos] = lineoffset - linelength / 2.
|
| 1634 |
+
self.set_segments(segments)
|
| 1635 |
+
self._linelength = linelength
|
| 1636 |
+
|
| 1637 |
+
def get_lineoffset(self):
|
| 1638 |
+
"""Return the offset of the lines used to mark each event."""
|
| 1639 |
+
return self._lineoffset
|
| 1640 |
+
|
| 1641 |
+
def set_lineoffset(self, lineoffset):
|
| 1642 |
+
"""Set the offset of the lines used to mark each event."""
|
| 1643 |
+
if lineoffset == self.get_lineoffset():
|
| 1644 |
+
return
|
| 1645 |
+
linelength = self.get_linelength()
|
| 1646 |
+
segments = self.get_segments()
|
| 1647 |
+
pos = 1 if self.is_horizontal() else 0
|
| 1648 |
+
for segment in segments:
|
| 1649 |
+
segment[0, pos] = lineoffset + linelength / 2.
|
| 1650 |
+
segment[1, pos] = lineoffset - linelength / 2.
|
| 1651 |
+
self.set_segments(segments)
|
| 1652 |
+
self._lineoffset = lineoffset
|
| 1653 |
+
|
| 1654 |
+
def get_linewidth(self):
|
| 1655 |
+
"""Get the width of the lines used to mark each event."""
|
| 1656 |
+
return super().get_linewidth()[0]
|
| 1657 |
+
|
| 1658 |
+
def get_linewidths(self):
|
| 1659 |
+
return super().get_linewidth()
|
| 1660 |
+
|
| 1661 |
+
def get_color(self):
|
| 1662 |
+
"""Return the color of the lines used to mark each event."""
|
| 1663 |
+
return self.get_colors()[0]
|
| 1664 |
+
|
| 1665 |
+
|
| 1666 |
+
class CircleCollection(_CollectionWithSizes):
|
| 1667 |
+
"""A collection of circles, drawn using splines."""
|
| 1668 |
+
|
| 1669 |
+
_factor = np.pi ** (-1/2)
|
| 1670 |
+
|
| 1671 |
+
def __init__(self, sizes, **kwargs):
|
| 1672 |
+
"""
|
| 1673 |
+
Parameters
|
| 1674 |
+
----------
|
| 1675 |
+
sizes : float or array-like
|
| 1676 |
+
The area of each circle in points^2.
|
| 1677 |
+
**kwargs
|
| 1678 |
+
Forwarded to `.Collection`.
|
| 1679 |
+
"""
|
| 1680 |
+
super().__init__(**kwargs)
|
| 1681 |
+
self.set_sizes(sizes)
|
| 1682 |
+
self.set_transform(transforms.IdentityTransform())
|
| 1683 |
+
self._paths = [mpath.Path.unit_circle()]
|
| 1684 |
+
|
| 1685 |
+
|
| 1686 |
+
class EllipseCollection(Collection):
|
| 1687 |
+
"""A collection of ellipses, drawn using splines."""
|
| 1688 |
+
|
| 1689 |
+
@_api.make_keyword_only("3.6", name="units")
|
| 1690 |
+
def __init__(self, widths, heights, angles, units='points', **kwargs):
|
| 1691 |
+
"""
|
| 1692 |
+
Parameters
|
| 1693 |
+
----------
|
| 1694 |
+
widths : array-like
|
| 1695 |
+
The lengths of the first axes (e.g., major axis lengths).
|
| 1696 |
+
heights : array-like
|
| 1697 |
+
The lengths of second axes.
|
| 1698 |
+
angles : array-like
|
| 1699 |
+
The angles of the first axes, degrees CCW from the x-axis.
|
| 1700 |
+
units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'}
|
| 1701 |
+
The units in which majors and minors are given; 'width' and
|
| 1702 |
+
'height' refer to the dimensions of the axes, while 'x' and 'y'
|
| 1703 |
+
refer to the *offsets* data units. 'xy' differs from all others in
|
| 1704 |
+
that the angle as plotted varies with the aspect ratio, and equals
|
| 1705 |
+
the specified angle only when the aspect ratio is unity. Hence
|
| 1706 |
+
it behaves the same as the `~.patches.Ellipse` with
|
| 1707 |
+
``axes.transData`` as its transform.
|
| 1708 |
+
**kwargs
|
| 1709 |
+
Forwarded to `Collection`.
|
| 1710 |
+
"""
|
| 1711 |
+
super().__init__(**kwargs)
|
| 1712 |
+
self._widths = 0.5 * np.asarray(widths).ravel()
|
| 1713 |
+
self._heights = 0.5 * np.asarray(heights).ravel()
|
| 1714 |
+
self._angles = np.deg2rad(angles).ravel()
|
| 1715 |
+
self._units = units
|
| 1716 |
+
self.set_transform(transforms.IdentityTransform())
|
| 1717 |
+
self._transforms = np.empty((0, 3, 3))
|
| 1718 |
+
self._paths = [mpath.Path.unit_circle()]
|
| 1719 |
+
|
| 1720 |
+
def _set_transforms(self):
|
| 1721 |
+
"""Calculate transforms immediately before drawing."""
|
| 1722 |
+
|
| 1723 |
+
ax = self.axes
|
| 1724 |
+
fig = self.figure
|
| 1725 |
+
|
| 1726 |
+
if self._units == 'xy':
|
| 1727 |
+
sc = 1
|
| 1728 |
+
elif self._units == 'x':
|
| 1729 |
+
sc = ax.bbox.width / ax.viewLim.width
|
| 1730 |
+
elif self._units == 'y':
|
| 1731 |
+
sc = ax.bbox.height / ax.viewLim.height
|
| 1732 |
+
elif self._units == 'inches':
|
| 1733 |
+
sc = fig.dpi
|
| 1734 |
+
elif self._units == 'points':
|
| 1735 |
+
sc = fig.dpi / 72.0
|
| 1736 |
+
elif self._units == 'width':
|
| 1737 |
+
sc = ax.bbox.width
|
| 1738 |
+
elif self._units == 'height':
|
| 1739 |
+
sc = ax.bbox.height
|
| 1740 |
+
elif self._units == 'dots':
|
| 1741 |
+
sc = 1.0
|
| 1742 |
+
else:
|
| 1743 |
+
raise ValueError(f'Unrecognized units: {self._units!r}')
|
| 1744 |
+
|
| 1745 |
+
self._transforms = np.zeros((len(self._widths), 3, 3))
|
| 1746 |
+
widths = self._widths * sc
|
| 1747 |
+
heights = self._heights * sc
|
| 1748 |
+
sin_angle = np.sin(self._angles)
|
| 1749 |
+
cos_angle = np.cos(self._angles)
|
| 1750 |
+
self._transforms[:, 0, 0] = widths * cos_angle
|
| 1751 |
+
self._transforms[:, 0, 1] = heights * -sin_angle
|
| 1752 |
+
self._transforms[:, 1, 0] = widths * sin_angle
|
| 1753 |
+
self._transforms[:, 1, 1] = heights * cos_angle
|
| 1754 |
+
self._transforms[:, 2, 2] = 1.0
|
| 1755 |
+
|
| 1756 |
+
_affine = transforms.Affine2D
|
| 1757 |
+
if self._units == 'xy':
|
| 1758 |
+
m = ax.transData.get_affine().get_matrix().copy()
|
| 1759 |
+
m[:2, 2:] = 0
|
| 1760 |
+
self.set_transform(_affine(m))
|
| 1761 |
+
|
| 1762 |
+
@artist.allow_rasterization
|
| 1763 |
+
def draw(self, renderer):
|
| 1764 |
+
self._set_transforms()
|
| 1765 |
+
super().draw(renderer)
|
| 1766 |
+
|
| 1767 |
+
|
| 1768 |
+
class PatchCollection(Collection):
|
| 1769 |
+
"""
|
| 1770 |
+
A generic collection of patches.
|
| 1771 |
+
|
| 1772 |
+
PatchCollection draws faster than a large number of equivalent individual
|
| 1773 |
+
Patches. It also makes it easier to assign a colormap to a heterogeneous
|
| 1774 |
+
collection of patches.
|
| 1775 |
+
"""
|
| 1776 |
+
|
| 1777 |
+
@_api.make_keyword_only("3.6", name="match_original")
|
| 1778 |
+
def __init__(self, patches, match_original=False, **kwargs):
|
| 1779 |
+
"""
|
| 1780 |
+
Parameters
|
| 1781 |
+
----------
|
| 1782 |
+
patches : list of `.Patch`
|
| 1783 |
+
A sequence of Patch objects. This list may include
|
| 1784 |
+
a heterogeneous assortment of different patch types.
|
| 1785 |
+
|
| 1786 |
+
match_original : bool, default: False
|
| 1787 |
+
If True, use the colors and linewidths of the original
|
| 1788 |
+
patches. If False, new colors may be assigned by
|
| 1789 |
+
providing the standard collection arguments, facecolor,
|
| 1790 |
+
edgecolor, linewidths, norm or cmap.
|
| 1791 |
+
|
| 1792 |
+
**kwargs
|
| 1793 |
+
All other parameters are forwarded to `.Collection`.
|
| 1794 |
+
|
| 1795 |
+
If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
|
| 1796 |
+
are None, they default to their `.rcParams` patch setting, in
|
| 1797 |
+
sequence form.
|
| 1798 |
+
|
| 1799 |
+
Notes
|
| 1800 |
+
-----
|
| 1801 |
+
The use of `~matplotlib.cm.ScalarMappable` functionality is optional.
|
| 1802 |
+
If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via
|
| 1803 |
+
a call to `~.ScalarMappable.set_array`), at draw time a call to scalar
|
| 1804 |
+
mappable will be made to set the face colors.
|
| 1805 |
+
"""
|
| 1806 |
+
|
| 1807 |
+
if match_original:
|
| 1808 |
+
def determine_facecolor(patch):
|
| 1809 |
+
if patch.get_fill():
|
| 1810 |
+
return patch.get_facecolor()
|
| 1811 |
+
return [0, 0, 0, 0]
|
| 1812 |
+
|
| 1813 |
+
kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
|
| 1814 |
+
kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
|
| 1815 |
+
kwargs['linewidths'] = [p.get_linewidth() for p in patches]
|
| 1816 |
+
kwargs['linestyles'] = [p.get_linestyle() for p in patches]
|
| 1817 |
+
kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]
|
| 1818 |
+
|
| 1819 |
+
super().__init__(**kwargs)
|
| 1820 |
+
|
| 1821 |
+
self.set_paths(patches)
|
| 1822 |
+
|
| 1823 |
+
def set_paths(self, patches):
|
| 1824 |
+
paths = [p.get_transform().transform_path(p.get_path())
|
| 1825 |
+
for p in patches]
|
| 1826 |
+
self._paths = paths
|
| 1827 |
+
|
| 1828 |
+
|
| 1829 |
+
class TriMesh(Collection):
|
| 1830 |
+
"""
|
| 1831 |
+
Class for the efficient drawing of a triangular mesh using Gouraud shading.
|
| 1832 |
+
|
| 1833 |
+
A triangular mesh is a `~matplotlib.tri.Triangulation` object.
|
| 1834 |
+
"""
|
| 1835 |
+
def __init__(self, triangulation, **kwargs):
|
| 1836 |
+
super().__init__(**kwargs)
|
| 1837 |
+
self._triangulation = triangulation
|
| 1838 |
+
self._shading = 'gouraud'
|
| 1839 |
+
|
| 1840 |
+
self._bbox = transforms.Bbox.unit()
|
| 1841 |
+
|
| 1842 |
+
# Unfortunately this requires a copy, unless Triangulation
|
| 1843 |
+
# was rewritten.
|
| 1844 |
+
xy = np.hstack((triangulation.x.reshape(-1, 1),
|
| 1845 |
+
triangulation.y.reshape(-1, 1)))
|
| 1846 |
+
self._bbox.update_from_data_xy(xy)
|
| 1847 |
+
|
| 1848 |
+
def get_paths(self):
|
| 1849 |
+
if self._paths is None:
|
| 1850 |
+
self.set_paths()
|
| 1851 |
+
return self._paths
|
| 1852 |
+
|
| 1853 |
+
def set_paths(self):
|
| 1854 |
+
self._paths = self.convert_mesh_to_paths(self._triangulation)
|
| 1855 |
+
|
| 1856 |
+
@staticmethod
|
| 1857 |
+
def convert_mesh_to_paths(tri):
|
| 1858 |
+
"""
|
| 1859 |
+
Convert a given mesh into a sequence of `.Path` objects.
|
| 1860 |
+
|
| 1861 |
+
This function is primarily of use to implementers of backends that do
|
| 1862 |
+
not directly support meshes.
|
| 1863 |
+
"""
|
| 1864 |
+
triangles = tri.get_masked_triangles()
|
| 1865 |
+
verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
|
| 1866 |
+
return [mpath.Path(x) for x in verts]
|
| 1867 |
+
|
| 1868 |
+
@artist.allow_rasterization
|
| 1869 |
+
def draw(self, renderer):
|
| 1870 |
+
if not self.get_visible():
|
| 1871 |
+
return
|
| 1872 |
+
renderer.open_group(self.__class__.__name__, gid=self.get_gid())
|
| 1873 |
+
transform = self.get_transform()
|
| 1874 |
+
|
| 1875 |
+
# Get a list of triangles and the color at each vertex.
|
| 1876 |
+
tri = self._triangulation
|
| 1877 |
+
triangles = tri.get_masked_triangles()
|
| 1878 |
+
|
| 1879 |
+
verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
|
| 1880 |
+
|
| 1881 |
+
self.update_scalarmappable()
|
| 1882 |
+
colors = self._facecolors[triangles]
|
| 1883 |
+
|
| 1884 |
+
gc = renderer.new_gc()
|
| 1885 |
+
self._set_gc_clip(gc)
|
| 1886 |
+
gc.set_linewidth(self.get_linewidth()[0])
|
| 1887 |
+
renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
|
| 1888 |
+
gc.restore()
|
| 1889 |
+
renderer.close_group(self.__class__.__name__)
|
| 1890 |
+
|
| 1891 |
+
|
| 1892 |
+
class QuadMesh(Collection):
|
| 1893 |
+
r"""
|
| 1894 |
+
Class for the efficient drawing of a quadrilateral mesh.
|
| 1895 |
+
|
| 1896 |
+
A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
|
| 1897 |
+
defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
|
| 1898 |
+
defined by the vertices ::
|
| 1899 |
+
|
| 1900 |
+
(m+1, n) ----------- (m+1, n+1)
|
| 1901 |
+
/ /
|
| 1902 |
+
/ /
|
| 1903 |
+
/ /
|
| 1904 |
+
(m, n) -------- (m, n+1)
|
| 1905 |
+
|
| 1906 |
+
The mesh need not be regular and the polygons need not be convex.
|
| 1907 |
+
|
| 1908 |
+
Parameters
|
| 1909 |
+
----------
|
| 1910 |
+
coordinates : (M+1, N+1, 2) array-like
|
| 1911 |
+
The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
|
| 1912 |
+
of vertex (m, n).
|
| 1913 |
+
|
| 1914 |
+
antialiased : bool, default: True
|
| 1915 |
+
|
| 1916 |
+
shading : {'flat', 'gouraud'}, default: 'flat'
|
| 1917 |
+
|
| 1918 |
+
Notes
|
| 1919 |
+
-----
|
| 1920 |
+
Unlike other `.Collection`\s, the default *pickradius* of `.QuadMesh` is 0,
|
| 1921 |
+
i.e. `~.Artist.contains` checks whether the test point is within any of the
|
| 1922 |
+
mesh quadrilaterals.
|
| 1923 |
+
|
| 1924 |
+
"""
|
| 1925 |
+
|
| 1926 |
+
def __init__(self, coordinates, *, antialiased=True, shading='flat',
|
| 1927 |
+
**kwargs):
|
| 1928 |
+
kwargs.setdefault("pickradius", 0)
|
| 1929 |
+
# end of signature deprecation code
|
| 1930 |
+
|
| 1931 |
+
_api.check_shape((None, None, 2), coordinates=coordinates)
|
| 1932 |
+
self._coordinates = coordinates
|
| 1933 |
+
self._antialiased = antialiased
|
| 1934 |
+
self._shading = shading
|
| 1935 |
+
self._bbox = transforms.Bbox.unit()
|
| 1936 |
+
self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2))
|
| 1937 |
+
# super init delayed after own init because array kwarg requires
|
| 1938 |
+
# self._coordinates and self._shading
|
| 1939 |
+
super().__init__(**kwargs)
|
| 1940 |
+
self.set_mouseover(False)
|
| 1941 |
+
|
| 1942 |
+
def get_paths(self):
|
| 1943 |
+
if self._paths is None:
|
| 1944 |
+
self.set_paths()
|
| 1945 |
+
return self._paths
|
| 1946 |
+
|
| 1947 |
+
def set_paths(self):
|
| 1948 |
+
self._paths = self._convert_mesh_to_paths(self._coordinates)
|
| 1949 |
+
self.stale = True
|
| 1950 |
+
|
| 1951 |
+
def set_array(self, A):
|
| 1952 |
+
"""
|
| 1953 |
+
Set the data values.
|
| 1954 |
+
|
| 1955 |
+
Parameters
|
| 1956 |
+
----------
|
| 1957 |
+
A : array-like
|
| 1958 |
+
The mesh data. Supported array shapes are:
|
| 1959 |
+
|
| 1960 |
+
- (M, N) or (M*N,): a mesh with scalar data. The values are mapped
|
| 1961 |
+
to colors using normalization and a colormap. See parameters
|
| 1962 |
+
*norm*, *cmap*, *vmin*, *vmax*.
|
| 1963 |
+
- (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
|
| 1964 |
+
- (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
|
| 1965 |
+
i.e. including transparency.
|
| 1966 |
+
|
| 1967 |
+
If the values are provided as a 2D grid, the shape must match the
|
| 1968 |
+
coordinates grid. If the values are 1D, they are reshaped to 2D.
|
| 1969 |
+
M, N follow from the coordinates grid, where the coordinates grid
|
| 1970 |
+
shape is (M, N) for 'gouraud' *shading* and (M+1, N+1) for 'flat'
|
| 1971 |
+
shading.
|
| 1972 |
+
"""
|
| 1973 |
+
height, width = self._coordinates.shape[0:-1]
|
| 1974 |
+
if self._shading == 'flat':
|
| 1975 |
+
h, w = height - 1, width - 1
|
| 1976 |
+
else:
|
| 1977 |
+
h, w = height, width
|
| 1978 |
+
ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)]
|
| 1979 |
+
if A is not None:
|
| 1980 |
+
shape = np.shape(A)
|
| 1981 |
+
if shape not in ok_shapes:
|
| 1982 |
+
raise ValueError(
|
| 1983 |
+
f"For X ({width}) and Y ({height}) with {self._shading} "
|
| 1984 |
+
f"shading, A should have shape "
|
| 1985 |
+
f"{' or '.join(map(str, ok_shapes))}, not {A.shape}")
|
| 1986 |
+
return super().set_array(A)
|
| 1987 |
+
|
| 1988 |
+
def get_datalim(self, transData):
|
| 1989 |
+
return (self.get_transform() - transData).transform_bbox(self._bbox)
|
| 1990 |
+
|
| 1991 |
+
def get_coordinates(self):
|
| 1992 |
+
"""
|
| 1993 |
+
Return the vertices of the mesh as an (M+1, N+1, 2) array.
|
| 1994 |
+
|
| 1995 |
+
M, N are the number of quadrilaterals in the rows / columns of the
|
| 1996 |
+
mesh, corresponding to (M+1, N+1) vertices.
|
| 1997 |
+
The last dimension specifies the components (x, y).
|
| 1998 |
+
"""
|
| 1999 |
+
return self._coordinates
|
| 2000 |
+
|
| 2001 |
+
@staticmethod
|
| 2002 |
+
def _convert_mesh_to_paths(coordinates):
|
| 2003 |
+
"""
|
| 2004 |
+
Convert a given mesh into a sequence of `.Path` objects.
|
| 2005 |
+
|
| 2006 |
+
This function is primarily of use to implementers of backends that do
|
| 2007 |
+
not directly support quadmeshes.
|
| 2008 |
+
"""
|
| 2009 |
+
if isinstance(coordinates, np.ma.MaskedArray):
|
| 2010 |
+
c = coordinates.data
|
| 2011 |
+
else:
|
| 2012 |
+
c = coordinates
|
| 2013 |
+
points = np.concatenate([
|
| 2014 |
+
c[:-1, :-1],
|
| 2015 |
+
c[:-1, 1:],
|
| 2016 |
+
c[1:, 1:],
|
| 2017 |
+
c[1:, :-1],
|
| 2018 |
+
c[:-1, :-1]
|
| 2019 |
+
], axis=2).reshape((-1, 5, 2))
|
| 2020 |
+
return [mpath.Path(x) for x in points]
|
| 2021 |
+
|
| 2022 |
+
def _convert_mesh_to_triangles(self, coordinates):
|
| 2023 |
+
"""
|
| 2024 |
+
Convert a given mesh into a sequence of triangles, each point
|
| 2025 |
+
with its own color. The result can be used to construct a call to
|
| 2026 |
+
`~.RendererBase.draw_gouraud_triangles`.
|
| 2027 |
+
"""
|
| 2028 |
+
if isinstance(coordinates, np.ma.MaskedArray):
|
| 2029 |
+
p = coordinates.data
|
| 2030 |
+
else:
|
| 2031 |
+
p = coordinates
|
| 2032 |
+
|
| 2033 |
+
p_a = p[:-1, :-1]
|
| 2034 |
+
p_b = p[:-1, 1:]
|
| 2035 |
+
p_c = p[1:, 1:]
|
| 2036 |
+
p_d = p[1:, :-1]
|
| 2037 |
+
p_center = (p_a + p_b + p_c + p_d) / 4.0
|
| 2038 |
+
triangles = np.concatenate([
|
| 2039 |
+
p_a, p_b, p_center,
|
| 2040 |
+
p_b, p_c, p_center,
|
| 2041 |
+
p_c, p_d, p_center,
|
| 2042 |
+
p_d, p_a, p_center,
|
| 2043 |
+
], axis=2).reshape((-1, 3, 2))
|
| 2044 |
+
|
| 2045 |
+
c = self.get_facecolor().reshape((*coordinates.shape[:2], 4))
|
| 2046 |
+
c_a = c[:-1, :-1]
|
| 2047 |
+
c_b = c[:-1, 1:]
|
| 2048 |
+
c_c = c[1:, 1:]
|
| 2049 |
+
c_d = c[1:, :-1]
|
| 2050 |
+
c_center = (c_a + c_b + c_c + c_d) / 4.0
|
| 2051 |
+
colors = np.concatenate([
|
| 2052 |
+
c_a, c_b, c_center,
|
| 2053 |
+
c_b, c_c, c_center,
|
| 2054 |
+
c_c, c_d, c_center,
|
| 2055 |
+
c_d, c_a, c_center,
|
| 2056 |
+
], axis=2).reshape((-1, 3, 4))
|
| 2057 |
+
|
| 2058 |
+
return triangles, colors
|
| 2059 |
+
|
| 2060 |
+
@artist.allow_rasterization
|
| 2061 |
+
def draw(self, renderer):
|
| 2062 |
+
if not self.get_visible():
|
| 2063 |
+
return
|
| 2064 |
+
renderer.open_group(self.__class__.__name__, self.get_gid())
|
| 2065 |
+
transform = self.get_transform()
|
| 2066 |
+
offset_trf = self.get_offset_transform()
|
| 2067 |
+
offsets = self.get_offsets()
|
| 2068 |
+
|
| 2069 |
+
if self.have_units():
|
| 2070 |
+
xs = self.convert_xunits(offsets[:, 0])
|
| 2071 |
+
ys = self.convert_yunits(offsets[:, 1])
|
| 2072 |
+
offsets = np.column_stack([xs, ys])
|
| 2073 |
+
|
| 2074 |
+
self.update_scalarmappable()
|
| 2075 |
+
|
| 2076 |
+
if not transform.is_affine:
|
| 2077 |
+
coordinates = self._coordinates.reshape((-1, 2))
|
| 2078 |
+
coordinates = transform.transform(coordinates)
|
| 2079 |
+
coordinates = coordinates.reshape(self._coordinates.shape)
|
| 2080 |
+
transform = transforms.IdentityTransform()
|
| 2081 |
+
else:
|
| 2082 |
+
coordinates = self._coordinates
|
| 2083 |
+
|
| 2084 |
+
if not offset_trf.is_affine:
|
| 2085 |
+
offsets = offset_trf.transform_non_affine(offsets)
|
| 2086 |
+
offset_trf = offset_trf.get_affine()
|
| 2087 |
+
|
| 2088 |
+
gc = renderer.new_gc()
|
| 2089 |
+
gc.set_snap(self.get_snap())
|
| 2090 |
+
self._set_gc_clip(gc)
|
| 2091 |
+
gc.set_linewidth(self.get_linewidth()[0])
|
| 2092 |
+
|
| 2093 |
+
if self._shading == 'gouraud':
|
| 2094 |
+
triangles, colors = self._convert_mesh_to_triangles(coordinates)
|
| 2095 |
+
renderer.draw_gouraud_triangles(
|
| 2096 |
+
gc, triangles, colors, transform.frozen())
|
| 2097 |
+
else:
|
| 2098 |
+
renderer.draw_quad_mesh(
|
| 2099 |
+
gc, transform.frozen(),
|
| 2100 |
+
coordinates.shape[1] - 1, coordinates.shape[0] - 1,
|
| 2101 |
+
coordinates, offsets, offset_trf,
|
| 2102 |
+
# Backends expect flattened rgba arrays (n*m, 4) for fc and ec
|
| 2103 |
+
self.get_facecolor().reshape((-1, 4)),
|
| 2104 |
+
self._antialiased, self.get_edgecolors().reshape((-1, 4)))
|
| 2105 |
+
gc.restore()
|
| 2106 |
+
renderer.close_group(self.__class__.__name__)
|
| 2107 |
+
self.stale = False
|
| 2108 |
+
|
| 2109 |
+
def get_cursor_data(self, event):
|
| 2110 |
+
contained, info = self.contains(event)
|
| 2111 |
+
if contained and self.get_array() is not None:
|
| 2112 |
+
return self.get_array().ravel()[info["ind"]]
|
| 2113 |
+
return None
|
omnilmm/lib/python3.10/site-packages/matplotlib/docstring.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib._docstring import * # noqa: F401, F403
|
| 2 |
+
from matplotlib import _api
|
| 3 |
+
_api.warn_deprecated(
|
| 4 |
+
"3.6", obj_type='module', name=f"{__name__}")
|
omnilmm/lib/python3.10/site-packages/matplotlib/font_manager.py
ADDED
|
@@ -0,0 +1,1553 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A module for finding, managing, and using fonts across platforms.
|
| 3 |
+
|
| 4 |
+
This module provides a single `FontManager` instance, ``fontManager``, that can
|
| 5 |
+
be shared across backends and platforms. The `findfont`
|
| 6 |
+
function returns the best TrueType (TTF) font file in the local or
|
| 7 |
+
system font path that matches the specified `FontProperties`
|
| 8 |
+
instance. The `FontManager` also handles Adobe Font Metrics
|
| 9 |
+
(AFM) font files for use by the PostScript backend.
|
| 10 |
+
|
| 11 |
+
The design is based on the `W3C Cascading Style Sheet, Level 1 (CSS1)
|
| 12 |
+
font specification <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_.
|
| 13 |
+
Future versions may implement the Level 2 or 2.1 specifications.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
# KNOWN ISSUES
|
| 17 |
+
#
|
| 18 |
+
# - documentation
|
| 19 |
+
# - font variant is untested
|
| 20 |
+
# - font stretch is incomplete
|
| 21 |
+
# - font size is incomplete
|
| 22 |
+
# - default font algorithm needs improvement and testing
|
| 23 |
+
# - setWeights function needs improvement
|
| 24 |
+
# - 'light' is an invalid weight value, remove it.
|
| 25 |
+
|
| 26 |
+
from base64 import b64encode
|
| 27 |
+
from collections import namedtuple
|
| 28 |
+
import copy
|
| 29 |
+
import dataclasses
|
| 30 |
+
from functools import lru_cache
|
| 31 |
+
from io import BytesIO
|
| 32 |
+
import json
|
| 33 |
+
import logging
|
| 34 |
+
from numbers import Number
|
| 35 |
+
import os
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
import re
|
| 38 |
+
import subprocess
|
| 39 |
+
import sys
|
| 40 |
+
import threading
|
| 41 |
+
|
| 42 |
+
import matplotlib as mpl
|
| 43 |
+
from matplotlib import _api, _afm, cbook, ft2font
|
| 44 |
+
from matplotlib._fontconfig_pattern import (
|
| 45 |
+
parse_fontconfig_pattern, generate_fontconfig_pattern)
|
| 46 |
+
from matplotlib.rcsetup import _validators
|
| 47 |
+
|
| 48 |
+
_log = logging.getLogger(__name__)
|
| 49 |
+
|
| 50 |
+
font_scalings = {
|
| 51 |
+
'xx-small': 0.579,
|
| 52 |
+
'x-small': 0.694,
|
| 53 |
+
'small': 0.833,
|
| 54 |
+
'medium': 1.0,
|
| 55 |
+
'large': 1.200,
|
| 56 |
+
'x-large': 1.440,
|
| 57 |
+
'xx-large': 1.728,
|
| 58 |
+
'larger': 1.2,
|
| 59 |
+
'smaller': 0.833,
|
| 60 |
+
None: 1.0,
|
| 61 |
+
}
|
| 62 |
+
stretch_dict = {
|
| 63 |
+
'ultra-condensed': 100,
|
| 64 |
+
'extra-condensed': 200,
|
| 65 |
+
'condensed': 300,
|
| 66 |
+
'semi-condensed': 400,
|
| 67 |
+
'normal': 500,
|
| 68 |
+
'semi-expanded': 600,
|
| 69 |
+
'semi-extended': 600,
|
| 70 |
+
'expanded': 700,
|
| 71 |
+
'extended': 700,
|
| 72 |
+
'extra-expanded': 800,
|
| 73 |
+
'extra-extended': 800,
|
| 74 |
+
'ultra-expanded': 900,
|
| 75 |
+
'ultra-extended': 900,
|
| 76 |
+
}
|
| 77 |
+
weight_dict = {
|
| 78 |
+
'ultralight': 100,
|
| 79 |
+
'light': 200,
|
| 80 |
+
'normal': 400,
|
| 81 |
+
'regular': 400,
|
| 82 |
+
'book': 400,
|
| 83 |
+
'medium': 500,
|
| 84 |
+
'roman': 500,
|
| 85 |
+
'semibold': 600,
|
| 86 |
+
'demibold': 600,
|
| 87 |
+
'demi': 600,
|
| 88 |
+
'bold': 700,
|
| 89 |
+
'heavy': 800,
|
| 90 |
+
'extra bold': 800,
|
| 91 |
+
'black': 900,
|
| 92 |
+
}
|
| 93 |
+
_weight_regexes = [
|
| 94 |
+
# From fontconfig's FcFreeTypeQueryFaceInternal; not the same as
|
| 95 |
+
# weight_dict!
|
| 96 |
+
("thin", 100),
|
| 97 |
+
("extralight", 200),
|
| 98 |
+
("ultralight", 200),
|
| 99 |
+
("demilight", 350),
|
| 100 |
+
("semilight", 350),
|
| 101 |
+
("light", 300), # Needs to come *after* demi/semilight!
|
| 102 |
+
("book", 380),
|
| 103 |
+
("regular", 400),
|
| 104 |
+
("normal", 400),
|
| 105 |
+
("medium", 500),
|
| 106 |
+
("demibold", 600),
|
| 107 |
+
("demi", 600),
|
| 108 |
+
("semibold", 600),
|
| 109 |
+
("extrabold", 800),
|
| 110 |
+
("superbold", 800),
|
| 111 |
+
("ultrabold", 800),
|
| 112 |
+
("bold", 700), # Needs to come *after* extra/super/ultrabold!
|
| 113 |
+
("ultrablack", 1000),
|
| 114 |
+
("superblack", 1000),
|
| 115 |
+
("extrablack", 1000),
|
| 116 |
+
(r"\bultra", 1000),
|
| 117 |
+
("black", 900), # Needs to come *after* ultra/super/extrablack!
|
| 118 |
+
("heavy", 900),
|
| 119 |
+
]
|
| 120 |
+
font_family_aliases = {
|
| 121 |
+
'serif',
|
| 122 |
+
'sans-serif',
|
| 123 |
+
'sans serif',
|
| 124 |
+
'cursive',
|
| 125 |
+
'fantasy',
|
| 126 |
+
'monospace',
|
| 127 |
+
'sans',
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
_ExceptionProxy = namedtuple('_ExceptionProxy', ['klass', 'message'])
|
| 131 |
+
|
| 132 |
+
# OS Font paths
|
| 133 |
+
try:
|
| 134 |
+
_HOME = Path.home()
|
| 135 |
+
except Exception: # Exceptions thrown by home() are not specified...
|
| 136 |
+
_HOME = Path(os.devnull) # Just an arbitrary path with no children.
|
| 137 |
+
MSFolders = \
|
| 138 |
+
r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
|
| 139 |
+
MSFontDirectories = [
|
| 140 |
+
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',
|
| 141 |
+
r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts']
|
| 142 |
+
MSUserFontDirectories = [
|
| 143 |
+
str(_HOME / 'AppData/Local/Microsoft/Windows/Fonts'),
|
| 144 |
+
str(_HOME / 'AppData/Roaming/Microsoft/Windows/Fonts'),
|
| 145 |
+
]
|
| 146 |
+
X11FontDirectories = [
|
| 147 |
+
# an old standard installation point
|
| 148 |
+
"/usr/X11R6/lib/X11/fonts/TTF/",
|
| 149 |
+
"/usr/X11/lib/X11/fonts",
|
| 150 |
+
# here is the new standard location for fonts
|
| 151 |
+
"/usr/share/fonts/",
|
| 152 |
+
# documented as a good place to install new fonts
|
| 153 |
+
"/usr/local/share/fonts/",
|
| 154 |
+
# common application, not really useful
|
| 155 |
+
"/usr/lib/openoffice/share/fonts/truetype/",
|
| 156 |
+
# user fonts
|
| 157 |
+
str((Path(os.environ.get('XDG_DATA_HOME') or _HOME / ".local/share"))
|
| 158 |
+
/ "fonts"),
|
| 159 |
+
str(_HOME / ".fonts"),
|
| 160 |
+
]
|
| 161 |
+
OSXFontDirectories = [
|
| 162 |
+
"/Library/Fonts/",
|
| 163 |
+
"/Network/Library/Fonts/",
|
| 164 |
+
"/System/Library/Fonts/",
|
| 165 |
+
# fonts installed via MacPorts
|
| 166 |
+
"/opt/local/share/fonts",
|
| 167 |
+
# user fonts
|
| 168 |
+
str(_HOME / "Library/Fonts"),
|
| 169 |
+
]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_fontext_synonyms(fontext):
|
| 173 |
+
"""
|
| 174 |
+
Return a list of file extensions that are synonyms for
|
| 175 |
+
the given file extension *fileext*.
|
| 176 |
+
"""
|
| 177 |
+
return {
|
| 178 |
+
'afm': ['afm'],
|
| 179 |
+
'otf': ['otf', 'ttc', 'ttf'],
|
| 180 |
+
'ttc': ['otf', 'ttc', 'ttf'],
|
| 181 |
+
'ttf': ['otf', 'ttc', 'ttf'],
|
| 182 |
+
}[fontext]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def list_fonts(directory, extensions):
|
| 186 |
+
"""
|
| 187 |
+
Return a list of all fonts matching any of the extensions, found
|
| 188 |
+
recursively under the directory.
|
| 189 |
+
"""
|
| 190 |
+
extensions = ["." + ext for ext in extensions]
|
| 191 |
+
return [os.path.join(dirpath, filename)
|
| 192 |
+
# os.walk ignores access errors, unlike Path.glob.
|
| 193 |
+
for dirpath, _, filenames in os.walk(directory)
|
| 194 |
+
for filename in filenames
|
| 195 |
+
if Path(filename).suffix.lower() in extensions]
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def win32FontDirectory():
|
| 199 |
+
r"""
|
| 200 |
+
Return the user-specified font directory for Win32. This is
|
| 201 |
+
looked up from the registry key ::
|
| 202 |
+
|
| 203 |
+
\\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
|
| 204 |
+
|
| 205 |
+
If the key is not found, ``%WINDIR%\Fonts`` will be returned.
|
| 206 |
+
"""
|
| 207 |
+
import winreg
|
| 208 |
+
try:
|
| 209 |
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user:
|
| 210 |
+
return winreg.QueryValueEx(user, 'Fonts')[0]
|
| 211 |
+
except OSError:
|
| 212 |
+
return os.path.join(os.environ['WINDIR'], 'Fonts')
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _get_win32_installed_fonts():
|
| 216 |
+
"""List the font paths known to the Windows registry."""
|
| 217 |
+
import winreg
|
| 218 |
+
items = set()
|
| 219 |
+
# Search and resolve fonts listed in the registry.
|
| 220 |
+
for domain, base_dirs in [
|
| 221 |
+
(winreg.HKEY_LOCAL_MACHINE, [win32FontDirectory()]), # System.
|
| 222 |
+
(winreg.HKEY_CURRENT_USER, MSUserFontDirectories), # User.
|
| 223 |
+
]:
|
| 224 |
+
for base_dir in base_dirs:
|
| 225 |
+
for reg_path in MSFontDirectories:
|
| 226 |
+
try:
|
| 227 |
+
with winreg.OpenKey(domain, reg_path) as local:
|
| 228 |
+
for j in range(winreg.QueryInfoKey(local)[1]):
|
| 229 |
+
# value may contain the filename of the font or its
|
| 230 |
+
# absolute path.
|
| 231 |
+
key, value, tp = winreg.EnumValue(local, j)
|
| 232 |
+
if not isinstance(value, str):
|
| 233 |
+
continue
|
| 234 |
+
try:
|
| 235 |
+
# If value contains already an absolute path,
|
| 236 |
+
# then it is not changed further.
|
| 237 |
+
path = Path(base_dir, value).resolve()
|
| 238 |
+
except RuntimeError:
|
| 239 |
+
# Don't fail with invalid entries.
|
| 240 |
+
continue
|
| 241 |
+
items.add(path)
|
| 242 |
+
except (OSError, MemoryError):
|
| 243 |
+
continue
|
| 244 |
+
return items
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@lru_cache()
|
| 248 |
+
def _get_fontconfig_fonts():
|
| 249 |
+
"""Cache and list the font paths known to ``fc-list``."""
|
| 250 |
+
try:
|
| 251 |
+
if b'--format' not in subprocess.check_output(['fc-list', '--help']):
|
| 252 |
+
_log.warning( # fontconfig 2.7 implemented --format.
|
| 253 |
+
'Matplotlib needs fontconfig>=2.7 to query system fonts.')
|
| 254 |
+
return []
|
| 255 |
+
out = subprocess.check_output(['fc-list', '--format=%{file}\\n'])
|
| 256 |
+
except (OSError, subprocess.CalledProcessError):
|
| 257 |
+
return []
|
| 258 |
+
return [Path(os.fsdecode(fname)) for fname in out.split(b'\n')]
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def findSystemFonts(fontpaths=None, fontext='ttf'):
|
| 262 |
+
"""
|
| 263 |
+
Search for fonts in the specified font paths. If no paths are
|
| 264 |
+
given, will use a standard set of system paths, as well as the
|
| 265 |
+
list of fonts tracked by fontconfig if fontconfig is installed and
|
| 266 |
+
available. A list of TrueType fonts are returned by default with
|
| 267 |
+
AFM fonts as an option.
|
| 268 |
+
"""
|
| 269 |
+
fontfiles = set()
|
| 270 |
+
fontexts = get_fontext_synonyms(fontext)
|
| 271 |
+
|
| 272 |
+
if fontpaths is None:
|
| 273 |
+
if sys.platform == 'win32':
|
| 274 |
+
installed_fonts = _get_win32_installed_fonts()
|
| 275 |
+
fontpaths = []
|
| 276 |
+
else:
|
| 277 |
+
installed_fonts = _get_fontconfig_fonts()
|
| 278 |
+
if sys.platform == 'darwin':
|
| 279 |
+
fontpaths = [*X11FontDirectories, *OSXFontDirectories]
|
| 280 |
+
else:
|
| 281 |
+
fontpaths = X11FontDirectories
|
| 282 |
+
fontfiles.update(str(path) for path in installed_fonts
|
| 283 |
+
if path.suffix.lower()[1:] in fontexts)
|
| 284 |
+
|
| 285 |
+
elif isinstance(fontpaths, str):
|
| 286 |
+
fontpaths = [fontpaths]
|
| 287 |
+
|
| 288 |
+
for path in fontpaths:
|
| 289 |
+
fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts)))
|
| 290 |
+
|
| 291 |
+
return [fname for fname in fontfiles if os.path.exists(fname)]
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _fontentry_helper_repr_png(fontent):
|
| 295 |
+
from matplotlib.figure import Figure # Circular import.
|
| 296 |
+
fig = Figure()
|
| 297 |
+
font_path = Path(fontent.fname) if fontent.fname != '' else None
|
| 298 |
+
fig.text(0, 0, fontent.name, font=font_path)
|
| 299 |
+
with BytesIO() as buf:
|
| 300 |
+
fig.savefig(buf, bbox_inches='tight', transparent=True)
|
| 301 |
+
return buf.getvalue()
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _fontentry_helper_repr_html(fontent):
|
| 305 |
+
png_stream = _fontentry_helper_repr_png(fontent)
|
| 306 |
+
png_b64 = b64encode(png_stream).decode()
|
| 307 |
+
return f"<img src=\"data:image/png;base64, {png_b64}\" />"
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
FontEntry = dataclasses.make_dataclass(
|
| 311 |
+
'FontEntry', [
|
| 312 |
+
('fname', str, dataclasses.field(default='')),
|
| 313 |
+
('name', str, dataclasses.field(default='')),
|
| 314 |
+
('style', str, dataclasses.field(default='normal')),
|
| 315 |
+
('variant', str, dataclasses.field(default='normal')),
|
| 316 |
+
('weight', str, dataclasses.field(default='normal')),
|
| 317 |
+
('stretch', str, dataclasses.field(default='normal')),
|
| 318 |
+
('size', str, dataclasses.field(default='medium')),
|
| 319 |
+
],
|
| 320 |
+
namespace={
|
| 321 |
+
'__doc__': """
|
| 322 |
+
A class for storing Font properties.
|
| 323 |
+
|
| 324 |
+
It is used when populating the font lookup dictionary.
|
| 325 |
+
""",
|
| 326 |
+
'_repr_html_': lambda self: _fontentry_helper_repr_html(self),
|
| 327 |
+
'_repr_png_': lambda self: _fontentry_helper_repr_png(self),
|
| 328 |
+
}
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def ttfFontProperty(font):
|
| 333 |
+
"""
|
| 334 |
+
Extract information from a TrueType font file.
|
| 335 |
+
|
| 336 |
+
Parameters
|
| 337 |
+
----------
|
| 338 |
+
font : `.FT2Font`
|
| 339 |
+
The TrueType font file from which information will be extracted.
|
| 340 |
+
|
| 341 |
+
Returns
|
| 342 |
+
-------
|
| 343 |
+
`FontEntry`
|
| 344 |
+
The extracted font properties.
|
| 345 |
+
|
| 346 |
+
"""
|
| 347 |
+
name = font.family_name
|
| 348 |
+
|
| 349 |
+
# Styles are: italic, oblique, and normal (default)
|
| 350 |
+
|
| 351 |
+
sfnt = font.get_sfnt()
|
| 352 |
+
mac_key = (1, # platform: macintosh
|
| 353 |
+
0, # id: roman
|
| 354 |
+
0) # langid: english
|
| 355 |
+
ms_key = (3, # platform: microsoft
|
| 356 |
+
1, # id: unicode_cs
|
| 357 |
+
0x0409) # langid: english_united_states
|
| 358 |
+
|
| 359 |
+
# These tables are actually mac_roman-encoded, but mac_roman support may be
|
| 360 |
+
# missing in some alternative Python implementations and we are only going
|
| 361 |
+
# to look for ASCII substrings, where any ASCII-compatible encoding works
|
| 362 |
+
# - or big-endian UTF-16, since important Microsoft fonts use that.
|
| 363 |
+
sfnt2 = (sfnt.get((*mac_key, 2), b'').decode('latin-1').lower() or
|
| 364 |
+
sfnt.get((*ms_key, 2), b'').decode('utf_16_be').lower())
|
| 365 |
+
sfnt4 = (sfnt.get((*mac_key, 4), b'').decode('latin-1').lower() or
|
| 366 |
+
sfnt.get((*ms_key, 4), b'').decode('utf_16_be').lower())
|
| 367 |
+
|
| 368 |
+
if sfnt4.find('oblique') >= 0:
|
| 369 |
+
style = 'oblique'
|
| 370 |
+
elif sfnt4.find('italic') >= 0:
|
| 371 |
+
style = 'italic'
|
| 372 |
+
elif sfnt2.find('regular') >= 0:
|
| 373 |
+
style = 'normal'
|
| 374 |
+
elif font.style_flags & ft2font.ITALIC:
|
| 375 |
+
style = 'italic'
|
| 376 |
+
else:
|
| 377 |
+
style = 'normal'
|
| 378 |
+
|
| 379 |
+
# Variants are: small-caps and normal (default)
|
| 380 |
+
|
| 381 |
+
# !!!! Untested
|
| 382 |
+
if name.lower() in ['capitals', 'small-caps']:
|
| 383 |
+
variant = 'small-caps'
|
| 384 |
+
else:
|
| 385 |
+
variant = 'normal'
|
| 386 |
+
|
| 387 |
+
# The weight-guessing algorithm is directly translated from fontconfig
|
| 388 |
+
# 2.13.1's FcFreeTypeQueryFaceInternal (fcfreetype.c).
|
| 389 |
+
wws_subfamily = 22
|
| 390 |
+
typographic_subfamily = 16
|
| 391 |
+
font_subfamily = 2
|
| 392 |
+
styles = [
|
| 393 |
+
sfnt.get((*mac_key, wws_subfamily), b'').decode('latin-1'),
|
| 394 |
+
sfnt.get((*mac_key, typographic_subfamily), b'').decode('latin-1'),
|
| 395 |
+
sfnt.get((*mac_key, font_subfamily), b'').decode('latin-1'),
|
| 396 |
+
sfnt.get((*ms_key, wws_subfamily), b'').decode('utf-16-be'),
|
| 397 |
+
sfnt.get((*ms_key, typographic_subfamily), b'').decode('utf-16-be'),
|
| 398 |
+
sfnt.get((*ms_key, font_subfamily), b'').decode('utf-16-be'),
|
| 399 |
+
]
|
| 400 |
+
styles = [*filter(None, styles)] or [font.style_name]
|
| 401 |
+
|
| 402 |
+
def get_weight(): # From fontconfig's FcFreeTypeQueryFaceInternal.
|
| 403 |
+
# OS/2 table weight.
|
| 404 |
+
os2 = font.get_sfnt_table("OS/2")
|
| 405 |
+
if os2 and os2["version"] != 0xffff:
|
| 406 |
+
return os2["usWeightClass"]
|
| 407 |
+
# PostScript font info weight.
|
| 408 |
+
try:
|
| 409 |
+
ps_font_info_weight = (
|
| 410 |
+
font.get_ps_font_info()["weight"].replace(" ", "") or "")
|
| 411 |
+
except ValueError:
|
| 412 |
+
pass
|
| 413 |
+
else:
|
| 414 |
+
for regex, weight in _weight_regexes:
|
| 415 |
+
if re.fullmatch(regex, ps_font_info_weight, re.I):
|
| 416 |
+
return weight
|
| 417 |
+
# Style name weight.
|
| 418 |
+
for style in styles:
|
| 419 |
+
style = style.replace(" ", "")
|
| 420 |
+
for regex, weight in _weight_regexes:
|
| 421 |
+
if re.search(regex, style, re.I):
|
| 422 |
+
return weight
|
| 423 |
+
if font.style_flags & ft2font.BOLD:
|
| 424 |
+
return 700 # "bold"
|
| 425 |
+
return 500 # "medium", not "regular"!
|
| 426 |
+
|
| 427 |
+
weight = int(get_weight())
|
| 428 |
+
|
| 429 |
+
# Stretch can be absolute and relative
|
| 430 |
+
# Absolute stretches are: ultra-condensed, extra-condensed, condensed,
|
| 431 |
+
# semi-condensed, normal, semi-expanded, expanded, extra-expanded,
|
| 432 |
+
# and ultra-expanded.
|
| 433 |
+
# Relative stretches are: wider, narrower
|
| 434 |
+
# Child value is: inherit
|
| 435 |
+
|
| 436 |
+
if any(word in sfnt4 for word in ['narrow', 'condensed', 'cond']):
|
| 437 |
+
stretch = 'condensed'
|
| 438 |
+
elif 'demi cond' in sfnt4:
|
| 439 |
+
stretch = 'semi-condensed'
|
| 440 |
+
elif any(word in sfnt4 for word in ['wide', 'expanded', 'extended']):
|
| 441 |
+
stretch = 'expanded'
|
| 442 |
+
else:
|
| 443 |
+
stretch = 'normal'
|
| 444 |
+
|
| 445 |
+
# Sizes can be absolute and relative.
|
| 446 |
+
# Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
|
| 447 |
+
# and xx-large.
|
| 448 |
+
# Relative sizes are: larger, smaller
|
| 449 |
+
# Length value is an absolute font size, e.g., 12pt
|
| 450 |
+
# Percentage values are in 'em's. Most robust specification.
|
| 451 |
+
|
| 452 |
+
if not font.scalable:
|
| 453 |
+
raise NotImplementedError("Non-scalable fonts are not supported")
|
| 454 |
+
size = 'scalable'
|
| 455 |
+
|
| 456 |
+
return FontEntry(font.fname, name, style, variant, weight, stretch, size)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def afmFontProperty(fontpath, font):
|
| 460 |
+
"""
|
| 461 |
+
Extract information from an AFM font file.
|
| 462 |
+
|
| 463 |
+
Parameters
|
| 464 |
+
----------
|
| 465 |
+
font : AFM
|
| 466 |
+
The AFM font file from which information will be extracted.
|
| 467 |
+
|
| 468 |
+
Returns
|
| 469 |
+
-------
|
| 470 |
+
`FontEntry`
|
| 471 |
+
The extracted font properties.
|
| 472 |
+
"""
|
| 473 |
+
|
| 474 |
+
name = font.get_familyname()
|
| 475 |
+
fontname = font.get_fontname().lower()
|
| 476 |
+
|
| 477 |
+
# Styles are: italic, oblique, and normal (default)
|
| 478 |
+
|
| 479 |
+
if font.get_angle() != 0 or 'italic' in name.lower():
|
| 480 |
+
style = 'italic'
|
| 481 |
+
elif 'oblique' in name.lower():
|
| 482 |
+
style = 'oblique'
|
| 483 |
+
else:
|
| 484 |
+
style = 'normal'
|
| 485 |
+
|
| 486 |
+
# Variants are: small-caps and normal (default)
|
| 487 |
+
|
| 488 |
+
# !!!! Untested
|
| 489 |
+
if name.lower() in ['capitals', 'small-caps']:
|
| 490 |
+
variant = 'small-caps'
|
| 491 |
+
else:
|
| 492 |
+
variant = 'normal'
|
| 493 |
+
|
| 494 |
+
weight = font.get_weight().lower()
|
| 495 |
+
if weight not in weight_dict:
|
| 496 |
+
weight = 'normal'
|
| 497 |
+
|
| 498 |
+
# Stretch can be absolute and relative
|
| 499 |
+
# Absolute stretches are: ultra-condensed, extra-condensed, condensed,
|
| 500 |
+
# semi-condensed, normal, semi-expanded, expanded, extra-expanded,
|
| 501 |
+
# and ultra-expanded.
|
| 502 |
+
# Relative stretches are: wider, narrower
|
| 503 |
+
# Child value is: inherit
|
| 504 |
+
if 'demi cond' in fontname:
|
| 505 |
+
stretch = 'semi-condensed'
|
| 506 |
+
elif any(word in fontname for word in ['narrow', 'cond']):
|
| 507 |
+
stretch = 'condensed'
|
| 508 |
+
elif any(word in fontname for word in ['wide', 'expanded', 'extended']):
|
| 509 |
+
stretch = 'expanded'
|
| 510 |
+
else:
|
| 511 |
+
stretch = 'normal'
|
| 512 |
+
|
| 513 |
+
# Sizes can be absolute and relative.
|
| 514 |
+
# Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
|
| 515 |
+
# and xx-large.
|
| 516 |
+
# Relative sizes are: larger, smaller
|
| 517 |
+
# Length value is an absolute font size, e.g., 12pt
|
| 518 |
+
# Percentage values are in 'em's. Most robust specification.
|
| 519 |
+
|
| 520 |
+
# All AFM fonts are apparently scalable.
|
| 521 |
+
|
| 522 |
+
size = 'scalable'
|
| 523 |
+
|
| 524 |
+
return FontEntry(fontpath, name, style, variant, weight, stretch, size)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class FontProperties:
|
| 528 |
+
"""
|
| 529 |
+
A class for storing and manipulating font properties.
|
| 530 |
+
|
| 531 |
+
The font properties are the six properties described in the
|
| 532 |
+
`W3C Cascading Style Sheet, Level 1
|
| 533 |
+
<http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ font
|
| 534 |
+
specification and *math_fontfamily* for math fonts:
|
| 535 |
+
|
| 536 |
+
- family: A list of font names in decreasing order of priority.
|
| 537 |
+
The items may include a generic font family name, either 'sans-serif',
|
| 538 |
+
'serif', 'cursive', 'fantasy', or 'monospace'. In that case, the actual
|
| 539 |
+
font to be used will be looked up from the associated rcParam during the
|
| 540 |
+
search process in `.findfont`. Default: :rc:`font.family`
|
| 541 |
+
|
| 542 |
+
- style: Either 'normal', 'italic' or 'oblique'.
|
| 543 |
+
Default: :rc:`font.style`
|
| 544 |
+
|
| 545 |
+
- variant: Either 'normal' or 'small-caps'.
|
| 546 |
+
Default: :rc:`font.variant`
|
| 547 |
+
|
| 548 |
+
- stretch: A numeric value in the range 0-1000 or one of
|
| 549 |
+
'ultra-condensed', 'extra-condensed', 'condensed',
|
| 550 |
+
'semi-condensed', 'normal', 'semi-expanded', 'expanded',
|
| 551 |
+
'extra-expanded' or 'ultra-expanded'. Default: :rc:`font.stretch`
|
| 552 |
+
|
| 553 |
+
- weight: A numeric value in the range 0-1000 or one of
|
| 554 |
+
'ultralight', 'light', 'normal', 'regular', 'book', 'medium',
|
| 555 |
+
'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy',
|
| 556 |
+
'extra bold', 'black'. Default: :rc:`font.weight`
|
| 557 |
+
|
| 558 |
+
- size: Either a relative value of 'xx-small', 'x-small',
|
| 559 |
+
'small', 'medium', 'large', 'x-large', 'xx-large' or an
|
| 560 |
+
absolute font size, e.g., 10. Default: :rc:`font.size`
|
| 561 |
+
|
| 562 |
+
- math_fontfamily: The family of fonts used to render math text.
|
| 563 |
+
Supported values are: 'dejavusans', 'dejavuserif', 'cm',
|
| 564 |
+
'stix', 'stixsans' and 'custom'. Default: :rc:`mathtext.fontset`
|
| 565 |
+
|
| 566 |
+
Alternatively, a font may be specified using the absolute path to a font
|
| 567 |
+
file, by using the *fname* kwarg. However, in this case, it is typically
|
| 568 |
+
simpler to just pass the path (as a `pathlib.Path`, not a `str`) to the
|
| 569 |
+
*font* kwarg of the `.Text` object.
|
| 570 |
+
|
| 571 |
+
The preferred usage of font sizes is to use the relative values,
|
| 572 |
+
e.g., 'large', instead of absolute font sizes, e.g., 12. This
|
| 573 |
+
approach allows all text sizes to be made larger or smaller based
|
| 574 |
+
on the font manager's default font size.
|
| 575 |
+
|
| 576 |
+
This class will also accept a fontconfig_ pattern_, if it is the only
|
| 577 |
+
argument provided. This support does not depend on fontconfig; we are
|
| 578 |
+
merely borrowing its pattern syntax for use here.
|
| 579 |
+
|
| 580 |
+
.. _fontconfig: https://www.freedesktop.org/wiki/Software/fontconfig/
|
| 581 |
+
.. _pattern:
|
| 582 |
+
https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
|
| 583 |
+
|
| 584 |
+
Note that Matplotlib's internal font manager and fontconfig use a
|
| 585 |
+
different algorithm to lookup fonts, so the results of the same pattern
|
| 586 |
+
may be different in Matplotlib than in other applications that use
|
| 587 |
+
fontconfig.
|
| 588 |
+
"""
|
| 589 |
+
|
| 590 |
+
def __init__(self, family=None, style=None, variant=None, weight=None,
|
| 591 |
+
stretch=None, size=None,
|
| 592 |
+
fname=None, # if set, it's a hardcoded filename to use
|
| 593 |
+
math_fontfamily=None):
|
| 594 |
+
self.set_family(family)
|
| 595 |
+
self.set_style(style)
|
| 596 |
+
self.set_variant(variant)
|
| 597 |
+
self.set_weight(weight)
|
| 598 |
+
self.set_stretch(stretch)
|
| 599 |
+
self.set_file(fname)
|
| 600 |
+
self.set_size(size)
|
| 601 |
+
self.set_math_fontfamily(math_fontfamily)
|
| 602 |
+
# Treat family as a fontconfig pattern if it is the only parameter
|
| 603 |
+
# provided. Even in that case, call the other setters first to set
|
| 604 |
+
# attributes not specified by the pattern to the rcParams defaults.
|
| 605 |
+
if (isinstance(family, str)
|
| 606 |
+
and style is None and variant is None and weight is None
|
| 607 |
+
and stretch is None and size is None and fname is None):
|
| 608 |
+
self.set_fontconfig_pattern(family)
|
| 609 |
+
|
| 610 |
+
@classmethod
|
| 611 |
+
def _from_any(cls, arg):
|
| 612 |
+
"""
|
| 613 |
+
Generic constructor which can build a `.FontProperties` from any of the
|
| 614 |
+
following:
|
| 615 |
+
|
| 616 |
+
- a `.FontProperties`: it is passed through as is;
|
| 617 |
+
- `None`: a `.FontProperties` using rc values is used;
|
| 618 |
+
- an `os.PathLike`: it is used as path to the font file;
|
| 619 |
+
- a `str`: it is parsed as a fontconfig pattern;
|
| 620 |
+
- a `dict`: it is passed as ``**kwargs`` to `.FontProperties`.
|
| 621 |
+
"""
|
| 622 |
+
if isinstance(arg, cls):
|
| 623 |
+
return arg
|
| 624 |
+
elif arg is None:
|
| 625 |
+
return cls()
|
| 626 |
+
elif isinstance(arg, os.PathLike):
|
| 627 |
+
return cls(fname=arg)
|
| 628 |
+
elif isinstance(arg, str):
|
| 629 |
+
return cls(arg)
|
| 630 |
+
else:
|
| 631 |
+
return cls(**arg)
|
| 632 |
+
|
| 633 |
+
def __hash__(self):
|
| 634 |
+
l = (tuple(self.get_family()),
|
| 635 |
+
self.get_slant(),
|
| 636 |
+
self.get_variant(),
|
| 637 |
+
self.get_weight(),
|
| 638 |
+
self.get_stretch(),
|
| 639 |
+
self.get_size(),
|
| 640 |
+
self.get_file(),
|
| 641 |
+
self.get_math_fontfamily())
|
| 642 |
+
return hash(l)
|
| 643 |
+
|
| 644 |
+
def __eq__(self, other):
|
| 645 |
+
return hash(self) == hash(other)
|
| 646 |
+
|
| 647 |
+
def __str__(self):
|
| 648 |
+
return self.get_fontconfig_pattern()
|
| 649 |
+
|
| 650 |
+
def get_family(self):
|
| 651 |
+
"""
|
| 652 |
+
Return a list of individual font family names or generic family names.
|
| 653 |
+
|
| 654 |
+
The font families or generic font families (which will be resolved
|
| 655 |
+
from their respective rcParams when searching for a matching font) in
|
| 656 |
+
the order of preference.
|
| 657 |
+
"""
|
| 658 |
+
return self._family
|
| 659 |
+
|
| 660 |
+
def get_name(self):
|
| 661 |
+
"""
|
| 662 |
+
Return the name of the font that best matches the font properties.
|
| 663 |
+
"""
|
| 664 |
+
return get_font(findfont(self)).family_name
|
| 665 |
+
|
| 666 |
+
def get_style(self):
|
| 667 |
+
"""
|
| 668 |
+
Return the font style. Values are: 'normal', 'italic' or 'oblique'.
|
| 669 |
+
"""
|
| 670 |
+
return self._slant
|
| 671 |
+
|
| 672 |
+
def get_variant(self):
|
| 673 |
+
"""
|
| 674 |
+
Return the font variant. Values are: 'normal' or 'small-caps'.
|
| 675 |
+
"""
|
| 676 |
+
return self._variant
|
| 677 |
+
|
| 678 |
+
def get_weight(self):
|
| 679 |
+
"""
|
| 680 |
+
Set the font weight. Options are: A numeric value in the
|
| 681 |
+
range 0-1000 or one of 'light', 'normal', 'regular', 'book',
|
| 682 |
+
'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold',
|
| 683 |
+
'heavy', 'extra bold', 'black'
|
| 684 |
+
"""
|
| 685 |
+
return self._weight
|
| 686 |
+
|
| 687 |
+
def get_stretch(self):
|
| 688 |
+
"""
|
| 689 |
+
Return the font stretch or width. Options are: 'ultra-condensed',
|
| 690 |
+
'extra-condensed', 'condensed', 'semi-condensed', 'normal',
|
| 691 |
+
'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'.
|
| 692 |
+
"""
|
| 693 |
+
return self._stretch
|
| 694 |
+
|
| 695 |
+
def get_size(self):
|
| 696 |
+
"""
|
| 697 |
+
Return the font size.
|
| 698 |
+
"""
|
| 699 |
+
return self._size
|
| 700 |
+
|
| 701 |
+
def get_file(self):
|
| 702 |
+
"""
|
| 703 |
+
Return the filename of the associated font.
|
| 704 |
+
"""
|
| 705 |
+
return self._file
|
| 706 |
+
|
| 707 |
+
def get_fontconfig_pattern(self):
|
| 708 |
+
"""
|
| 709 |
+
Get a fontconfig_ pattern_ suitable for looking up the font as
|
| 710 |
+
specified with fontconfig's ``fc-match`` utility.
|
| 711 |
+
|
| 712 |
+
This support does not depend on fontconfig; we are merely borrowing its
|
| 713 |
+
pattern syntax for use here.
|
| 714 |
+
"""
|
| 715 |
+
return generate_fontconfig_pattern(self)
|
| 716 |
+
|
| 717 |
+
def set_family(self, family):
|
| 718 |
+
"""
|
| 719 |
+
Change the font family. Can be either an alias (generic name
|
| 720 |
+
is CSS parlance), such as: 'serif', 'sans-serif', 'cursive',
|
| 721 |
+
'fantasy', or 'monospace', a real font name or a list of real
|
| 722 |
+
font names. Real font names are not supported when
|
| 723 |
+
:rc:`text.usetex` is `True`. Default: :rc:`font.family`
|
| 724 |
+
"""
|
| 725 |
+
if family is None:
|
| 726 |
+
family = mpl.rcParams['font.family']
|
| 727 |
+
if isinstance(family, str):
|
| 728 |
+
family = [family]
|
| 729 |
+
self._family = family
|
| 730 |
+
|
| 731 |
+
def set_style(self, style):
|
| 732 |
+
"""
|
| 733 |
+
Set the font style.
|
| 734 |
+
|
| 735 |
+
Parameters
|
| 736 |
+
----------
|
| 737 |
+
style : {'normal', 'italic', 'oblique'}, default: :rc:`font.style`
|
| 738 |
+
"""
|
| 739 |
+
if style is None:
|
| 740 |
+
style = mpl.rcParams['font.style']
|
| 741 |
+
_api.check_in_list(['normal', 'italic', 'oblique'], style=style)
|
| 742 |
+
self._slant = style
|
| 743 |
+
|
| 744 |
+
def set_variant(self, variant):
|
| 745 |
+
"""
|
| 746 |
+
Set the font variant.
|
| 747 |
+
|
| 748 |
+
Parameters
|
| 749 |
+
----------
|
| 750 |
+
variant : {'normal', 'small-caps'}, default: :rc:`font.variant`
|
| 751 |
+
"""
|
| 752 |
+
if variant is None:
|
| 753 |
+
variant = mpl.rcParams['font.variant']
|
| 754 |
+
_api.check_in_list(['normal', 'small-caps'], variant=variant)
|
| 755 |
+
self._variant = variant
|
| 756 |
+
|
| 757 |
+
def set_weight(self, weight):
|
| 758 |
+
"""
|
| 759 |
+
Set the font weight.
|
| 760 |
+
|
| 761 |
+
Parameters
|
| 762 |
+
----------
|
| 763 |
+
weight : int or {'ultralight', 'light', 'normal', 'regular', 'book', \
|
| 764 |
+
'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', \
|
| 765 |
+
'extra bold', 'black'}, default: :rc:`font.weight`
|
| 766 |
+
If int, must be in the range 0-1000.
|
| 767 |
+
"""
|
| 768 |
+
if weight is None:
|
| 769 |
+
weight = mpl.rcParams['font.weight']
|
| 770 |
+
if weight in weight_dict:
|
| 771 |
+
self._weight = weight
|
| 772 |
+
return
|
| 773 |
+
try:
|
| 774 |
+
weight = int(weight)
|
| 775 |
+
except ValueError:
|
| 776 |
+
pass
|
| 777 |
+
else:
|
| 778 |
+
if 0 <= weight <= 1000:
|
| 779 |
+
self._weight = weight
|
| 780 |
+
return
|
| 781 |
+
raise ValueError(f"{weight=} is invalid")
|
| 782 |
+
|
| 783 |
+
def set_stretch(self, stretch):
|
| 784 |
+
"""
|
| 785 |
+
Set the font stretch or width.
|
| 786 |
+
|
| 787 |
+
Parameters
|
| 788 |
+
----------
|
| 789 |
+
stretch : int or {'ultra-condensed', 'extra-condensed', 'condensed', \
|
| 790 |
+
'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', \
|
| 791 |
+
'ultra-expanded'}, default: :rc:`font.stretch`
|
| 792 |
+
If int, must be in the range 0-1000.
|
| 793 |
+
"""
|
| 794 |
+
if stretch is None:
|
| 795 |
+
stretch = mpl.rcParams['font.stretch']
|
| 796 |
+
if stretch in stretch_dict:
|
| 797 |
+
self._stretch = stretch
|
| 798 |
+
return
|
| 799 |
+
try:
|
| 800 |
+
stretch = int(stretch)
|
| 801 |
+
except ValueError:
|
| 802 |
+
pass
|
| 803 |
+
else:
|
| 804 |
+
if 0 <= stretch <= 1000:
|
| 805 |
+
self._stretch = stretch
|
| 806 |
+
return
|
| 807 |
+
raise ValueError(f"{stretch=} is invalid")
|
| 808 |
+
|
| 809 |
+
def set_size(self, size):
|
| 810 |
+
"""
|
| 811 |
+
Set the font size.
|
| 812 |
+
|
| 813 |
+
Parameters
|
| 814 |
+
----------
|
| 815 |
+
size : float or {'xx-small', 'x-small', 'small', 'medium', \
|
| 816 |
+
'large', 'x-large', 'xx-large'}, default: :rc:`font.size`
|
| 817 |
+
If a float, the font size in points. The string values denote
|
| 818 |
+
sizes relative to the default font size.
|
| 819 |
+
"""
|
| 820 |
+
if size is None:
|
| 821 |
+
size = mpl.rcParams['font.size']
|
| 822 |
+
try:
|
| 823 |
+
size = float(size)
|
| 824 |
+
except ValueError:
|
| 825 |
+
try:
|
| 826 |
+
scale = font_scalings[size]
|
| 827 |
+
except KeyError as err:
|
| 828 |
+
raise ValueError(
|
| 829 |
+
"Size is invalid. Valid font size are "
|
| 830 |
+
+ ", ".join(map(str, font_scalings))) from err
|
| 831 |
+
else:
|
| 832 |
+
size = scale * FontManager.get_default_size()
|
| 833 |
+
if size < 1.0:
|
| 834 |
+
_log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. '
|
| 835 |
+
'Setting fontsize = 1 pt', size)
|
| 836 |
+
size = 1.0
|
| 837 |
+
self._size = size
|
| 838 |
+
|
| 839 |
+
def set_file(self, file):
|
| 840 |
+
"""
|
| 841 |
+
Set the filename of the fontfile to use. In this case, all
|
| 842 |
+
other properties will be ignored.
|
| 843 |
+
"""
|
| 844 |
+
self._file = os.fspath(file) if file is not None else None
|
| 845 |
+
|
| 846 |
+
def set_fontconfig_pattern(self, pattern):
|
| 847 |
+
"""
|
| 848 |
+
Set the properties by parsing a fontconfig_ *pattern*.
|
| 849 |
+
|
| 850 |
+
This support does not depend on fontconfig; we are merely borrowing its
|
| 851 |
+
pattern syntax for use here.
|
| 852 |
+
"""
|
| 853 |
+
for key, val in parse_fontconfig_pattern(pattern).items():
|
| 854 |
+
if type(val) is list:
|
| 855 |
+
getattr(self, "set_" + key)(val[0])
|
| 856 |
+
else:
|
| 857 |
+
getattr(self, "set_" + key)(val)
|
| 858 |
+
|
| 859 |
+
def get_math_fontfamily(self):
|
| 860 |
+
"""
|
| 861 |
+
Return the name of the font family used for math text.
|
| 862 |
+
|
| 863 |
+
The default font is :rc:`mathtext.fontset`.
|
| 864 |
+
"""
|
| 865 |
+
return self._math_fontfamily
|
| 866 |
+
|
| 867 |
+
def set_math_fontfamily(self, fontfamily):
|
| 868 |
+
"""
|
| 869 |
+
Set the font family for text in math mode.
|
| 870 |
+
|
| 871 |
+
If not set explicitly, :rc:`mathtext.fontset` will be used.
|
| 872 |
+
|
| 873 |
+
Parameters
|
| 874 |
+
----------
|
| 875 |
+
fontfamily : str
|
| 876 |
+
The name of the font family.
|
| 877 |
+
|
| 878 |
+
Available font families are defined in the
|
| 879 |
+
:ref:`default matplotlibrc file <customizing-with-matplotlibrc-files>`.
|
| 880 |
+
|
| 881 |
+
See Also
|
| 882 |
+
--------
|
| 883 |
+
.text.Text.get_math_fontfamily
|
| 884 |
+
"""
|
| 885 |
+
if fontfamily is None:
|
| 886 |
+
fontfamily = mpl.rcParams['mathtext.fontset']
|
| 887 |
+
else:
|
| 888 |
+
valid_fonts = _validators['mathtext.fontset'].valid.values()
|
| 889 |
+
# _check_in_list() Validates the parameter math_fontfamily as
|
| 890 |
+
# if it were passed to rcParams['mathtext.fontset']
|
| 891 |
+
_api.check_in_list(valid_fonts, math_fontfamily=fontfamily)
|
| 892 |
+
self._math_fontfamily = fontfamily
|
| 893 |
+
|
| 894 |
+
def copy(self):
|
| 895 |
+
"""Return a copy of self."""
|
| 896 |
+
return copy.copy(self)
|
| 897 |
+
|
| 898 |
+
# Aliases
|
| 899 |
+
set_name = set_family
|
| 900 |
+
get_slant = get_style
|
| 901 |
+
set_slant = set_style
|
| 902 |
+
get_size_in_points = get_size
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
class _JSONEncoder(json.JSONEncoder):
|
| 906 |
+
def default(self, o):
|
| 907 |
+
if isinstance(o, FontManager):
|
| 908 |
+
return dict(o.__dict__, __class__='FontManager')
|
| 909 |
+
elif isinstance(o, FontEntry):
|
| 910 |
+
d = dict(o.__dict__, __class__='FontEntry')
|
| 911 |
+
try:
|
| 912 |
+
# Cache paths of fonts shipped with Matplotlib relative to the
|
| 913 |
+
# Matplotlib data path, which helps in the presence of venvs.
|
| 914 |
+
d["fname"] = str(
|
| 915 |
+
Path(d["fname"]).relative_to(mpl.get_data_path()))
|
| 916 |
+
except ValueError:
|
| 917 |
+
pass
|
| 918 |
+
return d
|
| 919 |
+
else:
|
| 920 |
+
return super().default(o)
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
def _json_decode(o):
|
| 924 |
+
cls = o.pop('__class__', None)
|
| 925 |
+
if cls is None:
|
| 926 |
+
return o
|
| 927 |
+
elif cls == 'FontManager':
|
| 928 |
+
r = FontManager.__new__(FontManager)
|
| 929 |
+
r.__dict__.update(o)
|
| 930 |
+
return r
|
| 931 |
+
elif cls == 'FontEntry':
|
| 932 |
+
r = FontEntry.__new__(FontEntry)
|
| 933 |
+
r.__dict__.update(o)
|
| 934 |
+
if not os.path.isabs(r.fname):
|
| 935 |
+
r.fname = os.path.join(mpl.get_data_path(), r.fname)
|
| 936 |
+
return r
|
| 937 |
+
else:
|
| 938 |
+
raise ValueError("Don't know how to deserialize __class__=%s" % cls)
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def json_dump(data, filename):
|
| 942 |
+
"""
|
| 943 |
+
Dump `FontManager` *data* as JSON to the file named *filename*.
|
| 944 |
+
|
| 945 |
+
See Also
|
| 946 |
+
--------
|
| 947 |
+
json_load
|
| 948 |
+
|
| 949 |
+
Notes
|
| 950 |
+
-----
|
| 951 |
+
File paths that are children of the Matplotlib data path (typically, fonts
|
| 952 |
+
shipped with Matplotlib) are stored relative to that data path (to remain
|
| 953 |
+
valid across virtualenvs).
|
| 954 |
+
|
| 955 |
+
This function temporarily locks the output file to prevent multiple
|
| 956 |
+
processes from overwriting one another's output.
|
| 957 |
+
"""
|
| 958 |
+
with cbook._lock_path(filename), open(filename, 'w') as fh:
|
| 959 |
+
try:
|
| 960 |
+
json.dump(data, fh, cls=_JSONEncoder, indent=2)
|
| 961 |
+
except OSError as e:
|
| 962 |
+
_log.warning('Could not save font_manager cache {}'.format(e))
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def json_load(filename):
|
| 966 |
+
"""
|
| 967 |
+
Load a `FontManager` from the JSON file named *filename*.
|
| 968 |
+
|
| 969 |
+
See Also
|
| 970 |
+
--------
|
| 971 |
+
json_dump
|
| 972 |
+
"""
|
| 973 |
+
with open(filename) as fh:
|
| 974 |
+
return json.load(fh, object_hook=_json_decode)
|
| 975 |
+
|
| 976 |
+
|
| 977 |
+
class FontManager:
|
| 978 |
+
"""
|
| 979 |
+
On import, the `FontManager` singleton instance creates a list of ttf and
|
| 980 |
+
afm fonts and caches their `FontProperties`. The `FontManager.findfont`
|
| 981 |
+
method does a nearest neighbor search to find the font that most closely
|
| 982 |
+
matches the specification. If no good enough match is found, the default
|
| 983 |
+
font is returned.
|
| 984 |
+
"""
|
| 985 |
+
# Increment this version number whenever the font cache data
|
| 986 |
+
# format or behavior has changed and requires an existing font
|
| 987 |
+
# cache files to be rebuilt.
|
| 988 |
+
__version__ = 330
|
| 989 |
+
|
| 990 |
+
def __init__(self, size=None, weight='normal'):
|
| 991 |
+
self._version = self.__version__
|
| 992 |
+
|
| 993 |
+
self.__default_weight = weight
|
| 994 |
+
self.default_size = size
|
| 995 |
+
|
| 996 |
+
# Create list of font paths.
|
| 997 |
+
paths = [cbook._get_data_path('fonts', subdir)
|
| 998 |
+
for subdir in ['ttf', 'afm', 'pdfcorefonts']]
|
| 999 |
+
_log.debug('font search path %s', paths)
|
| 1000 |
+
|
| 1001 |
+
self.defaultFamily = {
|
| 1002 |
+
'ttf': 'DejaVu Sans',
|
| 1003 |
+
'afm': 'Helvetica'}
|
| 1004 |
+
|
| 1005 |
+
self.afmlist = []
|
| 1006 |
+
self.ttflist = []
|
| 1007 |
+
|
| 1008 |
+
# Delay the warning by 5s.
|
| 1009 |
+
timer = threading.Timer(5, lambda: _log.warning(
|
| 1010 |
+
'Matplotlib is building the font cache; this may take a moment.'))
|
| 1011 |
+
timer.start()
|
| 1012 |
+
try:
|
| 1013 |
+
for fontext in ["afm", "ttf"]:
|
| 1014 |
+
for path in [*findSystemFonts(paths, fontext=fontext),
|
| 1015 |
+
*findSystemFonts(fontext=fontext)]:
|
| 1016 |
+
try:
|
| 1017 |
+
self.addfont(path)
|
| 1018 |
+
except OSError as exc:
|
| 1019 |
+
_log.info("Failed to open font file %s: %s", path, exc)
|
| 1020 |
+
except Exception as exc:
|
| 1021 |
+
_log.info("Failed to extract font properties from %s: "
|
| 1022 |
+
"%s", path, exc)
|
| 1023 |
+
finally:
|
| 1024 |
+
timer.cancel()
|
| 1025 |
+
|
| 1026 |
+
def addfont(self, path):
|
| 1027 |
+
"""
|
| 1028 |
+
Cache the properties of the font at *path* to make it available to the
|
| 1029 |
+
`FontManager`. The type of font is inferred from the path suffix.
|
| 1030 |
+
|
| 1031 |
+
Parameters
|
| 1032 |
+
----------
|
| 1033 |
+
path : str or path-like
|
| 1034 |
+
"""
|
| 1035 |
+
# Convert to string in case of a path as
|
| 1036 |
+
# afmFontProperty and FT2Font expect this
|
| 1037 |
+
path = os.fsdecode(path)
|
| 1038 |
+
if Path(path).suffix.lower() == ".afm":
|
| 1039 |
+
with open(path, "rb") as fh:
|
| 1040 |
+
font = _afm.AFM(fh)
|
| 1041 |
+
prop = afmFontProperty(path, font)
|
| 1042 |
+
self.afmlist.append(prop)
|
| 1043 |
+
else:
|
| 1044 |
+
font = ft2font.FT2Font(path)
|
| 1045 |
+
prop = ttfFontProperty(font)
|
| 1046 |
+
self.ttflist.append(prop)
|
| 1047 |
+
self._findfont_cached.cache_clear()
|
| 1048 |
+
|
| 1049 |
+
@property
|
| 1050 |
+
def defaultFont(self):
|
| 1051 |
+
# Lazily evaluated (findfont then caches the result) to avoid including
|
| 1052 |
+
# the venv path in the json serialization.
|
| 1053 |
+
return {ext: self.findfont(family, fontext=ext)
|
| 1054 |
+
for ext, family in self.defaultFamily.items()}
|
| 1055 |
+
|
| 1056 |
+
def get_default_weight(self):
|
| 1057 |
+
"""
|
| 1058 |
+
Return the default font weight.
|
| 1059 |
+
"""
|
| 1060 |
+
return self.__default_weight
|
| 1061 |
+
|
| 1062 |
+
@staticmethod
|
| 1063 |
+
def get_default_size():
|
| 1064 |
+
"""
|
| 1065 |
+
Return the default font size.
|
| 1066 |
+
"""
|
| 1067 |
+
return mpl.rcParams['font.size']
|
| 1068 |
+
|
| 1069 |
+
def set_default_weight(self, weight):
|
| 1070 |
+
"""
|
| 1071 |
+
Set the default font weight. The initial value is 'normal'.
|
| 1072 |
+
"""
|
| 1073 |
+
self.__default_weight = weight
|
| 1074 |
+
|
| 1075 |
+
@staticmethod
|
| 1076 |
+
def _expand_aliases(family):
|
| 1077 |
+
if family in ('sans', 'sans serif'):
|
| 1078 |
+
family = 'sans-serif'
|
| 1079 |
+
return mpl.rcParams['font.' + family]
|
| 1080 |
+
|
| 1081 |
+
# Each of the scoring functions below should return a value between
|
| 1082 |
+
# 0.0 (perfect match) and 1.0 (terrible match)
|
| 1083 |
+
def score_family(self, families, family2):
|
| 1084 |
+
"""
|
| 1085 |
+
Return a match score between the list of font families in
|
| 1086 |
+
*families* and the font family name *family2*.
|
| 1087 |
+
|
| 1088 |
+
An exact match at the head of the list returns 0.0.
|
| 1089 |
+
|
| 1090 |
+
A match further down the list will return between 0 and 1.
|
| 1091 |
+
|
| 1092 |
+
No match will return 1.0.
|
| 1093 |
+
"""
|
| 1094 |
+
if not isinstance(families, (list, tuple)):
|
| 1095 |
+
families = [families]
|
| 1096 |
+
elif len(families) == 0:
|
| 1097 |
+
return 1.0
|
| 1098 |
+
family2 = family2.lower()
|
| 1099 |
+
step = 1 / len(families)
|
| 1100 |
+
for i, family1 in enumerate(families):
|
| 1101 |
+
family1 = family1.lower()
|
| 1102 |
+
if family1 in font_family_aliases:
|
| 1103 |
+
options = [*map(str.lower, self._expand_aliases(family1))]
|
| 1104 |
+
if family2 in options:
|
| 1105 |
+
idx = options.index(family2)
|
| 1106 |
+
return (i + (idx / len(options))) * step
|
| 1107 |
+
elif family1 == family2:
|
| 1108 |
+
# The score should be weighted by where in the
|
| 1109 |
+
# list the font was found.
|
| 1110 |
+
return i * step
|
| 1111 |
+
return 1.0
|
| 1112 |
+
|
| 1113 |
+
def score_style(self, style1, style2):
|
| 1114 |
+
"""
|
| 1115 |
+
Return a match score between *style1* and *style2*.
|
| 1116 |
+
|
| 1117 |
+
An exact match returns 0.0.
|
| 1118 |
+
|
| 1119 |
+
A match between 'italic' and 'oblique' returns 0.1.
|
| 1120 |
+
|
| 1121 |
+
No match returns 1.0.
|
| 1122 |
+
"""
|
| 1123 |
+
if style1 == style2:
|
| 1124 |
+
return 0.0
|
| 1125 |
+
elif (style1 in ('italic', 'oblique')
|
| 1126 |
+
and style2 in ('italic', 'oblique')):
|
| 1127 |
+
return 0.1
|
| 1128 |
+
return 1.0
|
| 1129 |
+
|
| 1130 |
+
def score_variant(self, variant1, variant2):
|
| 1131 |
+
"""
|
| 1132 |
+
Return a match score between *variant1* and *variant2*.
|
| 1133 |
+
|
| 1134 |
+
An exact match returns 0.0, otherwise 1.0.
|
| 1135 |
+
"""
|
| 1136 |
+
if variant1 == variant2:
|
| 1137 |
+
return 0.0
|
| 1138 |
+
else:
|
| 1139 |
+
return 1.0
|
| 1140 |
+
|
| 1141 |
+
def score_stretch(self, stretch1, stretch2):
|
| 1142 |
+
"""
|
| 1143 |
+
Return a match score between *stretch1* and *stretch2*.
|
| 1144 |
+
|
| 1145 |
+
The result is the absolute value of the difference between the
|
| 1146 |
+
CSS numeric values of *stretch1* and *stretch2*, normalized
|
| 1147 |
+
between 0.0 and 1.0.
|
| 1148 |
+
"""
|
| 1149 |
+
try:
|
| 1150 |
+
stretchval1 = int(stretch1)
|
| 1151 |
+
except ValueError:
|
| 1152 |
+
stretchval1 = stretch_dict.get(stretch1, 500)
|
| 1153 |
+
try:
|
| 1154 |
+
stretchval2 = int(stretch2)
|
| 1155 |
+
except ValueError:
|
| 1156 |
+
stretchval2 = stretch_dict.get(stretch2, 500)
|
| 1157 |
+
return abs(stretchval1 - stretchval2) / 1000.0
|
| 1158 |
+
|
| 1159 |
+
def score_weight(self, weight1, weight2):
|
| 1160 |
+
"""
|
| 1161 |
+
Return a match score between *weight1* and *weight2*.
|
| 1162 |
+
|
| 1163 |
+
The result is 0.0 if both weight1 and weight 2 are given as strings
|
| 1164 |
+
and have the same value.
|
| 1165 |
+
|
| 1166 |
+
Otherwise, the result is the absolute value of the difference between
|
| 1167 |
+
the CSS numeric values of *weight1* and *weight2*, normalized between
|
| 1168 |
+
0.05 and 1.0.
|
| 1169 |
+
"""
|
| 1170 |
+
# exact match of the weight names, e.g. weight1 == weight2 == "regular"
|
| 1171 |
+
if cbook._str_equal(weight1, weight2):
|
| 1172 |
+
return 0.0
|
| 1173 |
+
w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1]
|
| 1174 |
+
w2 = weight2 if isinstance(weight2, Number) else weight_dict[weight2]
|
| 1175 |
+
return 0.95 * (abs(w1 - w2) / 1000) + 0.05
|
| 1176 |
+
|
| 1177 |
+
def score_size(self, size1, size2):
|
| 1178 |
+
"""
|
| 1179 |
+
Return a match score between *size1* and *size2*.
|
| 1180 |
+
|
| 1181 |
+
If *size2* (the size specified in the font file) is 'scalable', this
|
| 1182 |
+
function always returns 0.0, since any font size can be generated.
|
| 1183 |
+
|
| 1184 |
+
Otherwise, the result is the absolute distance between *size1* and
|
| 1185 |
+
*size2*, normalized so that the usual range of font sizes (6pt -
|
| 1186 |
+
72pt) will lie between 0.0 and 1.0.
|
| 1187 |
+
"""
|
| 1188 |
+
if size2 == 'scalable':
|
| 1189 |
+
return 0.0
|
| 1190 |
+
# Size value should have already been
|
| 1191 |
+
try:
|
| 1192 |
+
sizeval1 = float(size1)
|
| 1193 |
+
except ValueError:
|
| 1194 |
+
sizeval1 = self.default_size * font_scalings[size1]
|
| 1195 |
+
try:
|
| 1196 |
+
sizeval2 = float(size2)
|
| 1197 |
+
except ValueError:
|
| 1198 |
+
return 1.0
|
| 1199 |
+
return abs(sizeval1 - sizeval2) / 72
|
| 1200 |
+
|
| 1201 |
+
def findfont(self, prop, fontext='ttf', directory=None,
|
| 1202 |
+
fallback_to_default=True, rebuild_if_missing=True):
|
| 1203 |
+
"""
|
| 1204 |
+
Find a font that most closely matches the given font properties.
|
| 1205 |
+
|
| 1206 |
+
Parameters
|
| 1207 |
+
----------
|
| 1208 |
+
prop : str or `~matplotlib.font_manager.FontProperties`
|
| 1209 |
+
The font properties to search for. This can be either a
|
| 1210 |
+
`.FontProperties` object or a string defining a
|
| 1211 |
+
`fontconfig patterns`_.
|
| 1212 |
+
|
| 1213 |
+
fontext : {'ttf', 'afm'}, default: 'ttf'
|
| 1214 |
+
The extension of the font file:
|
| 1215 |
+
|
| 1216 |
+
- 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)
|
| 1217 |
+
- 'afm': Adobe Font Metrics (.afm)
|
| 1218 |
+
|
| 1219 |
+
directory : str, optional
|
| 1220 |
+
If given, only search this directory and its subdirectories.
|
| 1221 |
+
|
| 1222 |
+
fallback_to_default : bool
|
| 1223 |
+
If True, will fall back to the default font family (usually
|
| 1224 |
+
"DejaVu Sans" or "Helvetica") if the first lookup hard-fails.
|
| 1225 |
+
|
| 1226 |
+
rebuild_if_missing : bool
|
| 1227 |
+
Whether to rebuild the font cache and search again if the first
|
| 1228 |
+
match appears to point to a nonexisting font (i.e., the font cache
|
| 1229 |
+
contains outdated entries).
|
| 1230 |
+
|
| 1231 |
+
Returns
|
| 1232 |
+
-------
|
| 1233 |
+
str
|
| 1234 |
+
The filename of the best matching font.
|
| 1235 |
+
|
| 1236 |
+
Notes
|
| 1237 |
+
-----
|
| 1238 |
+
This performs a nearest neighbor search. Each font is given a
|
| 1239 |
+
similarity score to the target font properties. The first font with
|
| 1240 |
+
the highest score is returned. If no matches below a certain
|
| 1241 |
+
threshold are found, the default font (usually DejaVu Sans) is
|
| 1242 |
+
returned.
|
| 1243 |
+
|
| 1244 |
+
The result is cached, so subsequent lookups don't have to
|
| 1245 |
+
perform the O(n) nearest neighbor search.
|
| 1246 |
+
|
| 1247 |
+
See the `W3C Cascading Style Sheet, Level 1
|
| 1248 |
+
<http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ documentation
|
| 1249 |
+
for a description of the font finding algorithm.
|
| 1250 |
+
|
| 1251 |
+
.. _fontconfig patterns:
|
| 1252 |
+
https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
|
| 1253 |
+
"""
|
| 1254 |
+
# Pass the relevant rcParams (and the font manager, as `self`) to
|
| 1255 |
+
# _findfont_cached so to prevent using a stale cache entry after an
|
| 1256 |
+
# rcParam was changed.
|
| 1257 |
+
rc_params = tuple(tuple(mpl.rcParams[key]) for key in [
|
| 1258 |
+
"font.serif", "font.sans-serif", "font.cursive", "font.fantasy",
|
| 1259 |
+
"font.monospace"])
|
| 1260 |
+
ret = self._findfont_cached(
|
| 1261 |
+
prop, fontext, directory, fallback_to_default, rebuild_if_missing,
|
| 1262 |
+
rc_params)
|
| 1263 |
+
if isinstance(ret, _ExceptionProxy):
|
| 1264 |
+
raise ret.klass(ret.message)
|
| 1265 |
+
return ret
|
| 1266 |
+
|
| 1267 |
+
def get_font_names(self):
|
| 1268 |
+
"""Return the list of available fonts."""
|
| 1269 |
+
return list(set([font.name for font in self.ttflist]))
|
| 1270 |
+
|
| 1271 |
+
def _find_fonts_by_props(self, prop, fontext='ttf', directory=None,
|
| 1272 |
+
fallback_to_default=True, rebuild_if_missing=True):
|
| 1273 |
+
"""
|
| 1274 |
+
Find font families that most closely match the given properties.
|
| 1275 |
+
|
| 1276 |
+
Parameters
|
| 1277 |
+
----------
|
| 1278 |
+
prop : str or `~matplotlib.font_manager.FontProperties`
|
| 1279 |
+
The font properties to search for. This can be either a
|
| 1280 |
+
`.FontProperties` object or a string defining a
|
| 1281 |
+
`fontconfig patterns`_.
|
| 1282 |
+
|
| 1283 |
+
fontext : {'ttf', 'afm'}, default: 'ttf'
|
| 1284 |
+
The extension of the font file:
|
| 1285 |
+
|
| 1286 |
+
- 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)
|
| 1287 |
+
- 'afm': Adobe Font Metrics (.afm)
|
| 1288 |
+
|
| 1289 |
+
directory : str, optional
|
| 1290 |
+
If given, only search this directory and its subdirectories.
|
| 1291 |
+
|
| 1292 |
+
fallback_to_default : bool
|
| 1293 |
+
If True, will fall back to the default font family (usually
|
| 1294 |
+
"DejaVu Sans" or "Helvetica") if none of the families were found.
|
| 1295 |
+
|
| 1296 |
+
rebuild_if_missing : bool
|
| 1297 |
+
Whether to rebuild the font cache and search again if the first
|
| 1298 |
+
match appears to point to a nonexisting font (i.e., the font cache
|
| 1299 |
+
contains outdated entries).
|
| 1300 |
+
|
| 1301 |
+
Returns
|
| 1302 |
+
-------
|
| 1303 |
+
list[str]
|
| 1304 |
+
The paths of the fonts found
|
| 1305 |
+
|
| 1306 |
+
Notes
|
| 1307 |
+
-----
|
| 1308 |
+
This is an extension/wrapper of the original findfont API, which only
|
| 1309 |
+
returns a single font for given font properties. Instead, this API
|
| 1310 |
+
returns a dict containing multiple fonts and their filepaths
|
| 1311 |
+
which closely match the given font properties. Since this internally
|
| 1312 |
+
uses the original API, there's no change to the logic of performing the
|
| 1313 |
+
nearest neighbor search. See `findfont` for more details.
|
| 1314 |
+
"""
|
| 1315 |
+
|
| 1316 |
+
prop = FontProperties._from_any(prop)
|
| 1317 |
+
|
| 1318 |
+
fpaths = []
|
| 1319 |
+
for family in prop.get_family():
|
| 1320 |
+
cprop = prop.copy()
|
| 1321 |
+
cprop.set_family(family) # set current prop's family
|
| 1322 |
+
|
| 1323 |
+
try:
|
| 1324 |
+
fpaths.append(
|
| 1325 |
+
self.findfont(
|
| 1326 |
+
cprop, fontext, directory,
|
| 1327 |
+
fallback_to_default=False, # don't fallback to default
|
| 1328 |
+
rebuild_if_missing=rebuild_if_missing,
|
| 1329 |
+
)
|
| 1330 |
+
)
|
| 1331 |
+
except ValueError:
|
| 1332 |
+
if family in font_family_aliases:
|
| 1333 |
+
_log.warning(
|
| 1334 |
+
"findfont: Generic family %r not found because "
|
| 1335 |
+
"none of the following families were found: %s",
|
| 1336 |
+
family, ", ".join(self._expand_aliases(family))
|
| 1337 |
+
)
|
| 1338 |
+
else:
|
| 1339 |
+
_log.warning("findfont: Font family %r not found.", family)
|
| 1340 |
+
|
| 1341 |
+
# only add default family if no other font was found and
|
| 1342 |
+
# fallback_to_default is enabled
|
| 1343 |
+
if not fpaths:
|
| 1344 |
+
if fallback_to_default:
|
| 1345 |
+
dfamily = self.defaultFamily[fontext]
|
| 1346 |
+
cprop = prop.copy()
|
| 1347 |
+
cprop.set_family(dfamily)
|
| 1348 |
+
fpaths.append(
|
| 1349 |
+
self.findfont(
|
| 1350 |
+
cprop, fontext, directory,
|
| 1351 |
+
fallback_to_default=True,
|
| 1352 |
+
rebuild_if_missing=rebuild_if_missing,
|
| 1353 |
+
)
|
| 1354 |
+
)
|
| 1355 |
+
else:
|
| 1356 |
+
raise ValueError("Failed to find any font, and fallback "
|
| 1357 |
+
"to the default font was disabled")
|
| 1358 |
+
|
| 1359 |
+
return fpaths
|
| 1360 |
+
|
| 1361 |
+
@lru_cache(1024)
|
| 1362 |
+
def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
|
| 1363 |
+
rebuild_if_missing, rc_params):
|
| 1364 |
+
|
| 1365 |
+
prop = FontProperties._from_any(prop)
|
| 1366 |
+
|
| 1367 |
+
fname = prop.get_file()
|
| 1368 |
+
if fname is not None:
|
| 1369 |
+
return fname
|
| 1370 |
+
|
| 1371 |
+
if fontext == 'afm':
|
| 1372 |
+
fontlist = self.afmlist
|
| 1373 |
+
else:
|
| 1374 |
+
fontlist = self.ttflist
|
| 1375 |
+
|
| 1376 |
+
best_score = 1e64
|
| 1377 |
+
best_font = None
|
| 1378 |
+
|
| 1379 |
+
_log.debug('findfont: Matching %s.', prop)
|
| 1380 |
+
for font in fontlist:
|
| 1381 |
+
if (directory is not None and
|
| 1382 |
+
Path(directory) not in Path(font.fname).parents):
|
| 1383 |
+
continue
|
| 1384 |
+
# Matching family should have top priority, so multiply it by 10.
|
| 1385 |
+
score = (self.score_family(prop.get_family(), font.name) * 10
|
| 1386 |
+
+ self.score_style(prop.get_style(), font.style)
|
| 1387 |
+
+ self.score_variant(prop.get_variant(), font.variant)
|
| 1388 |
+
+ self.score_weight(prop.get_weight(), font.weight)
|
| 1389 |
+
+ self.score_stretch(prop.get_stretch(), font.stretch)
|
| 1390 |
+
+ self.score_size(prop.get_size(), font.size))
|
| 1391 |
+
_log.debug('findfont: score(%s) = %s', font, score)
|
| 1392 |
+
if score < best_score:
|
| 1393 |
+
best_score = score
|
| 1394 |
+
best_font = font
|
| 1395 |
+
if score == 0:
|
| 1396 |
+
break
|
| 1397 |
+
|
| 1398 |
+
if best_font is None or best_score >= 10.0:
|
| 1399 |
+
if fallback_to_default:
|
| 1400 |
+
_log.warning(
|
| 1401 |
+
'findfont: Font family %s not found. Falling back to %s.',
|
| 1402 |
+
prop.get_family(), self.defaultFamily[fontext])
|
| 1403 |
+
for family in map(str.lower, prop.get_family()):
|
| 1404 |
+
if family in font_family_aliases:
|
| 1405 |
+
_log.warning(
|
| 1406 |
+
"findfont: Generic family %r not found because "
|
| 1407 |
+
"none of the following families were found: %s",
|
| 1408 |
+
family, ", ".join(self._expand_aliases(family)))
|
| 1409 |
+
default_prop = prop.copy()
|
| 1410 |
+
default_prop.set_family(self.defaultFamily[fontext])
|
| 1411 |
+
return self.findfont(default_prop, fontext, directory,
|
| 1412 |
+
fallback_to_default=False)
|
| 1413 |
+
else:
|
| 1414 |
+
# This return instead of raise is intentional, as we wish to
|
| 1415 |
+
# cache that it was not found, which will not occur if it was
|
| 1416 |
+
# actually raised.
|
| 1417 |
+
return _ExceptionProxy(
|
| 1418 |
+
ValueError,
|
| 1419 |
+
f"Failed to find font {prop}, and fallback to the default font was disabled"
|
| 1420 |
+
)
|
| 1421 |
+
else:
|
| 1422 |
+
_log.debug('findfont: Matching %s to %s (%r) with score of %f.',
|
| 1423 |
+
prop, best_font.name, best_font.fname, best_score)
|
| 1424 |
+
result = best_font.fname
|
| 1425 |
+
|
| 1426 |
+
if not os.path.isfile(result):
|
| 1427 |
+
if rebuild_if_missing:
|
| 1428 |
+
_log.info(
|
| 1429 |
+
'findfont: Found a missing font file. Rebuilding cache.')
|
| 1430 |
+
new_fm = _load_fontmanager(try_read_cache=False)
|
| 1431 |
+
# Replace self by the new fontmanager, because users may have
|
| 1432 |
+
# a reference to this specific instance.
|
| 1433 |
+
# TODO: _load_fontmanager should really be (used by) a method
|
| 1434 |
+
# modifying the instance in place.
|
| 1435 |
+
vars(self).update(vars(new_fm))
|
| 1436 |
+
return self.findfont(
|
| 1437 |
+
prop, fontext, directory, rebuild_if_missing=False)
|
| 1438 |
+
else:
|
| 1439 |
+
# This return instead of raise is intentional, as we wish to
|
| 1440 |
+
# cache that it was not found, which will not occur if it was
|
| 1441 |
+
# actually raised.
|
| 1442 |
+
return _ExceptionProxy(ValueError, "No valid font could be found")
|
| 1443 |
+
|
| 1444 |
+
return _cached_realpath(result)
|
| 1445 |
+
|
| 1446 |
+
|
| 1447 |
+
@lru_cache()
|
| 1448 |
+
def is_opentype_cff_font(filename):
|
| 1449 |
+
"""
|
| 1450 |
+
Return whether the given font is a Postscript Compact Font Format Font
|
| 1451 |
+
embedded in an OpenType wrapper. Used by the PostScript and PDF backends
|
| 1452 |
+
that can not subset these fonts.
|
| 1453 |
+
"""
|
| 1454 |
+
if os.path.splitext(filename)[1].lower() == '.otf':
|
| 1455 |
+
with open(filename, 'rb') as fd:
|
| 1456 |
+
return fd.read(4) == b"OTTO"
|
| 1457 |
+
else:
|
| 1458 |
+
return False
|
| 1459 |
+
|
| 1460 |
+
|
| 1461 |
+
@lru_cache(64)
|
| 1462 |
+
def _get_font(font_filepaths, hinting_factor, *, _kerning_factor, thread_id):
|
| 1463 |
+
first_fontpath, *rest = font_filepaths
|
| 1464 |
+
return ft2font.FT2Font(
|
| 1465 |
+
first_fontpath, hinting_factor,
|
| 1466 |
+
_fallback_list=[
|
| 1467 |
+
ft2font.FT2Font(
|
| 1468 |
+
fpath, hinting_factor,
|
| 1469 |
+
_kerning_factor=_kerning_factor
|
| 1470 |
+
)
|
| 1471 |
+
for fpath in rest
|
| 1472 |
+
],
|
| 1473 |
+
_kerning_factor=_kerning_factor
|
| 1474 |
+
)
|
| 1475 |
+
|
| 1476 |
+
|
| 1477 |
+
# FT2Font objects cannot be used across fork()s because they reference the same
|
| 1478 |
+
# FT_Library object. While invalidating *all* existing FT2Fonts after a fork
|
| 1479 |
+
# would be too complicated to be worth it, the main way FT2Fonts get reused is
|
| 1480 |
+
# via the cache of _get_font, which we can empty upon forking (not on Windows,
|
| 1481 |
+
# which has no fork() or register_at_fork()).
|
| 1482 |
+
if hasattr(os, "register_at_fork"):
|
| 1483 |
+
os.register_at_fork(after_in_child=_get_font.cache_clear)
|
| 1484 |
+
|
| 1485 |
+
|
| 1486 |
+
@lru_cache(64)
|
| 1487 |
+
def _cached_realpath(path):
|
| 1488 |
+
# Resolving the path avoids embedding the font twice in pdf/ps output if a
|
| 1489 |
+
# single font is selected using two different relative paths.
|
| 1490 |
+
return os.path.realpath(path)
|
| 1491 |
+
|
| 1492 |
+
|
| 1493 |
+
@_api.rename_parameter('3.6', "filepath", "font_filepaths")
|
| 1494 |
+
def get_font(font_filepaths, hinting_factor=None):
|
| 1495 |
+
"""
|
| 1496 |
+
Get an `.ft2font.FT2Font` object given a list of file paths.
|
| 1497 |
+
|
| 1498 |
+
Parameters
|
| 1499 |
+
----------
|
| 1500 |
+
font_filepaths : Iterable[str, Path, bytes], str, Path, bytes
|
| 1501 |
+
Relative or absolute paths to the font files to be used.
|
| 1502 |
+
|
| 1503 |
+
If a single string, bytes, or `pathlib.Path`, then it will be treated
|
| 1504 |
+
as a list with that entry only.
|
| 1505 |
+
|
| 1506 |
+
If more than one filepath is passed, then the returned FT2Font object
|
| 1507 |
+
will fall back through the fonts, in the order given, to find a needed
|
| 1508 |
+
glyph.
|
| 1509 |
+
|
| 1510 |
+
Returns
|
| 1511 |
+
-------
|
| 1512 |
+
`.ft2font.FT2Font`
|
| 1513 |
+
|
| 1514 |
+
"""
|
| 1515 |
+
if isinstance(font_filepaths, (str, Path, bytes)):
|
| 1516 |
+
paths = (_cached_realpath(font_filepaths),)
|
| 1517 |
+
else:
|
| 1518 |
+
paths = tuple(_cached_realpath(fname) for fname in font_filepaths)
|
| 1519 |
+
|
| 1520 |
+
if hinting_factor is None:
|
| 1521 |
+
hinting_factor = mpl.rcParams['text.hinting_factor']
|
| 1522 |
+
|
| 1523 |
+
return _get_font(
|
| 1524 |
+
# must be a tuple to be cached
|
| 1525 |
+
paths,
|
| 1526 |
+
hinting_factor,
|
| 1527 |
+
_kerning_factor=mpl.rcParams['text.kerning_factor'],
|
| 1528 |
+
# also key on the thread ID to prevent segfaults with multi-threading
|
| 1529 |
+
thread_id=threading.get_ident()
|
| 1530 |
+
)
|
| 1531 |
+
|
| 1532 |
+
|
| 1533 |
+
def _load_fontmanager(*, try_read_cache=True):
|
| 1534 |
+
fm_path = Path(
|
| 1535 |
+
mpl.get_cachedir(), f"fontlist-v{FontManager.__version__}.json")
|
| 1536 |
+
if try_read_cache:
|
| 1537 |
+
try:
|
| 1538 |
+
fm = json_load(fm_path)
|
| 1539 |
+
except Exception:
|
| 1540 |
+
pass
|
| 1541 |
+
else:
|
| 1542 |
+
if getattr(fm, "_version", object()) == FontManager.__version__:
|
| 1543 |
+
_log.debug("Using fontManager instance from %s", fm_path)
|
| 1544 |
+
return fm
|
| 1545 |
+
fm = FontManager()
|
| 1546 |
+
json_dump(fm, fm_path)
|
| 1547 |
+
_log.info("generated new fontManager")
|
| 1548 |
+
return fm
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
fontManager = _load_fontmanager()
|
| 1552 |
+
findfont = fontManager.findfont
|
| 1553 |
+
get_font_names = fontManager.get_font_names
|
omnilmm/lib/python3.10/site-packages/matplotlib/fontconfig_pattern.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from pyparsing import ParseException
|
| 3 |
+
|
| 4 |
+
from matplotlib._fontconfig_pattern import * # noqa: F401, F403
|
| 5 |
+
from matplotlib._fontconfig_pattern import (
|
| 6 |
+
parse_fontconfig_pattern, _family_punc, _value_punc)
|
| 7 |
+
from matplotlib import _api
|
| 8 |
+
_api.warn_deprecated("3.6", name=__name__, obj_type="module")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
family_unescape = re.compile(r'\\([%s])' % _family_punc).sub
|
| 12 |
+
value_unescape = re.compile(r'\\([%s])' % _value_punc).sub
|
| 13 |
+
family_escape = re.compile(r'([%s])' % _family_punc).sub
|
| 14 |
+
value_escape = re.compile(r'([%s])' % _value_punc).sub
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class FontconfigPatternParser:
|
| 18 |
+
ParseException = ParseException
|
| 19 |
+
|
| 20 |
+
def parse(self, pattern): return parse_fontconfig_pattern(pattern)
|
omnilmm/lib/python3.10/site-packages/matplotlib/hatch.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contains classes for generating hatch patterns."""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from matplotlib import _api
|
| 6 |
+
from matplotlib.path import Path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class HatchPatternBase:
|
| 10 |
+
"""The base class for a hatch pattern."""
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class HorizontalHatch(HatchPatternBase):
|
| 15 |
+
def __init__(self, hatch, density):
|
| 16 |
+
self.num_lines = int((hatch.count('-') + hatch.count('+')) * density)
|
| 17 |
+
self.num_vertices = self.num_lines * 2
|
| 18 |
+
|
| 19 |
+
def set_vertices_and_codes(self, vertices, codes):
|
| 20 |
+
steps, stepsize = np.linspace(0.0, 1.0, self.num_lines, False,
|
| 21 |
+
retstep=True)
|
| 22 |
+
steps += stepsize / 2.
|
| 23 |
+
vertices[0::2, 0] = 0.0
|
| 24 |
+
vertices[0::2, 1] = steps
|
| 25 |
+
vertices[1::2, 0] = 1.0
|
| 26 |
+
vertices[1::2, 1] = steps
|
| 27 |
+
codes[0::2] = Path.MOVETO
|
| 28 |
+
codes[1::2] = Path.LINETO
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class VerticalHatch(HatchPatternBase):
|
| 32 |
+
def __init__(self, hatch, density):
|
| 33 |
+
self.num_lines = int((hatch.count('|') + hatch.count('+')) * density)
|
| 34 |
+
self.num_vertices = self.num_lines * 2
|
| 35 |
+
|
| 36 |
+
def set_vertices_and_codes(self, vertices, codes):
|
| 37 |
+
steps, stepsize = np.linspace(0.0, 1.0, self.num_lines, False,
|
| 38 |
+
retstep=True)
|
| 39 |
+
steps += stepsize / 2.
|
| 40 |
+
vertices[0::2, 0] = steps
|
| 41 |
+
vertices[0::2, 1] = 0.0
|
| 42 |
+
vertices[1::2, 0] = steps
|
| 43 |
+
vertices[1::2, 1] = 1.0
|
| 44 |
+
codes[0::2] = Path.MOVETO
|
| 45 |
+
codes[1::2] = Path.LINETO
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class NorthEastHatch(HatchPatternBase):
|
| 49 |
+
def __init__(self, hatch, density):
|
| 50 |
+
self.num_lines = int(
|
| 51 |
+
(hatch.count('/') + hatch.count('x') + hatch.count('X')) * density)
|
| 52 |
+
if self.num_lines:
|
| 53 |
+
self.num_vertices = (self.num_lines + 1) * 2
|
| 54 |
+
else:
|
| 55 |
+
self.num_vertices = 0
|
| 56 |
+
|
| 57 |
+
def set_vertices_and_codes(self, vertices, codes):
|
| 58 |
+
steps = np.linspace(-0.5, 0.5, self.num_lines + 1)
|
| 59 |
+
vertices[0::2, 0] = 0.0 + steps
|
| 60 |
+
vertices[0::2, 1] = 0.0 - steps
|
| 61 |
+
vertices[1::2, 0] = 1.0 + steps
|
| 62 |
+
vertices[1::2, 1] = 1.0 - steps
|
| 63 |
+
codes[0::2] = Path.MOVETO
|
| 64 |
+
codes[1::2] = Path.LINETO
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class SouthEastHatch(HatchPatternBase):
|
| 68 |
+
def __init__(self, hatch, density):
|
| 69 |
+
self.num_lines = int(
|
| 70 |
+
(hatch.count('\\') + hatch.count('x') + hatch.count('X'))
|
| 71 |
+
* density)
|
| 72 |
+
if self.num_lines:
|
| 73 |
+
self.num_vertices = (self.num_lines + 1) * 2
|
| 74 |
+
else:
|
| 75 |
+
self.num_vertices = 0
|
| 76 |
+
|
| 77 |
+
def set_vertices_and_codes(self, vertices, codes):
|
| 78 |
+
steps = np.linspace(-0.5, 0.5, self.num_lines + 1)
|
| 79 |
+
vertices[0::2, 0] = 0.0 + steps
|
| 80 |
+
vertices[0::2, 1] = 1.0 + steps
|
| 81 |
+
vertices[1::2, 0] = 1.0 + steps
|
| 82 |
+
vertices[1::2, 1] = 0.0 + steps
|
| 83 |
+
codes[0::2] = Path.MOVETO
|
| 84 |
+
codes[1::2] = Path.LINETO
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Shapes(HatchPatternBase):
|
| 88 |
+
filled = False
|
| 89 |
+
|
| 90 |
+
def __init__(self, hatch, density):
|
| 91 |
+
if self.num_rows == 0:
|
| 92 |
+
self.num_shapes = 0
|
| 93 |
+
self.num_vertices = 0
|
| 94 |
+
else:
|
| 95 |
+
self.num_shapes = ((self.num_rows // 2 + 1) * (self.num_rows + 1) +
|
| 96 |
+
(self.num_rows // 2) * self.num_rows)
|
| 97 |
+
self.num_vertices = (self.num_shapes *
|
| 98 |
+
len(self.shape_vertices) *
|
| 99 |
+
(1 if self.filled else 2))
|
| 100 |
+
|
| 101 |
+
def set_vertices_and_codes(self, vertices, codes):
|
| 102 |
+
offset = 1.0 / self.num_rows
|
| 103 |
+
shape_vertices = self.shape_vertices * offset * self.size
|
| 104 |
+
shape_codes = self.shape_codes
|
| 105 |
+
if not self.filled:
|
| 106 |
+
shape_vertices = np.concatenate( # Forward, then backward.
|
| 107 |
+
[shape_vertices, shape_vertices[::-1] * 0.9])
|
| 108 |
+
shape_codes = np.concatenate([shape_codes, shape_codes])
|
| 109 |
+
vertices_parts = []
|
| 110 |
+
codes_parts = []
|
| 111 |
+
for row in range(self.num_rows + 1):
|
| 112 |
+
if row % 2 == 0:
|
| 113 |
+
cols = np.linspace(0, 1, self.num_rows + 1)
|
| 114 |
+
else:
|
| 115 |
+
cols = np.linspace(offset / 2, 1 - offset / 2, self.num_rows)
|
| 116 |
+
row_pos = row * offset
|
| 117 |
+
for col_pos in cols:
|
| 118 |
+
vertices_parts.append(shape_vertices + [col_pos, row_pos])
|
| 119 |
+
codes_parts.append(shape_codes)
|
| 120 |
+
np.concatenate(vertices_parts, out=vertices)
|
| 121 |
+
np.concatenate(codes_parts, out=codes)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class Circles(Shapes):
|
| 125 |
+
def __init__(self, hatch, density):
|
| 126 |
+
path = Path.unit_circle()
|
| 127 |
+
self.shape_vertices = path.vertices
|
| 128 |
+
self.shape_codes = path.codes
|
| 129 |
+
super().__init__(hatch, density)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class SmallCircles(Circles):
|
| 133 |
+
size = 0.2
|
| 134 |
+
|
| 135 |
+
def __init__(self, hatch, density):
|
| 136 |
+
self.num_rows = (hatch.count('o')) * density
|
| 137 |
+
super().__init__(hatch, density)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class LargeCircles(Circles):
|
| 141 |
+
size = 0.35
|
| 142 |
+
|
| 143 |
+
def __init__(self, hatch, density):
|
| 144 |
+
self.num_rows = (hatch.count('O')) * density
|
| 145 |
+
super().__init__(hatch, density)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class SmallFilledCircles(Circles):
|
| 149 |
+
size = 0.1
|
| 150 |
+
filled = True
|
| 151 |
+
|
| 152 |
+
def __init__(self, hatch, density):
|
| 153 |
+
self.num_rows = (hatch.count('.')) * density
|
| 154 |
+
super().__init__(hatch, density)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class Stars(Shapes):
|
| 158 |
+
size = 1.0 / 3.0
|
| 159 |
+
filled = True
|
| 160 |
+
|
| 161 |
+
def __init__(self, hatch, density):
|
| 162 |
+
self.num_rows = (hatch.count('*')) * density
|
| 163 |
+
path = Path.unit_regular_star(5)
|
| 164 |
+
self.shape_vertices = path.vertices
|
| 165 |
+
self.shape_codes = np.full(len(self.shape_vertices), Path.LINETO,
|
| 166 |
+
dtype=Path.code_type)
|
| 167 |
+
self.shape_codes[0] = Path.MOVETO
|
| 168 |
+
super().__init__(hatch, density)
|
| 169 |
+
|
| 170 |
+
_hatch_types = [
|
| 171 |
+
HorizontalHatch,
|
| 172 |
+
VerticalHatch,
|
| 173 |
+
NorthEastHatch,
|
| 174 |
+
SouthEastHatch,
|
| 175 |
+
SmallCircles,
|
| 176 |
+
LargeCircles,
|
| 177 |
+
SmallFilledCircles,
|
| 178 |
+
Stars
|
| 179 |
+
]
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _validate_hatch_pattern(hatch):
|
| 183 |
+
valid_hatch_patterns = set(r'-+|/\xXoO.*')
|
| 184 |
+
if hatch is not None:
|
| 185 |
+
invalids = set(hatch).difference(valid_hatch_patterns)
|
| 186 |
+
if invalids:
|
| 187 |
+
valid = ''.join(sorted(valid_hatch_patterns))
|
| 188 |
+
invalids = ''.join(sorted(invalids))
|
| 189 |
+
_api.warn_deprecated(
|
| 190 |
+
'3.4',
|
| 191 |
+
removal='3.8', # one release after custom hatches (#20690)
|
| 192 |
+
message=f'hatch must consist of a string of "{valid}" or '
|
| 193 |
+
'None, but found the following invalid values '
|
| 194 |
+
f'"{invalids}". Passing invalid values is deprecated '
|
| 195 |
+
'since %(since)s and will become an error %(removal)s.'
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_path(hatchpattern, density=6):
|
| 200 |
+
"""
|
| 201 |
+
Given a hatch specifier, *hatchpattern*, generates Path to render
|
| 202 |
+
the hatch in a unit square. *density* is the number of lines per
|
| 203 |
+
unit square.
|
| 204 |
+
"""
|
| 205 |
+
density = int(density)
|
| 206 |
+
|
| 207 |
+
patterns = [hatch_type(hatchpattern, density)
|
| 208 |
+
for hatch_type in _hatch_types]
|
| 209 |
+
num_vertices = sum([pattern.num_vertices for pattern in patterns])
|
| 210 |
+
|
| 211 |
+
if num_vertices == 0:
|
| 212 |
+
return Path(np.empty((0, 2)))
|
| 213 |
+
|
| 214 |
+
vertices = np.empty((num_vertices, 2))
|
| 215 |
+
codes = np.empty(num_vertices, Path.code_type)
|
| 216 |
+
|
| 217 |
+
cursor = 0
|
| 218 |
+
for pattern in patterns:
|
| 219 |
+
if pattern.num_vertices != 0:
|
| 220 |
+
vertices_chunk = vertices[cursor:cursor + pattern.num_vertices]
|
| 221 |
+
codes_chunk = codes[cursor:cursor + pattern.num_vertices]
|
| 222 |
+
pattern.set_vertices_and_codes(vertices_chunk, codes_chunk)
|
| 223 |
+
cursor += pattern.num_vertices
|
| 224 |
+
|
| 225 |
+
return Path(vertices, codes)
|
omnilmm/lib/python3.10/site-packages/matplotlib/image.py
ADDED
|
@@ -0,0 +1,1818 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 2 |
+
The image module supports basic image loading, rescaling and display
|
| 3 |
+
operations.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import logging
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import PIL.PngImagePlugin
|
| 14 |
+
|
| 15 |
+
import matplotlib as mpl
|
| 16 |
+
from matplotlib import _api, cbook, cm
|
| 17 |
+
# For clarity, names from _image are given explicitly in this module
|
| 18 |
+
from matplotlib import _image
|
| 19 |
+
# For user convenience, the names from _image are also imported into
|
| 20 |
+
# the image namespace
|
| 21 |
+
from matplotlib._image import *
|
| 22 |
+
import matplotlib.artist as martist
|
| 23 |
+
from matplotlib.backend_bases import FigureCanvasBase
|
| 24 |
+
import matplotlib.colors as mcolors
|
| 25 |
+
from matplotlib.transforms import (
|
| 26 |
+
Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo,
|
| 27 |
+
IdentityTransform, TransformedBbox)
|
| 28 |
+
|
| 29 |
+
_log = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# map interpolation strings to module constants
|
| 32 |
+
_interpd_ = {
|
| 33 |
+
'antialiased': _image.NEAREST, # this will use nearest or Hanning...
|
| 34 |
+
'none': _image.NEAREST, # fall back to nearest when not supported
|
| 35 |
+
'nearest': _image.NEAREST,
|
| 36 |
+
'bilinear': _image.BILINEAR,
|
| 37 |
+
'bicubic': _image.BICUBIC,
|
| 38 |
+
'spline16': _image.SPLINE16,
|
| 39 |
+
'spline36': _image.SPLINE36,
|
| 40 |
+
'hanning': _image.HANNING,
|
| 41 |
+
'hamming': _image.HAMMING,
|
| 42 |
+
'hermite': _image.HERMITE,
|
| 43 |
+
'kaiser': _image.KAISER,
|
| 44 |
+
'quadric': _image.QUADRIC,
|
| 45 |
+
'catrom': _image.CATROM,
|
| 46 |
+
'gaussian': _image.GAUSSIAN,
|
| 47 |
+
'bessel': _image.BESSEL,
|
| 48 |
+
'mitchell': _image.MITCHELL,
|
| 49 |
+
'sinc': _image.SINC,
|
| 50 |
+
'lanczos': _image.LANCZOS,
|
| 51 |
+
'blackman': _image.BLACKMAN,
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
interpolations_names = set(_interpd_)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def composite_images(images, renderer, magnification=1.0):
|
| 58 |
+
"""
|
| 59 |
+
Composite a number of RGBA images into one. The images are
|
| 60 |
+
composited in the order in which they appear in the *images* list.
|
| 61 |
+
|
| 62 |
+
Parameters
|
| 63 |
+
----------
|
| 64 |
+
images : list of Images
|
| 65 |
+
Each must have a `make_image` method. For each image,
|
| 66 |
+
`can_composite` should return `True`, though this is not
|
| 67 |
+
enforced by this function. Each image must have a purely
|
| 68 |
+
affine transformation with no shear.
|
| 69 |
+
|
| 70 |
+
renderer : `.RendererBase`
|
| 71 |
+
|
| 72 |
+
magnification : float, default: 1
|
| 73 |
+
The additional magnification to apply for the renderer in use.
|
| 74 |
+
|
| 75 |
+
Returns
|
| 76 |
+
-------
|
| 77 |
+
image : uint8 array (M, N, 4)
|
| 78 |
+
The composited RGBA image.
|
| 79 |
+
offset_x, offset_y : float
|
| 80 |
+
The (left, bottom) offset where the composited image should be placed
|
| 81 |
+
in the output figure.
|
| 82 |
+
"""
|
| 83 |
+
if len(images) == 0:
|
| 84 |
+
return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
|
| 85 |
+
|
| 86 |
+
parts = []
|
| 87 |
+
bboxes = []
|
| 88 |
+
for image in images:
|
| 89 |
+
data, x, y, trans = image.make_image(renderer, magnification)
|
| 90 |
+
if data is not None:
|
| 91 |
+
x *= magnification
|
| 92 |
+
y *= magnification
|
| 93 |
+
parts.append((data, x, y, image._get_scalar_alpha()))
|
| 94 |
+
bboxes.append(
|
| 95 |
+
Bbox([[x, y], [x + data.shape[1], y + data.shape[0]]]))
|
| 96 |
+
|
| 97 |
+
if len(parts) == 0:
|
| 98 |
+
return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
|
| 99 |
+
|
| 100 |
+
bbox = Bbox.union(bboxes)
|
| 101 |
+
|
| 102 |
+
output = np.zeros(
|
| 103 |
+
(int(bbox.height), int(bbox.width), 4), dtype=np.uint8)
|
| 104 |
+
|
| 105 |
+
for data, x, y, alpha in parts:
|
| 106 |
+
trans = Affine2D().translate(x - bbox.x0, y - bbox.y0)
|
| 107 |
+
_image.resample(data, output, trans, _image.NEAREST,
|
| 108 |
+
resample=False, alpha=alpha)
|
| 109 |
+
|
| 110 |
+
return output, bbox.x0 / magnification, bbox.y0 / magnification
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _draw_list_compositing_images(
|
| 114 |
+
renderer, parent, artists, suppress_composite=None):
|
| 115 |
+
"""
|
| 116 |
+
Draw a sorted list of artists, compositing images into a single
|
| 117 |
+
image where possible.
|
| 118 |
+
|
| 119 |
+
For internal Matplotlib use only: It is here to reduce duplication
|
| 120 |
+
between `Figure.draw` and `Axes.draw`, but otherwise should not be
|
| 121 |
+
generally useful.
|
| 122 |
+
"""
|
| 123 |
+
has_images = any(isinstance(x, _ImageBase) for x in artists)
|
| 124 |
+
|
| 125 |
+
# override the renderer default if suppressComposite is not None
|
| 126 |
+
not_composite = (suppress_composite if suppress_composite is not None
|
| 127 |
+
else renderer.option_image_nocomposite())
|
| 128 |
+
|
| 129 |
+
if not_composite or not has_images:
|
| 130 |
+
for a in artists:
|
| 131 |
+
a.draw(renderer)
|
| 132 |
+
else:
|
| 133 |
+
# Composite any adjacent images together
|
| 134 |
+
image_group = []
|
| 135 |
+
mag = renderer.get_image_magnification()
|
| 136 |
+
|
| 137 |
+
def flush_images():
|
| 138 |
+
if len(image_group) == 1:
|
| 139 |
+
image_group[0].draw(renderer)
|
| 140 |
+
elif len(image_group) > 1:
|
| 141 |
+
data, l, b = composite_images(image_group, renderer, mag)
|
| 142 |
+
if data.size != 0:
|
| 143 |
+
gc = renderer.new_gc()
|
| 144 |
+
gc.set_clip_rectangle(parent.bbox)
|
| 145 |
+
gc.set_clip_path(parent.get_clip_path())
|
| 146 |
+
renderer.draw_image(gc, round(l), round(b), data)
|
| 147 |
+
gc.restore()
|
| 148 |
+
del image_group[:]
|
| 149 |
+
|
| 150 |
+
for a in artists:
|
| 151 |
+
if (isinstance(a, _ImageBase) and a.can_composite() and
|
| 152 |
+
a.get_clip_on() and not a.get_clip_path()):
|
| 153 |
+
image_group.append(a)
|
| 154 |
+
else:
|
| 155 |
+
flush_images()
|
| 156 |
+
a.draw(renderer)
|
| 157 |
+
flush_images()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _resample(
|
| 161 |
+
image_obj, data, out_shape, transform, *, resample=None, alpha=1):
|
| 162 |
+
"""
|
| 163 |
+
Convenience wrapper around `._image.resample` to resample *data* to
|
| 164 |
+
*out_shape* (with a third dimension if *data* is RGBA) that takes care of
|
| 165 |
+
allocating the output array and fetching the relevant properties from the
|
| 166 |
+
Image object *image_obj*.
|
| 167 |
+
"""
|
| 168 |
+
# AGG can only handle coordinates smaller than 24-bit signed integers,
|
| 169 |
+
# so raise errors if the input data is larger than _image.resample can
|
| 170 |
+
# handle.
|
| 171 |
+
msg = ('Data with more than {n} cannot be accurately displayed. '
|
| 172 |
+
'Downsampling to less than {n} before displaying. '
|
| 173 |
+
'To remove this warning, manually downsample your data.')
|
| 174 |
+
if data.shape[1] > 2**23:
|
| 175 |
+
warnings.warn(msg.format(n='2**23 columns'))
|
| 176 |
+
step = int(np.ceil(data.shape[1] / 2**23))
|
| 177 |
+
data = data[:, ::step]
|
| 178 |
+
transform = Affine2D().scale(step, 1) + transform
|
| 179 |
+
if data.shape[0] > 2**24:
|
| 180 |
+
warnings.warn(msg.format(n='2**24 rows'))
|
| 181 |
+
step = int(np.ceil(data.shape[0] / 2**24))
|
| 182 |
+
data = data[::step, :]
|
| 183 |
+
transform = Affine2D().scale(1, step) + transform
|
| 184 |
+
# decide if we need to apply anti-aliasing if the data is upsampled:
|
| 185 |
+
# compare the number of displayed pixels to the number of
|
| 186 |
+
# the data pixels.
|
| 187 |
+
interpolation = image_obj.get_interpolation()
|
| 188 |
+
if interpolation == 'antialiased':
|
| 189 |
+
# don't antialias if upsampling by an integer number or
|
| 190 |
+
# if zooming in more than a factor of 3
|
| 191 |
+
pos = np.array([[0, 0], [data.shape[1], data.shape[0]]])
|
| 192 |
+
disp = transform.transform(pos)
|
| 193 |
+
dispx = np.abs(np.diff(disp[:, 0]))
|
| 194 |
+
dispy = np.abs(np.diff(disp[:, 1]))
|
| 195 |
+
if ((dispx > 3 * data.shape[1] or
|
| 196 |
+
dispx == data.shape[1] or
|
| 197 |
+
dispx == 2 * data.shape[1]) and
|
| 198 |
+
(dispy > 3 * data.shape[0] or
|
| 199 |
+
dispy == data.shape[0] or
|
| 200 |
+
dispy == 2 * data.shape[0])):
|
| 201 |
+
interpolation = 'nearest'
|
| 202 |
+
else:
|
| 203 |
+
interpolation = 'hanning'
|
| 204 |
+
out = np.zeros(out_shape + data.shape[2:], data.dtype) # 2D->2D, 3D->3D.
|
| 205 |
+
if resample is None:
|
| 206 |
+
resample = image_obj.get_resample()
|
| 207 |
+
_image.resample(data, out, transform,
|
| 208 |
+
_interpd_[interpolation],
|
| 209 |
+
resample,
|
| 210 |
+
alpha,
|
| 211 |
+
image_obj.get_filternorm(),
|
| 212 |
+
image_obj.get_filterrad())
|
| 213 |
+
return out
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _rgb_to_rgba(A):
|
| 217 |
+
"""
|
| 218 |
+
Convert an RGB image to RGBA, as required by the image resample C++
|
| 219 |
+
extension.
|
| 220 |
+
"""
|
| 221 |
+
rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype)
|
| 222 |
+
rgba[:, :, :3] = A
|
| 223 |
+
if rgba.dtype == np.uint8:
|
| 224 |
+
rgba[:, :, 3] = 255
|
| 225 |
+
else:
|
| 226 |
+
rgba[:, :, 3] = 1.0
|
| 227 |
+
return rgba
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class _ImageBase(martist.Artist, cm.ScalarMappable):
|
| 231 |
+
"""
|
| 232 |
+
Base class for images.
|
| 233 |
+
|
| 234 |
+
interpolation and cmap default to their rc settings
|
| 235 |
+
|
| 236 |
+
cmap is a colors.Colormap instance
|
| 237 |
+
norm is a colors.Normalize instance to map luminance to 0-1
|
| 238 |
+
|
| 239 |
+
extent is data axes (left, right, bottom, top) for making image plots
|
| 240 |
+
registered with data plots. Default is to label the pixel
|
| 241 |
+
centers with the zero-based row and column indices.
|
| 242 |
+
|
| 243 |
+
Additional kwargs are matplotlib.artist properties
|
| 244 |
+
"""
|
| 245 |
+
zorder = 0
|
| 246 |
+
|
| 247 |
+
def __init__(self, ax,
|
| 248 |
+
cmap=None,
|
| 249 |
+
norm=None,
|
| 250 |
+
interpolation=None,
|
| 251 |
+
origin=None,
|
| 252 |
+
filternorm=True,
|
| 253 |
+
filterrad=4.0,
|
| 254 |
+
resample=False,
|
| 255 |
+
*,
|
| 256 |
+
interpolation_stage=None,
|
| 257 |
+
**kwargs
|
| 258 |
+
):
|
| 259 |
+
martist.Artist.__init__(self)
|
| 260 |
+
cm.ScalarMappable.__init__(self, norm, cmap)
|
| 261 |
+
if origin is None:
|
| 262 |
+
origin = mpl.rcParams['image.origin']
|
| 263 |
+
_api.check_in_list(["upper", "lower"], origin=origin)
|
| 264 |
+
self.origin = origin
|
| 265 |
+
self.set_filternorm(filternorm)
|
| 266 |
+
self.set_filterrad(filterrad)
|
| 267 |
+
self.set_interpolation(interpolation)
|
| 268 |
+
self.set_interpolation_stage(interpolation_stage)
|
| 269 |
+
self.set_resample(resample)
|
| 270 |
+
self.axes = ax
|
| 271 |
+
|
| 272 |
+
self._imcache = None
|
| 273 |
+
|
| 274 |
+
self._internal_update(kwargs)
|
| 275 |
+
|
| 276 |
+
def __str__(self):
|
| 277 |
+
try:
|
| 278 |
+
size = self.get_size()
|
| 279 |
+
return f"{type(self).__name__}(size={size!r})"
|
| 280 |
+
except RuntimeError:
|
| 281 |
+
return type(self).__name__
|
| 282 |
+
|
| 283 |
+
def __getstate__(self):
|
| 284 |
+
# Save some space on the pickle by not saving the cache.
|
| 285 |
+
return {**super().__getstate__(), "_imcache": None}
|
| 286 |
+
|
| 287 |
+
def get_size(self):
|
| 288 |
+
"""Return the size of the image as tuple (numrows, numcols)."""
|
| 289 |
+
if self._A is None:
|
| 290 |
+
raise RuntimeError('You must first set the image array')
|
| 291 |
+
|
| 292 |
+
return self._A.shape[:2]
|
| 293 |
+
|
| 294 |
+
def set_alpha(self, alpha):
|
| 295 |
+
"""
|
| 296 |
+
Set the alpha value used for blending - not supported on all backends.
|
| 297 |
+
|
| 298 |
+
Parameters
|
| 299 |
+
----------
|
| 300 |
+
alpha : float or 2D array-like or None
|
| 301 |
+
"""
|
| 302 |
+
martist.Artist._set_alpha_for_array(self, alpha)
|
| 303 |
+
if np.ndim(alpha) not in (0, 2):
|
| 304 |
+
raise TypeError('alpha must be a float, two-dimensional '
|
| 305 |
+
'array, or None')
|
| 306 |
+
self._imcache = None
|
| 307 |
+
|
| 308 |
+
def _get_scalar_alpha(self):
|
| 309 |
+
"""
|
| 310 |
+
Get a scalar alpha value to be applied to the artist as a whole.
|
| 311 |
+
|
| 312 |
+
If the alpha value is a matrix, the method returns 1.0 because pixels
|
| 313 |
+
have individual alpha values (see `~._ImageBase._make_image` for
|
| 314 |
+
details). If the alpha value is a scalar, the method returns said value
|
| 315 |
+
to be applied to the artist as a whole because pixels do not have
|
| 316 |
+
individual alpha values.
|
| 317 |
+
"""
|
| 318 |
+
return 1.0 if self._alpha is None or np.ndim(self._alpha) > 0 \
|
| 319 |
+
else self._alpha
|
| 320 |
+
|
| 321 |
+
def changed(self):
|
| 322 |
+
"""
|
| 323 |
+
Call this whenever the mappable is changed so observers can update.
|
| 324 |
+
"""
|
| 325 |
+
self._imcache = None
|
| 326 |
+
cm.ScalarMappable.changed(self)
|
| 327 |
+
|
| 328 |
+
def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
|
| 329 |
+
unsampled=False, round_to_pixel_border=True):
|
| 330 |
+
"""
|
| 331 |
+
Normalize, rescale, and colormap the image *A* from the given *in_bbox*
|
| 332 |
+
(in data space), to the given *out_bbox* (in pixel space) clipped to
|
| 333 |
+
the given *clip_bbox* (also in pixel space), and magnified by the
|
| 334 |
+
*magnification* factor.
|
| 335 |
+
|
| 336 |
+
*A* may be a greyscale image (M, N) with a dtype of float32, float64,
|
| 337 |
+
float128, uint16 or uint8, or an (M, N, 4) RGBA image with a dtype of
|
| 338 |
+
float32, float64, float128, or uint8.
|
| 339 |
+
|
| 340 |
+
If *unsampled* is True, the image will not be scaled, but an
|
| 341 |
+
appropriate affine transformation will be returned instead.
|
| 342 |
+
|
| 343 |
+
If *round_to_pixel_border* is True, the output image size will be
|
| 344 |
+
rounded to the nearest pixel boundary. This makes the images align
|
| 345 |
+
correctly with the axes. It should not be used if exact scaling is
|
| 346 |
+
needed, such as for `FigureImage`.
|
| 347 |
+
|
| 348 |
+
Returns
|
| 349 |
+
-------
|
| 350 |
+
image : (M, N, 4) uint8 array
|
| 351 |
+
The RGBA image, resampled unless *unsampled* is True.
|
| 352 |
+
x, y : float
|
| 353 |
+
The upper left corner where the image should be drawn, in pixel
|
| 354 |
+
space.
|
| 355 |
+
trans : Affine2D
|
| 356 |
+
The affine transformation from image to pixel space.
|
| 357 |
+
"""
|
| 358 |
+
if A is None:
|
| 359 |
+
raise RuntimeError('You must first set the image '
|
| 360 |
+
'array or the image attribute')
|
| 361 |
+
if A.size == 0:
|
| 362 |
+
raise RuntimeError("_make_image must get a non-empty image. "
|
| 363 |
+
"Your Artist's draw method must filter before "
|
| 364 |
+
"this method is called.")
|
| 365 |
+
|
| 366 |
+
clipped_bbox = Bbox.intersection(out_bbox, clip_bbox)
|
| 367 |
+
|
| 368 |
+
if clipped_bbox is None:
|
| 369 |
+
return None, 0, 0, None
|
| 370 |
+
|
| 371 |
+
out_width_base = clipped_bbox.width * magnification
|
| 372 |
+
out_height_base = clipped_bbox.height * magnification
|
| 373 |
+
|
| 374 |
+
if out_width_base == 0 or out_height_base == 0:
|
| 375 |
+
return None, 0, 0, None
|
| 376 |
+
|
| 377 |
+
if self.origin == 'upper':
|
| 378 |
+
# Flip the input image using a transform. This avoids the
|
| 379 |
+
# problem with flipping the array, which results in a copy
|
| 380 |
+
# when it is converted to contiguous in the C wrapper
|
| 381 |
+
t0 = Affine2D().translate(0, -A.shape[0]).scale(1, -1)
|
| 382 |
+
else:
|
| 383 |
+
t0 = IdentityTransform()
|
| 384 |
+
|
| 385 |
+
t0 += (
|
| 386 |
+
Affine2D()
|
| 387 |
+
.scale(
|
| 388 |
+
in_bbox.width / A.shape[1],
|
| 389 |
+
in_bbox.height / A.shape[0])
|
| 390 |
+
.translate(in_bbox.x0, in_bbox.y0)
|
| 391 |
+
+ self.get_transform())
|
| 392 |
+
|
| 393 |
+
t = (t0
|
| 394 |
+
+ (Affine2D()
|
| 395 |
+
.translate(-clipped_bbox.x0, -clipped_bbox.y0)
|
| 396 |
+
.scale(magnification)))
|
| 397 |
+
|
| 398 |
+
# So that the image is aligned with the edge of the axes, we want to
|
| 399 |
+
# round up the output width to the next integer. This also means
|
| 400 |
+
# scaling the transform slightly to account for the extra subpixel.
|
| 401 |
+
if ((not unsampled) and t.is_affine and round_to_pixel_border and
|
| 402 |
+
(out_width_base % 1.0 != 0.0 or out_height_base % 1.0 != 0.0)):
|
| 403 |
+
out_width = math.ceil(out_width_base)
|
| 404 |
+
out_height = math.ceil(out_height_base)
|
| 405 |
+
extra_width = (out_width - out_width_base) / out_width_base
|
| 406 |
+
extra_height = (out_height - out_height_base) / out_height_base
|
| 407 |
+
t += Affine2D().scale(1.0 + extra_width, 1.0 + extra_height)
|
| 408 |
+
else:
|
| 409 |
+
out_width = int(out_width_base)
|
| 410 |
+
out_height = int(out_height_base)
|
| 411 |
+
out_shape = (out_height, out_width)
|
| 412 |
+
|
| 413 |
+
if not unsampled:
|
| 414 |
+
if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in (3, 4)):
|
| 415 |
+
raise ValueError(f"Invalid shape {A.shape} for image data")
|
| 416 |
+
if A.ndim == 2 and self._interpolation_stage != 'rgba':
|
| 417 |
+
# if we are a 2D array, then we are running through the
|
| 418 |
+
# norm + colormap transformation. However, in general the
|
| 419 |
+
# input data is not going to match the size on the screen so we
|
| 420 |
+
# have to resample to the correct number of pixels
|
| 421 |
+
|
| 422 |
+
# TODO slice input array first
|
| 423 |
+
a_min = A.min()
|
| 424 |
+
a_max = A.max()
|
| 425 |
+
if a_min is np.ma.masked: # All masked; values don't matter.
|
| 426 |
+
a_min, a_max = np.int32(0), np.int32(1)
|
| 427 |
+
if A.dtype.kind == 'f': # Float dtype: scale to same dtype.
|
| 428 |
+
scaled_dtype = np.dtype(
|
| 429 |
+
np.float64 if A.dtype.itemsize > 4 else np.float32)
|
| 430 |
+
if scaled_dtype.itemsize < A.dtype.itemsize:
|
| 431 |
+
_api.warn_external(f"Casting input data from {A.dtype}"
|
| 432 |
+
f" to {scaled_dtype} for imshow.")
|
| 433 |
+
else: # Int dtype, likely.
|
| 434 |
+
# Scale to appropriately sized float: use float32 if the
|
| 435 |
+
# dynamic range is small, to limit the memory footprint.
|
| 436 |
+
da = a_max.astype(np.float64) - a_min.astype(np.float64)
|
| 437 |
+
scaled_dtype = np.float64 if da > 1e8 else np.float32
|
| 438 |
+
|
| 439 |
+
# Scale the input data to [.1, .9]. The Agg interpolators clip
|
| 440 |
+
# to [0, 1] internally, and we use a smaller input scale to
|
| 441 |
+
# identify the interpolated points that need to be flagged as
|
| 442 |
+
# over/under. This may introduce numeric instabilities in very
|
| 443 |
+
# broadly scaled data.
|
| 444 |
+
|
| 445 |
+
# Always copy, and don't allow array subtypes.
|
| 446 |
+
A_scaled = np.array(A, dtype=scaled_dtype)
|
| 447 |
+
# Clip scaled data around norm if necessary. This is necessary
|
| 448 |
+
# for big numbers at the edge of float64's ability to represent
|
| 449 |
+
# changes. Applying a norm first would be good, but ruins the
|
| 450 |
+
# interpolation of over numbers.
|
| 451 |
+
self.norm.autoscale_None(A)
|
| 452 |
+
dv = np.float64(self.norm.vmax) - np.float64(self.norm.vmin)
|
| 453 |
+
vmid = np.float64(self.norm.vmin) + dv / 2
|
| 454 |
+
fact = 1e7 if scaled_dtype == np.float64 else 1e4
|
| 455 |
+
newmin = vmid - dv * fact
|
| 456 |
+
if newmin < a_min:
|
| 457 |
+
newmin = None
|
| 458 |
+
else:
|
| 459 |
+
a_min = np.float64(newmin)
|
| 460 |
+
newmax = vmid + dv * fact
|
| 461 |
+
if newmax > a_max:
|
| 462 |
+
newmax = None
|
| 463 |
+
else:
|
| 464 |
+
a_max = np.float64(newmax)
|
| 465 |
+
if newmax is not None or newmin is not None:
|
| 466 |
+
np.clip(A_scaled, newmin, newmax, out=A_scaled)
|
| 467 |
+
|
| 468 |
+
# Rescale the raw data to [offset, 1-offset] so that the
|
| 469 |
+
# resampling code will run cleanly. Using dyadic numbers here
|
| 470 |
+
# could reduce the error, but would not fully eliminate it and
|
| 471 |
+
# breaks a number of tests (due to the slightly different
|
| 472 |
+
# error bouncing some pixels across a boundary in the (very
|
| 473 |
+
# quantized) colormapping step).
|
| 474 |
+
offset = .1
|
| 475 |
+
frac = .8
|
| 476 |
+
# Run vmin/vmax through the same rescaling as the raw data;
|
| 477 |
+
# otherwise, data values close or equal to the boundaries can
|
| 478 |
+
# end up on the wrong side due to floating point error.
|
| 479 |
+
vmin, vmax = self.norm.vmin, self.norm.vmax
|
| 480 |
+
if vmin is np.ma.masked:
|
| 481 |
+
vmin, vmax = a_min, a_max
|
| 482 |
+
vrange = np.array([vmin, vmax], dtype=scaled_dtype)
|
| 483 |
+
|
| 484 |
+
A_scaled -= a_min
|
| 485 |
+
vrange -= a_min
|
| 486 |
+
# .item() handles a_min/a_max being ndarray subclasses.
|
| 487 |
+
a_min = a_min.astype(scaled_dtype).item()
|
| 488 |
+
a_max = a_max.astype(scaled_dtype).item()
|
| 489 |
+
|
| 490 |
+
if a_min != a_max:
|
| 491 |
+
A_scaled /= ((a_max - a_min) / frac)
|
| 492 |
+
vrange /= ((a_max - a_min) / frac)
|
| 493 |
+
A_scaled += offset
|
| 494 |
+
vrange += offset
|
| 495 |
+
# resample the input data to the correct resolution and shape
|
| 496 |
+
A_resampled = _resample(self, A_scaled, out_shape, t)
|
| 497 |
+
del A_scaled # Make sure we don't use A_scaled anymore!
|
| 498 |
+
# Un-scale the resampled data to approximately the original
|
| 499 |
+
# range. Things that interpolated to outside the original range
|
| 500 |
+
# will still be outside, but possibly clipped in the case of
|
| 501 |
+
# higher order interpolation + drastically changing data.
|
| 502 |
+
A_resampled -= offset
|
| 503 |
+
vrange -= offset
|
| 504 |
+
if a_min != a_max:
|
| 505 |
+
A_resampled *= ((a_max - a_min) / frac)
|
| 506 |
+
vrange *= ((a_max - a_min) / frac)
|
| 507 |
+
A_resampled += a_min
|
| 508 |
+
vrange += a_min
|
| 509 |
+
# if using NoNorm, cast back to the original datatype
|
| 510 |
+
if isinstance(self.norm, mcolors.NoNorm):
|
| 511 |
+
A_resampled = A_resampled.astype(A.dtype)
|
| 512 |
+
|
| 513 |
+
mask = (np.where(A.mask, np.float32(np.nan), np.float32(1))
|
| 514 |
+
if A.mask.shape == A.shape # nontrivial mask
|
| 515 |
+
else np.ones_like(A, np.float32))
|
| 516 |
+
# we always have to interpolate the mask to account for
|
| 517 |
+
# non-affine transformations
|
| 518 |
+
out_alpha = _resample(self, mask, out_shape, t, resample=True)
|
| 519 |
+
del mask # Make sure we don't use mask anymore!
|
| 520 |
+
# Agg updates out_alpha in place. If the pixel has no image
|
| 521 |
+
# data it will not be updated (and still be 0 as we initialized
|
| 522 |
+
# it), if input data that would go into that output pixel than
|
| 523 |
+
# it will be `nan`, if all the input data for a pixel is good
|
| 524 |
+
# it will be 1, and if there is _some_ good data in that output
|
| 525 |
+
# pixel it will be between [0, 1] (such as a rotated image).
|
| 526 |
+
out_mask = np.isnan(out_alpha)
|
| 527 |
+
out_alpha[out_mask] = 1
|
| 528 |
+
# Apply the pixel-by-pixel alpha values if present
|
| 529 |
+
alpha = self.get_alpha()
|
| 530 |
+
if alpha is not None and np.ndim(alpha) > 0:
|
| 531 |
+
out_alpha *= _resample(self, alpha, out_shape,
|
| 532 |
+
t, resample=True)
|
| 533 |
+
# mask and run through the norm
|
| 534 |
+
resampled_masked = np.ma.masked_array(A_resampled, out_mask)
|
| 535 |
+
# we have re-set the vmin/vmax to account for small errors
|
| 536 |
+
# that may have moved input values in/out of range
|
| 537 |
+
s_vmin, s_vmax = vrange
|
| 538 |
+
if isinstance(self.norm, mcolors.LogNorm) and s_vmin <= 0:
|
| 539 |
+
# Don't give 0 or negative values to LogNorm
|
| 540 |
+
s_vmin = np.finfo(scaled_dtype).eps
|
| 541 |
+
# Block the norm from sending an update signal during the
|
| 542 |
+
# temporary vmin/vmax change
|
| 543 |
+
with self.norm.callbacks.blocked(), \
|
| 544 |
+
cbook._setattr_cm(self.norm, vmin=s_vmin, vmax=s_vmax):
|
| 545 |
+
output = self.norm(resampled_masked)
|
| 546 |
+
else:
|
| 547 |
+
if A.ndim == 2: # _interpolation_stage == 'rgba'
|
| 548 |
+
self.norm.autoscale_None(A)
|
| 549 |
+
A = self.to_rgba(A)
|
| 550 |
+
if A.shape[2] == 3:
|
| 551 |
+
A = _rgb_to_rgba(A)
|
| 552 |
+
alpha = self._get_scalar_alpha()
|
| 553 |
+
output_alpha = _resample( # resample alpha channel
|
| 554 |
+
self, A[..., 3], out_shape, t, alpha=alpha)
|
| 555 |
+
output = _resample( # resample rgb channels
|
| 556 |
+
self, _rgb_to_rgba(A[..., :3]), out_shape, t, alpha=alpha)
|
| 557 |
+
output[..., 3] = output_alpha # recombine rgb and alpha
|
| 558 |
+
|
| 559 |
+
# output is now either a 2D array of normed (int or float) data
|
| 560 |
+
# or an RGBA array of re-sampled input
|
| 561 |
+
output = self.to_rgba(output, bytes=True, norm=False)
|
| 562 |
+
# output is now a correctly sized RGBA array of uint8
|
| 563 |
+
|
| 564 |
+
# Apply alpha *after* if the input was greyscale without a mask
|
| 565 |
+
if A.ndim == 2:
|
| 566 |
+
alpha = self._get_scalar_alpha()
|
| 567 |
+
alpha_channel = output[:, :, 3]
|
| 568 |
+
alpha_channel[:] = ( # Assignment will cast to uint8.
|
| 569 |
+
alpha_channel.astype(np.float32) * out_alpha * alpha)
|
| 570 |
+
|
| 571 |
+
else:
|
| 572 |
+
if self._imcache is None:
|
| 573 |
+
self._imcache = self.to_rgba(A, bytes=True, norm=(A.ndim == 2))
|
| 574 |
+
output = self._imcache
|
| 575 |
+
|
| 576 |
+
# Subset the input image to only the part that will be displayed.
|
| 577 |
+
subset = TransformedBbox(clip_bbox, t0.inverted()).frozen()
|
| 578 |
+
output = output[
|
| 579 |
+
int(max(subset.ymin, 0)):
|
| 580 |
+
int(min(subset.ymax + 1, output.shape[0])),
|
| 581 |
+
int(max(subset.xmin, 0)):
|
| 582 |
+
int(min(subset.xmax + 1, output.shape[1]))]
|
| 583 |
+
|
| 584 |
+
t = Affine2D().translate(
|
| 585 |
+
int(max(subset.xmin, 0)), int(max(subset.ymin, 0))) + t
|
| 586 |
+
|
| 587 |
+
return output, clipped_bbox.x0, clipped_bbox.y0, t
|
| 588 |
+
|
| 589 |
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
| 590 |
+
"""
|
| 591 |
+
Normalize, rescale, and colormap this image's data for rendering using
|
| 592 |
+
*renderer*, with the given *magnification*.
|
| 593 |
+
|
| 594 |
+
If *unsampled* is True, the image will not be scaled, but an
|
| 595 |
+
appropriate affine transformation will be returned instead.
|
| 596 |
+
|
| 597 |
+
Returns
|
| 598 |
+
-------
|
| 599 |
+
image : (M, N, 4) uint8 array
|
| 600 |
+
The RGBA image, resampled unless *unsampled* is True.
|
| 601 |
+
x, y : float
|
| 602 |
+
The upper left corner where the image should be drawn, in pixel
|
| 603 |
+
space.
|
| 604 |
+
trans : Affine2D
|
| 605 |
+
The affine transformation from image to pixel space.
|
| 606 |
+
"""
|
| 607 |
+
raise NotImplementedError('The make_image method must be overridden')
|
| 608 |
+
|
| 609 |
+
def _check_unsampled_image(self):
|
| 610 |
+
"""
|
| 611 |
+
Return whether the image is better to be drawn unsampled.
|
| 612 |
+
|
| 613 |
+
The derived class needs to override it.
|
| 614 |
+
"""
|
| 615 |
+
return False
|
| 616 |
+
|
| 617 |
+
@martist.allow_rasterization
|
| 618 |
+
def draw(self, renderer, *args, **kwargs):
|
| 619 |
+
# if not visible, declare victory and return
|
| 620 |
+
if not self.get_visible():
|
| 621 |
+
self.stale = False
|
| 622 |
+
return
|
| 623 |
+
# for empty images, there is nothing to draw!
|
| 624 |
+
if self.get_array().size == 0:
|
| 625 |
+
self.stale = False
|
| 626 |
+
return
|
| 627 |
+
# actually render the image.
|
| 628 |
+
gc = renderer.new_gc()
|
| 629 |
+
self._set_gc_clip(gc)
|
| 630 |
+
gc.set_alpha(self._get_scalar_alpha())
|
| 631 |
+
gc.set_url(self.get_url())
|
| 632 |
+
gc.set_gid(self.get_gid())
|
| 633 |
+
if (renderer.option_scale_image() # Renderer supports transform kwarg.
|
| 634 |
+
and self._check_unsampled_image()
|
| 635 |
+
and self.get_transform().is_affine):
|
| 636 |
+
im, l, b, trans = self.make_image(renderer, unsampled=True)
|
| 637 |
+
if im is not None:
|
| 638 |
+
trans = Affine2D().scale(im.shape[1], im.shape[0]) + trans
|
| 639 |
+
renderer.draw_image(gc, l, b, im, trans)
|
| 640 |
+
else:
|
| 641 |
+
im, l, b, trans = self.make_image(
|
| 642 |
+
renderer, renderer.get_image_magnification())
|
| 643 |
+
if im is not None:
|
| 644 |
+
renderer.draw_image(gc, l, b, im)
|
| 645 |
+
gc.restore()
|
| 646 |
+
self.stale = False
|
| 647 |
+
|
| 648 |
+
def contains(self, mouseevent):
|
| 649 |
+
"""Test whether the mouse event occurred within the image."""
|
| 650 |
+
inside, info = self._default_contains(mouseevent)
|
| 651 |
+
if inside is not None:
|
| 652 |
+
return inside, info
|
| 653 |
+
# 1) This doesn't work for figimage; but figimage also needs a fix
|
| 654 |
+
# below (as the check cannot use x/ydata and extents).
|
| 655 |
+
# 2) As long as the check below uses x/ydata, we need to test axes
|
| 656 |
+
# identity instead of `self.axes.contains(event)` because even if
|
| 657 |
+
# axes overlap, x/ydata is only valid for event.inaxes anyways.
|
| 658 |
+
if self.axes is not mouseevent.inaxes:
|
| 659 |
+
return False, {}
|
| 660 |
+
# TODO: make sure this is consistent with patch and patch
|
| 661 |
+
# collection on nonlinear transformed coordinates.
|
| 662 |
+
# TODO: consider returning image coordinates (shouldn't
|
| 663 |
+
# be too difficult given that the image is rectilinear
|
| 664 |
+
trans = self.get_transform().inverted()
|
| 665 |
+
x, y = trans.transform([mouseevent.x, mouseevent.y])
|
| 666 |
+
xmin, xmax, ymin, ymax = self.get_extent()
|
| 667 |
+
if xmin > xmax:
|
| 668 |
+
xmin, xmax = xmax, xmin
|
| 669 |
+
if ymin > ymax:
|
| 670 |
+
ymin, ymax = ymax, ymin
|
| 671 |
+
|
| 672 |
+
if x is not None and y is not None:
|
| 673 |
+
inside = (xmin <= x <= xmax) and (ymin <= y <= ymax)
|
| 674 |
+
else:
|
| 675 |
+
inside = False
|
| 676 |
+
|
| 677 |
+
return inside, {}
|
| 678 |
+
|
| 679 |
+
def write_png(self, fname):
|
| 680 |
+
"""Write the image to png file *fname*."""
|
| 681 |
+
im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
|
| 682 |
+
bytes=True, norm=True)
|
| 683 |
+
PIL.Image.fromarray(im).save(fname, format="png")
|
| 684 |
+
|
| 685 |
+
def set_data(self, A):
|
| 686 |
+
"""
|
| 687 |
+
Set the image array.
|
| 688 |
+
|
| 689 |
+
Note that this function does *not* update the normalization used.
|
| 690 |
+
|
| 691 |
+
Parameters
|
| 692 |
+
----------
|
| 693 |
+
A : array-like or `PIL.Image.Image`
|
| 694 |
+
"""
|
| 695 |
+
if isinstance(A, PIL.Image.Image):
|
| 696 |
+
A = pil_to_array(A) # Needed e.g. to apply png palette.
|
| 697 |
+
self._A = cbook.safe_masked_invalid(A, copy=True)
|
| 698 |
+
|
| 699 |
+
if (self._A.dtype != np.uint8 and
|
| 700 |
+
not np.can_cast(self._A.dtype, float, "same_kind")):
|
| 701 |
+
raise TypeError("Image data of dtype {} cannot be converted to "
|
| 702 |
+
"float".format(self._A.dtype))
|
| 703 |
+
|
| 704 |
+
if self._A.ndim == 3 and self._A.shape[-1] == 1:
|
| 705 |
+
# If just one dimension assume scalar and apply colormap
|
| 706 |
+
self._A = self._A[:, :, 0]
|
| 707 |
+
|
| 708 |
+
if not (self._A.ndim == 2
|
| 709 |
+
or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
|
| 710 |
+
raise TypeError("Invalid shape {} for image data"
|
| 711 |
+
.format(self._A.shape))
|
| 712 |
+
|
| 713 |
+
if self._A.ndim == 3:
|
| 714 |
+
# If the input data has values outside the valid range (after
|
| 715 |
+
# normalisation), we issue a warning and then clip X to the bounds
|
| 716 |
+
# - otherwise casting wraps extreme values, hiding outliers and
|
| 717 |
+
# making reliable interpretation impossible.
|
| 718 |
+
high = 255 if np.issubdtype(self._A.dtype, np.integer) else 1
|
| 719 |
+
if self._A.min() < 0 or high < self._A.max():
|
| 720 |
+
_log.warning(
|
| 721 |
+
'Clipping input data to the valid range for imshow with '
|
| 722 |
+
'RGB data ([0..1] for floats or [0..255] for integers).'
|
| 723 |
+
)
|
| 724 |
+
self._A = np.clip(self._A, 0, high)
|
| 725 |
+
# Cast unsupported integer types to uint8
|
| 726 |
+
if self._A.dtype != np.uint8 and np.issubdtype(self._A.dtype,
|
| 727 |
+
np.integer):
|
| 728 |
+
self._A = self._A.astype(np.uint8)
|
| 729 |
+
|
| 730 |
+
self._imcache = None
|
| 731 |
+
self.stale = True
|
| 732 |
+
|
| 733 |
+
def set_array(self, A):
|
| 734 |
+
"""
|
| 735 |
+
Retained for backwards compatibility - use set_data instead.
|
| 736 |
+
|
| 737 |
+
Parameters
|
| 738 |
+
----------
|
| 739 |
+
A : array-like
|
| 740 |
+
"""
|
| 741 |
+
# This also needs to be here to override the inherited
|
| 742 |
+
# cm.ScalarMappable.set_array method so it is not invoked by mistake.
|
| 743 |
+
self.set_data(A)
|
| 744 |
+
|
| 745 |
+
def get_interpolation(self):
|
| 746 |
+
"""
|
| 747 |
+
Return the interpolation method the image uses when resizing.
|
| 748 |
+
|
| 749 |
+
One of 'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16',
|
| 750 |
+
'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
|
| 751 |
+
'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos',
|
| 752 |
+
or 'none'.
|
| 753 |
+
"""
|
| 754 |
+
return self._interpolation
|
| 755 |
+
|
| 756 |
+
def set_interpolation(self, s):
|
| 757 |
+
"""
|
| 758 |
+
Set the interpolation method the image uses when resizing.
|
| 759 |
+
|
| 760 |
+
If None, use :rc:`image.interpolation`. If 'none', the image is
|
| 761 |
+
shown as is without interpolating. 'none' is only supported in
|
| 762 |
+
agg, ps and pdf backends and will fall back to 'nearest' mode
|
| 763 |
+
for other backends.
|
| 764 |
+
|
| 765 |
+
Parameters
|
| 766 |
+
----------
|
| 767 |
+
s : {'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', \
|
| 768 |
+
'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', \
|
| 769 |
+
'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'} or None
|
| 770 |
+
"""
|
| 771 |
+
if s is None:
|
| 772 |
+
s = mpl.rcParams['image.interpolation']
|
| 773 |
+
s = s.lower()
|
| 774 |
+
_api.check_in_list(_interpd_, interpolation=s)
|
| 775 |
+
self._interpolation = s
|
| 776 |
+
self.stale = True
|
| 777 |
+
|
| 778 |
+
def set_interpolation_stage(self, s):
|
| 779 |
+
"""
|
| 780 |
+
Set when interpolation happens during the transform to RGBA.
|
| 781 |
+
|
| 782 |
+
Parameters
|
| 783 |
+
----------
|
| 784 |
+
s : {'data', 'rgba'} or None
|
| 785 |
+
Whether to apply up/downsampling interpolation in data or rgba
|
| 786 |
+
space.
|
| 787 |
+
"""
|
| 788 |
+
if s is None:
|
| 789 |
+
s = "data" # placeholder for maybe having rcParam
|
| 790 |
+
_api.check_in_list(['data', 'rgba'], s=s)
|
| 791 |
+
self._interpolation_stage = s
|
| 792 |
+
self.stale = True
|
| 793 |
+
|
| 794 |
+
def can_composite(self):
|
| 795 |
+
"""Return whether the image can be composited with its neighbors."""
|
| 796 |
+
trans = self.get_transform()
|
| 797 |
+
return (
|
| 798 |
+
self._interpolation != 'none' and
|
| 799 |
+
trans.is_affine and
|
| 800 |
+
trans.is_separable)
|
| 801 |
+
|
| 802 |
+
def set_resample(self, v):
|
| 803 |
+
"""
|
| 804 |
+
Set whether image resampling is used.
|
| 805 |
+
|
| 806 |
+
Parameters
|
| 807 |
+
----------
|
| 808 |
+
v : bool or None
|
| 809 |
+
If None, use :rc:`image.resample`.
|
| 810 |
+
"""
|
| 811 |
+
if v is None:
|
| 812 |
+
v = mpl.rcParams['image.resample']
|
| 813 |
+
self._resample = v
|
| 814 |
+
self.stale = True
|
| 815 |
+
|
| 816 |
+
def get_resample(self):
|
| 817 |
+
"""Return whether image resampling is used."""
|
| 818 |
+
return self._resample
|
| 819 |
+
|
| 820 |
+
def set_filternorm(self, filternorm):
|
| 821 |
+
"""
|
| 822 |
+
Set whether the resize filter normalizes the weights.
|
| 823 |
+
|
| 824 |
+
See help for `~.Axes.imshow`.
|
| 825 |
+
|
| 826 |
+
Parameters
|
| 827 |
+
----------
|
| 828 |
+
filternorm : bool
|
| 829 |
+
"""
|
| 830 |
+
self._filternorm = bool(filternorm)
|
| 831 |
+
self.stale = True
|
| 832 |
+
|
| 833 |
+
def get_filternorm(self):
|
| 834 |
+
"""Return whether the resize filter normalizes the weights."""
|
| 835 |
+
return self._filternorm
|
| 836 |
+
|
| 837 |
+
def set_filterrad(self, filterrad):
|
| 838 |
+
"""
|
| 839 |
+
Set the resize filter radius only applicable to some
|
| 840 |
+
interpolation schemes -- see help for imshow
|
| 841 |
+
|
| 842 |
+
Parameters
|
| 843 |
+
----------
|
| 844 |
+
filterrad : positive float
|
| 845 |
+
"""
|
| 846 |
+
r = float(filterrad)
|
| 847 |
+
if r <= 0:
|
| 848 |
+
raise ValueError("The filter radius must be a positive number")
|
| 849 |
+
self._filterrad = r
|
| 850 |
+
self.stale = True
|
| 851 |
+
|
| 852 |
+
def get_filterrad(self):
|
| 853 |
+
"""Return the filterrad setting."""
|
| 854 |
+
return self._filterrad
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
class AxesImage(_ImageBase):
|
| 858 |
+
"""
|
| 859 |
+
An image attached to an Axes.
|
| 860 |
+
|
| 861 |
+
Parameters
|
| 862 |
+
----------
|
| 863 |
+
ax : `~matplotlib.axes.Axes`
|
| 864 |
+
The axes the image will belong to.
|
| 865 |
+
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
|
| 866 |
+
The Colormap instance or registered colormap name used to map scalar
|
| 867 |
+
data to colors.
|
| 868 |
+
norm : str or `~matplotlib.colors.Normalize`
|
| 869 |
+
Maps luminance to 0-1.
|
| 870 |
+
interpolation : str, default: :rc:`image.interpolation`
|
| 871 |
+
Supported values are 'none', 'antialiased', 'nearest', 'bilinear',
|
| 872 |
+
'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',
|
| 873 |
+
'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',
|
| 874 |
+
'sinc', 'lanczos', 'blackman'.
|
| 875 |
+
interpolation_stage : {'data', 'rgba'}, default: 'data'
|
| 876 |
+
If 'data', interpolation
|
| 877 |
+
is carried out on the data provided by the user. If 'rgba', the
|
| 878 |
+
interpolation is carried out after the colormapping has been
|
| 879 |
+
applied (visual interpolation).
|
| 880 |
+
origin : {'upper', 'lower'}, default: :rc:`image.origin`
|
| 881 |
+
Place the [0, 0] index of the array in the upper left or lower left
|
| 882 |
+
corner of the axes. The convention 'upper' is typically used for
|
| 883 |
+
matrices and images.
|
| 884 |
+
extent : tuple, optional
|
| 885 |
+
The data axes (left, right, bottom, top) for making image plots
|
| 886 |
+
registered with data plots. Default is to label the pixel
|
| 887 |
+
centers with the zero-based row and column indices.
|
| 888 |
+
filternorm : bool, default: True
|
| 889 |
+
A parameter for the antigrain image resize filter
|
| 890 |
+
(see the antigrain documentation).
|
| 891 |
+
If filternorm is set, the filter normalizes integer values and corrects
|
| 892 |
+
the rounding errors. It doesn't do anything with the source floating
|
| 893 |
+
point values, it corrects only integers according to the rule of 1.0
|
| 894 |
+
which means that any sum of pixel weights must be equal to 1.0. So,
|
| 895 |
+
the filter function must produce a graph of the proper shape.
|
| 896 |
+
filterrad : float > 0, default: 4
|
| 897 |
+
The filter radius for filters that have a radius parameter, i.e. when
|
| 898 |
+
interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
|
| 899 |
+
resample : bool, default: False
|
| 900 |
+
When True, use a full resampling method. When False, only resample when
|
| 901 |
+
the output image is larger than the input image.
|
| 902 |
+
**kwargs : `~matplotlib.artist.Artist` properties
|
| 903 |
+
"""
|
| 904 |
+
|
| 905 |
+
@_api.make_keyword_only("3.6", name="cmap")
|
| 906 |
+
def __init__(self, ax,
|
| 907 |
+
cmap=None,
|
| 908 |
+
norm=None,
|
| 909 |
+
interpolation=None,
|
| 910 |
+
origin=None,
|
| 911 |
+
extent=None,
|
| 912 |
+
filternorm=True,
|
| 913 |
+
filterrad=4.0,
|
| 914 |
+
resample=False,
|
| 915 |
+
*,
|
| 916 |
+
interpolation_stage=None,
|
| 917 |
+
**kwargs
|
| 918 |
+
):
|
| 919 |
+
|
| 920 |
+
self._extent = extent
|
| 921 |
+
|
| 922 |
+
super().__init__(
|
| 923 |
+
ax,
|
| 924 |
+
cmap=cmap,
|
| 925 |
+
norm=norm,
|
| 926 |
+
interpolation=interpolation,
|
| 927 |
+
origin=origin,
|
| 928 |
+
filternorm=filternorm,
|
| 929 |
+
filterrad=filterrad,
|
| 930 |
+
resample=resample,
|
| 931 |
+
interpolation_stage=interpolation_stage,
|
| 932 |
+
**kwargs
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
def get_window_extent(self, renderer=None):
|
| 936 |
+
x0, x1, y0, y1 = self._extent
|
| 937 |
+
bbox = Bbox.from_extents([x0, y0, x1, y1])
|
| 938 |
+
return bbox.transformed(self.get_transform())
|
| 939 |
+
|
| 940 |
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
| 941 |
+
# docstring inherited
|
| 942 |
+
trans = self.get_transform()
|
| 943 |
+
# image is created in the canvas coordinate.
|
| 944 |
+
x1, x2, y1, y2 = self.get_extent()
|
| 945 |
+
bbox = Bbox(np.array([[x1, y1], [x2, y2]]))
|
| 946 |
+
transformed_bbox = TransformedBbox(bbox, trans)
|
| 947 |
+
clip = ((self.get_clip_box() or self.axes.bbox) if self.get_clip_on()
|
| 948 |
+
else self.figure.bbox)
|
| 949 |
+
return self._make_image(self._A, bbox, transformed_bbox, clip,
|
| 950 |
+
magnification, unsampled=unsampled)
|
| 951 |
+
|
| 952 |
+
def _check_unsampled_image(self):
|
| 953 |
+
"""Return whether the image would be better drawn unsampled."""
|
| 954 |
+
return self.get_interpolation() == "none"
|
| 955 |
+
|
| 956 |
+
def set_extent(self, extent, **kwargs):
|
| 957 |
+
"""
|
| 958 |
+
Set the image extent.
|
| 959 |
+
|
| 960 |
+
Parameters
|
| 961 |
+
----------
|
| 962 |
+
extent : 4-tuple of float
|
| 963 |
+
The position and size of the image as tuple
|
| 964 |
+
``(left, right, bottom, top)`` in data coordinates.
|
| 965 |
+
**kwargs
|
| 966 |
+
Other parameters from which unit info (i.e., the *xunits*,
|
| 967 |
+
*yunits*, *zunits* (for 3D axes), *runits* and *thetaunits* (for
|
| 968 |
+
polar axes) entries are applied, if present.
|
| 969 |
+
|
| 970 |
+
Notes
|
| 971 |
+
-----
|
| 972 |
+
This updates ``ax.dataLim``, and, if autoscaling, sets ``ax.viewLim``
|
| 973 |
+
to tightly fit the image, regardless of ``dataLim``. Autoscaling
|
| 974 |
+
state is not changed, so following this with ``ax.autoscale_view()``
|
| 975 |
+
will redo the autoscaling in accord with ``dataLim``.
|
| 976 |
+
"""
|
| 977 |
+
(xmin, xmax), (ymin, ymax) = self.axes._process_unit_info(
|
| 978 |
+
[("x", [extent[0], extent[1]]),
|
| 979 |
+
("y", [extent[2], extent[3]])],
|
| 980 |
+
kwargs)
|
| 981 |
+
if kwargs:
|
| 982 |
+
raise _api.kwarg_error("set_extent", kwargs)
|
| 983 |
+
xmin = self.axes._validate_converted_limits(
|
| 984 |
+
xmin, self.convert_xunits)
|
| 985 |
+
xmax = self.axes._validate_converted_limits(
|
| 986 |
+
xmax, self.convert_xunits)
|
| 987 |
+
ymin = self.axes._validate_converted_limits(
|
| 988 |
+
ymin, self.convert_yunits)
|
| 989 |
+
ymax = self.axes._validate_converted_limits(
|
| 990 |
+
ymax, self.convert_yunits)
|
| 991 |
+
extent = [xmin, xmax, ymin, ymax]
|
| 992 |
+
|
| 993 |
+
self._extent = extent
|
| 994 |
+
corners = (xmin, ymin), (xmax, ymax)
|
| 995 |
+
self.axes.update_datalim(corners)
|
| 996 |
+
self.sticky_edges.x[:] = [xmin, xmax]
|
| 997 |
+
self.sticky_edges.y[:] = [ymin, ymax]
|
| 998 |
+
if self.axes.get_autoscalex_on():
|
| 999 |
+
self.axes.set_xlim((xmin, xmax), auto=None)
|
| 1000 |
+
if self.axes.get_autoscaley_on():
|
| 1001 |
+
self.axes.set_ylim((ymin, ymax), auto=None)
|
| 1002 |
+
self.stale = True
|
| 1003 |
+
|
| 1004 |
+
def get_extent(self):
|
| 1005 |
+
"""Return the image extent as tuple (left, right, bottom, top)."""
|
| 1006 |
+
if self._extent is not None:
|
| 1007 |
+
return self._extent
|
| 1008 |
+
else:
|
| 1009 |
+
sz = self.get_size()
|
| 1010 |
+
numrows, numcols = sz
|
| 1011 |
+
if self.origin == 'upper':
|
| 1012 |
+
return (-0.5, numcols-0.5, numrows-0.5, -0.5)
|
| 1013 |
+
else:
|
| 1014 |
+
return (-0.5, numcols-0.5, -0.5, numrows-0.5)
|
| 1015 |
+
|
| 1016 |
+
def get_cursor_data(self, event):
|
| 1017 |
+
"""
|
| 1018 |
+
Return the image value at the event position or *None* if the event is
|
| 1019 |
+
outside the image.
|
| 1020 |
+
|
| 1021 |
+
See Also
|
| 1022 |
+
--------
|
| 1023 |
+
matplotlib.artist.Artist.get_cursor_data
|
| 1024 |
+
"""
|
| 1025 |
+
xmin, xmax, ymin, ymax = self.get_extent()
|
| 1026 |
+
if self.origin == 'upper':
|
| 1027 |
+
ymin, ymax = ymax, ymin
|
| 1028 |
+
arr = self.get_array()
|
| 1029 |
+
data_extent = Bbox([[xmin, ymin], [xmax, ymax]])
|
| 1030 |
+
array_extent = Bbox([[0, 0], [arr.shape[1], arr.shape[0]]])
|
| 1031 |
+
trans = self.get_transform().inverted()
|
| 1032 |
+
trans += BboxTransform(boxin=data_extent, boxout=array_extent)
|
| 1033 |
+
point = trans.transform([event.x, event.y])
|
| 1034 |
+
if any(np.isnan(point)):
|
| 1035 |
+
return None
|
| 1036 |
+
j, i = point.astype(int)
|
| 1037 |
+
# Clip the coordinates at array bounds
|
| 1038 |
+
if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]):
|
| 1039 |
+
return None
|
| 1040 |
+
else:
|
| 1041 |
+
return arr[i, j]
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
class NonUniformImage(AxesImage):
|
| 1045 |
+
mouseover = False # This class still needs its own get_cursor_data impl.
|
| 1046 |
+
|
| 1047 |
+
def __init__(self, ax, *, interpolation='nearest', **kwargs):
|
| 1048 |
+
"""
|
| 1049 |
+
Parameters
|
| 1050 |
+
----------
|
| 1051 |
+
ax : `~matplotlib.axes.Axes`
|
| 1052 |
+
The axes the image will belong to.
|
| 1053 |
+
interpolation : {'nearest', 'bilinear'}, default: 'nearest'
|
| 1054 |
+
The interpolation scheme used in the resampling.
|
| 1055 |
+
**kwargs
|
| 1056 |
+
All other keyword arguments are identical to those of `.AxesImage`.
|
| 1057 |
+
"""
|
| 1058 |
+
super().__init__(ax, **kwargs)
|
| 1059 |
+
self.set_interpolation(interpolation)
|
| 1060 |
+
|
| 1061 |
+
def _check_unsampled_image(self):
|
| 1062 |
+
"""Return False. Do not use unsampled image."""
|
| 1063 |
+
return False
|
| 1064 |
+
|
| 1065 |
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
| 1066 |
+
# docstring inherited
|
| 1067 |
+
if self._A is None:
|
| 1068 |
+
raise RuntimeError('You must first set the image array')
|
| 1069 |
+
if unsampled:
|
| 1070 |
+
raise ValueError('unsampled not supported on NonUniformImage')
|
| 1071 |
+
A = self._A
|
| 1072 |
+
if A.ndim == 2:
|
| 1073 |
+
if A.dtype != np.uint8:
|
| 1074 |
+
A = self.to_rgba(A, bytes=True)
|
| 1075 |
+
else:
|
| 1076 |
+
A = np.repeat(A[:, :, np.newaxis], 4, 2)
|
| 1077 |
+
A[:, :, 3] = 255
|
| 1078 |
+
else:
|
| 1079 |
+
if A.dtype != np.uint8:
|
| 1080 |
+
A = (255*A).astype(np.uint8)
|
| 1081 |
+
if A.shape[2] == 3:
|
| 1082 |
+
B = np.zeros(tuple([*A.shape[0:2], 4]), np.uint8)
|
| 1083 |
+
B[:, :, 0:3] = A
|
| 1084 |
+
B[:, :, 3] = 255
|
| 1085 |
+
A = B
|
| 1086 |
+
vl = self.axes.viewLim
|
| 1087 |
+
l, b, r, t = self.axes.bbox.extents
|
| 1088 |
+
width = int(((round(r) + 0.5) - (round(l) - 0.5)) * magnification)
|
| 1089 |
+
height = int(((round(t) + 0.5) - (round(b) - 0.5)) * magnification)
|
| 1090 |
+
x_pix = np.linspace(vl.x0, vl.x1, width)
|
| 1091 |
+
y_pix = np.linspace(vl.y0, vl.y1, height)
|
| 1092 |
+
if self._interpolation == "nearest":
|
| 1093 |
+
x_mid = (self._Ax[:-1] + self._Ax[1:]) / 2
|
| 1094 |
+
y_mid = (self._Ay[:-1] + self._Ay[1:]) / 2
|
| 1095 |
+
x_int = x_mid.searchsorted(x_pix)
|
| 1096 |
+
y_int = y_mid.searchsorted(y_pix)
|
| 1097 |
+
# The following is equal to `A[y_int[:, None], x_int[None, :]]`,
|
| 1098 |
+
# but many times faster. Both casting to uint32 (to have an
|
| 1099 |
+
# effectively 1D array) and manual index flattening matter.
|
| 1100 |
+
im = (
|
| 1101 |
+
np.ascontiguousarray(A).view(np.uint32).ravel()[
|
| 1102 |
+
np.add.outer(y_int * A.shape[1], x_int)]
|
| 1103 |
+
.view(np.uint8).reshape((height, width, 4)))
|
| 1104 |
+
else: # self._interpolation == "bilinear"
|
| 1105 |
+
# Use np.interp to compute x_int/x_float has similar speed.
|
| 1106 |
+
x_int = np.clip(
|
| 1107 |
+
self._Ax.searchsorted(x_pix) - 1, 0, len(self._Ax) - 2)
|
| 1108 |
+
y_int = np.clip(
|
| 1109 |
+
self._Ay.searchsorted(y_pix) - 1, 0, len(self._Ay) - 2)
|
| 1110 |
+
idx_int = np.add.outer(y_int * A.shape[1], x_int)
|
| 1111 |
+
x_frac = np.clip(
|
| 1112 |
+
np.divide(x_pix - self._Ax[x_int], np.diff(self._Ax)[x_int],
|
| 1113 |
+
dtype=np.float32), # Downcasting helps with speed.
|
| 1114 |
+
0, 1)
|
| 1115 |
+
y_frac = np.clip(
|
| 1116 |
+
np.divide(y_pix - self._Ay[y_int], np.diff(self._Ay)[y_int],
|
| 1117 |
+
dtype=np.float32),
|
| 1118 |
+
0, 1)
|
| 1119 |
+
f00 = np.outer(1 - y_frac, 1 - x_frac)
|
| 1120 |
+
f10 = np.outer(y_frac, 1 - x_frac)
|
| 1121 |
+
f01 = np.outer(1 - y_frac, x_frac)
|
| 1122 |
+
f11 = np.outer(y_frac, x_frac)
|
| 1123 |
+
im = np.empty((height, width, 4), np.uint8)
|
| 1124 |
+
for chan in range(4):
|
| 1125 |
+
ac = A[:, :, chan].reshape(-1) # reshape(-1) avoids a copy.
|
| 1126 |
+
# Shifting the buffer start (`ac[offset:]`) avoids an array
|
| 1127 |
+
# addition (`ac[idx_int + offset]`).
|
| 1128 |
+
buf = f00 * ac[idx_int]
|
| 1129 |
+
buf += f10 * ac[A.shape[1]:][idx_int]
|
| 1130 |
+
buf += f01 * ac[1:][idx_int]
|
| 1131 |
+
buf += f11 * ac[A.shape[1] + 1:][idx_int]
|
| 1132 |
+
im[:, :, chan] = buf # Implicitly casts to uint8.
|
| 1133 |
+
return im, l, b, IdentityTransform()
|
| 1134 |
+
|
| 1135 |
+
def set_data(self, x, y, A):
|
| 1136 |
+
"""
|
| 1137 |
+
Set the grid for the pixel centers, and the pixel values.
|
| 1138 |
+
|
| 1139 |
+
Parameters
|
| 1140 |
+
----------
|
| 1141 |
+
x, y : 1D array-like
|
| 1142 |
+
Monotonic arrays of shapes (N,) and (M,), respectively, specifying
|
| 1143 |
+
pixel centers.
|
| 1144 |
+
A : array-like
|
| 1145 |
+
(M, N) `~numpy.ndarray` or masked array of values to be
|
| 1146 |
+
colormapped, or (M, N, 3) RGB array, or (M, N, 4) RGBA array.
|
| 1147 |
+
"""
|
| 1148 |
+
x = np.array(x, np.float32)
|
| 1149 |
+
y = np.array(y, np.float32)
|
| 1150 |
+
A = cbook.safe_masked_invalid(A, copy=True)
|
| 1151 |
+
if not (x.ndim == y.ndim == 1 and A.shape[0:2] == y.shape + x.shape):
|
| 1152 |
+
raise TypeError("Axes don't match array shape")
|
| 1153 |
+
if A.ndim not in [2, 3]:
|
| 1154 |
+
raise TypeError("Can only plot 2D or 3D data")
|
| 1155 |
+
if A.ndim == 3 and A.shape[2] not in [1, 3, 4]:
|
| 1156 |
+
raise TypeError("3D arrays must have three (RGB) "
|
| 1157 |
+
"or four (RGBA) color components")
|
| 1158 |
+
if A.ndim == 3 and A.shape[2] == 1:
|
| 1159 |
+
A = A.squeeze(axis=-1)
|
| 1160 |
+
self._A = A
|
| 1161 |
+
self._Ax = x
|
| 1162 |
+
self._Ay = y
|
| 1163 |
+
self._imcache = None
|
| 1164 |
+
|
| 1165 |
+
self.stale = True
|
| 1166 |
+
|
| 1167 |
+
def set_array(self, *args):
|
| 1168 |
+
raise NotImplementedError('Method not supported')
|
| 1169 |
+
|
| 1170 |
+
def set_interpolation(self, s):
|
| 1171 |
+
"""
|
| 1172 |
+
Parameters
|
| 1173 |
+
----------
|
| 1174 |
+
s : {'nearest', 'bilinear'} or None
|
| 1175 |
+
If None, use :rc:`image.interpolation`.
|
| 1176 |
+
"""
|
| 1177 |
+
if s is not None and s not in ('nearest', 'bilinear'):
|
| 1178 |
+
raise NotImplementedError('Only nearest neighbor and '
|
| 1179 |
+
'bilinear interpolations are supported')
|
| 1180 |
+
super().set_interpolation(s)
|
| 1181 |
+
|
| 1182 |
+
def get_extent(self):
|
| 1183 |
+
if self._A is None:
|
| 1184 |
+
raise RuntimeError('Must set data first')
|
| 1185 |
+
return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1]
|
| 1186 |
+
|
| 1187 |
+
def set_filternorm(self, s):
|
| 1188 |
+
pass
|
| 1189 |
+
|
| 1190 |
+
def set_filterrad(self, s):
|
| 1191 |
+
pass
|
| 1192 |
+
|
| 1193 |
+
def set_norm(self, norm):
|
| 1194 |
+
if self._A is not None:
|
| 1195 |
+
raise RuntimeError('Cannot change colors after loading data')
|
| 1196 |
+
super().set_norm(norm)
|
| 1197 |
+
|
| 1198 |
+
def set_cmap(self, cmap):
|
| 1199 |
+
if self._A is not None:
|
| 1200 |
+
raise RuntimeError('Cannot change colors after loading data')
|
| 1201 |
+
super().set_cmap(cmap)
|
| 1202 |
+
|
| 1203 |
+
|
| 1204 |
+
class PcolorImage(AxesImage):
|
| 1205 |
+
"""
|
| 1206 |
+
Make a pcolor-style plot with an irregular rectangular grid.
|
| 1207 |
+
|
| 1208 |
+
This uses a variation of the original irregular image code,
|
| 1209 |
+
and it is used by pcolorfast for the corresponding grid type.
|
| 1210 |
+
"""
|
| 1211 |
+
|
| 1212 |
+
@_api.make_keyword_only("3.6", name="cmap")
|
| 1213 |
+
def __init__(self, ax,
|
| 1214 |
+
x=None,
|
| 1215 |
+
y=None,
|
| 1216 |
+
A=None,
|
| 1217 |
+
cmap=None,
|
| 1218 |
+
norm=None,
|
| 1219 |
+
**kwargs
|
| 1220 |
+
):
|
| 1221 |
+
"""
|
| 1222 |
+
Parameters
|
| 1223 |
+
----------
|
| 1224 |
+
ax : `~matplotlib.axes.Axes`
|
| 1225 |
+
The axes the image will belong to.
|
| 1226 |
+
x, y : 1D array-like, optional
|
| 1227 |
+
Monotonic arrays of length N+1 and M+1, respectively, specifying
|
| 1228 |
+
rectangle boundaries. If not given, will default to
|
| 1229 |
+
``range(N + 1)`` and ``range(M + 1)``, respectively.
|
| 1230 |
+
A : array-like
|
| 1231 |
+
The data to be color-coded. The interpretation depends on the
|
| 1232 |
+
shape:
|
| 1233 |
+
|
| 1234 |
+
- (M, N) `~numpy.ndarray` or masked array: values to be colormapped
|
| 1235 |
+
- (M, N, 3): RGB array
|
| 1236 |
+
- (M, N, 4): RGBA array
|
| 1237 |
+
|
| 1238 |
+
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
|
| 1239 |
+
The Colormap instance or registered colormap name used to map
|
| 1240 |
+
scalar data to colors.
|
| 1241 |
+
norm : str or `~matplotlib.colors.Normalize`
|
| 1242 |
+
Maps luminance to 0-1.
|
| 1243 |
+
**kwargs : `~matplotlib.artist.Artist` properties
|
| 1244 |
+
"""
|
| 1245 |
+
super().__init__(ax, norm=norm, cmap=cmap)
|
| 1246 |
+
self._internal_update(kwargs)
|
| 1247 |
+
if A is not None:
|
| 1248 |
+
self.set_data(x, y, A)
|
| 1249 |
+
|
| 1250 |
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
| 1251 |
+
# docstring inherited
|
| 1252 |
+
if self._A is None:
|
| 1253 |
+
raise RuntimeError('You must first set the image array')
|
| 1254 |
+
if unsampled:
|
| 1255 |
+
raise ValueError('unsampled not supported on PColorImage')
|
| 1256 |
+
|
| 1257 |
+
if self._imcache is None:
|
| 1258 |
+
A = self.to_rgba(self._A, bytes=True)
|
| 1259 |
+
self._imcache = np.pad(A, [(1, 1), (1, 1), (0, 0)], "constant")
|
| 1260 |
+
padded_A = self._imcache
|
| 1261 |
+
bg = mcolors.to_rgba(self.axes.patch.get_facecolor(), 0)
|
| 1262 |
+
bg = (np.array(bg) * 255).astype(np.uint8)
|
| 1263 |
+
if (padded_A[0, 0] != bg).all():
|
| 1264 |
+
padded_A[[0, -1], :] = padded_A[:, [0, -1]] = bg
|
| 1265 |
+
|
| 1266 |
+
l, b, r, t = self.axes.bbox.extents
|
| 1267 |
+
width = (round(r) + 0.5) - (round(l) - 0.5)
|
| 1268 |
+
height = (round(t) + 0.5) - (round(b) - 0.5)
|
| 1269 |
+
width = round(width * magnification)
|
| 1270 |
+
height = round(height * magnification)
|
| 1271 |
+
vl = self.axes.viewLim
|
| 1272 |
+
|
| 1273 |
+
x_pix = np.linspace(vl.x0, vl.x1, width)
|
| 1274 |
+
y_pix = np.linspace(vl.y0, vl.y1, height)
|
| 1275 |
+
x_int = self._Ax.searchsorted(x_pix)
|
| 1276 |
+
y_int = self._Ay.searchsorted(y_pix)
|
| 1277 |
+
im = ( # See comment in NonUniformImage.make_image re: performance.
|
| 1278 |
+
padded_A.view(np.uint32).ravel()[
|
| 1279 |
+
np.add.outer(y_int * padded_A.shape[1], x_int)]
|
| 1280 |
+
.view(np.uint8).reshape((height, width, 4)))
|
| 1281 |
+
return im, l, b, IdentityTransform()
|
| 1282 |
+
|
| 1283 |
+
def _check_unsampled_image(self):
|
| 1284 |
+
return False
|
| 1285 |
+
|
| 1286 |
+
def set_data(self, x, y, A):
|
| 1287 |
+
"""
|
| 1288 |
+
Set the grid for the rectangle boundaries, and the data values.
|
| 1289 |
+
|
| 1290 |
+
Parameters
|
| 1291 |
+
----------
|
| 1292 |
+
x, y : 1D array-like, optional
|
| 1293 |
+
Monotonic arrays of length N+1 and M+1, respectively, specifying
|
| 1294 |
+
rectangle boundaries. If not given, will default to
|
| 1295 |
+
``range(N + 1)`` and ``range(M + 1)``, respectively.
|
| 1296 |
+
A : array-like
|
| 1297 |
+
The data to be color-coded. The interpretation depends on the
|
| 1298 |
+
shape:
|
| 1299 |
+
|
| 1300 |
+
- (M, N) `~numpy.ndarray` or masked array: values to be colormapped
|
| 1301 |
+
- (M, N, 3): RGB array
|
| 1302 |
+
- (M, N, 4): RGBA array
|
| 1303 |
+
"""
|
| 1304 |
+
A = cbook.safe_masked_invalid(A, copy=True)
|
| 1305 |
+
if x is None:
|
| 1306 |
+
x = np.arange(0, A.shape[1]+1, dtype=np.float64)
|
| 1307 |
+
else:
|
| 1308 |
+
x = np.array(x, np.float64).ravel()
|
| 1309 |
+
if y is None:
|
| 1310 |
+
y = np.arange(0, A.shape[0]+1, dtype=np.float64)
|
| 1311 |
+
else:
|
| 1312 |
+
y = np.array(y, np.float64).ravel()
|
| 1313 |
+
|
| 1314 |
+
if A.shape[:2] != (y.size-1, x.size-1):
|
| 1315 |
+
raise ValueError(
|
| 1316 |
+
"Axes don't match array shape. Got %s, expected %s." %
|
| 1317 |
+
(A.shape[:2], (y.size - 1, x.size - 1)))
|
| 1318 |
+
if A.ndim not in [2, 3]:
|
| 1319 |
+
raise ValueError("A must be 2D or 3D")
|
| 1320 |
+
if A.ndim == 3:
|
| 1321 |
+
if A.shape[2] == 1:
|
| 1322 |
+
A = A.squeeze(axis=-1)
|
| 1323 |
+
elif A.shape[2] not in [3, 4]:
|
| 1324 |
+
raise ValueError("3D arrays must have RGB or RGBA as last dim")
|
| 1325 |
+
|
| 1326 |
+
# For efficient cursor readout, ensure x and y are increasing.
|
| 1327 |
+
if x[-1] < x[0]:
|
| 1328 |
+
x = x[::-1]
|
| 1329 |
+
A = A[:, ::-1]
|
| 1330 |
+
if y[-1] < y[0]:
|
| 1331 |
+
y = y[::-1]
|
| 1332 |
+
A = A[::-1]
|
| 1333 |
+
|
| 1334 |
+
self._A = A
|
| 1335 |
+
self._Ax = x
|
| 1336 |
+
self._Ay = y
|
| 1337 |
+
self._imcache = None
|
| 1338 |
+
self.stale = True
|
| 1339 |
+
|
| 1340 |
+
def set_array(self, *args):
|
| 1341 |
+
raise NotImplementedError('Method not supported')
|
| 1342 |
+
|
| 1343 |
+
def get_cursor_data(self, event):
|
| 1344 |
+
# docstring inherited
|
| 1345 |
+
x, y = event.xdata, event.ydata
|
| 1346 |
+
if (x < self._Ax[0] or x > self._Ax[-1] or
|
| 1347 |
+
y < self._Ay[0] or y > self._Ay[-1]):
|
| 1348 |
+
return None
|
| 1349 |
+
j = np.searchsorted(self._Ax, x) - 1
|
| 1350 |
+
i = np.searchsorted(self._Ay, y) - 1
|
| 1351 |
+
try:
|
| 1352 |
+
return self._A[i, j]
|
| 1353 |
+
except IndexError:
|
| 1354 |
+
return None
|
| 1355 |
+
|
| 1356 |
+
|
| 1357 |
+
class FigureImage(_ImageBase):
|
| 1358 |
+
"""An image attached to a figure."""
|
| 1359 |
+
|
| 1360 |
+
zorder = 0
|
| 1361 |
+
|
| 1362 |
+
_interpolation = 'nearest'
|
| 1363 |
+
|
| 1364 |
+
@_api.make_keyword_only("3.6", name="cmap")
|
| 1365 |
+
def __init__(self, fig,
|
| 1366 |
+
cmap=None,
|
| 1367 |
+
norm=None,
|
| 1368 |
+
offsetx=0,
|
| 1369 |
+
offsety=0,
|
| 1370 |
+
origin=None,
|
| 1371 |
+
**kwargs
|
| 1372 |
+
):
|
| 1373 |
+
"""
|
| 1374 |
+
cmap is a colors.Colormap instance
|
| 1375 |
+
norm is a colors.Normalize instance to map luminance to 0-1
|
| 1376 |
+
|
| 1377 |
+
kwargs are an optional list of Artist keyword args
|
| 1378 |
+
"""
|
| 1379 |
+
super().__init__(
|
| 1380 |
+
None,
|
| 1381 |
+
norm=norm,
|
| 1382 |
+
cmap=cmap,
|
| 1383 |
+
origin=origin
|
| 1384 |
+
)
|
| 1385 |
+
self.figure = fig
|
| 1386 |
+
self.ox = offsetx
|
| 1387 |
+
self.oy = offsety
|
| 1388 |
+
self._internal_update(kwargs)
|
| 1389 |
+
self.magnification = 1.0
|
| 1390 |
+
|
| 1391 |
+
def get_extent(self):
|
| 1392 |
+
"""Return the image extent as tuple (left, right, bottom, top)."""
|
| 1393 |
+
numrows, numcols = self.get_size()
|
| 1394 |
+
return (-0.5 + self.ox, numcols-0.5 + self.ox,
|
| 1395 |
+
-0.5 + self.oy, numrows-0.5 + self.oy)
|
| 1396 |
+
|
| 1397 |
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
| 1398 |
+
# docstring inherited
|
| 1399 |
+
fac = renderer.dpi/self.figure.dpi
|
| 1400 |
+
# fac here is to account for pdf, eps, svg backends where
|
| 1401 |
+
# figure.dpi is set to 72. This means we need to scale the
|
| 1402 |
+
# image (using magnification) and offset it appropriately.
|
| 1403 |
+
bbox = Bbox([[self.ox/fac, self.oy/fac],
|
| 1404 |
+
[(self.ox/fac + self._A.shape[1]),
|
| 1405 |
+
(self.oy/fac + self._A.shape[0])]])
|
| 1406 |
+
width, height = self.figure.get_size_inches()
|
| 1407 |
+
width *= renderer.dpi
|
| 1408 |
+
height *= renderer.dpi
|
| 1409 |
+
clip = Bbox([[0, 0], [width, height]])
|
| 1410 |
+
return self._make_image(
|
| 1411 |
+
self._A, bbox, bbox, clip, magnification=magnification / fac,
|
| 1412 |
+
unsampled=unsampled, round_to_pixel_border=False)
|
| 1413 |
+
|
| 1414 |
+
def set_data(self, A):
|
| 1415 |
+
"""Set the image array."""
|
| 1416 |
+
cm.ScalarMappable.set_array(self, A)
|
| 1417 |
+
self.stale = True
|
| 1418 |
+
|
| 1419 |
+
|
| 1420 |
+
class BboxImage(_ImageBase):
|
| 1421 |
+
"""The Image class whose size is determined by the given bbox."""
|
| 1422 |
+
|
| 1423 |
+
@_api.make_keyword_only("3.6", name="cmap")
|
| 1424 |
+
def __init__(self, bbox,
|
| 1425 |
+
cmap=None,
|
| 1426 |
+
norm=None,
|
| 1427 |
+
interpolation=None,
|
| 1428 |
+
origin=None,
|
| 1429 |
+
filternorm=True,
|
| 1430 |
+
filterrad=4.0,
|
| 1431 |
+
resample=False,
|
| 1432 |
+
**kwargs
|
| 1433 |
+
):
|
| 1434 |
+
"""
|
| 1435 |
+
cmap is a colors.Colormap instance
|
| 1436 |
+
norm is a colors.Normalize instance to map luminance to 0-1
|
| 1437 |
+
|
| 1438 |
+
kwargs are an optional list of Artist keyword args
|
| 1439 |
+
"""
|
| 1440 |
+
super().__init__(
|
| 1441 |
+
None,
|
| 1442 |
+
cmap=cmap,
|
| 1443 |
+
norm=norm,
|
| 1444 |
+
interpolation=interpolation,
|
| 1445 |
+
origin=origin,
|
| 1446 |
+
filternorm=filternorm,
|
| 1447 |
+
filterrad=filterrad,
|
| 1448 |
+
resample=resample,
|
| 1449 |
+
**kwargs
|
| 1450 |
+
)
|
| 1451 |
+
self.bbox = bbox
|
| 1452 |
+
|
| 1453 |
+
def get_window_extent(self, renderer=None):
|
| 1454 |
+
if renderer is None:
|
| 1455 |
+
renderer = self.get_figure()._get_renderer()
|
| 1456 |
+
|
| 1457 |
+
if isinstance(self.bbox, BboxBase):
|
| 1458 |
+
return self.bbox
|
| 1459 |
+
elif callable(self.bbox):
|
| 1460 |
+
return self.bbox(renderer)
|
| 1461 |
+
else:
|
| 1462 |
+
raise ValueError("Unknown type of bbox")
|
| 1463 |
+
|
| 1464 |
+
def contains(self, mouseevent):
|
| 1465 |
+
"""Test whether the mouse event occurred within the image."""
|
| 1466 |
+
inside, info = self._default_contains(mouseevent)
|
| 1467 |
+
if inside is not None:
|
| 1468 |
+
return inside, info
|
| 1469 |
+
|
| 1470 |
+
if not self.get_visible(): # or self.get_figure()._renderer is None:
|
| 1471 |
+
return False, {}
|
| 1472 |
+
|
| 1473 |
+
x, y = mouseevent.x, mouseevent.y
|
| 1474 |
+
inside = self.get_window_extent().contains(x, y)
|
| 1475 |
+
|
| 1476 |
+
return inside, {}
|
| 1477 |
+
|
| 1478 |
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
| 1479 |
+
# docstring inherited
|
| 1480 |
+
width, height = renderer.get_canvas_width_height()
|
| 1481 |
+
bbox_in = self.get_window_extent(renderer).frozen()
|
| 1482 |
+
bbox_in._points /= [width, height]
|
| 1483 |
+
bbox_out = self.get_window_extent(renderer)
|
| 1484 |
+
clip = Bbox([[0, 0], [width, height]])
|
| 1485 |
+
self._transform = BboxTransformTo(clip)
|
| 1486 |
+
return self._make_image(
|
| 1487 |
+
self._A,
|
| 1488 |
+
bbox_in, bbox_out, clip, magnification, unsampled=unsampled)
|
| 1489 |
+
|
| 1490 |
+
|
| 1491 |
+
def imread(fname, format=None):
|
| 1492 |
+
"""
|
| 1493 |
+
Read an image from a file into an array.
|
| 1494 |
+
|
| 1495 |
+
.. note::
|
| 1496 |
+
|
| 1497 |
+
This function exists for historical reasons. It is recommended to
|
| 1498 |
+
use `PIL.Image.open` instead for loading images.
|
| 1499 |
+
|
| 1500 |
+
Parameters
|
| 1501 |
+
----------
|
| 1502 |
+
fname : str or file-like
|
| 1503 |
+
The image file to read: a filename, a URL or a file-like object opened
|
| 1504 |
+
in read-binary mode.
|
| 1505 |
+
|
| 1506 |
+
Passing a URL is deprecated. Please open the URL
|
| 1507 |
+
for reading and pass the result to Pillow, e.g. with
|
| 1508 |
+
``np.array(PIL.Image.open(urllib.request.urlopen(url)))``.
|
| 1509 |
+
format : str, optional
|
| 1510 |
+
The image file format assumed for reading the data. The image is
|
| 1511 |
+
loaded as a PNG file if *format* is set to "png", if *fname* is a path
|
| 1512 |
+
or opened file with a ".png" extension, or if it is a URL. In all
|
| 1513 |
+
other cases, *format* is ignored and the format is auto-detected by
|
| 1514 |
+
`PIL.Image.open`.
|
| 1515 |
+
|
| 1516 |
+
Returns
|
| 1517 |
+
-------
|
| 1518 |
+
`numpy.array`
|
| 1519 |
+
The image data. The returned array has shape
|
| 1520 |
+
|
| 1521 |
+
- (M, N) for grayscale images.
|
| 1522 |
+
- (M, N, 3) for RGB images.
|
| 1523 |
+
- (M, N, 4) for RGBA images.
|
| 1524 |
+
|
| 1525 |
+
PNG images are returned as float arrays (0-1). All other formats are
|
| 1526 |
+
returned as int arrays, with a bit depth determined by the file's
|
| 1527 |
+
contents.
|
| 1528 |
+
"""
|
| 1529 |
+
# hide imports to speed initial import on systems with slow linkers
|
| 1530 |
+
from urllib import parse
|
| 1531 |
+
|
| 1532 |
+
if format is None:
|
| 1533 |
+
if isinstance(fname, str):
|
| 1534 |
+
parsed = parse.urlparse(fname)
|
| 1535 |
+
# If the string is a URL (Windows paths appear as if they have a
|
| 1536 |
+
# length-1 scheme), assume png.
|
| 1537 |
+
if len(parsed.scheme) > 1:
|
| 1538 |
+
ext = 'png'
|
| 1539 |
+
else:
|
| 1540 |
+
ext = Path(fname).suffix.lower()[1:]
|
| 1541 |
+
elif hasattr(fname, 'geturl'): # Returned by urlopen().
|
| 1542 |
+
# We could try to parse the url's path and use the extension, but
|
| 1543 |
+
# returning png is consistent with the block above. Note that this
|
| 1544 |
+
# if clause has to come before checking for fname.name as
|
| 1545 |
+
# urlopen("file:///...") also has a name attribute (with the fixed
|
| 1546 |
+
# value "<urllib response>").
|
| 1547 |
+
ext = 'png'
|
| 1548 |
+
elif hasattr(fname, 'name'):
|
| 1549 |
+
ext = Path(fname.name).suffix.lower()[1:]
|
| 1550 |
+
else:
|
| 1551 |
+
ext = 'png'
|
| 1552 |
+
else:
|
| 1553 |
+
ext = format
|
| 1554 |
+
img_open = (
|
| 1555 |
+
PIL.PngImagePlugin.PngImageFile if ext == 'png' else PIL.Image.open)
|
| 1556 |
+
if isinstance(fname, str) and len(parse.urlparse(fname).scheme) > 1:
|
| 1557 |
+
# Pillow doesn't handle URLs directly.
|
| 1558 |
+
raise ValueError(
|
| 1559 |
+
"Please open the URL for reading and pass the "
|
| 1560 |
+
"result to Pillow, e.g. with "
|
| 1561 |
+
"``np.array(PIL.Image.open(urllib.request.urlopen(url)))``."
|
| 1562 |
+
)
|
| 1563 |
+
with img_open(fname) as image:
|
| 1564 |
+
return (_pil_png_to_float_array(image)
|
| 1565 |
+
if isinstance(image, PIL.PngImagePlugin.PngImageFile) else
|
| 1566 |
+
pil_to_array(image))
|
| 1567 |
+
|
| 1568 |
+
|
| 1569 |
+
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
|
| 1570 |
+
origin=None, dpi=100, *, metadata=None, pil_kwargs=None):
|
| 1571 |
+
"""
|
| 1572 |
+
Colormap and save an array as an image file.
|
| 1573 |
+
|
| 1574 |
+
RGB(A) images are passed through. Single channel images will be
|
| 1575 |
+
colormapped according to *cmap* and *norm*.
|
| 1576 |
+
|
| 1577 |
+
.. note::
|
| 1578 |
+
|
| 1579 |
+
If you want to save a single channel image as gray scale please use an
|
| 1580 |
+
image I/O library (such as pillow, tifffile, or imageio) directly.
|
| 1581 |
+
|
| 1582 |
+
Parameters
|
| 1583 |
+
----------
|
| 1584 |
+
fname : str or path-like or file-like
|
| 1585 |
+
A path or a file-like object to store the image in.
|
| 1586 |
+
If *format* is not set, then the output format is inferred from the
|
| 1587 |
+
extension of *fname*, if any, and from :rc:`savefig.format` otherwise.
|
| 1588 |
+
If *format* is set, it determines the output format.
|
| 1589 |
+
arr : array-like
|
| 1590 |
+
The image data. The shape can be one of
|
| 1591 |
+
MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
|
| 1592 |
+
vmin, vmax : float, optional
|
| 1593 |
+
*vmin* and *vmax* set the color scaling for the image by fixing the
|
| 1594 |
+
values that map to the colormap color limits. If either *vmin*
|
| 1595 |
+
or *vmax* is None, that limit is determined from the *arr*
|
| 1596 |
+
min/max value.
|
| 1597 |
+
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
|
| 1598 |
+
A Colormap instance or registered colormap name. The colormap
|
| 1599 |
+
maps scalar data to colors. It is ignored for RGB(A) data.
|
| 1600 |
+
format : str, optional
|
| 1601 |
+
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this
|
| 1602 |
+
is unset is documented under *fname*.
|
| 1603 |
+
origin : {'upper', 'lower'}, default: :rc:`image.origin`
|
| 1604 |
+
Indicates whether the ``(0, 0)`` index of the array is in the upper
|
| 1605 |
+
left or lower left corner of the axes.
|
| 1606 |
+
dpi : float
|
| 1607 |
+
The DPI to store in the metadata of the file. This does not affect the
|
| 1608 |
+
resolution of the output image. Depending on file format, this may be
|
| 1609 |
+
rounded to the nearest integer.
|
| 1610 |
+
metadata : dict, optional
|
| 1611 |
+
Metadata in the image file. The supported keys depend on the output
|
| 1612 |
+
format, see the documentation of the respective backends for more
|
| 1613 |
+
information.
|
| 1614 |
+
pil_kwargs : dict, optional
|
| 1615 |
+
Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo'
|
| 1616 |
+
key is present, it completely overrides *metadata*, including the
|
| 1617 |
+
default 'Software' key.
|
| 1618 |
+
"""
|
| 1619 |
+
from matplotlib.figure import Figure
|
| 1620 |
+
if isinstance(fname, os.PathLike):
|
| 1621 |
+
fname = os.fspath(fname)
|
| 1622 |
+
if format is None:
|
| 1623 |
+
format = (Path(fname).suffix[1:] if isinstance(fname, str)
|
| 1624 |
+
else mpl.rcParams["savefig.format"]).lower()
|
| 1625 |
+
if format in ["pdf", "ps", "eps", "svg"]:
|
| 1626 |
+
# Vector formats that are not handled by PIL.
|
| 1627 |
+
if pil_kwargs is not None:
|
| 1628 |
+
raise ValueError(
|
| 1629 |
+
f"Cannot use 'pil_kwargs' when saving to {format}")
|
| 1630 |
+
fig = Figure(dpi=dpi, frameon=False)
|
| 1631 |
+
fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
|
| 1632 |
+
resize=True)
|
| 1633 |
+
fig.savefig(fname, dpi=dpi, format=format, transparent=True,
|
| 1634 |
+
metadata=metadata)
|
| 1635 |
+
else:
|
| 1636 |
+
# Don't bother creating an image; this avoids rounding errors on the
|
| 1637 |
+
# size when dividing and then multiplying by dpi.
|
| 1638 |
+
if origin is None:
|
| 1639 |
+
origin = mpl.rcParams["image.origin"]
|
| 1640 |
+
if origin == "lower":
|
| 1641 |
+
arr = arr[::-1]
|
| 1642 |
+
if (isinstance(arr, memoryview) and arr.format == "B"
|
| 1643 |
+
and arr.ndim == 3 and arr.shape[-1] == 4):
|
| 1644 |
+
# Such an ``arr`` would also be handled fine by sm.to_rgba below
|
| 1645 |
+
# (after casting with asarray), but it is useful to special-case it
|
| 1646 |
+
# because that's what backend_agg passes, and can be in fact used
|
| 1647 |
+
# as is, saving a few operations.
|
| 1648 |
+
rgba = arr
|
| 1649 |
+
else:
|
| 1650 |
+
sm = cm.ScalarMappable(cmap=cmap)
|
| 1651 |
+
sm.set_clim(vmin, vmax)
|
| 1652 |
+
rgba = sm.to_rgba(arr, bytes=True)
|
| 1653 |
+
if pil_kwargs is None:
|
| 1654 |
+
pil_kwargs = {}
|
| 1655 |
+
else:
|
| 1656 |
+
# we modify this below, so make a copy (don't modify caller's dict)
|
| 1657 |
+
pil_kwargs = pil_kwargs.copy()
|
| 1658 |
+
pil_shape = (rgba.shape[1], rgba.shape[0])
|
| 1659 |
+
image = PIL.Image.frombuffer(
|
| 1660 |
+
"RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1)
|
| 1661 |
+
if format == "png":
|
| 1662 |
+
# Only use the metadata kwarg if pnginfo is not set, because the
|
| 1663 |
+
# semantics of duplicate keys in pnginfo is unclear.
|
| 1664 |
+
if "pnginfo" in pil_kwargs:
|
| 1665 |
+
if metadata:
|
| 1666 |
+
_api.warn_external("'metadata' is overridden by the "
|
| 1667 |
+
"'pnginfo' entry in 'pil_kwargs'.")
|
| 1668 |
+
else:
|
| 1669 |
+
metadata = {
|
| 1670 |
+
"Software": (f"Matplotlib version{mpl.__version__}, "
|
| 1671 |
+
f"https://matplotlib.org/"),
|
| 1672 |
+
**(metadata if metadata is not None else {}),
|
| 1673 |
+
}
|
| 1674 |
+
pil_kwargs["pnginfo"] = pnginfo = PIL.PngImagePlugin.PngInfo()
|
| 1675 |
+
for k, v in metadata.items():
|
| 1676 |
+
if v is not None:
|
| 1677 |
+
pnginfo.add_text(k, v)
|
| 1678 |
+
if format in ["jpg", "jpeg"]:
|
| 1679 |
+
format = "jpeg" # Pillow doesn't recognize "jpg".
|
| 1680 |
+
facecolor = mpl.rcParams["savefig.facecolor"]
|
| 1681 |
+
if cbook._str_equal(facecolor, "auto"):
|
| 1682 |
+
facecolor = mpl.rcParams["figure.facecolor"]
|
| 1683 |
+
color = tuple(int(x * 255) for x in mcolors.to_rgb(facecolor))
|
| 1684 |
+
background = PIL.Image.new("RGB", pil_shape, color)
|
| 1685 |
+
background.paste(image, image)
|
| 1686 |
+
image = background
|
| 1687 |
+
pil_kwargs.setdefault("format", format)
|
| 1688 |
+
pil_kwargs.setdefault("dpi", (dpi, dpi))
|
| 1689 |
+
image.save(fname, **pil_kwargs)
|
| 1690 |
+
|
| 1691 |
+
|
| 1692 |
+
def pil_to_array(pilImage):
|
| 1693 |
+
"""
|
| 1694 |
+
Load a `PIL image`_ and return it as a numpy int array.
|
| 1695 |
+
|
| 1696 |
+
.. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
|
| 1697 |
+
|
| 1698 |
+
Returns
|
| 1699 |
+
-------
|
| 1700 |
+
numpy.array
|
| 1701 |
+
|
| 1702 |
+
The array shape depends on the image type:
|
| 1703 |
+
|
| 1704 |
+
- (M, N) for grayscale images.
|
| 1705 |
+
- (M, N, 3) for RGB images.
|
| 1706 |
+
- (M, N, 4) for RGBA images.
|
| 1707 |
+
"""
|
| 1708 |
+
if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
|
| 1709 |
+
# return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
|
| 1710 |
+
return np.asarray(pilImage)
|
| 1711 |
+
elif pilImage.mode.startswith('I;16'):
|
| 1712 |
+
# return MxN luminance array of uint16
|
| 1713 |
+
raw = pilImage.tobytes('raw', pilImage.mode)
|
| 1714 |
+
if pilImage.mode.endswith('B'):
|
| 1715 |
+
x = np.frombuffer(raw, '>u2')
|
| 1716 |
+
else:
|
| 1717 |
+
x = np.frombuffer(raw, '<u2')
|
| 1718 |
+
return x.reshape(pilImage.size[::-1]).astype('=u2')
|
| 1719 |
+
else: # try to convert to an rgba image
|
| 1720 |
+
try:
|
| 1721 |
+
pilImage = pilImage.convert('RGBA')
|
| 1722 |
+
except ValueError as err:
|
| 1723 |
+
raise RuntimeError('Unknown image mode') from err
|
| 1724 |
+
return np.asarray(pilImage) # return MxNx4 RGBA array
|
| 1725 |
+
|
| 1726 |
+
|
| 1727 |
+
def _pil_png_to_float_array(pil_png):
|
| 1728 |
+
"""Convert a PIL `PNGImageFile` to a 0-1 float array."""
|
| 1729 |
+
# Unlike pil_to_array this converts to 0-1 float32s for backcompat with the
|
| 1730 |
+
# old libpng-based loader.
|
| 1731 |
+
# The supported rawmodes are from PIL.PngImagePlugin._MODES. When
|
| 1732 |
+
# mode == "RGB(A)", the 16-bit raw data has already been coarsened to 8-bit
|
| 1733 |
+
# by Pillow.
|
| 1734 |
+
mode = pil_png.mode
|
| 1735 |
+
rawmode = pil_png.png.im_rawmode
|
| 1736 |
+
if rawmode == "1": # Grayscale.
|
| 1737 |
+
return np.asarray(pil_png, np.float32)
|
| 1738 |
+
if rawmode == "L;2": # Grayscale.
|
| 1739 |
+
return np.divide(pil_png, 2**2 - 1, dtype=np.float32)
|
| 1740 |
+
if rawmode == "L;4": # Grayscale.
|
| 1741 |
+
return np.divide(pil_png, 2**4 - 1, dtype=np.float32)
|
| 1742 |
+
if rawmode == "L": # Grayscale.
|
| 1743 |
+
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
|
| 1744 |
+
if rawmode == "I;16B": # Grayscale.
|
| 1745 |
+
return np.divide(pil_png, 2**16 - 1, dtype=np.float32)
|
| 1746 |
+
if mode == "RGB": # RGB.
|
| 1747 |
+
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
|
| 1748 |
+
if mode == "P": # Palette.
|
| 1749 |
+
return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32)
|
| 1750 |
+
if mode == "LA": # Grayscale + alpha.
|
| 1751 |
+
return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32)
|
| 1752 |
+
if mode == "RGBA": # RGBA.
|
| 1753 |
+
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
|
| 1754 |
+
raise ValueError(f"Unknown PIL rawmode: {rawmode}")
|
| 1755 |
+
|
| 1756 |
+
|
| 1757 |
+
def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
|
| 1758 |
+
preview=False):
|
| 1759 |
+
"""
|
| 1760 |
+
Make a thumbnail of image in *infile* with output filename *thumbfile*.
|
| 1761 |
+
|
| 1762 |
+
See :doc:`/gallery/misc/image_thumbnail_sgskip`.
|
| 1763 |
+
|
| 1764 |
+
Parameters
|
| 1765 |
+
----------
|
| 1766 |
+
infile : str or file-like
|
| 1767 |
+
The image file. Matplotlib relies on Pillow_ for image reading, and
|
| 1768 |
+
thus supports a wide range of file formats, including PNG, JPG, TIFF
|
| 1769 |
+
and others.
|
| 1770 |
+
|
| 1771 |
+
.. _Pillow: https://python-pillow.org/
|
| 1772 |
+
|
| 1773 |
+
thumbfile : str or file-like
|
| 1774 |
+
The thumbnail filename.
|
| 1775 |
+
|
| 1776 |
+
scale : float, default: 0.1
|
| 1777 |
+
The scale factor for the thumbnail.
|
| 1778 |
+
|
| 1779 |
+
interpolation : str, default: 'bilinear'
|
| 1780 |
+
The interpolation scheme used in the resampling. See the
|
| 1781 |
+
*interpolation* parameter of `~.Axes.imshow` for possible values.
|
| 1782 |
+
|
| 1783 |
+
preview : bool, default: False
|
| 1784 |
+
If True, the default backend (presumably a user interface
|
| 1785 |
+
backend) will be used which will cause a figure to be raised if
|
| 1786 |
+
`~matplotlib.pyplot.show` is called. If it is False, the figure is
|
| 1787 |
+
created using `.FigureCanvasBase` and the drawing backend is selected
|
| 1788 |
+
as `.Figure.savefig` would normally do.
|
| 1789 |
+
|
| 1790 |
+
Returns
|
| 1791 |
+
-------
|
| 1792 |
+
`.Figure`
|
| 1793 |
+
The figure instance containing the thumbnail.
|
| 1794 |
+
"""
|
| 1795 |
+
|
| 1796 |
+
im = imread(infile)
|
| 1797 |
+
rows, cols, depth = im.shape
|
| 1798 |
+
|
| 1799 |
+
# This doesn't really matter (it cancels in the end) but the API needs it.
|
| 1800 |
+
dpi = 100
|
| 1801 |
+
|
| 1802 |
+
height = rows / dpi * scale
|
| 1803 |
+
width = cols / dpi * scale
|
| 1804 |
+
|
| 1805 |
+
if preview:
|
| 1806 |
+
# Let the UI backend do everything.
|
| 1807 |
+
import matplotlib.pyplot as plt
|
| 1808 |
+
fig = plt.figure(figsize=(width, height), dpi=dpi)
|
| 1809 |
+
else:
|
| 1810 |
+
from matplotlib.figure import Figure
|
| 1811 |
+
fig = Figure(figsize=(width, height), dpi=dpi)
|
| 1812 |
+
FigureCanvasBase(fig)
|
| 1813 |
+
|
| 1814 |
+
ax = fig.add_axes([0, 0, 1, 1], aspect='auto',
|
| 1815 |
+
frameon=False, xticks=[], yticks=[])
|
| 1816 |
+
ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation)
|
| 1817 |
+
fig.savefig(thumbfile, dpi=dpi)
|
| 1818 |
+
return fig
|
omnilmm/lib/python3.10/site-packages/matplotlib/legend_handler.py
ADDED
|
@@ -0,0 +1,817 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Default legend handlers.
|
| 3 |
+
|
| 4 |
+
.. important::
|
| 5 |
+
|
| 6 |
+
This is a low-level legend API, which most end users do not need.
|
| 7 |
+
|
| 8 |
+
We recommend that you are familiar with the :doc:`legend guide
|
| 9 |
+
</tutorials/intermediate/legend_guide>` before reading this documentation.
|
| 10 |
+
|
| 11 |
+
Legend handlers are expected to be a callable object with a following
|
| 12 |
+
signature::
|
| 13 |
+
|
| 14 |
+
legend_handler(legend, orig_handle, fontsize, handlebox)
|
| 15 |
+
|
| 16 |
+
Where *legend* is the legend itself, *orig_handle* is the original
|
| 17 |
+
plot, *fontsize* is the fontsize in pixels, and *handlebox* is an
|
| 18 |
+
`.OffsetBox` instance. Within the call, you should create relevant
|
| 19 |
+
artists (using relevant properties from the *legend* and/or
|
| 20 |
+
*orig_handle*) and add them into the *handlebox*. The artists need to
|
| 21 |
+
be scaled according to the *fontsize* (note that the size is in pixels,
|
| 22 |
+
i.e., this is dpi-scaled value).
|
| 23 |
+
|
| 24 |
+
This module includes definition of several legend handler classes
|
| 25 |
+
derived from the base class (HandlerBase) with the following method::
|
| 26 |
+
|
| 27 |
+
def legend_artist(self, legend, orig_handle, fontsize, handlebox)
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
from itertools import cycle
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
|
| 34 |
+
from matplotlib import _api, cbook
|
| 35 |
+
from matplotlib.lines import Line2D
|
| 36 |
+
from matplotlib.patches import Rectangle
|
| 37 |
+
import matplotlib.collections as mcoll
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def update_from_first_child(tgt, src):
|
| 41 |
+
first_child = next(iter(src.get_children()), None)
|
| 42 |
+
if first_child is not None:
|
| 43 |
+
tgt.update_from(first_child)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class HandlerBase:
|
| 47 |
+
"""
|
| 48 |
+
A base class for default legend handlers.
|
| 49 |
+
|
| 50 |
+
The derived classes are meant to override *create_artists* method, which
|
| 51 |
+
has the following signature::
|
| 52 |
+
|
| 53 |
+
def create_artists(self, legend, orig_handle,
|
| 54 |
+
xdescent, ydescent, width, height, fontsize,
|
| 55 |
+
trans):
|
| 56 |
+
|
| 57 |
+
The overridden method needs to create artists of the given
|
| 58 |
+
transform that fits in the given dimension (xdescent, ydescent,
|
| 59 |
+
width, height) that are scaled by fontsize if necessary.
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
def __init__(self, xpad=0., ypad=0., update_func=None):
|
| 63 |
+
"""
|
| 64 |
+
Parameters
|
| 65 |
+
----------
|
| 66 |
+
|
| 67 |
+
xpad : float, optional
|
| 68 |
+
Padding in x-direction.
|
| 69 |
+
ypad : float, optional
|
| 70 |
+
Padding in y-direction.
|
| 71 |
+
update_func : callable, optional
|
| 72 |
+
Function for updating the legend handler properties from another
|
| 73 |
+
legend handler, used by `~HandlerBase.update_prop`.
|
| 74 |
+
"""
|
| 75 |
+
self._xpad, self._ypad = xpad, ypad
|
| 76 |
+
self._update_prop_func = update_func
|
| 77 |
+
|
| 78 |
+
def _update_prop(self, legend_handle, orig_handle):
|
| 79 |
+
if self._update_prop_func is None:
|
| 80 |
+
self._default_update_prop(legend_handle, orig_handle)
|
| 81 |
+
else:
|
| 82 |
+
self._update_prop_func(legend_handle, orig_handle)
|
| 83 |
+
|
| 84 |
+
def _default_update_prop(self, legend_handle, orig_handle):
|
| 85 |
+
legend_handle.update_from(orig_handle)
|
| 86 |
+
|
| 87 |
+
def update_prop(self, legend_handle, orig_handle, legend):
|
| 88 |
+
|
| 89 |
+
self._update_prop(legend_handle, orig_handle)
|
| 90 |
+
|
| 91 |
+
legend._set_artist_props(legend_handle)
|
| 92 |
+
legend_handle.set_clip_box(None)
|
| 93 |
+
legend_handle.set_clip_path(None)
|
| 94 |
+
|
| 95 |
+
def adjust_drawing_area(self, legend, orig_handle,
|
| 96 |
+
xdescent, ydescent, width, height, fontsize,
|
| 97 |
+
):
|
| 98 |
+
xdescent = xdescent - self._xpad * fontsize
|
| 99 |
+
ydescent = ydescent - self._ypad * fontsize
|
| 100 |
+
width = width - self._xpad * fontsize
|
| 101 |
+
height = height - self._ypad * fontsize
|
| 102 |
+
return xdescent, ydescent, width, height
|
| 103 |
+
|
| 104 |
+
def legend_artist(self, legend, orig_handle,
|
| 105 |
+
fontsize, handlebox):
|
| 106 |
+
"""
|
| 107 |
+
Return the artist that this HandlerBase generates for the given
|
| 108 |
+
original artist/handle.
|
| 109 |
+
|
| 110 |
+
Parameters
|
| 111 |
+
----------
|
| 112 |
+
legend : `~matplotlib.legend.Legend`
|
| 113 |
+
The legend for which these legend artists are being created.
|
| 114 |
+
orig_handle : :class:`matplotlib.artist.Artist` or similar
|
| 115 |
+
The object for which these legend artists are being created.
|
| 116 |
+
fontsize : int
|
| 117 |
+
The fontsize in pixels. The artists being created should
|
| 118 |
+
be scaled according to the given fontsize.
|
| 119 |
+
handlebox : `~matplotlib.offsetbox.OffsetBox`
|
| 120 |
+
The box which has been created to hold this legend entry's
|
| 121 |
+
artists. Artists created in the `legend_artist` method must
|
| 122 |
+
be added to this handlebox inside this method.
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
xdescent, ydescent, width, height = self.adjust_drawing_area(
|
| 126 |
+
legend, orig_handle,
|
| 127 |
+
handlebox.xdescent, handlebox.ydescent,
|
| 128 |
+
handlebox.width, handlebox.height,
|
| 129 |
+
fontsize)
|
| 130 |
+
artists = self.create_artists(legend, orig_handle,
|
| 131 |
+
xdescent, ydescent, width, height,
|
| 132 |
+
fontsize, handlebox.get_transform())
|
| 133 |
+
|
| 134 |
+
# create_artists will return a list of artists.
|
| 135 |
+
for a in artists:
|
| 136 |
+
handlebox.add_artist(a)
|
| 137 |
+
|
| 138 |
+
# we only return the first artist
|
| 139 |
+
return artists[0]
|
| 140 |
+
|
| 141 |
+
def create_artists(self, legend, orig_handle,
|
| 142 |
+
xdescent, ydescent, width, height, fontsize,
|
| 143 |
+
trans):
|
| 144 |
+
"""
|
| 145 |
+
Return the legend artists generated.
|
| 146 |
+
|
| 147 |
+
Parameters
|
| 148 |
+
----------
|
| 149 |
+
legend : `~matplotlib.legend.Legend`
|
| 150 |
+
The legend for which these legend artists are being created.
|
| 151 |
+
orig_handle : `~matplotlib.artist.Artist` or similar
|
| 152 |
+
The object for which these legend artists are being created.
|
| 153 |
+
xdescent, ydescent, width, height : int
|
| 154 |
+
The rectangle (*xdescent*, *ydescent*, *width*, *height*) that the
|
| 155 |
+
legend artists being created should fit within.
|
| 156 |
+
fontsize : int
|
| 157 |
+
The fontsize in pixels. The legend artists being created should
|
| 158 |
+
be scaled according to the given fontsize.
|
| 159 |
+
trans : `~matplotlib.transforms.Transform`
|
| 160 |
+
The transform that is applied to the legend artists being created.
|
| 161 |
+
Typically from unit coordinates in the handler box to screen
|
| 162 |
+
coordinates.
|
| 163 |
+
"""
|
| 164 |
+
raise NotImplementedError('Derived must override')
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class HandlerNpoints(HandlerBase):
|
| 168 |
+
"""
|
| 169 |
+
A legend handler that shows *numpoints* points in the legend entry.
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
def __init__(self, marker_pad=0.3, numpoints=None, **kwargs):
|
| 173 |
+
"""
|
| 174 |
+
Parameters
|
| 175 |
+
----------
|
| 176 |
+
marker_pad : float
|
| 177 |
+
Padding between points in legend entry.
|
| 178 |
+
numpoints : int
|
| 179 |
+
Number of points to show in legend entry.
|
| 180 |
+
**kwargs
|
| 181 |
+
Keyword arguments forwarded to `.HandlerBase`.
|
| 182 |
+
"""
|
| 183 |
+
super().__init__(**kwargs)
|
| 184 |
+
|
| 185 |
+
self._numpoints = numpoints
|
| 186 |
+
self._marker_pad = marker_pad
|
| 187 |
+
|
| 188 |
+
def get_numpoints(self, legend):
|
| 189 |
+
if self._numpoints is None:
|
| 190 |
+
return legend.numpoints
|
| 191 |
+
else:
|
| 192 |
+
return self._numpoints
|
| 193 |
+
|
| 194 |
+
def get_xdata(self, legend, xdescent, ydescent, width, height, fontsize):
|
| 195 |
+
numpoints = self.get_numpoints(legend)
|
| 196 |
+
if numpoints > 1:
|
| 197 |
+
# we put some pad here to compensate the size of the marker
|
| 198 |
+
pad = self._marker_pad * fontsize
|
| 199 |
+
xdata = np.linspace(-xdescent + pad,
|
| 200 |
+
-xdescent + width - pad,
|
| 201 |
+
numpoints)
|
| 202 |
+
xdata_marker = xdata
|
| 203 |
+
else:
|
| 204 |
+
xdata = [-xdescent, -xdescent + width]
|
| 205 |
+
xdata_marker = [-xdescent + 0.5 * width]
|
| 206 |
+
return xdata, xdata_marker
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class HandlerNpointsYoffsets(HandlerNpoints):
|
| 210 |
+
"""
|
| 211 |
+
A legend handler that shows *numpoints* in the legend, and allows them to
|
| 212 |
+
be individually offset in the y-direction.
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
def __init__(self, numpoints=None, yoffsets=None, **kwargs):
|
| 216 |
+
"""
|
| 217 |
+
Parameters
|
| 218 |
+
----------
|
| 219 |
+
numpoints : int
|
| 220 |
+
Number of points to show in legend entry.
|
| 221 |
+
yoffsets : array of floats
|
| 222 |
+
Length *numpoints* list of y offsets for each point in
|
| 223 |
+
legend entry.
|
| 224 |
+
**kwargs
|
| 225 |
+
Keyword arguments forwarded to `.HandlerNpoints`.
|
| 226 |
+
"""
|
| 227 |
+
super().__init__(numpoints=numpoints, **kwargs)
|
| 228 |
+
self._yoffsets = yoffsets
|
| 229 |
+
|
| 230 |
+
def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):
|
| 231 |
+
if self._yoffsets is None:
|
| 232 |
+
ydata = height * legend._scatteryoffsets
|
| 233 |
+
else:
|
| 234 |
+
ydata = height * np.asarray(self._yoffsets)
|
| 235 |
+
|
| 236 |
+
return ydata
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class HandlerLine2DCompound(HandlerNpoints):
|
| 240 |
+
"""
|
| 241 |
+
Original handler for `.Line2D` instances, that relies on combining
|
| 242 |
+
a line-only with a marker-only artist. May be deprecated in the future.
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
def create_artists(self, legend, orig_handle,
|
| 246 |
+
xdescent, ydescent, width, height, fontsize,
|
| 247 |
+
trans):
|
| 248 |
+
# docstring inherited
|
| 249 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 250 |
+
width, height, fontsize)
|
| 251 |
+
|
| 252 |
+
ydata = np.full_like(xdata, ((height - ydescent) / 2))
|
| 253 |
+
legline = Line2D(xdata, ydata)
|
| 254 |
+
|
| 255 |
+
self.update_prop(legline, orig_handle, legend)
|
| 256 |
+
legline.set_drawstyle('default')
|
| 257 |
+
legline.set_marker("")
|
| 258 |
+
|
| 259 |
+
legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
|
| 260 |
+
self.update_prop(legline_marker, orig_handle, legend)
|
| 261 |
+
legline_marker.set_linestyle('None')
|
| 262 |
+
if legend.markerscale != 1:
|
| 263 |
+
newsz = legline_marker.get_markersize() * legend.markerscale
|
| 264 |
+
legline_marker.set_markersize(newsz)
|
| 265 |
+
# we don't want to add this to the return list because
|
| 266 |
+
# the texts and handles are assumed to be in one-to-one
|
| 267 |
+
# correspondence.
|
| 268 |
+
legline._legmarker = legline_marker
|
| 269 |
+
|
| 270 |
+
legline.set_transform(trans)
|
| 271 |
+
legline_marker.set_transform(trans)
|
| 272 |
+
|
| 273 |
+
return [legline, legline_marker]
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class HandlerLine2D(HandlerNpoints):
|
| 277 |
+
"""
|
| 278 |
+
Handler for `.Line2D` instances.
|
| 279 |
+
|
| 280 |
+
See Also
|
| 281 |
+
--------
|
| 282 |
+
HandlerLine2DCompound : An earlier handler implementation, which used one
|
| 283 |
+
artist for the line and another for the marker(s).
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
def create_artists(self, legend, orig_handle,
|
| 287 |
+
xdescent, ydescent, width, height, fontsize,
|
| 288 |
+
trans):
|
| 289 |
+
# docstring inherited
|
| 290 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 291 |
+
width, height, fontsize)
|
| 292 |
+
|
| 293 |
+
markevery = None
|
| 294 |
+
if self.get_numpoints(legend) == 1:
|
| 295 |
+
# Special case: one wants a single marker in the center
|
| 296 |
+
# and a line that extends on both sides. One will use a
|
| 297 |
+
# 3 points line, but only mark the #1 (i.e. middle) point.
|
| 298 |
+
xdata = np.linspace(xdata[0], xdata[-1], 3)
|
| 299 |
+
markevery = [1]
|
| 300 |
+
|
| 301 |
+
ydata = np.full_like(xdata, (height - ydescent) / 2)
|
| 302 |
+
legline = Line2D(xdata, ydata, markevery=markevery)
|
| 303 |
+
|
| 304 |
+
self.update_prop(legline, orig_handle, legend)
|
| 305 |
+
|
| 306 |
+
if legend.markerscale != 1:
|
| 307 |
+
newsz = legline.get_markersize() * legend.markerscale
|
| 308 |
+
legline.set_markersize(newsz)
|
| 309 |
+
|
| 310 |
+
legline.set_transform(trans)
|
| 311 |
+
|
| 312 |
+
return [legline]
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class HandlerPatch(HandlerBase):
|
| 316 |
+
"""
|
| 317 |
+
Handler for `.Patch` instances.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
def __init__(self, patch_func=None, **kwargs):
|
| 321 |
+
"""
|
| 322 |
+
Parameters
|
| 323 |
+
----------
|
| 324 |
+
patch_func : callable, optional
|
| 325 |
+
The function that creates the legend key artist.
|
| 326 |
+
*patch_func* should have the signature::
|
| 327 |
+
|
| 328 |
+
def patch_func(legend=legend, orig_handle=orig_handle,
|
| 329 |
+
xdescent=xdescent, ydescent=ydescent,
|
| 330 |
+
width=width, height=height, fontsize=fontsize)
|
| 331 |
+
|
| 332 |
+
Subsequently, the created artist will have its ``update_prop``
|
| 333 |
+
method called and the appropriate transform will be applied.
|
| 334 |
+
|
| 335 |
+
**kwargs
|
| 336 |
+
Keyword arguments forwarded to `.HandlerBase`.
|
| 337 |
+
"""
|
| 338 |
+
super().__init__(**kwargs)
|
| 339 |
+
self._patch_func = patch_func
|
| 340 |
+
|
| 341 |
+
def _create_patch(self, legend, orig_handle,
|
| 342 |
+
xdescent, ydescent, width, height, fontsize):
|
| 343 |
+
if self._patch_func is None:
|
| 344 |
+
p = Rectangle(xy=(-xdescent, -ydescent),
|
| 345 |
+
width=width, height=height)
|
| 346 |
+
else:
|
| 347 |
+
p = self._patch_func(legend=legend, orig_handle=orig_handle,
|
| 348 |
+
xdescent=xdescent, ydescent=ydescent,
|
| 349 |
+
width=width, height=height, fontsize=fontsize)
|
| 350 |
+
return p
|
| 351 |
+
|
| 352 |
+
def create_artists(self, legend, orig_handle,
|
| 353 |
+
xdescent, ydescent, width, height, fontsize, trans):
|
| 354 |
+
# docstring inherited
|
| 355 |
+
p = self._create_patch(legend, orig_handle,
|
| 356 |
+
xdescent, ydescent, width, height, fontsize)
|
| 357 |
+
self.update_prop(p, orig_handle, legend)
|
| 358 |
+
p.set_transform(trans)
|
| 359 |
+
return [p]
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class HandlerStepPatch(HandlerBase):
|
| 363 |
+
"""
|
| 364 |
+
Handler for `~.matplotlib.patches.StepPatch` instances.
|
| 365 |
+
"""
|
| 366 |
+
|
| 367 |
+
@staticmethod
|
| 368 |
+
def _create_patch(orig_handle, xdescent, ydescent, width, height):
|
| 369 |
+
return Rectangle(xy=(-xdescent, -ydescent), width=width,
|
| 370 |
+
height=height, color=orig_handle.get_facecolor())
|
| 371 |
+
|
| 372 |
+
@staticmethod
|
| 373 |
+
def _create_line(orig_handle, width, height):
|
| 374 |
+
# Unfilled StepPatch should show as a line
|
| 375 |
+
legline = Line2D([0, width], [height/2, height/2],
|
| 376 |
+
color=orig_handle.get_edgecolor(),
|
| 377 |
+
linestyle=orig_handle.get_linestyle(),
|
| 378 |
+
linewidth=orig_handle.get_linewidth(),
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Overwrite manually because patch and line properties don't mix
|
| 382 |
+
legline.set_drawstyle('default')
|
| 383 |
+
legline.set_marker("")
|
| 384 |
+
return legline
|
| 385 |
+
|
| 386 |
+
def create_artists(self, legend, orig_handle,
|
| 387 |
+
xdescent, ydescent, width, height, fontsize, trans):
|
| 388 |
+
# docstring inherited
|
| 389 |
+
if orig_handle.get_fill() or (orig_handle.get_hatch() is not None):
|
| 390 |
+
p = self._create_patch(orig_handle, xdescent, ydescent, width,
|
| 391 |
+
height)
|
| 392 |
+
self.update_prop(p, orig_handle, legend)
|
| 393 |
+
else:
|
| 394 |
+
p = self._create_line(orig_handle, width, height)
|
| 395 |
+
p.set_transform(trans)
|
| 396 |
+
return [p]
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class HandlerLineCollection(HandlerLine2D):
|
| 400 |
+
"""
|
| 401 |
+
Handler for `.LineCollection` instances.
|
| 402 |
+
"""
|
| 403 |
+
def get_numpoints(self, legend):
|
| 404 |
+
if self._numpoints is None:
|
| 405 |
+
return legend.scatterpoints
|
| 406 |
+
else:
|
| 407 |
+
return self._numpoints
|
| 408 |
+
|
| 409 |
+
def _default_update_prop(self, legend_handle, orig_handle):
|
| 410 |
+
lw = orig_handle.get_linewidths()[0]
|
| 411 |
+
dashes = orig_handle._us_linestyles[0]
|
| 412 |
+
color = orig_handle.get_colors()[0]
|
| 413 |
+
legend_handle.set_color(color)
|
| 414 |
+
legend_handle.set_linestyle(dashes)
|
| 415 |
+
legend_handle.set_linewidth(lw)
|
| 416 |
+
|
| 417 |
+
def create_artists(self, legend, orig_handle,
|
| 418 |
+
xdescent, ydescent, width, height, fontsize, trans):
|
| 419 |
+
# docstring inherited
|
| 420 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 421 |
+
width, height, fontsize)
|
| 422 |
+
ydata = np.full_like(xdata, (height - ydescent) / 2)
|
| 423 |
+
legline = Line2D(xdata, ydata)
|
| 424 |
+
|
| 425 |
+
self.update_prop(legline, orig_handle, legend)
|
| 426 |
+
legline.set_transform(trans)
|
| 427 |
+
|
| 428 |
+
return [legline]
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class HandlerRegularPolyCollection(HandlerNpointsYoffsets):
|
| 432 |
+
r"""Handler for `.RegularPolyCollection`\s."""
|
| 433 |
+
|
| 434 |
+
def __init__(self, yoffsets=None, sizes=None, **kwargs):
|
| 435 |
+
super().__init__(yoffsets=yoffsets, **kwargs)
|
| 436 |
+
|
| 437 |
+
self._sizes = sizes
|
| 438 |
+
|
| 439 |
+
def get_numpoints(self, legend):
|
| 440 |
+
if self._numpoints is None:
|
| 441 |
+
return legend.scatterpoints
|
| 442 |
+
else:
|
| 443 |
+
return self._numpoints
|
| 444 |
+
|
| 445 |
+
def get_sizes(self, legend, orig_handle,
|
| 446 |
+
xdescent, ydescent, width, height, fontsize):
|
| 447 |
+
if self._sizes is None:
|
| 448 |
+
handle_sizes = orig_handle.get_sizes()
|
| 449 |
+
if not len(handle_sizes):
|
| 450 |
+
handle_sizes = [1]
|
| 451 |
+
size_max = max(handle_sizes) * legend.markerscale ** 2
|
| 452 |
+
size_min = min(handle_sizes) * legend.markerscale ** 2
|
| 453 |
+
|
| 454 |
+
numpoints = self.get_numpoints(legend)
|
| 455 |
+
if numpoints < 4:
|
| 456 |
+
sizes = [.5 * (size_max + size_min), size_max,
|
| 457 |
+
size_min][:numpoints]
|
| 458 |
+
else:
|
| 459 |
+
rng = (size_max - size_min)
|
| 460 |
+
sizes = rng * np.linspace(0, 1, numpoints) + size_min
|
| 461 |
+
else:
|
| 462 |
+
sizes = self._sizes
|
| 463 |
+
|
| 464 |
+
return sizes
|
| 465 |
+
|
| 466 |
+
def update_prop(self, legend_handle, orig_handle, legend):
|
| 467 |
+
|
| 468 |
+
self._update_prop(legend_handle, orig_handle)
|
| 469 |
+
|
| 470 |
+
legend_handle.set_figure(legend.figure)
|
| 471 |
+
# legend._set_artist_props(legend_handle)
|
| 472 |
+
legend_handle.set_clip_box(None)
|
| 473 |
+
legend_handle.set_clip_path(None)
|
| 474 |
+
|
| 475 |
+
@_api.rename_parameter("3.6", "transOffset", "offset_transform")
|
| 476 |
+
def create_collection(self, orig_handle, sizes, offsets, offset_transform):
|
| 477 |
+
return type(orig_handle)(
|
| 478 |
+
orig_handle.get_numsides(),
|
| 479 |
+
rotation=orig_handle.get_rotation(), sizes=sizes,
|
| 480 |
+
offsets=offsets, offset_transform=offset_transform,
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
def create_artists(self, legend, orig_handle,
|
| 484 |
+
xdescent, ydescent, width, height, fontsize,
|
| 485 |
+
trans):
|
| 486 |
+
# docstring inherited
|
| 487 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 488 |
+
width, height, fontsize)
|
| 489 |
+
|
| 490 |
+
ydata = self.get_ydata(legend, xdescent, ydescent,
|
| 491 |
+
width, height, fontsize)
|
| 492 |
+
|
| 493 |
+
sizes = self.get_sizes(legend, orig_handle, xdescent, ydescent,
|
| 494 |
+
width, height, fontsize)
|
| 495 |
+
|
| 496 |
+
p = self.create_collection(
|
| 497 |
+
orig_handle, sizes,
|
| 498 |
+
offsets=list(zip(xdata_marker, ydata)), offset_transform=trans)
|
| 499 |
+
|
| 500 |
+
self.update_prop(p, orig_handle, legend)
|
| 501 |
+
p.set_offset_transform(trans)
|
| 502 |
+
return [p]
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
class HandlerPathCollection(HandlerRegularPolyCollection):
|
| 506 |
+
r"""Handler for `.PathCollection`\s, which are used by `~.Axes.scatter`."""
|
| 507 |
+
|
| 508 |
+
@_api.rename_parameter("3.6", "transOffset", "offset_transform")
|
| 509 |
+
def create_collection(self, orig_handle, sizes, offsets, offset_transform):
|
| 510 |
+
return type(orig_handle)(
|
| 511 |
+
[orig_handle.get_paths()[0]], sizes=sizes,
|
| 512 |
+
offsets=offsets, offset_transform=offset_transform,
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class HandlerCircleCollection(HandlerRegularPolyCollection):
|
| 517 |
+
r"""Handler for `.CircleCollection`\s."""
|
| 518 |
+
|
| 519 |
+
@_api.rename_parameter("3.6", "transOffset", "offset_transform")
|
| 520 |
+
def create_collection(self, orig_handle, sizes, offsets, offset_transform):
|
| 521 |
+
return type(orig_handle)(
|
| 522 |
+
sizes, offsets=offsets, offset_transform=offset_transform)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
class HandlerErrorbar(HandlerLine2D):
|
| 526 |
+
"""Handler for Errorbars."""
|
| 527 |
+
|
| 528 |
+
def __init__(self, xerr_size=0.5, yerr_size=None,
|
| 529 |
+
marker_pad=0.3, numpoints=None, **kwargs):
|
| 530 |
+
|
| 531 |
+
self._xerr_size = xerr_size
|
| 532 |
+
self._yerr_size = yerr_size
|
| 533 |
+
|
| 534 |
+
super().__init__(marker_pad=marker_pad, numpoints=numpoints, **kwargs)
|
| 535 |
+
|
| 536 |
+
def get_err_size(self, legend, xdescent, ydescent,
|
| 537 |
+
width, height, fontsize):
|
| 538 |
+
xerr_size = self._xerr_size * fontsize
|
| 539 |
+
|
| 540 |
+
if self._yerr_size is None:
|
| 541 |
+
yerr_size = xerr_size
|
| 542 |
+
else:
|
| 543 |
+
yerr_size = self._yerr_size * fontsize
|
| 544 |
+
|
| 545 |
+
return xerr_size, yerr_size
|
| 546 |
+
|
| 547 |
+
def create_artists(self, legend, orig_handle,
|
| 548 |
+
xdescent, ydescent, width, height, fontsize,
|
| 549 |
+
trans):
|
| 550 |
+
# docstring inherited
|
| 551 |
+
plotlines, caplines, barlinecols = orig_handle
|
| 552 |
+
|
| 553 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 554 |
+
width, height, fontsize)
|
| 555 |
+
|
| 556 |
+
ydata = np.full_like(xdata, (height - ydescent) / 2)
|
| 557 |
+
legline = Line2D(xdata, ydata)
|
| 558 |
+
|
| 559 |
+
xdata_marker = np.asarray(xdata_marker)
|
| 560 |
+
ydata_marker = np.asarray(ydata[:len(xdata_marker)])
|
| 561 |
+
|
| 562 |
+
xerr_size, yerr_size = self.get_err_size(legend, xdescent, ydescent,
|
| 563 |
+
width, height, fontsize)
|
| 564 |
+
|
| 565 |
+
legline_marker = Line2D(xdata_marker, ydata_marker)
|
| 566 |
+
|
| 567 |
+
# when plotlines are None (only errorbars are drawn), we just
|
| 568 |
+
# make legline invisible.
|
| 569 |
+
if plotlines is None:
|
| 570 |
+
legline.set_visible(False)
|
| 571 |
+
legline_marker.set_visible(False)
|
| 572 |
+
else:
|
| 573 |
+
self.update_prop(legline, plotlines, legend)
|
| 574 |
+
|
| 575 |
+
legline.set_drawstyle('default')
|
| 576 |
+
legline.set_marker('none')
|
| 577 |
+
|
| 578 |
+
self.update_prop(legline_marker, plotlines, legend)
|
| 579 |
+
legline_marker.set_linestyle('None')
|
| 580 |
+
|
| 581 |
+
if legend.markerscale != 1:
|
| 582 |
+
newsz = legline_marker.get_markersize() * legend.markerscale
|
| 583 |
+
legline_marker.set_markersize(newsz)
|
| 584 |
+
|
| 585 |
+
handle_barlinecols = []
|
| 586 |
+
handle_caplines = []
|
| 587 |
+
|
| 588 |
+
if orig_handle.has_xerr:
|
| 589 |
+
verts = [((x - xerr_size, y), (x + xerr_size, y))
|
| 590 |
+
for x, y in zip(xdata_marker, ydata_marker)]
|
| 591 |
+
coll = mcoll.LineCollection(verts)
|
| 592 |
+
self.update_prop(coll, barlinecols[0], legend)
|
| 593 |
+
handle_barlinecols.append(coll)
|
| 594 |
+
|
| 595 |
+
if caplines:
|
| 596 |
+
capline_left = Line2D(xdata_marker - xerr_size, ydata_marker)
|
| 597 |
+
capline_right = Line2D(xdata_marker + xerr_size, ydata_marker)
|
| 598 |
+
self.update_prop(capline_left, caplines[0], legend)
|
| 599 |
+
self.update_prop(capline_right, caplines[0], legend)
|
| 600 |
+
capline_left.set_marker("|")
|
| 601 |
+
capline_right.set_marker("|")
|
| 602 |
+
|
| 603 |
+
handle_caplines.append(capline_left)
|
| 604 |
+
handle_caplines.append(capline_right)
|
| 605 |
+
|
| 606 |
+
if orig_handle.has_yerr:
|
| 607 |
+
verts = [((x, y - yerr_size), (x, y + yerr_size))
|
| 608 |
+
for x, y in zip(xdata_marker, ydata_marker)]
|
| 609 |
+
coll = mcoll.LineCollection(verts)
|
| 610 |
+
self.update_prop(coll, barlinecols[0], legend)
|
| 611 |
+
handle_barlinecols.append(coll)
|
| 612 |
+
|
| 613 |
+
if caplines:
|
| 614 |
+
capline_left = Line2D(xdata_marker, ydata_marker - yerr_size)
|
| 615 |
+
capline_right = Line2D(xdata_marker, ydata_marker + yerr_size)
|
| 616 |
+
self.update_prop(capline_left, caplines[0], legend)
|
| 617 |
+
self.update_prop(capline_right, caplines[0], legend)
|
| 618 |
+
capline_left.set_marker("_")
|
| 619 |
+
capline_right.set_marker("_")
|
| 620 |
+
|
| 621 |
+
handle_caplines.append(capline_left)
|
| 622 |
+
handle_caplines.append(capline_right)
|
| 623 |
+
|
| 624 |
+
artists = [
|
| 625 |
+
*handle_barlinecols, *handle_caplines, legline, legline_marker,
|
| 626 |
+
]
|
| 627 |
+
for artist in artists:
|
| 628 |
+
artist.set_transform(trans)
|
| 629 |
+
return artists
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
class HandlerStem(HandlerNpointsYoffsets):
|
| 633 |
+
"""
|
| 634 |
+
Handler for plots produced by `~.Axes.stem`.
|
| 635 |
+
"""
|
| 636 |
+
|
| 637 |
+
def __init__(self, marker_pad=0.3, numpoints=None,
|
| 638 |
+
bottom=None, yoffsets=None, **kwargs):
|
| 639 |
+
"""
|
| 640 |
+
Parameters
|
| 641 |
+
----------
|
| 642 |
+
marker_pad : float, default: 0.3
|
| 643 |
+
Padding between points in legend entry.
|
| 644 |
+
numpoints : int, optional
|
| 645 |
+
Number of points to show in legend entry.
|
| 646 |
+
bottom : float, optional
|
| 647 |
+
|
| 648 |
+
yoffsets : array of floats, optional
|
| 649 |
+
Length *numpoints* list of y offsets for each point in
|
| 650 |
+
legend entry.
|
| 651 |
+
**kwargs
|
| 652 |
+
Keyword arguments forwarded to `.HandlerNpointsYoffsets`.
|
| 653 |
+
"""
|
| 654 |
+
super().__init__(marker_pad=marker_pad, numpoints=numpoints,
|
| 655 |
+
yoffsets=yoffsets, **kwargs)
|
| 656 |
+
self._bottom = bottom
|
| 657 |
+
|
| 658 |
+
def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):
|
| 659 |
+
if self._yoffsets is None:
|
| 660 |
+
ydata = height * (0.5 * legend._scatteryoffsets + 0.5)
|
| 661 |
+
else:
|
| 662 |
+
ydata = height * np.asarray(self._yoffsets)
|
| 663 |
+
|
| 664 |
+
return ydata
|
| 665 |
+
|
| 666 |
+
def create_artists(self, legend, orig_handle,
|
| 667 |
+
xdescent, ydescent, width, height, fontsize,
|
| 668 |
+
trans):
|
| 669 |
+
# docstring inherited
|
| 670 |
+
markerline, stemlines, baseline = orig_handle
|
| 671 |
+
# Check to see if the stemcontainer is storing lines as a list or a
|
| 672 |
+
# LineCollection. Eventually using a list will be removed, and this
|
| 673 |
+
# logic can also be removed.
|
| 674 |
+
using_linecoll = isinstance(stemlines, mcoll.LineCollection)
|
| 675 |
+
|
| 676 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 677 |
+
width, height, fontsize)
|
| 678 |
+
|
| 679 |
+
ydata = self.get_ydata(legend, xdescent, ydescent,
|
| 680 |
+
width, height, fontsize)
|
| 681 |
+
|
| 682 |
+
if self._bottom is None:
|
| 683 |
+
bottom = 0.
|
| 684 |
+
else:
|
| 685 |
+
bottom = self._bottom
|
| 686 |
+
|
| 687 |
+
leg_markerline = Line2D(xdata_marker, ydata[:len(xdata_marker)])
|
| 688 |
+
self.update_prop(leg_markerline, markerline, legend)
|
| 689 |
+
|
| 690 |
+
leg_stemlines = [Line2D([x, x], [bottom, y])
|
| 691 |
+
for x, y in zip(xdata_marker, ydata)]
|
| 692 |
+
|
| 693 |
+
if using_linecoll:
|
| 694 |
+
# change the function used by update_prop() from the default
|
| 695 |
+
# to one that handles LineCollection
|
| 696 |
+
with cbook._setattr_cm(
|
| 697 |
+
self, _update_prop_func=self._copy_collection_props):
|
| 698 |
+
for line in leg_stemlines:
|
| 699 |
+
self.update_prop(line, stemlines, legend)
|
| 700 |
+
|
| 701 |
+
else:
|
| 702 |
+
for lm, m in zip(leg_stemlines, stemlines):
|
| 703 |
+
self.update_prop(lm, m, legend)
|
| 704 |
+
|
| 705 |
+
leg_baseline = Line2D([np.min(xdata), np.max(xdata)],
|
| 706 |
+
[bottom, bottom])
|
| 707 |
+
self.update_prop(leg_baseline, baseline, legend)
|
| 708 |
+
|
| 709 |
+
artists = [*leg_stemlines, leg_baseline, leg_markerline]
|
| 710 |
+
for artist in artists:
|
| 711 |
+
artist.set_transform(trans)
|
| 712 |
+
return artists
|
| 713 |
+
|
| 714 |
+
def _copy_collection_props(self, legend_handle, orig_handle):
|
| 715 |
+
"""
|
| 716 |
+
Copy properties from the `.LineCollection` *orig_handle* to the
|
| 717 |
+
`.Line2D` *legend_handle*.
|
| 718 |
+
"""
|
| 719 |
+
legend_handle.set_color(orig_handle.get_color()[0])
|
| 720 |
+
legend_handle.set_linestyle(orig_handle.get_linestyle()[0])
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
class HandlerTuple(HandlerBase):
|
| 724 |
+
"""
|
| 725 |
+
Handler for Tuple.
|
| 726 |
+
"""
|
| 727 |
+
|
| 728 |
+
def __init__(self, ndivide=1, pad=None, **kwargs):
|
| 729 |
+
"""
|
| 730 |
+
Parameters
|
| 731 |
+
----------
|
| 732 |
+
ndivide : int, default: 1
|
| 733 |
+
The number of sections to divide the legend area into. If None,
|
| 734 |
+
use the length of the input tuple.
|
| 735 |
+
pad : float, default: :rc:`legend.borderpad`
|
| 736 |
+
Padding in units of fraction of font size.
|
| 737 |
+
**kwargs
|
| 738 |
+
Keyword arguments forwarded to `.HandlerBase`.
|
| 739 |
+
"""
|
| 740 |
+
self._ndivide = ndivide
|
| 741 |
+
self._pad = pad
|
| 742 |
+
super().__init__(**kwargs)
|
| 743 |
+
|
| 744 |
+
def create_artists(self, legend, orig_handle,
|
| 745 |
+
xdescent, ydescent, width, height, fontsize,
|
| 746 |
+
trans):
|
| 747 |
+
# docstring inherited
|
| 748 |
+
handler_map = legend.get_legend_handler_map()
|
| 749 |
+
|
| 750 |
+
if self._ndivide is None:
|
| 751 |
+
ndivide = len(orig_handle)
|
| 752 |
+
else:
|
| 753 |
+
ndivide = self._ndivide
|
| 754 |
+
|
| 755 |
+
if self._pad is None:
|
| 756 |
+
pad = legend.borderpad * fontsize
|
| 757 |
+
else:
|
| 758 |
+
pad = self._pad * fontsize
|
| 759 |
+
|
| 760 |
+
if ndivide > 1:
|
| 761 |
+
width = (width - pad * (ndivide - 1)) / ndivide
|
| 762 |
+
|
| 763 |
+
xds_cycle = cycle(xdescent - (width + pad) * np.arange(ndivide))
|
| 764 |
+
|
| 765 |
+
a_list = []
|
| 766 |
+
for handle1 in orig_handle:
|
| 767 |
+
handler = legend.get_legend_handler(handler_map, handle1)
|
| 768 |
+
_a_list = handler.create_artists(
|
| 769 |
+
legend, handle1,
|
| 770 |
+
next(xds_cycle), ydescent, width, height, fontsize, trans)
|
| 771 |
+
a_list.extend(_a_list)
|
| 772 |
+
|
| 773 |
+
return a_list
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
class HandlerPolyCollection(HandlerBase):
|
| 777 |
+
"""
|
| 778 |
+
Handler for `.PolyCollection` used in `~.Axes.fill_between` and
|
| 779 |
+
`~.Axes.stackplot`.
|
| 780 |
+
"""
|
| 781 |
+
def _update_prop(self, legend_handle, orig_handle):
|
| 782 |
+
def first_color(colors):
|
| 783 |
+
if colors.size == 0:
|
| 784 |
+
return (0, 0, 0, 0)
|
| 785 |
+
return tuple(colors[0])
|
| 786 |
+
|
| 787 |
+
def get_first(prop_array):
|
| 788 |
+
if len(prop_array):
|
| 789 |
+
return prop_array[0]
|
| 790 |
+
else:
|
| 791 |
+
return None
|
| 792 |
+
|
| 793 |
+
# orig_handle is a PolyCollection and legend_handle is a Patch.
|
| 794 |
+
# Directly set Patch color attributes (must be RGBA tuples).
|
| 795 |
+
legend_handle._facecolor = first_color(orig_handle.get_facecolor())
|
| 796 |
+
legend_handle._edgecolor = first_color(orig_handle.get_edgecolor())
|
| 797 |
+
legend_handle._original_facecolor = orig_handle._original_facecolor
|
| 798 |
+
legend_handle._original_edgecolor = orig_handle._original_edgecolor
|
| 799 |
+
legend_handle._fill = orig_handle.get_fill()
|
| 800 |
+
legend_handle._hatch = orig_handle.get_hatch()
|
| 801 |
+
# Hatch color is anomalous in having no getters and setters.
|
| 802 |
+
legend_handle._hatch_color = orig_handle._hatch_color
|
| 803 |
+
# Setters are fine for the remaining attributes.
|
| 804 |
+
legend_handle.set_linewidth(get_first(orig_handle.get_linewidths()))
|
| 805 |
+
legend_handle.set_linestyle(get_first(orig_handle.get_linestyles()))
|
| 806 |
+
legend_handle.set_transform(get_first(orig_handle.get_transforms()))
|
| 807 |
+
legend_handle.set_figure(orig_handle.get_figure())
|
| 808 |
+
# Alpha is already taken into account by the color attributes.
|
| 809 |
+
|
| 810 |
+
def create_artists(self, legend, orig_handle,
|
| 811 |
+
xdescent, ydescent, width, height, fontsize, trans):
|
| 812 |
+
# docstring inherited
|
| 813 |
+
p = Rectangle(xy=(-xdescent, -ydescent),
|
| 814 |
+
width=width, height=height)
|
| 815 |
+
self.update_prop(p, orig_handle, legend)
|
| 816 |
+
p.set_transform(trans)
|
| 817 |
+
return [p]
|
omnilmm/lib/python3.10/site-packages/matplotlib/scale.py
ADDED
|
@@ -0,0 +1,748 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Scales define the distribution of data values on an axis, e.g. a log scaling.
|
| 3 |
+
They are defined as subclasses of `ScaleBase`.
|
| 4 |
+
|
| 5 |
+
See also `.axes.Axes.set_xscale` and the scales examples in the documentation.
|
| 6 |
+
|
| 7 |
+
See :doc:`/gallery/scales/custom_scale` for a full example of defining a custom
|
| 8 |
+
scale.
|
| 9 |
+
|
| 10 |
+
Matplotlib also supports non-separable transformations that operate on both
|
| 11 |
+
`~.axis.Axis` at the same time. They are known as projections, and defined in
|
| 12 |
+
`matplotlib.projections`.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import textwrap
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
import matplotlib as mpl
|
| 21 |
+
from matplotlib import _api, _docstring
|
| 22 |
+
from matplotlib.ticker import (
|
| 23 |
+
NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
|
| 24 |
+
NullLocator, LogLocator, AutoLocator, AutoMinorLocator,
|
| 25 |
+
SymmetricalLogLocator, AsinhLocator, LogitLocator)
|
| 26 |
+
from matplotlib.transforms import Transform, IdentityTransform
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ScaleBase:
|
| 30 |
+
"""
|
| 31 |
+
The base class for all scales.
|
| 32 |
+
|
| 33 |
+
Scales are separable transformations, working on a single dimension.
|
| 34 |
+
|
| 35 |
+
Subclasses should override
|
| 36 |
+
|
| 37 |
+
:attr:`name`
|
| 38 |
+
The scale's name.
|
| 39 |
+
:meth:`get_transform`
|
| 40 |
+
A method returning a `.Transform`, which converts data coordinates to
|
| 41 |
+
scaled coordinates. This transform should be invertible, so that e.g.
|
| 42 |
+
mouse positions can be converted back to data coordinates.
|
| 43 |
+
:meth:`set_default_locators_and_formatters`
|
| 44 |
+
A method that sets default locators and formatters for an `~.axis.Axis`
|
| 45 |
+
that uses this scale.
|
| 46 |
+
:meth:`limit_range_for_scale`
|
| 47 |
+
An optional method that "fixes" the axis range to acceptable values,
|
| 48 |
+
e.g. restricting log-scaled axes to positive values.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(self, axis):
|
| 52 |
+
r"""
|
| 53 |
+
Construct a new scale.
|
| 54 |
+
|
| 55 |
+
Notes
|
| 56 |
+
-----
|
| 57 |
+
The following note is for scale implementors.
|
| 58 |
+
|
| 59 |
+
For back-compatibility reasons, scales take an `~matplotlib.axis.Axis`
|
| 60 |
+
object as first argument. However, this argument should not
|
| 61 |
+
be used: a single scale object should be usable by multiple
|
| 62 |
+
`~matplotlib.axis.Axis`\es at the same time.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def get_transform(self):
|
| 66 |
+
"""
|
| 67 |
+
Return the `.Transform` object associated with this scale.
|
| 68 |
+
"""
|
| 69 |
+
raise NotImplementedError()
|
| 70 |
+
|
| 71 |
+
def set_default_locators_and_formatters(self, axis):
|
| 72 |
+
"""
|
| 73 |
+
Set the locators and formatters of *axis* to instances suitable for
|
| 74 |
+
this scale.
|
| 75 |
+
"""
|
| 76 |
+
raise NotImplementedError()
|
| 77 |
+
|
| 78 |
+
def limit_range_for_scale(self, vmin, vmax, minpos):
|
| 79 |
+
"""
|
| 80 |
+
Return the range *vmin*, *vmax*, restricted to the
|
| 81 |
+
domain supported by this scale (if any).
|
| 82 |
+
|
| 83 |
+
*minpos* should be the minimum positive value in the data.
|
| 84 |
+
This is used by log scales to determine a minimum value.
|
| 85 |
+
"""
|
| 86 |
+
return vmin, vmax
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class LinearScale(ScaleBase):
|
| 90 |
+
"""
|
| 91 |
+
The default linear scale.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
name = 'linear'
|
| 95 |
+
|
| 96 |
+
def __init__(self, axis):
|
| 97 |
+
# This method is present only to prevent inheritance of the base class'
|
| 98 |
+
# constructor docstring, which would otherwise end up interpolated into
|
| 99 |
+
# the docstring of Axis.set_scale.
|
| 100 |
+
"""
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def set_default_locators_and_formatters(self, axis):
|
| 104 |
+
# docstring inherited
|
| 105 |
+
axis.set_major_locator(AutoLocator())
|
| 106 |
+
axis.set_major_formatter(ScalarFormatter())
|
| 107 |
+
axis.set_minor_formatter(NullFormatter())
|
| 108 |
+
# update the minor locator for x and y axis based on rcParams
|
| 109 |
+
if (axis.axis_name == 'x' and mpl.rcParams['xtick.minor.visible'] or
|
| 110 |
+
axis.axis_name == 'y' and mpl.rcParams['ytick.minor.visible']):
|
| 111 |
+
axis.set_minor_locator(AutoMinorLocator())
|
| 112 |
+
else:
|
| 113 |
+
axis.set_minor_locator(NullLocator())
|
| 114 |
+
|
| 115 |
+
def get_transform(self):
|
| 116 |
+
"""
|
| 117 |
+
Return the transform for linear scaling, which is just the
|
| 118 |
+
`~matplotlib.transforms.IdentityTransform`.
|
| 119 |
+
"""
|
| 120 |
+
return IdentityTransform()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class FuncTransform(Transform):
|
| 124 |
+
"""
|
| 125 |
+
A simple transform that takes and arbitrary function for the
|
| 126 |
+
forward and inverse transform.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
input_dims = output_dims = 1
|
| 130 |
+
|
| 131 |
+
def __init__(self, forward, inverse):
|
| 132 |
+
"""
|
| 133 |
+
Parameters
|
| 134 |
+
----------
|
| 135 |
+
forward : callable
|
| 136 |
+
The forward function for the transform. This function must have
|
| 137 |
+
an inverse and, for best behavior, be monotonic.
|
| 138 |
+
It must have the signature::
|
| 139 |
+
|
| 140 |
+
def forward(values: array-like) -> array-like
|
| 141 |
+
|
| 142 |
+
inverse : callable
|
| 143 |
+
The inverse of the forward function. Signature as ``forward``.
|
| 144 |
+
"""
|
| 145 |
+
super().__init__()
|
| 146 |
+
if callable(forward) and callable(inverse):
|
| 147 |
+
self._forward = forward
|
| 148 |
+
self._inverse = inverse
|
| 149 |
+
else:
|
| 150 |
+
raise ValueError('arguments to FuncTransform must be functions')
|
| 151 |
+
|
| 152 |
+
def transform_non_affine(self, values):
|
| 153 |
+
return self._forward(values)
|
| 154 |
+
|
| 155 |
+
def inverted(self):
|
| 156 |
+
return FuncTransform(self._inverse, self._forward)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class FuncScale(ScaleBase):
|
| 160 |
+
"""
|
| 161 |
+
Provide an arbitrary scale with user-supplied function for the axis.
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
name = 'function'
|
| 165 |
+
|
| 166 |
+
def __init__(self, axis, functions):
|
| 167 |
+
"""
|
| 168 |
+
Parameters
|
| 169 |
+
----------
|
| 170 |
+
axis : `~matplotlib.axis.Axis`
|
| 171 |
+
The axis for the scale.
|
| 172 |
+
functions : (callable, callable)
|
| 173 |
+
two-tuple of the forward and inverse functions for the scale.
|
| 174 |
+
The forward function must be monotonic.
|
| 175 |
+
|
| 176 |
+
Both functions must have the signature::
|
| 177 |
+
|
| 178 |
+
def forward(values: array-like) -> array-like
|
| 179 |
+
"""
|
| 180 |
+
forward, inverse = functions
|
| 181 |
+
transform = FuncTransform(forward, inverse)
|
| 182 |
+
self._transform = transform
|
| 183 |
+
|
| 184 |
+
def get_transform(self):
|
| 185 |
+
"""Return the `.FuncTransform` associated with this scale."""
|
| 186 |
+
return self._transform
|
| 187 |
+
|
| 188 |
+
def set_default_locators_and_formatters(self, axis):
|
| 189 |
+
# docstring inherited
|
| 190 |
+
axis.set_major_locator(AutoLocator())
|
| 191 |
+
axis.set_major_formatter(ScalarFormatter())
|
| 192 |
+
axis.set_minor_formatter(NullFormatter())
|
| 193 |
+
# update the minor locator for x and y axis based on rcParams
|
| 194 |
+
if (axis.axis_name == 'x' and mpl.rcParams['xtick.minor.visible'] or
|
| 195 |
+
axis.axis_name == 'y' and mpl.rcParams['ytick.minor.visible']):
|
| 196 |
+
axis.set_minor_locator(AutoMinorLocator())
|
| 197 |
+
else:
|
| 198 |
+
axis.set_minor_locator(NullLocator())
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class LogTransform(Transform):
|
| 202 |
+
input_dims = output_dims = 1
|
| 203 |
+
|
| 204 |
+
def __init__(self, base, nonpositive='clip'):
|
| 205 |
+
super().__init__()
|
| 206 |
+
if base <= 0 or base == 1:
|
| 207 |
+
raise ValueError('The log base cannot be <= 0 or == 1')
|
| 208 |
+
self.base = base
|
| 209 |
+
self._clip = _api.check_getitem(
|
| 210 |
+
{"clip": True, "mask": False}, nonpositive=nonpositive)
|
| 211 |
+
|
| 212 |
+
def __str__(self):
|
| 213 |
+
return "{}(base={}, nonpositive={!r})".format(
|
| 214 |
+
type(self).__name__, self.base, "clip" if self._clip else "mask")
|
| 215 |
+
|
| 216 |
+
def transform_non_affine(self, a):
|
| 217 |
+
# Ignore invalid values due to nans being passed to the transform.
|
| 218 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 219 |
+
log = {np.e: np.log, 2: np.log2, 10: np.log10}.get(self.base)
|
| 220 |
+
if log: # If possible, do everything in a single call to NumPy.
|
| 221 |
+
out = log(a)
|
| 222 |
+
else:
|
| 223 |
+
out = np.log(a)
|
| 224 |
+
out /= np.log(self.base)
|
| 225 |
+
if self._clip:
|
| 226 |
+
# SVG spec says that conforming viewers must support values up
|
| 227 |
+
# to 3.4e38 (C float); however experiments suggest that
|
| 228 |
+
# Inkscape (which uses cairo for rendering) runs into cairo's
|
| 229 |
+
# 24-bit limit (which is apparently shared by Agg).
|
| 230 |
+
# Ghostscript (used for pdf rendering appears to overflow even
|
| 231 |
+
# earlier, with the max value around 2 ** 15 for the tests to
|
| 232 |
+
# pass. On the other hand, in practice, we want to clip beyond
|
| 233 |
+
# np.log10(np.nextafter(0, 1)) ~ -323
|
| 234 |
+
# so 1000 seems safe.
|
| 235 |
+
out[a <= 0] = -1000
|
| 236 |
+
return out
|
| 237 |
+
|
| 238 |
+
def inverted(self):
|
| 239 |
+
return InvertedLogTransform(self.base)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class InvertedLogTransform(Transform):
|
| 243 |
+
input_dims = output_dims = 1
|
| 244 |
+
|
| 245 |
+
def __init__(self, base):
|
| 246 |
+
super().__init__()
|
| 247 |
+
self.base = base
|
| 248 |
+
|
| 249 |
+
def __str__(self):
|
| 250 |
+
return "{}(base={})".format(type(self).__name__, self.base)
|
| 251 |
+
|
| 252 |
+
def transform_non_affine(self, a):
|
| 253 |
+
return np.power(self.base, a)
|
| 254 |
+
|
| 255 |
+
def inverted(self):
|
| 256 |
+
return LogTransform(self.base)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class LogScale(ScaleBase):
|
| 260 |
+
"""
|
| 261 |
+
A standard logarithmic scale. Care is taken to only plot positive values.
|
| 262 |
+
"""
|
| 263 |
+
name = 'log'
|
| 264 |
+
|
| 265 |
+
def __init__(self, axis, *, base=10, subs=None, nonpositive="clip"):
|
| 266 |
+
"""
|
| 267 |
+
Parameters
|
| 268 |
+
----------
|
| 269 |
+
axis : `~matplotlib.axis.Axis`
|
| 270 |
+
The axis for the scale.
|
| 271 |
+
base : float, default: 10
|
| 272 |
+
The base of the logarithm.
|
| 273 |
+
nonpositive : {'clip', 'mask'}, default: 'clip'
|
| 274 |
+
Determines the behavior for non-positive values. They can either
|
| 275 |
+
be masked as invalid, or clipped to a very small positive number.
|
| 276 |
+
subs : sequence of int, default: None
|
| 277 |
+
Where to place the subticks between each major tick. For example,
|
| 278 |
+
in a log10 scale, ``[2, 3, 4, 5, 6, 7, 8, 9]`` will place 8
|
| 279 |
+
logarithmically spaced minor ticks between each major tick.
|
| 280 |
+
"""
|
| 281 |
+
self._transform = LogTransform(base, nonpositive)
|
| 282 |
+
self.subs = subs
|
| 283 |
+
|
| 284 |
+
base = property(lambda self: self._transform.base)
|
| 285 |
+
|
| 286 |
+
def set_default_locators_and_formatters(self, axis):
|
| 287 |
+
# docstring inherited
|
| 288 |
+
axis.set_major_locator(LogLocator(self.base))
|
| 289 |
+
axis.set_major_formatter(LogFormatterSciNotation(self.base))
|
| 290 |
+
axis.set_minor_locator(LogLocator(self.base, self.subs))
|
| 291 |
+
axis.set_minor_formatter(
|
| 292 |
+
LogFormatterSciNotation(self.base,
|
| 293 |
+
labelOnlyBase=(self.subs is not None)))
|
| 294 |
+
|
| 295 |
+
def get_transform(self):
|
| 296 |
+
"""Return the `.LogTransform` associated with this scale."""
|
| 297 |
+
return self._transform
|
| 298 |
+
|
| 299 |
+
def limit_range_for_scale(self, vmin, vmax, minpos):
|
| 300 |
+
"""Limit the domain to positive values."""
|
| 301 |
+
if not np.isfinite(minpos):
|
| 302 |
+
minpos = 1e-300 # Should rarely (if ever) have a visible effect.
|
| 303 |
+
|
| 304 |
+
return (minpos if vmin <= 0 else vmin,
|
| 305 |
+
minpos if vmax <= 0 else vmax)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class FuncScaleLog(LogScale):
|
| 309 |
+
"""
|
| 310 |
+
Provide an arbitrary scale with user-supplied function for the axis and
|
| 311 |
+
then put on a logarithmic axes.
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
name = 'functionlog'
|
| 315 |
+
|
| 316 |
+
def __init__(self, axis, functions, base=10):
|
| 317 |
+
"""
|
| 318 |
+
Parameters
|
| 319 |
+
----------
|
| 320 |
+
axis : `~matplotlib.axis.Axis`
|
| 321 |
+
The axis for the scale.
|
| 322 |
+
functions : (callable, callable)
|
| 323 |
+
two-tuple of the forward and inverse functions for the scale.
|
| 324 |
+
The forward function must be monotonic.
|
| 325 |
+
|
| 326 |
+
Both functions must have the signature::
|
| 327 |
+
|
| 328 |
+
def forward(values: array-like) -> array-like
|
| 329 |
+
|
| 330 |
+
base : float, default: 10
|
| 331 |
+
Logarithmic base of the scale.
|
| 332 |
+
"""
|
| 333 |
+
forward, inverse = functions
|
| 334 |
+
self.subs = None
|
| 335 |
+
self._transform = FuncTransform(forward, inverse) + LogTransform(base)
|
| 336 |
+
|
| 337 |
+
@property
|
| 338 |
+
def base(self):
|
| 339 |
+
return self._transform._b.base # Base of the LogTransform.
|
| 340 |
+
|
| 341 |
+
def get_transform(self):
|
| 342 |
+
"""Return the `.Transform` associated with this scale."""
|
| 343 |
+
return self._transform
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class SymmetricalLogTransform(Transform):
|
| 347 |
+
input_dims = output_dims = 1
|
| 348 |
+
|
| 349 |
+
def __init__(self, base, linthresh, linscale):
|
| 350 |
+
super().__init__()
|
| 351 |
+
if base <= 1.0:
|
| 352 |
+
raise ValueError("'base' must be larger than 1")
|
| 353 |
+
if linthresh <= 0.0:
|
| 354 |
+
raise ValueError("'linthresh' must be positive")
|
| 355 |
+
if linscale <= 0.0:
|
| 356 |
+
raise ValueError("'linscale' must be positive")
|
| 357 |
+
self.base = base
|
| 358 |
+
self.linthresh = linthresh
|
| 359 |
+
self.linscale = linscale
|
| 360 |
+
self._linscale_adj = (linscale / (1.0 - self.base ** -1))
|
| 361 |
+
self._log_base = np.log(base)
|
| 362 |
+
|
| 363 |
+
def transform_non_affine(self, a):
|
| 364 |
+
abs_a = np.abs(a)
|
| 365 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 366 |
+
out = np.sign(a) * self.linthresh * (
|
| 367 |
+
self._linscale_adj +
|
| 368 |
+
np.log(abs_a / self.linthresh) / self._log_base)
|
| 369 |
+
inside = abs_a <= self.linthresh
|
| 370 |
+
out[inside] = a[inside] * self._linscale_adj
|
| 371 |
+
return out
|
| 372 |
+
|
| 373 |
+
def inverted(self):
|
| 374 |
+
return InvertedSymmetricalLogTransform(self.base, self.linthresh,
|
| 375 |
+
self.linscale)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
class InvertedSymmetricalLogTransform(Transform):
|
| 379 |
+
input_dims = output_dims = 1
|
| 380 |
+
|
| 381 |
+
def __init__(self, base, linthresh, linscale):
|
| 382 |
+
super().__init__()
|
| 383 |
+
symlog = SymmetricalLogTransform(base, linthresh, linscale)
|
| 384 |
+
self.base = base
|
| 385 |
+
self.linthresh = linthresh
|
| 386 |
+
self.invlinthresh = symlog.transform(linthresh)
|
| 387 |
+
self.linscale = linscale
|
| 388 |
+
self._linscale_adj = (linscale / (1.0 - self.base ** -1))
|
| 389 |
+
|
| 390 |
+
def transform_non_affine(self, a):
|
| 391 |
+
abs_a = np.abs(a)
|
| 392 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 393 |
+
out = np.sign(a) * self.linthresh * (
|
| 394 |
+
np.power(self.base,
|
| 395 |
+
abs_a / self.linthresh - self._linscale_adj))
|
| 396 |
+
inside = abs_a <= self.invlinthresh
|
| 397 |
+
out[inside] = a[inside] / self._linscale_adj
|
| 398 |
+
return out
|
| 399 |
+
|
| 400 |
+
def inverted(self):
|
| 401 |
+
return SymmetricalLogTransform(self.base,
|
| 402 |
+
self.linthresh, self.linscale)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class SymmetricalLogScale(ScaleBase):
|
| 406 |
+
"""
|
| 407 |
+
The symmetrical logarithmic scale is logarithmic in both the
|
| 408 |
+
positive and negative directions from the origin.
|
| 409 |
+
|
| 410 |
+
Since the values close to zero tend toward infinity, there is a
|
| 411 |
+
need to have a range around zero that is linear. The parameter
|
| 412 |
+
*linthresh* allows the user to specify the size of this range
|
| 413 |
+
(-*linthresh*, *linthresh*).
|
| 414 |
+
|
| 415 |
+
Parameters
|
| 416 |
+
----------
|
| 417 |
+
base : float, default: 10
|
| 418 |
+
The base of the logarithm.
|
| 419 |
+
|
| 420 |
+
linthresh : float, default: 2
|
| 421 |
+
Defines the range ``(-x, x)``, within which the plot is linear.
|
| 422 |
+
This avoids having the plot go to infinity around zero.
|
| 423 |
+
|
| 424 |
+
subs : sequence of int
|
| 425 |
+
Where to place the subticks between each major tick.
|
| 426 |
+
For example, in a log10 scale: ``[2, 3, 4, 5, 6, 7, 8, 9]`` will place
|
| 427 |
+
8 logarithmically spaced minor ticks between each major tick.
|
| 428 |
+
|
| 429 |
+
linscale : float, optional
|
| 430 |
+
This allows the linear range ``(-linthresh, linthresh)`` to be
|
| 431 |
+
stretched relative to the logarithmic range. Its value is the number of
|
| 432 |
+
decades to use for each half of the linear range. For example, when
|
| 433 |
+
*linscale* == 1.0 (the default), the space used for the positive and
|
| 434 |
+
negative halves of the linear range will be equal to one decade in
|
| 435 |
+
the logarithmic range.
|
| 436 |
+
"""
|
| 437 |
+
name = 'symlog'
|
| 438 |
+
|
| 439 |
+
def __init__(self, axis, *, base=10, linthresh=2, subs=None, linscale=1):
|
| 440 |
+
self._transform = SymmetricalLogTransform(base, linthresh, linscale)
|
| 441 |
+
self.subs = subs
|
| 442 |
+
|
| 443 |
+
base = property(lambda self: self._transform.base)
|
| 444 |
+
linthresh = property(lambda self: self._transform.linthresh)
|
| 445 |
+
linscale = property(lambda self: self._transform.linscale)
|
| 446 |
+
|
| 447 |
+
def set_default_locators_and_formatters(self, axis):
|
| 448 |
+
# docstring inherited
|
| 449 |
+
axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))
|
| 450 |
+
axis.set_major_formatter(LogFormatterSciNotation(self.base))
|
| 451 |
+
axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(),
|
| 452 |
+
self.subs))
|
| 453 |
+
axis.set_minor_formatter(NullFormatter())
|
| 454 |
+
|
| 455 |
+
def get_transform(self):
|
| 456 |
+
"""Return the `.SymmetricalLogTransform` associated with this scale."""
|
| 457 |
+
return self._transform
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class AsinhTransform(Transform):
|
| 461 |
+
"""Inverse hyperbolic-sine transformation used by `.AsinhScale`"""
|
| 462 |
+
input_dims = output_dims = 1
|
| 463 |
+
|
| 464 |
+
def __init__(self, linear_width):
|
| 465 |
+
super().__init__()
|
| 466 |
+
if linear_width <= 0.0:
|
| 467 |
+
raise ValueError("Scale parameter 'linear_width' " +
|
| 468 |
+
"must be strictly positive")
|
| 469 |
+
self.linear_width = linear_width
|
| 470 |
+
|
| 471 |
+
def transform_non_affine(self, a):
|
| 472 |
+
return self.linear_width * np.arcsinh(a / self.linear_width)
|
| 473 |
+
|
| 474 |
+
def inverted(self):
|
| 475 |
+
return InvertedAsinhTransform(self.linear_width)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class InvertedAsinhTransform(Transform):
|
| 479 |
+
"""Hyperbolic sine transformation used by `.AsinhScale`"""
|
| 480 |
+
input_dims = output_dims = 1
|
| 481 |
+
|
| 482 |
+
def __init__(self, linear_width):
|
| 483 |
+
super().__init__()
|
| 484 |
+
self.linear_width = linear_width
|
| 485 |
+
|
| 486 |
+
def transform_non_affine(self, a):
|
| 487 |
+
return self.linear_width * np.sinh(a / self.linear_width)
|
| 488 |
+
|
| 489 |
+
def inverted(self):
|
| 490 |
+
return AsinhTransform(self.linear_width)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
class AsinhScale(ScaleBase):
|
| 494 |
+
"""
|
| 495 |
+
A quasi-logarithmic scale based on the inverse hyperbolic sine (asinh)
|
| 496 |
+
|
| 497 |
+
For values close to zero, this is essentially a linear scale,
|
| 498 |
+
but for large magnitude values (either positive or negative)
|
| 499 |
+
it is asymptotically logarithmic. The transition between these
|
| 500 |
+
linear and logarithmic regimes is smooth, and has no discontinuities
|
| 501 |
+
in the function gradient in contrast to
|
| 502 |
+
the `.SymmetricalLogScale` ("symlog") scale.
|
| 503 |
+
|
| 504 |
+
Specifically, the transformation of an axis coordinate :math:`a` is
|
| 505 |
+
:math:`a \\rightarrow a_0 \\sinh^{-1} (a / a_0)` where :math:`a_0`
|
| 506 |
+
is the effective width of the linear region of the transformation.
|
| 507 |
+
In that region, the transformation is
|
| 508 |
+
:math:`a \\rightarrow a + \\mathcal{O}(a^3)`.
|
| 509 |
+
For large values of :math:`a` the transformation behaves as
|
| 510 |
+
:math:`a \\rightarrow a_0 \\, \\mathrm{sgn}(a) \\ln |a| + \\mathcal{O}(1)`.
|
| 511 |
+
|
| 512 |
+
.. note::
|
| 513 |
+
|
| 514 |
+
This API is provisional and may be revised in the future
|
| 515 |
+
based on early user feedback.
|
| 516 |
+
"""
|
| 517 |
+
|
| 518 |
+
name = 'asinh'
|
| 519 |
+
|
| 520 |
+
auto_tick_multipliers = {
|
| 521 |
+
3: (2, ),
|
| 522 |
+
4: (2, ),
|
| 523 |
+
5: (2, ),
|
| 524 |
+
8: (2, 4),
|
| 525 |
+
10: (2, 5),
|
| 526 |
+
16: (2, 4, 8),
|
| 527 |
+
64: (4, 16),
|
| 528 |
+
1024: (256, 512)
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
def __init__(self, axis, *, linear_width=1.0,
|
| 532 |
+
base=10, subs='auto', **kwargs):
|
| 533 |
+
"""
|
| 534 |
+
Parameters
|
| 535 |
+
----------
|
| 536 |
+
linear_width : float, default: 1
|
| 537 |
+
The scale parameter (elsewhere referred to as :math:`a_0`)
|
| 538 |
+
defining the extent of the quasi-linear region,
|
| 539 |
+
and the coordinate values beyond which the transformation
|
| 540 |
+
becomes asymptotically logarithmic.
|
| 541 |
+
base : int, default: 10
|
| 542 |
+
The number base used for rounding tick locations
|
| 543 |
+
on a logarithmic scale. If this is less than one,
|
| 544 |
+
then rounding is to the nearest integer multiple
|
| 545 |
+
of powers of ten.
|
| 546 |
+
subs : sequence of int
|
| 547 |
+
Multiples of the number base used for minor ticks.
|
| 548 |
+
If set to 'auto', this will use built-in defaults,
|
| 549 |
+
e.g. (2, 5) for base=10.
|
| 550 |
+
"""
|
| 551 |
+
super().__init__(axis)
|
| 552 |
+
self._transform = AsinhTransform(linear_width)
|
| 553 |
+
self._base = int(base)
|
| 554 |
+
if subs == 'auto':
|
| 555 |
+
self._subs = self.auto_tick_multipliers.get(self._base)
|
| 556 |
+
else:
|
| 557 |
+
self._subs = subs
|
| 558 |
+
|
| 559 |
+
linear_width = property(lambda self: self._transform.linear_width)
|
| 560 |
+
|
| 561 |
+
def get_transform(self):
|
| 562 |
+
return self._transform
|
| 563 |
+
|
| 564 |
+
def set_default_locators_and_formatters(self, axis):
|
| 565 |
+
axis.set(major_locator=AsinhLocator(self.linear_width,
|
| 566 |
+
base=self._base),
|
| 567 |
+
minor_locator=AsinhLocator(self.linear_width,
|
| 568 |
+
base=self._base,
|
| 569 |
+
subs=self._subs),
|
| 570 |
+
minor_formatter=NullFormatter())
|
| 571 |
+
if self._base > 1:
|
| 572 |
+
axis.set_major_formatter(LogFormatterSciNotation(self._base))
|
| 573 |
+
else:
|
| 574 |
+
axis.set_major_formatter('{x:.3g}'),
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class LogitTransform(Transform):
|
| 578 |
+
input_dims = output_dims = 1
|
| 579 |
+
|
| 580 |
+
def __init__(self, nonpositive='mask'):
|
| 581 |
+
super().__init__()
|
| 582 |
+
_api.check_in_list(['mask', 'clip'], nonpositive=nonpositive)
|
| 583 |
+
self._nonpositive = nonpositive
|
| 584 |
+
self._clip = {"clip": True, "mask": False}[nonpositive]
|
| 585 |
+
|
| 586 |
+
def transform_non_affine(self, a):
|
| 587 |
+
"""logit transform (base 10), masked or clipped"""
|
| 588 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 589 |
+
out = np.log10(a / (1 - a))
|
| 590 |
+
if self._clip: # See LogTransform for choice of clip value.
|
| 591 |
+
out[a <= 0] = -1000
|
| 592 |
+
out[1 <= a] = 1000
|
| 593 |
+
return out
|
| 594 |
+
|
| 595 |
+
def inverted(self):
|
| 596 |
+
return LogisticTransform(self._nonpositive)
|
| 597 |
+
|
| 598 |
+
def __str__(self):
|
| 599 |
+
return "{}({!r})".format(type(self).__name__, self._nonpositive)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
class LogisticTransform(Transform):
|
| 603 |
+
input_dims = output_dims = 1
|
| 604 |
+
|
| 605 |
+
def __init__(self, nonpositive='mask'):
|
| 606 |
+
super().__init__()
|
| 607 |
+
self._nonpositive = nonpositive
|
| 608 |
+
|
| 609 |
+
def transform_non_affine(self, a):
|
| 610 |
+
"""logistic transform (base 10)"""
|
| 611 |
+
return 1.0 / (1 + 10**(-a))
|
| 612 |
+
|
| 613 |
+
def inverted(self):
|
| 614 |
+
return LogitTransform(self._nonpositive)
|
| 615 |
+
|
| 616 |
+
def __str__(self):
|
| 617 |
+
return "{}({!r})".format(type(self).__name__, self._nonpositive)
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
class LogitScale(ScaleBase):
|
| 621 |
+
"""
|
| 622 |
+
Logit scale for data between zero and one, both excluded.
|
| 623 |
+
|
| 624 |
+
This scale is similar to a log scale close to zero and to one, and almost
|
| 625 |
+
linear around 0.5. It maps the interval ]0, 1[ onto ]-infty, +infty[.
|
| 626 |
+
"""
|
| 627 |
+
name = 'logit'
|
| 628 |
+
|
| 629 |
+
def __init__(self, axis, nonpositive='mask', *,
|
| 630 |
+
one_half=r"\frac{1}{2}", use_overline=False):
|
| 631 |
+
r"""
|
| 632 |
+
Parameters
|
| 633 |
+
----------
|
| 634 |
+
axis : `~matplotlib.axis.Axis`
|
| 635 |
+
Currently unused.
|
| 636 |
+
nonpositive : {'mask', 'clip'}
|
| 637 |
+
Determines the behavior for values beyond the open interval ]0, 1[.
|
| 638 |
+
They can either be masked as invalid, or clipped to a number very
|
| 639 |
+
close to 0 or 1.
|
| 640 |
+
use_overline : bool, default: False
|
| 641 |
+
Indicate the usage of survival notation (\overline{x}) in place of
|
| 642 |
+
standard notation (1-x) for probability close to one.
|
| 643 |
+
one_half : str, default: r"\frac{1}{2}"
|
| 644 |
+
The string used for ticks formatter to represent 1/2.
|
| 645 |
+
"""
|
| 646 |
+
self._transform = LogitTransform(nonpositive)
|
| 647 |
+
self._use_overline = use_overline
|
| 648 |
+
self._one_half = one_half
|
| 649 |
+
|
| 650 |
+
def get_transform(self):
|
| 651 |
+
"""Return the `.LogitTransform` associated with this scale."""
|
| 652 |
+
return self._transform
|
| 653 |
+
|
| 654 |
+
def set_default_locators_and_formatters(self, axis):
|
| 655 |
+
# docstring inherited
|
| 656 |
+
# ..., 0.01, 0.1, 0.5, 0.9, 0.99, ...
|
| 657 |
+
axis.set_major_locator(LogitLocator())
|
| 658 |
+
axis.set_major_formatter(
|
| 659 |
+
LogitFormatter(
|
| 660 |
+
one_half=self._one_half,
|
| 661 |
+
use_overline=self._use_overline
|
| 662 |
+
)
|
| 663 |
+
)
|
| 664 |
+
axis.set_minor_locator(LogitLocator(minor=True))
|
| 665 |
+
axis.set_minor_formatter(
|
| 666 |
+
LogitFormatter(
|
| 667 |
+
minor=True,
|
| 668 |
+
one_half=self._one_half,
|
| 669 |
+
use_overline=self._use_overline
|
| 670 |
+
)
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
def limit_range_for_scale(self, vmin, vmax, minpos):
|
| 674 |
+
"""
|
| 675 |
+
Limit the domain to values between 0 and 1 (excluded).
|
| 676 |
+
"""
|
| 677 |
+
if not np.isfinite(minpos):
|
| 678 |
+
minpos = 1e-7 # Should rarely (if ever) have a visible effect.
|
| 679 |
+
return (minpos if vmin <= 0 else vmin,
|
| 680 |
+
1 - minpos if vmax >= 1 else vmax)
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
_scale_mapping = {
|
| 684 |
+
'linear': LinearScale,
|
| 685 |
+
'log': LogScale,
|
| 686 |
+
'symlog': SymmetricalLogScale,
|
| 687 |
+
'asinh': AsinhScale,
|
| 688 |
+
'logit': LogitScale,
|
| 689 |
+
'function': FuncScale,
|
| 690 |
+
'functionlog': FuncScaleLog,
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def get_scale_names():
|
| 695 |
+
"""Return the names of the available scales."""
|
| 696 |
+
return sorted(_scale_mapping)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def scale_factory(scale, axis, **kwargs):
|
| 700 |
+
"""
|
| 701 |
+
Return a scale class by name.
|
| 702 |
+
|
| 703 |
+
Parameters
|
| 704 |
+
----------
|
| 705 |
+
scale : {%(names)s}
|
| 706 |
+
axis : `~matplotlib.axis.Axis`
|
| 707 |
+
"""
|
| 708 |
+
scale_cls = _api.check_getitem(_scale_mapping, scale=scale)
|
| 709 |
+
return scale_cls(axis, **kwargs)
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
if scale_factory.__doc__:
|
| 713 |
+
scale_factory.__doc__ = scale_factory.__doc__ % {
|
| 714 |
+
"names": ", ".join(map(repr, get_scale_names()))}
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def register_scale(scale_class):
|
| 718 |
+
"""
|
| 719 |
+
Register a new kind of scale.
|
| 720 |
+
|
| 721 |
+
Parameters
|
| 722 |
+
----------
|
| 723 |
+
scale_class : subclass of `ScaleBase`
|
| 724 |
+
The scale to register.
|
| 725 |
+
"""
|
| 726 |
+
_scale_mapping[scale_class.name] = scale_class
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _get_scale_docs():
|
| 730 |
+
"""
|
| 731 |
+
Helper function for generating docstrings related to scales.
|
| 732 |
+
"""
|
| 733 |
+
docs = []
|
| 734 |
+
for name, scale_class in _scale_mapping.items():
|
| 735 |
+
docstring = inspect.getdoc(scale_class.__init__) or ""
|
| 736 |
+
docs.extend([
|
| 737 |
+
f" {name!r}",
|
| 738 |
+
"",
|
| 739 |
+
textwrap.indent(docstring, " " * 8),
|
| 740 |
+
""
|
| 741 |
+
])
|
| 742 |
+
return "\n".join(docs)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
_docstring.interpd.update(
|
| 746 |
+
scale_type='{%s}' % ', '.join([repr(x) for x in get_scale_names()]),
|
| 747 |
+
scale_docs=_get_scale_docs().rstrip(),
|
| 748 |
+
)
|
omnilmm/lib/python3.10/site-packages/matplotlib/stackplot.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Stacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflow
|
| 3 |
+
answer:
|
| 4 |
+
https://stackoverflow.com/q/2225995/
|
| 5 |
+
|
| 6 |
+
(https://stackoverflow.com/users/66549/doug)
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import itertools
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
from matplotlib import _api
|
| 14 |
+
|
| 15 |
+
__all__ = ['stackplot']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def stackplot(axes, x, *args,
|
| 19 |
+
labels=(), colors=None, baseline='zero',
|
| 20 |
+
**kwargs):
|
| 21 |
+
"""
|
| 22 |
+
Draw a stacked area plot.
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
----------
|
| 26 |
+
x : (N,) array-like
|
| 27 |
+
|
| 28 |
+
y : (M, N) array-like
|
| 29 |
+
The data is assumed to be unstacked. Each of the following
|
| 30 |
+
calls is legal::
|
| 31 |
+
|
| 32 |
+
stackplot(x, y) # where y has shape (M, N)
|
| 33 |
+
stackplot(x, y1, y2, y3) # where y1, y2, y3, y4 have length N
|
| 34 |
+
|
| 35 |
+
baseline : {'zero', 'sym', 'wiggle', 'weighted_wiggle'}
|
| 36 |
+
Method used to calculate the baseline:
|
| 37 |
+
|
| 38 |
+
- ``'zero'``: Constant zero baseline, i.e. a simple stacked plot.
|
| 39 |
+
- ``'sym'``: Symmetric around zero and is sometimes called
|
| 40 |
+
'ThemeRiver'.
|
| 41 |
+
- ``'wiggle'``: Minimizes the sum of the squared slopes.
|
| 42 |
+
- ``'weighted_wiggle'``: Does the same but weights to account for
|
| 43 |
+
size of each layer. It is also called 'Streamgraph'-layout. More
|
| 44 |
+
details can be found at http://leebyron.com/streamgraph/.
|
| 45 |
+
|
| 46 |
+
labels : list of str, optional
|
| 47 |
+
A sequence of labels to assign to each data series. If unspecified,
|
| 48 |
+
then no labels will be applied to artists.
|
| 49 |
+
|
| 50 |
+
colors : list of color, optional
|
| 51 |
+
A sequence of colors to be cycled through and used to color the stacked
|
| 52 |
+
areas. The sequence need not be exactly the same length as the number
|
| 53 |
+
of provided *y*, in which case the colors will repeat from the
|
| 54 |
+
beginning.
|
| 55 |
+
|
| 56 |
+
If not specified, the colors from the Axes property cycle will be used.
|
| 57 |
+
|
| 58 |
+
data : indexable object, optional
|
| 59 |
+
DATA_PARAMETER_PLACEHOLDER
|
| 60 |
+
|
| 61 |
+
**kwargs
|
| 62 |
+
All other keyword arguments are passed to `.Axes.fill_between`.
|
| 63 |
+
|
| 64 |
+
Returns
|
| 65 |
+
-------
|
| 66 |
+
list of `.PolyCollection`
|
| 67 |
+
A list of `.PolyCollection` instances, one for each element in the
|
| 68 |
+
stacked area plot.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
y = np.row_stack(args)
|
| 72 |
+
|
| 73 |
+
labels = iter(labels)
|
| 74 |
+
if colors is not None:
|
| 75 |
+
colors = itertools.cycle(colors)
|
| 76 |
+
else:
|
| 77 |
+
colors = (axes._get_lines.get_next_color() for _ in y)
|
| 78 |
+
|
| 79 |
+
# Assume data passed has not been 'stacked', so stack it here.
|
| 80 |
+
# We'll need a float buffer for the upcoming calculations.
|
| 81 |
+
stack = np.cumsum(y, axis=0, dtype=np.promote_types(y.dtype, np.float32))
|
| 82 |
+
|
| 83 |
+
_api.check_in_list(['zero', 'sym', 'wiggle', 'weighted_wiggle'],
|
| 84 |
+
baseline=baseline)
|
| 85 |
+
if baseline == 'zero':
|
| 86 |
+
first_line = 0.
|
| 87 |
+
|
| 88 |
+
elif baseline == 'sym':
|
| 89 |
+
first_line = -np.sum(y, 0) * 0.5
|
| 90 |
+
stack += first_line[None, :]
|
| 91 |
+
|
| 92 |
+
elif baseline == 'wiggle':
|
| 93 |
+
m = y.shape[0]
|
| 94 |
+
first_line = (y * (m - 0.5 - np.arange(m)[:, None])).sum(0)
|
| 95 |
+
first_line /= -m
|
| 96 |
+
stack += first_line
|
| 97 |
+
|
| 98 |
+
elif baseline == 'weighted_wiggle':
|
| 99 |
+
total = np.sum(y, 0)
|
| 100 |
+
# multiply by 1/total (or zero) to avoid infinities in the division:
|
| 101 |
+
inv_total = np.zeros_like(total)
|
| 102 |
+
mask = total > 0
|
| 103 |
+
inv_total[mask] = 1.0 / total[mask]
|
| 104 |
+
increase = np.hstack((y[:, 0:1], np.diff(y)))
|
| 105 |
+
below_size = total - stack
|
| 106 |
+
below_size += 0.5 * y
|
| 107 |
+
move_up = below_size * inv_total
|
| 108 |
+
move_up[:, 0] = 0.5
|
| 109 |
+
center = (move_up - 0.5) * increase
|
| 110 |
+
center = np.cumsum(center.sum(0))
|
| 111 |
+
first_line = center - 0.5 * total
|
| 112 |
+
stack += first_line
|
| 113 |
+
|
| 114 |
+
# Color between x = 0 and the first array.
|
| 115 |
+
coll = axes.fill_between(x, first_line, stack[0, :],
|
| 116 |
+
facecolor=next(colors), label=next(labels, None),
|
| 117 |
+
**kwargs)
|
| 118 |
+
coll.sticky_edges.y[:] = [0]
|
| 119 |
+
r = [coll]
|
| 120 |
+
|
| 121 |
+
# Color between array i-1 and array i
|
| 122 |
+
for i in range(len(y) - 1):
|
| 123 |
+
r.append(axes.fill_between(x, stack[i, :], stack[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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Classes for including text in a figure.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import functools
|
| 6 |
+
import logging
|
| 7 |
+
import math
|
| 8 |
+
from numbers import Real
|
| 9 |
+
import weakref
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
import matplotlib as mpl
|
| 14 |
+
from . import _api, artist, cbook, _docstring
|
| 15 |
+
from .artist import Artist
|
| 16 |
+
from .font_manager import FontProperties
|
| 17 |
+
from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle
|
| 18 |
+
from .textpath import TextPath, TextToPath # noqa # Logically located here
|
| 19 |
+
from .transforms import (
|
| 20 |
+
Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@_api.deprecated("3.6")
|
| 27 |
+
def get_rotation(rotation):
|
| 28 |
+
"""
|
| 29 |
+
Return *rotation* normalized to an angle between 0 and 360 degrees.
|
| 30 |
+
|
| 31 |
+
Parameters
|
| 32 |
+
----------
|
| 33 |
+
rotation : float or {None, 'horizontal', 'vertical'}
|
| 34 |
+
Rotation angle in degrees. *None* and 'horizontal' equal 0,
|
| 35 |
+
'vertical' equals 90.
|
| 36 |
+
|
| 37 |
+
Returns
|
| 38 |
+
-------
|
| 39 |
+
float
|
| 40 |
+
"""
|
| 41 |
+
try:
|
| 42 |
+
return float(rotation) % 360
|
| 43 |
+
except (ValueError, TypeError) as err:
|
| 44 |
+
if cbook._str_equal(rotation, 'horizontal') or rotation is None:
|
| 45 |
+
return 0.
|
| 46 |
+
elif cbook._str_equal(rotation, 'vertical'):
|
| 47 |
+
return 90.
|
| 48 |
+
else:
|
| 49 |
+
raise ValueError("rotation is {!r}; expected either 'horizontal', "
|
| 50 |
+
"'vertical', numeric value, or None"
|
| 51 |
+
.format(rotation)) from err
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _get_textbox(text, renderer):
|
| 55 |
+
"""
|
| 56 |
+
Calculate the bounding box of the text.
|
| 57 |
+
|
| 58 |
+
The bbox position takes text rotation into account, but the width and
|
| 59 |
+
height are those of the unrotated box (unlike `.Text.get_window_extent`).
|
| 60 |
+
"""
|
| 61 |
+
# TODO : This function may move into the Text class as a method. As a
|
| 62 |
+
# matter of fact, the information from the _get_textbox function
|
| 63 |
+
# should be available during the Text._get_layout() call, which is
|
| 64 |
+
# called within the _get_textbox. So, it would better to move this
|
| 65 |
+
# function as a method with some refactoring of _get_layout method.
|
| 66 |
+
|
| 67 |
+
projected_xs = []
|
| 68 |
+
projected_ys = []
|
| 69 |
+
|
| 70 |
+
theta = np.deg2rad(text.get_rotation())
|
| 71 |
+
tr = Affine2D().rotate(-theta)
|
| 72 |
+
|
| 73 |
+
_, parts, d = text._get_layout(renderer)
|
| 74 |
+
|
| 75 |
+
for t, wh, x, y in parts:
|
| 76 |
+
w, h = wh
|
| 77 |
+
|
| 78 |
+
xt1, yt1 = tr.transform((x, y))
|
| 79 |
+
yt1 -= d
|
| 80 |
+
xt2, yt2 = xt1 + w, yt1 + h
|
| 81 |
+
|
| 82 |
+
projected_xs.extend([xt1, xt2])
|
| 83 |
+
projected_ys.extend([yt1, yt2])
|
| 84 |
+
|
| 85 |
+
xt_box, yt_box = min(projected_xs), min(projected_ys)
|
| 86 |
+
w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box
|
| 87 |
+
|
| 88 |
+
x_box, y_box = Affine2D().rotate(theta).transform((xt_box, yt_box))
|
| 89 |
+
|
| 90 |
+
return x_box, y_box, w_box, h_box
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi):
|
| 94 |
+
"""Call ``renderer.get_text_width_height_descent``, caching the results."""
|
| 95 |
+
# Cached based on a copy of fontprop so that later in-place mutations of
|
| 96 |
+
# the passed-in argument do not mess up the cache.
|
| 97 |
+
return _get_text_metrics_with_cache_impl(
|
| 98 |
+
weakref.ref(renderer), text, fontprop.copy(), ismath, dpi)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@functools.lru_cache(4096)
|
| 102 |
+
def _get_text_metrics_with_cache_impl(
|
| 103 |
+
renderer_ref, text, fontprop, ismath, dpi):
|
| 104 |
+
# dpi is unused, but participates in cache invalidation (via the renderer).
|
| 105 |
+
return renderer_ref().get_text_width_height_descent(text, fontprop, ismath)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@_docstring.interpd
|
| 109 |
+
@_api.define_aliases({
|
| 110 |
+
"color": ["c"],
|
| 111 |
+
"fontfamily": ["family"],
|
| 112 |
+
"fontproperties": ["font", "font_properties"],
|
| 113 |
+
"horizontalalignment": ["ha"],
|
| 114 |
+
"multialignment": ["ma"],
|
| 115 |
+
"fontname": ["name"],
|
| 116 |
+
"fontsize": ["size"],
|
| 117 |
+
"fontstretch": ["stretch"],
|
| 118 |
+
"fontstyle": ["style"],
|
| 119 |
+
"fontvariant": ["variant"],
|
| 120 |
+
"verticalalignment": ["va"],
|
| 121 |
+
"fontweight": ["weight"],
|
| 122 |
+
})
|
| 123 |
+
class Text(Artist):
|
| 124 |
+
"""Handle storing and drawing of text in window or data coordinates."""
|
| 125 |
+
|
| 126 |
+
zorder = 3
|
| 127 |
+
_charsize_cache = dict()
|
| 128 |
+
|
| 129 |
+
def __repr__(self):
|
| 130 |
+
return "Text(%s, %s, %s)" % (self._x, self._y, repr(self._text))
|
| 131 |
+
|
| 132 |
+
@_api.make_keyword_only("3.6", name="color")
|
| 133 |
+
def __init__(self,
|
| 134 |
+
x=0, y=0, text='',
|
| 135 |
+
color=None, # defaults to rc params
|
| 136 |
+
verticalalignment='baseline',
|
| 137 |
+
horizontalalignment='left',
|
| 138 |
+
multialignment=None,
|
| 139 |
+
fontproperties=None, # defaults to FontProperties()
|
| 140 |
+
rotation=None,
|
| 141 |
+
linespacing=None,
|
| 142 |
+
rotation_mode=None,
|
| 143 |
+
usetex=None, # defaults to rcParams['text.usetex']
|
| 144 |
+
wrap=False,
|
| 145 |
+
transform_rotates_text=False,
|
| 146 |
+
*,
|
| 147 |
+
parse_math=None, # defaults to rcParams['text.parse_math']
|
| 148 |
+
**kwargs
|
| 149 |
+
):
|
| 150 |
+
"""
|
| 151 |
+
Create a `.Text` instance at *x*, *y* with string *text*.
|
| 152 |
+
|
| 153 |
+
The text is aligned relative to the anchor point (*x*, *y*) according
|
| 154 |
+
to ``horizontalalignment`` (default: 'left') and ``verticalalignment``
|
| 155 |
+
(default: 'bottom'). See also
|
| 156 |
+
:doc:`/gallery/text_labels_and_annotations/text_alignment`.
|
| 157 |
+
|
| 158 |
+
While Text accepts the 'label' keyword argument, by default it is not
|
| 159 |
+
added to the handles of a legend.
|
| 160 |
+
|
| 161 |
+
Valid keyword arguments are:
|
| 162 |
+
|
| 163 |
+
%(Text:kwdoc)s
|
| 164 |
+
"""
|
| 165 |
+
super().__init__()
|
| 166 |
+
self._x, self._y = x, y
|
| 167 |
+
self._text = ''
|
| 168 |
+
self._reset_visual_defaults(
|
| 169 |
+
text=text,
|
| 170 |
+
color=color,
|
| 171 |
+
fontproperties=fontproperties,
|
| 172 |
+
usetex=usetex,
|
| 173 |
+
parse_math=parse_math,
|
| 174 |
+
wrap=wrap,
|
| 175 |
+
verticalalignment=verticalalignment,
|
| 176 |
+
horizontalalignment=horizontalalignment,
|
| 177 |
+
multialignment=multialignment,
|
| 178 |
+
rotation=rotation,
|
| 179 |
+
transform_rotates_text=transform_rotates_text,
|
| 180 |
+
linespacing=linespacing,
|
| 181 |
+
rotation_mode=rotation_mode,
|
| 182 |
+
)
|
| 183 |
+
self.update(kwargs)
|
| 184 |
+
|
| 185 |
+
def _reset_visual_defaults(
|
| 186 |
+
self,
|
| 187 |
+
text='',
|
| 188 |
+
color=None,
|
| 189 |
+
fontproperties=None,
|
| 190 |
+
usetex=None,
|
| 191 |
+
parse_math=None,
|
| 192 |
+
wrap=False,
|
| 193 |
+
verticalalignment='baseline',
|
| 194 |
+
horizontalalignment='left',
|
| 195 |
+
multialignment=None,
|
| 196 |
+
rotation=None,
|
| 197 |
+
transform_rotates_text=False,
|
| 198 |
+
linespacing=None,
|
| 199 |
+
rotation_mode=None,
|
| 200 |
+
):
|
| 201 |
+
self.set_text(text)
|
| 202 |
+
self.set_color(
|
| 203 |
+
color if color is not None else mpl.rcParams["text.color"])
|
| 204 |
+
self.set_fontproperties(fontproperties)
|
| 205 |
+
self.set_usetex(usetex)
|
| 206 |
+
self.set_parse_math(parse_math if parse_math is not None else
|
| 207 |
+
mpl.rcParams['text.parse_math'])
|
| 208 |
+
self.set_wrap(wrap)
|
| 209 |
+
self.set_verticalalignment(verticalalignment)
|
| 210 |
+
self.set_horizontalalignment(horizontalalignment)
|
| 211 |
+
self._multialignment = multialignment
|
| 212 |
+
self.set_rotation(rotation)
|
| 213 |
+
self._transform_rotates_text = transform_rotates_text
|
| 214 |
+
self._bbox_patch = None # a FancyBboxPatch instance
|
| 215 |
+
self._renderer = None
|
| 216 |
+
if linespacing is None:
|
| 217 |
+
linespacing = 1.2 # Maybe use rcParam later.
|
| 218 |
+
self.set_linespacing(linespacing)
|
| 219 |
+
self.set_rotation_mode(rotation_mode)
|
| 220 |
+
|
| 221 |
+
def update(self, kwargs):
|
| 222 |
+
# docstring inherited
|
| 223 |
+
kwargs = cbook.normalize_kwargs(kwargs, Text)
|
| 224 |
+
sentinel = object() # bbox can be None, so use another sentinel.
|
| 225 |
+
# Update fontproperties first, as it has lowest priority.
|
| 226 |
+
fontproperties = kwargs.pop("fontproperties", sentinel)
|
| 227 |
+
if fontproperties is not sentinel:
|
| 228 |
+
self.set_fontproperties(fontproperties)
|
| 229 |
+
# Update bbox last, as it depends on font properties.
|
| 230 |
+
bbox = kwargs.pop("bbox", sentinel)
|
| 231 |
+
super().update(kwargs)
|
| 232 |
+
if bbox is not sentinel:
|
| 233 |
+
self.set_bbox(bbox)
|
| 234 |
+
|
| 235 |
+
def __getstate__(self):
|
| 236 |
+
d = super().__getstate__()
|
| 237 |
+
# remove the cached _renderer (if it exists)
|
| 238 |
+
d['_renderer'] = None
|
| 239 |
+
return d
|
| 240 |
+
|
| 241 |
+
def contains(self, mouseevent):
|
| 242 |
+
"""
|
| 243 |
+
Return whether the mouse event occurred inside the axis-aligned
|
| 244 |
+
bounding-box of the text.
|
| 245 |
+
"""
|
| 246 |
+
inside, info = self._default_contains(mouseevent)
|
| 247 |
+
if inside is not None:
|
| 248 |
+
return inside, info
|
| 249 |
+
|
| 250 |
+
if not self.get_visible() or self._renderer is None:
|
| 251 |
+
return False, {}
|
| 252 |
+
|
| 253 |
+
# Explicitly use Text.get_window_extent(self) and not
|
| 254 |
+
# self.get_window_extent() so that Annotation.contains does not
|
| 255 |
+
# accidentally cover the entire annotation bounding box.
|
| 256 |
+
bbox = Text.get_window_extent(self)
|
| 257 |
+
inside = (bbox.x0 <= mouseevent.x <= bbox.x1
|
| 258 |
+
and bbox.y0 <= mouseevent.y <= bbox.y1)
|
| 259 |
+
|
| 260 |
+
cattr = {}
|
| 261 |
+
# if the text has a surrounding patch, also check containment for it,
|
| 262 |
+
# and merge the results with the results for the text.
|
| 263 |
+
if self._bbox_patch:
|
| 264 |
+
patch_inside, patch_cattr = self._bbox_patch.contains(mouseevent)
|
| 265 |
+
inside = inside or patch_inside
|
| 266 |
+
cattr["bbox_patch"] = patch_cattr
|
| 267 |
+
|
| 268 |
+
return inside, cattr
|
| 269 |
+
|
| 270 |
+
def _get_xy_display(self):
|
| 271 |
+
"""
|
| 272 |
+
Get the (possibly unit converted) transformed x, y in display coords.
|
| 273 |
+
"""
|
| 274 |
+
x, y = self.get_unitless_position()
|
| 275 |
+
return self.get_transform().transform((x, y))
|
| 276 |
+
|
| 277 |
+
def _get_multialignment(self):
|
| 278 |
+
if self._multialignment is not None:
|
| 279 |
+
return self._multialignment
|
| 280 |
+
else:
|
| 281 |
+
return self._horizontalalignment
|
| 282 |
+
|
| 283 |
+
def _char_index_at(self, x):
|
| 284 |
+
"""
|
| 285 |
+
Calculate the index closest to the coordinate x in display space.
|
| 286 |
+
|
| 287 |
+
The position of text[index] is assumed to be the sum of the widths
|
| 288 |
+
of all preceding characters text[:index].
|
| 289 |
+
|
| 290 |
+
This works only on single line texts.
|
| 291 |
+
"""
|
| 292 |
+
if not self._text:
|
| 293 |
+
return 0
|
| 294 |
+
|
| 295 |
+
text = self._text
|
| 296 |
+
|
| 297 |
+
fontproperties = str(self._fontproperties)
|
| 298 |
+
if fontproperties not in Text._charsize_cache:
|
| 299 |
+
Text._charsize_cache[fontproperties] = dict()
|
| 300 |
+
|
| 301 |
+
charsize_cache = Text._charsize_cache[fontproperties]
|
| 302 |
+
for char in set(text):
|
| 303 |
+
if char not in charsize_cache:
|
| 304 |
+
self.set_text(char)
|
| 305 |
+
bb = self.get_window_extent()
|
| 306 |
+
charsize_cache[char] = bb.x1 - bb.x0
|
| 307 |
+
|
| 308 |
+
self.set_text(text)
|
| 309 |
+
bb = self.get_window_extent()
|
| 310 |
+
|
| 311 |
+
size_accum = np.cumsum([0] + [charsize_cache[x] for x in text])
|
| 312 |
+
std_x = x - bb.x0
|
| 313 |
+
return (np.abs(size_accum - std_x)).argmin()
|
| 314 |
+
|
| 315 |
+
def get_rotation(self):
|
| 316 |
+
"""Return the text angle in degrees between 0 and 360."""
|
| 317 |
+
if self.get_transform_rotates_text():
|
| 318 |
+
return self.get_transform().transform_angles(
|
| 319 |
+
[self._rotation], [self.get_unitless_position()]).item(0)
|
| 320 |
+
else:
|
| 321 |
+
return self._rotation
|
| 322 |
+
|
| 323 |
+
def get_transform_rotates_text(self):
|
| 324 |
+
"""
|
| 325 |
+
Return whether rotations of the transform affect the text direction.
|
| 326 |
+
"""
|
| 327 |
+
return self._transform_rotates_text
|
| 328 |
+
|
| 329 |
+
def set_rotation_mode(self, m):
|
| 330 |
+
"""
|
| 331 |
+
Set text rotation mode.
|
| 332 |
+
|
| 333 |
+
Parameters
|
| 334 |
+
----------
|
| 335 |
+
m : {None, 'default', 'anchor'}
|
| 336 |
+
If ``None`` or ``"default"``, the text will be first rotated, then
|
| 337 |
+
aligned according to their horizontal and vertical alignments. If
|
| 338 |
+
``"anchor"``, then alignment occurs before rotation.
|
| 339 |
+
"""
|
| 340 |
+
_api.check_in_list(["anchor", "default", None], rotation_mode=m)
|
| 341 |
+
self._rotation_mode = m
|
| 342 |
+
self.stale = True
|
| 343 |
+
|
| 344 |
+
def get_rotation_mode(self):
|
| 345 |
+
"""Return the text rotation mode."""
|
| 346 |
+
return self._rotation_mode
|
| 347 |
+
|
| 348 |
+
def update_from(self, other):
|
| 349 |
+
# docstring inherited
|
| 350 |
+
super().update_from(other)
|
| 351 |
+
self._color = other._color
|
| 352 |
+
self._multialignment = other._multialignment
|
| 353 |
+
self._verticalalignment = other._verticalalignment
|
| 354 |
+
self._horizontalalignment = other._horizontalalignment
|
| 355 |
+
self._fontproperties = other._fontproperties.copy()
|
| 356 |
+
self._usetex = other._usetex
|
| 357 |
+
self._rotation = other._rotation
|
| 358 |
+
self._transform_rotates_text = other._transform_rotates_text
|
| 359 |
+
self._picker = other._picker
|
| 360 |
+
self._linespacing = other._linespacing
|
| 361 |
+
self.stale = True
|
| 362 |
+
|
| 363 |
+
def _get_layout(self, renderer):
|
| 364 |
+
"""
|
| 365 |
+
Return the extent (bbox) of the text together with
|
| 366 |
+
multiple-alignment information. Note that it returns an extent
|
| 367 |
+
of a rotated text when necessary.
|
| 368 |
+
"""
|
| 369 |
+
thisx, thisy = 0.0, 0.0
|
| 370 |
+
lines = self._get_wrapped_text().split("\n") # Ensures lines is not empty.
|
| 371 |
+
|
| 372 |
+
ws = []
|
| 373 |
+
hs = []
|
| 374 |
+
xs = []
|
| 375 |
+
ys = []
|
| 376 |
+
|
| 377 |
+
# Full vertical extent of font, including ascenders and descenders:
|
| 378 |
+
_, lp_h, lp_d = _get_text_metrics_with_cache(
|
| 379 |
+
renderer, "lp", self._fontproperties,
|
| 380 |
+
ismath="TeX" if self.get_usetex() else False, dpi=self.figure.dpi)
|
| 381 |
+
min_dy = (lp_h - lp_d) * self._linespacing
|
| 382 |
+
|
| 383 |
+
for i, line in enumerate(lines):
|
| 384 |
+
clean_line, ismath = self._preprocess_math(line)
|
| 385 |
+
if clean_line:
|
| 386 |
+
w, h, d = _get_text_metrics_with_cache(
|
| 387 |
+
renderer, clean_line, self._fontproperties,
|
| 388 |
+
ismath=ismath, dpi=self.figure.dpi)
|
| 389 |
+
else:
|
| 390 |
+
w = h = d = 0
|
| 391 |
+
|
| 392 |
+
# For multiline text, increase the line spacing when the text
|
| 393 |
+
# net-height (excluding baseline) is larger than that of a "l"
|
| 394 |
+
# (e.g., use of superscripts), which seems what TeX does.
|
| 395 |
+
h = max(h, lp_h)
|
| 396 |
+
d = max(d, lp_d)
|
| 397 |
+
|
| 398 |
+
ws.append(w)
|
| 399 |
+
hs.append(h)
|
| 400 |
+
|
| 401 |
+
# Metrics of the last line that are needed later:
|
| 402 |
+
baseline = (h - d) - thisy
|
| 403 |
+
|
| 404 |
+
if i == 0:
|
| 405 |
+
# position at baseline
|
| 406 |
+
thisy = -(h - d)
|
| 407 |
+
else:
|
| 408 |
+
# put baseline a good distance from bottom of previous line
|
| 409 |
+
thisy -= max(min_dy, (h - d) * self._linespacing)
|
| 410 |
+
|
| 411 |
+
xs.append(thisx) # == 0.
|
| 412 |
+
ys.append(thisy)
|
| 413 |
+
|
| 414 |
+
thisy -= d
|
| 415 |
+
|
| 416 |
+
# Metrics of the last line that are needed later:
|
| 417 |
+
descent = d
|
| 418 |
+
|
| 419 |
+
# Bounding box definition:
|
| 420 |
+
width = max(ws)
|
| 421 |
+
xmin = 0
|
| 422 |
+
xmax = width
|
| 423 |
+
ymax = 0
|
| 424 |
+
ymin = ys[-1] - descent # baseline of last line minus its descent
|
| 425 |
+
|
| 426 |
+
# get the rotation matrix
|
| 427 |
+
M = Affine2D().rotate_deg(self.get_rotation())
|
| 428 |
+
|
| 429 |
+
# now offset the individual text lines within the box
|
| 430 |
+
malign = self._get_multialignment()
|
| 431 |
+
if malign == 'left':
|
| 432 |
+
offset_layout = [(x, y) for x, y in zip(xs, ys)]
|
| 433 |
+
elif malign == 'center':
|
| 434 |
+
offset_layout = [(x + width / 2 - w / 2, y)
|
| 435 |
+
for x, y, w in zip(xs, ys, ws)]
|
| 436 |
+
elif malign == 'right':
|
| 437 |
+
offset_layout = [(x + width - w, y)
|
| 438 |
+
for x, y, w in zip(xs, ys, ws)]
|
| 439 |
+
|
| 440 |
+
# the corners of the unrotated bounding box
|
| 441 |
+
corners_horiz = np.array(
|
| 442 |
+
[(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)])
|
| 443 |
+
|
| 444 |
+
# now rotate the bbox
|
| 445 |
+
corners_rotated = M.transform(corners_horiz)
|
| 446 |
+
# compute the bounds of the rotated box
|
| 447 |
+
xmin = corners_rotated[:, 0].min()
|
| 448 |
+
xmax = corners_rotated[:, 0].max()
|
| 449 |
+
ymin = corners_rotated[:, 1].min()
|
| 450 |
+
ymax = corners_rotated[:, 1].max()
|
| 451 |
+
width = xmax - xmin
|
| 452 |
+
height = ymax - ymin
|
| 453 |
+
|
| 454 |
+
# Now move the box to the target position offset the display
|
| 455 |
+
# bbox by alignment
|
| 456 |
+
halign = self._horizontalalignment
|
| 457 |
+
valign = self._verticalalignment
|
| 458 |
+
|
| 459 |
+
rotation_mode = self.get_rotation_mode()
|
| 460 |
+
if rotation_mode != "anchor":
|
| 461 |
+
# compute the text location in display coords and the offsets
|
| 462 |
+
# necessary to align the bbox with that location
|
| 463 |
+
if halign == 'center':
|
| 464 |
+
offsetx = (xmin + xmax) / 2
|
| 465 |
+
elif halign == 'right':
|
| 466 |
+
offsetx = xmax
|
| 467 |
+
else:
|
| 468 |
+
offsetx = xmin
|
| 469 |
+
|
| 470 |
+
if valign == 'center':
|
| 471 |
+
offsety = (ymin + ymax) / 2
|
| 472 |
+
elif valign == 'top':
|
| 473 |
+
offsety = ymax
|
| 474 |
+
elif valign == 'baseline':
|
| 475 |
+
offsety = ymin + descent
|
| 476 |
+
elif valign == 'center_baseline':
|
| 477 |
+
offsety = ymin + height - baseline / 2.0
|
| 478 |
+
else:
|
| 479 |
+
offsety = ymin
|
| 480 |
+
else:
|
| 481 |
+
xmin1, ymin1 = corners_horiz[0]
|
| 482 |
+
xmax1, ymax1 = corners_horiz[2]
|
| 483 |
+
|
| 484 |
+
if halign == 'center':
|
| 485 |
+
offsetx = (xmin1 + xmax1) / 2.0
|
| 486 |
+
elif halign == 'right':
|
| 487 |
+
offsetx = xmax1
|
| 488 |
+
else:
|
| 489 |
+
offsetx = xmin1
|
| 490 |
+
|
| 491 |
+
if valign == 'center':
|
| 492 |
+
offsety = (ymin1 + ymax1) / 2.0
|
| 493 |
+
elif valign == 'top':
|
| 494 |
+
offsety = ymax1
|
| 495 |
+
elif valign == 'baseline':
|
| 496 |
+
offsety = ymax1 - baseline
|
| 497 |
+
elif valign == 'center_baseline':
|
| 498 |
+
offsety = ymax1 - baseline / 2.0
|
| 499 |
+
else:
|
| 500 |
+
offsety = ymin1
|
| 501 |
+
|
| 502 |
+
offsetx, offsety = M.transform((offsetx, offsety))
|
| 503 |
+
|
| 504 |
+
xmin -= offsetx
|
| 505 |
+
ymin -= offsety
|
| 506 |
+
|
| 507 |
+
bbox = Bbox.from_bounds(xmin, ymin, width, height)
|
| 508 |
+
|
| 509 |
+
# now rotate the positions around the first (x, y) position
|
| 510 |
+
xys = M.transform(offset_layout) - (offsetx, offsety)
|
| 511 |
+
|
| 512 |
+
return bbox, list(zip(lines, zip(ws, hs), *xys.T)), descent
|
| 513 |
+
|
| 514 |
+
def set_bbox(self, rectprops):
|
| 515 |
+
"""
|
| 516 |
+
Draw a bounding box around self.
|
| 517 |
+
|
| 518 |
+
Parameters
|
| 519 |
+
----------
|
| 520 |
+
rectprops : dict with properties for `.patches.FancyBboxPatch`
|
| 521 |
+
The default boxstyle is 'square'. The mutation
|
| 522 |
+
scale of the `.patches.FancyBboxPatch` is set to the fontsize.
|
| 523 |
+
|
| 524 |
+
Examples
|
| 525 |
+
--------
|
| 526 |
+
::
|
| 527 |
+
|
| 528 |
+
t.set_bbox(dict(facecolor='red', alpha=0.5))
|
| 529 |
+
"""
|
| 530 |
+
|
| 531 |
+
if rectprops is not None:
|
| 532 |
+
props = rectprops.copy()
|
| 533 |
+
boxstyle = props.pop("boxstyle", None)
|
| 534 |
+
pad = props.pop("pad", None)
|
| 535 |
+
if boxstyle is None:
|
| 536 |
+
boxstyle = "square"
|
| 537 |
+
if pad is None:
|
| 538 |
+
pad = 4 # points
|
| 539 |
+
pad /= self.get_size() # to fraction of font size
|
| 540 |
+
else:
|
| 541 |
+
if pad is None:
|
| 542 |
+
pad = 0.3
|
| 543 |
+
# boxstyle could be a callable or a string
|
| 544 |
+
if isinstance(boxstyle, str) and "pad" not in boxstyle:
|
| 545 |
+
boxstyle += ",pad=%0.2f" % pad
|
| 546 |
+
self._bbox_patch = FancyBboxPatch(
|
| 547 |
+
(0, 0), 1, 1,
|
| 548 |
+
boxstyle=boxstyle, transform=IdentityTransform(), **props)
|
| 549 |
+
else:
|
| 550 |
+
self._bbox_patch = None
|
| 551 |
+
|
| 552 |
+
self._update_clip_properties()
|
| 553 |
+
|
| 554 |
+
def get_bbox_patch(self):
|
| 555 |
+
"""
|
| 556 |
+
Return the bbox Patch, or None if the `.patches.FancyBboxPatch`
|
| 557 |
+
is not made.
|
| 558 |
+
"""
|
| 559 |
+
return self._bbox_patch
|
| 560 |
+
|
| 561 |
+
def update_bbox_position_size(self, renderer):
|
| 562 |
+
"""
|
| 563 |
+
Update the location and the size of the bbox.
|
| 564 |
+
|
| 565 |
+
This method should be used when the position and size of the bbox needs
|
| 566 |
+
to be updated before actually drawing the bbox.
|
| 567 |
+
"""
|
| 568 |
+
if self._bbox_patch:
|
| 569 |
+
# don't use self.get_unitless_position here, which refers to text
|
| 570 |
+
# position in Text:
|
| 571 |
+
posx = float(self.convert_xunits(self._x))
|
| 572 |
+
posy = float(self.convert_yunits(self._y))
|
| 573 |
+
posx, posy = self.get_transform().transform((posx, posy))
|
| 574 |
+
|
| 575 |
+
x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
|
| 576 |
+
self._bbox_patch.set_bounds(0., 0., w_box, h_box)
|
| 577 |
+
self._bbox_patch.set_transform(
|
| 578 |
+
Affine2D()
|
| 579 |
+
.rotate_deg(self.get_rotation())
|
| 580 |
+
.translate(posx + x_box, posy + y_box))
|
| 581 |
+
fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
|
| 582 |
+
self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
|
| 583 |
+
|
| 584 |
+
def _update_clip_properties(self):
|
| 585 |
+
clipprops = dict(clip_box=self.clipbox,
|
| 586 |
+
clip_path=self._clippath,
|
| 587 |
+
clip_on=self._clipon)
|
| 588 |
+
if self._bbox_patch:
|
| 589 |
+
self._bbox_patch.update(clipprops)
|
| 590 |
+
|
| 591 |
+
def set_clip_box(self, clipbox):
|
| 592 |
+
# docstring inherited.
|
| 593 |
+
super().set_clip_box(clipbox)
|
| 594 |
+
self._update_clip_properties()
|
| 595 |
+
|
| 596 |
+
def set_clip_path(self, path, transform=None):
|
| 597 |
+
# docstring inherited.
|
| 598 |
+
super().set_clip_path(path, transform)
|
| 599 |
+
self._update_clip_properties()
|
| 600 |
+
|
| 601 |
+
def set_clip_on(self, b):
|
| 602 |
+
# docstring inherited.
|
| 603 |
+
super().set_clip_on(b)
|
| 604 |
+
self._update_clip_properties()
|
| 605 |
+
|
| 606 |
+
def get_wrap(self):
|
| 607 |
+
"""Return whether the text can be wrapped."""
|
| 608 |
+
return self._wrap
|
| 609 |
+
|
| 610 |
+
def set_wrap(self, wrap):
|
| 611 |
+
"""
|
| 612 |
+
Set whether the text can be wrapped.
|
| 613 |
+
|
| 614 |
+
Parameters
|
| 615 |
+
----------
|
| 616 |
+
wrap : bool
|
| 617 |
+
|
| 618 |
+
Notes
|
| 619 |
+
-----
|
| 620 |
+
Wrapping does not work together with
|
| 621 |
+
``savefig(..., bbox_inches='tight')`` (which is also used internally
|
| 622 |
+
by ``%matplotlib inline`` in IPython/Jupyter). The 'tight' setting
|
| 623 |
+
rescales the canvas to accommodate all content and happens before
|
| 624 |
+
wrapping.
|
| 625 |
+
"""
|
| 626 |
+
self._wrap = wrap
|
| 627 |
+
|
| 628 |
+
def _get_wrap_line_width(self):
|
| 629 |
+
"""
|
| 630 |
+
Return the maximum line width for wrapping text based on the current
|
| 631 |
+
orientation.
|
| 632 |
+
"""
|
| 633 |
+
x0, y0 = self.get_transform().transform(self.get_position())
|
| 634 |
+
figure_box = self.get_figure().get_window_extent()
|
| 635 |
+
|
| 636 |
+
# Calculate available width based on text alignment
|
| 637 |
+
alignment = self.get_horizontalalignment()
|
| 638 |
+
self.set_rotation_mode('anchor')
|
| 639 |
+
rotation = self.get_rotation()
|
| 640 |
+
|
| 641 |
+
left = self._get_dist_to_box(rotation, x0, y0, figure_box)
|
| 642 |
+
right = self._get_dist_to_box(
|
| 643 |
+
(180 + rotation) % 360, x0, y0, figure_box)
|
| 644 |
+
|
| 645 |
+
if alignment == 'left':
|
| 646 |
+
line_width = left
|
| 647 |
+
elif alignment == 'right':
|
| 648 |
+
line_width = right
|
| 649 |
+
else:
|
| 650 |
+
line_width = 2 * min(left, right)
|
| 651 |
+
|
| 652 |
+
return line_width
|
| 653 |
+
|
| 654 |
+
def _get_dist_to_box(self, rotation, x0, y0, figure_box):
|
| 655 |
+
"""
|
| 656 |
+
Return the distance from the given points to the boundaries of a
|
| 657 |
+
rotated box, in pixels.
|
| 658 |
+
"""
|
| 659 |
+
if rotation > 270:
|
| 660 |
+
quad = rotation - 270
|
| 661 |
+
h1 = y0 / math.cos(math.radians(quad))
|
| 662 |
+
h2 = (figure_box.x1 - x0) / math.cos(math.radians(90 - quad))
|
| 663 |
+
elif rotation > 180:
|
| 664 |
+
quad = rotation - 180
|
| 665 |
+
h1 = x0 / math.cos(math.radians(quad))
|
| 666 |
+
h2 = y0 / math.cos(math.radians(90 - quad))
|
| 667 |
+
elif rotation > 90:
|
| 668 |
+
quad = rotation - 90
|
| 669 |
+
h1 = (figure_box.y1 - y0) / math.cos(math.radians(quad))
|
| 670 |
+
h2 = x0 / math.cos(math.radians(90 - quad))
|
| 671 |
+
else:
|
| 672 |
+
h1 = (figure_box.x1 - x0) / math.cos(math.radians(rotation))
|
| 673 |
+
h2 = (figure_box.y1 - y0) / math.cos(math.radians(90 - rotation))
|
| 674 |
+
|
| 675 |
+
return min(h1, h2)
|
| 676 |
+
|
| 677 |
+
def _get_rendered_text_width(self, text):
|
| 678 |
+
"""
|
| 679 |
+
Return the width of a given text string, in pixels.
|
| 680 |
+
"""
|
| 681 |
+
w, h, d = self._renderer.get_text_width_height_descent(
|
| 682 |
+
text,
|
| 683 |
+
self.get_fontproperties(),
|
| 684 |
+
False)
|
| 685 |
+
return math.ceil(w)
|
| 686 |
+
|
| 687 |
+
def _get_wrapped_text(self):
|
| 688 |
+
"""
|
| 689 |
+
Return a copy of the text string with new lines added so that the text
|
| 690 |
+
is wrapped relative to the parent figure (if `get_wrap` is True).
|
| 691 |
+
"""
|
| 692 |
+
if not self.get_wrap():
|
| 693 |
+
return self.get_text()
|
| 694 |
+
|
| 695 |
+
# Not fit to handle breaking up latex syntax correctly, so
|
| 696 |
+
# ignore latex for now.
|
| 697 |
+
if self.get_usetex():
|
| 698 |
+
return self.get_text()
|
| 699 |
+
|
| 700 |
+
# Build the line incrementally, for a more accurate measure of length
|
| 701 |
+
line_width = self._get_wrap_line_width()
|
| 702 |
+
wrapped_lines = []
|
| 703 |
+
|
| 704 |
+
# New lines in the user's text force a split
|
| 705 |
+
unwrapped_lines = self.get_text().split('\n')
|
| 706 |
+
|
| 707 |
+
# Now wrap each individual unwrapped line
|
| 708 |
+
for unwrapped_line in unwrapped_lines:
|
| 709 |
+
|
| 710 |
+
sub_words = unwrapped_line.split(' ')
|
| 711 |
+
# Remove items from sub_words as we go, so stop when empty
|
| 712 |
+
while len(sub_words) > 0:
|
| 713 |
+
if len(sub_words) == 1:
|
| 714 |
+
# Only one word, so just add it to the end
|
| 715 |
+
wrapped_lines.append(sub_words.pop(0))
|
| 716 |
+
continue
|
| 717 |
+
|
| 718 |
+
for i in range(2, len(sub_words) + 1):
|
| 719 |
+
# Get width of all words up to and including here
|
| 720 |
+
line = ' '.join(sub_words[:i])
|
| 721 |
+
current_width = self._get_rendered_text_width(line)
|
| 722 |
+
|
| 723 |
+
# If all these words are too wide, append all not including
|
| 724 |
+
# last word
|
| 725 |
+
if current_width > line_width:
|
| 726 |
+
wrapped_lines.append(' '.join(sub_words[:i - 1]))
|
| 727 |
+
sub_words = sub_words[i - 1:]
|
| 728 |
+
break
|
| 729 |
+
|
| 730 |
+
# Otherwise if all words fit in the width, append them all
|
| 731 |
+
elif i == len(sub_words):
|
| 732 |
+
wrapped_lines.append(' '.join(sub_words[:i]))
|
| 733 |
+
sub_words = []
|
| 734 |
+
break
|
| 735 |
+
|
| 736 |
+
return '\n'.join(wrapped_lines)
|
| 737 |
+
|
| 738 |
+
@artist.allow_rasterization
|
| 739 |
+
def draw(self, renderer):
|
| 740 |
+
# docstring inherited
|
| 741 |
+
|
| 742 |
+
if renderer is not None:
|
| 743 |
+
self._renderer = renderer
|
| 744 |
+
if not self.get_visible():
|
| 745 |
+
return
|
| 746 |
+
if self.get_text() == '':
|
| 747 |
+
return
|
| 748 |
+
|
| 749 |
+
renderer.open_group('text', self.get_gid())
|
| 750 |
+
|
| 751 |
+
with self._cm_set(text=self._get_wrapped_text()):
|
| 752 |
+
bbox, info, descent = self._get_layout(renderer)
|
| 753 |
+
trans = self.get_transform()
|
| 754 |
+
|
| 755 |
+
# don't use self.get_position here, which refers to text
|
| 756 |
+
# position in Text:
|
| 757 |
+
posx = float(self.convert_xunits(self._x))
|
| 758 |
+
posy = float(self.convert_yunits(self._y))
|
| 759 |
+
posx, posy = trans.transform((posx, posy))
|
| 760 |
+
if not np.isfinite(posx) or not np.isfinite(posy):
|
| 761 |
+
_log.warning("posx and posy should be finite values")
|
| 762 |
+
return
|
| 763 |
+
canvasw, canvash = renderer.get_canvas_width_height()
|
| 764 |
+
|
| 765 |
+
# Update the location and size of the bbox
|
| 766 |
+
# (`.patches.FancyBboxPatch`), and draw it.
|
| 767 |
+
if self._bbox_patch:
|
| 768 |
+
self.update_bbox_position_size(renderer)
|
| 769 |
+
self._bbox_patch.draw(renderer)
|
| 770 |
+
|
| 771 |
+
gc = renderer.new_gc()
|
| 772 |
+
gc.set_foreground(self.get_color())
|
| 773 |
+
gc.set_alpha(self.get_alpha())
|
| 774 |
+
gc.set_url(self._url)
|
| 775 |
+
self._set_gc_clip(gc)
|
| 776 |
+
|
| 777 |
+
angle = self.get_rotation()
|
| 778 |
+
|
| 779 |
+
for line, wh, x, y in info:
|
| 780 |
+
|
| 781 |
+
mtext = self if len(info) == 1 else None
|
| 782 |
+
x = x + posx
|
| 783 |
+
y = y + posy
|
| 784 |
+
if renderer.flipy():
|
| 785 |
+
y = canvash - y
|
| 786 |
+
clean_line, ismath = self._preprocess_math(line)
|
| 787 |
+
|
| 788 |
+
if self.get_path_effects():
|
| 789 |
+
from matplotlib.patheffects import PathEffectRenderer
|
| 790 |
+
textrenderer = PathEffectRenderer(
|
| 791 |
+
self.get_path_effects(), renderer)
|
| 792 |
+
else:
|
| 793 |
+
textrenderer = renderer
|
| 794 |
+
|
| 795 |
+
if self.get_usetex():
|
| 796 |
+
textrenderer.draw_tex(gc, x, y, clean_line,
|
| 797 |
+
self._fontproperties, angle,
|
| 798 |
+
mtext=mtext)
|
| 799 |
+
else:
|
| 800 |
+
textrenderer.draw_text(gc, x, y, clean_line,
|
| 801 |
+
self._fontproperties, angle,
|
| 802 |
+
ismath=ismath, mtext=mtext)
|
| 803 |
+
|
| 804 |
+
gc.restore()
|
| 805 |
+
renderer.close_group('text')
|
| 806 |
+
self.stale = False
|
| 807 |
+
|
| 808 |
+
def get_color(self):
|
| 809 |
+
"""Return the color of the text."""
|
| 810 |
+
return self._color
|
| 811 |
+
|
| 812 |
+
def get_fontproperties(self):
|
| 813 |
+
"""Return the `.font_manager.FontProperties`."""
|
| 814 |
+
return self._fontproperties
|
| 815 |
+
|
| 816 |
+
def get_fontfamily(self):
|
| 817 |
+
"""
|
| 818 |
+
Return the list of font families used for font lookup.
|
| 819 |
+
|
| 820 |
+
See Also
|
| 821 |
+
--------
|
| 822 |
+
.font_manager.FontProperties.get_family
|
| 823 |
+
"""
|
| 824 |
+
return self._fontproperties.get_family()
|
| 825 |
+
|
| 826 |
+
def get_fontname(self):
|
| 827 |
+
"""
|
| 828 |
+
Return the font name as a string.
|
| 829 |
+
|
| 830 |
+
See Also
|
| 831 |
+
--------
|
| 832 |
+
.font_manager.FontProperties.get_name
|
| 833 |
+
"""
|
| 834 |
+
return self._fontproperties.get_name()
|
| 835 |
+
|
| 836 |
+
def get_fontstyle(self):
|
| 837 |
+
"""
|
| 838 |
+
Return the font style as a string.
|
| 839 |
+
|
| 840 |
+
See Also
|
| 841 |
+
--------
|
| 842 |
+
.font_manager.FontProperties.get_style
|
| 843 |
+
"""
|
| 844 |
+
return self._fontproperties.get_style()
|
| 845 |
+
|
| 846 |
+
def get_fontsize(self):
|
| 847 |
+
"""
|
| 848 |
+
Return the font size as an integer.
|
| 849 |
+
|
| 850 |
+
See Also
|
| 851 |
+
--------
|
| 852 |
+
.font_manager.FontProperties.get_size_in_points
|
| 853 |
+
"""
|
| 854 |
+
return self._fontproperties.get_size_in_points()
|
| 855 |
+
|
| 856 |
+
def get_fontvariant(self):
|
| 857 |
+
"""
|
| 858 |
+
Return the font variant as a string.
|
| 859 |
+
|
| 860 |
+
See Also
|
| 861 |
+
--------
|
| 862 |
+
.font_manager.FontProperties.get_variant
|
| 863 |
+
"""
|
| 864 |
+
return self._fontproperties.get_variant()
|
| 865 |
+
|
| 866 |
+
def get_fontweight(self):
|
| 867 |
+
"""
|
| 868 |
+
Return the font weight as a string or a number.
|
| 869 |
+
|
| 870 |
+
See Also
|
| 871 |
+
--------
|
| 872 |
+
.font_manager.FontProperties.get_weight
|
| 873 |
+
"""
|
| 874 |
+
return self._fontproperties.get_weight()
|
| 875 |
+
|
| 876 |
+
def get_stretch(self):
|
| 877 |
+
"""
|
| 878 |
+
Return the font stretch as a string or a number.
|
| 879 |
+
|
| 880 |
+
See Also
|
| 881 |
+
--------
|
| 882 |
+
.font_manager.FontProperties.get_stretch
|
| 883 |
+
"""
|
| 884 |
+
return self._fontproperties.get_stretch()
|
| 885 |
+
|
| 886 |
+
def get_horizontalalignment(self):
|
| 887 |
+
"""
|
| 888 |
+
Return the horizontal alignment as a string. Will be one of
|
| 889 |
+
'left', 'center' or 'right'.
|
| 890 |
+
"""
|
| 891 |
+
return self._horizontalalignment
|
| 892 |
+
|
| 893 |
+
def get_unitless_position(self):
|
| 894 |
+
"""Return the (x, y) unitless position of the text."""
|
| 895 |
+
# This will get the position with all unit information stripped away.
|
| 896 |
+
# This is here for convenience since it is done in several locations.
|
| 897 |
+
x = float(self.convert_xunits(self._x))
|
| 898 |
+
y = float(self.convert_yunits(self._y))
|
| 899 |
+
return x, y
|
| 900 |
+
|
| 901 |
+
def get_position(self):
|
| 902 |
+
"""Return the (x, y) position of the text."""
|
| 903 |
+
# This should return the same data (possible unitized) as was
|
| 904 |
+
# specified with 'set_x' and 'set_y'.
|
| 905 |
+
return self._x, self._y
|
| 906 |
+
|
| 907 |
+
def get_text(self):
|
| 908 |
+
"""Return the text string."""
|
| 909 |
+
return self._text
|
| 910 |
+
|
| 911 |
+
def get_verticalalignment(self):
|
| 912 |
+
"""
|
| 913 |
+
Return the vertical alignment as a string. Will be one of
|
| 914 |
+
'top', 'center', 'bottom', 'baseline' or 'center_baseline'.
|
| 915 |
+
"""
|
| 916 |
+
return self._verticalalignment
|
| 917 |
+
|
| 918 |
+
def get_window_extent(self, renderer=None, dpi=None):
|
| 919 |
+
"""
|
| 920 |
+
Return the `.Bbox` bounding the text, in display units.
|
| 921 |
+
|
| 922 |
+
In addition to being used internally, this is useful for specifying
|
| 923 |
+
clickable regions in a png file on a web page.
|
| 924 |
+
|
| 925 |
+
Parameters
|
| 926 |
+
----------
|
| 927 |
+
renderer : Renderer, optional
|
| 928 |
+
A renderer is needed to compute the bounding box. If the artist
|
| 929 |
+
has already been drawn, the renderer is cached; thus, it is only
|
| 930 |
+
necessary to pass this argument when calling `get_window_extent`
|
| 931 |
+
before the first draw. In practice, it is usually easier to
|
| 932 |
+
trigger a draw first, e.g. by calling
|
| 933 |
+
`~.Figure.draw_without_rendering` or ``plt.show()``.
|
| 934 |
+
|
| 935 |
+
dpi : float, optional
|
| 936 |
+
The dpi value for computing the bbox, defaults to
|
| 937 |
+
``self.figure.dpi`` (*not* the renderer dpi); should be set e.g. if
|
| 938 |
+
to match regions with a figure saved with a custom dpi value.
|
| 939 |
+
"""
|
| 940 |
+
if not self.get_visible():
|
| 941 |
+
return Bbox.unit()
|
| 942 |
+
if dpi is None:
|
| 943 |
+
dpi = self.figure.dpi
|
| 944 |
+
if self.get_text() == '':
|
| 945 |
+
with cbook._setattr_cm(self.figure, dpi=dpi):
|
| 946 |
+
tx, ty = self._get_xy_display()
|
| 947 |
+
return Bbox.from_bounds(tx, ty, 0, 0)
|
| 948 |
+
|
| 949 |
+
if renderer is not None:
|
| 950 |
+
self._renderer = renderer
|
| 951 |
+
if self._renderer is None:
|
| 952 |
+
self._renderer = self.figure._get_renderer()
|
| 953 |
+
if self._renderer is None:
|
| 954 |
+
raise RuntimeError(
|
| 955 |
+
"Cannot get window extent of text w/o renderer. You likely "
|
| 956 |
+
"want to call 'figure.draw_without_rendering()' first.")
|
| 957 |
+
|
| 958 |
+
with cbook._setattr_cm(self.figure, dpi=dpi):
|
| 959 |
+
bbox, info, descent = self._get_layout(self._renderer)
|
| 960 |
+
x, y = self.get_unitless_position()
|
| 961 |
+
x, y = self.get_transform().transform((x, y))
|
| 962 |
+
bbox = bbox.translated(x, y)
|
| 963 |
+
return bbox
|
| 964 |
+
|
| 965 |
+
def set_backgroundcolor(self, color):
|
| 966 |
+
"""
|
| 967 |
+
Set the background color of the text by updating the bbox.
|
| 968 |
+
|
| 969 |
+
Parameters
|
| 970 |
+
----------
|
| 971 |
+
color : color
|
| 972 |
+
|
| 973 |
+
See Also
|
| 974 |
+
--------
|
| 975 |
+
.set_bbox : To change the position of the bounding box
|
| 976 |
+
"""
|
| 977 |
+
if self._bbox_patch is None:
|
| 978 |
+
self.set_bbox(dict(facecolor=color, edgecolor=color))
|
| 979 |
+
else:
|
| 980 |
+
self._bbox_patch.update(dict(facecolor=color))
|
| 981 |
+
|
| 982 |
+
self._update_clip_properties()
|
| 983 |
+
self.stale = True
|
| 984 |
+
|
| 985 |
+
def set_color(self, color):
|
| 986 |
+
"""
|
| 987 |
+
Set the foreground color of the text
|
| 988 |
+
|
| 989 |
+
Parameters
|
| 990 |
+
----------
|
| 991 |
+
color : color
|
| 992 |
+
"""
|
| 993 |
+
# "auto" is only supported by axisartist, but we can just let it error
|
| 994 |
+
# out at draw time for simplicity.
|
| 995 |
+
if not cbook._str_equal(color, "auto"):
|
| 996 |
+
mpl.colors._check_color_like(color=color)
|
| 997 |
+
self._color = color
|
| 998 |
+
self.stale = True
|
| 999 |
+
|
| 1000 |
+
def set_horizontalalignment(self, align):
|
| 1001 |
+
"""
|
| 1002 |
+
Set the horizontal alignment relative to the anchor point.
|
| 1003 |
+
|
| 1004 |
+
See also :doc:`/gallery/text_labels_and_annotations/text_alignment`.
|
| 1005 |
+
|
| 1006 |
+
Parameters
|
| 1007 |
+
----------
|
| 1008 |
+
align : {'left', 'center', 'right'}
|
| 1009 |
+
"""
|
| 1010 |
+
_api.check_in_list(['center', 'right', 'left'], align=align)
|
| 1011 |
+
self._horizontalalignment = align
|
| 1012 |
+
self.stale = True
|
| 1013 |
+
|
| 1014 |
+
def set_multialignment(self, align):
|
| 1015 |
+
"""
|
| 1016 |
+
Set the text alignment for multiline texts.
|
| 1017 |
+
|
| 1018 |
+
The layout of the bounding box of all the lines is determined by the
|
| 1019 |
+
horizontalalignment and verticalalignment properties. This property
|
| 1020 |
+
controls the alignment of the text lines within that box.
|
| 1021 |
+
|
| 1022 |
+
Parameters
|
| 1023 |
+
----------
|
| 1024 |
+
align : {'left', 'right', 'center'}
|
| 1025 |
+
"""
|
| 1026 |
+
_api.check_in_list(['center', 'right', 'left'], align=align)
|
| 1027 |
+
self._multialignment = align
|
| 1028 |
+
self.stale = True
|
| 1029 |
+
|
| 1030 |
+
def set_linespacing(self, spacing):
|
| 1031 |
+
"""
|
| 1032 |
+
Set the line spacing as a multiple of the font size.
|
| 1033 |
+
|
| 1034 |
+
The default line spacing is 1.2.
|
| 1035 |
+
|
| 1036 |
+
Parameters
|
| 1037 |
+
----------
|
| 1038 |
+
spacing : float (multiple of font size)
|
| 1039 |
+
"""
|
| 1040 |
+
_api.check_isinstance(Real, spacing=spacing)
|
| 1041 |
+
self._linespacing = spacing
|
| 1042 |
+
self.stale = True
|
| 1043 |
+
|
| 1044 |
+
def set_fontfamily(self, fontname):
|
| 1045 |
+
"""
|
| 1046 |
+
Set the font family. Can be either a single string, or a list of
|
| 1047 |
+
strings in decreasing priority. Each string may be either a real font
|
| 1048 |
+
name or a generic font class name. If the latter, the specific font
|
| 1049 |
+
names will be looked up in the corresponding rcParams.
|
| 1050 |
+
|
| 1051 |
+
If a `Text` instance is constructed with ``fontfamily=None``, then the
|
| 1052 |
+
font is set to :rc:`font.family`, and the
|
| 1053 |
+
same is done when `set_fontfamily()` is called on an existing
|
| 1054 |
+
`Text` instance.
|
| 1055 |
+
|
| 1056 |
+
Parameters
|
| 1057 |
+
----------
|
| 1058 |
+
fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \
|
| 1059 |
+
'monospace'}
|
| 1060 |
+
|
| 1061 |
+
See Also
|
| 1062 |
+
--------
|
| 1063 |
+
.font_manager.FontProperties.set_family
|
| 1064 |
+
"""
|
| 1065 |
+
self._fontproperties.set_family(fontname)
|
| 1066 |
+
self.stale = True
|
| 1067 |
+
|
| 1068 |
+
def set_fontvariant(self, variant):
|
| 1069 |
+
"""
|
| 1070 |
+
Set the font variant.
|
| 1071 |
+
|
| 1072 |
+
Parameters
|
| 1073 |
+
----------
|
| 1074 |
+
variant : {'normal', 'small-caps'}
|
| 1075 |
+
|
| 1076 |
+
See Also
|
| 1077 |
+
--------
|
| 1078 |
+
.font_manager.FontProperties.set_variant
|
| 1079 |
+
"""
|
| 1080 |
+
self._fontproperties.set_variant(variant)
|
| 1081 |
+
self.stale = True
|
| 1082 |
+
|
| 1083 |
+
def set_fontstyle(self, fontstyle):
|
| 1084 |
+
"""
|
| 1085 |
+
Set the font style.
|
| 1086 |
+
|
| 1087 |
+
Parameters
|
| 1088 |
+
----------
|
| 1089 |
+
fontstyle : {'normal', 'italic', 'oblique'}
|
| 1090 |
+
|
| 1091 |
+
See Also
|
| 1092 |
+
--------
|
| 1093 |
+
.font_manager.FontProperties.set_style
|
| 1094 |
+
"""
|
| 1095 |
+
self._fontproperties.set_style(fontstyle)
|
| 1096 |
+
self.stale = True
|
| 1097 |
+
|
| 1098 |
+
def set_fontsize(self, fontsize):
|
| 1099 |
+
"""
|
| 1100 |
+
Set the font size.
|
| 1101 |
+
|
| 1102 |
+
Parameters
|
| 1103 |
+
----------
|
| 1104 |
+
fontsize : float or {'xx-small', 'x-small', 'small', 'medium', \
|
| 1105 |
+
'large', 'x-large', 'xx-large'}
|
| 1106 |
+
If a float, the fontsize in points. The string values denote sizes
|
| 1107 |
+
relative to the default font size.
|
| 1108 |
+
|
| 1109 |
+
See Also
|
| 1110 |
+
--------
|
| 1111 |
+
.font_manager.FontProperties.set_size
|
| 1112 |
+
"""
|
| 1113 |
+
self._fontproperties.set_size(fontsize)
|
| 1114 |
+
self.stale = True
|
| 1115 |
+
|
| 1116 |
+
def get_math_fontfamily(self):
|
| 1117 |
+
"""
|
| 1118 |
+
Return the font family name for math text rendered by Matplotlib.
|
| 1119 |
+
|
| 1120 |
+
The default value is :rc:`mathtext.fontset`.
|
| 1121 |
+
|
| 1122 |
+
See Also
|
| 1123 |
+
--------
|
| 1124 |
+
set_math_fontfamily
|
| 1125 |
+
"""
|
| 1126 |
+
return self._fontproperties.get_math_fontfamily()
|
| 1127 |
+
|
| 1128 |
+
def set_math_fontfamily(self, fontfamily):
|
| 1129 |
+
"""
|
| 1130 |
+
Set the font family for math text rendered by Matplotlib.
|
| 1131 |
+
|
| 1132 |
+
This does only affect Matplotlib's own math renderer. It has no effect
|
| 1133 |
+
when rendering with TeX (``usetex=True``).
|
| 1134 |
+
|
| 1135 |
+
Parameters
|
| 1136 |
+
----------
|
| 1137 |
+
fontfamily : str
|
| 1138 |
+
The name of the font family.
|
| 1139 |
+
|
| 1140 |
+
Available font families are defined in the
|
| 1141 |
+
:ref:`default matplotlibrc file
|
| 1142 |
+
<customizing-with-matplotlibrc-files>`.
|
| 1143 |
+
|
| 1144 |
+
See Also
|
| 1145 |
+
--------
|
| 1146 |
+
get_math_fontfamily
|
| 1147 |
+
"""
|
| 1148 |
+
self._fontproperties.set_math_fontfamily(fontfamily)
|
| 1149 |
+
|
| 1150 |
+
def set_fontweight(self, weight):
|
| 1151 |
+
"""
|
| 1152 |
+
Set the font weight.
|
| 1153 |
+
|
| 1154 |
+
Parameters
|
| 1155 |
+
----------
|
| 1156 |
+
weight : {a numeric value in range 0-1000, 'ultralight', 'light', \
|
| 1157 |
+
'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', \
|
| 1158 |
+
'demi', 'bold', 'heavy', 'extra bold', 'black'}
|
| 1159 |
+
|
| 1160 |
+
See Also
|
| 1161 |
+
--------
|
| 1162 |
+
.font_manager.FontProperties.set_weight
|
| 1163 |
+
"""
|
| 1164 |
+
self._fontproperties.set_weight(weight)
|
| 1165 |
+
self.stale = True
|
| 1166 |
+
|
| 1167 |
+
def set_fontstretch(self, stretch):
|
| 1168 |
+
"""
|
| 1169 |
+
Set the font stretch (horizontal condensation or expansion).
|
| 1170 |
+
|
| 1171 |
+
Parameters
|
| 1172 |
+
----------
|
| 1173 |
+
stretch : {a numeric value in range 0-1000, 'ultra-condensed', \
|
| 1174 |
+
'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', \
|
| 1175 |
+
'expanded', 'extra-expanded', 'ultra-expanded'}
|
| 1176 |
+
|
| 1177 |
+
See Also
|
| 1178 |
+
--------
|
| 1179 |
+
.font_manager.FontProperties.set_stretch
|
| 1180 |
+
"""
|
| 1181 |
+
self._fontproperties.set_stretch(stretch)
|
| 1182 |
+
self.stale = True
|
| 1183 |
+
|
| 1184 |
+
def set_position(self, xy):
|
| 1185 |
+
"""
|
| 1186 |
+
Set the (*x*, *y*) position of the text.
|
| 1187 |
+
|
| 1188 |
+
Parameters
|
| 1189 |
+
----------
|
| 1190 |
+
xy : (float, float)
|
| 1191 |
+
"""
|
| 1192 |
+
self.set_x(xy[0])
|
| 1193 |
+
self.set_y(xy[1])
|
| 1194 |
+
|
| 1195 |
+
def set_x(self, x):
|
| 1196 |
+
"""
|
| 1197 |
+
Set the *x* position of the text.
|
| 1198 |
+
|
| 1199 |
+
Parameters
|
| 1200 |
+
----------
|
| 1201 |
+
x : float
|
| 1202 |
+
"""
|
| 1203 |
+
self._x = x
|
| 1204 |
+
self.stale = True
|
| 1205 |
+
|
| 1206 |
+
def set_y(self, y):
|
| 1207 |
+
"""
|
| 1208 |
+
Set the *y* position of the text.
|
| 1209 |
+
|
| 1210 |
+
Parameters
|
| 1211 |
+
----------
|
| 1212 |
+
y : float
|
| 1213 |
+
"""
|
| 1214 |
+
self._y = y
|
| 1215 |
+
self.stale = True
|
| 1216 |
+
|
| 1217 |
+
def set_rotation(self, s):
|
| 1218 |
+
"""
|
| 1219 |
+
Set the rotation of the text.
|
| 1220 |
+
|
| 1221 |
+
Parameters
|
| 1222 |
+
----------
|
| 1223 |
+
s : float or {'vertical', 'horizontal'}
|
| 1224 |
+
The rotation angle in degrees in mathematically positive direction
|
| 1225 |
+
(counterclockwise). 'horizontal' equals 0, 'vertical' equals 90.
|
| 1226 |
+
"""
|
| 1227 |
+
if isinstance(s, Real):
|
| 1228 |
+
self._rotation = float(s) % 360
|
| 1229 |
+
elif cbook._str_equal(s, 'horizontal') or s is None:
|
| 1230 |
+
self._rotation = 0.
|
| 1231 |
+
elif cbook._str_equal(s, 'vertical'):
|
| 1232 |
+
self._rotation = 90.
|
| 1233 |
+
else:
|
| 1234 |
+
raise ValueError("rotation must be 'vertical', 'horizontal' or "
|
| 1235 |
+
f"a number, not {s}")
|
| 1236 |
+
self.stale = True
|
| 1237 |
+
|
| 1238 |
+
def set_transform_rotates_text(self, t):
|
| 1239 |
+
"""
|
| 1240 |
+
Whether rotations of the transform affect the text direction.
|
| 1241 |
+
|
| 1242 |
+
Parameters
|
| 1243 |
+
----------
|
| 1244 |
+
t : bool
|
| 1245 |
+
"""
|
| 1246 |
+
self._transform_rotates_text = t
|
| 1247 |
+
self.stale = True
|
| 1248 |
+
|
| 1249 |
+
def set_verticalalignment(self, align):
|
| 1250 |
+
"""
|
| 1251 |
+
Set the vertical alignment relative to the anchor point.
|
| 1252 |
+
|
| 1253 |
+
See also :doc:`/gallery/text_labels_and_annotations/text_alignment`.
|
| 1254 |
+
|
| 1255 |
+
Parameters
|
| 1256 |
+
----------
|
| 1257 |
+
align : {'bottom', 'baseline', 'center', 'center_baseline', 'top'}
|
| 1258 |
+
"""
|
| 1259 |
+
_api.check_in_list(
|
| 1260 |
+
['top', 'bottom', 'center', 'baseline', 'center_baseline'],
|
| 1261 |
+
align=align)
|
| 1262 |
+
self._verticalalignment = align
|
| 1263 |
+
self.stale = True
|
| 1264 |
+
|
| 1265 |
+
def set_text(self, s):
|
| 1266 |
+
r"""
|
| 1267 |
+
Set the text string *s*.
|
| 1268 |
+
|
| 1269 |
+
It may contain newlines (``\n``) or math in LaTeX syntax.
|
| 1270 |
+
|
| 1271 |
+
Parameters
|
| 1272 |
+
----------
|
| 1273 |
+
s : object
|
| 1274 |
+
Any object gets converted to its `str` representation, except for
|
| 1275 |
+
``None`` which is converted to an empty string.
|
| 1276 |
+
"""
|
| 1277 |
+
if s is None:
|
| 1278 |
+
s = ''
|
| 1279 |
+
if s != self._text:
|
| 1280 |
+
self._text = str(s)
|
| 1281 |
+
self.stale = True
|
| 1282 |
+
|
| 1283 |
+
def _preprocess_math(self, s):
|
| 1284 |
+
"""
|
| 1285 |
+
Return the string *s* after mathtext preprocessing, and the kind of
|
| 1286 |
+
mathtext support needed.
|
| 1287 |
+
|
| 1288 |
+
- If *self* is configured to use TeX, return *s* unchanged except that
|
| 1289 |
+
a single space gets escaped, and the flag "TeX".
|
| 1290 |
+
- Otherwise, if *s* is mathtext (has an even number of unescaped dollar
|
| 1291 |
+
signs) and ``parse_math`` is not set to False, return *s* and the
|
| 1292 |
+
flag True.
|
| 1293 |
+
- Otherwise, return *s* with dollar signs unescaped, and the flag
|
| 1294 |
+
False.
|
| 1295 |
+
"""
|
| 1296 |
+
if self.get_usetex():
|
| 1297 |
+
if s == " ":
|
| 1298 |
+
s = r"\ "
|
| 1299 |
+
return s, "TeX"
|
| 1300 |
+
elif not self.get_parse_math():
|
| 1301 |
+
return s, False
|
| 1302 |
+
elif cbook.is_math_text(s):
|
| 1303 |
+
return s, True
|
| 1304 |
+
else:
|
| 1305 |
+
return s.replace(r"\$", "$"), False
|
| 1306 |
+
|
| 1307 |
+
def set_fontproperties(self, fp):
|
| 1308 |
+
"""
|
| 1309 |
+
Set the font properties that control the text.
|
| 1310 |
+
|
| 1311 |
+
Parameters
|
| 1312 |
+
----------
|
| 1313 |
+
fp : `.font_manager.FontProperties` or `str` or `pathlib.Path`
|
| 1314 |
+
If a `str`, it is interpreted as a fontconfig pattern parsed by
|
| 1315 |
+
`.FontProperties`. If a `pathlib.Path`, it is interpreted as the
|
| 1316 |
+
absolute path to a font file.
|
| 1317 |
+
"""
|
| 1318 |
+
self._fontproperties = FontProperties._from_any(fp).copy()
|
| 1319 |
+
self.stale = True
|
| 1320 |
+
|
| 1321 |
+
def set_usetex(self, usetex):
|
| 1322 |
+
"""
|
| 1323 |
+
Parameters
|
| 1324 |
+
----------
|
| 1325 |
+
usetex : bool or None
|
| 1326 |
+
Whether to render using TeX, ``None`` means to use
|
| 1327 |
+
:rc:`text.usetex`.
|
| 1328 |
+
"""
|
| 1329 |
+
if usetex is None:
|
| 1330 |
+
self._usetex = mpl.rcParams['text.usetex']
|
| 1331 |
+
else:
|
| 1332 |
+
self._usetex = bool(usetex)
|
| 1333 |
+
self.stale = True
|
| 1334 |
+
|
| 1335 |
+
def get_usetex(self):
|
| 1336 |
+
"""Return whether this `Text` object uses TeX for rendering."""
|
| 1337 |
+
return self._usetex
|
| 1338 |
+
|
| 1339 |
+
def set_parse_math(self, parse_math):
|
| 1340 |
+
"""
|
| 1341 |
+
Override switch to disable any mathtext parsing for this `Text`.
|
| 1342 |
+
|
| 1343 |
+
Parameters
|
| 1344 |
+
----------
|
| 1345 |
+
parse_math : bool
|
| 1346 |
+
If False, this `Text` will never use mathtext. If True, mathtext
|
| 1347 |
+
will be used if there is an even number of unescaped dollar signs.
|
| 1348 |
+
"""
|
| 1349 |
+
self._parse_math = bool(parse_math)
|
| 1350 |
+
|
| 1351 |
+
def get_parse_math(self):
|
| 1352 |
+
"""Return whether mathtext parsing is considered for this `Text`."""
|
| 1353 |
+
return self._parse_math
|
| 1354 |
+
|
| 1355 |
+
def set_fontname(self, fontname):
|
| 1356 |
+
"""
|
| 1357 |
+
Alias for `set_family`.
|
| 1358 |
+
|
| 1359 |
+
One-way alias only: the getter differs.
|
| 1360 |
+
|
| 1361 |
+
Parameters
|
| 1362 |
+
----------
|
| 1363 |
+
fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \
|
| 1364 |
+
'monospace'}
|
| 1365 |
+
|
| 1366 |
+
See Also
|
| 1367 |
+
--------
|
| 1368 |
+
.font_manager.FontProperties.set_family
|
| 1369 |
+
|
| 1370 |
+
"""
|
| 1371 |
+
return self.set_family(fontname)
|
| 1372 |
+
|
| 1373 |
+
|
| 1374 |
+
class OffsetFrom:
|
| 1375 |
+
"""Callable helper class for working with `Annotation`."""
|
| 1376 |
+
|
| 1377 |
+
def __init__(self, artist, ref_coord, unit="points"):
|
| 1378 |
+
"""
|
| 1379 |
+
Parameters
|
| 1380 |
+
----------
|
| 1381 |
+
artist : `~matplotlib.artist.Artist` or `.BboxBase` or `.Transform`
|
| 1382 |
+
The object to compute the offset from.
|
| 1383 |
+
|
| 1384 |
+
ref_coord : (float, float)
|
| 1385 |
+
If *artist* is an `.Artist` or `.BboxBase`, this values is
|
| 1386 |
+
the location to of the offset origin in fractions of the
|
| 1387 |
+
*artist* bounding box.
|
| 1388 |
+
|
| 1389 |
+
If *artist* is a transform, the offset origin is the
|
| 1390 |
+
transform applied to this value.
|
| 1391 |
+
|
| 1392 |
+
unit : {'points, 'pixels'}, default: 'points'
|
| 1393 |
+
The screen units to use (pixels or points) for the offset input.
|
| 1394 |
+
"""
|
| 1395 |
+
self._artist = artist
|
| 1396 |
+
self._ref_coord = ref_coord
|
| 1397 |
+
self.set_unit(unit)
|
| 1398 |
+
|
| 1399 |
+
def set_unit(self, unit):
|
| 1400 |
+
"""
|
| 1401 |
+
Set the unit for input to the transform used by ``__call__``.
|
| 1402 |
+
|
| 1403 |
+
Parameters
|
| 1404 |
+
----------
|
| 1405 |
+
unit : {'points', 'pixels'}
|
| 1406 |
+
"""
|
| 1407 |
+
_api.check_in_list(["points", "pixels"], unit=unit)
|
| 1408 |
+
self._unit = unit
|
| 1409 |
+
|
| 1410 |
+
def get_unit(self):
|
| 1411 |
+
"""Return the unit for input to the transform used by ``__call__``."""
|
| 1412 |
+
return self._unit
|
| 1413 |
+
|
| 1414 |
+
def _get_scale(self, renderer):
|
| 1415 |
+
unit = self.get_unit()
|
| 1416 |
+
if unit == "pixels":
|
| 1417 |
+
return 1.
|
| 1418 |
+
else:
|
| 1419 |
+
return renderer.points_to_pixels(1.)
|
| 1420 |
+
|
| 1421 |
+
def __call__(self, renderer):
|
| 1422 |
+
"""
|
| 1423 |
+
Return the offset transform.
|
| 1424 |
+
|
| 1425 |
+
Parameters
|
| 1426 |
+
----------
|
| 1427 |
+
renderer : `RendererBase`
|
| 1428 |
+
The renderer to use to compute the offset
|
| 1429 |
+
|
| 1430 |
+
Returns
|
| 1431 |
+
-------
|
| 1432 |
+
`Transform`
|
| 1433 |
+
Maps (x, y) in pixel or point units to screen units
|
| 1434 |
+
relative to the given artist.
|
| 1435 |
+
"""
|
| 1436 |
+
if isinstance(self._artist, Artist):
|
| 1437 |
+
bbox = self._artist.get_window_extent(renderer)
|
| 1438 |
+
xf, yf = self._ref_coord
|
| 1439 |
+
x = bbox.x0 + bbox.width * xf
|
| 1440 |
+
y = bbox.y0 + bbox.height * yf
|
| 1441 |
+
elif isinstance(self._artist, BboxBase):
|
| 1442 |
+
bbox = self._artist
|
| 1443 |
+
xf, yf = self._ref_coord
|
| 1444 |
+
x = bbox.x0 + bbox.width * xf
|
| 1445 |
+
y = bbox.y0 + bbox.height * yf
|
| 1446 |
+
elif isinstance(self._artist, Transform):
|
| 1447 |
+
x, y = self._artist.transform(self._ref_coord)
|
| 1448 |
+
else:
|
| 1449 |
+
raise RuntimeError("unknown type")
|
| 1450 |
+
|
| 1451 |
+
sc = self._get_scale(renderer)
|
| 1452 |
+
tr = Affine2D().scale(sc).translate(x, y)
|
| 1453 |
+
|
| 1454 |
+
return tr
|
| 1455 |
+
|
| 1456 |
+
|
| 1457 |
+
class _AnnotationBase:
|
| 1458 |
+
def __init__(self,
|
| 1459 |
+
xy,
|
| 1460 |
+
xycoords='data',
|
| 1461 |
+
annotation_clip=None):
|
| 1462 |
+
|
| 1463 |
+
self.xy = xy
|
| 1464 |
+
self.xycoords = xycoords
|
| 1465 |
+
self.set_annotation_clip(annotation_clip)
|
| 1466 |
+
|
| 1467 |
+
self._draggable = None
|
| 1468 |
+
|
| 1469 |
+
def _get_xy(self, renderer, x, y, s):
|
| 1470 |
+
if isinstance(s, tuple):
|
| 1471 |
+
s1, s2 = s
|
| 1472 |
+
else:
|
| 1473 |
+
s1, s2 = s, s
|
| 1474 |
+
if s1 == 'data':
|
| 1475 |
+
x = float(self.convert_xunits(x))
|
| 1476 |
+
if s2 == 'data':
|
| 1477 |
+
y = float(self.convert_yunits(y))
|
| 1478 |
+
return self._get_xy_transform(renderer, s).transform((x, y))
|
| 1479 |
+
|
| 1480 |
+
def _get_xy_transform(self, renderer, s):
|
| 1481 |
+
|
| 1482 |
+
if isinstance(s, tuple):
|
| 1483 |
+
s1, s2 = s
|
| 1484 |
+
from matplotlib.transforms import blended_transform_factory
|
| 1485 |
+
tr1 = self._get_xy_transform(renderer, s1)
|
| 1486 |
+
tr2 = self._get_xy_transform(renderer, s2)
|
| 1487 |
+
tr = blended_transform_factory(tr1, tr2)
|
| 1488 |
+
return tr
|
| 1489 |
+
elif callable(s):
|
| 1490 |
+
tr = s(renderer)
|
| 1491 |
+
if isinstance(tr, BboxBase):
|
| 1492 |
+
return BboxTransformTo(tr)
|
| 1493 |
+
elif isinstance(tr, Transform):
|
| 1494 |
+
return tr
|
| 1495 |
+
else:
|
| 1496 |
+
raise RuntimeError("Unknown return type")
|
| 1497 |
+
elif isinstance(s, Artist):
|
| 1498 |
+
bbox = s.get_window_extent(renderer)
|
| 1499 |
+
return BboxTransformTo(bbox)
|
| 1500 |
+
elif isinstance(s, BboxBase):
|
| 1501 |
+
return BboxTransformTo(s)
|
| 1502 |
+
elif isinstance(s, Transform):
|
| 1503 |
+
return s
|
| 1504 |
+
elif not isinstance(s, str):
|
| 1505 |
+
raise RuntimeError(f"Unknown coordinate type: {s!r}")
|
| 1506 |
+
|
| 1507 |
+
if s == 'data':
|
| 1508 |
+
return self.axes.transData
|
| 1509 |
+
elif s == 'polar':
|
| 1510 |
+
from matplotlib.projections import PolarAxes
|
| 1511 |
+
tr = PolarAxes.PolarTransform()
|
| 1512 |
+
trans = tr + self.axes.transData
|
| 1513 |
+
return trans
|
| 1514 |
+
|
| 1515 |
+
s_ = s.split()
|
| 1516 |
+
if len(s_) != 2:
|
| 1517 |
+
raise ValueError(f"{s!r} is not a recognized coordinate")
|
| 1518 |
+
|
| 1519 |
+
bbox0, xy0 = None, None
|
| 1520 |
+
|
| 1521 |
+
bbox_name, unit = s_
|
| 1522 |
+
# if unit is offset-like
|
| 1523 |
+
if bbox_name == "figure":
|
| 1524 |
+
bbox0 = self.figure.figbbox
|
| 1525 |
+
elif bbox_name == "subfigure":
|
| 1526 |
+
bbox0 = self.figure.bbox
|
| 1527 |
+
elif bbox_name == "axes":
|
| 1528 |
+
bbox0 = self.axes.bbox
|
| 1529 |
+
# elif bbox_name == "bbox":
|
| 1530 |
+
# if bbox is None:
|
| 1531 |
+
# raise RuntimeError("bbox is specified as a coordinate but "
|
| 1532 |
+
# "never set")
|
| 1533 |
+
# bbox0 = self._get_bbox(renderer, bbox)
|
| 1534 |
+
|
| 1535 |
+
if bbox0 is not None:
|
| 1536 |
+
xy0 = bbox0.p0
|
| 1537 |
+
elif bbox_name == "offset":
|
| 1538 |
+
xy0 = self._get_ref_xy(renderer)
|
| 1539 |
+
|
| 1540 |
+
if xy0 is not None:
|
| 1541 |
+
# reference x, y in display coordinate
|
| 1542 |
+
ref_x, ref_y = xy0
|
| 1543 |
+
if unit == "points":
|
| 1544 |
+
# dots per points
|
| 1545 |
+
dpp = self.figure.dpi / 72
|
| 1546 |
+
tr = Affine2D().scale(dpp)
|
| 1547 |
+
elif unit == "pixels":
|
| 1548 |
+
tr = Affine2D()
|
| 1549 |
+
elif unit == "fontsize":
|
| 1550 |
+
fontsize = self.get_size()
|
| 1551 |
+
dpp = fontsize * self.figure.dpi / 72
|
| 1552 |
+
tr = Affine2D().scale(dpp)
|
| 1553 |
+
elif unit == "fraction":
|
| 1554 |
+
w, h = bbox0.size
|
| 1555 |
+
tr = Affine2D().scale(w, h)
|
| 1556 |
+
else:
|
| 1557 |
+
raise ValueError(f"{unit!r} is not a recognized unit")
|
| 1558 |
+
|
| 1559 |
+
return tr.translate(ref_x, ref_y)
|
| 1560 |
+
|
| 1561 |
+
else:
|
| 1562 |
+
raise ValueError(f"{s!r} is not a recognized coordinate")
|
| 1563 |
+
|
| 1564 |
+
def _get_ref_xy(self, renderer):
|
| 1565 |
+
"""
|
| 1566 |
+
Return x, y (in display coordinates) that is to be used for a reference
|
| 1567 |
+
of any offset coordinate.
|
| 1568 |
+
"""
|
| 1569 |
+
return self._get_xy(renderer, *self.xy, self.xycoords)
|
| 1570 |
+
|
| 1571 |
+
# def _get_bbox(self, renderer):
|
| 1572 |
+
# if hasattr(bbox, "bounds"):
|
| 1573 |
+
# return bbox
|
| 1574 |
+
# elif hasattr(bbox, "get_window_extent"):
|
| 1575 |
+
# bbox = bbox.get_window_extent()
|
| 1576 |
+
# return bbox
|
| 1577 |
+
# else:
|
| 1578 |
+
# raise ValueError("A bbox instance is expected but got %s" %
|
| 1579 |
+
# str(bbox))
|
| 1580 |
+
|
| 1581 |
+
def set_annotation_clip(self, b):
|
| 1582 |
+
"""
|
| 1583 |
+
Set the annotation's clipping behavior.
|
| 1584 |
+
|
| 1585 |
+
Parameters
|
| 1586 |
+
----------
|
| 1587 |
+
b : bool or None
|
| 1588 |
+
- True: The annotation will be clipped when ``self.xy`` is
|
| 1589 |
+
outside the axes.
|
| 1590 |
+
- False: The annotation will always be drawn.
|
| 1591 |
+
- None: The annotation will be clipped when ``self.xy`` is
|
| 1592 |
+
outside the axes and ``self.xycoords == "data"``.
|
| 1593 |
+
"""
|
| 1594 |
+
self._annotation_clip = b
|
| 1595 |
+
|
| 1596 |
+
def get_annotation_clip(self):
|
| 1597 |
+
"""
|
| 1598 |
+
Return the annotation's clipping behavior.
|
| 1599 |
+
|
| 1600 |
+
See `set_annotation_clip` for the meaning of return values.
|
| 1601 |
+
"""
|
| 1602 |
+
return self._annotation_clip
|
| 1603 |
+
|
| 1604 |
+
def _get_position_xy(self, renderer):
|
| 1605 |
+
"""Return the pixel position of the annotated point."""
|
| 1606 |
+
x, y = self.xy
|
| 1607 |
+
return self._get_xy(renderer, x, y, self.xycoords)
|
| 1608 |
+
|
| 1609 |
+
def _check_xy(self, renderer=None):
|
| 1610 |
+
"""Check whether the annotation at *xy_pixel* should be drawn."""
|
| 1611 |
+
if renderer is None:
|
| 1612 |
+
renderer = self.figure._get_renderer()
|
| 1613 |
+
b = self.get_annotation_clip()
|
| 1614 |
+
if b or (b is None and self.xycoords == "data"):
|
| 1615 |
+
# check if self.xy is inside the axes.
|
| 1616 |
+
xy_pixel = self._get_position_xy(renderer)
|
| 1617 |
+
return self.axes.contains_point(xy_pixel)
|
| 1618 |
+
return True
|
| 1619 |
+
|
| 1620 |
+
def draggable(self, state=None, use_blit=False):
|
| 1621 |
+
"""
|
| 1622 |
+
Set whether the annotation is draggable with the mouse.
|
| 1623 |
+
|
| 1624 |
+
Parameters
|
| 1625 |
+
----------
|
| 1626 |
+
state : bool or None
|
| 1627 |
+
- True or False: set the draggability.
|
| 1628 |
+
- None: toggle the draggability.
|
| 1629 |
+
use_blit : bool, default: False
|
| 1630 |
+
Use blitting for faster image composition. For details see
|
| 1631 |
+
:ref:`func-animation`.
|
| 1632 |
+
|
| 1633 |
+
Returns
|
| 1634 |
+
-------
|
| 1635 |
+
DraggableAnnotation or None
|
| 1636 |
+
If the annotation is draggable, the corresponding
|
| 1637 |
+
`.DraggableAnnotation` helper is returned.
|
| 1638 |
+
"""
|
| 1639 |
+
from matplotlib.offsetbox import DraggableAnnotation
|
| 1640 |
+
is_draggable = self._draggable is not None
|
| 1641 |
+
|
| 1642 |
+
# if state is None we'll toggle
|
| 1643 |
+
if state is None:
|
| 1644 |
+
state = not is_draggable
|
| 1645 |
+
|
| 1646 |
+
if state:
|
| 1647 |
+
if self._draggable is None:
|
| 1648 |
+
self._draggable = DraggableAnnotation(self, use_blit)
|
| 1649 |
+
else:
|
| 1650 |
+
if self._draggable is not None:
|
| 1651 |
+
self._draggable.disconnect()
|
| 1652 |
+
self._draggable = None
|
| 1653 |
+
|
| 1654 |
+
return self._draggable
|
| 1655 |
+
|
| 1656 |
+
|
| 1657 |
+
class Annotation(Text, _AnnotationBase):
|
| 1658 |
+
"""
|
| 1659 |
+
An `.Annotation` is a `.Text` that can refer to a specific position *xy*.
|
| 1660 |
+
Optionally an arrow pointing from the text to *xy* can be drawn.
|
| 1661 |
+
|
| 1662 |
+
Attributes
|
| 1663 |
+
----------
|
| 1664 |
+
xy
|
| 1665 |
+
The annotated position.
|
| 1666 |
+
xycoords
|
| 1667 |
+
The coordinate system for *xy*.
|
| 1668 |
+
arrow_patch
|
| 1669 |
+
A `.FancyArrowPatch` to point from *xytext* to *xy*.
|
| 1670 |
+
"""
|
| 1671 |
+
|
| 1672 |
+
def __str__(self):
|
| 1673 |
+
return "Annotation(%g, %g, %r)" % (self.xy[0], self.xy[1], self._text)
|
| 1674 |
+
|
| 1675 |
+
def __init__(self, text, xy,
|
| 1676 |
+
xytext=None,
|
| 1677 |
+
xycoords='data',
|
| 1678 |
+
textcoords=None,
|
| 1679 |
+
arrowprops=None,
|
| 1680 |
+
annotation_clip=None,
|
| 1681 |
+
**kwargs):
|
| 1682 |
+
"""
|
| 1683 |
+
Annotate the point *xy* with text *text*.
|
| 1684 |
+
|
| 1685 |
+
In the simplest form, the text is placed at *xy*.
|
| 1686 |
+
|
| 1687 |
+
Optionally, the text can be displayed in another position *xytext*.
|
| 1688 |
+
An arrow pointing from the text to the annotated point *xy* can then
|
| 1689 |
+
be added by defining *arrowprops*.
|
| 1690 |
+
|
| 1691 |
+
Parameters
|
| 1692 |
+
----------
|
| 1693 |
+
text : str
|
| 1694 |
+
The text of the annotation.
|
| 1695 |
+
|
| 1696 |
+
xy : (float, float)
|
| 1697 |
+
The point *(x, y)* to annotate. The coordinate system is determined
|
| 1698 |
+
by *xycoords*.
|
| 1699 |
+
|
| 1700 |
+
xytext : (float, float), default: *xy*
|
| 1701 |
+
The position *(x, y)* to place the text at. The coordinate system
|
| 1702 |
+
is determined by *textcoords*.
|
| 1703 |
+
|
| 1704 |
+
xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \
|
| 1705 |
+
callable, default: 'data'
|
| 1706 |
+
|
| 1707 |
+
The coordinate system that *xy* is given in. The following types
|
| 1708 |
+
of values are supported:
|
| 1709 |
+
|
| 1710 |
+
- One of the following strings:
|
| 1711 |
+
|
| 1712 |
+
==================== ============================================
|
| 1713 |
+
Value Description
|
| 1714 |
+
==================== ============================================
|
| 1715 |
+
'figure points' Points from the lower left of the figure
|
| 1716 |
+
'figure pixels' Pixels from the lower left of the figure
|
| 1717 |
+
'figure fraction' Fraction of figure from lower left
|
| 1718 |
+
'subfigure points' Points from the lower left of the subfigure
|
| 1719 |
+
'subfigure pixels' Pixels from the lower left of the subfigure
|
| 1720 |
+
'subfigure fraction' Fraction of subfigure from lower left
|
| 1721 |
+
'axes points' Points from lower left corner of axes
|
| 1722 |
+
'axes pixels' Pixels from lower left corner of axes
|
| 1723 |
+
'axes fraction' Fraction of axes from lower left
|
| 1724 |
+
'data' Use the coordinate system of the object
|
| 1725 |
+
being annotated (default)
|
| 1726 |
+
'polar' *(theta, r)* if not native 'data'
|
| 1727 |
+
coordinates
|
| 1728 |
+
==================== ============================================
|
| 1729 |
+
|
| 1730 |
+
Note that 'subfigure pixels' and 'figure pixels' are the same
|
| 1731 |
+
for the parent figure, so users who want code that is usable in
|
| 1732 |
+
a subfigure can use 'subfigure pixels'.
|
| 1733 |
+
|
| 1734 |
+
- An `.Artist`: *xy* is interpreted as a fraction of the artist's
|
| 1735 |
+
`~matplotlib.transforms.Bbox`. E.g. *(0, 0)* would be the lower
|
| 1736 |
+
left corner of the bounding box and *(0.5, 1)* would be the
|
| 1737 |
+
center top of the bounding box.
|
| 1738 |
+
|
| 1739 |
+
- A `.Transform` to transform *xy* to screen coordinates.
|
| 1740 |
+
|
| 1741 |
+
- A function with one of the following signatures::
|
| 1742 |
+
|
| 1743 |
+
def transform(renderer) -> Bbox
|
| 1744 |
+
def transform(renderer) -> Transform
|
| 1745 |
+
|
| 1746 |
+
where *renderer* is a `.RendererBase` subclass.
|
| 1747 |
+
|
| 1748 |
+
The result of the function is interpreted like the `.Artist` and
|
| 1749 |
+
`.Transform` cases above.
|
| 1750 |
+
|
| 1751 |
+
- A tuple *(xcoords, ycoords)* specifying separate coordinate
|
| 1752 |
+
systems for *x* and *y*. *xcoords* and *ycoords* must each be
|
| 1753 |
+
of one of the above described types.
|
| 1754 |
+
|
| 1755 |
+
See :ref:`plotting-guide-annotation` for more details.
|
| 1756 |
+
|
| 1757 |
+
textcoords : single or two-tuple of str or `.Artist` or `.Transform` \
|
| 1758 |
+
or callable, default: value of *xycoords*
|
| 1759 |
+
The coordinate system that *xytext* is given in.
|
| 1760 |
+
|
| 1761 |
+
All *xycoords* values are valid as well as the following
|
| 1762 |
+
strings:
|
| 1763 |
+
|
| 1764 |
+
================= =========================================
|
| 1765 |
+
Value Description
|
| 1766 |
+
================= =========================================
|
| 1767 |
+
'offset points' Offset (in points) from the *xy* value
|
| 1768 |
+
'offset pixels' Offset (in pixels) from the *xy* value
|
| 1769 |
+
================= =========================================
|
| 1770 |
+
|
| 1771 |
+
arrowprops : dict, optional
|
| 1772 |
+
The properties used to draw a `.FancyArrowPatch` arrow between the
|
| 1773 |
+
positions *xy* and *xytext*. Defaults to None, i.e. no arrow is
|
| 1774 |
+
drawn.
|
| 1775 |
+
|
| 1776 |
+
For historical reasons there are two different ways to specify
|
| 1777 |
+
arrows, "simple" and "fancy":
|
| 1778 |
+
|
| 1779 |
+
**Simple arrow:**
|
| 1780 |
+
|
| 1781 |
+
If *arrowprops* does not contain the key 'arrowstyle' the
|
| 1782 |
+
allowed keys are:
|
| 1783 |
+
|
| 1784 |
+
========== ======================================================
|
| 1785 |
+
Key Description
|
| 1786 |
+
========== ======================================================
|
| 1787 |
+
width The width of the arrow in points
|
| 1788 |
+
headwidth The width of the base of the arrow head in points
|
| 1789 |
+
headlength The length of the arrow head in points
|
| 1790 |
+
shrink Fraction of total length to shrink from both ends
|
| 1791 |
+
? Any key to :class:`matplotlib.patches.FancyArrowPatch`
|
| 1792 |
+
========== ======================================================
|
| 1793 |
+
|
| 1794 |
+
The arrow is attached to the edge of the text box, the exact
|
| 1795 |
+
position (corners or centers) depending on where it's pointing to.
|
| 1796 |
+
|
| 1797 |
+
**Fancy arrow:**
|
| 1798 |
+
|
| 1799 |
+
This is used if 'arrowstyle' is provided in the *arrowprops*.
|
| 1800 |
+
|
| 1801 |
+
Valid keys are the following `~matplotlib.patches.FancyArrowPatch`
|
| 1802 |
+
parameters:
|
| 1803 |
+
|
| 1804 |
+
=============== ==================================================
|
| 1805 |
+
Key Description
|
| 1806 |
+
=============== ==================================================
|
| 1807 |
+
arrowstyle the arrow style
|
| 1808 |
+
connectionstyle the connection style
|
| 1809 |
+
relpos see below; default is (0.5, 0.5)
|
| 1810 |
+
patchA default is bounding box of the text
|
| 1811 |
+
patchB default is None
|
| 1812 |
+
shrinkA default is 2 points
|
| 1813 |
+
shrinkB default is 2 points
|
| 1814 |
+
mutation_scale default is text size (in points)
|
| 1815 |
+
mutation_aspect default is 1.
|
| 1816 |
+
? any key for :class:`matplotlib.patches.PathPatch`
|
| 1817 |
+
=============== ==================================================
|
| 1818 |
+
|
| 1819 |
+
The exact starting point position of the arrow is defined by
|
| 1820 |
+
*relpos*. It's a tuple of relative coordinates of the text box,
|
| 1821 |
+
where (0, 0) is the lower left corner and (1, 1) is the upper
|
| 1822 |
+
right corner. Values <0 and >1 are supported and specify points
|
| 1823 |
+
outside the text box. By default (0.5, 0.5), so the starting point
|
| 1824 |
+
is centered in the text box.
|
| 1825 |
+
|
| 1826 |
+
annotation_clip : bool or None, default: None
|
| 1827 |
+
Whether to clip (i.e. not draw) the annotation when the annotation
|
| 1828 |
+
point *xy* is outside the axes area.
|
| 1829 |
+
|
| 1830 |
+
- If *True*, the annotation will be clipped when *xy* is outside
|
| 1831 |
+
the axes.
|
| 1832 |
+
- If *False*, the annotation will always be drawn.
|
| 1833 |
+
- If *None*, the annotation will be clipped when *xy* is outside
|
| 1834 |
+
the axes and *xycoords* is 'data'.
|
| 1835 |
+
|
| 1836 |
+
**kwargs
|
| 1837 |
+
Additional kwargs are passed to `~matplotlib.text.Text`.
|
| 1838 |
+
|
| 1839 |
+
Returns
|
| 1840 |
+
-------
|
| 1841 |
+
`.Annotation`
|
| 1842 |
+
|
| 1843 |
+
See Also
|
| 1844 |
+
--------
|
| 1845 |
+
:ref:`plotting-guide-annotation`
|
| 1846 |
+
|
| 1847 |
+
"""
|
| 1848 |
+
_AnnotationBase.__init__(self,
|
| 1849 |
+
xy,
|
| 1850 |
+
xycoords=xycoords,
|
| 1851 |
+
annotation_clip=annotation_clip)
|
| 1852 |
+
# warn about wonky input data
|
| 1853 |
+
if (xytext is None and
|
| 1854 |
+
textcoords is not None and
|
| 1855 |
+
textcoords != xycoords):
|
| 1856 |
+
_api.warn_external("You have used the `textcoords` kwarg, but "
|
| 1857 |
+
"not the `xytext` kwarg. This can lead to "
|
| 1858 |
+
"surprising results.")
|
| 1859 |
+
|
| 1860 |
+
# clean up textcoords and assign default
|
| 1861 |
+
if textcoords is None:
|
| 1862 |
+
textcoords = self.xycoords
|
| 1863 |
+
self._textcoords = textcoords
|
| 1864 |
+
|
| 1865 |
+
# cleanup xytext defaults
|
| 1866 |
+
if xytext is None:
|
| 1867 |
+
xytext = self.xy
|
| 1868 |
+
x, y = xytext
|
| 1869 |
+
|
| 1870 |
+
self.arrowprops = arrowprops
|
| 1871 |
+
if arrowprops is not None:
|
| 1872 |
+
arrowprops = arrowprops.copy()
|
| 1873 |
+
if "arrowstyle" in arrowprops:
|
| 1874 |
+
self._arrow_relpos = arrowprops.pop("relpos", (0.5, 0.5))
|
| 1875 |
+
else:
|
| 1876 |
+
# modified YAArrow API to be used with FancyArrowPatch
|
| 1877 |
+
for key in [
|
| 1878 |
+
'width', 'headwidth', 'headlength', 'shrink', 'frac']:
|
| 1879 |
+
arrowprops.pop(key, None)
|
| 1880 |
+
self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), **arrowprops)
|
| 1881 |
+
else:
|
| 1882 |
+
self.arrow_patch = None
|
| 1883 |
+
|
| 1884 |
+
# Must come last, as some kwargs may be propagated to arrow_patch.
|
| 1885 |
+
Text.__init__(self, x, y, text, **kwargs)
|
| 1886 |
+
|
| 1887 |
+
def contains(self, event):
|
| 1888 |
+
inside, info = self._default_contains(event)
|
| 1889 |
+
if inside is not None:
|
| 1890 |
+
return inside, info
|
| 1891 |
+
contains, tinfo = Text.contains(self, event)
|
| 1892 |
+
if self.arrow_patch is not None:
|
| 1893 |
+
in_patch, _ = self.arrow_patch.contains(event)
|
| 1894 |
+
contains = contains or in_patch
|
| 1895 |
+
return contains, tinfo
|
| 1896 |
+
|
| 1897 |
+
@property
|
| 1898 |
+
def xycoords(self):
|
| 1899 |
+
return self._xycoords
|
| 1900 |
+
|
| 1901 |
+
@xycoords.setter
|
| 1902 |
+
def xycoords(self, xycoords):
|
| 1903 |
+
def is_offset(s):
|
| 1904 |
+
return isinstance(s, str) and s.startswith("offset")
|
| 1905 |
+
|
| 1906 |
+
if (isinstance(xycoords, tuple) and any(map(is_offset, xycoords))
|
| 1907 |
+
or is_offset(xycoords)):
|
| 1908 |
+
raise ValueError("xycoords cannot be an offset coordinate")
|
| 1909 |
+
self._xycoords = xycoords
|
| 1910 |
+
|
| 1911 |
+
@property
|
| 1912 |
+
def xyann(self):
|
| 1913 |
+
"""
|
| 1914 |
+
The text position.
|
| 1915 |
+
|
| 1916 |
+
See also *xytext* in `.Annotation`.
|
| 1917 |
+
"""
|
| 1918 |
+
return self.get_position()
|
| 1919 |
+
|
| 1920 |
+
@xyann.setter
|
| 1921 |
+
def xyann(self, xytext):
|
| 1922 |
+
self.set_position(xytext)
|
| 1923 |
+
|
| 1924 |
+
def get_anncoords(self):
|
| 1925 |
+
"""
|
| 1926 |
+
Return the coordinate system to use for `.Annotation.xyann`.
|
| 1927 |
+
|
| 1928 |
+
See also *xycoords* in `.Annotation`.
|
| 1929 |
+
"""
|
| 1930 |
+
return self._textcoords
|
| 1931 |
+
|
| 1932 |
+
def set_anncoords(self, coords):
|
| 1933 |
+
"""
|
| 1934 |
+
Set the coordinate system to use for `.Annotation.xyann`.
|
| 1935 |
+
|
| 1936 |
+
See also *xycoords* in `.Annotation`.
|
| 1937 |
+
"""
|
| 1938 |
+
self._textcoords = coords
|
| 1939 |
+
|
| 1940 |
+
anncoords = property(get_anncoords, set_anncoords, doc="""
|
| 1941 |
+
The coordinate system to use for `.Annotation.xyann`.""")
|
| 1942 |
+
|
| 1943 |
+
def set_figure(self, fig):
|
| 1944 |
+
# docstring inherited
|
| 1945 |
+
if self.arrow_patch is not None:
|
| 1946 |
+
self.arrow_patch.set_figure(fig)
|
| 1947 |
+
Artist.set_figure(self, fig)
|
| 1948 |
+
|
| 1949 |
+
def update_positions(self, renderer):
|
| 1950 |
+
"""
|
| 1951 |
+
Update the pixel positions of the annotation text and the arrow patch.
|
| 1952 |
+
"""
|
| 1953 |
+
# generate transformation
|
| 1954 |
+
self.set_transform(self._get_xy_transform(renderer, self.anncoords))
|
| 1955 |
+
|
| 1956 |
+
arrowprops = self.arrowprops
|
| 1957 |
+
if arrowprops is None:
|
| 1958 |
+
return
|
| 1959 |
+
|
| 1960 |
+
bbox = Text.get_window_extent(self, renderer)
|
| 1961 |
+
|
| 1962 |
+
arrow_end = x1, y1 = self._get_position_xy(renderer) # Annotated pos.
|
| 1963 |
+
|
| 1964 |
+
ms = arrowprops.get("mutation_scale", self.get_size())
|
| 1965 |
+
self.arrow_patch.set_mutation_scale(ms)
|
| 1966 |
+
|
| 1967 |
+
if "arrowstyle" not in arrowprops:
|
| 1968 |
+
# Approximately simulate the YAArrow.
|
| 1969 |
+
shrink = arrowprops.get('shrink', 0.0)
|
| 1970 |
+
width = arrowprops.get('width', 4)
|
| 1971 |
+
headwidth = arrowprops.get('headwidth', 12)
|
| 1972 |
+
if 'frac' in arrowprops:
|
| 1973 |
+
_api.warn_external(
|
| 1974 |
+
"'frac' option in 'arrowprops' is no longer supported;"
|
| 1975 |
+
" use 'headlength' to set the head length in points.")
|
| 1976 |
+
headlength = arrowprops.get('headlength', 12)
|
| 1977 |
+
|
| 1978 |
+
# NB: ms is in pts
|
| 1979 |
+
stylekw = dict(head_length=headlength / ms,
|
| 1980 |
+
head_width=headwidth / ms,
|
| 1981 |
+
tail_width=width / ms)
|
| 1982 |
+
|
| 1983 |
+
self.arrow_patch.set_arrowstyle('simple', **stylekw)
|
| 1984 |
+
|
| 1985 |
+
# using YAArrow style:
|
| 1986 |
+
# pick the corner of the text bbox closest to annotated point.
|
| 1987 |
+
xpos = [(bbox.x0, 0), ((bbox.x0 + bbox.x1) / 2, 0.5), (bbox.x1, 1)]
|
| 1988 |
+
ypos = [(bbox.y0, 0), ((bbox.y0 + bbox.y1) / 2, 0.5), (bbox.y1, 1)]
|
| 1989 |
+
x, relposx = min(xpos, key=lambda v: abs(v[0] - x1))
|
| 1990 |
+
y, relposy = min(ypos, key=lambda v: abs(v[0] - y1))
|
| 1991 |
+
self._arrow_relpos = (relposx, relposy)
|
| 1992 |
+
r = np.hypot(y - y1, x - x1)
|
| 1993 |
+
shrink_pts = shrink * r / renderer.points_to_pixels(1)
|
| 1994 |
+
self.arrow_patch.shrinkA = self.arrow_patch.shrinkB = shrink_pts
|
| 1995 |
+
|
| 1996 |
+
# adjust the starting point of the arrow relative to the textbox.
|
| 1997 |
+
# TODO : Rotation needs to be accounted.
|
| 1998 |
+
arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos
|
| 1999 |
+
# The arrow is drawn from arrow_begin to arrow_end. It will be first
|
| 2000 |
+
# clipped by patchA and patchB. Then it will be shrunk by shrinkA and
|
| 2001 |
+
# shrinkB (in points). If patchA is not set, self.bbox_patch is used.
|
| 2002 |
+
self.arrow_patch.set_positions(arrow_begin, arrow_end)
|
| 2003 |
+
|
| 2004 |
+
if "patchA" in arrowprops:
|
| 2005 |
+
patchA = arrowprops["patchA"]
|
| 2006 |
+
elif self._bbox_patch:
|
| 2007 |
+
patchA = self._bbox_patch
|
| 2008 |
+
elif self.get_text() == "":
|
| 2009 |
+
patchA = None
|
| 2010 |
+
else:
|
| 2011 |
+
pad = renderer.points_to_pixels(4)
|
| 2012 |
+
patchA = Rectangle(
|
| 2013 |
+
xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2),
|
| 2014 |
+
width=bbox.width + pad, height=bbox.height + pad,
|
| 2015 |
+
transform=IdentityTransform(), clip_on=False)
|
| 2016 |
+
self.arrow_patch.set_patchA(patchA)
|
| 2017 |
+
|
| 2018 |
+
@artist.allow_rasterization
|
| 2019 |
+
def draw(self, renderer):
|
| 2020 |
+
# docstring inherited
|
| 2021 |
+
if renderer is not None:
|
| 2022 |
+
self._renderer = renderer
|
| 2023 |
+
if not self.get_visible() or not self._check_xy(renderer):
|
| 2024 |
+
return
|
| 2025 |
+
# Update text positions before `Text.draw` would, so that the
|
| 2026 |
+
# FancyArrowPatch is correctly positioned.
|
| 2027 |
+
self.update_positions(renderer)
|
| 2028 |
+
self.update_bbox_position_size(renderer)
|
| 2029 |
+
if self.arrow_patch is not None: # FancyArrowPatch
|
| 2030 |
+
if self.arrow_patch.figure is None and self.figure is not None:
|
| 2031 |
+
self.arrow_patch.figure = self.figure
|
| 2032 |
+
self.arrow_patch.draw(renderer)
|
| 2033 |
+
# Draw text, including FancyBboxPatch, after FancyArrowPatch.
|
| 2034 |
+
# Otherwise, a wedge arrowstyle can land partly on top of the Bbox.
|
| 2035 |
+
Text.draw(self, renderer)
|
| 2036 |
+
|
| 2037 |
+
def get_window_extent(self, renderer=None):
|
| 2038 |
+
# docstring inherited
|
| 2039 |
+
# This block is the same as in Text.get_window_extent, but we need to
|
| 2040 |
+
# set the renderer before calling update_positions().
|
| 2041 |
+
if not self.get_visible() or not self._check_xy(renderer):
|
| 2042 |
+
return Bbox.unit()
|
| 2043 |
+
if renderer is not None:
|
| 2044 |
+
self._renderer = renderer
|
| 2045 |
+
if self._renderer is None:
|
| 2046 |
+
self._renderer = self.figure._get_renderer()
|
| 2047 |
+
if self._renderer is None:
|
| 2048 |
+
raise RuntimeError('Cannot get window extent w/o renderer')
|
| 2049 |
+
|
| 2050 |
+
self.update_positions(self._renderer)
|
| 2051 |
+
|
| 2052 |
+
text_bbox = Text.get_window_extent(self)
|
| 2053 |
+
bboxes = [text_bbox]
|
| 2054 |
+
|
| 2055 |
+
if self.arrow_patch is not None:
|
| 2056 |
+
bboxes.append(self.arrow_patch.get_window_extent())
|
| 2057 |
+
|
| 2058 |
+
return Bbox.union(bboxes)
|
| 2059 |
+
|
| 2060 |
+
def get_tightbbox(self, renderer=None):
|
| 2061 |
+
# docstring inherited
|
| 2062 |
+
if not self._check_xy(renderer):
|
| 2063 |
+
return Bbox.null()
|
| 2064 |
+
return super().get_tightbbox(renderer)
|
| 2065 |
+
|
| 2066 |
+
|
| 2067 |
+
_docstring.interpd.update(Annotation=Annotation.__init__.__doc__)
|
omnilmm/lib/python3.10/site-packages/matplotlib/textpath.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
import logging
|
| 3 |
+
import urllib.parse
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from matplotlib import _api, _text_helpers, dviread
|
| 8 |
+
from matplotlib.font_manager import (
|
| 9 |
+
FontProperties, get_font, fontManager as _fontManager
|
| 10 |
+
)
|
| 11 |
+
from matplotlib.ft2font import LOAD_NO_HINTING, LOAD_TARGET_LIGHT
|
| 12 |
+
from matplotlib.mathtext import MathTextParser
|
| 13 |
+
from matplotlib.path import Path
|
| 14 |
+
from matplotlib.texmanager import TexManager
|
| 15 |
+
from matplotlib.transforms import Affine2D
|
| 16 |
+
|
| 17 |
+
_log = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TextToPath:
|
| 21 |
+
"""A class that converts strings to paths."""
|
| 22 |
+
|
| 23 |
+
FONT_SCALE = 100.
|
| 24 |
+
DPI = 72
|
| 25 |
+
|
| 26 |
+
def __init__(self):
|
| 27 |
+
self.mathtext_parser = MathTextParser('path')
|
| 28 |
+
self._texmanager = None
|
| 29 |
+
|
| 30 |
+
def _get_font(self, prop):
|
| 31 |
+
"""
|
| 32 |
+
Find the `FT2Font` matching font properties *prop*, with its size set.
|
| 33 |
+
"""
|
| 34 |
+
filenames = _fontManager._find_fonts_by_props(prop)
|
| 35 |
+
font = get_font(filenames)
|
| 36 |
+
font.set_size(self.FONT_SCALE, self.DPI)
|
| 37 |
+
return font
|
| 38 |
+
|
| 39 |
+
def _get_hinting_flag(self):
|
| 40 |
+
return LOAD_NO_HINTING
|
| 41 |
+
|
| 42 |
+
def _get_char_id(self, font, ccode):
|
| 43 |
+
"""
|
| 44 |
+
Return a unique id for the given font and character-code set.
|
| 45 |
+
"""
|
| 46 |
+
return urllib.parse.quote(f"{font.postscript_name}-{ccode:x}")
|
| 47 |
+
|
| 48 |
+
def get_text_width_height_descent(self, s, prop, ismath):
|
| 49 |
+
fontsize = prop.get_size_in_points()
|
| 50 |
+
|
| 51 |
+
if ismath == "TeX":
|
| 52 |
+
return TexManager().get_text_width_height_descent(s, fontsize)
|
| 53 |
+
|
| 54 |
+
scale = fontsize / self.FONT_SCALE
|
| 55 |
+
|
| 56 |
+
if ismath:
|
| 57 |
+
prop = prop.copy()
|
| 58 |
+
prop.set_size(self.FONT_SCALE)
|
| 59 |
+
width, height, descent, *_ = \
|
| 60 |
+
self.mathtext_parser.parse(s, 72, prop)
|
| 61 |
+
return width * scale, height * scale, descent * scale
|
| 62 |
+
|
| 63 |
+
font = self._get_font(prop)
|
| 64 |
+
font.set_text(s, 0.0, flags=LOAD_NO_HINTING)
|
| 65 |
+
w, h = font.get_width_height()
|
| 66 |
+
w /= 64.0 # convert from subpixels
|
| 67 |
+
h /= 64.0
|
| 68 |
+
d = font.get_descent()
|
| 69 |
+
d /= 64.0
|
| 70 |
+
return w * scale, h * scale, d * scale
|
| 71 |
+
|
| 72 |
+
def get_text_path(self, prop, s, ismath=False):
|
| 73 |
+
"""
|
| 74 |
+
Convert text *s* to path (a tuple of vertices and codes for
|
| 75 |
+
matplotlib.path.Path).
|
| 76 |
+
|
| 77 |
+
Parameters
|
| 78 |
+
----------
|
| 79 |
+
prop : `~matplotlib.font_manager.FontProperties`
|
| 80 |
+
The font properties for the text.
|
| 81 |
+
|
| 82 |
+
s : str
|
| 83 |
+
The text to be converted.
|
| 84 |
+
|
| 85 |
+
ismath : {False, True, "TeX"}
|
| 86 |
+
If True, use mathtext parser. If "TeX", use tex for rendering.
|
| 87 |
+
|
| 88 |
+
Returns
|
| 89 |
+
-------
|
| 90 |
+
verts : list
|
| 91 |
+
A list of numpy arrays containing the x and y coordinates of the
|
| 92 |
+
vertices.
|
| 93 |
+
|
| 94 |
+
codes : list
|
| 95 |
+
A list of path codes.
|
| 96 |
+
|
| 97 |
+
Examples
|
| 98 |
+
--------
|
| 99 |
+
Create a list of vertices and codes from a text, and create a `.Path`
|
| 100 |
+
from those::
|
| 101 |
+
|
| 102 |
+
from matplotlib.path import Path
|
| 103 |
+
from matplotlib.text import TextToPath
|
| 104 |
+
from matplotlib.font_manager import FontProperties
|
| 105 |
+
|
| 106 |
+
fp = FontProperties(family="Humor Sans", style="italic")
|
| 107 |
+
verts, codes = TextToPath().get_text_path(fp, "ABC")
|
| 108 |
+
path = Path(verts, codes, closed=False)
|
| 109 |
+
|
| 110 |
+
Also see `TextPath` for a more direct way to create a path from a text.
|
| 111 |
+
"""
|
| 112 |
+
if ismath == "TeX":
|
| 113 |
+
glyph_info, glyph_map, rects = self.get_glyphs_tex(prop, s)
|
| 114 |
+
elif not ismath:
|
| 115 |
+
font = self._get_font(prop)
|
| 116 |
+
glyph_info, glyph_map, rects = self.get_glyphs_with_font(font, s)
|
| 117 |
+
else:
|
| 118 |
+
glyph_info, glyph_map, rects = self.get_glyphs_mathtext(prop, s)
|
| 119 |
+
|
| 120 |
+
verts, codes = [], []
|
| 121 |
+
for glyph_id, xposition, yposition, scale in glyph_info:
|
| 122 |
+
verts1, codes1 = glyph_map[glyph_id]
|
| 123 |
+
verts.extend(verts1 * scale + [xposition, yposition])
|
| 124 |
+
codes.extend(codes1)
|
| 125 |
+
for verts1, codes1 in rects:
|
| 126 |
+
verts.extend(verts1)
|
| 127 |
+
codes.extend(codes1)
|
| 128 |
+
|
| 129 |
+
# Make sure an empty string or one with nothing to print
|
| 130 |
+
# (e.g. only spaces & newlines) will be valid/empty path
|
| 131 |
+
if not verts:
|
| 132 |
+
verts = np.empty((0, 2))
|
| 133 |
+
|
| 134 |
+
return verts, codes
|
| 135 |
+
|
| 136 |
+
def get_glyphs_with_font(self, font, s, glyph_map=None,
|
| 137 |
+
return_new_glyphs_only=False):
|
| 138 |
+
"""
|
| 139 |
+
Convert string *s* to vertices and codes using the provided ttf font.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
if glyph_map is None:
|
| 143 |
+
glyph_map = OrderedDict()
|
| 144 |
+
|
| 145 |
+
if return_new_glyphs_only:
|
| 146 |
+
glyph_map_new = OrderedDict()
|
| 147 |
+
else:
|
| 148 |
+
glyph_map_new = glyph_map
|
| 149 |
+
|
| 150 |
+
xpositions = []
|
| 151 |
+
glyph_ids = []
|
| 152 |
+
for item in _text_helpers.layout(s, font):
|
| 153 |
+
char_id = self._get_char_id(item.ft_object, ord(item.char))
|
| 154 |
+
glyph_ids.append(char_id)
|
| 155 |
+
xpositions.append(item.x)
|
| 156 |
+
if char_id not in glyph_map:
|
| 157 |
+
glyph_map_new[char_id] = item.ft_object.get_path()
|
| 158 |
+
|
| 159 |
+
ypositions = [0] * len(xpositions)
|
| 160 |
+
sizes = [1.] * len(xpositions)
|
| 161 |
+
|
| 162 |
+
rects = []
|
| 163 |
+
|
| 164 |
+
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
|
| 165 |
+
glyph_map_new, rects)
|
| 166 |
+
|
| 167 |
+
def get_glyphs_mathtext(self, prop, s, glyph_map=None,
|
| 168 |
+
return_new_glyphs_only=False):
|
| 169 |
+
"""
|
| 170 |
+
Parse mathtext string *s* and convert it to a (vertices, codes) pair.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
prop = prop.copy()
|
| 174 |
+
prop.set_size(self.FONT_SCALE)
|
| 175 |
+
|
| 176 |
+
width, height, descent, glyphs, rects = self.mathtext_parser.parse(
|
| 177 |
+
s, self.DPI, prop)
|
| 178 |
+
|
| 179 |
+
if not glyph_map:
|
| 180 |
+
glyph_map = OrderedDict()
|
| 181 |
+
|
| 182 |
+
if return_new_glyphs_only:
|
| 183 |
+
glyph_map_new = OrderedDict()
|
| 184 |
+
else:
|
| 185 |
+
glyph_map_new = glyph_map
|
| 186 |
+
|
| 187 |
+
xpositions = []
|
| 188 |
+
ypositions = []
|
| 189 |
+
glyph_ids = []
|
| 190 |
+
sizes = []
|
| 191 |
+
|
| 192 |
+
for font, fontsize, ccode, ox, oy in glyphs:
|
| 193 |
+
char_id = self._get_char_id(font, ccode)
|
| 194 |
+
if char_id not in glyph_map:
|
| 195 |
+
font.clear()
|
| 196 |
+
font.set_size(self.FONT_SCALE, self.DPI)
|
| 197 |
+
font.load_char(ccode, flags=LOAD_NO_HINTING)
|
| 198 |
+
glyph_map_new[char_id] = font.get_path()
|
| 199 |
+
|
| 200 |
+
xpositions.append(ox)
|
| 201 |
+
ypositions.append(oy)
|
| 202 |
+
glyph_ids.append(char_id)
|
| 203 |
+
size = fontsize / self.FONT_SCALE
|
| 204 |
+
sizes.append(size)
|
| 205 |
+
|
| 206 |
+
myrects = []
|
| 207 |
+
for ox, oy, w, h in rects:
|
| 208 |
+
vert1 = [(ox, oy), (ox, oy + h), (ox + w, oy + h),
|
| 209 |
+
(ox + w, oy), (ox, oy), (0, 0)]
|
| 210 |
+
code1 = [Path.MOVETO,
|
| 211 |
+
Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
|
| 212 |
+
Path.CLOSEPOLY]
|
| 213 |
+
myrects.append((vert1, code1))
|
| 214 |
+
|
| 215 |
+
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
|
| 216 |
+
glyph_map_new, myrects)
|
| 217 |
+
|
| 218 |
+
@_api.deprecated("3.6", alternative="TexManager()")
|
| 219 |
+
def get_texmanager(self):
|
| 220 |
+
"""Return the cached `~.texmanager.TexManager` instance."""
|
| 221 |
+
if self._texmanager is None:
|
| 222 |
+
self._texmanager = TexManager()
|
| 223 |
+
return self._texmanager
|
| 224 |
+
|
| 225 |
+
def get_glyphs_tex(self, prop, s, glyph_map=None,
|
| 226 |
+
return_new_glyphs_only=False):
|
| 227 |
+
"""Convert the string *s* to vertices and codes using usetex mode."""
|
| 228 |
+
# Mostly borrowed from pdf backend.
|
| 229 |
+
|
| 230 |
+
dvifile = TexManager().make_dvi(s, self.FONT_SCALE)
|
| 231 |
+
with dviread.Dvi(dvifile, self.DPI) as dvi:
|
| 232 |
+
page, = dvi
|
| 233 |
+
|
| 234 |
+
if glyph_map is None:
|
| 235 |
+
glyph_map = OrderedDict()
|
| 236 |
+
|
| 237 |
+
if return_new_glyphs_only:
|
| 238 |
+
glyph_map_new = OrderedDict()
|
| 239 |
+
else:
|
| 240 |
+
glyph_map_new = glyph_map
|
| 241 |
+
|
| 242 |
+
glyph_ids, xpositions, ypositions, sizes = [], [], [], []
|
| 243 |
+
|
| 244 |
+
# Gather font information and do some setup for combining
|
| 245 |
+
# characters into strings.
|
| 246 |
+
for text in page.text:
|
| 247 |
+
font = get_font(text.font_path)
|
| 248 |
+
char_id = self._get_char_id(font, text.glyph)
|
| 249 |
+
if char_id not in glyph_map:
|
| 250 |
+
font.clear()
|
| 251 |
+
font.set_size(self.FONT_SCALE, self.DPI)
|
| 252 |
+
glyph_name_or_index = text.glyph_name_or_index
|
| 253 |
+
if isinstance(glyph_name_or_index, str):
|
| 254 |
+
index = font.get_name_index(glyph_name_or_index)
|
| 255 |
+
font.load_glyph(index, flags=LOAD_TARGET_LIGHT)
|
| 256 |
+
elif isinstance(glyph_name_or_index, int):
|
| 257 |
+
self._select_native_charmap(font)
|
| 258 |
+
font.load_char(
|
| 259 |
+
glyph_name_or_index, flags=LOAD_TARGET_LIGHT)
|
| 260 |
+
else: # Should not occur.
|
| 261 |
+
raise TypeError(f"Glyph spec of unexpected type: "
|
| 262 |
+
f"{glyph_name_or_index!r}")
|
| 263 |
+
glyph_map_new[char_id] = font.get_path()
|
| 264 |
+
|
| 265 |
+
glyph_ids.append(char_id)
|
| 266 |
+
xpositions.append(text.x)
|
| 267 |
+
ypositions.append(text.y)
|
| 268 |
+
sizes.append(text.font_size / self.FONT_SCALE)
|
| 269 |
+
|
| 270 |
+
myrects = []
|
| 271 |
+
|
| 272 |
+
for ox, oy, h, w in page.boxes:
|
| 273 |
+
vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h),
|
| 274 |
+
(ox, oy + h), (ox, oy), (0, 0)]
|
| 275 |
+
code1 = [Path.MOVETO,
|
| 276 |
+
Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
|
| 277 |
+
Path.CLOSEPOLY]
|
| 278 |
+
myrects.append((vert1, code1))
|
| 279 |
+
|
| 280 |
+
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
|
| 281 |
+
glyph_map_new, myrects)
|
| 282 |
+
|
| 283 |
+
@staticmethod
|
| 284 |
+
def _select_native_charmap(font):
|
| 285 |
+
# Select the native charmap. (we can't directly identify it but it's
|
| 286 |
+
# typically an Adobe charmap).
|
| 287 |
+
for charmap_code in [
|
| 288 |
+
1094992451, # ADOBE_CUSTOM.
|
| 289 |
+
1094995778, # ADOBE_STANDARD.
|
| 290 |
+
]:
|
| 291 |
+
try:
|
| 292 |
+
font.select_charmap(charmap_code)
|
| 293 |
+
except (ValueError, RuntimeError):
|
| 294 |
+
pass
|
| 295 |
+
else:
|
| 296 |
+
break
|
| 297 |
+
else:
|
| 298 |
+
_log.warning("No supported encoding in font (%s).", font.fname)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
text_to_path = TextToPath()
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class TextPath(Path):
|
| 305 |
+
"""
|
| 306 |
+
Create a path from the text.
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
def __init__(self, xy, s, size=None, prop=None,
|
| 310 |
+
_interpolation_steps=1, usetex=False):
|
| 311 |
+
r"""
|
| 312 |
+
Create a path from the text. Note that it simply is a path,
|
| 313 |
+
not an artist. You need to use the `.PathPatch` (or other artists)
|
| 314 |
+
to draw this path onto the canvas.
|
| 315 |
+
|
| 316 |
+
Parameters
|
| 317 |
+
----------
|
| 318 |
+
xy : tuple or array of two float values
|
| 319 |
+
Position of the text. For no offset, use ``xy=(0, 0)``.
|
| 320 |
+
|
| 321 |
+
s : str
|
| 322 |
+
The text to convert to a path.
|
| 323 |
+
|
| 324 |
+
size : float, optional
|
| 325 |
+
Font size in points. Defaults to the size specified via the font
|
| 326 |
+
properties *prop*.
|
| 327 |
+
|
| 328 |
+
prop : `~matplotlib.font_manager.FontProperties`, optional
|
| 329 |
+
Font property. If not provided, will use a default
|
| 330 |
+
`.FontProperties` with parameters from the
|
| 331 |
+
:ref:`rcParams<customizing-with-dynamic-rc-settings>`.
|
| 332 |
+
|
| 333 |
+
_interpolation_steps : int, optional
|
| 334 |
+
(Currently ignored)
|
| 335 |
+
|
| 336 |
+
usetex : bool, default: False
|
| 337 |
+
Whether to use tex rendering.
|
| 338 |
+
|
| 339 |
+
Examples
|
| 340 |
+
--------
|
| 341 |
+
The following creates a path from the string "ABC" with Helvetica
|
| 342 |
+
font face; and another path from the latex fraction 1/2::
|
| 343 |
+
|
| 344 |
+
from matplotlib.text import TextPath
|
| 345 |
+
from matplotlib.font_manager import FontProperties
|
| 346 |
+
|
| 347 |
+
fp = FontProperties(family="Helvetica", style="italic")
|
| 348 |
+
path1 = TextPath((12, 12), "ABC", size=12, prop=fp)
|
| 349 |
+
path2 = TextPath((0, 0), r"$\frac{1}{2}$", size=12, usetex=True)
|
| 350 |
+
|
| 351 |
+
Also see :doc:`/gallery/text_labels_and_annotations/demo_text_path`.
|
| 352 |
+
"""
|
| 353 |
+
# Circular import.
|
| 354 |
+
from matplotlib.text import Text
|
| 355 |
+
|
| 356 |
+
prop = FontProperties._from_any(prop)
|
| 357 |
+
if size is None:
|
| 358 |
+
size = prop.get_size_in_points()
|
| 359 |
+
|
| 360 |
+
self._xy = xy
|
| 361 |
+
self.set_size(size)
|
| 362 |
+
|
| 363 |
+
self._cached_vertices = None
|
| 364 |
+
s, ismath = Text(usetex=usetex)._preprocess_math(s)
|
| 365 |
+
super().__init__(
|
| 366 |
+
*text_to_path.get_text_path(prop, s, ismath=ismath),
|
| 367 |
+
_interpolation_steps=_interpolation_steps,
|
| 368 |
+
readonly=True)
|
| 369 |
+
self._should_simplify = False
|
| 370 |
+
|
| 371 |
+
def set_size(self, size):
|
| 372 |
+
"""Set the text size."""
|
| 373 |
+
self._size = size
|
| 374 |
+
self._invalid = True
|
| 375 |
+
|
| 376 |
+
def get_size(self):
|
| 377 |
+
"""Get the text size."""
|
| 378 |
+
return self._size
|
| 379 |
+
|
| 380 |
+
@property
|
| 381 |
+
def vertices(self):
|
| 382 |
+
"""
|
| 383 |
+
Return the cached path after updating it if necessary.
|
| 384 |
+
"""
|
| 385 |
+
self._revalidate_path()
|
| 386 |
+
return self._cached_vertices
|
| 387 |
+
|
| 388 |
+
@property
|
| 389 |
+
def codes(self):
|
| 390 |
+
"""
|
| 391 |
+
Return the codes
|
| 392 |
+
"""
|
| 393 |
+
return self._codes
|
| 394 |
+
|
| 395 |
+
def _revalidate_path(self):
|
| 396 |
+
"""
|
| 397 |
+
Update the path if necessary.
|
| 398 |
+
|
| 399 |
+
The path for the text is initially create with the font size of
|
| 400 |
+
`.FONT_SCALE`, and this path is rescaled to other size when necessary.
|
| 401 |
+
"""
|
| 402 |
+
if self._invalid or self._cached_vertices is None:
|
| 403 |
+
tr = (Affine2D()
|
| 404 |
+
.scale(self._size / text_to_path.FONT_SCALE)
|
| 405 |
+
.translate(*self._xy))
|
| 406 |
+
self._cached_vertices = tr.transform(self._vertices)
|
| 407 |
+
self._cached_vertices.flags.writeable = False
|
| 408 |
+
self._invalid = False
|
omnilmm/lib/python3.10/site-packages/matplotlib/widgets.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
omnilmm/lib/python3.10/site-packages/pkg_resources/__init__.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
omnilmm/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:191fd421685d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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Pluggable Distributions of Python Software
|
| 2 |
+
==========================================
|
| 3 |
+
|
| 4 |
+
Distributions
|
| 5 |
+
-------------
|
| 6 |
+
|
| 7 |
+
A "Distribution" is a collection of files that represent a "Release" of a
|
| 8 |
+
"Project" as of a particular point in time, denoted by a
|
| 9 |
+
"Version"::
|
| 10 |
+
|
| 11 |
+
>>> import sys, pkg_resources
|
| 12 |
+
>>> from pkg_resources import Distribution
|
| 13 |
+
>>> Distribution(project_name="Foo", version="1.2")
|
| 14 |
+
Foo 1.2
|
| 15 |
+
|
| 16 |
+
Distributions have a location, which can be a filename, URL, or really anything
|
| 17 |
+
else you care to use::
|
| 18 |
+
|
| 19 |
+
>>> dist = Distribution(
|
| 20 |
+
... location="http://example.com/something",
|
| 21 |
+
... project_name="Bar", version="0.9"
|
| 22 |
+
... )
|
| 23 |
+
|
| 24 |
+
>>> dist
|
| 25 |
+
Bar 0.9 (http://example.com/something)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
Distributions have various introspectable attributes::
|
| 29 |
+
|
| 30 |
+
>>> dist.location
|
| 31 |
+
'http://example.com/something'
|
| 32 |
+
|
| 33 |
+
>>> dist.project_name
|
| 34 |
+
'Bar'
|
| 35 |
+
|
| 36 |
+
>>> dist.version
|
| 37 |
+
'0.9'
|
| 38 |
+
|
| 39 |
+
>>> dist.py_version == '{}.{}'.format(*sys.version_info)
|
| 40 |
+
True
|
| 41 |
+
|
| 42 |
+
>>> print(dist.platform)
|
| 43 |
+
None
|
| 44 |
+
|
| 45 |
+
Including various computed attributes::
|
| 46 |
+
|
| 47 |
+
>>> from pkg_resources import parse_version
|
| 48 |
+
>>> dist.parsed_version == parse_version(dist.version)
|
| 49 |
+
True
|
| 50 |
+
|
| 51 |
+
>>> dist.key # case-insensitive form of the project name
|
| 52 |
+
'bar'
|
| 53 |
+
|
| 54 |
+
Distributions are compared (and hashed) by version first::
|
| 55 |
+
|
| 56 |
+
>>> Distribution(version='1.0') == Distribution(version='1.0')
|
| 57 |
+
True
|
| 58 |
+
>>> Distribution(version='1.0') == Distribution(version='1.1')
|
| 59 |
+
False
|
| 60 |
+
>>> Distribution(version='1.0') < Distribution(version='1.1')
|
| 61 |
+
True
|
| 62 |
+
|
| 63 |
+
but also by project name (case-insensitive), platform, Python version,
|
| 64 |
+
location, etc.::
|
| 65 |
+
|
| 66 |
+
>>> Distribution(project_name="Foo",version="1.0") == \
|
| 67 |
+
... Distribution(project_name="Foo",version="1.0")
|
| 68 |
+
True
|
| 69 |
+
|
| 70 |
+
>>> Distribution(project_name="Foo",version="1.0") == \
|
| 71 |
+
... Distribution(project_name="foo",version="1.0")
|
| 72 |
+
True
|
| 73 |
+
|
| 74 |
+
>>> Distribution(project_name="Foo",version="1.0") == \
|
| 75 |
+
... Distribution(project_name="Foo",version="1.1")
|
| 76 |
+
False
|
| 77 |
+
|
| 78 |
+
>>> Distribution(project_name="Foo",py_version="2.3",version="1.0") == \
|
| 79 |
+
... Distribution(project_name="Foo",py_version="2.4",version="1.0")
|
| 80 |
+
False
|
| 81 |
+
|
| 82 |
+
>>> Distribution(location="spam",version="1.0") == \
|
| 83 |
+
... Distribution(location="spam",version="1.0")
|
| 84 |
+
True
|
| 85 |
+
|
| 86 |
+
>>> Distribution(location="spam",version="1.0") == \
|
| 87 |
+
... Distribution(location="baz",version="1.0")
|
| 88 |
+
False
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
Hash and compare distribution by prio/plat
|
| 93 |
+
|
| 94 |
+
Get version from metadata
|
| 95 |
+
provider capabilities
|
| 96 |
+
egg_name()
|
| 97 |
+
as_requirement()
|
| 98 |
+
from_location, from_filename (w/path normalization)
|
| 99 |
+
|
| 100 |
+
Releases may have zero or more "Requirements", which indicate
|
| 101 |
+
what releases of another project the release requires in order to
|
| 102 |
+
function. A Requirement names the other project, expresses some criteria
|
| 103 |
+
as to what releases of that project are acceptable, and lists any "Extras"
|
| 104 |
+
that the requiring release may need from that project. (An Extra is an
|
| 105 |
+
optional feature of a Release, that can only be used if its additional
|
| 106 |
+
Requirements are satisfied.)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
The Working Set
|
| 111 |
+
---------------
|
| 112 |
+
|
| 113 |
+
A collection of active distributions is called a Working Set. Note that a
|
| 114 |
+
Working Set can contain any importable distribution, not just pluggable ones.
|
| 115 |
+
For example, the Python standard library is an importable distribution that
|
| 116 |
+
will usually be part of the Working Set, even though it is not pluggable.
|
| 117 |
+
Similarly, when you are doing development work on a project, the files you are
|
| 118 |
+
editing are also a Distribution. (And, with a little attention to the
|
| 119 |
+
directory names used, and including some additional metadata, such a
|
| 120 |
+
"development distribution" can be made pluggable as well.)
|
| 121 |
+
|
| 122 |
+
>>> from pkg_resources import WorkingSet
|
| 123 |
+
|
| 124 |
+
A working set's entries are the sys.path entries that correspond to the active
|
| 125 |
+
distributions. By default, the working set's entries are the items on
|
| 126 |
+
``sys.path``::
|
| 127 |
+
|
| 128 |
+
>>> ws = WorkingSet()
|
| 129 |
+
>>> ws.entries == sys.path
|
| 130 |
+
True
|
| 131 |
+
|
| 132 |
+
But you can also create an empty working set explicitly, and add distributions
|
| 133 |
+
to it::
|
| 134 |
+
|
| 135 |
+
>>> ws = WorkingSet([])
|
| 136 |
+
>>> ws.add(dist)
|
| 137 |
+
>>> ws.entries
|
| 138 |
+
['http://example.com/something']
|
| 139 |
+
>>> dist in ws
|
| 140 |
+
True
|
| 141 |
+
>>> Distribution('foo',version="") in ws
|
| 142 |
+
False
|
| 143 |
+
|
| 144 |
+
And you can iterate over its distributions::
|
| 145 |
+
|
| 146 |
+
>>> list(ws)
|
| 147 |
+
[Bar 0.9 (http://example.com/something)]
|
| 148 |
+
|
| 149 |
+
Adding the same distribution more than once is a no-op::
|
| 150 |
+
|
| 151 |
+
>>> ws.add(dist)
|
| 152 |
+
>>> list(ws)
|
| 153 |
+
[Bar 0.9 (http://example.com/something)]
|
| 154 |
+
|
| 155 |
+
For that matter, adding multiple distributions for the same project also does
|
| 156 |
+
nothing, because a working set can only hold one active distribution per
|
| 157 |
+
project -- the first one added to it::
|
| 158 |
+
|
| 159 |
+
>>> ws.add(
|
| 160 |
+
... Distribution(
|
| 161 |
+
... 'http://example.com/something', project_name="Bar",
|
| 162 |
+
... version="7.2"
|
| 163 |
+
... )
|
| 164 |
+
... )
|
| 165 |
+
>>> list(ws)
|
| 166 |
+
[Bar 0.9 (http://example.com/something)]
|
| 167 |
+
|
| 168 |
+
You can append a path entry to a working set using ``add_entry()``::
|
| 169 |
+
|
| 170 |
+
>>> ws.entries
|
| 171 |
+
['http://example.com/something']
|
| 172 |
+
>>> ws.add_entry(pkg_resources.__file__)
|
| 173 |
+
>>> ws.entries
|
| 174 |
+
['http://example.com/something', '...pkg_resources...']
|
| 175 |
+
|
| 176 |
+
Multiple additions result in multiple entries, even if the entry is already in
|
| 177 |
+
the working set (because ``sys.path`` can contain the same entry more than
|
| 178 |
+
once)::
|
| 179 |
+
|
| 180 |
+
>>> ws.add_entry(pkg_resources.__file__)
|
| 181 |
+
>>> ws.entries
|
| 182 |
+
['...example.com...', '...pkg_resources...', '...pkg_resources...']
|
| 183 |
+
|
| 184 |
+
And you can specify the path entry a distribution was found under, using the
|
| 185 |
+
optional second parameter to ``add()``::
|
| 186 |
+
|
| 187 |
+
>>> ws = WorkingSet([])
|
| 188 |
+
>>> ws.add(dist,"foo")
|
| 189 |
+
>>> ws.entries
|
| 190 |
+
['foo']
|
| 191 |
+
|
| 192 |
+
But even if a distribution is found under multiple path entries, it still only
|
| 193 |
+
shows up once when iterating the working set:
|
| 194 |
+
|
| 195 |
+
>>> ws.add_entry(ws.entries[0])
|
| 196 |
+
>>> list(ws)
|
| 197 |
+
[Bar 0.9 (http://example.com/something)]
|
| 198 |
+
|
| 199 |
+
You can ask a WorkingSet to ``find()`` a distribution matching a requirement::
|
| 200 |
+
|
| 201 |
+
>>> from pkg_resources import Requirement
|
| 202 |
+
>>> print(ws.find(Requirement.parse("Foo==1.0"))) # no match, return None
|
| 203 |
+
None
|
| 204 |
+
|
| 205 |
+
>>> ws.find(Requirement.parse("Bar==0.9")) # match, return distribution
|
| 206 |
+
Bar 0.9 (http://example.com/something)
|
| 207 |
+
|
| 208 |
+
Note that asking for a conflicting version of a distribution already in a
|
| 209 |
+
working set triggers a ``pkg_resources.VersionConflict`` error:
|
| 210 |
+
|
| 211 |
+
>>> try:
|
| 212 |
+
... ws.find(Requirement.parse("Bar==1.0"))
|
| 213 |
+
... except pkg_resources.VersionConflict as exc:
|
| 214 |
+
... print(str(exc))
|
| 215 |
+
... else:
|
| 216 |
+
... raise AssertionError("VersionConflict was not raised")
|
| 217 |
+
(Bar 0.9 (http://example.com/something), Requirement.parse('Bar==1.0'))
|
| 218 |
+
|
| 219 |
+
You can subscribe a callback function to receive notifications whenever a new
|
| 220 |
+
distribution is added to a working set. The callback is immediately invoked
|
| 221 |
+
once for each existing distribution in the working set, and then is called
|
| 222 |
+
again for new distributions added thereafter::
|
| 223 |
+
|
| 224 |
+
>>> def added(dist): print("Added %s" % dist)
|
| 225 |
+
>>> ws.subscribe(added)
|
| 226 |
+
Added Bar 0.9
|
| 227 |
+
>>> foo12 = Distribution(project_name="Foo", version="1.2", location="f12")
|
| 228 |
+
>>> ws.add(foo12)
|
| 229 |
+
Added Foo 1.2
|
| 230 |
+
|
| 231 |
+
Note, however, that only the first distribution added for a given project name
|
| 232 |
+
will trigger a callback, even during the initial ``subscribe()`` callback::
|
| 233 |
+
|
| 234 |
+
>>> foo14 = Distribution(project_name="Foo", version="1.4", location="f14")
|
| 235 |
+
>>> ws.add(foo14) # no callback, because Foo 1.2 is already active
|
| 236 |
+
|
| 237 |
+
>>> ws = WorkingSet([])
|
| 238 |
+
>>> ws.add(foo12)
|
| 239 |
+
>>> ws.add(foo14)
|
| 240 |
+
>>> ws.subscribe(added)
|
| 241 |
+
Added Foo 1.2
|
| 242 |
+
|
| 243 |
+
And adding a callback more than once has no effect, either::
|
| 244 |
+
|
| 245 |
+
>>> ws.subscribe(added) # no callbacks
|
| 246 |
+
|
| 247 |
+
# and no double-callbacks on subsequent additions, either
|
| 248 |
+
>>> just_a_test = Distribution(project_name="JustATest", version="0.99")
|
| 249 |
+
>>> ws.add(just_a_test)
|
| 250 |
+
Added JustATest 0.99
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
Finding Plugins
|
| 254 |
+
---------------
|
| 255 |
+
|
| 256 |
+
``WorkingSet`` objects can be used to figure out what plugins in an
|
| 257 |
+
``Environment`` can be loaded without any resolution errors::
|
| 258 |
+
|
| 259 |
+
>>> from pkg_resources import Environment
|
| 260 |
+
|
| 261 |
+
>>> plugins = Environment([]) # normally, a list of plugin directories
|
| 262 |
+
>>> plugins.add(foo12)
|
| 263 |
+
>>> plugins.add(foo14)
|
| 264 |
+
>>> plugins.add(just_a_test)
|
| 265 |
+
|
| 266 |
+
In the simplest case, we just get the newest version of each distribution in
|
| 267 |
+
the plugin environment::
|
| 268 |
+
|
| 269 |
+
>>> ws = WorkingSet([])
|
| 270 |
+
>>> ws.find_plugins(plugins)
|
| 271 |
+
([JustATest 0.99, Foo 1.4 (f14)], {})
|
| 272 |
+
|
| 273 |
+
But if there's a problem with a version conflict or missing requirements, the
|
| 274 |
+
method falls back to older versions, and the error info dict will contain an
|
| 275 |
+
exception instance for each unloadable plugin::
|
| 276 |
+
|
| 277 |
+
>>> ws.add(foo12) # this will conflict with Foo 1.4
|
| 278 |
+
>>> ws.find_plugins(plugins)
|
| 279 |
+
([JustATest 0.99, Foo 1.2 (f12)], {Foo 1.4 (f14): VersionConflict(...)})
|
| 280 |
+
|
| 281 |
+
But if you disallow fallbacks, the failed plugin will be skipped instead of
|
| 282 |
+
trying older versions::
|
| 283 |
+
|
| 284 |
+
>>> ws.find_plugins(plugins, fallback=False)
|
| 285 |
+
([JustATest 0.99], {Foo 1.4 (f14): VersionConflict(...)})
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
Platform Compatibility Rules
|
| 290 |
+
----------------------------
|
| 291 |
+
|
| 292 |
+
On the Mac, there are potential compatibility issues for modules compiled
|
| 293 |
+
on newer versions of macOS than what the user is running. Additionally,
|
| 294 |
+
macOS will soon have two platforms to contend with: Intel and PowerPC.
|
| 295 |
+
|
| 296 |
+
Basic equality works as on other platforms::
|
| 297 |
+
|
| 298 |
+
>>> from pkg_resources import compatible_platforms as cp
|
| 299 |
+
>>> reqd = 'macosx-10.4-ppc'
|
| 300 |
+
>>> cp(reqd, reqd)
|
| 301 |
+
True
|
| 302 |
+
>>> cp("win32", reqd)
|
| 303 |
+
False
|
| 304 |
+
|
| 305 |
+
Distributions made on other machine types are not compatible::
|
| 306 |
+
|
| 307 |
+
>>> cp("macosx-10.4-i386", reqd)
|
| 308 |
+
False
|
| 309 |
+
|
| 310 |
+
Distributions made on earlier versions of the OS are compatible, as
|
| 311 |
+
long as they are from the same top-level version. The patchlevel version
|
| 312 |
+
number does not matter::
|
| 313 |
+
|
| 314 |
+
>>> cp("macosx-10.4-ppc", reqd)
|
| 315 |
+
True
|
| 316 |
+
>>> cp("macosx-10.3-ppc", reqd)
|
| 317 |
+
True
|
| 318 |
+
>>> cp("macosx-10.5-ppc", reqd)
|
| 319 |
+
False
|
| 320 |
+
>>> cp("macosx-9.5-ppc", reqd)
|
| 321 |
+
False
|
| 322 |
+
|
| 323 |
+
Backwards compatibility for packages made via earlier versions of
|
| 324 |
+
setuptools is provided as well::
|
| 325 |
+
|
| 326 |
+
>>> cp("darwin-8.2.0-Power_Macintosh", reqd)
|
| 327 |
+
True
|
| 328 |
+
>>> cp("darwin-7.2.0-Power_Macintosh", reqd)
|
| 329 |
+
True
|
| 330 |
+
>>> cp("darwin-8.2.0-Power_Macintosh", "macosx-10.3-ppc")
|
| 331 |
+
False
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
Environment Markers
|
| 335 |
+
-------------------
|
| 336 |
+
|
| 337 |
+
>>> from pkg_resources import invalid_marker as im, evaluate_marker as em
|
| 338 |
+
>>> import os
|
| 339 |
+
|
| 340 |
+
>>> print(im("sys_platform"))
|
| 341 |
+
Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
|
| 342 |
+
sys_platform
|
| 343 |
+
^
|
| 344 |
+
|
| 345 |
+
>>> print(im("sys_platform=="))
|
| 346 |
+
Expected a marker variable or quoted string
|
| 347 |
+
sys_platform==
|
| 348 |
+
^
|
| 349 |
+
|
| 350 |
+
>>> print(im("sys_platform=='win32'"))
|
| 351 |
+
False
|
| 352 |
+
|
| 353 |
+
>>> print(im("sys=='x'"))
|
| 354 |
+
Expected a marker variable or quoted string
|
| 355 |
+
sys=='x'
|
| 356 |
+
^
|
| 357 |
+
|
| 358 |
+
>>> print(im("(extra)"))
|
| 359 |
+
Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
|
| 360 |
+
(extra)
|
| 361 |
+
^
|
| 362 |
+
|
| 363 |
+
>>> print(im("(extra"))
|
| 364 |
+
Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
|
| 365 |
+
(extra
|
| 366 |
+
^
|
| 367 |
+
|
| 368 |
+
>>> print(im("os.open('foo')=='y'"))
|
| 369 |
+
Expected a marker variable or quoted string
|
| 370 |
+
os.open('foo')=='y'
|
| 371 |
+
^
|
| 372 |
+
|
| 373 |
+
>>> print(im("'x'=='y' and os.open('foo')=='y'")) # no short-circuit!
|
| 374 |
+
Expected a marker variable or quoted string
|
| 375 |
+
'x'=='y' and os.open('foo')=='y'
|
| 376 |
+
^
|
| 377 |
+
|
| 378 |
+
>>> print(im("'x'=='x' or os.open('foo')=='y'")) # no short-circuit!
|
| 379 |
+
Expected a marker variable or quoted string
|
| 380 |
+
'x'=='x' or os.open('foo')=='y'
|
| 381 |
+
^
|
| 382 |
+
|
| 383 |
+
>>> print(im("r'x'=='x'"))
|
| 384 |
+
Expected a marker variable or quoted string
|
| 385 |
+
r'x'=='x'
|
| 386 |
+
^
|
| 387 |
+
|
| 388 |
+
>>> print(im("'''x'''=='x'"))
|
| 389 |
+
Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
|
| 390 |
+
'''x'''=='x'
|
| 391 |
+
^
|
| 392 |
+
|
| 393 |
+
>>> print(im('"""x"""=="x"'))
|
| 394 |
+
Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
|
| 395 |
+
"""x"""=="x"
|
| 396 |
+
^
|
| 397 |
+
|
| 398 |
+
>>> print(im(r"x\n=='x'"))
|
| 399 |
+
Expected a marker variable or quoted string
|
| 400 |
+
x\n=='x'
|
| 401 |
+
^
|
| 402 |
+
|
| 403 |
+
>>> print(im("os.open=='y'"))
|
| 404 |
+
Expected a marker variable or quoted string
|
| 405 |
+
os.open=='y'
|
| 406 |
+
^
|
| 407 |
+
|
| 408 |
+
>>> em("sys_platform=='win32'") == (sys.platform=='win32')
|
| 409 |
+
True
|
| 410 |
+
|
| 411 |
+
>>> em("python_version >= '2.7'")
|
| 412 |
+
True
|
| 413 |
+
|
| 414 |
+
>>> em("python_version > '2.6'")
|
| 415 |
+
True
|
| 416 |
+
|
| 417 |
+
>>> im("implementation_name=='cpython'")
|
| 418 |
+
False
|
| 419 |
+
|
| 420 |
+
>>> im("platform_python_implementation=='CPython'")
|
| 421 |
+
False
|
| 422 |
+
|
| 423 |
+
>>> im("implementation_version=='3.5.1'")
|
| 424 |
+
False
|
omnilmm/lib/python3.10/site-packages/pkg_resources/py.typed
ADDED
|
File without changes
|
omnilmm/lib/python3.10/site-packages/pkg_resources/tests/__init__.py
ADDED
|
File without changes
|
omnilmm/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (153 Bytes). View file
|
|
|