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 +2 -0
- parrot/lib/python3.10/site-packages/matplotlib/__init__.pyi +115 -0
- parrot/lib/python3.10/site-packages/matplotlib/_cm_listed.py +0 -0
- parrot/lib/python3.10/site-packages/matplotlib/_color_data.py +1141 -0
- parrot/lib/python3.10/site-packages/matplotlib/_docstring.py +125 -0
- parrot/lib/python3.10/site-packages/matplotlib/_enums.pyi +18 -0
- parrot/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py +111 -0
- parrot/lib/python3.10/site-packages/matplotlib/_image.pyi +0 -0
- parrot/lib/python3.10/site-packages/matplotlib/_path.pyi +9 -0
- parrot/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py +134 -0
- parrot/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi +29 -0
- parrot/lib/python3.10/site-packages/matplotlib/_tri.pyi +26 -0
- parrot/lib/python3.10/site-packages/matplotlib/_version.py +1 -0
- parrot/lib/python3.10/site-packages/matplotlib/axis.pyi +280 -0
- parrot/lib/python3.10/site-packages/matplotlib/backend_managers.pyi +64 -0
- parrot/lib/python3.10/site-packages/matplotlib/cbook.pyi +186 -0
- parrot/lib/python3.10/site-packages/matplotlib/collections.pyi +236 -0
- parrot/lib/python3.10/site-packages/matplotlib/colorbar.py +1559 -0
- parrot/lib/python3.10/site-packages/matplotlib/colorbar.pyi +136 -0
- parrot/lib/python3.10/site-packages/matplotlib/colors.pyi +354 -0
- parrot/lib/python3.10/site-packages/matplotlib/container.py +141 -0
- parrot/lib/python3.10/site-packages/matplotlib/dviread.py +1107 -0
- parrot/lib/python3.10/site-packages/matplotlib/dviread.pyi +90 -0
- parrot/lib/python3.10/site-packages/matplotlib/ft2font.pyi +253 -0
- parrot/lib/python3.10/site-packages/matplotlib/gridspec.pyi +160 -0
- parrot/lib/python3.10/site-packages/matplotlib/legend.py +1385 -0
- parrot/lib/python3.10/site-packages/matplotlib/legend_handler.py +813 -0
- parrot/lib/python3.10/site-packages/matplotlib/markers.py +908 -0
- parrot/lib/python3.10/site-packages/matplotlib/markers.pyi +51 -0
- parrot/lib/python3.10/site-packages/matplotlib/patches.pyi +755 -0
- parrot/lib/python3.10/site-packages/matplotlib/path.py +1096 -0
- parrot/lib/python3.10/site-packages/matplotlib/py.typed +0 -0
- parrot/lib/python3.10/site-packages/matplotlib/rcsetup.py +1377 -0
- parrot/lib/python3.10/site-packages/matplotlib/sankey.py +814 -0
- parrot/lib/python3.10/site-packages/matplotlib/sankey.pyi +61 -0
- parrot/lib/python3.10/site-packages/matplotlib/stackplot.py +147 -0
- parrot/lib/python3.10/site-packages/matplotlib/streamplot.py +712 -0
- parrot/lib/python3.10/site-packages/matplotlib/streamplot.pyi +82 -0
- parrot/lib/python3.10/site-packages/matplotlib/text.py +2027 -0
- parrot/lib/python3.10/site-packages/matplotlib/textpath.py +397 -0
- parrot/lib/python3.10/site-packages/matplotlib/widgets.pyi +490 -0
- parrot/lib/python3.10/site-packages/scipy/ndimage/_ni_label.cpython-310-x86_64-linux-gnu.so +3 -0
- parrot/lib/python3.10/site-packages/torchvision.libs/libnvjpeg.f00ca762.so.12 +3 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_clamp_max.h +82 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_cos.h +44 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_native.h +22 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_softmax.h +39 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_spsolve_native.h +21 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell.h +39 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_impl_ops.h +39 -0
.gitattributes
CHANGED
|
@@ -1882,3 +1882,5 @@ videollama2/lib/python3.10/site-packages/sklearn/decomposition/_cdnmf_fast.cpyth
|
|
| 1882 |
parrot/lib/python3.10/site-packages/scipy/odr/__odrpack.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1883 |
videollama2/lib/python3.10/site-packages/sklearn/manifold/_barnes_hut_tsne.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1884 |
videollama2/lib/python3.10/site-packages/sklearn/ensemble/_gradient_boosting.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 1882 |
parrot/lib/python3.10/site-packages/scipy/odr/__odrpack.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1883 |
videollama2/lib/python3.10/site-packages/sklearn/manifold/_barnes_hut_tsne.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1884 |
videollama2/lib/python3.10/site-packages/sklearn/ensemble/_gradient_boosting.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1885 |
+
parrot/lib/python3.10/site-packages/scipy/ndimage/_ni_label.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1886 |
+
parrot/lib/python3.10/site-packages/torchvision.libs/libnvjpeg.f00ca762.so.12 filter=lfs diff=lfs merge=lfs -text
|
parrot/lib/python3.10/site-packages/matplotlib/__init__.pyi
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = [
|
| 2 |
+
"__bibtex__",
|
| 3 |
+
"__version__",
|
| 4 |
+
"__version_info__",
|
| 5 |
+
"set_loglevel",
|
| 6 |
+
"ExecutableNotFoundError",
|
| 7 |
+
"get_configdir",
|
| 8 |
+
"get_cachedir",
|
| 9 |
+
"get_data_path",
|
| 10 |
+
"matplotlib_fname",
|
| 11 |
+
"MatplotlibDeprecationWarning",
|
| 12 |
+
"RcParams",
|
| 13 |
+
"rc_params",
|
| 14 |
+
"rc_params_from_file",
|
| 15 |
+
"rcParamsDefault",
|
| 16 |
+
"rcParams",
|
| 17 |
+
"rcParamsOrig",
|
| 18 |
+
"defaultParams",
|
| 19 |
+
"rc",
|
| 20 |
+
"rcdefaults",
|
| 21 |
+
"rc_file_defaults",
|
| 22 |
+
"rc_file",
|
| 23 |
+
"rc_context",
|
| 24 |
+
"use",
|
| 25 |
+
"get_backend",
|
| 26 |
+
"interactive",
|
| 27 |
+
"is_interactive",
|
| 28 |
+
"colormaps",
|
| 29 |
+
"color_sequences",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
import os
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
|
| 35 |
+
from collections.abc import Callable, Generator
|
| 36 |
+
import contextlib
|
| 37 |
+
from packaging.version import Version
|
| 38 |
+
|
| 39 |
+
from matplotlib._api import MatplotlibDeprecationWarning
|
| 40 |
+
from typing import Any, NamedTuple
|
| 41 |
+
|
| 42 |
+
class _VersionInfo(NamedTuple):
|
| 43 |
+
major: int
|
| 44 |
+
minor: int
|
| 45 |
+
micro: int
|
| 46 |
+
releaselevel: str
|
| 47 |
+
serial: int
|
| 48 |
+
|
| 49 |
+
__bibtex__: str
|
| 50 |
+
__version__: str
|
| 51 |
+
__version_info__: _VersionInfo
|
| 52 |
+
|
| 53 |
+
def set_loglevel(level: str) -> None: ...
|
| 54 |
+
|
| 55 |
+
class _ExecInfo(NamedTuple):
|
| 56 |
+
executable: str
|
| 57 |
+
raw_version: str
|
| 58 |
+
version: Version
|
| 59 |
+
|
| 60 |
+
class ExecutableNotFoundError(FileNotFoundError): ...
|
| 61 |
+
|
| 62 |
+
def _get_executable_info(name: str) -> _ExecInfo: ...
|
| 63 |
+
def get_configdir() -> str: ...
|
| 64 |
+
def get_cachedir() -> str: ...
|
| 65 |
+
def get_data_path() -> str: ...
|
| 66 |
+
def matplotlib_fname() -> str: ...
|
| 67 |
+
|
| 68 |
+
class RcParams(dict[str, Any]):
|
| 69 |
+
validate: dict[str, Callable]
|
| 70 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 71 |
+
def _set(self, key: str, val: Any) -> None: ...
|
| 72 |
+
def _get(self, key: str) -> Any: ...
|
| 73 |
+
def __setitem__(self, key: str, val: Any) -> None: ...
|
| 74 |
+
def __getitem__(self, key: str) -> Any: ...
|
| 75 |
+
def __iter__(self) -> Generator[str, None, None]: ...
|
| 76 |
+
def __len__(self) -> int: ...
|
| 77 |
+
def find_all(self, pattern: str) -> RcParams: ...
|
| 78 |
+
def copy(self) -> RcParams: ...
|
| 79 |
+
|
| 80 |
+
def rc_params(fail_on_error: bool = ...) -> RcParams: ...
|
| 81 |
+
def rc_params_from_file(
|
| 82 |
+
fname: str | Path | os.PathLike,
|
| 83 |
+
fail_on_error: bool = ...,
|
| 84 |
+
use_default_template: bool = ...,
|
| 85 |
+
) -> RcParams: ...
|
| 86 |
+
|
| 87 |
+
rcParamsDefault: RcParams
|
| 88 |
+
rcParams: RcParams
|
| 89 |
+
rcParamsOrig: RcParams
|
| 90 |
+
defaultParams: dict[str, Any]
|
| 91 |
+
|
| 92 |
+
def rc(group: str, **kwargs) -> None: ...
|
| 93 |
+
def rcdefaults() -> None: ...
|
| 94 |
+
def rc_file_defaults() -> None: ...
|
| 95 |
+
def rc_file(
|
| 96 |
+
fname: str | Path | os.PathLike, *, use_default_template: bool = ...
|
| 97 |
+
) -> None: ...
|
| 98 |
+
@contextlib.contextmanager
|
| 99 |
+
def rc_context(
|
| 100 |
+
rc: dict[str, Any] | None = ..., fname: str | Path | os.PathLike | None = ...
|
| 101 |
+
) -> Generator[None, None, None]: ...
|
| 102 |
+
def use(backend: str, *, force: bool = ...) -> None: ...
|
| 103 |
+
def get_backend() -> str: ...
|
| 104 |
+
def interactive(b: bool) -> None: ...
|
| 105 |
+
def is_interactive() -> bool: ...
|
| 106 |
+
|
| 107 |
+
def _preprocess_data(
|
| 108 |
+
func: Callable | None = ...,
|
| 109 |
+
*,
|
| 110 |
+
replace_names: list[str] | None = ...,
|
| 111 |
+
label_namer: str | None = ...
|
| 112 |
+
) -> Callable: ...
|
| 113 |
+
|
| 114 |
+
from matplotlib.cm import _colormaps as colormaps
|
| 115 |
+
from matplotlib.colors import _color_sequences as color_sequences
|
parrot/lib/python3.10/site-packages/matplotlib/_cm_listed.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
parrot/lib/python3.10/site-packages/matplotlib/_color_data.py
ADDED
|
@@ -0,0 +1,1141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BASE_COLORS = {
|
| 2 |
+
'b': (0, 0, 1), # blue
|
| 3 |
+
'g': (0, 0.5, 0), # green
|
| 4 |
+
'r': (1, 0, 0), # red
|
| 5 |
+
'c': (0, 0.75, 0.75), # cyan
|
| 6 |
+
'm': (0.75, 0, 0.75), # magenta
|
| 7 |
+
'y': (0.75, 0.75, 0), # yellow
|
| 8 |
+
'k': (0, 0, 0), # black
|
| 9 |
+
'w': (1, 1, 1), # white
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# These colors are from Tableau
|
| 14 |
+
TABLEAU_COLORS = {
|
| 15 |
+
'tab:blue': '#1f77b4',
|
| 16 |
+
'tab:orange': '#ff7f0e',
|
| 17 |
+
'tab:green': '#2ca02c',
|
| 18 |
+
'tab:red': '#d62728',
|
| 19 |
+
'tab:purple': '#9467bd',
|
| 20 |
+
'tab:brown': '#8c564b',
|
| 21 |
+
'tab:pink': '#e377c2',
|
| 22 |
+
'tab:gray': '#7f7f7f',
|
| 23 |
+
'tab:olive': '#bcbd22',
|
| 24 |
+
'tab:cyan': '#17becf',
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# This mapping of color names -> hex values is taken from
|
| 29 |
+
# a survey run by Randall Munroe see:
|
| 30 |
+
# https://blog.xkcd.com/2010/05/03/color-survey-results/
|
| 31 |
+
# for more details. The results are hosted at
|
| 32 |
+
# https://xkcd.com/color/rgb/
|
| 33 |
+
# and also available as a text file at
|
| 34 |
+
# https://xkcd.com/color/rgb.txt
|
| 35 |
+
#
|
| 36 |
+
# License: https://creativecommons.org/publicdomain/zero/1.0/
|
| 37 |
+
XKCD_COLORS = {
|
| 38 |
+
'cloudy blue': '#acc2d9',
|
| 39 |
+
'dark pastel green': '#56ae57',
|
| 40 |
+
'dust': '#b2996e',
|
| 41 |
+
'electric lime': '#a8ff04',
|
| 42 |
+
'fresh green': '#69d84f',
|
| 43 |
+
'light eggplant': '#894585',
|
| 44 |
+
'nasty green': '#70b23f',
|
| 45 |
+
'really light blue': '#d4ffff',
|
| 46 |
+
'tea': '#65ab7c',
|
| 47 |
+
'warm purple': '#952e8f',
|
| 48 |
+
'yellowish tan': '#fcfc81',
|
| 49 |
+
'cement': '#a5a391',
|
| 50 |
+
'dark grass green': '#388004',
|
| 51 |
+
'dusty teal': '#4c9085',
|
| 52 |
+
'grey teal': '#5e9b8a',
|
| 53 |
+
'macaroni and cheese': '#efb435',
|
| 54 |
+
'pinkish tan': '#d99b82',
|
| 55 |
+
'spruce': '#0a5f38',
|
| 56 |
+
'strong blue': '#0c06f7',
|
| 57 |
+
'toxic green': '#61de2a',
|
| 58 |
+
'windows blue': '#3778bf',
|
| 59 |
+
'blue blue': '#2242c7',
|
| 60 |
+
'blue with a hint of purple': '#533cc6',
|
| 61 |
+
'booger': '#9bb53c',
|
| 62 |
+
'bright sea green': '#05ffa6',
|
| 63 |
+
'dark green blue': '#1f6357',
|
| 64 |
+
'deep turquoise': '#017374',
|
| 65 |
+
'green teal': '#0cb577',
|
| 66 |
+
'strong pink': '#ff0789',
|
| 67 |
+
'bland': '#afa88b',
|
| 68 |
+
'deep aqua': '#08787f',
|
| 69 |
+
'lavender pink': '#dd85d7',
|
| 70 |
+
'light moss green': '#a6c875',
|
| 71 |
+
'light seafoam green': '#a7ffb5',
|
| 72 |
+
'olive yellow': '#c2b709',
|
| 73 |
+
'pig pink': '#e78ea5',
|
| 74 |
+
'deep lilac': '#966ebd',
|
| 75 |
+
'desert': '#ccad60',
|
| 76 |
+
'dusty lavender': '#ac86a8',
|
| 77 |
+
'purpley grey': '#947e94',
|
| 78 |
+
'purply': '#983fb2',
|
| 79 |
+
'candy pink': '#ff63e9',
|
| 80 |
+
'light pastel green': '#b2fba5',
|
| 81 |
+
'boring green': '#63b365',
|
| 82 |
+
'kiwi green': '#8ee53f',
|
| 83 |
+
'light grey green': '#b7e1a1',
|
| 84 |
+
'orange pink': '#ff6f52',
|
| 85 |
+
'tea green': '#bdf8a3',
|
| 86 |
+
'very light brown': '#d3b683',
|
| 87 |
+
'egg shell': '#fffcc4',
|
| 88 |
+
'eggplant purple': '#430541',
|
| 89 |
+
'powder pink': '#ffb2d0',
|
| 90 |
+
'reddish grey': '#997570',
|
| 91 |
+
'baby shit brown': '#ad900d',
|
| 92 |
+
'liliac': '#c48efd',
|
| 93 |
+
'stormy blue': '#507b9c',
|
| 94 |
+
'ugly brown': '#7d7103',
|
| 95 |
+
'custard': '#fffd78',
|
| 96 |
+
'darkish pink': '#da467d',
|
| 97 |
+
'deep brown': '#410200',
|
| 98 |
+
'greenish beige': '#c9d179',
|
| 99 |
+
'manilla': '#fffa86',
|
| 100 |
+
'off blue': '#5684ae',
|
| 101 |
+
'battleship grey': '#6b7c85',
|
| 102 |
+
'browny green': '#6f6c0a',
|
| 103 |
+
'bruise': '#7e4071',
|
| 104 |
+
'kelley green': '#009337',
|
| 105 |
+
'sickly yellow': '#d0e429',
|
| 106 |
+
'sunny yellow': '#fff917',
|
| 107 |
+
'azul': '#1d5dec',
|
| 108 |
+
'darkgreen': '#054907',
|
| 109 |
+
'green/yellow': '#b5ce08',
|
| 110 |
+
'lichen': '#8fb67b',
|
| 111 |
+
'light light green': '#c8ffb0',
|
| 112 |
+
'pale gold': '#fdde6c',
|
| 113 |
+
'sun yellow': '#ffdf22',
|
| 114 |
+
'tan green': '#a9be70',
|
| 115 |
+
'burple': '#6832e3',
|
| 116 |
+
'butterscotch': '#fdb147',
|
| 117 |
+
'toupe': '#c7ac7d',
|
| 118 |
+
'dark cream': '#fff39a',
|
| 119 |
+
'indian red': '#850e04',
|
| 120 |
+
'light lavendar': '#efc0fe',
|
| 121 |
+
'poison green': '#40fd14',
|
| 122 |
+
'baby puke green': '#b6c406',
|
| 123 |
+
'bright yellow green': '#9dff00',
|
| 124 |
+
'charcoal grey': '#3c4142',
|
| 125 |
+
'squash': '#f2ab15',
|
| 126 |
+
'cinnamon': '#ac4f06',
|
| 127 |
+
'light pea green': '#c4fe82',
|
| 128 |
+
'radioactive green': '#2cfa1f',
|
| 129 |
+
'raw sienna': '#9a6200',
|
| 130 |
+
'baby purple': '#ca9bf7',
|
| 131 |
+
'cocoa': '#875f42',
|
| 132 |
+
'light royal blue': '#3a2efe',
|
| 133 |
+
'orangeish': '#fd8d49',
|
| 134 |
+
'rust brown': '#8b3103',
|
| 135 |
+
'sand brown': '#cba560',
|
| 136 |
+
'swamp': '#698339',
|
| 137 |
+
'tealish green': '#0cdc73',
|
| 138 |
+
'burnt siena': '#b75203',
|
| 139 |
+
'camo': '#7f8f4e',
|
| 140 |
+
'dusk blue': '#26538d',
|
| 141 |
+
'fern': '#63a950',
|
| 142 |
+
'old rose': '#c87f89',
|
| 143 |
+
'pale light green': '#b1fc99',
|
| 144 |
+
'peachy pink': '#ff9a8a',
|
| 145 |
+
'rosy pink': '#f6688e',
|
| 146 |
+
'light bluish green': '#76fda8',
|
| 147 |
+
'light bright green': '#53fe5c',
|
| 148 |
+
'light neon green': '#4efd54',
|
| 149 |
+
'light seafoam': '#a0febf',
|
| 150 |
+
'tiffany blue': '#7bf2da',
|
| 151 |
+
'washed out green': '#bcf5a6',
|
| 152 |
+
'browny orange': '#ca6b02',
|
| 153 |
+
'nice blue': '#107ab0',
|
| 154 |
+
'sapphire': '#2138ab',
|
| 155 |
+
'greyish teal': '#719f91',
|
| 156 |
+
'orangey yellow': '#fdb915',
|
| 157 |
+
'parchment': '#fefcaf',
|
| 158 |
+
'straw': '#fcf679',
|
| 159 |
+
'very dark brown': '#1d0200',
|
| 160 |
+
'terracota': '#cb6843',
|
| 161 |
+
'ugly blue': '#31668a',
|
| 162 |
+
'clear blue': '#247afd',
|
| 163 |
+
'creme': '#ffffb6',
|
| 164 |
+
'foam green': '#90fda9',
|
| 165 |
+
'grey/green': '#86a17d',
|
| 166 |
+
'light gold': '#fddc5c',
|
| 167 |
+
'seafoam blue': '#78d1b6',
|
| 168 |
+
'topaz': '#13bbaf',
|
| 169 |
+
'violet pink': '#fb5ffc',
|
| 170 |
+
'wintergreen': '#20f986',
|
| 171 |
+
'yellow tan': '#ffe36e',
|
| 172 |
+
'dark fuchsia': '#9d0759',
|
| 173 |
+
'indigo blue': '#3a18b1',
|
| 174 |
+
'light yellowish green': '#c2ff89',
|
| 175 |
+
'pale magenta': '#d767ad',
|
| 176 |
+
'rich purple': '#720058',
|
| 177 |
+
'sunflower yellow': '#ffda03',
|
| 178 |
+
'green/blue': '#01c08d',
|
| 179 |
+
'leather': '#ac7434',
|
| 180 |
+
'racing green': '#014600',
|
| 181 |
+
'vivid purple': '#9900fa',
|
| 182 |
+
'dark royal blue': '#02066f',
|
| 183 |
+
'hazel': '#8e7618',
|
| 184 |
+
'muted pink': '#d1768f',
|
| 185 |
+
'booger green': '#96b403',
|
| 186 |
+
'canary': '#fdff63',
|
| 187 |
+
'cool grey': '#95a3a6',
|
| 188 |
+
'dark taupe': '#7f684e',
|
| 189 |
+
'darkish purple': '#751973',
|
| 190 |
+
'true green': '#089404',
|
| 191 |
+
'coral pink': '#ff6163',
|
| 192 |
+
'dark sage': '#598556',
|
| 193 |
+
'dark slate blue': '#214761',
|
| 194 |
+
'flat blue': '#3c73a8',
|
| 195 |
+
'mushroom': '#ba9e88',
|
| 196 |
+
'rich blue': '#021bf9',
|
| 197 |
+
'dirty purple': '#734a65',
|
| 198 |
+
'greenblue': '#23c48b',
|
| 199 |
+
'icky green': '#8fae22',
|
| 200 |
+
'light khaki': '#e6f2a2',
|
| 201 |
+
'warm blue': '#4b57db',
|
| 202 |
+
'dark hot pink': '#d90166',
|
| 203 |
+
'deep sea blue': '#015482',
|
| 204 |
+
'carmine': '#9d0216',
|
| 205 |
+
'dark yellow green': '#728f02',
|
| 206 |
+
'pale peach': '#ffe5ad',
|
| 207 |
+
'plum purple': '#4e0550',
|
| 208 |
+
'golden rod': '#f9bc08',
|
| 209 |
+
'neon red': '#ff073a',
|
| 210 |
+
'old pink': '#c77986',
|
| 211 |
+
'very pale blue': '#d6fffe',
|
| 212 |
+
'blood orange': '#fe4b03',
|
| 213 |
+
'grapefruit': '#fd5956',
|
| 214 |
+
'sand yellow': '#fce166',
|
| 215 |
+
'clay brown': '#b2713d',
|
| 216 |
+
'dark blue grey': '#1f3b4d',
|
| 217 |
+
'flat green': '#699d4c',
|
| 218 |
+
'light green blue': '#56fca2',
|
| 219 |
+
'warm pink': '#fb5581',
|
| 220 |
+
'dodger blue': '#3e82fc',
|
| 221 |
+
'gross green': '#a0bf16',
|
| 222 |
+
'ice': '#d6fffa',
|
| 223 |
+
'metallic blue': '#4f738e',
|
| 224 |
+
'pale salmon': '#ffb19a',
|
| 225 |
+
'sap green': '#5c8b15',
|
| 226 |
+
'algae': '#54ac68',
|
| 227 |
+
'bluey grey': '#89a0b0',
|
| 228 |
+
'greeny grey': '#7ea07a',
|
| 229 |
+
'highlighter green': '#1bfc06',
|
| 230 |
+
'light light blue': '#cafffb',
|
| 231 |
+
'light mint': '#b6ffbb',
|
| 232 |
+
'raw umber': '#a75e09',
|
| 233 |
+
'vivid blue': '#152eff',
|
| 234 |
+
'deep lavender': '#8d5eb7',
|
| 235 |
+
'dull teal': '#5f9e8f',
|
| 236 |
+
'light greenish blue': '#63f7b4',
|
| 237 |
+
'mud green': '#606602',
|
| 238 |
+
'pinky': '#fc86aa',
|
| 239 |
+
'red wine': '#8c0034',
|
| 240 |
+
'shit green': '#758000',
|
| 241 |
+
'tan brown': '#ab7e4c',
|
| 242 |
+
'darkblue': '#030764',
|
| 243 |
+
'rosa': '#fe86a4',
|
| 244 |
+
'lipstick': '#d5174e',
|
| 245 |
+
'pale mauve': '#fed0fc',
|
| 246 |
+
'claret': '#680018',
|
| 247 |
+
'dandelion': '#fedf08',
|
| 248 |
+
'orangered': '#fe420f',
|
| 249 |
+
'poop green': '#6f7c00',
|
| 250 |
+
'ruby': '#ca0147',
|
| 251 |
+
'dark': '#1b2431',
|
| 252 |
+
'greenish turquoise': '#00fbb0',
|
| 253 |
+
'pastel red': '#db5856',
|
| 254 |
+
'piss yellow': '#ddd618',
|
| 255 |
+
'bright cyan': '#41fdfe',
|
| 256 |
+
'dark coral': '#cf524e',
|
| 257 |
+
'algae green': '#21c36f',
|
| 258 |
+
'darkish red': '#a90308',
|
| 259 |
+
'reddy brown': '#6e1005',
|
| 260 |
+
'blush pink': '#fe828c',
|
| 261 |
+
'camouflage green': '#4b6113',
|
| 262 |
+
'lawn green': '#4da409',
|
| 263 |
+
'putty': '#beae8a',
|
| 264 |
+
'vibrant blue': '#0339f8',
|
| 265 |
+
'dark sand': '#a88f59',
|
| 266 |
+
'purple/blue': '#5d21d0',
|
| 267 |
+
'saffron': '#feb209',
|
| 268 |
+
'twilight': '#4e518b',
|
| 269 |
+
'warm brown': '#964e02',
|
| 270 |
+
'bluegrey': '#85a3b2',
|
| 271 |
+
'bubble gum pink': '#ff69af',
|
| 272 |
+
'duck egg blue': '#c3fbf4',
|
| 273 |
+
'greenish cyan': '#2afeb7',
|
| 274 |
+
'petrol': '#005f6a',
|
| 275 |
+
'royal': '#0c1793',
|
| 276 |
+
'butter': '#ffff81',
|
| 277 |
+
'dusty orange': '#f0833a',
|
| 278 |
+
'off yellow': '#f1f33f',
|
| 279 |
+
'pale olive green': '#b1d27b',
|
| 280 |
+
'orangish': '#fc824a',
|
| 281 |
+
'leaf': '#71aa34',
|
| 282 |
+
'light blue grey': '#b7c9e2',
|
| 283 |
+
'dried blood': '#4b0101',
|
| 284 |
+
'lightish purple': '#a552e6',
|
| 285 |
+
'rusty red': '#af2f0d',
|
| 286 |
+
'lavender blue': '#8b88f8',
|
| 287 |
+
'light grass green': '#9af764',
|
| 288 |
+
'light mint green': '#a6fbb2',
|
| 289 |
+
'sunflower': '#ffc512',
|
| 290 |
+
'velvet': '#750851',
|
| 291 |
+
'brick orange': '#c14a09',
|
| 292 |
+
'lightish red': '#fe2f4a',
|
| 293 |
+
'pure blue': '#0203e2',
|
| 294 |
+
'twilight blue': '#0a437a',
|
| 295 |
+
'violet red': '#a50055',
|
| 296 |
+
'yellowy brown': '#ae8b0c',
|
| 297 |
+
'carnation': '#fd798f',
|
| 298 |
+
'muddy yellow': '#bfac05',
|
| 299 |
+
'dark seafoam green': '#3eaf76',
|
| 300 |
+
'deep rose': '#c74767',
|
| 301 |
+
'dusty red': '#b9484e',
|
| 302 |
+
'grey/blue': '#647d8e',
|
| 303 |
+
'lemon lime': '#bffe28',
|
| 304 |
+
'purple/pink': '#d725de',
|
| 305 |
+
'brown yellow': '#b29705',
|
| 306 |
+
'purple brown': '#673a3f',
|
| 307 |
+
'wisteria': '#a87dc2',
|
| 308 |
+
'banana yellow': '#fafe4b',
|
| 309 |
+
'lipstick red': '#c0022f',
|
| 310 |
+
'water blue': '#0e87cc',
|
| 311 |
+
'brown grey': '#8d8468',
|
| 312 |
+
'vibrant purple': '#ad03de',
|
| 313 |
+
'baby green': '#8cff9e',
|
| 314 |
+
'barf green': '#94ac02',
|
| 315 |
+
'eggshell blue': '#c4fff7',
|
| 316 |
+
'sandy yellow': '#fdee73',
|
| 317 |
+
'cool green': '#33b864',
|
| 318 |
+
'pale': '#fff9d0',
|
| 319 |
+
'blue/grey': '#758da3',
|
| 320 |
+
'hot magenta': '#f504c9',
|
| 321 |
+
'greyblue': '#77a1b5',
|
| 322 |
+
'purpley': '#8756e4',
|
| 323 |
+
'baby shit green': '#889717',
|
| 324 |
+
'brownish pink': '#c27e79',
|
| 325 |
+
'dark aquamarine': '#017371',
|
| 326 |
+
'diarrhea': '#9f8303',
|
| 327 |
+
'light mustard': '#f7d560',
|
| 328 |
+
'pale sky blue': '#bdf6fe',
|
| 329 |
+
'turtle green': '#75b84f',
|
| 330 |
+
'bright olive': '#9cbb04',
|
| 331 |
+
'dark grey blue': '#29465b',
|
| 332 |
+
'greeny brown': '#696006',
|
| 333 |
+
'lemon green': '#adf802',
|
| 334 |
+
'light periwinkle': '#c1c6fc',
|
| 335 |
+
'seaweed green': '#35ad6b',
|
| 336 |
+
'sunshine yellow': '#fffd37',
|
| 337 |
+
'ugly purple': '#a442a0',
|
| 338 |
+
'medium pink': '#f36196',
|
| 339 |
+
'puke brown': '#947706',
|
| 340 |
+
'very light pink': '#fff4f2',
|
| 341 |
+
'viridian': '#1e9167',
|
| 342 |
+
'bile': '#b5c306',
|
| 343 |
+
'faded yellow': '#feff7f',
|
| 344 |
+
'very pale green': '#cffdbc',
|
| 345 |
+
'vibrant green': '#0add08',
|
| 346 |
+
'bright lime': '#87fd05',
|
| 347 |
+
'spearmint': '#1ef876',
|
| 348 |
+
'light aquamarine': '#7bfdc7',
|
| 349 |
+
'light sage': '#bcecac',
|
| 350 |
+
'yellowgreen': '#bbf90f',
|
| 351 |
+
'baby poo': '#ab9004',
|
| 352 |
+
'dark seafoam': '#1fb57a',
|
| 353 |
+
'deep teal': '#00555a',
|
| 354 |
+
'heather': '#a484ac',
|
| 355 |
+
'rust orange': '#c45508',
|
| 356 |
+
'dirty blue': '#3f829d',
|
| 357 |
+
'fern green': '#548d44',
|
| 358 |
+
'bright lilac': '#c95efb',
|
| 359 |
+
'weird green': '#3ae57f',
|
| 360 |
+
'peacock blue': '#016795',
|
| 361 |
+
'avocado green': '#87a922',
|
| 362 |
+
'faded orange': '#f0944d',
|
| 363 |
+
'grape purple': '#5d1451',
|
| 364 |
+
'hot green': '#25ff29',
|
| 365 |
+
'lime yellow': '#d0fe1d',
|
| 366 |
+
'mango': '#ffa62b',
|
| 367 |
+
'shamrock': '#01b44c',
|
| 368 |
+
'bubblegum': '#ff6cb5',
|
| 369 |
+
'purplish brown': '#6b4247',
|
| 370 |
+
'vomit yellow': '#c7c10c',
|
| 371 |
+
'pale cyan': '#b7fffa',
|
| 372 |
+
'key lime': '#aeff6e',
|
| 373 |
+
'tomato red': '#ec2d01',
|
| 374 |
+
'lightgreen': '#76ff7b',
|
| 375 |
+
'merlot': '#730039',
|
| 376 |
+
'night blue': '#040348',
|
| 377 |
+
'purpleish pink': '#df4ec8',
|
| 378 |
+
'apple': '#6ecb3c',
|
| 379 |
+
'baby poop green': '#8f9805',
|
| 380 |
+
'green apple': '#5edc1f',
|
| 381 |
+
'heliotrope': '#d94ff5',
|
| 382 |
+
'yellow/green': '#c8fd3d',
|
| 383 |
+
'almost black': '#070d0d',
|
| 384 |
+
'cool blue': '#4984b8',
|
| 385 |
+
'leafy green': '#51b73b',
|
| 386 |
+
'mustard brown': '#ac7e04',
|
| 387 |
+
'dusk': '#4e5481',
|
| 388 |
+
'dull brown': '#876e4b',
|
| 389 |
+
'frog green': '#58bc08',
|
| 390 |
+
'vivid green': '#2fef10',
|
| 391 |
+
'bright light green': '#2dfe54',
|
| 392 |
+
'fluro green': '#0aff02',
|
| 393 |
+
'kiwi': '#9cef43',
|
| 394 |
+
'seaweed': '#18d17b',
|
| 395 |
+
'navy green': '#35530a',
|
| 396 |
+
'ultramarine blue': '#1805db',
|
| 397 |
+
'iris': '#6258c4',
|
| 398 |
+
'pastel orange': '#ff964f',
|
| 399 |
+
'yellowish orange': '#ffab0f',
|
| 400 |
+
'perrywinkle': '#8f8ce7',
|
| 401 |
+
'tealish': '#24bca8',
|
| 402 |
+
'dark plum': '#3f012c',
|
| 403 |
+
'pear': '#cbf85f',
|
| 404 |
+
'pinkish orange': '#ff724c',
|
| 405 |
+
'midnight purple': '#280137',
|
| 406 |
+
'light urple': '#b36ff6',
|
| 407 |
+
'dark mint': '#48c072',
|
| 408 |
+
'greenish tan': '#bccb7a',
|
| 409 |
+
'light burgundy': '#a8415b',
|
| 410 |
+
'turquoise blue': '#06b1c4',
|
| 411 |
+
'ugly pink': '#cd7584',
|
| 412 |
+
'sandy': '#f1da7a',
|
| 413 |
+
'electric pink': '#ff0490',
|
| 414 |
+
'muted purple': '#805b87',
|
| 415 |
+
'mid green': '#50a747',
|
| 416 |
+
'greyish': '#a8a495',
|
| 417 |
+
'neon yellow': '#cfff04',
|
| 418 |
+
'banana': '#ffff7e',
|
| 419 |
+
'carnation pink': '#ff7fa7',
|
| 420 |
+
'tomato': '#ef4026',
|
| 421 |
+
'sea': '#3c9992',
|
| 422 |
+
'muddy brown': '#886806',
|
| 423 |
+
'turquoise green': '#04f489',
|
| 424 |
+
'buff': '#fef69e',
|
| 425 |
+
'fawn': '#cfaf7b',
|
| 426 |
+
'muted blue': '#3b719f',
|
| 427 |
+
'pale rose': '#fdc1c5',
|
| 428 |
+
'dark mint green': '#20c073',
|
| 429 |
+
'amethyst': '#9b5fc0',
|
| 430 |
+
'blue/green': '#0f9b8e',
|
| 431 |
+
'chestnut': '#742802',
|
| 432 |
+
'sick green': '#9db92c',
|
| 433 |
+
'pea': '#a4bf20',
|
| 434 |
+
'rusty orange': '#cd5909',
|
| 435 |
+
'stone': '#ada587',
|
| 436 |
+
'rose red': '#be013c',
|
| 437 |
+
'pale aqua': '#b8ffeb',
|
| 438 |
+
'deep orange': '#dc4d01',
|
| 439 |
+
'earth': '#a2653e',
|
| 440 |
+
'mossy green': '#638b27',
|
| 441 |
+
'grassy green': '#419c03',
|
| 442 |
+
'pale lime green': '#b1ff65',
|
| 443 |
+
'light grey blue': '#9dbcd4',
|
| 444 |
+
'pale grey': '#fdfdfe',
|
| 445 |
+
'asparagus': '#77ab56',
|
| 446 |
+
'blueberry': '#464196',
|
| 447 |
+
'purple red': '#990147',
|
| 448 |
+
'pale lime': '#befd73',
|
| 449 |
+
'greenish teal': '#32bf84',
|
| 450 |
+
'caramel': '#af6f09',
|
| 451 |
+
'deep magenta': '#a0025c',
|
| 452 |
+
'light peach': '#ffd8b1',
|
| 453 |
+
'milk chocolate': '#7f4e1e',
|
| 454 |
+
'ocher': '#bf9b0c',
|
| 455 |
+
'off green': '#6ba353',
|
| 456 |
+
'purply pink': '#f075e6',
|
| 457 |
+
'lightblue': '#7bc8f6',
|
| 458 |
+
'dusky blue': '#475f94',
|
| 459 |
+
'golden': '#f5bf03',
|
| 460 |
+
'light beige': '#fffeb6',
|
| 461 |
+
'butter yellow': '#fffd74',
|
| 462 |
+
'dusky purple': '#895b7b',
|
| 463 |
+
'french blue': '#436bad',
|
| 464 |
+
'ugly yellow': '#d0c101',
|
| 465 |
+
'greeny yellow': '#c6f808',
|
| 466 |
+
'orangish red': '#f43605',
|
| 467 |
+
'shamrock green': '#02c14d',
|
| 468 |
+
'orangish brown': '#b25f03',
|
| 469 |
+
'tree green': '#2a7e19',
|
| 470 |
+
'deep violet': '#490648',
|
| 471 |
+
'gunmetal': '#536267',
|
| 472 |
+
'blue/purple': '#5a06ef',
|
| 473 |
+
'cherry': '#cf0234',
|
| 474 |
+
'sandy brown': '#c4a661',
|
| 475 |
+
'warm grey': '#978a84',
|
| 476 |
+
'dark indigo': '#1f0954',
|
| 477 |
+
'midnight': '#03012d',
|
| 478 |
+
'bluey green': '#2bb179',
|
| 479 |
+
'grey pink': '#c3909b',
|
| 480 |
+
'soft purple': '#a66fb5',
|
| 481 |
+
'blood': '#770001',
|
| 482 |
+
'brown red': '#922b05',
|
| 483 |
+
'medium grey': '#7d7f7c',
|
| 484 |
+
'berry': '#990f4b',
|
| 485 |
+
'poo': '#8f7303',
|
| 486 |
+
'purpley pink': '#c83cb9',
|
| 487 |
+
'light salmon': '#fea993',
|
| 488 |
+
'snot': '#acbb0d',
|
| 489 |
+
'easter purple': '#c071fe',
|
| 490 |
+
'light yellow green': '#ccfd7f',
|
| 491 |
+
'dark navy blue': '#00022e',
|
| 492 |
+
'drab': '#828344',
|
| 493 |
+
'light rose': '#ffc5cb',
|
| 494 |
+
'rouge': '#ab1239',
|
| 495 |
+
'purplish red': '#b0054b',
|
| 496 |
+
'slime green': '#99cc04',
|
| 497 |
+
'baby poop': '#937c00',
|
| 498 |
+
'irish green': '#019529',
|
| 499 |
+
'pink/purple': '#ef1de7',
|
| 500 |
+
'dark navy': '#000435',
|
| 501 |
+
'greeny blue': '#42b395',
|
| 502 |
+
'light plum': '#9d5783',
|
| 503 |
+
'pinkish grey': '#c8aca9',
|
| 504 |
+
'dirty orange': '#c87606',
|
| 505 |
+
'rust red': '#aa2704',
|
| 506 |
+
'pale lilac': '#e4cbff',
|
| 507 |
+
'orangey red': '#fa4224',
|
| 508 |
+
'primary blue': '#0804f9',
|
| 509 |
+
'kermit green': '#5cb200',
|
| 510 |
+
'brownish purple': '#76424e',
|
| 511 |
+
'murky green': '#6c7a0e',
|
| 512 |
+
'wheat': '#fbdd7e',
|
| 513 |
+
'very dark purple': '#2a0134',
|
| 514 |
+
'bottle green': '#044a05',
|
| 515 |
+
'watermelon': '#fd4659',
|
| 516 |
+
'deep sky blue': '#0d75f8',
|
| 517 |
+
'fire engine red': '#fe0002',
|
| 518 |
+
'yellow ochre': '#cb9d06',
|
| 519 |
+
'pumpkin orange': '#fb7d07',
|
| 520 |
+
'pale olive': '#b9cc81',
|
| 521 |
+
'light lilac': '#edc8ff',
|
| 522 |
+
'lightish green': '#61e160',
|
| 523 |
+
'carolina blue': '#8ab8fe',
|
| 524 |
+
'mulberry': '#920a4e',
|
| 525 |
+
'shocking pink': '#fe02a2',
|
| 526 |
+
'auburn': '#9a3001',
|
| 527 |
+
'bright lime green': '#65fe08',
|
| 528 |
+
'celadon': '#befdb7',
|
| 529 |
+
'pinkish brown': '#b17261',
|
| 530 |
+
'poo brown': '#885f01',
|
| 531 |
+
'bright sky blue': '#02ccfe',
|
| 532 |
+
'celery': '#c1fd95',
|
| 533 |
+
'dirt brown': '#836539',
|
| 534 |
+
'strawberry': '#fb2943',
|
| 535 |
+
'dark lime': '#84b701',
|
| 536 |
+
'copper': '#b66325',
|
| 537 |
+
'medium brown': '#7f5112',
|
| 538 |
+
'muted green': '#5fa052',
|
| 539 |
+
"robin's egg": '#6dedfd',
|
| 540 |
+
'bright aqua': '#0bf9ea',
|
| 541 |
+
'bright lavender': '#c760ff',
|
| 542 |
+
'ivory': '#ffffcb',
|
| 543 |
+
'very light purple': '#f6cefc',
|
| 544 |
+
'light navy': '#155084',
|
| 545 |
+
'pink red': '#f5054f',
|
| 546 |
+
'olive brown': '#645403',
|
| 547 |
+
'poop brown': '#7a5901',
|
| 548 |
+
'mustard green': '#a8b504',
|
| 549 |
+
'ocean green': '#3d9973',
|
| 550 |
+
'very dark blue': '#000133',
|
| 551 |
+
'dusty green': '#76a973',
|
| 552 |
+
'light navy blue': '#2e5a88',
|
| 553 |
+
'minty green': '#0bf77d',
|
| 554 |
+
'adobe': '#bd6c48',
|
| 555 |
+
'barney': '#ac1db8',
|
| 556 |
+
'jade green': '#2baf6a',
|
| 557 |
+
'bright light blue': '#26f7fd',
|
| 558 |
+
'light lime': '#aefd6c',
|
| 559 |
+
'dark khaki': '#9b8f55',
|
| 560 |
+
'orange yellow': '#ffad01',
|
| 561 |
+
'ocre': '#c69c04',
|
| 562 |
+
'maize': '#f4d054',
|
| 563 |
+
'faded pink': '#de9dac',
|
| 564 |
+
'british racing green': '#05480d',
|
| 565 |
+
'sandstone': '#c9ae74',
|
| 566 |
+
'mud brown': '#60460f',
|
| 567 |
+
'light sea green': '#98f6b0',
|
| 568 |
+
'robin egg blue': '#8af1fe',
|
| 569 |
+
'aqua marine': '#2ee8bb',
|
| 570 |
+
'dark sea green': '#11875d',
|
| 571 |
+
'soft pink': '#fdb0c0',
|
| 572 |
+
'orangey brown': '#b16002',
|
| 573 |
+
'cherry red': '#f7022a',
|
| 574 |
+
'burnt yellow': '#d5ab09',
|
| 575 |
+
'brownish grey': '#86775f',
|
| 576 |
+
'camel': '#c69f59',
|
| 577 |
+
'purplish grey': '#7a687f',
|
| 578 |
+
'marine': '#042e60',
|
| 579 |
+
'greyish pink': '#c88d94',
|
| 580 |
+
'pale turquoise': '#a5fbd5',
|
| 581 |
+
'pastel yellow': '#fffe71',
|
| 582 |
+
'bluey purple': '#6241c7',
|
| 583 |
+
'canary yellow': '#fffe40',
|
| 584 |
+
'faded red': '#d3494e',
|
| 585 |
+
'sepia': '#985e2b',
|
| 586 |
+
'coffee': '#a6814c',
|
| 587 |
+
'bright magenta': '#ff08e8',
|
| 588 |
+
'mocha': '#9d7651',
|
| 589 |
+
'ecru': '#feffca',
|
| 590 |
+
'purpleish': '#98568d',
|
| 591 |
+
'cranberry': '#9e003a',
|
| 592 |
+
'darkish green': '#287c37',
|
| 593 |
+
'brown orange': '#b96902',
|
| 594 |
+
'dusky rose': '#ba6873',
|
| 595 |
+
'melon': '#ff7855',
|
| 596 |
+
'sickly green': '#94b21c',
|
| 597 |
+
'silver': '#c5c9c7',
|
| 598 |
+
'purply blue': '#661aee',
|
| 599 |
+
'purpleish blue': '#6140ef',
|
| 600 |
+
'hospital green': '#9be5aa',
|
| 601 |
+
'shit brown': '#7b5804',
|
| 602 |
+
'mid blue': '#276ab3',
|
| 603 |
+
'amber': '#feb308',
|
| 604 |
+
'easter green': '#8cfd7e',
|
| 605 |
+
'soft blue': '#6488ea',
|
| 606 |
+
'cerulean blue': '#056eee',
|
| 607 |
+
'golden brown': '#b27a01',
|
| 608 |
+
'bright turquoise': '#0ffef9',
|
| 609 |
+
'red pink': '#fa2a55',
|
| 610 |
+
'red purple': '#820747',
|
| 611 |
+
'greyish brown': '#7a6a4f',
|
| 612 |
+
'vermillion': '#f4320c',
|
| 613 |
+
'russet': '#a13905',
|
| 614 |
+
'steel grey': '#6f828a',
|
| 615 |
+
'lighter purple': '#a55af4',
|
| 616 |
+
'bright violet': '#ad0afd',
|
| 617 |
+
'prussian blue': '#004577',
|
| 618 |
+
'slate green': '#658d6d',
|
| 619 |
+
'dirty pink': '#ca7b80',
|
| 620 |
+
'dark blue green': '#005249',
|
| 621 |
+
'pine': '#2b5d34',
|
| 622 |
+
'yellowy green': '#bff128',
|
| 623 |
+
'dark gold': '#b59410',
|
| 624 |
+
'bluish': '#2976bb',
|
| 625 |
+
'darkish blue': '#014182',
|
| 626 |
+
'dull red': '#bb3f3f',
|
| 627 |
+
'pinky red': '#fc2647',
|
| 628 |
+
'bronze': '#a87900',
|
| 629 |
+
'pale teal': '#82cbb2',
|
| 630 |
+
'military green': '#667c3e',
|
| 631 |
+
'barbie pink': '#fe46a5',
|
| 632 |
+
'bubblegum pink': '#fe83cc',
|
| 633 |
+
'pea soup green': '#94a617',
|
| 634 |
+
'dark mustard': '#a88905',
|
| 635 |
+
'shit': '#7f5f00',
|
| 636 |
+
'medium purple': '#9e43a2',
|
| 637 |
+
'very dark green': '#062e03',
|
| 638 |
+
'dirt': '#8a6e45',
|
| 639 |
+
'dusky pink': '#cc7a8b',
|
| 640 |
+
'red violet': '#9e0168',
|
| 641 |
+
'lemon yellow': '#fdff38',
|
| 642 |
+
'pistachio': '#c0fa8b',
|
| 643 |
+
'dull yellow': '#eedc5b',
|
| 644 |
+
'dark lime green': '#7ebd01',
|
| 645 |
+
'denim blue': '#3b5b92',
|
| 646 |
+
'teal blue': '#01889f',
|
| 647 |
+
'lightish blue': '#3d7afd',
|
| 648 |
+
'purpley blue': '#5f34e7',
|
| 649 |
+
'light indigo': '#6d5acf',
|
| 650 |
+
'swamp green': '#748500',
|
| 651 |
+
'brown green': '#706c11',
|
| 652 |
+
'dark maroon': '#3c0008',
|
| 653 |
+
'hot purple': '#cb00f5',
|
| 654 |
+
'dark forest green': '#002d04',
|
| 655 |
+
'faded blue': '#658cbb',
|
| 656 |
+
'drab green': '#749551',
|
| 657 |
+
'light lime green': '#b9ff66',
|
| 658 |
+
'snot green': '#9dc100',
|
| 659 |
+
'yellowish': '#faee66',
|
| 660 |
+
'light blue green': '#7efbb3',
|
| 661 |
+
'bordeaux': '#7b002c',
|
| 662 |
+
'light mauve': '#c292a1',
|
| 663 |
+
'ocean': '#017b92',
|
| 664 |
+
'marigold': '#fcc006',
|
| 665 |
+
'muddy green': '#657432',
|
| 666 |
+
'dull orange': '#d8863b',
|
| 667 |
+
'steel': '#738595',
|
| 668 |
+
'electric purple': '#aa23ff',
|
| 669 |
+
'fluorescent green': '#08ff08',
|
| 670 |
+
'yellowish brown': '#9b7a01',
|
| 671 |
+
'blush': '#f29e8e',
|
| 672 |
+
'soft green': '#6fc276',
|
| 673 |
+
'bright orange': '#ff5b00',
|
| 674 |
+
'lemon': '#fdff52',
|
| 675 |
+
'purple grey': '#866f85',
|
| 676 |
+
'acid green': '#8ffe09',
|
| 677 |
+
'pale lavender': '#eecffe',
|
| 678 |
+
'violet blue': '#510ac9',
|
| 679 |
+
'light forest green': '#4f9153',
|
| 680 |
+
'burnt red': '#9f2305',
|
| 681 |
+
'khaki green': '#728639',
|
| 682 |
+
'cerise': '#de0c62',
|
| 683 |
+
'faded purple': '#916e99',
|
| 684 |
+
'apricot': '#ffb16d',
|
| 685 |
+
'dark olive green': '#3c4d03',
|
| 686 |
+
'grey brown': '#7f7053',
|
| 687 |
+
'green grey': '#77926f',
|
| 688 |
+
'true blue': '#010fcc',
|
| 689 |
+
'pale violet': '#ceaefa',
|
| 690 |
+
'periwinkle blue': '#8f99fb',
|
| 691 |
+
'light sky blue': '#c6fcff',
|
| 692 |
+
'blurple': '#5539cc',
|
| 693 |
+
'green brown': '#544e03',
|
| 694 |
+
'bluegreen': '#017a79',
|
| 695 |
+
'bright teal': '#01f9c6',
|
| 696 |
+
'brownish yellow': '#c9b003',
|
| 697 |
+
'pea soup': '#929901',
|
| 698 |
+
'forest': '#0b5509',
|
| 699 |
+
'barney purple': '#a00498',
|
| 700 |
+
'ultramarine': '#2000b1',
|
| 701 |
+
'purplish': '#94568c',
|
| 702 |
+
'puke yellow': '#c2be0e',
|
| 703 |
+
'bluish grey': '#748b97',
|
| 704 |
+
'dark periwinkle': '#665fd1',
|
| 705 |
+
'dark lilac': '#9c6da5',
|
| 706 |
+
'reddish': '#c44240',
|
| 707 |
+
'light maroon': '#a24857',
|
| 708 |
+
'dusty purple': '#825f87',
|
| 709 |
+
'terra cotta': '#c9643b',
|
| 710 |
+
'avocado': '#90b134',
|
| 711 |
+
'marine blue': '#01386a',
|
| 712 |
+
'teal green': '#25a36f',
|
| 713 |
+
'slate grey': '#59656d',
|
| 714 |
+
'lighter green': '#75fd63',
|
| 715 |
+
'electric green': '#21fc0d',
|
| 716 |
+
'dusty blue': '#5a86ad',
|
| 717 |
+
'golden yellow': '#fec615',
|
| 718 |
+
'bright yellow': '#fffd01',
|
| 719 |
+
'light lavender': '#dfc5fe',
|
| 720 |
+
'umber': '#b26400',
|
| 721 |
+
'poop': '#7f5e00',
|
| 722 |
+
'dark peach': '#de7e5d',
|
| 723 |
+
'jungle green': '#048243',
|
| 724 |
+
'eggshell': '#ffffd4',
|
| 725 |
+
'denim': '#3b638c',
|
| 726 |
+
'yellow brown': '#b79400',
|
| 727 |
+
'dull purple': '#84597e',
|
| 728 |
+
'chocolate brown': '#411900',
|
| 729 |
+
'wine red': '#7b0323',
|
| 730 |
+
'neon blue': '#04d9ff',
|
| 731 |
+
'dirty green': '#667e2c',
|
| 732 |
+
'light tan': '#fbeeac',
|
| 733 |
+
'ice blue': '#d7fffe',
|
| 734 |
+
'cadet blue': '#4e7496',
|
| 735 |
+
'dark mauve': '#874c62',
|
| 736 |
+
'very light blue': '#d5ffff',
|
| 737 |
+
'grey purple': '#826d8c',
|
| 738 |
+
'pastel pink': '#ffbacd',
|
| 739 |
+
'very light green': '#d1ffbd',
|
| 740 |
+
'dark sky blue': '#448ee4',
|
| 741 |
+
'evergreen': '#05472a',
|
| 742 |
+
'dull pink': '#d5869d',
|
| 743 |
+
'aubergine': '#3d0734',
|
| 744 |
+
'mahogany': '#4a0100',
|
| 745 |
+
'reddish orange': '#f8481c',
|
| 746 |
+
'deep green': '#02590f',
|
| 747 |
+
'vomit green': '#89a203',
|
| 748 |
+
'purple pink': '#e03fd8',
|
| 749 |
+
'dusty pink': '#d58a94',
|
| 750 |
+
'faded green': '#7bb274',
|
| 751 |
+
'camo green': '#526525',
|
| 752 |
+
'pinky purple': '#c94cbe',
|
| 753 |
+
'pink purple': '#db4bda',
|
| 754 |
+
'brownish red': '#9e3623',
|
| 755 |
+
'dark rose': '#b5485d',
|
| 756 |
+
'mud': '#735c12',
|
| 757 |
+
'brownish': '#9c6d57',
|
| 758 |
+
'emerald green': '#028f1e',
|
| 759 |
+
'pale brown': '#b1916e',
|
| 760 |
+
'dull blue': '#49759c',
|
| 761 |
+
'burnt umber': '#a0450e',
|
| 762 |
+
'medium green': '#39ad48',
|
| 763 |
+
'clay': '#b66a50',
|
| 764 |
+
'light aqua': '#8cffdb',
|
| 765 |
+
'light olive green': '#a4be5c',
|
| 766 |
+
'brownish orange': '#cb7723',
|
| 767 |
+
'dark aqua': '#05696b',
|
| 768 |
+
'purplish pink': '#ce5dae',
|
| 769 |
+
'dark salmon': '#c85a53',
|
| 770 |
+
'greenish grey': '#96ae8d',
|
| 771 |
+
'jade': '#1fa774',
|
| 772 |
+
'ugly green': '#7a9703',
|
| 773 |
+
'dark beige': '#ac9362',
|
| 774 |
+
'emerald': '#01a049',
|
| 775 |
+
'pale red': '#d9544d',
|
| 776 |
+
'light magenta': '#fa5ff7',
|
| 777 |
+
'sky': '#82cafc',
|
| 778 |
+
'light cyan': '#acfffc',
|
| 779 |
+
'yellow orange': '#fcb001',
|
| 780 |
+
'reddish purple': '#910951',
|
| 781 |
+
'reddish pink': '#fe2c54',
|
| 782 |
+
'orchid': '#c875c4',
|
| 783 |
+
'dirty yellow': '#cdc50a',
|
| 784 |
+
'orange red': '#fd411e',
|
| 785 |
+
'deep red': '#9a0200',
|
| 786 |
+
'orange brown': '#be6400',
|
| 787 |
+
'cobalt blue': '#030aa7',
|
| 788 |
+
'neon pink': '#fe019a',
|
| 789 |
+
'rose pink': '#f7879a',
|
| 790 |
+
'greyish purple': '#887191',
|
| 791 |
+
'raspberry': '#b00149',
|
| 792 |
+
'aqua green': '#12e193',
|
| 793 |
+
'salmon pink': '#fe7b7c',
|
| 794 |
+
'tangerine': '#ff9408',
|
| 795 |
+
'brownish green': '#6a6e09',
|
| 796 |
+
'red brown': '#8b2e16',
|
| 797 |
+
'greenish brown': '#696112',
|
| 798 |
+
'pumpkin': '#e17701',
|
| 799 |
+
'pine green': '#0a481e',
|
| 800 |
+
'charcoal': '#343837',
|
| 801 |
+
'baby pink': '#ffb7ce',
|
| 802 |
+
'cornflower': '#6a79f7',
|
| 803 |
+
'blue violet': '#5d06e9',
|
| 804 |
+
'chocolate': '#3d1c02',
|
| 805 |
+
'greyish green': '#82a67d',
|
| 806 |
+
'scarlet': '#be0119',
|
| 807 |
+
'green yellow': '#c9ff27',
|
| 808 |
+
'dark olive': '#373e02',
|
| 809 |
+
'sienna': '#a9561e',
|
| 810 |
+
'pastel purple': '#caa0ff',
|
| 811 |
+
'terracotta': '#ca6641',
|
| 812 |
+
'aqua blue': '#02d8e9',
|
| 813 |
+
'sage green': '#88b378',
|
| 814 |
+
'blood red': '#980002',
|
| 815 |
+
'deep pink': '#cb0162',
|
| 816 |
+
'grass': '#5cac2d',
|
| 817 |
+
'moss': '#769958',
|
| 818 |
+
'pastel blue': '#a2bffe',
|
| 819 |
+
'bluish green': '#10a674',
|
| 820 |
+
'green blue': '#06b48b',
|
| 821 |
+
'dark tan': '#af884a',
|
| 822 |
+
'greenish blue': '#0b8b87',
|
| 823 |
+
'pale orange': '#ffa756',
|
| 824 |
+
'vomit': '#a2a415',
|
| 825 |
+
'forrest green': '#154406',
|
| 826 |
+
'dark lavender': '#856798',
|
| 827 |
+
'dark violet': '#34013f',
|
| 828 |
+
'purple blue': '#632de9',
|
| 829 |
+
'dark cyan': '#0a888a',
|
| 830 |
+
'olive drab': '#6f7632',
|
| 831 |
+
'pinkish': '#d46a7e',
|
| 832 |
+
'cobalt': '#1e488f',
|
| 833 |
+
'neon purple': '#bc13fe',
|
| 834 |
+
'light turquoise': '#7ef4cc',
|
| 835 |
+
'apple green': '#76cd26',
|
| 836 |
+
'dull green': '#74a662',
|
| 837 |
+
'wine': '#80013f',
|
| 838 |
+
'powder blue': '#b1d1fc',
|
| 839 |
+
'off white': '#ffffe4',
|
| 840 |
+
'electric blue': '#0652ff',
|
| 841 |
+
'dark turquoise': '#045c5a',
|
| 842 |
+
'blue purple': '#5729ce',
|
| 843 |
+
'azure': '#069af3',
|
| 844 |
+
'bright red': '#ff000d',
|
| 845 |
+
'pinkish red': '#f10c45',
|
| 846 |
+
'cornflower blue': '#5170d7',
|
| 847 |
+
'light olive': '#acbf69',
|
| 848 |
+
'grape': '#6c3461',
|
| 849 |
+
'greyish blue': '#5e819d',
|
| 850 |
+
'purplish blue': '#601ef9',
|
| 851 |
+
'yellowish green': '#b0dd16',
|
| 852 |
+
'greenish yellow': '#cdfd02',
|
| 853 |
+
'medium blue': '#2c6fbb',
|
| 854 |
+
'dusty rose': '#c0737a',
|
| 855 |
+
'light violet': '#d6b4fc',
|
| 856 |
+
'midnight blue': '#020035',
|
| 857 |
+
'bluish purple': '#703be7',
|
| 858 |
+
'red orange': '#fd3c06',
|
| 859 |
+
'dark magenta': '#960056',
|
| 860 |
+
'greenish': '#40a368',
|
| 861 |
+
'ocean blue': '#03719c',
|
| 862 |
+
'coral': '#fc5a50',
|
| 863 |
+
'cream': '#ffffc2',
|
| 864 |
+
'reddish brown': '#7f2b0a',
|
| 865 |
+
'burnt sienna': '#b04e0f',
|
| 866 |
+
'brick': '#a03623',
|
| 867 |
+
'sage': '#87ae73',
|
| 868 |
+
'grey green': '#789b73',
|
| 869 |
+
'white': '#ffffff',
|
| 870 |
+
"robin's egg blue": '#98eff9',
|
| 871 |
+
'moss green': '#658b38',
|
| 872 |
+
'steel blue': '#5a7d9a',
|
| 873 |
+
'eggplant': '#380835',
|
| 874 |
+
'light yellow': '#fffe7a',
|
| 875 |
+
'leaf green': '#5ca904',
|
| 876 |
+
'light grey': '#d8dcd6',
|
| 877 |
+
'puke': '#a5a502',
|
| 878 |
+
'pinkish purple': '#d648d7',
|
| 879 |
+
'sea blue': '#047495',
|
| 880 |
+
'pale purple': '#b790d4',
|
| 881 |
+
'slate blue': '#5b7c99',
|
| 882 |
+
'blue grey': '#607c8e',
|
| 883 |
+
'hunter green': '#0b4008',
|
| 884 |
+
'fuchsia': '#ed0dd9',
|
| 885 |
+
'crimson': '#8c000f',
|
| 886 |
+
'pale yellow': '#ffff84',
|
| 887 |
+
'ochre': '#bf9005',
|
| 888 |
+
'mustard yellow': '#d2bd0a',
|
| 889 |
+
'light red': '#ff474c',
|
| 890 |
+
'cerulean': '#0485d1',
|
| 891 |
+
'pale pink': '#ffcfdc',
|
| 892 |
+
'deep blue': '#040273',
|
| 893 |
+
'rust': '#a83c09',
|
| 894 |
+
'light teal': '#90e4c1',
|
| 895 |
+
'slate': '#516572',
|
| 896 |
+
'goldenrod': '#fac205',
|
| 897 |
+
'dark yellow': '#d5b60a',
|
| 898 |
+
'dark grey': '#363737',
|
| 899 |
+
'army green': '#4b5d16',
|
| 900 |
+
'grey blue': '#6b8ba4',
|
| 901 |
+
'seafoam': '#80f9ad',
|
| 902 |
+
'puce': '#a57e52',
|
| 903 |
+
'spring green': '#a9f971',
|
| 904 |
+
'dark orange': '#c65102',
|
| 905 |
+
'sand': '#e2ca76',
|
| 906 |
+
'pastel green': '#b0ff9d',
|
| 907 |
+
'mint': '#9ffeb0',
|
| 908 |
+
'light orange': '#fdaa48',
|
| 909 |
+
'bright pink': '#fe01b1',
|
| 910 |
+
'chartreuse': '#c1f80a',
|
| 911 |
+
'deep purple': '#36013f',
|
| 912 |
+
'dark brown': '#341c02',
|
| 913 |
+
'taupe': '#b9a281',
|
| 914 |
+
'pea green': '#8eab12',
|
| 915 |
+
'puke green': '#9aae07',
|
| 916 |
+
'kelly green': '#02ab2e',
|
| 917 |
+
'seafoam green': '#7af9ab',
|
| 918 |
+
'blue green': '#137e6d',
|
| 919 |
+
'khaki': '#aaa662',
|
| 920 |
+
'burgundy': '#610023',
|
| 921 |
+
'dark teal': '#014d4e',
|
| 922 |
+
'brick red': '#8f1402',
|
| 923 |
+
'royal purple': '#4b006e',
|
| 924 |
+
'plum': '#580f41',
|
| 925 |
+
'mint green': '#8fff9f',
|
| 926 |
+
'gold': '#dbb40c',
|
| 927 |
+
'baby blue': '#a2cffe',
|
| 928 |
+
'yellow green': '#c0fb2d',
|
| 929 |
+
'bright purple': '#be03fd',
|
| 930 |
+
'dark red': '#840000',
|
| 931 |
+
'pale blue': '#d0fefe',
|
| 932 |
+
'grass green': '#3f9b0b',
|
| 933 |
+
'navy': '#01153e',
|
| 934 |
+
'aquamarine': '#04d8b2',
|
| 935 |
+
'burnt orange': '#c04e01',
|
| 936 |
+
'neon green': '#0cff0c',
|
| 937 |
+
'bright blue': '#0165fc',
|
| 938 |
+
'rose': '#cf6275',
|
| 939 |
+
'light pink': '#ffd1df',
|
| 940 |
+
'mustard': '#ceb301',
|
| 941 |
+
'indigo': '#380282',
|
| 942 |
+
'lime': '#aaff32',
|
| 943 |
+
'sea green': '#53fca1',
|
| 944 |
+
'periwinkle': '#8e82fe',
|
| 945 |
+
'dark pink': '#cb416b',
|
| 946 |
+
'olive green': '#677a04',
|
| 947 |
+
'peach': '#ffb07c',
|
| 948 |
+
'pale green': '#c7fdb5',
|
| 949 |
+
'light brown': '#ad8150',
|
| 950 |
+
'hot pink': '#ff028d',
|
| 951 |
+
'black': '#000000',
|
| 952 |
+
'lilac': '#cea2fd',
|
| 953 |
+
'navy blue': '#001146',
|
| 954 |
+
'royal blue': '#0504aa',
|
| 955 |
+
'beige': '#e6daa6',
|
| 956 |
+
'salmon': '#ff796c',
|
| 957 |
+
'olive': '#6e750e',
|
| 958 |
+
'maroon': '#650021',
|
| 959 |
+
'bright green': '#01ff07',
|
| 960 |
+
'dark purple': '#35063e',
|
| 961 |
+
'mauve': '#ae7181',
|
| 962 |
+
'forest green': '#06470c',
|
| 963 |
+
'aqua': '#13eac9',
|
| 964 |
+
'cyan': '#00ffff',
|
| 965 |
+
'tan': '#d1b26f',
|
| 966 |
+
'dark blue': '#00035b',
|
| 967 |
+
'lavender': '#c79fef',
|
| 968 |
+
'turquoise': '#06c2ac',
|
| 969 |
+
'dark green': '#033500',
|
| 970 |
+
'violet': '#9a0eea',
|
| 971 |
+
'light purple': '#bf77f6',
|
| 972 |
+
'lime green': '#89fe05',
|
| 973 |
+
'grey': '#929591',
|
| 974 |
+
'sky blue': '#75bbfd',
|
| 975 |
+
'yellow': '#ffff14',
|
| 976 |
+
'magenta': '#c20078',
|
| 977 |
+
'light green': '#96f97b',
|
| 978 |
+
'orange': '#f97306',
|
| 979 |
+
'teal': '#029386',
|
| 980 |
+
'light blue': '#95d0fc',
|
| 981 |
+
'red': '#e50000',
|
| 982 |
+
'brown': '#653700',
|
| 983 |
+
'pink': '#ff81c0',
|
| 984 |
+
'blue': '#0343df',
|
| 985 |
+
'green': '#15b01a',
|
| 986 |
+
'purple': '#7e1e9c'}
|
| 987 |
+
|
| 988 |
+
# Normalize name to "xkcd:<name>" to avoid name collisions.
|
| 989 |
+
XKCD_COLORS = {'xkcd:' + name: value for name, value in XKCD_COLORS.items()}
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
# https://drafts.csswg.org/css-color-4/#named-colors
|
| 993 |
+
CSS4_COLORS = {
|
| 994 |
+
'aliceblue': '#F0F8FF',
|
| 995 |
+
'antiquewhite': '#FAEBD7',
|
| 996 |
+
'aqua': '#00FFFF',
|
| 997 |
+
'aquamarine': '#7FFFD4',
|
| 998 |
+
'azure': '#F0FFFF',
|
| 999 |
+
'beige': '#F5F5DC',
|
| 1000 |
+
'bisque': '#FFE4C4',
|
| 1001 |
+
'black': '#000000',
|
| 1002 |
+
'blanchedalmond': '#FFEBCD',
|
| 1003 |
+
'blue': '#0000FF',
|
| 1004 |
+
'blueviolet': '#8A2BE2',
|
| 1005 |
+
'brown': '#A52A2A',
|
| 1006 |
+
'burlywood': '#DEB887',
|
| 1007 |
+
'cadetblue': '#5F9EA0',
|
| 1008 |
+
'chartreuse': '#7FFF00',
|
| 1009 |
+
'chocolate': '#D2691E',
|
| 1010 |
+
'coral': '#FF7F50',
|
| 1011 |
+
'cornflowerblue': '#6495ED',
|
| 1012 |
+
'cornsilk': '#FFF8DC',
|
| 1013 |
+
'crimson': '#DC143C',
|
| 1014 |
+
'cyan': '#00FFFF',
|
| 1015 |
+
'darkblue': '#00008B',
|
| 1016 |
+
'darkcyan': '#008B8B',
|
| 1017 |
+
'darkgoldenrod': '#B8860B',
|
| 1018 |
+
'darkgray': '#A9A9A9',
|
| 1019 |
+
'darkgreen': '#006400',
|
| 1020 |
+
'darkgrey': '#A9A9A9',
|
| 1021 |
+
'darkkhaki': '#BDB76B',
|
| 1022 |
+
'darkmagenta': '#8B008B',
|
| 1023 |
+
'darkolivegreen': '#556B2F',
|
| 1024 |
+
'darkorange': '#FF8C00',
|
| 1025 |
+
'darkorchid': '#9932CC',
|
| 1026 |
+
'darkred': '#8B0000',
|
| 1027 |
+
'darksalmon': '#E9967A',
|
| 1028 |
+
'darkseagreen': '#8FBC8F',
|
| 1029 |
+
'darkslateblue': '#483D8B',
|
| 1030 |
+
'darkslategray': '#2F4F4F',
|
| 1031 |
+
'darkslategrey': '#2F4F4F',
|
| 1032 |
+
'darkturquoise': '#00CED1',
|
| 1033 |
+
'darkviolet': '#9400D3',
|
| 1034 |
+
'deeppink': '#FF1493',
|
| 1035 |
+
'deepskyblue': '#00BFFF',
|
| 1036 |
+
'dimgray': '#696969',
|
| 1037 |
+
'dimgrey': '#696969',
|
| 1038 |
+
'dodgerblue': '#1E90FF',
|
| 1039 |
+
'firebrick': '#B22222',
|
| 1040 |
+
'floralwhite': '#FFFAF0',
|
| 1041 |
+
'forestgreen': '#228B22',
|
| 1042 |
+
'fuchsia': '#FF00FF',
|
| 1043 |
+
'gainsboro': '#DCDCDC',
|
| 1044 |
+
'ghostwhite': '#F8F8FF',
|
| 1045 |
+
'gold': '#FFD700',
|
| 1046 |
+
'goldenrod': '#DAA520',
|
| 1047 |
+
'gray': '#808080',
|
| 1048 |
+
'green': '#008000',
|
| 1049 |
+
'greenyellow': '#ADFF2F',
|
| 1050 |
+
'grey': '#808080',
|
| 1051 |
+
'honeydew': '#F0FFF0',
|
| 1052 |
+
'hotpink': '#FF69B4',
|
| 1053 |
+
'indianred': '#CD5C5C',
|
| 1054 |
+
'indigo': '#4B0082',
|
| 1055 |
+
'ivory': '#FFFFF0',
|
| 1056 |
+
'khaki': '#F0E68C',
|
| 1057 |
+
'lavender': '#E6E6FA',
|
| 1058 |
+
'lavenderblush': '#FFF0F5',
|
| 1059 |
+
'lawngreen': '#7CFC00',
|
| 1060 |
+
'lemonchiffon': '#FFFACD',
|
| 1061 |
+
'lightblue': '#ADD8E6',
|
| 1062 |
+
'lightcoral': '#F08080',
|
| 1063 |
+
'lightcyan': '#E0FFFF',
|
| 1064 |
+
'lightgoldenrodyellow': '#FAFAD2',
|
| 1065 |
+
'lightgray': '#D3D3D3',
|
| 1066 |
+
'lightgreen': '#90EE90',
|
| 1067 |
+
'lightgrey': '#D3D3D3',
|
| 1068 |
+
'lightpink': '#FFB6C1',
|
| 1069 |
+
'lightsalmon': '#FFA07A',
|
| 1070 |
+
'lightseagreen': '#20B2AA',
|
| 1071 |
+
'lightskyblue': '#87CEFA',
|
| 1072 |
+
'lightslategray': '#778899',
|
| 1073 |
+
'lightslategrey': '#778899',
|
| 1074 |
+
'lightsteelblue': '#B0C4DE',
|
| 1075 |
+
'lightyellow': '#FFFFE0',
|
| 1076 |
+
'lime': '#00FF00',
|
| 1077 |
+
'limegreen': '#32CD32',
|
| 1078 |
+
'linen': '#FAF0E6',
|
| 1079 |
+
'magenta': '#FF00FF',
|
| 1080 |
+
'maroon': '#800000',
|
| 1081 |
+
'mediumaquamarine': '#66CDAA',
|
| 1082 |
+
'mediumblue': '#0000CD',
|
| 1083 |
+
'mediumorchid': '#BA55D3',
|
| 1084 |
+
'mediumpurple': '#9370DB',
|
| 1085 |
+
'mediumseagreen': '#3CB371',
|
| 1086 |
+
'mediumslateblue': '#7B68EE',
|
| 1087 |
+
'mediumspringgreen': '#00FA9A',
|
| 1088 |
+
'mediumturquoise': '#48D1CC',
|
| 1089 |
+
'mediumvioletred': '#C71585',
|
| 1090 |
+
'midnightblue': '#191970',
|
| 1091 |
+
'mintcream': '#F5FFFA',
|
| 1092 |
+
'mistyrose': '#FFE4E1',
|
| 1093 |
+
'moccasin': '#FFE4B5',
|
| 1094 |
+
'navajowhite': '#FFDEAD',
|
| 1095 |
+
'navy': '#000080',
|
| 1096 |
+
'oldlace': '#FDF5E6',
|
| 1097 |
+
'olive': '#808000',
|
| 1098 |
+
'olivedrab': '#6B8E23',
|
| 1099 |
+
'orange': '#FFA500',
|
| 1100 |
+
'orangered': '#FF4500',
|
| 1101 |
+
'orchid': '#DA70D6',
|
| 1102 |
+
'palegoldenrod': '#EEE8AA',
|
| 1103 |
+
'palegreen': '#98FB98',
|
| 1104 |
+
'paleturquoise': '#AFEEEE',
|
| 1105 |
+
'palevioletred': '#DB7093',
|
| 1106 |
+
'papayawhip': '#FFEFD5',
|
| 1107 |
+
'peachpuff': '#FFDAB9',
|
| 1108 |
+
'peru': '#CD853F',
|
| 1109 |
+
'pink': '#FFC0CB',
|
| 1110 |
+
'plum': '#DDA0DD',
|
| 1111 |
+
'powderblue': '#B0E0E6',
|
| 1112 |
+
'purple': '#800080',
|
| 1113 |
+
'rebeccapurple': '#663399',
|
| 1114 |
+
'red': '#FF0000',
|
| 1115 |
+
'rosybrown': '#BC8F8F',
|
| 1116 |
+
'royalblue': '#4169E1',
|
| 1117 |
+
'saddlebrown': '#8B4513',
|
| 1118 |
+
'salmon': '#FA8072',
|
| 1119 |
+
'sandybrown': '#F4A460',
|
| 1120 |
+
'seagreen': '#2E8B57',
|
| 1121 |
+
'seashell': '#FFF5EE',
|
| 1122 |
+
'sienna': '#A0522D',
|
| 1123 |
+
'silver': '#C0C0C0',
|
| 1124 |
+
'skyblue': '#87CEEB',
|
| 1125 |
+
'slateblue': '#6A5ACD',
|
| 1126 |
+
'slategray': '#708090',
|
| 1127 |
+
'slategrey': '#708090',
|
| 1128 |
+
'snow': '#FFFAFA',
|
| 1129 |
+
'springgreen': '#00FF7F',
|
| 1130 |
+
'steelblue': '#4682B4',
|
| 1131 |
+
'tan': '#D2B48C',
|
| 1132 |
+
'teal': '#008080',
|
| 1133 |
+
'thistle': '#D8BFD8',
|
| 1134 |
+
'tomato': '#FF6347',
|
| 1135 |
+
'turquoise': '#40E0D0',
|
| 1136 |
+
'violet': '#EE82EE',
|
| 1137 |
+
'wheat': '#F5DEB3',
|
| 1138 |
+
'white': '#FFFFFF',
|
| 1139 |
+
'whitesmoke': '#F5F5F5',
|
| 1140 |
+
'yellow': '#FFFF00',
|
| 1141 |
+
'yellowgreen': '#9ACD32'}
|
parrot/lib/python3.10/site-packages/matplotlib/_docstring.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
|
| 3 |
+
from . import _api
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def kwarg_doc(text):
|
| 7 |
+
"""
|
| 8 |
+
Decorator for defining the kwdoc documentation of artist properties.
|
| 9 |
+
|
| 10 |
+
This decorator can be applied to artist property setter methods.
|
| 11 |
+
The given text is stored in a private attribute ``_kwarg_doc`` on
|
| 12 |
+
the method. It is used to overwrite auto-generated documentation
|
| 13 |
+
in the *kwdoc list* for artists. The kwdoc list is used to document
|
| 14 |
+
``**kwargs`` when they are properties of an artist. See e.g. the
|
| 15 |
+
``**kwargs`` section in `.Axes.text`.
|
| 16 |
+
|
| 17 |
+
The text should contain the supported types, as well as the default
|
| 18 |
+
value if applicable, e.g.:
|
| 19 |
+
|
| 20 |
+
@_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
|
| 21 |
+
def set_usetex(self, usetex):
|
| 22 |
+
|
| 23 |
+
See Also
|
| 24 |
+
--------
|
| 25 |
+
matplotlib.artist.kwdoc
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
def decorator(func):
|
| 29 |
+
func._kwarg_doc = text
|
| 30 |
+
return func
|
| 31 |
+
return decorator
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Substitution:
|
| 35 |
+
"""
|
| 36 |
+
A decorator that performs %-substitution on an object's docstring.
|
| 37 |
+
|
| 38 |
+
This decorator should be robust even if ``obj.__doc__`` is None (for
|
| 39 |
+
example, if -OO was passed to the interpreter).
|
| 40 |
+
|
| 41 |
+
Usage: construct a docstring.Substitution with a sequence or dictionary
|
| 42 |
+
suitable for performing substitution; then decorate a suitable function
|
| 43 |
+
with the constructed object, e.g.::
|
| 44 |
+
|
| 45 |
+
sub_author_name = Substitution(author='Jason')
|
| 46 |
+
|
| 47 |
+
@sub_author_name
|
| 48 |
+
def some_function(x):
|
| 49 |
+
"%(author)s wrote this function"
|
| 50 |
+
|
| 51 |
+
# note that some_function.__doc__ is now "Jason wrote this function"
|
| 52 |
+
|
| 53 |
+
One can also use positional arguments::
|
| 54 |
+
|
| 55 |
+
sub_first_last_names = Substitution('Edgar Allen', 'Poe')
|
| 56 |
+
|
| 57 |
+
@sub_first_last_names
|
| 58 |
+
def some_function(x):
|
| 59 |
+
"%s %s wrote the Raven"
|
| 60 |
+
"""
|
| 61 |
+
def __init__(self, *args, **kwargs):
|
| 62 |
+
if args and kwargs:
|
| 63 |
+
raise TypeError("Only positional or keyword args are allowed")
|
| 64 |
+
self.params = args or kwargs
|
| 65 |
+
|
| 66 |
+
def __call__(self, func):
|
| 67 |
+
if func.__doc__:
|
| 68 |
+
func.__doc__ = inspect.cleandoc(func.__doc__) % self.params
|
| 69 |
+
return func
|
| 70 |
+
|
| 71 |
+
def update(self, *args, **kwargs):
|
| 72 |
+
"""
|
| 73 |
+
Update ``self.params`` (which must be a dict) with the supplied args.
|
| 74 |
+
"""
|
| 75 |
+
self.params.update(*args, **kwargs)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class _ArtistKwdocLoader(dict):
|
| 79 |
+
def __missing__(self, key):
|
| 80 |
+
if not key.endswith(":kwdoc"):
|
| 81 |
+
raise KeyError(key)
|
| 82 |
+
name = key[:-len(":kwdoc")]
|
| 83 |
+
from matplotlib.artist import Artist, kwdoc
|
| 84 |
+
try:
|
| 85 |
+
cls, = [cls for cls in _api.recursive_subclasses(Artist)
|
| 86 |
+
if cls.__name__ == name]
|
| 87 |
+
except ValueError as e:
|
| 88 |
+
raise KeyError(key) from e
|
| 89 |
+
return self.setdefault(key, kwdoc(cls))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class _ArtistPropertiesSubstitution(Substitution):
|
| 93 |
+
"""
|
| 94 |
+
A `.Substitution` with two additional features:
|
| 95 |
+
|
| 96 |
+
- Substitutions of the form ``%(classname:kwdoc)s`` (ending with the
|
| 97 |
+
literal ":kwdoc" suffix) trigger lookup of an Artist subclass with the
|
| 98 |
+
given *classname*, and are substituted with the `.kwdoc` of that class.
|
| 99 |
+
- Decorating a class triggers substitution both on the class docstring and
|
| 100 |
+
on the class' ``__init__`` docstring (which is a commonly required
|
| 101 |
+
pattern for Artist subclasses).
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def __init__(self):
|
| 105 |
+
self.params = _ArtistKwdocLoader()
|
| 106 |
+
|
| 107 |
+
def __call__(self, obj):
|
| 108 |
+
super().__call__(obj)
|
| 109 |
+
if isinstance(obj, type) and obj.__init__ != object.__init__:
|
| 110 |
+
self(obj.__init__)
|
| 111 |
+
return obj
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def copy(source):
|
| 115 |
+
"""Copy a docstring from another source function (if present)."""
|
| 116 |
+
def do_copy(target):
|
| 117 |
+
if source.__doc__:
|
| 118 |
+
target.__doc__ = source.__doc__
|
| 119 |
+
return target
|
| 120 |
+
return do_copy
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# Create a decorator that will house the various docstring snippets reused
|
| 124 |
+
# throughout Matplotlib.
|
| 125 |
+
dedent_interpd = interpd = _ArtistPropertiesSubstitution()
|
parrot/lib/python3.10/site-packages/matplotlib/_enums.pyi
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
|
| 3 |
+
class _AutoStringNameEnum(Enum):
|
| 4 |
+
def __hash__(self) -> int: ...
|
| 5 |
+
|
| 6 |
+
class JoinStyle(str, _AutoStringNameEnum):
|
| 7 |
+
miter: str
|
| 8 |
+
round: str
|
| 9 |
+
bevel: str
|
| 10 |
+
@staticmethod
|
| 11 |
+
def demo() -> None: ...
|
| 12 |
+
|
| 13 |
+
class CapStyle(str, _AutoStringNameEnum):
|
| 14 |
+
butt: str
|
| 15 |
+
projecting: str
|
| 16 |
+
round: str
|
| 17 |
+
@staticmethod
|
| 18 |
+
def demo() -> None: ...
|
parrot/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, oneOf)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_family_punc = r'\\\-:,'
|
| 20 |
+
_family_unescape = partial(re.compile(r'\\(?=[%s])' % _family_punc).sub, '')
|
| 21 |
+
_family_escape = partial(re.compile(r'(?=[%s])' % _family_punc).sub, r'\\')
|
| 22 |
+
_value_punc = r'\\=_:,'
|
| 23 |
+
_value_unescape = partial(re.compile(r'\\(?=[%s])' % _value_punc).sub, '')
|
| 24 |
+
_value_escape = partial(re.compile(r'(?=[%s])' % _value_punc).sub, r'\\')
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
_CONSTANTS = {
|
| 28 |
+
'thin': ('weight', 'light'),
|
| 29 |
+
'extralight': ('weight', 'light'),
|
| 30 |
+
'ultralight': ('weight', 'light'),
|
| 31 |
+
'light': ('weight', 'light'),
|
| 32 |
+
'book': ('weight', 'book'),
|
| 33 |
+
'regular': ('weight', 'regular'),
|
| 34 |
+
'normal': ('weight', 'normal'),
|
| 35 |
+
'medium': ('weight', 'medium'),
|
| 36 |
+
'demibold': ('weight', 'demibold'),
|
| 37 |
+
'semibold': ('weight', 'semibold'),
|
| 38 |
+
'bold': ('weight', 'bold'),
|
| 39 |
+
'extrabold': ('weight', 'extra bold'),
|
| 40 |
+
'black': ('weight', 'black'),
|
| 41 |
+
'heavy': ('weight', 'heavy'),
|
| 42 |
+
'roman': ('slant', 'normal'),
|
| 43 |
+
'italic': ('slant', 'italic'),
|
| 44 |
+
'oblique': ('slant', 'oblique'),
|
| 45 |
+
'ultracondensed': ('width', 'ultra-condensed'),
|
| 46 |
+
'extracondensed': ('width', 'extra-condensed'),
|
| 47 |
+
'condensed': ('width', 'condensed'),
|
| 48 |
+
'semicondensed': ('width', 'semi-condensed'),
|
| 49 |
+
'expanded': ('width', 'expanded'),
|
| 50 |
+
'extraexpanded': ('width', 'extra-expanded'),
|
| 51 |
+
'ultraexpanded': ('width', 'ultra-expanded'),
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@lru_cache # The parser instance is a singleton.
|
| 56 |
+
def _make_fontconfig_parser():
|
| 57 |
+
def comma_separated(elem):
|
| 58 |
+
return elem + ZeroOrMore(Suppress(",") + elem)
|
| 59 |
+
|
| 60 |
+
family = Regex(fr"([^{_family_punc}]|(\\[{_family_punc}]))*")
|
| 61 |
+
size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)")
|
| 62 |
+
name = Regex(r"[a-z]+")
|
| 63 |
+
value = Regex(fr"([^{_value_punc}]|(\\[{_value_punc}]))*")
|
| 64 |
+
prop = Group((name + Suppress("=") + comma_separated(value)) | oneOf(_CONSTANTS))
|
| 65 |
+
return (
|
| 66 |
+
Optional(comma_separated(family)("families"))
|
| 67 |
+
+ Optional("-" + comma_separated(size)("sizes"))
|
| 68 |
+
+ ZeroOrMore(":" + prop("properties*"))
|
| 69 |
+
+ StringEnd()
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# `parse_fontconfig_pattern` is a bottleneck during the tests because it is
|
| 74 |
+
# repeatedly called when the rcParams are reset (to validate the default
|
| 75 |
+
# fonts). In practice, the cache size doesn't grow beyond a few dozen entries
|
| 76 |
+
# during the test suite.
|
| 77 |
+
@lru_cache
|
| 78 |
+
def parse_fontconfig_pattern(pattern):
|
| 79 |
+
"""
|
| 80 |
+
Parse a fontconfig *pattern* into a dict that can initialize a
|
| 81 |
+
`.font_manager.FontProperties` object.
|
| 82 |
+
"""
|
| 83 |
+
parser = _make_fontconfig_parser()
|
| 84 |
+
try:
|
| 85 |
+
parse = parser.parseString(pattern)
|
| 86 |
+
except ParseException as err:
|
| 87 |
+
# explain becomes a plain method on pyparsing 3 (err.explain(0)).
|
| 88 |
+
raise ValueError("\n" + ParseException.explain(err, 0)) from None
|
| 89 |
+
parser.resetCache()
|
| 90 |
+
props = {}
|
| 91 |
+
if "families" in parse:
|
| 92 |
+
props["family"] = [*map(_family_unescape, parse["families"])]
|
| 93 |
+
if "sizes" in parse:
|
| 94 |
+
props["size"] = [*parse["sizes"]]
|
| 95 |
+
for prop in parse.get("properties", []):
|
| 96 |
+
if len(prop) == 1:
|
| 97 |
+
prop = _CONSTANTS[prop[0]]
|
| 98 |
+
k, *v = prop
|
| 99 |
+
props.setdefault(k, []).extend(map(_value_unescape, v))
|
| 100 |
+
return props
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def generate_fontconfig_pattern(d):
|
| 104 |
+
"""Convert a `.FontProperties` to a fontconfig pattern string."""
|
| 105 |
+
kvs = [(k, getattr(d, f"get_{k}")())
|
| 106 |
+
for k in ["style", "variant", "weight", "stretch", "file", "size"]]
|
| 107 |
+
# Families is given first without a leading keyword. Other entries (which
|
| 108 |
+
# are necessarily scalar) are given as key=value, skipping Nones.
|
| 109 |
+
return (",".join(_family_escape(f) for f in d.get_family())
|
| 110 |
+
+ "".join(f":{k}={_value_escape(str(v))}"
|
| 111 |
+
for k, v in kvs if v is not None))
|
parrot/lib/python3.10/site-packages/matplotlib/_image.pyi
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/matplotlib/_path.pyi
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from .transforms import BboxBase
|
| 6 |
+
|
| 7 |
+
def affine_transform(points: np.ndarray, trans: np.ndarray) -> np.ndarray: ...
|
| 8 |
+
def count_bboxes_overlapping_bbox(bbox: BboxBase, bboxes: Sequence[BboxBase]) -> int: ...
|
| 9 |
+
def update_path_extents(path, trans, rect, minpos, ignore): ...
|
parrot/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Manage figures for the pyplot interface.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import atexit
|
| 6 |
+
from collections import OrderedDict
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Gcf:
|
| 10 |
+
"""
|
| 11 |
+
Singleton to maintain the relation between figures and their managers, and
|
| 12 |
+
keep track of and "active" figure and manager.
|
| 13 |
+
|
| 14 |
+
The canvas of a figure created through pyplot is associated with a figure
|
| 15 |
+
manager, which handles the interaction between the figure and the backend.
|
| 16 |
+
pyplot keeps track of figure managers using an identifier, the "figure
|
| 17 |
+
number" or "manager number" (which can actually be any hashable value);
|
| 18 |
+
this number is available as the :attr:`number` attribute of the manager.
|
| 19 |
+
|
| 20 |
+
This class is never instantiated; it consists of an `OrderedDict` mapping
|
| 21 |
+
figure/manager numbers to managers, and a set of class methods that
|
| 22 |
+
manipulate this `OrderedDict`.
|
| 23 |
+
|
| 24 |
+
Attributes
|
| 25 |
+
----------
|
| 26 |
+
figs : OrderedDict
|
| 27 |
+
`OrderedDict` mapping numbers to managers; the active manager is at the
|
| 28 |
+
end.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
figs = OrderedDict()
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def get_fig_manager(cls, num):
|
| 35 |
+
"""
|
| 36 |
+
If manager number *num* exists, make it the active one and return it;
|
| 37 |
+
otherwise return *None*.
|
| 38 |
+
"""
|
| 39 |
+
manager = cls.figs.get(num, None)
|
| 40 |
+
if manager is not None:
|
| 41 |
+
cls.set_active(manager)
|
| 42 |
+
return manager
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def destroy(cls, num):
|
| 46 |
+
"""
|
| 47 |
+
Destroy manager *num* -- either a manager instance or a manager number.
|
| 48 |
+
|
| 49 |
+
In the interactive backends, this is bound to the window "destroy" and
|
| 50 |
+
"delete" events.
|
| 51 |
+
|
| 52 |
+
It is recommended to pass a manager instance, to avoid confusion when
|
| 53 |
+
two managers share the same number.
|
| 54 |
+
"""
|
| 55 |
+
if all(hasattr(num, attr) for attr in ["num", "destroy"]):
|
| 56 |
+
manager = num
|
| 57 |
+
if cls.figs.get(manager.num) is manager:
|
| 58 |
+
cls.figs.pop(manager.num)
|
| 59 |
+
else:
|
| 60 |
+
try:
|
| 61 |
+
manager = cls.figs.pop(num)
|
| 62 |
+
except KeyError:
|
| 63 |
+
return
|
| 64 |
+
if hasattr(manager, "_cidgcf"):
|
| 65 |
+
manager.canvas.mpl_disconnect(manager._cidgcf)
|
| 66 |
+
manager.destroy()
|
| 67 |
+
|
| 68 |
+
@classmethod
|
| 69 |
+
def destroy_fig(cls, fig):
|
| 70 |
+
"""Destroy figure *fig*."""
|
| 71 |
+
num = next((manager.num for manager in cls.figs.values()
|
| 72 |
+
if manager.canvas.figure == fig), None)
|
| 73 |
+
if num is not None:
|
| 74 |
+
cls.destroy(num)
|
| 75 |
+
|
| 76 |
+
@classmethod
|
| 77 |
+
def destroy_all(cls):
|
| 78 |
+
"""Destroy all figures."""
|
| 79 |
+
for manager in list(cls.figs.values()):
|
| 80 |
+
manager.canvas.mpl_disconnect(manager._cidgcf)
|
| 81 |
+
manager.destroy()
|
| 82 |
+
cls.figs.clear()
|
| 83 |
+
|
| 84 |
+
@classmethod
|
| 85 |
+
def has_fignum(cls, num):
|
| 86 |
+
"""Return whether figure number *num* exists."""
|
| 87 |
+
return num in cls.figs
|
| 88 |
+
|
| 89 |
+
@classmethod
|
| 90 |
+
def get_all_fig_managers(cls):
|
| 91 |
+
"""Return a list of figure managers."""
|
| 92 |
+
return list(cls.figs.values())
|
| 93 |
+
|
| 94 |
+
@classmethod
|
| 95 |
+
def get_num_fig_managers(cls):
|
| 96 |
+
"""Return the number of figures being managed."""
|
| 97 |
+
return len(cls.figs)
|
| 98 |
+
|
| 99 |
+
@classmethod
|
| 100 |
+
def get_active(cls):
|
| 101 |
+
"""Return the active manager, or *None* if there is no manager."""
|
| 102 |
+
return next(reversed(cls.figs.values())) if cls.figs else None
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def _set_new_active_manager(cls, manager):
|
| 106 |
+
"""Adopt *manager* into pyplot and make it the active manager."""
|
| 107 |
+
if not hasattr(manager, "_cidgcf"):
|
| 108 |
+
manager._cidgcf = manager.canvas.mpl_connect(
|
| 109 |
+
"button_press_event", lambda event: cls.set_active(manager))
|
| 110 |
+
fig = manager.canvas.figure
|
| 111 |
+
fig.number = manager.num
|
| 112 |
+
label = fig.get_label()
|
| 113 |
+
if label:
|
| 114 |
+
manager.set_window_title(label)
|
| 115 |
+
cls.set_active(manager)
|
| 116 |
+
|
| 117 |
+
@classmethod
|
| 118 |
+
def set_active(cls, manager):
|
| 119 |
+
"""Make *manager* the active manager."""
|
| 120 |
+
cls.figs[manager.num] = manager
|
| 121 |
+
cls.figs.move_to_end(manager.num)
|
| 122 |
+
|
| 123 |
+
@classmethod
|
| 124 |
+
def draw_all(cls, force=False):
|
| 125 |
+
"""
|
| 126 |
+
Redraw all stale managed figures, or, if *force* is True, all managed
|
| 127 |
+
figures.
|
| 128 |
+
"""
|
| 129 |
+
for manager in cls.get_all_fig_managers():
|
| 130 |
+
if force or manager.canvas.figure.stale:
|
| 131 |
+
manager.canvas.draw_idle()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
atexit.register(Gcf.destroy_all)
|
parrot/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
|
| 3 |
+
from matplotlib.backend_bases import FigureManagerBase
|
| 4 |
+
from matplotlib.figure import Figure
|
| 5 |
+
|
| 6 |
+
class Gcf:
|
| 7 |
+
figs: OrderedDict[int, FigureManagerBase]
|
| 8 |
+
@classmethod
|
| 9 |
+
def get_fig_manager(cls, num: int) -> FigureManagerBase | None: ...
|
| 10 |
+
@classmethod
|
| 11 |
+
def destroy(cls, num: int | FigureManagerBase) -> None: ...
|
| 12 |
+
@classmethod
|
| 13 |
+
def destroy_fig(cls, fig: Figure) -> None: ...
|
| 14 |
+
@classmethod
|
| 15 |
+
def destroy_all(cls) -> None: ...
|
| 16 |
+
@classmethod
|
| 17 |
+
def has_fignum(cls, num: int) -> bool: ...
|
| 18 |
+
@classmethod
|
| 19 |
+
def get_all_fig_managers(cls) -> list[FigureManagerBase]: ...
|
| 20 |
+
@classmethod
|
| 21 |
+
def get_num_fig_managers(cls) -> int: ...
|
| 22 |
+
@classmethod
|
| 23 |
+
def get_active(cls) -> FigureManagerBase | None: ...
|
| 24 |
+
@classmethod
|
| 25 |
+
def _set_new_active_manager(cls, manager: FigureManagerBase) -> None: ...
|
| 26 |
+
@classmethod
|
| 27 |
+
def set_active(cls, manager: FigureManagerBase) -> None: ...
|
| 28 |
+
@classmethod
|
| 29 |
+
def draw_all(cls, force: bool = ...) -> None: ...
|
parrot/lib/python3.10/site-packages/matplotlib/_tri.pyi
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a private module implemented in C++
|
| 2 |
+
# As such these type stubs are overly generic, but here to allow these types
|
| 3 |
+
# as return types for public methods
|
| 4 |
+
from typing import Any, final
|
| 5 |
+
|
| 6 |
+
@final
|
| 7 |
+
class TrapezoidMapTriFinder:
|
| 8 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 9 |
+
def find_many(self, *args, **kwargs) -> Any: ...
|
| 10 |
+
def get_tree_stats(self, *args, **kwargs) -> Any: ...
|
| 11 |
+
def initialize(self, *args, **kwargs) -> Any: ...
|
| 12 |
+
def print_tree(self, *args, **kwargs) -> Any: ...
|
| 13 |
+
|
| 14 |
+
@final
|
| 15 |
+
class TriContourGenerator:
|
| 16 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 17 |
+
def create_contour(self, *args, **kwargs) -> Any: ...
|
| 18 |
+
def create_filled_contour(self, *args, **kwargs) -> Any: ...
|
| 19 |
+
|
| 20 |
+
@final
|
| 21 |
+
class Triangulation:
|
| 22 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 23 |
+
def calculate_plane_coefficients(self, *args, **kwargs) -> Any: ...
|
| 24 |
+
def get_edges(self, *args, **kwargs) -> Any: ...
|
| 25 |
+
def get_neighbors(self, *args, **kwargs) -> Any: ...
|
| 26 |
+
def set_mask(self, *args, **kwargs) -> Any: ...
|
parrot/lib/python3.10/site-packages/matplotlib/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
version = "3.9.2"
|
parrot/lib/python3.10/site-packages/matplotlib/axis.pyi
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 2 |
+
import datetime
|
| 3 |
+
from typing import Any, Literal, overload
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from numpy.typing import ArrayLike
|
| 7 |
+
|
| 8 |
+
import matplotlib.artist as martist
|
| 9 |
+
from matplotlib import cbook
|
| 10 |
+
from matplotlib.axes import Axes
|
| 11 |
+
from matplotlib.backend_bases import RendererBase
|
| 12 |
+
from matplotlib.lines import Line2D
|
| 13 |
+
from matplotlib.text import Text
|
| 14 |
+
from matplotlib.ticker import Locator, Formatter
|
| 15 |
+
from matplotlib.transforms import Transform, Bbox
|
| 16 |
+
from matplotlib.typing import ColorType
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
GRIDLINE_INTERPOLATION_STEPS: int
|
| 20 |
+
|
| 21 |
+
class Tick(martist.Artist):
|
| 22 |
+
axes: Axes
|
| 23 |
+
tick1line: Line2D
|
| 24 |
+
tick2line: Line2D
|
| 25 |
+
gridline: Line2D
|
| 26 |
+
label1: Text
|
| 27 |
+
label2: Text
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
axes: Axes,
|
| 31 |
+
loc: float,
|
| 32 |
+
*,
|
| 33 |
+
size: float | None = ...,
|
| 34 |
+
width: float | None = ...,
|
| 35 |
+
color: ColorType | None = ...,
|
| 36 |
+
tickdir: Literal["in", "inout", "out"] | None = ...,
|
| 37 |
+
pad: float | None = ...,
|
| 38 |
+
labelsize: float | None = ...,
|
| 39 |
+
labelcolor: ColorType | None = ...,
|
| 40 |
+
labelfontfamily: str | Sequence[str] | None = ...,
|
| 41 |
+
zorder: float | None = ...,
|
| 42 |
+
gridOn: bool | None = ...,
|
| 43 |
+
tick1On: bool = ...,
|
| 44 |
+
tick2On: bool = ...,
|
| 45 |
+
label1On: bool = ...,
|
| 46 |
+
label2On: bool = ...,
|
| 47 |
+
major: bool = ...,
|
| 48 |
+
labelrotation: float = ...,
|
| 49 |
+
grid_color: ColorType | None = ...,
|
| 50 |
+
grid_linestyle: str | None = ...,
|
| 51 |
+
grid_linewidth: float | None = ...,
|
| 52 |
+
grid_alpha: float | None = ...,
|
| 53 |
+
**kwargs
|
| 54 |
+
) -> None: ...
|
| 55 |
+
def get_tickdir(self) -> Literal["in", "inout", "out"]: ...
|
| 56 |
+
def get_tick_padding(self) -> float: ...
|
| 57 |
+
def get_children(self) -> list[martist.Artist]: ...
|
| 58 |
+
stale: bool
|
| 59 |
+
def set_pad(self, val: float) -> None: ...
|
| 60 |
+
def get_pad(self) -> None: ...
|
| 61 |
+
def get_loc(self) -> float: ...
|
| 62 |
+
def set_label1(self, s: object) -> None: ...
|
| 63 |
+
def set_label(self, s: object) -> None: ...
|
| 64 |
+
def set_label2(self, s: object) -> None: ...
|
| 65 |
+
def set_url(self, url: str | None) -> None: ...
|
| 66 |
+
def get_view_interval(self) -> ArrayLike: ...
|
| 67 |
+
def update_position(self, loc: float) -> None: ...
|
| 68 |
+
|
| 69 |
+
class XTick(Tick):
|
| 70 |
+
__name__: str
|
| 71 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 72 |
+
stale: bool
|
| 73 |
+
def update_position(self, loc: float) -> None: ...
|
| 74 |
+
def get_view_interval(self) -> np.ndarray: ...
|
| 75 |
+
|
| 76 |
+
class YTick(Tick):
|
| 77 |
+
__name__: str
|
| 78 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 79 |
+
stale: bool
|
| 80 |
+
def update_position(self, loc: float) -> None: ...
|
| 81 |
+
def get_view_interval(self) -> np.ndarray: ...
|
| 82 |
+
|
| 83 |
+
class Ticker:
|
| 84 |
+
def __init__(self) -> None: ...
|
| 85 |
+
@property
|
| 86 |
+
def locator(self) -> Locator | None: ...
|
| 87 |
+
@locator.setter
|
| 88 |
+
def locator(self, locator: Locator) -> None: ...
|
| 89 |
+
@property
|
| 90 |
+
def formatter(self) -> Formatter | None: ...
|
| 91 |
+
@formatter.setter
|
| 92 |
+
def formatter(self, formatter: Formatter) -> None: ...
|
| 93 |
+
|
| 94 |
+
class _LazyTickList:
|
| 95 |
+
def __init__(self, major: bool) -> None: ...
|
| 96 |
+
# Replace return with Self when py3.9 is dropped
|
| 97 |
+
@overload
|
| 98 |
+
def __get__(self, instance: None, owner: None) -> _LazyTickList: ...
|
| 99 |
+
@overload
|
| 100 |
+
def __get__(self, instance: Axis, owner: type[Axis]) -> list[Tick]: ...
|
| 101 |
+
|
| 102 |
+
class Axis(martist.Artist):
|
| 103 |
+
OFFSETTEXTPAD: int
|
| 104 |
+
isDefault_label: bool
|
| 105 |
+
axes: Axes
|
| 106 |
+
major: Ticker
|
| 107 |
+
minor: Ticker
|
| 108 |
+
callbacks: cbook.CallbackRegistry
|
| 109 |
+
label: Text
|
| 110 |
+
offsetText: Text
|
| 111 |
+
labelpad: float
|
| 112 |
+
pickradius: float
|
| 113 |
+
def __init__(self, axes, *, pickradius: float = ...,
|
| 114 |
+
clear: bool = ...) -> None: ...
|
| 115 |
+
@property
|
| 116 |
+
def isDefault_majloc(self) -> bool: ...
|
| 117 |
+
@isDefault_majloc.setter
|
| 118 |
+
def isDefault_majloc(self, value: bool) -> None: ...
|
| 119 |
+
@property
|
| 120 |
+
def isDefault_majfmt(self) -> bool: ...
|
| 121 |
+
@isDefault_majfmt.setter
|
| 122 |
+
def isDefault_majfmt(self, value: bool) -> None: ...
|
| 123 |
+
@property
|
| 124 |
+
def isDefault_minloc(self) -> bool: ...
|
| 125 |
+
@isDefault_minloc.setter
|
| 126 |
+
def isDefault_minloc(self, value: bool) -> None: ...
|
| 127 |
+
@property
|
| 128 |
+
def isDefault_minfmt(self) -> bool: ...
|
| 129 |
+
@isDefault_minfmt.setter
|
| 130 |
+
def isDefault_minfmt(self, value: bool) -> None: ...
|
| 131 |
+
majorTicks: _LazyTickList
|
| 132 |
+
minorTicks: _LazyTickList
|
| 133 |
+
def get_remove_overlapping_locs(self) -> bool: ...
|
| 134 |
+
def set_remove_overlapping_locs(self, val: bool) -> None: ...
|
| 135 |
+
@property
|
| 136 |
+
def remove_overlapping_locs(self) -> bool: ...
|
| 137 |
+
@remove_overlapping_locs.setter
|
| 138 |
+
def remove_overlapping_locs(self, val: bool) -> None: ...
|
| 139 |
+
stale: bool
|
| 140 |
+
def set_label_coords(
|
| 141 |
+
self, x: float, y: float, transform: Transform | None = ...
|
| 142 |
+
) -> None: ...
|
| 143 |
+
def get_transform(self) -> Transform: ...
|
| 144 |
+
def get_scale(self) -> str: ...
|
| 145 |
+
def limit_range_for_scale(
|
| 146 |
+
self, vmin: float, vmax: float
|
| 147 |
+
) -> tuple[float, float]: ...
|
| 148 |
+
def get_children(self) -> list[martist.Artist]: ...
|
| 149 |
+
# TODO units
|
| 150 |
+
converter: Any
|
| 151 |
+
units: Any
|
| 152 |
+
def clear(self) -> None: ...
|
| 153 |
+
def reset_ticks(self) -> None: ...
|
| 154 |
+
def minorticks_on(self) -> None: ...
|
| 155 |
+
def minorticks_off(self) -> None: ...
|
| 156 |
+
def set_tick_params(
|
| 157 |
+
self,
|
| 158 |
+
which: Literal["major", "minor", "both"] = ...,
|
| 159 |
+
reset: bool = ...,
|
| 160 |
+
**kwargs
|
| 161 |
+
) -> None: ...
|
| 162 |
+
def get_tick_params(
|
| 163 |
+
self, which: Literal["major", "minor"] = ...
|
| 164 |
+
) -> dict[str, Any]: ...
|
| 165 |
+
def get_view_interval(self) -> tuple[float, float]: ...
|
| 166 |
+
def set_view_interval(
|
| 167 |
+
self, vmin: float, vmax: float, ignore: bool = ...
|
| 168 |
+
) -> None: ...
|
| 169 |
+
def get_data_interval(self) -> tuple[float, float]: ...
|
| 170 |
+
def set_data_interval(
|
| 171 |
+
self, vmin: float, vmax: float, ignore: bool = ...
|
| 172 |
+
) -> None: ...
|
| 173 |
+
def get_inverted(self) -> bool: ...
|
| 174 |
+
def set_inverted(self, inverted: bool) -> None: ...
|
| 175 |
+
def set_default_intervals(self) -> None: ...
|
| 176 |
+
def get_tightbbox(
|
| 177 |
+
self, renderer: RendererBase | None = ..., *, for_layout_only: bool = ...
|
| 178 |
+
) -> Bbox | None: ...
|
| 179 |
+
def get_tick_padding(self) -> float: ...
|
| 180 |
+
def get_gridlines(self) -> list[Line2D]: ...
|
| 181 |
+
def get_label(self) -> Text: ...
|
| 182 |
+
def get_offset_text(self) -> Text: ...
|
| 183 |
+
def get_pickradius(self) -> float: ...
|
| 184 |
+
def get_majorticklabels(self) -> list[Text]: ...
|
| 185 |
+
def get_minorticklabels(self) -> list[Text]: ...
|
| 186 |
+
def get_ticklabels(
|
| 187 |
+
self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...
|
| 188 |
+
) -> list[Text]: ...
|
| 189 |
+
def get_majorticklines(self) -> list[Line2D]: ...
|
| 190 |
+
def get_minorticklines(self) -> list[Line2D]: ...
|
| 191 |
+
def get_ticklines(self, minor: bool = ...) -> list[Line2D]: ...
|
| 192 |
+
def get_majorticklocs(self) -> np.ndarray: ...
|
| 193 |
+
def get_minorticklocs(self) -> np.ndarray: ...
|
| 194 |
+
def get_ticklocs(self, *, minor: bool = ...) -> np.ndarray: ...
|
| 195 |
+
def get_ticks_direction(self, minor: bool = ...) -> np.ndarray: ...
|
| 196 |
+
def get_label_text(self) -> str: ...
|
| 197 |
+
def get_major_locator(self) -> Locator: ...
|
| 198 |
+
def get_minor_locator(self) -> Locator: ...
|
| 199 |
+
def get_major_formatter(self) -> Formatter: ...
|
| 200 |
+
def get_minor_formatter(self) -> Formatter: ...
|
| 201 |
+
def get_major_ticks(self, numticks: int | None = ...) -> list[Tick]: ...
|
| 202 |
+
def get_minor_ticks(self, numticks: int | None = ...) -> list[Tick]: ...
|
| 203 |
+
def grid(
|
| 204 |
+
self,
|
| 205 |
+
visible: bool | None = ...,
|
| 206 |
+
which: Literal["major", "minor", "both"] = ...,
|
| 207 |
+
**kwargs
|
| 208 |
+
) -> None: ...
|
| 209 |
+
# TODO units
|
| 210 |
+
def update_units(self, data): ...
|
| 211 |
+
def have_units(self) -> bool: ...
|
| 212 |
+
def convert_units(self, x): ...
|
| 213 |
+
def set_units(self, u) -> None: ...
|
| 214 |
+
def get_units(self): ...
|
| 215 |
+
def set_label_text(
|
| 216 |
+
self, label: str, fontdict: dict[str, Any] | None = ..., **kwargs
|
| 217 |
+
) -> Text: ...
|
| 218 |
+
def set_major_formatter(
|
| 219 |
+
self, formatter: Formatter | str | Callable[[float, float], str]
|
| 220 |
+
) -> None: ...
|
| 221 |
+
def set_minor_formatter(
|
| 222 |
+
self, formatter: Formatter | str | Callable[[float, float], str]
|
| 223 |
+
) -> None: ...
|
| 224 |
+
def set_major_locator(self, locator: Locator) -> None: ...
|
| 225 |
+
def set_minor_locator(self, locator: Locator) -> None: ...
|
| 226 |
+
def set_pickradius(self, pickradius: float) -> None: ...
|
| 227 |
+
def set_ticklabels(
|
| 228 |
+
self,
|
| 229 |
+
labels: Iterable[str | Text],
|
| 230 |
+
*,
|
| 231 |
+
minor: bool = ...,
|
| 232 |
+
fontdict: dict[str, Any] | None = ...,
|
| 233 |
+
**kwargs
|
| 234 |
+
) -> list[Text]: ...
|
| 235 |
+
def set_ticks(
|
| 236 |
+
self,
|
| 237 |
+
ticks: ArrayLike,
|
| 238 |
+
labels: Iterable[str] | None = ...,
|
| 239 |
+
*,
|
| 240 |
+
minor: bool = ...,
|
| 241 |
+
**kwargs
|
| 242 |
+
) -> list[Tick]: ...
|
| 243 |
+
def axis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...
|
| 244 |
+
def get_tick_space(self) -> int: ...
|
| 245 |
+
def get_label_position(self) -> Literal["top", "bottom"]: ...
|
| 246 |
+
def set_label_position(
|
| 247 |
+
self, position: Literal["top", "bottom", "left", "right"]
|
| 248 |
+
) -> None: ...
|
| 249 |
+
def get_minpos(self) -> float: ...
|
| 250 |
+
|
| 251 |
+
class XAxis(Axis):
|
| 252 |
+
__name__: str
|
| 253 |
+
axis_name: str
|
| 254 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 255 |
+
label_position: Literal["bottom", "top"]
|
| 256 |
+
stale: bool
|
| 257 |
+
def set_label_position(self, position: Literal["bottom", "top"]) -> None: ... # type: ignore[override]
|
| 258 |
+
def set_ticks_position(
|
| 259 |
+
self, position: Literal["top", "bottom", "both", "default", "none"]
|
| 260 |
+
) -> None: ...
|
| 261 |
+
def tick_top(self) -> None: ...
|
| 262 |
+
def tick_bottom(self) -> None: ...
|
| 263 |
+
def get_ticks_position(self) -> Literal["top", "bottom", "default", "unknown"]: ...
|
| 264 |
+
def get_tick_space(self) -> int: ...
|
| 265 |
+
|
| 266 |
+
class YAxis(Axis):
|
| 267 |
+
__name__: str
|
| 268 |
+
axis_name: str
|
| 269 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 270 |
+
label_position: Literal["left", "right"]
|
| 271 |
+
stale: bool
|
| 272 |
+
def set_label_position(self, position: Literal["left", "right"]) -> None: ... # type: ignore[override]
|
| 273 |
+
def set_offset_position(self, position: Literal["left", "right"]) -> None: ...
|
| 274 |
+
def set_ticks_position(
|
| 275 |
+
self, position: Literal["left", "right", "both", "default", "none"]
|
| 276 |
+
) -> None: ...
|
| 277 |
+
def tick_right(self) -> None: ...
|
| 278 |
+
def tick_left(self) -> None: ...
|
| 279 |
+
def get_ticks_position(self) -> Literal["left", "right", "default", "unknown"]: ...
|
| 280 |
+
def get_tick_space(self) -> int: ...
|
parrot/lib/python3.10/site-packages/matplotlib/backend_managers.pyi
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib import backend_tools, widgets
|
| 2 |
+
from matplotlib.backend_bases import FigureCanvasBase
|
| 3 |
+
from matplotlib.figure import Figure
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable, Iterable
|
| 6 |
+
from typing import Any, TypeVar
|
| 7 |
+
|
| 8 |
+
class ToolEvent:
|
| 9 |
+
name: str
|
| 10 |
+
sender: Any
|
| 11 |
+
tool: backend_tools.ToolBase
|
| 12 |
+
data: Any
|
| 13 |
+
def __init__(self, name, sender, tool, data: Any | None = ...) -> None: ...
|
| 14 |
+
|
| 15 |
+
class ToolTriggerEvent(ToolEvent):
|
| 16 |
+
canvasevent: ToolEvent
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
name,
|
| 20 |
+
sender,
|
| 21 |
+
tool,
|
| 22 |
+
canvasevent: ToolEvent | None = ...,
|
| 23 |
+
data: Any | None = ...,
|
| 24 |
+
) -> None: ...
|
| 25 |
+
|
| 26 |
+
class ToolManagerMessageEvent:
|
| 27 |
+
name: str
|
| 28 |
+
sender: Any
|
| 29 |
+
message: str
|
| 30 |
+
def __init__(self, name: str, sender: Any, message: str) -> None: ...
|
| 31 |
+
|
| 32 |
+
class ToolManager:
|
| 33 |
+
keypresslock: widgets.LockDraw
|
| 34 |
+
messagelock: widgets.LockDraw
|
| 35 |
+
def __init__(self, figure: Figure | None = ...) -> None: ...
|
| 36 |
+
@property
|
| 37 |
+
def canvas(self) -> FigureCanvasBase | None: ...
|
| 38 |
+
@property
|
| 39 |
+
def figure(self) -> Figure | None: ...
|
| 40 |
+
@figure.setter
|
| 41 |
+
def figure(self, figure: Figure) -> None: ...
|
| 42 |
+
def set_figure(self, figure: Figure, update_tools: bool = ...) -> None: ...
|
| 43 |
+
def toolmanager_connect(self, s: str, func: Callable[[ToolEvent], Any]) -> int: ...
|
| 44 |
+
def toolmanager_disconnect(self, cid: int) -> None: ...
|
| 45 |
+
def message_event(self, message: str, sender: Any | None = ...) -> None: ...
|
| 46 |
+
@property
|
| 47 |
+
def active_toggle(self) -> dict[str | None, list[str] | str]: ...
|
| 48 |
+
def get_tool_keymap(self, name: str) -> list[str]: ...
|
| 49 |
+
def update_keymap(self, name: str, key: str | Iterable[str]) -> None: ...
|
| 50 |
+
def remove_tool(self, name: str) -> None: ...
|
| 51 |
+
_T = TypeVar("_T", bound=backend_tools.ToolBase)
|
| 52 |
+
def add_tool(self, name: str, tool: type[_T], *args, **kwargs) -> _T: ...
|
| 53 |
+
def trigger_tool(
|
| 54 |
+
self,
|
| 55 |
+
name: str | backend_tools.ToolBase,
|
| 56 |
+
sender: Any | None = ...,
|
| 57 |
+
canvasevent: ToolEvent | None = ...,
|
| 58 |
+
data: Any | None = ...,
|
| 59 |
+
) -> None: ...
|
| 60 |
+
@property
|
| 61 |
+
def tools(self) -> dict[str, backend_tools.ToolBase]: ...
|
| 62 |
+
def get_tool(
|
| 63 |
+
self, name: str | backend_tools.ToolBase, warn: bool = ...
|
| 64 |
+
) -> backend_tools.ToolBase | None: ...
|
parrot/lib/python3.10/site-packages/matplotlib/cbook.pyi
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections.abc
|
| 2 |
+
from collections.abc import Callable, Collection, Generator, Iterable, Iterator
|
| 3 |
+
import contextlib
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from matplotlib.artist import Artist
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from numpy.typing import ArrayLike
|
| 11 |
+
|
| 12 |
+
from typing import (
|
| 13 |
+
Any,
|
| 14 |
+
Generic,
|
| 15 |
+
IO,
|
| 16 |
+
Literal,
|
| 17 |
+
TypeVar,
|
| 18 |
+
overload,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
_T = TypeVar("_T")
|
| 22 |
+
|
| 23 |
+
def _get_running_interactive_framework() -> str | None: ...
|
| 24 |
+
|
| 25 |
+
class CallbackRegistry:
|
| 26 |
+
exception_handler: Callable[[Exception], Any]
|
| 27 |
+
callbacks: dict[Any, dict[int, Any]]
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
exception_handler: Callable[[Exception], Any] | None = ...,
|
| 31 |
+
*,
|
| 32 |
+
signals: Iterable[Any] | None = ...,
|
| 33 |
+
) -> None: ...
|
| 34 |
+
def connect(self, signal: Any, func: Callable) -> int: ...
|
| 35 |
+
def disconnect(self, cid: int) -> None: ...
|
| 36 |
+
def process(self, s: Any, *args, **kwargs) -> None: ...
|
| 37 |
+
def blocked(
|
| 38 |
+
self, *, signal: Any | None = ...
|
| 39 |
+
) -> contextlib.AbstractContextManager[None]: ...
|
| 40 |
+
|
| 41 |
+
class silent_list(list[_T]):
|
| 42 |
+
type: str | None
|
| 43 |
+
def __init__(self, type: str | None, seq: Iterable[_T] | None = ...) -> None: ...
|
| 44 |
+
|
| 45 |
+
def strip_math(s: str) -> str: ...
|
| 46 |
+
def is_writable_file_like(obj: Any) -> bool: ...
|
| 47 |
+
def file_requires_unicode(x: Any) -> bool: ...
|
| 48 |
+
@overload
|
| 49 |
+
def to_filehandle(
|
| 50 |
+
fname: str | os.PathLike | IO,
|
| 51 |
+
flag: str = ...,
|
| 52 |
+
return_opened: Literal[False] = ...,
|
| 53 |
+
encoding: str | None = ...,
|
| 54 |
+
) -> IO: ...
|
| 55 |
+
@overload
|
| 56 |
+
def to_filehandle(
|
| 57 |
+
fname: str | os.PathLike | IO,
|
| 58 |
+
flag: str,
|
| 59 |
+
return_opened: Literal[True],
|
| 60 |
+
encoding: str | None = ...,
|
| 61 |
+
) -> tuple[IO, bool]: ...
|
| 62 |
+
@overload
|
| 63 |
+
def to_filehandle(
|
| 64 |
+
fname: str | os.PathLike | IO,
|
| 65 |
+
*, # if flag given, will match previous sig
|
| 66 |
+
return_opened: Literal[True],
|
| 67 |
+
encoding: str | None = ...,
|
| 68 |
+
) -> tuple[IO, bool]: ...
|
| 69 |
+
def open_file_cm(
|
| 70 |
+
path_or_file: str | os.PathLike | IO,
|
| 71 |
+
mode: str = ...,
|
| 72 |
+
encoding: str | None = ...,
|
| 73 |
+
) -> contextlib.AbstractContextManager[IO]: ...
|
| 74 |
+
def is_scalar_or_string(val: Any) -> bool: ...
|
| 75 |
+
@overload
|
| 76 |
+
def get_sample_data(
|
| 77 |
+
fname: str | os.PathLike, asfileobj: Literal[True] = ..., *, np_load: Literal[True]
|
| 78 |
+
) -> np.ndarray: ...
|
| 79 |
+
@overload
|
| 80 |
+
def get_sample_data(
|
| 81 |
+
fname: str | os.PathLike,
|
| 82 |
+
asfileobj: Literal[True] = ...,
|
| 83 |
+
*,
|
| 84 |
+
np_load: Literal[False] = ...,
|
| 85 |
+
) -> IO: ...
|
| 86 |
+
@overload
|
| 87 |
+
def get_sample_data(
|
| 88 |
+
fname: str | os.PathLike, asfileobj: Literal[False], *, np_load: bool = ...
|
| 89 |
+
) -> str: ...
|
| 90 |
+
def _get_data_path(*args: Path | str) -> Path: ...
|
| 91 |
+
def flatten(
|
| 92 |
+
seq: Iterable[Any], scalarp: Callable[[Any], bool] = ...
|
| 93 |
+
) -> Generator[Any, None, None]: ...
|
| 94 |
+
|
| 95 |
+
class Stack(Generic[_T]):
|
| 96 |
+
def __init__(self, default: _T | None = ...) -> None: ...
|
| 97 |
+
def __call__(self) -> _T: ...
|
| 98 |
+
def __len__(self) -> int: ...
|
| 99 |
+
def __getitem__(self, ind: int) -> _T: ...
|
| 100 |
+
def forward(self) -> _T: ...
|
| 101 |
+
def back(self) -> _T: ...
|
| 102 |
+
def push(self, o: _T) -> _T: ...
|
| 103 |
+
def home(self) -> _T: ...
|
| 104 |
+
def empty(self) -> bool: ...
|
| 105 |
+
def clear(self) -> None: ...
|
| 106 |
+
def bubble(self, o: _T) -> _T: ...
|
| 107 |
+
def remove(self, o: _T) -> None: ...
|
| 108 |
+
|
| 109 |
+
def safe_masked_invalid(x: ArrayLike, copy: bool = ...) -> np.ndarray: ...
|
| 110 |
+
def print_cycles(
|
| 111 |
+
objects: Iterable[Any], outstream: IO = ..., show_progress: bool = ...
|
| 112 |
+
) -> None: ...
|
| 113 |
+
|
| 114 |
+
class Grouper(Generic[_T]):
|
| 115 |
+
def __init__(self, init: Iterable[_T] = ...) -> None: ...
|
| 116 |
+
def __contains__(self, item: _T) -> bool: ...
|
| 117 |
+
def clean(self) -> None: ...
|
| 118 |
+
def join(self, a: _T, *args: _T) -> None: ...
|
| 119 |
+
def joined(self, a: _T, b: _T) -> bool: ...
|
| 120 |
+
def remove(self, a: _T) -> None: ...
|
| 121 |
+
def __iter__(self) -> Iterator[list[_T]]: ...
|
| 122 |
+
def get_siblings(self, a: _T) -> list[_T]: ...
|
| 123 |
+
|
| 124 |
+
class GrouperView(Generic[_T]):
|
| 125 |
+
def __init__(self, grouper: Grouper[_T]) -> None: ...
|
| 126 |
+
def __contains__(self, item: _T) -> bool: ...
|
| 127 |
+
def __iter__(self) -> Iterator[list[_T]]: ...
|
| 128 |
+
def joined(self, a: _T, b: _T) -> bool: ...
|
| 129 |
+
def get_siblings(self, a: _T) -> list[_T]: ...
|
| 130 |
+
|
| 131 |
+
def simple_linear_interpolation(a: ArrayLike, steps: int) -> np.ndarray: ...
|
| 132 |
+
def delete_masked_points(*args): ...
|
| 133 |
+
def _broadcast_with_masks(*args: ArrayLike, compress: bool = ...) -> list[ArrayLike]: ...
|
| 134 |
+
def boxplot_stats(
|
| 135 |
+
X: ArrayLike,
|
| 136 |
+
whis: float | tuple[float, float] = ...,
|
| 137 |
+
bootstrap: int | None = ...,
|
| 138 |
+
labels: ArrayLike | None = ...,
|
| 139 |
+
autorange: bool = ...,
|
| 140 |
+
) -> list[dict[str, Any]]: ...
|
| 141 |
+
|
| 142 |
+
ls_mapper: dict[str, str]
|
| 143 |
+
ls_mapper_r: dict[str, str]
|
| 144 |
+
|
| 145 |
+
def contiguous_regions(mask: ArrayLike) -> list[np.ndarray]: ...
|
| 146 |
+
def is_math_text(s: str) -> bool: ...
|
| 147 |
+
def violin_stats(
|
| 148 |
+
X: ArrayLike, method: Callable, points: int = ..., quantiles: ArrayLike | None = ...
|
| 149 |
+
) -> list[dict[str, Any]]: ...
|
| 150 |
+
def pts_to_prestep(x: ArrayLike, *args: ArrayLike) -> np.ndarray: ...
|
| 151 |
+
def pts_to_poststep(x: ArrayLike, *args: ArrayLike) -> np.ndarray: ...
|
| 152 |
+
def pts_to_midstep(x: np.ndarray, *args: np.ndarray) -> np.ndarray: ...
|
| 153 |
+
|
| 154 |
+
STEP_LOOKUP_MAP: dict[str, Callable]
|
| 155 |
+
|
| 156 |
+
def index_of(y: float | ArrayLike) -> tuple[np.ndarray, np.ndarray]: ...
|
| 157 |
+
def safe_first_element(obj: Collection[_T]) -> _T: ...
|
| 158 |
+
def sanitize_sequence(data): ...
|
| 159 |
+
def normalize_kwargs(
|
| 160 |
+
kw: dict[str, Any],
|
| 161 |
+
alias_mapping: dict[str, list[str]] | type[Artist] | Artist | None = ...,
|
| 162 |
+
) -> dict[str, Any]: ...
|
| 163 |
+
def _lock_path(path: str | os.PathLike) -> contextlib.AbstractContextManager[None]: ...
|
| 164 |
+
def _str_equal(obj: Any, s: str) -> bool: ...
|
| 165 |
+
def _str_lower_equal(obj: Any, s: str) -> bool: ...
|
| 166 |
+
def _array_perimeter(arr: np.ndarray) -> np.ndarray: ...
|
| 167 |
+
def _unfold(arr: np.ndarray, axis: int, size: int, step: int) -> np.ndarray: ...
|
| 168 |
+
def _array_patch_perimeters(x: np.ndarray, rstride: int, cstride: int) -> np.ndarray: ...
|
| 169 |
+
def _setattr_cm(obj: Any, **kwargs) -> contextlib.AbstractContextManager[None]: ...
|
| 170 |
+
|
| 171 |
+
class _OrderedSet(collections.abc.MutableSet):
|
| 172 |
+
def __init__(self) -> None: ...
|
| 173 |
+
def __contains__(self, key) -> bool: ...
|
| 174 |
+
def __iter__(self): ...
|
| 175 |
+
def __len__(self) -> int: ...
|
| 176 |
+
def add(self, key) -> None: ...
|
| 177 |
+
def discard(self, key) -> None: ...
|
| 178 |
+
|
| 179 |
+
def _setup_new_guiapp() -> None: ...
|
| 180 |
+
def _format_approx(number: float, precision: int) -> str: ...
|
| 181 |
+
def _g_sig_digits(value: float, delta: float) -> int: ...
|
| 182 |
+
def _unikey_or_keysym_to_mplkey(unikey: str, keysym: str) -> str: ...
|
| 183 |
+
def _is_torch_array(x: Any) -> bool: ...
|
| 184 |
+
def _is_jax_array(x: Any)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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy.typing import ArrayLike, NDArray
|
| 6 |
+
|
| 7 |
+
from . import artist, cm, transforms
|
| 8 |
+
from .backend_bases import MouseEvent
|
| 9 |
+
from .artist import Artist
|
| 10 |
+
from .colors import Normalize, Colormap
|
| 11 |
+
from .lines import Line2D
|
| 12 |
+
from .path import Path
|
| 13 |
+
from .patches import Patch
|
| 14 |
+
from .ticker import Locator, Formatter
|
| 15 |
+
from .tri import Triangulation
|
| 16 |
+
from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
|
| 17 |
+
|
| 18 |
+
class Collection(artist.Artist, cm.ScalarMappable):
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
*,
|
| 22 |
+
edgecolors: ColorType | Sequence[ColorType] | None = ...,
|
| 23 |
+
facecolors: ColorType | Sequence[ColorType] | None = ...,
|
| 24 |
+
linewidths: float | Sequence[float] | None = ...,
|
| 25 |
+
linestyles: LineStyleType | Sequence[LineStyleType] = ...,
|
| 26 |
+
capstyle: CapStyleType | None = ...,
|
| 27 |
+
joinstyle: JoinStyleType | None = ...,
|
| 28 |
+
antialiaseds: bool | Sequence[bool] | None = ...,
|
| 29 |
+
offsets: tuple[float, float] | Sequence[tuple[float, float]] | None = ...,
|
| 30 |
+
offset_transform: transforms.Transform | None = ...,
|
| 31 |
+
norm: Normalize | None = ...,
|
| 32 |
+
cmap: Colormap | None = ...,
|
| 33 |
+
pickradius: float = ...,
|
| 34 |
+
hatch: str | None = ...,
|
| 35 |
+
urls: Sequence[str] | None = ...,
|
| 36 |
+
zorder: float = ...,
|
| 37 |
+
**kwargs
|
| 38 |
+
) -> None: ...
|
| 39 |
+
def get_paths(self) -> Sequence[Path]: ...
|
| 40 |
+
def set_paths(self, paths: Sequence[Path]) -> None: ...
|
| 41 |
+
def get_transforms(self) -> Sequence[transforms.Transform]: ...
|
| 42 |
+
def get_offset_transform(self) -> transforms.Transform: ...
|
| 43 |
+
def set_offset_transform(self, offset_transform: transforms.Transform) -> None: ...
|
| 44 |
+
def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ...
|
| 45 |
+
def set_pickradius(self, pickradius: float) -> None: ...
|
| 46 |
+
def get_pickradius(self) -> float: ...
|
| 47 |
+
def set_urls(self, urls: Sequence[str | None]) -> None: ...
|
| 48 |
+
def get_urls(self) -> Sequence[str | None]: ...
|
| 49 |
+
def set_hatch(self, hatch: str) -> None: ...
|
| 50 |
+
def get_hatch(self) -> str: ...
|
| 51 |
+
def set_offsets(self, offsets: ArrayLike) -> None: ...
|
| 52 |
+
def get_offsets(self) -> ArrayLike: ...
|
| 53 |
+
def set_linewidth(self, lw: float | Sequence[float]) -> None: ...
|
| 54 |
+
def set_linestyle(self, ls: LineStyleType | Sequence[LineStyleType]) -> None: ...
|
| 55 |
+
def set_capstyle(self, cs: CapStyleType) -> None: ...
|
| 56 |
+
def get_capstyle(self) -> Literal["butt", "projecting", "round"] | None: ...
|
| 57 |
+
def set_joinstyle(self, js: JoinStyleType) -> None: ...
|
| 58 |
+
def get_joinstyle(self) -> Literal["miter", "round", "bevel"] | None: ...
|
| 59 |
+
def set_antialiased(self, aa: bool | Sequence[bool]) -> None: ...
|
| 60 |
+
def get_antialiased(self) -> NDArray[np.bool_]: ...
|
| 61 |
+
def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ...
|
| 62 |
+
def set_facecolor(self, c: ColorType | Sequence[ColorType]) -> None: ...
|
| 63 |
+
def get_facecolor(self) -> ColorType | Sequence[ColorType]: ...
|
| 64 |
+
def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ...
|
| 65 |
+
def set_edgecolor(self, c: ColorType | Sequence[ColorType]) -> None: ...
|
| 66 |
+
def set_alpha(self, alpha: float | Sequence[float] | None) -> None: ...
|
| 67 |
+
def get_linewidth(self) -> float | Sequence[float]: ...
|
| 68 |
+
def get_linestyle(self) -> LineStyleType | Sequence[LineStyleType]: ...
|
| 69 |
+
def update_scalarmappable(self) -> None: ...
|
| 70 |
+
def get_fill(self) -> bool: ...
|
| 71 |
+
def update_from(self, other: Artist) -> None: ...
|
| 72 |
+
|
| 73 |
+
class _CollectionWithSizes(Collection):
|
| 74 |
+
def get_sizes(self) -> np.ndarray: ...
|
| 75 |
+
def set_sizes(self, sizes: ArrayLike | None, dpi: float = ...) -> None: ...
|
| 76 |
+
|
| 77 |
+
class PathCollection(_CollectionWithSizes):
|
| 78 |
+
def __init__(
|
| 79 |
+
self, paths: Sequence[Path], sizes: ArrayLike | None = ..., **kwargs
|
| 80 |
+
) -> None: ...
|
| 81 |
+
def set_paths(self, paths: Sequence[Path]) -> None: ...
|
| 82 |
+
def get_paths(self) -> Sequence[Path]: ...
|
| 83 |
+
def legend_elements(
|
| 84 |
+
self,
|
| 85 |
+
prop: Literal["colors", "sizes"] = ...,
|
| 86 |
+
num: int | Literal["auto"] | ArrayLike | Locator = ...,
|
| 87 |
+
fmt: str | Formatter | None = ...,
|
| 88 |
+
func: Callable[[ArrayLike], ArrayLike] = ...,
|
| 89 |
+
**kwargs,
|
| 90 |
+
) -> tuple[list[Line2D], list[str]]: ...
|
| 91 |
+
|
| 92 |
+
class PolyCollection(_CollectionWithSizes):
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
verts: Sequence[ArrayLike],
|
| 96 |
+
sizes: ArrayLike | None = ...,
|
| 97 |
+
*,
|
| 98 |
+
closed: bool = ...,
|
| 99 |
+
**kwargs
|
| 100 |
+
) -> None: ...
|
| 101 |
+
def set_verts(
|
| 102 |
+
self, verts: Sequence[ArrayLike | Path], closed: bool = ...
|
| 103 |
+
) -> None: ...
|
| 104 |
+
def set_paths(self, verts: Sequence[Path], closed: bool = ...) -> None: ...
|
| 105 |
+
def set_verts_and_codes(
|
| 106 |
+
self, verts: Sequence[ArrayLike | Path], codes: Sequence[int]
|
| 107 |
+
) -> None: ...
|
| 108 |
+
|
| 109 |
+
class RegularPolyCollection(_CollectionWithSizes):
|
| 110 |
+
def __init__(
|
| 111 |
+
self, numsides: int, *, rotation: float = ..., sizes: ArrayLike = ..., **kwargs
|
| 112 |
+
) -> None: ...
|
| 113 |
+
def get_numsides(self) -> int: ...
|
| 114 |
+
def get_rotation(self) -> float: ...
|
| 115 |
+
|
| 116 |
+
class StarPolygonCollection(RegularPolyCollection): ...
|
| 117 |
+
class AsteriskPolygonCollection(RegularPolyCollection): ...
|
| 118 |
+
|
| 119 |
+
class LineCollection(Collection):
|
| 120 |
+
def __init__(
|
| 121 |
+
self, segments: Sequence[ArrayLike], *, zorder: float = ..., **kwargs
|
| 122 |
+
) -> None: ...
|
| 123 |
+
def set_segments(self, segments: Sequence[ArrayLike] | None) -> None: ...
|
| 124 |
+
def set_verts(self, segments: Sequence[ArrayLike] | None) -> None: ...
|
| 125 |
+
def set_paths(self, segments: Sequence[ArrayLike] | None) -> None: ... # type: ignore[override]
|
| 126 |
+
def get_segments(self) -> list[np.ndarray]: ...
|
| 127 |
+
def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ...
|
| 128 |
+
def set_colors(self, c: ColorType | Sequence[ColorType]) -> None: ...
|
| 129 |
+
def set_gapcolor(self, gapcolor: ColorType | Sequence[ColorType] | None) -> None: ...
|
| 130 |
+
def get_color(self) -> ColorType | Sequence[ColorType]: ...
|
| 131 |
+
def get_colors(self) -> ColorType | Sequence[ColorType]: ...
|
| 132 |
+
def get_gapcolor(self) -> ColorType | Sequence[ColorType] | None: ...
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class EventCollection(LineCollection):
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
positions: ArrayLike,
|
| 139 |
+
orientation: Literal["horizontal", "vertical"] = ...,
|
| 140 |
+
*,
|
| 141 |
+
lineoffset: float = ...,
|
| 142 |
+
linelength: float = ...,
|
| 143 |
+
linewidth: float | Sequence[float] | None = ...,
|
| 144 |
+
color: ColorType | Sequence[ColorType] | None = ...,
|
| 145 |
+
linestyle: LineStyleType | Sequence[LineStyleType] = ...,
|
| 146 |
+
antialiased: bool | Sequence[bool] | None = ...,
|
| 147 |
+
**kwargs
|
| 148 |
+
) -> None: ...
|
| 149 |
+
def get_positions(self) -> list[float]: ...
|
| 150 |
+
def set_positions(self, positions: Sequence[float] | None) -> None: ...
|
| 151 |
+
def add_positions(self, position: Sequence[float] | None) -> None: ...
|
| 152 |
+
def extend_positions(self, position: Sequence[float] | None) -> None: ...
|
| 153 |
+
def append_positions(self, position: Sequence[float] | None) -> None: ...
|
| 154 |
+
def is_horizontal(self) -> bool: ...
|
| 155 |
+
def get_orientation(self) -> Literal["horizontal", "vertical"]: ...
|
| 156 |
+
def switch_orientation(self) -> None: ...
|
| 157 |
+
def set_orientation(
|
| 158 |
+
self, orientation: Literal["horizontal", "vertical"]
|
| 159 |
+
) -> None: ...
|
| 160 |
+
def get_linelength(self) -> float | Sequence[float]: ...
|
| 161 |
+
def set_linelength(self, linelength: float | Sequence[float]) -> None: ...
|
| 162 |
+
def get_lineoffset(self) -> float: ...
|
| 163 |
+
def set_lineoffset(self, lineoffset: float) -> None: ...
|
| 164 |
+
def get_linewidth(self) -> float: ...
|
| 165 |
+
def get_linewidths(self) -> Sequence[float]: ...
|
| 166 |
+
def get_color(self) -> ColorType: ...
|
| 167 |
+
|
| 168 |
+
class CircleCollection(_CollectionWithSizes):
|
| 169 |
+
def __init__(self, sizes: float | ArrayLike, **kwargs) -> None: ...
|
| 170 |
+
|
| 171 |
+
class EllipseCollection(Collection):
|
| 172 |
+
def __init__(
|
| 173 |
+
self,
|
| 174 |
+
widths: ArrayLike,
|
| 175 |
+
heights: ArrayLike,
|
| 176 |
+
angles: ArrayLike,
|
| 177 |
+
*,
|
| 178 |
+
units: Literal[
|
| 179 |
+
"points", "inches", "dots", "width", "height", "x", "y", "xy"
|
| 180 |
+
] = ...,
|
| 181 |
+
**kwargs
|
| 182 |
+
) -> None: ...
|
| 183 |
+
def set_widths(self, widths: ArrayLike) -> None: ...
|
| 184 |
+
def set_heights(self, heights: ArrayLike) -> None: ...
|
| 185 |
+
def set_angles(self, angles: ArrayLike) -> None: ...
|
| 186 |
+
def get_widths(self) -> ArrayLike: ...
|
| 187 |
+
def get_heights(self) -> ArrayLike: ...
|
| 188 |
+
def get_angles(self) -> ArrayLike: ...
|
| 189 |
+
|
| 190 |
+
class PatchCollection(Collection):
|
| 191 |
+
def __init__(
|
| 192 |
+
self, patches: Iterable[Patch], *, match_original: bool = ..., **kwargs
|
| 193 |
+
) -> None: ...
|
| 194 |
+
def set_paths(self, patches: Iterable[Patch]) -> None: ... # type: ignore[override]
|
| 195 |
+
|
| 196 |
+
class TriMesh(Collection):
|
| 197 |
+
def __init__(self, triangulation: Triangulation, **kwargs) -> None: ...
|
| 198 |
+
def get_paths(self) -> list[Path]: ...
|
| 199 |
+
# Parent class has an argument, perhaps add a noop arg?
|
| 200 |
+
def set_paths(self) -> None: ... # type: ignore[override]
|
| 201 |
+
@staticmethod
|
| 202 |
+
def convert_mesh_to_paths(tri: Triangulation) -> list[Path]: ...
|
| 203 |
+
|
| 204 |
+
class _MeshData:
|
| 205 |
+
def __init__(
|
| 206 |
+
self,
|
| 207 |
+
coordinates: ArrayLike,
|
| 208 |
+
*,
|
| 209 |
+
shading: Literal["flat", "gouraud"] = ...,
|
| 210 |
+
) -> None: ...
|
| 211 |
+
def set_array(self, A: ArrayLike | None) -> None: ...
|
| 212 |
+
def get_coordinates(self) -> ArrayLike: ...
|
| 213 |
+
def get_facecolor(self) -> ColorType | Sequence[ColorType]: ...
|
| 214 |
+
def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ...
|
| 215 |
+
|
| 216 |
+
class QuadMesh(_MeshData, Collection):
|
| 217 |
+
def __init__(
|
| 218 |
+
self,
|
| 219 |
+
coordinates: ArrayLike,
|
| 220 |
+
*,
|
| 221 |
+
antialiased: bool = ...,
|
| 222 |
+
shading: Literal["flat", "gouraud"] = ...,
|
| 223 |
+
**kwargs
|
| 224 |
+
) -> None: ...
|
| 225 |
+
def get_paths(self) -> list[Path]: ...
|
| 226 |
+
# Parent class has an argument, perhaps add a noop arg?
|
| 227 |
+
def set_paths(self) -> None: ... # type: ignore[override]
|
| 228 |
+
def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ...
|
| 229 |
+
def get_cursor_data(self, event: MouseEvent) -> float: ...
|
| 230 |
+
|
| 231 |
+
class PolyQuadMesh(_MeshData, PolyCollection):
|
| 232 |
+
def __init__(
|
| 233 |
+
self,
|
| 234 |
+
coordinates: ArrayLike,
|
| 235 |
+
**kwargs
|
| 236 |
+
) -> None: ...
|
parrot/lib/python3.10/site-packages/matplotlib/colorbar.py
ADDED
|
@@ -0,0 +1,1559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Colorbars are a visualization of the mapping from scalar values to colors.
|
| 3 |
+
In Matplotlib they are drawn into a dedicated `~.axes.Axes`.
|
| 4 |
+
|
| 5 |
+
.. note::
|
| 6 |
+
Colorbars are typically created through `.Figure.colorbar` or its pyplot
|
| 7 |
+
wrapper `.pyplot.colorbar`, which internally use `.Colorbar` together with
|
| 8 |
+
`.make_axes_gridspec` (for `.GridSpec`-positioned Axes) or `.make_axes` (for
|
| 9 |
+
non-`.GridSpec`-positioned Axes).
|
| 10 |
+
|
| 11 |
+
End-users most likely won't need to directly use this module's API.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import logging
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
import matplotlib as mpl
|
| 19 |
+
from matplotlib import _api, cbook, collections, cm, colors, contour, ticker
|
| 20 |
+
import matplotlib.artist as martist
|
| 21 |
+
import matplotlib.patches as mpatches
|
| 22 |
+
import matplotlib.path as mpath
|
| 23 |
+
import matplotlib.spines as mspines
|
| 24 |
+
import matplotlib.transforms as mtransforms
|
| 25 |
+
from matplotlib import _docstring
|
| 26 |
+
|
| 27 |
+
_log = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
_docstring.interpd.update(
|
| 30 |
+
_make_axes_kw_doc="""
|
| 31 |
+
location : None or {'left', 'right', 'top', 'bottom'}
|
| 32 |
+
The location, relative to the parent Axes, where the colorbar Axes
|
| 33 |
+
is created. It also determines the *orientation* of the colorbar
|
| 34 |
+
(colorbars on the left and right are vertical, colorbars at the top
|
| 35 |
+
and bottom are horizontal). If None, the location will come from the
|
| 36 |
+
*orientation* if it is set (vertical colorbars on the right, horizontal
|
| 37 |
+
ones at the bottom), or default to 'right' if *orientation* is unset.
|
| 38 |
+
|
| 39 |
+
orientation : None or {'vertical', 'horizontal'}
|
| 40 |
+
The orientation of the colorbar. It is preferable to set the *location*
|
| 41 |
+
of the colorbar, as that also determines the *orientation*; passing
|
| 42 |
+
incompatible values for *location* and *orientation* raises an exception.
|
| 43 |
+
|
| 44 |
+
fraction : float, default: 0.15
|
| 45 |
+
Fraction of original Axes to use for colorbar.
|
| 46 |
+
|
| 47 |
+
shrink : float, default: 1.0
|
| 48 |
+
Fraction by which to multiply the size of the colorbar.
|
| 49 |
+
|
| 50 |
+
aspect : float, default: 20
|
| 51 |
+
Ratio of long to short dimensions.
|
| 52 |
+
|
| 53 |
+
pad : float, default: 0.05 if vertical, 0.15 if horizontal
|
| 54 |
+
Fraction of original Axes between colorbar and new image Axes.
|
| 55 |
+
|
| 56 |
+
anchor : (float, float), optional
|
| 57 |
+
The anchor point of the colorbar Axes.
|
| 58 |
+
Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.
|
| 59 |
+
|
| 60 |
+
panchor : (float, float), or *False*, optional
|
| 61 |
+
The anchor point of the colorbar parent Axes. If *False*, the parent
|
| 62 |
+
axes' anchor will be unchanged.
|
| 63 |
+
Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.""",
|
| 64 |
+
_colormap_kw_doc="""
|
| 65 |
+
extend : {'neither', 'both', 'min', 'max'}
|
| 66 |
+
Make pointed end(s) for out-of-range values (unless 'neither'). These are
|
| 67 |
+
set for a given colormap using the colormap set_under and set_over methods.
|
| 68 |
+
|
| 69 |
+
extendfrac : {*None*, 'auto', length, lengths}
|
| 70 |
+
If set to *None*, both the minimum and maximum triangular colorbar
|
| 71 |
+
extensions will have a length of 5% of the interior colorbar length (this
|
| 72 |
+
is the default setting).
|
| 73 |
+
|
| 74 |
+
If set to 'auto', makes the triangular colorbar extensions the same lengths
|
| 75 |
+
as the interior boxes (when *spacing* is set to 'uniform') or the same
|
| 76 |
+
lengths as the respective adjacent interior boxes (when *spacing* is set to
|
| 77 |
+
'proportional').
|
| 78 |
+
|
| 79 |
+
If a scalar, indicates the length of both the minimum and maximum
|
| 80 |
+
triangular colorbar extensions as a fraction of the interior colorbar
|
| 81 |
+
length. A two-element sequence of fractions may also be given, indicating
|
| 82 |
+
the lengths of the minimum and maximum colorbar extensions respectively as
|
| 83 |
+
a fraction of the interior colorbar length.
|
| 84 |
+
|
| 85 |
+
extendrect : bool
|
| 86 |
+
If *False* the minimum and maximum colorbar extensions will be triangular
|
| 87 |
+
(the default). If *True* the extensions will be rectangular.
|
| 88 |
+
|
| 89 |
+
spacing : {'uniform', 'proportional'}
|
| 90 |
+
For discrete colorbars (`.BoundaryNorm` or contours), 'uniform' gives each
|
| 91 |
+
color the same space; 'proportional' makes the space proportional to the
|
| 92 |
+
data interval.
|
| 93 |
+
|
| 94 |
+
ticks : None or list of ticks or Locator
|
| 95 |
+
If None, ticks are determined automatically from the input.
|
| 96 |
+
|
| 97 |
+
format : None or str or Formatter
|
| 98 |
+
If None, `~.ticker.ScalarFormatter` is used.
|
| 99 |
+
Format strings, e.g., ``"%4.2e"`` or ``"{x:.2e}"``, are supported.
|
| 100 |
+
An alternative `~.ticker.Formatter` may be given instead.
|
| 101 |
+
|
| 102 |
+
drawedges : bool
|
| 103 |
+
Whether to draw lines at color boundaries.
|
| 104 |
+
|
| 105 |
+
label : str
|
| 106 |
+
The label on the colorbar's long axis.
|
| 107 |
+
|
| 108 |
+
boundaries, values : None or a sequence
|
| 109 |
+
If unset, the colormap will be displayed on a 0-1 scale.
|
| 110 |
+
If sequences, *values* must have a length 1 less than *boundaries*. For
|
| 111 |
+
each region delimited by adjacent entries in *boundaries*, the color mapped
|
| 112 |
+
to the corresponding value in values will be used.
|
| 113 |
+
Normally only useful for indexed colors (i.e. ``norm=NoNorm()``) or other
|
| 114 |
+
unusual circumstances.""")
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _set_ticks_on_axis_warn(*args, **kwargs):
|
| 118 |
+
# a top level function which gets put in at the axes'
|
| 119 |
+
# set_xticks and set_yticks by Colorbar.__init__.
|
| 120 |
+
_api.warn_external("Use the colorbar set_ticks() method instead.")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class _ColorbarSpine(mspines.Spine):
|
| 124 |
+
def __init__(self, axes):
|
| 125 |
+
self._ax = axes
|
| 126 |
+
super().__init__(axes, 'colorbar', mpath.Path(np.empty((0, 2))))
|
| 127 |
+
mpatches.Patch.set_transform(self, axes.transAxes)
|
| 128 |
+
|
| 129 |
+
def get_window_extent(self, renderer=None):
|
| 130 |
+
# This Spine has no Axis associated with it, and doesn't need to adjust
|
| 131 |
+
# its location, so we can directly get the window extent from the
|
| 132 |
+
# super-super-class.
|
| 133 |
+
return mpatches.Patch.get_window_extent(self, renderer=renderer)
|
| 134 |
+
|
| 135 |
+
def set_xy(self, xy):
|
| 136 |
+
self._path = mpath.Path(xy, closed=True)
|
| 137 |
+
self._xy = xy
|
| 138 |
+
self.stale = True
|
| 139 |
+
|
| 140 |
+
def draw(self, renderer):
|
| 141 |
+
ret = mpatches.Patch.draw(self, renderer)
|
| 142 |
+
self.stale = False
|
| 143 |
+
return ret
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class _ColorbarAxesLocator:
|
| 147 |
+
"""
|
| 148 |
+
Shrink the Axes if there are triangular or rectangular extends.
|
| 149 |
+
"""
|
| 150 |
+
def __init__(self, cbar):
|
| 151 |
+
self._cbar = cbar
|
| 152 |
+
self._orig_locator = cbar.ax._axes_locator
|
| 153 |
+
|
| 154 |
+
def __call__(self, ax, renderer):
|
| 155 |
+
if self._orig_locator is not None:
|
| 156 |
+
pos = self._orig_locator(ax, renderer)
|
| 157 |
+
else:
|
| 158 |
+
pos = ax.get_position(original=True)
|
| 159 |
+
if self._cbar.extend == 'neither':
|
| 160 |
+
return pos
|
| 161 |
+
|
| 162 |
+
y, extendlen = self._cbar._proportional_y()
|
| 163 |
+
if not self._cbar._extend_lower():
|
| 164 |
+
extendlen[0] = 0
|
| 165 |
+
if not self._cbar._extend_upper():
|
| 166 |
+
extendlen[1] = 0
|
| 167 |
+
len = sum(extendlen) + 1
|
| 168 |
+
shrink = 1 / len
|
| 169 |
+
offset = extendlen[0] / len
|
| 170 |
+
# we need to reset the aspect ratio of the axes to account
|
| 171 |
+
# of the extends...
|
| 172 |
+
if hasattr(ax, '_colorbar_info'):
|
| 173 |
+
aspect = ax._colorbar_info['aspect']
|
| 174 |
+
else:
|
| 175 |
+
aspect = False
|
| 176 |
+
# now shrink and/or offset to take into account the
|
| 177 |
+
# extend tri/rectangles.
|
| 178 |
+
if self._cbar.orientation == 'vertical':
|
| 179 |
+
if aspect:
|
| 180 |
+
self._cbar.ax.set_box_aspect(aspect*shrink)
|
| 181 |
+
pos = pos.shrunk(1, shrink).translated(0, offset * pos.height)
|
| 182 |
+
else:
|
| 183 |
+
if aspect:
|
| 184 |
+
self._cbar.ax.set_box_aspect(1/(aspect * shrink))
|
| 185 |
+
pos = pos.shrunk(shrink, 1).translated(offset * pos.width, 0)
|
| 186 |
+
return pos
|
| 187 |
+
|
| 188 |
+
def get_subplotspec(self):
|
| 189 |
+
# make tight_layout happy..
|
| 190 |
+
return (
|
| 191 |
+
self._cbar.ax.get_subplotspec()
|
| 192 |
+
or getattr(self._orig_locator, "get_subplotspec", lambda: None)())
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@_docstring.interpd
|
| 196 |
+
class Colorbar:
|
| 197 |
+
r"""
|
| 198 |
+
Draw a colorbar in an existing Axes.
|
| 199 |
+
|
| 200 |
+
Typically, colorbars are created using `.Figure.colorbar` or
|
| 201 |
+
`.pyplot.colorbar` and associated with `.ScalarMappable`\s (such as an
|
| 202 |
+
`.AxesImage` generated via `~.axes.Axes.imshow`).
|
| 203 |
+
|
| 204 |
+
In order to draw a colorbar not associated with other elements in the
|
| 205 |
+
figure, e.g. when showing a colormap by itself, one can create an empty
|
| 206 |
+
`.ScalarMappable`, or directly pass *cmap* and *norm* instead of *mappable*
|
| 207 |
+
to `Colorbar`.
|
| 208 |
+
|
| 209 |
+
Useful public methods are :meth:`set_label` and :meth:`add_lines`.
|
| 210 |
+
|
| 211 |
+
Attributes
|
| 212 |
+
----------
|
| 213 |
+
ax : `~matplotlib.axes.Axes`
|
| 214 |
+
The `~.axes.Axes` instance in which the colorbar is drawn.
|
| 215 |
+
lines : list
|
| 216 |
+
A list of `.LineCollection` (empty if no lines were drawn).
|
| 217 |
+
dividers : `.LineCollection`
|
| 218 |
+
A LineCollection (empty if *drawedges* is ``False``).
|
| 219 |
+
|
| 220 |
+
Parameters
|
| 221 |
+
----------
|
| 222 |
+
ax : `~matplotlib.axes.Axes`
|
| 223 |
+
The `~.axes.Axes` instance in which the colorbar is drawn.
|
| 224 |
+
|
| 225 |
+
mappable : `.ScalarMappable`
|
| 226 |
+
The mappable whose colormap and norm will be used.
|
| 227 |
+
|
| 228 |
+
To show the under- and over- value colors, the mappable's norm should
|
| 229 |
+
be specified as ::
|
| 230 |
+
|
| 231 |
+
norm = colors.Normalize(clip=False)
|
| 232 |
+
|
| 233 |
+
To show the colors versus index instead of on a 0-1 scale, use::
|
| 234 |
+
|
| 235 |
+
norm=colors.NoNorm()
|
| 236 |
+
|
| 237 |
+
cmap : `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
|
| 238 |
+
The colormap to use. This parameter is ignored, unless *mappable* is
|
| 239 |
+
None.
|
| 240 |
+
|
| 241 |
+
norm : `~matplotlib.colors.Normalize`
|
| 242 |
+
The normalization to use. This parameter is ignored, unless *mappable*
|
| 243 |
+
is None.
|
| 244 |
+
|
| 245 |
+
alpha : float
|
| 246 |
+
The colorbar transparency between 0 (transparent) and 1 (opaque).
|
| 247 |
+
|
| 248 |
+
orientation : None or {'vertical', 'horizontal'}
|
| 249 |
+
If None, use the value determined by *location*. If both
|
| 250 |
+
*orientation* and *location* are None then defaults to 'vertical'.
|
| 251 |
+
|
| 252 |
+
ticklocation : {'auto', 'left', 'right', 'top', 'bottom'}
|
| 253 |
+
The location of the colorbar ticks. The *ticklocation* must match
|
| 254 |
+
*orientation*. For example, a horizontal colorbar can only have ticks
|
| 255 |
+
at the top or the bottom. If 'auto', the ticks will be the same as
|
| 256 |
+
*location*, so a colorbar to the left will have ticks to the left. If
|
| 257 |
+
*location* is None, the ticks will be at the bottom for a horizontal
|
| 258 |
+
colorbar and at the right for a vertical.
|
| 259 |
+
|
| 260 |
+
%(_colormap_kw_doc)s
|
| 261 |
+
|
| 262 |
+
location : None or {'left', 'right', 'top', 'bottom'}
|
| 263 |
+
Set the *orientation* and *ticklocation* of the colorbar using a
|
| 264 |
+
single argument. Colorbars on the left and right are vertical,
|
| 265 |
+
colorbars at the top and bottom are horizontal. The *ticklocation* is
|
| 266 |
+
the same as *location*, so if *location* is 'top', the ticks are on
|
| 267 |
+
the top. *orientation* and/or *ticklocation* can be provided as well
|
| 268 |
+
and overrides the value set by *location*, but there will be an error
|
| 269 |
+
for incompatible combinations.
|
| 270 |
+
|
| 271 |
+
.. versionadded:: 3.7
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
n_rasterize = 50 # rasterize solids if number of colors >= n_rasterize
|
| 275 |
+
|
| 276 |
+
def __init__(self, ax, mappable=None, *, cmap=None,
|
| 277 |
+
norm=None,
|
| 278 |
+
alpha=None,
|
| 279 |
+
values=None,
|
| 280 |
+
boundaries=None,
|
| 281 |
+
orientation=None,
|
| 282 |
+
ticklocation='auto',
|
| 283 |
+
extend=None,
|
| 284 |
+
spacing='uniform', # uniform or proportional
|
| 285 |
+
ticks=None,
|
| 286 |
+
format=None,
|
| 287 |
+
drawedges=False,
|
| 288 |
+
extendfrac=None,
|
| 289 |
+
extendrect=False,
|
| 290 |
+
label='',
|
| 291 |
+
location=None,
|
| 292 |
+
):
|
| 293 |
+
|
| 294 |
+
if mappable is None:
|
| 295 |
+
mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
|
| 296 |
+
|
| 297 |
+
self.mappable = mappable
|
| 298 |
+
cmap = mappable.cmap
|
| 299 |
+
norm = mappable.norm
|
| 300 |
+
|
| 301 |
+
filled = True
|
| 302 |
+
if isinstance(mappable, contour.ContourSet):
|
| 303 |
+
cs = mappable
|
| 304 |
+
alpha = cs.get_alpha()
|
| 305 |
+
boundaries = cs._levels
|
| 306 |
+
values = cs.cvalues
|
| 307 |
+
extend = cs.extend
|
| 308 |
+
filled = cs.filled
|
| 309 |
+
if ticks is None:
|
| 310 |
+
ticks = ticker.FixedLocator(cs.levels, nbins=10)
|
| 311 |
+
elif isinstance(mappable, martist.Artist):
|
| 312 |
+
alpha = mappable.get_alpha()
|
| 313 |
+
|
| 314 |
+
mappable.colorbar = self
|
| 315 |
+
mappable.colorbar_cid = mappable.callbacks.connect(
|
| 316 |
+
'changed', self.update_normal)
|
| 317 |
+
|
| 318 |
+
location_orientation = _get_orientation_from_location(location)
|
| 319 |
+
|
| 320 |
+
_api.check_in_list(
|
| 321 |
+
[None, 'vertical', 'horizontal'], orientation=orientation)
|
| 322 |
+
_api.check_in_list(
|
| 323 |
+
['auto', 'left', 'right', 'top', 'bottom'],
|
| 324 |
+
ticklocation=ticklocation)
|
| 325 |
+
_api.check_in_list(
|
| 326 |
+
['uniform', 'proportional'], spacing=spacing)
|
| 327 |
+
|
| 328 |
+
if location_orientation is not None and orientation is not None:
|
| 329 |
+
if location_orientation != orientation:
|
| 330 |
+
raise TypeError(
|
| 331 |
+
"location and orientation are mutually exclusive")
|
| 332 |
+
else:
|
| 333 |
+
orientation = orientation or location_orientation or "vertical"
|
| 334 |
+
|
| 335 |
+
self.ax = ax
|
| 336 |
+
self.ax._axes_locator = _ColorbarAxesLocator(self)
|
| 337 |
+
|
| 338 |
+
if extend is None:
|
| 339 |
+
if (not isinstance(mappable, contour.ContourSet)
|
| 340 |
+
and getattr(cmap, 'colorbar_extend', False) is not False):
|
| 341 |
+
extend = cmap.colorbar_extend
|
| 342 |
+
elif hasattr(norm, 'extend'):
|
| 343 |
+
extend = norm.extend
|
| 344 |
+
else:
|
| 345 |
+
extend = 'neither'
|
| 346 |
+
self.alpha = None
|
| 347 |
+
# Call set_alpha to handle array-like alphas properly
|
| 348 |
+
self.set_alpha(alpha)
|
| 349 |
+
self.cmap = cmap
|
| 350 |
+
self.norm = norm
|
| 351 |
+
self.values = values
|
| 352 |
+
self.boundaries = boundaries
|
| 353 |
+
self.extend = extend
|
| 354 |
+
self._inside = _api.check_getitem(
|
| 355 |
+
{'neither': slice(0, None), 'both': slice(1, -1),
|
| 356 |
+
'min': slice(1, None), 'max': slice(0, -1)},
|
| 357 |
+
extend=extend)
|
| 358 |
+
self.spacing = spacing
|
| 359 |
+
self.orientation = orientation
|
| 360 |
+
self.drawedges = drawedges
|
| 361 |
+
self._filled = filled
|
| 362 |
+
self.extendfrac = extendfrac
|
| 363 |
+
self.extendrect = extendrect
|
| 364 |
+
self._extend_patches = []
|
| 365 |
+
self.solids = None
|
| 366 |
+
self.solids_patches = []
|
| 367 |
+
self.lines = []
|
| 368 |
+
|
| 369 |
+
for spine in self.ax.spines.values():
|
| 370 |
+
spine.set_visible(False)
|
| 371 |
+
self.outline = self.ax.spines['outline'] = _ColorbarSpine(self.ax)
|
| 372 |
+
|
| 373 |
+
self.dividers = collections.LineCollection(
|
| 374 |
+
[],
|
| 375 |
+
colors=[mpl.rcParams['axes.edgecolor']],
|
| 376 |
+
linewidths=[0.5 * mpl.rcParams['axes.linewidth']],
|
| 377 |
+
clip_on=False)
|
| 378 |
+
self.ax.add_collection(self.dividers)
|
| 379 |
+
|
| 380 |
+
self._locator = None
|
| 381 |
+
self._minorlocator = None
|
| 382 |
+
self._formatter = None
|
| 383 |
+
self._minorformatter = None
|
| 384 |
+
|
| 385 |
+
if ticklocation == 'auto':
|
| 386 |
+
ticklocation = _get_ticklocation_from_orientation(
|
| 387 |
+
orientation) if location is None else location
|
| 388 |
+
self.ticklocation = ticklocation
|
| 389 |
+
|
| 390 |
+
self.set_label(label)
|
| 391 |
+
self._reset_locator_formatter_scale()
|
| 392 |
+
|
| 393 |
+
if np.iterable(ticks):
|
| 394 |
+
self._locator = ticker.FixedLocator(ticks, nbins=len(ticks))
|
| 395 |
+
else:
|
| 396 |
+
self._locator = ticks
|
| 397 |
+
|
| 398 |
+
if isinstance(format, str):
|
| 399 |
+
# Check format between FormatStrFormatter and StrMethodFormatter
|
| 400 |
+
try:
|
| 401 |
+
self._formatter = ticker.FormatStrFormatter(format)
|
| 402 |
+
_ = self._formatter(0)
|
| 403 |
+
except (TypeError, ValueError):
|
| 404 |
+
self._formatter = ticker.StrMethodFormatter(format)
|
| 405 |
+
else:
|
| 406 |
+
self._formatter = format # Assume it is a Formatter or None
|
| 407 |
+
self._draw_all()
|
| 408 |
+
|
| 409 |
+
if isinstance(mappable, contour.ContourSet) and not mappable.filled:
|
| 410 |
+
self.add_lines(mappable)
|
| 411 |
+
|
| 412 |
+
# Link the Axes and Colorbar for interactive use
|
| 413 |
+
self.ax._colorbar = self
|
| 414 |
+
# Don't navigate on any of these types of mappables
|
| 415 |
+
if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) or
|
| 416 |
+
isinstance(self.mappable, contour.ContourSet)):
|
| 417 |
+
self.ax.set_navigate(False)
|
| 418 |
+
|
| 419 |
+
# These are the functions that set up interactivity on this colorbar
|
| 420 |
+
self._interactive_funcs = ["_get_view", "_set_view",
|
| 421 |
+
"_set_view_from_bbox", "drag_pan"]
|
| 422 |
+
for x in self._interactive_funcs:
|
| 423 |
+
setattr(self.ax, x, getattr(self, x))
|
| 424 |
+
# Set the cla function to the cbar's method to override it
|
| 425 |
+
self.ax.cla = self._cbar_cla
|
| 426 |
+
# Callbacks for the extend calculations to handle inverting the axis
|
| 427 |
+
self._extend_cid1 = self.ax.callbacks.connect(
|
| 428 |
+
"xlim_changed", self._do_extends)
|
| 429 |
+
self._extend_cid2 = self.ax.callbacks.connect(
|
| 430 |
+
"ylim_changed", self._do_extends)
|
| 431 |
+
|
| 432 |
+
@property
|
| 433 |
+
def locator(self):
|
| 434 |
+
"""Major tick `.Locator` for the colorbar."""
|
| 435 |
+
return self._long_axis().get_major_locator()
|
| 436 |
+
|
| 437 |
+
@locator.setter
|
| 438 |
+
def locator(self, loc):
|
| 439 |
+
self._long_axis().set_major_locator(loc)
|
| 440 |
+
self._locator = loc
|
| 441 |
+
|
| 442 |
+
@property
|
| 443 |
+
def minorlocator(self):
|
| 444 |
+
"""Minor tick `.Locator` for the colorbar."""
|
| 445 |
+
return self._long_axis().get_minor_locator()
|
| 446 |
+
|
| 447 |
+
@minorlocator.setter
|
| 448 |
+
def minorlocator(self, loc):
|
| 449 |
+
self._long_axis().set_minor_locator(loc)
|
| 450 |
+
self._minorlocator = loc
|
| 451 |
+
|
| 452 |
+
@property
|
| 453 |
+
def formatter(self):
|
| 454 |
+
"""Major tick label `.Formatter` for the colorbar."""
|
| 455 |
+
return self._long_axis().get_major_formatter()
|
| 456 |
+
|
| 457 |
+
@formatter.setter
|
| 458 |
+
def formatter(self, fmt):
|
| 459 |
+
self._long_axis().set_major_formatter(fmt)
|
| 460 |
+
self._formatter = fmt
|
| 461 |
+
|
| 462 |
+
@property
|
| 463 |
+
def minorformatter(self):
|
| 464 |
+
"""Minor tick `.Formatter` for the colorbar."""
|
| 465 |
+
return self._long_axis().get_minor_formatter()
|
| 466 |
+
|
| 467 |
+
@minorformatter.setter
|
| 468 |
+
def minorformatter(self, fmt):
|
| 469 |
+
self._long_axis().set_minor_formatter(fmt)
|
| 470 |
+
self._minorformatter = fmt
|
| 471 |
+
|
| 472 |
+
def _cbar_cla(self):
|
| 473 |
+
"""Function to clear the interactive colorbar state."""
|
| 474 |
+
for x in self._interactive_funcs:
|
| 475 |
+
delattr(self.ax, x)
|
| 476 |
+
# We now restore the old cla() back and can call it directly
|
| 477 |
+
del self.ax.cla
|
| 478 |
+
self.ax.cla()
|
| 479 |
+
|
| 480 |
+
def update_normal(self, mappable):
|
| 481 |
+
"""
|
| 482 |
+
Update solid patches, lines, etc.
|
| 483 |
+
|
| 484 |
+
This is meant to be called when the norm of the image or contour plot
|
| 485 |
+
to which this colorbar belongs changes.
|
| 486 |
+
|
| 487 |
+
If the norm on the mappable is different than before, this resets the
|
| 488 |
+
locator and formatter for the axis, so if these have been customized,
|
| 489 |
+
they will need to be customized again. However, if the norm only
|
| 490 |
+
changes values of *vmin*, *vmax* or *cmap* then the old formatter
|
| 491 |
+
and locator will be preserved.
|
| 492 |
+
"""
|
| 493 |
+
_log.debug('colorbar update normal %r %r', mappable.norm, self.norm)
|
| 494 |
+
self.mappable = mappable
|
| 495 |
+
self.set_alpha(mappable.get_alpha())
|
| 496 |
+
self.cmap = mappable.cmap
|
| 497 |
+
if mappable.norm != self.norm:
|
| 498 |
+
self.norm = mappable.norm
|
| 499 |
+
self._reset_locator_formatter_scale()
|
| 500 |
+
|
| 501 |
+
self._draw_all()
|
| 502 |
+
if isinstance(self.mappable, contour.ContourSet):
|
| 503 |
+
CS = self.mappable
|
| 504 |
+
if not CS.filled:
|
| 505 |
+
self.add_lines(CS)
|
| 506 |
+
self.stale = True
|
| 507 |
+
|
| 508 |
+
def _draw_all(self):
|
| 509 |
+
"""
|
| 510 |
+
Calculate any free parameters based on the current cmap and norm,
|
| 511 |
+
and do all the drawing.
|
| 512 |
+
"""
|
| 513 |
+
if self.orientation == 'vertical':
|
| 514 |
+
if mpl.rcParams['ytick.minor.visible']:
|
| 515 |
+
self.minorticks_on()
|
| 516 |
+
else:
|
| 517 |
+
if mpl.rcParams['xtick.minor.visible']:
|
| 518 |
+
self.minorticks_on()
|
| 519 |
+
self._long_axis().set(label_position=self.ticklocation,
|
| 520 |
+
ticks_position=self.ticklocation)
|
| 521 |
+
self._short_axis().set_ticks([])
|
| 522 |
+
self._short_axis().set_ticks([], minor=True)
|
| 523 |
+
|
| 524 |
+
# Set self._boundaries and self._values, including extensions.
|
| 525 |
+
# self._boundaries are the edges of each square of color, and
|
| 526 |
+
# self._values are the value to map into the norm to get the
|
| 527 |
+
# color:
|
| 528 |
+
self._process_values()
|
| 529 |
+
# Set self.vmin and self.vmax to first and last boundary, excluding
|
| 530 |
+
# extensions:
|
| 531 |
+
self.vmin, self.vmax = self._boundaries[self._inside][[0, -1]]
|
| 532 |
+
# Compute the X/Y mesh.
|
| 533 |
+
X, Y = self._mesh()
|
| 534 |
+
# draw the extend triangles, and shrink the inner Axes to accommodate.
|
| 535 |
+
# also adds the outline path to self.outline spine:
|
| 536 |
+
self._do_extends()
|
| 537 |
+
lower, upper = self.vmin, self.vmax
|
| 538 |
+
if self._long_axis().get_inverted():
|
| 539 |
+
# If the axis is inverted, we need to swap the vmin/vmax
|
| 540 |
+
lower, upper = upper, lower
|
| 541 |
+
if self.orientation == 'vertical':
|
| 542 |
+
self.ax.set_xlim(0, 1)
|
| 543 |
+
self.ax.set_ylim(lower, upper)
|
| 544 |
+
else:
|
| 545 |
+
self.ax.set_ylim(0, 1)
|
| 546 |
+
self.ax.set_xlim(lower, upper)
|
| 547 |
+
|
| 548 |
+
# set up the tick locators and formatters. A bit complicated because
|
| 549 |
+
# boundary norms + uniform spacing requires a manual locator.
|
| 550 |
+
self.update_ticks()
|
| 551 |
+
|
| 552 |
+
if self._filled:
|
| 553 |
+
ind = np.arange(len(self._values))
|
| 554 |
+
if self._extend_lower():
|
| 555 |
+
ind = ind[1:]
|
| 556 |
+
if self._extend_upper():
|
| 557 |
+
ind = ind[:-1]
|
| 558 |
+
self._add_solids(X, Y, self._values[ind, np.newaxis])
|
| 559 |
+
|
| 560 |
+
def _add_solids(self, X, Y, C):
|
| 561 |
+
"""Draw the colors; optionally add separators."""
|
| 562 |
+
# Cleanup previously set artists.
|
| 563 |
+
if self.solids is not None:
|
| 564 |
+
self.solids.remove()
|
| 565 |
+
for solid in self.solids_patches:
|
| 566 |
+
solid.remove()
|
| 567 |
+
# Add new artist(s), based on mappable type. Use individual patches if
|
| 568 |
+
# hatching is needed, pcolormesh otherwise.
|
| 569 |
+
mappable = getattr(self, 'mappable', None)
|
| 570 |
+
if (isinstance(mappable, contour.ContourSet)
|
| 571 |
+
and any(hatch is not None for hatch in mappable.hatches)):
|
| 572 |
+
self._add_solids_patches(X, Y, C, mappable)
|
| 573 |
+
else:
|
| 574 |
+
self.solids = self.ax.pcolormesh(
|
| 575 |
+
X, Y, C, cmap=self.cmap, norm=self.norm, alpha=self.alpha,
|
| 576 |
+
edgecolors='none', shading='flat')
|
| 577 |
+
if not self.drawedges:
|
| 578 |
+
if len(self._y) >= self.n_rasterize:
|
| 579 |
+
self.solids.set_rasterized(True)
|
| 580 |
+
self._update_dividers()
|
| 581 |
+
|
| 582 |
+
def _update_dividers(self):
|
| 583 |
+
if not self.drawedges:
|
| 584 |
+
self.dividers.set_segments([])
|
| 585 |
+
return
|
| 586 |
+
# Place all *internal* dividers.
|
| 587 |
+
if self.orientation == 'vertical':
|
| 588 |
+
lims = self.ax.get_ylim()
|
| 589 |
+
bounds = (lims[0] < self._y) & (self._y < lims[1])
|
| 590 |
+
else:
|
| 591 |
+
lims = self.ax.get_xlim()
|
| 592 |
+
bounds = (lims[0] < self._y) & (self._y < lims[1])
|
| 593 |
+
y = self._y[bounds]
|
| 594 |
+
# And then add outer dividers if extensions are on.
|
| 595 |
+
if self._extend_lower():
|
| 596 |
+
y = np.insert(y, 0, lims[0])
|
| 597 |
+
if self._extend_upper():
|
| 598 |
+
y = np.append(y, lims[1])
|
| 599 |
+
X, Y = np.meshgrid([0, 1], y)
|
| 600 |
+
if self.orientation == 'vertical':
|
| 601 |
+
segments = np.dstack([X, Y])
|
| 602 |
+
else:
|
| 603 |
+
segments = np.dstack([Y, X])
|
| 604 |
+
self.dividers.set_segments(segments)
|
| 605 |
+
|
| 606 |
+
def _add_solids_patches(self, X, Y, C, mappable):
|
| 607 |
+
hatches = mappable.hatches * (len(C) + 1) # Have enough hatches.
|
| 608 |
+
if self._extend_lower():
|
| 609 |
+
# remove first hatch that goes into the extend patch
|
| 610 |
+
hatches = hatches[1:]
|
| 611 |
+
patches = []
|
| 612 |
+
for i in range(len(X) - 1):
|
| 613 |
+
xy = np.array([[X[i, 0], Y[i, 1]],
|
| 614 |
+
[X[i, 1], Y[i, 0]],
|
| 615 |
+
[X[i + 1, 1], Y[i + 1, 0]],
|
| 616 |
+
[X[i + 1, 0], Y[i + 1, 1]]])
|
| 617 |
+
patch = mpatches.PathPatch(mpath.Path(xy),
|
| 618 |
+
facecolor=self.cmap(self.norm(C[i][0])),
|
| 619 |
+
hatch=hatches[i], linewidth=0,
|
| 620 |
+
antialiased=False, alpha=self.alpha)
|
| 621 |
+
self.ax.add_patch(patch)
|
| 622 |
+
patches.append(patch)
|
| 623 |
+
self.solids_patches = patches
|
| 624 |
+
|
| 625 |
+
def _do_extends(self, ax=None):
|
| 626 |
+
"""
|
| 627 |
+
Add the extend tri/rectangles on the outside of the Axes.
|
| 628 |
+
|
| 629 |
+
ax is unused, but required due to the callbacks on xlim/ylim changed
|
| 630 |
+
"""
|
| 631 |
+
# Clean up any previous extend patches
|
| 632 |
+
for patch in self._extend_patches:
|
| 633 |
+
patch.remove()
|
| 634 |
+
self._extend_patches = []
|
| 635 |
+
# extend lengths are fraction of the *inner* part of colorbar,
|
| 636 |
+
# not the total colorbar:
|
| 637 |
+
_, extendlen = self._proportional_y()
|
| 638 |
+
bot = 0 - (extendlen[0] if self._extend_lower() else 0)
|
| 639 |
+
top = 1 + (extendlen[1] if self._extend_upper() else 0)
|
| 640 |
+
|
| 641 |
+
# xyout is the outline of the colorbar including the extend patches:
|
| 642 |
+
if not self.extendrect:
|
| 643 |
+
# triangle:
|
| 644 |
+
xyout = np.array([[0, 0], [0.5, bot], [1, 0],
|
| 645 |
+
[1, 1], [0.5, top], [0, 1], [0, 0]])
|
| 646 |
+
else:
|
| 647 |
+
# rectangle:
|
| 648 |
+
xyout = np.array([[0, 0], [0, bot], [1, bot], [1, 0],
|
| 649 |
+
[1, 1], [1, top], [0, top], [0, 1],
|
| 650 |
+
[0, 0]])
|
| 651 |
+
|
| 652 |
+
if self.orientation == 'horizontal':
|
| 653 |
+
xyout = xyout[:, ::-1]
|
| 654 |
+
|
| 655 |
+
# xyout is the path for the spine:
|
| 656 |
+
self.outline.set_xy(xyout)
|
| 657 |
+
if not self._filled:
|
| 658 |
+
return
|
| 659 |
+
|
| 660 |
+
# Make extend triangles or rectangles filled patches. These are
|
| 661 |
+
# defined in the outer parent axes' coordinates:
|
| 662 |
+
mappable = getattr(self, 'mappable', None)
|
| 663 |
+
if (isinstance(mappable, contour.ContourSet)
|
| 664 |
+
and any(hatch is not None for hatch in mappable.hatches)):
|
| 665 |
+
hatches = mappable.hatches * (len(self._y) + 1)
|
| 666 |
+
else:
|
| 667 |
+
hatches = [None] * (len(self._y) + 1)
|
| 668 |
+
|
| 669 |
+
if self._extend_lower():
|
| 670 |
+
if not self.extendrect:
|
| 671 |
+
# triangle
|
| 672 |
+
xy = np.array([[0, 0], [0.5, bot], [1, 0]])
|
| 673 |
+
else:
|
| 674 |
+
# rectangle
|
| 675 |
+
xy = np.array([[0, 0], [0, bot], [1., bot], [1, 0]])
|
| 676 |
+
if self.orientation == 'horizontal':
|
| 677 |
+
xy = xy[:, ::-1]
|
| 678 |
+
# add the patch
|
| 679 |
+
val = -1 if self._long_axis().get_inverted() else 0
|
| 680 |
+
color = self.cmap(self.norm(self._values[val]))
|
| 681 |
+
patch = mpatches.PathPatch(
|
| 682 |
+
mpath.Path(xy), facecolor=color, alpha=self.alpha,
|
| 683 |
+
linewidth=0, antialiased=False,
|
| 684 |
+
transform=self.ax.transAxes,
|
| 685 |
+
hatch=hatches[0], clip_on=False,
|
| 686 |
+
# Place it right behind the standard patches, which is
|
| 687 |
+
# needed if we updated the extends
|
| 688 |
+
zorder=np.nextafter(self.ax.patch.zorder, -np.inf))
|
| 689 |
+
self.ax.add_patch(patch)
|
| 690 |
+
self._extend_patches.append(patch)
|
| 691 |
+
# remove first hatch that goes into the extend patch
|
| 692 |
+
hatches = hatches[1:]
|
| 693 |
+
if self._extend_upper():
|
| 694 |
+
if not self.extendrect:
|
| 695 |
+
# triangle
|
| 696 |
+
xy = np.array([[0, 1], [0.5, top], [1, 1]])
|
| 697 |
+
else:
|
| 698 |
+
# rectangle
|
| 699 |
+
xy = np.array([[0, 1], [0, top], [1, top], [1, 1]])
|
| 700 |
+
if self.orientation == 'horizontal':
|
| 701 |
+
xy = xy[:, ::-1]
|
| 702 |
+
# add the patch
|
| 703 |
+
val = 0 if self._long_axis().get_inverted() else -1
|
| 704 |
+
color = self.cmap(self.norm(self._values[val]))
|
| 705 |
+
hatch_idx = len(self._y) - 1
|
| 706 |
+
patch = mpatches.PathPatch(
|
| 707 |
+
mpath.Path(xy), facecolor=color, alpha=self.alpha,
|
| 708 |
+
linewidth=0, antialiased=False,
|
| 709 |
+
transform=self.ax.transAxes, hatch=hatches[hatch_idx],
|
| 710 |
+
clip_on=False,
|
| 711 |
+
# Place it right behind the standard patches, which is
|
| 712 |
+
# needed if we updated the extends
|
| 713 |
+
zorder=np.nextafter(self.ax.patch.zorder, -np.inf))
|
| 714 |
+
self.ax.add_patch(patch)
|
| 715 |
+
self._extend_patches.append(patch)
|
| 716 |
+
|
| 717 |
+
self._update_dividers()
|
| 718 |
+
|
| 719 |
+
def add_lines(self, *args, **kwargs):
|
| 720 |
+
"""
|
| 721 |
+
Draw lines on the colorbar.
|
| 722 |
+
|
| 723 |
+
The lines are appended to the list :attr:`lines`.
|
| 724 |
+
|
| 725 |
+
Parameters
|
| 726 |
+
----------
|
| 727 |
+
levels : array-like
|
| 728 |
+
The positions of the lines.
|
| 729 |
+
colors : :mpltype:`color` or list of :mpltype:`color`
|
| 730 |
+
Either a single color applying to all lines or one color value for
|
| 731 |
+
each line.
|
| 732 |
+
linewidths : float or array-like
|
| 733 |
+
Either a single linewidth applying to all lines or one linewidth
|
| 734 |
+
for each line.
|
| 735 |
+
erase : bool, default: True
|
| 736 |
+
Whether to remove any previously added lines.
|
| 737 |
+
|
| 738 |
+
Notes
|
| 739 |
+
-----
|
| 740 |
+
Alternatively, this method can also be called with the signature
|
| 741 |
+
``colorbar.add_lines(contour_set, erase=True)``, in which case
|
| 742 |
+
*levels*, *colors*, and *linewidths* are taken from *contour_set*.
|
| 743 |
+
"""
|
| 744 |
+
params = _api.select_matching_signature(
|
| 745 |
+
[lambda self, CS, erase=True: locals(),
|
| 746 |
+
lambda self, levels, colors, linewidths, erase=True: locals()],
|
| 747 |
+
self, *args, **kwargs)
|
| 748 |
+
if "CS" in params:
|
| 749 |
+
self, cs, erase = params.values()
|
| 750 |
+
if not isinstance(cs, contour.ContourSet) or cs.filled:
|
| 751 |
+
raise ValueError("If a single artist is passed to add_lines, "
|
| 752 |
+
"it must be a ContourSet of lines")
|
| 753 |
+
# TODO: Make colorbar lines auto-follow changes in contour lines.
|
| 754 |
+
return self.add_lines(
|
| 755 |
+
cs.levels,
|
| 756 |
+
cs.to_rgba(cs.cvalues, cs.alpha),
|
| 757 |
+
cs.get_linewidths(),
|
| 758 |
+
erase=erase)
|
| 759 |
+
else:
|
| 760 |
+
self, levels, colors, linewidths, erase = params.values()
|
| 761 |
+
|
| 762 |
+
y = self._locate(levels)
|
| 763 |
+
rtol = (self._y[-1] - self._y[0]) * 1e-10
|
| 764 |
+
igood = (y < self._y[-1] + rtol) & (y > self._y[0] - rtol)
|
| 765 |
+
y = y[igood]
|
| 766 |
+
if np.iterable(colors):
|
| 767 |
+
colors = np.asarray(colors)[igood]
|
| 768 |
+
if np.iterable(linewidths):
|
| 769 |
+
linewidths = np.asarray(linewidths)[igood]
|
| 770 |
+
X, Y = np.meshgrid([0, 1], y)
|
| 771 |
+
if self.orientation == 'vertical':
|
| 772 |
+
xy = np.stack([X, Y], axis=-1)
|
| 773 |
+
else:
|
| 774 |
+
xy = np.stack([Y, X], axis=-1)
|
| 775 |
+
col = collections.LineCollection(xy, linewidths=linewidths,
|
| 776 |
+
colors=colors)
|
| 777 |
+
|
| 778 |
+
if erase and self.lines:
|
| 779 |
+
for lc in self.lines:
|
| 780 |
+
lc.remove()
|
| 781 |
+
self.lines = []
|
| 782 |
+
self.lines.append(col)
|
| 783 |
+
|
| 784 |
+
# make a clip path that is just a linewidth bigger than the Axes...
|
| 785 |
+
fac = np.max(linewidths) / 72
|
| 786 |
+
xy = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
|
| 787 |
+
inches = self.ax.get_figure().dpi_scale_trans
|
| 788 |
+
# do in inches:
|
| 789 |
+
xy = inches.inverted().transform(self.ax.transAxes.transform(xy))
|
| 790 |
+
xy[[0, 1, 4], 1] -= fac
|
| 791 |
+
xy[[2, 3], 1] += fac
|
| 792 |
+
# back to axes units...
|
| 793 |
+
xy = self.ax.transAxes.inverted().transform(inches.transform(xy))
|
| 794 |
+
col.set_clip_path(mpath.Path(xy, closed=True),
|
| 795 |
+
self.ax.transAxes)
|
| 796 |
+
self.ax.add_collection(col)
|
| 797 |
+
self.stale = True
|
| 798 |
+
|
| 799 |
+
def update_ticks(self):
|
| 800 |
+
"""
|
| 801 |
+
Set up the ticks and ticklabels. This should not be needed by users.
|
| 802 |
+
"""
|
| 803 |
+
# Get the locator and formatter; defaults to self._locator if not None.
|
| 804 |
+
self._get_ticker_locator_formatter()
|
| 805 |
+
self._long_axis().set_major_locator(self._locator)
|
| 806 |
+
self._long_axis().set_minor_locator(self._minorlocator)
|
| 807 |
+
self._long_axis().set_major_formatter(self._formatter)
|
| 808 |
+
|
| 809 |
+
def _get_ticker_locator_formatter(self):
|
| 810 |
+
"""
|
| 811 |
+
Return the ``locator`` and ``formatter`` of the colorbar.
|
| 812 |
+
|
| 813 |
+
If they have not been defined (i.e. are *None*), the formatter and
|
| 814 |
+
locator are retrieved from the axis, or from the value of the
|
| 815 |
+
boundaries for a boundary norm.
|
| 816 |
+
|
| 817 |
+
Called by update_ticks...
|
| 818 |
+
"""
|
| 819 |
+
locator = self._locator
|
| 820 |
+
formatter = self._formatter
|
| 821 |
+
minorlocator = self._minorlocator
|
| 822 |
+
if isinstance(self.norm, colors.BoundaryNorm):
|
| 823 |
+
b = self.norm.boundaries
|
| 824 |
+
if locator is None:
|
| 825 |
+
locator = ticker.FixedLocator(b, nbins=10)
|
| 826 |
+
if minorlocator is None:
|
| 827 |
+
minorlocator = ticker.FixedLocator(b)
|
| 828 |
+
elif isinstance(self.norm, colors.NoNorm):
|
| 829 |
+
if locator is None:
|
| 830 |
+
# put ticks on integers between the boundaries of NoNorm
|
| 831 |
+
nv = len(self._values)
|
| 832 |
+
base = 1 + int(nv / 10)
|
| 833 |
+
locator = ticker.IndexLocator(base=base, offset=.5)
|
| 834 |
+
elif self.boundaries is not None:
|
| 835 |
+
b = self._boundaries[self._inside]
|
| 836 |
+
if locator is None:
|
| 837 |
+
locator = ticker.FixedLocator(b, nbins=10)
|
| 838 |
+
else: # most cases:
|
| 839 |
+
if locator is None:
|
| 840 |
+
# we haven't set the locator explicitly, so use the default
|
| 841 |
+
# for this axis:
|
| 842 |
+
locator = self._long_axis().get_major_locator()
|
| 843 |
+
if minorlocator is None:
|
| 844 |
+
minorlocator = self._long_axis().get_minor_locator()
|
| 845 |
+
|
| 846 |
+
if minorlocator is None:
|
| 847 |
+
minorlocator = ticker.NullLocator()
|
| 848 |
+
|
| 849 |
+
if formatter is None:
|
| 850 |
+
formatter = self._long_axis().get_major_formatter()
|
| 851 |
+
|
| 852 |
+
self._locator = locator
|
| 853 |
+
self._formatter = formatter
|
| 854 |
+
self._minorlocator = minorlocator
|
| 855 |
+
_log.debug('locator: %r', locator)
|
| 856 |
+
|
| 857 |
+
def set_ticks(self, ticks, *, labels=None, minor=False, **kwargs):
|
| 858 |
+
"""
|
| 859 |
+
Set tick locations.
|
| 860 |
+
|
| 861 |
+
Parameters
|
| 862 |
+
----------
|
| 863 |
+
ticks : 1D array-like
|
| 864 |
+
List of tick locations.
|
| 865 |
+
labels : list of str, optional
|
| 866 |
+
List of tick labels. If not set, the labels show the data value.
|
| 867 |
+
minor : bool, default: False
|
| 868 |
+
If ``False``, set the major ticks; if ``True``, the minor ticks.
|
| 869 |
+
**kwargs
|
| 870 |
+
`.Text` properties for the labels. These take effect only if you
|
| 871 |
+
pass *labels*. In other cases, please use `~.Axes.tick_params`.
|
| 872 |
+
"""
|
| 873 |
+
if np.iterable(ticks):
|
| 874 |
+
self._long_axis().set_ticks(ticks, labels=labels, minor=minor,
|
| 875 |
+
**kwargs)
|
| 876 |
+
self._locator = self._long_axis().get_major_locator()
|
| 877 |
+
else:
|
| 878 |
+
self._locator = ticks
|
| 879 |
+
self._long_axis().set_major_locator(self._locator)
|
| 880 |
+
self.stale = True
|
| 881 |
+
|
| 882 |
+
def get_ticks(self, minor=False):
|
| 883 |
+
"""
|
| 884 |
+
Return the ticks as a list of locations.
|
| 885 |
+
|
| 886 |
+
Parameters
|
| 887 |
+
----------
|
| 888 |
+
minor : boolean, default: False
|
| 889 |
+
if True return the minor ticks.
|
| 890 |
+
"""
|
| 891 |
+
if minor:
|
| 892 |
+
return self._long_axis().get_minorticklocs()
|
| 893 |
+
else:
|
| 894 |
+
return self._long_axis().get_majorticklocs()
|
| 895 |
+
|
| 896 |
+
def set_ticklabels(self, ticklabels, *, minor=False, **kwargs):
|
| 897 |
+
"""
|
| 898 |
+
[*Discouraged*] Set tick labels.
|
| 899 |
+
|
| 900 |
+
.. admonition:: Discouraged
|
| 901 |
+
|
| 902 |
+
The use of this method is discouraged, because of the dependency
|
| 903 |
+
on tick positions. In most cases, you'll want to use
|
| 904 |
+
``set_ticks(positions, labels=labels)`` instead.
|
| 905 |
+
|
| 906 |
+
If you are using this method, you should always fix the tick
|
| 907 |
+
positions before, e.g. by using `.Colorbar.set_ticks` or by
|
| 908 |
+
explicitly setting a `~.ticker.FixedLocator` on the long axis
|
| 909 |
+
of the colorbar. Otherwise, ticks are free to move and the
|
| 910 |
+
labels may end up in unexpected positions.
|
| 911 |
+
|
| 912 |
+
Parameters
|
| 913 |
+
----------
|
| 914 |
+
ticklabels : sequence of str or of `.Text`
|
| 915 |
+
Texts for labeling each tick location in the sequence set by
|
| 916 |
+
`.Colorbar.set_ticks`; the number of labels must match the number
|
| 917 |
+
of locations.
|
| 918 |
+
|
| 919 |
+
update_ticks : bool, default: True
|
| 920 |
+
This keyword argument is ignored and will be removed.
|
| 921 |
+
Deprecated
|
| 922 |
+
|
| 923 |
+
minor : bool
|
| 924 |
+
If True, set minor ticks instead of major ticks.
|
| 925 |
+
|
| 926 |
+
**kwargs
|
| 927 |
+
`.Text` properties for the labels.
|
| 928 |
+
"""
|
| 929 |
+
self._long_axis().set_ticklabels(ticklabels, minor=minor, **kwargs)
|
| 930 |
+
|
| 931 |
+
def minorticks_on(self):
|
| 932 |
+
"""
|
| 933 |
+
Turn on colorbar minor ticks.
|
| 934 |
+
"""
|
| 935 |
+
self.ax.minorticks_on()
|
| 936 |
+
self._short_axis().set_minor_locator(ticker.NullLocator())
|
| 937 |
+
|
| 938 |
+
def minorticks_off(self):
|
| 939 |
+
"""Turn the minor ticks of the colorbar off."""
|
| 940 |
+
self._minorlocator = ticker.NullLocator()
|
| 941 |
+
self._long_axis().set_minor_locator(self._minorlocator)
|
| 942 |
+
|
| 943 |
+
def set_label(self, label, *, loc=None, **kwargs):
|
| 944 |
+
"""
|
| 945 |
+
Add a label to the long axis of the colorbar.
|
| 946 |
+
|
| 947 |
+
Parameters
|
| 948 |
+
----------
|
| 949 |
+
label : str
|
| 950 |
+
The label text.
|
| 951 |
+
loc : str, optional
|
| 952 |
+
The location of the label.
|
| 953 |
+
|
| 954 |
+
- For horizontal orientation one of {'left', 'center', 'right'}
|
| 955 |
+
- For vertical orientation one of {'bottom', 'center', 'top'}
|
| 956 |
+
|
| 957 |
+
Defaults to :rc:`xaxis.labellocation` or :rc:`yaxis.labellocation`
|
| 958 |
+
depending on the orientation.
|
| 959 |
+
**kwargs
|
| 960 |
+
Keyword arguments are passed to `~.Axes.set_xlabel` /
|
| 961 |
+
`~.Axes.set_ylabel`.
|
| 962 |
+
Supported keywords are *labelpad* and `.Text` properties.
|
| 963 |
+
"""
|
| 964 |
+
if self.orientation == "vertical":
|
| 965 |
+
self.ax.set_ylabel(label, loc=loc, **kwargs)
|
| 966 |
+
else:
|
| 967 |
+
self.ax.set_xlabel(label, loc=loc, **kwargs)
|
| 968 |
+
self.stale = True
|
| 969 |
+
|
| 970 |
+
def set_alpha(self, alpha):
|
| 971 |
+
"""
|
| 972 |
+
Set the transparency between 0 (transparent) and 1 (opaque).
|
| 973 |
+
|
| 974 |
+
If an array is provided, *alpha* will be set to None to use the
|
| 975 |
+
transparency values associated with the colormap.
|
| 976 |
+
"""
|
| 977 |
+
self.alpha = None if isinstance(alpha, np.ndarray) else alpha
|
| 978 |
+
|
| 979 |
+
def _set_scale(self, scale, **kwargs):
|
| 980 |
+
"""
|
| 981 |
+
Set the colorbar long axis scale.
|
| 982 |
+
|
| 983 |
+
Parameters
|
| 984 |
+
----------
|
| 985 |
+
scale : {"linear", "log", "symlog", "logit", ...} or `.ScaleBase`
|
| 986 |
+
The axis scale type to apply.
|
| 987 |
+
|
| 988 |
+
**kwargs
|
| 989 |
+
Different keyword arguments are accepted, depending on the scale.
|
| 990 |
+
See the respective class keyword arguments:
|
| 991 |
+
|
| 992 |
+
- `matplotlib.scale.LinearScale`
|
| 993 |
+
- `matplotlib.scale.LogScale`
|
| 994 |
+
- `matplotlib.scale.SymmetricalLogScale`
|
| 995 |
+
- `matplotlib.scale.LogitScale`
|
| 996 |
+
- `matplotlib.scale.FuncScale`
|
| 997 |
+
- `matplotlib.scale.AsinhScale`
|
| 998 |
+
|
| 999 |
+
Notes
|
| 1000 |
+
-----
|
| 1001 |
+
By default, Matplotlib supports the above-mentioned scales.
|
| 1002 |
+
Additionally, custom scales may be registered using
|
| 1003 |
+
`matplotlib.scale.register_scale`. These scales can then also
|
| 1004 |
+
be used here.
|
| 1005 |
+
"""
|
| 1006 |
+
self._long_axis()._set_axes_scale(scale, **kwargs)
|
| 1007 |
+
|
| 1008 |
+
def remove(self):
|
| 1009 |
+
"""
|
| 1010 |
+
Remove this colorbar from the figure.
|
| 1011 |
+
|
| 1012 |
+
If the colorbar was created with ``use_gridspec=True`` the previous
|
| 1013 |
+
gridspec is restored.
|
| 1014 |
+
"""
|
| 1015 |
+
if hasattr(self.ax, '_colorbar_info'):
|
| 1016 |
+
parents = self.ax._colorbar_info['parents']
|
| 1017 |
+
for a in parents:
|
| 1018 |
+
if self.ax in a._colorbars:
|
| 1019 |
+
a._colorbars.remove(self.ax)
|
| 1020 |
+
|
| 1021 |
+
self.ax.remove()
|
| 1022 |
+
|
| 1023 |
+
self.mappable.callbacks.disconnect(self.mappable.colorbar_cid)
|
| 1024 |
+
self.mappable.colorbar = None
|
| 1025 |
+
self.mappable.colorbar_cid = None
|
| 1026 |
+
# Remove the extension callbacks
|
| 1027 |
+
self.ax.callbacks.disconnect(self._extend_cid1)
|
| 1028 |
+
self.ax.callbacks.disconnect(self._extend_cid2)
|
| 1029 |
+
|
| 1030 |
+
try:
|
| 1031 |
+
ax = self.mappable.axes
|
| 1032 |
+
except AttributeError:
|
| 1033 |
+
return
|
| 1034 |
+
try:
|
| 1035 |
+
subplotspec = self.ax.get_subplotspec().get_gridspec()._subplot_spec
|
| 1036 |
+
except AttributeError: # use_gridspec was False
|
| 1037 |
+
pos = ax.get_position(original=True)
|
| 1038 |
+
ax._set_position(pos)
|
| 1039 |
+
else: # use_gridspec was True
|
| 1040 |
+
ax.set_subplotspec(subplotspec)
|
| 1041 |
+
|
| 1042 |
+
def _process_values(self):
|
| 1043 |
+
"""
|
| 1044 |
+
Set `_boundaries` and `_values` based on the self.boundaries and
|
| 1045 |
+
self.values if not None, or based on the size of the colormap and
|
| 1046 |
+
the vmin/vmax of the norm.
|
| 1047 |
+
"""
|
| 1048 |
+
if self.values is not None:
|
| 1049 |
+
# set self._boundaries from the values...
|
| 1050 |
+
self._values = np.array(self.values)
|
| 1051 |
+
if self.boundaries is None:
|
| 1052 |
+
# bracket values by 1/2 dv:
|
| 1053 |
+
b = np.zeros(len(self.values) + 1)
|
| 1054 |
+
b[1:-1] = 0.5 * (self._values[:-1] + self._values[1:])
|
| 1055 |
+
b[0] = 2.0 * b[1] - b[2]
|
| 1056 |
+
b[-1] = 2.0 * b[-2] - b[-3]
|
| 1057 |
+
self._boundaries = b
|
| 1058 |
+
return
|
| 1059 |
+
self._boundaries = np.array(self.boundaries)
|
| 1060 |
+
return
|
| 1061 |
+
|
| 1062 |
+
# otherwise values are set from the boundaries
|
| 1063 |
+
if isinstance(self.norm, colors.BoundaryNorm):
|
| 1064 |
+
b = self.norm.boundaries
|
| 1065 |
+
elif isinstance(self.norm, colors.NoNorm):
|
| 1066 |
+
# NoNorm has N blocks, so N+1 boundaries, centered on integers:
|
| 1067 |
+
b = np.arange(self.cmap.N + 1) - .5
|
| 1068 |
+
elif self.boundaries is not None:
|
| 1069 |
+
b = self.boundaries
|
| 1070 |
+
else:
|
| 1071 |
+
# otherwise make the boundaries from the size of the cmap:
|
| 1072 |
+
N = self.cmap.N + 1
|
| 1073 |
+
b, _ = self._uniform_y(N)
|
| 1074 |
+
# add extra boundaries if needed:
|
| 1075 |
+
if self._extend_lower():
|
| 1076 |
+
b = np.hstack((b[0] - 1, b))
|
| 1077 |
+
if self._extend_upper():
|
| 1078 |
+
b = np.hstack((b, b[-1] + 1))
|
| 1079 |
+
|
| 1080 |
+
# transform from 0-1 to vmin-vmax:
|
| 1081 |
+
if self.mappable.get_array() is not None:
|
| 1082 |
+
self.mappable.autoscale_None()
|
| 1083 |
+
if not self.norm.scaled():
|
| 1084 |
+
# If we still aren't scaled after autoscaling, use 0, 1 as default
|
| 1085 |
+
self.norm.vmin = 0
|
| 1086 |
+
self.norm.vmax = 1
|
| 1087 |
+
self.norm.vmin, self.norm.vmax = mtransforms.nonsingular(
|
| 1088 |
+
self.norm.vmin, self.norm.vmax, expander=0.1)
|
| 1089 |
+
if (not isinstance(self.norm, colors.BoundaryNorm) and
|
| 1090 |
+
(self.boundaries is None)):
|
| 1091 |
+
b = self.norm.inverse(b)
|
| 1092 |
+
|
| 1093 |
+
self._boundaries = np.asarray(b, dtype=float)
|
| 1094 |
+
self._values = 0.5 * (self._boundaries[:-1] + self._boundaries[1:])
|
| 1095 |
+
if isinstance(self.norm, colors.NoNorm):
|
| 1096 |
+
self._values = (self._values + 0.00001).astype(np.int16)
|
| 1097 |
+
|
| 1098 |
+
def _mesh(self):
|
| 1099 |
+
"""
|
| 1100 |
+
Return the coordinate arrays for the colorbar pcolormesh/patches.
|
| 1101 |
+
|
| 1102 |
+
These are scaled between vmin and vmax, and already handle colorbar
|
| 1103 |
+
orientation.
|
| 1104 |
+
"""
|
| 1105 |
+
y, _ = self._proportional_y()
|
| 1106 |
+
# Use the vmin and vmax of the colorbar, which may not be the same
|
| 1107 |
+
# as the norm. There are situations where the colormap has a
|
| 1108 |
+
# narrower range than the colorbar and we want to accommodate the
|
| 1109 |
+
# extra contours.
|
| 1110 |
+
if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm))
|
| 1111 |
+
or self.boundaries is not None):
|
| 1112 |
+
# not using a norm.
|
| 1113 |
+
y = y * (self.vmax - self.vmin) + self.vmin
|
| 1114 |
+
else:
|
| 1115 |
+
# Update the norm values in a context manager as it is only
|
| 1116 |
+
# a temporary change and we don't want to propagate any signals
|
| 1117 |
+
# attached to the norm (callbacks.blocked).
|
| 1118 |
+
with self.norm.callbacks.blocked(), \
|
| 1119 |
+
cbook._setattr_cm(self.norm,
|
| 1120 |
+
vmin=self.vmin,
|
| 1121 |
+
vmax=self.vmax):
|
| 1122 |
+
y = self.norm.inverse(y)
|
| 1123 |
+
self._y = y
|
| 1124 |
+
X, Y = np.meshgrid([0., 1.], y)
|
| 1125 |
+
if self.orientation == 'vertical':
|
| 1126 |
+
return (X, Y)
|
| 1127 |
+
else:
|
| 1128 |
+
return (Y, X)
|
| 1129 |
+
|
| 1130 |
+
def _forward_boundaries(self, x):
|
| 1131 |
+
# map boundaries equally between 0 and 1...
|
| 1132 |
+
b = self._boundaries
|
| 1133 |
+
y = np.interp(x, b, np.linspace(0, 1, len(b)))
|
| 1134 |
+
# the following avoids ticks in the extends:
|
| 1135 |
+
eps = (b[-1] - b[0]) * 1e-6
|
| 1136 |
+
# map these _well_ out of bounds to keep any ticks out
|
| 1137 |
+
# of the extends region...
|
| 1138 |
+
y[x < b[0]-eps] = -1
|
| 1139 |
+
y[x > b[-1]+eps] = 2
|
| 1140 |
+
return y
|
| 1141 |
+
|
| 1142 |
+
def _inverse_boundaries(self, x):
|
| 1143 |
+
# invert the above...
|
| 1144 |
+
b = self._boundaries
|
| 1145 |
+
return np.interp(x, np.linspace(0, 1, len(b)), b)
|
| 1146 |
+
|
| 1147 |
+
def _reset_locator_formatter_scale(self):
|
| 1148 |
+
"""
|
| 1149 |
+
Reset the locator et al to defaults. Any user-hardcoded changes
|
| 1150 |
+
need to be re-entered if this gets called (either at init, or when
|
| 1151 |
+
the mappable normal gets changed: Colorbar.update_normal)
|
| 1152 |
+
"""
|
| 1153 |
+
self._process_values()
|
| 1154 |
+
self._locator = None
|
| 1155 |
+
self._minorlocator = None
|
| 1156 |
+
self._formatter = None
|
| 1157 |
+
self._minorformatter = None
|
| 1158 |
+
if (isinstance(self.mappable, contour.ContourSet) and
|
| 1159 |
+
isinstance(self.norm, colors.LogNorm)):
|
| 1160 |
+
# if contours have lognorm, give them a log scale...
|
| 1161 |
+
self._set_scale('log')
|
| 1162 |
+
elif (self.boundaries is not None or
|
| 1163 |
+
isinstance(self.norm, colors.BoundaryNorm)):
|
| 1164 |
+
if self.spacing == 'uniform':
|
| 1165 |
+
funcs = (self._forward_boundaries, self._inverse_boundaries)
|
| 1166 |
+
self._set_scale('function', functions=funcs)
|
| 1167 |
+
elif self.spacing == 'proportional':
|
| 1168 |
+
self._set_scale('linear')
|
| 1169 |
+
elif getattr(self.norm, '_scale', None):
|
| 1170 |
+
# use the norm's scale (if it exists and is not None):
|
| 1171 |
+
self._set_scale(self.norm._scale)
|
| 1172 |
+
elif type(self.norm) is colors.Normalize:
|
| 1173 |
+
# plain Normalize:
|
| 1174 |
+
self._set_scale('linear')
|
| 1175 |
+
else:
|
| 1176 |
+
# norm._scale is None or not an attr: derive the scale from
|
| 1177 |
+
# the Norm:
|
| 1178 |
+
funcs = (self.norm, self.norm.inverse)
|
| 1179 |
+
self._set_scale('function', functions=funcs)
|
| 1180 |
+
|
| 1181 |
+
def _locate(self, x):
|
| 1182 |
+
"""
|
| 1183 |
+
Given a set of color data values, return their
|
| 1184 |
+
corresponding colorbar data coordinates.
|
| 1185 |
+
"""
|
| 1186 |
+
if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)):
|
| 1187 |
+
b = self._boundaries
|
| 1188 |
+
xn = x
|
| 1189 |
+
else:
|
| 1190 |
+
# Do calculations using normalized coordinates so
|
| 1191 |
+
# as to make the interpolation more accurate.
|
| 1192 |
+
b = self.norm(self._boundaries, clip=False).filled()
|
| 1193 |
+
xn = self.norm(x, clip=False).filled()
|
| 1194 |
+
|
| 1195 |
+
bunique = b[self._inside]
|
| 1196 |
+
yunique = self._y
|
| 1197 |
+
|
| 1198 |
+
z = np.interp(xn, bunique, yunique)
|
| 1199 |
+
return z
|
| 1200 |
+
|
| 1201 |
+
# trivial helpers
|
| 1202 |
+
|
| 1203 |
+
def _uniform_y(self, N):
|
| 1204 |
+
"""
|
| 1205 |
+
Return colorbar data coordinates for *N* uniformly
|
| 1206 |
+
spaced boundaries, plus extension lengths if required.
|
| 1207 |
+
"""
|
| 1208 |
+
automin = automax = 1. / (N - 1.)
|
| 1209 |
+
extendlength = self._get_extension_lengths(self.extendfrac,
|
| 1210 |
+
automin, automax,
|
| 1211 |
+
default=0.05)
|
| 1212 |
+
y = np.linspace(0, 1, N)
|
| 1213 |
+
return y, extendlength
|
| 1214 |
+
|
| 1215 |
+
def _proportional_y(self):
|
| 1216 |
+
"""
|
| 1217 |
+
Return colorbar data coordinates for the boundaries of
|
| 1218 |
+
a proportional colorbar, plus extension lengths if required:
|
| 1219 |
+
"""
|
| 1220 |
+
if (isinstance(self.norm, colors.BoundaryNorm) or
|
| 1221 |
+
self.boundaries is not None):
|
| 1222 |
+
y = (self._boundaries - self._boundaries[self._inside][0])
|
| 1223 |
+
y = y / (self._boundaries[self._inside][-1] -
|
| 1224 |
+
self._boundaries[self._inside][0])
|
| 1225 |
+
# need yscaled the same as the axes scale to get
|
| 1226 |
+
# the extend lengths.
|
| 1227 |
+
if self.spacing == 'uniform':
|
| 1228 |
+
yscaled = self._forward_boundaries(self._boundaries)
|
| 1229 |
+
else:
|
| 1230 |
+
yscaled = y
|
| 1231 |
+
else:
|
| 1232 |
+
y = self.norm(self._boundaries.copy())
|
| 1233 |
+
y = np.ma.filled(y, np.nan)
|
| 1234 |
+
# the norm and the scale should be the same...
|
| 1235 |
+
yscaled = y
|
| 1236 |
+
y = y[self._inside]
|
| 1237 |
+
yscaled = yscaled[self._inside]
|
| 1238 |
+
# normalize from 0..1:
|
| 1239 |
+
norm = colors.Normalize(y[0], y[-1])
|
| 1240 |
+
y = np.ma.filled(norm(y), np.nan)
|
| 1241 |
+
norm = colors.Normalize(yscaled[0], yscaled[-1])
|
| 1242 |
+
yscaled = np.ma.filled(norm(yscaled), np.nan)
|
| 1243 |
+
# make the lower and upper extend lengths proportional to the lengths
|
| 1244 |
+
# of the first and last boundary spacing (if extendfrac='auto'):
|
| 1245 |
+
automin = yscaled[1] - yscaled[0]
|
| 1246 |
+
automax = yscaled[-1] - yscaled[-2]
|
| 1247 |
+
extendlength = [0, 0]
|
| 1248 |
+
if self._extend_lower() or self._extend_upper():
|
| 1249 |
+
extendlength = self._get_extension_lengths(
|
| 1250 |
+
self.extendfrac, automin, automax, default=0.05)
|
| 1251 |
+
return y, extendlength
|
| 1252 |
+
|
| 1253 |
+
def _get_extension_lengths(self, frac, automin, automax, default=0.05):
|
| 1254 |
+
"""
|
| 1255 |
+
Return the lengths of colorbar extensions.
|
| 1256 |
+
|
| 1257 |
+
This is a helper method for _uniform_y and _proportional_y.
|
| 1258 |
+
"""
|
| 1259 |
+
# Set the default value.
|
| 1260 |
+
extendlength = np.array([default, default])
|
| 1261 |
+
if isinstance(frac, str):
|
| 1262 |
+
_api.check_in_list(['auto'], extendfrac=frac.lower())
|
| 1263 |
+
# Use the provided values when 'auto' is required.
|
| 1264 |
+
extendlength[:] = [automin, automax]
|
| 1265 |
+
elif frac is not None:
|
| 1266 |
+
try:
|
| 1267 |
+
# Try to set min and max extension fractions directly.
|
| 1268 |
+
extendlength[:] = frac
|
| 1269 |
+
# If frac is a sequence containing None then NaN may
|
| 1270 |
+
# be encountered. This is an error.
|
| 1271 |
+
if np.isnan(extendlength).any():
|
| 1272 |
+
raise ValueError()
|
| 1273 |
+
except (TypeError, ValueError) as err:
|
| 1274 |
+
# Raise an error on encountering an invalid value for frac.
|
| 1275 |
+
raise ValueError('invalid value for extendfrac') from err
|
| 1276 |
+
return extendlength
|
| 1277 |
+
|
| 1278 |
+
def _extend_lower(self):
|
| 1279 |
+
"""Return whether the lower limit is open ended."""
|
| 1280 |
+
minmax = "max" if self._long_axis().get_inverted() else "min"
|
| 1281 |
+
return self.extend in ('both', minmax)
|
| 1282 |
+
|
| 1283 |
+
def _extend_upper(self):
|
| 1284 |
+
"""Return whether the upper limit is open ended."""
|
| 1285 |
+
minmax = "min" if self._long_axis().get_inverted() else "max"
|
| 1286 |
+
return self.extend in ('both', minmax)
|
| 1287 |
+
|
| 1288 |
+
def _long_axis(self):
|
| 1289 |
+
"""Return the long axis"""
|
| 1290 |
+
if self.orientation == 'vertical':
|
| 1291 |
+
return self.ax.yaxis
|
| 1292 |
+
return self.ax.xaxis
|
| 1293 |
+
|
| 1294 |
+
def _short_axis(self):
|
| 1295 |
+
"""Return the short axis"""
|
| 1296 |
+
if self.orientation == 'vertical':
|
| 1297 |
+
return self.ax.xaxis
|
| 1298 |
+
return self.ax.yaxis
|
| 1299 |
+
|
| 1300 |
+
def _get_view(self):
|
| 1301 |
+
# docstring inherited
|
| 1302 |
+
# An interactive view for a colorbar is the norm's vmin/vmax
|
| 1303 |
+
return self.norm.vmin, self.norm.vmax
|
| 1304 |
+
|
| 1305 |
+
def _set_view(self, view):
|
| 1306 |
+
# docstring inherited
|
| 1307 |
+
# An interactive view for a colorbar is the norm's vmin/vmax
|
| 1308 |
+
self.norm.vmin, self.norm.vmax = view
|
| 1309 |
+
|
| 1310 |
+
def _set_view_from_bbox(self, bbox, direction='in',
|
| 1311 |
+
mode=None, twinx=False, twiny=False):
|
| 1312 |
+
# docstring inherited
|
| 1313 |
+
# For colorbars, we use the zoom bbox to scale the norm's vmin/vmax
|
| 1314 |
+
new_xbound, new_ybound = self.ax._prepare_view_from_bbox(
|
| 1315 |
+
bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny)
|
| 1316 |
+
if self.orientation == 'horizontal':
|
| 1317 |
+
self.norm.vmin, self.norm.vmax = new_xbound
|
| 1318 |
+
elif self.orientation == 'vertical':
|
| 1319 |
+
self.norm.vmin, self.norm.vmax = new_ybound
|
| 1320 |
+
|
| 1321 |
+
def drag_pan(self, button, key, x, y):
|
| 1322 |
+
# docstring inherited
|
| 1323 |
+
points = self.ax._get_pan_points(button, key, x, y)
|
| 1324 |
+
if points is not None:
|
| 1325 |
+
if self.orientation == 'horizontal':
|
| 1326 |
+
self.norm.vmin, self.norm.vmax = points[:, 0]
|
| 1327 |
+
elif self.orientation == 'vertical':
|
| 1328 |
+
self.norm.vmin, self.norm.vmax = points[:, 1]
|
| 1329 |
+
|
| 1330 |
+
|
| 1331 |
+
ColorbarBase = Colorbar # Backcompat API
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
def _normalize_location_orientation(location, orientation):
|
| 1335 |
+
if location is None:
|
| 1336 |
+
location = _get_ticklocation_from_orientation(orientation)
|
| 1337 |
+
loc_settings = _api.check_getitem({
|
| 1338 |
+
"left": {"location": "left", "anchor": (1.0, 0.5),
|
| 1339 |
+
"panchor": (0.0, 0.5), "pad": 0.10},
|
| 1340 |
+
"right": {"location": "right", "anchor": (0.0, 0.5),
|
| 1341 |
+
"panchor": (1.0, 0.5), "pad": 0.05},
|
| 1342 |
+
"top": {"location": "top", "anchor": (0.5, 0.0),
|
| 1343 |
+
"panchor": (0.5, 1.0), "pad": 0.05},
|
| 1344 |
+
"bottom": {"location": "bottom", "anchor": (0.5, 1.0),
|
| 1345 |
+
"panchor": (0.5, 0.0), "pad": 0.15},
|
| 1346 |
+
}, location=location)
|
| 1347 |
+
loc_settings["orientation"] = _get_orientation_from_location(location)
|
| 1348 |
+
if orientation is not None and orientation != loc_settings["orientation"]:
|
| 1349 |
+
# Allow the user to pass both if they are consistent.
|
| 1350 |
+
raise TypeError("location and orientation are mutually exclusive")
|
| 1351 |
+
return loc_settings
|
| 1352 |
+
|
| 1353 |
+
|
| 1354 |
+
def _get_orientation_from_location(location):
|
| 1355 |
+
return _api.check_getitem(
|
| 1356 |
+
{None: None, "left": "vertical", "right": "vertical",
|
| 1357 |
+
"top": "horizontal", "bottom": "horizontal"}, location=location)
|
| 1358 |
+
|
| 1359 |
+
|
| 1360 |
+
def _get_ticklocation_from_orientation(orientation):
|
| 1361 |
+
return _api.check_getitem(
|
| 1362 |
+
{None: "right", "vertical": "right", "horizontal": "bottom"},
|
| 1363 |
+
orientation=orientation)
|
| 1364 |
+
|
| 1365 |
+
|
| 1366 |
+
@_docstring.interpd
|
| 1367 |
+
def make_axes(parents, location=None, orientation=None, fraction=0.15,
|
| 1368 |
+
shrink=1.0, aspect=20, **kwargs):
|
| 1369 |
+
"""
|
| 1370 |
+
Create an `~.axes.Axes` suitable for a colorbar.
|
| 1371 |
+
|
| 1372 |
+
The Axes is placed in the figure of the *parents* Axes, by resizing and
|
| 1373 |
+
repositioning *parents*.
|
| 1374 |
+
|
| 1375 |
+
Parameters
|
| 1376 |
+
----------
|
| 1377 |
+
parents : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of `~.axes.Axes`
|
| 1378 |
+
The Axes to use as parents for placing the colorbar.
|
| 1379 |
+
%(_make_axes_kw_doc)s
|
| 1380 |
+
|
| 1381 |
+
Returns
|
| 1382 |
+
-------
|
| 1383 |
+
cax : `~matplotlib.axes.Axes`
|
| 1384 |
+
The child Axes.
|
| 1385 |
+
kwargs : dict
|
| 1386 |
+
The reduced keyword dictionary to be passed when creating the colorbar
|
| 1387 |
+
instance.
|
| 1388 |
+
"""
|
| 1389 |
+
loc_settings = _normalize_location_orientation(location, orientation)
|
| 1390 |
+
# put appropriate values into the kwargs dict for passing back to
|
| 1391 |
+
# the Colorbar class
|
| 1392 |
+
kwargs['orientation'] = loc_settings['orientation']
|
| 1393 |
+
location = kwargs['ticklocation'] = loc_settings['location']
|
| 1394 |
+
|
| 1395 |
+
anchor = kwargs.pop('anchor', loc_settings['anchor'])
|
| 1396 |
+
panchor = kwargs.pop('panchor', loc_settings['panchor'])
|
| 1397 |
+
aspect0 = aspect
|
| 1398 |
+
# turn parents into a list if it is not already. Note we cannot
|
| 1399 |
+
# use .flatten or .ravel as these copy the references rather than
|
| 1400 |
+
# reuse them, leading to a memory leak
|
| 1401 |
+
if isinstance(parents, np.ndarray):
|
| 1402 |
+
parents = list(parents.flat)
|
| 1403 |
+
elif np.iterable(parents):
|
| 1404 |
+
parents = list(parents)
|
| 1405 |
+
else:
|
| 1406 |
+
parents = [parents]
|
| 1407 |
+
|
| 1408 |
+
fig = parents[0].get_figure()
|
| 1409 |
+
|
| 1410 |
+
pad0 = 0.05 if fig.get_constrained_layout() else loc_settings['pad']
|
| 1411 |
+
pad = kwargs.pop('pad', pad0)
|
| 1412 |
+
|
| 1413 |
+
if not all(fig is ax.get_figure() for ax in parents):
|
| 1414 |
+
raise ValueError('Unable to create a colorbar Axes as not all '
|
| 1415 |
+
'parents share the same figure.')
|
| 1416 |
+
|
| 1417 |
+
# take a bounding box around all of the given Axes
|
| 1418 |
+
parents_bbox = mtransforms.Bbox.union(
|
| 1419 |
+
[ax.get_position(original=True).frozen() for ax in parents])
|
| 1420 |
+
|
| 1421 |
+
pb = parents_bbox
|
| 1422 |
+
if location in ('left', 'right'):
|
| 1423 |
+
if location == 'left':
|
| 1424 |
+
pbcb, _, pb1 = pb.splitx(fraction, fraction + pad)
|
| 1425 |
+
else:
|
| 1426 |
+
pb1, _, pbcb = pb.splitx(1 - fraction - pad, 1 - fraction)
|
| 1427 |
+
pbcb = pbcb.shrunk(1.0, shrink).anchored(anchor, pbcb)
|
| 1428 |
+
else:
|
| 1429 |
+
if location == 'bottom':
|
| 1430 |
+
pbcb, _, pb1 = pb.splity(fraction, fraction + pad)
|
| 1431 |
+
else:
|
| 1432 |
+
pb1, _, pbcb = pb.splity(1 - fraction - pad, 1 - fraction)
|
| 1433 |
+
pbcb = pbcb.shrunk(shrink, 1.0).anchored(anchor, pbcb)
|
| 1434 |
+
|
| 1435 |
+
# define the aspect ratio in terms of y's per x rather than x's per y
|
| 1436 |
+
aspect = 1.0 / aspect
|
| 1437 |
+
|
| 1438 |
+
# define a transform which takes us from old axes coordinates to
|
| 1439 |
+
# new axes coordinates
|
| 1440 |
+
shrinking_trans = mtransforms.BboxTransform(parents_bbox, pb1)
|
| 1441 |
+
|
| 1442 |
+
# transform each of the Axes in parents using the new transform
|
| 1443 |
+
for ax in parents:
|
| 1444 |
+
new_posn = shrinking_trans.transform(ax.get_position(original=True))
|
| 1445 |
+
new_posn = mtransforms.Bbox(new_posn)
|
| 1446 |
+
ax._set_position(new_posn)
|
| 1447 |
+
if panchor is not False:
|
| 1448 |
+
ax.set_anchor(panchor)
|
| 1449 |
+
|
| 1450 |
+
cax = fig.add_axes(pbcb, label="<colorbar>")
|
| 1451 |
+
for a in parents:
|
| 1452 |
+
# tell the parent it has a colorbar
|
| 1453 |
+
a._colorbars += [cax]
|
| 1454 |
+
cax._colorbar_info = dict(
|
| 1455 |
+
parents=parents,
|
| 1456 |
+
location=location,
|
| 1457 |
+
shrink=shrink,
|
| 1458 |
+
anchor=anchor,
|
| 1459 |
+
panchor=panchor,
|
| 1460 |
+
fraction=fraction,
|
| 1461 |
+
aspect=aspect0,
|
| 1462 |
+
pad=pad)
|
| 1463 |
+
# and we need to set the aspect ratio by hand...
|
| 1464 |
+
cax.set_anchor(anchor)
|
| 1465 |
+
cax.set_box_aspect(aspect)
|
| 1466 |
+
cax.set_aspect('auto')
|
| 1467 |
+
|
| 1468 |
+
return cax, kwargs
|
| 1469 |
+
|
| 1470 |
+
|
| 1471 |
+
@_docstring.interpd
|
| 1472 |
+
def make_axes_gridspec(parent, *, location=None, orientation=None,
|
| 1473 |
+
fraction=0.15, shrink=1.0, aspect=20, **kwargs):
|
| 1474 |
+
"""
|
| 1475 |
+
Create an `~.axes.Axes` suitable for a colorbar.
|
| 1476 |
+
|
| 1477 |
+
The Axes is placed in the figure of the *parent* Axes, by resizing and
|
| 1478 |
+
repositioning *parent*.
|
| 1479 |
+
|
| 1480 |
+
This function is similar to `.make_axes` and mostly compatible with it.
|
| 1481 |
+
Primary differences are
|
| 1482 |
+
|
| 1483 |
+
- `.make_axes_gridspec` requires the *parent* to have a subplotspec.
|
| 1484 |
+
- `.make_axes` positions the Axes in figure coordinates;
|
| 1485 |
+
`.make_axes_gridspec` positions it using a subplotspec.
|
| 1486 |
+
- `.make_axes` updates the position of the parent. `.make_axes_gridspec`
|
| 1487 |
+
replaces the parent gridspec with a new one.
|
| 1488 |
+
|
| 1489 |
+
Parameters
|
| 1490 |
+
----------
|
| 1491 |
+
parent : `~matplotlib.axes.Axes`
|
| 1492 |
+
The Axes to use as parent for placing the colorbar.
|
| 1493 |
+
%(_make_axes_kw_doc)s
|
| 1494 |
+
|
| 1495 |
+
Returns
|
| 1496 |
+
-------
|
| 1497 |
+
cax : `~matplotlib.axes.Axes`
|
| 1498 |
+
The child Axes.
|
| 1499 |
+
kwargs : dict
|
| 1500 |
+
The reduced keyword dictionary to be passed when creating the colorbar
|
| 1501 |
+
instance.
|
| 1502 |
+
"""
|
| 1503 |
+
|
| 1504 |
+
loc_settings = _normalize_location_orientation(location, orientation)
|
| 1505 |
+
kwargs['orientation'] = loc_settings['orientation']
|
| 1506 |
+
location = kwargs['ticklocation'] = loc_settings['location']
|
| 1507 |
+
|
| 1508 |
+
aspect0 = aspect
|
| 1509 |
+
anchor = kwargs.pop('anchor', loc_settings['anchor'])
|
| 1510 |
+
panchor = kwargs.pop('panchor', loc_settings['panchor'])
|
| 1511 |
+
pad = kwargs.pop('pad', loc_settings["pad"])
|
| 1512 |
+
wh_space = 2 * pad / (1 - pad)
|
| 1513 |
+
|
| 1514 |
+
if location in ('left', 'right'):
|
| 1515 |
+
gs = parent.get_subplotspec().subgridspec(
|
| 1516 |
+
3, 2, wspace=wh_space, hspace=0,
|
| 1517 |
+
height_ratios=[(1-anchor[1])*(1-shrink), shrink, anchor[1]*(1-shrink)])
|
| 1518 |
+
if location == 'left':
|
| 1519 |
+
gs.set_width_ratios([fraction, 1 - fraction - pad])
|
| 1520 |
+
ss_main = gs[:, 1]
|
| 1521 |
+
ss_cb = gs[1, 0]
|
| 1522 |
+
else:
|
| 1523 |
+
gs.set_width_ratios([1 - fraction - pad, fraction])
|
| 1524 |
+
ss_main = gs[:, 0]
|
| 1525 |
+
ss_cb = gs[1, 1]
|
| 1526 |
+
else:
|
| 1527 |
+
gs = parent.get_subplotspec().subgridspec(
|
| 1528 |
+
2, 3, hspace=wh_space, wspace=0,
|
| 1529 |
+
width_ratios=[anchor[0]*(1-shrink), shrink, (1-anchor[0])*(1-shrink)])
|
| 1530 |
+
if location == 'top':
|
| 1531 |
+
gs.set_height_ratios([fraction, 1 - fraction - pad])
|
| 1532 |
+
ss_main = gs[1, :]
|
| 1533 |
+
ss_cb = gs[0, 1]
|
| 1534 |
+
else:
|
| 1535 |
+
gs.set_height_ratios([1 - fraction - pad, fraction])
|
| 1536 |
+
ss_main = gs[0, :]
|
| 1537 |
+
ss_cb = gs[1, 1]
|
| 1538 |
+
aspect = 1 / aspect
|
| 1539 |
+
|
| 1540 |
+
parent.set_subplotspec(ss_main)
|
| 1541 |
+
if panchor is not False:
|
| 1542 |
+
parent.set_anchor(panchor)
|
| 1543 |
+
|
| 1544 |
+
fig = parent.get_figure()
|
| 1545 |
+
cax = fig.add_subplot(ss_cb, label="<colorbar>")
|
| 1546 |
+
cax.set_anchor(anchor)
|
| 1547 |
+
cax.set_box_aspect(aspect)
|
| 1548 |
+
cax.set_aspect('auto')
|
| 1549 |
+
cax._colorbar_info = dict(
|
| 1550 |
+
location=location,
|
| 1551 |
+
parents=[parent],
|
| 1552 |
+
shrink=shrink,
|
| 1553 |
+
anchor=anchor,
|
| 1554 |
+
panchor=panchor,
|
| 1555 |
+
fraction=fraction,
|
| 1556 |
+
aspect=aspect0,
|
| 1557 |
+
pad=pad)
|
| 1558 |
+
|
| 1559 |
+
return cax, kwargs
|
parrot/lib/python3.10/site-packages/matplotlib/colorbar.pyi
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import matplotlib.spines as mspines
|
| 2 |
+
from matplotlib import cm, collections, colors, contour
|
| 3 |
+
from matplotlib.axes import Axes
|
| 4 |
+
from matplotlib.backend_bases import RendererBase
|
| 5 |
+
from matplotlib.patches import Patch
|
| 6 |
+
from matplotlib.ticker import Locator, Formatter
|
| 7 |
+
from matplotlib.transforms import Bbox
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from numpy.typing import ArrayLike
|
| 11 |
+
from collections.abc import Sequence
|
| 12 |
+
from typing import Any, Literal, overload
|
| 13 |
+
from .typing import ColorType
|
| 14 |
+
|
| 15 |
+
class _ColorbarSpine(mspines.Spines):
|
| 16 |
+
def __init__(self, axes: Axes): ...
|
| 17 |
+
def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox:...
|
| 18 |
+
def set_xy(self, xy: ArrayLike) -> None: ...
|
| 19 |
+
def draw(self, renderer: RendererBase | None) -> None:...
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Colorbar:
|
| 23 |
+
n_rasterize: int
|
| 24 |
+
mappable: cm.ScalarMappable
|
| 25 |
+
ax: Axes
|
| 26 |
+
alpha: float | None
|
| 27 |
+
cmap: colors.Colormap
|
| 28 |
+
norm: colors.Normalize
|
| 29 |
+
values: Sequence[float] | None
|
| 30 |
+
boundaries: Sequence[float] | None
|
| 31 |
+
extend: Literal["neither", "both", "min", "max"]
|
| 32 |
+
spacing: Literal["uniform", "proportional"]
|
| 33 |
+
orientation: Literal["vertical", "horizontal"]
|
| 34 |
+
drawedges: bool
|
| 35 |
+
extendfrac: Literal["auto"] | float | Sequence[float] | None
|
| 36 |
+
extendrect: bool
|
| 37 |
+
solids: None | collections.QuadMesh
|
| 38 |
+
solids_patches: list[Patch]
|
| 39 |
+
lines: list[collections.LineCollection]
|
| 40 |
+
outline: _ColorbarSpine
|
| 41 |
+
dividers: collections.LineCollection
|
| 42 |
+
ticklocation: Literal["left", "right", "top", "bottom"]
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
ax: Axes,
|
| 46 |
+
mappable: cm.ScalarMappable | None = ...,
|
| 47 |
+
*,
|
| 48 |
+
cmap: str | colors.Colormap | None = ...,
|
| 49 |
+
norm: colors.Normalize | None = ...,
|
| 50 |
+
alpha: float | None = ...,
|
| 51 |
+
values: Sequence[float] | None = ...,
|
| 52 |
+
boundaries: Sequence[float] | None = ...,
|
| 53 |
+
orientation: Literal["vertical", "horizontal"] | None = ...,
|
| 54 |
+
ticklocation: Literal["auto", "left", "right", "top", "bottom"] = ...,
|
| 55 |
+
extend: Literal["neither", "both", "min", "max"] | None = ...,
|
| 56 |
+
spacing: Literal["uniform", "proportional"] = ...,
|
| 57 |
+
ticks: Sequence[float] | Locator | None = ...,
|
| 58 |
+
format: str | Formatter | None = ...,
|
| 59 |
+
drawedges: bool = ...,
|
| 60 |
+
extendfrac: Literal["auto"] | float | Sequence[float] | None = ...,
|
| 61 |
+
extendrect: bool = ...,
|
| 62 |
+
label: str = ...,
|
| 63 |
+
location: Literal["left", "right", "top", "bottom"] | None = ...
|
| 64 |
+
) -> None: ...
|
| 65 |
+
@property
|
| 66 |
+
def locator(self) -> Locator: ...
|
| 67 |
+
@locator.setter
|
| 68 |
+
def locator(self, loc: Locator) -> None: ...
|
| 69 |
+
@property
|
| 70 |
+
def minorlocator(self) -> Locator: ...
|
| 71 |
+
@minorlocator.setter
|
| 72 |
+
def minorlocator(self, loc: Locator) -> None: ...
|
| 73 |
+
@property
|
| 74 |
+
def formatter(self) -> Formatter: ...
|
| 75 |
+
@formatter.setter
|
| 76 |
+
def formatter(self, fmt: Formatter) -> None: ...
|
| 77 |
+
@property
|
| 78 |
+
def minorformatter(self) -> Formatter: ...
|
| 79 |
+
@minorformatter.setter
|
| 80 |
+
def minorformatter(self, fmt: Formatter) -> None: ...
|
| 81 |
+
def update_normal(self, mappable: cm.ScalarMappable) -> None: ...
|
| 82 |
+
@overload
|
| 83 |
+
def add_lines(self, CS: contour.ContourSet, erase: bool = ...) -> None: ...
|
| 84 |
+
@overload
|
| 85 |
+
def add_lines(
|
| 86 |
+
self,
|
| 87 |
+
levels: ArrayLike,
|
| 88 |
+
colors: ColorType | Sequence[ColorType],
|
| 89 |
+
linewidths: float | ArrayLike,
|
| 90 |
+
erase: bool = ...,
|
| 91 |
+
) -> None: ...
|
| 92 |
+
def update_ticks(self) -> None: ...
|
| 93 |
+
def set_ticks(
|
| 94 |
+
self,
|
| 95 |
+
ticks: Sequence[float] | Locator,
|
| 96 |
+
*,
|
| 97 |
+
labels: Sequence[str] | None = ...,
|
| 98 |
+
minor: bool = ...,
|
| 99 |
+
**kwargs
|
| 100 |
+
) -> None: ...
|
| 101 |
+
def get_ticks(self, minor: bool = ...) -> np.ndarray: ...
|
| 102 |
+
def set_ticklabels(
|
| 103 |
+
self,
|
| 104 |
+
ticklabels: Sequence[str],
|
| 105 |
+
*,
|
| 106 |
+
minor: bool = ...,
|
| 107 |
+
**kwargs
|
| 108 |
+
) -> None: ...
|
| 109 |
+
def minorticks_on(self) -> None: ...
|
| 110 |
+
def minorticks_off(self) -> None: ...
|
| 111 |
+
def set_label(self, label: str, *, loc: str | None = ..., **kwargs) -> None: ...
|
| 112 |
+
def set_alpha(self, alpha: float | np.ndarray) -> None: ...
|
| 113 |
+
def remove(self) -> None: ...
|
| 114 |
+
def drag_pan(self, button: Any, key: Any, x: float, y: float) -> None: ...
|
| 115 |
+
|
| 116 |
+
ColorbarBase = Colorbar
|
| 117 |
+
|
| 118 |
+
def make_axes(
|
| 119 |
+
parents: Axes | list[Axes] | np.ndarray,
|
| 120 |
+
location: Literal["left", "right", "top", "bottom"] | None = ...,
|
| 121 |
+
orientation: Literal["vertical", "horizontal"] | None = ...,
|
| 122 |
+
fraction: float = ...,
|
| 123 |
+
shrink: float = ...,
|
| 124 |
+
aspect: float = ...,
|
| 125 |
+
**kwargs
|
| 126 |
+
) -> tuple[Axes, dict[str, Any]]: ...
|
| 127 |
+
def make_axes_gridspec(
|
| 128 |
+
parent: Axes,
|
| 129 |
+
*,
|
| 130 |
+
location: Literal["left", "right", "top", "bottom"] | None = ...,
|
| 131 |
+
orientation: Literal["vertical", "horizontal"] | None = ...,
|
| 132 |
+
fraction: float = ...,
|
| 133 |
+
shrink: float = ...,
|
| 134 |
+
aspect: float = ...,
|
| 135 |
+
**kwargs
|
| 136 |
+
) -> tuple[Axes, dict[str, Any]]: ...
|
parrot/lib/python3.10/site-packages/matplotlib/colors.pyi
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
| 2 |
+
from matplotlib import cbook, scale
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
from typing import Any, Literal, overload
|
| 6 |
+
from .typing import ColorType
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from numpy.typing import ArrayLike
|
| 10 |
+
|
| 11 |
+
# Explicitly export colors dictionaries which are imported in the impl
|
| 12 |
+
BASE_COLORS: dict[str, ColorType]
|
| 13 |
+
CSS4_COLORS: dict[str, ColorType]
|
| 14 |
+
TABLEAU_COLORS: dict[str, ColorType]
|
| 15 |
+
XKCD_COLORS: dict[str, ColorType]
|
| 16 |
+
|
| 17 |
+
class _ColorMapping(dict[str, ColorType]):
|
| 18 |
+
cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]]
|
| 19 |
+
def __init__(self, mapping) -> None: ...
|
| 20 |
+
def __setitem__(self, key, value) -> None: ...
|
| 21 |
+
def __delitem__(self, key) -> None: ...
|
| 22 |
+
|
| 23 |
+
def get_named_colors_mapping() -> _ColorMapping: ...
|
| 24 |
+
|
| 25 |
+
class ColorSequenceRegistry(Mapping):
|
| 26 |
+
def __init__(self) -> None: ...
|
| 27 |
+
def __getitem__(self, item: str) -> list[ColorType]: ...
|
| 28 |
+
def __iter__(self) -> Iterator[str]: ...
|
| 29 |
+
def __len__(self) -> int: ...
|
| 30 |
+
def register(self, name: str, color_list: Iterable[ColorType]) -> None: ...
|
| 31 |
+
def unregister(self, name: str) -> None: ...
|
| 32 |
+
|
| 33 |
+
_color_sequences: ColorSequenceRegistry = ...
|
| 34 |
+
|
| 35 |
+
def is_color_like(c: Any) -> bool: ...
|
| 36 |
+
def same_color(c1: ColorType, c2: ColorType) -> bool: ...
|
| 37 |
+
def to_rgba(
|
| 38 |
+
c: ColorType, alpha: float | None = ...
|
| 39 |
+
) -> tuple[float, float, float, float]: ...
|
| 40 |
+
def to_rgba_array(
|
| 41 |
+
c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ...
|
| 42 |
+
) -> np.ndarray: ...
|
| 43 |
+
def to_rgb(c: ColorType) -> tuple[float, float, float]: ...
|
| 44 |
+
def to_hex(c: ColorType, keep_alpha: bool = ...) -> str: ...
|
| 45 |
+
|
| 46 |
+
cnames: dict[str, ColorType]
|
| 47 |
+
hexColorPattern: re.Pattern
|
| 48 |
+
rgb2hex = to_hex
|
| 49 |
+
hex2color = to_rgb
|
| 50 |
+
|
| 51 |
+
class ColorConverter:
|
| 52 |
+
colors: _ColorMapping
|
| 53 |
+
cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]]
|
| 54 |
+
@staticmethod
|
| 55 |
+
def to_rgb(c: ColorType) -> tuple[float, float, float]: ...
|
| 56 |
+
@staticmethod
|
| 57 |
+
def to_rgba(
|
| 58 |
+
c: ColorType, alpha: float | None = ...
|
| 59 |
+
) -> tuple[float, float, float, float]: ...
|
| 60 |
+
@staticmethod
|
| 61 |
+
def to_rgba_array(
|
| 62 |
+
c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ...
|
| 63 |
+
) -> np.ndarray: ...
|
| 64 |
+
|
| 65 |
+
colorConverter: ColorConverter
|
| 66 |
+
|
| 67 |
+
class Colormap:
|
| 68 |
+
name: str
|
| 69 |
+
N: int
|
| 70 |
+
colorbar_extend: bool
|
| 71 |
+
def __init__(self, name: str, N: int = ...) -> None: ...
|
| 72 |
+
@overload
|
| 73 |
+
def __call__(
|
| 74 |
+
self, X: Sequence[float] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ...
|
| 75 |
+
) -> np.ndarray: ...
|
| 76 |
+
@overload
|
| 77 |
+
def __call__(
|
| 78 |
+
self, X: float, alpha: float | None = ..., bytes: bool = ...
|
| 79 |
+
) -> tuple[float, float, float, float]: ...
|
| 80 |
+
@overload
|
| 81 |
+
def __call__(
|
| 82 |
+
self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ...
|
| 83 |
+
) -> tuple[float, float, float, float] | np.ndarray: ...
|
| 84 |
+
def __copy__(self) -> Colormap: ...
|
| 85 |
+
def __eq__(self, other: object) -> bool: ...
|
| 86 |
+
def get_bad(self) -> np.ndarray: ...
|
| 87 |
+
def set_bad(self, color: ColorType = ..., alpha: float | None = ...) -> None: ...
|
| 88 |
+
def get_under(self) -> np.ndarray: ...
|
| 89 |
+
def set_under(self, color: ColorType = ..., alpha: float | None = ...) -> None: ...
|
| 90 |
+
def get_over(self) -> np.ndarray: ...
|
| 91 |
+
def set_over(self, color: ColorType = ..., alpha: float | None = ...) -> None: ...
|
| 92 |
+
def set_extremes(
|
| 93 |
+
self,
|
| 94 |
+
*,
|
| 95 |
+
bad: ColorType | None = ...,
|
| 96 |
+
under: ColorType | None = ...,
|
| 97 |
+
over: ColorType | None = ...
|
| 98 |
+
) -> None: ...
|
| 99 |
+
def with_extremes(
|
| 100 |
+
self,
|
| 101 |
+
*,
|
| 102 |
+
bad: ColorType | None = ...,
|
| 103 |
+
under: ColorType | None = ...,
|
| 104 |
+
over: ColorType | None = ...
|
| 105 |
+
) -> Colormap: ...
|
| 106 |
+
def is_gray(self) -> bool: ...
|
| 107 |
+
def resampled(self, lutsize: int) -> Colormap: ...
|
| 108 |
+
def reversed(self, name: str | None = ...) -> Colormap: ...
|
| 109 |
+
def _repr_html_(self) -> str: ...
|
| 110 |
+
def _repr_png_(self) -> bytes: ...
|
| 111 |
+
def copy(self) -> Colormap: ...
|
| 112 |
+
|
| 113 |
+
class LinearSegmentedColormap(Colormap):
|
| 114 |
+
monochrome: bool
|
| 115 |
+
def __init__(
|
| 116 |
+
self,
|
| 117 |
+
name: str,
|
| 118 |
+
segmentdata: dict[
|
| 119 |
+
Literal["red", "green", "blue", "alpha"], Sequence[tuple[float, ...]]
|
| 120 |
+
],
|
| 121 |
+
N: int = ...,
|
| 122 |
+
gamma: float = ...,
|
| 123 |
+
) -> None: ...
|
| 124 |
+
def set_gamma(self, gamma: float) -> None: ...
|
| 125 |
+
@staticmethod
|
| 126 |
+
def from_list(
|
| 127 |
+
name: str, colors: ArrayLike | Sequence[tuple[float, ColorType]], N: int = ..., gamma: float = ...
|
| 128 |
+
) -> LinearSegmentedColormap: ...
|
| 129 |
+
def resampled(self, lutsize: int) -> LinearSegmentedColormap: ...
|
| 130 |
+
def reversed(self, name: str | None = ...) -> LinearSegmentedColormap: ...
|
| 131 |
+
|
| 132 |
+
class ListedColormap(Colormap):
|
| 133 |
+
monochrome: bool
|
| 134 |
+
colors: ArrayLike | ColorType
|
| 135 |
+
def __init__(
|
| 136 |
+
self, colors: ArrayLike | ColorType, name: str = ..., N: int | None = ...
|
| 137 |
+
) -> None: ...
|
| 138 |
+
def resampled(self, lutsize: int) -> ListedColormap: ...
|
| 139 |
+
def reversed(self, name: str | None = ...) -> ListedColormap: ...
|
| 140 |
+
|
| 141 |
+
class Normalize:
|
| 142 |
+
callbacks: cbook.CallbackRegistry
|
| 143 |
+
def __init__(
|
| 144 |
+
self, vmin: float | None = ..., vmax: float | None = ..., clip: bool = ...
|
| 145 |
+
) -> None: ...
|
| 146 |
+
@property
|
| 147 |
+
def vmin(self) -> float | None: ...
|
| 148 |
+
@vmin.setter
|
| 149 |
+
def vmin(self, value: float | None) -> None: ...
|
| 150 |
+
@property
|
| 151 |
+
def vmax(self) -> float | None: ...
|
| 152 |
+
@vmax.setter
|
| 153 |
+
def vmax(self, value: float | None) -> None: ...
|
| 154 |
+
@property
|
| 155 |
+
def clip(self) -> bool: ...
|
| 156 |
+
@clip.setter
|
| 157 |
+
def clip(self, value: bool) -> None: ...
|
| 158 |
+
@staticmethod
|
| 159 |
+
def process_value(value: ArrayLike) -> tuple[np.ma.MaskedArray, bool]: ...
|
| 160 |
+
@overload
|
| 161 |
+
def __call__(self, value: float, clip: bool | None = ...) -> float: ...
|
| 162 |
+
@overload
|
| 163 |
+
def __call__(self, value: np.ndarray, clip: bool | None = ...) -> np.ma.MaskedArray: ...
|
| 164 |
+
@overload
|
| 165 |
+
def __call__(self, value: ArrayLike, clip: bool | None = ...) -> ArrayLike: ...
|
| 166 |
+
@overload
|
| 167 |
+
def inverse(self, value: float) -> float: ...
|
| 168 |
+
@overload
|
| 169 |
+
def inverse(self, value: np.ndarray) -> np.ma.MaskedArray: ...
|
| 170 |
+
@overload
|
| 171 |
+
def inverse(self, value: ArrayLike) -> ArrayLike: ...
|
| 172 |
+
def autoscale(self, A: ArrayLike) -> None: ...
|
| 173 |
+
def autoscale_None(self, A: ArrayLike) -> None: ...
|
| 174 |
+
def scaled(self) -> bool: ...
|
| 175 |
+
|
| 176 |
+
class TwoSlopeNorm(Normalize):
|
| 177 |
+
def __init__(
|
| 178 |
+
self, vcenter: float, vmin: float | None = ..., vmax: float | None = ...
|
| 179 |
+
) -> None: ...
|
| 180 |
+
@property
|
| 181 |
+
def vcenter(self) -> float: ...
|
| 182 |
+
@vcenter.setter
|
| 183 |
+
def vcenter(self, value: float) -> None: ...
|
| 184 |
+
def autoscale_None(self, A: ArrayLike) -> None: ...
|
| 185 |
+
|
| 186 |
+
class CenteredNorm(Normalize):
|
| 187 |
+
def __init__(
|
| 188 |
+
self, vcenter: float = ..., halfrange: float | None = ..., clip: bool = ...
|
| 189 |
+
) -> None: ...
|
| 190 |
+
@property
|
| 191 |
+
def vcenter(self) -> float: ...
|
| 192 |
+
@vcenter.setter
|
| 193 |
+
def vcenter(self, vcenter: float) -> None: ...
|
| 194 |
+
@property
|
| 195 |
+
def halfrange(self) -> float: ...
|
| 196 |
+
@halfrange.setter
|
| 197 |
+
def halfrange(self, halfrange: float) -> None: ...
|
| 198 |
+
|
| 199 |
+
@overload
|
| 200 |
+
def make_norm_from_scale(
|
| 201 |
+
scale_cls: type[scale.ScaleBase],
|
| 202 |
+
base_norm_cls: type[Normalize],
|
| 203 |
+
*,
|
| 204 |
+
init: Callable | None = ...
|
| 205 |
+
) -> type[Normalize]: ...
|
| 206 |
+
@overload
|
| 207 |
+
def make_norm_from_scale(
|
| 208 |
+
scale_cls: type[scale.ScaleBase],
|
| 209 |
+
base_norm_cls: None = ...,
|
| 210 |
+
*,
|
| 211 |
+
init: Callable | None = ...
|
| 212 |
+
) -> Callable[[type[Normalize]], type[Normalize]]: ...
|
| 213 |
+
|
| 214 |
+
class FuncNorm(Normalize):
|
| 215 |
+
def __init__(
|
| 216 |
+
self,
|
| 217 |
+
functions: tuple[Callable, Callable],
|
| 218 |
+
vmin: float | None = ...,
|
| 219 |
+
vmax: float | None = ...,
|
| 220 |
+
clip: bool = ...,
|
| 221 |
+
) -> None: ...
|
| 222 |
+
class LogNorm(Normalize): ...
|
| 223 |
+
|
| 224 |
+
class SymLogNorm(Normalize):
|
| 225 |
+
def __init__(
|
| 226 |
+
self,
|
| 227 |
+
linthresh: float,
|
| 228 |
+
linscale: float = ...,
|
| 229 |
+
vmin: float | None = ...,
|
| 230 |
+
vmax: float | None = ...,
|
| 231 |
+
clip: bool = ...,
|
| 232 |
+
*,
|
| 233 |
+
base: float = ...,
|
| 234 |
+
) -> None: ...
|
| 235 |
+
@property
|
| 236 |
+
def linthresh(self) -> float: ...
|
| 237 |
+
@linthresh.setter
|
| 238 |
+
def linthresh(self, value: float) -> None: ...
|
| 239 |
+
|
| 240 |
+
class AsinhNorm(Normalize):
|
| 241 |
+
def __init__(
|
| 242 |
+
self,
|
| 243 |
+
linear_width: float = ...,
|
| 244 |
+
vmin: float | None = ...,
|
| 245 |
+
vmax: float | None = ...,
|
| 246 |
+
clip: bool = ...,
|
| 247 |
+
) -> None: ...
|
| 248 |
+
@property
|
| 249 |
+
def linear_width(self) -> float: ...
|
| 250 |
+
@linear_width.setter
|
| 251 |
+
def linear_width(self, value: float) -> None: ...
|
| 252 |
+
|
| 253 |
+
class PowerNorm(Normalize):
|
| 254 |
+
gamma: float
|
| 255 |
+
def __init__(
|
| 256 |
+
self,
|
| 257 |
+
gamma: float,
|
| 258 |
+
vmin: float | None = ...,
|
| 259 |
+
vmax: float | None = ...,
|
| 260 |
+
clip: bool = ...,
|
| 261 |
+
) -> None: ...
|
| 262 |
+
|
| 263 |
+
class BoundaryNorm(Normalize):
|
| 264 |
+
boundaries: np.ndarray
|
| 265 |
+
N: int
|
| 266 |
+
Ncmap: int
|
| 267 |
+
extend: Literal["neither", "both", "min", "max"]
|
| 268 |
+
def __init__(
|
| 269 |
+
self,
|
| 270 |
+
boundaries: ArrayLike,
|
| 271 |
+
ncolors: int,
|
| 272 |
+
clip: bool = ...,
|
| 273 |
+
*,
|
| 274 |
+
extend: Literal["neither", "both", "min", "max"] = ...
|
| 275 |
+
) -> None: ...
|
| 276 |
+
|
| 277 |
+
class NoNorm(Normalize): ...
|
| 278 |
+
|
| 279 |
+
def rgb_to_hsv(arr: ArrayLike) -> np.ndarray: ...
|
| 280 |
+
def hsv_to_rgb(hsv: ArrayLike) -> np.ndarray: ...
|
| 281 |
+
|
| 282 |
+
class LightSource:
|
| 283 |
+
azdeg: float
|
| 284 |
+
altdeg: float
|
| 285 |
+
hsv_min_val: float
|
| 286 |
+
hsv_max_val: float
|
| 287 |
+
hsv_min_sat: float
|
| 288 |
+
hsv_max_sat: float
|
| 289 |
+
def __init__(
|
| 290 |
+
self,
|
| 291 |
+
azdeg: float = ...,
|
| 292 |
+
altdeg: float = ...,
|
| 293 |
+
hsv_min_val: float = ...,
|
| 294 |
+
hsv_max_val: float = ...,
|
| 295 |
+
hsv_min_sat: float = ...,
|
| 296 |
+
hsv_max_sat: float = ...,
|
| 297 |
+
) -> None: ...
|
| 298 |
+
@property
|
| 299 |
+
def direction(self) -> np.ndarray: ...
|
| 300 |
+
def hillshade(
|
| 301 |
+
self,
|
| 302 |
+
elevation: ArrayLike,
|
| 303 |
+
vert_exag: float = ...,
|
| 304 |
+
dx: float = ...,
|
| 305 |
+
dy: float = ...,
|
| 306 |
+
fraction: float = ...,
|
| 307 |
+
) -> np.ndarray: ...
|
| 308 |
+
def shade_normals(
|
| 309 |
+
self, normals: np.ndarray, fraction: float = ...
|
| 310 |
+
) -> np.ndarray: ...
|
| 311 |
+
def shade(
|
| 312 |
+
self,
|
| 313 |
+
data: ArrayLike,
|
| 314 |
+
cmap: Colormap,
|
| 315 |
+
norm: Normalize | None = ...,
|
| 316 |
+
blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ...,
|
| 317 |
+
vmin: float | None = ...,
|
| 318 |
+
vmax: float | None = ...,
|
| 319 |
+
vert_exag: float = ...,
|
| 320 |
+
dx: float = ...,
|
| 321 |
+
dy: float = ...,
|
| 322 |
+
fraction: float = ...,
|
| 323 |
+
**kwargs
|
| 324 |
+
) -> np.ndarray: ...
|
| 325 |
+
def shade_rgb(
|
| 326 |
+
self,
|
| 327 |
+
rgb: ArrayLike,
|
| 328 |
+
elevation: ArrayLike,
|
| 329 |
+
fraction: float = ...,
|
| 330 |
+
blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ...,
|
| 331 |
+
vert_exag: float = ...,
|
| 332 |
+
dx: float = ...,
|
| 333 |
+
dy: float = ...,
|
| 334 |
+
**kwargs
|
| 335 |
+
) -> np.ndarray: ...
|
| 336 |
+
def blend_hsv(
|
| 337 |
+
self,
|
| 338 |
+
rgb: ArrayLike,
|
| 339 |
+
intensity: ArrayLike,
|
| 340 |
+
hsv_max_sat: float | None = ...,
|
| 341 |
+
hsv_max_val: float | None = ...,
|
| 342 |
+
hsv_min_val: float | None = ...,
|
| 343 |
+
hsv_min_sat: float | None = ...,
|
| 344 |
+
) -> ArrayLike: ...
|
| 345 |
+
def blend_soft_light(
|
| 346 |
+
self, rgb: np.ndarray, intensity: np.ndarray
|
| 347 |
+
) -> np.ndarray: ...
|
| 348 |
+
def blend_overlay(self, rgb: np.ndarray, intensity: np.ndarray) -> np.ndarray: ...
|
| 349 |
+
|
| 350 |
+
def from_levels_and_colors(
|
| 351 |
+
levels: Sequence[float],
|
| 352 |
+
colors: Sequence[ColorType],
|
| 353 |
+
extend: Literal["neither", "min", "max", "both"] = ...,
|
| 354 |
+
) -> tuple[ListedColormap, BoundaryNorm]: ...
|
parrot/lib/python3.10/site-packages/matplotlib/container.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib import cbook
|
| 2 |
+
from matplotlib.artist import Artist
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Container(tuple):
|
| 6 |
+
"""
|
| 7 |
+
Base class for containers.
|
| 8 |
+
|
| 9 |
+
Containers are classes that collect semantically related Artists such as
|
| 10 |
+
the bars of a bar plot.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def __repr__(self):
|
| 14 |
+
return f"<{type(self).__name__} object of {len(self)} artists>"
|
| 15 |
+
|
| 16 |
+
def __new__(cls, *args, **kwargs):
|
| 17 |
+
return tuple.__new__(cls, args[0])
|
| 18 |
+
|
| 19 |
+
def __init__(self, kl, label=None):
|
| 20 |
+
self._callbacks = cbook.CallbackRegistry(signals=["pchanged"])
|
| 21 |
+
self._remove_method = None
|
| 22 |
+
self._label = str(label) if label is not None else None
|
| 23 |
+
|
| 24 |
+
def remove(self):
|
| 25 |
+
for c in cbook.flatten(
|
| 26 |
+
self, scalarp=lambda x: isinstance(x, Artist)):
|
| 27 |
+
if c is not None:
|
| 28 |
+
c.remove()
|
| 29 |
+
if self._remove_method:
|
| 30 |
+
self._remove_method(self)
|
| 31 |
+
|
| 32 |
+
def get_children(self):
|
| 33 |
+
return [child for child in cbook.flatten(self) if child is not None]
|
| 34 |
+
|
| 35 |
+
get_label = Artist.get_label
|
| 36 |
+
set_label = Artist.set_label
|
| 37 |
+
add_callback = Artist.add_callback
|
| 38 |
+
remove_callback = Artist.remove_callback
|
| 39 |
+
pchanged = Artist.pchanged
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class BarContainer(Container):
|
| 43 |
+
"""
|
| 44 |
+
Container for the artists of bar plots (e.g. created by `.Axes.bar`).
|
| 45 |
+
|
| 46 |
+
The container can be treated as a tuple of the *patches* themselves.
|
| 47 |
+
Additionally, you can access these and further parameters by the
|
| 48 |
+
attributes.
|
| 49 |
+
|
| 50 |
+
Attributes
|
| 51 |
+
----------
|
| 52 |
+
patches : list of :class:`~matplotlib.patches.Rectangle`
|
| 53 |
+
The artists of the bars.
|
| 54 |
+
|
| 55 |
+
errorbar : None or :class:`~matplotlib.container.ErrorbarContainer`
|
| 56 |
+
A container for the error bar artists if error bars are present.
|
| 57 |
+
*None* otherwise.
|
| 58 |
+
|
| 59 |
+
datavalues : None or array-like
|
| 60 |
+
The underlying data values corresponding to the bars.
|
| 61 |
+
|
| 62 |
+
orientation : {'vertical', 'horizontal'}, default: None
|
| 63 |
+
If 'vertical', the bars are assumed to be vertical.
|
| 64 |
+
If 'horizontal', the bars are assumed to be horizontal.
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
def __init__(self, patches, errorbar=None, *, datavalues=None,
|
| 69 |
+
orientation=None, **kwargs):
|
| 70 |
+
self.patches = patches
|
| 71 |
+
self.errorbar = errorbar
|
| 72 |
+
self.datavalues = datavalues
|
| 73 |
+
self.orientation = orientation
|
| 74 |
+
super().__init__(patches, **kwargs)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class ErrorbarContainer(Container):
|
| 78 |
+
"""
|
| 79 |
+
Container for the artists of error bars (e.g. created by `.Axes.errorbar`).
|
| 80 |
+
|
| 81 |
+
The container can be treated as the *lines* tuple itself.
|
| 82 |
+
Additionally, you can access these and further parameters by the
|
| 83 |
+
attributes.
|
| 84 |
+
|
| 85 |
+
Attributes
|
| 86 |
+
----------
|
| 87 |
+
lines : tuple
|
| 88 |
+
Tuple of ``(data_line, caplines, barlinecols)``.
|
| 89 |
+
|
| 90 |
+
- data_line : A `~matplotlib.lines.Line2D` instance of x, y plot markers
|
| 91 |
+
and/or line.
|
| 92 |
+
- caplines : A tuple of `~matplotlib.lines.Line2D` instances of the error
|
| 93 |
+
bar caps.
|
| 94 |
+
- barlinecols : A tuple of `~matplotlib.collections.LineCollection` with the
|
| 95 |
+
horizontal and vertical error ranges.
|
| 96 |
+
|
| 97 |
+
has_xerr, has_yerr : bool
|
| 98 |
+
``True`` if the errorbar has x/y errors.
|
| 99 |
+
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def __init__(self, lines, has_xerr=False, has_yerr=False, **kwargs):
|
| 103 |
+
self.lines = lines
|
| 104 |
+
self.has_xerr = has_xerr
|
| 105 |
+
self.has_yerr = has_yerr
|
| 106 |
+
super().__init__(lines, **kwargs)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class StemContainer(Container):
|
| 110 |
+
"""
|
| 111 |
+
Container for the artists created in a :meth:`.Axes.stem` plot.
|
| 112 |
+
|
| 113 |
+
The container can be treated like a namedtuple ``(markerline, stemlines,
|
| 114 |
+
baseline)``.
|
| 115 |
+
|
| 116 |
+
Attributes
|
| 117 |
+
----------
|
| 118 |
+
markerline : `~matplotlib.lines.Line2D`
|
| 119 |
+
The artist of the markers at the stem heads.
|
| 120 |
+
|
| 121 |
+
stemlines : `~matplotlib.collections.LineCollection`
|
| 122 |
+
The artists of the vertical lines for all stems.
|
| 123 |
+
|
| 124 |
+
baseline : `~matplotlib.lines.Line2D`
|
| 125 |
+
The artist of the horizontal baseline.
|
| 126 |
+
"""
|
| 127 |
+
def __init__(self, markerline_stemlines_baseline, **kwargs):
|
| 128 |
+
"""
|
| 129 |
+
Parameters
|
| 130 |
+
----------
|
| 131 |
+
markerline_stemlines_baseline : tuple
|
| 132 |
+
Tuple of ``(markerline, stemlines, baseline)``.
|
| 133 |
+
``markerline`` contains the `.Line2D` of the markers,
|
| 134 |
+
``stemlines`` is a `.LineCollection` of the main lines,
|
| 135 |
+
``baseline`` is the `.Line2D` of the baseline.
|
| 136 |
+
"""
|
| 137 |
+
markerline, stemlines, baseline = markerline_stemlines_baseline
|
| 138 |
+
self.markerline = markerline
|
| 139 |
+
self.stemlines = stemlines
|
| 140 |
+
self.baseline = baseline
|
| 141 |
+
super().__init__(markerline_stemlines_baseline, **kwargs)
|
parrot/lib/python3.10/site-packages/matplotlib/dviread.py
ADDED
|
@@ -0,0 +1,1107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A module for reading dvi files output by TeX. Several limitations make
|
| 3 |
+
this not (currently) useful as a general-purpose dvi preprocessor, but
|
| 4 |
+
it is currently used by the pdf backend for processing usetex text.
|
| 5 |
+
|
| 6 |
+
Interface::
|
| 7 |
+
|
| 8 |
+
with Dvi(filename, 72) as dvi:
|
| 9 |
+
# iterate over pages:
|
| 10 |
+
for page in dvi:
|
| 11 |
+
w, h, d = page.width, page.height, page.descent
|
| 12 |
+
for x, y, font, glyph, width in page.text:
|
| 13 |
+
fontname = font.texname
|
| 14 |
+
pointsize = font.size
|
| 15 |
+
...
|
| 16 |
+
for x, y, height, width in page.boxes:
|
| 17 |
+
...
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from collections import namedtuple
|
| 21 |
+
import enum
|
| 22 |
+
from functools import lru_cache, partial, wraps
|
| 23 |
+
import logging
|
| 24 |
+
import os
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
import re
|
| 27 |
+
import struct
|
| 28 |
+
import subprocess
|
| 29 |
+
import sys
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
from matplotlib import _api, cbook
|
| 34 |
+
|
| 35 |
+
_log = logging.getLogger(__name__)
|
| 36 |
+
|
| 37 |
+
# Many dvi related files are looked for by external processes, require
|
| 38 |
+
# additional parsing, and are used many times per rendering, which is why they
|
| 39 |
+
# are cached using lru_cache().
|
| 40 |
+
|
| 41 |
+
# Dvi is a bytecode format documented in
|
| 42 |
+
# https://ctan.org/pkg/dvitype
|
| 43 |
+
# https://texdoc.org/serve/dvitype.pdf/0
|
| 44 |
+
#
|
| 45 |
+
# The file consists of a preamble, some number of pages, a postamble,
|
| 46 |
+
# and a finale. Different opcodes are allowed in different contexts,
|
| 47 |
+
# so the Dvi object has a parser state:
|
| 48 |
+
#
|
| 49 |
+
# pre: expecting the preamble
|
| 50 |
+
# outer: between pages (followed by a page or the postamble,
|
| 51 |
+
# also e.g. font definitions are allowed)
|
| 52 |
+
# page: processing a page
|
| 53 |
+
# post_post: state after the postamble (our current implementation
|
| 54 |
+
# just stops reading)
|
| 55 |
+
# finale: the finale (unimplemented in our current implementation)
|
| 56 |
+
|
| 57 |
+
_dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale')
|
| 58 |
+
|
| 59 |
+
# The marks on a page consist of text and boxes. A page also has dimensions.
|
| 60 |
+
Page = namedtuple('Page', 'text boxes height width descent')
|
| 61 |
+
Box = namedtuple('Box', 'x y height width')
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Also a namedtuple, for backcompat.
|
| 65 |
+
class Text(namedtuple('Text', 'x y font glyph width')):
|
| 66 |
+
"""
|
| 67 |
+
A glyph in the dvi file.
|
| 68 |
+
|
| 69 |
+
The *x* and *y* attributes directly position the glyph. The *font*,
|
| 70 |
+
*glyph*, and *width* attributes are kept public for back-compatibility,
|
| 71 |
+
but users wanting to draw the glyph themselves are encouraged to instead
|
| 72 |
+
load the font specified by `font_path` at `font_size`, warp it with the
|
| 73 |
+
effects specified by `font_effects`, and load the glyph specified by
|
| 74 |
+
`glyph_name_or_index`.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def _get_pdftexmap_entry(self):
|
| 78 |
+
return PsfontsMap(find_tex_file("pdftex.map"))[self.font.texname]
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def font_path(self):
|
| 82 |
+
"""The `~pathlib.Path` to the font for this glyph."""
|
| 83 |
+
psfont = self._get_pdftexmap_entry()
|
| 84 |
+
if psfont.filename is None:
|
| 85 |
+
raise ValueError("No usable font file found for {} ({}); "
|
| 86 |
+
"the font may lack a Type-1 version"
|
| 87 |
+
.format(psfont.psname.decode("ascii"),
|
| 88 |
+
psfont.texname.decode("ascii")))
|
| 89 |
+
return Path(psfont.filename)
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def font_size(self):
|
| 93 |
+
"""The font size."""
|
| 94 |
+
return self.font.size
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def font_effects(self):
|
| 98 |
+
"""
|
| 99 |
+
The "font effects" dict for this glyph.
|
| 100 |
+
|
| 101 |
+
This dict contains the values for this glyph of SlantFont and
|
| 102 |
+
ExtendFont (if any), read off :file:`pdftex.map`.
|
| 103 |
+
"""
|
| 104 |
+
return self._get_pdftexmap_entry().effects
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def glyph_name_or_index(self):
|
| 108 |
+
"""
|
| 109 |
+
Either the glyph name or the native charmap glyph index.
|
| 110 |
+
|
| 111 |
+
If :file:`pdftex.map` specifies an encoding for this glyph's font, that
|
| 112 |
+
is a mapping of glyph indices to Adobe glyph names; use it to convert
|
| 113 |
+
dvi indices to glyph names. Callers can then convert glyph names to
|
| 114 |
+
glyph indices (with FT_Get_Name_Index/get_name_index), and load the
|
| 115 |
+
glyph using FT_Load_Glyph/load_glyph.
|
| 116 |
+
|
| 117 |
+
If :file:`pdftex.map` specifies no encoding, the indices directly map
|
| 118 |
+
to the font's "native" charmap; glyphs should directly load using
|
| 119 |
+
FT_Load_Char/load_char after selecting the native charmap.
|
| 120 |
+
"""
|
| 121 |
+
entry = self._get_pdftexmap_entry()
|
| 122 |
+
return (_parse_enc(entry.encoding)[self.glyph]
|
| 123 |
+
if entry.encoding is not None else self.glyph)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# Opcode argument parsing
|
| 127 |
+
#
|
| 128 |
+
# Each of the following functions takes a Dvi object and delta, which is the
|
| 129 |
+
# difference between the opcode and the minimum opcode with the same meaning.
|
| 130 |
+
# Dvi opcodes often encode the number of argument bytes in this delta.
|
| 131 |
+
_arg_mapping = dict(
|
| 132 |
+
# raw: Return delta as is.
|
| 133 |
+
raw=lambda dvi, delta: delta,
|
| 134 |
+
# u1: Read 1 byte as an unsigned number.
|
| 135 |
+
u1=lambda dvi, delta: dvi._arg(1, signed=False),
|
| 136 |
+
# u4: Read 4 bytes as an unsigned number.
|
| 137 |
+
u4=lambda dvi, delta: dvi._arg(4, signed=False),
|
| 138 |
+
# s4: Read 4 bytes as a signed number.
|
| 139 |
+
s4=lambda dvi, delta: dvi._arg(4, signed=True),
|
| 140 |
+
# slen: Read delta bytes as a signed number, or None if delta is None.
|
| 141 |
+
slen=lambda dvi, delta: dvi._arg(delta, signed=True) if delta else None,
|
| 142 |
+
# slen1: Read (delta + 1) bytes as a signed number.
|
| 143 |
+
slen1=lambda dvi, delta: dvi._arg(delta + 1, signed=True),
|
| 144 |
+
# ulen1: Read (delta + 1) bytes as an unsigned number.
|
| 145 |
+
ulen1=lambda dvi, delta: dvi._arg(delta + 1, signed=False),
|
| 146 |
+
# olen1: Read (delta + 1) bytes as an unsigned number if less than 4 bytes,
|
| 147 |
+
# as a signed number if 4 bytes.
|
| 148 |
+
olen1=lambda dvi, delta: dvi._arg(delta + 1, signed=(delta == 3)),
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _dispatch(table, min, max=None, state=None, args=('raw',)):
|
| 153 |
+
"""
|
| 154 |
+
Decorator for dispatch by opcode. Sets the values in *table*
|
| 155 |
+
from *min* to *max* to this method, adds a check that the Dvi state
|
| 156 |
+
matches *state* if not None, reads arguments from the file according
|
| 157 |
+
to *args*.
|
| 158 |
+
|
| 159 |
+
Parameters
|
| 160 |
+
----------
|
| 161 |
+
table : dict[int, callable]
|
| 162 |
+
The dispatch table to be filled in.
|
| 163 |
+
|
| 164 |
+
min, max : int
|
| 165 |
+
Range of opcodes that calls the registered function; *max* defaults to
|
| 166 |
+
*min*.
|
| 167 |
+
|
| 168 |
+
state : _dvistate, optional
|
| 169 |
+
State of the Dvi object in which these opcodes are allowed.
|
| 170 |
+
|
| 171 |
+
args : list[str], default: ['raw']
|
| 172 |
+
Sequence of argument specifications:
|
| 173 |
+
|
| 174 |
+
- 'raw': opcode minus minimum
|
| 175 |
+
- 'u1': read one unsigned byte
|
| 176 |
+
- 'u4': read four bytes, treat as an unsigned number
|
| 177 |
+
- 's4': read four bytes, treat as a signed number
|
| 178 |
+
- 'slen': read (opcode - minimum) bytes, treat as signed
|
| 179 |
+
- 'slen1': read (opcode - minimum + 1) bytes, treat as signed
|
| 180 |
+
- 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned
|
| 181 |
+
- 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned
|
| 182 |
+
if under four bytes, signed if four bytes
|
| 183 |
+
"""
|
| 184 |
+
def decorate(method):
|
| 185 |
+
get_args = [_arg_mapping[x] for x in args]
|
| 186 |
+
|
| 187 |
+
@wraps(method)
|
| 188 |
+
def wrapper(self, byte):
|
| 189 |
+
if state is not None and self.state != state:
|
| 190 |
+
raise ValueError("state precondition failed")
|
| 191 |
+
return method(self, *[f(self, byte-min) for f in get_args])
|
| 192 |
+
if max is None:
|
| 193 |
+
table[min] = wrapper
|
| 194 |
+
else:
|
| 195 |
+
for i in range(min, max+1):
|
| 196 |
+
assert table[i] is None
|
| 197 |
+
table[i] = wrapper
|
| 198 |
+
return wrapper
|
| 199 |
+
return decorate
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class Dvi:
|
| 203 |
+
"""
|
| 204 |
+
A reader for a dvi ("device-independent") file, as produced by TeX.
|
| 205 |
+
|
| 206 |
+
The current implementation can only iterate through pages in order,
|
| 207 |
+
and does not even attempt to verify the postamble.
|
| 208 |
+
|
| 209 |
+
This class can be used as a context manager to close the underlying
|
| 210 |
+
file upon exit. Pages can be read via iteration. Here is an overly
|
| 211 |
+
simple way to extract text without trying to detect whitespace::
|
| 212 |
+
|
| 213 |
+
>>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi:
|
| 214 |
+
... for page in dvi:
|
| 215 |
+
... print(''.join(chr(t.glyph) for t in page.text))
|
| 216 |
+
"""
|
| 217 |
+
# dispatch table
|
| 218 |
+
_dtable = [None] * 256
|
| 219 |
+
_dispatch = partial(_dispatch, _dtable)
|
| 220 |
+
|
| 221 |
+
def __init__(self, filename, dpi):
|
| 222 |
+
"""
|
| 223 |
+
Read the data from the file named *filename* and convert
|
| 224 |
+
TeX's internal units to units of *dpi* per inch.
|
| 225 |
+
*dpi* only sets the units and does not limit the resolution.
|
| 226 |
+
Use None to return TeX's internal units.
|
| 227 |
+
"""
|
| 228 |
+
_log.debug('Dvi: %s', filename)
|
| 229 |
+
self.file = open(filename, 'rb')
|
| 230 |
+
self.dpi = dpi
|
| 231 |
+
self.fonts = {}
|
| 232 |
+
self.state = _dvistate.pre
|
| 233 |
+
|
| 234 |
+
def __enter__(self):
|
| 235 |
+
"""Context manager enter method, does nothing."""
|
| 236 |
+
return self
|
| 237 |
+
|
| 238 |
+
def __exit__(self, etype, evalue, etrace):
|
| 239 |
+
"""
|
| 240 |
+
Context manager exit method, closes the underlying file if it is open.
|
| 241 |
+
"""
|
| 242 |
+
self.close()
|
| 243 |
+
|
| 244 |
+
def __iter__(self):
|
| 245 |
+
"""
|
| 246 |
+
Iterate through the pages of the file.
|
| 247 |
+
|
| 248 |
+
Yields
|
| 249 |
+
------
|
| 250 |
+
Page
|
| 251 |
+
Details of all the text and box objects on the page.
|
| 252 |
+
The Page tuple contains lists of Text and Box tuples and
|
| 253 |
+
the page dimensions, and the Text and Box tuples contain
|
| 254 |
+
coordinates transformed into a standard Cartesian
|
| 255 |
+
coordinate system at the dpi value given when initializing.
|
| 256 |
+
The coordinates are floating point numbers, but otherwise
|
| 257 |
+
precision is not lost and coordinate values are not clipped to
|
| 258 |
+
integers.
|
| 259 |
+
"""
|
| 260 |
+
while self._read():
|
| 261 |
+
yield self._output()
|
| 262 |
+
|
| 263 |
+
def close(self):
|
| 264 |
+
"""Close the underlying file if it is open."""
|
| 265 |
+
if not self.file.closed:
|
| 266 |
+
self.file.close()
|
| 267 |
+
|
| 268 |
+
def _output(self):
|
| 269 |
+
"""
|
| 270 |
+
Output the text and boxes belonging to the most recent page.
|
| 271 |
+
page = dvi._output()
|
| 272 |
+
"""
|
| 273 |
+
minx, miny, maxx, maxy = np.inf, np.inf, -np.inf, -np.inf
|
| 274 |
+
maxy_pure = -np.inf
|
| 275 |
+
for elt in self.text + self.boxes:
|
| 276 |
+
if isinstance(elt, Box):
|
| 277 |
+
x, y, h, w = elt
|
| 278 |
+
e = 0 # zero depth
|
| 279 |
+
else: # glyph
|
| 280 |
+
x, y, font, g, w = elt
|
| 281 |
+
h, e = font._height_depth_of(g)
|
| 282 |
+
minx = min(minx, x)
|
| 283 |
+
miny = min(miny, y - h)
|
| 284 |
+
maxx = max(maxx, x + w)
|
| 285 |
+
maxy = max(maxy, y + e)
|
| 286 |
+
maxy_pure = max(maxy_pure, y)
|
| 287 |
+
if self._baseline_v is not None:
|
| 288 |
+
maxy_pure = self._baseline_v # This should normally be the case.
|
| 289 |
+
self._baseline_v = None
|
| 290 |
+
|
| 291 |
+
if not self.text and not self.boxes: # Avoid infs/nans from inf+/-inf.
|
| 292 |
+
return Page(text=[], boxes=[], width=0, height=0, descent=0)
|
| 293 |
+
|
| 294 |
+
if self.dpi is None:
|
| 295 |
+
# special case for ease of debugging: output raw dvi coordinates
|
| 296 |
+
return Page(text=self.text, boxes=self.boxes,
|
| 297 |
+
width=maxx-minx, height=maxy_pure-miny,
|
| 298 |
+
descent=maxy-maxy_pure)
|
| 299 |
+
|
| 300 |
+
# convert from TeX's "scaled points" to dpi units
|
| 301 |
+
d = self.dpi / (72.27 * 2**16)
|
| 302 |
+
descent = (maxy - maxy_pure) * d
|
| 303 |
+
|
| 304 |
+
text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d)
|
| 305 |
+
for (x, y, f, g, w) in self.text]
|
| 306 |
+
boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d)
|
| 307 |
+
for (x, y, h, w) in self.boxes]
|
| 308 |
+
|
| 309 |
+
return Page(text=text, boxes=boxes, width=(maxx-minx)*d,
|
| 310 |
+
height=(maxy_pure-miny)*d, descent=descent)
|
| 311 |
+
|
| 312 |
+
def _read(self):
|
| 313 |
+
"""
|
| 314 |
+
Read one page from the file. Return True if successful,
|
| 315 |
+
False if there were no more pages.
|
| 316 |
+
"""
|
| 317 |
+
# Pages appear to start with the sequence
|
| 318 |
+
# bop (begin of page)
|
| 319 |
+
# xxx comment
|
| 320 |
+
# <push, ..., pop> # if using chemformula
|
| 321 |
+
# down
|
| 322 |
+
# push
|
| 323 |
+
# down
|
| 324 |
+
# <push, push, xxx, right, xxx, pop, pop> # if using xcolor
|
| 325 |
+
# down
|
| 326 |
+
# push
|
| 327 |
+
# down (possibly multiple)
|
| 328 |
+
# push <= here, v is the baseline position.
|
| 329 |
+
# etc.
|
| 330 |
+
# (dviasm is useful to explore this structure.)
|
| 331 |
+
# Thus, we use the vertical position at the first time the stack depth
|
| 332 |
+
# reaches 3, while at least three "downs" have been executed (excluding
|
| 333 |
+
# those popped out (corresponding to the chemformula preamble)), as the
|
| 334 |
+
# baseline (the "down" count is necessary to handle xcolor).
|
| 335 |
+
down_stack = [0]
|
| 336 |
+
self._baseline_v = None
|
| 337 |
+
while True:
|
| 338 |
+
byte = self.file.read(1)[0]
|
| 339 |
+
self._dtable[byte](self, byte)
|
| 340 |
+
name = self._dtable[byte].__name__
|
| 341 |
+
if name == "_push":
|
| 342 |
+
down_stack.append(down_stack[-1])
|
| 343 |
+
elif name == "_pop":
|
| 344 |
+
down_stack.pop()
|
| 345 |
+
elif name == "_down":
|
| 346 |
+
down_stack[-1] += 1
|
| 347 |
+
if (self._baseline_v is None
|
| 348 |
+
and len(getattr(self, "stack", [])) == 3
|
| 349 |
+
and down_stack[-1] >= 4):
|
| 350 |
+
self._baseline_v = self.v
|
| 351 |
+
if byte == 140: # end of page
|
| 352 |
+
return True
|
| 353 |
+
if self.state is _dvistate.post_post: # end of file
|
| 354 |
+
self.close()
|
| 355 |
+
return False
|
| 356 |
+
|
| 357 |
+
def _arg(self, nbytes, signed=False):
|
| 358 |
+
"""
|
| 359 |
+
Read and return a big-endian integer *nbytes* long.
|
| 360 |
+
Signedness is determined by the *signed* keyword.
|
| 361 |
+
"""
|
| 362 |
+
return int.from_bytes(self.file.read(nbytes), "big", signed=signed)
|
| 363 |
+
|
| 364 |
+
@_dispatch(min=0, max=127, state=_dvistate.inpage)
|
| 365 |
+
def _set_char_immediate(self, char):
|
| 366 |
+
self._put_char_real(char)
|
| 367 |
+
self.h += self.fonts[self.f]._width_of(char)
|
| 368 |
+
|
| 369 |
+
@_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',))
|
| 370 |
+
def _set_char(self, char):
|
| 371 |
+
self._put_char_real(char)
|
| 372 |
+
self.h += self.fonts[self.f]._width_of(char)
|
| 373 |
+
|
| 374 |
+
@_dispatch(132, state=_dvistate.inpage, args=('s4', 's4'))
|
| 375 |
+
def _set_rule(self, a, b):
|
| 376 |
+
self._put_rule_real(a, b)
|
| 377 |
+
self.h += b
|
| 378 |
+
|
| 379 |
+
@_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',))
|
| 380 |
+
def _put_char(self, char):
|
| 381 |
+
self._put_char_real(char)
|
| 382 |
+
|
| 383 |
+
def _put_char_real(self, char):
|
| 384 |
+
font = self.fonts[self.f]
|
| 385 |
+
if font._vf is None:
|
| 386 |
+
self.text.append(Text(self.h, self.v, font, char,
|
| 387 |
+
font._width_of(char)))
|
| 388 |
+
else:
|
| 389 |
+
scale = font._scale
|
| 390 |
+
for x, y, f, g, w in font._vf[char].text:
|
| 391 |
+
newf = DviFont(scale=_mul2012(scale, f._scale),
|
| 392 |
+
tfm=f._tfm, texname=f.texname, vf=f._vf)
|
| 393 |
+
self.text.append(Text(self.h + _mul2012(x, scale),
|
| 394 |
+
self.v + _mul2012(y, scale),
|
| 395 |
+
newf, g, newf._width_of(g)))
|
| 396 |
+
self.boxes.extend([Box(self.h + _mul2012(x, scale),
|
| 397 |
+
self.v + _mul2012(y, scale),
|
| 398 |
+
_mul2012(a, scale), _mul2012(b, scale))
|
| 399 |
+
for x, y, a, b in font._vf[char].boxes])
|
| 400 |
+
|
| 401 |
+
@_dispatch(137, state=_dvistate.inpage, args=('s4', 's4'))
|
| 402 |
+
def _put_rule(self, a, b):
|
| 403 |
+
self._put_rule_real(a, b)
|
| 404 |
+
|
| 405 |
+
def _put_rule_real(self, a, b):
|
| 406 |
+
if a > 0 and b > 0:
|
| 407 |
+
self.boxes.append(Box(self.h, self.v, a, b))
|
| 408 |
+
|
| 409 |
+
@_dispatch(138)
|
| 410 |
+
def _nop(self, _):
|
| 411 |
+
pass
|
| 412 |
+
|
| 413 |
+
@_dispatch(139, state=_dvistate.outer, args=('s4',)*11)
|
| 414 |
+
def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p):
|
| 415 |
+
self.state = _dvistate.inpage
|
| 416 |
+
self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
|
| 417 |
+
self.stack = []
|
| 418 |
+
self.text = [] # list of Text objects
|
| 419 |
+
self.boxes = [] # list of Box objects
|
| 420 |
+
|
| 421 |
+
@_dispatch(140, state=_dvistate.inpage)
|
| 422 |
+
def _eop(self, _):
|
| 423 |
+
self.state = _dvistate.outer
|
| 424 |
+
del self.h, self.v, self.w, self.x, self.y, self.z, self.stack
|
| 425 |
+
|
| 426 |
+
@_dispatch(141, state=_dvistate.inpage)
|
| 427 |
+
def _push(self, _):
|
| 428 |
+
self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z))
|
| 429 |
+
|
| 430 |
+
@_dispatch(142, state=_dvistate.inpage)
|
| 431 |
+
def _pop(self, _):
|
| 432 |
+
self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop()
|
| 433 |
+
|
| 434 |
+
@_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',))
|
| 435 |
+
def _right(self, b):
|
| 436 |
+
self.h += b
|
| 437 |
+
|
| 438 |
+
@_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',))
|
| 439 |
+
def _right_w(self, new_w):
|
| 440 |
+
if new_w is not None:
|
| 441 |
+
self.w = new_w
|
| 442 |
+
self.h += self.w
|
| 443 |
+
|
| 444 |
+
@_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',))
|
| 445 |
+
def _right_x(self, new_x):
|
| 446 |
+
if new_x is not None:
|
| 447 |
+
self.x = new_x
|
| 448 |
+
self.h += self.x
|
| 449 |
+
|
| 450 |
+
@_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',))
|
| 451 |
+
def _down(self, a):
|
| 452 |
+
self.v += a
|
| 453 |
+
|
| 454 |
+
@_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',))
|
| 455 |
+
def _down_y(self, new_y):
|
| 456 |
+
if new_y is not None:
|
| 457 |
+
self.y = new_y
|
| 458 |
+
self.v += self.y
|
| 459 |
+
|
| 460 |
+
@_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',))
|
| 461 |
+
def _down_z(self, new_z):
|
| 462 |
+
if new_z is not None:
|
| 463 |
+
self.z = new_z
|
| 464 |
+
self.v += self.z
|
| 465 |
+
|
| 466 |
+
@_dispatch(min=171, max=234, state=_dvistate.inpage)
|
| 467 |
+
def _fnt_num_immediate(self, k):
|
| 468 |
+
self.f = k
|
| 469 |
+
|
| 470 |
+
@_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',))
|
| 471 |
+
def _fnt_num(self, new_f):
|
| 472 |
+
self.f = new_f
|
| 473 |
+
|
| 474 |
+
@_dispatch(min=239, max=242, args=('ulen1',))
|
| 475 |
+
def _xxx(self, datalen):
|
| 476 |
+
special = self.file.read(datalen)
|
| 477 |
+
_log.debug(
|
| 478 |
+
'Dvi._xxx: encountered special: %s',
|
| 479 |
+
''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch
|
| 480 |
+
for ch in special]))
|
| 481 |
+
|
| 482 |
+
@_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
|
| 483 |
+
def _fnt_def(self, k, c, s, d, a, l):
|
| 484 |
+
self._fnt_def_real(k, c, s, d, a, l)
|
| 485 |
+
|
| 486 |
+
def _fnt_def_real(self, k, c, s, d, a, l):
|
| 487 |
+
n = self.file.read(a + l)
|
| 488 |
+
fontname = n[-l:].decode('ascii')
|
| 489 |
+
tfm = _tfmfile(fontname)
|
| 490 |
+
if c != 0 and tfm.checksum != 0 and c != tfm.checksum:
|
| 491 |
+
raise ValueError('tfm checksum mismatch: %s' % n)
|
| 492 |
+
try:
|
| 493 |
+
vf = _vffile(fontname)
|
| 494 |
+
except FileNotFoundError:
|
| 495 |
+
vf = None
|
| 496 |
+
self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf)
|
| 497 |
+
|
| 498 |
+
@_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1'))
|
| 499 |
+
def _pre(self, i, num, den, mag, k):
|
| 500 |
+
self.file.read(k) # comment in the dvi file
|
| 501 |
+
if i != 2:
|
| 502 |
+
raise ValueError("Unknown dvi format %d" % i)
|
| 503 |
+
if num != 25400000 or den != 7227 * 2**16:
|
| 504 |
+
raise ValueError("Nonstandard units in dvi file")
|
| 505 |
+
# meaning: TeX always uses those exact values, so it
|
| 506 |
+
# should be enough for us to support those
|
| 507 |
+
# (There are 72.27 pt to an inch so 7227 pt =
|
| 508 |
+
# 7227 * 2**16 sp to 100 in. The numerator is multiplied
|
| 509 |
+
# by 10^5 to get units of 10**-7 meters.)
|
| 510 |
+
if mag != 1000:
|
| 511 |
+
raise ValueError("Nonstandard magnification in dvi file")
|
| 512 |
+
# meaning: LaTeX seems to frown on setting \mag, so
|
| 513 |
+
# I think we can assume this is constant
|
| 514 |
+
self.state = _dvistate.outer
|
| 515 |
+
|
| 516 |
+
@_dispatch(248, state=_dvistate.outer)
|
| 517 |
+
def _post(self, _):
|
| 518 |
+
self.state = _dvistate.post_post
|
| 519 |
+
# TODO: actually read the postamble and finale?
|
| 520 |
+
# currently post_post just triggers closing the file
|
| 521 |
+
|
| 522 |
+
@_dispatch(249)
|
| 523 |
+
def _post_post(self, _):
|
| 524 |
+
raise NotImplementedError
|
| 525 |
+
|
| 526 |
+
@_dispatch(min=250, max=255)
|
| 527 |
+
def _malformed(self, offset):
|
| 528 |
+
raise ValueError(f"unknown command: byte {250 + offset}")
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
class DviFont:
|
| 532 |
+
"""
|
| 533 |
+
Encapsulation of a font that a DVI file can refer to.
|
| 534 |
+
|
| 535 |
+
This class holds a font's texname and size, supports comparison,
|
| 536 |
+
and knows the widths of glyphs in the same units as the AFM file.
|
| 537 |
+
There are also internal attributes (for use by dviread.py) that
|
| 538 |
+
are *not* used for comparison.
|
| 539 |
+
|
| 540 |
+
The size is in Adobe points (converted from TeX points).
|
| 541 |
+
|
| 542 |
+
Parameters
|
| 543 |
+
----------
|
| 544 |
+
scale : float
|
| 545 |
+
Factor by which the font is scaled from its natural size.
|
| 546 |
+
tfm : Tfm
|
| 547 |
+
TeX font metrics for this font
|
| 548 |
+
texname : bytes
|
| 549 |
+
Name of the font as used internally by TeX and friends, as an ASCII
|
| 550 |
+
bytestring. This is usually very different from any external font
|
| 551 |
+
names; `PsfontsMap` can be used to find the external name of the font.
|
| 552 |
+
vf : Vf
|
| 553 |
+
A TeX "virtual font" file, or None if this font is not virtual.
|
| 554 |
+
|
| 555 |
+
Attributes
|
| 556 |
+
----------
|
| 557 |
+
texname : bytes
|
| 558 |
+
size : float
|
| 559 |
+
Size of the font in Adobe points, converted from the slightly
|
| 560 |
+
smaller TeX points.
|
| 561 |
+
widths : list
|
| 562 |
+
Widths of glyphs in glyph-space units, typically 1/1000ths of
|
| 563 |
+
the point size.
|
| 564 |
+
|
| 565 |
+
"""
|
| 566 |
+
__slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm')
|
| 567 |
+
|
| 568 |
+
def __init__(self, scale, tfm, texname, vf):
|
| 569 |
+
_api.check_isinstance(bytes, texname=texname)
|
| 570 |
+
self._scale = scale
|
| 571 |
+
self._tfm = tfm
|
| 572 |
+
self.texname = texname
|
| 573 |
+
self._vf = vf
|
| 574 |
+
self.size = scale * (72.0 / (72.27 * 2**16))
|
| 575 |
+
try:
|
| 576 |
+
nchars = max(tfm.width) + 1
|
| 577 |
+
except ValueError:
|
| 578 |
+
nchars = 0
|
| 579 |
+
self.widths = [(1000*tfm.width.get(char, 0)) >> 20
|
| 580 |
+
for char in range(nchars)]
|
| 581 |
+
|
| 582 |
+
def __eq__(self, other):
|
| 583 |
+
return (type(self) is type(other)
|
| 584 |
+
and self.texname == other.texname and self.size == other.size)
|
| 585 |
+
|
| 586 |
+
def __ne__(self, other):
|
| 587 |
+
return not self.__eq__(other)
|
| 588 |
+
|
| 589 |
+
def __repr__(self):
|
| 590 |
+
return f"<{type(self).__name__}: {self.texname}>"
|
| 591 |
+
|
| 592 |
+
def _width_of(self, char):
|
| 593 |
+
"""Width of char in dvi units."""
|
| 594 |
+
width = self._tfm.width.get(char, None)
|
| 595 |
+
if width is not None:
|
| 596 |
+
return _mul2012(width, self._scale)
|
| 597 |
+
_log.debug('No width for char %d in font %s.', char, self.texname)
|
| 598 |
+
return 0
|
| 599 |
+
|
| 600 |
+
def _height_depth_of(self, char):
|
| 601 |
+
"""Height and depth of char in dvi units."""
|
| 602 |
+
result = []
|
| 603 |
+
for metric, name in ((self._tfm.height, "height"),
|
| 604 |
+
(self._tfm.depth, "depth")):
|
| 605 |
+
value = metric.get(char, None)
|
| 606 |
+
if value is None:
|
| 607 |
+
_log.debug('No %s for char %d in font %s',
|
| 608 |
+
name, char, self.texname)
|
| 609 |
+
result.append(0)
|
| 610 |
+
else:
|
| 611 |
+
result.append(_mul2012(value, self._scale))
|
| 612 |
+
# cmsyXX (symbols font) glyph 0 ("minus") has a nonzero descent
|
| 613 |
+
# so that TeX aligns equations properly
|
| 614 |
+
# (https://tex.stackexchange.com/q/526103/)
|
| 615 |
+
# but we actually care about the rasterization depth to align
|
| 616 |
+
# the dvipng-generated images.
|
| 617 |
+
if re.match(br'^cmsy\d+$', self.texname) and char == 0:
|
| 618 |
+
result[-1] = 0
|
| 619 |
+
return result
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class Vf(Dvi):
|
| 623 |
+
r"""
|
| 624 |
+
A virtual font (\*.vf file) containing subroutines for dvi files.
|
| 625 |
+
|
| 626 |
+
Parameters
|
| 627 |
+
----------
|
| 628 |
+
filename : str or path-like
|
| 629 |
+
|
| 630 |
+
Notes
|
| 631 |
+
-----
|
| 632 |
+
The virtual font format is a derivative of dvi:
|
| 633 |
+
http://mirrors.ctan.org/info/knuth/virtual-fonts
|
| 634 |
+
This class reuses some of the machinery of `Dvi`
|
| 635 |
+
but replaces the `_read` loop and dispatch mechanism.
|
| 636 |
+
|
| 637 |
+
Examples
|
| 638 |
+
--------
|
| 639 |
+
::
|
| 640 |
+
|
| 641 |
+
vf = Vf(filename)
|
| 642 |
+
glyph = vf[code]
|
| 643 |
+
glyph.text, glyph.boxes, glyph.width
|
| 644 |
+
"""
|
| 645 |
+
|
| 646 |
+
def __init__(self, filename):
|
| 647 |
+
super().__init__(filename, 0)
|
| 648 |
+
try:
|
| 649 |
+
self._first_font = None
|
| 650 |
+
self._chars = {}
|
| 651 |
+
self._read()
|
| 652 |
+
finally:
|
| 653 |
+
self.close()
|
| 654 |
+
|
| 655 |
+
def __getitem__(self, code):
|
| 656 |
+
return self._chars[code]
|
| 657 |
+
|
| 658 |
+
def _read(self):
|
| 659 |
+
"""
|
| 660 |
+
Read one page from the file. Return True if successful,
|
| 661 |
+
False if there were no more pages.
|
| 662 |
+
"""
|
| 663 |
+
packet_char, packet_ends = None, None
|
| 664 |
+
packet_len, packet_width = None, None
|
| 665 |
+
while True:
|
| 666 |
+
byte = self.file.read(1)[0]
|
| 667 |
+
# If we are in a packet, execute the dvi instructions
|
| 668 |
+
if self.state is _dvistate.inpage:
|
| 669 |
+
byte_at = self.file.tell()-1
|
| 670 |
+
if byte_at == packet_ends:
|
| 671 |
+
self._finalize_packet(packet_char, packet_width)
|
| 672 |
+
packet_len, packet_char, packet_width = None, None, None
|
| 673 |
+
# fall through to out-of-packet code
|
| 674 |
+
elif byte_at > packet_ends:
|
| 675 |
+
raise ValueError("Packet length mismatch in vf file")
|
| 676 |
+
else:
|
| 677 |
+
if byte in (139, 140) or byte >= 243:
|
| 678 |
+
raise ValueError(
|
| 679 |
+
"Inappropriate opcode %d in vf file" % byte)
|
| 680 |
+
Dvi._dtable[byte](self, byte)
|
| 681 |
+
continue
|
| 682 |
+
|
| 683 |
+
# We are outside a packet
|
| 684 |
+
if byte < 242: # a short packet (length given by byte)
|
| 685 |
+
packet_len = byte
|
| 686 |
+
packet_char, packet_width = self._arg(1), self._arg(3)
|
| 687 |
+
packet_ends = self._init_packet(byte)
|
| 688 |
+
self.state = _dvistate.inpage
|
| 689 |
+
elif byte == 242: # a long packet
|
| 690 |
+
packet_len, packet_char, packet_width = \
|
| 691 |
+
[self._arg(x) for x in (4, 4, 4)]
|
| 692 |
+
self._init_packet(packet_len)
|
| 693 |
+
elif 243 <= byte <= 246:
|
| 694 |
+
k = self._arg(byte - 242, byte == 246)
|
| 695 |
+
c, s, d, a, l = [self._arg(x) for x in (4, 4, 4, 1, 1)]
|
| 696 |
+
self._fnt_def_real(k, c, s, d, a, l)
|
| 697 |
+
if self._first_font is None:
|
| 698 |
+
self._first_font = k
|
| 699 |
+
elif byte == 247: # preamble
|
| 700 |
+
i, k = self._arg(1), self._arg(1)
|
| 701 |
+
x = self.file.read(k)
|
| 702 |
+
cs, ds = self._arg(4), self._arg(4)
|
| 703 |
+
self._pre(i, x, cs, ds)
|
| 704 |
+
elif byte == 248: # postamble (just some number of 248s)
|
| 705 |
+
break
|
| 706 |
+
else:
|
| 707 |
+
raise ValueError("Unknown vf opcode %d" % byte)
|
| 708 |
+
|
| 709 |
+
def _init_packet(self, pl):
|
| 710 |
+
if self.state != _dvistate.outer:
|
| 711 |
+
raise ValueError("Misplaced packet in vf file")
|
| 712 |
+
self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
|
| 713 |
+
self.stack, self.text, self.boxes = [], [], []
|
| 714 |
+
self.f = self._first_font
|
| 715 |
+
return self.file.tell() + pl
|
| 716 |
+
|
| 717 |
+
def _finalize_packet(self, packet_char, packet_width):
|
| 718 |
+
self._chars[packet_char] = Page(
|
| 719 |
+
text=self.text, boxes=self.boxes, width=packet_width,
|
| 720 |
+
height=None, descent=None)
|
| 721 |
+
self.state = _dvistate.outer
|
| 722 |
+
|
| 723 |
+
def _pre(self, i, x, cs, ds):
|
| 724 |
+
if self.state is not _dvistate.pre:
|
| 725 |
+
raise ValueError("pre command in middle of vf file")
|
| 726 |
+
if i != 202:
|
| 727 |
+
raise ValueError("Unknown vf format %d" % i)
|
| 728 |
+
if len(x):
|
| 729 |
+
_log.debug('vf file comment: %s', x)
|
| 730 |
+
self.state = _dvistate.outer
|
| 731 |
+
# cs = checksum, ds = design size
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def _mul2012(num1, num2):
|
| 735 |
+
"""Multiply two numbers in 20.12 fixed point format."""
|
| 736 |
+
# Separated into a function because >> has surprising precedence
|
| 737 |
+
return (num1*num2) >> 20
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
class Tfm:
|
| 741 |
+
"""
|
| 742 |
+
A TeX Font Metric file.
|
| 743 |
+
|
| 744 |
+
This implementation covers only the bare minimum needed by the Dvi class.
|
| 745 |
+
|
| 746 |
+
Parameters
|
| 747 |
+
----------
|
| 748 |
+
filename : str or path-like
|
| 749 |
+
|
| 750 |
+
Attributes
|
| 751 |
+
----------
|
| 752 |
+
checksum : int
|
| 753 |
+
Used for verifying against the dvi file.
|
| 754 |
+
design_size : int
|
| 755 |
+
Design size of the font (unknown units)
|
| 756 |
+
width, height, depth : dict
|
| 757 |
+
Dimensions of each character, need to be scaled by the factor
|
| 758 |
+
specified in the dvi file. These are dicts because indexing may
|
| 759 |
+
not start from 0.
|
| 760 |
+
"""
|
| 761 |
+
__slots__ = ('checksum', 'design_size', 'width', 'height', 'depth')
|
| 762 |
+
|
| 763 |
+
def __init__(self, filename):
|
| 764 |
+
_log.debug('opening tfm file %s', filename)
|
| 765 |
+
with open(filename, 'rb') as file:
|
| 766 |
+
header1 = file.read(24)
|
| 767 |
+
lh, bc, ec, nw, nh, nd = struct.unpack('!6H', header1[2:14])
|
| 768 |
+
_log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d',
|
| 769 |
+
lh, bc, ec, nw, nh, nd)
|
| 770 |
+
header2 = file.read(4*lh)
|
| 771 |
+
self.checksum, self.design_size = struct.unpack('!2I', header2[:8])
|
| 772 |
+
# there is also encoding information etc.
|
| 773 |
+
char_info = file.read(4*(ec-bc+1))
|
| 774 |
+
widths = struct.unpack(f'!{nw}i', file.read(4*nw))
|
| 775 |
+
heights = struct.unpack(f'!{nh}i', file.read(4*nh))
|
| 776 |
+
depths = struct.unpack(f'!{nd}i', file.read(4*nd))
|
| 777 |
+
self.width, self.height, self.depth = {}, {}, {}
|
| 778 |
+
for idx, char in enumerate(range(bc, ec+1)):
|
| 779 |
+
byte0 = char_info[4*idx]
|
| 780 |
+
byte1 = char_info[4*idx+1]
|
| 781 |
+
self.width[char] = widths[byte0]
|
| 782 |
+
self.height[char] = heights[byte1 >> 4]
|
| 783 |
+
self.depth[char] = depths[byte1 & 0xf]
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
PsFont = namedtuple('PsFont', 'texname psname effects encoding filename')
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
class PsfontsMap:
|
| 790 |
+
"""
|
| 791 |
+
A psfonts.map formatted file, mapping TeX fonts to PS fonts.
|
| 792 |
+
|
| 793 |
+
Parameters
|
| 794 |
+
----------
|
| 795 |
+
filename : str or path-like
|
| 796 |
+
|
| 797 |
+
Notes
|
| 798 |
+
-----
|
| 799 |
+
For historical reasons, TeX knows many Type-1 fonts by different
|
| 800 |
+
names than the outside world. (For one thing, the names have to
|
| 801 |
+
fit in eight characters.) Also, TeX's native fonts are not Type-1
|
| 802 |
+
but Metafont, which is nontrivial to convert to PostScript except
|
| 803 |
+
as a bitmap. While high-quality conversions to Type-1 format exist
|
| 804 |
+
and are shipped with modern TeX distributions, we need to know
|
| 805 |
+
which Type-1 fonts are the counterparts of which native fonts. For
|
| 806 |
+
these reasons a mapping is needed from internal font names to font
|
| 807 |
+
file names.
|
| 808 |
+
|
| 809 |
+
A texmf tree typically includes mapping files called e.g.
|
| 810 |
+
:file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`.
|
| 811 |
+
The file :file:`psfonts.map` is used by :program:`dvips`,
|
| 812 |
+
:file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map`
|
| 813 |
+
by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding
|
| 814 |
+
the 35 PostScript fonts (i.e., have no filename for them, as in
|
| 815 |
+
the Times-Bold example above), while the pdf-related files perhaps
|
| 816 |
+
only avoid the "Base 14" pdf fonts. But the user may have
|
| 817 |
+
configured these files differently.
|
| 818 |
+
|
| 819 |
+
Examples
|
| 820 |
+
--------
|
| 821 |
+
>>> map = PsfontsMap(find_tex_file('pdftex.map'))
|
| 822 |
+
>>> entry = map[b'ptmbo8r']
|
| 823 |
+
>>> entry.texname
|
| 824 |
+
b'ptmbo8r'
|
| 825 |
+
>>> entry.psname
|
| 826 |
+
b'Times-Bold'
|
| 827 |
+
>>> entry.encoding
|
| 828 |
+
'/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc'
|
| 829 |
+
>>> entry.effects
|
| 830 |
+
{'slant': 0.16700000000000001}
|
| 831 |
+
>>> entry.filename
|
| 832 |
+
"""
|
| 833 |
+
__slots__ = ('_filename', '_unparsed', '_parsed')
|
| 834 |
+
|
| 835 |
+
# Create a filename -> PsfontsMap cache, so that calling
|
| 836 |
+
# `PsfontsMap(filename)` with the same filename a second time immediately
|
| 837 |
+
# returns the same object.
|
| 838 |
+
@lru_cache
|
| 839 |
+
def __new__(cls, filename):
|
| 840 |
+
self = object.__new__(cls)
|
| 841 |
+
self._filename = os.fsdecode(filename)
|
| 842 |
+
# Some TeX distributions have enormous pdftex.map files which would
|
| 843 |
+
# take hundreds of milliseconds to parse, but it is easy enough to just
|
| 844 |
+
# store the unparsed lines (keyed by the first word, which is the
|
| 845 |
+
# texname) and parse them on-demand.
|
| 846 |
+
with open(filename, 'rb') as file:
|
| 847 |
+
self._unparsed = {}
|
| 848 |
+
for line in file:
|
| 849 |
+
tfmname = line.split(b' ', 1)[0]
|
| 850 |
+
self._unparsed.setdefault(tfmname, []).append(line)
|
| 851 |
+
self._parsed = {}
|
| 852 |
+
return self
|
| 853 |
+
|
| 854 |
+
def __getitem__(self, texname):
|
| 855 |
+
assert isinstance(texname, bytes)
|
| 856 |
+
if texname in self._unparsed:
|
| 857 |
+
for line in self._unparsed.pop(texname):
|
| 858 |
+
if self._parse_and_cache_line(line):
|
| 859 |
+
break
|
| 860 |
+
try:
|
| 861 |
+
return self._parsed[texname]
|
| 862 |
+
except KeyError:
|
| 863 |
+
raise LookupError(
|
| 864 |
+
f"An associated PostScript font (required by Matplotlib) "
|
| 865 |
+
f"could not be found for TeX font {texname.decode('ascii')!r} "
|
| 866 |
+
f"in {self._filename!r}; this problem can often be solved by "
|
| 867 |
+
f"installing a suitable PostScript font package in your TeX "
|
| 868 |
+
f"package manager") from None
|
| 869 |
+
|
| 870 |
+
def _parse_and_cache_line(self, line):
|
| 871 |
+
"""
|
| 872 |
+
Parse a line in the font mapping file.
|
| 873 |
+
|
| 874 |
+
The format is (partially) documented at
|
| 875 |
+
http://mirrors.ctan.org/systems/doc/pdftex/manual/pdftex-a.pdf
|
| 876 |
+
https://tug.org/texinfohtml/dvips.html#psfonts_002emap
|
| 877 |
+
Each line can have the following fields:
|
| 878 |
+
|
| 879 |
+
- tfmname (first, only required field),
|
| 880 |
+
- psname (defaults to tfmname, must come immediately after tfmname if
|
| 881 |
+
present),
|
| 882 |
+
- fontflags (integer, must come immediately after psname if present,
|
| 883 |
+
ignored by us),
|
| 884 |
+
- special (SlantFont and ExtendFont, only field that is double-quoted),
|
| 885 |
+
- fontfile, encodingfile (optional, prefixed by <, <<, or <[; << always
|
| 886 |
+
precedes a font, <[ always precedes an encoding, < can precede either
|
| 887 |
+
but then an encoding file must have extension .enc; < and << also
|
| 888 |
+
request different font subsetting behaviors but we ignore that; < can
|
| 889 |
+
be separated from the filename by whitespace).
|
| 890 |
+
|
| 891 |
+
special, fontfile, and encodingfile can appear in any order.
|
| 892 |
+
"""
|
| 893 |
+
# If the map file specifies multiple encodings for a font, we
|
| 894 |
+
# follow pdfTeX in choosing the last one specified. Such
|
| 895 |
+
# entries are probably mistakes but they have occurred.
|
| 896 |
+
# https://tex.stackexchange.com/q/10826/
|
| 897 |
+
|
| 898 |
+
if not line or line.startswith((b" ", b"%", b"*", b";", b"#")):
|
| 899 |
+
return
|
| 900 |
+
tfmname = basename = special = encodingfile = fontfile = None
|
| 901 |
+
is_subsetted = is_t1 = is_truetype = False
|
| 902 |
+
matches = re.finditer(br'"([^"]*)(?:"|$)|(\S+)', line)
|
| 903 |
+
for match in matches:
|
| 904 |
+
quoted, unquoted = match.groups()
|
| 905 |
+
if unquoted:
|
| 906 |
+
if unquoted.startswith(b"<<"): # font
|
| 907 |
+
fontfile = unquoted[2:]
|
| 908 |
+
elif unquoted.startswith(b"<["): # encoding
|
| 909 |
+
encodingfile = unquoted[2:]
|
| 910 |
+
elif unquoted.startswith(b"<"): # font or encoding
|
| 911 |
+
word = (
|
| 912 |
+
# <foo => foo
|
| 913 |
+
unquoted[1:]
|
| 914 |
+
# < by itself => read the next word
|
| 915 |
+
or next(filter(None, next(matches).groups())))
|
| 916 |
+
if word.endswith(b".enc"):
|
| 917 |
+
encodingfile = word
|
| 918 |
+
else:
|
| 919 |
+
fontfile = word
|
| 920 |
+
is_subsetted = True
|
| 921 |
+
elif tfmname is None:
|
| 922 |
+
tfmname = unquoted
|
| 923 |
+
elif basename is None:
|
| 924 |
+
basename = unquoted
|
| 925 |
+
elif quoted:
|
| 926 |
+
special = quoted
|
| 927 |
+
effects = {}
|
| 928 |
+
if special:
|
| 929 |
+
words = reversed(special.split())
|
| 930 |
+
for word in words:
|
| 931 |
+
if word == b"SlantFont":
|
| 932 |
+
effects["slant"] = float(next(words))
|
| 933 |
+
elif word == b"ExtendFont":
|
| 934 |
+
effects["extend"] = float(next(words))
|
| 935 |
+
|
| 936 |
+
# Verify some properties of the line that would cause it to be ignored
|
| 937 |
+
# otherwise.
|
| 938 |
+
if fontfile is not None:
|
| 939 |
+
if fontfile.endswith((b".ttf", b".ttc")):
|
| 940 |
+
is_truetype = True
|
| 941 |
+
elif not fontfile.endswith(b".otf"):
|
| 942 |
+
is_t1 = True
|
| 943 |
+
elif basename is not None:
|
| 944 |
+
is_t1 = True
|
| 945 |
+
if is_truetype and is_subsetted and encodingfile is None:
|
| 946 |
+
return
|
| 947 |
+
if not is_t1 and ("slant" in effects or "extend" in effects):
|
| 948 |
+
return
|
| 949 |
+
if abs(effects.get("slant", 0)) > 1:
|
| 950 |
+
return
|
| 951 |
+
if abs(effects.get("extend", 0)) > 2:
|
| 952 |
+
return
|
| 953 |
+
|
| 954 |
+
if basename is None:
|
| 955 |
+
basename = tfmname
|
| 956 |
+
if encodingfile is not None:
|
| 957 |
+
encodingfile = find_tex_file(encodingfile)
|
| 958 |
+
if fontfile is not None:
|
| 959 |
+
fontfile = find_tex_file(fontfile)
|
| 960 |
+
self._parsed[tfmname] = PsFont(
|
| 961 |
+
texname=tfmname, psname=basename, effects=effects,
|
| 962 |
+
encoding=encodingfile, filename=fontfile)
|
| 963 |
+
return True
|
| 964 |
+
|
| 965 |
+
|
| 966 |
+
def _parse_enc(path):
|
| 967 |
+
r"""
|
| 968 |
+
Parse a \*.enc file referenced from a psfonts.map style file.
|
| 969 |
+
|
| 970 |
+
The format supported by this function is a tiny subset of PostScript.
|
| 971 |
+
|
| 972 |
+
Parameters
|
| 973 |
+
----------
|
| 974 |
+
path : `os.PathLike`
|
| 975 |
+
|
| 976 |
+
Returns
|
| 977 |
+
-------
|
| 978 |
+
list
|
| 979 |
+
The nth entry of the list is the PostScript glyph name of the nth
|
| 980 |
+
glyph.
|
| 981 |
+
"""
|
| 982 |
+
no_comments = re.sub("%.*", "", Path(path).read_text(encoding="ascii"))
|
| 983 |
+
array = re.search(r"(?s)\[(.*)\]", no_comments).group(1)
|
| 984 |
+
lines = [line for line in array.split() if line]
|
| 985 |
+
if all(line.startswith("/") for line in lines):
|
| 986 |
+
return [line[1:] for line in lines]
|
| 987 |
+
else:
|
| 988 |
+
raise ValueError(f"Failed to parse {path} as Postscript encoding")
|
| 989 |
+
|
| 990 |
+
|
| 991 |
+
class _LuatexKpsewhich:
|
| 992 |
+
@lru_cache # A singleton.
|
| 993 |
+
def __new__(cls):
|
| 994 |
+
self = object.__new__(cls)
|
| 995 |
+
self._proc = self._new_proc()
|
| 996 |
+
return self
|
| 997 |
+
|
| 998 |
+
def _new_proc(self):
|
| 999 |
+
return subprocess.Popen(
|
| 1000 |
+
["luatex", "--luaonly",
|
| 1001 |
+
str(cbook._get_data_path("kpsewhich.lua"))],
|
| 1002 |
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
| 1003 |
+
|
| 1004 |
+
def search(self, filename):
|
| 1005 |
+
if self._proc.poll() is not None: # Dead, restart it.
|
| 1006 |
+
self._proc = self._new_proc()
|
| 1007 |
+
self._proc.stdin.write(os.fsencode(filename) + b"\n")
|
| 1008 |
+
self._proc.stdin.flush()
|
| 1009 |
+
out = self._proc.stdout.readline().rstrip()
|
| 1010 |
+
return None if out == b"nil" else os.fsdecode(out)
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
@lru_cache
|
| 1014 |
+
def find_tex_file(filename):
|
| 1015 |
+
"""
|
| 1016 |
+
Find a file in the texmf tree using kpathsea_.
|
| 1017 |
+
|
| 1018 |
+
The kpathsea library, provided by most existing TeX distributions, both
|
| 1019 |
+
on Unix-like systems and on Windows (MikTeX), is invoked via a long-lived
|
| 1020 |
+
luatex process if luatex is installed, or via kpsewhich otherwise.
|
| 1021 |
+
|
| 1022 |
+
.. _kpathsea: https://www.tug.org/kpathsea/
|
| 1023 |
+
|
| 1024 |
+
Parameters
|
| 1025 |
+
----------
|
| 1026 |
+
filename : str or path-like
|
| 1027 |
+
|
| 1028 |
+
Raises
|
| 1029 |
+
------
|
| 1030 |
+
FileNotFoundError
|
| 1031 |
+
If the file is not found.
|
| 1032 |
+
"""
|
| 1033 |
+
|
| 1034 |
+
# we expect these to always be ascii encoded, but use utf-8
|
| 1035 |
+
# out of caution
|
| 1036 |
+
if isinstance(filename, bytes):
|
| 1037 |
+
filename = filename.decode('utf-8', errors='replace')
|
| 1038 |
+
|
| 1039 |
+
try:
|
| 1040 |
+
lk = _LuatexKpsewhich()
|
| 1041 |
+
except FileNotFoundError:
|
| 1042 |
+
lk = None # Fallback to directly calling kpsewhich, as below.
|
| 1043 |
+
|
| 1044 |
+
if lk:
|
| 1045 |
+
path = lk.search(filename)
|
| 1046 |
+
else:
|
| 1047 |
+
if sys.platform == 'win32':
|
| 1048 |
+
# On Windows only, kpathsea can use utf-8 for cmd args and output.
|
| 1049 |
+
# The `command_line_encoding` environment variable is set to force
|
| 1050 |
+
# it to always use utf-8 encoding. See Matplotlib issue #11848.
|
| 1051 |
+
kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'},
|
| 1052 |
+
'encoding': 'utf-8'}
|
| 1053 |
+
else: # On POSIX, run through the equivalent of os.fsdecode().
|
| 1054 |
+
kwargs = {'encoding': sys.getfilesystemencoding(),
|
| 1055 |
+
'errors': 'surrogateescape'}
|
| 1056 |
+
|
| 1057 |
+
try:
|
| 1058 |
+
path = (cbook._check_and_log_subprocess(['kpsewhich', filename],
|
| 1059 |
+
_log, **kwargs)
|
| 1060 |
+
.rstrip('\n'))
|
| 1061 |
+
except (FileNotFoundError, RuntimeError):
|
| 1062 |
+
path = None
|
| 1063 |
+
|
| 1064 |
+
if path:
|
| 1065 |
+
return path
|
| 1066 |
+
else:
|
| 1067 |
+
raise FileNotFoundError(
|
| 1068 |
+
f"Matplotlib's TeX implementation searched for a file named "
|
| 1069 |
+
f"{filename!r} in your texmf tree, but could not find it")
|
| 1070 |
+
|
| 1071 |
+
|
| 1072 |
+
@lru_cache
|
| 1073 |
+
def _fontfile(cls, suffix, texname):
|
| 1074 |
+
return cls(find_tex_file(texname + suffix))
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
_tfmfile = partial(_fontfile, Tfm, ".tfm")
|
| 1078 |
+
_vffile = partial(_fontfile, Vf, ".vf")
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
if __name__ == '__main__':
|
| 1082 |
+
from argparse import ArgumentParser
|
| 1083 |
+
import itertools
|
| 1084 |
+
|
| 1085 |
+
parser = ArgumentParser()
|
| 1086 |
+
parser.add_argument("filename")
|
| 1087 |
+
parser.add_argument("dpi", nargs="?", type=float, default=None)
|
| 1088 |
+
args = parser.parse_args()
|
| 1089 |
+
with Dvi(args.filename, args.dpi) as dvi:
|
| 1090 |
+
fontmap = PsfontsMap(find_tex_file('pdftex.map'))
|
| 1091 |
+
for page in dvi:
|
| 1092 |
+
print(f"=== new page === "
|
| 1093 |
+
f"(w: {page.width}, h: {page.height}, d: {page.descent})")
|
| 1094 |
+
for font, group in itertools.groupby(
|
| 1095 |
+
page.text, lambda text: text.font):
|
| 1096 |
+
print(f"font: {font.texname.decode('latin-1')!r}\t"
|
| 1097 |
+
f"scale: {font._scale / 2 ** 20}")
|
| 1098 |
+
print("x", "y", "glyph", "chr", "w", "(glyphs)", sep="\t")
|
| 1099 |
+
for text in group:
|
| 1100 |
+
print(text.x, text.y, text.glyph,
|
| 1101 |
+
chr(text.glyph) if chr(text.glyph).isprintable()
|
| 1102 |
+
else ".",
|
| 1103 |
+
text.width, sep="\t")
|
| 1104 |
+
if page.boxes:
|
| 1105 |
+
print("x", "y", "h", "w", "", "(boxes)", sep="\t")
|
| 1106 |
+
for box in page.boxes:
|
| 1107 |
+
print(box.x, box.y, box.height, box.width, sep="\t")
|
parrot/lib/python3.10/site-packages/matplotlib/dviread.pyi
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import io
|
| 3 |
+
import os
|
| 4 |
+
from enum import Enum
|
| 5 |
+
from collections.abc import Generator
|
| 6 |
+
|
| 7 |
+
from typing import NamedTuple
|
| 8 |
+
|
| 9 |
+
class _dvistate(Enum):
|
| 10 |
+
pre: int
|
| 11 |
+
outer: int
|
| 12 |
+
inpage: int
|
| 13 |
+
post_post: int
|
| 14 |
+
finale: int
|
| 15 |
+
|
| 16 |
+
class Page(NamedTuple):
|
| 17 |
+
text: list[Text]
|
| 18 |
+
boxes: list[Box]
|
| 19 |
+
height: int
|
| 20 |
+
width: int
|
| 21 |
+
descent: int
|
| 22 |
+
|
| 23 |
+
class Box(NamedTuple):
|
| 24 |
+
x: int
|
| 25 |
+
y: int
|
| 26 |
+
height: int
|
| 27 |
+
width: int
|
| 28 |
+
|
| 29 |
+
class Text(NamedTuple):
|
| 30 |
+
x: int
|
| 31 |
+
y: int
|
| 32 |
+
font: DviFont
|
| 33 |
+
glyph: int
|
| 34 |
+
width: int
|
| 35 |
+
@property
|
| 36 |
+
def font_path(self) -> Path: ...
|
| 37 |
+
@property
|
| 38 |
+
def font_size(self) -> float: ...
|
| 39 |
+
@property
|
| 40 |
+
def font_effects(self) -> dict[str, float]: ...
|
| 41 |
+
@property
|
| 42 |
+
def glyph_name_or_index(self) -> int | str: ...
|
| 43 |
+
|
| 44 |
+
class Dvi:
|
| 45 |
+
file: io.BufferedReader
|
| 46 |
+
dpi: float | None
|
| 47 |
+
fonts: dict[int, DviFont]
|
| 48 |
+
state: _dvistate
|
| 49 |
+
def __init__(self, filename: str | os.PathLike, dpi: float | None) -> None: ...
|
| 50 |
+
# Replace return with Self when py3.9 is dropped
|
| 51 |
+
def __enter__(self) -> Dvi: ...
|
| 52 |
+
def __exit__(self, etype, evalue, etrace) -> None: ...
|
| 53 |
+
def __iter__(self) -> Generator[Page, None, None]: ...
|
| 54 |
+
def close(self) -> None: ...
|
| 55 |
+
|
| 56 |
+
class DviFont:
|
| 57 |
+
texname: bytes
|
| 58 |
+
size: float
|
| 59 |
+
widths: list[int]
|
| 60 |
+
def __init__(
|
| 61 |
+
self, scale: float, tfm: Tfm, texname: bytes, vf: Vf | None
|
| 62 |
+
) -> None: ...
|
| 63 |
+
def __eq__(self, other: object) -> bool: ...
|
| 64 |
+
def __ne__(self, other: object) -> bool: ...
|
| 65 |
+
|
| 66 |
+
class Vf(Dvi):
|
| 67 |
+
def __init__(self, filename: str | os.PathLike) -> None: ...
|
| 68 |
+
def __getitem__(self, code: int) -> Page: ...
|
| 69 |
+
|
| 70 |
+
class Tfm:
|
| 71 |
+
checksum: int
|
| 72 |
+
design_size: int
|
| 73 |
+
width: dict[int, int]
|
| 74 |
+
height: dict[int, int]
|
| 75 |
+
depth: dict[int, int]
|
| 76 |
+
def __init__(self, filename: str | os.PathLike) -> None: ...
|
| 77 |
+
|
| 78 |
+
class PsFont(NamedTuple):
|
| 79 |
+
texname: bytes
|
| 80 |
+
psname: bytes
|
| 81 |
+
effects: dict[str, float]
|
| 82 |
+
encoding: None | bytes
|
| 83 |
+
filename: str
|
| 84 |
+
|
| 85 |
+
class PsfontsMap:
|
| 86 |
+
# Replace return with Self when py3.9 is dropped
|
| 87 |
+
def __new__(cls, filename: str | os.PathLike) -> PsfontsMap: ...
|
| 88 |
+
def __getitem__(self, texname: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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import BinaryIO, Literal, TypedDict, overload
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from numpy.typing import NDArray
|
| 5 |
+
|
| 6 |
+
__freetype_build_type__: str
|
| 7 |
+
__freetype_version__: str
|
| 8 |
+
BOLD: int
|
| 9 |
+
EXTERNAL_STREAM: int
|
| 10 |
+
FAST_GLYPHS: int
|
| 11 |
+
FIXED_SIZES: int
|
| 12 |
+
FIXED_WIDTH: int
|
| 13 |
+
GLYPH_NAMES: int
|
| 14 |
+
HORIZONTAL: int
|
| 15 |
+
ITALIC: int
|
| 16 |
+
KERNING: int
|
| 17 |
+
KERNING_DEFAULT: int
|
| 18 |
+
KERNING_UNFITTED: int
|
| 19 |
+
KERNING_UNSCALED: int
|
| 20 |
+
LOAD_CROP_BITMAP: int
|
| 21 |
+
LOAD_DEFAULT: int
|
| 22 |
+
LOAD_FORCE_AUTOHINT: int
|
| 23 |
+
LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH: int
|
| 24 |
+
LOAD_IGNORE_TRANSFORM: int
|
| 25 |
+
LOAD_LINEAR_DESIGN: int
|
| 26 |
+
LOAD_MONOCHROME: int
|
| 27 |
+
LOAD_NO_AUTOHINT: int
|
| 28 |
+
LOAD_NO_BITMAP: int
|
| 29 |
+
LOAD_NO_HINTING: int
|
| 30 |
+
LOAD_NO_RECURSE: int
|
| 31 |
+
LOAD_NO_SCALE: int
|
| 32 |
+
LOAD_PEDANTIC: int
|
| 33 |
+
LOAD_RENDER: int
|
| 34 |
+
LOAD_TARGET_LCD: int
|
| 35 |
+
LOAD_TARGET_LCD_V: int
|
| 36 |
+
LOAD_TARGET_LIGHT: int
|
| 37 |
+
LOAD_TARGET_MONO: int
|
| 38 |
+
LOAD_TARGET_NORMAL: int
|
| 39 |
+
LOAD_VERTICAL_LAYOUT: int
|
| 40 |
+
MULTIPLE_MASTERS: int
|
| 41 |
+
SCALABLE: int
|
| 42 |
+
SFNT: int
|
| 43 |
+
VERTICAL: int
|
| 44 |
+
|
| 45 |
+
class _SfntHeadDict(TypedDict):
|
| 46 |
+
version: tuple[int, int]
|
| 47 |
+
fontRevision: tuple[int, int]
|
| 48 |
+
checkSumAdjustment: int
|
| 49 |
+
magicNumber: int
|
| 50 |
+
flags: int
|
| 51 |
+
unitsPerEm: int
|
| 52 |
+
created: tuple[int, int]
|
| 53 |
+
modified: tuple[int, int]
|
| 54 |
+
xMin: int
|
| 55 |
+
yMin: int
|
| 56 |
+
xMax: int
|
| 57 |
+
yMax: int
|
| 58 |
+
macStyle: int
|
| 59 |
+
lowestRecPPEM: int
|
| 60 |
+
fontDirectionHint: int
|
| 61 |
+
indexToLocFormat: int
|
| 62 |
+
glyphDataFormat: int
|
| 63 |
+
|
| 64 |
+
class _SfntMaxpDict(TypedDict):
|
| 65 |
+
version: tuple[int, int]
|
| 66 |
+
numGlyphs: int
|
| 67 |
+
maxPoints: int
|
| 68 |
+
maxContours: int
|
| 69 |
+
maxComponentPoints: int
|
| 70 |
+
maxComponentContours: int
|
| 71 |
+
maxZones: int
|
| 72 |
+
maxTwilightPoints: int
|
| 73 |
+
maxStorage: int
|
| 74 |
+
maxFunctionDefs: int
|
| 75 |
+
maxInstructionDefs: int
|
| 76 |
+
maxStackElements: int
|
| 77 |
+
maxSizeOfInstructions: int
|
| 78 |
+
maxComponentElements: int
|
| 79 |
+
maxComponentDepth: int
|
| 80 |
+
|
| 81 |
+
class _SfntOs2Dict(TypedDict):
|
| 82 |
+
version: int
|
| 83 |
+
xAvgCharWidth: int
|
| 84 |
+
usWeightClass: int
|
| 85 |
+
usWidthClass: int
|
| 86 |
+
fsType: int
|
| 87 |
+
ySubscriptXSize: int
|
| 88 |
+
ySubscriptYSize: int
|
| 89 |
+
ySubscriptXOffset: int
|
| 90 |
+
ySubscriptYOffset: int
|
| 91 |
+
ySuperscriptXSize: int
|
| 92 |
+
ySuperscriptYSize: int
|
| 93 |
+
ySuperscriptXOffset: int
|
| 94 |
+
ySuperscriptYOffset: int
|
| 95 |
+
yStrikeoutSize: int
|
| 96 |
+
yStrikeoutPosition: int
|
| 97 |
+
sFamilyClass: int
|
| 98 |
+
panose: bytes
|
| 99 |
+
ulCharRange: tuple[int, int, int, int]
|
| 100 |
+
achVendID: bytes
|
| 101 |
+
fsSelection: int
|
| 102 |
+
fsFirstCharIndex: int
|
| 103 |
+
fsLastCharIndex: int
|
| 104 |
+
|
| 105 |
+
class _SfntHheaDict(TypedDict):
|
| 106 |
+
version: tuple[int, int]
|
| 107 |
+
ascent: int
|
| 108 |
+
descent: int
|
| 109 |
+
lineGap: int
|
| 110 |
+
advanceWidthMax: int
|
| 111 |
+
minLeftBearing: int
|
| 112 |
+
minRightBearing: int
|
| 113 |
+
xMaxExtent: int
|
| 114 |
+
caretSlopeRise: int
|
| 115 |
+
caretSlopeRun: int
|
| 116 |
+
caretOffset: int
|
| 117 |
+
metricDataFormat: int
|
| 118 |
+
numOfLongHorMetrics: int
|
| 119 |
+
|
| 120 |
+
class _SfntVheaDict(TypedDict):
|
| 121 |
+
version: tuple[int, int]
|
| 122 |
+
vertTypoAscender: int
|
| 123 |
+
vertTypoDescender: int
|
| 124 |
+
vertTypoLineGap: int
|
| 125 |
+
advanceHeightMax: int
|
| 126 |
+
minTopSideBearing: int
|
| 127 |
+
minBottomSizeBearing: int
|
| 128 |
+
yMaxExtent: int
|
| 129 |
+
caretSlopeRise: int
|
| 130 |
+
caretSlopeRun: int
|
| 131 |
+
caretOffset: int
|
| 132 |
+
metricDataFormat: int
|
| 133 |
+
numOfLongVerMetrics: int
|
| 134 |
+
|
| 135 |
+
class _SfntPostDict(TypedDict):
|
| 136 |
+
format: tuple[int, int]
|
| 137 |
+
italicAngle: tuple[int, int]
|
| 138 |
+
underlinePosition: int
|
| 139 |
+
underlineThickness: int
|
| 140 |
+
isFixedPitch: int
|
| 141 |
+
minMemType42: int
|
| 142 |
+
maxMemType42: int
|
| 143 |
+
minMemType1: int
|
| 144 |
+
maxMemType1: int
|
| 145 |
+
|
| 146 |
+
class _SfntPcltDict(TypedDict):
|
| 147 |
+
version: tuple[int, int]
|
| 148 |
+
fontNumber: int
|
| 149 |
+
pitch: int
|
| 150 |
+
xHeight: int
|
| 151 |
+
style: int
|
| 152 |
+
typeFamily: int
|
| 153 |
+
capHeight: int
|
| 154 |
+
symbolSet: int
|
| 155 |
+
typeFace: bytes
|
| 156 |
+
characterComplement: bytes
|
| 157 |
+
strokeWeight: int
|
| 158 |
+
widthType: int
|
| 159 |
+
serifStyle: int
|
| 160 |
+
|
| 161 |
+
class FT2Font:
|
| 162 |
+
ascender: int
|
| 163 |
+
bbox: tuple[int, int, int, int]
|
| 164 |
+
descender: int
|
| 165 |
+
face_flags: int
|
| 166 |
+
family_name: str
|
| 167 |
+
fname: str
|
| 168 |
+
height: int
|
| 169 |
+
max_advance_height: int
|
| 170 |
+
max_advance_width: int
|
| 171 |
+
num_charmaps: int
|
| 172 |
+
num_faces: int
|
| 173 |
+
num_fixed_sizes: int
|
| 174 |
+
num_glyphs: int
|
| 175 |
+
postscript_name: str
|
| 176 |
+
scalable: bool
|
| 177 |
+
style_flags: int
|
| 178 |
+
style_name: str
|
| 179 |
+
underline_position: int
|
| 180 |
+
underline_thickness: int
|
| 181 |
+
units_per_EM: int
|
| 182 |
+
|
| 183 |
+
def __init__(
|
| 184 |
+
self,
|
| 185 |
+
filename: str | BinaryIO,
|
| 186 |
+
hinting_factor: int = ...,
|
| 187 |
+
*,
|
| 188 |
+
_fallback_list: list[FT2Font] | None = ...,
|
| 189 |
+
_kerning_factor: int = ...
|
| 190 |
+
) -> None: ...
|
| 191 |
+
def _get_fontmap(self, string: str) -> dict[str, FT2Font]: ...
|
| 192 |
+
def clear(self) -> None: ...
|
| 193 |
+
def draw_glyph_to_bitmap(
|
| 194 |
+
self, image: FT2Image, x: float, y: float, glyph: Glyph, antialiased: bool = ...
|
| 195 |
+
) -> None: ...
|
| 196 |
+
def draw_glyphs_to_bitmap(self, antialiased: bool = ...) -> None: ...
|
| 197 |
+
def get_bitmap_offset(self) -> tuple[int, int]: ...
|
| 198 |
+
def get_char_index(self, codepoint: int) -> int: ...
|
| 199 |
+
def get_charmap(self) -> dict[int, int]: ...
|
| 200 |
+
def get_descent(self) -> int: ...
|
| 201 |
+
def get_glyph_name(self, index: int) -> str: ...
|
| 202 |
+
def get_image(self) -> NDArray[np.uint8]: ...
|
| 203 |
+
def get_kerning(self, left: int, right: int, mode: int) -> int: ...
|
| 204 |
+
def get_name_index(self, name: str) -> int: ...
|
| 205 |
+
def get_num_glyphs(self) -> int: ...
|
| 206 |
+
def get_path(self) -> tuple[NDArray[np.float64], NDArray[np.int8]]: ...
|
| 207 |
+
def get_ps_font_info(
|
| 208 |
+
self,
|
| 209 |
+
) -> tuple[str, str, str, str, str, int, int, int, int]: ...
|
| 210 |
+
def get_sfnt(self) -> dict[tuple[int, int, int, int], bytes]: ...
|
| 211 |
+
@overload
|
| 212 |
+
def get_sfnt_table(self, name: Literal["head"]) -> _SfntHeadDict | None: ...
|
| 213 |
+
@overload
|
| 214 |
+
def get_sfnt_table(self, name: Literal["maxp"]) -> _SfntMaxpDict | None: ...
|
| 215 |
+
@overload
|
| 216 |
+
def get_sfnt_table(self, name: Literal["OS/2"]) -> _SfntOs2Dict | None: ...
|
| 217 |
+
@overload
|
| 218 |
+
def get_sfnt_table(self, name: Literal["hhea"]) -> _SfntHheaDict | None: ...
|
| 219 |
+
@overload
|
| 220 |
+
def get_sfnt_table(self, name: Literal["vhea"]) -> _SfntVheaDict | None: ...
|
| 221 |
+
@overload
|
| 222 |
+
def get_sfnt_table(self, name: Literal["post"]) -> _SfntPostDict | None: ...
|
| 223 |
+
@overload
|
| 224 |
+
def get_sfnt_table(self, name: Literal["pclt"]) -> _SfntPcltDict | None: ...
|
| 225 |
+
def get_width_height(self) -> tuple[int, int]: ...
|
| 226 |
+
def get_xys(self, antialiased: bool = ...) -> NDArray[np.float64]: ...
|
| 227 |
+
def load_char(self, charcode: int, flags: int = ...) -> Glyph: ...
|
| 228 |
+
def load_glyph(self, glyphindex: int, flags: int = ...) -> Glyph: ...
|
| 229 |
+
def select_charmap(self, i: int) -> None: ...
|
| 230 |
+
def set_charmap(self, i: int) -> None: ...
|
| 231 |
+
def set_size(self, ptsize: float, dpi: float) -> None: ...
|
| 232 |
+
def set_text(
|
| 233 |
+
self, string: str, angle: float = ..., flags: int = ...
|
| 234 |
+
) -> NDArray[np.float64]: ...
|
| 235 |
+
|
| 236 |
+
class FT2Image: # TODO: When updating mypy>=1.4, subclass from Buffer.
|
| 237 |
+
def __init__(self, width: float, height: float) -> None: ...
|
| 238 |
+
def draw_rect(self, x0: float, y0: float, x1: float, y1: float) -> None: ...
|
| 239 |
+
def draw_rect_filled(self, x0: float, y0: float, x1: float, y1: float) -> None: ...
|
| 240 |
+
|
| 241 |
+
class Glyph:
|
| 242 |
+
width: int
|
| 243 |
+
height: int
|
| 244 |
+
horiBearingX: int
|
| 245 |
+
horiBearingY: int
|
| 246 |
+
horiAdvance: int
|
| 247 |
+
linearHoriAdvance: int
|
| 248 |
+
vertBearingX: int
|
| 249 |
+
vertBearingY: int
|
| 250 |
+
vertAdvance: int
|
| 251 |
+
|
| 252 |
+
@property
|
| 253 |
+
def bbox(self) -> tuple[int, int, int, int]: ...
|
parrot/lib/python3.10/site-packages/matplotlib/gridspec.pyi
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Literal, overload
|
| 2 |
+
|
| 3 |
+
from numpy.typing import ArrayLike
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from matplotlib.axes import Axes, SubplotBase
|
| 7 |
+
from matplotlib.backend_bases import RendererBase
|
| 8 |
+
from matplotlib.figure import Figure
|
| 9 |
+
from matplotlib.transforms import Bbox
|
| 10 |
+
|
| 11 |
+
class GridSpecBase:
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
nrows: int,
|
| 15 |
+
ncols: int,
|
| 16 |
+
height_ratios: ArrayLike | None = ...,
|
| 17 |
+
width_ratios: ArrayLike | None = ...,
|
| 18 |
+
) -> None: ...
|
| 19 |
+
@property
|
| 20 |
+
def nrows(self) -> int: ...
|
| 21 |
+
@property
|
| 22 |
+
def ncols(self) -> int: ...
|
| 23 |
+
def get_geometry(self) -> tuple[int, int]: ...
|
| 24 |
+
def get_subplot_params(self, figure: Figure | None = ...) -> SubplotParams: ...
|
| 25 |
+
def new_subplotspec(
|
| 26 |
+
self, loc: tuple[int, int], rowspan: int = ..., colspan: int = ...
|
| 27 |
+
) -> SubplotSpec: ...
|
| 28 |
+
def set_width_ratios(self, width_ratios: ArrayLike | None) -> None: ...
|
| 29 |
+
def get_width_ratios(self) -> ArrayLike: ...
|
| 30 |
+
def set_height_ratios(self, height_ratios: ArrayLike | None) -> None: ...
|
| 31 |
+
def get_height_ratios(self) -> ArrayLike: ...
|
| 32 |
+
def get_grid_positions(
|
| 33 |
+
self, fig: Figure
|
| 34 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: ...
|
| 35 |
+
@staticmethod
|
| 36 |
+
def _check_gridspec_exists(figure: Figure, nrows: int, ncols: int) -> GridSpec: ...
|
| 37 |
+
def __getitem__(
|
| 38 |
+
self, key: tuple[int | slice, int | slice] | slice | int
|
| 39 |
+
) -> SubplotSpec: ...
|
| 40 |
+
@overload
|
| 41 |
+
def subplots(
|
| 42 |
+
self,
|
| 43 |
+
*,
|
| 44 |
+
sharex: bool | Literal["all", "row", "col", "none"] = ...,
|
| 45 |
+
sharey: bool | Literal["all", "row", "col", "none"] = ...,
|
| 46 |
+
squeeze: Literal[False],
|
| 47 |
+
subplot_kw: dict[str, Any] | None = ...
|
| 48 |
+
) -> np.ndarray: ...
|
| 49 |
+
@overload
|
| 50 |
+
def subplots(
|
| 51 |
+
self,
|
| 52 |
+
*,
|
| 53 |
+
sharex: bool | Literal["all", "row", "col", "none"] = ...,
|
| 54 |
+
sharey: bool | Literal["all", "row", "col", "none"] = ...,
|
| 55 |
+
squeeze: Literal[True] = ...,
|
| 56 |
+
subplot_kw: dict[str, Any] | None = ...
|
| 57 |
+
) -> np.ndarray | Axes: ...
|
| 58 |
+
|
| 59 |
+
class GridSpec(GridSpecBase):
|
| 60 |
+
left: float | None
|
| 61 |
+
bottom: float | None
|
| 62 |
+
right: float | None
|
| 63 |
+
top: float | None
|
| 64 |
+
wspace: float | None
|
| 65 |
+
hspace: float | None
|
| 66 |
+
figure: Figure | None
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
nrows: int,
|
| 70 |
+
ncols: int,
|
| 71 |
+
figure: Figure | None = ...,
|
| 72 |
+
left: float | None = ...,
|
| 73 |
+
bottom: float | None = ...,
|
| 74 |
+
right: float | None = ...,
|
| 75 |
+
top: float | None = ...,
|
| 76 |
+
wspace: float | None = ...,
|
| 77 |
+
hspace: float | None = ...,
|
| 78 |
+
width_ratios: ArrayLike | None = ...,
|
| 79 |
+
height_ratios: ArrayLike | None = ...,
|
| 80 |
+
) -> None: ...
|
| 81 |
+
def update(self, **kwargs: float | None) -> None: ...
|
| 82 |
+
def locally_modified_subplot_params(self) -> list[str]: ...
|
| 83 |
+
def tight_layout(
|
| 84 |
+
self,
|
| 85 |
+
figure: Figure,
|
| 86 |
+
renderer: RendererBase | None = ...,
|
| 87 |
+
pad: float = ...,
|
| 88 |
+
h_pad: float | None = ...,
|
| 89 |
+
w_pad: float | None = ...,
|
| 90 |
+
rect: tuple[float, float, float, float] | None = ...,
|
| 91 |
+
) -> None: ...
|
| 92 |
+
|
| 93 |
+
class GridSpecFromSubplotSpec(GridSpecBase):
|
| 94 |
+
figure: Figure | None
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
nrows: int,
|
| 98 |
+
ncols: int,
|
| 99 |
+
subplot_spec: SubplotSpec,
|
| 100 |
+
wspace: float | None = ...,
|
| 101 |
+
hspace: float | None = ...,
|
| 102 |
+
height_ratios: ArrayLike | None = ...,
|
| 103 |
+
width_ratios: ArrayLike | None = ...,
|
| 104 |
+
) -> None: ...
|
| 105 |
+
def get_topmost_subplotspec(self) -> SubplotSpec: ...
|
| 106 |
+
|
| 107 |
+
class SubplotSpec:
|
| 108 |
+
num1: int
|
| 109 |
+
def __init__(
|
| 110 |
+
self, gridspec: GridSpecBase, num1: int, num2: int | None = ...
|
| 111 |
+
) -> None: ...
|
| 112 |
+
@staticmethod
|
| 113 |
+
def _from_subplot_args(figure, args): ...
|
| 114 |
+
@property
|
| 115 |
+
def num2(self) -> int: ...
|
| 116 |
+
@num2.setter
|
| 117 |
+
def num2(self, value: int) -> None: ...
|
| 118 |
+
def get_gridspec(self) -> GridSpec: ...
|
| 119 |
+
def get_geometry(self) -> tuple[int, int, int, int]: ...
|
| 120 |
+
@property
|
| 121 |
+
def rowspan(self) -> range: ...
|
| 122 |
+
@property
|
| 123 |
+
def colspan(self) -> range: ...
|
| 124 |
+
def is_first_row(self) -> bool: ...
|
| 125 |
+
def is_last_row(self) -> bool: ...
|
| 126 |
+
def is_first_col(self) -> bool: ...
|
| 127 |
+
def is_last_col(self) -> bool: ...
|
| 128 |
+
def get_position(self, figure: Figure) -> Bbox: ...
|
| 129 |
+
def get_topmost_subplotspec(self) -> SubplotSpec: ...
|
| 130 |
+
def __eq__(self, other: object) -> bool: ...
|
| 131 |
+
def __hash__(self) -> int: ...
|
| 132 |
+
def subgridspec(
|
| 133 |
+
self, nrows: int, ncols: int, **kwargs
|
| 134 |
+
) -> GridSpecFromSubplotSpec: ...
|
| 135 |
+
|
| 136 |
+
class SubplotParams:
|
| 137 |
+
def __init__(
|
| 138 |
+
self,
|
| 139 |
+
left: float | None = ...,
|
| 140 |
+
bottom: float | None = ...,
|
| 141 |
+
right: float | None = ...,
|
| 142 |
+
top: float | None = ...,
|
| 143 |
+
wspace: float | None = ...,
|
| 144 |
+
hspace: float | None = ...,
|
| 145 |
+
) -> None: ...
|
| 146 |
+
left: float
|
| 147 |
+
right: float
|
| 148 |
+
bottom: float
|
| 149 |
+
top: float
|
| 150 |
+
wspace: float
|
| 151 |
+
hspace: float
|
| 152 |
+
def update(
|
| 153 |
+
self,
|
| 154 |
+
left: float | None = ...,
|
| 155 |
+
bottom: float | None = ...,
|
| 156 |
+
right: float | None = ...,
|
| 157 |
+
top: float | None = ...,
|
| 158 |
+
wspace: float | None = ...,
|
| 159 |
+
hspace: float | None = ...,
|
| 160 |
+
) -> None: ...
|
parrot/lib/python3.10/site-packages/matplotlib/legend.py
ADDED
|
@@ -0,0 +1,1385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
.. important::
|
| 6 |
+
|
| 7 |
+
It is unlikely that you would ever create a Legend instance manually.
|
| 8 |
+
Most users would normally create a legend via the `~.Axes.legend`
|
| 9 |
+
function. For more details on legends there is also a :ref:`legend guide
|
| 10 |
+
<legend_guide>`.
|
| 11 |
+
|
| 12 |
+
The `Legend` class is a container of legend handles and legend texts.
|
| 13 |
+
|
| 14 |
+
The legend handler map specifies how to create legend handles from artists
|
| 15 |
+
(lines, patches, etc.) in the Axes or figures. Default legend handlers are
|
| 16 |
+
defined in the :mod:`~matplotlib.legend_handler` module. While not all artist
|
| 17 |
+
types are covered by the default legend handlers, custom legend handlers can be
|
| 18 |
+
defined to support arbitrary objects.
|
| 19 |
+
|
| 20 |
+
See the :ref`<legend_guide>` for more
|
| 21 |
+
information.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import itertools
|
| 25 |
+
import logging
|
| 26 |
+
import numbers
|
| 27 |
+
import time
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
import matplotlib as mpl
|
| 32 |
+
from matplotlib import _api, _docstring, cbook, colors, offsetbox
|
| 33 |
+
from matplotlib.artist import Artist, allow_rasterization
|
| 34 |
+
from matplotlib.cbook import silent_list
|
| 35 |
+
from matplotlib.font_manager import FontProperties
|
| 36 |
+
from matplotlib.lines import Line2D
|
| 37 |
+
from matplotlib.patches import (Patch, Rectangle, Shadow, FancyBboxPatch,
|
| 38 |
+
StepPatch)
|
| 39 |
+
from matplotlib.collections import (
|
| 40 |
+
Collection, CircleCollection, LineCollection, PathCollection,
|
| 41 |
+
PolyCollection, RegularPolyCollection)
|
| 42 |
+
from matplotlib.text import Text
|
| 43 |
+
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
|
| 44 |
+
from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
|
| 45 |
+
from matplotlib.offsetbox import (
|
| 46 |
+
AnchoredOffsetbox, DraggableOffsetBox,
|
| 47 |
+
HPacker, VPacker,
|
| 48 |
+
DrawingArea, TextArea,
|
| 49 |
+
)
|
| 50 |
+
from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer
|
| 51 |
+
from . import legend_handler
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class DraggableLegend(DraggableOffsetBox):
|
| 55 |
+
def __init__(self, legend, use_blit=False, update="loc"):
|
| 56 |
+
"""
|
| 57 |
+
Wrapper around a `.Legend` to support mouse dragging.
|
| 58 |
+
|
| 59 |
+
Parameters
|
| 60 |
+
----------
|
| 61 |
+
legend : `.Legend`
|
| 62 |
+
The `.Legend` instance to wrap.
|
| 63 |
+
use_blit : bool, optional
|
| 64 |
+
Use blitting for faster image composition. For details see
|
| 65 |
+
:ref:`func-animation`.
|
| 66 |
+
update : {'loc', 'bbox'}, optional
|
| 67 |
+
If "loc", update the *loc* parameter of the legend upon finalizing.
|
| 68 |
+
If "bbox", update the *bbox_to_anchor* parameter.
|
| 69 |
+
"""
|
| 70 |
+
self.legend = legend
|
| 71 |
+
|
| 72 |
+
_api.check_in_list(["loc", "bbox"], update=update)
|
| 73 |
+
self._update = update
|
| 74 |
+
|
| 75 |
+
super().__init__(legend, legend._legend_box, use_blit=use_blit)
|
| 76 |
+
|
| 77 |
+
def finalize_offset(self):
|
| 78 |
+
if self._update == "loc":
|
| 79 |
+
self._update_loc(self.get_loc_in_canvas())
|
| 80 |
+
elif self._update == "bbox":
|
| 81 |
+
self._update_bbox_to_anchor(self.get_loc_in_canvas())
|
| 82 |
+
|
| 83 |
+
def _update_loc(self, loc_in_canvas):
|
| 84 |
+
bbox = self.legend.get_bbox_to_anchor()
|
| 85 |
+
# if bbox has zero width or height, the transformation is
|
| 86 |
+
# ill-defined. Fall back to the default bbox_to_anchor.
|
| 87 |
+
if bbox.width == 0 or bbox.height == 0:
|
| 88 |
+
self.legend.set_bbox_to_anchor(None)
|
| 89 |
+
bbox = self.legend.get_bbox_to_anchor()
|
| 90 |
+
_bbox_transform = BboxTransformFrom(bbox)
|
| 91 |
+
self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas))
|
| 92 |
+
|
| 93 |
+
def _update_bbox_to_anchor(self, loc_in_canvas):
|
| 94 |
+
loc_in_bbox = self.legend.axes.transAxes.transform(loc_in_canvas)
|
| 95 |
+
self.legend.set_bbox_to_anchor(loc_in_bbox)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
_legend_kw_doc_base = """
|
| 99 |
+
bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
|
| 100 |
+
Box that is used to position the legend in conjunction with *loc*.
|
| 101 |
+
Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or
|
| 102 |
+
`figure.bbox` (if `.Figure.legend`). This argument allows arbitrary
|
| 103 |
+
placement of the legend.
|
| 104 |
+
|
| 105 |
+
Bbox coordinates are interpreted in the coordinate system given by
|
| 106 |
+
*bbox_transform*, with the default transform
|
| 107 |
+
Axes or Figure coordinates, depending on which ``legend`` is called.
|
| 108 |
+
|
| 109 |
+
If a 4-tuple or `.BboxBase` is given, then it specifies the bbox
|
| 110 |
+
``(x, y, width, height)`` that the legend is placed in.
|
| 111 |
+
To put the legend in the best location in the bottom right
|
| 112 |
+
quadrant of the Axes (or figure)::
|
| 113 |
+
|
| 114 |
+
loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
|
| 115 |
+
|
| 116 |
+
A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at
|
| 117 |
+
x, y. For example, to put the legend's upper right-hand corner in the
|
| 118 |
+
center of the Axes (or figure) the following keywords can be used::
|
| 119 |
+
|
| 120 |
+
loc='upper right', bbox_to_anchor=(0.5, 0.5)
|
| 121 |
+
|
| 122 |
+
ncols : int, default: 1
|
| 123 |
+
The number of columns that the legend has.
|
| 124 |
+
|
| 125 |
+
For backward compatibility, the spelling *ncol* is also supported
|
| 126 |
+
but it is discouraged. If both are given, *ncols* takes precedence.
|
| 127 |
+
|
| 128 |
+
prop : None or `~matplotlib.font_manager.FontProperties` or dict
|
| 129 |
+
The font properties of the legend. If None (default), the current
|
| 130 |
+
:data:`matplotlib.rcParams` will be used.
|
| 131 |
+
|
| 132 |
+
fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
|
| 133 |
+
'x-large', 'xx-large'}
|
| 134 |
+
The font size of the legend. If the value is numeric the size will be the
|
| 135 |
+
absolute font size in points. String values are relative to the current
|
| 136 |
+
default font size. This argument is only used if *prop* is not specified.
|
| 137 |
+
|
| 138 |
+
labelcolor : str or list, default: :rc:`legend.labelcolor`
|
| 139 |
+
The color of the text in the legend. Either a valid color string
|
| 140 |
+
(for example, 'red'), or a list of color strings. The labelcolor can
|
| 141 |
+
also be made to match the color of the line or marker using 'linecolor',
|
| 142 |
+
'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').
|
| 143 |
+
|
| 144 |
+
Labelcolor can be set globally using :rc:`legend.labelcolor`. If None,
|
| 145 |
+
use :rc:`text.color`.
|
| 146 |
+
|
| 147 |
+
numpoints : int, default: :rc:`legend.numpoints`
|
| 148 |
+
The number of marker points in the legend when creating a legend
|
| 149 |
+
entry for a `.Line2D` (line).
|
| 150 |
+
|
| 151 |
+
scatterpoints : int, default: :rc:`legend.scatterpoints`
|
| 152 |
+
The number of marker points in the legend when creating
|
| 153 |
+
a legend entry for a `.PathCollection` (scatter plot).
|
| 154 |
+
|
| 155 |
+
scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]``
|
| 156 |
+
The vertical offset (relative to the font size) for the markers
|
| 157 |
+
created for a scatter plot legend entry. 0.0 is at the base the
|
| 158 |
+
legend text, and 1.0 is at the top. To draw all markers at the
|
| 159 |
+
same height, set to ``[0.5]``.
|
| 160 |
+
|
| 161 |
+
markerscale : float, default: :rc:`legend.markerscale`
|
| 162 |
+
The relative size of legend markers compared to the originally drawn ones.
|
| 163 |
+
|
| 164 |
+
markerfirst : bool, default: True
|
| 165 |
+
If *True*, legend marker is placed to the left of the legend label.
|
| 166 |
+
If *False*, legend marker is placed to the right of the legend label.
|
| 167 |
+
|
| 168 |
+
reverse : bool, default: False
|
| 169 |
+
If *True*, the legend labels are displayed in reverse order from the input.
|
| 170 |
+
If *False*, the legend labels are displayed in the same order as the input.
|
| 171 |
+
|
| 172 |
+
.. versionadded:: 3.7
|
| 173 |
+
|
| 174 |
+
frameon : bool, default: :rc:`legend.frameon`
|
| 175 |
+
Whether the legend should be drawn on a patch (frame).
|
| 176 |
+
|
| 177 |
+
fancybox : bool, default: :rc:`legend.fancybox`
|
| 178 |
+
Whether round edges should be enabled around the `.FancyBboxPatch` which
|
| 179 |
+
makes up the legend's background.
|
| 180 |
+
|
| 181 |
+
shadow : None, bool or dict, default: :rc:`legend.shadow`
|
| 182 |
+
Whether to draw a shadow behind the legend.
|
| 183 |
+
The shadow can be configured using `.Patch` keywords.
|
| 184 |
+
Customization via :rc:`legend.shadow` is currently not supported.
|
| 185 |
+
|
| 186 |
+
framealpha : float, default: :rc:`legend.framealpha`
|
| 187 |
+
The alpha transparency of the legend's background.
|
| 188 |
+
If *shadow* is activated and *framealpha* is ``None``, the default value is
|
| 189 |
+
ignored.
|
| 190 |
+
|
| 191 |
+
facecolor : "inherit" or color, default: :rc:`legend.facecolor`
|
| 192 |
+
The legend's background color.
|
| 193 |
+
If ``"inherit"``, use :rc:`axes.facecolor`.
|
| 194 |
+
|
| 195 |
+
edgecolor : "inherit" or color, default: :rc:`legend.edgecolor`
|
| 196 |
+
The legend's background patch edge color.
|
| 197 |
+
If ``"inherit"``, use :rc:`axes.edgecolor`.
|
| 198 |
+
|
| 199 |
+
mode : {"expand", None}
|
| 200 |
+
If *mode* is set to ``"expand"`` the legend will be horizontally
|
| 201 |
+
expanded to fill the Axes area (or *bbox_to_anchor* if defines
|
| 202 |
+
the legend's size).
|
| 203 |
+
|
| 204 |
+
bbox_transform : None or `~matplotlib.transforms.Transform`
|
| 205 |
+
The transform for the bounding box (*bbox_to_anchor*). For a value
|
| 206 |
+
of ``None`` (default) the Axes'
|
| 207 |
+
:data:`~matplotlib.axes.Axes.transAxes` transform will be used.
|
| 208 |
+
|
| 209 |
+
title : str or None
|
| 210 |
+
The legend's title. Default is no title (``None``).
|
| 211 |
+
|
| 212 |
+
title_fontproperties : None or `~matplotlib.font_manager.FontProperties` or dict
|
| 213 |
+
The font properties of the legend's title. If None (default), the
|
| 214 |
+
*title_fontsize* argument will be used if present; if *title_fontsize* is
|
| 215 |
+
also None, the current :rc:`legend.title_fontsize` will be used.
|
| 216 |
+
|
| 217 |
+
title_fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
|
| 218 |
+
'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`
|
| 219 |
+
The font size of the legend's title.
|
| 220 |
+
Note: This cannot be combined with *title_fontproperties*. If you want
|
| 221 |
+
to set the fontsize alongside other font properties, use the *size*
|
| 222 |
+
parameter in *title_fontproperties*.
|
| 223 |
+
|
| 224 |
+
alignment : {'center', 'left', 'right'}, default: 'center'
|
| 225 |
+
The alignment of the legend title and the box of entries. The entries
|
| 226 |
+
are aligned as a single block, so that markers always lined up.
|
| 227 |
+
|
| 228 |
+
borderpad : float, default: :rc:`legend.borderpad`
|
| 229 |
+
The fractional whitespace inside the legend border, in font-size units.
|
| 230 |
+
|
| 231 |
+
labelspacing : float, default: :rc:`legend.labelspacing`
|
| 232 |
+
The vertical space between the legend entries, in font-size units.
|
| 233 |
+
|
| 234 |
+
handlelength : float, default: :rc:`legend.handlelength`
|
| 235 |
+
The length of the legend handles, in font-size units.
|
| 236 |
+
|
| 237 |
+
handleheight : float, default: :rc:`legend.handleheight`
|
| 238 |
+
The height of the legend handles, in font-size units.
|
| 239 |
+
|
| 240 |
+
handletextpad : float, default: :rc:`legend.handletextpad`
|
| 241 |
+
The pad between the legend handle and text, in font-size units.
|
| 242 |
+
|
| 243 |
+
borderaxespad : float, default: :rc:`legend.borderaxespad`
|
| 244 |
+
The pad between the Axes and legend border, in font-size units.
|
| 245 |
+
|
| 246 |
+
columnspacing : float, default: :rc:`legend.columnspacing`
|
| 247 |
+
The spacing between columns, in font-size units.
|
| 248 |
+
|
| 249 |
+
handler_map : dict or None
|
| 250 |
+
The custom dictionary mapping instances or types to a legend
|
| 251 |
+
handler. This *handler_map* updates the default handler map
|
| 252 |
+
found at `matplotlib.legend.Legend.get_legend_handler_map`.
|
| 253 |
+
|
| 254 |
+
draggable : bool, default: False
|
| 255 |
+
Whether the legend can be dragged with the mouse.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
_loc_doc_base = """
|
| 259 |
+
loc : str or pair of floats, default: {default}
|
| 260 |
+
The location of the legend.
|
| 261 |
+
|
| 262 |
+
The strings ``'upper left'``, ``'upper right'``, ``'lower left'``,
|
| 263 |
+
``'lower right'`` place the legend at the corresponding corner of the
|
| 264 |
+
{parent}.
|
| 265 |
+
|
| 266 |
+
The strings ``'upper center'``, ``'lower center'``, ``'center left'``,
|
| 267 |
+
``'center right'`` place the legend at the center of the corresponding edge
|
| 268 |
+
of the {parent}.
|
| 269 |
+
|
| 270 |
+
The string ``'center'`` places the legend at the center of the {parent}.
|
| 271 |
+
{best}
|
| 272 |
+
The location can also be a 2-tuple giving the coordinates of the lower-left
|
| 273 |
+
corner of the legend in {parent} coordinates (in which case *bbox_to_anchor*
|
| 274 |
+
will be ignored).
|
| 275 |
+
|
| 276 |
+
For back-compatibility, ``'center right'`` (but no other location) can also
|
| 277 |
+
be spelled ``'right'``, and each "string" location can also be given as a
|
| 278 |
+
numeric value:
|
| 279 |
+
|
| 280 |
+
================== =============
|
| 281 |
+
Location String Location Code
|
| 282 |
+
================== =============
|
| 283 |
+
'best' (Axes only) 0
|
| 284 |
+
'upper right' 1
|
| 285 |
+
'upper left' 2
|
| 286 |
+
'lower left' 3
|
| 287 |
+
'lower right' 4
|
| 288 |
+
'right' 5
|
| 289 |
+
'center left' 6
|
| 290 |
+
'center right' 7
|
| 291 |
+
'lower center' 8
|
| 292 |
+
'upper center' 9
|
| 293 |
+
'center' 10
|
| 294 |
+
================== =============
|
| 295 |
+
{outside}"""
|
| 296 |
+
|
| 297 |
+
_loc_doc_best = """
|
| 298 |
+
The string ``'best'`` places the legend at the location, among the nine
|
| 299 |
+
locations defined so far, with the minimum overlap with other drawn
|
| 300 |
+
artists. This option can be quite slow for plots with large amounts of
|
| 301 |
+
data; your plotting speed may benefit from providing a specific location.
|
| 302 |
+
"""
|
| 303 |
+
|
| 304 |
+
_legend_kw_axes_st = (
|
| 305 |
+
_loc_doc_base.format(parent='axes', default=':rc:`legend.loc`',
|
| 306 |
+
best=_loc_doc_best, outside='') +
|
| 307 |
+
_legend_kw_doc_base)
|
| 308 |
+
_docstring.interpd.update(_legend_kw_axes=_legend_kw_axes_st)
|
| 309 |
+
|
| 310 |
+
_outside_doc = """
|
| 311 |
+
If a figure is using the constrained layout manager, the string codes
|
| 312 |
+
of the *loc* keyword argument can get better layout behaviour using the
|
| 313 |
+
prefix 'outside'. There is ambiguity at the corners, so 'outside
|
| 314 |
+
upper right' will make space for the legend above the rest of the
|
| 315 |
+
axes in the layout, and 'outside right upper' will make space on the
|
| 316 |
+
right side of the layout. In addition to the values of *loc*
|
| 317 |
+
listed above, we have 'outside right upper', 'outside right lower',
|
| 318 |
+
'outside left upper', and 'outside left lower'. See
|
| 319 |
+
:ref:`legend_guide` for more details.
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
_legend_kw_figure_st = (
|
| 323 |
+
_loc_doc_base.format(parent='figure', default="'upper right'",
|
| 324 |
+
best='', outside=_outside_doc) +
|
| 325 |
+
_legend_kw_doc_base)
|
| 326 |
+
_docstring.interpd.update(_legend_kw_figure=_legend_kw_figure_st)
|
| 327 |
+
|
| 328 |
+
_legend_kw_both_st = (
|
| 329 |
+
_loc_doc_base.format(parent='axes/figure',
|
| 330 |
+
default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
|
| 331 |
+
best=_loc_doc_best, outside=_outside_doc) +
|
| 332 |
+
_legend_kw_doc_base)
|
| 333 |
+
_docstring.interpd.update(_legend_kw_doc=_legend_kw_both_st)
|
| 334 |
+
|
| 335 |
+
_legend_kw_set_loc_st = (
|
| 336 |
+
_loc_doc_base.format(parent='axes/figure',
|
| 337 |
+
default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
|
| 338 |
+
best=_loc_doc_best, outside=_outside_doc))
|
| 339 |
+
_docstring.interpd.update(_legend_kw_set_loc_doc=_legend_kw_set_loc_st)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class Legend(Artist):
|
| 343 |
+
"""
|
| 344 |
+
Place a legend on the figure/axes.
|
| 345 |
+
"""
|
| 346 |
+
|
| 347 |
+
# 'best' is only implemented for Axes legends
|
| 348 |
+
codes = {'best': 0, **AnchoredOffsetbox.codes}
|
| 349 |
+
zorder = 5
|
| 350 |
+
|
| 351 |
+
def __str__(self):
|
| 352 |
+
return "Legend"
|
| 353 |
+
|
| 354 |
+
@_docstring.dedent_interpd
|
| 355 |
+
def __init__(
|
| 356 |
+
self, parent, handles, labels,
|
| 357 |
+
*,
|
| 358 |
+
loc=None,
|
| 359 |
+
numpoints=None, # number of points in the legend line
|
| 360 |
+
markerscale=None, # relative size of legend markers vs. original
|
| 361 |
+
markerfirst=True, # left/right ordering of legend marker and label
|
| 362 |
+
reverse=False, # reverse ordering of legend marker and label
|
| 363 |
+
scatterpoints=None, # number of scatter points
|
| 364 |
+
scatteryoffsets=None,
|
| 365 |
+
prop=None, # properties for the legend texts
|
| 366 |
+
fontsize=None, # keyword to set font size directly
|
| 367 |
+
labelcolor=None, # keyword to set the text color
|
| 368 |
+
|
| 369 |
+
# spacing & pad defined as a fraction of the font-size
|
| 370 |
+
borderpad=None, # whitespace inside the legend border
|
| 371 |
+
labelspacing=None, # vertical space between the legend entries
|
| 372 |
+
handlelength=None, # length of the legend handles
|
| 373 |
+
handleheight=None, # height of the legend handles
|
| 374 |
+
handletextpad=None, # pad between the legend handle and text
|
| 375 |
+
borderaxespad=None, # pad between the Axes and legend border
|
| 376 |
+
columnspacing=None, # spacing between columns
|
| 377 |
+
|
| 378 |
+
ncols=1, # number of columns
|
| 379 |
+
mode=None, # horizontal distribution of columns: None or "expand"
|
| 380 |
+
|
| 381 |
+
fancybox=None, # True: fancy box, False: rounded box, None: rcParam
|
| 382 |
+
shadow=None,
|
| 383 |
+
title=None, # legend title
|
| 384 |
+
title_fontsize=None, # legend title font size
|
| 385 |
+
framealpha=None, # set frame alpha
|
| 386 |
+
edgecolor=None, # frame patch edgecolor
|
| 387 |
+
facecolor=None, # frame patch facecolor
|
| 388 |
+
|
| 389 |
+
bbox_to_anchor=None, # bbox to which the legend will be anchored
|
| 390 |
+
bbox_transform=None, # transform for the bbox
|
| 391 |
+
frameon=None, # draw frame
|
| 392 |
+
handler_map=None,
|
| 393 |
+
title_fontproperties=None, # properties for the legend title
|
| 394 |
+
alignment="center", # control the alignment within the legend box
|
| 395 |
+
ncol=1, # synonym for ncols (backward compatibility)
|
| 396 |
+
draggable=False # whether the legend can be dragged with the mouse
|
| 397 |
+
):
|
| 398 |
+
"""
|
| 399 |
+
Parameters
|
| 400 |
+
----------
|
| 401 |
+
parent : `~matplotlib.axes.Axes` or `.Figure`
|
| 402 |
+
The artist that contains the legend.
|
| 403 |
+
|
| 404 |
+
handles : list of (`.Artist` or tuple of `.Artist`)
|
| 405 |
+
A list of Artists (lines, patches) to be added to the legend.
|
| 406 |
+
|
| 407 |
+
labels : list of str
|
| 408 |
+
A list of labels to show next to the artists. The length of handles
|
| 409 |
+
and labels should be the same. If they are not, they are truncated
|
| 410 |
+
to the length of the shorter list.
|
| 411 |
+
|
| 412 |
+
Other Parameters
|
| 413 |
+
----------------
|
| 414 |
+
%(_legend_kw_doc)s
|
| 415 |
+
|
| 416 |
+
Attributes
|
| 417 |
+
----------
|
| 418 |
+
legend_handles
|
| 419 |
+
List of `.Artist` objects added as legend entries.
|
| 420 |
+
|
| 421 |
+
.. versionadded:: 3.7
|
| 422 |
+
"""
|
| 423 |
+
# local import only to avoid circularity
|
| 424 |
+
from matplotlib.axes import Axes
|
| 425 |
+
from matplotlib.figure import FigureBase
|
| 426 |
+
|
| 427 |
+
super().__init__()
|
| 428 |
+
|
| 429 |
+
if prop is None:
|
| 430 |
+
self.prop = FontProperties(size=mpl._val_or_rc(fontsize, "legend.fontsize"))
|
| 431 |
+
else:
|
| 432 |
+
self.prop = FontProperties._from_any(prop)
|
| 433 |
+
if isinstance(prop, dict) and "size" not in prop:
|
| 434 |
+
self.prop.set_size(mpl.rcParams["legend.fontsize"])
|
| 435 |
+
|
| 436 |
+
self._fontsize = self.prop.get_size_in_points()
|
| 437 |
+
|
| 438 |
+
self.texts = []
|
| 439 |
+
self.legend_handles = []
|
| 440 |
+
self._legend_title_box = None
|
| 441 |
+
|
| 442 |
+
#: A dictionary with the extra handler mappings for this Legend
|
| 443 |
+
#: instance.
|
| 444 |
+
self._custom_handler_map = handler_map
|
| 445 |
+
|
| 446 |
+
self.numpoints = mpl._val_or_rc(numpoints, 'legend.numpoints')
|
| 447 |
+
self.markerscale = mpl._val_or_rc(markerscale, 'legend.markerscale')
|
| 448 |
+
self.scatterpoints = mpl._val_or_rc(scatterpoints, 'legend.scatterpoints')
|
| 449 |
+
self.borderpad = mpl._val_or_rc(borderpad, 'legend.borderpad')
|
| 450 |
+
self.labelspacing = mpl._val_or_rc(labelspacing, 'legend.labelspacing')
|
| 451 |
+
self.handlelength = mpl._val_or_rc(handlelength, 'legend.handlelength')
|
| 452 |
+
self.handleheight = mpl._val_or_rc(handleheight, 'legend.handleheight')
|
| 453 |
+
self.handletextpad = mpl._val_or_rc(handletextpad, 'legend.handletextpad')
|
| 454 |
+
self.borderaxespad = mpl._val_or_rc(borderaxespad, 'legend.borderaxespad')
|
| 455 |
+
self.columnspacing = mpl._val_or_rc(columnspacing, 'legend.columnspacing')
|
| 456 |
+
self.shadow = mpl._val_or_rc(shadow, 'legend.shadow')
|
| 457 |
+
# trim handles and labels if illegal label...
|
| 458 |
+
_lab, _hand = [], []
|
| 459 |
+
for label, handle in zip(labels, handles):
|
| 460 |
+
if isinstance(label, str) and label.startswith('_'):
|
| 461 |
+
_api.warn_deprecated("3.8", message=(
|
| 462 |
+
"An artist whose label starts with an underscore was passed to "
|
| 463 |
+
"legend(); such artists will no longer be ignored in the future. "
|
| 464 |
+
"To suppress this warning, explicitly filter out such artists, "
|
| 465 |
+
"e.g. with `[art for art in artists if not "
|
| 466 |
+
"art.get_label().startswith('_')]`."))
|
| 467 |
+
else:
|
| 468 |
+
_lab.append(label)
|
| 469 |
+
_hand.append(handle)
|
| 470 |
+
labels, handles = _lab, _hand
|
| 471 |
+
|
| 472 |
+
if reverse:
|
| 473 |
+
labels.reverse()
|
| 474 |
+
handles.reverse()
|
| 475 |
+
|
| 476 |
+
if len(handles) < 2:
|
| 477 |
+
ncols = 1
|
| 478 |
+
self._ncols = ncols if ncols != 1 else ncol
|
| 479 |
+
|
| 480 |
+
if self.numpoints <= 0:
|
| 481 |
+
raise ValueError("numpoints must be > 0; it was %d" % numpoints)
|
| 482 |
+
|
| 483 |
+
# introduce y-offset for handles of the scatter plot
|
| 484 |
+
if scatteryoffsets is None:
|
| 485 |
+
self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
|
| 486 |
+
else:
|
| 487 |
+
self._scatteryoffsets = np.asarray(scatteryoffsets)
|
| 488 |
+
reps = self.scatterpoints // len(self._scatteryoffsets) + 1
|
| 489 |
+
self._scatteryoffsets = np.tile(self._scatteryoffsets,
|
| 490 |
+
reps)[:self.scatterpoints]
|
| 491 |
+
|
| 492 |
+
# _legend_box is a VPacker instance that contains all
|
| 493 |
+
# legend items and will be initialized from _init_legend_box()
|
| 494 |
+
# method.
|
| 495 |
+
self._legend_box = None
|
| 496 |
+
|
| 497 |
+
if isinstance(parent, Axes):
|
| 498 |
+
self.isaxes = True
|
| 499 |
+
self.axes = parent
|
| 500 |
+
self.set_figure(parent.figure)
|
| 501 |
+
elif isinstance(parent, FigureBase):
|
| 502 |
+
self.isaxes = False
|
| 503 |
+
self.set_figure(parent)
|
| 504 |
+
else:
|
| 505 |
+
raise TypeError(
|
| 506 |
+
"Legend needs either Axes or FigureBase as parent"
|
| 507 |
+
)
|
| 508 |
+
self.parent = parent
|
| 509 |
+
|
| 510 |
+
self._mode = mode
|
| 511 |
+
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
|
| 512 |
+
|
| 513 |
+
# Figure out if self.shadow is valid
|
| 514 |
+
# If shadow was None, rcParams loads False
|
| 515 |
+
# So it shouldn't be None here
|
| 516 |
+
|
| 517 |
+
self._shadow_props = {'ox': 2, 'oy': -2} # default location offsets
|
| 518 |
+
if isinstance(self.shadow, dict):
|
| 519 |
+
self._shadow_props.update(self.shadow)
|
| 520 |
+
self.shadow = True
|
| 521 |
+
elif self.shadow in (0, 1, True, False):
|
| 522 |
+
self.shadow = bool(self.shadow)
|
| 523 |
+
else:
|
| 524 |
+
raise ValueError(
|
| 525 |
+
'Legend shadow must be a dict or bool, not '
|
| 526 |
+
f'{self.shadow!r} of type {type(self.shadow)}.'
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# We use FancyBboxPatch to draw a legend frame. The location
|
| 530 |
+
# and size of the box will be updated during the drawing time.
|
| 531 |
+
|
| 532 |
+
facecolor = mpl._val_or_rc(facecolor, "legend.facecolor")
|
| 533 |
+
if facecolor == 'inherit':
|
| 534 |
+
facecolor = mpl.rcParams["axes.facecolor"]
|
| 535 |
+
|
| 536 |
+
edgecolor = mpl._val_or_rc(edgecolor, "legend.edgecolor")
|
| 537 |
+
if edgecolor == 'inherit':
|
| 538 |
+
edgecolor = mpl.rcParams["axes.edgecolor"]
|
| 539 |
+
|
| 540 |
+
fancybox = mpl._val_or_rc(fancybox, "legend.fancybox")
|
| 541 |
+
|
| 542 |
+
self.legendPatch = FancyBboxPatch(
|
| 543 |
+
xy=(0, 0), width=1, height=1,
|
| 544 |
+
facecolor=facecolor, edgecolor=edgecolor,
|
| 545 |
+
# If shadow is used, default to alpha=1 (#8943).
|
| 546 |
+
alpha=(framealpha if framealpha is not None
|
| 547 |
+
else 1 if shadow
|
| 548 |
+
else mpl.rcParams["legend.framealpha"]),
|
| 549 |
+
# The width and height of the legendPatch will be set (in draw())
|
| 550 |
+
# to the length that includes the padding. Thus we set pad=0 here.
|
| 551 |
+
boxstyle=("round,pad=0,rounding_size=0.2" if fancybox
|
| 552 |
+
else "square,pad=0"),
|
| 553 |
+
mutation_scale=self._fontsize,
|
| 554 |
+
snap=True,
|
| 555 |
+
visible=mpl._val_or_rc(frameon, "legend.frameon")
|
| 556 |
+
)
|
| 557 |
+
self._set_artist_props(self.legendPatch)
|
| 558 |
+
|
| 559 |
+
_api.check_in_list(["center", "left", "right"], alignment=alignment)
|
| 560 |
+
self._alignment = alignment
|
| 561 |
+
|
| 562 |
+
# init with null renderer
|
| 563 |
+
self._init_legend_box(handles, labels, markerfirst)
|
| 564 |
+
|
| 565 |
+
# Set legend location
|
| 566 |
+
self.set_loc(loc)
|
| 567 |
+
|
| 568 |
+
# figure out title font properties:
|
| 569 |
+
if title_fontsize is not None and title_fontproperties is not None:
|
| 570 |
+
raise ValueError(
|
| 571 |
+
"title_fontsize and title_fontproperties can't be specified "
|
| 572 |
+
"at the same time. Only use one of them. ")
|
| 573 |
+
title_prop_fp = FontProperties._from_any(title_fontproperties)
|
| 574 |
+
if isinstance(title_fontproperties, dict):
|
| 575 |
+
if "size" not in title_fontproperties:
|
| 576 |
+
title_fontsize = mpl.rcParams["legend.title_fontsize"]
|
| 577 |
+
title_prop_fp.set_size(title_fontsize)
|
| 578 |
+
elif title_fontsize is not None:
|
| 579 |
+
title_prop_fp.set_size(title_fontsize)
|
| 580 |
+
elif not isinstance(title_fontproperties, FontProperties):
|
| 581 |
+
title_fontsize = mpl.rcParams["legend.title_fontsize"]
|
| 582 |
+
title_prop_fp.set_size(title_fontsize)
|
| 583 |
+
|
| 584 |
+
self.set_title(title, prop=title_prop_fp)
|
| 585 |
+
|
| 586 |
+
self._draggable = None
|
| 587 |
+
self.set_draggable(state=draggable)
|
| 588 |
+
|
| 589 |
+
# set the text color
|
| 590 |
+
|
| 591 |
+
color_getters = { # getter function depends on line or patch
|
| 592 |
+
'linecolor': ['get_color', 'get_facecolor'],
|
| 593 |
+
'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
|
| 594 |
+
'mfc': ['get_markerfacecolor', 'get_facecolor'],
|
| 595 |
+
'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
|
| 596 |
+
'mec': ['get_markeredgecolor', 'get_edgecolor'],
|
| 597 |
+
}
|
| 598 |
+
labelcolor = mpl._val_or_rc(labelcolor, 'legend.labelcolor')
|
| 599 |
+
if labelcolor is None:
|
| 600 |
+
labelcolor = mpl.rcParams['text.color']
|
| 601 |
+
if isinstance(labelcolor, str) and labelcolor in color_getters:
|
| 602 |
+
getter_names = color_getters[labelcolor]
|
| 603 |
+
for handle, text in zip(self.legend_handles, self.texts):
|
| 604 |
+
try:
|
| 605 |
+
if handle.get_array() is not None:
|
| 606 |
+
continue
|
| 607 |
+
except AttributeError:
|
| 608 |
+
pass
|
| 609 |
+
for getter_name in getter_names:
|
| 610 |
+
try:
|
| 611 |
+
color = getattr(handle, getter_name)()
|
| 612 |
+
if isinstance(color, np.ndarray):
|
| 613 |
+
if (
|
| 614 |
+
color.shape[0] == 1
|
| 615 |
+
or np.isclose(color, color[0]).all()
|
| 616 |
+
):
|
| 617 |
+
text.set_color(color[0])
|
| 618 |
+
else:
|
| 619 |
+
pass
|
| 620 |
+
else:
|
| 621 |
+
text.set_color(color)
|
| 622 |
+
break
|
| 623 |
+
except AttributeError:
|
| 624 |
+
pass
|
| 625 |
+
elif cbook._str_equal(labelcolor, 'none'):
|
| 626 |
+
for text in self.texts:
|
| 627 |
+
text.set_color(labelcolor)
|
| 628 |
+
elif np.iterable(labelcolor):
|
| 629 |
+
for text, color in zip(self.texts,
|
| 630 |
+
itertools.cycle(
|
| 631 |
+
colors.to_rgba_array(labelcolor))):
|
| 632 |
+
text.set_color(color)
|
| 633 |
+
else:
|
| 634 |
+
raise ValueError(f"Invalid labelcolor: {labelcolor!r}")
|
| 635 |
+
|
| 636 |
+
def _set_artist_props(self, a):
|
| 637 |
+
"""
|
| 638 |
+
Set the boilerplate props for artists added to Axes.
|
| 639 |
+
"""
|
| 640 |
+
a.set_figure(self.figure)
|
| 641 |
+
if self.isaxes:
|
| 642 |
+
a.axes = self.axes
|
| 643 |
+
|
| 644 |
+
a.set_transform(self.get_transform())
|
| 645 |
+
|
| 646 |
+
@_docstring.dedent_interpd
|
| 647 |
+
def set_loc(self, loc=None):
|
| 648 |
+
"""
|
| 649 |
+
Set the location of the legend.
|
| 650 |
+
|
| 651 |
+
.. versionadded:: 3.8
|
| 652 |
+
|
| 653 |
+
Parameters
|
| 654 |
+
----------
|
| 655 |
+
%(_legend_kw_set_loc_doc)s
|
| 656 |
+
"""
|
| 657 |
+
loc0 = loc
|
| 658 |
+
self._loc_used_default = loc is None
|
| 659 |
+
if loc is None:
|
| 660 |
+
loc = mpl.rcParams["legend.loc"]
|
| 661 |
+
if not self.isaxes and loc in [0, 'best']:
|
| 662 |
+
loc = 'upper right'
|
| 663 |
+
|
| 664 |
+
type_err_message = ("loc must be string, coordinate tuple, or"
|
| 665 |
+
f" an integer 0-10, not {loc!r}")
|
| 666 |
+
|
| 667 |
+
# handle outside legends:
|
| 668 |
+
self._outside_loc = None
|
| 669 |
+
if isinstance(loc, str):
|
| 670 |
+
if loc.split()[0] == 'outside':
|
| 671 |
+
# strip outside:
|
| 672 |
+
loc = loc.split('outside ')[1]
|
| 673 |
+
# strip "center" at the beginning
|
| 674 |
+
self._outside_loc = loc.replace('center ', '')
|
| 675 |
+
# strip first
|
| 676 |
+
self._outside_loc = self._outside_loc.split()[0]
|
| 677 |
+
locs = loc.split()
|
| 678 |
+
if len(locs) > 1 and locs[0] in ('right', 'left'):
|
| 679 |
+
# locs doesn't accept "left upper", etc, so swap
|
| 680 |
+
if locs[0] != 'center':
|
| 681 |
+
locs = locs[::-1]
|
| 682 |
+
loc = locs[0] + ' ' + locs[1]
|
| 683 |
+
# check that loc is in acceptable strings
|
| 684 |
+
loc = _api.check_getitem(self.codes, loc=loc)
|
| 685 |
+
elif np.iterable(loc):
|
| 686 |
+
# coerce iterable into tuple
|
| 687 |
+
loc = tuple(loc)
|
| 688 |
+
# validate the tuple represents Real coordinates
|
| 689 |
+
if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc):
|
| 690 |
+
raise ValueError(type_err_message)
|
| 691 |
+
elif isinstance(loc, int):
|
| 692 |
+
# validate the integer represents a string numeric value
|
| 693 |
+
if loc < 0 or loc > 10:
|
| 694 |
+
raise ValueError(type_err_message)
|
| 695 |
+
else:
|
| 696 |
+
# all other cases are invalid values of loc
|
| 697 |
+
raise ValueError(type_err_message)
|
| 698 |
+
|
| 699 |
+
if self.isaxes and self._outside_loc:
|
| 700 |
+
raise ValueError(
|
| 701 |
+
f"'outside' option for loc='{loc0}' keyword argument only "
|
| 702 |
+
"works for figure legends")
|
| 703 |
+
|
| 704 |
+
if not self.isaxes and loc == 0:
|
| 705 |
+
raise ValueError(
|
| 706 |
+
"Automatic legend placement (loc='best') not implemented for "
|
| 707 |
+
"figure legend")
|
| 708 |
+
|
| 709 |
+
tmp = self._loc_used_default
|
| 710 |
+
self._set_loc(loc)
|
| 711 |
+
self._loc_used_default = tmp # ignore changes done by _set_loc
|
| 712 |
+
|
| 713 |
+
def _set_loc(self, loc):
|
| 714 |
+
# find_offset function will be provided to _legend_box and
|
| 715 |
+
# _legend_box will draw itself at the location of the return
|
| 716 |
+
# value of the find_offset.
|
| 717 |
+
self._loc_used_default = False
|
| 718 |
+
self._loc_real = loc
|
| 719 |
+
self.stale = True
|
| 720 |
+
self._legend_box.set_offset(self._findoffset)
|
| 721 |
+
|
| 722 |
+
def set_ncols(self, ncols):
|
| 723 |
+
"""Set the number of columns."""
|
| 724 |
+
self._ncols = ncols
|
| 725 |
+
|
| 726 |
+
def _get_loc(self):
|
| 727 |
+
return self._loc_real
|
| 728 |
+
|
| 729 |
+
_loc = property(_get_loc, _set_loc)
|
| 730 |
+
|
| 731 |
+
def _findoffset(self, width, height, xdescent, ydescent, renderer):
|
| 732 |
+
"""Helper function to locate the legend."""
|
| 733 |
+
|
| 734 |
+
if self._loc == 0: # "best".
|
| 735 |
+
x, y = self._find_best_position(width, height, renderer)
|
| 736 |
+
elif self._loc in Legend.codes.values(): # Fixed location.
|
| 737 |
+
bbox = Bbox.from_bounds(0, 0, width, height)
|
| 738 |
+
x, y = self._get_anchored_bbox(self._loc, bbox,
|
| 739 |
+
self.get_bbox_to_anchor(),
|
| 740 |
+
renderer)
|
| 741 |
+
else: # Axes or figure coordinates.
|
| 742 |
+
fx, fy = self._loc
|
| 743 |
+
bbox = self.get_bbox_to_anchor()
|
| 744 |
+
x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
|
| 745 |
+
|
| 746 |
+
return x + xdescent, y + ydescent
|
| 747 |
+
|
| 748 |
+
@allow_rasterization
|
| 749 |
+
def draw(self, renderer):
|
| 750 |
+
# docstring inherited
|
| 751 |
+
if not self.get_visible():
|
| 752 |
+
return
|
| 753 |
+
|
| 754 |
+
renderer.open_group('legend', gid=self.get_gid())
|
| 755 |
+
|
| 756 |
+
fontsize = renderer.points_to_pixels(self._fontsize)
|
| 757 |
+
|
| 758 |
+
# if mode == fill, set the width of the legend_box to the
|
| 759 |
+
# width of the parent (minus pads)
|
| 760 |
+
if self._mode in ["expand"]:
|
| 761 |
+
pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
|
| 762 |
+
self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
|
| 763 |
+
|
| 764 |
+
# update the location and size of the legend. This needs to
|
| 765 |
+
# be done in any case to clip the figure right.
|
| 766 |
+
bbox = self._legend_box.get_window_extent(renderer)
|
| 767 |
+
self.legendPatch.set_bounds(bbox.bounds)
|
| 768 |
+
self.legendPatch.set_mutation_scale(fontsize)
|
| 769 |
+
|
| 770 |
+
# self.shadow is validated in __init__
|
| 771 |
+
# So by here it is a bool and self._shadow_props contains any configs
|
| 772 |
+
|
| 773 |
+
if self.shadow:
|
| 774 |
+
Shadow(self.legendPatch, **self._shadow_props).draw(renderer)
|
| 775 |
+
|
| 776 |
+
self.legendPatch.draw(renderer)
|
| 777 |
+
self._legend_box.draw(renderer)
|
| 778 |
+
|
| 779 |
+
renderer.close_group('legend')
|
| 780 |
+
self.stale = False
|
| 781 |
+
|
| 782 |
+
# _default_handler_map defines the default mapping between plot
|
| 783 |
+
# elements and the legend handlers.
|
| 784 |
+
|
| 785 |
+
_default_handler_map = {
|
| 786 |
+
StemContainer: legend_handler.HandlerStem(),
|
| 787 |
+
ErrorbarContainer: legend_handler.HandlerErrorbar(),
|
| 788 |
+
Line2D: legend_handler.HandlerLine2D(),
|
| 789 |
+
Patch: legend_handler.HandlerPatch(),
|
| 790 |
+
StepPatch: legend_handler.HandlerStepPatch(),
|
| 791 |
+
LineCollection: legend_handler.HandlerLineCollection(),
|
| 792 |
+
RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
|
| 793 |
+
CircleCollection: legend_handler.HandlerCircleCollection(),
|
| 794 |
+
BarContainer: legend_handler.HandlerPatch(
|
| 795 |
+
update_func=legend_handler.update_from_first_child),
|
| 796 |
+
tuple: legend_handler.HandlerTuple(),
|
| 797 |
+
PathCollection: legend_handler.HandlerPathCollection(),
|
| 798 |
+
PolyCollection: legend_handler.HandlerPolyCollection()
|
| 799 |
+
}
|
| 800 |
+
|
| 801 |
+
# (get|set|update)_default_handler_maps are public interfaces to
|
| 802 |
+
# modify the default handler map.
|
| 803 |
+
|
| 804 |
+
@classmethod
|
| 805 |
+
def get_default_handler_map(cls):
|
| 806 |
+
"""Return the global default handler map, shared by all legends."""
|
| 807 |
+
return cls._default_handler_map
|
| 808 |
+
|
| 809 |
+
@classmethod
|
| 810 |
+
def set_default_handler_map(cls, handler_map):
|
| 811 |
+
"""Set the global default handler map, shared by all legends."""
|
| 812 |
+
cls._default_handler_map = handler_map
|
| 813 |
+
|
| 814 |
+
@classmethod
|
| 815 |
+
def update_default_handler_map(cls, handler_map):
|
| 816 |
+
"""Update the global default handler map, shared by all legends."""
|
| 817 |
+
cls._default_handler_map.update(handler_map)
|
| 818 |
+
|
| 819 |
+
def get_legend_handler_map(self):
|
| 820 |
+
"""Return this legend instance's handler map."""
|
| 821 |
+
default_handler_map = self.get_default_handler_map()
|
| 822 |
+
return ({**default_handler_map, **self._custom_handler_map}
|
| 823 |
+
if self._custom_handler_map else default_handler_map)
|
| 824 |
+
|
| 825 |
+
@staticmethod
|
| 826 |
+
def get_legend_handler(legend_handler_map, orig_handle):
|
| 827 |
+
"""
|
| 828 |
+
Return a legend handler from *legend_handler_map* that
|
| 829 |
+
corresponds to *orig_handler*.
|
| 830 |
+
|
| 831 |
+
*legend_handler_map* should be a dictionary object (that is
|
| 832 |
+
returned by the get_legend_handler_map method).
|
| 833 |
+
|
| 834 |
+
It first checks if the *orig_handle* itself is a key in the
|
| 835 |
+
*legend_handler_map* and return the associated value.
|
| 836 |
+
Otherwise, it checks for each of the classes in its
|
| 837 |
+
method-resolution-order. If no matching key is found, it
|
| 838 |
+
returns ``None``.
|
| 839 |
+
"""
|
| 840 |
+
try:
|
| 841 |
+
return legend_handler_map[orig_handle]
|
| 842 |
+
except (TypeError, KeyError): # TypeError if unhashable.
|
| 843 |
+
pass
|
| 844 |
+
for handle_type in type(orig_handle).mro():
|
| 845 |
+
try:
|
| 846 |
+
return legend_handler_map[handle_type]
|
| 847 |
+
except KeyError:
|
| 848 |
+
pass
|
| 849 |
+
return None
|
| 850 |
+
|
| 851 |
+
def _init_legend_box(self, handles, labels, markerfirst=True):
|
| 852 |
+
"""
|
| 853 |
+
Initialize the legend_box. The legend_box is an instance of
|
| 854 |
+
the OffsetBox, which is packed with legend handles and
|
| 855 |
+
texts. Once packed, their location is calculated during the
|
| 856 |
+
drawing time.
|
| 857 |
+
"""
|
| 858 |
+
|
| 859 |
+
fontsize = self._fontsize
|
| 860 |
+
|
| 861 |
+
# legend_box is a HPacker, horizontally packed with columns.
|
| 862 |
+
# Each column is a VPacker, vertically packed with legend items.
|
| 863 |
+
# Each legend item is a HPacker packed with:
|
| 864 |
+
# - handlebox: a DrawingArea which contains the legend handle.
|
| 865 |
+
# - labelbox: a TextArea which contains the legend text.
|
| 866 |
+
|
| 867 |
+
text_list = [] # the list of text instances
|
| 868 |
+
handle_list = [] # the list of handle instances
|
| 869 |
+
handles_and_labels = []
|
| 870 |
+
|
| 871 |
+
# The approximate height and descent of text. These values are
|
| 872 |
+
# only used for plotting the legend handle.
|
| 873 |
+
descent = 0.35 * fontsize * (self.handleheight - 0.7) # heuristic.
|
| 874 |
+
height = fontsize * self.handleheight - descent
|
| 875 |
+
# each handle needs to be drawn inside a box of (x, y, w, h) =
|
| 876 |
+
# (0, -descent, width, height). And their coordinates should
|
| 877 |
+
# be given in the display coordinates.
|
| 878 |
+
|
| 879 |
+
# The transformation of each handle will be automatically set
|
| 880 |
+
# to self.get_transform(). If the artist does not use its
|
| 881 |
+
# default transform (e.g., Collections), you need to
|
| 882 |
+
# manually set their transform to the self.get_transform().
|
| 883 |
+
legend_handler_map = self.get_legend_handler_map()
|
| 884 |
+
|
| 885 |
+
for orig_handle, label in zip(handles, labels):
|
| 886 |
+
handler = self.get_legend_handler(legend_handler_map, orig_handle)
|
| 887 |
+
if handler is None:
|
| 888 |
+
_api.warn_external(
|
| 889 |
+
"Legend does not support handles for "
|
| 890 |
+
f"{type(orig_handle).__name__} "
|
| 891 |
+
"instances.\nA proxy artist may be used "
|
| 892 |
+
"instead.\nSee: https://matplotlib.org/"
|
| 893 |
+
"stable/users/explain/axes/legend_guide.html"
|
| 894 |
+
"#controlling-the-legend-entries")
|
| 895 |
+
# No handle for this artist, so we just defer to None.
|
| 896 |
+
handle_list.append(None)
|
| 897 |
+
else:
|
| 898 |
+
textbox = TextArea(label, multilinebaseline=True,
|
| 899 |
+
textprops=dict(
|
| 900 |
+
verticalalignment='baseline',
|
| 901 |
+
horizontalalignment='left',
|
| 902 |
+
fontproperties=self.prop))
|
| 903 |
+
handlebox = DrawingArea(width=self.handlelength * fontsize,
|
| 904 |
+
height=height,
|
| 905 |
+
xdescent=0., ydescent=descent)
|
| 906 |
+
|
| 907 |
+
text_list.append(textbox._text)
|
| 908 |
+
# Create the artist for the legend which represents the
|
| 909 |
+
# original artist/handle.
|
| 910 |
+
handle_list.append(handler.legend_artist(self, orig_handle,
|
| 911 |
+
fontsize, handlebox))
|
| 912 |
+
handles_and_labels.append((handlebox, textbox))
|
| 913 |
+
|
| 914 |
+
columnbox = []
|
| 915 |
+
# array_split splits n handles_and_labels into ncols columns, with the
|
| 916 |
+
# first n%ncols columns having an extra entry. filter(len, ...)
|
| 917 |
+
# handles the case where n < ncols: the last ncols-n columns are empty
|
| 918 |
+
# and get filtered out.
|
| 919 |
+
for handles_and_labels_column in filter(
|
| 920 |
+
len, np.array_split(handles_and_labels, self._ncols)):
|
| 921 |
+
# pack handlebox and labelbox into itembox
|
| 922 |
+
itemboxes = [HPacker(pad=0,
|
| 923 |
+
sep=self.handletextpad * fontsize,
|
| 924 |
+
children=[h, t] if markerfirst else [t, h],
|
| 925 |
+
align="baseline")
|
| 926 |
+
for h, t in handles_and_labels_column]
|
| 927 |
+
# pack columnbox
|
| 928 |
+
alignment = "baseline" if markerfirst else "right"
|
| 929 |
+
columnbox.append(VPacker(pad=0,
|
| 930 |
+
sep=self.labelspacing * fontsize,
|
| 931 |
+
align=alignment,
|
| 932 |
+
children=itemboxes))
|
| 933 |
+
|
| 934 |
+
mode = "expand" if self._mode == "expand" else "fixed"
|
| 935 |
+
sep = self.columnspacing * fontsize
|
| 936 |
+
self._legend_handle_box = HPacker(pad=0,
|
| 937 |
+
sep=sep, align="baseline",
|
| 938 |
+
mode=mode,
|
| 939 |
+
children=columnbox)
|
| 940 |
+
self._legend_title_box = TextArea("")
|
| 941 |
+
self._legend_box = VPacker(pad=self.borderpad * fontsize,
|
| 942 |
+
sep=self.labelspacing * fontsize,
|
| 943 |
+
align=self._alignment,
|
| 944 |
+
children=[self._legend_title_box,
|
| 945 |
+
self._legend_handle_box])
|
| 946 |
+
self._legend_box.set_figure(self.figure)
|
| 947 |
+
self._legend_box.axes = self.axes
|
| 948 |
+
self.texts = text_list
|
| 949 |
+
self.legend_handles = handle_list
|
| 950 |
+
|
| 951 |
+
def _auto_legend_data(self):
|
| 952 |
+
"""
|
| 953 |
+
Return display coordinates for hit testing for "best" positioning.
|
| 954 |
+
|
| 955 |
+
Returns
|
| 956 |
+
-------
|
| 957 |
+
bboxes
|
| 958 |
+
List of bounding boxes of all patches.
|
| 959 |
+
lines
|
| 960 |
+
List of `.Path` corresponding to each line.
|
| 961 |
+
offsets
|
| 962 |
+
List of (x, y) offsets of all collection.
|
| 963 |
+
"""
|
| 964 |
+
assert self.isaxes # always holds, as this is only called internally
|
| 965 |
+
bboxes = []
|
| 966 |
+
lines = []
|
| 967 |
+
offsets = []
|
| 968 |
+
for artist in self.parent._children:
|
| 969 |
+
if isinstance(artist, Line2D):
|
| 970 |
+
lines.append(
|
| 971 |
+
artist.get_transform().transform_path(artist.get_path()))
|
| 972 |
+
elif isinstance(artist, Rectangle):
|
| 973 |
+
bboxes.append(
|
| 974 |
+
artist.get_bbox().transformed(artist.get_data_transform()))
|
| 975 |
+
elif isinstance(artist, Patch):
|
| 976 |
+
lines.append(
|
| 977 |
+
artist.get_transform().transform_path(artist.get_path()))
|
| 978 |
+
elif isinstance(artist, PolyCollection):
|
| 979 |
+
lines.extend(artist.get_transform().transform_path(path)
|
| 980 |
+
for path in artist.get_paths())
|
| 981 |
+
elif isinstance(artist, Collection):
|
| 982 |
+
transform, transOffset, hoffsets, _ = artist._prepare_points()
|
| 983 |
+
if len(hoffsets):
|
| 984 |
+
offsets.extend(transOffset.transform(hoffsets))
|
| 985 |
+
elif isinstance(artist, Text):
|
| 986 |
+
bboxes.append(artist.get_window_extent())
|
| 987 |
+
|
| 988 |
+
return bboxes, lines, offsets
|
| 989 |
+
|
| 990 |
+
def get_children(self):
|
| 991 |
+
# docstring inherited
|
| 992 |
+
return [self._legend_box, self.get_frame()]
|
| 993 |
+
|
| 994 |
+
def get_frame(self):
|
| 995 |
+
"""Return the `~.patches.Rectangle` used to frame the legend."""
|
| 996 |
+
return self.legendPatch
|
| 997 |
+
|
| 998 |
+
def get_lines(self):
|
| 999 |
+
r"""Return the list of `~.lines.Line2D`\s in the legend."""
|
| 1000 |
+
return [h for h in self.legend_handles if isinstance(h, Line2D)]
|
| 1001 |
+
|
| 1002 |
+
def get_patches(self):
|
| 1003 |
+
r"""Return the list of `~.patches.Patch`\s in the legend."""
|
| 1004 |
+
return silent_list('Patch',
|
| 1005 |
+
[h for h in self.legend_handles
|
| 1006 |
+
if isinstance(h, Patch)])
|
| 1007 |
+
|
| 1008 |
+
def get_texts(self):
|
| 1009 |
+
r"""Return the list of `~.text.Text`\s in the legend."""
|
| 1010 |
+
return silent_list('Text', self.texts)
|
| 1011 |
+
|
| 1012 |
+
def set_alignment(self, alignment):
|
| 1013 |
+
"""
|
| 1014 |
+
Set the alignment of the legend title and the box of entries.
|
| 1015 |
+
|
| 1016 |
+
The entries are aligned as a single block, so that markers always
|
| 1017 |
+
lined up.
|
| 1018 |
+
|
| 1019 |
+
Parameters
|
| 1020 |
+
----------
|
| 1021 |
+
alignment : {'center', 'left', 'right'}.
|
| 1022 |
+
|
| 1023 |
+
"""
|
| 1024 |
+
_api.check_in_list(["center", "left", "right"], alignment=alignment)
|
| 1025 |
+
self._alignment = alignment
|
| 1026 |
+
self._legend_box.align = alignment
|
| 1027 |
+
|
| 1028 |
+
def get_alignment(self):
|
| 1029 |
+
"""Get the alignment value of the legend box"""
|
| 1030 |
+
return self._legend_box.align
|
| 1031 |
+
|
| 1032 |
+
def set_title(self, title, prop=None):
|
| 1033 |
+
"""
|
| 1034 |
+
Set legend title and title style.
|
| 1035 |
+
|
| 1036 |
+
Parameters
|
| 1037 |
+
----------
|
| 1038 |
+
title : str
|
| 1039 |
+
The legend title.
|
| 1040 |
+
|
| 1041 |
+
prop : `.font_manager.FontProperties` or `str` or `pathlib.Path`
|
| 1042 |
+
The font properties of the legend title.
|
| 1043 |
+
If a `str`, it is interpreted as a fontconfig pattern parsed by
|
| 1044 |
+
`.FontProperties`. If a `pathlib.Path`, it is interpreted as the
|
| 1045 |
+
absolute path to a font file.
|
| 1046 |
+
|
| 1047 |
+
"""
|
| 1048 |
+
self._legend_title_box._text.set_text(title)
|
| 1049 |
+
if title:
|
| 1050 |
+
self._legend_title_box._text.set_visible(True)
|
| 1051 |
+
self._legend_title_box.set_visible(True)
|
| 1052 |
+
else:
|
| 1053 |
+
self._legend_title_box._text.set_visible(False)
|
| 1054 |
+
self._legend_title_box.set_visible(False)
|
| 1055 |
+
|
| 1056 |
+
if prop is not None:
|
| 1057 |
+
self._legend_title_box._text.set_fontproperties(prop)
|
| 1058 |
+
|
| 1059 |
+
self.stale = True
|
| 1060 |
+
|
| 1061 |
+
def get_title(self):
|
| 1062 |
+
"""Return the `.Text` instance for the legend title."""
|
| 1063 |
+
return self._legend_title_box._text
|
| 1064 |
+
|
| 1065 |
+
def get_window_extent(self, renderer=None):
|
| 1066 |
+
# docstring inherited
|
| 1067 |
+
if renderer is None:
|
| 1068 |
+
renderer = self.figure._get_renderer()
|
| 1069 |
+
return self._legend_box.get_window_extent(renderer=renderer)
|
| 1070 |
+
|
| 1071 |
+
def get_tightbbox(self, renderer=None):
|
| 1072 |
+
# docstring inherited
|
| 1073 |
+
return self._legend_box.get_window_extent(renderer)
|
| 1074 |
+
|
| 1075 |
+
def get_frame_on(self):
|
| 1076 |
+
"""Get whether the legend box patch is drawn."""
|
| 1077 |
+
return self.legendPatch.get_visible()
|
| 1078 |
+
|
| 1079 |
+
def set_frame_on(self, b):
|
| 1080 |
+
"""
|
| 1081 |
+
Set whether the legend box patch is drawn.
|
| 1082 |
+
|
| 1083 |
+
Parameters
|
| 1084 |
+
----------
|
| 1085 |
+
b : bool
|
| 1086 |
+
"""
|
| 1087 |
+
self.legendPatch.set_visible(b)
|
| 1088 |
+
self.stale = True
|
| 1089 |
+
|
| 1090 |
+
draw_frame = set_frame_on # Backcompat alias.
|
| 1091 |
+
|
| 1092 |
+
def get_bbox_to_anchor(self):
|
| 1093 |
+
"""Return the bbox that the legend will be anchored to."""
|
| 1094 |
+
if self._bbox_to_anchor is None:
|
| 1095 |
+
return self.parent.bbox
|
| 1096 |
+
else:
|
| 1097 |
+
return self._bbox_to_anchor
|
| 1098 |
+
|
| 1099 |
+
def set_bbox_to_anchor(self, bbox, transform=None):
|
| 1100 |
+
"""
|
| 1101 |
+
Set the bbox that the legend will be anchored to.
|
| 1102 |
+
|
| 1103 |
+
Parameters
|
| 1104 |
+
----------
|
| 1105 |
+
bbox : `~matplotlib.transforms.BboxBase` or tuple
|
| 1106 |
+
The bounding box can be specified in the following ways:
|
| 1107 |
+
|
| 1108 |
+
- A `.BboxBase` instance
|
| 1109 |
+
- A tuple of ``(left, bottom, width, height)`` in the given
|
| 1110 |
+
transform (normalized axes coordinate if None)
|
| 1111 |
+
- A tuple of ``(left, bottom)`` where the width and height will be
|
| 1112 |
+
assumed to be zero.
|
| 1113 |
+
- *None*, to remove the bbox anchoring, and use the parent bbox.
|
| 1114 |
+
|
| 1115 |
+
transform : `~matplotlib.transforms.Transform`, optional
|
| 1116 |
+
A transform to apply to the bounding box. If not specified, this
|
| 1117 |
+
will use a transform to the bounding box of the parent.
|
| 1118 |
+
"""
|
| 1119 |
+
if bbox is None:
|
| 1120 |
+
self._bbox_to_anchor = None
|
| 1121 |
+
return
|
| 1122 |
+
elif isinstance(bbox, BboxBase):
|
| 1123 |
+
self._bbox_to_anchor = bbox
|
| 1124 |
+
else:
|
| 1125 |
+
try:
|
| 1126 |
+
l = len(bbox)
|
| 1127 |
+
except TypeError as err:
|
| 1128 |
+
raise ValueError(f"Invalid bbox: {bbox}") from err
|
| 1129 |
+
|
| 1130 |
+
if l == 2:
|
| 1131 |
+
bbox = [bbox[0], bbox[1], 0, 0]
|
| 1132 |
+
|
| 1133 |
+
self._bbox_to_anchor = Bbox.from_bounds(*bbox)
|
| 1134 |
+
|
| 1135 |
+
if transform is None:
|
| 1136 |
+
transform = BboxTransformTo(self.parent.bbox)
|
| 1137 |
+
|
| 1138 |
+
self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
|
| 1139 |
+
transform)
|
| 1140 |
+
self.stale = True
|
| 1141 |
+
|
| 1142 |
+
def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
|
| 1143 |
+
"""
|
| 1144 |
+
Place the *bbox* inside the *parentbbox* according to a given
|
| 1145 |
+
location code. Return the (x, y) coordinate of the bbox.
|
| 1146 |
+
|
| 1147 |
+
Parameters
|
| 1148 |
+
----------
|
| 1149 |
+
loc : int
|
| 1150 |
+
A location code in range(1, 11). This corresponds to the possible
|
| 1151 |
+
values for ``self._loc``, excluding "best".
|
| 1152 |
+
bbox : `~matplotlib.transforms.Bbox`
|
| 1153 |
+
bbox to be placed, in display coordinates.
|
| 1154 |
+
parentbbox : `~matplotlib.transforms.Bbox`
|
| 1155 |
+
A parent box which will contain the bbox, in display coordinates.
|
| 1156 |
+
"""
|
| 1157 |
+
return offsetbox._get_anchored_bbox(
|
| 1158 |
+
loc, bbox, parentbbox,
|
| 1159 |
+
self.borderaxespad * renderer.points_to_pixels(self._fontsize))
|
| 1160 |
+
|
| 1161 |
+
def _find_best_position(self, width, height, renderer):
|
| 1162 |
+
"""Determine the best location to place the legend."""
|
| 1163 |
+
assert self.isaxes # always holds, as this is only called internally
|
| 1164 |
+
|
| 1165 |
+
start_time = time.perf_counter()
|
| 1166 |
+
|
| 1167 |
+
bboxes, lines, offsets = self._auto_legend_data()
|
| 1168 |
+
|
| 1169 |
+
bbox = Bbox.from_bounds(0, 0, width, height)
|
| 1170 |
+
|
| 1171 |
+
candidates = []
|
| 1172 |
+
for idx in range(1, len(self.codes)):
|
| 1173 |
+
l, b = self._get_anchored_bbox(idx, bbox,
|
| 1174 |
+
self.get_bbox_to_anchor(),
|
| 1175 |
+
renderer)
|
| 1176 |
+
legendBox = Bbox.from_bounds(l, b, width, height)
|
| 1177 |
+
# XXX TODO: If markers are present, it would be good to take them
|
| 1178 |
+
# into account when checking vertex overlaps in the next line.
|
| 1179 |
+
badness = (sum(legendBox.count_contains(line.vertices)
|
| 1180 |
+
for line in lines)
|
| 1181 |
+
+ legendBox.count_contains(offsets)
|
| 1182 |
+
+ legendBox.count_overlaps(bboxes)
|
| 1183 |
+
+ sum(line.intersects_bbox(legendBox, filled=False)
|
| 1184 |
+
for line in lines))
|
| 1185 |
+
# Include the index to favor lower codes in case of a tie.
|
| 1186 |
+
candidates.append((badness, idx, (l, b)))
|
| 1187 |
+
if badness == 0:
|
| 1188 |
+
break
|
| 1189 |
+
|
| 1190 |
+
_, _, (l, b) = min(candidates)
|
| 1191 |
+
|
| 1192 |
+
if self._loc_used_default and time.perf_counter() - start_time > 1:
|
| 1193 |
+
_api.warn_external(
|
| 1194 |
+
'Creating legend with loc="best" can be slow with large '
|
| 1195 |
+
'amounts of data.')
|
| 1196 |
+
|
| 1197 |
+
return l, b
|
| 1198 |
+
|
| 1199 |
+
@_api.rename_parameter("3.8", "event", "mouseevent")
|
| 1200 |
+
def contains(self, mouseevent):
|
| 1201 |
+
return self.legendPatch.contains(mouseevent)
|
| 1202 |
+
|
| 1203 |
+
def set_draggable(self, state, use_blit=False, update='loc'):
|
| 1204 |
+
"""
|
| 1205 |
+
Enable or disable mouse dragging support of the legend.
|
| 1206 |
+
|
| 1207 |
+
Parameters
|
| 1208 |
+
----------
|
| 1209 |
+
state : bool
|
| 1210 |
+
Whether mouse dragging is enabled.
|
| 1211 |
+
use_blit : bool, optional
|
| 1212 |
+
Use blitting for faster image composition. For details see
|
| 1213 |
+
:ref:`func-animation`.
|
| 1214 |
+
update : {'loc', 'bbox'}, optional
|
| 1215 |
+
The legend parameter to be changed when dragged:
|
| 1216 |
+
|
| 1217 |
+
- 'loc': update the *loc* parameter of the legend
|
| 1218 |
+
- 'bbox': update the *bbox_to_anchor* parameter of the legend
|
| 1219 |
+
|
| 1220 |
+
Returns
|
| 1221 |
+
-------
|
| 1222 |
+
`.DraggableLegend` or *None*
|
| 1223 |
+
If *state* is ``True`` this returns the `.DraggableLegend` helper
|
| 1224 |
+
instance. Otherwise this returns *None*.
|
| 1225 |
+
"""
|
| 1226 |
+
if state:
|
| 1227 |
+
if self._draggable is None:
|
| 1228 |
+
self._draggable = DraggableLegend(self,
|
| 1229 |
+
use_blit,
|
| 1230 |
+
update=update)
|
| 1231 |
+
else:
|
| 1232 |
+
if self._draggable is not None:
|
| 1233 |
+
self._draggable.disconnect()
|
| 1234 |
+
self._draggable = None
|
| 1235 |
+
return self._draggable
|
| 1236 |
+
|
| 1237 |
+
def get_draggable(self):
|
| 1238 |
+
"""Return ``True`` if the legend is draggable, ``False`` otherwise."""
|
| 1239 |
+
return self._draggable is not None
|
| 1240 |
+
|
| 1241 |
+
|
| 1242 |
+
# Helper functions to parse legend arguments for both `figure.legend` and
|
| 1243 |
+
# `axes.legend`:
|
| 1244 |
+
def _get_legend_handles(axs, legend_handler_map=None):
|
| 1245 |
+
"""Yield artists that can be used as handles in a legend."""
|
| 1246 |
+
handles_original = []
|
| 1247 |
+
for ax in axs:
|
| 1248 |
+
handles_original += [
|
| 1249 |
+
*(a for a in ax._children
|
| 1250 |
+
if isinstance(a, (Line2D, Patch, Collection, Text))),
|
| 1251 |
+
*ax.containers]
|
| 1252 |
+
# support parasite Axes:
|
| 1253 |
+
if hasattr(ax, 'parasites'):
|
| 1254 |
+
for axx in ax.parasites:
|
| 1255 |
+
handles_original += [
|
| 1256 |
+
*(a for a in axx._children
|
| 1257 |
+
if isinstance(a, (Line2D, Patch, Collection, Text))),
|
| 1258 |
+
*axx.containers]
|
| 1259 |
+
|
| 1260 |
+
handler_map = {**Legend.get_default_handler_map(),
|
| 1261 |
+
**(legend_handler_map or {})}
|
| 1262 |
+
has_handler = Legend.get_legend_handler
|
| 1263 |
+
for handle in handles_original:
|
| 1264 |
+
label = handle.get_label()
|
| 1265 |
+
if label != '_nolegend_' and has_handler(handler_map, handle):
|
| 1266 |
+
yield handle
|
| 1267 |
+
elif (label and not label.startswith('_') and
|
| 1268 |
+
not has_handler(handler_map, handle)):
|
| 1269 |
+
_api.warn_external(
|
| 1270 |
+
"Legend does not support handles for "
|
| 1271 |
+
f"{type(handle).__name__} "
|
| 1272 |
+
"instances.\nSee: https://matplotlib.org/stable/"
|
| 1273 |
+
"tutorials/intermediate/legend_guide.html"
|
| 1274 |
+
"#implementing-a-custom-legend-handler")
|
| 1275 |
+
continue
|
| 1276 |
+
|
| 1277 |
+
|
| 1278 |
+
def _get_legend_handles_labels(axs, legend_handler_map=None):
|
| 1279 |
+
"""Return handles and labels for legend."""
|
| 1280 |
+
handles = []
|
| 1281 |
+
labels = []
|
| 1282 |
+
for handle in _get_legend_handles(axs, legend_handler_map):
|
| 1283 |
+
label = handle.get_label()
|
| 1284 |
+
if label and not label.startswith('_'):
|
| 1285 |
+
handles.append(handle)
|
| 1286 |
+
labels.append(label)
|
| 1287 |
+
return handles, labels
|
| 1288 |
+
|
| 1289 |
+
|
| 1290 |
+
def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
|
| 1291 |
+
"""
|
| 1292 |
+
Get the handles and labels from the calls to either ``figure.legend``
|
| 1293 |
+
or ``axes.legend``.
|
| 1294 |
+
|
| 1295 |
+
The parser is a bit involved because we support::
|
| 1296 |
+
|
| 1297 |
+
legend()
|
| 1298 |
+
legend(labels)
|
| 1299 |
+
legend(handles, labels)
|
| 1300 |
+
legend(labels=labels)
|
| 1301 |
+
legend(handles=handles)
|
| 1302 |
+
legend(handles=handles, labels=labels)
|
| 1303 |
+
|
| 1304 |
+
The behavior for a mixture of positional and keyword handles and labels
|
| 1305 |
+
is undefined and issues a warning; it will be an error in the future.
|
| 1306 |
+
|
| 1307 |
+
Parameters
|
| 1308 |
+
----------
|
| 1309 |
+
axs : list of `.Axes`
|
| 1310 |
+
If handles are not given explicitly, the artists in these Axes are
|
| 1311 |
+
used as handles.
|
| 1312 |
+
*args : tuple
|
| 1313 |
+
Positional parameters passed to ``legend()``.
|
| 1314 |
+
handles
|
| 1315 |
+
The value of the keyword argument ``legend(handles=...)``, or *None*
|
| 1316 |
+
if that keyword argument was not used.
|
| 1317 |
+
labels
|
| 1318 |
+
The value of the keyword argument ``legend(labels=...)``, or *None*
|
| 1319 |
+
if that keyword argument was not used.
|
| 1320 |
+
**kwargs
|
| 1321 |
+
All other keyword arguments passed to ``legend()``.
|
| 1322 |
+
|
| 1323 |
+
Returns
|
| 1324 |
+
-------
|
| 1325 |
+
handles : list of (`.Artist` or tuple of `.Artist`)
|
| 1326 |
+
The legend handles.
|
| 1327 |
+
labels : list of str
|
| 1328 |
+
The legend labels.
|
| 1329 |
+
kwargs : dict
|
| 1330 |
+
*kwargs* with keywords handles and labels removed.
|
| 1331 |
+
|
| 1332 |
+
"""
|
| 1333 |
+
log = logging.getLogger(__name__)
|
| 1334 |
+
|
| 1335 |
+
handlers = kwargs.get('handler_map')
|
| 1336 |
+
|
| 1337 |
+
if (handles is not None or labels is not None) and args:
|
| 1338 |
+
_api.warn_deprecated("3.9", message=(
|
| 1339 |
+
"You have mixed positional and keyword arguments, some input may "
|
| 1340 |
+
"be discarded. This is deprecated since %(since)s and will "
|
| 1341 |
+
"become an error %(removal)s."))
|
| 1342 |
+
|
| 1343 |
+
if (hasattr(handles, "__len__") and
|
| 1344 |
+
hasattr(labels, "__len__") and
|
| 1345 |
+
len(handles) != len(labels)):
|
| 1346 |
+
_api.warn_external(f"Mismatched number of handles and labels: "
|
| 1347 |
+
f"len(handles) = {len(handles)} "
|
| 1348 |
+
f"len(labels) = {len(labels)}")
|
| 1349 |
+
# if got both handles and labels as kwargs, make same length
|
| 1350 |
+
if handles and labels:
|
| 1351 |
+
handles, labels = zip(*zip(handles, labels))
|
| 1352 |
+
|
| 1353 |
+
elif handles is not None and labels is None:
|
| 1354 |
+
labels = [handle.get_label() for handle in handles]
|
| 1355 |
+
|
| 1356 |
+
elif labels is not None and handles is None:
|
| 1357 |
+
# Get as many handles as there are labels.
|
| 1358 |
+
handles = [handle for handle, label
|
| 1359 |
+
in zip(_get_legend_handles(axs, handlers), labels)]
|
| 1360 |
+
|
| 1361 |
+
elif len(args) == 0: # 0 args: automatically detect labels and handles.
|
| 1362 |
+
handles, labels = _get_legend_handles_labels(axs, handlers)
|
| 1363 |
+
if not handles:
|
| 1364 |
+
_api.warn_external(
|
| 1365 |
+
"No artists with labels found to put in legend. Note that "
|
| 1366 |
+
"artists whose label start with an underscore are ignored "
|
| 1367 |
+
"when legend() is called with no argument.")
|
| 1368 |
+
|
| 1369 |
+
elif len(args) == 1: # 1 arg: user defined labels, automatic handle detection.
|
| 1370 |
+
labels, = args
|
| 1371 |
+
if any(isinstance(l, Artist) for l in labels):
|
| 1372 |
+
raise TypeError("A single argument passed to legend() must be a "
|
| 1373 |
+
"list of labels, but found an Artist in there.")
|
| 1374 |
+
|
| 1375 |
+
# Get as many handles as there are labels.
|
| 1376 |
+
handles = [handle for handle, label
|
| 1377 |
+
in zip(_get_legend_handles(axs, handlers), labels)]
|
| 1378 |
+
|
| 1379 |
+
elif len(args) == 2: # 2 args: user defined handles and labels.
|
| 1380 |
+
handles, labels = args[:2]
|
| 1381 |
+
|
| 1382 |
+
else:
|
| 1383 |
+
raise _api.nargs_error('legend', '0-2', len(args))
|
| 1384 |
+
|
| 1385 |
+
return handles, labels, kwargs
|
parrot/lib/python3.10/site-packages/matplotlib/legend_handler.py
ADDED
|
@@ -0,0 +1,813 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 :ref:`legend guide
|
| 9 |
+
<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 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 |
+
xpad : float, optional
|
| 67 |
+
Padding in x-direction.
|
| 68 |
+
ypad : float, optional
|
| 69 |
+
Padding in y-direction.
|
| 70 |
+
update_func : callable, optional
|
| 71 |
+
Function for updating the legend handler properties from another
|
| 72 |
+
legend handler, used by `~HandlerBase.update_prop`.
|
| 73 |
+
"""
|
| 74 |
+
self._xpad, self._ypad = xpad, ypad
|
| 75 |
+
self._update_prop_func = update_func
|
| 76 |
+
|
| 77 |
+
def _update_prop(self, legend_handle, orig_handle):
|
| 78 |
+
if self._update_prop_func is None:
|
| 79 |
+
self._default_update_prop(legend_handle, orig_handle)
|
| 80 |
+
else:
|
| 81 |
+
self._update_prop_func(legend_handle, orig_handle)
|
| 82 |
+
|
| 83 |
+
def _default_update_prop(self, legend_handle, orig_handle):
|
| 84 |
+
legend_handle.update_from(orig_handle)
|
| 85 |
+
|
| 86 |
+
def update_prop(self, legend_handle, orig_handle, legend):
|
| 87 |
+
|
| 88 |
+
self._update_prop(legend_handle, orig_handle)
|
| 89 |
+
|
| 90 |
+
legend._set_artist_props(legend_handle)
|
| 91 |
+
legend_handle.set_clip_box(None)
|
| 92 |
+
legend_handle.set_clip_path(None)
|
| 93 |
+
|
| 94 |
+
def adjust_drawing_area(self, legend, orig_handle,
|
| 95 |
+
xdescent, ydescent, width, height, fontsize,
|
| 96 |
+
):
|
| 97 |
+
xdescent = xdescent - self._xpad * fontsize
|
| 98 |
+
ydescent = ydescent - self._ypad * fontsize
|
| 99 |
+
width = width - self._xpad * fontsize
|
| 100 |
+
height = height - self._ypad * fontsize
|
| 101 |
+
return xdescent, ydescent, width, height
|
| 102 |
+
|
| 103 |
+
def legend_artist(self, legend, orig_handle,
|
| 104 |
+
fontsize, handlebox):
|
| 105 |
+
"""
|
| 106 |
+
Return the artist that this HandlerBase generates for the given
|
| 107 |
+
original artist/handle.
|
| 108 |
+
|
| 109 |
+
Parameters
|
| 110 |
+
----------
|
| 111 |
+
legend : `~matplotlib.legend.Legend`
|
| 112 |
+
The legend for which these legend artists are being created.
|
| 113 |
+
orig_handle : :class:`matplotlib.artist.Artist` or similar
|
| 114 |
+
The object for which these legend artists are being created.
|
| 115 |
+
fontsize : int
|
| 116 |
+
The fontsize in pixels. The artists being created should
|
| 117 |
+
be scaled according to the given fontsize.
|
| 118 |
+
handlebox : `~matplotlib.offsetbox.OffsetBox`
|
| 119 |
+
The box which has been created to hold this legend entry's
|
| 120 |
+
artists. Artists created in the `legend_artist` method must
|
| 121 |
+
be added to this handlebox inside this method.
|
| 122 |
+
|
| 123 |
+
"""
|
| 124 |
+
xdescent, ydescent, width, height = self.adjust_drawing_area(
|
| 125 |
+
legend, orig_handle,
|
| 126 |
+
handlebox.xdescent, handlebox.ydescent,
|
| 127 |
+
handlebox.width, handlebox.height,
|
| 128 |
+
fontsize)
|
| 129 |
+
artists = self.create_artists(legend, orig_handle,
|
| 130 |
+
xdescent, ydescent, width, height,
|
| 131 |
+
fontsize, handlebox.get_transform())
|
| 132 |
+
|
| 133 |
+
# create_artists will return a list of artists.
|
| 134 |
+
for a in artists:
|
| 135 |
+
handlebox.add_artist(a)
|
| 136 |
+
|
| 137 |
+
# we only return the first artist
|
| 138 |
+
return artists[0]
|
| 139 |
+
|
| 140 |
+
def create_artists(self, legend, orig_handle,
|
| 141 |
+
xdescent, ydescent, width, height, fontsize,
|
| 142 |
+
trans):
|
| 143 |
+
"""
|
| 144 |
+
Return the legend artists generated.
|
| 145 |
+
|
| 146 |
+
Parameters
|
| 147 |
+
----------
|
| 148 |
+
legend : `~matplotlib.legend.Legend`
|
| 149 |
+
The legend for which these legend artists are being created.
|
| 150 |
+
orig_handle : `~matplotlib.artist.Artist` or similar
|
| 151 |
+
The object for which these legend artists are being created.
|
| 152 |
+
xdescent, ydescent, width, height : int
|
| 153 |
+
The rectangle (*xdescent*, *ydescent*, *width*, *height*) that the
|
| 154 |
+
legend artists being created should fit within.
|
| 155 |
+
fontsize : int
|
| 156 |
+
The fontsize in pixels. The legend artists being created should
|
| 157 |
+
be scaled according to the given fontsize.
|
| 158 |
+
trans : `~matplotlib.transforms.Transform`
|
| 159 |
+
The transform that is applied to the legend artists being created.
|
| 160 |
+
Typically from unit coordinates in the handler box to screen
|
| 161 |
+
coordinates.
|
| 162 |
+
"""
|
| 163 |
+
raise NotImplementedError('Derived must override')
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class HandlerNpoints(HandlerBase):
|
| 167 |
+
"""
|
| 168 |
+
A legend handler that shows *numpoints* points in the legend entry.
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
def __init__(self, marker_pad=0.3, numpoints=None, **kwargs):
|
| 172 |
+
"""
|
| 173 |
+
Parameters
|
| 174 |
+
----------
|
| 175 |
+
marker_pad : float
|
| 176 |
+
Padding between points in legend entry.
|
| 177 |
+
numpoints : int
|
| 178 |
+
Number of points to show in legend entry.
|
| 179 |
+
**kwargs
|
| 180 |
+
Keyword arguments forwarded to `.HandlerBase`.
|
| 181 |
+
"""
|
| 182 |
+
super().__init__(**kwargs)
|
| 183 |
+
|
| 184 |
+
self._numpoints = numpoints
|
| 185 |
+
self._marker_pad = marker_pad
|
| 186 |
+
|
| 187 |
+
def get_numpoints(self, legend):
|
| 188 |
+
if self._numpoints is None:
|
| 189 |
+
return legend.numpoints
|
| 190 |
+
else:
|
| 191 |
+
return self._numpoints
|
| 192 |
+
|
| 193 |
+
def get_xdata(self, legend, xdescent, ydescent, width, height, fontsize):
|
| 194 |
+
numpoints = self.get_numpoints(legend)
|
| 195 |
+
if numpoints > 1:
|
| 196 |
+
# we put some pad here to compensate the size of the marker
|
| 197 |
+
pad = self._marker_pad * fontsize
|
| 198 |
+
xdata = np.linspace(-xdescent + pad,
|
| 199 |
+
-xdescent + width - pad,
|
| 200 |
+
numpoints)
|
| 201 |
+
xdata_marker = xdata
|
| 202 |
+
else:
|
| 203 |
+
xdata = [-xdescent, -xdescent + width]
|
| 204 |
+
xdata_marker = [-xdescent + 0.5 * width]
|
| 205 |
+
return xdata, xdata_marker
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class HandlerNpointsYoffsets(HandlerNpoints):
|
| 209 |
+
"""
|
| 210 |
+
A legend handler that shows *numpoints* in the legend, and allows them to
|
| 211 |
+
be individually offset in the y-direction.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
def __init__(self, numpoints=None, yoffsets=None, **kwargs):
|
| 215 |
+
"""
|
| 216 |
+
Parameters
|
| 217 |
+
----------
|
| 218 |
+
numpoints : int
|
| 219 |
+
Number of points to show in legend entry.
|
| 220 |
+
yoffsets : array of floats
|
| 221 |
+
Length *numpoints* list of y offsets for each point in
|
| 222 |
+
legend entry.
|
| 223 |
+
**kwargs
|
| 224 |
+
Keyword arguments forwarded to `.HandlerNpoints`.
|
| 225 |
+
"""
|
| 226 |
+
super().__init__(numpoints=numpoints, **kwargs)
|
| 227 |
+
self._yoffsets = yoffsets
|
| 228 |
+
|
| 229 |
+
def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):
|
| 230 |
+
if self._yoffsets is None:
|
| 231 |
+
ydata = height * legend._scatteryoffsets
|
| 232 |
+
else:
|
| 233 |
+
ydata = height * np.asarray(self._yoffsets)
|
| 234 |
+
|
| 235 |
+
return ydata
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class HandlerLine2DCompound(HandlerNpoints):
|
| 239 |
+
"""
|
| 240 |
+
Original handler for `.Line2D` instances, that relies on combining
|
| 241 |
+
a line-only with a marker-only artist. May be deprecated in the future.
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
def create_artists(self, legend, orig_handle,
|
| 245 |
+
xdescent, ydescent, width, height, fontsize,
|
| 246 |
+
trans):
|
| 247 |
+
# docstring inherited
|
| 248 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 249 |
+
width, height, fontsize)
|
| 250 |
+
|
| 251 |
+
ydata = np.full_like(xdata, ((height - ydescent) / 2))
|
| 252 |
+
legline = Line2D(xdata, ydata)
|
| 253 |
+
|
| 254 |
+
self.update_prop(legline, orig_handle, legend)
|
| 255 |
+
legline.set_drawstyle('default')
|
| 256 |
+
legline.set_marker("")
|
| 257 |
+
|
| 258 |
+
legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
|
| 259 |
+
self.update_prop(legline_marker, orig_handle, legend)
|
| 260 |
+
legline_marker.set_linestyle('None')
|
| 261 |
+
if legend.markerscale != 1:
|
| 262 |
+
newsz = legline_marker.get_markersize() * legend.markerscale
|
| 263 |
+
legline_marker.set_markersize(newsz)
|
| 264 |
+
# we don't want to add this to the return list because
|
| 265 |
+
# the texts and handles are assumed to be in one-to-one
|
| 266 |
+
# correspondence.
|
| 267 |
+
legline._legmarker = legline_marker
|
| 268 |
+
|
| 269 |
+
legline.set_transform(trans)
|
| 270 |
+
legline_marker.set_transform(trans)
|
| 271 |
+
|
| 272 |
+
return [legline, legline_marker]
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class HandlerLine2D(HandlerNpoints):
|
| 276 |
+
"""
|
| 277 |
+
Handler for `.Line2D` instances.
|
| 278 |
+
|
| 279 |
+
See Also
|
| 280 |
+
--------
|
| 281 |
+
HandlerLine2DCompound : An earlier handler implementation, which used one
|
| 282 |
+
artist for the line and another for the marker(s).
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
def create_artists(self, legend, orig_handle,
|
| 286 |
+
xdescent, ydescent, width, height, fontsize,
|
| 287 |
+
trans):
|
| 288 |
+
# docstring inherited
|
| 289 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 290 |
+
width, height, fontsize)
|
| 291 |
+
|
| 292 |
+
markevery = None
|
| 293 |
+
if self.get_numpoints(legend) == 1:
|
| 294 |
+
# Special case: one wants a single marker in the center
|
| 295 |
+
# and a line that extends on both sides. One will use a
|
| 296 |
+
# 3 points line, but only mark the #1 (i.e. middle) point.
|
| 297 |
+
xdata = np.linspace(xdata[0], xdata[-1], 3)
|
| 298 |
+
markevery = [1]
|
| 299 |
+
|
| 300 |
+
ydata = np.full_like(xdata, (height - ydescent) / 2)
|
| 301 |
+
legline = Line2D(xdata, ydata, markevery=markevery)
|
| 302 |
+
|
| 303 |
+
self.update_prop(legline, orig_handle, legend)
|
| 304 |
+
|
| 305 |
+
if legend.markerscale != 1:
|
| 306 |
+
newsz = legline.get_markersize() * legend.markerscale
|
| 307 |
+
legline.set_markersize(newsz)
|
| 308 |
+
|
| 309 |
+
legline.set_transform(trans)
|
| 310 |
+
|
| 311 |
+
return [legline]
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class HandlerPatch(HandlerBase):
|
| 315 |
+
"""
|
| 316 |
+
Handler for `.Patch` instances.
|
| 317 |
+
"""
|
| 318 |
+
|
| 319 |
+
def __init__(self, patch_func=None, **kwargs):
|
| 320 |
+
"""
|
| 321 |
+
Parameters
|
| 322 |
+
----------
|
| 323 |
+
patch_func : callable, optional
|
| 324 |
+
The function that creates the legend key artist.
|
| 325 |
+
*patch_func* should have the signature::
|
| 326 |
+
|
| 327 |
+
def patch_func(legend=legend, orig_handle=orig_handle,
|
| 328 |
+
xdescent=xdescent, ydescent=ydescent,
|
| 329 |
+
width=width, height=height, fontsize=fontsize)
|
| 330 |
+
|
| 331 |
+
Subsequently, the created artist will have its ``update_prop``
|
| 332 |
+
method called and the appropriate transform will be applied.
|
| 333 |
+
|
| 334 |
+
**kwargs
|
| 335 |
+
Keyword arguments forwarded to `.HandlerBase`.
|
| 336 |
+
"""
|
| 337 |
+
super().__init__(**kwargs)
|
| 338 |
+
self._patch_func = patch_func
|
| 339 |
+
|
| 340 |
+
def _create_patch(self, legend, orig_handle,
|
| 341 |
+
xdescent, ydescent, width, height, fontsize):
|
| 342 |
+
if self._patch_func is None:
|
| 343 |
+
p = Rectangle(xy=(-xdescent, -ydescent),
|
| 344 |
+
width=width, height=height)
|
| 345 |
+
else:
|
| 346 |
+
p = self._patch_func(legend=legend, orig_handle=orig_handle,
|
| 347 |
+
xdescent=xdescent, ydescent=ydescent,
|
| 348 |
+
width=width, height=height, fontsize=fontsize)
|
| 349 |
+
return p
|
| 350 |
+
|
| 351 |
+
def create_artists(self, legend, orig_handle,
|
| 352 |
+
xdescent, ydescent, width, height, fontsize, trans):
|
| 353 |
+
# docstring inherited
|
| 354 |
+
p = self._create_patch(legend, orig_handle,
|
| 355 |
+
xdescent, ydescent, width, height, fontsize)
|
| 356 |
+
self.update_prop(p, orig_handle, legend)
|
| 357 |
+
p.set_transform(trans)
|
| 358 |
+
return [p]
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class HandlerStepPatch(HandlerBase):
|
| 362 |
+
"""
|
| 363 |
+
Handler for `~.matplotlib.patches.StepPatch` instances.
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
@staticmethod
|
| 367 |
+
def _create_patch(orig_handle, xdescent, ydescent, width, height):
|
| 368 |
+
return Rectangle(xy=(-xdescent, -ydescent), width=width,
|
| 369 |
+
height=height, color=orig_handle.get_facecolor())
|
| 370 |
+
|
| 371 |
+
@staticmethod
|
| 372 |
+
def _create_line(orig_handle, width, height):
|
| 373 |
+
# Unfilled StepPatch should show as a line
|
| 374 |
+
legline = Line2D([0, width], [height/2, height/2],
|
| 375 |
+
color=orig_handle.get_edgecolor(),
|
| 376 |
+
linestyle=orig_handle.get_linestyle(),
|
| 377 |
+
linewidth=orig_handle.get_linewidth(),
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
# Overwrite manually because patch and line properties don't mix
|
| 381 |
+
legline.set_drawstyle('default')
|
| 382 |
+
legline.set_marker("")
|
| 383 |
+
return legline
|
| 384 |
+
|
| 385 |
+
def create_artists(self, legend, orig_handle,
|
| 386 |
+
xdescent, ydescent, width, height, fontsize, trans):
|
| 387 |
+
# docstring inherited
|
| 388 |
+
if orig_handle.get_fill() or (orig_handle.get_hatch() is not None):
|
| 389 |
+
p = self._create_patch(orig_handle, xdescent, ydescent, width,
|
| 390 |
+
height)
|
| 391 |
+
self.update_prop(p, orig_handle, legend)
|
| 392 |
+
else:
|
| 393 |
+
p = self._create_line(orig_handle, width, height)
|
| 394 |
+
p.set_transform(trans)
|
| 395 |
+
return [p]
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class HandlerLineCollection(HandlerLine2D):
|
| 399 |
+
"""
|
| 400 |
+
Handler for `.LineCollection` instances.
|
| 401 |
+
"""
|
| 402 |
+
def get_numpoints(self, legend):
|
| 403 |
+
if self._numpoints is None:
|
| 404 |
+
return legend.scatterpoints
|
| 405 |
+
else:
|
| 406 |
+
return self._numpoints
|
| 407 |
+
|
| 408 |
+
def _default_update_prop(self, legend_handle, orig_handle):
|
| 409 |
+
lw = orig_handle.get_linewidths()[0]
|
| 410 |
+
dashes = orig_handle._us_linestyles[0]
|
| 411 |
+
color = orig_handle.get_colors()[0]
|
| 412 |
+
legend_handle.set_color(color)
|
| 413 |
+
legend_handle.set_linestyle(dashes)
|
| 414 |
+
legend_handle.set_linewidth(lw)
|
| 415 |
+
|
| 416 |
+
def create_artists(self, legend, orig_handle,
|
| 417 |
+
xdescent, ydescent, width, height, fontsize, trans):
|
| 418 |
+
# docstring inherited
|
| 419 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 420 |
+
width, height, fontsize)
|
| 421 |
+
ydata = np.full_like(xdata, (height - ydescent) / 2)
|
| 422 |
+
legline = Line2D(xdata, ydata)
|
| 423 |
+
|
| 424 |
+
self.update_prop(legline, orig_handle, legend)
|
| 425 |
+
legline.set_transform(trans)
|
| 426 |
+
|
| 427 |
+
return [legline]
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
class HandlerRegularPolyCollection(HandlerNpointsYoffsets):
|
| 431 |
+
r"""Handler for `.RegularPolyCollection`\s."""
|
| 432 |
+
|
| 433 |
+
def __init__(self, yoffsets=None, sizes=None, **kwargs):
|
| 434 |
+
super().__init__(yoffsets=yoffsets, **kwargs)
|
| 435 |
+
|
| 436 |
+
self._sizes = sizes
|
| 437 |
+
|
| 438 |
+
def get_numpoints(self, legend):
|
| 439 |
+
if self._numpoints is None:
|
| 440 |
+
return legend.scatterpoints
|
| 441 |
+
else:
|
| 442 |
+
return self._numpoints
|
| 443 |
+
|
| 444 |
+
def get_sizes(self, legend, orig_handle,
|
| 445 |
+
xdescent, ydescent, width, height, fontsize):
|
| 446 |
+
if self._sizes is None:
|
| 447 |
+
handle_sizes = orig_handle.get_sizes()
|
| 448 |
+
if not len(handle_sizes):
|
| 449 |
+
handle_sizes = [1]
|
| 450 |
+
size_max = max(handle_sizes) * legend.markerscale ** 2
|
| 451 |
+
size_min = min(handle_sizes) * legend.markerscale ** 2
|
| 452 |
+
|
| 453 |
+
numpoints = self.get_numpoints(legend)
|
| 454 |
+
if numpoints < 4:
|
| 455 |
+
sizes = [.5 * (size_max + size_min), size_max,
|
| 456 |
+
size_min][:numpoints]
|
| 457 |
+
else:
|
| 458 |
+
rng = (size_max - size_min)
|
| 459 |
+
sizes = rng * np.linspace(0, 1, numpoints) + size_min
|
| 460 |
+
else:
|
| 461 |
+
sizes = self._sizes
|
| 462 |
+
|
| 463 |
+
return sizes
|
| 464 |
+
|
| 465 |
+
def update_prop(self, legend_handle, orig_handle, legend):
|
| 466 |
+
|
| 467 |
+
self._update_prop(legend_handle, orig_handle)
|
| 468 |
+
|
| 469 |
+
legend_handle.set_figure(legend.figure)
|
| 470 |
+
# legend._set_artist_props(legend_handle)
|
| 471 |
+
legend_handle.set_clip_box(None)
|
| 472 |
+
legend_handle.set_clip_path(None)
|
| 473 |
+
|
| 474 |
+
def create_collection(self, orig_handle, sizes, offsets, offset_transform):
|
| 475 |
+
return type(orig_handle)(
|
| 476 |
+
orig_handle.get_numsides(),
|
| 477 |
+
rotation=orig_handle.get_rotation(), sizes=sizes,
|
| 478 |
+
offsets=offsets, offset_transform=offset_transform,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
def create_artists(self, legend, orig_handle,
|
| 482 |
+
xdescent, ydescent, width, height, fontsize,
|
| 483 |
+
trans):
|
| 484 |
+
# docstring inherited
|
| 485 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 486 |
+
width, height, fontsize)
|
| 487 |
+
|
| 488 |
+
ydata = self.get_ydata(legend, xdescent, ydescent,
|
| 489 |
+
width, height, fontsize)
|
| 490 |
+
|
| 491 |
+
sizes = self.get_sizes(legend, orig_handle, xdescent, ydescent,
|
| 492 |
+
width, height, fontsize)
|
| 493 |
+
|
| 494 |
+
p = self.create_collection(
|
| 495 |
+
orig_handle, sizes,
|
| 496 |
+
offsets=list(zip(xdata_marker, ydata)), offset_transform=trans)
|
| 497 |
+
|
| 498 |
+
self.update_prop(p, orig_handle, legend)
|
| 499 |
+
p.set_offset_transform(trans)
|
| 500 |
+
return [p]
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class HandlerPathCollection(HandlerRegularPolyCollection):
|
| 504 |
+
r"""Handler for `.PathCollection`\s, which are used by `~.Axes.scatter`."""
|
| 505 |
+
|
| 506 |
+
def create_collection(self, orig_handle, sizes, offsets, offset_transform):
|
| 507 |
+
return type(orig_handle)(
|
| 508 |
+
[orig_handle.get_paths()[0]], sizes=sizes,
|
| 509 |
+
offsets=offsets, offset_transform=offset_transform,
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class HandlerCircleCollection(HandlerRegularPolyCollection):
|
| 514 |
+
r"""Handler for `.CircleCollection`\s."""
|
| 515 |
+
|
| 516 |
+
def create_collection(self, orig_handle, sizes, offsets, offset_transform):
|
| 517 |
+
return type(orig_handle)(
|
| 518 |
+
sizes, offsets=offsets, offset_transform=offset_transform)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class HandlerErrorbar(HandlerLine2D):
|
| 522 |
+
"""Handler for Errorbars."""
|
| 523 |
+
|
| 524 |
+
def __init__(self, xerr_size=0.5, yerr_size=None,
|
| 525 |
+
marker_pad=0.3, numpoints=None, **kwargs):
|
| 526 |
+
|
| 527 |
+
self._xerr_size = xerr_size
|
| 528 |
+
self._yerr_size = yerr_size
|
| 529 |
+
|
| 530 |
+
super().__init__(marker_pad=marker_pad, numpoints=numpoints, **kwargs)
|
| 531 |
+
|
| 532 |
+
def get_err_size(self, legend, xdescent, ydescent,
|
| 533 |
+
width, height, fontsize):
|
| 534 |
+
xerr_size = self._xerr_size * fontsize
|
| 535 |
+
|
| 536 |
+
if self._yerr_size is None:
|
| 537 |
+
yerr_size = xerr_size
|
| 538 |
+
else:
|
| 539 |
+
yerr_size = self._yerr_size * fontsize
|
| 540 |
+
|
| 541 |
+
return xerr_size, yerr_size
|
| 542 |
+
|
| 543 |
+
def create_artists(self, legend, orig_handle,
|
| 544 |
+
xdescent, ydescent, width, height, fontsize,
|
| 545 |
+
trans):
|
| 546 |
+
# docstring inherited
|
| 547 |
+
plotlines, caplines, barlinecols = orig_handle
|
| 548 |
+
|
| 549 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 550 |
+
width, height, fontsize)
|
| 551 |
+
|
| 552 |
+
ydata = np.full_like(xdata, (height - ydescent) / 2)
|
| 553 |
+
legline = Line2D(xdata, ydata)
|
| 554 |
+
|
| 555 |
+
xdata_marker = np.asarray(xdata_marker)
|
| 556 |
+
ydata_marker = np.asarray(ydata[:len(xdata_marker)])
|
| 557 |
+
|
| 558 |
+
xerr_size, yerr_size = self.get_err_size(legend, xdescent, ydescent,
|
| 559 |
+
width, height, fontsize)
|
| 560 |
+
|
| 561 |
+
legline_marker = Line2D(xdata_marker, ydata_marker)
|
| 562 |
+
|
| 563 |
+
# when plotlines are None (only errorbars are drawn), we just
|
| 564 |
+
# make legline invisible.
|
| 565 |
+
if plotlines is None:
|
| 566 |
+
legline.set_visible(False)
|
| 567 |
+
legline_marker.set_visible(False)
|
| 568 |
+
else:
|
| 569 |
+
self.update_prop(legline, plotlines, legend)
|
| 570 |
+
|
| 571 |
+
legline.set_drawstyle('default')
|
| 572 |
+
legline.set_marker('none')
|
| 573 |
+
|
| 574 |
+
self.update_prop(legline_marker, plotlines, legend)
|
| 575 |
+
legline_marker.set_linestyle('None')
|
| 576 |
+
|
| 577 |
+
if legend.markerscale != 1:
|
| 578 |
+
newsz = legline_marker.get_markersize() * legend.markerscale
|
| 579 |
+
legline_marker.set_markersize(newsz)
|
| 580 |
+
|
| 581 |
+
handle_barlinecols = []
|
| 582 |
+
handle_caplines = []
|
| 583 |
+
|
| 584 |
+
if orig_handle.has_xerr:
|
| 585 |
+
verts = [((x - xerr_size, y), (x + xerr_size, y))
|
| 586 |
+
for x, y in zip(xdata_marker, ydata_marker)]
|
| 587 |
+
coll = mcoll.LineCollection(verts)
|
| 588 |
+
self.update_prop(coll, barlinecols[0], legend)
|
| 589 |
+
handle_barlinecols.append(coll)
|
| 590 |
+
|
| 591 |
+
if caplines:
|
| 592 |
+
capline_left = Line2D(xdata_marker - xerr_size, ydata_marker)
|
| 593 |
+
capline_right = Line2D(xdata_marker + xerr_size, ydata_marker)
|
| 594 |
+
self.update_prop(capline_left, caplines[0], legend)
|
| 595 |
+
self.update_prop(capline_right, caplines[0], legend)
|
| 596 |
+
capline_left.set_marker("|")
|
| 597 |
+
capline_right.set_marker("|")
|
| 598 |
+
|
| 599 |
+
handle_caplines.append(capline_left)
|
| 600 |
+
handle_caplines.append(capline_right)
|
| 601 |
+
|
| 602 |
+
if orig_handle.has_yerr:
|
| 603 |
+
verts = [((x, y - yerr_size), (x, y + yerr_size))
|
| 604 |
+
for x, y in zip(xdata_marker, ydata_marker)]
|
| 605 |
+
coll = mcoll.LineCollection(verts)
|
| 606 |
+
self.update_prop(coll, barlinecols[0], legend)
|
| 607 |
+
handle_barlinecols.append(coll)
|
| 608 |
+
|
| 609 |
+
if caplines:
|
| 610 |
+
capline_left = Line2D(xdata_marker, ydata_marker - yerr_size)
|
| 611 |
+
capline_right = Line2D(xdata_marker, ydata_marker + yerr_size)
|
| 612 |
+
self.update_prop(capline_left, caplines[0], legend)
|
| 613 |
+
self.update_prop(capline_right, caplines[0], legend)
|
| 614 |
+
capline_left.set_marker("_")
|
| 615 |
+
capline_right.set_marker("_")
|
| 616 |
+
|
| 617 |
+
handle_caplines.append(capline_left)
|
| 618 |
+
handle_caplines.append(capline_right)
|
| 619 |
+
|
| 620 |
+
artists = [
|
| 621 |
+
*handle_barlinecols, *handle_caplines, legline, legline_marker,
|
| 622 |
+
]
|
| 623 |
+
for artist in artists:
|
| 624 |
+
artist.set_transform(trans)
|
| 625 |
+
return artists
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
class HandlerStem(HandlerNpointsYoffsets):
|
| 629 |
+
"""
|
| 630 |
+
Handler for plots produced by `~.Axes.stem`.
|
| 631 |
+
"""
|
| 632 |
+
|
| 633 |
+
def __init__(self, marker_pad=0.3, numpoints=None,
|
| 634 |
+
bottom=None, yoffsets=None, **kwargs):
|
| 635 |
+
"""
|
| 636 |
+
Parameters
|
| 637 |
+
----------
|
| 638 |
+
marker_pad : float, default: 0.3
|
| 639 |
+
Padding between points in legend entry.
|
| 640 |
+
numpoints : int, optional
|
| 641 |
+
Number of points to show in legend entry.
|
| 642 |
+
bottom : float, optional
|
| 643 |
+
|
| 644 |
+
yoffsets : array of floats, optional
|
| 645 |
+
Length *numpoints* list of y offsets for each point in
|
| 646 |
+
legend entry.
|
| 647 |
+
**kwargs
|
| 648 |
+
Keyword arguments forwarded to `.HandlerNpointsYoffsets`.
|
| 649 |
+
"""
|
| 650 |
+
super().__init__(marker_pad=marker_pad, numpoints=numpoints,
|
| 651 |
+
yoffsets=yoffsets, **kwargs)
|
| 652 |
+
self._bottom = bottom
|
| 653 |
+
|
| 654 |
+
def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):
|
| 655 |
+
if self._yoffsets is None:
|
| 656 |
+
ydata = height * (0.5 * legend._scatteryoffsets + 0.5)
|
| 657 |
+
else:
|
| 658 |
+
ydata = height * np.asarray(self._yoffsets)
|
| 659 |
+
|
| 660 |
+
return ydata
|
| 661 |
+
|
| 662 |
+
def create_artists(self, legend, orig_handle,
|
| 663 |
+
xdescent, ydescent, width, height, fontsize,
|
| 664 |
+
trans):
|
| 665 |
+
# docstring inherited
|
| 666 |
+
markerline, stemlines, baseline = orig_handle
|
| 667 |
+
# Check to see if the stemcontainer is storing lines as a list or a
|
| 668 |
+
# LineCollection. Eventually using a list will be removed, and this
|
| 669 |
+
# logic can also be removed.
|
| 670 |
+
using_linecoll = isinstance(stemlines, mcoll.LineCollection)
|
| 671 |
+
|
| 672 |
+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
|
| 673 |
+
width, height, fontsize)
|
| 674 |
+
|
| 675 |
+
ydata = self.get_ydata(legend, xdescent, ydescent,
|
| 676 |
+
width, height, fontsize)
|
| 677 |
+
|
| 678 |
+
if self._bottom is None:
|
| 679 |
+
bottom = 0.
|
| 680 |
+
else:
|
| 681 |
+
bottom = self._bottom
|
| 682 |
+
|
| 683 |
+
leg_markerline = Line2D(xdata_marker, ydata[:len(xdata_marker)])
|
| 684 |
+
self.update_prop(leg_markerline, markerline, legend)
|
| 685 |
+
|
| 686 |
+
leg_stemlines = [Line2D([x, x], [bottom, y])
|
| 687 |
+
for x, y in zip(xdata_marker, ydata)]
|
| 688 |
+
|
| 689 |
+
if using_linecoll:
|
| 690 |
+
# change the function used by update_prop() from the default
|
| 691 |
+
# to one that handles LineCollection
|
| 692 |
+
with cbook._setattr_cm(
|
| 693 |
+
self, _update_prop_func=self._copy_collection_props):
|
| 694 |
+
for line in leg_stemlines:
|
| 695 |
+
self.update_prop(line, stemlines, legend)
|
| 696 |
+
|
| 697 |
+
else:
|
| 698 |
+
for lm, m in zip(leg_stemlines, stemlines):
|
| 699 |
+
self.update_prop(lm, m, legend)
|
| 700 |
+
|
| 701 |
+
leg_baseline = Line2D([np.min(xdata), np.max(xdata)],
|
| 702 |
+
[bottom, bottom])
|
| 703 |
+
self.update_prop(leg_baseline, baseline, legend)
|
| 704 |
+
|
| 705 |
+
artists = [*leg_stemlines, leg_baseline, leg_markerline]
|
| 706 |
+
for artist in artists:
|
| 707 |
+
artist.set_transform(trans)
|
| 708 |
+
return artists
|
| 709 |
+
|
| 710 |
+
def _copy_collection_props(self, legend_handle, orig_handle):
|
| 711 |
+
"""
|
| 712 |
+
Copy properties from the `.LineCollection` *orig_handle* to the
|
| 713 |
+
`.Line2D` *legend_handle*.
|
| 714 |
+
"""
|
| 715 |
+
legend_handle.set_color(orig_handle.get_color()[0])
|
| 716 |
+
legend_handle.set_linestyle(orig_handle.get_linestyle()[0])
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
class HandlerTuple(HandlerBase):
|
| 720 |
+
"""
|
| 721 |
+
Handler for Tuple.
|
| 722 |
+
"""
|
| 723 |
+
|
| 724 |
+
def __init__(self, ndivide=1, pad=None, **kwargs):
|
| 725 |
+
"""
|
| 726 |
+
Parameters
|
| 727 |
+
----------
|
| 728 |
+
ndivide : int or None, default: 1
|
| 729 |
+
The number of sections to divide the legend area into. If None,
|
| 730 |
+
use the length of the input tuple.
|
| 731 |
+
pad : float, default: :rc:`legend.borderpad`
|
| 732 |
+
Padding in units of fraction of font size.
|
| 733 |
+
**kwargs
|
| 734 |
+
Keyword arguments forwarded to `.HandlerBase`.
|
| 735 |
+
"""
|
| 736 |
+
self._ndivide = ndivide
|
| 737 |
+
self._pad = pad
|
| 738 |
+
super().__init__(**kwargs)
|
| 739 |
+
|
| 740 |
+
def create_artists(self, legend, orig_handle,
|
| 741 |
+
xdescent, ydescent, width, height, fontsize,
|
| 742 |
+
trans):
|
| 743 |
+
# docstring inherited
|
| 744 |
+
handler_map = legend.get_legend_handler_map()
|
| 745 |
+
|
| 746 |
+
if self._ndivide is None:
|
| 747 |
+
ndivide = len(orig_handle)
|
| 748 |
+
else:
|
| 749 |
+
ndivide = self._ndivide
|
| 750 |
+
|
| 751 |
+
if self._pad is None:
|
| 752 |
+
pad = legend.borderpad * fontsize
|
| 753 |
+
else:
|
| 754 |
+
pad = self._pad * fontsize
|
| 755 |
+
|
| 756 |
+
if ndivide > 1:
|
| 757 |
+
width = (width - pad * (ndivide - 1)) / ndivide
|
| 758 |
+
|
| 759 |
+
xds_cycle = cycle(xdescent - (width + pad) * np.arange(ndivide))
|
| 760 |
+
|
| 761 |
+
a_list = []
|
| 762 |
+
for handle1 in orig_handle:
|
| 763 |
+
handler = legend.get_legend_handler(handler_map, handle1)
|
| 764 |
+
_a_list = handler.create_artists(
|
| 765 |
+
legend, handle1,
|
| 766 |
+
next(xds_cycle), ydescent, width, height, fontsize, trans)
|
| 767 |
+
a_list.extend(_a_list)
|
| 768 |
+
|
| 769 |
+
return a_list
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
class HandlerPolyCollection(HandlerBase):
|
| 773 |
+
"""
|
| 774 |
+
Handler for `.PolyCollection` used in `~.Axes.fill_between` and
|
| 775 |
+
`~.Axes.stackplot`.
|
| 776 |
+
"""
|
| 777 |
+
def _update_prop(self, legend_handle, orig_handle):
|
| 778 |
+
def first_color(colors):
|
| 779 |
+
if colors.size == 0:
|
| 780 |
+
return (0, 0, 0, 0)
|
| 781 |
+
return tuple(colors[0])
|
| 782 |
+
|
| 783 |
+
def get_first(prop_array):
|
| 784 |
+
if len(prop_array):
|
| 785 |
+
return prop_array[0]
|
| 786 |
+
else:
|
| 787 |
+
return None
|
| 788 |
+
|
| 789 |
+
# orig_handle is a PolyCollection and legend_handle is a Patch.
|
| 790 |
+
# Directly set Patch color attributes (must be RGBA tuples).
|
| 791 |
+
legend_handle._facecolor = first_color(orig_handle.get_facecolor())
|
| 792 |
+
legend_handle._edgecolor = first_color(orig_handle.get_edgecolor())
|
| 793 |
+
legend_handle._original_facecolor = orig_handle._original_facecolor
|
| 794 |
+
legend_handle._original_edgecolor = orig_handle._original_edgecolor
|
| 795 |
+
legend_handle._fill = orig_handle.get_fill()
|
| 796 |
+
legend_handle._hatch = orig_handle.get_hatch()
|
| 797 |
+
# Hatch color is anomalous in having no getters and setters.
|
| 798 |
+
legend_handle._hatch_color = orig_handle._hatch_color
|
| 799 |
+
# Setters are fine for the remaining attributes.
|
| 800 |
+
legend_handle.set_linewidth(get_first(orig_handle.get_linewidths()))
|
| 801 |
+
legend_handle.set_linestyle(get_first(orig_handle.get_linestyles()))
|
| 802 |
+
legend_handle.set_transform(get_first(orig_handle.get_transforms()))
|
| 803 |
+
legend_handle.set_figure(orig_handle.get_figure())
|
| 804 |
+
# Alpha is already taken into account by the color attributes.
|
| 805 |
+
|
| 806 |
+
def create_artists(self, legend, orig_handle,
|
| 807 |
+
xdescent, ydescent, width, height, fontsize, trans):
|
| 808 |
+
# docstring inherited
|
| 809 |
+
p = Rectangle(xy=(-xdescent, -ydescent),
|
| 810 |
+
width=width, height=height)
|
| 811 |
+
self.update_prop(p, orig_handle, legend)
|
| 812 |
+
p.set_transform(trans)
|
| 813 |
+
return [p]
|
parrot/lib/python3.10/site-packages/matplotlib/markers.py
ADDED
|
@@ -0,0 +1,908 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
Functions to handle markers; used by the marker functionality of
|
| 3 |
+
`~matplotlib.axes.Axes.plot`, `~matplotlib.axes.Axes.scatter`, and
|
| 4 |
+
`~matplotlib.axes.Axes.errorbar`.
|
| 5 |
+
|
| 6 |
+
All possible markers are defined here:
|
| 7 |
+
|
| 8 |
+
============================== ====== =========================================
|
| 9 |
+
marker symbol description
|
| 10 |
+
============================== ====== =========================================
|
| 11 |
+
``"."`` |m00| point
|
| 12 |
+
``","`` |m01| pixel
|
| 13 |
+
``"o"`` |m02| circle
|
| 14 |
+
``"v"`` |m03| triangle_down
|
| 15 |
+
``"^"`` |m04| triangle_up
|
| 16 |
+
``"<"`` |m05| triangle_left
|
| 17 |
+
``">"`` |m06| triangle_right
|
| 18 |
+
``"1"`` |m07| tri_down
|
| 19 |
+
``"2"`` |m08| tri_up
|
| 20 |
+
``"3"`` |m09| tri_left
|
| 21 |
+
``"4"`` |m10| tri_right
|
| 22 |
+
``"8"`` |m11| octagon
|
| 23 |
+
``"s"`` |m12| square
|
| 24 |
+
``"p"`` |m13| pentagon
|
| 25 |
+
``"P"`` |m23| plus (filled)
|
| 26 |
+
``"*"`` |m14| star
|
| 27 |
+
``"h"`` |m15| hexagon1
|
| 28 |
+
``"H"`` |m16| hexagon2
|
| 29 |
+
``"+"`` |m17| plus
|
| 30 |
+
``"x"`` |m18| x
|
| 31 |
+
``"X"`` |m24| x (filled)
|
| 32 |
+
``"D"`` |m19| diamond
|
| 33 |
+
``"d"`` |m20| thin_diamond
|
| 34 |
+
``"|"`` |m21| vline
|
| 35 |
+
``"_"`` |m22| hline
|
| 36 |
+
``0`` (``TICKLEFT``) |m25| tickleft
|
| 37 |
+
``1`` (``TICKRIGHT``) |m26| tickright
|
| 38 |
+
``2`` (``TICKUP``) |m27| tickup
|
| 39 |
+
``3`` (``TICKDOWN``) |m28| tickdown
|
| 40 |
+
``4`` (``CARETLEFT``) |m29| caretleft
|
| 41 |
+
``5`` (``CARETRIGHT``) |m30| caretright
|
| 42 |
+
``6`` (``CARETUP``) |m31| caretup
|
| 43 |
+
``7`` (``CARETDOWN``) |m32| caretdown
|
| 44 |
+
``8`` (``CARETLEFTBASE``) |m33| caretleft (centered at base)
|
| 45 |
+
``9`` (``CARETRIGHTBASE``) |m34| caretright (centered at base)
|
| 46 |
+
``10`` (``CARETUPBASE``) |m35| caretup (centered at base)
|
| 47 |
+
``11`` (``CARETDOWNBASE``) |m36| caretdown (centered at base)
|
| 48 |
+
``"none"`` or ``"None"`` nothing
|
| 49 |
+
``" "`` or ``""`` nothing
|
| 50 |
+
``"$...$"`` |m37| Render the string using mathtext.
|
| 51 |
+
E.g ``"$f$"`` for marker showing the
|
| 52 |
+
letter ``f``.
|
| 53 |
+
``verts`` A list of (x, y) pairs used for Path
|
| 54 |
+
vertices. The center of the marker is
|
| 55 |
+
located at (0, 0) and the size is
|
| 56 |
+
normalized, such that the created path
|
| 57 |
+
is encapsulated inside the unit cell.
|
| 58 |
+
``path`` A `~matplotlib.path.Path` instance.
|
| 59 |
+
``(numsides, 0, angle)`` A regular polygon with ``numsides``
|
| 60 |
+
sides, rotated by ``angle``.
|
| 61 |
+
``(numsides, 1, angle)`` A star-like symbol with ``numsides``
|
| 62 |
+
sides, rotated by ``angle``.
|
| 63 |
+
``(numsides, 2, angle)`` An asterisk with ``numsides`` sides,
|
| 64 |
+
rotated by ``angle``.
|
| 65 |
+
============================== ====== =========================================
|
| 66 |
+
|
| 67 |
+
Note that special symbols can be defined via the
|
| 68 |
+
:ref:`STIX math font <mathtext>`,
|
| 69 |
+
e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer to the
|
| 70 |
+
`STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
|
| 71 |
+
Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
|
| 72 |
+
|
| 73 |
+
Integer numbers from ``0`` to ``11`` create lines and triangles. Those are
|
| 74 |
+
equally accessible via capitalized variables, like ``CARETDOWNBASE``.
|
| 75 |
+
Hence the following are equivalent::
|
| 76 |
+
|
| 77 |
+
plt.plot([1, 2, 3], marker=11)
|
| 78 |
+
plt.plot([1, 2, 3], marker=matplotlib.markers.CARETDOWNBASE)
|
| 79 |
+
|
| 80 |
+
Markers join and cap styles can be customized by creating a new instance of
|
| 81 |
+
MarkerStyle.
|
| 82 |
+
A MarkerStyle can also have a custom `~matplotlib.transforms.Transform`
|
| 83 |
+
allowing it to be arbitrarily rotated or offset.
|
| 84 |
+
|
| 85 |
+
Examples showing the use of markers:
|
| 86 |
+
|
| 87 |
+
* :doc:`/gallery/lines_bars_and_markers/marker_reference`
|
| 88 |
+
* :doc:`/gallery/lines_bars_and_markers/scatter_star_poly`
|
| 89 |
+
* :doc:`/gallery/lines_bars_and_markers/multivariate_marker_plot`
|
| 90 |
+
|
| 91 |
+
.. |m00| image:: /_static/markers/m00.png
|
| 92 |
+
.. |m01| image:: /_static/markers/m01.png
|
| 93 |
+
.. |m02| image:: /_static/markers/m02.png
|
| 94 |
+
.. |m03| image:: /_static/markers/m03.png
|
| 95 |
+
.. |m04| image:: /_static/markers/m04.png
|
| 96 |
+
.. |m05| image:: /_static/markers/m05.png
|
| 97 |
+
.. |m06| image:: /_static/markers/m06.png
|
| 98 |
+
.. |m07| image:: /_static/markers/m07.png
|
| 99 |
+
.. |m08| image:: /_static/markers/m08.png
|
| 100 |
+
.. |m09| image:: /_static/markers/m09.png
|
| 101 |
+
.. |m10| image:: /_static/markers/m10.png
|
| 102 |
+
.. |m11| image:: /_static/markers/m11.png
|
| 103 |
+
.. |m12| image:: /_static/markers/m12.png
|
| 104 |
+
.. |m13| image:: /_static/markers/m13.png
|
| 105 |
+
.. |m14| image:: /_static/markers/m14.png
|
| 106 |
+
.. |m15| image:: /_static/markers/m15.png
|
| 107 |
+
.. |m16| image:: /_static/markers/m16.png
|
| 108 |
+
.. |m17| image:: /_static/markers/m17.png
|
| 109 |
+
.. |m18| image:: /_static/markers/m18.png
|
| 110 |
+
.. |m19| image:: /_static/markers/m19.png
|
| 111 |
+
.. |m20| image:: /_static/markers/m20.png
|
| 112 |
+
.. |m21| image:: /_static/markers/m21.png
|
| 113 |
+
.. |m22| image:: /_static/markers/m22.png
|
| 114 |
+
.. |m23| image:: /_static/markers/m23.png
|
| 115 |
+
.. |m24| image:: /_static/markers/m24.png
|
| 116 |
+
.. |m25| image:: /_static/markers/m25.png
|
| 117 |
+
.. |m26| image:: /_static/markers/m26.png
|
| 118 |
+
.. |m27| image:: /_static/markers/m27.png
|
| 119 |
+
.. |m28| image:: /_static/markers/m28.png
|
| 120 |
+
.. |m29| image:: /_static/markers/m29.png
|
| 121 |
+
.. |m30| image:: /_static/markers/m30.png
|
| 122 |
+
.. |m31| image:: /_static/markers/m31.png
|
| 123 |
+
.. |m32| image:: /_static/markers/m32.png
|
| 124 |
+
.. |m33| image:: /_static/markers/m33.png
|
| 125 |
+
.. |m34| image:: /_static/markers/m34.png
|
| 126 |
+
.. |m35| image:: /_static/markers/m35.png
|
| 127 |
+
.. |m36| image:: /_static/markers/m36.png
|
| 128 |
+
.. |m37| image:: /_static/markers/m37.png
|
| 129 |
+
"""
|
| 130 |
+
import copy
|
| 131 |
+
|
| 132 |
+
from collections.abc import Sized
|
| 133 |
+
|
| 134 |
+
import numpy as np
|
| 135 |
+
|
| 136 |
+
import matplotlib as mpl
|
| 137 |
+
from . import _api, cbook
|
| 138 |
+
from .path import Path
|
| 139 |
+
from .transforms import IdentityTransform, Affine2D
|
| 140 |
+
from ._enums import JoinStyle, CapStyle
|
| 141 |
+
|
| 142 |
+
# special-purpose marker identifiers:
|
| 143 |
+
(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN,
|
| 144 |
+
CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
|
| 145 |
+
CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = range(12)
|
| 146 |
+
|
| 147 |
+
_empty_path = Path(np.empty((0, 2)))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class MarkerStyle:
|
| 151 |
+
"""
|
| 152 |
+
A class representing marker types.
|
| 153 |
+
|
| 154 |
+
Instances are immutable. If you need to change anything, create a new
|
| 155 |
+
instance.
|
| 156 |
+
|
| 157 |
+
Attributes
|
| 158 |
+
----------
|
| 159 |
+
markers : dict
|
| 160 |
+
All known markers.
|
| 161 |
+
filled_markers : tuple
|
| 162 |
+
All known filled markers. This is a subset of *markers*.
|
| 163 |
+
fillstyles : tuple
|
| 164 |
+
The supported fillstyles.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
markers = {
|
| 168 |
+
'.': 'point',
|
| 169 |
+
',': 'pixel',
|
| 170 |
+
'o': 'circle',
|
| 171 |
+
'v': 'triangle_down',
|
| 172 |
+
'^': 'triangle_up',
|
| 173 |
+
'<': 'triangle_left',
|
| 174 |
+
'>': 'triangle_right',
|
| 175 |
+
'1': 'tri_down',
|
| 176 |
+
'2': 'tri_up',
|
| 177 |
+
'3': 'tri_left',
|
| 178 |
+
'4': 'tri_right',
|
| 179 |
+
'8': 'octagon',
|
| 180 |
+
's': 'square',
|
| 181 |
+
'p': 'pentagon',
|
| 182 |
+
'*': 'star',
|
| 183 |
+
'h': 'hexagon1',
|
| 184 |
+
'H': 'hexagon2',
|
| 185 |
+
'+': 'plus',
|
| 186 |
+
'x': 'x',
|
| 187 |
+
'D': 'diamond',
|
| 188 |
+
'd': 'thin_diamond',
|
| 189 |
+
'|': 'vline',
|
| 190 |
+
'_': 'hline',
|
| 191 |
+
'P': 'plus_filled',
|
| 192 |
+
'X': 'x_filled',
|
| 193 |
+
TICKLEFT: 'tickleft',
|
| 194 |
+
TICKRIGHT: 'tickright',
|
| 195 |
+
TICKUP: 'tickup',
|
| 196 |
+
TICKDOWN: 'tickdown',
|
| 197 |
+
CARETLEFT: 'caretleft',
|
| 198 |
+
CARETRIGHT: 'caretright',
|
| 199 |
+
CARETUP: 'caretup',
|
| 200 |
+
CARETDOWN: 'caretdown',
|
| 201 |
+
CARETLEFTBASE: 'caretleftbase',
|
| 202 |
+
CARETRIGHTBASE: 'caretrightbase',
|
| 203 |
+
CARETUPBASE: 'caretupbase',
|
| 204 |
+
CARETDOWNBASE: 'caretdownbase',
|
| 205 |
+
"None": 'nothing',
|
| 206 |
+
"none": 'nothing',
|
| 207 |
+
' ': 'nothing',
|
| 208 |
+
'': 'nothing'
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
# Just used for informational purposes. is_filled()
|
| 212 |
+
# is calculated in the _set_* functions.
|
| 213 |
+
filled_markers = (
|
| 214 |
+
'.', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd',
|
| 215 |
+
'P', 'X')
|
| 216 |
+
|
| 217 |
+
fillstyles = ('full', 'left', 'right', 'bottom', 'top', 'none')
|
| 218 |
+
_half_fillstyles = ('left', 'right', 'bottom', 'top')
|
| 219 |
+
|
| 220 |
+
def __init__(self, marker,
|
| 221 |
+
fillstyle=None, transform=None, capstyle=None, joinstyle=None):
|
| 222 |
+
"""
|
| 223 |
+
Parameters
|
| 224 |
+
----------
|
| 225 |
+
marker : str, array-like, Path, MarkerStyle
|
| 226 |
+
- Another instance of `MarkerStyle` copies the details of that *marker*.
|
| 227 |
+
- For other possible marker values, see the module docstring
|
| 228 |
+
`matplotlib.markers`.
|
| 229 |
+
|
| 230 |
+
fillstyle : str, default: :rc:`markers.fillstyle`
|
| 231 |
+
One of 'full', 'left', 'right', 'bottom', 'top', 'none'.
|
| 232 |
+
|
| 233 |
+
transform : `~matplotlib.transforms.Transform`, optional
|
| 234 |
+
Transform that will be combined with the native transform of the
|
| 235 |
+
marker.
|
| 236 |
+
|
| 237 |
+
capstyle : `.CapStyle` or %(CapStyle)s, optional
|
| 238 |
+
Cap style that will override the default cap style of the marker.
|
| 239 |
+
|
| 240 |
+
joinstyle : `.JoinStyle` or %(JoinStyle)s, optional
|
| 241 |
+
Join style that will override the default join style of the marker.
|
| 242 |
+
"""
|
| 243 |
+
self._marker_function = None
|
| 244 |
+
self._user_transform = transform
|
| 245 |
+
self._user_capstyle = CapStyle(capstyle) if capstyle is not None else None
|
| 246 |
+
self._user_joinstyle = JoinStyle(joinstyle) if joinstyle is not None else None
|
| 247 |
+
self._set_fillstyle(fillstyle)
|
| 248 |
+
self._set_marker(marker)
|
| 249 |
+
|
| 250 |
+
def _recache(self):
|
| 251 |
+
if self._marker_function is None:
|
| 252 |
+
return
|
| 253 |
+
self._path = _empty_path
|
| 254 |
+
self._transform = IdentityTransform()
|
| 255 |
+
self._alt_path = None
|
| 256 |
+
self._alt_transform = None
|
| 257 |
+
self._snap_threshold = None
|
| 258 |
+
self._joinstyle = JoinStyle.round
|
| 259 |
+
self._capstyle = self._user_capstyle or CapStyle.butt
|
| 260 |
+
# Initial guess: Assume the marker is filled unless the fillstyle is
|
| 261 |
+
# set to 'none'. The marker function will override this for unfilled
|
| 262 |
+
# markers.
|
| 263 |
+
self._filled = self._fillstyle != 'none'
|
| 264 |
+
self._marker_function()
|
| 265 |
+
|
| 266 |
+
def __bool__(self):
|
| 267 |
+
return bool(len(self._path.vertices))
|
| 268 |
+
|
| 269 |
+
def is_filled(self):
|
| 270 |
+
return self._filled
|
| 271 |
+
|
| 272 |
+
def get_fillstyle(self):
|
| 273 |
+
return self._fillstyle
|
| 274 |
+
|
| 275 |
+
def _set_fillstyle(self, fillstyle):
|
| 276 |
+
"""
|
| 277 |
+
Set the fillstyle.
|
| 278 |
+
|
| 279 |
+
Parameters
|
| 280 |
+
----------
|
| 281 |
+
fillstyle : {'full', 'left', 'right', 'bottom', 'top', 'none'}
|
| 282 |
+
The part of the marker surface that is colored with
|
| 283 |
+
markerfacecolor.
|
| 284 |
+
"""
|
| 285 |
+
if fillstyle is None:
|
| 286 |
+
fillstyle = mpl.rcParams['markers.fillstyle']
|
| 287 |
+
_api.check_in_list(self.fillstyles, fillstyle=fillstyle)
|
| 288 |
+
self._fillstyle = fillstyle
|
| 289 |
+
|
| 290 |
+
def get_joinstyle(self):
|
| 291 |
+
return self._joinstyle.name
|
| 292 |
+
|
| 293 |
+
def get_capstyle(self):
|
| 294 |
+
return self._capstyle.name
|
| 295 |
+
|
| 296 |
+
def get_marker(self):
|
| 297 |
+
return self._marker
|
| 298 |
+
|
| 299 |
+
def _set_marker(self, marker):
|
| 300 |
+
"""
|
| 301 |
+
Set the marker.
|
| 302 |
+
|
| 303 |
+
Parameters
|
| 304 |
+
----------
|
| 305 |
+
marker : str, array-like, Path, MarkerStyle
|
| 306 |
+
- Another instance of `MarkerStyle` copies the details of that *marker*.
|
| 307 |
+
- For other possible marker values see the module docstring
|
| 308 |
+
`matplotlib.markers`.
|
| 309 |
+
"""
|
| 310 |
+
if isinstance(marker, str) and cbook.is_math_text(marker):
|
| 311 |
+
self._marker_function = self._set_mathtext_path
|
| 312 |
+
elif isinstance(marker, (int, str)) and marker in self.markers:
|
| 313 |
+
self._marker_function = getattr(self, '_set_' + self.markers[marker])
|
| 314 |
+
elif (isinstance(marker, np.ndarray) and marker.ndim == 2 and
|
| 315 |
+
marker.shape[1] == 2):
|
| 316 |
+
self._marker_function = self._set_vertices
|
| 317 |
+
elif isinstance(marker, Path):
|
| 318 |
+
self._marker_function = self._set_path_marker
|
| 319 |
+
elif (isinstance(marker, Sized) and len(marker) in (2, 3) and
|
| 320 |
+
marker[1] in (0, 1, 2)):
|
| 321 |
+
self._marker_function = self._set_tuple_marker
|
| 322 |
+
elif isinstance(marker, MarkerStyle):
|
| 323 |
+
self.__dict__ = copy.deepcopy(marker.__dict__)
|
| 324 |
+
else:
|
| 325 |
+
try:
|
| 326 |
+
Path(marker)
|
| 327 |
+
self._marker_function = self._set_vertices
|
| 328 |
+
except ValueError as err:
|
| 329 |
+
raise ValueError(
|
| 330 |
+
f'Unrecognized marker style {marker!r}') from err
|
| 331 |
+
|
| 332 |
+
if not isinstance(marker, MarkerStyle):
|
| 333 |
+
self._marker = marker
|
| 334 |
+
self._recache()
|
| 335 |
+
|
| 336 |
+
def get_path(self):
|
| 337 |
+
"""
|
| 338 |
+
Return a `.Path` for the primary part of the marker.
|
| 339 |
+
|
| 340 |
+
For unfilled markers this is the whole marker, for filled markers,
|
| 341 |
+
this is the area to be drawn with *markerfacecolor*.
|
| 342 |
+
"""
|
| 343 |
+
return self._path
|
| 344 |
+
|
| 345 |
+
def get_transform(self):
|
| 346 |
+
"""
|
| 347 |
+
Return the transform to be applied to the `.Path` from
|
| 348 |
+
`MarkerStyle.get_path()`.
|
| 349 |
+
"""
|
| 350 |
+
if self._user_transform is None:
|
| 351 |
+
return self._transform.frozen()
|
| 352 |
+
else:
|
| 353 |
+
return (self._transform + self._user_transform).frozen()
|
| 354 |
+
|
| 355 |
+
def get_alt_path(self):
|
| 356 |
+
"""
|
| 357 |
+
Return a `.Path` for the alternate part of the marker.
|
| 358 |
+
|
| 359 |
+
For unfilled markers, this is *None*; for filled markers, this is the
|
| 360 |
+
area to be drawn with *markerfacecoloralt*.
|
| 361 |
+
"""
|
| 362 |
+
return self._alt_path
|
| 363 |
+
|
| 364 |
+
def get_alt_transform(self):
|
| 365 |
+
"""
|
| 366 |
+
Return the transform to be applied to the `.Path` from
|
| 367 |
+
`MarkerStyle.get_alt_path()`.
|
| 368 |
+
"""
|
| 369 |
+
if self._user_transform is None:
|
| 370 |
+
return self._alt_transform.frozen()
|
| 371 |
+
else:
|
| 372 |
+
return (self._alt_transform + self._user_transform).frozen()
|
| 373 |
+
|
| 374 |
+
def get_snap_threshold(self):
|
| 375 |
+
return self._snap_threshold
|
| 376 |
+
|
| 377 |
+
def get_user_transform(self):
|
| 378 |
+
"""Return user supplied part of marker transform."""
|
| 379 |
+
if self._user_transform is not None:
|
| 380 |
+
return self._user_transform.frozen()
|
| 381 |
+
|
| 382 |
+
def transformed(self, transform):
|
| 383 |
+
"""
|
| 384 |
+
Return a new version of this marker with the transform applied.
|
| 385 |
+
|
| 386 |
+
Parameters
|
| 387 |
+
----------
|
| 388 |
+
transform : `~matplotlib.transforms.Affine2D`
|
| 389 |
+
Transform will be combined with current user supplied transform.
|
| 390 |
+
"""
|
| 391 |
+
new_marker = MarkerStyle(self)
|
| 392 |
+
if new_marker._user_transform is not None:
|
| 393 |
+
new_marker._user_transform += transform
|
| 394 |
+
else:
|
| 395 |
+
new_marker._user_transform = transform
|
| 396 |
+
return new_marker
|
| 397 |
+
|
| 398 |
+
def rotated(self, *, deg=None, rad=None):
|
| 399 |
+
"""
|
| 400 |
+
Return a new version of this marker rotated by specified angle.
|
| 401 |
+
|
| 402 |
+
Parameters
|
| 403 |
+
----------
|
| 404 |
+
deg : float, optional
|
| 405 |
+
Rotation angle in degrees.
|
| 406 |
+
|
| 407 |
+
rad : float, optional
|
| 408 |
+
Rotation angle in radians.
|
| 409 |
+
|
| 410 |
+
.. note:: You must specify exactly one of deg or rad.
|
| 411 |
+
"""
|
| 412 |
+
if deg is None and rad is None:
|
| 413 |
+
raise ValueError('One of deg or rad is required')
|
| 414 |
+
if deg is not None and rad is not None:
|
| 415 |
+
raise ValueError('Only one of deg and rad can be supplied')
|
| 416 |
+
new_marker = MarkerStyle(self)
|
| 417 |
+
if new_marker._user_transform is None:
|
| 418 |
+
new_marker._user_transform = Affine2D()
|
| 419 |
+
|
| 420 |
+
if deg is not None:
|
| 421 |
+
new_marker._user_transform.rotate_deg(deg)
|
| 422 |
+
if rad is not None:
|
| 423 |
+
new_marker._user_transform.rotate(rad)
|
| 424 |
+
|
| 425 |
+
return new_marker
|
| 426 |
+
|
| 427 |
+
def scaled(self, sx, sy=None):
|
| 428 |
+
"""
|
| 429 |
+
Return new marker scaled by specified scale factors.
|
| 430 |
+
|
| 431 |
+
If *sy* is not given, the same scale is applied in both the *x*- and
|
| 432 |
+
*y*-directions.
|
| 433 |
+
|
| 434 |
+
Parameters
|
| 435 |
+
----------
|
| 436 |
+
sx : float
|
| 437 |
+
*X*-direction scaling factor.
|
| 438 |
+
sy : float, optional
|
| 439 |
+
*Y*-direction scaling factor.
|
| 440 |
+
"""
|
| 441 |
+
if sy is None:
|
| 442 |
+
sy = sx
|
| 443 |
+
|
| 444 |
+
new_marker = MarkerStyle(self)
|
| 445 |
+
_transform = new_marker._user_transform or Affine2D()
|
| 446 |
+
new_marker._user_transform = _transform.scale(sx, sy)
|
| 447 |
+
return new_marker
|
| 448 |
+
|
| 449 |
+
def _set_nothing(self):
|
| 450 |
+
self._filled = False
|
| 451 |
+
|
| 452 |
+
def _set_custom_marker(self, path):
|
| 453 |
+
rescale = np.max(np.abs(path.vertices)) # max of x's and y's.
|
| 454 |
+
self._transform = Affine2D().scale(0.5 / rescale)
|
| 455 |
+
self._path = path
|
| 456 |
+
|
| 457 |
+
def _set_path_marker(self):
|
| 458 |
+
self._set_custom_marker(self._marker)
|
| 459 |
+
|
| 460 |
+
def _set_vertices(self):
|
| 461 |
+
self._set_custom_marker(Path(self._marker))
|
| 462 |
+
|
| 463 |
+
def _set_tuple_marker(self):
|
| 464 |
+
marker = self._marker
|
| 465 |
+
if len(marker) == 2:
|
| 466 |
+
numsides, rotation = marker[0], 0.0
|
| 467 |
+
elif len(marker) == 3:
|
| 468 |
+
numsides, rotation = marker[0], marker[2]
|
| 469 |
+
symstyle = marker[1]
|
| 470 |
+
if symstyle == 0:
|
| 471 |
+
self._path = Path.unit_regular_polygon(numsides)
|
| 472 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 473 |
+
elif symstyle == 1:
|
| 474 |
+
self._path = Path.unit_regular_star(numsides)
|
| 475 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.bevel
|
| 476 |
+
elif symstyle == 2:
|
| 477 |
+
self._path = Path.unit_regular_asterisk(numsides)
|
| 478 |
+
self._filled = False
|
| 479 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.bevel
|
| 480 |
+
else:
|
| 481 |
+
raise ValueError(f"Unexpected tuple marker: {marker}")
|
| 482 |
+
self._transform = Affine2D().scale(0.5).rotate_deg(rotation)
|
| 483 |
+
|
| 484 |
+
def _set_mathtext_path(self):
|
| 485 |
+
"""
|
| 486 |
+
Draw mathtext markers '$...$' using `.TextPath` object.
|
| 487 |
+
|
| 488 |
+
Submitted by tcb
|
| 489 |
+
"""
|
| 490 |
+
from matplotlib.text import TextPath
|
| 491 |
+
|
| 492 |
+
# again, the properties could be initialised just once outside
|
| 493 |
+
# this function
|
| 494 |
+
text = TextPath(xy=(0, 0), s=self.get_marker(),
|
| 495 |
+
usetex=mpl.rcParams['text.usetex'])
|
| 496 |
+
if len(text.vertices) == 0:
|
| 497 |
+
return
|
| 498 |
+
|
| 499 |
+
bbox = text.get_extents()
|
| 500 |
+
max_dim = max(bbox.width, bbox.height)
|
| 501 |
+
self._transform = (
|
| 502 |
+
Affine2D()
|
| 503 |
+
.translate(-bbox.xmin + 0.5 * -bbox.width, -bbox.ymin + 0.5 * -bbox.height)
|
| 504 |
+
.scale(1.0 / max_dim))
|
| 505 |
+
self._path = text
|
| 506 |
+
self._snap = False
|
| 507 |
+
|
| 508 |
+
def _half_fill(self):
|
| 509 |
+
return self.get_fillstyle() in self._half_fillstyles
|
| 510 |
+
|
| 511 |
+
def _set_circle(self, size=1.0):
|
| 512 |
+
self._transform = Affine2D().scale(0.5 * size)
|
| 513 |
+
self._snap_threshold = np.inf
|
| 514 |
+
if not self._half_fill():
|
| 515 |
+
self._path = Path.unit_circle()
|
| 516 |
+
else:
|
| 517 |
+
self._path = self._alt_path = Path.unit_circle_righthalf()
|
| 518 |
+
fs = self.get_fillstyle()
|
| 519 |
+
self._transform.rotate_deg(
|
| 520 |
+
{'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs])
|
| 521 |
+
self._alt_transform = self._transform.frozen().rotate_deg(180.)
|
| 522 |
+
|
| 523 |
+
def _set_point(self):
|
| 524 |
+
self._set_circle(size=0.5)
|
| 525 |
+
|
| 526 |
+
def _set_pixel(self):
|
| 527 |
+
self._path = Path.unit_rectangle()
|
| 528 |
+
# Ideally, you'd want -0.5, -0.5 here, but then the snapping
|
| 529 |
+
# algorithm in the Agg backend will round this to a 2x2
|
| 530 |
+
# rectangle from (-1, -1) to (1, 1). By offsetting it
|
| 531 |
+
# slightly, we can force it to be (0, 0) to (1, 1), which both
|
| 532 |
+
# makes it only be a single pixel and places it correctly
|
| 533 |
+
# aligned to 1-width stroking (i.e. the ticks). This hack is
|
| 534 |
+
# the best of a number of bad alternatives, mainly because the
|
| 535 |
+
# backends are not aware of what marker is actually being used
|
| 536 |
+
# beyond just its path data.
|
| 537 |
+
self._transform = Affine2D().translate(-0.49999, -0.49999)
|
| 538 |
+
self._snap_threshold = None
|
| 539 |
+
|
| 540 |
+
_triangle_path = Path._create_closed([[0, 1], [-1, -1], [1, -1]])
|
| 541 |
+
# Going down halfway looks to small. Golden ratio is too far.
|
| 542 |
+
_triangle_path_u = Path._create_closed([[0, 1], [-3/5, -1/5], [3/5, -1/5]])
|
| 543 |
+
_triangle_path_d = Path._create_closed(
|
| 544 |
+
[[-3/5, -1/5], [3/5, -1/5], [1, -1], [-1, -1]])
|
| 545 |
+
_triangle_path_l = Path._create_closed([[0, 1], [0, -1], [-1, -1]])
|
| 546 |
+
_triangle_path_r = Path._create_closed([[0, 1], [0, -1], [1, -1]])
|
| 547 |
+
|
| 548 |
+
def _set_triangle(self, rot, skip):
|
| 549 |
+
self._transform = Affine2D().scale(0.5).rotate_deg(rot)
|
| 550 |
+
self._snap_threshold = 5.0
|
| 551 |
+
|
| 552 |
+
if not self._half_fill():
|
| 553 |
+
self._path = self._triangle_path
|
| 554 |
+
else:
|
| 555 |
+
mpaths = [self._triangle_path_u,
|
| 556 |
+
self._triangle_path_l,
|
| 557 |
+
self._triangle_path_d,
|
| 558 |
+
self._triangle_path_r]
|
| 559 |
+
|
| 560 |
+
fs = self.get_fillstyle()
|
| 561 |
+
if fs == 'top':
|
| 562 |
+
self._path = mpaths[(0 + skip) % 4]
|
| 563 |
+
self._alt_path = mpaths[(2 + skip) % 4]
|
| 564 |
+
elif fs == 'bottom':
|
| 565 |
+
self._path = mpaths[(2 + skip) % 4]
|
| 566 |
+
self._alt_path = mpaths[(0 + skip) % 4]
|
| 567 |
+
elif fs == 'left':
|
| 568 |
+
self._path = mpaths[(1 + skip) % 4]
|
| 569 |
+
self._alt_path = mpaths[(3 + skip) % 4]
|
| 570 |
+
else:
|
| 571 |
+
self._path = mpaths[(3 + skip) % 4]
|
| 572 |
+
self._alt_path = mpaths[(1 + skip) % 4]
|
| 573 |
+
|
| 574 |
+
self._alt_transform = self._transform
|
| 575 |
+
|
| 576 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 577 |
+
|
| 578 |
+
def _set_triangle_up(self):
|
| 579 |
+
return self._set_triangle(0.0, 0)
|
| 580 |
+
|
| 581 |
+
def _set_triangle_down(self):
|
| 582 |
+
return self._set_triangle(180.0, 2)
|
| 583 |
+
|
| 584 |
+
def _set_triangle_left(self):
|
| 585 |
+
return self._set_triangle(90.0, 3)
|
| 586 |
+
|
| 587 |
+
def _set_triangle_right(self):
|
| 588 |
+
return self._set_triangle(270.0, 1)
|
| 589 |
+
|
| 590 |
+
def _set_square(self):
|
| 591 |
+
self._transform = Affine2D().translate(-0.5, -0.5)
|
| 592 |
+
self._snap_threshold = 2.0
|
| 593 |
+
if not self._half_fill():
|
| 594 |
+
self._path = Path.unit_rectangle()
|
| 595 |
+
else:
|
| 596 |
+
# Build a bottom filled square out of two rectangles, one filled.
|
| 597 |
+
self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5],
|
| 598 |
+
[0.0, 0.5], [0.0, 0.0]])
|
| 599 |
+
self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0],
|
| 600 |
+
[0.0, 1.0], [0.0, 0.5]])
|
| 601 |
+
fs = self.get_fillstyle()
|
| 602 |
+
rotate = {'bottom': 0, 'right': 90, 'top': 180, 'left': 270}[fs]
|
| 603 |
+
self._transform.rotate_deg(rotate)
|
| 604 |
+
self._alt_transform = self._transform
|
| 605 |
+
|
| 606 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 607 |
+
|
| 608 |
+
def _set_diamond(self):
|
| 609 |
+
self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45)
|
| 610 |
+
self._snap_threshold = 5.0
|
| 611 |
+
if not self._half_fill():
|
| 612 |
+
self._path = Path.unit_rectangle()
|
| 613 |
+
else:
|
| 614 |
+
self._path = Path([[0, 0], [1, 0], [1, 1], [0, 0]])
|
| 615 |
+
self._alt_path = Path([[0, 0], [0, 1], [1, 1], [0, 0]])
|
| 616 |
+
fs = self.get_fillstyle()
|
| 617 |
+
rotate = {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs]
|
| 618 |
+
self._transform.rotate_deg(rotate)
|
| 619 |
+
self._alt_transform = self._transform
|
| 620 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 621 |
+
|
| 622 |
+
def _set_thin_diamond(self):
|
| 623 |
+
self._set_diamond()
|
| 624 |
+
self._transform.scale(0.6, 1.0)
|
| 625 |
+
|
| 626 |
+
def _set_pentagon(self):
|
| 627 |
+
self._transform = Affine2D().scale(0.5)
|
| 628 |
+
self._snap_threshold = 5.0
|
| 629 |
+
|
| 630 |
+
polypath = Path.unit_regular_polygon(5)
|
| 631 |
+
|
| 632 |
+
if not self._half_fill():
|
| 633 |
+
self._path = polypath
|
| 634 |
+
else:
|
| 635 |
+
verts = polypath.vertices
|
| 636 |
+
y = (1 + np.sqrt(5)) / 4.
|
| 637 |
+
top = Path(verts[[0, 1, 4, 0]])
|
| 638 |
+
bottom = Path(verts[[1, 2, 3, 4, 1]])
|
| 639 |
+
left = Path([verts[0], verts[1], verts[2], [0, -y], verts[0]])
|
| 640 |
+
right = Path([verts[0], verts[4], verts[3], [0, -y], verts[0]])
|
| 641 |
+
self._path, self._alt_path = {
|
| 642 |
+
'top': (top, bottom), 'bottom': (bottom, top),
|
| 643 |
+
'left': (left, right), 'right': (right, left),
|
| 644 |
+
}[self.get_fillstyle()]
|
| 645 |
+
self._alt_transform = self._transform
|
| 646 |
+
|
| 647 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 648 |
+
|
| 649 |
+
def _set_star(self):
|
| 650 |
+
self._transform = Affine2D().scale(0.5)
|
| 651 |
+
self._snap_threshold = 5.0
|
| 652 |
+
|
| 653 |
+
polypath = Path.unit_regular_star(5, innerCircle=0.381966)
|
| 654 |
+
|
| 655 |
+
if not self._half_fill():
|
| 656 |
+
self._path = polypath
|
| 657 |
+
else:
|
| 658 |
+
verts = polypath.vertices
|
| 659 |
+
top = Path(np.concatenate([verts[0:4], verts[7:10], verts[0:1]]))
|
| 660 |
+
bottom = Path(np.concatenate([verts[3:8], verts[3:4]]))
|
| 661 |
+
left = Path(np.concatenate([verts[0:6], verts[0:1]]))
|
| 662 |
+
right = Path(np.concatenate([verts[0:1], verts[5:10], verts[0:1]]))
|
| 663 |
+
self._path, self._alt_path = {
|
| 664 |
+
'top': (top, bottom), 'bottom': (bottom, top),
|
| 665 |
+
'left': (left, right), 'right': (right, left),
|
| 666 |
+
}[self.get_fillstyle()]
|
| 667 |
+
self._alt_transform = self._transform
|
| 668 |
+
|
| 669 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.bevel
|
| 670 |
+
|
| 671 |
+
def _set_hexagon1(self):
|
| 672 |
+
self._transform = Affine2D().scale(0.5)
|
| 673 |
+
self._snap_threshold = None
|
| 674 |
+
|
| 675 |
+
polypath = Path.unit_regular_polygon(6)
|
| 676 |
+
|
| 677 |
+
if not self._half_fill():
|
| 678 |
+
self._path = polypath
|
| 679 |
+
else:
|
| 680 |
+
verts = polypath.vertices
|
| 681 |
+
# not drawing inside lines
|
| 682 |
+
x = np.abs(np.cos(5 * np.pi / 6.))
|
| 683 |
+
top = Path(np.concatenate([[(-x, 0)], verts[[1, 0, 5]], [(x, 0)]]))
|
| 684 |
+
bottom = Path(np.concatenate([[(-x, 0)], verts[2:5], [(x, 0)]]))
|
| 685 |
+
left = Path(verts[0:4])
|
| 686 |
+
right = Path(verts[[0, 5, 4, 3]])
|
| 687 |
+
self._path, self._alt_path = {
|
| 688 |
+
'top': (top, bottom), 'bottom': (bottom, top),
|
| 689 |
+
'left': (left, right), 'right': (right, left),
|
| 690 |
+
}[self.get_fillstyle()]
|
| 691 |
+
self._alt_transform = self._transform
|
| 692 |
+
|
| 693 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 694 |
+
|
| 695 |
+
def _set_hexagon2(self):
|
| 696 |
+
self._transform = Affine2D().scale(0.5).rotate_deg(30)
|
| 697 |
+
self._snap_threshold = None
|
| 698 |
+
|
| 699 |
+
polypath = Path.unit_regular_polygon(6)
|
| 700 |
+
|
| 701 |
+
if not self._half_fill():
|
| 702 |
+
self._path = polypath
|
| 703 |
+
else:
|
| 704 |
+
verts = polypath.vertices
|
| 705 |
+
# not drawing inside lines
|
| 706 |
+
x, y = np.sqrt(3) / 4, 3 / 4.
|
| 707 |
+
top = Path(verts[[1, 0, 5, 4, 1]])
|
| 708 |
+
bottom = Path(verts[1:5])
|
| 709 |
+
left = Path(np.concatenate([
|
| 710 |
+
[(x, y)], verts[:3], [(-x, -y), (x, y)]]))
|
| 711 |
+
right = Path(np.concatenate([
|
| 712 |
+
[(x, y)], verts[5:2:-1], [(-x, -y)]]))
|
| 713 |
+
self._path, self._alt_path = {
|
| 714 |
+
'top': (top, bottom), 'bottom': (bottom, top),
|
| 715 |
+
'left': (left, right), 'right': (right, left),
|
| 716 |
+
}[self.get_fillstyle()]
|
| 717 |
+
self._alt_transform = self._transform
|
| 718 |
+
|
| 719 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 720 |
+
|
| 721 |
+
def _set_octagon(self):
|
| 722 |
+
self._transform = Affine2D().scale(0.5)
|
| 723 |
+
self._snap_threshold = 5.0
|
| 724 |
+
|
| 725 |
+
polypath = Path.unit_regular_polygon(8)
|
| 726 |
+
|
| 727 |
+
if not self._half_fill():
|
| 728 |
+
self._transform.rotate_deg(22.5)
|
| 729 |
+
self._path = polypath
|
| 730 |
+
else:
|
| 731 |
+
x = np.sqrt(2.) / 4.
|
| 732 |
+
self._path = self._alt_path = Path(
|
| 733 |
+
[[0, -1], [0, 1], [-x, 1], [-1, x],
|
| 734 |
+
[-1, -x], [-x, -1], [0, -1]])
|
| 735 |
+
fs = self.get_fillstyle()
|
| 736 |
+
self._transform.rotate_deg(
|
| 737 |
+
{'left': 0, 'bottom': 90, 'right': 180, 'top': 270}[fs])
|
| 738 |
+
self._alt_transform = self._transform.frozen().rotate_deg(180.0)
|
| 739 |
+
|
| 740 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 741 |
+
|
| 742 |
+
_line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]])
|
| 743 |
+
|
| 744 |
+
def _set_vline(self):
|
| 745 |
+
self._transform = Affine2D().scale(0.5)
|
| 746 |
+
self._snap_threshold = 1.0
|
| 747 |
+
self._filled = False
|
| 748 |
+
self._path = self._line_marker_path
|
| 749 |
+
|
| 750 |
+
def _set_hline(self):
|
| 751 |
+
self._set_vline()
|
| 752 |
+
self._transform = self._transform.rotate_deg(90)
|
| 753 |
+
|
| 754 |
+
_tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]])
|
| 755 |
+
|
| 756 |
+
def _set_tickleft(self):
|
| 757 |
+
self._transform = Affine2D().scale(-1.0, 1.0)
|
| 758 |
+
self._snap_threshold = 1.0
|
| 759 |
+
self._filled = False
|
| 760 |
+
self._path = self._tickhoriz_path
|
| 761 |
+
|
| 762 |
+
def _set_tickright(self):
|
| 763 |
+
self._transform = Affine2D().scale(1.0, 1.0)
|
| 764 |
+
self._snap_threshold = 1.0
|
| 765 |
+
self._filled = False
|
| 766 |
+
self._path = self._tickhoriz_path
|
| 767 |
+
|
| 768 |
+
_tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]])
|
| 769 |
+
|
| 770 |
+
def _set_tickup(self):
|
| 771 |
+
self._transform = Affine2D().scale(1.0, 1.0)
|
| 772 |
+
self._snap_threshold = 1.0
|
| 773 |
+
self._filled = False
|
| 774 |
+
self._path = self._tickvert_path
|
| 775 |
+
|
| 776 |
+
def _set_tickdown(self):
|
| 777 |
+
self._transform = Affine2D().scale(1.0, -1.0)
|
| 778 |
+
self._snap_threshold = 1.0
|
| 779 |
+
self._filled = False
|
| 780 |
+
self._path = self._tickvert_path
|
| 781 |
+
|
| 782 |
+
_tri_path = Path([[0.0, 0.0], [0.0, -1.0],
|
| 783 |
+
[0.0, 0.0], [0.8, 0.5],
|
| 784 |
+
[0.0, 0.0], [-0.8, 0.5]],
|
| 785 |
+
[Path.MOVETO, Path.LINETO,
|
| 786 |
+
Path.MOVETO, Path.LINETO,
|
| 787 |
+
Path.MOVETO, Path.LINETO])
|
| 788 |
+
|
| 789 |
+
def _set_tri_down(self):
|
| 790 |
+
self._transform = Affine2D().scale(0.5)
|
| 791 |
+
self._snap_threshold = 5.0
|
| 792 |
+
self._filled = False
|
| 793 |
+
self._path = self._tri_path
|
| 794 |
+
|
| 795 |
+
def _set_tri_up(self):
|
| 796 |
+
self._set_tri_down()
|
| 797 |
+
self._transform = self._transform.rotate_deg(180)
|
| 798 |
+
|
| 799 |
+
def _set_tri_left(self):
|
| 800 |
+
self._set_tri_down()
|
| 801 |
+
self._transform = self._transform.rotate_deg(270)
|
| 802 |
+
|
| 803 |
+
def _set_tri_right(self):
|
| 804 |
+
self._set_tri_down()
|
| 805 |
+
self._transform = self._transform.rotate_deg(90)
|
| 806 |
+
|
| 807 |
+
_caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]])
|
| 808 |
+
|
| 809 |
+
def _set_caretdown(self):
|
| 810 |
+
self._transform = Affine2D().scale(0.5)
|
| 811 |
+
self._snap_threshold = 3.0
|
| 812 |
+
self._filled = False
|
| 813 |
+
self._path = self._caret_path
|
| 814 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 815 |
+
|
| 816 |
+
def _set_caretup(self):
|
| 817 |
+
self._set_caretdown()
|
| 818 |
+
self._transform = self._transform.rotate_deg(180)
|
| 819 |
+
|
| 820 |
+
def _set_caretleft(self):
|
| 821 |
+
self._set_caretdown()
|
| 822 |
+
self._transform = self._transform.rotate_deg(270)
|
| 823 |
+
|
| 824 |
+
def _set_caretright(self):
|
| 825 |
+
self._set_caretdown()
|
| 826 |
+
self._transform = self._transform.rotate_deg(90)
|
| 827 |
+
|
| 828 |
+
_caret_path_base = Path([[-1.0, 0.0], [0.0, -1.5], [1.0, 0]])
|
| 829 |
+
|
| 830 |
+
def _set_caretdownbase(self):
|
| 831 |
+
self._set_caretdown()
|
| 832 |
+
self._path = self._caret_path_base
|
| 833 |
+
|
| 834 |
+
def _set_caretupbase(self):
|
| 835 |
+
self._set_caretdownbase()
|
| 836 |
+
self._transform = self._transform.rotate_deg(180)
|
| 837 |
+
|
| 838 |
+
def _set_caretleftbase(self):
|
| 839 |
+
self._set_caretdownbase()
|
| 840 |
+
self._transform = self._transform.rotate_deg(270)
|
| 841 |
+
|
| 842 |
+
def _set_caretrightbase(self):
|
| 843 |
+
self._set_caretdownbase()
|
| 844 |
+
self._transform = self._transform.rotate_deg(90)
|
| 845 |
+
|
| 846 |
+
_plus_path = Path([[-1.0, 0.0], [1.0, 0.0],
|
| 847 |
+
[0.0, -1.0], [0.0, 1.0]],
|
| 848 |
+
[Path.MOVETO, Path.LINETO,
|
| 849 |
+
Path.MOVETO, Path.LINETO])
|
| 850 |
+
|
| 851 |
+
def _set_plus(self):
|
| 852 |
+
self._transform = Affine2D().scale(0.5)
|
| 853 |
+
self._snap_threshold = 1.0
|
| 854 |
+
self._filled = False
|
| 855 |
+
self._path = self._plus_path
|
| 856 |
+
|
| 857 |
+
_x_path = Path([[-1.0, -1.0], [1.0, 1.0],
|
| 858 |
+
[-1.0, 1.0], [1.0, -1.0]],
|
| 859 |
+
[Path.MOVETO, Path.LINETO,
|
| 860 |
+
Path.MOVETO, Path.LINETO])
|
| 861 |
+
|
| 862 |
+
def _set_x(self):
|
| 863 |
+
self._transform = Affine2D().scale(0.5)
|
| 864 |
+
self._snap_threshold = 3.0
|
| 865 |
+
self._filled = False
|
| 866 |
+
self._path = self._x_path
|
| 867 |
+
|
| 868 |
+
_plus_filled_path = Path._create_closed(np.array([
|
| 869 |
+
(-1, -3), (+1, -3), (+1, -1), (+3, -1), (+3, +1), (+1, +1),
|
| 870 |
+
(+1, +3), (-1, +3), (-1, +1), (-3, +1), (-3, -1), (-1, -1)]) / 6)
|
| 871 |
+
_plus_filled_path_t = Path._create_closed(np.array([
|
| 872 |
+
(+3, 0), (+3, +1), (+1, +1), (+1, +3),
|
| 873 |
+
(-1, +3), (-1, +1), (-3, +1), (-3, 0)]) / 6)
|
| 874 |
+
|
| 875 |
+
def _set_plus_filled(self):
|
| 876 |
+
self._transform = Affine2D()
|
| 877 |
+
self._snap_threshold = 5.0
|
| 878 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 879 |
+
if not self._half_fill():
|
| 880 |
+
self._path = self._plus_filled_path
|
| 881 |
+
else:
|
| 882 |
+
# Rotate top half path to support all partitions
|
| 883 |
+
self._path = self._alt_path = self._plus_filled_path_t
|
| 884 |
+
fs = self.get_fillstyle()
|
| 885 |
+
self._transform.rotate_deg(
|
| 886 |
+
{'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs])
|
| 887 |
+
self._alt_transform = self._transform.frozen().rotate_deg(180)
|
| 888 |
+
|
| 889 |
+
_x_filled_path = Path._create_closed(np.array([
|
| 890 |
+
(-1, -2), (0, -1), (+1, -2), (+2, -1), (+1, 0), (+2, +1),
|
| 891 |
+
(+1, +2), (0, +1), (-1, +2), (-2, +1), (-1, 0), (-2, -1)]) / 4)
|
| 892 |
+
_x_filled_path_t = Path._create_closed(np.array([
|
| 893 |
+
(+1, 0), (+2, +1), (+1, +2), (0, +1),
|
| 894 |
+
(-1, +2), (-2, +1), (-1, 0)]) / 4)
|
| 895 |
+
|
| 896 |
+
def _set_x_filled(self):
|
| 897 |
+
self._transform = Affine2D()
|
| 898 |
+
self._snap_threshold = 5.0
|
| 899 |
+
self._joinstyle = self._user_joinstyle or JoinStyle.miter
|
| 900 |
+
if not self._half_fill():
|
| 901 |
+
self._path = self._x_filled_path
|
| 902 |
+
else:
|
| 903 |
+
# Rotate top half path to support all partitions
|
| 904 |
+
self._path = self._alt_path = self._x_filled_path_t
|
| 905 |
+
fs = self.get_fillstyle()
|
| 906 |
+
self._transform.rotate_deg(
|
| 907 |
+
{'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs])
|
| 908 |
+
self._alt_transform = self._transform.frozen().rotate_deg(180)
|
parrot/lib/python3.10/site-packages/matplotlib/markers.pyi
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Literal
|
| 2 |
+
|
| 3 |
+
from .path import Path
|
| 4 |
+
from .transforms import Affine2D, Transform
|
| 5 |
+
|
| 6 |
+
from numpy.typing import ArrayLike
|
| 7 |
+
from .typing import CapStyleType, FillStyleType, JoinStyleType
|
| 8 |
+
|
| 9 |
+
TICKLEFT: int
|
| 10 |
+
TICKRIGHT: int
|
| 11 |
+
TICKUP: int
|
| 12 |
+
TICKDOWN: int
|
| 13 |
+
CARETLEFT: int
|
| 14 |
+
CARETRIGHT: int
|
| 15 |
+
CARETUP: int
|
| 16 |
+
CARETDOWN: int
|
| 17 |
+
CARETLEFTBASE: int
|
| 18 |
+
CARETRIGHTBASE: int
|
| 19 |
+
CARETUPBASE: int
|
| 20 |
+
CARETDOWNBASE: int
|
| 21 |
+
|
| 22 |
+
class MarkerStyle:
|
| 23 |
+
markers: dict[str | int, str]
|
| 24 |
+
filled_markers: tuple[str, ...]
|
| 25 |
+
fillstyles: tuple[FillStyleType, ...]
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
marker: str | ArrayLike | Path | MarkerStyle,
|
| 30 |
+
fillstyle: FillStyleType | None = ...,
|
| 31 |
+
transform: Transform | None = ...,
|
| 32 |
+
capstyle: CapStyleType | None = ...,
|
| 33 |
+
joinstyle: JoinStyleType | None = ...,
|
| 34 |
+
) -> None: ...
|
| 35 |
+
def __bool__(self) -> bool: ...
|
| 36 |
+
def is_filled(self) -> bool: ...
|
| 37 |
+
def get_fillstyle(self) -> FillStyleType: ...
|
| 38 |
+
def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
|
| 39 |
+
def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
|
| 40 |
+
def get_marker(self) -> str | ArrayLike | Path | None: ...
|
| 41 |
+
def get_path(self) -> Path: ...
|
| 42 |
+
def get_transform(self) -> Transform: ...
|
| 43 |
+
def get_alt_path(self) -> Path | None: ...
|
| 44 |
+
def get_alt_transform(self) -> Transform: ...
|
| 45 |
+
def get_snap_threshold(self) -> float | None: ...
|
| 46 |
+
def get_user_transform(self) -> Transform | None: ...
|
| 47 |
+
def transformed(self, transform: Affine2D) -> MarkerStyle: ...
|
| 48 |
+
def rotated(
|
| 49 |
+
self, *, deg: float | None = ..., rad: float | None = ...
|
| 50 |
+
) -> MarkerStyle: ...
|
| 51 |
+
def scaled(self, sx: float, sy: float | None = ...) -> MarkerStyle: ...
|
parrot/lib/python3.10/site-packages/matplotlib/patches.pyi
ADDED
|
@@ -0,0 +1,755 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ist
|
| 2 |
+
from .axes import Axes
|
| 3 |
+
from .backend_bases import RendererBase, MouseEvent
|
| 4 |
+
from .path import Path
|
| 5 |
+
from .transforms import Transform, Bbox
|
| 6 |
+
|
| 7 |
+
from typing import Any, Literal, overload
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from numpy.typing import ArrayLike
|
| 11 |
+
from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
|
| 12 |
+
|
| 13 |
+
class Patch(artist.Artist):
|
| 14 |
+
zorder: float
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
*,
|
| 18 |
+
edgecolor: ColorType | None = ...,
|
| 19 |
+
facecolor: ColorType | None = ...,
|
| 20 |
+
color: ColorType | None = ...,
|
| 21 |
+
linewidth: float | None = ...,
|
| 22 |
+
linestyle: LineStyleType | None = ...,
|
| 23 |
+
antialiased: bool | None = ...,
|
| 24 |
+
hatch: str | None = ...,
|
| 25 |
+
fill: bool = ...,
|
| 26 |
+
capstyle: CapStyleType | None = ...,
|
| 27 |
+
joinstyle: JoinStyleType | None = ...,
|
| 28 |
+
**kwargs,
|
| 29 |
+
) -> None: ...
|
| 30 |
+
def get_verts(self) -> ArrayLike: ...
|
| 31 |
+
def contains(self, mouseevent: MouseEvent, radius: float | None = None) -> tuple[bool, dict[Any, Any]]: ...
|
| 32 |
+
def contains_point(
|
| 33 |
+
self, point: tuple[float, float], radius: float | None = ...
|
| 34 |
+
) -> bool: ...
|
| 35 |
+
def contains_points(
|
| 36 |
+
self, points: ArrayLike, radius: float | None = ...
|
| 37 |
+
) -> np.ndarray: ...
|
| 38 |
+
def get_extents(self) -> Bbox: ...
|
| 39 |
+
def get_transform(self) -> Transform: ...
|
| 40 |
+
def get_data_transform(self) -> Transform: ...
|
| 41 |
+
def get_patch_transform(self) -> Transform: ...
|
| 42 |
+
def get_antialiased(self) -> bool: ...
|
| 43 |
+
def get_edgecolor(self) -> ColorType: ...
|
| 44 |
+
def get_facecolor(self) -> ColorType: ...
|
| 45 |
+
def get_linewidth(self) -> float: ...
|
| 46 |
+
def get_linestyle(self) -> LineStyleType: ...
|
| 47 |
+
def set_antialiased(self, aa: bool | None) -> None: ...
|
| 48 |
+
def set_edgecolor(self, color: ColorType | None) -> None: ...
|
| 49 |
+
def set_facecolor(self, color: ColorType | None) -> None: ...
|
| 50 |
+
def set_color(self, c: ColorType | None) -> None: ...
|
| 51 |
+
def set_alpha(self, alpha: float | None) -> None: ...
|
| 52 |
+
def set_linewidth(self, w: float | None) -> None: ...
|
| 53 |
+
def set_linestyle(self, ls: LineStyleType | None) -> None: ...
|
| 54 |
+
def set_fill(self, b: bool) -> None: ...
|
| 55 |
+
def get_fill(self) -> bool: ...
|
| 56 |
+
fill = property(get_fill, set_fill)
|
| 57 |
+
def set_capstyle(self, s: CapStyleType) -> None: ...
|
| 58 |
+
def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
|
| 59 |
+
def set_joinstyle(self, s: JoinStyleType) -> None: ...
|
| 60 |
+
def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
|
| 61 |
+
def set_hatch(self, hatch: str) -> None: ...
|
| 62 |
+
def get_hatch(self) -> str: ...
|
| 63 |
+
def get_path(self) -> Path: ...
|
| 64 |
+
|
| 65 |
+
class Shadow(Patch):
|
| 66 |
+
patch: Patch
|
| 67 |
+
def __init__(self, patch: Patch, ox: float, oy: float, *, shade: float = ..., **kwargs) -> None: ...
|
| 68 |
+
|
| 69 |
+
class Rectangle(Patch):
|
| 70 |
+
angle: float
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
xy: tuple[float, float],
|
| 74 |
+
width: float,
|
| 75 |
+
height: float,
|
| 76 |
+
*,
|
| 77 |
+
angle: float = ...,
|
| 78 |
+
rotation_point: Literal["xy", "center"] | tuple[float, float] = ...,
|
| 79 |
+
**kwargs,
|
| 80 |
+
) -> None: ...
|
| 81 |
+
@property
|
| 82 |
+
def rotation_point(self) -> Literal["xy", "center"] | tuple[float, float]: ...
|
| 83 |
+
@rotation_point.setter
|
| 84 |
+
def rotation_point(
|
| 85 |
+
self, value: Literal["xy", "center"] | tuple[float, float]
|
| 86 |
+
) -> None: ...
|
| 87 |
+
def get_x(self) -> float: ...
|
| 88 |
+
def get_y(self) -> float: ...
|
| 89 |
+
def get_xy(self) -> tuple[float, float]: ...
|
| 90 |
+
def get_corners(self) -> np.ndarray: ...
|
| 91 |
+
def get_center(self) -> np.ndarray: ...
|
| 92 |
+
def get_width(self) -> float: ...
|
| 93 |
+
def get_height(self) -> float: ...
|
| 94 |
+
def get_angle(self) -> float: ...
|
| 95 |
+
def set_x(self, x: float) -> None: ...
|
| 96 |
+
def set_y(self, y: float) -> None: ...
|
| 97 |
+
def set_angle(self, angle: float) -> None: ...
|
| 98 |
+
def set_xy(self, xy: tuple[float, float]) -> None: ...
|
| 99 |
+
def set_width(self, w: float) -> None: ...
|
| 100 |
+
def set_height(self, h: float) -> None: ...
|
| 101 |
+
@overload
|
| 102 |
+
def set_bounds(self, args: tuple[float, float, float, float], /) -> None: ...
|
| 103 |
+
@overload
|
| 104 |
+
def set_bounds(
|
| 105 |
+
self, left: float, bottom: float, width: float, height: float, /
|
| 106 |
+
) -> None: ...
|
| 107 |
+
def get_bbox(self) -> Bbox: ...
|
| 108 |
+
xy = property(get_xy, set_xy)
|
| 109 |
+
|
| 110 |
+
class RegularPolygon(Patch):
|
| 111 |
+
xy: tuple[float, float]
|
| 112 |
+
numvertices: int
|
| 113 |
+
orientation: float
|
| 114 |
+
radius: float
|
| 115 |
+
def __init__(
|
| 116 |
+
self,
|
| 117 |
+
xy: tuple[float, float],
|
| 118 |
+
numVertices: int,
|
| 119 |
+
*,
|
| 120 |
+
radius: float = ...,
|
| 121 |
+
orientation: float = ...,
|
| 122 |
+
**kwargs,
|
| 123 |
+
) -> None: ...
|
| 124 |
+
|
| 125 |
+
class PathPatch(Patch):
|
| 126 |
+
def __init__(self, path: Path, **kwargs) -> None: ...
|
| 127 |
+
def set_path(self, path: Path) -> None: ...
|
| 128 |
+
|
| 129 |
+
class StepPatch(PathPatch):
|
| 130 |
+
orientation: Literal["vertical", "horizontal"]
|
| 131 |
+
def __init__(
|
| 132 |
+
self,
|
| 133 |
+
values: ArrayLike,
|
| 134 |
+
edges: ArrayLike,
|
| 135 |
+
*,
|
| 136 |
+
orientation: Literal["vertical", "horizontal"] = ...,
|
| 137 |
+
baseline: float = ...,
|
| 138 |
+
**kwargs,
|
| 139 |
+
) -> None: ...
|
| 140 |
+
|
| 141 |
+
# NamedTuple StairData, defined in body of method
|
| 142 |
+
def get_data(self) -> tuple[np.ndarray, np.ndarray, float]: ...
|
| 143 |
+
def set_data(
|
| 144 |
+
self,
|
| 145 |
+
values: ArrayLike | None = ...,
|
| 146 |
+
edges: ArrayLike | None = ...,
|
| 147 |
+
baseline: float | None = ...,
|
| 148 |
+
) -> None: ...
|
| 149 |
+
|
| 150 |
+
class Polygon(Patch):
|
| 151 |
+
def __init__(self, xy: ArrayLike, *, closed: bool = ..., **kwargs) -> None: ...
|
| 152 |
+
def get_closed(self) -> bool: ...
|
| 153 |
+
def set_closed(self, closed: bool) -> None: ...
|
| 154 |
+
def get_xy(self) -> np.ndarray: ...
|
| 155 |
+
def set_xy(self, xy: ArrayLike) -> None: ...
|
| 156 |
+
xy = property(get_xy, set_xy)
|
| 157 |
+
|
| 158 |
+
class Wedge(Patch):
|
| 159 |
+
center: tuple[float, float]
|
| 160 |
+
r: float
|
| 161 |
+
theta1: float
|
| 162 |
+
theta2: float
|
| 163 |
+
width: float | None
|
| 164 |
+
def __init__(
|
| 165 |
+
self,
|
| 166 |
+
center: tuple[float, float],
|
| 167 |
+
r: float,
|
| 168 |
+
theta1: float,
|
| 169 |
+
theta2: float,
|
| 170 |
+
*,
|
| 171 |
+
width: float | None = ...,
|
| 172 |
+
**kwargs,
|
| 173 |
+
) -> None: ...
|
| 174 |
+
def set_center(self, center: tuple[float, float]) -> None: ...
|
| 175 |
+
def set_radius(self, radius: float) -> None: ...
|
| 176 |
+
def set_theta1(self, theta1: float) -> None: ...
|
| 177 |
+
def set_theta2(self, theta2: float) -> None: ...
|
| 178 |
+
def set_width(self, width: float | None) -> None: ...
|
| 179 |
+
|
| 180 |
+
class Arrow(Patch):
|
| 181 |
+
def __init__(
|
| 182 |
+
self, x: float, y: float, dx: float, dy: float, *, width: float = ..., **kwargs
|
| 183 |
+
) -> None: ...
|
| 184 |
+
def set_data(
|
| 185 |
+
self,
|
| 186 |
+
x: float | None = ...,
|
| 187 |
+
y: float | None = ...,
|
| 188 |
+
dx: float | None = ...,
|
| 189 |
+
dy: float | None = ...,
|
| 190 |
+
width: float | None = ...,
|
| 191 |
+
) -> None: ...
|
| 192 |
+
class FancyArrow(Polygon):
|
| 193 |
+
def __init__(
|
| 194 |
+
self,
|
| 195 |
+
x: float,
|
| 196 |
+
y: float,
|
| 197 |
+
dx: float,
|
| 198 |
+
dy: float,
|
| 199 |
+
*,
|
| 200 |
+
width: float = ...,
|
| 201 |
+
length_includes_head: bool = ...,
|
| 202 |
+
head_width: float | None = ...,
|
| 203 |
+
head_length: float | None = ...,
|
| 204 |
+
shape: Literal["full", "left", "right"] = ...,
|
| 205 |
+
overhang: float = ...,
|
| 206 |
+
head_starts_at_zero: bool = ...,
|
| 207 |
+
**kwargs,
|
| 208 |
+
) -> None: ...
|
| 209 |
+
def set_data(
|
| 210 |
+
self,
|
| 211 |
+
*,
|
| 212 |
+
x: float | None = ...,
|
| 213 |
+
y: float | None = ...,
|
| 214 |
+
dx: float | None = ...,
|
| 215 |
+
dy: float | None = ...,
|
| 216 |
+
width: float | None = ...,
|
| 217 |
+
head_width: float | None = ...,
|
| 218 |
+
head_length: float | None = ...,
|
| 219 |
+
) -> None: ...
|
| 220 |
+
|
| 221 |
+
class CirclePolygon(RegularPolygon):
|
| 222 |
+
def __init__(
|
| 223 |
+
self,
|
| 224 |
+
xy: tuple[float, float],
|
| 225 |
+
radius: float = ...,
|
| 226 |
+
*,
|
| 227 |
+
resolution: int = ...,
|
| 228 |
+
**kwargs,
|
| 229 |
+
) -> None: ...
|
| 230 |
+
|
| 231 |
+
class Ellipse(Patch):
|
| 232 |
+
def __init__(
|
| 233 |
+
self,
|
| 234 |
+
xy: tuple[float, float],
|
| 235 |
+
width: float,
|
| 236 |
+
height: float,
|
| 237 |
+
*,
|
| 238 |
+
angle: float = ...,
|
| 239 |
+
**kwargs,
|
| 240 |
+
) -> None: ...
|
| 241 |
+
def set_center(self, xy: tuple[float, float]) -> None: ...
|
| 242 |
+
def get_center(self) -> float: ...
|
| 243 |
+
center = property(get_center, set_center)
|
| 244 |
+
|
| 245 |
+
def set_width(self, width: float) -> None: ...
|
| 246 |
+
def get_width(self) -> float: ...
|
| 247 |
+
width = property(get_width, set_width)
|
| 248 |
+
|
| 249 |
+
def set_height(self, height: float) -> None: ...
|
| 250 |
+
def get_height(self) -> float: ...
|
| 251 |
+
height = property(get_height, set_height)
|
| 252 |
+
|
| 253 |
+
def set_angle(self, angle: float) -> None: ...
|
| 254 |
+
def get_angle(self) -> float: ...
|
| 255 |
+
angle = property(get_angle, set_angle)
|
| 256 |
+
|
| 257 |
+
def get_corners(self) -> np.ndarray: ...
|
| 258 |
+
|
| 259 |
+
def get_vertices(self) -> list[tuple[float, float]]: ...
|
| 260 |
+
def get_co_vertices(self) -> list[tuple[float, float]]: ...
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class Annulus(Patch):
|
| 264 |
+
a: float
|
| 265 |
+
b: float
|
| 266 |
+
def __init__(
|
| 267 |
+
self,
|
| 268 |
+
xy: tuple[float, float],
|
| 269 |
+
r: float | tuple[float, float],
|
| 270 |
+
width: float,
|
| 271 |
+
angle: float = ...,
|
| 272 |
+
**kwargs,
|
| 273 |
+
) -> None: ...
|
| 274 |
+
def set_center(self, xy: tuple[float, float]) -> None: ...
|
| 275 |
+
def get_center(self) -> tuple[float, float]: ...
|
| 276 |
+
center = property(get_center, set_center)
|
| 277 |
+
|
| 278 |
+
def set_width(self, width: float) -> None: ...
|
| 279 |
+
def get_width(self) -> float: ...
|
| 280 |
+
width = property(get_width, set_width)
|
| 281 |
+
|
| 282 |
+
def set_angle(self, angle: float) -> None: ...
|
| 283 |
+
def get_angle(self) -> float: ...
|
| 284 |
+
angle = property(get_angle, set_angle)
|
| 285 |
+
|
| 286 |
+
def set_semimajor(self, a: float) -> None: ...
|
| 287 |
+
def set_semiminor(self, b: float) -> None: ...
|
| 288 |
+
def set_radii(self, r: float | tuple[float, float]) -> None: ...
|
| 289 |
+
def get_radii(self) -> tuple[float, float]: ...
|
| 290 |
+
radii = property(get_radii, set_radii)
|
| 291 |
+
|
| 292 |
+
class Circle(Ellipse):
|
| 293 |
+
def __init__(
|
| 294 |
+
self, xy: tuple[float, float], radius: float = ..., **kwargs
|
| 295 |
+
) -> None: ...
|
| 296 |
+
def set_radius(self, radius: float) -> None: ...
|
| 297 |
+
def get_radius(self) -> float: ...
|
| 298 |
+
radius = property(get_radius, set_radius)
|
| 299 |
+
|
| 300 |
+
class Arc(Ellipse):
|
| 301 |
+
theta1: float
|
| 302 |
+
theta2: float
|
| 303 |
+
def __init__(
|
| 304 |
+
self,
|
| 305 |
+
xy: tuple[float, float],
|
| 306 |
+
width: float,
|
| 307 |
+
height: float,
|
| 308 |
+
*,
|
| 309 |
+
angle: float = ...,
|
| 310 |
+
theta1: float = ...,
|
| 311 |
+
theta2: float = ...,
|
| 312 |
+
**kwargs,
|
| 313 |
+
) -> None: ...
|
| 314 |
+
|
| 315 |
+
def bbox_artist(
|
| 316 |
+
artist: artist.Artist,
|
| 317 |
+
renderer: RendererBase,
|
| 318 |
+
props: dict[str, Any] | None = ...,
|
| 319 |
+
fill: bool = ...,
|
| 320 |
+
) -> None: ...
|
| 321 |
+
def draw_bbox(
|
| 322 |
+
bbox: Bbox,
|
| 323 |
+
renderer: RendererBase,
|
| 324 |
+
color: ColorType = ...,
|
| 325 |
+
trans: Transform | None = ...,
|
| 326 |
+
) -> None: ...
|
| 327 |
+
|
| 328 |
+
class _Style:
|
| 329 |
+
def __new__(cls, stylename, **kwargs): ...
|
| 330 |
+
@classmethod
|
| 331 |
+
def get_styles(cls) -> dict[str, type]: ...
|
| 332 |
+
@classmethod
|
| 333 |
+
def pprint_styles(cls) -> str: ...
|
| 334 |
+
@classmethod
|
| 335 |
+
def register(cls, name: str, style: type) -> None: ...
|
| 336 |
+
|
| 337 |
+
class BoxStyle(_Style):
|
| 338 |
+
class Square(BoxStyle):
|
| 339 |
+
pad: float
|
| 340 |
+
def __init__(self, pad: float = ...) -> None: ...
|
| 341 |
+
def __call__(
|
| 342 |
+
self,
|
| 343 |
+
x0: float,
|
| 344 |
+
y0: float,
|
| 345 |
+
width: float,
|
| 346 |
+
height: float,
|
| 347 |
+
mutation_size: float,
|
| 348 |
+
) -> Path: ...
|
| 349 |
+
|
| 350 |
+
class Circle(BoxStyle):
|
| 351 |
+
pad: float
|
| 352 |
+
def __init__(self, pad: float = ...) -> None: ...
|
| 353 |
+
def __call__(
|
| 354 |
+
self,
|
| 355 |
+
x0: float,
|
| 356 |
+
y0: float,
|
| 357 |
+
width: float,
|
| 358 |
+
height: float,
|
| 359 |
+
mutation_size: float,
|
| 360 |
+
) -> Path: ...
|
| 361 |
+
|
| 362 |
+
class Ellipse(BoxStyle):
|
| 363 |
+
pad: float
|
| 364 |
+
def __init__(self, pad: float = ...) -> None: ...
|
| 365 |
+
def __call__(
|
| 366 |
+
self,
|
| 367 |
+
x0: float,
|
| 368 |
+
y0: float,
|
| 369 |
+
width: float,
|
| 370 |
+
height: float,
|
| 371 |
+
mutation_size: float,
|
| 372 |
+
) -> Path: ...
|
| 373 |
+
|
| 374 |
+
class LArrow(BoxStyle):
|
| 375 |
+
pad: float
|
| 376 |
+
def __init__(self, pad: float = ...) -> None: ...
|
| 377 |
+
def __call__(
|
| 378 |
+
self,
|
| 379 |
+
x0: float,
|
| 380 |
+
y0: float,
|
| 381 |
+
width: float,
|
| 382 |
+
height: float,
|
| 383 |
+
mutation_size: float,
|
| 384 |
+
) -> Path: ...
|
| 385 |
+
|
| 386 |
+
class RArrow(LArrow):
|
| 387 |
+
def __call__(
|
| 388 |
+
self,
|
| 389 |
+
x0: float,
|
| 390 |
+
y0: float,
|
| 391 |
+
width: float,
|
| 392 |
+
height: float,
|
| 393 |
+
mutation_size: float,
|
| 394 |
+
) -> Path: ...
|
| 395 |
+
|
| 396 |
+
class DArrow(BoxStyle):
|
| 397 |
+
pad: float
|
| 398 |
+
def __init__(self, pad: float = ...) -> None: ...
|
| 399 |
+
def __call__(
|
| 400 |
+
self,
|
| 401 |
+
x0: float,
|
| 402 |
+
y0: float,
|
| 403 |
+
width: float,
|
| 404 |
+
height: float,
|
| 405 |
+
mutation_size: float,
|
| 406 |
+
) -> Path: ...
|
| 407 |
+
|
| 408 |
+
class Round(BoxStyle):
|
| 409 |
+
pad: float
|
| 410 |
+
rounding_size: float | None
|
| 411 |
+
def __init__(
|
| 412 |
+
self, pad: float = ..., rounding_size: float | None = ...
|
| 413 |
+
) -> None: ...
|
| 414 |
+
def __call__(
|
| 415 |
+
self,
|
| 416 |
+
x0: float,
|
| 417 |
+
y0: float,
|
| 418 |
+
width: float,
|
| 419 |
+
height: float,
|
| 420 |
+
mutation_size: float,
|
| 421 |
+
) -> Path: ...
|
| 422 |
+
|
| 423 |
+
class Round4(BoxStyle):
|
| 424 |
+
pad: float
|
| 425 |
+
rounding_size: float | None
|
| 426 |
+
def __init__(
|
| 427 |
+
self, pad: float = ..., rounding_size: float | None = ...
|
| 428 |
+
) -> None: ...
|
| 429 |
+
def __call__(
|
| 430 |
+
self,
|
| 431 |
+
x0: float,
|
| 432 |
+
y0: float,
|
| 433 |
+
width: float,
|
| 434 |
+
height: float,
|
| 435 |
+
mutation_size: float,
|
| 436 |
+
) -> Path: ...
|
| 437 |
+
|
| 438 |
+
class Sawtooth(BoxStyle):
|
| 439 |
+
pad: float
|
| 440 |
+
tooth_size: float | None
|
| 441 |
+
def __init__(
|
| 442 |
+
self, pad: float = ..., tooth_size: float | None = ...
|
| 443 |
+
) -> None: ...
|
| 444 |
+
def __call__(
|
| 445 |
+
self,
|
| 446 |
+
x0: float,
|
| 447 |
+
y0: float,
|
| 448 |
+
width: float,
|
| 449 |
+
height: float,
|
| 450 |
+
mutation_size: float,
|
| 451 |
+
) -> Path: ...
|
| 452 |
+
|
| 453 |
+
class Roundtooth(Sawtooth):
|
| 454 |
+
def __call__(
|
| 455 |
+
self,
|
| 456 |
+
x0: float,
|
| 457 |
+
y0: float,
|
| 458 |
+
width: float,
|
| 459 |
+
height: float,
|
| 460 |
+
mutation_size: float,
|
| 461 |
+
) -> Path: ...
|
| 462 |
+
|
| 463 |
+
class ConnectionStyle(_Style):
|
| 464 |
+
class _Base(ConnectionStyle):
|
| 465 |
+
def __call__(
|
| 466 |
+
self,
|
| 467 |
+
posA: tuple[float, float],
|
| 468 |
+
posB: tuple[float, float],
|
| 469 |
+
shrinkA: float = ...,
|
| 470 |
+
shrinkB: float = ...,
|
| 471 |
+
patchA: Patch | None = ...,
|
| 472 |
+
patchB: Patch | None = ...,
|
| 473 |
+
) -> Path: ...
|
| 474 |
+
|
| 475 |
+
class Arc3(_Base):
|
| 476 |
+
rad: float
|
| 477 |
+
def __init__(self, rad: float = ...) -> None: ...
|
| 478 |
+
def connect(
|
| 479 |
+
self, posA: tuple[float, float], posB: tuple[float, float]
|
| 480 |
+
) -> Path: ...
|
| 481 |
+
|
| 482 |
+
class Angle3(_Base):
|
| 483 |
+
angleA: float
|
| 484 |
+
angleB: float
|
| 485 |
+
def __init__(self, angleA: float = ..., angleB: float = ...) -> None: ...
|
| 486 |
+
def connect(
|
| 487 |
+
self, posA: tuple[float, float], posB: tuple[float, float]
|
| 488 |
+
) -> Path: ...
|
| 489 |
+
|
| 490 |
+
class Angle(_Base):
|
| 491 |
+
angleA: float
|
| 492 |
+
angleB: float
|
| 493 |
+
rad: float
|
| 494 |
+
def __init__(
|
| 495 |
+
self, angleA: float = ..., angleB: float = ..., rad: float = ...
|
| 496 |
+
) -> None: ...
|
| 497 |
+
def connect(
|
| 498 |
+
self, posA: tuple[float, float], posB: tuple[float, float]
|
| 499 |
+
) -> Path: ...
|
| 500 |
+
|
| 501 |
+
class Arc(_Base):
|
| 502 |
+
angleA: float
|
| 503 |
+
angleB: float
|
| 504 |
+
armA: float | None
|
| 505 |
+
armB: float | None
|
| 506 |
+
rad: float
|
| 507 |
+
def __init__(
|
| 508 |
+
self,
|
| 509 |
+
angleA: float = ...,
|
| 510 |
+
angleB: float = ...,
|
| 511 |
+
armA: float | None = ...,
|
| 512 |
+
armB: float | None = ...,
|
| 513 |
+
rad: float = ...,
|
| 514 |
+
) -> None: ...
|
| 515 |
+
def connect(
|
| 516 |
+
self, posA: tuple[float, float], posB: tuple[float, float]
|
| 517 |
+
) -> Path: ...
|
| 518 |
+
|
| 519 |
+
class Bar(_Base):
|
| 520 |
+
armA: float
|
| 521 |
+
armB: float
|
| 522 |
+
fraction: float
|
| 523 |
+
angle: float | None
|
| 524 |
+
def __init__(
|
| 525 |
+
self,
|
| 526 |
+
armA: float = ...,
|
| 527 |
+
armB: float = ...,
|
| 528 |
+
fraction: float = ...,
|
| 529 |
+
angle: float | None = ...,
|
| 530 |
+
) -> None: ...
|
| 531 |
+
def connect(
|
| 532 |
+
self, posA: tuple[float, float], posB: tuple[float, float]
|
| 533 |
+
) -> Path: ...
|
| 534 |
+
|
| 535 |
+
class ArrowStyle(_Style):
|
| 536 |
+
class _Base(ArrowStyle):
|
| 537 |
+
@staticmethod
|
| 538 |
+
def ensure_quadratic_bezier(path: Path) -> list[float]: ...
|
| 539 |
+
def transmute(
|
| 540 |
+
self, path: Path, mutation_size: float, linewidth: float
|
| 541 |
+
) -> tuple[Path, bool]: ...
|
| 542 |
+
def __call__(
|
| 543 |
+
self,
|
| 544 |
+
path: Path,
|
| 545 |
+
mutation_size: float,
|
| 546 |
+
linewidth: float,
|
| 547 |
+
aspect_ratio: float = ...,
|
| 548 |
+
) -> tuple[Path, bool]: ...
|
| 549 |
+
|
| 550 |
+
class _Curve(_Base):
|
| 551 |
+
arrow: str
|
| 552 |
+
fillbegin: bool
|
| 553 |
+
fillend: bool
|
| 554 |
+
def __init__(
|
| 555 |
+
self,
|
| 556 |
+
head_length: float = ...,
|
| 557 |
+
head_width: float = ...,
|
| 558 |
+
widthA: float = ...,
|
| 559 |
+
widthB: float = ...,
|
| 560 |
+
lengthA: float = ...,
|
| 561 |
+
lengthB: float = ...,
|
| 562 |
+
angleA: float | None = ...,
|
| 563 |
+
angleB: float | None = ...,
|
| 564 |
+
scaleA: float | None = ...,
|
| 565 |
+
scaleB: float | None = ...,
|
| 566 |
+
) -> None: ...
|
| 567 |
+
|
| 568 |
+
class Curve(_Curve):
|
| 569 |
+
def __init__(self) -> None: ...
|
| 570 |
+
|
| 571 |
+
class CurveA(_Curve):
|
| 572 |
+
arrow: str
|
| 573 |
+
|
| 574 |
+
class CurveB(_Curve):
|
| 575 |
+
arrow: str
|
| 576 |
+
|
| 577 |
+
class CurveAB(_Curve):
|
| 578 |
+
arrow: str
|
| 579 |
+
|
| 580 |
+
class CurveFilledA(_Curve):
|
| 581 |
+
arrow: str
|
| 582 |
+
|
| 583 |
+
class CurveFilledB(_Curve):
|
| 584 |
+
arrow: str
|
| 585 |
+
|
| 586 |
+
class CurveFilledAB(_Curve):
|
| 587 |
+
arrow: str
|
| 588 |
+
|
| 589 |
+
class BracketA(_Curve):
|
| 590 |
+
arrow: str
|
| 591 |
+
def __init__(
|
| 592 |
+
self, widthA: float = ..., lengthA: float = ..., angleA: float = ...
|
| 593 |
+
) -> None: ...
|
| 594 |
+
|
| 595 |
+
class BracketB(_Curve):
|
| 596 |
+
arrow: str
|
| 597 |
+
def __init__(
|
| 598 |
+
self, widthB: float = ..., lengthB: float = ..., angleB: float = ...
|
| 599 |
+
) -> None: ...
|
| 600 |
+
|
| 601 |
+
class BracketAB(_Curve):
|
| 602 |
+
arrow: str
|
| 603 |
+
def __init__(
|
| 604 |
+
self,
|
| 605 |
+
widthA: float = ...,
|
| 606 |
+
lengthA: float = ...,
|
| 607 |
+
angleA: float = ...,
|
| 608 |
+
widthB: float = ...,
|
| 609 |
+
lengthB: float = ...,
|
| 610 |
+
angleB: float = ...,
|
| 611 |
+
) -> None: ...
|
| 612 |
+
|
| 613 |
+
class BarAB(_Curve):
|
| 614 |
+
arrow: str
|
| 615 |
+
def __init__(
|
| 616 |
+
self,
|
| 617 |
+
widthA: float = ...,
|
| 618 |
+
angleA: float = ...,
|
| 619 |
+
widthB: float = ...,
|
| 620 |
+
angleB: float = ...,
|
| 621 |
+
) -> None: ...
|
| 622 |
+
|
| 623 |
+
class BracketCurve(_Curve):
|
| 624 |
+
arrow: str
|
| 625 |
+
def __init__(
|
| 626 |
+
self, widthA: float = ..., lengthA: float = ..., angleA: float | None = ...
|
| 627 |
+
) -> None: ...
|
| 628 |
+
|
| 629 |
+
class CurveBracket(_Curve):
|
| 630 |
+
arrow: str
|
| 631 |
+
def __init__(
|
| 632 |
+
self, widthB: float = ..., lengthB: float = ..., angleB: float | None = ...
|
| 633 |
+
) -> None: ...
|
| 634 |
+
|
| 635 |
+
class Simple(_Base):
|
| 636 |
+
def __init__(
|
| 637 |
+
self,
|
| 638 |
+
head_length: float = ...,
|
| 639 |
+
head_width: float = ...,
|
| 640 |
+
tail_width: float = ...,
|
| 641 |
+
) -> None: ...
|
| 642 |
+
|
| 643 |
+
class Fancy(_Base):
|
| 644 |
+
def __init__(
|
| 645 |
+
self,
|
| 646 |
+
head_length: float = ...,
|
| 647 |
+
head_width: float = ...,
|
| 648 |
+
tail_width: float = ...,
|
| 649 |
+
) -> None: ...
|
| 650 |
+
|
| 651 |
+
class Wedge(_Base):
|
| 652 |
+
tail_width: float
|
| 653 |
+
shrink_factor: float
|
| 654 |
+
def __init__(
|
| 655 |
+
self, tail_width: float = ..., shrink_factor: float = ...
|
| 656 |
+
) -> None: ...
|
| 657 |
+
|
| 658 |
+
class FancyBboxPatch(Patch):
|
| 659 |
+
def __init__(
|
| 660 |
+
self,
|
| 661 |
+
xy: tuple[float, float],
|
| 662 |
+
width: float,
|
| 663 |
+
height: float,
|
| 664 |
+
boxstyle: str | BoxStyle = ...,
|
| 665 |
+
*,
|
| 666 |
+
mutation_scale: float = ...,
|
| 667 |
+
mutation_aspect: float = ...,
|
| 668 |
+
**kwargs,
|
| 669 |
+
) -> None: ...
|
| 670 |
+
def set_boxstyle(self, boxstyle: str | BoxStyle | None = ..., **kwargs) -> None: ...
|
| 671 |
+
def get_boxstyle(self) -> BoxStyle: ...
|
| 672 |
+
def set_mutation_scale(self, scale: float) -> None: ...
|
| 673 |
+
def get_mutation_scale(self) -> float: ...
|
| 674 |
+
def set_mutation_aspect(self, aspect: float) -> None: ...
|
| 675 |
+
def get_mutation_aspect(self) -> float: ...
|
| 676 |
+
def get_x(self) -> float: ...
|
| 677 |
+
def get_y(self) -> float: ...
|
| 678 |
+
def get_width(self) -> float: ...
|
| 679 |
+
def get_height(self) -> float: ...
|
| 680 |
+
def set_x(self, x: float) -> None: ...
|
| 681 |
+
def set_y(self, y: float) -> None: ...
|
| 682 |
+
def set_width(self, w: float) -> None: ...
|
| 683 |
+
def set_height(self, h: float) -> None: ...
|
| 684 |
+
@overload
|
| 685 |
+
def set_bounds(self, args: tuple[float, float, float, float], /) -> None: ...
|
| 686 |
+
@overload
|
| 687 |
+
def set_bounds(
|
| 688 |
+
self, left: float, bottom: float, width: float, height: float, /
|
| 689 |
+
) -> None: ...
|
| 690 |
+
def get_bbox(self) -> Bbox: ...
|
| 691 |
+
|
| 692 |
+
class FancyArrowPatch(Patch):
|
| 693 |
+
patchA: Patch
|
| 694 |
+
patchB: Patch
|
| 695 |
+
shrinkA: float
|
| 696 |
+
shrinkB: float
|
| 697 |
+
def __init__(
|
| 698 |
+
self,
|
| 699 |
+
posA: tuple[float, float] | None = ...,
|
| 700 |
+
posB: tuple[float, float] | None = ...,
|
| 701 |
+
*,
|
| 702 |
+
path: Path | None = ...,
|
| 703 |
+
arrowstyle: str | ArrowStyle = ...,
|
| 704 |
+
connectionstyle: str | ConnectionStyle = ...,
|
| 705 |
+
patchA: Patch | None = ...,
|
| 706 |
+
patchB: Patch | None = ...,
|
| 707 |
+
shrinkA: float = ...,
|
| 708 |
+
shrinkB: float = ...,
|
| 709 |
+
mutation_scale: float = ...,
|
| 710 |
+
mutation_aspect: float | None = ...,
|
| 711 |
+
**kwargs,
|
| 712 |
+
) -> None: ...
|
| 713 |
+
def set_positions(
|
| 714 |
+
self, posA: tuple[float, float], posB: tuple[float, float]
|
| 715 |
+
) -> None: ...
|
| 716 |
+
def set_patchA(self, patchA: Patch) -> None: ...
|
| 717 |
+
def set_patchB(self, patchB: Patch) -> None: ...
|
| 718 |
+
def set_connectionstyle(self, connectionstyle: str | ConnectionStyle | None = ..., **kwargs) -> None: ...
|
| 719 |
+
def get_connectionstyle(self) -> ConnectionStyle: ...
|
| 720 |
+
def set_arrowstyle(self, arrowstyle: str | ArrowStyle | None = ..., **kwargs) -> None: ...
|
| 721 |
+
def get_arrowstyle(self) -> ArrowStyle: ...
|
| 722 |
+
def set_mutation_scale(self, scale: float) -> None: ...
|
| 723 |
+
def get_mutation_scale(self) -> float: ...
|
| 724 |
+
def set_mutation_aspect(self, aspect: float | None) -> None: ...
|
| 725 |
+
def get_mutation_aspect(self) -> float: ...
|
| 726 |
+
|
| 727 |
+
class ConnectionPatch(FancyArrowPatch):
|
| 728 |
+
xy1: tuple[float, float]
|
| 729 |
+
xy2: tuple[float, float]
|
| 730 |
+
coords1: str | Transform
|
| 731 |
+
coords2: str | Transform | None
|
| 732 |
+
axesA: Axes | None
|
| 733 |
+
axesB: Axes | None
|
| 734 |
+
def __init__(
|
| 735 |
+
self,
|
| 736 |
+
xyA: tuple[float, float],
|
| 737 |
+
xyB: tuple[float, float],
|
| 738 |
+
coordsA: str | Transform,
|
| 739 |
+
coordsB: str | Transform | None = ...,
|
| 740 |
+
*,
|
| 741 |
+
axesA: Axes | None = ...,
|
| 742 |
+
axesB: Axes | None = ...,
|
| 743 |
+
arrowstyle: str | ArrowStyle = ...,
|
| 744 |
+
connectionstyle: str | ConnectionStyle = ...,
|
| 745 |
+
patchA: Patch | None = ...,
|
| 746 |
+
patchB: Patch | None = ...,
|
| 747 |
+
shrinkA: float = ...,
|
| 748 |
+
shrinkB: float = ...,
|
| 749 |
+
mutation_scale: float = ...,
|
| 750 |
+
mutation_aspect: float | None = ...,
|
| 751 |
+
clip_on: bool = ...,
|
| 752 |
+
**kwargs,
|
| 753 |
+
) -> None: ...
|
| 754 |
+
def set_annotation_clip(self, b: bool | None) -> None: ...
|
| 755 |
+
def get_annotation_clip(self) -> bool | None: ...
|
parrot/lib/python3.10/site-packages/matplotlib/path.py
ADDED
|
@@ -0,0 +1,1096 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
A module for dealing with the polylines used throughout Matplotlib.
|
| 3 |
+
|
| 4 |
+
The primary class for polyline handling in Matplotlib is `Path`. Almost all
|
| 5 |
+
vector drawing makes use of `Path`\s somewhere in the drawing pipeline.
|
| 6 |
+
|
| 7 |
+
Whilst a `Path` instance itself cannot be drawn, some `.Artist` subclasses,
|
| 8 |
+
such as `.PathPatch` and `.PathCollection`, can be used for convenient `Path`
|
| 9 |
+
visualisation.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import copy
|
| 13 |
+
from functools import lru_cache
|
| 14 |
+
from weakref import WeakValueDictionary
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
import matplotlib as mpl
|
| 19 |
+
from . import _api, _path
|
| 20 |
+
from .cbook import _to_unmasked_float_array, simple_linear_interpolation
|
| 21 |
+
from .bezier import BezierSegment
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Path:
|
| 25 |
+
"""
|
| 26 |
+
A series of possibly disconnected, possibly closed, line and curve
|
| 27 |
+
segments.
|
| 28 |
+
|
| 29 |
+
The underlying storage is made up of two parallel numpy arrays:
|
| 30 |
+
|
| 31 |
+
- *vertices*: an (N, 2) float array of vertices
|
| 32 |
+
- *codes*: an N-length `numpy.uint8` array of path codes, or None
|
| 33 |
+
|
| 34 |
+
These two arrays always have the same length in the first
|
| 35 |
+
dimension. For example, to represent a cubic curve, you must
|
| 36 |
+
provide three vertices and three `CURVE4` codes.
|
| 37 |
+
|
| 38 |
+
The code types are:
|
| 39 |
+
|
| 40 |
+
- `STOP` : 1 vertex (ignored)
|
| 41 |
+
A marker for the end of the entire path (currently not required and
|
| 42 |
+
ignored)
|
| 43 |
+
|
| 44 |
+
- `MOVETO` : 1 vertex
|
| 45 |
+
Pick up the pen and move to the given vertex.
|
| 46 |
+
|
| 47 |
+
- `LINETO` : 1 vertex
|
| 48 |
+
Draw a line from the current position to the given vertex.
|
| 49 |
+
|
| 50 |
+
- `CURVE3` : 1 control point, 1 endpoint
|
| 51 |
+
Draw a quadratic Bézier curve from the current position, with the given
|
| 52 |
+
control point, to the given end point.
|
| 53 |
+
|
| 54 |
+
- `CURVE4` : 2 control points, 1 endpoint
|
| 55 |
+
Draw a cubic Bézier curve from the current position, with the given
|
| 56 |
+
control points, to the given end point.
|
| 57 |
+
|
| 58 |
+
- `CLOSEPOLY` : 1 vertex (ignored)
|
| 59 |
+
Draw a line segment to the start point of the current polyline.
|
| 60 |
+
|
| 61 |
+
If *codes* is None, it is interpreted as a `MOVETO` followed by a series
|
| 62 |
+
of `LINETO`.
|
| 63 |
+
|
| 64 |
+
Users of Path objects should not access the vertices and codes arrays
|
| 65 |
+
directly. Instead, they should use `iter_segments` or `cleaned` to get the
|
| 66 |
+
vertex/code pairs. This helps, in particular, to consistently handle the
|
| 67 |
+
case of *codes* being None.
|
| 68 |
+
|
| 69 |
+
Some behavior of Path objects can be controlled by rcParams. See the
|
| 70 |
+
rcParams whose keys start with 'path.'.
|
| 71 |
+
|
| 72 |
+
.. note::
|
| 73 |
+
|
| 74 |
+
The vertices and codes arrays should be treated as
|
| 75 |
+
immutable -- there are a number of optimizations and assumptions
|
| 76 |
+
made up front in the constructor that will not change when the
|
| 77 |
+
data changes.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
code_type = np.uint8
|
| 81 |
+
|
| 82 |
+
# Path codes
|
| 83 |
+
STOP = code_type(0) # 1 vertex
|
| 84 |
+
MOVETO = code_type(1) # 1 vertex
|
| 85 |
+
LINETO = code_type(2) # 1 vertex
|
| 86 |
+
CURVE3 = code_type(3) # 2 vertices
|
| 87 |
+
CURVE4 = code_type(4) # 3 vertices
|
| 88 |
+
CLOSEPOLY = code_type(79) # 1 vertex
|
| 89 |
+
|
| 90 |
+
#: A dictionary mapping Path codes to the number of vertices that the
|
| 91 |
+
#: code expects.
|
| 92 |
+
NUM_VERTICES_FOR_CODE = {STOP: 1,
|
| 93 |
+
MOVETO: 1,
|
| 94 |
+
LINETO: 1,
|
| 95 |
+
CURVE3: 2,
|
| 96 |
+
CURVE4: 3,
|
| 97 |
+
CLOSEPOLY: 1}
|
| 98 |
+
|
| 99 |
+
def __init__(self, vertices, codes=None, _interpolation_steps=1,
|
| 100 |
+
closed=False, readonly=False):
|
| 101 |
+
"""
|
| 102 |
+
Create a new path with the given vertices and codes.
|
| 103 |
+
|
| 104 |
+
Parameters
|
| 105 |
+
----------
|
| 106 |
+
vertices : (N, 2) array-like
|
| 107 |
+
The path vertices, as an array, masked array or sequence of pairs.
|
| 108 |
+
Masked values, if any, will be converted to NaNs, which are then
|
| 109 |
+
handled correctly by the Agg PathIterator and other consumers of
|
| 110 |
+
path data, such as :meth:`iter_segments`.
|
| 111 |
+
codes : array-like or None, optional
|
| 112 |
+
N-length array of integers representing the codes of the path.
|
| 113 |
+
If not None, codes must be the same length as vertices.
|
| 114 |
+
If None, *vertices* will be treated as a series of line segments.
|
| 115 |
+
_interpolation_steps : int, optional
|
| 116 |
+
Used as a hint to certain projections, such as Polar, that this
|
| 117 |
+
path should be linearly interpolated immediately before drawing.
|
| 118 |
+
This attribute is primarily an implementation detail and is not
|
| 119 |
+
intended for public use.
|
| 120 |
+
closed : bool, optional
|
| 121 |
+
If *codes* is None and closed is True, vertices will be treated as
|
| 122 |
+
line segments of a closed polygon. Note that the last vertex will
|
| 123 |
+
then be ignored (as the corresponding code will be set to
|
| 124 |
+
`CLOSEPOLY`).
|
| 125 |
+
readonly : bool, optional
|
| 126 |
+
Makes the path behave in an immutable way and sets the vertices
|
| 127 |
+
and codes as read-only arrays.
|
| 128 |
+
"""
|
| 129 |
+
vertices = _to_unmasked_float_array(vertices)
|
| 130 |
+
_api.check_shape((None, 2), vertices=vertices)
|
| 131 |
+
|
| 132 |
+
if codes is not None:
|
| 133 |
+
codes = np.asarray(codes, self.code_type)
|
| 134 |
+
if codes.ndim != 1 or len(codes) != len(vertices):
|
| 135 |
+
raise ValueError("'codes' must be a 1D list or array with the "
|
| 136 |
+
"same length of 'vertices'. "
|
| 137 |
+
f"Your vertices have shape {vertices.shape} "
|
| 138 |
+
f"but your codes have shape {codes.shape}")
|
| 139 |
+
if len(codes) and codes[0] != self.MOVETO:
|
| 140 |
+
raise ValueError("The first element of 'code' must be equal "
|
| 141 |
+
f"to 'MOVETO' ({self.MOVETO}). "
|
| 142 |
+
f"Your first code is {codes[0]}")
|
| 143 |
+
elif closed and len(vertices):
|
| 144 |
+
codes = np.empty(len(vertices), dtype=self.code_type)
|
| 145 |
+
codes[0] = self.MOVETO
|
| 146 |
+
codes[1:-1] = self.LINETO
|
| 147 |
+
codes[-1] = self.CLOSEPOLY
|
| 148 |
+
|
| 149 |
+
self._vertices = vertices
|
| 150 |
+
self._codes = codes
|
| 151 |
+
self._interpolation_steps = _interpolation_steps
|
| 152 |
+
self._update_values()
|
| 153 |
+
|
| 154 |
+
if readonly:
|
| 155 |
+
self._vertices.flags.writeable = False
|
| 156 |
+
if self._codes is not None:
|
| 157 |
+
self._codes.flags.writeable = False
|
| 158 |
+
self._readonly = True
|
| 159 |
+
else:
|
| 160 |
+
self._readonly = False
|
| 161 |
+
|
| 162 |
+
@classmethod
|
| 163 |
+
def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
|
| 164 |
+
"""
|
| 165 |
+
Create a Path instance without the expense of calling the constructor.
|
| 166 |
+
|
| 167 |
+
Parameters
|
| 168 |
+
----------
|
| 169 |
+
verts : array-like
|
| 170 |
+
codes : array
|
| 171 |
+
internals_from : Path or None
|
| 172 |
+
If not None, another `Path` from which the attributes
|
| 173 |
+
``should_simplify``, ``simplify_threshold``, and
|
| 174 |
+
``interpolation_steps`` will be copied. Note that ``readonly`` is
|
| 175 |
+
never copied, and always set to ``False`` by this constructor.
|
| 176 |
+
"""
|
| 177 |
+
pth = cls.__new__(cls)
|
| 178 |
+
pth._vertices = _to_unmasked_float_array(verts)
|
| 179 |
+
pth._codes = codes
|
| 180 |
+
pth._readonly = False
|
| 181 |
+
if internals_from is not None:
|
| 182 |
+
pth._should_simplify = internals_from._should_simplify
|
| 183 |
+
pth._simplify_threshold = internals_from._simplify_threshold
|
| 184 |
+
pth._interpolation_steps = internals_from._interpolation_steps
|
| 185 |
+
else:
|
| 186 |
+
pth._should_simplify = True
|
| 187 |
+
pth._simplify_threshold = mpl.rcParams['path.simplify_threshold']
|
| 188 |
+
pth._interpolation_steps = 1
|
| 189 |
+
return pth
|
| 190 |
+
|
| 191 |
+
@classmethod
|
| 192 |
+
def _create_closed(cls, vertices):
|
| 193 |
+
"""
|
| 194 |
+
Create a closed polygonal path going through *vertices*.
|
| 195 |
+
|
| 196 |
+
Unlike ``Path(..., closed=True)``, *vertices* should **not** end with
|
| 197 |
+
an entry for the CLOSEPATH; this entry is added by `._create_closed`.
|
| 198 |
+
"""
|
| 199 |
+
v = _to_unmasked_float_array(vertices)
|
| 200 |
+
return cls(np.concatenate([v, v[:1]]), closed=True)
|
| 201 |
+
|
| 202 |
+
def _update_values(self):
|
| 203 |
+
self._simplify_threshold = mpl.rcParams['path.simplify_threshold']
|
| 204 |
+
self._should_simplify = (
|
| 205 |
+
self._simplify_threshold > 0 and
|
| 206 |
+
mpl.rcParams['path.simplify'] and
|
| 207 |
+
len(self._vertices) >= 128 and
|
| 208 |
+
(self._codes is None or np.all(self._codes <= Path.LINETO))
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def vertices(self):
|
| 213 |
+
"""The vertices of the `Path` as an (N, 2) array."""
|
| 214 |
+
return self._vertices
|
| 215 |
+
|
| 216 |
+
@vertices.setter
|
| 217 |
+
def vertices(self, vertices):
|
| 218 |
+
if self._readonly:
|
| 219 |
+
raise AttributeError("Can't set vertices on a readonly Path")
|
| 220 |
+
self._vertices = vertices
|
| 221 |
+
self._update_values()
|
| 222 |
+
|
| 223 |
+
@property
|
| 224 |
+
def codes(self):
|
| 225 |
+
"""
|
| 226 |
+
The list of codes in the `Path` as a 1D array.
|
| 227 |
+
|
| 228 |
+
Each code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4` or
|
| 229 |
+
`CLOSEPOLY`. For codes that correspond to more than one vertex
|
| 230 |
+
(`CURVE3` and `CURVE4`), that code will be repeated so that the length
|
| 231 |
+
of `vertices` and `codes` is always the same.
|
| 232 |
+
"""
|
| 233 |
+
return self._codes
|
| 234 |
+
|
| 235 |
+
@codes.setter
|
| 236 |
+
def codes(self, codes):
|
| 237 |
+
if self._readonly:
|
| 238 |
+
raise AttributeError("Can't set codes on a readonly Path")
|
| 239 |
+
self._codes = codes
|
| 240 |
+
self._update_values()
|
| 241 |
+
|
| 242 |
+
@property
|
| 243 |
+
def simplify_threshold(self):
|
| 244 |
+
"""
|
| 245 |
+
The fraction of a pixel difference below which vertices will
|
| 246 |
+
be simplified out.
|
| 247 |
+
"""
|
| 248 |
+
return self._simplify_threshold
|
| 249 |
+
|
| 250 |
+
@simplify_threshold.setter
|
| 251 |
+
def simplify_threshold(self, threshold):
|
| 252 |
+
self._simplify_threshold = threshold
|
| 253 |
+
|
| 254 |
+
@property
|
| 255 |
+
def should_simplify(self):
|
| 256 |
+
"""
|
| 257 |
+
`True` if the vertices array should be simplified.
|
| 258 |
+
"""
|
| 259 |
+
return self._should_simplify
|
| 260 |
+
|
| 261 |
+
@should_simplify.setter
|
| 262 |
+
def should_simplify(self, should_simplify):
|
| 263 |
+
self._should_simplify = should_simplify
|
| 264 |
+
|
| 265 |
+
@property
|
| 266 |
+
def readonly(self):
|
| 267 |
+
"""
|
| 268 |
+
`True` if the `Path` is read-only.
|
| 269 |
+
"""
|
| 270 |
+
return self._readonly
|
| 271 |
+
|
| 272 |
+
def copy(self):
|
| 273 |
+
"""
|
| 274 |
+
Return a shallow copy of the `Path`, which will share the
|
| 275 |
+
vertices and codes with the source `Path`.
|
| 276 |
+
"""
|
| 277 |
+
return copy.copy(self)
|
| 278 |
+
|
| 279 |
+
def __deepcopy__(self, memo=None):
|
| 280 |
+
"""
|
| 281 |
+
Return a deepcopy of the `Path`. The `Path` will not be
|
| 282 |
+
readonly, even if the source `Path` is.
|
| 283 |
+
"""
|
| 284 |
+
# Deepcopying arrays (vertices, codes) strips the writeable=False flag.
|
| 285 |
+
p = copy.deepcopy(super(), memo)
|
| 286 |
+
p._readonly = False
|
| 287 |
+
return p
|
| 288 |
+
|
| 289 |
+
deepcopy = __deepcopy__
|
| 290 |
+
|
| 291 |
+
@classmethod
|
| 292 |
+
def make_compound_path_from_polys(cls, XY):
|
| 293 |
+
"""
|
| 294 |
+
Make a compound `Path` object to draw a number of polygons with equal
|
| 295 |
+
numbers of sides.
|
| 296 |
+
|
| 297 |
+
.. plot:: gallery/misc/histogram_path.py
|
| 298 |
+
|
| 299 |
+
Parameters
|
| 300 |
+
----------
|
| 301 |
+
XY : (numpolys, numsides, 2) array
|
| 302 |
+
"""
|
| 303 |
+
# for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
|
| 304 |
+
# the CLOSEPOLY; the vert for the closepoly is ignored but we still
|
| 305 |
+
# need it to keep the codes aligned with the vertices
|
| 306 |
+
numpolys, numsides, two = XY.shape
|
| 307 |
+
if two != 2:
|
| 308 |
+
raise ValueError("The third dimension of 'XY' must be 2")
|
| 309 |
+
stride = numsides + 1
|
| 310 |
+
nverts = numpolys * stride
|
| 311 |
+
verts = np.zeros((nverts, 2))
|
| 312 |
+
codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
|
| 313 |
+
codes[0::stride] = cls.MOVETO
|
| 314 |
+
codes[numsides::stride] = cls.CLOSEPOLY
|
| 315 |
+
for i in range(numsides):
|
| 316 |
+
verts[i::stride] = XY[:, i]
|
| 317 |
+
return cls(verts, codes)
|
| 318 |
+
|
| 319 |
+
@classmethod
|
| 320 |
+
def make_compound_path(cls, *args):
|
| 321 |
+
r"""
|
| 322 |
+
Concatenate a list of `Path`\s into a single `Path`, removing all `STOP`\s.
|
| 323 |
+
"""
|
| 324 |
+
if not args:
|
| 325 |
+
return Path(np.empty([0, 2], dtype=np.float32))
|
| 326 |
+
vertices = np.concatenate([path.vertices for path in args])
|
| 327 |
+
codes = np.empty(len(vertices), dtype=cls.code_type)
|
| 328 |
+
i = 0
|
| 329 |
+
for path in args:
|
| 330 |
+
size = len(path.vertices)
|
| 331 |
+
if path.codes is None:
|
| 332 |
+
if size:
|
| 333 |
+
codes[i] = cls.MOVETO
|
| 334 |
+
codes[i+1:i+size] = cls.LINETO
|
| 335 |
+
else:
|
| 336 |
+
codes[i:i+size] = path.codes
|
| 337 |
+
i += size
|
| 338 |
+
not_stop_mask = codes != cls.STOP # Remove STOPs, as internal STOPs are a bug.
|
| 339 |
+
return cls(vertices[not_stop_mask], codes[not_stop_mask])
|
| 340 |
+
|
| 341 |
+
def __repr__(self):
|
| 342 |
+
return f"Path({self.vertices!r}, {self.codes!r})"
|
| 343 |
+
|
| 344 |
+
def __len__(self):
|
| 345 |
+
return len(self.vertices)
|
| 346 |
+
|
| 347 |
+
def iter_segments(self, transform=None, remove_nans=True, clip=None,
|
| 348 |
+
snap=False, stroke_width=1.0, simplify=None,
|
| 349 |
+
curves=True, sketch=None):
|
| 350 |
+
"""
|
| 351 |
+
Iterate over all curve segments in the path.
|
| 352 |
+
|
| 353 |
+
Each iteration returns a pair ``(vertices, code)``, where ``vertices``
|
| 354 |
+
is a sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
|
| 355 |
+
|
| 356 |
+
Additionally, this method can provide a number of standard cleanups and
|
| 357 |
+
conversions to the path.
|
| 358 |
+
|
| 359 |
+
Parameters
|
| 360 |
+
----------
|
| 361 |
+
transform : None or :class:`~matplotlib.transforms.Transform`
|
| 362 |
+
If not None, the given affine transformation will be applied to the
|
| 363 |
+
path.
|
| 364 |
+
remove_nans : bool, optional
|
| 365 |
+
Whether to remove all NaNs from the path and skip over them using
|
| 366 |
+
MOVETO commands.
|
| 367 |
+
clip : None or (float, float, float, float), optional
|
| 368 |
+
If not None, must be a four-tuple (x1, y1, x2, y2)
|
| 369 |
+
defining a rectangle in which to clip the path.
|
| 370 |
+
snap : None or bool, optional
|
| 371 |
+
If True, snap all nodes to pixels; if False, don't snap them.
|
| 372 |
+
If None, snap if the path contains only segments
|
| 373 |
+
parallel to the x or y axes, and no more than 1024 of them.
|
| 374 |
+
stroke_width : float, optional
|
| 375 |
+
The width of the stroke being drawn (used for path snapping).
|
| 376 |
+
simplify : None or bool, optional
|
| 377 |
+
Whether to simplify the path by removing vertices
|
| 378 |
+
that do not affect its appearance. If None, use the
|
| 379 |
+
:attr:`should_simplify` attribute. See also :rc:`path.simplify`
|
| 380 |
+
and :rc:`path.simplify_threshold`.
|
| 381 |
+
curves : bool, optional
|
| 382 |
+
If True, curve segments will be returned as curve segments.
|
| 383 |
+
If False, all curves will be converted to line segments.
|
| 384 |
+
sketch : None or sequence, optional
|
| 385 |
+
If not None, must be a 3-tuple of the form
|
| 386 |
+
(scale, length, randomness), representing the sketch parameters.
|
| 387 |
+
"""
|
| 388 |
+
if not len(self):
|
| 389 |
+
return
|
| 390 |
+
|
| 391 |
+
cleaned = self.cleaned(transform=transform,
|
| 392 |
+
remove_nans=remove_nans, clip=clip,
|
| 393 |
+
snap=snap, stroke_width=stroke_width,
|
| 394 |
+
simplify=simplify, curves=curves,
|
| 395 |
+
sketch=sketch)
|
| 396 |
+
|
| 397 |
+
# Cache these object lookups for performance in the loop.
|
| 398 |
+
NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
|
| 399 |
+
STOP = self.STOP
|
| 400 |
+
|
| 401 |
+
vertices = iter(cleaned.vertices)
|
| 402 |
+
codes = iter(cleaned.codes)
|
| 403 |
+
for curr_vertices, code in zip(vertices, codes):
|
| 404 |
+
if code == STOP:
|
| 405 |
+
break
|
| 406 |
+
extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
|
| 407 |
+
if extra_vertices:
|
| 408 |
+
for i in range(extra_vertices):
|
| 409 |
+
next(codes)
|
| 410 |
+
curr_vertices = np.append(curr_vertices, next(vertices))
|
| 411 |
+
yield curr_vertices, code
|
| 412 |
+
|
| 413 |
+
def iter_bezier(self, **kwargs):
|
| 414 |
+
"""
|
| 415 |
+
Iterate over each Bézier curve (lines included) in a `Path`.
|
| 416 |
+
|
| 417 |
+
Parameters
|
| 418 |
+
----------
|
| 419 |
+
**kwargs
|
| 420 |
+
Forwarded to `.iter_segments`.
|
| 421 |
+
|
| 422 |
+
Yields
|
| 423 |
+
------
|
| 424 |
+
B : `~matplotlib.bezier.BezierSegment`
|
| 425 |
+
The Bézier curves that make up the current path. Note in particular
|
| 426 |
+
that freestanding points are Bézier curves of order 0, and lines
|
| 427 |
+
are Bézier curves of order 1 (with two control points).
|
| 428 |
+
code : `~matplotlib.path.Path.code_type`
|
| 429 |
+
The code describing what kind of curve is being returned.
|
| 430 |
+
`MOVETO`, `LINETO`, `CURVE3`, and `CURVE4` correspond to
|
| 431 |
+
Bézier curves with 1, 2, 3, and 4 control points (respectively).
|
| 432 |
+
`CLOSEPOLY` is a `LINETO` with the control points correctly
|
| 433 |
+
chosen based on the start/end points of the current stroke.
|
| 434 |
+
"""
|
| 435 |
+
first_vert = None
|
| 436 |
+
prev_vert = None
|
| 437 |
+
for verts, code in self.iter_segments(**kwargs):
|
| 438 |
+
if first_vert is None:
|
| 439 |
+
if code != Path.MOVETO:
|
| 440 |
+
raise ValueError("Malformed path, must start with MOVETO.")
|
| 441 |
+
if code == Path.MOVETO: # a point is like "CURVE1"
|
| 442 |
+
first_vert = verts
|
| 443 |
+
yield BezierSegment(np.array([first_vert])), code
|
| 444 |
+
elif code == Path.LINETO: # "CURVE2"
|
| 445 |
+
yield BezierSegment(np.array([prev_vert, verts])), code
|
| 446 |
+
elif code == Path.CURVE3:
|
| 447 |
+
yield BezierSegment(np.array([prev_vert, verts[:2],
|
| 448 |
+
verts[2:]])), code
|
| 449 |
+
elif code == Path.CURVE4:
|
| 450 |
+
yield BezierSegment(np.array([prev_vert, verts[:2],
|
| 451 |
+
verts[2:4], verts[4:]])), code
|
| 452 |
+
elif code == Path.CLOSEPOLY:
|
| 453 |
+
yield BezierSegment(np.array([prev_vert, first_vert])), code
|
| 454 |
+
elif code == Path.STOP:
|
| 455 |
+
return
|
| 456 |
+
else:
|
| 457 |
+
raise ValueError(f"Invalid Path.code_type: {code}")
|
| 458 |
+
prev_vert = verts[-2:]
|
| 459 |
+
|
| 460 |
+
def _iter_connected_components(self):
|
| 461 |
+
"""Return subpaths split at MOVETOs."""
|
| 462 |
+
if self.codes is None:
|
| 463 |
+
yield self
|
| 464 |
+
else:
|
| 465 |
+
idxs = np.append((self.codes == Path.MOVETO).nonzero()[0], len(self.codes))
|
| 466 |
+
for sl in map(slice, idxs, idxs[1:]):
|
| 467 |
+
yield Path._fast_from_codes_and_verts(
|
| 468 |
+
self.vertices[sl], self.codes[sl], self)
|
| 469 |
+
|
| 470 |
+
def cleaned(self, transform=None, remove_nans=False, clip=None,
|
| 471 |
+
*, simplify=False, curves=False,
|
| 472 |
+
stroke_width=1.0, snap=False, sketch=None):
|
| 473 |
+
"""
|
| 474 |
+
Return a new `Path` with vertices and codes cleaned according to the
|
| 475 |
+
parameters.
|
| 476 |
+
|
| 477 |
+
See Also
|
| 478 |
+
--------
|
| 479 |
+
Path.iter_segments : for details of the keyword arguments.
|
| 480 |
+
"""
|
| 481 |
+
vertices, codes = _path.cleanup_path(
|
| 482 |
+
self, transform, remove_nans, clip, snap, stroke_width, simplify,
|
| 483 |
+
curves, sketch)
|
| 484 |
+
pth = Path._fast_from_codes_and_verts(vertices, codes, self)
|
| 485 |
+
if not simplify:
|
| 486 |
+
pth._should_simplify = False
|
| 487 |
+
return pth
|
| 488 |
+
|
| 489 |
+
def transformed(self, transform):
|
| 490 |
+
"""
|
| 491 |
+
Return a transformed copy of the path.
|
| 492 |
+
|
| 493 |
+
See Also
|
| 494 |
+
--------
|
| 495 |
+
matplotlib.transforms.TransformedPath
|
| 496 |
+
A specialized path class that will cache the transformed result and
|
| 497 |
+
automatically update when the transform changes.
|
| 498 |
+
"""
|
| 499 |
+
return Path(transform.transform(self.vertices), self.codes,
|
| 500 |
+
self._interpolation_steps)
|
| 501 |
+
|
| 502 |
+
def contains_point(self, point, transform=None, radius=0.0):
|
| 503 |
+
"""
|
| 504 |
+
Return whether the area enclosed by the path contains the given point.
|
| 505 |
+
|
| 506 |
+
The path is always treated as closed; i.e. if the last code is not
|
| 507 |
+
`CLOSEPOLY` an implicit segment connecting the last vertex to the first
|
| 508 |
+
vertex is assumed.
|
| 509 |
+
|
| 510 |
+
Parameters
|
| 511 |
+
----------
|
| 512 |
+
point : (float, float)
|
| 513 |
+
The point (x, y) to check.
|
| 514 |
+
transform : `~matplotlib.transforms.Transform`, optional
|
| 515 |
+
If not ``None``, *point* will be compared to ``self`` transformed
|
| 516 |
+
by *transform*; i.e. for a correct check, *transform* should
|
| 517 |
+
transform the path into the coordinate system of *point*.
|
| 518 |
+
radius : float, default: 0
|
| 519 |
+
Additional margin on the path in coordinates of *point*.
|
| 520 |
+
The path is extended tangentially by *radius/2*; i.e. if you would
|
| 521 |
+
draw the path with a linewidth of *radius*, all points on the line
|
| 522 |
+
would still be considered to be contained in the area. Conversely,
|
| 523 |
+
negative values shrink the area: Points on the imaginary line
|
| 524 |
+
will be considered outside the area.
|
| 525 |
+
|
| 526 |
+
Returns
|
| 527 |
+
-------
|
| 528 |
+
bool
|
| 529 |
+
|
| 530 |
+
Notes
|
| 531 |
+
-----
|
| 532 |
+
The current algorithm has some limitations:
|
| 533 |
+
|
| 534 |
+
- The result is undefined for points exactly at the boundary
|
| 535 |
+
(i.e. at the path shifted by *radius/2*).
|
| 536 |
+
- The result is undefined if there is no enclosed area, i.e. all
|
| 537 |
+
vertices are on a straight line.
|
| 538 |
+
- If bounding lines start to cross each other due to *radius* shift,
|
| 539 |
+
the result is not guaranteed to be correct.
|
| 540 |
+
"""
|
| 541 |
+
if transform is not None:
|
| 542 |
+
transform = transform.frozen()
|
| 543 |
+
# `point_in_path` does not handle nonlinear transforms, so we
|
| 544 |
+
# transform the path ourselves. If *transform* is affine, letting
|
| 545 |
+
# `point_in_path` handle the transform avoids allocating an extra
|
| 546 |
+
# buffer.
|
| 547 |
+
if transform and not transform.is_affine:
|
| 548 |
+
self = transform.transform_path(self)
|
| 549 |
+
transform = None
|
| 550 |
+
return _path.point_in_path(point[0], point[1], radius, self, transform)
|
| 551 |
+
|
| 552 |
+
def contains_points(self, points, transform=None, radius=0.0):
|
| 553 |
+
"""
|
| 554 |
+
Return whether the area enclosed by the path contains the given points.
|
| 555 |
+
|
| 556 |
+
The path is always treated as closed; i.e. if the last code is not
|
| 557 |
+
`CLOSEPOLY` an implicit segment connecting the last vertex to the first
|
| 558 |
+
vertex is assumed.
|
| 559 |
+
|
| 560 |
+
Parameters
|
| 561 |
+
----------
|
| 562 |
+
points : (N, 2) array
|
| 563 |
+
The points to check. Columns contain x and y values.
|
| 564 |
+
transform : `~matplotlib.transforms.Transform`, optional
|
| 565 |
+
If not ``None``, *points* will be compared to ``self`` transformed
|
| 566 |
+
by *transform*; i.e. for a correct check, *transform* should
|
| 567 |
+
transform the path into the coordinate system of *points*.
|
| 568 |
+
radius : float, default: 0
|
| 569 |
+
Additional margin on the path in coordinates of *points*.
|
| 570 |
+
The path is extended tangentially by *radius/2*; i.e. if you would
|
| 571 |
+
draw the path with a linewidth of *radius*, all points on the line
|
| 572 |
+
would still be considered to be contained in the area. Conversely,
|
| 573 |
+
negative values shrink the area: Points on the imaginary line
|
| 574 |
+
will be considered outside the area.
|
| 575 |
+
|
| 576 |
+
Returns
|
| 577 |
+
-------
|
| 578 |
+
length-N bool array
|
| 579 |
+
|
| 580 |
+
Notes
|
| 581 |
+
-----
|
| 582 |
+
The current algorithm has some limitations:
|
| 583 |
+
|
| 584 |
+
- The result is undefined for points exactly at the boundary
|
| 585 |
+
(i.e. at the path shifted by *radius/2*).
|
| 586 |
+
- The result is undefined if there is no enclosed area, i.e. all
|
| 587 |
+
vertices are on a straight line.
|
| 588 |
+
- If bounding lines start to cross each other due to *radius* shift,
|
| 589 |
+
the result is not guaranteed to be correct.
|
| 590 |
+
"""
|
| 591 |
+
if transform is not None:
|
| 592 |
+
transform = transform.frozen()
|
| 593 |
+
result = _path.points_in_path(points, radius, self, transform)
|
| 594 |
+
return result.astype('bool')
|
| 595 |
+
|
| 596 |
+
def contains_path(self, path, transform=None):
|
| 597 |
+
"""
|
| 598 |
+
Return whether this (closed) path completely contains the given path.
|
| 599 |
+
|
| 600 |
+
If *transform* is not ``None``, the path will be transformed before
|
| 601 |
+
checking for containment.
|
| 602 |
+
"""
|
| 603 |
+
if transform is not None:
|
| 604 |
+
transform = transform.frozen()
|
| 605 |
+
return _path.path_in_path(self, None, path, transform)
|
| 606 |
+
|
| 607 |
+
def get_extents(self, transform=None, **kwargs):
|
| 608 |
+
"""
|
| 609 |
+
Get Bbox of the path.
|
| 610 |
+
|
| 611 |
+
Parameters
|
| 612 |
+
----------
|
| 613 |
+
transform : `~matplotlib.transforms.Transform`, optional
|
| 614 |
+
Transform to apply to path before computing extents, if any.
|
| 615 |
+
**kwargs
|
| 616 |
+
Forwarded to `.iter_bezier`.
|
| 617 |
+
|
| 618 |
+
Returns
|
| 619 |
+
-------
|
| 620 |
+
matplotlib.transforms.Bbox
|
| 621 |
+
The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])
|
| 622 |
+
"""
|
| 623 |
+
from .transforms import Bbox
|
| 624 |
+
if transform is not None:
|
| 625 |
+
self = transform.transform_path(self)
|
| 626 |
+
if self.codes is None:
|
| 627 |
+
xys = self.vertices
|
| 628 |
+
elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
|
| 629 |
+
# Optimization for the straight line case.
|
| 630 |
+
# Instead of iterating through each curve, consider
|
| 631 |
+
# each line segment's end-points
|
| 632 |
+
# (recall that STOP and CLOSEPOLY vertices are ignored)
|
| 633 |
+
xys = self.vertices[np.isin(self.codes,
|
| 634 |
+
[Path.MOVETO, Path.LINETO])]
|
| 635 |
+
else:
|
| 636 |
+
xys = []
|
| 637 |
+
for curve, code in self.iter_bezier(**kwargs):
|
| 638 |
+
# places where the derivative is zero can be extrema
|
| 639 |
+
_, dzeros = curve.axis_aligned_extrema()
|
| 640 |
+
# as can the ends of the curve
|
| 641 |
+
xys.append(curve([0, *dzeros, 1]))
|
| 642 |
+
xys = np.concatenate(xys)
|
| 643 |
+
if len(xys):
|
| 644 |
+
return Bbox([xys.min(axis=0), xys.max(axis=0)])
|
| 645 |
+
else:
|
| 646 |
+
return Bbox.null()
|
| 647 |
+
|
| 648 |
+
def intersects_path(self, other, filled=True):
|
| 649 |
+
"""
|
| 650 |
+
Return whether if this path intersects another given path.
|
| 651 |
+
|
| 652 |
+
If *filled* is True, then this also returns True if one path completely
|
| 653 |
+
encloses the other (i.e., the paths are treated as filled).
|
| 654 |
+
"""
|
| 655 |
+
return _path.path_intersects_path(self, other, filled)
|
| 656 |
+
|
| 657 |
+
def intersects_bbox(self, bbox, filled=True):
|
| 658 |
+
"""
|
| 659 |
+
Return whether this path intersects a given `~.transforms.Bbox`.
|
| 660 |
+
|
| 661 |
+
If *filled* is True, then this also returns True if the path completely
|
| 662 |
+
encloses the `.Bbox` (i.e., the path is treated as filled).
|
| 663 |
+
|
| 664 |
+
The bounding box is always considered filled.
|
| 665 |
+
"""
|
| 666 |
+
return _path.path_intersects_rectangle(
|
| 667 |
+
self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
|
| 668 |
+
|
| 669 |
+
def interpolated(self, steps):
|
| 670 |
+
"""
|
| 671 |
+
Return a new path resampled to length N x *steps*.
|
| 672 |
+
|
| 673 |
+
Codes other than `LINETO` are not handled correctly.
|
| 674 |
+
"""
|
| 675 |
+
if steps == 1:
|
| 676 |
+
return self
|
| 677 |
+
|
| 678 |
+
vertices = simple_linear_interpolation(self.vertices, steps)
|
| 679 |
+
codes = self.codes
|
| 680 |
+
if codes is not None:
|
| 681 |
+
new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
|
| 682 |
+
dtype=self.code_type)
|
| 683 |
+
new_codes[0::steps] = codes
|
| 684 |
+
else:
|
| 685 |
+
new_codes = None
|
| 686 |
+
return Path(vertices, new_codes)
|
| 687 |
+
|
| 688 |
+
def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
|
| 689 |
+
"""
|
| 690 |
+
Convert this path to a list of polygons or polylines. Each
|
| 691 |
+
polygon/polyline is an (N, 2) array of vertices. In other words,
|
| 692 |
+
each polygon has no `MOVETO` instructions or curves. This
|
| 693 |
+
is useful for displaying in backends that do not support
|
| 694 |
+
compound paths or Bézier curves.
|
| 695 |
+
|
| 696 |
+
If *width* and *height* are both non-zero then the lines will
|
| 697 |
+
be simplified so that vertices outside of (0, 0), (width,
|
| 698 |
+
height) will be clipped.
|
| 699 |
+
|
| 700 |
+
The resulting polygons will be simplified if the
|
| 701 |
+
:attr:`Path.should_simplify` attribute of the path is `True`.
|
| 702 |
+
|
| 703 |
+
If *closed_only* is `True` (default), only closed polygons,
|
| 704 |
+
with the last point being the same as the first point, will be
|
| 705 |
+
returned. Any unclosed polylines in the path will be
|
| 706 |
+
explicitly closed. If *closed_only* is `False`, any unclosed
|
| 707 |
+
polygons in the path will be returned as unclosed polygons,
|
| 708 |
+
and the closed polygons will be returned explicitly closed by
|
| 709 |
+
setting the last point to the same as the first point.
|
| 710 |
+
"""
|
| 711 |
+
if len(self.vertices) == 0:
|
| 712 |
+
return []
|
| 713 |
+
|
| 714 |
+
if transform is not None:
|
| 715 |
+
transform = transform.frozen()
|
| 716 |
+
|
| 717 |
+
if self.codes is None and (width == 0 or height == 0):
|
| 718 |
+
vertices = self.vertices
|
| 719 |
+
if closed_only:
|
| 720 |
+
if len(vertices) < 3:
|
| 721 |
+
return []
|
| 722 |
+
elif np.any(vertices[0] != vertices[-1]):
|
| 723 |
+
vertices = [*vertices, vertices[0]]
|
| 724 |
+
|
| 725 |
+
if transform is None:
|
| 726 |
+
return [vertices]
|
| 727 |
+
else:
|
| 728 |
+
return [transform.transform(vertices)]
|
| 729 |
+
|
| 730 |
+
# Deal with the case where there are curves and/or multiple
|
| 731 |
+
# subpaths (using extension code)
|
| 732 |
+
return _path.convert_path_to_polygons(
|
| 733 |
+
self, transform, width, height, closed_only)
|
| 734 |
+
|
| 735 |
+
_unit_rectangle = None
|
| 736 |
+
|
| 737 |
+
@classmethod
|
| 738 |
+
def unit_rectangle(cls):
|
| 739 |
+
"""
|
| 740 |
+
Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
|
| 741 |
+
"""
|
| 742 |
+
if cls._unit_rectangle is None:
|
| 743 |
+
cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]],
|
| 744 |
+
closed=True, readonly=True)
|
| 745 |
+
return cls._unit_rectangle
|
| 746 |
+
|
| 747 |
+
_unit_regular_polygons = WeakValueDictionary()
|
| 748 |
+
|
| 749 |
+
@classmethod
|
| 750 |
+
def unit_regular_polygon(cls, numVertices):
|
| 751 |
+
"""
|
| 752 |
+
Return a :class:`Path` instance for a unit regular polygon with the
|
| 753 |
+
given *numVertices* such that the circumscribing circle has radius 1.0,
|
| 754 |
+
centered at (0, 0).
|
| 755 |
+
"""
|
| 756 |
+
if numVertices <= 16:
|
| 757 |
+
path = cls._unit_regular_polygons.get(numVertices)
|
| 758 |
+
else:
|
| 759 |
+
path = None
|
| 760 |
+
if path is None:
|
| 761 |
+
theta = ((2 * np.pi / numVertices) * np.arange(numVertices + 1)
|
| 762 |
+
# This initial rotation is to make sure the polygon always
|
| 763 |
+
# "points-up".
|
| 764 |
+
+ np.pi / 2)
|
| 765 |
+
verts = np.column_stack((np.cos(theta), np.sin(theta)))
|
| 766 |
+
path = cls(verts, closed=True, readonly=True)
|
| 767 |
+
if numVertices <= 16:
|
| 768 |
+
cls._unit_regular_polygons[numVertices] = path
|
| 769 |
+
return path
|
| 770 |
+
|
| 771 |
+
_unit_regular_stars = WeakValueDictionary()
|
| 772 |
+
|
| 773 |
+
@classmethod
|
| 774 |
+
def unit_regular_star(cls, numVertices, innerCircle=0.5):
|
| 775 |
+
"""
|
| 776 |
+
Return a :class:`Path` for a unit regular star with the given
|
| 777 |
+
numVertices and radius of 1.0, centered at (0, 0).
|
| 778 |
+
"""
|
| 779 |
+
if numVertices <= 16:
|
| 780 |
+
path = cls._unit_regular_stars.get((numVertices, innerCircle))
|
| 781 |
+
else:
|
| 782 |
+
path = None
|
| 783 |
+
if path is None:
|
| 784 |
+
ns2 = numVertices * 2
|
| 785 |
+
theta = (2*np.pi/ns2 * np.arange(ns2 + 1))
|
| 786 |
+
# This initial rotation is to make sure the polygon always
|
| 787 |
+
# "points-up"
|
| 788 |
+
theta += np.pi / 2.0
|
| 789 |
+
r = np.ones(ns2 + 1)
|
| 790 |
+
r[1::2] = innerCircle
|
| 791 |
+
verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T
|
| 792 |
+
path = cls(verts, closed=True, readonly=True)
|
| 793 |
+
if numVertices <= 16:
|
| 794 |
+
cls._unit_regular_stars[(numVertices, innerCircle)] = path
|
| 795 |
+
return path
|
| 796 |
+
|
| 797 |
+
@classmethod
|
| 798 |
+
def unit_regular_asterisk(cls, numVertices):
|
| 799 |
+
"""
|
| 800 |
+
Return a :class:`Path` for a unit regular asterisk with the given
|
| 801 |
+
numVertices and radius of 1.0, centered at (0, 0).
|
| 802 |
+
"""
|
| 803 |
+
return cls.unit_regular_star(numVertices, 0.0)
|
| 804 |
+
|
| 805 |
+
_unit_circle = None
|
| 806 |
+
|
| 807 |
+
@classmethod
|
| 808 |
+
def unit_circle(cls):
|
| 809 |
+
"""
|
| 810 |
+
Return the readonly :class:`Path` of the unit circle.
|
| 811 |
+
|
| 812 |
+
For most cases, :func:`Path.circle` will be what you want.
|
| 813 |
+
"""
|
| 814 |
+
if cls._unit_circle is None:
|
| 815 |
+
cls._unit_circle = cls.circle(center=(0, 0), radius=1,
|
| 816 |
+
readonly=True)
|
| 817 |
+
return cls._unit_circle
|
| 818 |
+
|
| 819 |
+
@classmethod
|
| 820 |
+
def circle(cls, center=(0., 0.), radius=1., readonly=False):
|
| 821 |
+
"""
|
| 822 |
+
Return a `Path` representing a circle of a given radius and center.
|
| 823 |
+
|
| 824 |
+
Parameters
|
| 825 |
+
----------
|
| 826 |
+
center : (float, float), default: (0, 0)
|
| 827 |
+
The center of the circle.
|
| 828 |
+
radius : float, default: 1
|
| 829 |
+
The radius of the circle.
|
| 830 |
+
readonly : bool
|
| 831 |
+
Whether the created path should have the "readonly" argument
|
| 832 |
+
set when creating the Path instance.
|
| 833 |
+
|
| 834 |
+
Notes
|
| 835 |
+
-----
|
| 836 |
+
The circle is approximated using 8 cubic Bézier curves, as described in
|
| 837 |
+
|
| 838 |
+
Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
|
| 839 |
+
Bezier Cubic Splines <https://www.tinaja.com/glib/ellipse4.pdf>`_.
|
| 840 |
+
"""
|
| 841 |
+
MAGIC = 0.2652031
|
| 842 |
+
SQRTHALF = np.sqrt(0.5)
|
| 843 |
+
MAGIC45 = SQRTHALF * MAGIC
|
| 844 |
+
|
| 845 |
+
vertices = np.array([[0.0, -1.0],
|
| 846 |
+
|
| 847 |
+
[MAGIC, -1.0],
|
| 848 |
+
[SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
|
| 849 |
+
[SQRTHALF, -SQRTHALF],
|
| 850 |
+
|
| 851 |
+
[SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
|
| 852 |
+
[1.0, -MAGIC],
|
| 853 |
+
[1.0, 0.0],
|
| 854 |
+
|
| 855 |
+
[1.0, MAGIC],
|
| 856 |
+
[SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
|
| 857 |
+
[SQRTHALF, SQRTHALF],
|
| 858 |
+
|
| 859 |
+
[SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
|
| 860 |
+
[MAGIC, 1.0],
|
| 861 |
+
[0.0, 1.0],
|
| 862 |
+
|
| 863 |
+
[-MAGIC, 1.0],
|
| 864 |
+
[-SQRTHALF+MAGIC45, SQRTHALF+MAGIC45],
|
| 865 |
+
[-SQRTHALF, SQRTHALF],
|
| 866 |
+
|
| 867 |
+
[-SQRTHALF-MAGIC45, SQRTHALF-MAGIC45],
|
| 868 |
+
[-1.0, MAGIC],
|
| 869 |
+
[-1.0, 0.0],
|
| 870 |
+
|
| 871 |
+
[-1.0, -MAGIC],
|
| 872 |
+
[-SQRTHALF-MAGIC45, -SQRTHALF+MAGIC45],
|
| 873 |
+
[-SQRTHALF, -SQRTHALF],
|
| 874 |
+
|
| 875 |
+
[-SQRTHALF+MAGIC45, -SQRTHALF-MAGIC45],
|
| 876 |
+
[-MAGIC, -1.0],
|
| 877 |
+
[0.0, -1.0],
|
| 878 |
+
|
| 879 |
+
[0.0, -1.0]],
|
| 880 |
+
dtype=float)
|
| 881 |
+
|
| 882 |
+
codes = [cls.CURVE4] * 26
|
| 883 |
+
codes[0] = cls.MOVETO
|
| 884 |
+
codes[-1] = cls.CLOSEPOLY
|
| 885 |
+
return Path(vertices * radius + center, codes, readonly=readonly)
|
| 886 |
+
|
| 887 |
+
_unit_circle_righthalf = None
|
| 888 |
+
|
| 889 |
+
@classmethod
|
| 890 |
+
def unit_circle_righthalf(cls):
|
| 891 |
+
"""
|
| 892 |
+
Return a `Path` of the right half of a unit circle.
|
| 893 |
+
|
| 894 |
+
See `Path.circle` for the reference on the approximation used.
|
| 895 |
+
"""
|
| 896 |
+
if cls._unit_circle_righthalf is None:
|
| 897 |
+
MAGIC = 0.2652031
|
| 898 |
+
SQRTHALF = np.sqrt(0.5)
|
| 899 |
+
MAGIC45 = SQRTHALF * MAGIC
|
| 900 |
+
|
| 901 |
+
vertices = np.array(
|
| 902 |
+
[[0.0, -1.0],
|
| 903 |
+
|
| 904 |
+
[MAGIC, -1.0],
|
| 905 |
+
[SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
|
| 906 |
+
[SQRTHALF, -SQRTHALF],
|
| 907 |
+
|
| 908 |
+
[SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
|
| 909 |
+
[1.0, -MAGIC],
|
| 910 |
+
[1.0, 0.0],
|
| 911 |
+
|
| 912 |
+
[1.0, MAGIC],
|
| 913 |
+
[SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
|
| 914 |
+
[SQRTHALF, SQRTHALF],
|
| 915 |
+
|
| 916 |
+
[SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
|
| 917 |
+
[MAGIC, 1.0],
|
| 918 |
+
[0.0, 1.0],
|
| 919 |
+
|
| 920 |
+
[0.0, -1.0]],
|
| 921 |
+
|
| 922 |
+
float)
|
| 923 |
+
|
| 924 |
+
codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
|
| 925 |
+
codes[0] = cls.MOVETO
|
| 926 |
+
codes[-1] = cls.CLOSEPOLY
|
| 927 |
+
|
| 928 |
+
cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
|
| 929 |
+
return cls._unit_circle_righthalf
|
| 930 |
+
|
| 931 |
+
@classmethod
|
| 932 |
+
def arc(cls, theta1, theta2, n=None, is_wedge=False):
|
| 933 |
+
"""
|
| 934 |
+
Return a `Path` for the unit circle arc from angles *theta1* to
|
| 935 |
+
*theta2* (in degrees).
|
| 936 |
+
|
| 937 |
+
*theta2* is unwrapped to produce the shortest arc within 360 degrees.
|
| 938 |
+
That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
|
| 939 |
+
*theta2* - 360 and not a full circle plus some extra overlap.
|
| 940 |
+
|
| 941 |
+
If *n* is provided, it is the number of spline segments to make.
|
| 942 |
+
If *n* is not provided, the number of spline segments is
|
| 943 |
+
determined based on the delta between *theta1* and *theta2*.
|
| 944 |
+
|
| 945 |
+
Masionobe, L. 2003. `Drawing an elliptical arc using
|
| 946 |
+
polylines, quadratic or cubic Bezier curves
|
| 947 |
+
<https://web.archive.org/web/20190318044212/http://www.spaceroots.org/documents/ellipse/index.html>`_.
|
| 948 |
+
"""
|
| 949 |
+
halfpi = np.pi * 0.5
|
| 950 |
+
|
| 951 |
+
eta1 = theta1
|
| 952 |
+
eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
|
| 953 |
+
# Ensure 2pi range is not flattened to 0 due to floating-point errors,
|
| 954 |
+
# but don't try to expand existing 0 range.
|
| 955 |
+
if theta2 != theta1 and eta2 <= eta1:
|
| 956 |
+
eta2 += 360
|
| 957 |
+
eta1, eta2 = np.deg2rad([eta1, eta2])
|
| 958 |
+
|
| 959 |
+
# number of curve segments to make
|
| 960 |
+
if n is None:
|
| 961 |
+
n = int(2 ** np.ceil((eta2 - eta1) / halfpi))
|
| 962 |
+
if n < 1:
|
| 963 |
+
raise ValueError("n must be >= 1 or None")
|
| 964 |
+
|
| 965 |
+
deta = (eta2 - eta1) / n
|
| 966 |
+
t = np.tan(0.5 * deta)
|
| 967 |
+
alpha = np.sin(deta) * (np.sqrt(4.0 + 3.0 * t * t) - 1) / 3.0
|
| 968 |
+
|
| 969 |
+
steps = np.linspace(eta1, eta2, n + 1, True)
|
| 970 |
+
cos_eta = np.cos(steps)
|
| 971 |
+
sin_eta = np.sin(steps)
|
| 972 |
+
|
| 973 |
+
xA = cos_eta[:-1]
|
| 974 |
+
yA = sin_eta[:-1]
|
| 975 |
+
xA_dot = -yA
|
| 976 |
+
yA_dot = xA
|
| 977 |
+
|
| 978 |
+
xB = cos_eta[1:]
|
| 979 |
+
yB = sin_eta[1:]
|
| 980 |
+
xB_dot = -yB
|
| 981 |
+
yB_dot = xB
|
| 982 |
+
|
| 983 |
+
if is_wedge:
|
| 984 |
+
length = n * 3 + 4
|
| 985 |
+
vertices = np.zeros((length, 2), float)
|
| 986 |
+
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
|
| 987 |
+
vertices[1] = [xA[0], yA[0]]
|
| 988 |
+
codes[0:2] = [cls.MOVETO, cls.LINETO]
|
| 989 |
+
codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
|
| 990 |
+
vertex_offset = 2
|
| 991 |
+
end = length - 2
|
| 992 |
+
else:
|
| 993 |
+
length = n * 3 + 1
|
| 994 |
+
vertices = np.empty((length, 2), float)
|
| 995 |
+
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
|
| 996 |
+
vertices[0] = [xA[0], yA[0]]
|
| 997 |
+
codes[0] = cls.MOVETO
|
| 998 |
+
vertex_offset = 1
|
| 999 |
+
end = length
|
| 1000 |
+
|
| 1001 |
+
vertices[vertex_offset:end:3, 0] = xA + alpha * xA_dot
|
| 1002 |
+
vertices[vertex_offset:end:3, 1] = yA + alpha * yA_dot
|
| 1003 |
+
vertices[vertex_offset+1:end:3, 0] = xB - alpha * xB_dot
|
| 1004 |
+
vertices[vertex_offset+1:end:3, 1] = yB - alpha * yB_dot
|
| 1005 |
+
vertices[vertex_offset+2:end:3, 0] = xB
|
| 1006 |
+
vertices[vertex_offset+2:end:3, 1] = yB
|
| 1007 |
+
|
| 1008 |
+
return cls(vertices, codes, readonly=True)
|
| 1009 |
+
|
| 1010 |
+
@classmethod
|
| 1011 |
+
def wedge(cls, theta1, theta2, n=None):
|
| 1012 |
+
"""
|
| 1013 |
+
Return a `Path` for the unit circle wedge from angles *theta1* to
|
| 1014 |
+
*theta2* (in degrees).
|
| 1015 |
+
|
| 1016 |
+
*theta2* is unwrapped to produce the shortest wedge within 360 degrees.
|
| 1017 |
+
That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
|
| 1018 |
+
to *theta2* - 360 and not a full circle plus some extra overlap.
|
| 1019 |
+
|
| 1020 |
+
If *n* is provided, it is the number of spline segments to make.
|
| 1021 |
+
If *n* is not provided, the number of spline segments is
|
| 1022 |
+
determined based on the delta between *theta1* and *theta2*.
|
| 1023 |
+
|
| 1024 |
+
See `Path.arc` for the reference on the approximation used.
|
| 1025 |
+
"""
|
| 1026 |
+
return cls.arc(theta1, theta2, n, True)
|
| 1027 |
+
|
| 1028 |
+
@staticmethod
|
| 1029 |
+
@lru_cache(8)
|
| 1030 |
+
def hatch(hatchpattern, density=6):
|
| 1031 |
+
"""
|
| 1032 |
+
Given a hatch specifier, *hatchpattern*, generates a `Path` that
|
| 1033 |
+
can be used in a repeated hatching pattern. *density* is the
|
| 1034 |
+
number of lines per unit square.
|
| 1035 |
+
"""
|
| 1036 |
+
from matplotlib.hatch import get_path
|
| 1037 |
+
return (get_path(hatchpattern, density)
|
| 1038 |
+
if hatchpattern is not None else None)
|
| 1039 |
+
|
| 1040 |
+
def clip_to_bbox(self, bbox, inside=True):
|
| 1041 |
+
"""
|
| 1042 |
+
Clip the path to the given bounding box.
|
| 1043 |
+
|
| 1044 |
+
The path must be made up of one or more closed polygons. This
|
| 1045 |
+
algorithm will not behave correctly for unclosed paths.
|
| 1046 |
+
|
| 1047 |
+
If *inside* is `True`, clip to the inside of the box, otherwise
|
| 1048 |
+
to the outside of the box.
|
| 1049 |
+
"""
|
| 1050 |
+
verts = _path.clip_path_to_rect(self, bbox, inside)
|
| 1051 |
+
paths = [Path(poly) for poly in verts]
|
| 1052 |
+
return self.make_compound_path(*paths)
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
def get_path_collection_extents(
|
| 1056 |
+
master_transform, paths, transforms, offsets, offset_transform):
|
| 1057 |
+
r"""
|
| 1058 |
+
Get bounding box of a `.PathCollection`\s internal objects.
|
| 1059 |
+
|
| 1060 |
+
That is, given a sequence of `Path`\s, `.Transform`\s objects, and offsets, as found
|
| 1061 |
+
in a `.PathCollection`, return the bounding box that encapsulates all of them.
|
| 1062 |
+
|
| 1063 |
+
Parameters
|
| 1064 |
+
----------
|
| 1065 |
+
master_transform : `~matplotlib.transforms.Transform`
|
| 1066 |
+
Global transformation applied to all paths.
|
| 1067 |
+
paths : list of `Path`
|
| 1068 |
+
transforms : list of `~matplotlib.transforms.Affine2DBase`
|
| 1069 |
+
If non-empty, this overrides *master_transform*.
|
| 1070 |
+
offsets : (N, 2) array-like
|
| 1071 |
+
offset_transform : `~matplotlib.transforms.Affine2DBase`
|
| 1072 |
+
Transform applied to the offsets before offsetting the path.
|
| 1073 |
+
|
| 1074 |
+
Notes
|
| 1075 |
+
-----
|
| 1076 |
+
The way that *paths*, *transforms* and *offsets* are combined follows the same
|
| 1077 |
+
method as for collections: each is iterated over independently, so if you have 3
|
| 1078 |
+
paths (A, B, C), 2 transforms (α, β) and 1 offset (O), their combinations are as
|
| 1079 |
+
follows:
|
| 1080 |
+
|
| 1081 |
+
- (A, α, O)
|
| 1082 |
+
- (B, β, O)
|
| 1083 |
+
- (C, α, O)
|
| 1084 |
+
"""
|
| 1085 |
+
from .transforms import Bbox
|
| 1086 |
+
if len(paths) == 0:
|
| 1087 |
+
raise ValueError("No paths provided")
|
| 1088 |
+
if len(offsets) == 0:
|
| 1089 |
+
_api.warn_deprecated(
|
| 1090 |
+
"3.8", message="Calling get_path_collection_extents() with an"
|
| 1091 |
+
" empty offsets list is deprecated since %(since)s. Support will"
|
| 1092 |
+
" be removed %(removal)s.")
|
| 1093 |
+
extents, minpos = _path.get_path_collection_extents(
|
| 1094 |
+
master_transform, paths, np.atleast_3d(transforms),
|
| 1095 |
+
offsets, offset_transform)
|
| 1096 |
+
return Bbox.from_extents(*extents, minpos=minpos)
|
parrot/lib/python3.10/site-packages/matplotlib/py.typed
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/matplotlib/rcsetup.py
ADDED
|
@@ -0,0 +1,1377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The rcsetup module contains the validation code for customization using
|
| 3 |
+
Matplotlib's rc settings.
|
| 4 |
+
|
| 5 |
+
Each rc setting is assigned a function used to validate any attempted changes
|
| 6 |
+
to that setting. The validation functions are defined in the rcsetup module,
|
| 7 |
+
and are used to construct the rcParams global object which stores the settings
|
| 8 |
+
and is referenced throughout Matplotlib.
|
| 9 |
+
|
| 10 |
+
The default values of the rc settings are set in the default matplotlibrc file.
|
| 11 |
+
Any additions or deletions to the parameter set listed here should also be
|
| 12 |
+
propagated to the :file:`lib/matplotlib/mpl-data/matplotlibrc` in Matplotlib's
|
| 13 |
+
root source directory.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import ast
|
| 17 |
+
from functools import lru_cache, reduce
|
| 18 |
+
from numbers import Real
|
| 19 |
+
import operator
|
| 20 |
+
import os
|
| 21 |
+
import re
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from matplotlib import _api, cbook
|
| 26 |
+
from matplotlib.backends import BackendFilter, backend_registry
|
| 27 |
+
from matplotlib.cbook import ls_mapper
|
| 28 |
+
from matplotlib.colors import Colormap, is_color_like
|
| 29 |
+
from matplotlib._fontconfig_pattern import parse_fontconfig_pattern
|
| 30 |
+
from matplotlib._enums import JoinStyle, CapStyle
|
| 31 |
+
|
| 32 |
+
# Don't let the original cycler collide with our validating cycler
|
| 33 |
+
from cycler import Cycler, cycler as ccycler
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@_api.caching_module_getattr
|
| 37 |
+
class __getattr__:
|
| 38 |
+
@_api.deprecated(
|
| 39 |
+
"3.9",
|
| 40 |
+
alternative="``matplotlib.backends.backend_registry.list_builtin"
|
| 41 |
+
"(matplotlib.backends.BackendFilter.INTERACTIVE)``")
|
| 42 |
+
@property
|
| 43 |
+
def interactive_bk(self):
|
| 44 |
+
return backend_registry.list_builtin(BackendFilter.INTERACTIVE)
|
| 45 |
+
|
| 46 |
+
@_api.deprecated(
|
| 47 |
+
"3.9",
|
| 48 |
+
alternative="``matplotlib.backends.backend_registry.list_builtin"
|
| 49 |
+
"(matplotlib.backends.BackendFilter.NON_INTERACTIVE)``")
|
| 50 |
+
@property
|
| 51 |
+
def non_interactive_bk(self):
|
| 52 |
+
return backend_registry.list_builtin(BackendFilter.NON_INTERACTIVE)
|
| 53 |
+
|
| 54 |
+
@_api.deprecated(
|
| 55 |
+
"3.9",
|
| 56 |
+
alternative="``matplotlib.backends.backend_registry.list_builtin()``")
|
| 57 |
+
@property
|
| 58 |
+
def all_backends(self):
|
| 59 |
+
return backend_registry.list_builtin()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class ValidateInStrings:
|
| 63 |
+
def __init__(self, key, valid, ignorecase=False, *,
|
| 64 |
+
_deprecated_since=None):
|
| 65 |
+
"""*valid* is a list of legal strings."""
|
| 66 |
+
self.key = key
|
| 67 |
+
self.ignorecase = ignorecase
|
| 68 |
+
self._deprecated_since = _deprecated_since
|
| 69 |
+
|
| 70 |
+
def func(s):
|
| 71 |
+
if ignorecase:
|
| 72 |
+
return s.lower()
|
| 73 |
+
else:
|
| 74 |
+
return s
|
| 75 |
+
self.valid = {func(k): k for k in valid}
|
| 76 |
+
|
| 77 |
+
def __call__(self, s):
|
| 78 |
+
if self._deprecated_since:
|
| 79 |
+
name, = (k for k, v in globals().items() if v is self)
|
| 80 |
+
_api.warn_deprecated(
|
| 81 |
+
self._deprecated_since, name=name, obj_type="function")
|
| 82 |
+
if self.ignorecase and isinstance(s, str):
|
| 83 |
+
s = s.lower()
|
| 84 |
+
if s in self.valid:
|
| 85 |
+
return self.valid[s]
|
| 86 |
+
msg = (f"{s!r} is not a valid value for {self.key}; supported values "
|
| 87 |
+
f"are {[*self.valid.values()]}")
|
| 88 |
+
if (isinstance(s, str)
|
| 89 |
+
and (s.startswith('"') and s.endswith('"')
|
| 90 |
+
or s.startswith("'") and s.endswith("'"))
|
| 91 |
+
and s[1:-1] in self.valid):
|
| 92 |
+
msg += "; remove quotes surrounding your string"
|
| 93 |
+
raise ValueError(msg)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@lru_cache
|
| 97 |
+
def _listify_validator(scalar_validator, allow_stringlist=False, *,
|
| 98 |
+
n=None, doc=None):
|
| 99 |
+
def f(s):
|
| 100 |
+
if isinstance(s, str):
|
| 101 |
+
try:
|
| 102 |
+
val = [scalar_validator(v.strip()) for v in s.split(',')
|
| 103 |
+
if v.strip()]
|
| 104 |
+
except Exception:
|
| 105 |
+
if allow_stringlist:
|
| 106 |
+
# Sometimes, a list of colors might be a single string
|
| 107 |
+
# of single-letter colornames. So give that a shot.
|
| 108 |
+
val = [scalar_validator(v.strip()) for v in s if v.strip()]
|
| 109 |
+
else:
|
| 110 |
+
raise
|
| 111 |
+
# Allow any ordered sequence type -- generators, np.ndarray, pd.Series
|
| 112 |
+
# -- but not sets, whose iteration order is non-deterministic.
|
| 113 |
+
elif np.iterable(s) and not isinstance(s, (set, frozenset)):
|
| 114 |
+
# The condition on this list comprehension will preserve the
|
| 115 |
+
# behavior of filtering out any empty strings (behavior was
|
| 116 |
+
# from the original validate_stringlist()), while allowing
|
| 117 |
+
# any non-string/text scalar values such as numbers and arrays.
|
| 118 |
+
val = [scalar_validator(v) for v in s
|
| 119 |
+
if not isinstance(v, str) or v]
|
| 120 |
+
else:
|
| 121 |
+
raise ValueError(
|
| 122 |
+
f"Expected str or other non-set iterable, but got {s}")
|
| 123 |
+
if n is not None and len(val) != n:
|
| 124 |
+
raise ValueError(
|
| 125 |
+
f"Expected {n} values, but there are {len(val)} values in {s}")
|
| 126 |
+
return val
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
f.__name__ = f"{scalar_validator.__name__}list"
|
| 130 |
+
except AttributeError: # class instance.
|
| 131 |
+
f.__name__ = f"{type(scalar_validator).__name__}List"
|
| 132 |
+
f.__qualname__ = f.__qualname__.rsplit(".", 1)[0] + "." + f.__name__
|
| 133 |
+
f.__doc__ = doc if doc is not None else scalar_validator.__doc__
|
| 134 |
+
return f
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def validate_any(s):
|
| 138 |
+
return s
|
| 139 |
+
validate_anylist = _listify_validator(validate_any)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _validate_date(s):
|
| 143 |
+
try:
|
| 144 |
+
np.datetime64(s)
|
| 145 |
+
return s
|
| 146 |
+
except ValueError:
|
| 147 |
+
raise ValueError(
|
| 148 |
+
f'{s!r} should be a string that can be parsed by numpy.datetime64')
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def validate_bool(b):
|
| 152 |
+
"""Convert b to ``bool`` or raise."""
|
| 153 |
+
if isinstance(b, str):
|
| 154 |
+
b = b.lower()
|
| 155 |
+
if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
|
| 156 |
+
return True
|
| 157 |
+
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
|
| 158 |
+
return False
|
| 159 |
+
else:
|
| 160 |
+
raise ValueError(f'Cannot convert {b!r} to bool')
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def validate_axisbelow(s):
|
| 164 |
+
try:
|
| 165 |
+
return validate_bool(s)
|
| 166 |
+
except ValueError:
|
| 167 |
+
if isinstance(s, str):
|
| 168 |
+
if s == 'line':
|
| 169 |
+
return 'line'
|
| 170 |
+
raise ValueError(f'{s!r} cannot be interpreted as'
|
| 171 |
+
' True, False, or "line"')
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def validate_dpi(s):
|
| 175 |
+
"""Confirm s is string 'figure' or convert s to float or raise."""
|
| 176 |
+
if s == 'figure':
|
| 177 |
+
return s
|
| 178 |
+
try:
|
| 179 |
+
return float(s)
|
| 180 |
+
except ValueError as e:
|
| 181 |
+
raise ValueError(f'{s!r} is not string "figure" and '
|
| 182 |
+
f'could not convert {s!r} to float') from e
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _make_type_validator(cls, *, allow_none=False):
|
| 186 |
+
"""
|
| 187 |
+
Return a validator that converts inputs to *cls* or raises (and possibly
|
| 188 |
+
allows ``None`` as well).
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
def validator(s):
|
| 192 |
+
if (allow_none and
|
| 193 |
+
(s is None or cbook._str_lower_equal(s, "none"))):
|
| 194 |
+
return None
|
| 195 |
+
if cls is str and not isinstance(s, str):
|
| 196 |
+
raise ValueError(f'Could not convert {s!r} to str')
|
| 197 |
+
try:
|
| 198 |
+
return cls(s)
|
| 199 |
+
except (TypeError, ValueError) as e:
|
| 200 |
+
raise ValueError(
|
| 201 |
+
f'Could not convert {s!r} to {cls.__name__}') from e
|
| 202 |
+
|
| 203 |
+
validator.__name__ = f"validate_{cls.__name__}"
|
| 204 |
+
if allow_none:
|
| 205 |
+
validator.__name__ += "_or_None"
|
| 206 |
+
validator.__qualname__ = (
|
| 207 |
+
validator.__qualname__.rsplit(".", 1)[0] + "." + validator.__name__)
|
| 208 |
+
return validator
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
validate_string = _make_type_validator(str)
|
| 212 |
+
validate_string_or_None = _make_type_validator(str, allow_none=True)
|
| 213 |
+
validate_stringlist = _listify_validator(
|
| 214 |
+
validate_string, doc='return a list of strings')
|
| 215 |
+
validate_int = _make_type_validator(int)
|
| 216 |
+
validate_int_or_None = _make_type_validator(int, allow_none=True)
|
| 217 |
+
validate_float = _make_type_validator(float)
|
| 218 |
+
validate_float_or_None = _make_type_validator(float, allow_none=True)
|
| 219 |
+
validate_floatlist = _listify_validator(
|
| 220 |
+
validate_float, doc='return a list of floats')
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _validate_marker(s):
|
| 224 |
+
try:
|
| 225 |
+
return validate_int(s)
|
| 226 |
+
except ValueError as e:
|
| 227 |
+
try:
|
| 228 |
+
return validate_string(s)
|
| 229 |
+
except ValueError as e:
|
| 230 |
+
raise ValueError('Supported markers are [string, int]') from e
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
_validate_markerlist = _listify_validator(
|
| 234 |
+
_validate_marker, doc='return a list of markers')
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _validate_pathlike(s):
|
| 238 |
+
if isinstance(s, (str, os.PathLike)):
|
| 239 |
+
# Store value as str because savefig.directory needs to distinguish
|
| 240 |
+
# between "" (cwd) and "." (cwd, but gets updated by user selections).
|
| 241 |
+
return os.fsdecode(s)
|
| 242 |
+
else:
|
| 243 |
+
return validate_string(s)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def validate_fonttype(s):
|
| 247 |
+
"""
|
| 248 |
+
Confirm that this is a Postscript or PDF font type that we know how to
|
| 249 |
+
convert to.
|
| 250 |
+
"""
|
| 251 |
+
fonttypes = {'type3': 3,
|
| 252 |
+
'truetype': 42}
|
| 253 |
+
try:
|
| 254 |
+
fonttype = validate_int(s)
|
| 255 |
+
except ValueError:
|
| 256 |
+
try:
|
| 257 |
+
return fonttypes[s.lower()]
|
| 258 |
+
except KeyError as e:
|
| 259 |
+
raise ValueError('Supported Postscript/PDF font types are %s'
|
| 260 |
+
% list(fonttypes)) from e
|
| 261 |
+
else:
|
| 262 |
+
if fonttype not in fonttypes.values():
|
| 263 |
+
raise ValueError(
|
| 264 |
+
'Supported Postscript/PDF font types are %s' %
|
| 265 |
+
list(fonttypes.values()))
|
| 266 |
+
return fonttype
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
_auto_backend_sentinel = object()
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def validate_backend(s):
|
| 273 |
+
if s is _auto_backend_sentinel or backend_registry.is_valid_backend(s):
|
| 274 |
+
return s
|
| 275 |
+
else:
|
| 276 |
+
msg = (f"'{s}' is not a valid value for backend; supported values are "
|
| 277 |
+
f"{backend_registry.list_all()}")
|
| 278 |
+
raise ValueError(msg)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _validate_toolbar(s):
|
| 282 |
+
s = ValidateInStrings(
|
| 283 |
+
'toolbar', ['None', 'toolbar2', 'toolmanager'], ignorecase=True)(s)
|
| 284 |
+
if s == 'toolmanager':
|
| 285 |
+
_api.warn_external(
|
| 286 |
+
"Treat the new Tool classes introduced in v1.5 as experimental "
|
| 287 |
+
"for now; the API and rcParam may change in future versions.")
|
| 288 |
+
return s
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def validate_color_or_inherit(s):
|
| 292 |
+
"""Return a valid color arg."""
|
| 293 |
+
if cbook._str_equal(s, 'inherit'):
|
| 294 |
+
return s
|
| 295 |
+
return validate_color(s)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def validate_color_or_auto(s):
|
| 299 |
+
if cbook._str_equal(s, 'auto'):
|
| 300 |
+
return s
|
| 301 |
+
return validate_color(s)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def validate_color_for_prop_cycle(s):
|
| 305 |
+
# N-th color cycle syntax can't go into the color cycle.
|
| 306 |
+
if isinstance(s, str) and re.match("^C[0-9]$", s):
|
| 307 |
+
raise ValueError(f"Cannot put cycle reference ({s!r}) in prop_cycler")
|
| 308 |
+
return validate_color(s)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _validate_color_or_linecolor(s):
|
| 312 |
+
if cbook._str_equal(s, 'linecolor'):
|
| 313 |
+
return s
|
| 314 |
+
elif cbook._str_equal(s, 'mfc') or cbook._str_equal(s, 'markerfacecolor'):
|
| 315 |
+
return 'markerfacecolor'
|
| 316 |
+
elif cbook._str_equal(s, 'mec') or cbook._str_equal(s, 'markeredgecolor'):
|
| 317 |
+
return 'markeredgecolor'
|
| 318 |
+
elif s is None:
|
| 319 |
+
return None
|
| 320 |
+
elif isinstance(s, str) and len(s) == 6 or len(s) == 8:
|
| 321 |
+
stmp = '#' + s
|
| 322 |
+
if is_color_like(stmp):
|
| 323 |
+
return stmp
|
| 324 |
+
if s.lower() == 'none':
|
| 325 |
+
return None
|
| 326 |
+
elif is_color_like(s):
|
| 327 |
+
return s
|
| 328 |
+
|
| 329 |
+
raise ValueError(f'{s!r} does not look like a color arg')
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def validate_color(s):
|
| 333 |
+
"""Return a valid color arg."""
|
| 334 |
+
if isinstance(s, str):
|
| 335 |
+
if s.lower() == 'none':
|
| 336 |
+
return 'none'
|
| 337 |
+
if len(s) == 6 or len(s) == 8:
|
| 338 |
+
stmp = '#' + s
|
| 339 |
+
if is_color_like(stmp):
|
| 340 |
+
return stmp
|
| 341 |
+
|
| 342 |
+
if is_color_like(s):
|
| 343 |
+
return s
|
| 344 |
+
|
| 345 |
+
# If it is still valid, it must be a tuple (as a string from matplotlibrc).
|
| 346 |
+
try:
|
| 347 |
+
color = ast.literal_eval(s)
|
| 348 |
+
except (SyntaxError, ValueError):
|
| 349 |
+
pass
|
| 350 |
+
else:
|
| 351 |
+
if is_color_like(color):
|
| 352 |
+
return color
|
| 353 |
+
|
| 354 |
+
raise ValueError(f'{s!r} does not look like a color arg')
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
validate_colorlist = _listify_validator(
|
| 358 |
+
validate_color, allow_stringlist=True, doc='return a list of colorspecs')
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _validate_cmap(s):
|
| 362 |
+
_api.check_isinstance((str, Colormap), cmap=s)
|
| 363 |
+
return s
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def validate_aspect(s):
|
| 367 |
+
if s in ('auto', 'equal'):
|
| 368 |
+
return s
|
| 369 |
+
try:
|
| 370 |
+
return float(s)
|
| 371 |
+
except ValueError as e:
|
| 372 |
+
raise ValueError('not a valid aspect specification') from e
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def validate_fontsize_None(s):
|
| 376 |
+
if s is None or s == 'None':
|
| 377 |
+
return None
|
| 378 |
+
else:
|
| 379 |
+
return validate_fontsize(s)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def validate_fontsize(s):
|
| 383 |
+
fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
|
| 384 |
+
'x-large', 'xx-large', 'smaller', 'larger']
|
| 385 |
+
if isinstance(s, str):
|
| 386 |
+
s = s.lower()
|
| 387 |
+
if s in fontsizes:
|
| 388 |
+
return s
|
| 389 |
+
try:
|
| 390 |
+
return float(s)
|
| 391 |
+
except ValueError as e:
|
| 392 |
+
raise ValueError("%s is not a valid font size. Valid font sizes "
|
| 393 |
+
"are %s." % (s, ", ".join(fontsizes))) from e
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
validate_fontsizelist = _listify_validator(validate_fontsize)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def validate_fontweight(s):
|
| 400 |
+
weights = [
|
| 401 |
+
'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman',
|
| 402 |
+
'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black']
|
| 403 |
+
# Note: Historically, weights have been case-sensitive in Matplotlib
|
| 404 |
+
if s in weights:
|
| 405 |
+
return s
|
| 406 |
+
try:
|
| 407 |
+
return int(s)
|
| 408 |
+
except (ValueError, TypeError) as e:
|
| 409 |
+
raise ValueError(f'{s} is not a valid font weight.') from e
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def validate_fontstretch(s):
|
| 413 |
+
stretchvalues = [
|
| 414 |
+
'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed',
|
| 415 |
+
'normal', 'semi-expanded', 'expanded', 'extra-expanded',
|
| 416 |
+
'ultra-expanded']
|
| 417 |
+
# Note: Historically, stretchvalues have been case-sensitive in Matplotlib
|
| 418 |
+
if s in stretchvalues:
|
| 419 |
+
return s
|
| 420 |
+
try:
|
| 421 |
+
return int(s)
|
| 422 |
+
except (ValueError, TypeError) as e:
|
| 423 |
+
raise ValueError(f'{s} is not a valid font stretch.') from e
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def validate_font_properties(s):
|
| 427 |
+
parse_fontconfig_pattern(s)
|
| 428 |
+
return s
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def _validate_mathtext_fallback(s):
|
| 432 |
+
_fallback_fonts = ['cm', 'stix', 'stixsans']
|
| 433 |
+
if isinstance(s, str):
|
| 434 |
+
s = s.lower()
|
| 435 |
+
if s is None or s == 'none':
|
| 436 |
+
return None
|
| 437 |
+
elif s.lower() in _fallback_fonts:
|
| 438 |
+
return s
|
| 439 |
+
else:
|
| 440 |
+
raise ValueError(
|
| 441 |
+
f"{s} is not a valid fallback font name. Valid fallback font "
|
| 442 |
+
f"names are {','.join(_fallback_fonts)}. Passing 'None' will turn "
|
| 443 |
+
"fallback off.")
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def validate_whiskers(s):
|
| 447 |
+
try:
|
| 448 |
+
return _listify_validator(validate_float, n=2)(s)
|
| 449 |
+
except (TypeError, ValueError):
|
| 450 |
+
try:
|
| 451 |
+
return float(s)
|
| 452 |
+
except ValueError as e:
|
| 453 |
+
raise ValueError("Not a valid whisker value [float, "
|
| 454 |
+
"(float, float)]") from e
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def validate_ps_distiller(s):
|
| 458 |
+
if isinstance(s, str):
|
| 459 |
+
s = s.lower()
|
| 460 |
+
if s in ('none', None, 'false', False):
|
| 461 |
+
return None
|
| 462 |
+
else:
|
| 463 |
+
return ValidateInStrings('ps.usedistiller', ['ghostscript', 'xpdf'])(s)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def _validate_papersize(s):
|
| 467 |
+
# Re-inline this validator when the 'auto' deprecation expires.
|
| 468 |
+
s = ValidateInStrings("ps.papersize",
|
| 469 |
+
["figure", "auto", "letter", "legal", "ledger",
|
| 470 |
+
*[f"{ab}{i}" for ab in "ab" for i in range(11)]],
|
| 471 |
+
ignorecase=True)(s)
|
| 472 |
+
if s == "auto":
|
| 473 |
+
_api.warn_deprecated("3.8", name="ps.papersize='auto'",
|
| 474 |
+
addendum="Pass an explicit paper type, figure, or omit "
|
| 475 |
+
"the *ps.papersize* rcParam entirely.")
|
| 476 |
+
return s
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
# A validator dedicated to the named line styles, based on the items in
|
| 480 |
+
# ls_mapper, and a list of possible strings read from Line2D.set_linestyle
|
| 481 |
+
_validate_named_linestyle = ValidateInStrings(
|
| 482 |
+
'linestyle',
|
| 483 |
+
[*ls_mapper.keys(), *ls_mapper.values(), 'None', 'none', ' ', ''],
|
| 484 |
+
ignorecase=True)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _validate_linestyle(ls):
|
| 488 |
+
"""
|
| 489 |
+
A validator for all possible line styles, the named ones *and*
|
| 490 |
+
the on-off ink sequences.
|
| 491 |
+
"""
|
| 492 |
+
if isinstance(ls, str):
|
| 493 |
+
try: # Look first for a valid named line style, like '--' or 'solid'.
|
| 494 |
+
return _validate_named_linestyle(ls)
|
| 495 |
+
except ValueError:
|
| 496 |
+
pass
|
| 497 |
+
try:
|
| 498 |
+
ls = ast.literal_eval(ls) # Parsing matplotlibrc.
|
| 499 |
+
except (SyntaxError, ValueError):
|
| 500 |
+
pass # Will error with the ValueError at the end.
|
| 501 |
+
|
| 502 |
+
def _is_iterable_not_string_like(x):
|
| 503 |
+
# Explicitly exclude bytes/bytearrays so that they are not
|
| 504 |
+
# nonsensically interpreted as sequences of numbers (codepoints).
|
| 505 |
+
return np.iterable(x) and not isinstance(x, (str, bytes, bytearray))
|
| 506 |
+
|
| 507 |
+
if _is_iterable_not_string_like(ls):
|
| 508 |
+
if len(ls) == 2 and _is_iterable_not_string_like(ls[1]):
|
| 509 |
+
# (offset, (on, off, on, off, ...))
|
| 510 |
+
offset, onoff = ls
|
| 511 |
+
else:
|
| 512 |
+
# For backcompat: (on, off, on, off, ...); the offset is implicit.
|
| 513 |
+
offset = 0
|
| 514 |
+
onoff = ls
|
| 515 |
+
|
| 516 |
+
if (isinstance(offset, Real)
|
| 517 |
+
and len(onoff) % 2 == 0
|
| 518 |
+
and all(isinstance(elem, Real) for elem in onoff)):
|
| 519 |
+
return (offset, onoff)
|
| 520 |
+
|
| 521 |
+
raise ValueError(f"linestyle {ls!r} is not a valid on-off ink sequence.")
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
validate_fillstyle = ValidateInStrings(
|
| 525 |
+
'markers.fillstyle', ['full', 'left', 'right', 'bottom', 'top', 'none'])
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
validate_fillstylelist = _listify_validator(validate_fillstyle)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def validate_markevery(s):
|
| 532 |
+
"""
|
| 533 |
+
Validate the markevery property of a Line2D object.
|
| 534 |
+
|
| 535 |
+
Parameters
|
| 536 |
+
----------
|
| 537 |
+
s : None, int, (int, int), slice, float, (float, float), or list[int]
|
| 538 |
+
|
| 539 |
+
Returns
|
| 540 |
+
-------
|
| 541 |
+
None, int, (int, int), slice, float, (float, float), or list[int]
|
| 542 |
+
"""
|
| 543 |
+
# Validate s against type slice float int and None
|
| 544 |
+
if isinstance(s, (slice, float, int, type(None))):
|
| 545 |
+
return s
|
| 546 |
+
# Validate s against type tuple
|
| 547 |
+
if isinstance(s, tuple):
|
| 548 |
+
if (len(s) == 2
|
| 549 |
+
and (all(isinstance(e, int) for e in s)
|
| 550 |
+
or all(isinstance(e, float) for e in s))):
|
| 551 |
+
return s
|
| 552 |
+
else:
|
| 553 |
+
raise TypeError(
|
| 554 |
+
"'markevery' tuple must be pair of ints or of floats")
|
| 555 |
+
# Validate s against type list
|
| 556 |
+
if isinstance(s, list):
|
| 557 |
+
if all(isinstance(e, int) for e in s):
|
| 558 |
+
return s
|
| 559 |
+
else:
|
| 560 |
+
raise TypeError(
|
| 561 |
+
"'markevery' list must have all elements of type int")
|
| 562 |
+
raise TypeError("'markevery' is of an invalid type")
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
validate_markeverylist = _listify_validator(validate_markevery)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def validate_bbox(s):
|
| 569 |
+
if isinstance(s, str):
|
| 570 |
+
s = s.lower()
|
| 571 |
+
if s == 'tight':
|
| 572 |
+
return s
|
| 573 |
+
if s == 'standard':
|
| 574 |
+
return None
|
| 575 |
+
raise ValueError("bbox should be 'tight' or 'standard'")
|
| 576 |
+
elif s is not None:
|
| 577 |
+
# Backwards compatibility. None is equivalent to 'standard'.
|
| 578 |
+
raise ValueError("bbox should be 'tight' or 'standard'")
|
| 579 |
+
return s
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def validate_sketch(s):
|
| 583 |
+
|
| 584 |
+
if isinstance(s, str):
|
| 585 |
+
s = s.lower().strip()
|
| 586 |
+
if s.startswith("(") and s.endswith(")"):
|
| 587 |
+
s = s[1:-1]
|
| 588 |
+
if s == 'none' or s is None:
|
| 589 |
+
return None
|
| 590 |
+
try:
|
| 591 |
+
return tuple(_listify_validator(validate_float, n=3)(s))
|
| 592 |
+
except ValueError as exc:
|
| 593 |
+
raise ValueError("Expected a (scale, length, randomness) tuple") from exc
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def _validate_greaterthan_minushalf(s):
|
| 597 |
+
s = validate_float(s)
|
| 598 |
+
if s > -0.5:
|
| 599 |
+
return s
|
| 600 |
+
else:
|
| 601 |
+
raise RuntimeError(f'Value must be >-0.5; got {s}')
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def _validate_greaterequal0_lessequal1(s):
|
| 605 |
+
s = validate_float(s)
|
| 606 |
+
if 0 <= s <= 1:
|
| 607 |
+
return s
|
| 608 |
+
else:
|
| 609 |
+
raise RuntimeError(f'Value must be >=0 and <=1; got {s}')
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def _validate_int_greaterequal0(s):
|
| 613 |
+
s = validate_int(s)
|
| 614 |
+
if s >= 0:
|
| 615 |
+
return s
|
| 616 |
+
else:
|
| 617 |
+
raise RuntimeError(f'Value must be >=0; got {s}')
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def validate_hatch(s):
|
| 621 |
+
r"""
|
| 622 |
+
Validate a hatch pattern.
|
| 623 |
+
A hatch pattern string can have any sequence of the following
|
| 624 |
+
characters: ``\ / | - + * . x o O``.
|
| 625 |
+
"""
|
| 626 |
+
if not isinstance(s, str):
|
| 627 |
+
raise ValueError("Hatch pattern must be a string")
|
| 628 |
+
_api.check_isinstance(str, hatch_pattern=s)
|
| 629 |
+
unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'}
|
| 630 |
+
if unknown:
|
| 631 |
+
raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))
|
| 632 |
+
return s
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
validate_hatchlist = _listify_validator(validate_hatch)
|
| 636 |
+
validate_dashlist = _listify_validator(validate_floatlist)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def _validate_minor_tick_ndivs(n):
|
| 640 |
+
"""
|
| 641 |
+
Validate ndiv parameter related to the minor ticks.
|
| 642 |
+
It controls the number of minor ticks to be placed between
|
| 643 |
+
two major ticks.
|
| 644 |
+
"""
|
| 645 |
+
|
| 646 |
+
if cbook._str_lower_equal(n, 'auto'):
|
| 647 |
+
return n
|
| 648 |
+
try:
|
| 649 |
+
n = _validate_int_greaterequal0(n)
|
| 650 |
+
return n
|
| 651 |
+
except (RuntimeError, ValueError):
|
| 652 |
+
pass
|
| 653 |
+
|
| 654 |
+
raise ValueError("'tick.minor.ndivs' must be 'auto' or non-negative int")
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
_prop_validators = {
|
| 658 |
+
'color': _listify_validator(validate_color_for_prop_cycle,
|
| 659 |
+
allow_stringlist=True),
|
| 660 |
+
'linewidth': validate_floatlist,
|
| 661 |
+
'linestyle': _listify_validator(_validate_linestyle),
|
| 662 |
+
'facecolor': validate_colorlist,
|
| 663 |
+
'edgecolor': validate_colorlist,
|
| 664 |
+
'joinstyle': _listify_validator(JoinStyle),
|
| 665 |
+
'capstyle': _listify_validator(CapStyle),
|
| 666 |
+
'fillstyle': validate_fillstylelist,
|
| 667 |
+
'markerfacecolor': validate_colorlist,
|
| 668 |
+
'markersize': validate_floatlist,
|
| 669 |
+
'markeredgewidth': validate_floatlist,
|
| 670 |
+
'markeredgecolor': validate_colorlist,
|
| 671 |
+
'markevery': validate_markeverylist,
|
| 672 |
+
'alpha': validate_floatlist,
|
| 673 |
+
'marker': _validate_markerlist,
|
| 674 |
+
'hatch': validate_hatchlist,
|
| 675 |
+
'dashes': validate_dashlist,
|
| 676 |
+
}
|
| 677 |
+
_prop_aliases = {
|
| 678 |
+
'c': 'color',
|
| 679 |
+
'lw': 'linewidth',
|
| 680 |
+
'ls': 'linestyle',
|
| 681 |
+
'fc': 'facecolor',
|
| 682 |
+
'ec': 'edgecolor',
|
| 683 |
+
'mfc': 'markerfacecolor',
|
| 684 |
+
'mec': 'markeredgecolor',
|
| 685 |
+
'mew': 'markeredgewidth',
|
| 686 |
+
'ms': 'markersize',
|
| 687 |
+
}
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def cycler(*args, **kwargs):
|
| 691 |
+
"""
|
| 692 |
+
Create a `~cycler.Cycler` object much like :func:`cycler.cycler`,
|
| 693 |
+
but includes input validation.
|
| 694 |
+
|
| 695 |
+
Call signatures::
|
| 696 |
+
|
| 697 |
+
cycler(cycler)
|
| 698 |
+
cycler(label=values[, label2=values2[, ...]])
|
| 699 |
+
cycler(label, values)
|
| 700 |
+
|
| 701 |
+
Form 1 copies a given `~cycler.Cycler` object.
|
| 702 |
+
|
| 703 |
+
Form 2 creates a `~cycler.Cycler` which cycles over one or more
|
| 704 |
+
properties simultaneously. If multiple properties are given, their
|
| 705 |
+
value lists must have the same length.
|
| 706 |
+
|
| 707 |
+
Form 3 creates a `~cycler.Cycler` for a single property. This form
|
| 708 |
+
exists for compatibility with the original cycler. Its use is
|
| 709 |
+
discouraged in favor of the kwarg form, i.e. ``cycler(label=values)``.
|
| 710 |
+
|
| 711 |
+
Parameters
|
| 712 |
+
----------
|
| 713 |
+
cycler : Cycler
|
| 714 |
+
Copy constructor for Cycler.
|
| 715 |
+
|
| 716 |
+
label : str
|
| 717 |
+
The property key. Must be a valid `.Artist` property.
|
| 718 |
+
For example, 'color' or 'linestyle'. Aliases are allowed,
|
| 719 |
+
such as 'c' for 'color' and 'lw' for 'linewidth'.
|
| 720 |
+
|
| 721 |
+
values : iterable
|
| 722 |
+
Finite-length iterable of the property values. These values
|
| 723 |
+
are validated and will raise a ValueError if invalid.
|
| 724 |
+
|
| 725 |
+
Returns
|
| 726 |
+
-------
|
| 727 |
+
Cycler
|
| 728 |
+
A new :class:`~cycler.Cycler` for the given properties.
|
| 729 |
+
|
| 730 |
+
Examples
|
| 731 |
+
--------
|
| 732 |
+
Creating a cycler for a single property:
|
| 733 |
+
|
| 734 |
+
>>> c = cycler(color=['red', 'green', 'blue'])
|
| 735 |
+
|
| 736 |
+
Creating a cycler for simultaneously cycling over multiple properties
|
| 737 |
+
(e.g. red circle, green plus, blue cross):
|
| 738 |
+
|
| 739 |
+
>>> c = cycler(color=['red', 'green', 'blue'],
|
| 740 |
+
... marker=['o', '+', 'x'])
|
| 741 |
+
|
| 742 |
+
"""
|
| 743 |
+
if args and kwargs:
|
| 744 |
+
raise TypeError("cycler() can only accept positional OR keyword "
|
| 745 |
+
"arguments -- not both.")
|
| 746 |
+
elif not args and not kwargs:
|
| 747 |
+
raise TypeError("cycler() must have positional OR keyword arguments")
|
| 748 |
+
|
| 749 |
+
if len(args) == 1:
|
| 750 |
+
if not isinstance(args[0], Cycler):
|
| 751 |
+
raise TypeError("If only one positional argument given, it must "
|
| 752 |
+
"be a Cycler instance.")
|
| 753 |
+
return validate_cycler(args[0])
|
| 754 |
+
elif len(args) == 2:
|
| 755 |
+
pairs = [(args[0], args[1])]
|
| 756 |
+
elif len(args) > 2:
|
| 757 |
+
raise _api.nargs_error('cycler', '0-2', len(args))
|
| 758 |
+
else:
|
| 759 |
+
pairs = kwargs.items()
|
| 760 |
+
|
| 761 |
+
validated = []
|
| 762 |
+
for prop, vals in pairs:
|
| 763 |
+
norm_prop = _prop_aliases.get(prop, prop)
|
| 764 |
+
validator = _prop_validators.get(norm_prop, None)
|
| 765 |
+
if validator is None:
|
| 766 |
+
raise TypeError("Unknown artist property: %s" % prop)
|
| 767 |
+
vals = validator(vals)
|
| 768 |
+
# We will normalize the property names as well to reduce
|
| 769 |
+
# the amount of alias handling code elsewhere.
|
| 770 |
+
validated.append((norm_prop, vals))
|
| 771 |
+
|
| 772 |
+
return reduce(operator.add, (ccycler(k, v) for k, v in validated))
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
class _DunderChecker(ast.NodeVisitor):
|
| 776 |
+
def visit_Attribute(self, node):
|
| 777 |
+
if node.attr.startswith("__") and node.attr.endswith("__"):
|
| 778 |
+
raise ValueError("cycler strings with dunders are forbidden")
|
| 779 |
+
self.generic_visit(node)
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
# A validator dedicated to the named legend loc
|
| 783 |
+
_validate_named_legend_loc = ValidateInStrings(
|
| 784 |
+
'legend.loc',
|
| 785 |
+
[
|
| 786 |
+
"best",
|
| 787 |
+
"upper right", "upper left", "lower left", "lower right", "right",
|
| 788 |
+
"center left", "center right", "lower center", "upper center",
|
| 789 |
+
"center"],
|
| 790 |
+
ignorecase=True)
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def _validate_legend_loc(loc):
|
| 794 |
+
"""
|
| 795 |
+
Confirm that loc is a type which rc.Params["legend.loc"] supports.
|
| 796 |
+
|
| 797 |
+
.. versionadded:: 3.8
|
| 798 |
+
|
| 799 |
+
Parameters
|
| 800 |
+
----------
|
| 801 |
+
loc : str | int | (float, float) | str((float, float))
|
| 802 |
+
The location of the legend.
|
| 803 |
+
|
| 804 |
+
Returns
|
| 805 |
+
-------
|
| 806 |
+
loc : str | int | (float, float) or raise ValueError exception
|
| 807 |
+
The location of the legend.
|
| 808 |
+
"""
|
| 809 |
+
if isinstance(loc, str):
|
| 810 |
+
try:
|
| 811 |
+
return _validate_named_legend_loc(loc)
|
| 812 |
+
except ValueError:
|
| 813 |
+
pass
|
| 814 |
+
try:
|
| 815 |
+
loc = ast.literal_eval(loc)
|
| 816 |
+
except (SyntaxError, ValueError):
|
| 817 |
+
pass
|
| 818 |
+
if isinstance(loc, int):
|
| 819 |
+
if 0 <= loc <= 10:
|
| 820 |
+
return loc
|
| 821 |
+
if isinstance(loc, tuple):
|
| 822 |
+
if len(loc) == 2 and all(isinstance(e, Real) for e in loc):
|
| 823 |
+
return loc
|
| 824 |
+
raise ValueError(f"{loc} is not a valid legend location.")
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def validate_cycler(s):
|
| 828 |
+
"""Return a Cycler object from a string repr or the object itself."""
|
| 829 |
+
if isinstance(s, str):
|
| 830 |
+
# TODO: We might want to rethink this...
|
| 831 |
+
# While I think I have it quite locked down, it is execution of
|
| 832 |
+
# arbitrary code without sanitation.
|
| 833 |
+
# Combine this with the possibility that rcparams might come from the
|
| 834 |
+
# internet (future plans), this could be downright dangerous.
|
| 835 |
+
# I locked it down by only having the 'cycler()' function available.
|
| 836 |
+
# UPDATE: Partly plugging a security hole.
|
| 837 |
+
# I really should have read this:
|
| 838 |
+
# https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
|
| 839 |
+
# We should replace this eval with a combo of PyParsing and
|
| 840 |
+
# ast.literal_eval()
|
| 841 |
+
try:
|
| 842 |
+
_DunderChecker().visit(ast.parse(s))
|
| 843 |
+
s = eval(s, {'cycler': cycler, '__builtins__': {}})
|
| 844 |
+
except BaseException as e:
|
| 845 |
+
raise ValueError(f"{s!r} is not a valid cycler construction: {e}"
|
| 846 |
+
) from e
|
| 847 |
+
# Should make sure what comes from the above eval()
|
| 848 |
+
# is a Cycler object.
|
| 849 |
+
if isinstance(s, Cycler):
|
| 850 |
+
cycler_inst = s
|
| 851 |
+
else:
|
| 852 |
+
raise ValueError(f"Object is not a string or Cycler instance: {s!r}")
|
| 853 |
+
|
| 854 |
+
unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases))
|
| 855 |
+
if unknowns:
|
| 856 |
+
raise ValueError("Unknown artist properties: %s" % unknowns)
|
| 857 |
+
|
| 858 |
+
# Not a full validation, but it'll at least normalize property names
|
| 859 |
+
# A fuller validation would require v0.10 of cycler.
|
| 860 |
+
checker = set()
|
| 861 |
+
for prop in cycler_inst.keys:
|
| 862 |
+
norm_prop = _prop_aliases.get(prop, prop)
|
| 863 |
+
if norm_prop != prop and norm_prop in cycler_inst.keys:
|
| 864 |
+
raise ValueError(f"Cannot specify both {norm_prop!r} and alias "
|
| 865 |
+
f"{prop!r} in the same prop_cycle")
|
| 866 |
+
if norm_prop in checker:
|
| 867 |
+
raise ValueError(f"Another property was already aliased to "
|
| 868 |
+
f"{norm_prop!r}. Collision normalizing {prop!r}.")
|
| 869 |
+
checker.update([norm_prop])
|
| 870 |
+
|
| 871 |
+
# This is just an extra-careful check, just in case there is some
|
| 872 |
+
# edge-case I haven't thought of.
|
| 873 |
+
assert len(checker) == len(cycler_inst.keys)
|
| 874 |
+
|
| 875 |
+
# Now, it should be safe to mutate this cycler
|
| 876 |
+
for prop in cycler_inst.keys:
|
| 877 |
+
norm_prop = _prop_aliases.get(prop, prop)
|
| 878 |
+
cycler_inst.change_key(prop, norm_prop)
|
| 879 |
+
|
| 880 |
+
for key, vals in cycler_inst.by_key().items():
|
| 881 |
+
_prop_validators[key](vals)
|
| 882 |
+
|
| 883 |
+
return cycler_inst
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
def validate_hist_bins(s):
|
| 887 |
+
valid_strs = ["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"]
|
| 888 |
+
if isinstance(s, str) and s in valid_strs:
|
| 889 |
+
return s
|
| 890 |
+
try:
|
| 891 |
+
return int(s)
|
| 892 |
+
except (TypeError, ValueError):
|
| 893 |
+
pass
|
| 894 |
+
try:
|
| 895 |
+
return validate_floatlist(s)
|
| 896 |
+
except ValueError:
|
| 897 |
+
pass
|
| 898 |
+
raise ValueError(f"'hist.bins' must be one of {valid_strs}, an int or"
|
| 899 |
+
" a sequence of floats")
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
class _ignorecase(list):
|
| 903 |
+
"""A marker class indicating that a list-of-str is case-insensitive."""
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
def _convert_validator_spec(key, conv):
|
| 907 |
+
if isinstance(conv, list):
|
| 908 |
+
ignorecase = isinstance(conv, _ignorecase)
|
| 909 |
+
return ValidateInStrings(key, conv, ignorecase=ignorecase)
|
| 910 |
+
else:
|
| 911 |
+
return conv
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
# Mapping of rcParams to validators.
|
| 915 |
+
# Converters given as lists or _ignorecase are converted to ValidateInStrings
|
| 916 |
+
# immediately below.
|
| 917 |
+
# The rcParams defaults are defined in lib/matplotlib/mpl-data/matplotlibrc, which
|
| 918 |
+
# gets copied to matplotlib/mpl-data/matplotlibrc by the setup script.
|
| 919 |
+
_validators = {
|
| 920 |
+
"backend": validate_backend,
|
| 921 |
+
"backend_fallback": validate_bool,
|
| 922 |
+
"figure.hooks": validate_stringlist,
|
| 923 |
+
"toolbar": _validate_toolbar,
|
| 924 |
+
"interactive": validate_bool,
|
| 925 |
+
"timezone": validate_string,
|
| 926 |
+
|
| 927 |
+
"webagg.port": validate_int,
|
| 928 |
+
"webagg.address": validate_string,
|
| 929 |
+
"webagg.open_in_browser": validate_bool,
|
| 930 |
+
"webagg.port_retries": validate_int,
|
| 931 |
+
|
| 932 |
+
# line props
|
| 933 |
+
"lines.linewidth": validate_float, # line width in points
|
| 934 |
+
"lines.linestyle": _validate_linestyle, # solid line
|
| 935 |
+
"lines.color": validate_color, # first color in color cycle
|
| 936 |
+
"lines.marker": _validate_marker, # marker name
|
| 937 |
+
"lines.markerfacecolor": validate_color_or_auto, # default color
|
| 938 |
+
"lines.markeredgecolor": validate_color_or_auto, # default color
|
| 939 |
+
"lines.markeredgewidth": validate_float,
|
| 940 |
+
"lines.markersize": validate_float, # markersize, in points
|
| 941 |
+
"lines.antialiased": validate_bool, # antialiased (no jaggies)
|
| 942 |
+
"lines.dash_joinstyle": JoinStyle,
|
| 943 |
+
"lines.solid_joinstyle": JoinStyle,
|
| 944 |
+
"lines.dash_capstyle": CapStyle,
|
| 945 |
+
"lines.solid_capstyle": CapStyle,
|
| 946 |
+
"lines.dashed_pattern": validate_floatlist,
|
| 947 |
+
"lines.dashdot_pattern": validate_floatlist,
|
| 948 |
+
"lines.dotted_pattern": validate_floatlist,
|
| 949 |
+
"lines.scale_dashes": validate_bool,
|
| 950 |
+
|
| 951 |
+
# marker props
|
| 952 |
+
"markers.fillstyle": validate_fillstyle,
|
| 953 |
+
|
| 954 |
+
## pcolor(mesh) props:
|
| 955 |
+
"pcolor.shading": ["auto", "flat", "nearest", "gouraud"],
|
| 956 |
+
"pcolormesh.snap": validate_bool,
|
| 957 |
+
|
| 958 |
+
## patch props
|
| 959 |
+
"patch.linewidth": validate_float, # line width in points
|
| 960 |
+
"patch.edgecolor": validate_color,
|
| 961 |
+
"patch.force_edgecolor": validate_bool,
|
| 962 |
+
"patch.facecolor": validate_color, # first color in cycle
|
| 963 |
+
"patch.antialiased": validate_bool, # antialiased (no jaggies)
|
| 964 |
+
|
| 965 |
+
## hatch props
|
| 966 |
+
"hatch.color": validate_color,
|
| 967 |
+
"hatch.linewidth": validate_float,
|
| 968 |
+
|
| 969 |
+
## Histogram properties
|
| 970 |
+
"hist.bins": validate_hist_bins,
|
| 971 |
+
|
| 972 |
+
## Boxplot properties
|
| 973 |
+
"boxplot.notch": validate_bool,
|
| 974 |
+
"boxplot.vertical": validate_bool,
|
| 975 |
+
"boxplot.whiskers": validate_whiskers,
|
| 976 |
+
"boxplot.bootstrap": validate_int_or_None,
|
| 977 |
+
"boxplot.patchartist": validate_bool,
|
| 978 |
+
"boxplot.showmeans": validate_bool,
|
| 979 |
+
"boxplot.showcaps": validate_bool,
|
| 980 |
+
"boxplot.showbox": validate_bool,
|
| 981 |
+
"boxplot.showfliers": validate_bool,
|
| 982 |
+
"boxplot.meanline": validate_bool,
|
| 983 |
+
|
| 984 |
+
"boxplot.flierprops.color": validate_color,
|
| 985 |
+
"boxplot.flierprops.marker": _validate_marker,
|
| 986 |
+
"boxplot.flierprops.markerfacecolor": validate_color_or_auto,
|
| 987 |
+
"boxplot.flierprops.markeredgecolor": validate_color,
|
| 988 |
+
"boxplot.flierprops.markeredgewidth": validate_float,
|
| 989 |
+
"boxplot.flierprops.markersize": validate_float,
|
| 990 |
+
"boxplot.flierprops.linestyle": _validate_linestyle,
|
| 991 |
+
"boxplot.flierprops.linewidth": validate_float,
|
| 992 |
+
|
| 993 |
+
"boxplot.boxprops.color": validate_color,
|
| 994 |
+
"boxplot.boxprops.linewidth": validate_float,
|
| 995 |
+
"boxplot.boxprops.linestyle": _validate_linestyle,
|
| 996 |
+
|
| 997 |
+
"boxplot.whiskerprops.color": validate_color,
|
| 998 |
+
"boxplot.whiskerprops.linewidth": validate_float,
|
| 999 |
+
"boxplot.whiskerprops.linestyle": _validate_linestyle,
|
| 1000 |
+
|
| 1001 |
+
"boxplot.capprops.color": validate_color,
|
| 1002 |
+
"boxplot.capprops.linewidth": validate_float,
|
| 1003 |
+
"boxplot.capprops.linestyle": _validate_linestyle,
|
| 1004 |
+
|
| 1005 |
+
"boxplot.medianprops.color": validate_color,
|
| 1006 |
+
"boxplot.medianprops.linewidth": validate_float,
|
| 1007 |
+
"boxplot.medianprops.linestyle": _validate_linestyle,
|
| 1008 |
+
|
| 1009 |
+
"boxplot.meanprops.color": validate_color,
|
| 1010 |
+
"boxplot.meanprops.marker": _validate_marker,
|
| 1011 |
+
"boxplot.meanprops.markerfacecolor": validate_color,
|
| 1012 |
+
"boxplot.meanprops.markeredgecolor": validate_color,
|
| 1013 |
+
"boxplot.meanprops.markersize": validate_float,
|
| 1014 |
+
"boxplot.meanprops.linestyle": _validate_linestyle,
|
| 1015 |
+
"boxplot.meanprops.linewidth": validate_float,
|
| 1016 |
+
|
| 1017 |
+
## font props
|
| 1018 |
+
"font.family": validate_stringlist, # used by text object
|
| 1019 |
+
"font.style": validate_string,
|
| 1020 |
+
"font.variant": validate_string,
|
| 1021 |
+
"font.stretch": validate_fontstretch,
|
| 1022 |
+
"font.weight": validate_fontweight,
|
| 1023 |
+
"font.size": validate_float, # Base font size in points
|
| 1024 |
+
"font.serif": validate_stringlist,
|
| 1025 |
+
"font.sans-serif": validate_stringlist,
|
| 1026 |
+
"font.cursive": validate_stringlist,
|
| 1027 |
+
"font.fantasy": validate_stringlist,
|
| 1028 |
+
"font.monospace": validate_stringlist,
|
| 1029 |
+
|
| 1030 |
+
# text props
|
| 1031 |
+
"text.color": validate_color,
|
| 1032 |
+
"text.usetex": validate_bool,
|
| 1033 |
+
"text.latex.preamble": validate_string,
|
| 1034 |
+
"text.hinting": ["default", "no_autohint", "force_autohint",
|
| 1035 |
+
"no_hinting", "auto", "native", "either", "none"],
|
| 1036 |
+
"text.hinting_factor": validate_int,
|
| 1037 |
+
"text.kerning_factor": validate_int,
|
| 1038 |
+
"text.antialiased": validate_bool,
|
| 1039 |
+
"text.parse_math": validate_bool,
|
| 1040 |
+
|
| 1041 |
+
"mathtext.cal": validate_font_properties,
|
| 1042 |
+
"mathtext.rm": validate_font_properties,
|
| 1043 |
+
"mathtext.tt": validate_font_properties,
|
| 1044 |
+
"mathtext.it": validate_font_properties,
|
| 1045 |
+
"mathtext.bf": validate_font_properties,
|
| 1046 |
+
"mathtext.bfit": validate_font_properties,
|
| 1047 |
+
"mathtext.sf": validate_font_properties,
|
| 1048 |
+
"mathtext.fontset": ["dejavusans", "dejavuserif", "cm", "stix",
|
| 1049 |
+
"stixsans", "custom"],
|
| 1050 |
+
"mathtext.default": ["rm", "cal", "bfit", "it", "tt", "sf", "bf", "default",
|
| 1051 |
+
"bb", "frak", "scr", "regular"],
|
| 1052 |
+
"mathtext.fallback": _validate_mathtext_fallback,
|
| 1053 |
+
|
| 1054 |
+
"image.aspect": validate_aspect, # equal, auto, a number
|
| 1055 |
+
"image.interpolation": validate_string,
|
| 1056 |
+
"image.interpolation_stage": ["data", "rgba"],
|
| 1057 |
+
"image.cmap": _validate_cmap, # gray, jet, etc.
|
| 1058 |
+
"image.lut": validate_int, # lookup table
|
| 1059 |
+
"image.origin": ["upper", "lower"],
|
| 1060 |
+
"image.resample": validate_bool,
|
| 1061 |
+
# Specify whether vector graphics backends will combine all images on a
|
| 1062 |
+
# set of Axes into a single composite image
|
| 1063 |
+
"image.composite_image": validate_bool,
|
| 1064 |
+
|
| 1065 |
+
# contour props
|
| 1066 |
+
"contour.negative_linestyle": _validate_linestyle,
|
| 1067 |
+
"contour.corner_mask": validate_bool,
|
| 1068 |
+
"contour.linewidth": validate_float_or_None,
|
| 1069 |
+
"contour.algorithm": ["mpl2005", "mpl2014", "serial", "threaded"],
|
| 1070 |
+
|
| 1071 |
+
# errorbar props
|
| 1072 |
+
"errorbar.capsize": validate_float,
|
| 1073 |
+
|
| 1074 |
+
# axis props
|
| 1075 |
+
# alignment of x/y axis title
|
| 1076 |
+
"xaxis.labellocation": ["left", "center", "right"],
|
| 1077 |
+
"yaxis.labellocation": ["bottom", "center", "top"],
|
| 1078 |
+
|
| 1079 |
+
# Axes props
|
| 1080 |
+
"axes.axisbelow": validate_axisbelow,
|
| 1081 |
+
"axes.facecolor": validate_color, # background color
|
| 1082 |
+
"axes.edgecolor": validate_color, # edge color
|
| 1083 |
+
"axes.linewidth": validate_float, # edge linewidth
|
| 1084 |
+
|
| 1085 |
+
"axes.spines.left": validate_bool, # Set visibility of axes spines,
|
| 1086 |
+
"axes.spines.right": validate_bool, # i.e., the lines around the chart
|
| 1087 |
+
"axes.spines.bottom": validate_bool, # denoting data boundary.
|
| 1088 |
+
"axes.spines.top": validate_bool,
|
| 1089 |
+
|
| 1090 |
+
"axes.titlesize": validate_fontsize, # Axes title fontsize
|
| 1091 |
+
"axes.titlelocation": ["left", "center", "right"], # Axes title alignment
|
| 1092 |
+
"axes.titleweight": validate_fontweight, # Axes title font weight
|
| 1093 |
+
"axes.titlecolor": validate_color_or_auto, # Axes title font color
|
| 1094 |
+
# title location, axes units, None means auto
|
| 1095 |
+
"axes.titley": validate_float_or_None,
|
| 1096 |
+
# pad from Axes top decoration to title in points
|
| 1097 |
+
"axes.titlepad": validate_float,
|
| 1098 |
+
"axes.grid": validate_bool, # display grid or not
|
| 1099 |
+
"axes.grid.which": ["minor", "both", "major"], # which grids are drawn
|
| 1100 |
+
"axes.grid.axis": ["x", "y", "both"], # grid type
|
| 1101 |
+
"axes.labelsize": validate_fontsize, # fontsize of x & y labels
|
| 1102 |
+
"axes.labelpad": validate_float, # space between label and axis
|
| 1103 |
+
"axes.labelweight": validate_fontweight, # fontsize of x & y labels
|
| 1104 |
+
"axes.labelcolor": validate_color, # color of axis label
|
| 1105 |
+
# use scientific notation if log10 of the axis range is smaller than the
|
| 1106 |
+
# first or larger than the second
|
| 1107 |
+
"axes.formatter.limits": _listify_validator(validate_int, n=2),
|
| 1108 |
+
# use current locale to format ticks
|
| 1109 |
+
"axes.formatter.use_locale": validate_bool,
|
| 1110 |
+
"axes.formatter.use_mathtext": validate_bool,
|
| 1111 |
+
# minimum exponent to format in scientific notation
|
| 1112 |
+
"axes.formatter.min_exponent": validate_int,
|
| 1113 |
+
"axes.formatter.useoffset": validate_bool,
|
| 1114 |
+
"axes.formatter.offset_threshold": validate_int,
|
| 1115 |
+
"axes.unicode_minus": validate_bool,
|
| 1116 |
+
# This entry can be either a cycler object or a string repr of a
|
| 1117 |
+
# cycler-object, which gets eval()'ed to create the object.
|
| 1118 |
+
"axes.prop_cycle": validate_cycler,
|
| 1119 |
+
# If "data", axes limits are set close to the data.
|
| 1120 |
+
# If "round_numbers" axes limits are set to the nearest round numbers.
|
| 1121 |
+
"axes.autolimit_mode": ["data", "round_numbers"],
|
| 1122 |
+
"axes.xmargin": _validate_greaterthan_minushalf, # margin added to xaxis
|
| 1123 |
+
"axes.ymargin": _validate_greaterthan_minushalf, # margin added to yaxis
|
| 1124 |
+
"axes.zmargin": _validate_greaterthan_minushalf, # margin added to zaxis
|
| 1125 |
+
|
| 1126 |
+
"polaraxes.grid": validate_bool, # display polar grid or not
|
| 1127 |
+
"axes3d.grid": validate_bool, # display 3d grid
|
| 1128 |
+
"axes3d.automargin": validate_bool, # automatically add margin when
|
| 1129 |
+
# manually setting 3D axis limits
|
| 1130 |
+
|
| 1131 |
+
"axes3d.xaxis.panecolor": validate_color, # 3d background pane
|
| 1132 |
+
"axes3d.yaxis.panecolor": validate_color, # 3d background pane
|
| 1133 |
+
"axes3d.zaxis.panecolor": validate_color, # 3d background pane
|
| 1134 |
+
|
| 1135 |
+
# scatter props
|
| 1136 |
+
"scatter.marker": _validate_marker,
|
| 1137 |
+
"scatter.edgecolors": validate_string,
|
| 1138 |
+
|
| 1139 |
+
"date.epoch": _validate_date,
|
| 1140 |
+
"date.autoformatter.year": validate_string,
|
| 1141 |
+
"date.autoformatter.month": validate_string,
|
| 1142 |
+
"date.autoformatter.day": validate_string,
|
| 1143 |
+
"date.autoformatter.hour": validate_string,
|
| 1144 |
+
"date.autoformatter.minute": validate_string,
|
| 1145 |
+
"date.autoformatter.second": validate_string,
|
| 1146 |
+
"date.autoformatter.microsecond": validate_string,
|
| 1147 |
+
|
| 1148 |
+
'date.converter': ['auto', 'concise'],
|
| 1149 |
+
# for auto date locator, choose interval_multiples
|
| 1150 |
+
'date.interval_multiples': validate_bool,
|
| 1151 |
+
|
| 1152 |
+
# legend properties
|
| 1153 |
+
"legend.fancybox": validate_bool,
|
| 1154 |
+
"legend.loc": _validate_legend_loc,
|
| 1155 |
+
|
| 1156 |
+
# the number of points in the legend line
|
| 1157 |
+
"legend.numpoints": validate_int,
|
| 1158 |
+
# the number of points in the legend line for scatter
|
| 1159 |
+
"legend.scatterpoints": validate_int,
|
| 1160 |
+
"legend.fontsize": validate_fontsize,
|
| 1161 |
+
"legend.title_fontsize": validate_fontsize_None,
|
| 1162 |
+
# color of the legend
|
| 1163 |
+
"legend.labelcolor": _validate_color_or_linecolor,
|
| 1164 |
+
# the relative size of legend markers vs. original
|
| 1165 |
+
"legend.markerscale": validate_float,
|
| 1166 |
+
# using dict in rcParams not yet supported, so make sure it is bool
|
| 1167 |
+
"legend.shadow": validate_bool,
|
| 1168 |
+
# whether or not to draw a frame around legend
|
| 1169 |
+
"legend.frameon": validate_bool,
|
| 1170 |
+
# alpha value of the legend frame
|
| 1171 |
+
"legend.framealpha": validate_float_or_None,
|
| 1172 |
+
|
| 1173 |
+
## the following dimensions are in fraction of the font size
|
| 1174 |
+
"legend.borderpad": validate_float, # units are fontsize
|
| 1175 |
+
# the vertical space between the legend entries
|
| 1176 |
+
"legend.labelspacing": validate_float,
|
| 1177 |
+
# the length of the legend lines
|
| 1178 |
+
"legend.handlelength": validate_float,
|
| 1179 |
+
# the length of the legend lines
|
| 1180 |
+
"legend.handleheight": validate_float,
|
| 1181 |
+
# the space between the legend line and legend text
|
| 1182 |
+
"legend.handletextpad": validate_float,
|
| 1183 |
+
# the border between the Axes and legend edge
|
| 1184 |
+
"legend.borderaxespad": validate_float,
|
| 1185 |
+
# the border between the Axes and legend edge
|
| 1186 |
+
"legend.columnspacing": validate_float,
|
| 1187 |
+
"legend.facecolor": validate_color_or_inherit,
|
| 1188 |
+
"legend.edgecolor": validate_color_or_inherit,
|
| 1189 |
+
|
| 1190 |
+
# tick properties
|
| 1191 |
+
"xtick.top": validate_bool, # draw ticks on top side
|
| 1192 |
+
"xtick.bottom": validate_bool, # draw ticks on bottom side
|
| 1193 |
+
"xtick.labeltop": validate_bool, # draw label on top
|
| 1194 |
+
"xtick.labelbottom": validate_bool, # draw label on bottom
|
| 1195 |
+
"xtick.major.size": validate_float, # major xtick size in points
|
| 1196 |
+
"xtick.minor.size": validate_float, # minor xtick size in points
|
| 1197 |
+
"xtick.major.width": validate_float, # major xtick width in points
|
| 1198 |
+
"xtick.minor.width": validate_float, # minor xtick width in points
|
| 1199 |
+
"xtick.major.pad": validate_float, # distance to label in points
|
| 1200 |
+
"xtick.minor.pad": validate_float, # distance to label in points
|
| 1201 |
+
"xtick.color": validate_color, # color of xticks
|
| 1202 |
+
"xtick.labelcolor": validate_color_or_inherit, # color of xtick labels
|
| 1203 |
+
"xtick.minor.visible": validate_bool, # visibility of minor xticks
|
| 1204 |
+
"xtick.minor.top": validate_bool, # draw top minor xticks
|
| 1205 |
+
"xtick.minor.bottom": validate_bool, # draw bottom minor xticks
|
| 1206 |
+
"xtick.major.top": validate_bool, # draw top major xticks
|
| 1207 |
+
"xtick.major.bottom": validate_bool, # draw bottom major xticks
|
| 1208 |
+
# number of minor xticks
|
| 1209 |
+
"xtick.minor.ndivs": _validate_minor_tick_ndivs,
|
| 1210 |
+
"xtick.labelsize": validate_fontsize, # fontsize of xtick labels
|
| 1211 |
+
"xtick.direction": ["out", "in", "inout"], # direction of xticks
|
| 1212 |
+
"xtick.alignment": ["center", "right", "left"],
|
| 1213 |
+
|
| 1214 |
+
"ytick.left": validate_bool, # draw ticks on left side
|
| 1215 |
+
"ytick.right": validate_bool, # draw ticks on right side
|
| 1216 |
+
"ytick.labelleft": validate_bool, # draw tick labels on left side
|
| 1217 |
+
"ytick.labelright": validate_bool, # draw tick labels on right side
|
| 1218 |
+
"ytick.major.size": validate_float, # major ytick size in points
|
| 1219 |
+
"ytick.minor.size": validate_float, # minor ytick size in points
|
| 1220 |
+
"ytick.major.width": validate_float, # major ytick width in points
|
| 1221 |
+
"ytick.minor.width": validate_float, # minor ytick width in points
|
| 1222 |
+
"ytick.major.pad": validate_float, # distance to label in points
|
| 1223 |
+
"ytick.minor.pad": validate_float, # distance to label in points
|
| 1224 |
+
"ytick.color": validate_color, # color of yticks
|
| 1225 |
+
"ytick.labelcolor": validate_color_or_inherit, # color of ytick labels
|
| 1226 |
+
"ytick.minor.visible": validate_bool, # visibility of minor yticks
|
| 1227 |
+
"ytick.minor.left": validate_bool, # draw left minor yticks
|
| 1228 |
+
"ytick.minor.right": validate_bool, # draw right minor yticks
|
| 1229 |
+
"ytick.major.left": validate_bool, # draw left major yticks
|
| 1230 |
+
"ytick.major.right": validate_bool, # draw right major yticks
|
| 1231 |
+
# number of minor yticks
|
| 1232 |
+
"ytick.minor.ndivs": _validate_minor_tick_ndivs,
|
| 1233 |
+
"ytick.labelsize": validate_fontsize, # fontsize of ytick labels
|
| 1234 |
+
"ytick.direction": ["out", "in", "inout"], # direction of yticks
|
| 1235 |
+
"ytick.alignment": [
|
| 1236 |
+
"center", "top", "bottom", "baseline", "center_baseline"],
|
| 1237 |
+
|
| 1238 |
+
"grid.color": validate_color, # grid color
|
| 1239 |
+
"grid.linestyle": _validate_linestyle, # solid
|
| 1240 |
+
"grid.linewidth": validate_float, # in points
|
| 1241 |
+
"grid.alpha": validate_float,
|
| 1242 |
+
|
| 1243 |
+
## figure props
|
| 1244 |
+
# figure title
|
| 1245 |
+
"figure.titlesize": validate_fontsize,
|
| 1246 |
+
"figure.titleweight": validate_fontweight,
|
| 1247 |
+
|
| 1248 |
+
# figure labels
|
| 1249 |
+
"figure.labelsize": validate_fontsize,
|
| 1250 |
+
"figure.labelweight": validate_fontweight,
|
| 1251 |
+
|
| 1252 |
+
# figure size in inches: width by height
|
| 1253 |
+
"figure.figsize": _listify_validator(validate_float, n=2),
|
| 1254 |
+
"figure.dpi": validate_float,
|
| 1255 |
+
"figure.facecolor": validate_color,
|
| 1256 |
+
"figure.edgecolor": validate_color,
|
| 1257 |
+
"figure.frameon": validate_bool,
|
| 1258 |
+
"figure.autolayout": validate_bool,
|
| 1259 |
+
"figure.max_open_warning": validate_int,
|
| 1260 |
+
"figure.raise_window": validate_bool,
|
| 1261 |
+
"macosx.window_mode": ["system", "tab", "window"],
|
| 1262 |
+
|
| 1263 |
+
"figure.subplot.left": validate_float,
|
| 1264 |
+
"figure.subplot.right": validate_float,
|
| 1265 |
+
"figure.subplot.bottom": validate_float,
|
| 1266 |
+
"figure.subplot.top": validate_float,
|
| 1267 |
+
"figure.subplot.wspace": validate_float,
|
| 1268 |
+
"figure.subplot.hspace": validate_float,
|
| 1269 |
+
|
| 1270 |
+
"figure.constrained_layout.use": validate_bool, # run constrained_layout?
|
| 1271 |
+
# wspace and hspace are fraction of adjacent subplots to use for space.
|
| 1272 |
+
# Much smaller than above because we don't need room for the text.
|
| 1273 |
+
"figure.constrained_layout.hspace": validate_float,
|
| 1274 |
+
"figure.constrained_layout.wspace": validate_float,
|
| 1275 |
+
# buffer around the Axes, in inches.
|
| 1276 |
+
"figure.constrained_layout.h_pad": validate_float,
|
| 1277 |
+
"figure.constrained_layout.w_pad": validate_float,
|
| 1278 |
+
|
| 1279 |
+
## Saving figure's properties
|
| 1280 |
+
'savefig.dpi': validate_dpi,
|
| 1281 |
+
'savefig.facecolor': validate_color_or_auto,
|
| 1282 |
+
'savefig.edgecolor': validate_color_or_auto,
|
| 1283 |
+
'savefig.orientation': ['landscape', 'portrait'],
|
| 1284 |
+
"savefig.format": validate_string,
|
| 1285 |
+
"savefig.bbox": validate_bbox, # "tight", or "standard" (= None)
|
| 1286 |
+
"savefig.pad_inches": validate_float,
|
| 1287 |
+
# default directory in savefig dialog box
|
| 1288 |
+
"savefig.directory": _validate_pathlike,
|
| 1289 |
+
"savefig.transparent": validate_bool,
|
| 1290 |
+
|
| 1291 |
+
"tk.window_focus": validate_bool, # Maintain shell focus for TkAgg
|
| 1292 |
+
|
| 1293 |
+
# Set the papersize/type
|
| 1294 |
+
"ps.papersize": _validate_papersize,
|
| 1295 |
+
"ps.useafm": validate_bool,
|
| 1296 |
+
# use ghostscript or xpdf to distill ps output
|
| 1297 |
+
"ps.usedistiller": validate_ps_distiller,
|
| 1298 |
+
"ps.distiller.res": validate_int, # dpi
|
| 1299 |
+
"ps.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
|
| 1300 |
+
"pdf.compression": validate_int, # 0-9 compression level; 0 to disable
|
| 1301 |
+
"pdf.inheritcolor": validate_bool, # skip color setting commands
|
| 1302 |
+
# use only the 14 PDF core fonts embedded in every PDF viewing application
|
| 1303 |
+
"pdf.use14corefonts": validate_bool,
|
| 1304 |
+
"pdf.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
|
| 1305 |
+
|
| 1306 |
+
"pgf.texsystem": ["xelatex", "lualatex", "pdflatex"], # latex variant used
|
| 1307 |
+
"pgf.rcfonts": validate_bool, # use mpl's rc settings for font config
|
| 1308 |
+
"pgf.preamble": validate_string, # custom LaTeX preamble
|
| 1309 |
+
|
| 1310 |
+
# write raster image data into the svg file
|
| 1311 |
+
"svg.image_inline": validate_bool,
|
| 1312 |
+
"svg.fonttype": ["none", "path"], # save text as text ("none") or "paths"
|
| 1313 |
+
"svg.hashsalt": validate_string_or_None,
|
| 1314 |
+
|
| 1315 |
+
# set this when you want to generate hardcopy docstring
|
| 1316 |
+
"docstring.hardcopy": validate_bool,
|
| 1317 |
+
|
| 1318 |
+
"path.simplify": validate_bool,
|
| 1319 |
+
"path.simplify_threshold": _validate_greaterequal0_lessequal1,
|
| 1320 |
+
"path.snap": validate_bool,
|
| 1321 |
+
"path.sketch": validate_sketch,
|
| 1322 |
+
"path.effects": validate_anylist,
|
| 1323 |
+
"agg.path.chunksize": validate_int, # 0 to disable chunking
|
| 1324 |
+
|
| 1325 |
+
# key-mappings (multi-character mappings should be a list/tuple)
|
| 1326 |
+
"keymap.fullscreen": validate_stringlist,
|
| 1327 |
+
"keymap.home": validate_stringlist,
|
| 1328 |
+
"keymap.back": validate_stringlist,
|
| 1329 |
+
"keymap.forward": validate_stringlist,
|
| 1330 |
+
"keymap.pan": validate_stringlist,
|
| 1331 |
+
"keymap.zoom": validate_stringlist,
|
| 1332 |
+
"keymap.save": validate_stringlist,
|
| 1333 |
+
"keymap.quit": validate_stringlist,
|
| 1334 |
+
"keymap.quit_all": validate_stringlist, # e.g.: "W", "cmd+W", "Q"
|
| 1335 |
+
"keymap.grid": validate_stringlist,
|
| 1336 |
+
"keymap.grid_minor": validate_stringlist,
|
| 1337 |
+
"keymap.yscale": validate_stringlist,
|
| 1338 |
+
"keymap.xscale": validate_stringlist,
|
| 1339 |
+
"keymap.help": validate_stringlist,
|
| 1340 |
+
"keymap.copy": validate_stringlist,
|
| 1341 |
+
|
| 1342 |
+
# Animation settings
|
| 1343 |
+
"animation.html": ["html5", "jshtml", "none"],
|
| 1344 |
+
# Limit, in MB, of size of base64 encoded animation in HTML
|
| 1345 |
+
# (i.e. IPython notebook)
|
| 1346 |
+
"animation.embed_limit": validate_float,
|
| 1347 |
+
"animation.writer": validate_string,
|
| 1348 |
+
"animation.codec": validate_string,
|
| 1349 |
+
"animation.bitrate": validate_int,
|
| 1350 |
+
# Controls image format when frames are written to disk
|
| 1351 |
+
"animation.frame_format": ["png", "jpeg", "tiff", "raw", "rgba", "ppm",
|
| 1352 |
+
"sgi", "bmp", "pbm", "svg"],
|
| 1353 |
+
# Path to ffmpeg binary. If just binary name, subprocess uses $PATH.
|
| 1354 |
+
"animation.ffmpeg_path": _validate_pathlike,
|
| 1355 |
+
# Additional arguments for ffmpeg movie writer (using pipes)
|
| 1356 |
+
"animation.ffmpeg_args": validate_stringlist,
|
| 1357 |
+
# Path to convert binary. If just binary name, subprocess uses $PATH.
|
| 1358 |
+
"animation.convert_path": _validate_pathlike,
|
| 1359 |
+
# Additional arguments for convert movie writer (using pipes)
|
| 1360 |
+
"animation.convert_args": validate_stringlist,
|
| 1361 |
+
|
| 1362 |
+
# Classic (pre 2.0) compatibility mode
|
| 1363 |
+
# This is used for things that are hard to make backward compatible
|
| 1364 |
+
# with a sane rcParam alone. This does *not* turn on classic mode
|
| 1365 |
+
# altogether. For that use `matplotlib.style.use("classic")`.
|
| 1366 |
+
"_internal.classic_mode": validate_bool
|
| 1367 |
+
}
|
| 1368 |
+
_hardcoded_defaults = { # Defaults not inferred from
|
| 1369 |
+
# lib/matplotlib/mpl-data/matplotlibrc...
|
| 1370 |
+
# ... because they are private:
|
| 1371 |
+
"_internal.classic_mode": False,
|
| 1372 |
+
# ... because they are deprecated:
|
| 1373 |
+
# No current deprecations.
|
| 1374 |
+
# backend is handled separately when constructing rcParamsDefault.
|
| 1375 |
+
}
|
| 1376 |
+
_validators = {k: _convert_validator_spec(k, conv)
|
| 1377 |
+
for k, conv in _validators.items()}
|
parrot/lib/python3.10/site-packages/matplotlib/sankey.py
ADDED
|
@@ -0,0 +1,814 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module for creating Sankey diagrams using Matplotlib.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
from types import SimpleNamespace
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
import matplotlib as mpl
|
| 11 |
+
from matplotlib.path import Path
|
| 12 |
+
from matplotlib.patches import PathPatch
|
| 13 |
+
from matplotlib.transforms import Affine2D
|
| 14 |
+
from matplotlib import _docstring
|
| 15 |
+
|
| 16 |
+
_log = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
__author__ = "Kevin L. Davies"
|
| 19 |
+
__credits__ = ["Yannick Copin"]
|
| 20 |
+
__license__ = "BSD"
|
| 21 |
+
__version__ = "2011/09/16"
|
| 22 |
+
|
| 23 |
+
# Angles [deg/90]
|
| 24 |
+
RIGHT = 0
|
| 25 |
+
UP = 1
|
| 26 |
+
# LEFT = 2
|
| 27 |
+
DOWN = 3
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Sankey:
|
| 31 |
+
"""
|
| 32 |
+
Sankey diagram.
|
| 33 |
+
|
| 34 |
+
Sankey diagrams are a specific type of flow diagram, in which
|
| 35 |
+
the width of the arrows is shown proportionally to the flow
|
| 36 |
+
quantity. They are typically used to visualize energy or
|
| 37 |
+
material or cost transfers between processes.
|
| 38 |
+
`Wikipedia (6/1/2011) <https://en.wikipedia.org/wiki/Sankey_diagram>`_
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25,
|
| 43 |
+
radius=0.1, shoulder=0.03, offset=0.15, head_angle=100,
|
| 44 |
+
margin=0.4, tolerance=1e-6, **kwargs):
|
| 45 |
+
"""
|
| 46 |
+
Create a new Sankey instance.
|
| 47 |
+
|
| 48 |
+
The optional arguments listed below are applied to all subdiagrams so
|
| 49 |
+
that there is consistent alignment and formatting.
|
| 50 |
+
|
| 51 |
+
In order to draw a complex Sankey diagram, create an instance of
|
| 52 |
+
`Sankey` by calling it without any kwargs::
|
| 53 |
+
|
| 54 |
+
sankey = Sankey()
|
| 55 |
+
|
| 56 |
+
Then add simple Sankey sub-diagrams::
|
| 57 |
+
|
| 58 |
+
sankey.add() # 1
|
| 59 |
+
sankey.add() # 2
|
| 60 |
+
#...
|
| 61 |
+
sankey.add() # n
|
| 62 |
+
|
| 63 |
+
Finally, create the full diagram::
|
| 64 |
+
|
| 65 |
+
sankey.finish()
|
| 66 |
+
|
| 67 |
+
Or, instead, simply daisy-chain those calls::
|
| 68 |
+
|
| 69 |
+
Sankey().add().add... .add().finish()
|
| 70 |
+
|
| 71 |
+
Other Parameters
|
| 72 |
+
----------------
|
| 73 |
+
ax : `~matplotlib.axes.Axes`
|
| 74 |
+
Axes onto which the data should be plotted. If *ax* isn't
|
| 75 |
+
provided, new Axes will be created.
|
| 76 |
+
scale : float
|
| 77 |
+
Scaling factor for the flows. *scale* sizes the width of the paths
|
| 78 |
+
in order to maintain proper layout. The same scale is applied to
|
| 79 |
+
all subdiagrams. The value should be chosen such that the product
|
| 80 |
+
of the scale and the sum of the inputs is approximately 1.0 (and
|
| 81 |
+
the product of the scale and the sum of the outputs is
|
| 82 |
+
approximately -1.0).
|
| 83 |
+
unit : str
|
| 84 |
+
The physical unit associated with the flow quantities. If *unit*
|
| 85 |
+
is None, then none of the quantities are labeled.
|
| 86 |
+
format : str or callable
|
| 87 |
+
A Python number formatting string or callable used to label the
|
| 88 |
+
flows with their quantities (i.e., a number times a unit, where the
|
| 89 |
+
unit is given). If a format string is given, the label will be
|
| 90 |
+
``format % quantity``. If a callable is given, it will be called
|
| 91 |
+
with ``quantity`` as an argument.
|
| 92 |
+
gap : float
|
| 93 |
+
Space between paths that break in/break away to/from the top or
|
| 94 |
+
bottom.
|
| 95 |
+
radius : float
|
| 96 |
+
Inner radius of the vertical paths.
|
| 97 |
+
shoulder : float
|
| 98 |
+
Size of the shoulders of output arrows.
|
| 99 |
+
offset : float
|
| 100 |
+
Text offset (from the dip or tip of the arrow).
|
| 101 |
+
head_angle : float
|
| 102 |
+
Angle, in degrees, of the arrow heads (and negative of the angle of
|
| 103 |
+
the tails).
|
| 104 |
+
margin : float
|
| 105 |
+
Minimum space between Sankey outlines and the edge of the plot
|
| 106 |
+
area.
|
| 107 |
+
tolerance : float
|
| 108 |
+
Acceptable maximum of the magnitude of the sum of flows. The
|
| 109 |
+
magnitude of the sum of connected flows cannot be greater than
|
| 110 |
+
*tolerance*.
|
| 111 |
+
**kwargs
|
| 112 |
+
Any additional keyword arguments will be passed to `add`, which
|
| 113 |
+
will create the first subdiagram.
|
| 114 |
+
|
| 115 |
+
See Also
|
| 116 |
+
--------
|
| 117 |
+
Sankey.add
|
| 118 |
+
Sankey.finish
|
| 119 |
+
|
| 120 |
+
Examples
|
| 121 |
+
--------
|
| 122 |
+
.. plot:: gallery/specialty_plots/sankey_basics.py
|
| 123 |
+
"""
|
| 124 |
+
# Check the arguments.
|
| 125 |
+
if gap < 0:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
"'gap' is negative, which is not allowed because it would "
|
| 128 |
+
"cause the paths to overlap")
|
| 129 |
+
if radius > gap:
|
| 130 |
+
raise ValueError(
|
| 131 |
+
"'radius' is greater than 'gap', which is not allowed because "
|
| 132 |
+
"it would cause the paths to overlap")
|
| 133 |
+
if head_angle < 0:
|
| 134 |
+
raise ValueError(
|
| 135 |
+
"'head_angle' is negative, which is not allowed because it "
|
| 136 |
+
"would cause inputs to look like outputs and vice versa")
|
| 137 |
+
if tolerance < 0:
|
| 138 |
+
raise ValueError(
|
| 139 |
+
"'tolerance' is negative, but it must be a magnitude")
|
| 140 |
+
|
| 141 |
+
# Create Axes if necessary.
|
| 142 |
+
if ax is None:
|
| 143 |
+
import matplotlib.pyplot as plt
|
| 144 |
+
fig = plt.figure()
|
| 145 |
+
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
|
| 146 |
+
|
| 147 |
+
self.diagrams = []
|
| 148 |
+
|
| 149 |
+
# Store the inputs.
|
| 150 |
+
self.ax = ax
|
| 151 |
+
self.unit = unit
|
| 152 |
+
self.format = format
|
| 153 |
+
self.scale = scale
|
| 154 |
+
self.gap = gap
|
| 155 |
+
self.radius = radius
|
| 156 |
+
self.shoulder = shoulder
|
| 157 |
+
self.offset = offset
|
| 158 |
+
self.margin = margin
|
| 159 |
+
self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0)
|
| 160 |
+
self.tolerance = tolerance
|
| 161 |
+
|
| 162 |
+
# Initialize the vertices of tight box around the diagram(s).
|
| 163 |
+
self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf))
|
| 164 |
+
|
| 165 |
+
# If there are any kwargs, create the first subdiagram.
|
| 166 |
+
if len(kwargs):
|
| 167 |
+
self.add(**kwargs)
|
| 168 |
+
|
| 169 |
+
def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)):
|
| 170 |
+
"""
|
| 171 |
+
Return the codes and vertices for a rotated, scaled, and translated
|
| 172 |
+
90 degree arc.
|
| 173 |
+
|
| 174 |
+
Other Parameters
|
| 175 |
+
----------------
|
| 176 |
+
quadrant : {0, 1, 2, 3}, default: 0
|
| 177 |
+
Uses 0-based indexing (0, 1, 2, or 3).
|
| 178 |
+
cw : bool, default: True
|
| 179 |
+
If True, the arc vertices are produced clockwise; counter-clockwise
|
| 180 |
+
otherwise.
|
| 181 |
+
radius : float, default: 1
|
| 182 |
+
The radius of the arc.
|
| 183 |
+
center : (float, float), default: (0, 0)
|
| 184 |
+
(x, y) tuple of the arc's center.
|
| 185 |
+
"""
|
| 186 |
+
# Note: It would be possible to use matplotlib's transforms to rotate,
|
| 187 |
+
# scale, and translate the arc, but since the angles are discrete,
|
| 188 |
+
# it's just as easy and maybe more efficient to do it here.
|
| 189 |
+
ARC_CODES = [Path.LINETO,
|
| 190 |
+
Path.CURVE4,
|
| 191 |
+
Path.CURVE4,
|
| 192 |
+
Path.CURVE4,
|
| 193 |
+
Path.CURVE4,
|
| 194 |
+
Path.CURVE4,
|
| 195 |
+
Path.CURVE4]
|
| 196 |
+
# Vertices of a cubic Bezier curve approximating a 90 deg arc
|
| 197 |
+
# These can be determined by Path.arc(0, 90).
|
| 198 |
+
ARC_VERTICES = np.array([[1.00000000e+00, 0.00000000e+00],
|
| 199 |
+
[1.00000000e+00, 2.65114773e-01],
|
| 200 |
+
[8.94571235e-01, 5.19642327e-01],
|
| 201 |
+
[7.07106781e-01, 7.07106781e-01],
|
| 202 |
+
[5.19642327e-01, 8.94571235e-01],
|
| 203 |
+
[2.65114773e-01, 1.00000000e+00],
|
| 204 |
+
# Insignificant
|
| 205 |
+
# [6.12303177e-17, 1.00000000e+00]])
|
| 206 |
+
[0.00000000e+00, 1.00000000e+00]])
|
| 207 |
+
if quadrant in (0, 2):
|
| 208 |
+
if cw:
|
| 209 |
+
vertices = ARC_VERTICES
|
| 210 |
+
else:
|
| 211 |
+
vertices = ARC_VERTICES[:, ::-1] # Swap x and y.
|
| 212 |
+
else: # 1, 3
|
| 213 |
+
# Negate x.
|
| 214 |
+
if cw:
|
| 215 |
+
# Swap x and y.
|
| 216 |
+
vertices = np.column_stack((-ARC_VERTICES[:, 1],
|
| 217 |
+
ARC_VERTICES[:, 0]))
|
| 218 |
+
else:
|
| 219 |
+
vertices = np.column_stack((-ARC_VERTICES[:, 0],
|
| 220 |
+
ARC_VERTICES[:, 1]))
|
| 221 |
+
if quadrant > 1:
|
| 222 |
+
radius = -radius # Rotate 180 deg.
|
| 223 |
+
return list(zip(ARC_CODES, radius * vertices +
|
| 224 |
+
np.tile(center, (ARC_VERTICES.shape[0], 1))))
|
| 225 |
+
|
| 226 |
+
def _add_input(self, path, angle, flow, length):
|
| 227 |
+
"""
|
| 228 |
+
Add an input to a path and return its tip and label locations.
|
| 229 |
+
"""
|
| 230 |
+
if angle is None:
|
| 231 |
+
return [0, 0], [0, 0]
|
| 232 |
+
else:
|
| 233 |
+
x, y = path[-1][1] # Use the last point as a reference.
|
| 234 |
+
dipdepth = (flow / 2) * self.pitch
|
| 235 |
+
if angle == RIGHT:
|
| 236 |
+
x -= length
|
| 237 |
+
dip = [x + dipdepth, y + flow / 2.0]
|
| 238 |
+
path.extend([(Path.LINETO, [x, y]),
|
| 239 |
+
(Path.LINETO, dip),
|
| 240 |
+
(Path.LINETO, [x, y + flow]),
|
| 241 |
+
(Path.LINETO, [x + self.gap, y + flow])])
|
| 242 |
+
label_location = [dip[0] - self.offset, dip[1]]
|
| 243 |
+
else: # Vertical
|
| 244 |
+
x -= self.gap
|
| 245 |
+
if angle == UP:
|
| 246 |
+
sign = 1
|
| 247 |
+
else:
|
| 248 |
+
sign = -1
|
| 249 |
+
|
| 250 |
+
dip = [x - flow / 2, y - sign * (length - dipdepth)]
|
| 251 |
+
if angle == DOWN:
|
| 252 |
+
quadrant = 2
|
| 253 |
+
else:
|
| 254 |
+
quadrant = 1
|
| 255 |
+
|
| 256 |
+
# Inner arc isn't needed if inner radius is zero
|
| 257 |
+
if self.radius:
|
| 258 |
+
path.extend(self._arc(quadrant=quadrant,
|
| 259 |
+
cw=angle == UP,
|
| 260 |
+
radius=self.radius,
|
| 261 |
+
center=(x + self.radius,
|
| 262 |
+
y - sign * self.radius)))
|
| 263 |
+
else:
|
| 264 |
+
path.append((Path.LINETO, [x, y]))
|
| 265 |
+
path.extend([(Path.LINETO, [x, y - sign * length]),
|
| 266 |
+
(Path.LINETO, dip),
|
| 267 |
+
(Path.LINETO, [x - flow, y - sign * length])])
|
| 268 |
+
path.extend(self._arc(quadrant=quadrant,
|
| 269 |
+
cw=angle == DOWN,
|
| 270 |
+
radius=flow + self.radius,
|
| 271 |
+
center=(x + self.radius,
|
| 272 |
+
y - sign * self.radius)))
|
| 273 |
+
path.append((Path.LINETO, [x - flow, y + sign * flow]))
|
| 274 |
+
label_location = [dip[0], dip[1] - sign * self.offset]
|
| 275 |
+
|
| 276 |
+
return dip, label_location
|
| 277 |
+
|
| 278 |
+
def _add_output(self, path, angle, flow, length):
|
| 279 |
+
"""
|
| 280 |
+
Append an output to a path and return its tip and label locations.
|
| 281 |
+
|
| 282 |
+
.. note:: *flow* is negative for an output.
|
| 283 |
+
"""
|
| 284 |
+
if angle is None:
|
| 285 |
+
return [0, 0], [0, 0]
|
| 286 |
+
else:
|
| 287 |
+
x, y = path[-1][1] # Use the last point as a reference.
|
| 288 |
+
tipheight = (self.shoulder - flow / 2) * self.pitch
|
| 289 |
+
if angle == RIGHT:
|
| 290 |
+
x += length
|
| 291 |
+
tip = [x + tipheight, y + flow / 2.0]
|
| 292 |
+
path.extend([(Path.LINETO, [x, y]),
|
| 293 |
+
(Path.LINETO, [x, y + self.shoulder]),
|
| 294 |
+
(Path.LINETO, tip),
|
| 295 |
+
(Path.LINETO, [x, y - self.shoulder + flow]),
|
| 296 |
+
(Path.LINETO, [x, y + flow]),
|
| 297 |
+
(Path.LINETO, [x - self.gap, y + flow])])
|
| 298 |
+
label_location = [tip[0] + self.offset, tip[1]]
|
| 299 |
+
else: # Vertical
|
| 300 |
+
x += self.gap
|
| 301 |
+
if angle == UP:
|
| 302 |
+
sign, quadrant = 1, 3
|
| 303 |
+
else:
|
| 304 |
+
sign, quadrant = -1, 0
|
| 305 |
+
|
| 306 |
+
tip = [x - flow / 2.0, y + sign * (length + tipheight)]
|
| 307 |
+
# Inner arc isn't needed if inner radius is zero
|
| 308 |
+
if self.radius:
|
| 309 |
+
path.extend(self._arc(quadrant=quadrant,
|
| 310 |
+
cw=angle == UP,
|
| 311 |
+
radius=self.radius,
|
| 312 |
+
center=(x - self.radius,
|
| 313 |
+
y + sign * self.radius)))
|
| 314 |
+
else:
|
| 315 |
+
path.append((Path.LINETO, [x, y]))
|
| 316 |
+
path.extend([(Path.LINETO, [x, y + sign * length]),
|
| 317 |
+
(Path.LINETO, [x - self.shoulder,
|
| 318 |
+
y + sign * length]),
|
| 319 |
+
(Path.LINETO, tip),
|
| 320 |
+
(Path.LINETO, [x + self.shoulder - flow,
|
| 321 |
+
y + sign * length]),
|
| 322 |
+
(Path.LINETO, [x - flow, y + sign * length])])
|
| 323 |
+
path.extend(self._arc(quadrant=quadrant,
|
| 324 |
+
cw=angle == DOWN,
|
| 325 |
+
radius=self.radius - flow,
|
| 326 |
+
center=(x - self.radius,
|
| 327 |
+
y + sign * self.radius)))
|
| 328 |
+
path.append((Path.LINETO, [x - flow, y + sign * flow]))
|
| 329 |
+
label_location = [tip[0], tip[1] + sign * self.offset]
|
| 330 |
+
return tip, label_location
|
| 331 |
+
|
| 332 |
+
def _revert(self, path, first_action=Path.LINETO):
|
| 333 |
+
"""
|
| 334 |
+
A path is not simply reversible by path[::-1] since the code
|
| 335 |
+
specifies an action to take from the **previous** point.
|
| 336 |
+
"""
|
| 337 |
+
reverse_path = []
|
| 338 |
+
next_code = first_action
|
| 339 |
+
for code, position in path[::-1]:
|
| 340 |
+
reverse_path.append((next_code, position))
|
| 341 |
+
next_code = code
|
| 342 |
+
return reverse_path
|
| 343 |
+
# This might be more efficient, but it fails because 'tuple' object
|
| 344 |
+
# doesn't support item assignment:
|
| 345 |
+
# path[1] = path[1][-1:0:-1]
|
| 346 |
+
# path[1][0] = first_action
|
| 347 |
+
# path[2] = path[2][::-1]
|
| 348 |
+
# return path
|
| 349 |
+
|
| 350 |
+
@_docstring.dedent_interpd
|
| 351 |
+
def add(self, patchlabel='', flows=None, orientations=None, labels='',
|
| 352 |
+
trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0),
|
| 353 |
+
rotation=0, **kwargs):
|
| 354 |
+
"""
|
| 355 |
+
Add a simple Sankey diagram with flows at the same hierarchical level.
|
| 356 |
+
|
| 357 |
+
Parameters
|
| 358 |
+
----------
|
| 359 |
+
patchlabel : str
|
| 360 |
+
Label to be placed at the center of the diagram.
|
| 361 |
+
Note that *label* (not *patchlabel*) can be passed as keyword
|
| 362 |
+
argument to create an entry in the legend.
|
| 363 |
+
|
| 364 |
+
flows : list of float
|
| 365 |
+
Array of flow values. By convention, inputs are positive and
|
| 366 |
+
outputs are negative.
|
| 367 |
+
|
| 368 |
+
Flows are placed along the top of the diagram from the inside out
|
| 369 |
+
in order of their index within *flows*. They are placed along the
|
| 370 |
+
sides of the diagram from the top down and along the bottom from
|
| 371 |
+
the outside in.
|
| 372 |
+
|
| 373 |
+
If the sum of the inputs and outputs is
|
| 374 |
+
nonzero, the discrepancy will appear as a cubic B��zier curve along
|
| 375 |
+
the top and bottom edges of the trunk.
|
| 376 |
+
|
| 377 |
+
orientations : list of {-1, 0, 1}
|
| 378 |
+
List of orientations of the flows (or a single orientation to be
|
| 379 |
+
used for all flows). Valid values are 0 (inputs from
|
| 380 |
+
the left, outputs to the right), 1 (from and to the top) or -1
|
| 381 |
+
(from and to the bottom).
|
| 382 |
+
|
| 383 |
+
labels : list of (str or None)
|
| 384 |
+
List of labels for the flows (or a single label to be used for all
|
| 385 |
+
flows). Each label may be *None* (no label), or a labeling string.
|
| 386 |
+
If an entry is a (possibly empty) string, then the quantity for the
|
| 387 |
+
corresponding flow will be shown below the string. However, if
|
| 388 |
+
the *unit* of the main diagram is None, then quantities are never
|
| 389 |
+
shown, regardless of the value of this argument.
|
| 390 |
+
|
| 391 |
+
trunklength : float
|
| 392 |
+
Length between the bases of the input and output groups (in
|
| 393 |
+
data-space units).
|
| 394 |
+
|
| 395 |
+
pathlengths : list of float
|
| 396 |
+
List of lengths of the vertical arrows before break-in or after
|
| 397 |
+
break-away. If a single value is given, then it will be applied to
|
| 398 |
+
the first (inside) paths on the top and bottom, and the length of
|
| 399 |
+
all other arrows will be justified accordingly. The *pathlengths*
|
| 400 |
+
are not applied to the horizontal inputs and outputs.
|
| 401 |
+
|
| 402 |
+
prior : int
|
| 403 |
+
Index of the prior diagram to which this diagram should be
|
| 404 |
+
connected.
|
| 405 |
+
|
| 406 |
+
connect : (int, int)
|
| 407 |
+
A (prior, this) tuple indexing the flow of the prior diagram and
|
| 408 |
+
the flow of this diagram which should be connected. If this is the
|
| 409 |
+
first diagram or *prior* is *None*, *connect* will be ignored.
|
| 410 |
+
|
| 411 |
+
rotation : float
|
| 412 |
+
Angle of rotation of the diagram in degrees. The interpretation of
|
| 413 |
+
the *orientations* argument will be rotated accordingly (e.g., if
|
| 414 |
+
*rotation* == 90, an *orientations* entry of 1 means to/from the
|
| 415 |
+
left). *rotation* is ignored if this diagram is connected to an
|
| 416 |
+
existing one (using *prior* and *connect*).
|
| 417 |
+
|
| 418 |
+
Returns
|
| 419 |
+
-------
|
| 420 |
+
Sankey
|
| 421 |
+
The current `.Sankey` instance.
|
| 422 |
+
|
| 423 |
+
Other Parameters
|
| 424 |
+
----------------
|
| 425 |
+
**kwargs
|
| 426 |
+
Additional keyword arguments set `matplotlib.patches.PathPatch`
|
| 427 |
+
properties, listed below. For example, one may want to use
|
| 428 |
+
``fill=False`` or ``label="A legend entry"``.
|
| 429 |
+
|
| 430 |
+
%(Patch:kwdoc)s
|
| 431 |
+
|
| 432 |
+
See Also
|
| 433 |
+
--------
|
| 434 |
+
Sankey.finish
|
| 435 |
+
"""
|
| 436 |
+
# Check and preprocess the arguments.
|
| 437 |
+
flows = np.array([1.0, -1.0]) if flows is None else np.array(flows)
|
| 438 |
+
n = flows.shape[0] # Number of flows
|
| 439 |
+
if rotation is None:
|
| 440 |
+
rotation = 0
|
| 441 |
+
else:
|
| 442 |
+
# In the code below, angles are expressed in deg/90.
|
| 443 |
+
rotation /= 90.0
|
| 444 |
+
if orientations is None:
|
| 445 |
+
orientations = 0
|
| 446 |
+
try:
|
| 447 |
+
orientations = np.broadcast_to(orientations, n)
|
| 448 |
+
except ValueError:
|
| 449 |
+
raise ValueError(
|
| 450 |
+
f"The shapes of 'flows' {np.shape(flows)} and 'orientations' "
|
| 451 |
+
f"{np.shape(orientations)} are incompatible"
|
| 452 |
+
) from None
|
| 453 |
+
try:
|
| 454 |
+
labels = np.broadcast_to(labels, n)
|
| 455 |
+
except ValueError:
|
| 456 |
+
raise ValueError(
|
| 457 |
+
f"The shapes of 'flows' {np.shape(flows)} and 'labels' "
|
| 458 |
+
f"{np.shape(labels)} are incompatible"
|
| 459 |
+
) from None
|
| 460 |
+
if trunklength < 0:
|
| 461 |
+
raise ValueError(
|
| 462 |
+
"'trunklength' is negative, which is not allowed because it "
|
| 463 |
+
"would cause poor layout")
|
| 464 |
+
if abs(np.sum(flows)) > self.tolerance:
|
| 465 |
+
_log.info("The sum of the flows is nonzero (%f; patchlabel=%r); "
|
| 466 |
+
"is the system not at steady state?",
|
| 467 |
+
np.sum(flows), patchlabel)
|
| 468 |
+
scaled_flows = self.scale * flows
|
| 469 |
+
gain = sum(max(flow, 0) for flow in scaled_flows)
|
| 470 |
+
loss = sum(min(flow, 0) for flow in scaled_flows)
|
| 471 |
+
if prior is not None:
|
| 472 |
+
if prior < 0:
|
| 473 |
+
raise ValueError("The index of the prior diagram is negative")
|
| 474 |
+
if min(connect) < 0:
|
| 475 |
+
raise ValueError(
|
| 476 |
+
"At least one of the connection indices is negative")
|
| 477 |
+
if prior >= len(self.diagrams):
|
| 478 |
+
raise ValueError(
|
| 479 |
+
f"The index of the prior diagram is {prior}, but there "
|
| 480 |
+
f"are only {len(self.diagrams)} other diagrams")
|
| 481 |
+
if connect[0] >= len(self.diagrams[prior].flows):
|
| 482 |
+
raise ValueError(
|
| 483 |
+
"The connection index to the source diagram is {}, but "
|
| 484 |
+
"that diagram has only {} flows".format(
|
| 485 |
+
connect[0], len(self.diagrams[prior].flows)))
|
| 486 |
+
if connect[1] >= n:
|
| 487 |
+
raise ValueError(
|
| 488 |
+
f"The connection index to this diagram is {connect[1]}, "
|
| 489 |
+
f"but this diagram has only {n} flows")
|
| 490 |
+
if self.diagrams[prior].angles[connect[0]] is None:
|
| 491 |
+
raise ValueError(
|
| 492 |
+
f"The connection cannot be made, which may occur if the "
|
| 493 |
+
f"magnitude of flow {connect[0]} of diagram {prior} is "
|
| 494 |
+
f"less than the specified tolerance")
|
| 495 |
+
flow_error = (self.diagrams[prior].flows[connect[0]] +
|
| 496 |
+
flows[connect[1]])
|
| 497 |
+
if abs(flow_error) >= self.tolerance:
|
| 498 |
+
raise ValueError(
|
| 499 |
+
f"The scaled sum of the connected flows is {flow_error}, "
|
| 500 |
+
f"which is not within the tolerance ({self.tolerance})")
|
| 501 |
+
|
| 502 |
+
# Determine if the flows are inputs.
|
| 503 |
+
are_inputs = [None] * n
|
| 504 |
+
for i, flow in enumerate(flows):
|
| 505 |
+
if flow >= self.tolerance:
|
| 506 |
+
are_inputs[i] = True
|
| 507 |
+
elif flow <= -self.tolerance:
|
| 508 |
+
are_inputs[i] = False
|
| 509 |
+
else:
|
| 510 |
+
_log.info(
|
| 511 |
+
"The magnitude of flow %d (%f) is below the tolerance "
|
| 512 |
+
"(%f).\nIt will not be shown, and it cannot be used in a "
|
| 513 |
+
"connection.", i, flow, self.tolerance)
|
| 514 |
+
|
| 515 |
+
# Determine the angles of the arrows (before rotation).
|
| 516 |
+
angles = [None] * n
|
| 517 |
+
for i, (orient, is_input) in enumerate(zip(orientations, are_inputs)):
|
| 518 |
+
if orient == 1:
|
| 519 |
+
if is_input:
|
| 520 |
+
angles[i] = DOWN
|
| 521 |
+
elif is_input is False:
|
| 522 |
+
# Be specific since is_input can be None.
|
| 523 |
+
angles[i] = UP
|
| 524 |
+
elif orient == 0:
|
| 525 |
+
if is_input is not None:
|
| 526 |
+
angles[i] = RIGHT
|
| 527 |
+
else:
|
| 528 |
+
if orient != -1:
|
| 529 |
+
raise ValueError(
|
| 530 |
+
f"The value of orientations[{i}] is {orient}, "
|
| 531 |
+
f"but it must be -1, 0, or 1")
|
| 532 |
+
if is_input:
|
| 533 |
+
angles[i] = UP
|
| 534 |
+
elif is_input is False:
|
| 535 |
+
angles[i] = DOWN
|
| 536 |
+
|
| 537 |
+
# Justify the lengths of the paths.
|
| 538 |
+
if np.iterable(pathlengths):
|
| 539 |
+
if len(pathlengths) != n:
|
| 540 |
+
raise ValueError(
|
| 541 |
+
f"The lengths of 'flows' ({n}) and 'pathlengths' "
|
| 542 |
+
f"({len(pathlengths)}) are incompatible")
|
| 543 |
+
else: # Make pathlengths into a list.
|
| 544 |
+
urlength = pathlengths
|
| 545 |
+
ullength = pathlengths
|
| 546 |
+
lrlength = pathlengths
|
| 547 |
+
lllength = pathlengths
|
| 548 |
+
d = dict(RIGHT=pathlengths)
|
| 549 |
+
pathlengths = [d.get(angle, 0) for angle in angles]
|
| 550 |
+
# Determine the lengths of the top-side arrows
|
| 551 |
+
# from the middle outwards.
|
| 552 |
+
for i, (angle, is_input, flow) in enumerate(zip(angles, are_inputs,
|
| 553 |
+
scaled_flows)):
|
| 554 |
+
if angle == DOWN and is_input:
|
| 555 |
+
pathlengths[i] = ullength
|
| 556 |
+
ullength += flow
|
| 557 |
+
elif angle == UP and is_input is False:
|
| 558 |
+
pathlengths[i] = urlength
|
| 559 |
+
urlength -= flow # Flow is negative for outputs.
|
| 560 |
+
# Determine the lengths of the bottom-side arrows
|
| 561 |
+
# from the middle outwards.
|
| 562 |
+
for i, (angle, is_input, flow) in enumerate(reversed(list(zip(
|
| 563 |
+
angles, are_inputs, scaled_flows)))):
|
| 564 |
+
if angle == UP and is_input:
|
| 565 |
+
pathlengths[n - i - 1] = lllength
|
| 566 |
+
lllength += flow
|
| 567 |
+
elif angle == DOWN and is_input is False:
|
| 568 |
+
pathlengths[n - i - 1] = lrlength
|
| 569 |
+
lrlength -= flow
|
| 570 |
+
# Determine the lengths of the left-side arrows
|
| 571 |
+
# from the bottom upwards.
|
| 572 |
+
has_left_input = False
|
| 573 |
+
for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
|
| 574 |
+
angles, are_inputs, zip(scaled_flows, pathlengths))))):
|
| 575 |
+
if angle == RIGHT:
|
| 576 |
+
if is_input:
|
| 577 |
+
if has_left_input:
|
| 578 |
+
pathlengths[n - i - 1] = 0
|
| 579 |
+
else:
|
| 580 |
+
has_left_input = True
|
| 581 |
+
# Determine the lengths of the right-side arrows
|
| 582 |
+
# from the top downwards.
|
| 583 |
+
has_right_output = False
|
| 584 |
+
for i, (angle, is_input, spec) in enumerate(zip(
|
| 585 |
+
angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
|
| 586 |
+
if angle == RIGHT:
|
| 587 |
+
if is_input is False:
|
| 588 |
+
if has_right_output:
|
| 589 |
+
pathlengths[i] = 0
|
| 590 |
+
else:
|
| 591 |
+
has_right_output = True
|
| 592 |
+
|
| 593 |
+
# Begin the subpaths, and smooth the transition if the sum of the flows
|
| 594 |
+
# is nonzero.
|
| 595 |
+
urpath = [(Path.MOVETO, [(self.gap - trunklength / 2.0), # Upper right
|
| 596 |
+
gain / 2.0]),
|
| 597 |
+
(Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
|
| 598 |
+
gain / 2.0]),
|
| 599 |
+
(Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
|
| 600 |
+
gain / 2.0]),
|
| 601 |
+
(Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
|
| 602 |
+
-loss / 2.0]),
|
| 603 |
+
(Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
|
| 604 |
+
-loss / 2.0]),
|
| 605 |
+
(Path.LINETO, [(trunklength / 2.0 - self.gap),
|
| 606 |
+
-loss / 2.0])]
|
| 607 |
+
llpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower left
|
| 608 |
+
loss / 2.0]),
|
| 609 |
+
(Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
|
| 610 |
+
loss / 2.0]),
|
| 611 |
+
(Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
|
| 612 |
+
loss / 2.0]),
|
| 613 |
+
(Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
|
| 614 |
+
-gain / 2.0]),
|
| 615 |
+
(Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
|
| 616 |
+
-gain / 2.0]),
|
| 617 |
+
(Path.LINETO, [(self.gap - trunklength / 2.0),
|
| 618 |
+
-gain / 2.0])]
|
| 619 |
+
lrpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower right
|
| 620 |
+
loss / 2.0])]
|
| 621 |
+
ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, # Upper left
|
| 622 |
+
gain / 2.0])]
|
| 623 |
+
|
| 624 |
+
# Add the subpaths and assign the locations of the tips and labels.
|
| 625 |
+
tips = np.zeros((n, 2))
|
| 626 |
+
label_locations = np.zeros((n, 2))
|
| 627 |
+
# Add the top-side inputs and outputs from the middle outwards.
|
| 628 |
+
for i, (angle, is_input, spec) in enumerate(zip(
|
| 629 |
+
angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
|
| 630 |
+
if angle == DOWN and is_input:
|
| 631 |
+
tips[i, :], label_locations[i, :] = self._add_input(
|
| 632 |
+
ulpath, angle, *spec)
|
| 633 |
+
elif angle == UP and is_input is False:
|
| 634 |
+
tips[i, :], label_locations[i, :] = self._add_output(
|
| 635 |
+
urpath, angle, *spec)
|
| 636 |
+
# Add the bottom-side inputs and outputs from the middle outwards.
|
| 637 |
+
for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
|
| 638 |
+
angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
|
| 639 |
+
if angle == UP and is_input:
|
| 640 |
+
tip, label_location = self._add_input(llpath, angle, *spec)
|
| 641 |
+
tips[n - i - 1, :] = tip
|
| 642 |
+
label_locations[n - i - 1, :] = label_location
|
| 643 |
+
elif angle == DOWN and is_input is False:
|
| 644 |
+
tip, label_location = self._add_output(lrpath, angle, *spec)
|
| 645 |
+
tips[n - i - 1, :] = tip
|
| 646 |
+
label_locations[n - i - 1, :] = label_location
|
| 647 |
+
# Add the left-side inputs from the bottom upwards.
|
| 648 |
+
has_left_input = False
|
| 649 |
+
for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
|
| 650 |
+
angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
|
| 651 |
+
if angle == RIGHT and is_input:
|
| 652 |
+
if not has_left_input:
|
| 653 |
+
# Make sure the lower path extends
|
| 654 |
+
# at least as far as the upper one.
|
| 655 |
+
if llpath[-1][1][0] > ulpath[-1][1][0]:
|
| 656 |
+
llpath.append((Path.LINETO, [ulpath[-1][1][0],
|
| 657 |
+
llpath[-1][1][1]]))
|
| 658 |
+
has_left_input = True
|
| 659 |
+
tip, label_location = self._add_input(llpath, angle, *spec)
|
| 660 |
+
tips[n - i - 1, :] = tip
|
| 661 |
+
label_locations[n - i - 1, :] = label_location
|
| 662 |
+
# Add the right-side outputs from the top downwards.
|
| 663 |
+
has_right_output = False
|
| 664 |
+
for i, (angle, is_input, spec) in enumerate(zip(
|
| 665 |
+
angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
|
| 666 |
+
if angle == RIGHT and is_input is False:
|
| 667 |
+
if not has_right_output:
|
| 668 |
+
# Make sure the upper path extends
|
| 669 |
+
# at least as far as the lower one.
|
| 670 |
+
if urpath[-1][1][0] < lrpath[-1][1][0]:
|
| 671 |
+
urpath.append((Path.LINETO, [lrpath[-1][1][0],
|
| 672 |
+
urpath[-1][1][1]]))
|
| 673 |
+
has_right_output = True
|
| 674 |
+
tips[i, :], label_locations[i, :] = self._add_output(
|
| 675 |
+
urpath, angle, *spec)
|
| 676 |
+
# Trim any hanging vertices.
|
| 677 |
+
if not has_left_input:
|
| 678 |
+
ulpath.pop()
|
| 679 |
+
llpath.pop()
|
| 680 |
+
if not has_right_output:
|
| 681 |
+
lrpath.pop()
|
| 682 |
+
urpath.pop()
|
| 683 |
+
|
| 684 |
+
# Concatenate the subpaths in the correct order (clockwise from top).
|
| 685 |
+
path = (urpath + self._revert(lrpath) + llpath + self._revert(ulpath) +
|
| 686 |
+
[(Path.CLOSEPOLY, urpath[0][1])])
|
| 687 |
+
|
| 688 |
+
# Create a patch with the Sankey outline.
|
| 689 |
+
codes, vertices = zip(*path)
|
| 690 |
+
vertices = np.array(vertices)
|
| 691 |
+
|
| 692 |
+
def _get_angle(a, r):
|
| 693 |
+
if a is None:
|
| 694 |
+
return None
|
| 695 |
+
else:
|
| 696 |
+
return a + r
|
| 697 |
+
|
| 698 |
+
if prior is None:
|
| 699 |
+
if rotation != 0: # By default, none of this is needed.
|
| 700 |
+
angles = [_get_angle(angle, rotation) for angle in angles]
|
| 701 |
+
rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
|
| 702 |
+
tips = rotate(tips)
|
| 703 |
+
label_locations = rotate(label_locations)
|
| 704 |
+
vertices = rotate(vertices)
|
| 705 |
+
text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center')
|
| 706 |
+
else:
|
| 707 |
+
rotation = (self.diagrams[prior].angles[connect[0]] -
|
| 708 |
+
angles[connect[1]])
|
| 709 |
+
angles = [_get_angle(angle, rotation) for angle in angles]
|
| 710 |
+
rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
|
| 711 |
+
tips = rotate(tips)
|
| 712 |
+
offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]]
|
| 713 |
+
translate = Affine2D().translate(*offset).transform_affine
|
| 714 |
+
tips = translate(tips)
|
| 715 |
+
label_locations = translate(rotate(label_locations))
|
| 716 |
+
vertices = translate(rotate(vertices))
|
| 717 |
+
kwds = dict(s=patchlabel, ha='center', va='center')
|
| 718 |
+
text = self.ax.text(*offset, **kwds)
|
| 719 |
+
if mpl.rcParams['_internal.classic_mode']:
|
| 720 |
+
fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4'))
|
| 721 |
+
lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5))
|
| 722 |
+
else:
|
| 723 |
+
fc = kwargs.pop('fc', kwargs.pop('facecolor', None))
|
| 724 |
+
lw = kwargs.pop('lw', kwargs.pop('linewidth', None))
|
| 725 |
+
if fc is None:
|
| 726 |
+
fc = self.ax._get_patches_for_fill.get_next_color()
|
| 727 |
+
patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs)
|
| 728 |
+
self.ax.add_patch(patch)
|
| 729 |
+
|
| 730 |
+
# Add the path labels.
|
| 731 |
+
texts = []
|
| 732 |
+
for number, angle, label, location in zip(flows, angles, labels,
|
| 733 |
+
label_locations):
|
| 734 |
+
if label is None or angle is None:
|
| 735 |
+
label = ''
|
| 736 |
+
elif self.unit is not None:
|
| 737 |
+
if isinstance(self.format, str):
|
| 738 |
+
quantity = self.format % abs(number) + self.unit
|
| 739 |
+
elif callable(self.format):
|
| 740 |
+
quantity = self.format(number)
|
| 741 |
+
else:
|
| 742 |
+
raise TypeError(
|
| 743 |
+
'format must be callable or a format string')
|
| 744 |
+
if label != '':
|
| 745 |
+
label += "\n"
|
| 746 |
+
label += quantity
|
| 747 |
+
texts.append(self.ax.text(x=location[0], y=location[1],
|
| 748 |
+
s=label,
|
| 749 |
+
ha='center', va='center'))
|
| 750 |
+
# Text objects are placed even they are empty (as long as the magnitude
|
| 751 |
+
# of the corresponding flow is larger than the tolerance) in case the
|
| 752 |
+
# user wants to provide labels later.
|
| 753 |
+
|
| 754 |
+
# Expand the size of the diagram if necessary.
|
| 755 |
+
self.extent = (min(np.min(vertices[:, 0]),
|
| 756 |
+
np.min(label_locations[:, 0]),
|
| 757 |
+
self.extent[0]),
|
| 758 |
+
max(np.max(vertices[:, 0]),
|
| 759 |
+
np.max(label_locations[:, 0]),
|
| 760 |
+
self.extent[1]),
|
| 761 |
+
min(np.min(vertices[:, 1]),
|
| 762 |
+
np.min(label_locations[:, 1]),
|
| 763 |
+
self.extent[2]),
|
| 764 |
+
max(np.max(vertices[:, 1]),
|
| 765 |
+
np.max(label_locations[:, 1]),
|
| 766 |
+
self.extent[3]))
|
| 767 |
+
# Include both vertices _and_ label locations in the extents; there are
|
| 768 |
+
# where either could determine the margins (e.g., arrow shoulders).
|
| 769 |
+
|
| 770 |
+
# Add this diagram as a subdiagram.
|
| 771 |
+
self.diagrams.append(
|
| 772 |
+
SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips,
|
| 773 |
+
text=text, texts=texts))
|
| 774 |
+
|
| 775 |
+
# Allow a daisy-chained call structure (see docstring for the class).
|
| 776 |
+
return self
|
| 777 |
+
|
| 778 |
+
def finish(self):
|
| 779 |
+
"""
|
| 780 |
+
Adjust the Axes and return a list of information about the Sankey
|
| 781 |
+
subdiagram(s).
|
| 782 |
+
|
| 783 |
+
Returns a list of subdiagrams with the following fields:
|
| 784 |
+
|
| 785 |
+
======== =============================================================
|
| 786 |
+
Field Description
|
| 787 |
+
======== =============================================================
|
| 788 |
+
*patch* Sankey outline (a `~matplotlib.patches.PathPatch`).
|
| 789 |
+
*flows* Flow values (positive for input, negative for output).
|
| 790 |
+
*angles* List of angles of the arrows [deg/90].
|
| 791 |
+
For example, if the diagram has not been rotated,
|
| 792 |
+
an input to the top side has an angle of 3 (DOWN),
|
| 793 |
+
and an output from the top side has an angle of 1 (UP).
|
| 794 |
+
If a flow has been skipped (because its magnitude is less
|
| 795 |
+
than *tolerance*), then its angle will be *None*.
|
| 796 |
+
*tips* (N, 2)-array of the (x, y) positions of the tips (or "dips")
|
| 797 |
+
of the flow paths.
|
| 798 |
+
If the magnitude of a flow is less the *tolerance* of this
|
| 799 |
+
`Sankey` instance, the flow is skipped and its tip will be at
|
| 800 |
+
the center of the diagram.
|
| 801 |
+
*text* `.Text` instance for the diagram label.
|
| 802 |
+
*texts* List of `.Text` instances for the flow labels.
|
| 803 |
+
======== =============================================================
|
| 804 |
+
|
| 805 |
+
See Also
|
| 806 |
+
--------
|
| 807 |
+
Sankey.add
|
| 808 |
+
"""
|
| 809 |
+
self.ax.axis([self.extent[0] - self.margin,
|
| 810 |
+
self.extent[1] + self.margin,
|
| 811 |
+
self.extent[2] - self.margin,
|
| 812 |
+
self.extent[3] + self.margin])
|
| 813 |
+
self.ax.set_aspect('equal', adjustable='datalim')
|
| 814 |
+
return self.diagrams
|
parrot/lib/python3.10/site-packages/matplotlib/sankey.pyi
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib.axes import Axes
|
| 2 |
+
|
| 3 |
+
from collections.abc import Callable, Iterable
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
__license__: str
|
| 9 |
+
__credits__: list[str]
|
| 10 |
+
__author__: str
|
| 11 |
+
__version__: str
|
| 12 |
+
|
| 13 |
+
RIGHT: int
|
| 14 |
+
UP: int
|
| 15 |
+
DOWN: int
|
| 16 |
+
|
| 17 |
+
# TODO typing units
|
| 18 |
+
class Sankey:
|
| 19 |
+
diagrams: list[Any]
|
| 20 |
+
ax: Axes
|
| 21 |
+
unit: Any
|
| 22 |
+
format: str | Callable[[float], str]
|
| 23 |
+
scale: float
|
| 24 |
+
gap: float
|
| 25 |
+
radius: float
|
| 26 |
+
shoulder: float
|
| 27 |
+
offset: float
|
| 28 |
+
margin: float
|
| 29 |
+
pitch: float
|
| 30 |
+
tolerance: float
|
| 31 |
+
extent: np.ndarray
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
ax: Axes | None = ...,
|
| 35 |
+
scale: float = ...,
|
| 36 |
+
unit: Any = ...,
|
| 37 |
+
format: str | Callable[[float], str] = ...,
|
| 38 |
+
gap: float = ...,
|
| 39 |
+
radius: float = ...,
|
| 40 |
+
shoulder: float = ...,
|
| 41 |
+
offset: float = ...,
|
| 42 |
+
head_angle: float = ...,
|
| 43 |
+
margin: float = ...,
|
| 44 |
+
tolerance: float = ...,
|
| 45 |
+
**kwargs
|
| 46 |
+
) -> None: ...
|
| 47 |
+
def add(
|
| 48 |
+
self,
|
| 49 |
+
patchlabel: str = ...,
|
| 50 |
+
flows: Iterable[float] | None = ...,
|
| 51 |
+
orientations: Iterable[int] | None = ...,
|
| 52 |
+
labels: str | Iterable[str | None] = ...,
|
| 53 |
+
trunklength: float = ...,
|
| 54 |
+
pathlengths: float | Iterable[float] = ...,
|
| 55 |
+
prior: int | None = ...,
|
| 56 |
+
connect: tuple[int, int] = ...,
|
| 57 |
+
rotation: float = ...,
|
| 58 |
+
**kwargs
|
| 59 |
+
# Replace return with Self when py3.9 is dropped
|
| 60 |
+
) -> Sankey: ...
|
| 61 |
+
def finish(self) -> list[Any]: ...
|
parrot/lib/python3.10/site-packages/matplotlib/stackplot.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, hatch=None, baseline='zero',
|
| 20 |
+
**kwargs):
|
| 21 |
+
"""
|
| 22 |
+
Draw a stacked area plot or a streamgraph.
|
| 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 :mpltype:`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 |
+
hatch : list of str, default: None
|
| 59 |
+
A sequence of hatching styles. See
|
| 60 |
+
:doc:`/gallery/shapes_and_collections/hatch_style_reference`.
|
| 61 |
+
The sequence will be cycled through for filling the
|
| 62 |
+
stacked areas from bottom to top.
|
| 63 |
+
It need not be exactly the same length as the number
|
| 64 |
+
of provided *y*, in which case the styles will repeat from the
|
| 65 |
+
beginning.
|
| 66 |
+
|
| 67 |
+
.. versionadded:: 3.9
|
| 68 |
+
Support for list input
|
| 69 |
+
|
| 70 |
+
data : indexable object, optional
|
| 71 |
+
DATA_PARAMETER_PLACEHOLDER
|
| 72 |
+
|
| 73 |
+
**kwargs
|
| 74 |
+
All other keyword arguments are passed to `.Axes.fill_between`.
|
| 75 |
+
|
| 76 |
+
Returns
|
| 77 |
+
-------
|
| 78 |
+
list of `.PolyCollection`
|
| 79 |
+
A list of `.PolyCollection` instances, one for each element in the
|
| 80 |
+
stacked area plot.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
y = np.vstack(args)
|
| 84 |
+
|
| 85 |
+
labels = iter(labels)
|
| 86 |
+
if colors is not None:
|
| 87 |
+
colors = itertools.cycle(colors)
|
| 88 |
+
else:
|
| 89 |
+
colors = (axes._get_lines.get_next_color() for _ in y)
|
| 90 |
+
|
| 91 |
+
if hatch is None or isinstance(hatch, str):
|
| 92 |
+
hatch = itertools.cycle([hatch])
|
| 93 |
+
else:
|
| 94 |
+
hatch = itertools.cycle(hatch)
|
| 95 |
+
|
| 96 |
+
# Assume data passed has not been 'stacked', so stack it here.
|
| 97 |
+
# We'll need a float buffer for the upcoming calculations.
|
| 98 |
+
stack = np.cumsum(y, axis=0, dtype=np.promote_types(y.dtype, np.float32))
|
| 99 |
+
|
| 100 |
+
_api.check_in_list(['zero', 'sym', 'wiggle', 'weighted_wiggle'],
|
| 101 |
+
baseline=baseline)
|
| 102 |
+
if baseline == 'zero':
|
| 103 |
+
first_line = 0.
|
| 104 |
+
|
| 105 |
+
elif baseline == 'sym':
|
| 106 |
+
first_line = -np.sum(y, 0) * 0.5
|
| 107 |
+
stack += first_line[None, :]
|
| 108 |
+
|
| 109 |
+
elif baseline == 'wiggle':
|
| 110 |
+
m = y.shape[0]
|
| 111 |
+
first_line = (y * (m - 0.5 - np.arange(m)[:, None])).sum(0)
|
| 112 |
+
first_line /= -m
|
| 113 |
+
stack += first_line
|
| 114 |
+
|
| 115 |
+
elif baseline == 'weighted_wiggle':
|
| 116 |
+
total = np.sum(y, 0)
|
| 117 |
+
# multiply by 1/total (or zero) to avoid infinities in the division:
|
| 118 |
+
inv_total = np.zeros_like(total)
|
| 119 |
+
mask = total > 0
|
| 120 |
+
inv_total[mask] = 1.0 / total[mask]
|
| 121 |
+
increase = np.hstack((y[:, 0:1], np.diff(y)))
|
| 122 |
+
below_size = total - stack
|
| 123 |
+
below_size += 0.5 * y
|
| 124 |
+
move_up = below_size * inv_total
|
| 125 |
+
move_up[:, 0] = 0.5
|
| 126 |
+
center = (move_up - 0.5) * increase
|
| 127 |
+
center = np.cumsum(center.sum(0))
|
| 128 |
+
first_line = center - 0.5 * total
|
| 129 |
+
stack += first_line
|
| 130 |
+
|
| 131 |
+
# Color between x = 0 and the first array.
|
| 132 |
+
coll = axes.fill_between(x, first_line, stack[0, :],
|
| 133 |
+
facecolor=next(colors),
|
| 134 |
+
hatch=next(hatch),
|
| 135 |
+
label=next(labels, None),
|
| 136 |
+
**kwargs)
|
| 137 |
+
coll.sticky_edges.y[:] = [0]
|
| 138 |
+
r = [coll]
|
| 139 |
+
|
| 140 |
+
# Color between array i-1 and array i
|
| 141 |
+
for i in range(len(y) - 1):
|
| 142 |
+
r.append(axes.fill_between(x, stack[i, :], stack[i + 1, :],
|
| 143 |
+
facecolor=next(colors),
|
| 144 |
+
hatch=next(hatch),
|
| 145 |
+
label=next(labels, None),
|
| 146 |
+
**kwargs))
|
| 147 |
+
return r
|
parrot/lib/python3.10/site-packages/matplotlib/streamplot.py
ADDED
|
@@ -0,0 +1,712 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Streamline plotting for 2D vector fields.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
import matplotlib as mpl
|
| 9 |
+
from matplotlib import _api, cm, patches
|
| 10 |
+
import matplotlib.colors as mcolors
|
| 11 |
+
import matplotlib.collections as mcollections
|
| 12 |
+
import matplotlib.lines as mlines
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
__all__ = ['streamplot']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
|
| 19 |
+
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
|
| 20 |
+
minlength=0.1, transform=None, zorder=None, start_points=None,
|
| 21 |
+
maxlength=4.0, integration_direction='both',
|
| 22 |
+
broken_streamlines=True):
|
| 23 |
+
"""
|
| 24 |
+
Draw streamlines of a vector flow.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
x, y : 1D/2D arrays
|
| 29 |
+
Evenly spaced strictly increasing arrays to make a grid. If 2D, all
|
| 30 |
+
rows of *x* must be equal and all columns of *y* must be equal; i.e.,
|
| 31 |
+
they must be as if generated by ``np.meshgrid(x_1d, y_1d)``.
|
| 32 |
+
u, v : 2D arrays
|
| 33 |
+
*x* and *y*-velocities. The number of rows and columns must match
|
| 34 |
+
the length of *y* and *x*, respectively.
|
| 35 |
+
density : float or (float, float)
|
| 36 |
+
Controls the closeness of streamlines. When ``density = 1``, the domain
|
| 37 |
+
is divided into a 30x30 grid. *density* linearly scales this grid.
|
| 38 |
+
Each cell in the grid can have, at most, one traversing streamline.
|
| 39 |
+
For different densities in each direction, use a tuple
|
| 40 |
+
(density_x, density_y).
|
| 41 |
+
linewidth : float or 2D array
|
| 42 |
+
The width of the streamlines. With a 2D array the line width can be
|
| 43 |
+
varied across the grid. The array must have the same shape as *u*
|
| 44 |
+
and *v*.
|
| 45 |
+
color : :mpltype:`color` or 2D array
|
| 46 |
+
The streamline color. If given an array, its values are converted to
|
| 47 |
+
colors using *cmap* and *norm*. The array must have the same shape
|
| 48 |
+
as *u* and *v*.
|
| 49 |
+
cmap, norm
|
| 50 |
+
Data normalization and colormapping parameters for *color*; only used
|
| 51 |
+
if *color* is an array of floats. See `~.Axes.imshow` for a detailed
|
| 52 |
+
description.
|
| 53 |
+
arrowsize : float
|
| 54 |
+
Scaling factor for the arrow size.
|
| 55 |
+
arrowstyle : str
|
| 56 |
+
Arrow style specification.
|
| 57 |
+
See `~matplotlib.patches.FancyArrowPatch`.
|
| 58 |
+
minlength : float
|
| 59 |
+
Minimum length of streamline in axes coordinates.
|
| 60 |
+
start_points : (N, 2) array
|
| 61 |
+
Coordinates of starting points for the streamlines in data coordinates
|
| 62 |
+
(the same coordinates as the *x* and *y* arrays).
|
| 63 |
+
zorder : float
|
| 64 |
+
The zorder of the streamlines and arrows.
|
| 65 |
+
Artists with lower zorder values are drawn first.
|
| 66 |
+
maxlength : float
|
| 67 |
+
Maximum length of streamline in axes coordinates.
|
| 68 |
+
integration_direction : {'forward', 'backward', 'both'}, default: 'both'
|
| 69 |
+
Integrate the streamline in forward, backward or both directions.
|
| 70 |
+
data : indexable object, optional
|
| 71 |
+
DATA_PARAMETER_PLACEHOLDER
|
| 72 |
+
broken_streamlines : boolean, default: True
|
| 73 |
+
If False, forces streamlines to continue until they
|
| 74 |
+
leave the plot domain. If True, they may be terminated if they
|
| 75 |
+
come too close to another streamline.
|
| 76 |
+
|
| 77 |
+
Returns
|
| 78 |
+
-------
|
| 79 |
+
StreamplotSet
|
| 80 |
+
Container object with attributes
|
| 81 |
+
|
| 82 |
+
- ``lines``: `.LineCollection` of streamlines
|
| 83 |
+
|
| 84 |
+
- ``arrows``: `.PatchCollection` containing `.FancyArrowPatch`
|
| 85 |
+
objects representing the arrows half-way along streamlines.
|
| 86 |
+
|
| 87 |
+
This container will probably change in the future to allow changes
|
| 88 |
+
to the colormap, alpha, etc. for both lines and arrows, but these
|
| 89 |
+
changes should be backward compatible.
|
| 90 |
+
"""
|
| 91 |
+
grid = Grid(x, y)
|
| 92 |
+
mask = StreamMask(density)
|
| 93 |
+
dmap = DomainMap(grid, mask)
|
| 94 |
+
|
| 95 |
+
if zorder is None:
|
| 96 |
+
zorder = mlines.Line2D.zorder
|
| 97 |
+
|
| 98 |
+
# default to data coordinates
|
| 99 |
+
if transform is None:
|
| 100 |
+
transform = axes.transData
|
| 101 |
+
|
| 102 |
+
if color is None:
|
| 103 |
+
color = axes._get_lines.get_next_color()
|
| 104 |
+
|
| 105 |
+
if linewidth is None:
|
| 106 |
+
linewidth = mpl.rcParams['lines.linewidth']
|
| 107 |
+
|
| 108 |
+
line_kw = {}
|
| 109 |
+
arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)
|
| 110 |
+
|
| 111 |
+
_api.check_in_list(['both', 'forward', 'backward'],
|
| 112 |
+
integration_direction=integration_direction)
|
| 113 |
+
|
| 114 |
+
if integration_direction == 'both':
|
| 115 |
+
maxlength /= 2.
|
| 116 |
+
|
| 117 |
+
use_multicolor_lines = isinstance(color, np.ndarray)
|
| 118 |
+
if use_multicolor_lines:
|
| 119 |
+
if color.shape != grid.shape:
|
| 120 |
+
raise ValueError("If 'color' is given, it must match the shape of "
|
| 121 |
+
"the (x, y) grid")
|
| 122 |
+
line_colors = [[]] # Empty entry allows concatenation of zero arrays.
|
| 123 |
+
color = np.ma.masked_invalid(color)
|
| 124 |
+
else:
|
| 125 |
+
line_kw['color'] = color
|
| 126 |
+
arrow_kw['color'] = color
|
| 127 |
+
|
| 128 |
+
if isinstance(linewidth, np.ndarray):
|
| 129 |
+
if linewidth.shape != grid.shape:
|
| 130 |
+
raise ValueError("If 'linewidth' is given, it must match the "
|
| 131 |
+
"shape of the (x, y) grid")
|
| 132 |
+
line_kw['linewidth'] = []
|
| 133 |
+
else:
|
| 134 |
+
line_kw['linewidth'] = linewidth
|
| 135 |
+
arrow_kw['linewidth'] = linewidth
|
| 136 |
+
|
| 137 |
+
line_kw['zorder'] = zorder
|
| 138 |
+
arrow_kw['zorder'] = zorder
|
| 139 |
+
|
| 140 |
+
# Sanity checks.
|
| 141 |
+
if u.shape != grid.shape or v.shape != grid.shape:
|
| 142 |
+
raise ValueError("'u' and 'v' must match the shape of the (x, y) grid")
|
| 143 |
+
|
| 144 |
+
u = np.ma.masked_invalid(u)
|
| 145 |
+
v = np.ma.masked_invalid(v)
|
| 146 |
+
|
| 147 |
+
integrate = _get_integrator(u, v, dmap, minlength, maxlength,
|
| 148 |
+
integration_direction)
|
| 149 |
+
|
| 150 |
+
trajectories = []
|
| 151 |
+
if start_points is None:
|
| 152 |
+
for xm, ym in _gen_starting_points(mask.shape):
|
| 153 |
+
if mask[ym, xm] == 0:
|
| 154 |
+
xg, yg = dmap.mask2grid(xm, ym)
|
| 155 |
+
t = integrate(xg, yg, broken_streamlines)
|
| 156 |
+
if t is not None:
|
| 157 |
+
trajectories.append(t)
|
| 158 |
+
else:
|
| 159 |
+
sp2 = np.asanyarray(start_points, dtype=float).copy()
|
| 160 |
+
|
| 161 |
+
# Check if start_points are outside the data boundaries
|
| 162 |
+
for xs, ys in sp2:
|
| 163 |
+
if not (grid.x_origin <= xs <= grid.x_origin + grid.width and
|
| 164 |
+
grid.y_origin <= ys <= grid.y_origin + grid.height):
|
| 165 |
+
raise ValueError(f"Starting point ({xs}, {ys}) outside of "
|
| 166 |
+
"data boundaries")
|
| 167 |
+
|
| 168 |
+
# Convert start_points from data to array coords
|
| 169 |
+
# Shift the seed points from the bottom left of the data so that
|
| 170 |
+
# data2grid works properly.
|
| 171 |
+
sp2[:, 0] -= grid.x_origin
|
| 172 |
+
sp2[:, 1] -= grid.y_origin
|
| 173 |
+
|
| 174 |
+
for xs, ys in sp2:
|
| 175 |
+
xg, yg = dmap.data2grid(xs, ys)
|
| 176 |
+
# Floating point issues can cause xg, yg to be slightly out of
|
| 177 |
+
# bounds for xs, ys on the upper boundaries. Because we have
|
| 178 |
+
# already checked that the starting points are within the original
|
| 179 |
+
# grid, clip the xg, yg to the grid to work around this issue
|
| 180 |
+
xg = np.clip(xg, 0, grid.nx - 1)
|
| 181 |
+
yg = np.clip(yg, 0, grid.ny - 1)
|
| 182 |
+
|
| 183 |
+
t = integrate(xg, yg, broken_streamlines)
|
| 184 |
+
if t is not None:
|
| 185 |
+
trajectories.append(t)
|
| 186 |
+
|
| 187 |
+
if use_multicolor_lines:
|
| 188 |
+
if norm is None:
|
| 189 |
+
norm = mcolors.Normalize(color.min(), color.max())
|
| 190 |
+
cmap = cm._ensure_cmap(cmap)
|
| 191 |
+
|
| 192 |
+
streamlines = []
|
| 193 |
+
arrows = []
|
| 194 |
+
for t in trajectories:
|
| 195 |
+
tgx, tgy = t.T
|
| 196 |
+
# Rescale from grid-coordinates to data-coordinates.
|
| 197 |
+
tx, ty = dmap.grid2data(tgx, tgy)
|
| 198 |
+
tx += grid.x_origin
|
| 199 |
+
ty += grid.y_origin
|
| 200 |
+
|
| 201 |
+
# Create multiple tiny segments if varying width or color is given
|
| 202 |
+
if isinstance(linewidth, np.ndarray) or use_multicolor_lines:
|
| 203 |
+
points = np.transpose([tx, ty]).reshape(-1, 1, 2)
|
| 204 |
+
streamlines.extend(np.hstack([points[:-1], points[1:]]))
|
| 205 |
+
else:
|
| 206 |
+
points = np.transpose([tx, ty])
|
| 207 |
+
streamlines.append(points)
|
| 208 |
+
|
| 209 |
+
# Add arrows halfway along each trajectory.
|
| 210 |
+
s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty)))
|
| 211 |
+
n = np.searchsorted(s, s[-1] / 2.)
|
| 212 |
+
arrow_tail = (tx[n], ty[n])
|
| 213 |
+
arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
|
| 214 |
+
|
| 215 |
+
if isinstance(linewidth, np.ndarray):
|
| 216 |
+
line_widths = interpgrid(linewidth, tgx, tgy)[:-1]
|
| 217 |
+
line_kw['linewidth'].extend(line_widths)
|
| 218 |
+
arrow_kw['linewidth'] = line_widths[n]
|
| 219 |
+
|
| 220 |
+
if use_multicolor_lines:
|
| 221 |
+
color_values = interpgrid(color, tgx, tgy)[:-1]
|
| 222 |
+
line_colors.append(color_values)
|
| 223 |
+
arrow_kw['color'] = cmap(norm(color_values[n]))
|
| 224 |
+
|
| 225 |
+
p = patches.FancyArrowPatch(
|
| 226 |
+
arrow_tail, arrow_head, transform=transform, **arrow_kw)
|
| 227 |
+
arrows.append(p)
|
| 228 |
+
|
| 229 |
+
lc = mcollections.LineCollection(
|
| 230 |
+
streamlines, transform=transform, **line_kw)
|
| 231 |
+
lc.sticky_edges.x[:] = [grid.x_origin, grid.x_origin + grid.width]
|
| 232 |
+
lc.sticky_edges.y[:] = [grid.y_origin, grid.y_origin + grid.height]
|
| 233 |
+
if use_multicolor_lines:
|
| 234 |
+
lc.set_array(np.ma.hstack(line_colors))
|
| 235 |
+
lc.set_cmap(cmap)
|
| 236 |
+
lc.set_norm(norm)
|
| 237 |
+
axes.add_collection(lc)
|
| 238 |
+
|
| 239 |
+
ac = mcollections.PatchCollection(arrows)
|
| 240 |
+
# Adding the collection itself is broken; see #2341.
|
| 241 |
+
for p in arrows:
|
| 242 |
+
axes.add_patch(p)
|
| 243 |
+
|
| 244 |
+
axes.autoscale_view()
|
| 245 |
+
stream_container = StreamplotSet(lc, ac)
|
| 246 |
+
return stream_container
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class StreamplotSet:
|
| 250 |
+
|
| 251 |
+
def __init__(self, lines, arrows):
|
| 252 |
+
self.lines = lines
|
| 253 |
+
self.arrows = arrows
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# Coordinate definitions
|
| 257 |
+
# ========================
|
| 258 |
+
|
| 259 |
+
class DomainMap:
|
| 260 |
+
"""
|
| 261 |
+
Map representing different coordinate systems.
|
| 262 |
+
|
| 263 |
+
Coordinate definitions:
|
| 264 |
+
|
| 265 |
+
* axes-coordinates goes from 0 to 1 in the domain.
|
| 266 |
+
* data-coordinates are specified by the input x-y coordinates.
|
| 267 |
+
* grid-coordinates goes from 0 to N and 0 to M for an N x M grid,
|
| 268 |
+
where N and M match the shape of the input data.
|
| 269 |
+
* mask-coordinates goes from 0 to N and 0 to M for an N x M mask,
|
| 270 |
+
where N and M are user-specified to control the density of streamlines.
|
| 271 |
+
|
| 272 |
+
This class also has methods for adding trajectories to the StreamMask.
|
| 273 |
+
Before adding a trajectory, run `start_trajectory` to keep track of regions
|
| 274 |
+
crossed by a given trajectory. Later, if you decide the trajectory is bad
|
| 275 |
+
(e.g., if the trajectory is very short) just call `undo_trajectory`.
|
| 276 |
+
"""
|
| 277 |
+
|
| 278 |
+
def __init__(self, grid, mask):
|
| 279 |
+
self.grid = grid
|
| 280 |
+
self.mask = mask
|
| 281 |
+
# Constants for conversion between grid- and mask-coordinates
|
| 282 |
+
self.x_grid2mask = (mask.nx - 1) / (grid.nx - 1)
|
| 283 |
+
self.y_grid2mask = (mask.ny - 1) / (grid.ny - 1)
|
| 284 |
+
|
| 285 |
+
self.x_mask2grid = 1. / self.x_grid2mask
|
| 286 |
+
self.y_mask2grid = 1. / self.y_grid2mask
|
| 287 |
+
|
| 288 |
+
self.x_data2grid = 1. / grid.dx
|
| 289 |
+
self.y_data2grid = 1. / grid.dy
|
| 290 |
+
|
| 291 |
+
def grid2mask(self, xi, yi):
|
| 292 |
+
"""Return nearest space in mask-coords from given grid-coords."""
|
| 293 |
+
return round(xi * self.x_grid2mask), round(yi * self.y_grid2mask)
|
| 294 |
+
|
| 295 |
+
def mask2grid(self, xm, ym):
|
| 296 |
+
return xm * self.x_mask2grid, ym * self.y_mask2grid
|
| 297 |
+
|
| 298 |
+
def data2grid(self, xd, yd):
|
| 299 |
+
return xd * self.x_data2grid, yd * self.y_data2grid
|
| 300 |
+
|
| 301 |
+
def grid2data(self, xg, yg):
|
| 302 |
+
return xg / self.x_data2grid, yg / self.y_data2grid
|
| 303 |
+
|
| 304 |
+
def start_trajectory(self, xg, yg, broken_streamlines=True):
|
| 305 |
+
xm, ym = self.grid2mask(xg, yg)
|
| 306 |
+
self.mask._start_trajectory(xm, ym, broken_streamlines)
|
| 307 |
+
|
| 308 |
+
def reset_start_point(self, xg, yg):
|
| 309 |
+
xm, ym = self.grid2mask(xg, yg)
|
| 310 |
+
self.mask._current_xy = (xm, ym)
|
| 311 |
+
|
| 312 |
+
def update_trajectory(self, xg, yg, broken_streamlines=True):
|
| 313 |
+
if not self.grid.within_grid(xg, yg):
|
| 314 |
+
raise InvalidIndexError
|
| 315 |
+
xm, ym = self.grid2mask(xg, yg)
|
| 316 |
+
self.mask._update_trajectory(xm, ym, broken_streamlines)
|
| 317 |
+
|
| 318 |
+
def undo_trajectory(self):
|
| 319 |
+
self.mask._undo_trajectory()
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class Grid:
|
| 323 |
+
"""Grid of data."""
|
| 324 |
+
def __init__(self, x, y):
|
| 325 |
+
|
| 326 |
+
if np.ndim(x) == 1:
|
| 327 |
+
pass
|
| 328 |
+
elif np.ndim(x) == 2:
|
| 329 |
+
x_row = x[0]
|
| 330 |
+
if not np.allclose(x_row, x):
|
| 331 |
+
raise ValueError("The rows of 'x' must be equal")
|
| 332 |
+
x = x_row
|
| 333 |
+
else:
|
| 334 |
+
raise ValueError("'x' can have at maximum 2 dimensions")
|
| 335 |
+
|
| 336 |
+
if np.ndim(y) == 1:
|
| 337 |
+
pass
|
| 338 |
+
elif np.ndim(y) == 2:
|
| 339 |
+
yt = np.transpose(y) # Also works for nested lists.
|
| 340 |
+
y_col = yt[0]
|
| 341 |
+
if not np.allclose(y_col, yt):
|
| 342 |
+
raise ValueError("The columns of 'y' must be equal")
|
| 343 |
+
y = y_col
|
| 344 |
+
else:
|
| 345 |
+
raise ValueError("'y' can have at maximum 2 dimensions")
|
| 346 |
+
|
| 347 |
+
if not (np.diff(x) > 0).all():
|
| 348 |
+
raise ValueError("'x' must be strictly increasing")
|
| 349 |
+
if not (np.diff(y) > 0).all():
|
| 350 |
+
raise ValueError("'y' must be strictly increasing")
|
| 351 |
+
|
| 352 |
+
self.nx = len(x)
|
| 353 |
+
self.ny = len(y)
|
| 354 |
+
|
| 355 |
+
self.dx = x[1] - x[0]
|
| 356 |
+
self.dy = y[1] - y[0]
|
| 357 |
+
|
| 358 |
+
self.x_origin = x[0]
|
| 359 |
+
self.y_origin = y[0]
|
| 360 |
+
|
| 361 |
+
self.width = x[-1] - x[0]
|
| 362 |
+
self.height = y[-1] - y[0]
|
| 363 |
+
|
| 364 |
+
if not np.allclose(np.diff(x), self.width / (self.nx - 1)):
|
| 365 |
+
raise ValueError("'x' values must be equally spaced")
|
| 366 |
+
if not np.allclose(np.diff(y), self.height / (self.ny - 1)):
|
| 367 |
+
raise ValueError("'y' values must be equally spaced")
|
| 368 |
+
|
| 369 |
+
@property
|
| 370 |
+
def shape(self):
|
| 371 |
+
return self.ny, self.nx
|
| 372 |
+
|
| 373 |
+
def within_grid(self, xi, yi):
|
| 374 |
+
"""Return whether (*xi*, *yi*) is a valid index of the grid."""
|
| 375 |
+
# Note that xi/yi can be floats; so, for example, we can't simply check
|
| 376 |
+
# `xi < self.nx` since *xi* can be `self.nx - 1 < xi < self.nx`
|
| 377 |
+
return 0 <= xi <= self.nx - 1 and 0 <= yi <= self.ny - 1
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class StreamMask:
|
| 381 |
+
"""
|
| 382 |
+
Mask to keep track of discrete regions crossed by streamlines.
|
| 383 |
+
|
| 384 |
+
The resolution of this grid determines the approximate spacing between
|
| 385 |
+
trajectories. Streamlines are only allowed to pass through zeroed cells:
|
| 386 |
+
When a streamline enters a cell, that cell is set to 1, and no new
|
| 387 |
+
streamlines are allowed to enter.
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
def __init__(self, density):
|
| 391 |
+
try:
|
| 392 |
+
self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int)
|
| 393 |
+
except ValueError as err:
|
| 394 |
+
raise ValueError("'density' must be a scalar or be of length "
|
| 395 |
+
"2") from err
|
| 396 |
+
if self.nx < 0 or self.ny < 0:
|
| 397 |
+
raise ValueError("'density' must be positive")
|
| 398 |
+
self._mask = np.zeros((self.ny, self.nx))
|
| 399 |
+
self.shape = self._mask.shape
|
| 400 |
+
|
| 401 |
+
self._current_xy = None
|
| 402 |
+
|
| 403 |
+
def __getitem__(self, args):
|
| 404 |
+
return self._mask[args]
|
| 405 |
+
|
| 406 |
+
def _start_trajectory(self, xm, ym, broken_streamlines=True):
|
| 407 |
+
"""Start recording streamline trajectory"""
|
| 408 |
+
self._traj = []
|
| 409 |
+
self._update_trajectory(xm, ym, broken_streamlines)
|
| 410 |
+
|
| 411 |
+
def _undo_trajectory(self):
|
| 412 |
+
"""Remove current trajectory from mask"""
|
| 413 |
+
for t in self._traj:
|
| 414 |
+
self._mask[t] = 0
|
| 415 |
+
|
| 416 |
+
def _update_trajectory(self, xm, ym, broken_streamlines=True):
|
| 417 |
+
"""
|
| 418 |
+
Update current trajectory position in mask.
|
| 419 |
+
|
| 420 |
+
If the new position has already been filled, raise `InvalidIndexError`.
|
| 421 |
+
"""
|
| 422 |
+
if self._current_xy != (xm, ym):
|
| 423 |
+
if self[ym, xm] == 0:
|
| 424 |
+
self._traj.append((ym, xm))
|
| 425 |
+
self._mask[ym, xm] = 1
|
| 426 |
+
self._current_xy = (xm, ym)
|
| 427 |
+
else:
|
| 428 |
+
if broken_streamlines:
|
| 429 |
+
raise InvalidIndexError
|
| 430 |
+
else:
|
| 431 |
+
pass
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
class InvalidIndexError(Exception):
|
| 435 |
+
pass
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
class TerminateTrajectory(Exception):
|
| 439 |
+
pass
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
# Integrator definitions
|
| 443 |
+
# =======================
|
| 444 |
+
|
| 445 |
+
def _get_integrator(u, v, dmap, minlength, maxlength, integration_direction):
|
| 446 |
+
|
| 447 |
+
# rescale velocity onto grid-coordinates for integrations.
|
| 448 |
+
u, v = dmap.data2grid(u, v)
|
| 449 |
+
|
| 450 |
+
# speed (path length) will be in axes-coordinates
|
| 451 |
+
u_ax = u / (dmap.grid.nx - 1)
|
| 452 |
+
v_ax = v / (dmap.grid.ny - 1)
|
| 453 |
+
speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2)
|
| 454 |
+
|
| 455 |
+
def forward_time(xi, yi):
|
| 456 |
+
if not dmap.grid.within_grid(xi, yi):
|
| 457 |
+
raise OutOfBounds
|
| 458 |
+
ds_dt = interpgrid(speed, xi, yi)
|
| 459 |
+
if ds_dt == 0:
|
| 460 |
+
raise TerminateTrajectory()
|
| 461 |
+
dt_ds = 1. / ds_dt
|
| 462 |
+
ui = interpgrid(u, xi, yi)
|
| 463 |
+
vi = interpgrid(v, xi, yi)
|
| 464 |
+
return ui * dt_ds, vi * dt_ds
|
| 465 |
+
|
| 466 |
+
def backward_time(xi, yi):
|
| 467 |
+
dxi, dyi = forward_time(xi, yi)
|
| 468 |
+
return -dxi, -dyi
|
| 469 |
+
|
| 470 |
+
def integrate(x0, y0, broken_streamlines=True):
|
| 471 |
+
"""
|
| 472 |
+
Return x, y grid-coordinates of trajectory based on starting point.
|
| 473 |
+
|
| 474 |
+
Integrate both forward and backward in time from starting point in
|
| 475 |
+
grid coordinates.
|
| 476 |
+
|
| 477 |
+
Integration is terminated when a trajectory reaches a domain boundary
|
| 478 |
+
or when it crosses into an already occupied cell in the StreamMask. The
|
| 479 |
+
resulting trajectory is None if it is shorter than `minlength`.
|
| 480 |
+
"""
|
| 481 |
+
|
| 482 |
+
stotal, xy_traj = 0., []
|
| 483 |
+
|
| 484 |
+
try:
|
| 485 |
+
dmap.start_trajectory(x0, y0, broken_streamlines)
|
| 486 |
+
except InvalidIndexError:
|
| 487 |
+
return None
|
| 488 |
+
if integration_direction in ['both', 'backward']:
|
| 489 |
+
s, xyt = _integrate_rk12(x0, y0, dmap, backward_time, maxlength,
|
| 490 |
+
broken_streamlines)
|
| 491 |
+
stotal += s
|
| 492 |
+
xy_traj += xyt[::-1]
|
| 493 |
+
|
| 494 |
+
if integration_direction in ['both', 'forward']:
|
| 495 |
+
dmap.reset_start_point(x0, y0)
|
| 496 |
+
s, xyt = _integrate_rk12(x0, y0, dmap, forward_time, maxlength,
|
| 497 |
+
broken_streamlines)
|
| 498 |
+
stotal += s
|
| 499 |
+
xy_traj += xyt[1:]
|
| 500 |
+
|
| 501 |
+
if stotal > minlength:
|
| 502 |
+
return np.broadcast_arrays(xy_traj, np.empty((1, 2)))[0]
|
| 503 |
+
else: # reject short trajectories
|
| 504 |
+
dmap.undo_trajectory()
|
| 505 |
+
return None
|
| 506 |
+
|
| 507 |
+
return integrate
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
class OutOfBounds(IndexError):
|
| 511 |
+
pass
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _integrate_rk12(x0, y0, dmap, f, maxlength, broken_streamlines=True):
|
| 515 |
+
"""
|
| 516 |
+
2nd-order Runge-Kutta algorithm with adaptive step size.
|
| 517 |
+
|
| 518 |
+
This method is also referred to as the improved Euler's method, or Heun's
|
| 519 |
+
method. This method is favored over higher-order methods because:
|
| 520 |
+
|
| 521 |
+
1. To get decent looking trajectories and to sample every mask cell
|
| 522 |
+
on the trajectory we need a small timestep, so a lower order
|
| 523 |
+
solver doesn't hurt us unless the data is *very* high resolution.
|
| 524 |
+
In fact, for cases where the user inputs
|
| 525 |
+
data smaller or of similar grid size to the mask grid, the higher
|
| 526 |
+
order corrections are negligible because of the very fast linear
|
| 527 |
+
interpolation used in `interpgrid`.
|
| 528 |
+
|
| 529 |
+
2. For high resolution input data (i.e. beyond the mask
|
| 530 |
+
resolution), we must reduce the timestep. Therefore, an adaptive
|
| 531 |
+
timestep is more suited to the problem as this would be very hard
|
| 532 |
+
to judge automatically otherwise.
|
| 533 |
+
|
| 534 |
+
This integrator is about 1.5 - 2x as fast as RK4 and RK45 solvers (using
|
| 535 |
+
similar Python implementations) in most setups.
|
| 536 |
+
"""
|
| 537 |
+
# This error is below that needed to match the RK4 integrator. It
|
| 538 |
+
# is set for visual reasons -- too low and corners start
|
| 539 |
+
# appearing ugly and jagged. Can be tuned.
|
| 540 |
+
maxerror = 0.003
|
| 541 |
+
|
| 542 |
+
# This limit is important (for all integrators) to avoid the
|
| 543 |
+
# trajectory skipping some mask cells. We could relax this
|
| 544 |
+
# condition if we use the code which is commented out below to
|
| 545 |
+
# increment the location gradually. However, due to the efficient
|
| 546 |
+
# nature of the interpolation, this doesn't boost speed by much
|
| 547 |
+
# for quite a bit of complexity.
|
| 548 |
+
maxds = min(1. / dmap.mask.nx, 1. / dmap.mask.ny, 0.1)
|
| 549 |
+
|
| 550 |
+
ds = maxds
|
| 551 |
+
stotal = 0
|
| 552 |
+
xi = x0
|
| 553 |
+
yi = y0
|
| 554 |
+
xyf_traj = []
|
| 555 |
+
|
| 556 |
+
while True:
|
| 557 |
+
try:
|
| 558 |
+
if dmap.grid.within_grid(xi, yi):
|
| 559 |
+
xyf_traj.append((xi, yi))
|
| 560 |
+
else:
|
| 561 |
+
raise OutOfBounds
|
| 562 |
+
|
| 563 |
+
# Compute the two intermediate gradients.
|
| 564 |
+
# f should raise OutOfBounds if the locations given are
|
| 565 |
+
# outside the grid.
|
| 566 |
+
k1x, k1y = f(xi, yi)
|
| 567 |
+
k2x, k2y = f(xi + ds * k1x, yi + ds * k1y)
|
| 568 |
+
|
| 569 |
+
except OutOfBounds:
|
| 570 |
+
# Out of the domain during this step.
|
| 571 |
+
# Take an Euler step to the boundary to improve neatness
|
| 572 |
+
# unless the trajectory is currently empty.
|
| 573 |
+
if xyf_traj:
|
| 574 |
+
ds, xyf_traj = _euler_step(xyf_traj, dmap, f)
|
| 575 |
+
stotal += ds
|
| 576 |
+
break
|
| 577 |
+
except TerminateTrajectory:
|
| 578 |
+
break
|
| 579 |
+
|
| 580 |
+
dx1 = ds * k1x
|
| 581 |
+
dy1 = ds * k1y
|
| 582 |
+
dx2 = ds * 0.5 * (k1x + k2x)
|
| 583 |
+
dy2 = ds * 0.5 * (k1y + k2y)
|
| 584 |
+
|
| 585 |
+
ny, nx = dmap.grid.shape
|
| 586 |
+
# Error is normalized to the axes coordinates
|
| 587 |
+
error = np.hypot((dx2 - dx1) / (nx - 1), (dy2 - dy1) / (ny - 1))
|
| 588 |
+
|
| 589 |
+
# Only save step if within error tolerance
|
| 590 |
+
if error < maxerror:
|
| 591 |
+
xi += dx2
|
| 592 |
+
yi += dy2
|
| 593 |
+
try:
|
| 594 |
+
dmap.update_trajectory(xi, yi, broken_streamlines)
|
| 595 |
+
except InvalidIndexError:
|
| 596 |
+
break
|
| 597 |
+
if stotal + ds > maxlength:
|
| 598 |
+
break
|
| 599 |
+
stotal += ds
|
| 600 |
+
|
| 601 |
+
# recalculate stepsize based on step error
|
| 602 |
+
if error == 0:
|
| 603 |
+
ds = maxds
|
| 604 |
+
else:
|
| 605 |
+
ds = min(maxds, 0.85 * ds * (maxerror / error) ** 0.5)
|
| 606 |
+
|
| 607 |
+
return stotal, xyf_traj
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def _euler_step(xyf_traj, dmap, f):
|
| 611 |
+
"""Simple Euler integration step that extends streamline to boundary."""
|
| 612 |
+
ny, nx = dmap.grid.shape
|
| 613 |
+
xi, yi = xyf_traj[-1]
|
| 614 |
+
cx, cy = f(xi, yi)
|
| 615 |
+
if cx == 0:
|
| 616 |
+
dsx = np.inf
|
| 617 |
+
elif cx < 0:
|
| 618 |
+
dsx = xi / -cx
|
| 619 |
+
else:
|
| 620 |
+
dsx = (nx - 1 - xi) / cx
|
| 621 |
+
if cy == 0:
|
| 622 |
+
dsy = np.inf
|
| 623 |
+
elif cy < 0:
|
| 624 |
+
dsy = yi / -cy
|
| 625 |
+
else:
|
| 626 |
+
dsy = (ny - 1 - yi) / cy
|
| 627 |
+
ds = min(dsx, dsy)
|
| 628 |
+
xyf_traj.append((xi + cx * ds, yi + cy * ds))
|
| 629 |
+
return ds, xyf_traj
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
# Utility functions
|
| 633 |
+
# ========================
|
| 634 |
+
|
| 635 |
+
def interpgrid(a, xi, yi):
|
| 636 |
+
"""Fast 2D, linear interpolation on an integer grid"""
|
| 637 |
+
|
| 638 |
+
Ny, Nx = np.shape(a)
|
| 639 |
+
if isinstance(xi, np.ndarray):
|
| 640 |
+
x = xi.astype(int)
|
| 641 |
+
y = yi.astype(int)
|
| 642 |
+
# Check that xn, yn don't exceed max index
|
| 643 |
+
xn = np.clip(x + 1, 0, Nx - 1)
|
| 644 |
+
yn = np.clip(y + 1, 0, Ny - 1)
|
| 645 |
+
else:
|
| 646 |
+
x = int(xi)
|
| 647 |
+
y = int(yi)
|
| 648 |
+
# conditional is faster than clipping for integers
|
| 649 |
+
if x == (Nx - 1):
|
| 650 |
+
xn = x
|
| 651 |
+
else:
|
| 652 |
+
xn = x + 1
|
| 653 |
+
if y == (Ny - 1):
|
| 654 |
+
yn = y
|
| 655 |
+
else:
|
| 656 |
+
yn = y + 1
|
| 657 |
+
|
| 658 |
+
a00 = a[y, x]
|
| 659 |
+
a01 = a[y, xn]
|
| 660 |
+
a10 = a[yn, x]
|
| 661 |
+
a11 = a[yn, xn]
|
| 662 |
+
xt = xi - x
|
| 663 |
+
yt = yi - y
|
| 664 |
+
a0 = a00 * (1 - xt) + a01 * xt
|
| 665 |
+
a1 = a10 * (1 - xt) + a11 * xt
|
| 666 |
+
ai = a0 * (1 - yt) + a1 * yt
|
| 667 |
+
|
| 668 |
+
if not isinstance(xi, np.ndarray):
|
| 669 |
+
if np.ma.is_masked(ai):
|
| 670 |
+
raise TerminateTrajectory
|
| 671 |
+
|
| 672 |
+
return ai
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def _gen_starting_points(shape):
|
| 676 |
+
"""
|
| 677 |
+
Yield starting points for streamlines.
|
| 678 |
+
|
| 679 |
+
Trying points on the boundary first gives higher quality streamlines.
|
| 680 |
+
This algorithm starts with a point on the mask corner and spirals inward.
|
| 681 |
+
This algorithm is inefficient, but fast compared to rest of streamplot.
|
| 682 |
+
"""
|
| 683 |
+
ny, nx = shape
|
| 684 |
+
xfirst = 0
|
| 685 |
+
yfirst = 1
|
| 686 |
+
xlast = nx - 1
|
| 687 |
+
ylast = ny - 1
|
| 688 |
+
x, y = 0, 0
|
| 689 |
+
direction = 'right'
|
| 690 |
+
for i in range(nx * ny):
|
| 691 |
+
yield x, y
|
| 692 |
+
|
| 693 |
+
if direction == 'right':
|
| 694 |
+
x += 1
|
| 695 |
+
if x >= xlast:
|
| 696 |
+
xlast -= 1
|
| 697 |
+
direction = 'up'
|
| 698 |
+
elif direction == 'up':
|
| 699 |
+
y += 1
|
| 700 |
+
if y >= ylast:
|
| 701 |
+
ylast -= 1
|
| 702 |
+
direction = 'left'
|
| 703 |
+
elif direction == 'left':
|
| 704 |
+
x -= 1
|
| 705 |
+
if x <= xfirst:
|
| 706 |
+
xfirst += 1
|
| 707 |
+
direction = 'down'
|
| 708 |
+
elif direction == 'down':
|
| 709 |
+
y -= 1
|
| 710 |
+
if y <= yfirst:
|
| 711 |
+
yfirst += 1
|
| 712 |
+
direction = 'right'
|
parrot/lib/python3.10/site-packages/matplotlib/streamplot.pyi
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib.axes import Axes
|
| 2 |
+
from matplotlib.colors import Normalize, Colormap
|
| 3 |
+
from matplotlib.collections import LineCollection, PatchCollection
|
| 4 |
+
from matplotlib.patches import ArrowStyle
|
| 5 |
+
from matplotlib.transforms import Transform
|
| 6 |
+
|
| 7 |
+
from typing import Literal
|
| 8 |
+
from numpy.typing import ArrayLike
|
| 9 |
+
from .typing import ColorType
|
| 10 |
+
|
| 11 |
+
def streamplot(
|
| 12 |
+
axes: Axes,
|
| 13 |
+
x: ArrayLike,
|
| 14 |
+
y: ArrayLike,
|
| 15 |
+
u: ArrayLike,
|
| 16 |
+
v: ArrayLike,
|
| 17 |
+
density: float | tuple[float, float] = ...,
|
| 18 |
+
linewidth: float | ArrayLike | None = ...,
|
| 19 |
+
color: ColorType | ArrayLike | None = ...,
|
| 20 |
+
cmap: str | Colormap | None = ...,
|
| 21 |
+
norm: str | Normalize | None = ...,
|
| 22 |
+
arrowsize: float = ...,
|
| 23 |
+
arrowstyle: str | ArrowStyle = ...,
|
| 24 |
+
minlength: float = ...,
|
| 25 |
+
transform: Transform | None = ...,
|
| 26 |
+
zorder: float | None = ...,
|
| 27 |
+
start_points: ArrayLike | None = ...,
|
| 28 |
+
maxlength: float = ...,
|
| 29 |
+
integration_direction: Literal["forward", "backward", "both"] = ...,
|
| 30 |
+
broken_streamlines: bool = ...,
|
| 31 |
+
) -> StreamplotSet: ...
|
| 32 |
+
|
| 33 |
+
class StreamplotSet:
|
| 34 |
+
lines: LineCollection
|
| 35 |
+
arrows: PatchCollection
|
| 36 |
+
def __init__(self, lines: LineCollection, arrows: PatchCollection) -> None: ...
|
| 37 |
+
|
| 38 |
+
class DomainMap:
|
| 39 |
+
grid: Grid
|
| 40 |
+
mask: StreamMask
|
| 41 |
+
x_grid2mask: float
|
| 42 |
+
y_grid2mask: float
|
| 43 |
+
x_mask2grid: float
|
| 44 |
+
y_mask2grid: float
|
| 45 |
+
x_data2grid: float
|
| 46 |
+
y_data2grid: float
|
| 47 |
+
def __init__(self, grid: Grid, mask: StreamMask) -> None: ...
|
| 48 |
+
def grid2mask(self, xi: float, yi: float) -> tuple[int, int]: ...
|
| 49 |
+
def mask2grid(self, xm: float, ym: float) -> tuple[float, float]: ...
|
| 50 |
+
def data2grid(self, xd: float, yd: float) -> tuple[float, float]: ...
|
| 51 |
+
def grid2data(self, xg: float, yg: float) -> tuple[float, float]: ...
|
| 52 |
+
def start_trajectory(
|
| 53 |
+
self, xg: float, yg: float, broken_streamlines: bool = ...
|
| 54 |
+
) -> None: ...
|
| 55 |
+
def reset_start_point(self, xg: float, yg: float) -> None: ...
|
| 56 |
+
def update_trajectory(self, xg, yg, broken_streamlines: bool = ...) -> None: ...
|
| 57 |
+
def undo_trajectory(self) -> None: ...
|
| 58 |
+
|
| 59 |
+
class Grid:
|
| 60 |
+
nx: int
|
| 61 |
+
ny: int
|
| 62 |
+
dx: float
|
| 63 |
+
dy: float
|
| 64 |
+
x_origin: float
|
| 65 |
+
y_origin: float
|
| 66 |
+
width: float
|
| 67 |
+
height: float
|
| 68 |
+
def __init__(self, x: ArrayLike, y: ArrayLike) -> None: ...
|
| 69 |
+
@property
|
| 70 |
+
def shape(self) -> tuple[int, int]: ...
|
| 71 |
+
def within_grid(self, xi: float, yi: float) -> bool: ...
|
| 72 |
+
|
| 73 |
+
class StreamMask:
|
| 74 |
+
nx: int
|
| 75 |
+
ny: int
|
| 76 |
+
shape: tuple[int, int]
|
| 77 |
+
def __init__(self, density: float | tuple[float, float]) -> None: ...
|
| 78 |
+
def __getitem__(self, args): ...
|
| 79 |
+
|
| 80 |
+
class InvalidIndexError(Exception): ...
|
| 81 |
+
class TerminateTrajectory(Exception): ...
|
| 82 |
+
class OutOfBounds(IndexError): ...
|
parrot/lib/python3.10/site-packages/matplotlib/text.py
ADDED
|
@@ -0,0 +1,2027 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
def _get_textbox(text, renderer):
|
| 27 |
+
"""
|
| 28 |
+
Calculate the bounding box of the text.
|
| 29 |
+
|
| 30 |
+
The bbox position takes text rotation into account, but the width and
|
| 31 |
+
height are those of the unrotated box (unlike `.Text.get_window_extent`).
|
| 32 |
+
"""
|
| 33 |
+
# TODO : This function may move into the Text class as a method. As a
|
| 34 |
+
# matter of fact, the information from the _get_textbox function
|
| 35 |
+
# should be available during the Text._get_layout() call, which is
|
| 36 |
+
# called within the _get_textbox. So, it would better to move this
|
| 37 |
+
# function as a method with some refactoring of _get_layout method.
|
| 38 |
+
|
| 39 |
+
projected_xs = []
|
| 40 |
+
projected_ys = []
|
| 41 |
+
|
| 42 |
+
theta = np.deg2rad(text.get_rotation())
|
| 43 |
+
tr = Affine2D().rotate(-theta)
|
| 44 |
+
|
| 45 |
+
_, parts, d = text._get_layout(renderer)
|
| 46 |
+
|
| 47 |
+
for t, wh, x, y in parts:
|
| 48 |
+
w, h = wh
|
| 49 |
+
|
| 50 |
+
xt1, yt1 = tr.transform((x, y))
|
| 51 |
+
yt1 -= d
|
| 52 |
+
xt2, yt2 = xt1 + w, yt1 + h
|
| 53 |
+
|
| 54 |
+
projected_xs.extend([xt1, xt2])
|
| 55 |
+
projected_ys.extend([yt1, yt2])
|
| 56 |
+
|
| 57 |
+
xt_box, yt_box = min(projected_xs), min(projected_ys)
|
| 58 |
+
w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box
|
| 59 |
+
|
| 60 |
+
x_box, y_box = Affine2D().rotate(theta).transform((xt_box, yt_box))
|
| 61 |
+
|
| 62 |
+
return x_box, y_box, w_box, h_box
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi):
|
| 66 |
+
"""Call ``renderer.get_text_width_height_descent``, caching the results."""
|
| 67 |
+
# Cached based on a copy of fontprop so that later in-place mutations of
|
| 68 |
+
# the passed-in argument do not mess up the cache.
|
| 69 |
+
return _get_text_metrics_with_cache_impl(
|
| 70 |
+
weakref.ref(renderer), text, fontprop.copy(), ismath, dpi)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@functools.lru_cache(4096)
|
| 74 |
+
def _get_text_metrics_with_cache_impl(
|
| 75 |
+
renderer_ref, text, fontprop, ismath, dpi):
|
| 76 |
+
# dpi is unused, but participates in cache invalidation (via the renderer).
|
| 77 |
+
return renderer_ref().get_text_width_height_descent(text, fontprop, ismath)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@_docstring.interpd
|
| 81 |
+
@_api.define_aliases({
|
| 82 |
+
"color": ["c"],
|
| 83 |
+
"fontproperties": ["font", "font_properties"],
|
| 84 |
+
"fontfamily": ["family"],
|
| 85 |
+
"fontname": ["name"],
|
| 86 |
+
"fontsize": ["size"],
|
| 87 |
+
"fontstretch": ["stretch"],
|
| 88 |
+
"fontstyle": ["style"],
|
| 89 |
+
"fontvariant": ["variant"],
|
| 90 |
+
"fontweight": ["weight"],
|
| 91 |
+
"horizontalalignment": ["ha"],
|
| 92 |
+
"verticalalignment": ["va"],
|
| 93 |
+
"multialignment": ["ma"],
|
| 94 |
+
})
|
| 95 |
+
class Text(Artist):
|
| 96 |
+
"""Handle storing and drawing of text in window or data coordinates."""
|
| 97 |
+
|
| 98 |
+
zorder = 3
|
| 99 |
+
_charsize_cache = dict()
|
| 100 |
+
|
| 101 |
+
def __repr__(self):
|
| 102 |
+
return f"Text({self._x}, {self._y}, {self._text!r})"
|
| 103 |
+
|
| 104 |
+
def __init__(self,
|
| 105 |
+
x=0, y=0, text='', *,
|
| 106 |
+
color=None, # defaults to rc params
|
| 107 |
+
verticalalignment='baseline',
|
| 108 |
+
horizontalalignment='left',
|
| 109 |
+
multialignment=None,
|
| 110 |
+
fontproperties=None, # defaults to FontProperties()
|
| 111 |
+
rotation=None,
|
| 112 |
+
linespacing=None,
|
| 113 |
+
rotation_mode=None,
|
| 114 |
+
usetex=None, # defaults to rcParams['text.usetex']
|
| 115 |
+
wrap=False,
|
| 116 |
+
transform_rotates_text=False,
|
| 117 |
+
parse_math=None, # defaults to rcParams['text.parse_math']
|
| 118 |
+
antialiased=None, # defaults to rcParams['text.antialiased']
|
| 119 |
+
**kwargs
|
| 120 |
+
):
|
| 121 |
+
"""
|
| 122 |
+
Create a `.Text` instance at *x*, *y* with string *text*.
|
| 123 |
+
|
| 124 |
+
The text is aligned relative to the anchor point (*x*, *y*) according
|
| 125 |
+
to ``horizontalalignment`` (default: 'left') and ``verticalalignment``
|
| 126 |
+
(default: 'baseline'). See also
|
| 127 |
+
:doc:`/gallery/text_labels_and_annotations/text_alignment`.
|
| 128 |
+
|
| 129 |
+
While Text accepts the 'label' keyword argument, by default it is not
|
| 130 |
+
added to the handles of a legend.
|
| 131 |
+
|
| 132 |
+
Valid keyword arguments are:
|
| 133 |
+
|
| 134 |
+
%(Text:kwdoc)s
|
| 135 |
+
"""
|
| 136 |
+
super().__init__()
|
| 137 |
+
self._x, self._y = x, y
|
| 138 |
+
self._text = ''
|
| 139 |
+
self._reset_visual_defaults(
|
| 140 |
+
text=text,
|
| 141 |
+
color=color,
|
| 142 |
+
fontproperties=fontproperties,
|
| 143 |
+
usetex=usetex,
|
| 144 |
+
parse_math=parse_math,
|
| 145 |
+
wrap=wrap,
|
| 146 |
+
verticalalignment=verticalalignment,
|
| 147 |
+
horizontalalignment=horizontalalignment,
|
| 148 |
+
multialignment=multialignment,
|
| 149 |
+
rotation=rotation,
|
| 150 |
+
transform_rotates_text=transform_rotates_text,
|
| 151 |
+
linespacing=linespacing,
|
| 152 |
+
rotation_mode=rotation_mode,
|
| 153 |
+
antialiased=antialiased
|
| 154 |
+
)
|
| 155 |
+
self.update(kwargs)
|
| 156 |
+
|
| 157 |
+
def _reset_visual_defaults(
|
| 158 |
+
self,
|
| 159 |
+
text='',
|
| 160 |
+
color=None,
|
| 161 |
+
fontproperties=None,
|
| 162 |
+
usetex=None,
|
| 163 |
+
parse_math=None,
|
| 164 |
+
wrap=False,
|
| 165 |
+
verticalalignment='baseline',
|
| 166 |
+
horizontalalignment='left',
|
| 167 |
+
multialignment=None,
|
| 168 |
+
rotation=None,
|
| 169 |
+
transform_rotates_text=False,
|
| 170 |
+
linespacing=None,
|
| 171 |
+
rotation_mode=None,
|
| 172 |
+
antialiased=None
|
| 173 |
+
):
|
| 174 |
+
self.set_text(text)
|
| 175 |
+
self.set_color(mpl._val_or_rc(color, "text.color"))
|
| 176 |
+
self.set_fontproperties(fontproperties)
|
| 177 |
+
self.set_usetex(usetex)
|
| 178 |
+
self.set_parse_math(mpl._val_or_rc(parse_math, 'text.parse_math'))
|
| 179 |
+
self.set_wrap(wrap)
|
| 180 |
+
self.set_verticalalignment(verticalalignment)
|
| 181 |
+
self.set_horizontalalignment(horizontalalignment)
|
| 182 |
+
self._multialignment = multialignment
|
| 183 |
+
self.set_rotation(rotation)
|
| 184 |
+
self._transform_rotates_text = transform_rotates_text
|
| 185 |
+
self._bbox_patch = None # a FancyBboxPatch instance
|
| 186 |
+
self._renderer = None
|
| 187 |
+
if linespacing is None:
|
| 188 |
+
linespacing = 1.2 # Maybe use rcParam later.
|
| 189 |
+
self.set_linespacing(linespacing)
|
| 190 |
+
self.set_rotation_mode(rotation_mode)
|
| 191 |
+
self.set_antialiased(antialiased if antialiased is not None else
|
| 192 |
+
mpl.rcParams['text.antialiased'])
|
| 193 |
+
|
| 194 |
+
def update(self, kwargs):
|
| 195 |
+
# docstring inherited
|
| 196 |
+
ret = []
|
| 197 |
+
kwargs = cbook.normalize_kwargs(kwargs, Text)
|
| 198 |
+
sentinel = object() # bbox can be None, so use another sentinel.
|
| 199 |
+
# Update fontproperties first, as it has lowest priority.
|
| 200 |
+
fontproperties = kwargs.pop("fontproperties", sentinel)
|
| 201 |
+
if fontproperties is not sentinel:
|
| 202 |
+
ret.append(self.set_fontproperties(fontproperties))
|
| 203 |
+
# Update bbox last, as it depends on font properties.
|
| 204 |
+
bbox = kwargs.pop("bbox", sentinel)
|
| 205 |
+
ret.extend(super().update(kwargs))
|
| 206 |
+
if bbox is not sentinel:
|
| 207 |
+
ret.append(self.set_bbox(bbox))
|
| 208 |
+
return ret
|
| 209 |
+
|
| 210 |
+
def __getstate__(self):
|
| 211 |
+
d = super().__getstate__()
|
| 212 |
+
# remove the cached _renderer (if it exists)
|
| 213 |
+
d['_renderer'] = None
|
| 214 |
+
return d
|
| 215 |
+
|
| 216 |
+
def contains(self, mouseevent):
|
| 217 |
+
"""
|
| 218 |
+
Return whether the mouse event occurred inside the axis-aligned
|
| 219 |
+
bounding-box of the text.
|
| 220 |
+
"""
|
| 221 |
+
if (self._different_canvas(mouseevent) or not self.get_visible()
|
| 222 |
+
or self._renderer is None):
|
| 223 |
+
return False, {}
|
| 224 |
+
# Explicitly use Text.get_window_extent(self) and not
|
| 225 |
+
# self.get_window_extent() so that Annotation.contains does not
|
| 226 |
+
# accidentally cover the entire annotation bounding box.
|
| 227 |
+
bbox = Text.get_window_extent(self)
|
| 228 |
+
inside = (bbox.x0 <= mouseevent.x <= bbox.x1
|
| 229 |
+
and bbox.y0 <= mouseevent.y <= bbox.y1)
|
| 230 |
+
cattr = {}
|
| 231 |
+
# if the text has a surrounding patch, also check containment for it,
|
| 232 |
+
# and merge the results with the results for the text.
|
| 233 |
+
if self._bbox_patch:
|
| 234 |
+
patch_inside, patch_cattr = self._bbox_patch.contains(mouseevent)
|
| 235 |
+
inside = inside or patch_inside
|
| 236 |
+
cattr["bbox_patch"] = patch_cattr
|
| 237 |
+
return inside, cattr
|
| 238 |
+
|
| 239 |
+
def _get_xy_display(self):
|
| 240 |
+
"""
|
| 241 |
+
Get the (possibly unit converted) transformed x, y in display coords.
|
| 242 |
+
"""
|
| 243 |
+
x, y = self.get_unitless_position()
|
| 244 |
+
return self.get_transform().transform((x, y))
|
| 245 |
+
|
| 246 |
+
def _get_multialignment(self):
|
| 247 |
+
if self._multialignment is not None:
|
| 248 |
+
return self._multialignment
|
| 249 |
+
else:
|
| 250 |
+
return self._horizontalalignment
|
| 251 |
+
|
| 252 |
+
def _char_index_at(self, x):
|
| 253 |
+
"""
|
| 254 |
+
Calculate the index closest to the coordinate x in display space.
|
| 255 |
+
|
| 256 |
+
The position of text[index] is assumed to be the sum of the widths
|
| 257 |
+
of all preceding characters text[:index].
|
| 258 |
+
|
| 259 |
+
This works only on single line texts.
|
| 260 |
+
"""
|
| 261 |
+
if not self._text:
|
| 262 |
+
return 0
|
| 263 |
+
|
| 264 |
+
text = self._text
|
| 265 |
+
|
| 266 |
+
fontproperties = str(self._fontproperties)
|
| 267 |
+
if fontproperties not in Text._charsize_cache:
|
| 268 |
+
Text._charsize_cache[fontproperties] = dict()
|
| 269 |
+
|
| 270 |
+
charsize_cache = Text._charsize_cache[fontproperties]
|
| 271 |
+
for char in set(text):
|
| 272 |
+
if char not in charsize_cache:
|
| 273 |
+
self.set_text(char)
|
| 274 |
+
bb = self.get_window_extent()
|
| 275 |
+
charsize_cache[char] = bb.x1 - bb.x0
|
| 276 |
+
|
| 277 |
+
self.set_text(text)
|
| 278 |
+
bb = self.get_window_extent()
|
| 279 |
+
|
| 280 |
+
size_accum = np.cumsum([0] + [charsize_cache[x] for x in text])
|
| 281 |
+
std_x = x - bb.x0
|
| 282 |
+
return (np.abs(size_accum - std_x)).argmin()
|
| 283 |
+
|
| 284 |
+
def get_rotation(self):
|
| 285 |
+
"""Return the text angle in degrees between 0 and 360."""
|
| 286 |
+
if self.get_transform_rotates_text():
|
| 287 |
+
return self.get_transform().transform_angles(
|
| 288 |
+
[self._rotation], [self.get_unitless_position()]).item(0)
|
| 289 |
+
else:
|
| 290 |
+
return self._rotation
|
| 291 |
+
|
| 292 |
+
def get_transform_rotates_text(self):
|
| 293 |
+
"""
|
| 294 |
+
Return whether rotations of the transform affect the text direction.
|
| 295 |
+
"""
|
| 296 |
+
return self._transform_rotates_text
|
| 297 |
+
|
| 298 |
+
def set_rotation_mode(self, m):
|
| 299 |
+
"""
|
| 300 |
+
Set text rotation mode.
|
| 301 |
+
|
| 302 |
+
Parameters
|
| 303 |
+
----------
|
| 304 |
+
m : {None, 'default', 'anchor'}
|
| 305 |
+
If ``"default"``, the text will be first rotated, then aligned according
|
| 306 |
+
to their horizontal and vertical alignments. If ``"anchor"``, then
|
| 307 |
+
alignment occurs before rotation. Passing ``None`` will set the rotation
|
| 308 |
+
mode to ``"default"``.
|
| 309 |
+
"""
|
| 310 |
+
if m is None:
|
| 311 |
+
m = "default"
|
| 312 |
+
else:
|
| 313 |
+
_api.check_in_list(("anchor", "default"), rotation_mode=m)
|
| 314 |
+
self._rotation_mode = m
|
| 315 |
+
self.stale = True
|
| 316 |
+
|
| 317 |
+
def get_rotation_mode(self):
|
| 318 |
+
"""Return the text rotation mode."""
|
| 319 |
+
return self._rotation_mode
|
| 320 |
+
|
| 321 |
+
def set_antialiased(self, antialiased):
|
| 322 |
+
"""
|
| 323 |
+
Set whether to use antialiased rendering.
|
| 324 |
+
|
| 325 |
+
Parameters
|
| 326 |
+
----------
|
| 327 |
+
antialiased : bool
|
| 328 |
+
|
| 329 |
+
Notes
|
| 330 |
+
-----
|
| 331 |
+
Antialiasing will be determined by :rc:`text.antialiased`
|
| 332 |
+
and the parameter *antialiased* will have no effect if the text contains
|
| 333 |
+
math expressions.
|
| 334 |
+
"""
|
| 335 |
+
self._antialiased = antialiased
|
| 336 |
+
self.stale = True
|
| 337 |
+
|
| 338 |
+
def get_antialiased(self):
|
| 339 |
+
"""Return whether antialiased rendering is used."""
|
| 340 |
+
return self._antialiased
|
| 341 |
+
|
| 342 |
+
def update_from(self, other):
|
| 343 |
+
# docstring inherited
|
| 344 |
+
super().update_from(other)
|
| 345 |
+
self._color = other._color
|
| 346 |
+
self._multialignment = other._multialignment
|
| 347 |
+
self._verticalalignment = other._verticalalignment
|
| 348 |
+
self._horizontalalignment = other._horizontalalignment
|
| 349 |
+
self._fontproperties = other._fontproperties.copy()
|
| 350 |
+
self._usetex = other._usetex
|
| 351 |
+
self._rotation = other._rotation
|
| 352 |
+
self._transform_rotates_text = other._transform_rotates_text
|
| 353 |
+
self._picker = other._picker
|
| 354 |
+
self._linespacing = other._linespacing
|
| 355 |
+
self._antialiased = other._antialiased
|
| 356 |
+
self.stale = True
|
| 357 |
+
|
| 358 |
+
def _get_layout(self, renderer):
|
| 359 |
+
"""
|
| 360 |
+
Return the extent (bbox) of the text together with
|
| 361 |
+
multiple-alignment information. Note that it returns an extent
|
| 362 |
+
of a rotated text when necessary.
|
| 363 |
+
"""
|
| 364 |
+
thisx, thisy = 0.0, 0.0
|
| 365 |
+
lines = self._get_wrapped_text().split("\n") # Ensures lines is not empty.
|
| 366 |
+
|
| 367 |
+
ws = []
|
| 368 |
+
hs = []
|
| 369 |
+
xs = []
|
| 370 |
+
ys = []
|
| 371 |
+
|
| 372 |
+
# Full vertical extent of font, including ascenders and descenders:
|
| 373 |
+
_, lp_h, lp_d = _get_text_metrics_with_cache(
|
| 374 |
+
renderer, "lp", self._fontproperties,
|
| 375 |
+
ismath="TeX" if self.get_usetex() else False, dpi=self.figure.dpi)
|
| 376 |
+
min_dy = (lp_h - lp_d) * self._linespacing
|
| 377 |
+
|
| 378 |
+
for i, line in enumerate(lines):
|
| 379 |
+
clean_line, ismath = self._preprocess_math(line)
|
| 380 |
+
if clean_line:
|
| 381 |
+
w, h, d = _get_text_metrics_with_cache(
|
| 382 |
+
renderer, clean_line, self._fontproperties,
|
| 383 |
+
ismath=ismath, dpi=self.figure.dpi)
|
| 384 |
+
else:
|
| 385 |
+
w = h = d = 0
|
| 386 |
+
|
| 387 |
+
# For multiline text, increase the line spacing when the text
|
| 388 |
+
# net-height (excluding baseline) is larger than that of a "l"
|
| 389 |
+
# (e.g., use of superscripts), which seems what TeX does.
|
| 390 |
+
h = max(h, lp_h)
|
| 391 |
+
d = max(d, lp_d)
|
| 392 |
+
|
| 393 |
+
ws.append(w)
|
| 394 |
+
hs.append(h)
|
| 395 |
+
|
| 396 |
+
# Metrics of the last line that are needed later:
|
| 397 |
+
baseline = (h - d) - thisy
|
| 398 |
+
|
| 399 |
+
if i == 0:
|
| 400 |
+
# position at baseline
|
| 401 |
+
thisy = -(h - d)
|
| 402 |
+
else:
|
| 403 |
+
# put baseline a good distance from bottom of previous line
|
| 404 |
+
thisy -= max(min_dy, (h - d) * self._linespacing)
|
| 405 |
+
|
| 406 |
+
xs.append(thisx) # == 0.
|
| 407 |
+
ys.append(thisy)
|
| 408 |
+
|
| 409 |
+
thisy -= d
|
| 410 |
+
|
| 411 |
+
# Metrics of the last line that are needed later:
|
| 412 |
+
descent = d
|
| 413 |
+
|
| 414 |
+
# Bounding box definition:
|
| 415 |
+
width = max(ws)
|
| 416 |
+
xmin = 0
|
| 417 |
+
xmax = width
|
| 418 |
+
ymax = 0
|
| 419 |
+
ymin = ys[-1] - descent # baseline of last line minus its descent
|
| 420 |
+
|
| 421 |
+
# get the rotation matrix
|
| 422 |
+
M = Affine2D().rotate_deg(self.get_rotation())
|
| 423 |
+
|
| 424 |
+
# now offset the individual text lines within the box
|
| 425 |
+
malign = self._get_multialignment()
|
| 426 |
+
if malign == 'left':
|
| 427 |
+
offset_layout = [(x, y) for x, y in zip(xs, ys)]
|
| 428 |
+
elif malign == 'center':
|
| 429 |
+
offset_layout = [(x + width / 2 - w / 2, y)
|
| 430 |
+
for x, y, w in zip(xs, ys, ws)]
|
| 431 |
+
elif malign == 'right':
|
| 432 |
+
offset_layout = [(x + width - w, y)
|
| 433 |
+
for x, y, w in zip(xs, ys, ws)]
|
| 434 |
+
|
| 435 |
+
# the corners of the unrotated bounding box
|
| 436 |
+
corners_horiz = np.array(
|
| 437 |
+
[(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)])
|
| 438 |
+
|
| 439 |
+
# now rotate the bbox
|
| 440 |
+
corners_rotated = M.transform(corners_horiz)
|
| 441 |
+
# compute the bounds of the rotated box
|
| 442 |
+
xmin = corners_rotated[:, 0].min()
|
| 443 |
+
xmax = corners_rotated[:, 0].max()
|
| 444 |
+
ymin = corners_rotated[:, 1].min()
|
| 445 |
+
ymax = corners_rotated[:, 1].max()
|
| 446 |
+
width = xmax - xmin
|
| 447 |
+
height = ymax - ymin
|
| 448 |
+
|
| 449 |
+
# Now move the box to the target position offset the display
|
| 450 |
+
# bbox by alignment
|
| 451 |
+
halign = self._horizontalalignment
|
| 452 |
+
valign = self._verticalalignment
|
| 453 |
+
|
| 454 |
+
rotation_mode = self.get_rotation_mode()
|
| 455 |
+
if rotation_mode != "anchor":
|
| 456 |
+
# compute the text location in display coords and the offsets
|
| 457 |
+
# necessary to align the bbox with that location
|
| 458 |
+
if halign == 'center':
|
| 459 |
+
offsetx = (xmin + xmax) / 2
|
| 460 |
+
elif halign == 'right':
|
| 461 |
+
offsetx = xmax
|
| 462 |
+
else:
|
| 463 |
+
offsetx = xmin
|
| 464 |
+
|
| 465 |
+
if valign == 'center':
|
| 466 |
+
offsety = (ymin + ymax) / 2
|
| 467 |
+
elif valign == 'top':
|
| 468 |
+
offsety = ymax
|
| 469 |
+
elif valign == 'baseline':
|
| 470 |
+
offsety = ymin + descent
|
| 471 |
+
elif valign == 'center_baseline':
|
| 472 |
+
offsety = ymin + height - baseline / 2.0
|
| 473 |
+
else:
|
| 474 |
+
offsety = ymin
|
| 475 |
+
else:
|
| 476 |
+
xmin1, ymin1 = corners_horiz[0]
|
| 477 |
+
xmax1, ymax1 = corners_horiz[2]
|
| 478 |
+
|
| 479 |
+
if halign == 'center':
|
| 480 |
+
offsetx = (xmin1 + xmax1) / 2.0
|
| 481 |
+
elif halign == 'right':
|
| 482 |
+
offsetx = xmax1
|
| 483 |
+
else:
|
| 484 |
+
offsetx = xmin1
|
| 485 |
+
|
| 486 |
+
if valign == 'center':
|
| 487 |
+
offsety = (ymin1 + ymax1) / 2.0
|
| 488 |
+
elif valign == 'top':
|
| 489 |
+
offsety = ymax1
|
| 490 |
+
elif valign == 'baseline':
|
| 491 |
+
offsety = ymax1 - baseline
|
| 492 |
+
elif valign == 'center_baseline':
|
| 493 |
+
offsety = ymax1 - baseline / 2.0
|
| 494 |
+
else:
|
| 495 |
+
offsety = ymin1
|
| 496 |
+
|
| 497 |
+
offsetx, offsety = M.transform((offsetx, offsety))
|
| 498 |
+
|
| 499 |
+
xmin -= offsetx
|
| 500 |
+
ymin -= offsety
|
| 501 |
+
|
| 502 |
+
bbox = Bbox.from_bounds(xmin, ymin, width, height)
|
| 503 |
+
|
| 504 |
+
# now rotate the positions around the first (x, y) position
|
| 505 |
+
xys = M.transform(offset_layout) - (offsetx, offsety)
|
| 506 |
+
|
| 507 |
+
return bbox, list(zip(lines, zip(ws, hs), *xys.T)), descent
|
| 508 |
+
|
| 509 |
+
def set_bbox(self, rectprops):
|
| 510 |
+
"""
|
| 511 |
+
Draw a bounding box around self.
|
| 512 |
+
|
| 513 |
+
Parameters
|
| 514 |
+
----------
|
| 515 |
+
rectprops : dict with properties for `.patches.FancyBboxPatch`
|
| 516 |
+
The default boxstyle is 'square'. The mutation
|
| 517 |
+
scale of the `.patches.FancyBboxPatch` is set to the fontsize.
|
| 518 |
+
|
| 519 |
+
Examples
|
| 520 |
+
--------
|
| 521 |
+
::
|
| 522 |
+
|
| 523 |
+
t.set_bbox(dict(facecolor='red', alpha=0.5))
|
| 524 |
+
"""
|
| 525 |
+
|
| 526 |
+
if rectprops is not None:
|
| 527 |
+
props = rectprops.copy()
|
| 528 |
+
boxstyle = props.pop("boxstyle", None)
|
| 529 |
+
pad = props.pop("pad", None)
|
| 530 |
+
if boxstyle is None:
|
| 531 |
+
boxstyle = "square"
|
| 532 |
+
if pad is None:
|
| 533 |
+
pad = 4 # points
|
| 534 |
+
pad /= self.get_size() # to fraction of font size
|
| 535 |
+
else:
|
| 536 |
+
if pad is None:
|
| 537 |
+
pad = 0.3
|
| 538 |
+
# boxstyle could be a callable or a string
|
| 539 |
+
if isinstance(boxstyle, str) and "pad" not in boxstyle:
|
| 540 |
+
boxstyle += ",pad=%0.2f" % pad
|
| 541 |
+
self._bbox_patch = FancyBboxPatch(
|
| 542 |
+
(0, 0), 1, 1,
|
| 543 |
+
boxstyle=boxstyle, transform=IdentityTransform(), **props)
|
| 544 |
+
else:
|
| 545 |
+
self._bbox_patch = None
|
| 546 |
+
|
| 547 |
+
self._update_clip_properties()
|
| 548 |
+
|
| 549 |
+
def get_bbox_patch(self):
|
| 550 |
+
"""
|
| 551 |
+
Return the bbox Patch, or None if the `.patches.FancyBboxPatch`
|
| 552 |
+
is not made.
|
| 553 |
+
"""
|
| 554 |
+
return self._bbox_patch
|
| 555 |
+
|
| 556 |
+
def update_bbox_position_size(self, renderer):
|
| 557 |
+
"""
|
| 558 |
+
Update the location and the size of the bbox.
|
| 559 |
+
|
| 560 |
+
This method should be used when the position and size of the bbox needs
|
| 561 |
+
to be updated before actually drawing the bbox.
|
| 562 |
+
"""
|
| 563 |
+
if self._bbox_patch:
|
| 564 |
+
# don't use self.get_unitless_position here, which refers to text
|
| 565 |
+
# position in Text:
|
| 566 |
+
posx = float(self.convert_xunits(self._x))
|
| 567 |
+
posy = float(self.convert_yunits(self._y))
|
| 568 |
+
posx, posy = self.get_transform().transform((posx, posy))
|
| 569 |
+
|
| 570 |
+
x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
|
| 571 |
+
self._bbox_patch.set_bounds(0., 0., w_box, h_box)
|
| 572 |
+
self._bbox_patch.set_transform(
|
| 573 |
+
Affine2D()
|
| 574 |
+
.rotate_deg(self.get_rotation())
|
| 575 |
+
.translate(posx + x_box, posy + y_box))
|
| 576 |
+
fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
|
| 577 |
+
self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
|
| 578 |
+
|
| 579 |
+
def _update_clip_properties(self):
|
| 580 |
+
if self._bbox_patch:
|
| 581 |
+
clipprops = dict(clip_box=self.clipbox,
|
| 582 |
+
clip_path=self._clippath,
|
| 583 |
+
clip_on=self._clipon)
|
| 584 |
+
self._bbox_patch.update(clipprops)
|
| 585 |
+
|
| 586 |
+
def set_clip_box(self, clipbox):
|
| 587 |
+
# docstring inherited.
|
| 588 |
+
super().set_clip_box(clipbox)
|
| 589 |
+
self._update_clip_properties()
|
| 590 |
+
|
| 591 |
+
def set_clip_path(self, path, transform=None):
|
| 592 |
+
# docstring inherited.
|
| 593 |
+
super().set_clip_path(path, transform)
|
| 594 |
+
self._update_clip_properties()
|
| 595 |
+
|
| 596 |
+
def set_clip_on(self, b):
|
| 597 |
+
# docstring inherited.
|
| 598 |
+
super().set_clip_on(b)
|
| 599 |
+
self._update_clip_properties()
|
| 600 |
+
|
| 601 |
+
def get_wrap(self):
|
| 602 |
+
"""Return whether the text can be wrapped."""
|
| 603 |
+
return self._wrap
|
| 604 |
+
|
| 605 |
+
def set_wrap(self, wrap):
|
| 606 |
+
"""
|
| 607 |
+
Set whether the text can be wrapped.
|
| 608 |
+
|
| 609 |
+
Wrapping makes sure the text is confined to the (sub)figure box. It
|
| 610 |
+
does not take into account any other artists.
|
| 611 |
+
|
| 612 |
+
Parameters
|
| 613 |
+
----------
|
| 614 |
+
wrap : bool
|
| 615 |
+
|
| 616 |
+
Notes
|
| 617 |
+
-----
|
| 618 |
+
Wrapping does not work together with
|
| 619 |
+
``savefig(..., bbox_inches='tight')`` (which is also used internally
|
| 620 |
+
by ``%matplotlib inline`` in IPython/Jupyter). The 'tight' setting
|
| 621 |
+
rescales the canvas to accommodate all content and happens before
|
| 622 |
+
wrapping.
|
| 623 |
+
"""
|
| 624 |
+
self._wrap = wrap
|
| 625 |
+
|
| 626 |
+
def _get_wrap_line_width(self):
|
| 627 |
+
"""
|
| 628 |
+
Return the maximum line width for wrapping text based on the current
|
| 629 |
+
orientation.
|
| 630 |
+
"""
|
| 631 |
+
x0, y0 = self.get_transform().transform(self.get_position())
|
| 632 |
+
figure_box = self.get_figure().get_window_extent()
|
| 633 |
+
|
| 634 |
+
# Calculate available width based on text alignment
|
| 635 |
+
alignment = self.get_horizontalalignment()
|
| 636 |
+
self.set_rotation_mode('anchor')
|
| 637 |
+
rotation = self.get_rotation()
|
| 638 |
+
|
| 639 |
+
left = self._get_dist_to_box(rotation, x0, y0, figure_box)
|
| 640 |
+
right = self._get_dist_to_box(
|
| 641 |
+
(180 + rotation) % 360, x0, y0, figure_box)
|
| 642 |
+
|
| 643 |
+
if alignment == 'left':
|
| 644 |
+
line_width = left
|
| 645 |
+
elif alignment == 'right':
|
| 646 |
+
line_width = right
|
| 647 |
+
else:
|
| 648 |
+
line_width = 2 * min(left, right)
|
| 649 |
+
|
| 650 |
+
return line_width
|
| 651 |
+
|
| 652 |
+
def _get_dist_to_box(self, rotation, x0, y0, figure_box):
|
| 653 |
+
"""
|
| 654 |
+
Return the distance from the given points to the boundaries of a
|
| 655 |
+
rotated box, in pixels.
|
| 656 |
+
"""
|
| 657 |
+
if rotation > 270:
|
| 658 |
+
quad = rotation - 270
|
| 659 |
+
h1 = (y0 - figure_box.y0) / math.cos(math.radians(quad))
|
| 660 |
+
h2 = (figure_box.x1 - x0) / math.cos(math.radians(90 - quad))
|
| 661 |
+
elif rotation > 180:
|
| 662 |
+
quad = rotation - 180
|
| 663 |
+
h1 = (x0 - figure_box.x0) / math.cos(math.radians(quad))
|
| 664 |
+
h2 = (y0 - figure_box.y0) / math.cos(math.radians(90 - quad))
|
| 665 |
+
elif rotation > 90:
|
| 666 |
+
quad = rotation - 90
|
| 667 |
+
h1 = (figure_box.y1 - y0) / math.cos(math.radians(quad))
|
| 668 |
+
h2 = (x0 - figure_box.x0) / math.cos(math.radians(90 - quad))
|
| 669 |
+
else:
|
| 670 |
+
h1 = (figure_box.x1 - x0) / math.cos(math.radians(rotation))
|
| 671 |
+
h2 = (figure_box.y1 - y0) / math.cos(math.radians(90 - rotation))
|
| 672 |
+
|
| 673 |
+
return min(h1, h2)
|
| 674 |
+
|
| 675 |
+
def _get_rendered_text_width(self, text):
|
| 676 |
+
"""
|
| 677 |
+
Return the width of a given text string, in pixels.
|
| 678 |
+
"""
|
| 679 |
+
|
| 680 |
+
w, h, d = self._renderer.get_text_width_height_descent(
|
| 681 |
+
text,
|
| 682 |
+
self.get_fontproperties(),
|
| 683 |
+
cbook.is_math_text(text))
|
| 684 |
+
return math.ceil(w)
|
| 685 |
+
|
| 686 |
+
def _get_wrapped_text(self):
|
| 687 |
+
"""
|
| 688 |
+
Return a copy of the text string with new lines added so that the text
|
| 689 |
+
is wrapped relative to the parent figure (if `get_wrap` is True).
|
| 690 |
+
"""
|
| 691 |
+
if not self.get_wrap():
|
| 692 |
+
return self.get_text()
|
| 693 |
+
|
| 694 |
+
# Not fit to handle breaking up latex syntax correctly, so
|
| 695 |
+
# ignore latex for now.
|
| 696 |
+
if self.get_usetex():
|
| 697 |
+
return self.get_text()
|
| 698 |
+
|
| 699 |
+
# Build the line incrementally, for a more accurate measure of length
|
| 700 |
+
line_width = self._get_wrap_line_width()
|
| 701 |
+
wrapped_lines = []
|
| 702 |
+
|
| 703 |
+
# New lines in the user's text force a split
|
| 704 |
+
unwrapped_lines = self.get_text().split('\n')
|
| 705 |
+
|
| 706 |
+
# Now wrap each individual unwrapped line
|
| 707 |
+
for unwrapped_line in unwrapped_lines:
|
| 708 |
+
|
| 709 |
+
sub_words = unwrapped_line.split(' ')
|
| 710 |
+
# Remove items from sub_words as we go, so stop when empty
|
| 711 |
+
while len(sub_words) > 0:
|
| 712 |
+
if len(sub_words) == 1:
|
| 713 |
+
# Only one word, so just add it to the end
|
| 714 |
+
wrapped_lines.append(sub_words.pop(0))
|
| 715 |
+
continue
|
| 716 |
+
|
| 717 |
+
for i in range(2, len(sub_words) + 1):
|
| 718 |
+
# Get width of all words up to and including here
|
| 719 |
+
line = ' '.join(sub_words[:i])
|
| 720 |
+
current_width = self._get_rendered_text_width(line)
|
| 721 |
+
|
| 722 |
+
# If all these words are too wide, append all not including
|
| 723 |
+
# last word
|
| 724 |
+
if current_width > line_width:
|
| 725 |
+
wrapped_lines.append(' '.join(sub_words[:i - 1]))
|
| 726 |
+
sub_words = sub_words[i - 1:]
|
| 727 |
+
break
|
| 728 |
+
|
| 729 |
+
# Otherwise if all words fit in the width, append them all
|
| 730 |
+
elif i == len(sub_words):
|
| 731 |
+
wrapped_lines.append(' '.join(sub_words[:i]))
|
| 732 |
+
sub_words = []
|
| 733 |
+
break
|
| 734 |
+
|
| 735 |
+
return '\n'.join(wrapped_lines)
|
| 736 |
+
|
| 737 |
+
@artist.allow_rasterization
|
| 738 |
+
def draw(self, renderer):
|
| 739 |
+
# docstring inherited
|
| 740 |
+
|
| 741 |
+
if renderer is not None:
|
| 742 |
+
self._renderer = renderer
|
| 743 |
+
if not self.get_visible():
|
| 744 |
+
return
|
| 745 |
+
if self.get_text() == '':
|
| 746 |
+
return
|
| 747 |
+
|
| 748 |
+
renderer.open_group('text', self.get_gid())
|
| 749 |
+
|
| 750 |
+
with self._cm_set(text=self._get_wrapped_text()):
|
| 751 |
+
bbox, info, descent = self._get_layout(renderer)
|
| 752 |
+
trans = self.get_transform()
|
| 753 |
+
|
| 754 |
+
# don't use self.get_position here, which refers to text
|
| 755 |
+
# position in Text:
|
| 756 |
+
posx = float(self.convert_xunits(self._x))
|
| 757 |
+
posy = float(self.convert_yunits(self._y))
|
| 758 |
+
posx, posy = trans.transform((posx, posy))
|
| 759 |
+
if not np.isfinite(posx) or not np.isfinite(posy):
|
| 760 |
+
_log.warning("posx and posy should be finite values")
|
| 761 |
+
return
|
| 762 |
+
canvasw, canvash = renderer.get_canvas_width_height()
|
| 763 |
+
|
| 764 |
+
# Update the location and size of the bbox
|
| 765 |
+
# (`.patches.FancyBboxPatch`), and draw it.
|
| 766 |
+
if self._bbox_patch:
|
| 767 |
+
self.update_bbox_position_size(renderer)
|
| 768 |
+
self._bbox_patch.draw(renderer)
|
| 769 |
+
|
| 770 |
+
gc = renderer.new_gc()
|
| 771 |
+
gc.set_foreground(self.get_color())
|
| 772 |
+
gc.set_alpha(self.get_alpha())
|
| 773 |
+
gc.set_url(self._url)
|
| 774 |
+
gc.set_antialiased(self._antialiased)
|
| 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 : :mpltype:`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 : :mpltype:`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 : {'baseline', 'bottom', '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 |
+
s = '' if s is None else str(s)
|
| 1278 |
+
if s != self._text:
|
| 1279 |
+
self._text = s
|
| 1280 |
+
self.stale = True
|
| 1281 |
+
|
| 1282 |
+
def _preprocess_math(self, s):
|
| 1283 |
+
"""
|
| 1284 |
+
Return the string *s* after mathtext preprocessing, and the kind of
|
| 1285 |
+
mathtext support needed.
|
| 1286 |
+
|
| 1287 |
+
- If *self* is configured to use TeX, return *s* unchanged except that
|
| 1288 |
+
a single space gets escaped, and the flag "TeX".
|
| 1289 |
+
- Otherwise, if *s* is mathtext (has an even number of unescaped dollar
|
| 1290 |
+
signs) and ``parse_math`` is not set to False, return *s* and the
|
| 1291 |
+
flag True.
|
| 1292 |
+
- Otherwise, return *s* with dollar signs unescaped, and the flag
|
| 1293 |
+
False.
|
| 1294 |
+
"""
|
| 1295 |
+
if self.get_usetex():
|
| 1296 |
+
if s == " ":
|
| 1297 |
+
s = r"\ "
|
| 1298 |
+
return s, "TeX"
|
| 1299 |
+
elif not self.get_parse_math():
|
| 1300 |
+
return s, False
|
| 1301 |
+
elif cbook.is_math_text(s):
|
| 1302 |
+
return s, True
|
| 1303 |
+
else:
|
| 1304 |
+
return s.replace(r"\$", "$"), False
|
| 1305 |
+
|
| 1306 |
+
def set_fontproperties(self, fp):
|
| 1307 |
+
"""
|
| 1308 |
+
Set the font properties that control the text.
|
| 1309 |
+
|
| 1310 |
+
Parameters
|
| 1311 |
+
----------
|
| 1312 |
+
fp : `.font_manager.FontProperties` or `str` or `pathlib.Path`
|
| 1313 |
+
If a `str`, it is interpreted as a fontconfig pattern parsed by
|
| 1314 |
+
`.FontProperties`. If a `pathlib.Path`, it is interpreted as the
|
| 1315 |
+
absolute path to a font file.
|
| 1316 |
+
"""
|
| 1317 |
+
self._fontproperties = FontProperties._from_any(fp).copy()
|
| 1318 |
+
self.stale = True
|
| 1319 |
+
|
| 1320 |
+
@_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
|
| 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_fontfamily`.
|
| 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 |
+
self.set_fontfamily(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 |
+
x, y = ref_coord # Make copy when ref_coord is an array (and check the shape).
|
| 1397 |
+
self._ref_coord = x, y
|
| 1398 |
+
self.set_unit(unit)
|
| 1399 |
+
|
| 1400 |
+
def set_unit(self, unit):
|
| 1401 |
+
"""
|
| 1402 |
+
Set the unit for input to the transform used by ``__call__``.
|
| 1403 |
+
|
| 1404 |
+
Parameters
|
| 1405 |
+
----------
|
| 1406 |
+
unit : {'points', 'pixels'}
|
| 1407 |
+
"""
|
| 1408 |
+
_api.check_in_list(["points", "pixels"], unit=unit)
|
| 1409 |
+
self._unit = unit
|
| 1410 |
+
|
| 1411 |
+
def get_unit(self):
|
| 1412 |
+
"""Return the unit for input to the transform used by ``__call__``."""
|
| 1413 |
+
return self._unit
|
| 1414 |
+
|
| 1415 |
+
def __call__(self, renderer):
|
| 1416 |
+
"""
|
| 1417 |
+
Return the offset transform.
|
| 1418 |
+
|
| 1419 |
+
Parameters
|
| 1420 |
+
----------
|
| 1421 |
+
renderer : `RendererBase`
|
| 1422 |
+
The renderer to use to compute the offset
|
| 1423 |
+
|
| 1424 |
+
Returns
|
| 1425 |
+
-------
|
| 1426 |
+
`Transform`
|
| 1427 |
+
Maps (x, y) in pixel or point units to screen units
|
| 1428 |
+
relative to the given artist.
|
| 1429 |
+
"""
|
| 1430 |
+
if isinstance(self._artist, Artist):
|
| 1431 |
+
bbox = self._artist.get_window_extent(renderer)
|
| 1432 |
+
xf, yf = self._ref_coord
|
| 1433 |
+
x = bbox.x0 + bbox.width * xf
|
| 1434 |
+
y = bbox.y0 + bbox.height * yf
|
| 1435 |
+
elif isinstance(self._artist, BboxBase):
|
| 1436 |
+
bbox = self._artist
|
| 1437 |
+
xf, yf = self._ref_coord
|
| 1438 |
+
x = bbox.x0 + bbox.width * xf
|
| 1439 |
+
y = bbox.y0 + bbox.height * yf
|
| 1440 |
+
elif isinstance(self._artist, Transform):
|
| 1441 |
+
x, y = self._artist.transform(self._ref_coord)
|
| 1442 |
+
else:
|
| 1443 |
+
_api.check_isinstance((Artist, BboxBase, Transform), artist=self._artist)
|
| 1444 |
+
scale = 1 if self._unit == "pixels" else renderer.points_to_pixels(1)
|
| 1445 |
+
return Affine2D().scale(scale).translate(x, y)
|
| 1446 |
+
|
| 1447 |
+
|
| 1448 |
+
class _AnnotationBase:
|
| 1449 |
+
def __init__(self,
|
| 1450 |
+
xy,
|
| 1451 |
+
xycoords='data',
|
| 1452 |
+
annotation_clip=None):
|
| 1453 |
+
|
| 1454 |
+
x, y = xy # Make copy when xy is an array (and check the shape).
|
| 1455 |
+
self.xy = x, y
|
| 1456 |
+
self.xycoords = xycoords
|
| 1457 |
+
self.set_annotation_clip(annotation_clip)
|
| 1458 |
+
|
| 1459 |
+
self._draggable = None
|
| 1460 |
+
|
| 1461 |
+
def _get_xy(self, renderer, xy, coords):
|
| 1462 |
+
x, y = xy
|
| 1463 |
+
xcoord, ycoord = coords if isinstance(coords, tuple) else (coords, coords)
|
| 1464 |
+
if xcoord == 'data':
|
| 1465 |
+
x = float(self.convert_xunits(x))
|
| 1466 |
+
if ycoord == 'data':
|
| 1467 |
+
y = float(self.convert_yunits(y))
|
| 1468 |
+
return self._get_xy_transform(renderer, coords).transform((x, y))
|
| 1469 |
+
|
| 1470 |
+
def _get_xy_transform(self, renderer, coords):
|
| 1471 |
+
|
| 1472 |
+
if isinstance(coords, tuple):
|
| 1473 |
+
xcoord, ycoord = coords
|
| 1474 |
+
from matplotlib.transforms import blended_transform_factory
|
| 1475 |
+
tr1 = self._get_xy_transform(renderer, xcoord)
|
| 1476 |
+
tr2 = self._get_xy_transform(renderer, ycoord)
|
| 1477 |
+
return blended_transform_factory(tr1, tr2)
|
| 1478 |
+
elif callable(coords):
|
| 1479 |
+
tr = coords(renderer)
|
| 1480 |
+
if isinstance(tr, BboxBase):
|
| 1481 |
+
return BboxTransformTo(tr)
|
| 1482 |
+
elif isinstance(tr, Transform):
|
| 1483 |
+
return tr
|
| 1484 |
+
else:
|
| 1485 |
+
raise TypeError(
|
| 1486 |
+
f"xycoords callable must return a BboxBase or Transform, not a "
|
| 1487 |
+
f"{type(tr).__name__}")
|
| 1488 |
+
elif isinstance(coords, Artist):
|
| 1489 |
+
bbox = coords.get_window_extent(renderer)
|
| 1490 |
+
return BboxTransformTo(bbox)
|
| 1491 |
+
elif isinstance(coords, BboxBase):
|
| 1492 |
+
return BboxTransformTo(coords)
|
| 1493 |
+
elif isinstance(coords, Transform):
|
| 1494 |
+
return coords
|
| 1495 |
+
elif not isinstance(coords, str):
|
| 1496 |
+
raise TypeError(
|
| 1497 |
+
f"'xycoords' must be an instance of str, tuple[str, str], Artist, "
|
| 1498 |
+
f"Transform, or Callable, not a {type(coords).__name__}")
|
| 1499 |
+
|
| 1500 |
+
if coords == 'data':
|
| 1501 |
+
return self.axes.transData
|
| 1502 |
+
elif coords == 'polar':
|
| 1503 |
+
from matplotlib.projections import PolarAxes
|
| 1504 |
+
tr = PolarAxes.PolarTransform(apply_theta_transforms=False)
|
| 1505 |
+
trans = tr + self.axes.transData
|
| 1506 |
+
return trans
|
| 1507 |
+
|
| 1508 |
+
try:
|
| 1509 |
+
bbox_name, unit = coords.split()
|
| 1510 |
+
except ValueError: # i.e. len(coords.split()) != 2.
|
| 1511 |
+
raise ValueError(f"{coords!r} is not a valid coordinate") from None
|
| 1512 |
+
|
| 1513 |
+
bbox0, xy0 = None, None
|
| 1514 |
+
|
| 1515 |
+
# if unit is offset-like
|
| 1516 |
+
if bbox_name == "figure":
|
| 1517 |
+
bbox0 = self.figure.figbbox
|
| 1518 |
+
elif bbox_name == "subfigure":
|
| 1519 |
+
bbox0 = self.figure.bbox
|
| 1520 |
+
elif bbox_name == "axes":
|
| 1521 |
+
bbox0 = self.axes.bbox
|
| 1522 |
+
|
| 1523 |
+
# reference x, y in display coordinate
|
| 1524 |
+
if bbox0 is not None:
|
| 1525 |
+
xy0 = bbox0.p0
|
| 1526 |
+
elif bbox_name == "offset":
|
| 1527 |
+
xy0 = self._get_position_xy(renderer)
|
| 1528 |
+
else:
|
| 1529 |
+
raise ValueError(f"{coords!r} is not a valid coordinate")
|
| 1530 |
+
|
| 1531 |
+
if unit == "points":
|
| 1532 |
+
tr = Affine2D().scale(self.figure.dpi / 72) # dpi/72 dots per point
|
| 1533 |
+
elif unit == "pixels":
|
| 1534 |
+
tr = Affine2D()
|
| 1535 |
+
elif unit == "fontsize":
|
| 1536 |
+
tr = Affine2D().scale(self.get_size() * self.figure.dpi / 72)
|
| 1537 |
+
elif unit == "fraction":
|
| 1538 |
+
tr = Affine2D().scale(*bbox0.size)
|
| 1539 |
+
else:
|
| 1540 |
+
raise ValueError(f"{unit!r} is not a recognized unit")
|
| 1541 |
+
|
| 1542 |
+
return tr.translate(*xy0)
|
| 1543 |
+
|
| 1544 |
+
def set_annotation_clip(self, b):
|
| 1545 |
+
"""
|
| 1546 |
+
Set the annotation's clipping behavior.
|
| 1547 |
+
|
| 1548 |
+
Parameters
|
| 1549 |
+
----------
|
| 1550 |
+
b : bool or None
|
| 1551 |
+
- True: The annotation will be clipped when ``self.xy`` is
|
| 1552 |
+
outside the Axes.
|
| 1553 |
+
- False: The annotation will always be drawn.
|
| 1554 |
+
- None: The annotation will be clipped when ``self.xy`` is
|
| 1555 |
+
outside the Axes and ``self.xycoords == "data"``.
|
| 1556 |
+
"""
|
| 1557 |
+
self._annotation_clip = b
|
| 1558 |
+
|
| 1559 |
+
def get_annotation_clip(self):
|
| 1560 |
+
"""
|
| 1561 |
+
Return the annotation's clipping behavior.
|
| 1562 |
+
|
| 1563 |
+
See `set_annotation_clip` for the meaning of return values.
|
| 1564 |
+
"""
|
| 1565 |
+
return self._annotation_clip
|
| 1566 |
+
|
| 1567 |
+
def _get_position_xy(self, renderer):
|
| 1568 |
+
"""Return the pixel position of the annotated point."""
|
| 1569 |
+
return self._get_xy(renderer, self.xy, self.xycoords)
|
| 1570 |
+
|
| 1571 |
+
def _check_xy(self, renderer=None):
|
| 1572 |
+
"""Check whether the annotation at *xy_pixel* should be drawn."""
|
| 1573 |
+
if renderer is None:
|
| 1574 |
+
renderer = self.figure._get_renderer()
|
| 1575 |
+
b = self.get_annotation_clip()
|
| 1576 |
+
if b or (b is None and self.xycoords == "data"):
|
| 1577 |
+
# check if self.xy is inside the Axes.
|
| 1578 |
+
xy_pixel = self._get_position_xy(renderer)
|
| 1579 |
+
return self.axes.contains_point(xy_pixel)
|
| 1580 |
+
return True
|
| 1581 |
+
|
| 1582 |
+
def draggable(self, state=None, use_blit=False):
|
| 1583 |
+
"""
|
| 1584 |
+
Set whether the annotation is draggable with the mouse.
|
| 1585 |
+
|
| 1586 |
+
Parameters
|
| 1587 |
+
----------
|
| 1588 |
+
state : bool or None
|
| 1589 |
+
- True or False: set the draggability.
|
| 1590 |
+
- None: toggle the draggability.
|
| 1591 |
+
use_blit : bool, default: False
|
| 1592 |
+
Use blitting for faster image composition. For details see
|
| 1593 |
+
:ref:`func-animation`.
|
| 1594 |
+
|
| 1595 |
+
Returns
|
| 1596 |
+
-------
|
| 1597 |
+
DraggableAnnotation or None
|
| 1598 |
+
If the annotation is draggable, the corresponding
|
| 1599 |
+
`.DraggableAnnotation` helper is returned.
|
| 1600 |
+
"""
|
| 1601 |
+
from matplotlib.offsetbox import DraggableAnnotation
|
| 1602 |
+
is_draggable = self._draggable is not None
|
| 1603 |
+
|
| 1604 |
+
# if state is None we'll toggle
|
| 1605 |
+
if state is None:
|
| 1606 |
+
state = not is_draggable
|
| 1607 |
+
|
| 1608 |
+
if state:
|
| 1609 |
+
if self._draggable is None:
|
| 1610 |
+
self._draggable = DraggableAnnotation(self, use_blit)
|
| 1611 |
+
else:
|
| 1612 |
+
if self._draggable is not None:
|
| 1613 |
+
self._draggable.disconnect()
|
| 1614 |
+
self._draggable = None
|
| 1615 |
+
|
| 1616 |
+
return self._draggable
|
| 1617 |
+
|
| 1618 |
+
|
| 1619 |
+
class Annotation(Text, _AnnotationBase):
|
| 1620 |
+
"""
|
| 1621 |
+
An `.Annotation` is a `.Text` that can refer to a specific position *xy*.
|
| 1622 |
+
Optionally an arrow pointing from the text to *xy* can be drawn.
|
| 1623 |
+
|
| 1624 |
+
Attributes
|
| 1625 |
+
----------
|
| 1626 |
+
xy
|
| 1627 |
+
The annotated position.
|
| 1628 |
+
xycoords
|
| 1629 |
+
The coordinate system for *xy*.
|
| 1630 |
+
arrow_patch
|
| 1631 |
+
A `.FancyArrowPatch` to point from *xytext* to *xy*.
|
| 1632 |
+
"""
|
| 1633 |
+
|
| 1634 |
+
def __str__(self):
|
| 1635 |
+
return f"Annotation({self.xy[0]:g}, {self.xy[1]:g}, {self._text!r})"
|
| 1636 |
+
|
| 1637 |
+
def __init__(self, text, xy,
|
| 1638 |
+
xytext=None,
|
| 1639 |
+
xycoords='data',
|
| 1640 |
+
textcoords=None,
|
| 1641 |
+
arrowprops=None,
|
| 1642 |
+
annotation_clip=None,
|
| 1643 |
+
**kwargs):
|
| 1644 |
+
"""
|
| 1645 |
+
Annotate the point *xy* with text *text*.
|
| 1646 |
+
|
| 1647 |
+
In the simplest form, the text is placed at *xy*.
|
| 1648 |
+
|
| 1649 |
+
Optionally, the text can be displayed in another position *xytext*.
|
| 1650 |
+
An arrow pointing from the text to the annotated point *xy* can then
|
| 1651 |
+
be added by defining *arrowprops*.
|
| 1652 |
+
|
| 1653 |
+
Parameters
|
| 1654 |
+
----------
|
| 1655 |
+
text : str
|
| 1656 |
+
The text of the annotation.
|
| 1657 |
+
|
| 1658 |
+
xy : (float, float)
|
| 1659 |
+
The point *(x, y)* to annotate. The coordinate system is determined
|
| 1660 |
+
by *xycoords*.
|
| 1661 |
+
|
| 1662 |
+
xytext : (float, float), default: *xy*
|
| 1663 |
+
The position *(x, y)* to place the text at. The coordinate system
|
| 1664 |
+
is determined by *textcoords*.
|
| 1665 |
+
|
| 1666 |
+
xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \
|
| 1667 |
+
callable, default: 'data'
|
| 1668 |
+
|
| 1669 |
+
The coordinate system that *xy* is given in. The following types
|
| 1670 |
+
of values are supported:
|
| 1671 |
+
|
| 1672 |
+
- One of the following strings:
|
| 1673 |
+
|
| 1674 |
+
==================== ============================================
|
| 1675 |
+
Value Description
|
| 1676 |
+
==================== ============================================
|
| 1677 |
+
'figure points' Points from the lower left of the figure
|
| 1678 |
+
'figure pixels' Pixels from the lower left of the figure
|
| 1679 |
+
'figure fraction' Fraction of figure from lower left
|
| 1680 |
+
'subfigure points' Points from the lower left of the subfigure
|
| 1681 |
+
'subfigure pixels' Pixels from the lower left of the subfigure
|
| 1682 |
+
'subfigure fraction' Fraction of subfigure from lower left
|
| 1683 |
+
'axes points' Points from lower left corner of the Axes
|
| 1684 |
+
'axes pixels' Pixels from lower left corner of the Axes
|
| 1685 |
+
'axes fraction' Fraction of Axes from lower left
|
| 1686 |
+
'data' Use the coordinate system of the object
|
| 1687 |
+
being annotated (default)
|
| 1688 |
+
'polar' *(theta, r)* if not native 'data'
|
| 1689 |
+
coordinates
|
| 1690 |
+
==================== ============================================
|
| 1691 |
+
|
| 1692 |
+
Note that 'subfigure pixels' and 'figure pixels' are the same
|
| 1693 |
+
for the parent figure, so users who want code that is usable in
|
| 1694 |
+
a subfigure can use 'subfigure pixels'.
|
| 1695 |
+
|
| 1696 |
+
- An `.Artist`: *xy* is interpreted as a fraction of the artist's
|
| 1697 |
+
`~matplotlib.transforms.Bbox`. E.g. *(0, 0)* would be the lower
|
| 1698 |
+
left corner of the bounding box and *(0.5, 1)* would be the
|
| 1699 |
+
center top of the bounding box.
|
| 1700 |
+
|
| 1701 |
+
- A `.Transform` to transform *xy* to screen coordinates.
|
| 1702 |
+
|
| 1703 |
+
- A function with one of the following signatures::
|
| 1704 |
+
|
| 1705 |
+
def transform(renderer) -> Bbox
|
| 1706 |
+
def transform(renderer) -> Transform
|
| 1707 |
+
|
| 1708 |
+
where *renderer* is a `.RendererBase` subclass.
|
| 1709 |
+
|
| 1710 |
+
The result of the function is interpreted like the `.Artist` and
|
| 1711 |
+
`.Transform` cases above.
|
| 1712 |
+
|
| 1713 |
+
- A tuple *(xcoords, ycoords)* specifying separate coordinate
|
| 1714 |
+
systems for *x* and *y*. *xcoords* and *ycoords* must each be
|
| 1715 |
+
of one of the above described types.
|
| 1716 |
+
|
| 1717 |
+
See :ref:`plotting-guide-annotation` for more details.
|
| 1718 |
+
|
| 1719 |
+
textcoords : single or two-tuple of str or `.Artist` or `.Transform` \
|
| 1720 |
+
or callable, default: value of *xycoords*
|
| 1721 |
+
The coordinate system that *xytext* is given in.
|
| 1722 |
+
|
| 1723 |
+
All *xycoords* values are valid as well as the following strings:
|
| 1724 |
+
|
| 1725 |
+
================= =================================================
|
| 1726 |
+
Value Description
|
| 1727 |
+
================= =================================================
|
| 1728 |
+
'offset points' Offset, in points, from the *xy* value
|
| 1729 |
+
'offset pixels' Offset, in pixels, from the *xy* value
|
| 1730 |
+
'offset fontsize' Offset, relative to fontsize, from the *xy* value
|
| 1731 |
+
================= =================================================
|
| 1732 |
+
|
| 1733 |
+
arrowprops : dict, optional
|
| 1734 |
+
The properties used to draw a `.FancyArrowPatch` arrow between the
|
| 1735 |
+
positions *xy* and *xytext*. Defaults to None, i.e. no arrow is
|
| 1736 |
+
drawn.
|
| 1737 |
+
|
| 1738 |
+
For historical reasons there are two different ways to specify
|
| 1739 |
+
arrows, "simple" and "fancy":
|
| 1740 |
+
|
| 1741 |
+
**Simple arrow:**
|
| 1742 |
+
|
| 1743 |
+
If *arrowprops* does not contain the key 'arrowstyle' the
|
| 1744 |
+
allowed keys are:
|
| 1745 |
+
|
| 1746 |
+
========== =================================================
|
| 1747 |
+
Key Description
|
| 1748 |
+
========== =================================================
|
| 1749 |
+
width The width of the arrow in points
|
| 1750 |
+
headwidth The width of the base of the arrow head in points
|
| 1751 |
+
headlength The length of the arrow head in points
|
| 1752 |
+
shrink Fraction of total length to shrink from both ends
|
| 1753 |
+
? Any `.FancyArrowPatch` property
|
| 1754 |
+
========== =================================================
|
| 1755 |
+
|
| 1756 |
+
The arrow is attached to the edge of the text box, the exact
|
| 1757 |
+
position (corners or centers) depending on where it's pointing to.
|
| 1758 |
+
|
| 1759 |
+
**Fancy arrow:**
|
| 1760 |
+
|
| 1761 |
+
This is used if 'arrowstyle' is provided in the *arrowprops*.
|
| 1762 |
+
|
| 1763 |
+
Valid keys are the following `.FancyArrowPatch` parameters:
|
| 1764 |
+
|
| 1765 |
+
=============== ===================================
|
| 1766 |
+
Key Description
|
| 1767 |
+
=============== ===================================
|
| 1768 |
+
arrowstyle The arrow style
|
| 1769 |
+
connectionstyle The connection style
|
| 1770 |
+
relpos See below; default is (0.5, 0.5)
|
| 1771 |
+
patchA Default is bounding box of the text
|
| 1772 |
+
patchB Default is None
|
| 1773 |
+
shrinkA In points. Default is 2 points
|
| 1774 |
+
shrinkB In points. Default is 2 points
|
| 1775 |
+
mutation_scale Default is text size (in points)
|
| 1776 |
+
mutation_aspect Default is 1
|
| 1777 |
+
? Any `.FancyArrowPatch` property
|
| 1778 |
+
=============== ===================================
|
| 1779 |
+
|
| 1780 |
+
The exact starting point position of the arrow is defined by
|
| 1781 |
+
*relpos*. It's a tuple of relative coordinates of the text box,
|
| 1782 |
+
where (0, 0) is the lower left corner and (1, 1) is the upper
|
| 1783 |
+
right corner. Values <0 and >1 are supported and specify points
|
| 1784 |
+
outside the text box. By default (0.5, 0.5), so the starting point
|
| 1785 |
+
is centered in the text box.
|
| 1786 |
+
|
| 1787 |
+
annotation_clip : bool or None, default: None
|
| 1788 |
+
Whether to clip (i.e. not draw) the annotation when the annotation
|
| 1789 |
+
point *xy* is outside the Axes area.
|
| 1790 |
+
|
| 1791 |
+
- If *True*, the annotation will be clipped when *xy* is outside
|
| 1792 |
+
the Axes.
|
| 1793 |
+
- If *False*, the annotation will always be drawn.
|
| 1794 |
+
- If *None*, the annotation will be clipped when *xy* is outside
|
| 1795 |
+
the Axes and *xycoords* is 'data'.
|
| 1796 |
+
|
| 1797 |
+
**kwargs
|
| 1798 |
+
Additional kwargs are passed to `.Text`.
|
| 1799 |
+
|
| 1800 |
+
Returns
|
| 1801 |
+
-------
|
| 1802 |
+
`.Annotation`
|
| 1803 |
+
|
| 1804 |
+
See Also
|
| 1805 |
+
--------
|
| 1806 |
+
:ref:`annotations`
|
| 1807 |
+
|
| 1808 |
+
"""
|
| 1809 |
+
_AnnotationBase.__init__(self,
|
| 1810 |
+
xy,
|
| 1811 |
+
xycoords=xycoords,
|
| 1812 |
+
annotation_clip=annotation_clip)
|
| 1813 |
+
# warn about wonky input data
|
| 1814 |
+
if (xytext is None and
|
| 1815 |
+
textcoords is not None and
|
| 1816 |
+
textcoords != xycoords):
|
| 1817 |
+
_api.warn_external("You have used the `textcoords` kwarg, but "
|
| 1818 |
+
"not the `xytext` kwarg. This can lead to "
|
| 1819 |
+
"surprising results.")
|
| 1820 |
+
|
| 1821 |
+
# clean up textcoords and assign default
|
| 1822 |
+
if textcoords is None:
|
| 1823 |
+
textcoords = self.xycoords
|
| 1824 |
+
self._textcoords = textcoords
|
| 1825 |
+
|
| 1826 |
+
# cleanup xytext defaults
|
| 1827 |
+
if xytext is None:
|
| 1828 |
+
xytext = self.xy
|
| 1829 |
+
x, y = xytext
|
| 1830 |
+
|
| 1831 |
+
self.arrowprops = arrowprops
|
| 1832 |
+
if arrowprops is not None:
|
| 1833 |
+
arrowprops = arrowprops.copy()
|
| 1834 |
+
if "arrowstyle" in arrowprops:
|
| 1835 |
+
self._arrow_relpos = arrowprops.pop("relpos", (0.5, 0.5))
|
| 1836 |
+
else:
|
| 1837 |
+
# modified YAArrow API to be used with FancyArrowPatch
|
| 1838 |
+
for key in ['width', 'headwidth', 'headlength', 'shrink']:
|
| 1839 |
+
arrowprops.pop(key, None)
|
| 1840 |
+
if 'frac' in arrowprops:
|
| 1841 |
+
_api.warn_deprecated(
|
| 1842 |
+
"3.8", name="the (unused) 'frac' key in 'arrowprops'")
|
| 1843 |
+
arrowprops.pop("frac")
|
| 1844 |
+
self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), **arrowprops)
|
| 1845 |
+
else:
|
| 1846 |
+
self.arrow_patch = None
|
| 1847 |
+
|
| 1848 |
+
# Must come last, as some kwargs may be propagated to arrow_patch.
|
| 1849 |
+
Text.__init__(self, x, y, text, **kwargs)
|
| 1850 |
+
|
| 1851 |
+
@_api.rename_parameter("3.8", "event", "mouseevent")
|
| 1852 |
+
def contains(self, mouseevent):
|
| 1853 |
+
if self._different_canvas(mouseevent):
|
| 1854 |
+
return False, {}
|
| 1855 |
+
contains, tinfo = Text.contains(self, mouseevent)
|
| 1856 |
+
if self.arrow_patch is not None:
|
| 1857 |
+
in_patch, _ = self.arrow_patch.contains(mouseevent)
|
| 1858 |
+
contains = contains or in_patch
|
| 1859 |
+
return contains, tinfo
|
| 1860 |
+
|
| 1861 |
+
@property
|
| 1862 |
+
def xycoords(self):
|
| 1863 |
+
return self._xycoords
|
| 1864 |
+
|
| 1865 |
+
@xycoords.setter
|
| 1866 |
+
def xycoords(self, xycoords):
|
| 1867 |
+
def is_offset(s):
|
| 1868 |
+
return isinstance(s, str) and s.startswith("offset")
|
| 1869 |
+
|
| 1870 |
+
if (isinstance(xycoords, tuple) and any(map(is_offset, xycoords))
|
| 1871 |
+
or is_offset(xycoords)):
|
| 1872 |
+
raise ValueError("xycoords cannot be an offset coordinate")
|
| 1873 |
+
self._xycoords = xycoords
|
| 1874 |
+
|
| 1875 |
+
@property
|
| 1876 |
+
def xyann(self):
|
| 1877 |
+
"""
|
| 1878 |
+
The text position.
|
| 1879 |
+
|
| 1880 |
+
See also *xytext* in `.Annotation`.
|
| 1881 |
+
"""
|
| 1882 |
+
return self.get_position()
|
| 1883 |
+
|
| 1884 |
+
@xyann.setter
|
| 1885 |
+
def xyann(self, xytext):
|
| 1886 |
+
self.set_position(xytext)
|
| 1887 |
+
|
| 1888 |
+
def get_anncoords(self):
|
| 1889 |
+
"""
|
| 1890 |
+
Return the coordinate system to use for `.Annotation.xyann`.
|
| 1891 |
+
|
| 1892 |
+
See also *xycoords* in `.Annotation`.
|
| 1893 |
+
"""
|
| 1894 |
+
return self._textcoords
|
| 1895 |
+
|
| 1896 |
+
def set_anncoords(self, coords):
|
| 1897 |
+
"""
|
| 1898 |
+
Set the coordinate system to use for `.Annotation.xyann`.
|
| 1899 |
+
|
| 1900 |
+
See also *xycoords* in `.Annotation`.
|
| 1901 |
+
"""
|
| 1902 |
+
self._textcoords = coords
|
| 1903 |
+
|
| 1904 |
+
anncoords = property(get_anncoords, set_anncoords, doc="""
|
| 1905 |
+
The coordinate system to use for `.Annotation.xyann`.""")
|
| 1906 |
+
|
| 1907 |
+
def set_figure(self, fig):
|
| 1908 |
+
# docstring inherited
|
| 1909 |
+
if self.arrow_patch is not None:
|
| 1910 |
+
self.arrow_patch.set_figure(fig)
|
| 1911 |
+
Artist.set_figure(self, fig)
|
| 1912 |
+
|
| 1913 |
+
def update_positions(self, renderer):
|
| 1914 |
+
"""
|
| 1915 |
+
Update the pixel positions of the annotation text and the arrow patch.
|
| 1916 |
+
"""
|
| 1917 |
+
# generate transformation
|
| 1918 |
+
self.set_transform(self._get_xy_transform(renderer, self.anncoords))
|
| 1919 |
+
|
| 1920 |
+
arrowprops = self.arrowprops
|
| 1921 |
+
if arrowprops is None:
|
| 1922 |
+
return
|
| 1923 |
+
|
| 1924 |
+
bbox = Text.get_window_extent(self, renderer)
|
| 1925 |
+
|
| 1926 |
+
arrow_end = x1, y1 = self._get_position_xy(renderer) # Annotated pos.
|
| 1927 |
+
|
| 1928 |
+
ms = arrowprops.get("mutation_scale", self.get_size())
|
| 1929 |
+
self.arrow_patch.set_mutation_scale(ms)
|
| 1930 |
+
|
| 1931 |
+
if "arrowstyle" not in arrowprops:
|
| 1932 |
+
# Approximately simulate the YAArrow.
|
| 1933 |
+
shrink = arrowprops.get('shrink', 0.0)
|
| 1934 |
+
width = arrowprops.get('width', 4)
|
| 1935 |
+
headwidth = arrowprops.get('headwidth', 12)
|
| 1936 |
+
headlength = arrowprops.get('headlength', 12)
|
| 1937 |
+
|
| 1938 |
+
# NB: ms is in pts
|
| 1939 |
+
stylekw = dict(head_length=headlength / ms,
|
| 1940 |
+
head_width=headwidth / ms,
|
| 1941 |
+
tail_width=width / ms)
|
| 1942 |
+
|
| 1943 |
+
self.arrow_patch.set_arrowstyle('simple', **stylekw)
|
| 1944 |
+
|
| 1945 |
+
# using YAArrow style:
|
| 1946 |
+
# pick the corner of the text bbox closest to annotated point.
|
| 1947 |
+
xpos = [(bbox.x0, 0), ((bbox.x0 + bbox.x1) / 2, 0.5), (bbox.x1, 1)]
|
| 1948 |
+
ypos = [(bbox.y0, 0), ((bbox.y0 + bbox.y1) / 2, 0.5), (bbox.y1, 1)]
|
| 1949 |
+
x, relposx = min(xpos, key=lambda v: abs(v[0] - x1))
|
| 1950 |
+
y, relposy = min(ypos, key=lambda v: abs(v[0] - y1))
|
| 1951 |
+
self._arrow_relpos = (relposx, relposy)
|
| 1952 |
+
r = np.hypot(y - y1, x - x1)
|
| 1953 |
+
shrink_pts = shrink * r / renderer.points_to_pixels(1)
|
| 1954 |
+
self.arrow_patch.shrinkA = self.arrow_patch.shrinkB = shrink_pts
|
| 1955 |
+
|
| 1956 |
+
# adjust the starting point of the arrow relative to the textbox.
|
| 1957 |
+
# TODO : Rotation needs to be accounted.
|
| 1958 |
+
arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos
|
| 1959 |
+
# The arrow is drawn from arrow_begin to arrow_end. It will be first
|
| 1960 |
+
# clipped by patchA and patchB. Then it will be shrunk by shrinkA and
|
| 1961 |
+
# shrinkB (in points). If patchA is not set, self.bbox_patch is used.
|
| 1962 |
+
self.arrow_patch.set_positions(arrow_begin, arrow_end)
|
| 1963 |
+
|
| 1964 |
+
if "patchA" in arrowprops:
|
| 1965 |
+
patchA = arrowprops["patchA"]
|
| 1966 |
+
elif self._bbox_patch:
|
| 1967 |
+
patchA = self._bbox_patch
|
| 1968 |
+
elif self.get_text() == "":
|
| 1969 |
+
patchA = None
|
| 1970 |
+
else:
|
| 1971 |
+
pad = renderer.points_to_pixels(4)
|
| 1972 |
+
patchA = Rectangle(
|
| 1973 |
+
xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2),
|
| 1974 |
+
width=bbox.width + pad, height=bbox.height + pad,
|
| 1975 |
+
transform=IdentityTransform(), clip_on=False)
|
| 1976 |
+
self.arrow_patch.set_patchA(patchA)
|
| 1977 |
+
|
| 1978 |
+
@artist.allow_rasterization
|
| 1979 |
+
def draw(self, renderer):
|
| 1980 |
+
# docstring inherited
|
| 1981 |
+
if renderer is not None:
|
| 1982 |
+
self._renderer = renderer
|
| 1983 |
+
if not self.get_visible() or not self._check_xy(renderer):
|
| 1984 |
+
return
|
| 1985 |
+
# Update text positions before `Text.draw` would, so that the
|
| 1986 |
+
# FancyArrowPatch is correctly positioned.
|
| 1987 |
+
self.update_positions(renderer)
|
| 1988 |
+
self.update_bbox_position_size(renderer)
|
| 1989 |
+
if self.arrow_patch is not None: # FancyArrowPatch
|
| 1990 |
+
if self.arrow_patch.figure is None and self.figure is not None:
|
| 1991 |
+
self.arrow_patch.figure = self.figure
|
| 1992 |
+
self.arrow_patch.draw(renderer)
|
| 1993 |
+
# Draw text, including FancyBboxPatch, after FancyArrowPatch.
|
| 1994 |
+
# Otherwise, a wedge arrowstyle can land partly on top of the Bbox.
|
| 1995 |
+
Text.draw(self, renderer)
|
| 1996 |
+
|
| 1997 |
+
def get_window_extent(self, renderer=None):
|
| 1998 |
+
# docstring inherited
|
| 1999 |
+
# This block is the same as in Text.get_window_extent, but we need to
|
| 2000 |
+
# set the renderer before calling update_positions().
|
| 2001 |
+
if not self.get_visible() or not self._check_xy(renderer):
|
| 2002 |
+
return Bbox.unit()
|
| 2003 |
+
if renderer is not None:
|
| 2004 |
+
self._renderer = renderer
|
| 2005 |
+
if self._renderer is None:
|
| 2006 |
+
self._renderer = self.figure._get_renderer()
|
| 2007 |
+
if self._renderer is None:
|
| 2008 |
+
raise RuntimeError('Cannot get window extent without renderer')
|
| 2009 |
+
|
| 2010 |
+
self.update_positions(self._renderer)
|
| 2011 |
+
|
| 2012 |
+
text_bbox = Text.get_window_extent(self)
|
| 2013 |
+
bboxes = [text_bbox]
|
| 2014 |
+
|
| 2015 |
+
if self.arrow_patch is not None:
|
| 2016 |
+
bboxes.append(self.arrow_patch.get_window_extent())
|
| 2017 |
+
|
| 2018 |
+
return Bbox.union(bboxes)
|
| 2019 |
+
|
| 2020 |
+
def get_tightbbox(self, renderer=None):
|
| 2021 |
+
# docstring inherited
|
| 2022 |
+
if not self._check_xy(renderer):
|
| 2023 |
+
return Bbox.null()
|
| 2024 |
+
return super().get_tightbbox(renderer)
|
| 2025 |
+
|
| 2026 |
+
|
| 2027 |
+
_docstring.interpd.update(Annotation=Annotation.__init__.__doc__)
|
parrot/lib/python3.10/site-packages/matplotlib/textpath.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 _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 |
+
s : str
|
| 82 |
+
The text to be converted.
|
| 83 |
+
ismath : {False, True, "TeX"}
|
| 84 |
+
If True, use mathtext parser. If "TeX", use tex for rendering.
|
| 85 |
+
|
| 86 |
+
Returns
|
| 87 |
+
-------
|
| 88 |
+
verts : list
|
| 89 |
+
A list of arrays containing the (x, y) coordinates of the vertices.
|
| 90 |
+
codes : list
|
| 91 |
+
A list of path codes.
|
| 92 |
+
|
| 93 |
+
Examples
|
| 94 |
+
--------
|
| 95 |
+
Create a list of vertices and codes from a text, and create a `.Path`
|
| 96 |
+
from those::
|
| 97 |
+
|
| 98 |
+
from matplotlib.path import Path
|
| 99 |
+
from matplotlib.text import TextToPath
|
| 100 |
+
from matplotlib.font_manager import FontProperties
|
| 101 |
+
|
| 102 |
+
fp = FontProperties(family="Comic Neue", style="italic")
|
| 103 |
+
verts, codes = TextToPath().get_text_path(fp, "ABC")
|
| 104 |
+
path = Path(verts, codes, closed=False)
|
| 105 |
+
|
| 106 |
+
Also see `TextPath` for a more direct way to create a path from a text.
|
| 107 |
+
"""
|
| 108 |
+
if ismath == "TeX":
|
| 109 |
+
glyph_info, glyph_map, rects = self.get_glyphs_tex(prop, s)
|
| 110 |
+
elif not ismath:
|
| 111 |
+
font = self._get_font(prop)
|
| 112 |
+
glyph_info, glyph_map, rects = self.get_glyphs_with_font(font, s)
|
| 113 |
+
else:
|
| 114 |
+
glyph_info, glyph_map, rects = self.get_glyphs_mathtext(prop, s)
|
| 115 |
+
|
| 116 |
+
verts, codes = [], []
|
| 117 |
+
for glyph_id, xposition, yposition, scale in glyph_info:
|
| 118 |
+
verts1, codes1 = glyph_map[glyph_id]
|
| 119 |
+
verts.extend(verts1 * scale + [xposition, yposition])
|
| 120 |
+
codes.extend(codes1)
|
| 121 |
+
for verts1, codes1 in rects:
|
| 122 |
+
verts.extend(verts1)
|
| 123 |
+
codes.extend(codes1)
|
| 124 |
+
|
| 125 |
+
# Make sure an empty string or one with nothing to print
|
| 126 |
+
# (e.g. only spaces & newlines) will be valid/empty path
|
| 127 |
+
if not verts:
|
| 128 |
+
verts = np.empty((0, 2))
|
| 129 |
+
|
| 130 |
+
return verts, codes
|
| 131 |
+
|
| 132 |
+
def get_glyphs_with_font(self, font, s, glyph_map=None,
|
| 133 |
+
return_new_glyphs_only=False):
|
| 134 |
+
"""
|
| 135 |
+
Convert string *s* to vertices and codes using the provided ttf font.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
if glyph_map is None:
|
| 139 |
+
glyph_map = OrderedDict()
|
| 140 |
+
|
| 141 |
+
if return_new_glyphs_only:
|
| 142 |
+
glyph_map_new = OrderedDict()
|
| 143 |
+
else:
|
| 144 |
+
glyph_map_new = glyph_map
|
| 145 |
+
|
| 146 |
+
xpositions = []
|
| 147 |
+
glyph_ids = []
|
| 148 |
+
for item in _text_helpers.layout(s, font):
|
| 149 |
+
char_id = self._get_char_id(item.ft_object, ord(item.char))
|
| 150 |
+
glyph_ids.append(char_id)
|
| 151 |
+
xpositions.append(item.x)
|
| 152 |
+
if char_id not in glyph_map:
|
| 153 |
+
glyph_map_new[char_id] = item.ft_object.get_path()
|
| 154 |
+
|
| 155 |
+
ypositions = [0] * len(xpositions)
|
| 156 |
+
sizes = [1.] * len(xpositions)
|
| 157 |
+
|
| 158 |
+
rects = []
|
| 159 |
+
|
| 160 |
+
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
|
| 161 |
+
glyph_map_new, rects)
|
| 162 |
+
|
| 163 |
+
def get_glyphs_mathtext(self, prop, s, glyph_map=None,
|
| 164 |
+
return_new_glyphs_only=False):
|
| 165 |
+
"""
|
| 166 |
+
Parse mathtext string *s* and convert it to a (vertices, codes) pair.
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
prop = prop.copy()
|
| 170 |
+
prop.set_size(self.FONT_SCALE)
|
| 171 |
+
|
| 172 |
+
width, height, descent, glyphs, rects = self.mathtext_parser.parse(
|
| 173 |
+
s, self.DPI, prop)
|
| 174 |
+
|
| 175 |
+
if not glyph_map:
|
| 176 |
+
glyph_map = OrderedDict()
|
| 177 |
+
|
| 178 |
+
if return_new_glyphs_only:
|
| 179 |
+
glyph_map_new = OrderedDict()
|
| 180 |
+
else:
|
| 181 |
+
glyph_map_new = glyph_map
|
| 182 |
+
|
| 183 |
+
xpositions = []
|
| 184 |
+
ypositions = []
|
| 185 |
+
glyph_ids = []
|
| 186 |
+
sizes = []
|
| 187 |
+
|
| 188 |
+
for font, fontsize, ccode, ox, oy in glyphs:
|
| 189 |
+
char_id = self._get_char_id(font, ccode)
|
| 190 |
+
if char_id not in glyph_map:
|
| 191 |
+
font.clear()
|
| 192 |
+
font.set_size(self.FONT_SCALE, self.DPI)
|
| 193 |
+
font.load_char(ccode, flags=LOAD_NO_HINTING)
|
| 194 |
+
glyph_map_new[char_id] = font.get_path()
|
| 195 |
+
|
| 196 |
+
xpositions.append(ox)
|
| 197 |
+
ypositions.append(oy)
|
| 198 |
+
glyph_ids.append(char_id)
|
| 199 |
+
size = fontsize / self.FONT_SCALE
|
| 200 |
+
sizes.append(size)
|
| 201 |
+
|
| 202 |
+
myrects = []
|
| 203 |
+
for ox, oy, w, h in rects:
|
| 204 |
+
vert1 = [(ox, oy), (ox, oy + h), (ox + w, oy + h),
|
| 205 |
+
(ox + w, oy), (ox, oy), (0, 0)]
|
| 206 |
+
code1 = [Path.MOVETO,
|
| 207 |
+
Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
|
| 208 |
+
Path.CLOSEPOLY]
|
| 209 |
+
myrects.append((vert1, code1))
|
| 210 |
+
|
| 211 |
+
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
|
| 212 |
+
glyph_map_new, myrects)
|
| 213 |
+
|
| 214 |
+
def get_glyphs_tex(self, prop, s, glyph_map=None,
|
| 215 |
+
return_new_glyphs_only=False):
|
| 216 |
+
"""Convert the string *s* to vertices and codes using usetex mode."""
|
| 217 |
+
# Mostly borrowed from pdf backend.
|
| 218 |
+
|
| 219 |
+
dvifile = TexManager().make_dvi(s, self.FONT_SCALE)
|
| 220 |
+
with dviread.Dvi(dvifile, self.DPI) as dvi:
|
| 221 |
+
page, = dvi
|
| 222 |
+
|
| 223 |
+
if glyph_map is None:
|
| 224 |
+
glyph_map = OrderedDict()
|
| 225 |
+
|
| 226 |
+
if return_new_glyphs_only:
|
| 227 |
+
glyph_map_new = OrderedDict()
|
| 228 |
+
else:
|
| 229 |
+
glyph_map_new = glyph_map
|
| 230 |
+
|
| 231 |
+
glyph_ids, xpositions, ypositions, sizes = [], [], [], []
|
| 232 |
+
|
| 233 |
+
# Gather font information and do some setup for combining
|
| 234 |
+
# characters into strings.
|
| 235 |
+
for text in page.text:
|
| 236 |
+
font = get_font(text.font_path)
|
| 237 |
+
char_id = self._get_char_id(font, text.glyph)
|
| 238 |
+
if char_id not in glyph_map:
|
| 239 |
+
font.clear()
|
| 240 |
+
font.set_size(self.FONT_SCALE, self.DPI)
|
| 241 |
+
glyph_name_or_index = text.glyph_name_or_index
|
| 242 |
+
if isinstance(glyph_name_or_index, str):
|
| 243 |
+
index = font.get_name_index(glyph_name_or_index)
|
| 244 |
+
font.load_glyph(index, flags=LOAD_TARGET_LIGHT)
|
| 245 |
+
elif isinstance(glyph_name_or_index, int):
|
| 246 |
+
self._select_native_charmap(font)
|
| 247 |
+
font.load_char(
|
| 248 |
+
glyph_name_or_index, flags=LOAD_TARGET_LIGHT)
|
| 249 |
+
else: # Should not occur.
|
| 250 |
+
raise TypeError(f"Glyph spec of unexpected type: "
|
| 251 |
+
f"{glyph_name_or_index!r}")
|
| 252 |
+
glyph_map_new[char_id] = font.get_path()
|
| 253 |
+
|
| 254 |
+
glyph_ids.append(char_id)
|
| 255 |
+
xpositions.append(text.x)
|
| 256 |
+
ypositions.append(text.y)
|
| 257 |
+
sizes.append(text.font_size / self.FONT_SCALE)
|
| 258 |
+
|
| 259 |
+
myrects = []
|
| 260 |
+
|
| 261 |
+
for ox, oy, h, w in page.boxes:
|
| 262 |
+
vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h),
|
| 263 |
+
(ox, oy + h), (ox, oy), (0, 0)]
|
| 264 |
+
code1 = [Path.MOVETO,
|
| 265 |
+
Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
|
| 266 |
+
Path.CLOSEPOLY]
|
| 267 |
+
myrects.append((vert1, code1))
|
| 268 |
+
|
| 269 |
+
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
|
| 270 |
+
glyph_map_new, myrects)
|
| 271 |
+
|
| 272 |
+
@staticmethod
|
| 273 |
+
def _select_native_charmap(font):
|
| 274 |
+
# Select the native charmap. (we can't directly identify it but it's
|
| 275 |
+
# typically an Adobe charmap).
|
| 276 |
+
for charmap_code in [
|
| 277 |
+
1094992451, # ADOBE_CUSTOM.
|
| 278 |
+
1094995778, # ADOBE_STANDARD.
|
| 279 |
+
]:
|
| 280 |
+
try:
|
| 281 |
+
font.select_charmap(charmap_code)
|
| 282 |
+
except (ValueError, RuntimeError):
|
| 283 |
+
pass
|
| 284 |
+
else:
|
| 285 |
+
break
|
| 286 |
+
else:
|
| 287 |
+
_log.warning("No supported encoding in font (%s).", font.fname)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
text_to_path = TextToPath()
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class TextPath(Path):
|
| 294 |
+
"""
|
| 295 |
+
Create a path from the text.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
def __init__(self, xy, s, size=None, prop=None,
|
| 299 |
+
_interpolation_steps=1, usetex=False):
|
| 300 |
+
r"""
|
| 301 |
+
Create a path from the text. Note that it simply is a path,
|
| 302 |
+
not an artist. You need to use the `.PathPatch` (or other artists)
|
| 303 |
+
to draw this path onto the canvas.
|
| 304 |
+
|
| 305 |
+
Parameters
|
| 306 |
+
----------
|
| 307 |
+
xy : tuple or array of two float values
|
| 308 |
+
Position of the text. For no offset, use ``xy=(0, 0)``.
|
| 309 |
+
|
| 310 |
+
s : str
|
| 311 |
+
The text to convert to a path.
|
| 312 |
+
|
| 313 |
+
size : float, optional
|
| 314 |
+
Font size in points. Defaults to the size specified via the font
|
| 315 |
+
properties *prop*.
|
| 316 |
+
|
| 317 |
+
prop : `~matplotlib.font_manager.FontProperties`, optional
|
| 318 |
+
Font property. If not provided, will use a default
|
| 319 |
+
`.FontProperties` with parameters from the
|
| 320 |
+
:ref:`rcParams<customizing-with-dynamic-rc-settings>`.
|
| 321 |
+
|
| 322 |
+
_interpolation_steps : int, optional
|
| 323 |
+
(Currently ignored)
|
| 324 |
+
|
| 325 |
+
usetex : bool, default: False
|
| 326 |
+
Whether to use tex rendering.
|
| 327 |
+
|
| 328 |
+
Examples
|
| 329 |
+
--------
|
| 330 |
+
The following creates a path from the string "ABC" with Helvetica
|
| 331 |
+
font face; and another path from the latex fraction 1/2::
|
| 332 |
+
|
| 333 |
+
from matplotlib.text import TextPath
|
| 334 |
+
from matplotlib.font_manager import FontProperties
|
| 335 |
+
|
| 336 |
+
fp = FontProperties(family="Helvetica", style="italic")
|
| 337 |
+
path1 = TextPath((12, 12), "ABC", size=12, prop=fp)
|
| 338 |
+
path2 = TextPath((0, 0), r"$\frac{1}{2}$", size=12, usetex=True)
|
| 339 |
+
|
| 340 |
+
Also see :doc:`/gallery/text_labels_and_annotations/demo_text_path`.
|
| 341 |
+
"""
|
| 342 |
+
# Circular import.
|
| 343 |
+
from matplotlib.text import Text
|
| 344 |
+
|
| 345 |
+
prop = FontProperties._from_any(prop)
|
| 346 |
+
if size is None:
|
| 347 |
+
size = prop.get_size_in_points()
|
| 348 |
+
|
| 349 |
+
self._xy = xy
|
| 350 |
+
self.set_size(size)
|
| 351 |
+
|
| 352 |
+
self._cached_vertices = None
|
| 353 |
+
s, ismath = Text(usetex=usetex)._preprocess_math(s)
|
| 354 |
+
super().__init__(
|
| 355 |
+
*text_to_path.get_text_path(prop, s, ismath=ismath),
|
| 356 |
+
_interpolation_steps=_interpolation_steps,
|
| 357 |
+
readonly=True)
|
| 358 |
+
self._should_simplify = False
|
| 359 |
+
|
| 360 |
+
def set_size(self, size):
|
| 361 |
+
"""Set the text size."""
|
| 362 |
+
self._size = size
|
| 363 |
+
self._invalid = True
|
| 364 |
+
|
| 365 |
+
def get_size(self):
|
| 366 |
+
"""Get the text size."""
|
| 367 |
+
return self._size
|
| 368 |
+
|
| 369 |
+
@property
|
| 370 |
+
def vertices(self):
|
| 371 |
+
"""
|
| 372 |
+
Return the cached path after updating it if necessary.
|
| 373 |
+
"""
|
| 374 |
+
self._revalidate_path()
|
| 375 |
+
return self._cached_vertices
|
| 376 |
+
|
| 377 |
+
@property
|
| 378 |
+
def codes(self):
|
| 379 |
+
"""
|
| 380 |
+
Return the codes
|
| 381 |
+
"""
|
| 382 |
+
return self._codes
|
| 383 |
+
|
| 384 |
+
def _revalidate_path(self):
|
| 385 |
+
"""
|
| 386 |
+
Update the path if necessary.
|
| 387 |
+
|
| 388 |
+
The path for the text is initially create with the font size of
|
| 389 |
+
`.FONT_SCALE`, and this path is rescaled to other size when necessary.
|
| 390 |
+
"""
|
| 391 |
+
if self._invalid or self._cached_vertices is None:
|
| 392 |
+
tr = (Affine2D()
|
| 393 |
+
.scale(self._size / text_to_path.FONT_SCALE)
|
| 394 |
+
.translate(*self._xy))
|
| 395 |
+
self._cached_vertices = tr.transform(self._vertices)
|
| 396 |
+
self._cached_vertices.flags.writeable = False
|
| 397 |
+
self._invalid = False
|
parrot/lib/python3.10/site-packages/matplotlib/widgets.pyi
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .artist import Artist
|
| 2 |
+
from .axes import Axes
|
| 3 |
+
from .backend_bases import FigureCanvasBase, Event, MouseEvent, MouseButton
|
| 4 |
+
from .collections import LineCollection
|
| 5 |
+
from .figure import Figure
|
| 6 |
+
from .lines import Line2D
|
| 7 |
+
from .patches import Circle, Polygon, Rectangle
|
| 8 |
+
from .text import Text
|
| 9 |
+
|
| 10 |
+
import PIL.Image
|
| 11 |
+
|
| 12 |
+
from collections.abc import Callable, Collection, Iterable, Sequence
|
| 13 |
+
from typing import Any, Literal
|
| 14 |
+
from numpy.typing import ArrayLike
|
| 15 |
+
from .typing import ColorType
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
class LockDraw:
|
| 19 |
+
def __init__(self) -> None: ...
|
| 20 |
+
def __call__(self, o: Any) -> None: ...
|
| 21 |
+
def release(self, o: Any) -> None: ...
|
| 22 |
+
def available(self, o: Any) -> bool: ...
|
| 23 |
+
def isowner(self, o: Any) -> bool: ...
|
| 24 |
+
def locked(self) -> bool: ...
|
| 25 |
+
|
| 26 |
+
class Widget:
|
| 27 |
+
drawon: bool
|
| 28 |
+
eventson: bool
|
| 29 |
+
active: bool
|
| 30 |
+
def set_active(self, active: bool) -> None: ...
|
| 31 |
+
def get_active(self) -> None: ...
|
| 32 |
+
def ignore(self, event) -> bool: ...
|
| 33 |
+
|
| 34 |
+
class AxesWidget(Widget):
|
| 35 |
+
ax: Axes
|
| 36 |
+
def __init__(self, ax: Axes) -> None: ...
|
| 37 |
+
@property
|
| 38 |
+
def canvas(self) -> FigureCanvasBase | None: ...
|
| 39 |
+
def connect_event(self, event: Event, callback: Callable) -> None: ...
|
| 40 |
+
def disconnect_events(self) -> None: ...
|
| 41 |
+
|
| 42 |
+
class Button(AxesWidget):
|
| 43 |
+
label: Text
|
| 44 |
+
color: ColorType
|
| 45 |
+
hovercolor: ColorType
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
ax: Axes,
|
| 49 |
+
label: str,
|
| 50 |
+
image: ArrayLike | PIL.Image.Image | None = ...,
|
| 51 |
+
color: ColorType = ...,
|
| 52 |
+
hovercolor: ColorType = ...,
|
| 53 |
+
*,
|
| 54 |
+
useblit: bool = ...
|
| 55 |
+
) -> None: ...
|
| 56 |
+
def on_clicked(self, func: Callable[[Event], Any]) -> int: ...
|
| 57 |
+
def disconnect(self, cid: int) -> None: ...
|
| 58 |
+
|
| 59 |
+
class SliderBase(AxesWidget):
|
| 60 |
+
orientation: Literal["horizontal", "vertical"]
|
| 61 |
+
closedmin: bool
|
| 62 |
+
closedmax: bool
|
| 63 |
+
valmin: float
|
| 64 |
+
valmax: float
|
| 65 |
+
valstep: float | ArrayLike | None
|
| 66 |
+
drag_active: bool
|
| 67 |
+
valfmt: str
|
| 68 |
+
def __init__(
|
| 69 |
+
self,
|
| 70 |
+
ax: Axes,
|
| 71 |
+
orientation: Literal["horizontal", "vertical"],
|
| 72 |
+
closedmin: bool,
|
| 73 |
+
closedmax: bool,
|
| 74 |
+
valmin: float,
|
| 75 |
+
valmax: float,
|
| 76 |
+
valfmt: str,
|
| 77 |
+
dragging: Slider | None,
|
| 78 |
+
valstep: float | ArrayLike | None,
|
| 79 |
+
) -> None: ...
|
| 80 |
+
def disconnect(self, cid: int) -> None: ...
|
| 81 |
+
def reset(self) -> None: ...
|
| 82 |
+
|
| 83 |
+
class Slider(SliderBase):
|
| 84 |
+
slidermin: Slider | None
|
| 85 |
+
slidermax: Slider | None
|
| 86 |
+
val: float
|
| 87 |
+
valinit: float
|
| 88 |
+
track: Rectangle
|
| 89 |
+
poly: Polygon
|
| 90 |
+
hline: Line2D
|
| 91 |
+
vline: Line2D
|
| 92 |
+
label: Text
|
| 93 |
+
valtext: Text
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
ax: Axes,
|
| 97 |
+
label: str,
|
| 98 |
+
valmin: float,
|
| 99 |
+
valmax: float,
|
| 100 |
+
*,
|
| 101 |
+
valinit: float = ...,
|
| 102 |
+
valfmt: str | None = ...,
|
| 103 |
+
closedmin: bool = ...,
|
| 104 |
+
closedmax: bool = ...,
|
| 105 |
+
slidermin: Slider | None = ...,
|
| 106 |
+
slidermax: Slider | None = ...,
|
| 107 |
+
dragging: bool = ...,
|
| 108 |
+
valstep: float | ArrayLike | None = ...,
|
| 109 |
+
orientation: Literal["horizontal", "vertical"] = ...,
|
| 110 |
+
initcolor: ColorType = ...,
|
| 111 |
+
track_color: ColorType = ...,
|
| 112 |
+
handle_style: dict[str, Any] | None = ...,
|
| 113 |
+
**kwargs
|
| 114 |
+
) -> None: ...
|
| 115 |
+
def set_val(self, val: float) -> None: ...
|
| 116 |
+
def on_changed(self, func: Callable[[float], Any]) -> int: ...
|
| 117 |
+
|
| 118 |
+
class RangeSlider(SliderBase):
|
| 119 |
+
val: tuple[float, float]
|
| 120 |
+
valinit: tuple[float, float]
|
| 121 |
+
track: Rectangle
|
| 122 |
+
poly: Polygon
|
| 123 |
+
label: Text
|
| 124 |
+
valtext: Text
|
| 125 |
+
def __init__(
|
| 126 |
+
self,
|
| 127 |
+
ax: Axes,
|
| 128 |
+
label: str,
|
| 129 |
+
valmin: float,
|
| 130 |
+
valmax: float,
|
| 131 |
+
*,
|
| 132 |
+
valinit: tuple[float, float] | None = ...,
|
| 133 |
+
valfmt: str | None = ...,
|
| 134 |
+
closedmin: bool = ...,
|
| 135 |
+
closedmax: bool = ...,
|
| 136 |
+
dragging: bool = ...,
|
| 137 |
+
valstep: float | ArrayLike | None = ...,
|
| 138 |
+
orientation: Literal["horizontal", "vertical"] = ...,
|
| 139 |
+
track_color: ColorType = ...,
|
| 140 |
+
handle_style: dict[str, Any] | None = ...,
|
| 141 |
+
**kwargs
|
| 142 |
+
) -> None: ...
|
| 143 |
+
def set_min(self, min: float) -> None: ...
|
| 144 |
+
def set_max(self, max: float) -> None: ...
|
| 145 |
+
def set_val(self, val: ArrayLike) -> None: ...
|
| 146 |
+
def on_changed(self, func: Callable[[tuple[float, float]], Any]) -> int: ...
|
| 147 |
+
|
| 148 |
+
class CheckButtons(AxesWidget):
|
| 149 |
+
labels: list[Text]
|
| 150 |
+
def __init__(
|
| 151 |
+
self,
|
| 152 |
+
ax: Axes,
|
| 153 |
+
labels: Sequence[str],
|
| 154 |
+
actives: Iterable[bool] | None = ...,
|
| 155 |
+
*,
|
| 156 |
+
useblit: bool = ...,
|
| 157 |
+
label_props: dict[str, Any] | None = ...,
|
| 158 |
+
frame_props: dict[str, Any] | None = ...,
|
| 159 |
+
check_props: dict[str, Any] | None = ...,
|
| 160 |
+
) -> None: ...
|
| 161 |
+
def set_label_props(self, props: dict[str, Any]) -> None: ...
|
| 162 |
+
def set_frame_props(self, props: dict[str, Any]) -> None: ...
|
| 163 |
+
def set_check_props(self, props: dict[str, Any]) -> None: ...
|
| 164 |
+
def set_active(self, index: int, state: bool | None = ...) -> None: ... # type: ignore[override]
|
| 165 |
+
def clear(self) -> None: ...
|
| 166 |
+
def get_status(self) -> list[bool]: ...
|
| 167 |
+
def get_checked_labels(self) -> list[str]: ...
|
| 168 |
+
def on_clicked(self, func: Callable[[str | None], Any]) -> int: ...
|
| 169 |
+
def disconnect(self, cid: int) -> None: ...
|
| 170 |
+
|
| 171 |
+
class TextBox(AxesWidget):
|
| 172 |
+
label: Text
|
| 173 |
+
text_disp: Text
|
| 174 |
+
cursor_index: int
|
| 175 |
+
cursor: LineCollection
|
| 176 |
+
color: ColorType
|
| 177 |
+
hovercolor: ColorType
|
| 178 |
+
capturekeystrokes: bool
|
| 179 |
+
def __init__(
|
| 180 |
+
self,
|
| 181 |
+
ax: Axes,
|
| 182 |
+
label: str,
|
| 183 |
+
initial: str = ...,
|
| 184 |
+
*,
|
| 185 |
+
color: ColorType = ...,
|
| 186 |
+
hovercolor: ColorType = ...,
|
| 187 |
+
label_pad: float = ...,
|
| 188 |
+
textalignment: Literal["left", "center", "right"] = ...,
|
| 189 |
+
) -> None: ...
|
| 190 |
+
@property
|
| 191 |
+
def text(self) -> str: ...
|
| 192 |
+
def set_val(self, val: str) -> None: ...
|
| 193 |
+
def begin_typing(self) -> None: ...
|
| 194 |
+
def stop_typing(self) -> None: ...
|
| 195 |
+
def on_text_change(self, func: Callable[[str], Any]) -> int: ...
|
| 196 |
+
def on_submit(self, func: Callable[[str], Any]) -> int: ...
|
| 197 |
+
def disconnect(self, cid: int) -> None: ...
|
| 198 |
+
|
| 199 |
+
class RadioButtons(AxesWidget):
|
| 200 |
+
activecolor: ColorType
|
| 201 |
+
value_selected: str
|
| 202 |
+
labels: list[Text]
|
| 203 |
+
def __init__(
|
| 204 |
+
self,
|
| 205 |
+
ax: Axes,
|
| 206 |
+
labels: Iterable[str],
|
| 207 |
+
active: int = ...,
|
| 208 |
+
activecolor: ColorType | None = ...,
|
| 209 |
+
*,
|
| 210 |
+
useblit: bool = ...,
|
| 211 |
+
label_props: dict[str, Any] | Sequence[dict[str, Any]] | None = ...,
|
| 212 |
+
radio_props: dict[str, Any] | None = ...,
|
| 213 |
+
) -> None: ...
|
| 214 |
+
def set_label_props(self, props: dict[str, Any]) -> None: ...
|
| 215 |
+
def set_radio_props(self, props: dict[str, Any]) -> None: ...
|
| 216 |
+
def set_active(self, index: int) -> None: ...
|
| 217 |
+
def clear(self) -> None: ...
|
| 218 |
+
def on_clicked(self, func: Callable[[str | None], Any]) -> int: ...
|
| 219 |
+
def disconnect(self, cid: int) -> None: ...
|
| 220 |
+
|
| 221 |
+
class SubplotTool(Widget):
|
| 222 |
+
figure: Figure
|
| 223 |
+
targetfig: Figure
|
| 224 |
+
buttonreset: Button
|
| 225 |
+
def __init__(self, targetfig: Figure, toolfig: Figure) -> None: ...
|
| 226 |
+
|
| 227 |
+
class Cursor(AxesWidget):
|
| 228 |
+
visible: bool
|
| 229 |
+
horizOn: bool
|
| 230 |
+
vertOn: bool
|
| 231 |
+
useblit: bool
|
| 232 |
+
lineh: Line2D
|
| 233 |
+
linev: Line2D
|
| 234 |
+
background: Any
|
| 235 |
+
needclear: bool
|
| 236 |
+
def __init__(
|
| 237 |
+
self,
|
| 238 |
+
ax: Axes,
|
| 239 |
+
*,
|
| 240 |
+
horizOn: bool = ...,
|
| 241 |
+
vertOn: bool = ...,
|
| 242 |
+
useblit: bool = ...,
|
| 243 |
+
**lineprops
|
| 244 |
+
) -> None: ...
|
| 245 |
+
def clear(self, event: Event) -> None: ...
|
| 246 |
+
def onmove(self, event: Event) -> None: ...
|
| 247 |
+
|
| 248 |
+
class MultiCursor(Widget):
|
| 249 |
+
axes: Sequence[Axes]
|
| 250 |
+
horizOn: bool
|
| 251 |
+
vertOn: bool
|
| 252 |
+
visible: bool
|
| 253 |
+
useblit: bool
|
| 254 |
+
vlines: list[Line2D]
|
| 255 |
+
hlines: list[Line2D]
|
| 256 |
+
def __init__(
|
| 257 |
+
self,
|
| 258 |
+
canvas: Any,
|
| 259 |
+
axes: Sequence[Axes],
|
| 260 |
+
*,
|
| 261 |
+
useblit: bool = ...,
|
| 262 |
+
horizOn: bool = ...,
|
| 263 |
+
vertOn: bool = ...,
|
| 264 |
+
**lineprops
|
| 265 |
+
) -> None: ...
|
| 266 |
+
def connect(self) -> None: ...
|
| 267 |
+
def disconnect(self) -> None: ...
|
| 268 |
+
def clear(self, event: Event) -> None: ...
|
| 269 |
+
def onmove(self, event: Event) -> None: ...
|
| 270 |
+
|
| 271 |
+
class _SelectorWidget(AxesWidget):
|
| 272 |
+
onselect: Callable[[float, float], Any]
|
| 273 |
+
useblit: bool
|
| 274 |
+
background: Any
|
| 275 |
+
validButtons: list[MouseButton]
|
| 276 |
+
def __init__(
|
| 277 |
+
self,
|
| 278 |
+
ax: Axes,
|
| 279 |
+
onselect: Callable[[float, float], Any],
|
| 280 |
+
useblit: bool = ...,
|
| 281 |
+
button: MouseButton | Collection[MouseButton] | None = ...,
|
| 282 |
+
state_modifier_keys: dict[str, str] | None = ...,
|
| 283 |
+
use_data_coordinates: bool = ...,
|
| 284 |
+
) -> None: ...
|
| 285 |
+
def update_background(self, event: Event) -> None: ...
|
| 286 |
+
def connect_default_events(self) -> None: ...
|
| 287 |
+
def ignore(self, event: Event) -> bool: ...
|
| 288 |
+
def update(self) -> None: ...
|
| 289 |
+
def press(self, event: Event) -> bool: ...
|
| 290 |
+
def release(self, event: Event) -> bool: ...
|
| 291 |
+
def onmove(self, event: Event) -> bool: ...
|
| 292 |
+
def on_scroll(self, event: Event) -> None: ...
|
| 293 |
+
def on_key_press(self, event: Event) -> None: ...
|
| 294 |
+
def on_key_release(self, event: Event) -> None: ...
|
| 295 |
+
def set_visible(self, visible: bool) -> None: ...
|
| 296 |
+
def get_visible(self) -> bool: ...
|
| 297 |
+
@property
|
| 298 |
+
def visible(self) -> bool: ...
|
| 299 |
+
def clear(self) -> None: ...
|
| 300 |
+
@property
|
| 301 |
+
def artists(self) -> tuple[Artist]: ...
|
| 302 |
+
def set_props(self, **props) -> None: ...
|
| 303 |
+
def set_handle_props(self, **handle_props) -> None: ...
|
| 304 |
+
def add_state(self, state: str) -> None: ...
|
| 305 |
+
def remove_state(self, state: str) -> None: ...
|
| 306 |
+
|
| 307 |
+
class SpanSelector(_SelectorWidget):
|
| 308 |
+
snap_values: ArrayLike | None
|
| 309 |
+
onmove_callback: Callable[[float, float], Any]
|
| 310 |
+
minspan: float
|
| 311 |
+
grab_range: float
|
| 312 |
+
drag_from_anywhere: bool
|
| 313 |
+
ignore_event_outside: bool
|
| 314 |
+
def __init__(
|
| 315 |
+
self,
|
| 316 |
+
ax: Axes,
|
| 317 |
+
onselect: Callable[[float, float], Any],
|
| 318 |
+
direction: Literal["horizontal", "vertical"],
|
| 319 |
+
*,
|
| 320 |
+
minspan: float = ...,
|
| 321 |
+
useblit: bool = ...,
|
| 322 |
+
props: dict[str, Any] | None = ...,
|
| 323 |
+
onmove_callback: Callable[[float, float], Any] | None = ...,
|
| 324 |
+
interactive: bool = ...,
|
| 325 |
+
button: MouseButton | Collection[MouseButton] | None = ...,
|
| 326 |
+
handle_props: dict[str, Any] | None = ...,
|
| 327 |
+
grab_range: float = ...,
|
| 328 |
+
state_modifier_keys: dict[str, str] | None = ...,
|
| 329 |
+
drag_from_anywhere: bool = ...,
|
| 330 |
+
ignore_event_outside: bool = ...,
|
| 331 |
+
snap_values: ArrayLike | None = ...,
|
| 332 |
+
) -> None: ...
|
| 333 |
+
def new_axes(
|
| 334 |
+
self,
|
| 335 |
+
ax: Axes,
|
| 336 |
+
*,
|
| 337 |
+
_props: dict[str, Any] | None = ...,
|
| 338 |
+
_init: bool = ...,
|
| 339 |
+
) -> None: ...
|
| 340 |
+
def connect_default_events(self) -> None: ...
|
| 341 |
+
@property
|
| 342 |
+
def direction(self) -> Literal["horizontal", "vertical"]: ...
|
| 343 |
+
@direction.setter
|
| 344 |
+
def direction(self, direction: Literal["horizontal", "vertical"]) -> None: ...
|
| 345 |
+
@property
|
| 346 |
+
def extents(self) -> tuple[float, float]: ...
|
| 347 |
+
@extents.setter
|
| 348 |
+
def extents(self, extents: tuple[float, float]) -> None: ...
|
| 349 |
+
|
| 350 |
+
class ToolLineHandles:
|
| 351 |
+
ax: Axes
|
| 352 |
+
def __init__(
|
| 353 |
+
self,
|
| 354 |
+
ax: Axes,
|
| 355 |
+
positions: ArrayLike,
|
| 356 |
+
direction: Literal["horizontal", "vertical"],
|
| 357 |
+
*,
|
| 358 |
+
line_props: dict[str, Any] | None = ...,
|
| 359 |
+
useblit: bool = ...,
|
| 360 |
+
) -> None: ...
|
| 361 |
+
@property
|
| 362 |
+
def artists(self) -> tuple[Line2D]: ...
|
| 363 |
+
@property
|
| 364 |
+
def positions(self) -> list[float]: ...
|
| 365 |
+
@property
|
| 366 |
+
def direction(self) -> Literal["horizontal", "vertical"]: ...
|
| 367 |
+
def set_data(self, positions: ArrayLike) -> None: ...
|
| 368 |
+
def set_visible(self, value: bool) -> None: ...
|
| 369 |
+
def set_animated(self, value: bool) -> None: ...
|
| 370 |
+
def remove(self) -> None: ...
|
| 371 |
+
def closest(self, x: float, y: float) -> tuple[int, float]: ...
|
| 372 |
+
|
| 373 |
+
class ToolHandles:
|
| 374 |
+
ax: Axes
|
| 375 |
+
def __init__(
|
| 376 |
+
self,
|
| 377 |
+
ax: Axes,
|
| 378 |
+
x: ArrayLike,
|
| 379 |
+
y: ArrayLike,
|
| 380 |
+
*,
|
| 381 |
+
marker: str = ...,
|
| 382 |
+
marker_props: dict[str, Any] | None = ...,
|
| 383 |
+
useblit: bool = ...,
|
| 384 |
+
) -> None: ...
|
| 385 |
+
@property
|
| 386 |
+
def x(self) -> ArrayLike: ...
|
| 387 |
+
@property
|
| 388 |
+
def y(self) -> ArrayLike: ...
|
| 389 |
+
@property
|
| 390 |
+
def artists(self) -> tuple[Line2D]: ...
|
| 391 |
+
def set_data(self, pts: ArrayLike, y: ArrayLike | None = ...) -> None: ...
|
| 392 |
+
def set_visible(self, val: bool) -> None: ...
|
| 393 |
+
def set_animated(self, val: bool) -> None: ...
|
| 394 |
+
def closest(self, x: float, y: float) -> tuple[int, float]: ...
|
| 395 |
+
|
| 396 |
+
class RectangleSelector(_SelectorWidget):
|
| 397 |
+
drag_from_anywhere: bool
|
| 398 |
+
ignore_event_outside: bool
|
| 399 |
+
minspanx: float
|
| 400 |
+
minspany: float
|
| 401 |
+
spancoords: Literal["data", "pixels"]
|
| 402 |
+
grab_range: float
|
| 403 |
+
def __init__(
|
| 404 |
+
self,
|
| 405 |
+
ax: Axes,
|
| 406 |
+
onselect: Callable[[MouseEvent, MouseEvent], Any],
|
| 407 |
+
*,
|
| 408 |
+
minspanx: float = ...,
|
| 409 |
+
minspany: float = ...,
|
| 410 |
+
useblit: bool = ...,
|
| 411 |
+
props: dict[str, Any] | None = ...,
|
| 412 |
+
spancoords: Literal["data", "pixels"] = ...,
|
| 413 |
+
button: MouseButton | Collection[MouseButton] | None = ...,
|
| 414 |
+
grab_range: float = ...,
|
| 415 |
+
handle_props: dict[str, Any] | None = ...,
|
| 416 |
+
interactive: bool = ...,
|
| 417 |
+
state_modifier_keys: dict[str, str] | None = ...,
|
| 418 |
+
drag_from_anywhere: bool = ...,
|
| 419 |
+
ignore_event_outside: bool = ...,
|
| 420 |
+
use_data_coordinates: bool = ...,
|
| 421 |
+
) -> None: ...
|
| 422 |
+
@property
|
| 423 |
+
def corners(self) -> tuple[np.ndarray, np.ndarray]: ...
|
| 424 |
+
@property
|
| 425 |
+
def edge_centers(self) -> tuple[np.ndarray, np.ndarray]: ...
|
| 426 |
+
@property
|
| 427 |
+
def center(self) -> tuple[float, float]: ...
|
| 428 |
+
@property
|
| 429 |
+
def extents(self) -> tuple[float, float, float, float]: ...
|
| 430 |
+
@extents.setter
|
| 431 |
+
def extents(self, extents: tuple[float, float, float, float]) -> None: ...
|
| 432 |
+
@property
|
| 433 |
+
def rotation(self) -> float: ...
|
| 434 |
+
@rotation.setter
|
| 435 |
+
def rotation(self, value: float) -> None: ...
|
| 436 |
+
@property
|
| 437 |
+
def geometry(self) -> np.ndarray: ...
|
| 438 |
+
|
| 439 |
+
class EllipseSelector(RectangleSelector): ...
|
| 440 |
+
|
| 441 |
+
class LassoSelector(_SelectorWidget):
|
| 442 |
+
verts: None | list[tuple[float, float]]
|
| 443 |
+
def __init__(
|
| 444 |
+
self,
|
| 445 |
+
ax: Axes,
|
| 446 |
+
onselect: Callable[[list[tuple[float, float]]], Any],
|
| 447 |
+
*,
|
| 448 |
+
useblit: bool = ...,
|
| 449 |
+
props: dict[str, Any] | None = ...,
|
| 450 |
+
button: MouseButton | Collection[MouseButton] | None = ...,
|
| 451 |
+
) -> None: ...
|
| 452 |
+
|
| 453 |
+
class PolygonSelector(_SelectorWidget):
|
| 454 |
+
grab_range: float
|
| 455 |
+
def __init__(
|
| 456 |
+
self,
|
| 457 |
+
ax: Axes,
|
| 458 |
+
onselect: Callable[[ArrayLike, ArrayLike], Any],
|
| 459 |
+
*,
|
| 460 |
+
useblit: bool = ...,
|
| 461 |
+
props: dict[str, Any] | None = ...,
|
| 462 |
+
handle_props: dict[str, Any] | None = ...,
|
| 463 |
+
grab_range: float = ...,
|
| 464 |
+
draw_bounding_box: bool = ...,
|
| 465 |
+
box_handle_props: dict[str, Any] | None = ...,
|
| 466 |
+
box_props: dict[str, Any] | None = ...
|
| 467 |
+
) -> None: ...
|
| 468 |
+
def onmove(self, event: Event) -> bool: ...
|
| 469 |
+
@property
|
| 470 |
+
def verts(self) -> list[tuple[float, float]]: ...
|
| 471 |
+
@verts.setter
|
| 472 |
+
def verts(self, xys: Sequence[tuple[float, float]]) -> None: ...
|
| 473 |
+
|
| 474 |
+
class Lasso(AxesWidget):
|
| 475 |
+
useblit: bool
|
| 476 |
+
background: Any
|
| 477 |
+
verts: list[tuple[float, float]] | None
|
| 478 |
+
line: Line2D
|
| 479 |
+
callback: Callable[[list[tuple[float, float]]], Any]
|
| 480 |
+
def __init__(
|
| 481 |
+
self,
|
| 482 |
+
ax: Axes,
|
| 483 |
+
xy: tuple[float, float],
|
| 484 |
+
callback: Callable[[list[tuple[float, float]]], Any],
|
| 485 |
+
*,
|
| 486 |
+
useblit: bool = ...,
|
| 487 |
+
props: dict[str, Any] | None = ...,
|
| 488 |
+
) -> None: ...
|
| 489 |
+
def onrelease(self, event: Event) -> None: ...
|
| 490 |
+
def onmove(self, event: Event) -> None: ...
|
parrot/lib/python3.10/site-packages/scipy/ndimage/_ni_label.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d5c4211a57c9e0992d24e1f8a78b954140cbd5d2bddbf24b3398f541d0505b11
|
| 3 |
+
size 424104
|
parrot/lib/python3.10/site-packages/torchvision.libs/libnvjpeg.f00ca762.so.12
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd88e93c4478fed775b700d24db43300261da1a71bc198b764abc260f6558ac6
|
| 3 |
+
size 6591280
|
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_clamp_max.h
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_foreach_clamp_max_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_foreach_clamp_max.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
|
| 26 |
+
inline ::std::vector<at::Tensor> _foreach_clamp_max(at::TensorList self, const at::Scalar & scalar) {
|
| 27 |
+
return at::_ops::_foreach_clamp_max_Scalar::call(self, scalar);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::_foreach_clamp_max_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
|
| 31 |
+
inline void _foreach_clamp_max_(at::TensorList self, const at::Scalar & scalar) {
|
| 32 |
+
return at::_ops::_foreach_clamp_max__Scalar::call(self, scalar);
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// aten::_foreach_clamp_max.List(Tensor[] self, Tensor[] other) -> Tensor[]
|
| 36 |
+
inline ::std::vector<at::Tensor> _foreach_clamp_max(at::TensorList self, at::TensorList other) {
|
| 37 |
+
return at::_ops::_foreach_clamp_max_List::call(self, other);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
// aten::_foreach_clamp_max_.List(Tensor(a!)[] self, Tensor[] other) -> ()
|
| 41 |
+
inline void _foreach_clamp_max_(at::TensorList self, at::TensorList other) {
|
| 42 |
+
return at::_ops::_foreach_clamp_max__List::call(self, other);
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
// aten::_foreach_clamp_max.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
|
| 46 |
+
inline ::std::vector<at::Tensor> _foreach_clamp_max(at::TensorList self, at::ArrayRef<at::Scalar> scalars) {
|
| 47 |
+
return at::_ops::_foreach_clamp_max_ScalarList::call(self, scalars);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
// aten::_foreach_clamp_max_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
|
| 51 |
+
inline void _foreach_clamp_max_(at::TensorList self, at::ArrayRef<at::Scalar> scalars) {
|
| 52 |
+
return at::_ops::_foreach_clamp_max__ScalarList::call(self, scalars);
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// aten::_foreach_clamp_max.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()
|
| 56 |
+
inline void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, const at::Scalar & scalar) {
|
| 57 |
+
return at::_ops::_foreach_clamp_max_Scalar_out::call(self, scalar, out);
|
| 58 |
+
}
|
| 59 |
+
// aten::_foreach_clamp_max.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()
|
| 60 |
+
inline void _foreach_clamp_max_outf(at::TensorList self, const at::Scalar & scalar, at::TensorList out) {
|
| 61 |
+
return at::_ops::_foreach_clamp_max_Scalar_out::call(self, scalar, out);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// aten::_foreach_clamp_max.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> ()
|
| 65 |
+
inline void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, at::TensorList other) {
|
| 66 |
+
return at::_ops::_foreach_clamp_max_List_out::call(self, other, out);
|
| 67 |
+
}
|
| 68 |
+
// aten::_foreach_clamp_max.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> ()
|
| 69 |
+
inline void _foreach_clamp_max_outf(at::TensorList self, at::TensorList other, at::TensorList out) {
|
| 70 |
+
return at::_ops::_foreach_clamp_max_List_out::call(self, other, out);
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// aten::_foreach_clamp_max.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()
|
| 74 |
+
inline void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, at::ArrayRef<at::Scalar> scalars) {
|
| 75 |
+
return at::_ops::_foreach_clamp_max_ScalarList_out::call(self, scalars, out);
|
| 76 |
+
}
|
| 77 |
+
// aten::_foreach_clamp_max.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()
|
| 78 |
+
inline void _foreach_clamp_max_outf(at::TensorList self, at::ArrayRef<at::Scalar> scalars, at::TensorList out) {
|
| 79 |
+
return at::_ops::_foreach_clamp_max_ScalarList_out::call(self, scalars, out);
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
}
|
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_cos.h
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_foreach_cos_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_foreach_cos(Tensor[] self) -> Tensor[]
|
| 26 |
+
inline ::std::vector<at::Tensor> _foreach_cos(at::TensorList self) {
|
| 27 |
+
return at::_ops::_foreach_cos::call(self);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::_foreach_cos_(Tensor(a!)[] self) -> ()
|
| 31 |
+
inline void _foreach_cos_(at::TensorList self) {
|
| 32 |
+
return at::_ops::_foreach_cos_::call(self);
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// aten::_foreach_cos.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
|
| 36 |
+
inline void _foreach_cos_out(at::TensorList out, at::TensorList self) {
|
| 37 |
+
return at::_ops::_foreach_cos_out::call(self, out);
|
| 38 |
+
}
|
| 39 |
+
// aten::_foreach_cos.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
|
| 40 |
+
inline void _foreach_cos_outf(at::TensorList self, at::TensorList out) {
|
| 41 |
+
return at::_ops::_foreach_cos_out::call(self, out);
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
}
|
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor _grid_sampler_2d_cpu_fallback(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners);
|
| 20 |
+
TORCH_API at::Tensor & _grid_sampler_2d_cpu_fallback_out(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, at::Tensor & out);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_softmax.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_softmax_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
|
| 26 |
+
inline at::Tensor _softmax(const at::Tensor & self, int64_t dim, bool half_to_float) {
|
| 27 |
+
return at::_ops::_softmax::call(self, dim, half_to_float);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!)
|
| 31 |
+
inline at::Tensor & _softmax_out(at::Tensor & out, const at::Tensor & self, int64_t dim, bool half_to_float) {
|
| 32 |
+
return at::_ops::_softmax_out::call(self, dim, half_to_float, out);
|
| 33 |
+
}
|
| 34 |
+
// aten::_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!)
|
| 35 |
+
inline at::Tensor & _softmax_outf(const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out) {
|
| 36 |
+
return at::_ops::_softmax_out::call(self, dim, half_to_float, out);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
}
|
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_spsolve_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor _sparse_csr_linear_solve(const at::Tensor & A, const at::Tensor & B, bool left=true);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_thnn_fused_lstm_cell_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_thnn_fused_lstm_cell(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor, Tensor)
|
| 26 |
+
inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _thnn_fused_lstm_cell(const at::Tensor & input_gates, const at::Tensor & hidden_gates, const at::Tensor & cx, const ::std::optional<at::Tensor> & input_bias={}, const ::std::optional<at::Tensor> & hidden_bias={}) {
|
| 27 |
+
return at::_ops::_thnn_fused_lstm_cell::call(input_gates, hidden_gates, cx, input_bias, hidden_bias);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::_thnn_fused_lstm_cell.out(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
|
| 31 |
+
inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _thnn_fused_lstm_cell_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & input_gates, const at::Tensor & hidden_gates, const at::Tensor & cx, const ::std::optional<at::Tensor> & input_bias={}, const ::std::optional<at::Tensor> & hidden_bias={}) {
|
| 32 |
+
return at::_ops::_thnn_fused_lstm_cell_out::call(input_gates, hidden_gates, cx, input_bias, hidden_bias, out0, out1, out2);
|
| 33 |
+
}
|
| 34 |
+
// aten::_thnn_fused_lstm_cell.out(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
|
| 35 |
+
inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _thnn_fused_lstm_cell_outf(const at::Tensor & input_gates, const at::Tensor & hidden_gates, const at::Tensor & cx, const ::std::optional<at::Tensor> & input_bias, const ::std::optional<at::Tensor> & hidden_bias, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
|
| 36 |
+
return at::_ops::_thnn_fused_lstm_cell_out::call(input_gates, hidden_gates, cx, input_bias, hidden_bias, out0, out1, out2);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
}
|
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_impl_ops.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API _thnn_fused_lstm_cell_backward_impl {
|
| 18 |
+
using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor> (const ::std::optional<at::Tensor> &, const ::std::optional<at::Tensor> &, const at::Tensor &, const at::Tensor &, const at::Tensor &, bool);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_thnn_fused_lstm_cell_backward_impl")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_thnn_fused_lstm_cell_backward_impl(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor)")
|
| 24 |
+
static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> call(const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, const at::Tensor & cx, const at::Tensor & cy, const at::Tensor & workspace, bool has_bias);
|
| 25 |
+
static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, const at::Tensor & cx, const at::Tensor & cy, const at::Tensor & workspace, bool has_bias);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API _thnn_fused_lstm_cell_backward_impl_out {
|
| 29 |
+
using schema = ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> (const ::std::optional<at::Tensor> &, const ::std::optional<at::Tensor> &, const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, at::Tensor &, at::Tensor &, at::Tensor &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_thnn_fused_lstm_cell_backward_impl")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_thnn_fused_lstm_cell_backward_impl.out(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))")
|
| 35 |
+
static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> call(const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, const at::Tensor & cx, const at::Tensor & cy, const at::Tensor & workspace, bool has_bias, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
|
| 36 |
+
static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, const at::Tensor & cx, const at::Tensor & cy, const at::Tensor & workspace, bool has_bias, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|