content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\formatting.cpython-313.pyc | formatting.cpython-313.pyc | Other | 8,122 | 0.8 | 0 | 0 | node-utils | 361 | 2023-10-22T00:15:57.628939 | Apache-2.0 | false | 49e5051343965f3701762c814c30e41d |
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\math.cpython-313.pyc | math.cpython-313.pyc | Other | 3,599 | 0.8 | 0.046512 | 0 | python-kit | 690 | 2025-03-14T05:27:03.574582 | GPL-3.0 | false | dd4362321e7792f123e582b7ed3f7a6b |
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\ruby.cpython-313.pyc | ruby.cpython-313.pyc | Other | 4,263 | 0.8 | 0 | 0 | awesome-app | 105 | 2024-06-27T07:43:34.987812 | BSD-3-Clause | false | ab80c6b3400f1a178866f146ef616e8c |
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\speedup.cpython-313.pyc | speedup.cpython-313.pyc | Other | 2,412 | 0.8 | 0 | 0 | node-utils | 286 | 2025-06-04T10:47:46.731846 | Apache-2.0 | false | 01212bf94276bb0e3beb9d6f51c6990d |
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\spoiler.cpython-313.pyc | spoiler.cpython-313.pyc | Other | 4,267 | 0.8 | 0.04 | 0 | awesome-app | 479 | 2023-12-16T01:16:53.223992 | MIT | false | 55cfcbdd33ce5cd4eae095d9f64a2435 |
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\table.cpython-313.pyc | table.cpython-313.pyc | Other | 8,602 | 0.8 | 0 | 0.009346 | node-utils | 535 | 2024-08-03T00:10:58.926558 | GPL-3.0 | false | ab5b6b5aa239d8ddc7559eb127e7bf7b |
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\task_lists.cpython-313.pyc | task_lists.cpython-313.pyc | Other | 3,215 | 0.8 | 0.057143 | 0 | react-lib | 173 | 2024-10-29T04:51:30.101912 | Apache-2.0 | false | 73b5a17ce546dfd379f5e55ec55bddd6 |
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\url.cpython-313.pyc | url.cpython-313.pyc | Other | 1,446 | 0.8 | 0 | 0 | react-lib | 161 | 2025-01-04T04:44:21.093998 | MIT | false | 3140df3f0fc54c6bd60f98d4407bbcd2 |
\n\n | .venv\Lib\site-packages\mistune\plugins\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 2,316 | 0.95 | 0 | 0.052632 | node-utils | 264 | 2024-11-23T05:21:49.481726 | BSD-3-Clause | false | 353a7cadf9c3a6b9681ad8e014330ad5 |
from typing import Any, ClassVar, Dict, Optional, Tuple, Literal\nfrom ..core import BaseRenderer, BlockState\nfrom ..util import escape as escape_text\nfrom ..util import safe_entity, striptags\n\n\nclass HTMLRenderer(BaseRenderer):\n """A renderer for converting Markdown to HTML."""\n\n _escape: bool\n NAME: ClassVar[Literal["html"]] = "html"\n HARMFUL_PROTOCOLS: ClassVar[Tuple[str, ...]] = (\n "javascript:",\n "vbscript:",\n "file:",\n "data:",\n )\n GOOD_DATA_PROTOCOLS: ClassVar[Tuple[str, ...]] = (\n "data:image/gif;",\n "data:image/png;",\n "data:image/jpeg;",\n "data:image/webp;",\n )\n\n def __init__(self, escape: bool = True, allow_harmful_protocols: Optional[bool] = None) -> None:\n super(HTMLRenderer, self).__init__()\n self._allow_harmful_protocols = allow_harmful_protocols\n self._escape = escape\n\n def render_token(self, token: Dict[str, Any], state: BlockState) -> str:\n # backward compitable with v2\n func = self._get_method(token["type"])\n attrs = token.get("attrs")\n\n if "raw" in token:\n text = token["raw"]\n elif "children" in token:\n text = self.render_tokens(token["children"], state)\n else:\n if attrs:\n return func(**attrs)\n else:\n return func()\n if attrs:\n return func(text, **attrs)\n else:\n return func(text)\n\n def safe_url(self, url: str) -> str:\n """Ensure the given URL is safe. This method is used for rendering\n links, images, and etc.\n """\n if self._allow_harmful_protocols is True:\n return escape_text(url)\n\n _url = url.lower()\n if self._allow_harmful_protocols and _url.startswith(tuple(self._allow_harmful_protocols)):\n return escape_text(url)\n\n if _url.startswith(self.HARMFUL_PROTOCOLS) and not _url.startswith(self.GOOD_DATA_PROTOCOLS):\n return "#harmful-link"\n return escape_text(url)\n\n def text(self, text: str) -> str:\n if self._escape:\n return escape_text(text)\n return safe_entity(text)\n\n def emphasis(self, text: str) -> str:\n return "<em>" + text + "</em>"\n\n def strong(self, text: str) -> str:\n return "<strong>" + text + "</strong>"\n\n def link(self, text: str, url: str, title: Optional[str] = None) -> str:\n s = '<a href="' + self.safe_url(url) + '"'\n if title:\n s += ' title="' + safe_entity(title) + '"'\n return s + ">" + text + "</a>"\n\n def image(self, text: str, url: str, title: Optional[str] = None) -> str:\n src = self.safe_url(url)\n alt = escape_text(striptags(text))\n s = '<img src="' + src + '" alt="' + alt + '"'\n if title:\n s += ' title="' + safe_entity(title) + '"'\n return s + " />"\n\n def codespan(self, text: str) -> str:\n return "<code>" + escape_text(text) + "</code>"\n\n def linebreak(self) -> str:\n return "<br />\n"\n\n def softbreak(self) -> str:\n return "\n"\n\n def inline_html(self, html: str) -> str:\n if self._escape:\n return escape_text(html)\n return html\n\n def paragraph(self, text: str) -> str:\n return "<p>" + text + "</p>\n"\n\n def heading(self, text: str, level: int, **attrs: Any) -> str:\n tag = "h" + str(level)\n html = "<" + tag\n _id = attrs.get("id")\n if _id:\n html += ' id="' + _id + '"'\n return html + ">" + text + "</" + tag + ">\n"\n\n def blank_line(self) -> str:\n return ""\n\n def thematic_break(self) -> str:\n return "<hr />\n"\n\n def block_text(self, text: str) -> str:\n return text\n\n def block_code(self, code: str, info: Optional[str] = None) -> str:\n html = "<pre><code"\n if info is not None:\n info = safe_entity(info.strip())\n if info:\n lang = info.split(None, 1)[0]\n html += ' class="language-' + lang + '"'\n return html + ">" + escape_text(code) + "</code></pre>\n"\n\n def block_quote(self, text: str) -> str:\n return "<blockquote>\n" + text + "</blockquote>\n"\n\n def block_html(self, html: str) -> str:\n if self._escape:\n return "<p>" + escape_text(html.strip()) + "</p>\n"\n return html + "\n"\n\n def block_error(self, text: str) -> str:\n return '<div class="error"><pre>' + text + "</pre></div>\n"\n\n def list(self, text: str, ordered: bool, **attrs: Any) -> str:\n if ordered:\n html = "<ol"\n start = attrs.get("start")\n if start is not None:\n html += ' start="' + str(start) + '"'\n return html + ">\n" + text + "</ol>\n"\n return "<ul>\n" + text + "</ul>\n"\n\n def list_item(self, text: str) -> str:\n return "<li>" + text + "</li>\n"\n | .venv\Lib\site-packages\mistune\renderers\html.py | html.py | Python | 4,926 | 0.95 | 0.287582 | 0.008065 | awesome-app | 582 | 2025-04-01T09:58:58.945019 | Apache-2.0 | false | 3546953c869aac31fe22952c5551a5e2 |
import re\nfrom textwrap import indent\nfrom typing import Any, Dict, Iterable, cast\n\nfrom ..core import BaseRenderer, BlockState\nfrom ..util import strip_end\nfrom ._list import render_list\n\nfenced_re = re.compile(r"^[`~]+", re.M)\n\n\nclass MarkdownRenderer(BaseRenderer):\n """A renderer to re-format Markdown text."""\n\n NAME = "markdown"\n\n def __call__(self, tokens: Iterable[Dict[str, Any]], state: BlockState) -> str:\n out = self.render_tokens(tokens, state)\n # special handle for line breaks\n out += "\n\n".join(self.render_referrences(state)) + "\n"\n return strip_end(out)\n\n def render_referrences(self, state: BlockState) -> Iterable[str]:\n ref_links = state.env["ref_links"]\n for key in ref_links:\n attrs = ref_links[key]\n text = "[" + attrs["label"] + "]: " + attrs["url"]\n title = attrs.get("title")\n if title:\n text += ' "' + title + '"'\n yield text\n\n def render_children(self, token: Dict[str, Any], state: BlockState) -> str:\n children = token["children"]\n return self.render_tokens(children, state)\n\n def text(self, token: Dict[str, Any], state: BlockState) -> str:\n return cast(str, token["raw"])\n\n def emphasis(self, token: Dict[str, Any], state: BlockState) -> str:\n return "*" + self.render_children(token, state) + "*"\n\n def strong(self, token: Dict[str, Any], state: BlockState) -> str:\n return "**" + self.render_children(token, state) + "**"\n\n def link(self, token: Dict[str, Any], state: BlockState) -> str:\n label = cast(str, token.get("label"))\n text = self.render_children(token, state)\n out = "[" + text + "]"\n if label:\n return out + "[" + label + "]"\n\n attrs = token["attrs"]\n url = attrs["url"]\n title = attrs.get("title")\n if text == url and not title:\n return "<" + text + ">"\n elif "mailto:" + text == url and not title:\n return "<" + text + ">"\n\n out += "("\n if "(" in url or ")" in url:\n out += "<" + url + ">"\n else:\n out += url\n if title:\n out += ' "' + title + '"'\n return out + ")"\n\n def image(self, token: Dict[str, Any], state: BlockState) -> str:\n return "!" + self.link(token, state)\n\n def codespan(self, token: Dict[str, Any], state: BlockState) -> str:\n return "`" + cast(str, token["raw"]) + "`"\n\n def linebreak(self, token: Dict[str, Any], state: BlockState) -> str:\n return " \n"\n\n def softbreak(self, token: Dict[str, Any], state: BlockState) -> str:\n return "\n"\n\n def blank_line(self, token: Dict[str, Any], state: BlockState) -> str:\n return ""\n\n def inline_html(self, token: Dict[str, Any], state: BlockState) -> str:\n return cast(str, token["raw"])\n\n def paragraph(self, token: Dict[str, Any], state: BlockState) -> str:\n text = self.render_children(token, state)\n return text + "\n\n"\n\n def heading(self, token: Dict[str, Any], state: BlockState) -> str:\n level = cast(int, token["attrs"]["level"])\n marker = "#" * level\n text = self.render_children(token, state)\n return marker + " " + text + "\n\n"\n\n def thematic_break(self, token: Dict[str, Any], state: BlockState) -> str:\n return "***\n\n"\n\n def block_text(self, token: Dict[str, Any], state: BlockState) -> str:\n return self.render_children(token, state) + "\n"\n\n def block_code(self, token: Dict[str, Any], state: BlockState) -> str:\n attrs = token.get("attrs", {})\n info = cast(str, attrs.get("info", ""))\n code = cast(str, token["raw"])\n if code and code[-1] != "\n":\n code += "\n"\n\n marker = token.get("marker")\n if not marker:\n marker = _get_fenced_marker(code)\n marker2 = cast(str, marker)\n return marker2 + info + "\n" + code + marker2 + "\n\n"\n\n def block_quote(self, token: Dict[str, Any], state: BlockState) -> str:\n text = indent(self.render_children(token, state), "> ", lambda _: True)\n text = text.rstrip("> \n")\n return text + "\n\n"\n\n def block_html(self, token: Dict[str, Any], state: BlockState) -> str:\n return cast(str, token["raw"]) + "\n\n"\n\n def block_error(self, token: Dict[str, Any], state: BlockState) -> str:\n return ""\n\n def list(self, token: Dict[str, Any], state: BlockState) -> str:\n return render_list(self, token, state)\n\n\ndef _get_fenced_marker(code: str) -> str:\n found = fenced_re.findall(code)\n if not found:\n return "```"\n\n ticks = [] # `\n waves = [] # ~\n for s in found:\n if s[0] == "`":\n ticks.append(len(s))\n else:\n waves.append(len(s))\n\n if not ticks:\n return "```"\n\n if not waves:\n return "~~~"\n return "`" * (max(ticks) + 1)\n | .venv\Lib\site-packages\mistune\renderers\markdown.py | markdown.py | Python | 4,962 | 0.95 | 0.253333 | 0.008696 | react-lib | 175 | 2025-04-05T10:40:52.923317 | Apache-2.0 | false | 68db56f69e67ae152e5a69dde69d3c09 |
from textwrap import indent\nfrom typing import Any, Dict, Iterable, List, cast\n\nfrom ..core import BaseRenderer, BlockState\nfrom ..util import strip_end\nfrom ._list import render_list\n\n\nclass RSTRenderer(BaseRenderer):\n """A renderer for converting Markdown to ReST."""\n\n NAME = "rst"\n\n #: marker symbols for heading\n HEADING_MARKERS = {\n 1: "=",\n 2: "-",\n 3: "~",\n 4: "^",\n 5: '"',\n 6: "'",\n }\n INLINE_IMAGE_PREFIX = "img-"\n\n def iter_tokens(self, tokens: Iterable[Dict[str, Any]], state: BlockState) -> Iterable[str]:\n prev = None\n for tok in tokens:\n # ignore blank line\n if tok["type"] == "blank_line":\n continue\n tok["prev"] = prev\n prev = tok\n yield self.render_token(tok, state)\n\n def __call__(self, tokens: Iterable[Dict[str, Any]], state: BlockState) -> str:\n state.env["inline_images"] = []\n out = self.render_tokens(tokens, state)\n # special handle for line breaks\n out += "\n\n".join(self.render_referrences(state)) + "\n"\n return strip_end(out)\n\n def render_referrences(self, state: BlockState) -> Iterable[str]:\n images = state.env["inline_images"]\n for index, token in enumerate(images):\n attrs = token["attrs"]\n alt = self.render_children(token, state)\n ident = self.INLINE_IMAGE_PREFIX + str(index)\n yield ".. |" + ident + "| image:: " + attrs["url"] + "\n :alt: " + alt\n\n def render_children(self, token: Dict[str, Any], state: BlockState) -> str:\n children = token["children"]\n return self.render_tokens(children, state)\n\n def text(self, token: Dict[str, Any], state: BlockState) -> str:\n text = cast(str, token["raw"])\n return text.replace("|", r"\|")\n\n def emphasis(self, token: Dict[str, Any], state: BlockState) -> str:\n return "*" + self.render_children(token, state) + "*"\n\n def strong(self, token: Dict[str, Any], state: BlockState) -> str:\n return "**" + self.render_children(token, state) + "**"\n\n def link(self, token: Dict[str, Any], state: BlockState) -> str:\n attrs = token["attrs"]\n text = self.render_children(token, state)\n return "`" + text + " <" + cast(str, attrs["url"]) + ">`__"\n\n def image(self, token: Dict[str, Any], state: BlockState) -> str:\n refs: List[Dict[str, Any]] = state.env["inline_images"]\n index = len(refs)\n refs.append(token)\n return "|" + self.INLINE_IMAGE_PREFIX + str(index) + "|"\n\n def codespan(self, token: Dict[str, Any], state: BlockState) -> str:\n return "``" + cast(str, token["raw"]) + "``"\n\n def linebreak(self, token: Dict[str, Any], state: BlockState) -> str:\n return "<linebreak>"\n\n def softbreak(self, token: Dict[str, Any], state: BlockState) -> str:\n return " "\n\n def inline_html(self, token: Dict[str, Any], state: BlockState) -> str:\n # rst does not support inline html\n return ""\n\n def paragraph(self, token: Dict[str, Any], state: BlockState) -> str:\n children = token["children"]\n if len(children) == 1 and children[0]["type"] == "image":\n image = children[0]\n attrs = image["attrs"]\n title = cast(str, attrs.get("title"))\n alt = self.render_children(image, state)\n text = ".. figure:: " + cast(str, attrs["url"])\n if title:\n text += "\n :alt: " + title\n text += "\n\n" + indent(alt, " ")\n else:\n text = self.render_tokens(children, state)\n lines = text.split("<linebreak>")\n if len(lines) > 1:\n text = "\n".join("| " + line for line in lines)\n return text + "\n\n"\n\n def heading(self, token: Dict[str, Any], state: BlockState) -> str:\n attrs = token["attrs"]\n text = self.render_children(token, state)\n marker = self.HEADING_MARKERS[attrs["level"]]\n return text + "\n" + marker * len(text) + "\n\n"\n\n def thematic_break(self, token: Dict[str, Any], state: BlockState) -> str:\n return "--------------\n\n"\n\n def block_text(self, token: Dict[str, Any], state: BlockState) -> str:\n return self.render_children(token, state) + "\n"\n\n def block_code(self, token: Dict[str, Any], state: BlockState) -> str:\n attrs = token.get("attrs", {})\n info = cast(str, attrs.get("info"))\n code = indent(cast(str, token["raw"]), " ")\n if info:\n lang = info.split()[0]\n return ".. code:: " + lang + "\n\n" + code + "\n"\n else:\n return "::\n\n" + code + "\n\n"\n\n def block_quote(self, token: Dict[str, Any], state: BlockState) -> str:\n text = indent(self.render_children(token, state), " ")\n prev = token["prev"]\n ignore_blocks = (\n "paragraph",\n "thematic_break",\n "linebreak",\n "heading",\n )\n if prev and prev["type"] not in ignore_blocks:\n text = "..\n\n" + text\n return text\n\n def block_html(self, token: Dict[str, Any], state: BlockState) -> str:\n raw = token["raw"]\n return ".. raw:: html\n\n" + indent(raw, " ") + "\n\n"\n\n def block_error(self, token: Dict[str, Any], state: BlockState) -> str:\n return ""\n\n def list(self, token: Dict[str, Any], state: BlockState) -> str:\n return render_list(self, token, state)\n | .venv\Lib\site-packages\mistune\renderers\rst.py | rst.py | Python | 5,523 | 0.95 | 0.234899 | 0.032787 | react-lib | 17 | 2023-12-02T20:19:35.874494 | BSD-3-Clause | false | cae37a7ac1cc2470f74c593ed39ac79b |
from typing import TYPE_CHECKING, Any, Dict, Iterable, cast\n\nfrom ..util import strip_end\n\nif TYPE_CHECKING:\n from ..core import BaseRenderer, BlockState\n\n\ndef render_list(renderer: "BaseRenderer", token: Dict[str, Any], state: "BlockState") -> str:\n attrs = token["attrs"]\n if attrs["ordered"]:\n children = _render_ordered_list(renderer, token, state)\n else:\n children = _render_unordered_list(renderer, token, state)\n\n text = "".join(children)\n parent = token.get("parent")\n if parent:\n if parent["tight"]:\n return text\n return text + "\n"\n return strip_end(text) + "\n"\n\n\ndef _render_list_item(\n renderer: "BaseRenderer",\n parent: Dict[str, Any],\n item: Dict[str, Any],\n state: "BlockState",\n) -> str:\n leading = cast(str, parent["leading"])\n text = ""\n for tok in item["children"]:\n if tok["type"] == "list":\n tok["parent"] = parent\n elif tok["type"] == "blank_line":\n continue\n text += renderer.render_token(tok, state)\n\n lines = text.splitlines()\n text = (lines[0] if lines else "") + "\n"\n prefix = " " * len(leading)\n for line in lines[1:]:\n if line:\n text += prefix + line + "\n"\n else:\n text += "\n"\n return leading + text\n\n\ndef _render_ordered_list(renderer: "BaseRenderer", token: Dict[str, Any], state: "BlockState") -> Iterable[str]:\n attrs = token["attrs"]\n start = attrs.get("start", 1)\n for item in token["children"]:\n leading = str(start) + token["bullet"] + " "\n parent = {\n "leading": leading,\n "tight": token["tight"],\n }\n yield _render_list_item(renderer, parent, item, state)\n start += 1\n\n\ndef _render_unordered_list(renderer: "BaseRenderer", token: Dict[str, Any], state: "BlockState") -> Iterable[str]:\n parent = {\n "leading": token["bullet"] + " ",\n "tight": token["tight"],\n }\n for item in token["children"]:\n yield _render_list_item(renderer, parent, item, state)\n | .venv\Lib\site-packages\mistune\renderers\_list.py | _list.py | Python | 2,066 | 0.85 | 0.214286 | 0 | react-lib | 147 | 2025-06-07T04:53:03.164902 | BSD-3-Clause | false | e9653d7d180d5d44e116bfadd8083cd3 |
\n\n | .venv\Lib\site-packages\mistune\renderers\__pycache__\html.cpython-313.pyc | html.cpython-313.pyc | Other | 8,652 | 0.8 | 0.057971 | 0.029412 | node-utils | 578 | 2023-08-26T08:53:47.567984 | Apache-2.0 | false | 46fa31103029472fb4abc386e9d0fdab |
\n\n | .venv\Lib\site-packages\mistune\renderers\__pycache__\markdown.cpython-313.pyc | markdown.cpython-313.pyc | Other | 8,909 | 0.8 | 0 | 0 | react-lib | 229 | 2023-12-07T17:51:51.092809 | Apache-2.0 | false | ae94bb97b568811dd064900523f2942d |
\n\n | .venv\Lib\site-packages\mistune\renderers\__pycache__\rst.cpython-313.pyc | rst.cpython-313.pyc | Other | 9,307 | 0.8 | 0.00813 | 0 | vue-tools | 868 | 2023-07-14T04:55:02.209183 | MIT | false | ae62f5fca780941e2f2cf350c41ddb51 |
\n\n | .venv\Lib\site-packages\mistune\renderers\__pycache__\_list.cpython-313.pyc | _list.cpython-313.pyc | Other | 2,975 | 0.8 | 0 | 0 | python-kit | 665 | 2025-03-21T18:43:36.298483 | GPL-3.0 | false | e0f923248db933246170dc2add92d2fa |
\n\n | .venv\Lib\site-packages\mistune\renderers\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 192 | 0.7 | 0 | 0 | awesome-app | 136 | 2025-04-30T20:10:55.192441 | MIT | false | da050e2fa5c069faba634a0dbcaf13c3 |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\block_parser.cpython-313.pyc | block_parser.cpython-313.pyc | Other | 20,012 | 0.95 | 0.05 | 0.01227 | python-kit | 894 | 2024-01-04T21:00:33.711165 | Apache-2.0 | false | 93d4cfd2e9615a90c47b90128f4d789a |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\core.cpython-313.pyc | core.cpython-313.pyc | Other | 13,612 | 0.95 | 0.022059 | 0.023438 | react-lib | 792 | 2025-01-18T07:24:50.189719 | MIT | false | 4575e4a049cfc91845b4bd28ebafd940 |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\helpers.cpython-313.pyc | helpers.cpython-313.pyc | Other | 5,862 | 0.8 | 0 | 0 | vue-tools | 876 | 2023-08-12T05:18:28.874246 | GPL-3.0 | false | 85d0a7a0bdaebc6557a0d33a7cec8a3d |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\inline_parser.cpython-313.pyc | inline_parser.cpython-313.pyc | Other | 15,720 | 0.8 | 0 | 0.035971 | python-kit | 554 | 2025-03-06T14:56:46.927522 | BSD-3-Clause | false | 8a23fcb9f0d1504934a8e5029f1ec6c0 |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\list_parser.cpython-313.pyc | list_parser.cpython-313.pyc | Other | 9,526 | 0.8 | 0.010526 | 0 | react-lib | 157 | 2025-01-31T10:15:52.664255 | GPL-3.0 | false | 5ca897b1f00561bbcc39237539596b5e |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\markdown.cpython-313.pyc | markdown.cpython-313.pyc | Other | 5,600 | 0.95 | 0 | 0 | node-utils | 783 | 2023-11-27T04:04:05.821192 | BSD-3-Clause | false | d0378bbbad7c705d6b25a6ef0c630709 |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\toc.cpython-313.pyc | toc.cpython-313.pyc | Other | 4,856 | 0.95 | 0.020833 | 0 | react-lib | 248 | 2024-06-17T12:17:48.493582 | Apache-2.0 | false | fd6c3331d87c18eea9a3c4d6851fdaed |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\util.cpython-313.pyc | util.cpython-313.pyc | Other | 3,830 | 0.8 | 0.047619 | 0.068966 | python-kit | 912 | 2023-08-26T07:37:10.951855 | Apache-2.0 | false | 3c85ea6affe81944546858e847fce7a8 |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 3,235 | 0.95 | 0.018519 | 0.042553 | vue-tools | 447 | 2025-06-25T14:43:14.474107 | BSD-3-Clause | false | 01c36bb6d8ec2c8707bfc97dd6af45b3 |
\n\n | .venv\Lib\site-packages\mistune\__pycache__\__main__.cpython-313.pyc | __main__.cpython-313.pyc | Other | 4,638 | 0.8 | 0 | 0.076923 | vue-tools | 788 | 2024-09-05T14:50:42.769290 | Apache-2.0 | false | 98344124d1b1d9cd462650c71cbf24dc |
pip\n | .venv\Lib\site-packages\mistune-3.1.3.dist-info\INSTALLER | INSTALLER | Other | 4 | 0.5 | 0 | 0 | awesome-app | 725 | 2024-04-02T10:35:55.060986 | GPL-3.0 | false | 365c9bfeb7d89244f2ce01c1de44cb85 |
Copyright (c) 2014, Hsiaoming Yang\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n* Neither the name of the creator nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n | .venv\Lib\site-packages\mistune-3.1.3.dist-info\LICENSE | LICENSE | Other | 1,475 | 0.7 | 0 | 0.428571 | vue-tools | 934 | 2024-04-03T11:34:21.925442 | GPL-3.0 | false | 7662a489238001edfceff24a3ce11cbd |
Metadata-Version: 2.2\nName: mistune\nVersion: 3.1.3\nSummary: A sane and fast Markdown parser with useful plugins and renderers\nAuthor-email: Hsiaoming Yang <me@lepture.com>\nLicense: BSD-3-Clause\nProject-URL: Documentation, https://mistune.lepture.com/\nProject-URL: Source, https://github.com/lepture/mistune\nProject-URL: Donate, https://github.com/sponsors/lepture\nClassifier: Development Status :: 4 - Beta\nClassifier: Environment :: Console\nClassifier: Environment :: Web Environment\nClassifier: Intended Audience :: Developers\nClassifier: License :: OSI Approved :: BSD License\nClassifier: Operating System :: OS Independent\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Programming Language :: Python :: 3.13\nClassifier: Programming Language :: Python :: Implementation :: CPython\nClassifier: Programming Language :: Python :: Implementation :: PyPy\nClassifier: Topic :: Text Processing :: Markup\nRequires-Python: >=3.8\nDescription-Content-Type: text/x-rst\nLicense-File: LICENSE\nRequires-Dist: typing-extensions; python_version < "3.11"\n\nMistune v3\n==========\n\nA fast yet powerful Python Markdown parser with renderers and plugins.\n\nOverview\n--------\n\nConvert Markdown to HTML with ease:\n\n.. code-block:: python\n\n import mistune\n mistune.html(your_markdown_text)\n\nUseful Links\n------------\n\n1. GitHub: https://github.com/lepture/mistune\n2. Docs: https://mistune.lepture.com/\n\nLicense\n-------\n\nMistune is licensed under BSD. Please see LICENSE for licensing details.\n | .venv\Lib\site-packages\mistune-3.1.3.dist-info\METADATA | METADATA | Other | 1,785 | 0.95 | 0.017857 | 0 | node-utils | 46 | 2023-11-25T17:55:47.974107 | MIT | false | 71691709904b7dba8511aa1b798f6bf9 |
mistune-3.1.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\nmistune-3.1.3.dist-info/LICENSE,sha256=U5AT_Y4Z90T4vw4npTK7_1TNaJ7O96gA9Wrl3IJL6HA,1475\nmistune-3.1.3.dist-info/METADATA,sha256=VV4BIW0GqVIiO89rujLho82SAYNGVTvnqZWomBZuJzI,1785\nmistune-3.1.3.dist-info/RECORD,,\nmistune-3.1.3.dist-info/WHEEL,sha256=beeZ86-EfXScwlR_HKu4SllMC9wUEj_8Z_4FJ3egI2w,91\nmistune-3.1.3.dist-info/top_level.txt,sha256=tjJTM65kAdwKAJ2mA769tnDGYYlfR8pqRsobKjVEfcg,8\nmistune/__init__.py,sha256=SSuHQAK_vZ8mEgiHL1TE2WmeX-l12JIHgsG367f1jnI,2938\nmistune/__main__.py,sha256=nm_90CryRFxKBzyizu_e4QQl9cp1UP3FUjuJYn1vesg,3207\nmistune/__pycache__/__init__.cpython-313.pyc,,\nmistune/__pycache__/__main__.cpython-313.pyc,,\nmistune/__pycache__/block_parser.cpython-313.pyc,,\nmistune/__pycache__/core.cpython-313.pyc,,\nmistune/__pycache__/helpers.cpython-313.pyc,,\nmistune/__pycache__/inline_parser.cpython-313.pyc,,\nmistune/__pycache__/list_parser.cpython-313.pyc,,\nmistune/__pycache__/markdown.cpython-313.pyc,,\nmistune/__pycache__/toc.cpython-313.pyc,,\nmistune/__pycache__/util.cpython-313.pyc,,\nmistune/block_parser.py,sha256=wCQhpILUyNJVVUscVIvcDSdQ25a4HGCAhmxg7Bb9Nak,16432\nmistune/core.py,sha256=TjqZWym7Ti54EcXxD1XRAf4jXbAzZmztYZkmjZLpcDQ,7600\nmistune/directives/__init__.py,sha256=qT7tgoezH28ZQXuflmZNl_OtN351khN8U0whfDeuDk4,867\nmistune/directives/__pycache__/__init__.cpython-313.pyc,,\nmistune/directives/__pycache__/_base.cpython-313.pyc,,\nmistune/directives/__pycache__/_fenced.cpython-313.pyc,,\nmistune/directives/__pycache__/_rst.cpython-313.pyc,,\nmistune/directives/__pycache__/admonition.cpython-313.pyc,,\nmistune/directives/__pycache__/image.cpython-313.pyc,,\nmistune/directives/__pycache__/include.cpython-313.pyc,,\nmistune/directives/__pycache__/toc.cpython-313.pyc,,\nmistune/directives/_base.py,sha256=qYYiixJ84YybGLC6K0PVz6Zr3zSk848UggVINND3P0A,4605\nmistune/directives/_fenced.py,sha256=R63TFEm5S_ncgvw6RQXMi1zC7XKDM3BQeqG-FUh2jA4,4826\nmistune/directives/_rst.py,sha256=0SxpcZ96q7QULnapFfIxY53vkEUsuYV4RqdxuBZQCp8,2282\nmistune/directives/admonition.py,sha256=jkR2g0eYpARkJ6pPXqL1dz6kIOZFCHkPUjif955RUhA,2207\nmistune/directives/image.py,sha256=KUoVX8_oMsfBTblQXUV6YSe4bZlFjeJSh5wTkQpK_CQ,5324\nmistune/directives/include.py,sha256=u43Hd8TgYPOToMwxRBye_sdUpxSx2elQhPw97enQZPI,2343\nmistune/directives/toc.py,sha256=xTkUlJmq-FjxdJbCGBEbnlGOGD-ZOUvNVbbAWFDUZ9c,3916\nmistune/helpers.py,sha256=7KfjlGy4J0F7DBOk11wO5-mNxspR31YbtmJbLzVXroQ,4358\nmistune/inline_parser.py,sha256=9Oj4SXHuedhKRDSLSDN-8BnrAo68oHo_4wemLRqHgzg,12670\nmistune/list_parser.py,sha256=BgdOC-sOAFcNvAzKYIiUiBgOIvI5mgmgfdcM9saA3ig,7635\nmistune/markdown.py,sha256=wG77MH2ZBkO6lpxwO2MCbIW_ysRqhuvOnhs9mpzpEaE,4019\nmistune/plugins/__init__.py,sha256=MGKK8a31ylsUBS8Uq5ukSLsN40ZodMpl59BI95UV5jE,1570\nmistune/plugins/__pycache__/__init__.cpython-313.pyc,,\nmistune/plugins/__pycache__/abbr.cpython-313.pyc,,\nmistune/plugins/__pycache__/def_list.cpython-313.pyc,,\nmistune/plugins/__pycache__/footnotes.cpython-313.pyc,,\nmistune/plugins/__pycache__/formatting.cpython-313.pyc,,\nmistune/plugins/__pycache__/math.cpython-313.pyc,,\nmistune/plugins/__pycache__/ruby.cpython-313.pyc,,\nmistune/plugins/__pycache__/speedup.cpython-313.pyc,,\nmistune/plugins/__pycache__/spoiler.cpython-313.pyc,,\nmistune/plugins/__pycache__/table.cpython-313.pyc,,\nmistune/plugins/__pycache__/task_lists.cpython-313.pyc,,\nmistune/plugins/__pycache__/url.cpython-313.pyc,,\nmistune/plugins/abbr.py,sha256=iS4omQnRkUQFOwYDMBtEyCCrbyr1gPBxsr5giFOR39E,3304\nmistune/plugins/def_list.py,sha256=j6c_j2J01ejlwCKwX2kQtUVQWtNiicUZZHkp00mi0KU,4008\nmistune/plugins/footnotes.py,sha256=1TmRXMmDqbP-Vbul4ZLNJlXirSnA2dNixwfRiAH4kkQ,4985\nmistune/plugins/formatting.py,sha256=zMa1vsSrJlQvUbwnKon6zQSolEkyLFCyyGtk4TnezG8,5435\nmistune/plugins/math.py,sha256=8bCEwYPPZU6nr7ObcDAXOhERecDyF0xr18m_znpnPbc,2146\nmistune/plugins/ruby.py,sha256=yjCXA7uUIldN45Pm2cnfrtJV1CSXgIjDclm0ZQcpjnU,3282\nmistune/plugins/speedup.py,sha256=lHxPdGMK3B0jzFxiyRwzk13xxjOa-EYbp8gBTLACFQU,1418\nmistune/plugins/spoiler.py,sha256=fAH6leeBvVGUtcajA7qWkM-IlQOyJhAep-05O-Y-WiM,2823\nmistune/plugins/table.py,sha256=xo8-ioD7tR4FEXGAdq_IX4JCZcv2dZ6jKk2SDh2j-Dw,5722\nmistune/plugins/task_lists.py,sha256=489qRZIlNj9VWKGkoCKO1adNIpR981iznaGUqiR11vM,2000\nmistune/plugins/url.py,sha256=IiexcUWRf5USDBlc8-ECNiCilsMf0frSFmys8wyrez8,800\nmistune/py.typed,sha256=durf3Hkenfp95IMLYpv-GcCnbKllxRY51DcmTZJqsB8,181\nmistune/renderers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nmistune/renderers/__pycache__/__init__.cpython-313.pyc,,\nmistune/renderers/__pycache__/_list.cpython-313.pyc,,\nmistune/renderers/__pycache__/html.cpython-313.pyc,,\nmistune/renderers/__pycache__/markdown.cpython-313.pyc,,\nmistune/renderers/__pycache__/rst.cpython-313.pyc,,\nmistune/renderers/_list.py,sha256=65vzfmHJucTcg4MStXwBGIR6ZOhI8H8IWx9hL4ZKws0,2066\nmistune/renderers/html.py,sha256=XQoaOAOQbKOz7WH7OoZ3R-AGMgc3zx05nDVg_o23MMg,4926\nmistune/renderers/markdown.py,sha256=Kt0qFW_pPlQ1LzSEDLY1xef0q4O1fixcb80ENgznSrE,4962\nmistune/renderers/rst.py,sha256=Kgcxi8tDnwvB7qb5GgtKPB5iYOilGMtm9sFLfLAAE60,5523\nmistune/toc.py,sha256=U_QqHACE8qEhLCZmUhtijLC36ZvSRuBXXP4GXYJXZcc,3638\nmistune/util.py,sha256=zQgXSy3VlNd2izq3Ms4YGTy8uwRDSzFodPeP8giOAcE,1978\n | .venv\Lib\site-packages\mistune-3.1.3.dist-info\RECORD | RECORD | Other | 5,299 | 0.7 | 0 | 0 | react-lib | 122 | 2023-12-25T08:13:28.014855 | Apache-2.0 | false | eaf4d9cf12df2100e460a3eeed186608 |
mistune\n | .venv\Lib\site-packages\mistune-3.1.3.dist-info\top_level.txt | top_level.txt | Other | 8 | 0.5 | 0 | 0 | node-utils | 196 | 2024-02-11T19:51:19.203460 | BSD-3-Clause | false | 9fcadb8eef9639d9c32097190f7d344b |
Wheel-Version: 1.0\nGenerator: setuptools (76.1.0)\nRoot-Is-Purelib: true\nTag: py3-none-any\n\n | .venv\Lib\site-packages\mistune-3.1.3.dist-info\WHEEL | WHEEL | Other | 91 | 0.5 | 0 | 0 | vue-tools | 803 | 2025-02-24T02:45:44.838447 | Apache-2.0 | false | 1183884662222bc6d045674285630815 |
from matplotlib import transforms\nfrom matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox,\n DrawingArea, TextArea, VPacker)\nfrom matplotlib.patches import (Rectangle, ArrowStyle,\n FancyArrowPatch, PathPatch)\nfrom matplotlib.text import TextPath\n\n__all__ = ['AnchoredDrawingArea', 'AnchoredAuxTransformBox',\n 'AnchoredSizeBar', 'AnchoredDirectionArrows']\n\n\nclass AnchoredDrawingArea(AnchoredOffsetbox):\n def __init__(self, width, height, xdescent, ydescent,\n loc, pad=0.4, borderpad=0.5, prop=None, frameon=True,\n **kwargs):\n """\n An anchored container with a fixed size and fillable `.DrawingArea`.\n\n Artists added to the *drawing_area* will have their coordinates\n interpreted as pixels. Any transformations set on the artists will be\n overridden.\n\n Parameters\n ----------\n width, height : float\n Width and height of the container, in pixels.\n xdescent, ydescent : float\n Descent of the container in the x- and y- direction, in pixels.\n loc : str\n Location of this artist. Valid locations are\n 'upper left', 'upper center', 'upper right',\n 'center left', 'center', 'center right',\n 'lower left', 'lower center', 'lower right'.\n For backward compatibility, numeric values are accepted as well.\n See the parameter *loc* of `.Legend` for details.\n pad : float, default: 0.4\n Padding around the child objects, in fraction of the font size.\n borderpad : float, default: 0.5\n Border padding, in fraction of the font size.\n prop : `~matplotlib.font_manager.FontProperties`, optional\n Font property used as a reference for paddings.\n frameon : bool, default: True\n If True, draw a box around this artist.\n **kwargs\n Keyword arguments forwarded to `.AnchoredOffsetbox`.\n\n Attributes\n ----------\n drawing_area : `~matplotlib.offsetbox.DrawingArea`\n A container for artists to display.\n\n Examples\n --------\n To display blue and red circles of different sizes in the upper right\n of an Axes *ax*:\n\n >>> ada = AnchoredDrawingArea(20, 20, 0, 0,\n ... loc='upper right', frameon=False)\n >>> ada.drawing_area.add_artist(Circle((10, 10), 10, fc="b"))\n >>> ada.drawing_area.add_artist(Circle((30, 10), 5, fc="r"))\n >>> ax.add_artist(ada)\n """\n self.da = DrawingArea(width, height, xdescent, ydescent)\n self.drawing_area = self.da\n\n super().__init__(\n loc, pad=pad, borderpad=borderpad, child=self.da, prop=None,\n frameon=frameon, **kwargs\n )\n\n\nclass AnchoredAuxTransformBox(AnchoredOffsetbox):\n def __init__(self, transform, loc,\n pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs):\n """\n An anchored container with transformed coordinates.\n\n Artists added to the *drawing_area* are scaled according to the\n coordinates of the transformation used. The dimensions of this artist\n will scale to contain the artists added.\n\n Parameters\n ----------\n transform : `~matplotlib.transforms.Transform`\n The transformation object for the coordinate system in use, i.e.,\n :attr:`matplotlib.axes.Axes.transData`.\n loc : str\n Location of this artist. Valid locations are\n 'upper left', 'upper center', 'upper right',\n 'center left', 'center', 'center right',\n 'lower left', 'lower center', 'lower right'.\n For backward compatibility, numeric values are accepted as well.\n See the parameter *loc* of `.Legend` for details.\n pad : float, default: 0.4\n Padding around the child objects, in fraction of the font size.\n borderpad : float, default: 0.5\n Border padding, in fraction of the font size.\n prop : `~matplotlib.font_manager.FontProperties`, optional\n Font property used as a reference for paddings.\n frameon : bool, default: True\n If True, draw a box around this artist.\n **kwargs\n Keyword arguments forwarded to `.AnchoredOffsetbox`.\n\n Attributes\n ----------\n drawing_area : `~matplotlib.offsetbox.AuxTransformBox`\n A container for artists to display.\n\n Examples\n --------\n To display an ellipse in the upper left, with a width of 0.1 and\n height of 0.4 in data coordinates:\n\n >>> box = AnchoredAuxTransformBox(ax.transData, loc='upper left')\n >>> el = Ellipse((0, 0), width=0.1, height=0.4, angle=30)\n >>> box.drawing_area.add_artist(el)\n >>> ax.add_artist(box)\n """\n self.drawing_area = AuxTransformBox(transform)\n\n super().__init__(loc, pad=pad, borderpad=borderpad,\n child=self.drawing_area, prop=prop, frameon=frameon,\n **kwargs)\n\n\nclass AnchoredSizeBar(AnchoredOffsetbox):\n def __init__(self, transform, size, label, loc,\n pad=0.1, borderpad=0.1, sep=2,\n frameon=True, size_vertical=0, color='black',\n label_top=False, fontproperties=None, fill_bar=None,\n **kwargs):\n """\n Draw a horizontal scale bar with a center-aligned label underneath.\n\n Parameters\n ----------\n transform : `~matplotlib.transforms.Transform`\n The transformation object for the coordinate system in use, i.e.,\n :attr:`matplotlib.axes.Axes.transData`.\n size : float\n Horizontal length of the size bar, given in coordinates of\n *transform*.\n label : str\n Label to display.\n loc : str\n Location of the size bar. Valid locations are\n 'upper left', 'upper center', 'upper right',\n 'center left', 'center', 'center right',\n 'lower left', 'lower center', 'lower right'.\n For backward compatibility, numeric values are accepted as well.\n See the parameter *loc* of `.Legend` for details.\n pad : float, default: 0.1\n Padding around the label and size bar, in fraction of the font\n size.\n borderpad : float, default: 0.1\n Border padding, in fraction of the font size.\n sep : float, default: 2\n Separation between the label and the size bar, in points.\n frameon : bool, default: True\n If True, draw a box around the horizontal bar and label.\n size_vertical : float, default: 0\n Vertical length of the size bar, given in coordinates of\n *transform*.\n color : str, default: 'black'\n Color for the size bar and label.\n label_top : bool, default: False\n If True, the label will be over the size bar.\n fontproperties : `~matplotlib.font_manager.FontProperties`, optional\n Font properties for the label text.\n fill_bar : bool, optional\n If True and if *size_vertical* is nonzero, the size bar will\n be filled in with the color specified by the size bar.\n Defaults to True if *size_vertical* is greater than\n zero and False otherwise.\n **kwargs\n Keyword arguments forwarded to `.AnchoredOffsetbox`.\n\n Attributes\n ----------\n size_bar : `~matplotlib.offsetbox.AuxTransformBox`\n Container for the size bar.\n txt_label : `~matplotlib.offsetbox.TextArea`\n Container for the label of the size bar.\n\n Notes\n -----\n If *prop* is passed as a keyword argument, but *fontproperties* is\n not, then *prop* is assumed to be the intended *fontproperties*.\n Using both *prop* and *fontproperties* is not supported.\n\n Examples\n --------\n >>> import matplotlib.pyplot as plt\n >>> import numpy as np\n >>> from mpl_toolkits.axes_grid1.anchored_artists import (\n ... AnchoredSizeBar)\n >>> fig, ax = plt.subplots()\n >>> ax.imshow(np.random.random((10, 10)))\n >>> bar = AnchoredSizeBar(ax.transData, 3, '3 data units', 4)\n >>> ax.add_artist(bar)\n >>> fig.show()\n\n Using all the optional parameters\n\n >>> import matplotlib.font_manager as fm\n >>> fontprops = fm.FontProperties(size=14, family='monospace')\n >>> bar = AnchoredSizeBar(ax.transData, 3, '3 units', 4, pad=0.5,\n ... sep=5, borderpad=0.5, frameon=False,\n ... size_vertical=0.5, color='white',\n ... fontproperties=fontprops)\n """\n if fill_bar is None:\n fill_bar = size_vertical > 0\n\n self.size_bar = AuxTransformBox(transform)\n self.size_bar.add_artist(Rectangle((0, 0), size, size_vertical,\n fill=fill_bar, facecolor=color,\n edgecolor=color))\n\n if fontproperties is None and 'prop' in kwargs:\n fontproperties = kwargs.pop('prop')\n\n if fontproperties is None:\n textprops = {'color': color}\n else:\n textprops = {'color': color, 'fontproperties': fontproperties}\n\n self.txt_label = TextArea(label, textprops=textprops)\n\n if label_top:\n _box_children = [self.txt_label, self.size_bar]\n else:\n _box_children = [self.size_bar, self.txt_label]\n\n self._box = VPacker(children=_box_children,\n align="center",\n pad=0, sep=sep)\n\n super().__init__(loc, pad=pad, borderpad=borderpad, child=self._box,\n prop=fontproperties, frameon=frameon, **kwargs)\n\n\nclass AnchoredDirectionArrows(AnchoredOffsetbox):\n def __init__(self, transform, label_x, label_y, length=0.15,\n fontsize=0.08, loc='upper left', angle=0, aspect_ratio=1,\n pad=0.4, borderpad=0.4, frameon=False, color='w', alpha=1,\n sep_x=0.01, sep_y=0, fontproperties=None, back_length=0.15,\n head_width=10, head_length=15, tail_width=2,\n text_props=None, arrow_props=None,\n **kwargs):\n """\n Draw two perpendicular arrows to indicate directions.\n\n Parameters\n ----------\n transform : `~matplotlib.transforms.Transform`\n The transformation object for the coordinate system in use, i.e.,\n :attr:`matplotlib.axes.Axes.transAxes`.\n label_x, label_y : str\n Label text for the x and y arrows\n length : float, default: 0.15\n Length of the arrow, given in coordinates of *transform*.\n fontsize : float, default: 0.08\n Size of label strings, given in coordinates of *transform*.\n loc : str, default: 'upper left'\n Location of the arrow. Valid locations are\n 'upper left', 'upper center', 'upper right',\n 'center left', 'center', 'center right',\n 'lower left', 'lower center', 'lower right'.\n For backward compatibility, numeric values are accepted as well.\n See the parameter *loc* of `.Legend` for details.\n angle : float, default: 0\n The angle of the arrows in degrees.\n aspect_ratio : float, default: 1\n The ratio of the length of arrow_x and arrow_y.\n Negative numbers can be used to change the direction.\n pad : float, default: 0.4\n Padding around the labels and arrows, in fraction of the font size.\n borderpad : float, default: 0.4\n Border padding, in fraction of the font size.\n frameon : bool, default: False\n If True, draw a box around the arrows and labels.\n color : str, default: 'white'\n Color for the arrows and labels.\n alpha : float, default: 1\n Alpha values of the arrows and labels\n sep_x, sep_y : float, default: 0.01 and 0 respectively\n Separation between the arrows and labels in coordinates of\n *transform*.\n fontproperties : `~matplotlib.font_manager.FontProperties`, optional\n Font properties for the label text.\n back_length : float, default: 0.15\n Fraction of the arrow behind the arrow crossing.\n head_width : float, default: 10\n Width of arrow head, sent to `.ArrowStyle`.\n head_length : float, default: 15\n Length of arrow head, sent to `.ArrowStyle`.\n tail_width : float, default: 2\n Width of arrow tail, sent to `.ArrowStyle`.\n text_props, arrow_props : dict\n Properties of the text and arrows, passed to `.TextPath` and\n `.FancyArrowPatch`.\n **kwargs\n Keyword arguments forwarded to `.AnchoredOffsetbox`.\n\n Attributes\n ----------\n arrow_x, arrow_y : `~matplotlib.patches.FancyArrowPatch`\n Arrow x and y\n text_path_x, text_path_y : `~matplotlib.text.TextPath`\n Path for arrow labels\n p_x, p_y : `~matplotlib.patches.PathPatch`\n Patch for arrow labels\n box : `~matplotlib.offsetbox.AuxTransformBox`\n Container for the arrows and labels.\n\n Notes\n -----\n If *prop* is passed as a keyword argument, but *fontproperties* is\n not, then *prop* is assumed to be the intended *fontproperties*.\n Using both *prop* and *fontproperties* is not supported.\n\n Examples\n --------\n >>> import matplotlib.pyplot as plt\n >>> import numpy as np\n >>> from mpl_toolkits.axes_grid1.anchored_artists import (\n ... AnchoredDirectionArrows)\n >>> fig, ax = plt.subplots()\n >>> ax.imshow(np.random.random((10, 10)))\n >>> arrows = AnchoredDirectionArrows(ax.transAxes, '111', '110')\n >>> ax.add_artist(arrows)\n >>> fig.show()\n\n Using several of the optional parameters, creating downward pointing\n arrow and high contrast text labels.\n\n >>> import matplotlib.font_manager as fm\n >>> fontprops = fm.FontProperties(family='monospace')\n >>> arrows = AnchoredDirectionArrows(ax.transAxes, 'East', 'South',\n ... loc='lower left', color='k',\n ... aspect_ratio=-1, sep_x=0.02,\n ... sep_y=-0.01,\n ... text_props={'ec':'w', 'fc':'k'},\n ... fontproperties=fontprops)\n """\n if arrow_props is None:\n arrow_props = {}\n\n if text_props is None:\n text_props = {}\n\n arrowstyle = ArrowStyle("Simple",\n head_width=head_width,\n head_length=head_length,\n tail_width=tail_width)\n\n if fontproperties is None and 'prop' in kwargs:\n fontproperties = kwargs.pop('prop')\n\n if 'color' not in arrow_props:\n arrow_props['color'] = color\n\n if 'alpha' not in arrow_props:\n arrow_props['alpha'] = alpha\n\n if 'color' not in text_props:\n text_props['color'] = color\n\n if 'alpha' not in text_props:\n text_props['alpha'] = alpha\n\n t_start = transform\n t_end = t_start + transforms.Affine2D().rotate_deg(angle)\n\n self.box = AuxTransformBox(t_end)\n\n length_x = length\n length_y = length*aspect_ratio\n\n self.arrow_x = FancyArrowPatch(\n (0, back_length*length_y),\n (length_x, back_length*length_y),\n arrowstyle=arrowstyle,\n shrinkA=0.0,\n shrinkB=0.0,\n **arrow_props)\n\n self.arrow_y = FancyArrowPatch(\n (back_length*length_x, 0),\n (back_length*length_x, length_y),\n arrowstyle=arrowstyle,\n shrinkA=0.0,\n shrinkB=0.0,\n **arrow_props)\n\n self.box.add_artist(self.arrow_x)\n self.box.add_artist(self.arrow_y)\n\n text_path_x = TextPath((\n length_x+sep_x, back_length*length_y+sep_y), label_x,\n size=fontsize, prop=fontproperties)\n self.p_x = PathPatch(text_path_x, transform=t_start, **text_props)\n self.box.add_artist(self.p_x)\n\n text_path_y = TextPath((\n length_x*back_length+sep_x, length_y*(1-back_length)+sep_y),\n label_y, size=fontsize, prop=fontproperties)\n self.p_y = PathPatch(text_path_y, **text_props)\n self.box.add_artist(self.p_y)\n\n super().__init__(loc, pad=pad, borderpad=borderpad, child=self.box,\n frameon=frameon, **kwargs)\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\anchored_artists.py | anchored_artists.py | Python | 17,161 | 0.85 | 0.101449 | 0.036313 | awesome-app | 513 | 2025-07-08T08:51:20.238219 | MIT | false | 5ba8b376b0452151c96bc7e9e3c4c55d |
"""\nHelper classes to adjust the positions of multiple axes at drawing time.\n"""\n\nimport functools\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api\nfrom matplotlib.gridspec import SubplotSpec\nimport matplotlib.transforms as mtransforms\nfrom . import axes_size as Size\n\n\nclass Divider:\n """\n An Axes positioning class.\n\n The divider is initialized with lists of horizontal and vertical sizes\n (:mod:`mpl_toolkits.axes_grid1.axes_size`) based on which a given\n rectangular area will be divided.\n\n The `new_locator` method then creates a callable object\n that can be used as the *axes_locator* of the axes.\n """\n\n def __init__(self, fig, pos, horizontal, vertical,\n aspect=None, anchor="C"):\n """\n Parameters\n ----------\n fig : Figure\n pos : tuple of 4 floats\n Position of the rectangle that will be divided.\n horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`\n Sizes for horizontal division.\n vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`\n Sizes for vertical division.\n aspect : bool, optional\n Whether overall rectangular area is reduced so that the relative\n part of the horizontal and vertical scales have the same scale.\n anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \\n'NW', 'W'}, default: 'C'\n Placement of the reduced rectangle, when *aspect* is True.\n """\n\n self._fig = fig\n self._pos = pos\n self._horizontal = horizontal\n self._vertical = vertical\n self._anchor = anchor\n self.set_anchor(anchor)\n self._aspect = aspect\n self._xrefindex = 0\n self._yrefindex = 0\n self._locator = None\n\n def get_horizontal_sizes(self, renderer):\n return np.array([s.get_size(renderer) for s in self.get_horizontal()])\n\n def get_vertical_sizes(self, renderer):\n return np.array([s.get_size(renderer) for s in self.get_vertical()])\n\n def set_position(self, pos):\n """\n Set the position of the rectangle.\n\n Parameters\n ----------\n pos : tuple of 4 floats\n position of the rectangle that will be divided\n """\n self._pos = pos\n\n def get_position(self):\n """Return the position of the rectangle."""\n return self._pos\n\n def set_anchor(self, anchor):\n """\n Parameters\n ----------\n anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \\n'NW', 'W'}\n Either an (*x*, *y*) pair of relative coordinates (0 is left or\n bottom, 1 is right or top), 'C' (center), or a cardinal direction\n ('SW', southwest, is bottom left, etc.).\n\n See Also\n --------\n .Axes.set_anchor\n """\n if isinstance(anchor, str):\n _api.check_in_list(mtransforms.Bbox.coefs, anchor=anchor)\n elif not isinstance(anchor, (tuple, list)) or len(anchor) != 2:\n raise TypeError("anchor must be str or 2-tuple")\n self._anchor = anchor\n\n def get_anchor(self):\n """Return the anchor."""\n return self._anchor\n\n def get_subplotspec(self):\n return None\n\n def set_horizontal(self, h):\n """\n Parameters\n ----------\n h : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`\n sizes for horizontal division\n """\n self._horizontal = h\n\n def get_horizontal(self):\n """Return horizontal sizes."""\n return self._horizontal\n\n def set_vertical(self, v):\n """\n Parameters\n ----------\n v : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`\n sizes for vertical division\n """\n self._vertical = v\n\n def get_vertical(self):\n """Return vertical sizes."""\n return self._vertical\n\n def set_aspect(self, aspect=False):\n """\n Parameters\n ----------\n aspect : bool\n """\n self._aspect = aspect\n\n def get_aspect(self):\n """Return aspect."""\n return self._aspect\n\n def set_locator(self, _locator):\n self._locator = _locator\n\n def get_locator(self):\n return self._locator\n\n def get_position_runtime(self, ax, renderer):\n if self._locator is None:\n return self.get_position()\n else:\n return self._locator(ax, renderer).bounds\n\n @staticmethod\n def _calc_k(sizes, total):\n # sizes is a (n, 2) array of (rel_size, abs_size); this method finds\n # the k factor such that sum(rel_size * k + abs_size) == total.\n rel_sum, abs_sum = sizes.sum(0)\n return (total - abs_sum) / rel_sum if rel_sum else 0\n\n @staticmethod\n def _calc_offsets(sizes, k):\n # Apply k factors to (n, 2) sizes array of (rel_size, abs_size); return\n # the resulting cumulative offset positions.\n return np.cumsum([0, *(sizes @ [k, 1])])\n\n def new_locator(self, nx, ny, nx1=None, ny1=None):\n """\n Return an axes locator callable for the specified cell.\n\n Parameters\n ----------\n nx, nx1 : int\n Integers specifying the column-position of the\n cell. When *nx1* is None, a single *nx*-th column is\n specified. Otherwise, location of columns spanning between *nx*\n to *nx1* (but excluding *nx1*-th column) is specified.\n ny, ny1 : int\n Same as *nx* and *nx1*, but for row positions.\n """\n if nx1 is None:\n nx1 = nx + 1\n if ny1 is None:\n ny1 = ny + 1\n # append_size("left") adds a new size at the beginning of the\n # horizontal size lists; this shift transforms e.g.\n # new_locator(nx=2, ...) into effectively new_locator(nx=3, ...). To\n # take that into account, instead of recording nx, we record\n # nx-self._xrefindex, where _xrefindex is shifted by 1 by each\n # append_size("left"), and re-add self._xrefindex back to nx in\n # _locate, when the actual axes position is computed. Ditto for y.\n xref = self._xrefindex\n yref = self._yrefindex\n locator = functools.partial(\n self._locate, nx - xref, ny - yref, nx1 - xref, ny1 - yref)\n locator.get_subplotspec = self.get_subplotspec\n return locator\n\n def _locate(self, nx, ny, nx1, ny1, axes, renderer):\n """\n Implementation of ``divider.new_locator().__call__``.\n\n The axes locator callable returned by ``new_locator()`` is created as\n a `functools.partial` of this method with *nx*, *ny*, *nx1*, and *ny1*\n specifying the requested cell.\n """\n nx += self._xrefindex\n nx1 += self._xrefindex\n ny += self._yrefindex\n ny1 += self._yrefindex\n\n fig_w, fig_h = self._fig.bbox.size / self._fig.dpi\n x, y, w, h = self.get_position_runtime(axes, renderer)\n\n hsizes = self.get_horizontal_sizes(renderer)\n vsizes = self.get_vertical_sizes(renderer)\n k_h = self._calc_k(hsizes, fig_w * w)\n k_v = self._calc_k(vsizes, fig_h * h)\n\n if self.get_aspect():\n k = min(k_h, k_v)\n ox = self._calc_offsets(hsizes, k)\n oy = self._calc_offsets(vsizes, k)\n\n ww = (ox[-1] - ox[0]) / fig_w\n hh = (oy[-1] - oy[0]) / fig_h\n pb = mtransforms.Bbox.from_bounds(x, y, w, h)\n pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)\n x0, y0 = pb1.anchored(self.get_anchor(), pb).p0\n\n else:\n ox = self._calc_offsets(hsizes, k_h)\n oy = self._calc_offsets(vsizes, k_v)\n x0, y0 = x, y\n\n if nx1 is None:\n nx1 = -1\n if ny1 is None:\n ny1 = -1\n\n x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w\n y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h\n\n return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)\n\n def append_size(self, position, size):\n _api.check_in_list(["left", "right", "bottom", "top"],\n position=position)\n if position == "left":\n self._horizontal.insert(0, size)\n self._xrefindex += 1\n elif position == "right":\n self._horizontal.append(size)\n elif position == "bottom":\n self._vertical.insert(0, size)\n self._yrefindex += 1\n else: # 'top'\n self._vertical.append(size)\n\n def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None):\n """\n Add auto-adjustable padding around *use_axes* to take their decorations\n (title, labels, ticks, ticklabels) into account during layout.\n\n Parameters\n ----------\n use_axes : `~matplotlib.axes.Axes` or list of `~matplotlib.axes.Axes`\n The Axes whose decorations are taken into account.\n pad : float, default: 0.1\n Additional padding in inches.\n adjust_dirs : list of {"left", "right", "bottom", "top"}, optional\n The sides where padding is added; defaults to all four sides.\n """\n if adjust_dirs is None:\n adjust_dirs = ["left", "right", "bottom", "top"]\n for d in adjust_dirs:\n self.append_size(d, Size._AxesDecorationsSize(use_axes, d) + pad)\n\n\nclass SubplotDivider(Divider):\n """\n The Divider class whose rectangle area is specified as a subplot geometry.\n """\n\n def __init__(self, fig, *args, horizontal=None, vertical=None,\n aspect=None, anchor='C'):\n """\n Parameters\n ----------\n fig : `~matplotlib.figure.Figure`\n\n *args : tuple (*nrows*, *ncols*, *index*) or int\n The array of subplots in the figure has dimensions ``(nrows,\n ncols)``, and *index* is the index of the subplot being created.\n *index* starts at 1 in the upper left corner and increases to the\n right.\n\n If *nrows*, *ncols*, and *index* are all single digit numbers, then\n *args* can be passed as a single 3-digit number (e.g. 234 for\n (2, 3, 4)).\n horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional\n Sizes for horizontal division.\n vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional\n Sizes for vertical division.\n aspect : bool, optional\n Whether overall rectangular area is reduced so that the relative\n part of the horizontal and vertical scales have the same scale.\n anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \\n'NW', 'W'}, default: 'C'\n Placement of the reduced rectangle, when *aspect* is True.\n """\n self.figure = fig\n super().__init__(fig, [0, 0, 1, 1],\n horizontal=horizontal or [], vertical=vertical or [],\n aspect=aspect, anchor=anchor)\n self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))\n\n def get_position(self):\n """Return the bounds of the subplot box."""\n return self.get_subplotspec().get_position(self.figure).bounds\n\n def get_subplotspec(self):\n """Get the SubplotSpec instance."""\n return self._subplotspec\n\n def set_subplotspec(self, subplotspec):\n """Set the SubplotSpec instance."""\n self._subplotspec = subplotspec\n self.set_position(subplotspec.get_position(self.figure))\n\n\nclass AxesDivider(Divider):\n """\n Divider based on the preexisting axes.\n """\n\n def __init__(self, axes, xref=None, yref=None):\n """\n Parameters\n ----------\n axes : :class:`~matplotlib.axes.Axes`\n xref\n yref\n """\n self._axes = axes\n if xref is None:\n self._xref = Size.AxesX(axes)\n else:\n self._xref = xref\n if yref is None:\n self._yref = Size.AxesY(axes)\n else:\n self._yref = yref\n\n super().__init__(fig=axes.get_figure(), pos=None,\n horizontal=[self._xref], vertical=[self._yref],\n aspect=None, anchor="C")\n\n def _get_new_axes(self, *, axes_class=None, **kwargs):\n axes = self._axes\n if axes_class is None:\n axes_class = type(axes)\n return axes_class(axes.get_figure(), axes.get_position(original=True),\n **kwargs)\n\n def new_horizontal(self, size, pad=None, pack_start=False, **kwargs):\n """\n Helper method for ``append_axes("left")`` and ``append_axes("right")``.\n\n See the documentation of `append_axes` for more details.\n\n :meta private:\n """\n if pad is None:\n pad = mpl.rcParams["figure.subplot.wspace"] * self._xref\n pos = "left" if pack_start else "right"\n if pad:\n if not isinstance(pad, Size._Base):\n pad = Size.from_any(pad, fraction_ref=self._xref)\n self.append_size(pos, pad)\n if not isinstance(size, Size._Base):\n size = Size.from_any(size, fraction_ref=self._xref)\n self.append_size(pos, size)\n locator = self.new_locator(\n nx=0 if pack_start else len(self._horizontal) - 1,\n ny=self._yrefindex)\n ax = self._get_new_axes(**kwargs)\n ax.set_axes_locator(locator)\n return ax\n\n def new_vertical(self, size, pad=None, pack_start=False, **kwargs):\n """\n Helper method for ``append_axes("top")`` and ``append_axes("bottom")``.\n\n See the documentation of `append_axes` for more details.\n\n :meta private:\n """\n if pad is None:\n pad = mpl.rcParams["figure.subplot.hspace"] * self._yref\n pos = "bottom" if pack_start else "top"\n if pad:\n if not isinstance(pad, Size._Base):\n pad = Size.from_any(pad, fraction_ref=self._yref)\n self.append_size(pos, pad)\n if not isinstance(size, Size._Base):\n size = Size.from_any(size, fraction_ref=self._yref)\n self.append_size(pos, size)\n locator = self.new_locator(\n nx=self._xrefindex,\n ny=0 if pack_start else len(self._vertical) - 1)\n ax = self._get_new_axes(**kwargs)\n ax.set_axes_locator(locator)\n return ax\n\n def append_axes(self, position, size, pad=None, *, axes_class=None,\n **kwargs):\n """\n Add a new axes on a given side of the main axes.\n\n Parameters\n ----------\n position : {"left", "right", "bottom", "top"}\n Where the new axes is positioned relative to the main axes.\n size : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str\n The axes width or height. float or str arguments are interpreted\n as ``axes_size.from_any(size, AxesX(<main_axes>))`` for left or\n right axes, and likewise with ``AxesY`` for bottom or top axes.\n pad : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str\n Padding between the axes. float or str arguments are interpreted\n as for *size*. Defaults to :rc:`figure.subplot.wspace` times the\n main Axes width (left or right axes) or :rc:`figure.subplot.hspace`\n times the main Axes height (bottom or top axes).\n axes_class : subclass type of `~.axes.Axes`, optional\n The type of the new axes. Defaults to the type of the main axes.\n **kwargs\n All extra keywords arguments are passed to the created axes.\n """\n create_axes, pack_start = _api.check_getitem({\n "left": (self.new_horizontal, True),\n "right": (self.new_horizontal, False),\n "bottom": (self.new_vertical, True),\n "top": (self.new_vertical, False),\n }, position=position)\n ax = create_axes(\n size, pad, pack_start=pack_start, axes_class=axes_class, **kwargs)\n self._fig.add_axes(ax)\n return ax\n\n def get_aspect(self):\n if self._aspect is None:\n aspect = self._axes.get_aspect()\n if aspect == "auto":\n return False\n else:\n return True\n else:\n return self._aspect\n\n def get_position(self):\n if self._pos is None:\n bbox = self._axes.get_position(original=True)\n return bbox.bounds\n else:\n return self._pos\n\n def get_anchor(self):\n if self._anchor is None:\n return self._axes.get_anchor()\n else:\n return self._anchor\n\n def get_subplotspec(self):\n return self._axes.get_subplotspec()\n\n\n# Helper for HBoxDivider/VBoxDivider.\n# The variable names are written for a horizontal layout, but the calculations\n# work identically for vertical layouts.\ndef _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor):\n\n total_width = fig_w * w\n max_height = fig_h * h\n\n # Determine the k factors.\n n = len(equal_heights)\n eq_rels, eq_abss = equal_heights.T\n sm_rels, sm_abss = summed_widths.T\n A = np.diag([*eq_rels, 0])\n A[:n, -1] = -1\n A[-1, :-1] = sm_rels\n B = [*(-eq_abss), total_width - sm_abss.sum()]\n # A @ K = B: This finds factors {k_0, ..., k_{N-1}, H} so that\n # eq_rel_i * k_i + eq_abs_i = H for all i: all axes have the same height\n # sum(sm_rel_i * k_i + sm_abs_i) = total_width: fixed total width\n # (foo_rel_i * k_i + foo_abs_i will end up being the size of foo.)\n *karray, height = np.linalg.solve(A, B)\n if height > max_height: # Additionally, upper-bound the height.\n karray = (max_height - eq_abss) / eq_rels\n\n # Compute the offsets corresponding to these factors.\n ox = np.cumsum([0, *(sm_rels * karray + sm_abss)])\n ww = (ox[-1] - ox[0]) / fig_w\n h0_rel, h0_abs = equal_heights[0]\n hh = (karray[0]*h0_rel + h0_abs) / fig_h\n pb = mtransforms.Bbox.from_bounds(x, y, w, h)\n pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)\n x0, y0 = pb1.anchored(anchor, pb).p0\n\n return x0, y0, ox, hh\n\n\nclass HBoxDivider(SubplotDivider):\n """\n A `.SubplotDivider` for laying out axes horizontally, while ensuring that\n they have equal heights.\n\n Examples\n --------\n .. plot:: gallery/axes_grid1/demo_axes_hbox_divider.py\n """\n\n def new_locator(self, nx, nx1=None):\n """\n Create an axes locator callable for the specified cell.\n\n Parameters\n ----------\n nx, nx1 : int\n Integers specifying the column-position of the\n cell. When *nx1* is None, a single *nx*-th column is\n specified. Otherwise, location of columns spanning between *nx*\n to *nx1* (but excluding *nx1*-th column) is specified.\n """\n return super().new_locator(nx, 0, nx1, 0)\n\n def _locate(self, nx, ny, nx1, ny1, axes, renderer):\n # docstring inherited\n nx += self._xrefindex\n nx1 += self._xrefindex\n fig_w, fig_h = self._fig.bbox.size / self._fig.dpi\n x, y, w, h = self.get_position_runtime(axes, renderer)\n summed_ws = self.get_horizontal_sizes(renderer)\n equal_hs = self.get_vertical_sizes(renderer)\n x0, y0, ox, hh = _locate(\n x, y, w, h, summed_ws, equal_hs, fig_w, fig_h, self.get_anchor())\n if nx1 is None:\n nx1 = -1\n x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w\n y1, h1 = y0, hh\n return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)\n\n\nclass VBoxDivider(SubplotDivider):\n """\n A `.SubplotDivider` for laying out axes vertically, while ensuring that\n they have equal widths.\n """\n\n def new_locator(self, ny, ny1=None):\n """\n Create an axes locator callable for the specified cell.\n\n Parameters\n ----------\n ny, ny1 : int\n Integers specifying the row-position of the\n cell. When *ny1* is None, a single *ny*-th row is\n specified. Otherwise, location of rows spanning between *ny*\n to *ny1* (but excluding *ny1*-th row) is specified.\n """\n return super().new_locator(0, ny, 0, ny1)\n\n def _locate(self, nx, ny, nx1, ny1, axes, renderer):\n # docstring inherited\n ny += self._yrefindex\n ny1 += self._yrefindex\n fig_w, fig_h = self._fig.bbox.size / self._fig.dpi\n x, y, w, h = self.get_position_runtime(axes, renderer)\n summed_hs = self.get_vertical_sizes(renderer)\n equal_ws = self.get_horizontal_sizes(renderer)\n y0, x0, oy, ww = _locate(\n y, x, h, w, summed_hs, equal_ws, fig_h, fig_w, self.get_anchor())\n if ny1 is None:\n ny1 = -1\n x1, w1 = x0, ww\n y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h\n return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)\n\n\ndef make_axes_locatable(axes):\n divider = AxesDivider(axes)\n locator = divider.new_locator(nx=0, ny=0)\n axes.set_axes_locator(locator)\n\n return divider\n\n\ndef make_axes_area_auto_adjustable(\n ax, use_axes=None, pad=0.1, adjust_dirs=None):\n """\n Add auto-adjustable padding around *ax* to take its decorations (title,\n labels, ticks, ticklabels) into account during layout, using\n `.Divider.add_auto_adjustable_area`.\n\n By default, padding is determined from the decorations of *ax*.\n Pass *use_axes* to consider the decorations of other Axes instead.\n """\n if adjust_dirs is None:\n adjust_dirs = ["left", "right", "bottom", "top"]\n divider = make_axes_locatable(ax)\n if use_axes is None:\n use_axes = ax\n divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad,\n adjust_dirs=adjust_dirs)\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\axes_divider.py | axes_divider.py | Python | 21,892 | 0.95 | 0.186084 | 0.055133 | python-kit | 393 | 2024-03-22T04:53:22.762080 | MIT | false | 39113740e7344187459a10329ee211a4 |
from numbers import Number\nimport functools\nfrom types import MethodType\n\nimport numpy as np\n\nfrom matplotlib import _api, cbook\nfrom matplotlib.gridspec import SubplotSpec\n\nfrom .axes_divider import Size, SubplotDivider, Divider\nfrom .mpl_axes import Axes, SimpleAxisArtist\n\n\nclass CbarAxesBase:\n def __init__(self, *args, orientation, **kwargs):\n self.orientation = orientation\n super().__init__(*args, **kwargs)\n\n def colorbar(self, mappable, **kwargs):\n return self.get_figure(root=False).colorbar(\n mappable, cax=self, location=self.orientation, **kwargs)\n\n\n_cbaraxes_class_factory = cbook._make_class_factory(CbarAxesBase, "Cbar{}")\n\n\nclass Grid:\n """\n A grid of Axes.\n\n In Matplotlib, the Axes location (and size) is specified in normalized\n figure coordinates. This may not be ideal for images that needs to be\n displayed with a given aspect ratio; for example, it is difficult to\n display multiple images of a same size with some fixed padding between\n them. AxesGrid can be used in such case.\n\n Attributes\n ----------\n axes_all : list of Axes\n A flat list of Axes. Note that you can also access this directly\n from the grid. The following is equivalent ::\n\n grid[i] == grid.axes_all[i]\n len(grid) == len(grid.axes_all)\n\n axes_column : list of list of Axes\n A 2D list of Axes where the first index is the column. This results\n in the usage pattern ``grid.axes_column[col][row]``.\n axes_row : list of list of Axes\n A 2D list of Axes where the first index is the row. This results\n in the usage pattern ``grid.axes_row[row][col]``.\n axes_llc : Axes\n The Axes in the lower left corner.\n ngrids : int\n Number of Axes in the grid.\n """\n\n _defaultAxesClass = Axes\n\n def __init__(self, fig,\n rect,\n nrows_ncols,\n ngrids=None,\n direction="row",\n axes_pad=0.02,\n *,\n share_all=False,\n share_x=True,\n share_y=True,\n label_mode="L",\n axes_class=None,\n aspect=False,\n ):\n """\n Parameters\n ----------\n fig : `.Figure`\n The parent figure.\n rect : (float, float, float, float), (int, int, int), int, or \\n `~.SubplotSpec`\n The axes position, as a ``(left, bottom, width, height)`` tuple,\n as a three-digit subplot position code (e.g., ``(1, 2, 1)`` or\n ``121``), or as a `~.SubplotSpec`.\n nrows_ncols : (int, int)\n Number of rows and columns in the grid.\n ngrids : int or None, default: None\n If not None, only the first *ngrids* axes in the grid are created.\n direction : {"row", "column"}, default: "row"\n Whether axes are created in row-major ("row by row") or\n column-major order ("column by column"). This also affects the\n order in which axes are accessed using indexing (``grid[index]``).\n axes_pad : float or (float, float), default: 0.02\n Padding or (horizontal padding, vertical padding) between axes, in\n inches.\n share_all : bool, default: False\n Whether all axes share their x- and y-axis. Overrides *share_x*\n and *share_y*.\n share_x : bool, default: True\n Whether all axes of a column share their x-axis.\n share_y : bool, default: True\n Whether all axes of a row share their y-axis.\n label_mode : {"L", "1", "all", "keep"}, default: "L"\n Determines which axes will get tick labels:\n\n - "L": All axes on the left column get vertical tick labels;\n all axes on the bottom row get horizontal tick labels.\n - "1": Only the bottom left axes is labelled.\n - "all": All axes are labelled.\n - "keep": Do not do anything.\n\n axes_class : subclass of `matplotlib.axes.Axes`, default: `.mpl_axes.Axes`\n The type of Axes to create.\n aspect : bool, default: False\n Whether the axes aspect ratio follows the aspect ratio of the data\n limits.\n """\n self._nrows, self._ncols = nrows_ncols\n\n if ngrids is None:\n ngrids = self._nrows * self._ncols\n else:\n if not 0 < ngrids <= self._nrows * self._ncols:\n raise ValueError(\n "ngrids must be positive and not larger than nrows*ncols")\n\n self.ngrids = ngrids\n\n self._horiz_pad_size, self._vert_pad_size = map(\n Size.Fixed, np.broadcast_to(axes_pad, 2))\n\n _api.check_in_list(["column", "row"], direction=direction)\n self._direction = direction\n\n if axes_class is None:\n axes_class = self._defaultAxesClass\n elif isinstance(axes_class, (list, tuple)):\n cls, kwargs = axes_class\n axes_class = functools.partial(cls, **kwargs)\n\n kw = dict(horizontal=[], vertical=[], aspect=aspect)\n if isinstance(rect, (Number, SubplotSpec)):\n self._divider = SubplotDivider(fig, rect, **kw)\n elif len(rect) == 3:\n self._divider = SubplotDivider(fig, *rect, **kw)\n elif len(rect) == 4:\n self._divider = Divider(fig, rect, **kw)\n else:\n raise TypeError("Incorrect rect format")\n\n rect = self._divider.get_position()\n\n axes_array = np.full((self._nrows, self._ncols), None, dtype=object)\n for i in range(self.ngrids):\n col, row = self._get_col_row(i)\n if share_all:\n sharex = sharey = axes_array[0, 0]\n else:\n sharex = axes_array[0, col] if share_x else None\n sharey = axes_array[row, 0] if share_y else None\n axes_array[row, col] = axes_class(\n fig, rect, sharex=sharex, sharey=sharey)\n self.axes_all = axes_array.ravel(\n order="C" if self._direction == "row" else "F").tolist()\n self.axes_column = axes_array.T.tolist()\n self.axes_row = axes_array.tolist()\n self.axes_llc = self.axes_column[0][-1]\n\n self._init_locators()\n\n for ax in self.axes_all:\n fig.add_axes(ax)\n\n self.set_label_mode(label_mode)\n\n def _init_locators(self):\n self._divider.set_horizontal(\n [Size.Scaled(1), self._horiz_pad_size] * (self._ncols-1) + [Size.Scaled(1)])\n self._divider.set_vertical(\n [Size.Scaled(1), self._vert_pad_size] * (self._nrows-1) + [Size.Scaled(1)])\n for i in range(self.ngrids):\n col, row = self._get_col_row(i)\n self.axes_all[i].set_axes_locator(\n self._divider.new_locator(nx=2 * col, ny=2 * (self._nrows - 1 - row)))\n\n def _get_col_row(self, n):\n if self._direction == "column":\n col, row = divmod(n, self._nrows)\n else:\n row, col = divmod(n, self._ncols)\n\n return col, row\n\n # Good to propagate __len__ if we have __getitem__\n def __len__(self):\n return len(self.axes_all)\n\n def __getitem__(self, i):\n return self.axes_all[i]\n\n def get_geometry(self):\n """\n Return the number of rows and columns of the grid as (nrows, ncols).\n """\n return self._nrows, self._ncols\n\n def set_axes_pad(self, axes_pad):\n """\n Set the padding between the axes.\n\n Parameters\n ----------\n axes_pad : (float, float)\n The padding (horizontal pad, vertical pad) in inches.\n """\n self._horiz_pad_size.fixed_size = axes_pad[0]\n self._vert_pad_size.fixed_size = axes_pad[1]\n\n def get_axes_pad(self):\n """\n Return the axes padding.\n\n Returns\n -------\n hpad, vpad\n Padding (horizontal pad, vertical pad) in inches.\n """\n return (self._horiz_pad_size.fixed_size,\n self._vert_pad_size.fixed_size)\n\n def set_aspect(self, aspect):\n """Set the aspect of the SubplotDivider."""\n self._divider.set_aspect(aspect)\n\n def get_aspect(self):\n """Return the aspect of the SubplotDivider."""\n return self._divider.get_aspect()\n\n def set_label_mode(self, mode):\n """\n Define which axes have tick labels.\n\n Parameters\n ----------\n mode : {"L", "1", "all", "keep"}\n The label mode:\n\n - "L": All axes on the left column get vertical tick labels;\n all axes on the bottom row get horizontal tick labels.\n - "1": Only the bottom left axes is labelled.\n - "all": All axes are labelled.\n - "keep": Do not do anything.\n """\n _api.check_in_list(["all", "L", "1", "keep"], mode=mode)\n is_last_row, is_first_col = (\n np.mgrid[:self._nrows, :self._ncols] == [[[self._nrows - 1]], [[0]]])\n if mode == "all":\n bottom = left = np.full((self._nrows, self._ncols), True)\n elif mode == "L":\n bottom = is_last_row\n left = is_first_col\n elif mode == "1":\n bottom = left = is_last_row & is_first_col\n else:\n return\n for i in range(self._nrows):\n for j in range(self._ncols):\n ax = self.axes_row[i][j]\n if isinstance(ax.axis, MethodType):\n bottom_axis = SimpleAxisArtist(ax.xaxis, 1, ax.spines["bottom"])\n left_axis = SimpleAxisArtist(ax.yaxis, 1, ax.spines["left"])\n else:\n bottom_axis = ax.axis["bottom"]\n left_axis = ax.axis["left"]\n bottom_axis.toggle(ticklabels=bottom[i, j], label=bottom[i, j])\n left_axis.toggle(ticklabels=left[i, j], label=left[i, j])\n\n def get_divider(self):\n return self._divider\n\n def set_axes_locator(self, locator):\n self._divider.set_locator(locator)\n\n def get_axes_locator(self):\n return self._divider.get_locator()\n\n\nclass ImageGrid(Grid):\n """\n A grid of Axes for Image display.\n\n This class is a specialization of `~.axes_grid1.axes_grid.Grid` for displaying a\n grid of images. In particular, it forces all axes in a column to share their x-axis\n and all axes in a row to share their y-axis. It further provides helpers to add\n colorbars to some or all axes.\n """\n\n def __init__(self, fig,\n rect,\n nrows_ncols,\n ngrids=None,\n direction="row",\n axes_pad=0.02,\n *,\n share_all=False,\n aspect=True,\n label_mode="L",\n cbar_mode=None,\n cbar_location="right",\n cbar_pad=None,\n cbar_size="5%",\n cbar_set_cax=True,\n axes_class=None,\n ):\n """\n Parameters\n ----------\n fig : `.Figure`\n The parent figure.\n rect : (float, float, float, float) or int\n The axes position, as a ``(left, bottom, width, height)`` tuple or\n as a three-digit subplot position code (e.g., "121").\n nrows_ncols : (int, int)\n Number of rows and columns in the grid.\n ngrids : int or None, default: None\n If not None, only the first *ngrids* axes in the grid are created.\n direction : {"row", "column"}, default: "row"\n Whether axes are created in row-major ("row by row") or\n column-major order ("column by column"). This also affects the\n order in which axes are accessed using indexing (``grid[index]``).\n axes_pad : float or (float, float), default: 0.02in\n Padding or (horizontal padding, vertical padding) between axes, in\n inches.\n share_all : bool, default: False\n Whether all axes share their x- and y-axis. Note that in any case,\n all axes in a column share their x-axis and all axes in a row share\n their y-axis.\n aspect : bool, default: True\n Whether the axes aspect ratio follows the aspect ratio of the data\n limits.\n label_mode : {"L", "1", "all"}, default: "L"\n Determines which axes will get tick labels:\n\n - "L": All axes on the left column get vertical tick labels;\n all axes on the bottom row get horizontal tick labels.\n - "1": Only the bottom left axes is labelled.\n - "all": all axes are labelled.\n\n cbar_mode : {"each", "single", "edge", None}, default: None\n Whether to create a colorbar for "each" axes, a "single" colorbar\n for the entire grid, colorbars only for axes on the "edge"\n determined by *cbar_location*, or no colorbars. The colorbars are\n stored in the :attr:`cbar_axes` attribute.\n cbar_location : {"left", "right", "bottom", "top"}, default: "right"\n cbar_pad : float, default: None\n Padding between the image axes and the colorbar axes.\n\n .. versionchanged:: 3.10\n ``cbar_mode="single"`` no longer adds *axes_pad* between the axes\n and the colorbar if the *cbar_location* is "left" or "bottom".\n\n cbar_size : size specification (see `.Size.from_any`), default: "5%"\n Colorbar size.\n cbar_set_cax : bool, default: True\n If True, each axes in the grid has a *cax* attribute that is bound\n to associated *cbar_axes*.\n axes_class : subclass of `matplotlib.axes.Axes`, default: None\n """\n _api.check_in_list(["each", "single", "edge", None],\n cbar_mode=cbar_mode)\n _api.check_in_list(["left", "right", "bottom", "top"],\n cbar_location=cbar_location)\n self._colorbar_mode = cbar_mode\n self._colorbar_location = cbar_location\n self._colorbar_pad = cbar_pad\n self._colorbar_size = cbar_size\n # The colorbar axes are created in _init_locators().\n\n super().__init__(\n fig, rect, nrows_ncols, ngrids,\n direction=direction, axes_pad=axes_pad,\n share_all=share_all, share_x=True, share_y=True, aspect=aspect,\n label_mode=label_mode, axes_class=axes_class)\n\n for ax in self.cbar_axes:\n fig.add_axes(ax)\n\n if cbar_set_cax:\n if self._colorbar_mode == "single":\n for ax in self.axes_all:\n ax.cax = self.cbar_axes[0]\n elif self._colorbar_mode == "edge":\n for index, ax in enumerate(self.axes_all):\n col, row = self._get_col_row(index)\n if self._colorbar_location in ("left", "right"):\n ax.cax = self.cbar_axes[row]\n else:\n ax.cax = self.cbar_axes[col]\n else:\n for ax, cax in zip(self.axes_all, self.cbar_axes):\n ax.cax = cax\n\n def _init_locators(self):\n # Slightly abusing this method to inject colorbar creation into init.\n\n if self._colorbar_pad is None:\n # horizontal or vertical arrangement?\n if self._colorbar_location in ("left", "right"):\n self._colorbar_pad = self._horiz_pad_size.fixed_size\n else:\n self._colorbar_pad = self._vert_pad_size.fixed_size\n self.cbar_axes = [\n _cbaraxes_class_factory(self._defaultAxesClass)(\n self.axes_all[0].get_figure(root=False), self._divider.get_position(),\n orientation=self._colorbar_location)\n for _ in range(self.ngrids)]\n\n cb_mode = self._colorbar_mode\n cb_location = self._colorbar_location\n\n h = []\n v = []\n\n h_ax_pos = []\n h_cb_pos = []\n if cb_mode == "single" and cb_location in ("left", "bottom"):\n if cb_location == "left":\n sz = self._nrows * Size.AxesX(self.axes_llc)\n h.append(Size.from_any(self._colorbar_size, sz))\n h.append(Size.from_any(self._colorbar_pad, sz))\n locator = self._divider.new_locator(nx=0, ny=0, ny1=-1)\n elif cb_location == "bottom":\n sz = self._ncols * Size.AxesY(self.axes_llc)\n v.append(Size.from_any(self._colorbar_size, sz))\n v.append(Size.from_any(self._colorbar_pad, sz))\n locator = self._divider.new_locator(nx=0, nx1=-1, ny=0)\n for i in range(self.ngrids):\n self.cbar_axes[i].set_visible(False)\n self.cbar_axes[0].set_axes_locator(locator)\n self.cbar_axes[0].set_visible(True)\n\n for col, ax in enumerate(self.axes_row[0]):\n if col != 0:\n h.append(self._horiz_pad_size)\n\n if ax:\n sz = Size.AxesX(ax, aspect="axes", ref_ax=self.axes_all[0])\n else:\n sz = Size.AxesX(self.axes_all[0],\n aspect="axes", ref_ax=self.axes_all[0])\n\n if (cb_location == "left"\n and (cb_mode == "each"\n or (cb_mode == "edge" and col == 0))):\n h_cb_pos.append(len(h))\n h.append(Size.from_any(self._colorbar_size, sz))\n h.append(Size.from_any(self._colorbar_pad, sz))\n\n h_ax_pos.append(len(h))\n h.append(sz)\n\n if (cb_location == "right"\n and (cb_mode == "each"\n or (cb_mode == "edge" and col == self._ncols - 1))):\n h.append(Size.from_any(self._colorbar_pad, sz))\n h_cb_pos.append(len(h))\n h.append(Size.from_any(self._colorbar_size, sz))\n\n v_ax_pos = []\n v_cb_pos = []\n for row, ax in enumerate(self.axes_column[0][::-1]):\n if row != 0:\n v.append(self._vert_pad_size)\n\n if ax:\n sz = Size.AxesY(ax, aspect="axes", ref_ax=self.axes_all[0])\n else:\n sz = Size.AxesY(self.axes_all[0],\n aspect="axes", ref_ax=self.axes_all[0])\n\n if (cb_location == "bottom"\n and (cb_mode == "each"\n or (cb_mode == "edge" and row == 0))):\n v_cb_pos.append(len(v))\n v.append(Size.from_any(self._colorbar_size, sz))\n v.append(Size.from_any(self._colorbar_pad, sz))\n\n v_ax_pos.append(len(v))\n v.append(sz)\n\n if (cb_location == "top"\n and (cb_mode == "each"\n or (cb_mode == "edge" and row == self._nrows - 1))):\n v.append(Size.from_any(self._colorbar_pad, sz))\n v_cb_pos.append(len(v))\n v.append(Size.from_any(self._colorbar_size, sz))\n\n for i in range(self.ngrids):\n col, row = self._get_col_row(i)\n locator = self._divider.new_locator(nx=h_ax_pos[col],\n ny=v_ax_pos[self._nrows-1-row])\n self.axes_all[i].set_axes_locator(locator)\n\n if cb_mode == "each":\n if cb_location in ("right", "left"):\n locator = self._divider.new_locator(\n nx=h_cb_pos[col], ny=v_ax_pos[self._nrows - 1 - row])\n\n elif cb_location in ("top", "bottom"):\n locator = self._divider.new_locator(\n nx=h_ax_pos[col], ny=v_cb_pos[self._nrows - 1 - row])\n\n self.cbar_axes[i].set_axes_locator(locator)\n elif cb_mode == "edge":\n if (cb_location == "left" and col == 0\n or cb_location == "right" and col == self._ncols - 1):\n locator = self._divider.new_locator(\n nx=h_cb_pos[0], ny=v_ax_pos[self._nrows - 1 - row])\n self.cbar_axes[row].set_axes_locator(locator)\n elif (cb_location == "bottom" and row == self._nrows - 1\n or cb_location == "top" and row == 0):\n locator = self._divider.new_locator(nx=h_ax_pos[col],\n ny=v_cb_pos[0])\n self.cbar_axes[col].set_axes_locator(locator)\n\n if cb_mode == "single":\n if cb_location == "right":\n sz = self._nrows * Size.AxesX(self.axes_llc)\n h.append(Size.from_any(self._colorbar_pad, sz))\n h.append(Size.from_any(self._colorbar_size, sz))\n locator = self._divider.new_locator(nx=-2, ny=0, ny1=-1)\n elif cb_location == "top":\n sz = self._ncols * Size.AxesY(self.axes_llc)\n v.append(Size.from_any(self._colorbar_pad, sz))\n v.append(Size.from_any(self._colorbar_size, sz))\n locator = self._divider.new_locator(nx=0, nx1=-1, ny=-2)\n if cb_location in ("right", "top"):\n for i in range(self.ngrids):\n self.cbar_axes[i].set_visible(False)\n self.cbar_axes[0].set_axes_locator(locator)\n self.cbar_axes[0].set_visible(True)\n elif cb_mode == "each":\n for i in range(self.ngrids):\n self.cbar_axes[i].set_visible(True)\n elif cb_mode == "edge":\n if cb_location in ("right", "left"):\n count = self._nrows\n else:\n count = self._ncols\n for i in range(count):\n self.cbar_axes[i].set_visible(True)\n for j in range(i + 1, self.ngrids):\n self.cbar_axes[j].set_visible(False)\n else:\n for i in range(self.ngrids):\n self.cbar_axes[i].set_visible(False)\n self.cbar_axes[i].set_position([1., 1., 0.001, 0.001],\n which="active")\n\n self._divider.set_horizontal(h)\n self._divider.set_vertical(v)\n\n\nAxesGrid = ImageGrid\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\axes_grid.py | axes_grid.py | Python | 22,344 | 0.95 | 0.147425 | 0.012448 | awesome-app | 764 | 2025-05-01T21:42:28.800935 | GPL-3.0 | false | 47917c7a21671789217be63d09ad3c3a |
from types import MethodType\n\nimport numpy as np\n\nfrom .axes_divider import make_axes_locatable, Size\nfrom .mpl_axes import Axes, SimpleAxisArtist\n\n\ndef make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs):\n """\n Parameters\n ----------\n ax : `~matplotlib.axes.Axes`\n Axes instance to create the RGB Axes in.\n pad : float, optional\n Fraction of the Axes height to pad.\n axes_class : `matplotlib.axes.Axes` or None, optional\n Axes class to use for the R, G, and B Axes. If None, use\n the same class as *ax*.\n **kwargs\n Forwarded to *axes_class* init for the R, G, and B Axes.\n """\n\n divider = make_axes_locatable(ax)\n\n pad_size = pad * Size.AxesY(ax)\n\n xsize = ((1-2*pad)/3) * Size.AxesX(ax)\n ysize = ((1-2*pad)/3) * Size.AxesY(ax)\n\n divider.set_horizontal([Size.AxesX(ax), pad_size, xsize])\n divider.set_vertical([ysize, pad_size, ysize, pad_size, ysize])\n\n ax.set_axes_locator(divider.new_locator(0, 0, ny1=-1))\n\n ax_rgb = []\n if axes_class is None:\n axes_class = type(ax)\n\n for ny in [4, 2, 0]:\n ax1 = axes_class(ax.get_figure(), ax.get_position(original=True),\n sharex=ax, sharey=ax, **kwargs)\n locator = divider.new_locator(nx=2, ny=ny)\n ax1.set_axes_locator(locator)\n for t in ax1.yaxis.get_ticklabels() + ax1.xaxis.get_ticklabels():\n t.set_visible(False)\n try:\n for axis in ax1.axis.values():\n axis.major_ticklabels.set_visible(False)\n except AttributeError:\n pass\n\n ax_rgb.append(ax1)\n\n fig = ax.get_figure()\n for ax1 in ax_rgb:\n fig.add_axes(ax1)\n\n return ax_rgb\n\n\nclass RGBAxes:\n """\n 4-panel `~.Axes.imshow` (RGB, R, G, B).\n\n Layout::\n\n ┌───────────────┬─────┐\n │ │ R │\n │ ├─────┤\n │ RGB │ G │\n │ ├─────┤\n │ │ B │\n └───────────────┴─────┘\n\n Subclasses can override the ``_defaultAxesClass`` attribute.\n By default RGBAxes uses `.mpl_axes.Axes`.\n\n Attributes\n ----------\n RGB : ``_defaultAxesClass``\n The Axes object for the three-channel `~.Axes.imshow`.\n R : ``_defaultAxesClass``\n The Axes object for the red channel `~.Axes.imshow`.\n G : ``_defaultAxesClass``\n The Axes object for the green channel `~.Axes.imshow`.\n B : ``_defaultAxesClass``\n The Axes object for the blue channel `~.Axes.imshow`.\n """\n\n _defaultAxesClass = Axes\n\n def __init__(self, *args, pad=0, **kwargs):\n """\n Parameters\n ----------\n pad : float, default: 0\n Fraction of the Axes height to put as padding.\n axes_class : `~matplotlib.axes.Axes`\n Axes class to use. If not provided, ``_defaultAxesClass`` is used.\n *args\n Forwarded to *axes_class* init for the RGB Axes\n **kwargs\n Forwarded to *axes_class* init for the RGB, R, G, and B Axes\n """\n axes_class = kwargs.pop("axes_class", self._defaultAxesClass)\n self.RGB = ax = axes_class(*args, **kwargs)\n ax.get_figure().add_axes(ax)\n self.R, self.G, self.B = make_rgb_axes(\n ax, pad=pad, axes_class=axes_class, **kwargs)\n # Set the line color and ticks for the axes.\n for ax1 in [self.RGB, self.R, self.G, self.B]:\n if isinstance(ax1.axis, MethodType):\n ad = Axes.AxisDict(self)\n ad.update(\n bottom=SimpleAxisArtist(ax1.xaxis, 1, ax1.spines["bottom"]),\n top=SimpleAxisArtist(ax1.xaxis, 2, ax1.spines["top"]),\n left=SimpleAxisArtist(ax1.yaxis, 1, ax1.spines["left"]),\n right=SimpleAxisArtist(ax1.yaxis, 2, ax1.spines["right"]))\n else:\n ad = ax1.axis\n ad[:].line.set_color("w")\n ad[:].major_ticks.set_markeredgecolor("w")\n\n def imshow_rgb(self, r, g, b, **kwargs):\n """\n Create the four images {rgb, r, g, b}.\n\n Parameters\n ----------\n r, g, b : array-like\n The red, green, and blue arrays.\n **kwargs\n Forwarded to `~.Axes.imshow` calls for the four images.\n\n Returns\n -------\n rgb : `~matplotlib.image.AxesImage`\n r : `~matplotlib.image.AxesImage`\n g : `~matplotlib.image.AxesImage`\n b : `~matplotlib.image.AxesImage`\n """\n if not (r.shape == g.shape == b.shape):\n raise ValueError(\n f'Input shapes ({r.shape}, {g.shape}, {b.shape}) do not match')\n RGB = np.dstack([r, g, b])\n R = np.zeros_like(RGB)\n R[:, :, 0] = r\n G = np.zeros_like(RGB)\n G[:, :, 1] = g\n B = np.zeros_like(RGB)\n B[:, :, 2] = b\n im_rgb = self.RGB.imshow(RGB, **kwargs)\n im_r = self.R.imshow(R, **kwargs)\n im_g = self.G.imshow(G, **kwargs)\n im_b = self.B.imshow(B, **kwargs)\n return im_rgb, im_r, im_g, im_b\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\axes_rgb.py | axes_rgb.py | Python | 5,227 | 0.95 | 0.165605 | 0.037879 | vue-tools | 938 | 2025-01-17T22:11:32.001915 | Apache-2.0 | false | 38cbfbbc8b7ee68841ae72a65b0ffac1 |
"""\nProvides classes of simple units that will be used with `.AxesDivider`\nclass (or others) to determine the size of each Axes. The unit\nclasses define `get_size` method that returns a tuple of two floats,\nmeaning relative and absolute sizes, respectively.\n\nNote that this class is nothing more than a simple tuple of two\nfloats. Take a look at the Divider class to see how these two\nvalues are used.\n\nOnce created, the unit classes can be modified by simple arithmetic\noperations: addition /subtraction with another unit type or a real number and scaling\n(multiplication or division) by a real number.\n"""\n\nfrom numbers import Real\n\nfrom matplotlib import _api\nfrom matplotlib.axes import Axes\n\n\nclass _Base:\n def __rmul__(self, other):\n return self * other\n\n def __mul__(self, other):\n if not isinstance(other, Real):\n return NotImplemented\n return Fraction(other, self)\n\n def __div__(self, other):\n return (1 / other) * self\n\n def __add__(self, other):\n if isinstance(other, _Base):\n return Add(self, other)\n else:\n return Add(self, Fixed(other))\n\n def __neg__(self):\n return -1 * self\n\n def __radd__(self, other):\n # other cannot be a _Base instance, because A + B would trigger\n # A.__add__(B) first.\n return Add(self, Fixed(other))\n\n def __sub__(self, other):\n return self + (-other)\n\n def get_size(self, renderer):\n """\n Return two-float tuple with relative and absolute sizes.\n """\n raise NotImplementedError("Subclasses must implement")\n\n\nclass Add(_Base):\n """\n Sum of two sizes.\n """\n\n def __init__(self, a, b):\n self._a = a\n self._b = b\n\n def get_size(self, renderer):\n a_rel_size, a_abs_size = self._a.get_size(renderer)\n b_rel_size, b_abs_size = self._b.get_size(renderer)\n return a_rel_size + b_rel_size, a_abs_size + b_abs_size\n\n\nclass Fixed(_Base):\n """\n Simple fixed size with absolute part = *fixed_size* and relative part = 0.\n """\n\n def __init__(self, fixed_size):\n _api.check_isinstance(Real, fixed_size=fixed_size)\n self.fixed_size = fixed_size\n\n def get_size(self, renderer):\n rel_size = 0.\n abs_size = self.fixed_size\n return rel_size, abs_size\n\n\nclass Scaled(_Base):\n """\n Simple scaled(?) size with absolute part = 0 and\n relative part = *scalable_size*.\n """\n\n def __init__(self, scalable_size):\n self._scalable_size = scalable_size\n\n def get_size(self, renderer):\n rel_size = self._scalable_size\n abs_size = 0.\n return rel_size, abs_size\n\nScalable = Scaled\n\n\ndef _get_axes_aspect(ax):\n aspect = ax.get_aspect()\n if aspect == "auto":\n aspect = 1.\n return aspect\n\n\nclass AxesX(_Base):\n """\n Scaled size whose relative part corresponds to the data width\n of the *axes* multiplied by the *aspect*.\n """\n\n def __init__(self, axes, aspect=1., ref_ax=None):\n self._axes = axes\n self._aspect = aspect\n if aspect == "axes" and ref_ax is None:\n raise ValueError("ref_ax must be set when aspect='axes'")\n self._ref_ax = ref_ax\n\n def get_size(self, renderer):\n l1, l2 = self._axes.get_xlim()\n if self._aspect == "axes":\n ref_aspect = _get_axes_aspect(self._ref_ax)\n aspect = ref_aspect / _get_axes_aspect(self._axes)\n else:\n aspect = self._aspect\n\n rel_size = abs(l2-l1)*aspect\n abs_size = 0.\n return rel_size, abs_size\n\n\nclass AxesY(_Base):\n """\n Scaled size whose relative part corresponds to the data height\n of the *axes* multiplied by the *aspect*.\n """\n\n def __init__(self, axes, aspect=1., ref_ax=None):\n self._axes = axes\n self._aspect = aspect\n if aspect == "axes" and ref_ax is None:\n raise ValueError("ref_ax must be set when aspect='axes'")\n self._ref_ax = ref_ax\n\n def get_size(self, renderer):\n l1, l2 = self._axes.get_ylim()\n\n if self._aspect == "axes":\n ref_aspect = _get_axes_aspect(self._ref_ax)\n aspect = _get_axes_aspect(self._axes)\n else:\n aspect = self._aspect\n\n rel_size = abs(l2-l1)*aspect\n abs_size = 0.\n return rel_size, abs_size\n\n\nclass MaxExtent(_Base):\n """\n Size whose absolute part is either the largest width or the largest height\n of the given *artist_list*.\n """\n\n def __init__(self, artist_list, w_or_h):\n self._artist_list = artist_list\n _api.check_in_list(["width", "height"], w_or_h=w_or_h)\n self._w_or_h = w_or_h\n\n def add_artist(self, a):\n self._artist_list.append(a)\n\n def get_size(self, renderer):\n rel_size = 0.\n extent_list = [\n getattr(a.get_window_extent(renderer), self._w_or_h) / a.figure.dpi\n for a in self._artist_list]\n abs_size = max(extent_list, default=0)\n return rel_size, abs_size\n\n\nclass MaxWidth(MaxExtent):\n """\n Size whose absolute part is the largest width of the given *artist_list*.\n """\n\n def __init__(self, artist_list):\n super().__init__(artist_list, "width")\n\n\nclass MaxHeight(MaxExtent):\n """\n Size whose absolute part is the largest height of the given *artist_list*.\n """\n\n def __init__(self, artist_list):\n super().__init__(artist_list, "height")\n\n\nclass Fraction(_Base):\n """\n An instance whose size is a *fraction* of the *ref_size*.\n\n >>> s = Fraction(0.3, AxesX(ax))\n """\n\n def __init__(self, fraction, ref_size):\n _api.check_isinstance(Real, fraction=fraction)\n self._fraction_ref = ref_size\n self._fraction = fraction\n\n def get_size(self, renderer):\n if self._fraction_ref is None:\n return self._fraction, 0.\n else:\n r, a = self._fraction_ref.get_size(renderer)\n rel_size = r*self._fraction\n abs_size = a*self._fraction\n return rel_size, abs_size\n\n\ndef from_any(size, fraction_ref=None):\n """\n Create a Fixed unit when the first argument is a float, or a\n Fraction unit if that is a string that ends with %. The second\n argument is only meaningful when Fraction unit is created.\n\n >>> from mpl_toolkits.axes_grid1.axes_size import from_any\n >>> a = from_any(1.2) # => Fixed(1.2)\n >>> from_any("50%", a) # => Fraction(0.5, a)\n """\n if isinstance(size, Real):\n return Fixed(size)\n elif isinstance(size, str):\n if size[-1] == "%":\n return Fraction(float(size[:-1]) / 100, fraction_ref)\n raise ValueError("Unknown format")\n\n\nclass _AxesDecorationsSize(_Base):\n """\n Fixed size, corresponding to the size of decorations on a given Axes side.\n """\n\n _get_size_map = {\n "left": lambda tight_bb, axes_bb: axes_bb.xmin - tight_bb.xmin,\n "right": lambda tight_bb, axes_bb: tight_bb.xmax - axes_bb.xmax,\n "bottom": lambda tight_bb, axes_bb: axes_bb.ymin - tight_bb.ymin,\n "top": lambda tight_bb, axes_bb: tight_bb.ymax - axes_bb.ymax,\n }\n\n def __init__(self, ax, direction):\n _api.check_in_list(self._get_size_map, direction=direction)\n self._direction = direction\n self._ax_list = [ax] if isinstance(ax, Axes) else ax\n\n def get_size(self, renderer):\n sz = max([\n self._get_size_map[self._direction](\n ax.get_tightbbox(renderer, call_axes_locator=False), ax.bbox)\n for ax in self._ax_list])\n dpi = renderer.points_to_pixels(72)\n abs_size = sz / dpi\n rel_size = 0\n return rel_size, abs_size\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\axes_size.py | axes_size.py | Python | 7,713 | 0.95 | 0.210332 | 0.009615 | vue-tools | 883 | 2025-02-11T13:09:29.630274 | MIT | false | 93428a31d5fd5683cc5f18b8a1ae674c |
"""\nA collection of functions and objects for creating or placing inset axes.\n"""\n\nfrom matplotlib import _api, _docstring\nfrom matplotlib.offsetbox import AnchoredOffsetbox\nfrom matplotlib.patches import Patch, Rectangle\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import Bbox\nfrom matplotlib.transforms import IdentityTransform, TransformedBbox\n\nfrom . import axes_size as Size\nfrom .parasite_axes import HostAxes\n\n\nclass AnchoredLocatorBase(AnchoredOffsetbox):\n def __init__(self, bbox_to_anchor, offsetbox, loc,\n borderpad=0.5, bbox_transform=None):\n super().__init__(\n loc, pad=0., child=None, borderpad=borderpad,\n bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform\n )\n\n def draw(self, renderer):\n raise RuntimeError("No draw method should be called")\n\n def __call__(self, ax, renderer):\n fig = ax.get_figure(root=False)\n if renderer is None:\n renderer = fig._get_renderer()\n self.axes = ax\n bbox = self.get_window_extent(renderer)\n px, py = self.get_offset(bbox.width, bbox.height, 0, 0, renderer)\n bbox_canvas = Bbox.from_bounds(px, py, bbox.width, bbox.height)\n tr = fig.transSubfigure.inverted()\n return TransformedBbox(bbox_canvas, tr)\n\n\nclass AnchoredSizeLocator(AnchoredLocatorBase):\n def __init__(self, bbox_to_anchor, x_size, y_size, loc,\n borderpad=0.5, bbox_transform=None):\n super().__init__(\n bbox_to_anchor, None, loc,\n borderpad=borderpad, bbox_transform=bbox_transform\n )\n\n self.x_size = Size.from_any(x_size)\n self.y_size = Size.from_any(y_size)\n\n def get_bbox(self, renderer):\n bbox = self.get_bbox_to_anchor()\n dpi = renderer.points_to_pixels(72.)\n\n r, a = self.x_size.get_size(renderer)\n width = bbox.width * r + a * dpi\n r, a = self.y_size.get_size(renderer)\n height = bbox.height * r + a * dpi\n\n fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())\n pad = self.pad * fontsize\n\n return Bbox.from_bounds(0, 0, width, height).padded(pad)\n\n\nclass AnchoredZoomLocator(AnchoredLocatorBase):\n def __init__(self, parent_axes, zoom, loc,\n borderpad=0.5,\n bbox_to_anchor=None,\n bbox_transform=None):\n self.parent_axes = parent_axes\n self.zoom = zoom\n if bbox_to_anchor is None:\n bbox_to_anchor = parent_axes.bbox\n super().__init__(\n bbox_to_anchor, None, loc, borderpad=borderpad,\n bbox_transform=bbox_transform)\n\n def get_bbox(self, renderer):\n bb = self.parent_axes.transData.transform_bbox(self.axes.viewLim)\n fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())\n pad = self.pad * fontsize\n return (\n Bbox.from_bounds(\n 0, 0, abs(bb.width * self.zoom), abs(bb.height * self.zoom))\n .padded(pad))\n\n\nclass BboxPatch(Patch):\n @_docstring.interpd\n def __init__(self, bbox, **kwargs):\n """\n Patch showing the shape bounded by a Bbox.\n\n Parameters\n ----------\n bbox : `~matplotlib.transforms.Bbox`\n Bbox to use for the extents of this patch.\n\n **kwargs\n Patch properties. Valid arguments include:\n\n %(Patch:kwdoc)s\n """\n if "transform" in kwargs:\n raise ValueError("transform should not be set")\n\n kwargs["transform"] = IdentityTransform()\n super().__init__(**kwargs)\n self.bbox = bbox\n\n def get_path(self):\n # docstring inherited\n x0, y0, x1, y1 = self.bbox.extents\n return Path._create_closed([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])\n\n\nclass BboxConnector(Patch):\n @staticmethod\n def get_bbox_edge_pos(bbox, loc):\n """\n Return the ``(x, y)`` coordinates of corner *loc* of *bbox*; parameters\n behave as documented for the `.BboxConnector` constructor.\n """\n x0, y0, x1, y1 = bbox.extents\n if loc == 1:\n return x1, y1\n elif loc == 2:\n return x0, y1\n elif loc == 3:\n return x0, y0\n elif loc == 4:\n return x1, y0\n\n @staticmethod\n def connect_bbox(bbox1, bbox2, loc1, loc2=None):\n """\n Construct a `.Path` connecting corner *loc1* of *bbox1* to corner\n *loc2* of *bbox2*, where parameters behave as documented as for the\n `.BboxConnector` constructor.\n """\n if isinstance(bbox1, Rectangle):\n bbox1 = TransformedBbox(Bbox.unit(), bbox1.get_transform())\n if isinstance(bbox2, Rectangle):\n bbox2 = TransformedBbox(Bbox.unit(), bbox2.get_transform())\n if loc2 is None:\n loc2 = loc1\n x1, y1 = BboxConnector.get_bbox_edge_pos(bbox1, loc1)\n x2, y2 = BboxConnector.get_bbox_edge_pos(bbox2, loc2)\n return Path([[x1, y1], [x2, y2]])\n\n @_docstring.interpd\n def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs):\n """\n Connect two bboxes with a straight line.\n\n Parameters\n ----------\n bbox1, bbox2 : `~matplotlib.transforms.Bbox`\n Bounding boxes to connect.\n\n loc1, loc2 : {1, 2, 3, 4}\n Corner of *bbox1* and *bbox2* to draw the line. Valid values are::\n\n 'upper right' : 1,\n 'upper left' : 2,\n 'lower left' : 3,\n 'lower right' : 4\n\n *loc2* is optional and defaults to *loc1*.\n\n **kwargs\n Patch properties for the line drawn. Valid arguments include:\n\n %(Patch:kwdoc)s\n """\n if "transform" in kwargs:\n raise ValueError("transform should not be set")\n\n kwargs["transform"] = IdentityTransform()\n kwargs.setdefault(\n "fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs)))\n super().__init__(**kwargs)\n self.bbox1 = bbox1\n self.bbox2 = bbox2\n self.loc1 = loc1\n self.loc2 = loc2\n\n def get_path(self):\n # docstring inherited\n return self.connect_bbox(self.bbox1, self.bbox2,\n self.loc1, self.loc2)\n\n\nclass BboxConnectorPatch(BboxConnector):\n @_docstring.interpd\n def __init__(self, bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, **kwargs):\n """\n Connect two bboxes with a quadrilateral.\n\n The quadrilateral is specified by two lines that start and end at\n corners of the bboxes. The four sides of the quadrilateral are defined\n by the two lines given, the line between the two corners specified in\n *bbox1* and the line between the two corners specified in *bbox2*.\n\n Parameters\n ----------\n bbox1, bbox2 : `~matplotlib.transforms.Bbox`\n Bounding boxes to connect.\n\n loc1a, loc2a, loc1b, loc2b : {1, 2, 3, 4}\n The first line connects corners *loc1a* of *bbox1* and *loc2a* of\n *bbox2*; the second line connects corners *loc1b* of *bbox1* and\n *loc2b* of *bbox2*. Valid values are::\n\n 'upper right' : 1,\n 'upper left' : 2,\n 'lower left' : 3,\n 'lower right' : 4\n\n **kwargs\n Patch properties for the line drawn:\n\n %(Patch:kwdoc)s\n """\n if "transform" in kwargs:\n raise ValueError("transform should not be set")\n super().__init__(bbox1, bbox2, loc1a, loc2a, **kwargs)\n self.loc1b = loc1b\n self.loc2b = loc2b\n\n def get_path(self):\n # docstring inherited\n path1 = self.connect_bbox(self.bbox1, self.bbox2, self.loc1, self.loc2)\n path2 = self.connect_bbox(self.bbox2, self.bbox1,\n self.loc2b, self.loc1b)\n path_merged = [*path1.vertices, *path2.vertices, path1.vertices[0]]\n return Path(path_merged)\n\n\ndef _add_inset_axes(parent_axes, axes_class, axes_kwargs, axes_locator):\n """Helper function to add an inset axes and disable navigation in it."""\n if axes_class is None:\n axes_class = HostAxes\n if axes_kwargs is None:\n axes_kwargs = {}\n fig = parent_axes.get_figure(root=False)\n inset_axes = axes_class(\n fig, parent_axes.get_position(),\n **{"navigate": False, **axes_kwargs, "axes_locator": axes_locator})\n return fig.add_axes(inset_axes)\n\n\n@_docstring.interpd\ndef inset_axes(parent_axes, width, height, loc='upper right',\n bbox_to_anchor=None, bbox_transform=None,\n axes_class=None, axes_kwargs=None,\n borderpad=0.5):\n """\n Create an inset axes with a given width and height.\n\n Both sizes used can be specified either in inches or percentage.\n For example,::\n\n inset_axes(parent_axes, width='40%%', height='30%%', loc='lower left')\n\n creates in inset axes in the lower left corner of *parent_axes* which spans\n over 30%% in height and 40%% in width of the *parent_axes*. Since the usage\n of `.inset_axes` may become slightly tricky when exceeding such standard\n cases, it is recommended to read :doc:`the examples\n </gallery/axes_grid1/inset_locator_demo>`.\n\n Notes\n -----\n The meaning of *bbox_to_anchor* and *bbox_to_transform* is interpreted\n differently from that of legend. The value of bbox_to_anchor\n (or the return value of its get_points method; the default is\n *parent_axes.bbox*) is transformed by the bbox_transform (the default\n is Identity transform) and then interpreted as points in the pixel\n coordinate (which is dpi dependent).\n\n Thus, following three calls are identical and creates an inset axes\n with respect to the *parent_axes*::\n\n axins = inset_axes(parent_axes, "30%%", "40%%")\n axins = inset_axes(parent_axes, "30%%", "40%%",\n bbox_to_anchor=parent_axes.bbox)\n axins = inset_axes(parent_axes, "30%%", "40%%",\n bbox_to_anchor=(0, 0, 1, 1),\n bbox_transform=parent_axes.transAxes)\n\n Parameters\n ----------\n parent_axes : `matplotlib.axes.Axes`\n Axes to place the inset axes.\n\n width, height : float or str\n Size of the inset axes to create. If a float is provided, it is\n the size in inches, e.g. *width=1.3*. If a string is provided, it is\n the size in relative units, e.g. *width='40%%'*. By default, i.e. if\n neither *bbox_to_anchor* nor *bbox_transform* are specified, those\n are relative to the parent_axes. Otherwise, they are to be understood\n relative to the bounding box provided via *bbox_to_anchor*.\n\n loc : str, default: 'upper right'\n Location to place the inset axes. Valid locations are\n 'upper left', 'upper center', 'upper right',\n 'center left', 'center', 'center right',\n 'lower left', 'lower center', 'lower right'.\n For backward compatibility, numeric values are accepted as well.\n See the parameter *loc* of `.Legend` for details.\n\n bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional\n Bbox that the inset axes will be anchored to. If None,\n a tuple of (0, 0, 1, 1) is used if *bbox_transform* is set\n to *parent_axes.transAxes* or *parent_axes.figure.transFigure*.\n Otherwise, *parent_axes.bbox* is used. If a tuple, can be either\n [left, bottom, width, height], or [left, bottom].\n If the kwargs *width* and/or *height* are specified in relative units,\n the 2-tuple [left, bottom] cannot be used. Note that,\n unless *bbox_transform* is set, the units of the bounding box\n are interpreted in the pixel coordinate. When using *bbox_to_anchor*\n with tuple, it almost always makes sense to also specify\n a *bbox_transform*. This might often be the axes transform\n *parent_axes.transAxes*.\n\n bbox_transform : `~matplotlib.transforms.Transform`, optional\n Transformation for the bbox that contains the inset axes.\n If None, a `.transforms.IdentityTransform` is used. The value\n of *bbox_to_anchor* (or the return value of its get_points method)\n is transformed by the *bbox_transform* and then interpreted\n as points in the pixel coordinate (which is dpi dependent).\n You may provide *bbox_to_anchor* in some normalized coordinate,\n and give an appropriate transform (e.g., *parent_axes.transAxes*).\n\n axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`\n The type of the newly created inset axes.\n\n axes_kwargs : dict, optional\n Keyword arguments to pass to the constructor of the inset axes.\n Valid arguments include:\n\n %(Axes:kwdoc)s\n\n borderpad : float, default: 0.5\n Padding between inset axes and the bbox_to_anchor.\n The units are axes font size, i.e. for a default font size of 10 points\n *borderpad = 0.5* is equivalent to a padding of 5 points.\n\n Returns\n -------\n inset_axes : *axes_class*\n Inset axes object created.\n """\n\n if (bbox_transform in [parent_axes.transAxes,\n parent_axes.get_figure(root=False).transFigure]\n and bbox_to_anchor is None):\n _api.warn_external("Using the axes or figure transform requires a "\n "bounding box in the respective coordinates. "\n "Using bbox_to_anchor=(0, 0, 1, 1) now.")\n bbox_to_anchor = (0, 0, 1, 1)\n if bbox_to_anchor is None:\n bbox_to_anchor = parent_axes.bbox\n if (isinstance(bbox_to_anchor, tuple) and\n (isinstance(width, str) or isinstance(height, str))):\n if len(bbox_to_anchor) != 4:\n raise ValueError("Using relative units for width or height "\n "requires to provide a 4-tuple or a "\n "`Bbox` instance to `bbox_to_anchor.")\n return _add_inset_axes(\n parent_axes, axes_class, axes_kwargs,\n AnchoredSizeLocator(\n bbox_to_anchor, width, height, loc=loc,\n bbox_transform=bbox_transform, borderpad=borderpad))\n\n\n@_docstring.interpd\ndef zoomed_inset_axes(parent_axes, zoom, loc='upper right',\n bbox_to_anchor=None, bbox_transform=None,\n axes_class=None, axes_kwargs=None,\n borderpad=0.5):\n """\n Create an anchored inset axes by scaling a parent axes. For usage, also see\n :doc:`the examples </gallery/axes_grid1/inset_locator_demo2>`.\n\n Parameters\n ----------\n parent_axes : `~matplotlib.axes.Axes`\n Axes to place the inset axes.\n\n zoom : float\n Scaling factor of the data axes. *zoom* > 1 will enlarge the\n coordinates (i.e., "zoomed in"), while *zoom* < 1 will shrink the\n coordinates (i.e., "zoomed out").\n\n loc : str, default: 'upper right'\n Location to place the inset axes. Valid locations are\n 'upper left', 'upper center', 'upper right',\n 'center left', 'center', 'center right',\n 'lower left', 'lower center', 'lower right'.\n For backward compatibility, numeric values are accepted as well.\n See the parameter *loc* of `.Legend` for details.\n\n bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional\n Bbox that the inset axes will be anchored to. If None,\n *parent_axes.bbox* is used. If a tuple, can be either\n [left, bottom, width, height], or [left, bottom].\n If the kwargs *width* and/or *height* are specified in relative units,\n the 2-tuple [left, bottom] cannot be used. Note that\n the units of the bounding box are determined through the transform\n in use. When using *bbox_to_anchor* it almost always makes sense to\n also specify a *bbox_transform*. This might often be the axes transform\n *parent_axes.transAxes*.\n\n bbox_transform : `~matplotlib.transforms.Transform`, optional\n Transformation for the bbox that contains the inset axes.\n If None, a `.transforms.IdentityTransform` is used (i.e. pixel\n coordinates). This is useful when not providing any argument to\n *bbox_to_anchor*. When using *bbox_to_anchor* it almost always makes\n sense to also specify a *bbox_transform*. This might often be the\n axes transform *parent_axes.transAxes*. Inversely, when specifying\n the axes- or figure-transform here, be aware that not specifying\n *bbox_to_anchor* will use *parent_axes.bbox*, the units of which are\n in display (pixel) coordinates.\n\n axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`\n The type of the newly created inset axes.\n\n axes_kwargs : dict, optional\n Keyword arguments to pass to the constructor of the inset axes.\n Valid arguments include:\n\n %(Axes:kwdoc)s\n\n borderpad : float, default: 0.5\n Padding between inset axes and the bbox_to_anchor.\n The units are axes font size, i.e. for a default font size of 10 points\n *borderpad = 0.5* is equivalent to a padding of 5 points.\n\n Returns\n -------\n inset_axes : *axes_class*\n Inset axes object created.\n """\n\n return _add_inset_axes(\n parent_axes, axes_class, axes_kwargs,\n AnchoredZoomLocator(\n parent_axes, zoom=zoom, loc=loc,\n bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform,\n borderpad=borderpad))\n\n\nclass _TransformedBboxWithCallback(TransformedBbox):\n """\n Variant of `.TransformBbox` which calls *callback* before returning points.\n\n Used by `.mark_inset` to unstale the parent axes' viewlim as needed.\n """\n\n def __init__(self, *args, callback, **kwargs):\n super().__init__(*args, **kwargs)\n self._callback = callback\n\n def get_points(self):\n self._callback()\n return super().get_points()\n\n\n@_docstring.interpd\ndef mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs):\n """\n Draw a box to mark the location of an area represented by an inset axes.\n\n This function draws a box in *parent_axes* at the bounding box of\n *inset_axes*, and shows a connection with the inset axes by drawing lines\n at the corners, giving a "zoomed in" effect.\n\n Parameters\n ----------\n parent_axes : `~matplotlib.axes.Axes`\n Axes which contains the area of the inset axes.\n\n inset_axes : `~matplotlib.axes.Axes`\n The inset axes.\n\n loc1, loc2 : {1, 2, 3, 4}\n Corners to use for connecting the inset axes and the area in the\n parent axes.\n\n **kwargs\n Patch properties for the lines and box drawn:\n\n %(Patch:kwdoc)s\n\n Returns\n -------\n pp : `~matplotlib.patches.Patch`\n The patch drawn to represent the area of the inset axes.\n\n p1, p2 : `~matplotlib.patches.Patch`\n The patches connecting two corners of the inset axes and its area.\n """\n rect = _TransformedBboxWithCallback(\n inset_axes.viewLim, parent_axes.transData,\n callback=parent_axes._unstale_viewLim)\n\n kwargs.setdefault("fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs)))\n pp = BboxPatch(rect, **kwargs)\n parent_axes.add_patch(pp)\n\n p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs)\n inset_axes.add_patch(p1)\n p1.set_clip_on(False)\n p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs)\n inset_axes.add_patch(p2)\n p2.set_clip_on(False)\n\n return pp, p1, p2\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\inset_locator.py | inset_locator.py | Python | 19,649 | 0.95 | 0.121387 | 0.052009 | node-utils | 70 | 2025-01-04T09:08:31.964708 | MIT | false | da9a64f9153e04bb46a00a3e61dee720 |
import matplotlib.axes as maxes\nfrom matplotlib.artist import Artist\nfrom matplotlib.axis import XAxis, YAxis\n\n\nclass SimpleChainedObjects:\n def __init__(self, objects):\n self._objects = objects\n\n def __getattr__(self, k):\n _a = SimpleChainedObjects([getattr(a, k) for a in self._objects])\n return _a\n\n def __call__(self, *args, **kwargs):\n for m in self._objects:\n m(*args, **kwargs)\n\n\nclass Axes(maxes.Axes):\n\n class AxisDict(dict):\n def __init__(self, axes):\n self.axes = axes\n super().__init__()\n\n def __getitem__(self, k):\n if isinstance(k, tuple):\n r = SimpleChainedObjects(\n # super() within a list comprehension needs explicit args.\n [super(Axes.AxisDict, self).__getitem__(k1) for k1 in k])\n return r\n elif isinstance(k, slice):\n if k.start is None and k.stop is None and k.step is None:\n return SimpleChainedObjects(list(self.values()))\n else:\n raise ValueError("Unsupported slice")\n else:\n return dict.__getitem__(self, k)\n\n def __call__(self, *v, **kwargs):\n return maxes.Axes.axis(self.axes, *v, **kwargs)\n\n @property\n def axis(self):\n return self._axislines\n\n def clear(self):\n # docstring inherited\n super().clear()\n # Init axis artists.\n self._axislines = self.AxisDict(self)\n self._axislines.update(\n bottom=SimpleAxisArtist(self.xaxis, 1, self.spines["bottom"]),\n top=SimpleAxisArtist(self.xaxis, 2, self.spines["top"]),\n left=SimpleAxisArtist(self.yaxis, 1, self.spines["left"]),\n right=SimpleAxisArtist(self.yaxis, 2, self.spines["right"]))\n\n\nclass SimpleAxisArtist(Artist):\n def __init__(self, axis, axisnum, spine):\n self._axis = axis\n self._axisnum = axisnum\n self.line = spine\n\n if isinstance(axis, XAxis):\n self._axis_direction = ["bottom", "top"][axisnum-1]\n elif isinstance(axis, YAxis):\n self._axis_direction = ["left", "right"][axisnum-1]\n else:\n raise ValueError(\n f"axis must be instance of XAxis or YAxis, but got {axis}")\n super().__init__()\n\n @property\n def major_ticks(self):\n tickline = "tick%dline" % self._axisnum\n return SimpleChainedObjects([getattr(tick, tickline)\n for tick in self._axis.get_major_ticks()])\n\n @property\n def major_ticklabels(self):\n label = "label%d" % self._axisnum\n return SimpleChainedObjects([getattr(tick, label)\n for tick in self._axis.get_major_ticks()])\n\n @property\n def label(self):\n return self._axis.label\n\n def set_visible(self, b):\n self.toggle(all=b)\n self.line.set_visible(b)\n self._axis.set_visible(True)\n super().set_visible(b)\n\n def set_label(self, txt):\n self._axis.set_label_text(txt)\n\n def toggle(self, all=None, ticks=None, ticklabels=None, label=None):\n\n if all:\n _ticks, _ticklabels, _label = True, True, True\n elif all is not None:\n _ticks, _ticklabels, _label = False, False, False\n else:\n _ticks, _ticklabels, _label = None, None, None\n\n if ticks is not None:\n _ticks = ticks\n if ticklabels is not None:\n _ticklabels = ticklabels\n if label is not None:\n _label = label\n\n if _ticks is not None:\n tickparam = {f"tick{self._axisnum}On": _ticks}\n self._axis.set_tick_params(**tickparam)\n if _ticklabels is not None:\n tickparam = {f"label{self._axisnum}On": _ticklabels}\n self._axis.set_tick_params(**tickparam)\n\n if _label is not None:\n pos = self._axis.get_label_position()\n if (pos == self._axis_direction) and not _label:\n self._axis.label.set_visible(False)\n elif _label:\n self._axis.label.set_visible(True)\n self._axis.set_label_position(self._axis_direction)\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\mpl_axes.py | mpl_axes.py | Python | 4,251 | 0.95 | 0.273438 | 0.028846 | awesome-app | 216 | 2025-04-23T08:54:42.085349 | GPL-3.0 | false | 13721bcac40ceb457fdc226c8041dd9c |
from matplotlib import _api, cbook\nimport matplotlib.artist as martist\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.transforms import Bbox\nfrom .mpl_axes import Axes\n\n\nclass ParasiteAxesBase:\n\n def __init__(self, parent_axes, aux_transform=None,\n *, viewlim_mode=None, **kwargs):\n self._parent_axes = parent_axes\n self.transAux = aux_transform\n self.set_viewlim_mode(viewlim_mode)\n kwargs["frameon"] = False\n super().__init__(parent_axes.get_figure(root=False),\n parent_axes._position, **kwargs)\n\n def clear(self):\n super().clear()\n martist.setp(self.get_children(), visible=False)\n self._get_lines = self._parent_axes._get_lines\n self._parent_axes.callbacks._connect_picklable(\n "xlim_changed", self._sync_lims)\n self._parent_axes.callbacks._connect_picklable(\n "ylim_changed", self._sync_lims)\n\n def pick(self, mouseevent):\n # This most likely goes to Artist.pick (depending on axes_class given\n # to the factory), which only handles pick events registered on the\n # axes associated with each child:\n super().pick(mouseevent)\n # But parasite axes are additionally given pick events from their host\n # axes (cf. HostAxesBase.pick), which we handle here:\n for a in self.get_children():\n if (hasattr(mouseevent.inaxes, "parasites")\n and self in mouseevent.inaxes.parasites):\n a.pick(mouseevent)\n\n # aux_transform support\n\n def _set_lim_and_transforms(self):\n if self.transAux is not None:\n self.transAxes = self._parent_axes.transAxes\n self.transData = self.transAux + self._parent_axes.transData\n self._xaxis_transform = mtransforms.blended_transform_factory(\n self.transData, self.transAxes)\n self._yaxis_transform = mtransforms.blended_transform_factory(\n self.transAxes, self.transData)\n else:\n super()._set_lim_and_transforms()\n\n def set_viewlim_mode(self, mode):\n _api.check_in_list([None, "equal", "transform"], mode=mode)\n self._viewlim_mode = mode\n\n def get_viewlim_mode(self):\n return self._viewlim_mode\n\n def _sync_lims(self, parent):\n viewlim = parent.viewLim.frozen()\n mode = self.get_viewlim_mode()\n if mode is None:\n pass\n elif mode == "equal":\n self.viewLim.set(viewlim)\n elif mode == "transform":\n self.viewLim.set(viewlim.transformed(self.transAux.inverted()))\n else:\n _api.check_in_list([None, "equal", "transform"], mode=mode)\n\n # end of aux_transform support\n\n\nparasite_axes_class_factory = cbook._make_class_factory(\n ParasiteAxesBase, "{}Parasite")\nParasiteAxes = parasite_axes_class_factory(Axes)\n\n\nclass HostAxesBase:\n def __init__(self, *args, **kwargs):\n self.parasites = []\n super().__init__(*args, **kwargs)\n\n def get_aux_axes(\n self, tr=None, viewlim_mode="equal", axes_class=None, **kwargs):\n """\n Add a parasite axes to this host.\n\n Despite this method's name, this should actually be thought of as an\n ``add_parasite_axes`` method.\n\n .. versionchanged:: 3.7\n Defaults to same base axes class as host axes.\n\n Parameters\n ----------\n tr : `~matplotlib.transforms.Transform` or None, default: None\n If a `.Transform`, the following relation will hold:\n ``parasite.transData = tr + host.transData``.\n If None, the parasite's and the host's ``transData`` are unrelated.\n viewlim_mode : {"equal", "transform", None}, default: "equal"\n How the parasite's view limits are set: directly equal to the\n parent axes ("equal"), equal after application of *tr*\n ("transform"), or independently (None).\n axes_class : subclass type of `~matplotlib.axes.Axes`, optional\n The `~.axes.Axes` subclass that is instantiated. If None, the base\n class of the host axes is used.\n **kwargs\n Other parameters are forwarded to the parasite axes constructor.\n """\n if axes_class is None:\n axes_class = self._base_axes_class\n parasite_axes_class = parasite_axes_class_factory(axes_class)\n ax2 = parasite_axes_class(\n self, tr, viewlim_mode=viewlim_mode, **kwargs)\n # note that ax2.transData == tr + ax1.transData\n # Anything you draw in ax2 will match the ticks and grids of ax1.\n self.parasites.append(ax2)\n ax2._remove_method = self.parasites.remove\n return ax2\n\n def draw(self, renderer):\n orig_children_len = len(self._children)\n\n locator = self.get_axes_locator()\n if locator:\n pos = locator(self, renderer)\n self.set_position(pos, which="active")\n self.apply_aspect(pos)\n else:\n self.apply_aspect()\n\n rect = self.get_position()\n for ax in self.parasites:\n ax.apply_aspect(rect)\n self._children.extend(ax.get_children())\n\n super().draw(renderer)\n del self._children[orig_children_len:]\n\n def clear(self):\n super().clear()\n for ax in self.parasites:\n ax.clear()\n\n def pick(self, mouseevent):\n super().pick(mouseevent)\n # Also pass pick events on to parasite axes and, in turn, their\n # children (cf. ParasiteAxesBase.pick)\n for a in self.parasites:\n a.pick(mouseevent)\n\n def twinx(self, axes_class=None):\n """\n Create a twin of Axes with a shared x-axis but independent y-axis.\n\n The y-axis of self will have ticks on the left and the returned axes\n will have ticks on the right.\n """\n ax = self._add_twin_axes(axes_class, sharex=self)\n self.axis["right"].set_visible(False)\n ax.axis["right"].set_visible(True)\n ax.axis["left", "top", "bottom"].set_visible(False)\n return ax\n\n def twiny(self, axes_class=None):\n """\n Create a twin of Axes with a shared y-axis but independent x-axis.\n\n The x-axis of self will have ticks on the bottom and the returned axes\n will have ticks on the top.\n """\n ax = self._add_twin_axes(axes_class, sharey=self)\n self.axis["top"].set_visible(False)\n ax.axis["top"].set_visible(True)\n ax.axis["left", "right", "bottom"].set_visible(False)\n return ax\n\n def twin(self, aux_trans=None, axes_class=None):\n """\n Create a twin of Axes with no shared axis.\n\n While self will have ticks on the left and bottom axis, the returned\n axes will have ticks on the top and right axis.\n """\n if aux_trans is None:\n aux_trans = mtransforms.IdentityTransform()\n ax = self._add_twin_axes(\n axes_class, aux_transform=aux_trans, viewlim_mode="transform")\n self.axis["top", "right"].set_visible(False)\n ax.axis["top", "right"].set_visible(True)\n ax.axis["left", "bottom"].set_visible(False)\n return ax\n\n def _add_twin_axes(self, axes_class, **kwargs):\n """\n Helper for `.twinx`/`.twiny`/`.twin`.\n\n *kwargs* are forwarded to the parasite axes constructor.\n """\n if axes_class is None:\n axes_class = self._base_axes_class\n ax = parasite_axes_class_factory(axes_class)(self, **kwargs)\n self.parasites.append(ax)\n ax._remove_method = self._remove_any_twin\n return ax\n\n def _remove_any_twin(self, ax):\n self.parasites.remove(ax)\n restore = ["top", "right"]\n if ax._sharex:\n restore.remove("top")\n if ax._sharey:\n restore.remove("right")\n self.axis[tuple(restore)].set_visible(True)\n self.axis[tuple(restore)].toggle(ticklabels=False, label=False)\n\n def get_tightbbox(self, renderer=None, *, call_axes_locator=True,\n bbox_extra_artists=None):\n bbs = [\n *[ax.get_tightbbox(renderer, call_axes_locator=call_axes_locator)\n for ax in self.parasites],\n super().get_tightbbox(renderer,\n call_axes_locator=call_axes_locator,\n bbox_extra_artists=bbox_extra_artists)]\n return Bbox.union([b for b in bbs if b.width != 0 or b.height != 0])\n\n\nhost_axes_class_factory = host_subplot_class_factory = \\n cbook._make_class_factory(HostAxesBase, "{}HostAxes", "_base_axes_class")\nHostAxes = SubplotHost = host_axes_class_factory(Axes)\n\n\ndef host_axes(*args, axes_class=Axes, figure=None, **kwargs):\n """\n Create axes that can act as a hosts to parasitic axes.\n\n Parameters\n ----------\n figure : `~matplotlib.figure.Figure`\n Figure to which the axes will be added. Defaults to the current figure\n `.pyplot.gcf()`.\n\n *args, **kwargs\n Will be passed on to the underlying `~.axes.Axes` object creation.\n """\n import matplotlib.pyplot as plt\n host_axes_class = host_axes_class_factory(axes_class)\n if figure is None:\n figure = plt.gcf()\n ax = host_axes_class(figure, *args, **kwargs)\n figure.add_axes(ax)\n return ax\n\n\nhost_subplot = host_axes\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\parasite_axes.py | parasite_axes.py | Python | 9,404 | 0.95 | 0.159533 | 0.074766 | awesome-app | 760 | 2024-12-19T12:56:00.042747 | BSD-3-Clause | false | 41be2ce89284dd3bf007cefd55d5f122 |
from . import axes_size as Size\nfrom .axes_divider import Divider, SubplotDivider, make_axes_locatable\nfrom .axes_grid import AxesGrid, Grid, ImageGrid\n\nfrom .parasite_axes import host_subplot, host_axes\n\n__all__ = ["Size",\n "Divider", "SubplotDivider", "make_axes_locatable",\n "AxesGrid", "Grid", "ImageGrid",\n "host_subplot", "host_axes"]\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__init__.py | __init__.py | Python | 371 | 0.85 | 0 | 0 | node-utils | 406 | 2025-05-09T22:16:33.600170 | BSD-3-Clause | false | 40ca61a5a903a67af811c36bed775a0d |
from matplotlib.testing.conftest import (mpl_test_settings, # noqa\n pytest_configure, pytest_unconfigure)\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\tests\conftest.py | conftest.py | Python | 147 | 0.95 | 0 | 0 | node-utils | 897 | 2025-04-09T05:50:55.528450 | MIT | true | a9af9c9b2ae8eefcebb125a652ac4c2b |
from itertools import product\nimport io\nimport platform\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nfrom matplotlib import cbook\nfrom matplotlib.backend_bases import MouseEvent\nfrom matplotlib.colors import LogNorm\nfrom matplotlib.patches import Circle, Ellipse\nfrom matplotlib.transforms import Bbox, TransformedBbox\nfrom matplotlib.testing.decorators import (\n check_figures_equal, image_comparison, remove_ticks_and_titles)\n\nfrom mpl_toolkits.axes_grid1 import (\n axes_size as Size,\n host_subplot, make_axes_locatable,\n Grid, AxesGrid, ImageGrid)\nfrom mpl_toolkits.axes_grid1.anchored_artists import (\n AnchoredAuxTransformBox, AnchoredDrawingArea,\n AnchoredDirectionArrows, AnchoredSizeBar)\nfrom mpl_toolkits.axes_grid1.axes_divider import (\n Divider, HBoxDivider, make_axes_area_auto_adjustable, SubplotDivider,\n VBoxDivider)\nfrom mpl_toolkits.axes_grid1.axes_rgb import RGBAxes\nfrom mpl_toolkits.axes_grid1.inset_locator import (\n zoomed_inset_axes, mark_inset, inset_axes, BboxConnectorPatch)\nimport mpl_toolkits.axes_grid1.mpl_axes\nimport pytest\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\n\ndef test_divider_append_axes():\n fig, ax = plt.subplots()\n divider = make_axes_locatable(ax)\n axs = {\n "main": ax,\n "top": divider.append_axes("top", 1.2, pad=0.1, sharex=ax),\n "bottom": divider.append_axes("bottom", 1.2, pad=0.1, sharex=ax),\n "left": divider.append_axes("left", 1.2, pad=0.1, sharey=ax),\n "right": divider.append_axes("right", 1.2, pad=0.1, sharey=ax),\n }\n fig.canvas.draw()\n bboxes = {k: axs[k].get_window_extent() for k in axs}\n dpi = fig.dpi\n assert bboxes["top"].height == pytest.approx(1.2 * dpi)\n assert bboxes["bottom"].height == pytest.approx(1.2 * dpi)\n assert bboxes["left"].width == pytest.approx(1.2 * dpi)\n assert bboxes["right"].width == pytest.approx(1.2 * dpi)\n assert bboxes["top"].y0 - bboxes["main"].y1 == pytest.approx(0.1 * dpi)\n assert bboxes["main"].y0 - bboxes["bottom"].y1 == pytest.approx(0.1 * dpi)\n assert bboxes["main"].x0 - bboxes["left"].x1 == pytest.approx(0.1 * dpi)\n assert bboxes["right"].x0 - bboxes["main"].x1 == pytest.approx(0.1 * dpi)\n assert bboxes["left"].y0 == bboxes["main"].y0 == bboxes["right"].y0\n assert bboxes["left"].y1 == bboxes["main"].y1 == bboxes["right"].y1\n assert bboxes["top"].x0 == bboxes["main"].x0 == bboxes["bottom"].x0\n assert bboxes["top"].x1 == bboxes["main"].x1 == bboxes["bottom"].x1\n\n\n# Update style when regenerating the test image\n@image_comparison(['twin_axes_empty_and_removed'], extensions=["png"], tol=1,\n style=('classic', '_classic_test_patch'))\ndef test_twin_axes_empty_and_removed():\n # Purely cosmetic font changes (avoid overlap)\n mpl.rcParams.update(\n {"font.size": 8, "xtick.labelsize": 8, "ytick.labelsize": 8})\n generators = ["twinx", "twiny", "twin"]\n modifiers = ["", "host invisible", "twin removed", "twin invisible",\n "twin removed\nhost invisible"]\n # Unmodified host subplot at the beginning for reference\n h = host_subplot(len(modifiers)+1, len(generators), 2)\n h.text(0.5, 0.5, "host_subplot",\n horizontalalignment="center", verticalalignment="center")\n # Host subplots with various modifications (twin*, visibility) applied\n for i, (mod, gen) in enumerate(product(modifiers, generators),\n len(generators) + 1):\n h = host_subplot(len(modifiers)+1, len(generators), i)\n t = getattr(h, gen)()\n if "twin invisible" in mod:\n t.axis[:].set_visible(False)\n if "twin removed" in mod:\n t.remove()\n if "host invisible" in mod:\n h.axis[:].set_visible(False)\n h.text(0.5, 0.5, gen + ("\n" + mod if mod else ""),\n horizontalalignment="center", verticalalignment="center")\n plt.subplots_adjust(wspace=0.5, hspace=1)\n\n\ndef test_twin_axes_both_with_units():\n host = host_subplot(111)\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n host.plot_date([0, 1, 2], [0, 1, 2], xdate=False, ydate=True)\n twin = host.twinx()\n twin.plot(["a", "b", "c"])\n assert host.get_yticklabels()[0].get_text() == "00:00:00"\n assert twin.get_yticklabels()[0].get_text() == "a"\n\n\ndef test_axesgrid_colorbar_log_smoketest():\n fig = plt.figure()\n grid = AxesGrid(fig, 111, # modified to be only subplot\n nrows_ncols=(1, 1),\n ngrids=1,\n label_mode="L",\n cbar_location="top",\n cbar_mode="single",\n )\n\n Z = 10000 * np.random.rand(10, 10)\n im = grid[0].imshow(Z, interpolation="nearest", norm=LogNorm())\n\n grid.cbar_axes[0].colorbar(im)\n\n\ndef test_inset_colorbar_tight_layout_smoketest():\n fig, ax = plt.subplots(1, 1)\n pts = ax.scatter([0, 1], [0, 1], c=[1, 5])\n\n cax = inset_axes(ax, width="3%", height="70%")\n plt.colorbar(pts, cax=cax)\n\n with pytest.warns(UserWarning, match="This figure includes Axes"):\n # Will warn, but not raise an error\n plt.tight_layout()\n\n\n@image_comparison(['inset_locator.png'], style='default', remove_text=True)\ndef test_inset_locator():\n fig, ax = plt.subplots(figsize=[5, 4])\n\n # prepare the demo image\n # Z is a 15x15 array\n Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")\n extent = (-3, 4, -4, 3)\n Z2 = np.zeros((150, 150))\n ny, nx = Z.shape\n Z2[30:30+ny, 30:30+nx] = Z\n\n ax.imshow(Z2, extent=extent, interpolation="nearest",\n origin="lower")\n\n axins = zoomed_inset_axes(ax, zoom=6, loc='upper right')\n axins.imshow(Z2, extent=extent, interpolation="nearest",\n origin="lower")\n axins.yaxis.get_major_locator().set_params(nbins=7)\n axins.xaxis.get_major_locator().set_params(nbins=7)\n # sub region of the original image\n x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9\n axins.set_xlim(x1, x2)\n axins.set_ylim(y1, y2)\n\n plt.xticks(visible=False)\n plt.yticks(visible=False)\n\n # draw a bbox of the region of the inset axes in the parent axes and\n # connecting lines between the bbox and the inset axes area\n mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")\n\n asb = AnchoredSizeBar(ax.transData,\n 0.5,\n '0.5',\n loc='lower center',\n pad=0.1, borderpad=0.5, sep=5,\n frameon=False)\n ax.add_artist(asb)\n\n\n@image_comparison(['inset_axes.png'], style='default', remove_text=True)\ndef test_inset_axes():\n fig, ax = plt.subplots(figsize=[5, 4])\n\n # prepare the demo image\n # Z is a 15x15 array\n Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")\n extent = (-3, 4, -4, 3)\n Z2 = np.zeros((150, 150))\n ny, nx = Z.shape\n Z2[30:30+ny, 30:30+nx] = Z\n\n ax.imshow(Z2, extent=extent, interpolation="nearest",\n origin="lower")\n\n # creating our inset axes with a bbox_transform parameter\n axins = inset_axes(ax, width=1., height=1., bbox_to_anchor=(1, 1),\n bbox_transform=ax.transAxes)\n\n axins.imshow(Z2, extent=extent, interpolation="nearest",\n origin="lower")\n axins.yaxis.get_major_locator().set_params(nbins=7)\n axins.xaxis.get_major_locator().set_params(nbins=7)\n # sub region of the original image\n x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9\n axins.set_xlim(x1, x2)\n axins.set_ylim(y1, y2)\n\n plt.xticks(visible=False)\n plt.yticks(visible=False)\n\n # draw a bbox of the region of the inset axes in the parent axes and\n # connecting lines between the bbox and the inset axes area\n mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")\n\n asb = AnchoredSizeBar(ax.transData,\n 0.5,\n '0.5',\n loc='lower center',\n pad=0.1, borderpad=0.5, sep=5,\n frameon=False)\n ax.add_artist(asb)\n\n\ndef test_inset_axes_complete():\n dpi = 100\n figsize = (6, 5)\n fig, ax = plt.subplots(figsize=figsize, dpi=dpi)\n fig.subplots_adjust(.1, .1, .9, .9)\n\n ins = inset_axes(ax, width=2., height=2., borderpad=0)\n fig.canvas.draw()\n assert_array_almost_equal(\n ins.get_position().extents,\n [(0.9*figsize[0]-2.)/figsize[0], (0.9*figsize[1]-2.)/figsize[1],\n 0.9, 0.9])\n\n ins = inset_axes(ax, width="40%", height="30%", borderpad=0)\n fig.canvas.draw()\n assert_array_almost_equal(\n ins.get_position().extents, [.9-.8*.4, .9-.8*.3, 0.9, 0.9])\n\n ins = inset_axes(ax, width=1., height=1.2, bbox_to_anchor=(200, 100),\n loc=3, borderpad=0)\n fig.canvas.draw()\n assert_array_almost_equal(\n ins.get_position().extents,\n [200/dpi/figsize[0], 100/dpi/figsize[1],\n (200/dpi+1)/figsize[0], (100/dpi+1.2)/figsize[1]])\n\n ins1 = inset_axes(ax, width="35%", height="60%", loc=3, borderpad=1)\n ins2 = inset_axes(ax, width="100%", height="100%",\n bbox_to_anchor=(0, 0, .35, .60),\n bbox_transform=ax.transAxes, loc=3, borderpad=1)\n fig.canvas.draw()\n assert_array_equal(ins1.get_position().extents,\n ins2.get_position().extents)\n\n with pytest.raises(ValueError):\n ins = inset_axes(ax, width="40%", height="30%",\n bbox_to_anchor=(0.4, 0.5))\n\n with pytest.warns(UserWarning):\n ins = inset_axes(ax, width="40%", height="30%",\n bbox_transform=ax.transAxes)\n\n\ndef test_inset_axes_tight():\n # gh-26287 found that inset_axes raised with bbox_inches=tight\n fig, ax = plt.subplots()\n inset_axes(ax, width=1.3, height=0.9)\n\n f = io.BytesIO()\n fig.savefig(f, bbox_inches="tight")\n\n\n@image_comparison(['fill_facecolor.png'], remove_text=True, style='mpl20')\ndef test_fill_facecolor():\n fig, ax = plt.subplots(1, 5)\n fig.set_size_inches(5, 5)\n for i in range(1, 4):\n ax[i].yaxis.set_visible(False)\n ax[4].yaxis.tick_right()\n bbox = Bbox.from_extents(0, 0.4, 1, 0.6)\n\n # fill with blue by setting 'fc' field\n bbox1 = TransformedBbox(bbox, ax[0].transData)\n bbox2 = TransformedBbox(bbox, ax[1].transData)\n # set color to BboxConnectorPatch\n p = BboxConnectorPatch(\n bbox1, bbox2, loc1a=1, loc2a=2, loc1b=4, loc2b=3,\n ec="r", fc="b")\n p.set_clip_on(False)\n ax[0].add_patch(p)\n # set color to marked area\n axins = zoomed_inset_axes(ax[0], 1, loc='upper right')\n axins.set_xlim(0, 0.2)\n axins.set_ylim(0, 0.2)\n plt.gca().axes.xaxis.set_ticks([])\n plt.gca().axes.yaxis.set_ticks([])\n mark_inset(ax[0], axins, loc1=2, loc2=4, fc="b", ec="0.5")\n\n # fill with yellow by setting 'facecolor' field\n bbox3 = TransformedBbox(bbox, ax[1].transData)\n bbox4 = TransformedBbox(bbox, ax[2].transData)\n # set color to BboxConnectorPatch\n p = BboxConnectorPatch(\n bbox3, bbox4, loc1a=1, loc2a=2, loc1b=4, loc2b=3,\n ec="r", facecolor="y")\n p.set_clip_on(False)\n ax[1].add_patch(p)\n # set color to marked area\n axins = zoomed_inset_axes(ax[1], 1, loc='upper right')\n axins.set_xlim(0, 0.2)\n axins.set_ylim(0, 0.2)\n plt.gca().axes.xaxis.set_ticks([])\n plt.gca().axes.yaxis.set_ticks([])\n mark_inset(ax[1], axins, loc1=2, loc2=4, facecolor="y", ec="0.5")\n\n # fill with green by setting 'color' field\n bbox5 = TransformedBbox(bbox, ax[2].transData)\n bbox6 = TransformedBbox(bbox, ax[3].transData)\n # set color to BboxConnectorPatch\n p = BboxConnectorPatch(\n bbox5, bbox6, loc1a=1, loc2a=2, loc1b=4, loc2b=3,\n ec="r", color="g")\n p.set_clip_on(False)\n ax[2].add_patch(p)\n # set color to marked area\n axins = zoomed_inset_axes(ax[2], 1, loc='upper right')\n axins.set_xlim(0, 0.2)\n axins.set_ylim(0, 0.2)\n plt.gca().axes.xaxis.set_ticks([])\n plt.gca().axes.yaxis.set_ticks([])\n mark_inset(ax[2], axins, loc1=2, loc2=4, color="g", ec="0.5")\n\n # fill with green but color won't show if set fill to False\n bbox7 = TransformedBbox(bbox, ax[3].transData)\n bbox8 = TransformedBbox(bbox, ax[4].transData)\n # BboxConnectorPatch won't show green\n p = BboxConnectorPatch(\n bbox7, bbox8, loc1a=1, loc2a=2, loc1b=4, loc2b=3,\n ec="r", fc="g", fill=False)\n p.set_clip_on(False)\n ax[3].add_patch(p)\n # marked area won't show green\n axins = zoomed_inset_axes(ax[3], 1, loc='upper right')\n axins.set_xlim(0, 0.2)\n axins.set_ylim(0, 0.2)\n axins.xaxis.set_ticks([])\n axins.yaxis.set_ticks([])\n mark_inset(ax[3], axins, loc1=2, loc2=4, fc="g", ec="0.5", fill=False)\n\n\n# Update style when regenerating the test image\n@image_comparison(['zoomed_axes.png', 'inverted_zoomed_axes.png'],\n style=('classic', '_classic_test_patch'),\n tol=0 if platform.machine() == 'x86_64' else 0.02)\ndef test_zooming_with_inverted_axes():\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3], [1, 2, 3])\n ax.axis([1, 3, 1, 3])\n inset_ax = zoomed_inset_axes(ax, zoom=2.5, loc='lower right')\n inset_ax.axis([1.1, 1.4, 1.1, 1.4])\n\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3], [1, 2, 3])\n ax.axis([3, 1, 3, 1])\n inset_ax = zoomed_inset_axes(ax, zoom=2.5, loc='lower right')\n inset_ax.axis([1.4, 1.1, 1.4, 1.1])\n\n\n# Update style when regenerating the test image\n@image_comparison(['anchored_direction_arrows.png'],\n tol=0 if platform.machine() == 'x86_64' else 0.01,\n style=('classic', '_classic_test_patch'))\ndef test_anchored_direction_arrows():\n fig, ax = plt.subplots()\n ax.imshow(np.zeros((10, 10)), interpolation='nearest')\n\n simple_arrow = AnchoredDirectionArrows(ax.transAxes, 'X', 'Y')\n ax.add_artist(simple_arrow)\n\n\n# Update style when regenerating the test image\n@image_comparison(['anchored_direction_arrows_many_args.png'],\n style=('classic', '_classic_test_patch'))\ndef test_anchored_direction_arrows_many_args():\n fig, ax = plt.subplots()\n ax.imshow(np.ones((10, 10)))\n\n direction_arrows = AnchoredDirectionArrows(\n ax.transAxes, 'A', 'B', loc='upper right', color='red',\n aspect_ratio=-0.5, pad=0.6, borderpad=2, frameon=True, alpha=0.7,\n sep_x=-0.06, sep_y=-0.08, back_length=0.1, head_width=9,\n head_length=10, tail_width=5)\n ax.add_artist(direction_arrows)\n\n\ndef test_axes_locatable_position():\n fig, ax = plt.subplots()\n divider = make_axes_locatable(ax)\n with mpl.rc_context({"figure.subplot.wspace": 0.02}):\n cax = divider.append_axes('right', size='5%')\n fig.canvas.draw()\n assert np.isclose(cax.get_position(original=False).width,\n 0.03621495327102808)\n\n\n@image_comparison(['image_grid_each_left_label_mode_all.png'], style='mpl20',\n savefig_kwarg={'bbox_inches': 'tight'})\ndef test_image_grid_each_left_label_mode_all():\n imdata = np.arange(100).reshape((10, 10))\n\n fig = plt.figure(1, (3, 3))\n grid = ImageGrid(fig, (1, 1, 1), nrows_ncols=(3, 2), axes_pad=(0.5, 0.3),\n cbar_mode="each", cbar_location="left", cbar_size="15%",\n label_mode="all")\n # 3-tuple rect => SubplotDivider\n assert isinstance(grid.get_divider(), SubplotDivider)\n assert grid.get_axes_pad() == (0.5, 0.3)\n assert grid.get_aspect() # True by default for ImageGrid\n for ax, cax in zip(grid, grid.cbar_axes):\n im = ax.imshow(imdata, interpolation='none')\n cax.colorbar(im)\n\n\n@image_comparison(['image_grid_single_bottom_label_mode_1.png'], style='mpl20',\n savefig_kwarg={'bbox_inches': 'tight'})\ndef test_image_grid_single_bottom():\n imdata = np.arange(100).reshape((10, 10))\n\n fig = plt.figure(1, (2.5, 1.5))\n grid = ImageGrid(fig, (0, 0, 1, 1), nrows_ncols=(1, 3),\n axes_pad=(0.2, 0.15), cbar_mode="single", cbar_pad=0.3,\n cbar_location="bottom", cbar_size="10%", label_mode="1")\n # 4-tuple rect => Divider, isinstance will give True for SubplotDivider\n assert type(grid.get_divider()) is Divider\n for i in range(3):\n im = grid[i].imshow(imdata, interpolation='none')\n grid.cbar_axes[0].colorbar(im)\n\n\ndef test_image_grid_label_mode_invalid():\n fig = plt.figure()\n with pytest.raises(ValueError, match="'foo' is not a valid value for mode"):\n ImageGrid(fig, (0, 0, 1, 1), (2, 1), label_mode="foo")\n\n\n@image_comparison(['image_grid.png'],\n remove_text=True, style='mpl20',\n savefig_kwarg={'bbox_inches': 'tight'})\ndef test_image_grid():\n # test that image grid works with bbox_inches=tight.\n im = np.arange(100).reshape((10, 10))\n\n fig = plt.figure(1, (4, 4))\n grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=0.1)\n assert grid.get_axes_pad() == (0.1, 0.1)\n for i in range(4):\n grid[i].imshow(im, interpolation='nearest')\n\n\ndef test_gettightbbox():\n fig, ax = plt.subplots(figsize=(8, 6))\n\n l, = ax.plot([1, 2, 3], [0, 1, 0])\n\n ax_zoom = zoomed_inset_axes(ax, 4)\n ax_zoom.plot([1, 2, 3], [0, 1, 0])\n\n mark_inset(ax, ax_zoom, loc1=1, loc2=3, fc="none", ec='0.3')\n\n remove_ticks_and_titles(fig)\n bbox = fig.get_tightbbox(fig.canvas.get_renderer())\n np.testing.assert_array_almost_equal(bbox.extents,\n [-17.7, -13.9, 7.2, 5.4])\n\n\n@pytest.mark.parametrize("click_on", ["big", "small"])\n@pytest.mark.parametrize("big_on_axes,small_on_axes", [\n ("gca", "gca"),\n ("host", "host"),\n ("host", "parasite"),\n ("parasite", "host"),\n ("parasite", "parasite")\n])\ndef test_picking_callbacks_overlap(big_on_axes, small_on_axes, click_on):\n """Test pick events on normal, host or parasite axes."""\n # Two rectangles are drawn and "clicked on", a small one and a big one\n # enclosing the small one. The axis on which they are drawn as well as the\n # rectangle that is clicked on are varied.\n # In each case we expect that both rectangles are picked if we click on the\n # small one and only the big one is picked if we click on the big one.\n # Also tests picking on normal axes ("gca") as a control.\n big = plt.Rectangle((0.25, 0.25), 0.5, 0.5, picker=5)\n small = plt.Rectangle((0.4, 0.4), 0.2, 0.2, facecolor="r", picker=5)\n # Machinery for "receiving" events\n received_events = []\n def on_pick(event):\n received_events.append(event)\n plt.gcf().canvas.mpl_connect('pick_event', on_pick)\n # Shortcut\n rectangles_on_axes = (big_on_axes, small_on_axes)\n # Axes setup\n axes = {"gca": None, "host": None, "parasite": None}\n if "gca" in rectangles_on_axes:\n axes["gca"] = plt.gca()\n if "host" in rectangles_on_axes or "parasite" in rectangles_on_axes:\n axes["host"] = host_subplot(111)\n axes["parasite"] = axes["host"].twin()\n # Add rectangles to axes\n axes[big_on_axes].add_patch(big)\n axes[small_on_axes].add_patch(small)\n # Simulate picking with click mouse event\n if click_on == "big":\n click_axes = axes[big_on_axes]\n axes_coords = (0.3, 0.3)\n else:\n click_axes = axes[small_on_axes]\n axes_coords = (0.5, 0.5)\n # In reality mouse events never happen on parasite axes, only host axes\n if click_axes is axes["parasite"]:\n click_axes = axes["host"]\n (x, y) = click_axes.transAxes.transform(axes_coords)\n m = MouseEvent("button_press_event", click_axes.get_figure(root=True).canvas, x, y,\n button=1)\n click_axes.pick(m)\n # Checks\n expected_n_events = 2 if click_on == "small" else 1\n assert len(received_events) == expected_n_events\n event_rects = [event.artist for event in received_events]\n assert big in event_rects\n if click_on == "small":\n assert small in event_rects\n\n\n@image_comparison(['anchored_artists.png'], remove_text=True, style='mpl20')\ndef test_anchored_artists():\n fig, ax = plt.subplots(figsize=(3, 3))\n ada = AnchoredDrawingArea(40, 20, 0, 0, loc='upper right', pad=0.,\n frameon=False)\n p1 = Circle((10, 10), 10)\n ada.drawing_area.add_artist(p1)\n p2 = Circle((30, 10), 5, fc="r")\n ada.drawing_area.add_artist(p2)\n ax.add_artist(ada)\n\n box = AnchoredAuxTransformBox(ax.transData, loc='upper left')\n el = Ellipse((0, 0), width=0.1, height=0.4, angle=30, color='cyan')\n box.drawing_area.add_artist(el)\n ax.add_artist(box)\n\n # This block used to test the AnchoredEllipse class, but that was removed. The block\n # remains, though it duplicates the above ellipse, so that the test image doesn't\n # need to be regenerated.\n box = AnchoredAuxTransformBox(ax.transData, loc='lower left', frameon=True,\n pad=0.5, borderpad=0.4)\n el = Ellipse((0, 0), width=0.1, height=0.25, angle=-60)\n box.drawing_area.add_artist(el)\n ax.add_artist(box)\n\n asb = AnchoredSizeBar(ax.transData, 0.2, r"0.2 units", loc='lower right',\n pad=0.3, borderpad=0.4, sep=4, fill_bar=True,\n frameon=False, label_top=True, prop={'size': 20},\n size_vertical=0.05, color='green')\n ax.add_artist(asb)\n\n\ndef test_hbox_divider():\n arr1 = np.arange(20).reshape((4, 5))\n arr2 = np.arange(20).reshape((5, 4))\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n ax1.imshow(arr1)\n ax2.imshow(arr2)\n\n pad = 0.5 # inches.\n divider = HBoxDivider(\n fig, 111, # Position of combined axes.\n horizontal=[Size.AxesX(ax1), Size.Fixed(pad), Size.AxesX(ax2)],\n vertical=[Size.AxesY(ax1), Size.Scaled(1), Size.AxesY(ax2)])\n ax1.set_axes_locator(divider.new_locator(0))\n ax2.set_axes_locator(divider.new_locator(2))\n\n fig.canvas.draw()\n p1 = ax1.get_position()\n p2 = ax2.get_position()\n assert p1.height == p2.height\n assert p2.width / p1.width == pytest.approx((4 / 5) ** 2)\n\n\ndef test_vbox_divider():\n arr1 = np.arange(20).reshape((4, 5))\n arr2 = np.arange(20).reshape((5, 4))\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n ax1.imshow(arr1)\n ax2.imshow(arr2)\n\n pad = 0.5 # inches.\n divider = VBoxDivider(\n fig, 111, # Position of combined axes.\n horizontal=[Size.AxesX(ax1), Size.Scaled(1), Size.AxesX(ax2)],\n vertical=[Size.AxesY(ax1), Size.Fixed(pad), Size.AxesY(ax2)])\n ax1.set_axes_locator(divider.new_locator(0))\n ax2.set_axes_locator(divider.new_locator(2))\n\n fig.canvas.draw()\n p1 = ax1.get_position()\n p2 = ax2.get_position()\n assert p1.width == p2.width\n assert p1.height / p2.height == pytest.approx((4 / 5) ** 2)\n\n\ndef test_axes_class_tuple():\n fig = plt.figure()\n axes_class = (mpl_toolkits.axes_grid1.mpl_axes.Axes, {})\n gr = AxesGrid(fig, 111, nrows_ncols=(1, 1), axes_class=axes_class)\n\n\ndef test_grid_axes_lists():\n """Test Grid axes_all, axes_row and axes_column relationship."""\n fig = plt.figure()\n grid = Grid(fig, 111, (2, 3), direction="row")\n assert_array_equal(grid, grid.axes_all)\n assert_array_equal(grid.axes_row, np.transpose(grid.axes_column))\n assert_array_equal(grid, np.ravel(grid.axes_row), "row")\n assert grid.get_geometry() == (2, 3)\n grid = Grid(fig, 111, (2, 3), direction="column")\n assert_array_equal(grid, np.ravel(grid.axes_column), "column")\n\n\n@pytest.mark.parametrize('direction', ('row', 'column'))\ndef test_grid_axes_position(direction):\n """Test positioning of the axes in Grid."""\n fig = plt.figure()\n grid = Grid(fig, 111, (2, 2), direction=direction)\n loc = [ax.get_axes_locator() for ax in np.ravel(grid.axes_row)]\n # Test nx.\n assert loc[1].args[0] > loc[0].args[0]\n assert loc[0].args[0] == loc[2].args[0]\n assert loc[3].args[0] == loc[1].args[0]\n # Test ny.\n assert loc[2].args[1] < loc[0].args[1]\n assert loc[0].args[1] == loc[1].args[1]\n assert loc[3].args[1] == loc[2].args[1]\n\n\n@pytest.mark.parametrize('rect, ngrids, error, message', (\n ((1, 1), None, TypeError, "Incorrect rect format"),\n (111, -1, ValueError, "ngrids must be positive"),\n (111, 7, ValueError, "ngrids must be positive"),\n))\ndef test_grid_errors(rect, ngrids, error, message):\n fig = plt.figure()\n with pytest.raises(error, match=message):\n Grid(fig, rect, (2, 3), ngrids=ngrids)\n\n\n@pytest.mark.parametrize('anchor, error, message', (\n (None, TypeError, "anchor must be str"),\n ("CC", ValueError, "'CC' is not a valid value for anchor"),\n ((1, 1, 1), TypeError, "anchor must be str"),\n))\ndef test_divider_errors(anchor, error, message):\n fig = plt.figure()\n with pytest.raises(error, match=message):\n Divider(fig, [0, 0, 1, 1], [Size.Fixed(1)], [Size.Fixed(1)],\n anchor=anchor)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_mark_inset_unstales_viewlim(fig_test, fig_ref):\n inset, full = fig_test.subplots(1, 2)\n full.plot([0, 5], [0, 5])\n inset.set(xlim=(1, 2), ylim=(1, 2))\n # Check that mark_inset unstales full's viewLim before drawing the marks.\n mark_inset(full, inset, 1, 4)\n\n inset, full = fig_ref.subplots(1, 2)\n full.plot([0, 5], [0, 5])\n inset.set(xlim=(1, 2), ylim=(1, 2))\n mark_inset(full, inset, 1, 4)\n # Manually unstale the full's viewLim.\n fig_ref.canvas.draw()\n\n\ndef test_auto_adjustable():\n fig = plt.figure()\n ax = fig.add_axes([0, 0, 1, 1])\n pad = 0.1\n make_axes_area_auto_adjustable(ax, pad=pad)\n fig.canvas.draw()\n tbb = ax.get_tightbbox()\n assert tbb.x0 == pytest.approx(pad * fig.dpi)\n assert tbb.x1 == pytest.approx(fig.bbox.width - pad * fig.dpi)\n assert tbb.y0 == pytest.approx(pad * fig.dpi)\n assert tbb.y1 == pytest.approx(fig.bbox.height - pad * fig.dpi)\n\n\n# Update style when regenerating the test image\n@image_comparison(['rgb_axes.png'], remove_text=True,\n style=('classic', '_classic_test_patch'))\ndef test_rgb_axes():\n fig = plt.figure()\n ax = RGBAxes(fig, (0.1, 0.1, 0.8, 0.8), pad=0.1)\n rng = np.random.default_rng(19680801)\n r = rng.random((5, 5))\n g = rng.random((5, 5))\n b = rng.random((5, 5))\n ax.imshow_rgb(r, g, b, interpolation='none')\n\n\n# The original version of this test relied on mpl_toolkits's slightly different\n# colorbar implementation; moving to matplotlib's own colorbar implementation\n# caused the small image comparison error.\n@image_comparison(['imagegrid_cbar_mode.png'],\n remove_text=True, style='mpl20', tol=0.3)\ndef test_imagegrid_cbar_mode_edge():\n arr = np.arange(16).reshape((4, 4))\n\n fig = plt.figure(figsize=(18, 9))\n\n positions = (241, 242, 243, 244, 245, 246, 247, 248)\n directions = ['row']*4 + ['column']*4\n cbar_locations = ['left', 'right', 'top', 'bottom']*2\n\n for position, direction, location in zip(\n positions, directions, cbar_locations):\n grid = ImageGrid(fig, position,\n nrows_ncols=(2, 2),\n direction=direction,\n cbar_location=location,\n cbar_size='20%',\n cbar_mode='edge')\n ax1, ax2, ax3, ax4 = grid\n\n ax1.imshow(arr, cmap='nipy_spectral')\n ax2.imshow(arr.T, cmap='hot')\n ax3.imshow(np.hypot(arr, arr.T), cmap='jet')\n ax4.imshow(np.arctan2(arr, arr.T), cmap='hsv')\n\n # In each row/column, the "first" colorbars must be overwritten by the\n # "second" ones. To achieve this, clear out the axes first.\n for ax in grid:\n ax.cax.cla()\n cb = ax.cax.colorbar(ax.images[0])\n\n\ndef test_imagegrid():\n fig = plt.figure()\n grid = ImageGrid(fig, 111, nrows_ncols=(1, 1))\n ax = grid[0]\n im = ax.imshow([[1, 2]], norm=mpl.colors.LogNorm())\n cb = ax.cax.colorbar(im)\n assert isinstance(cb.locator, mticker.LogLocator)\n\n\ndef test_removal():\n import matplotlib.pyplot as plt\n import mpl_toolkits.axisartist as AA\n fig = plt.figure()\n ax = host_subplot(111, axes_class=AA.Axes, figure=fig)\n col = ax.fill_between(range(5), 0, range(5))\n fig.canvas.draw()\n col.remove()\n fig.canvas.draw()\n\n\n@image_comparison(['anchored_locator_base_call.png'], style="mpl20")\ndef test_anchored_locator_base_call():\n fig = plt.figure(figsize=(3, 3))\n fig1, fig2 = fig.subfigures(nrows=2, ncols=1)\n\n ax = fig1.subplots()\n ax.set(aspect=1, xlim=(-15, 15), ylim=(-20, 5))\n ax.set(xticks=[], yticks=[])\n\n Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")\n extent = (-3, 4, -4, 3)\n\n axins = zoomed_inset_axes(ax, zoom=2, loc="upper left")\n axins.set(xticks=[], yticks=[])\n\n axins.imshow(Z, extent=extent, origin="lower")\n\n\ndef test_grid_with_axes_class_not_overriding_axis():\n Grid(plt.figure(), 111, (2, 2), axes_class=mpl.axes.Axes)\n RGBAxes(plt.figure(), 111, axes_class=mpl.axes.Axes)\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\tests\test_axes_grid1.py | test_axes_grid1.py | Python | 29,093 | 0.95 | 0.088235 | 0.093846 | awesome-app | 628 | 2025-02-10T17:29:17.489914 | BSD-3-Clause | true | b33724071120dca9234b45c1f1bf3102 |
from pathlib import Path\n\n\n# Check that the test directories exist\nif not (Path(__file__).parent / "baseline_images").exists():\n raise OSError(\n 'The baseline image directory does not exist. '\n 'This is most likely because the test data is not installed. '\n 'You may need to install matplotlib from source to get the '\n 'test data.')\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\tests\__init__.py | __init__.py | Python | 365 | 0.95 | 0.1 | 0.125 | python-kit | 178 | 2024-03-11T15:02:55.095153 | GPL-3.0 | true | 58fdb0c615f036e99765a61f6b25a3a4 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\tests\__pycache__\conftest.cpython-313.pyc | conftest.cpython-313.pyc | Other | 341 | 0.7 | 0 | 0 | vue-tools | 347 | 2023-11-09T15:53:31.390888 | Apache-2.0 | true | 330945a2f5d905b4b47b8b4c71b6b665 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\tests\__pycache__\test_axes_grid1.cpython-313.pyc | test_axes_grid1.cpython-313.pyc | Other | 44,869 | 0.8 | 0.005263 | 0.066474 | node-utils | 46 | 2023-08-30T04:30:02.130718 | Apache-2.0 | true | 5c92325d481af4b148300cef1e0f47df |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\tests\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 622 | 0.7 | 0 | 0 | react-lib | 756 | 2024-09-22T10:09:26.126141 | GPL-3.0 | true | 0bc69001ed9823cea8d58718997e182a |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\anchored_artists.cpython-313.pyc | anchored_artists.cpython-313.pyc | Other | 15,758 | 0.95 | 0.071207 | 0.02349 | vue-tools | 734 | 2025-06-25T02:14:29.323613 | BSD-3-Clause | false | 6d1734d6f3539e5292f43934852cd45b |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\axes_divider.cpython-313.pyc | axes_divider.cpython-313.pyc | Other | 27,585 | 0.95 | 0.072674 | 0.018868 | awesome-app | 110 | 2025-07-08T15:14:54.858777 | GPL-3.0 | false | 0ac93c6efbc34de721fece78684e8124 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\axes_grid.cpython-313.pyc | axes_grid.cpython-313.pyc | Other | 27,763 | 0.95 | 0.028213 | 0 | python-kit | 669 | 2024-06-20T12:40:51.203815 | BSD-3-Clause | false | e5441685328093e9be17b421739feaff |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\axes_rgb.cpython-313.pyc | axes_rgb.cpython-313.pyc | Other | 7,592 | 0.95 | 0.095238 | 0.034783 | awesome-app | 864 | 2024-06-21T19:43:28.096085 | BSD-3-Clause | false | 8942e6e10ccffd49b859d461096d3dd2 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\axes_size.cpython-313.pyc | axes_size.cpython-313.pyc | Other | 13,111 | 0.95 | 0.025641 | 0 | vue-tools | 48 | 2025-02-05T19:38:45.610191 | MIT | false | 9e3c9f56016f813d5e4172f8ab53fe23 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\inset_locator.cpython-313.pyc | inset_locator.cpython-313.pyc | Other | 23,599 | 0.95 | 0.053619 | 0.070064 | vue-tools | 257 | 2024-01-22T09:13:23.087027 | GPL-3.0 | false | e5f4700a22b4daf3bb3b9483d74ab732 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\mpl_axes.cpython-313.pyc | mpl_axes.cpython-313.pyc | Other | 7,963 | 0.8 | 0 | 0 | node-utils | 241 | 2024-09-22T21:16:15.107059 | GPL-3.0 | false | 8f27e35a6fa21782d15dd0dd069e8bfa |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\parasite_axes.cpython-313.pyc | parasite_axes.cpython-313.pyc | Other | 13,136 | 0.95 | 0.019868 | 0.022059 | react-lib | 239 | 2023-11-01T00:07:07.619745 | GPL-3.0 | false | 91c9bf9fbdfa798b33f8c5552092f045 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axes_grid1\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 567 | 0.7 | 0 | 0 | vue-tools | 244 | 2024-08-20T02:12:10.292388 | BSD-3-Clause | false | 6ded4958595266b7e343df45bb8ad670 |
import numpy as np\nimport math\n\nfrom mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple\n\n\ndef select_step_degree(dv):\n\n degree_limits_ = [1.5, 3, 7, 13, 20, 40, 70, 120, 270, 520]\n degree_steps_ = [1, 2, 5, 10, 15, 30, 45, 90, 180, 360]\n degree_factors = [1.] * len(degree_steps_)\n\n minsec_limits_ = [1.5, 2.5, 3.5, 8, 11, 18, 25, 45]\n minsec_steps_ = [1, 2, 3, 5, 10, 15, 20, 30]\n\n minute_limits_ = np.array(minsec_limits_) / 60\n minute_factors = [60.] * len(minute_limits_)\n\n second_limits_ = np.array(minsec_limits_) / 3600\n second_factors = [3600.] * len(second_limits_)\n\n degree_limits = [*second_limits_, *minute_limits_, *degree_limits_]\n degree_steps = [*minsec_steps_, *minsec_steps_, *degree_steps_]\n degree_factors = [*second_factors, *minute_factors, *degree_factors]\n\n n = np.searchsorted(degree_limits, dv)\n step = degree_steps[n]\n factor = degree_factors[n]\n\n return step, factor\n\n\ndef select_step_hour(dv):\n\n hour_limits_ = [1.5, 2.5, 3.5, 5, 7, 10, 15, 21, 36]\n hour_steps_ = [1, 2, 3, 4, 6, 8, 12, 18, 24]\n hour_factors = [1.] * len(hour_steps_)\n\n minsec_limits_ = [1.5, 2.5, 3.5, 4.5, 5.5, 8, 11, 14, 18, 25, 45]\n minsec_steps_ = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]\n\n minute_limits_ = np.array(minsec_limits_) / 60\n minute_factors = [60.] * len(minute_limits_)\n\n second_limits_ = np.array(minsec_limits_) / 3600\n second_factors = [3600.] * len(second_limits_)\n\n hour_limits = [*second_limits_, *minute_limits_, *hour_limits_]\n hour_steps = [*minsec_steps_, *minsec_steps_, *hour_steps_]\n hour_factors = [*second_factors, *minute_factors, *hour_factors]\n\n n = np.searchsorted(hour_limits, dv)\n step = hour_steps[n]\n factor = hour_factors[n]\n\n return step, factor\n\n\ndef select_step_sub(dv):\n\n # subarcsec or degree\n tmp = 10.**(int(math.log10(dv))-1.)\n\n factor = 1./tmp\n\n if 1.5*tmp >= dv:\n step = 1\n elif 3.*tmp >= dv:\n step = 2\n elif 7.*tmp >= dv:\n step = 5\n else:\n step = 1\n factor = 0.1*factor\n\n return step, factor\n\n\ndef select_step(v1, v2, nv, hour=False, include_last=True,\n threshold_factor=3600.):\n\n if v1 > v2:\n v1, v2 = v2, v1\n\n dv = (v2 - v1) / nv\n\n if hour:\n _select_step = select_step_hour\n cycle = 24.\n else:\n _select_step = select_step_degree\n cycle = 360.\n\n # for degree\n if dv > 1 / threshold_factor:\n step, factor = _select_step(dv)\n else:\n step, factor = select_step_sub(dv*threshold_factor)\n\n factor = factor * threshold_factor\n\n levs = np.arange(np.floor(v1 * factor / step),\n np.ceil(v2 * factor / step) + 0.5,\n dtype=int) * step\n\n # n : number of valid levels. If there is a cycle, e.g., [0, 90, 180,\n # 270, 360], the grid line needs to be extended from 0 to 360, so\n # we need to return the whole array. However, the last level (360)\n # needs to be ignored often. In this case, so we return n=4.\n\n n = len(levs)\n\n # we need to check the range of values\n # for example, -90 to 90, 0 to 360,\n\n if factor == 1. and levs[-1] >= levs[0] + cycle: # check for cycle\n nv = int(cycle / step)\n if include_last:\n levs = levs[0] + np.arange(0, nv+1, 1) * step\n else:\n levs = levs[0] + np.arange(0, nv, 1) * step\n\n n = len(levs)\n\n return np.array(levs), n, factor\n\n\ndef select_step24(v1, v2, nv, include_last=True, threshold_factor=3600):\n v1, v2 = v1 / 15, v2 / 15\n levs, n, factor = select_step(v1, v2, nv, hour=True,\n include_last=include_last,\n threshold_factor=threshold_factor)\n return levs * 15, n, factor\n\n\ndef select_step360(v1, v2, nv, include_last=True, threshold_factor=3600):\n return select_step(v1, v2, nv, hour=False,\n include_last=include_last,\n threshold_factor=threshold_factor)\n\n\nclass LocatorBase:\n def __init__(self, nbins, include_last=True):\n self.nbins = nbins\n self._include_last = include_last\n\n def set_params(self, nbins=None):\n if nbins is not None:\n self.nbins = int(nbins)\n\n\nclass LocatorHMS(LocatorBase):\n def __call__(self, v1, v2):\n return select_step24(v1, v2, self.nbins, self._include_last)\n\n\nclass LocatorHM(LocatorBase):\n def __call__(self, v1, v2):\n return select_step24(v1, v2, self.nbins, self._include_last,\n threshold_factor=60)\n\n\nclass LocatorH(LocatorBase):\n def __call__(self, v1, v2):\n return select_step24(v1, v2, self.nbins, self._include_last,\n threshold_factor=1)\n\n\nclass LocatorDMS(LocatorBase):\n def __call__(self, v1, v2):\n return select_step360(v1, v2, self.nbins, self._include_last)\n\n\nclass LocatorDM(LocatorBase):\n def __call__(self, v1, v2):\n return select_step360(v1, v2, self.nbins, self._include_last,\n threshold_factor=60)\n\n\nclass LocatorD(LocatorBase):\n def __call__(self, v1, v2):\n return select_step360(v1, v2, self.nbins, self._include_last,\n threshold_factor=1)\n\n\nclass FormatterDMS:\n deg_mark = r"^{\circ}"\n min_mark = r"^{\prime}"\n sec_mark = r"^{\prime\prime}"\n\n fmt_d = "$%d" + deg_mark + "$"\n fmt_ds = r"$%d.%s" + deg_mark + "$"\n\n # %s for sign\n fmt_d_m = r"$%s%d" + deg_mark + r"\,%02d" + min_mark + "$"\n fmt_d_ms = r"$%s%d" + deg_mark + r"\,%02d.%s" + min_mark + "$"\n\n fmt_d_m_partial = "$%s%d" + deg_mark + r"\,%02d" + min_mark + r"\,"\n fmt_s_partial = "%02d" + sec_mark + "$"\n fmt_ss_partial = "%02d.%s" + sec_mark + "$"\n\n def _get_number_fraction(self, factor):\n ## check for fractional numbers\n number_fraction = None\n # check for 60\n\n for threshold in [1, 60, 3600]:\n if factor <= threshold:\n break\n\n d = factor // threshold\n int_log_d = int(np.floor(np.log10(d)))\n if 10**int_log_d == d and d != 1:\n number_fraction = int_log_d\n factor = factor // 10**int_log_d\n return factor, number_fraction\n\n return factor, number_fraction\n\n def __call__(self, direction, factor, values):\n if len(values) == 0:\n return []\n\n ss = np.sign(values)\n signs = ["-" if v < 0 else "" for v in values]\n\n factor, number_fraction = self._get_number_fraction(factor)\n\n values = np.abs(values)\n\n if number_fraction is not None:\n values, frac_part = divmod(values, 10 ** number_fraction)\n frac_fmt = "%%0%dd" % (number_fraction,)\n frac_str = [frac_fmt % (f1,) for f1 in frac_part]\n\n if factor == 1:\n if number_fraction is None:\n return [self.fmt_d % (s * int(v),) for s, v in zip(ss, values)]\n else:\n return [self.fmt_ds % (s * int(v), f1)\n for s, v, f1 in zip(ss, values, frac_str)]\n elif factor == 60:\n deg_part, min_part = divmod(values, 60)\n if number_fraction is None:\n return [self.fmt_d_m % (s1, d1, m1)\n for s1, d1, m1 in zip(signs, deg_part, min_part)]\n else:\n return [self.fmt_d_ms % (s, d1, m1, f1)\n for s, d1, m1, f1\n in zip(signs, deg_part, min_part, frac_str)]\n\n elif factor == 3600:\n if ss[-1] == -1:\n inverse_order = True\n values = values[::-1]\n signs = signs[::-1]\n else:\n inverse_order = False\n\n l_hm_old = ""\n r = []\n\n deg_part, min_part_ = divmod(values, 3600)\n min_part, sec_part = divmod(min_part_, 60)\n\n if number_fraction is None:\n sec_str = [self.fmt_s_partial % (s1,) for s1 in sec_part]\n else:\n sec_str = [self.fmt_ss_partial % (s1, f1)\n for s1, f1 in zip(sec_part, frac_str)]\n\n for s, d1, m1, s1 in zip(signs, deg_part, min_part, sec_str):\n l_hm = self.fmt_d_m_partial % (s, d1, m1)\n if l_hm != l_hm_old:\n l_hm_old = l_hm\n l = l_hm + s1\n else:\n l = "$" + s + s1\n r.append(l)\n\n if inverse_order:\n return r[::-1]\n else:\n return r\n\n else: # factor > 3600.\n return [r"$%s^{\circ}$" % v for v in ss*values]\n\n\nclass FormatterHMS(FormatterDMS):\n deg_mark = r"^\mathrm{h}"\n min_mark = r"^\mathrm{m}"\n sec_mark = r"^\mathrm{s}"\n\n fmt_d = "$%d" + deg_mark + "$"\n fmt_ds = r"$%d.%s" + deg_mark + "$"\n\n # %s for sign\n fmt_d_m = r"$%s%d" + deg_mark + r"\,%02d" + min_mark+"$"\n fmt_d_ms = r"$%s%d" + deg_mark + r"\,%02d.%s" + min_mark+"$"\n\n fmt_d_m_partial = "$%s%d" + deg_mark + r"\,%02d" + min_mark + r"\,"\n fmt_s_partial = "%02d" + sec_mark + "$"\n fmt_ss_partial = "%02d.%s" + sec_mark + "$"\n\n def __call__(self, direction, factor, values): # hour\n return super().__call__(direction, factor, np.asarray(values) / 15)\n\n\nclass ExtremeFinderCycle(ExtremeFinderSimple):\n # docstring inherited\n\n def __init__(self, nx, ny,\n lon_cycle=360., lat_cycle=None,\n lon_minmax=None, lat_minmax=(-90, 90)):\n """\n This subclass handles the case where one or both coordinates should be\n taken modulo 360, or be restricted to not exceed a specific range.\n\n Parameters\n ----------\n nx, ny : int\n The number of samples in each direction.\n\n lon_cycle, lat_cycle : 360 or None\n If not None, values in the corresponding direction are taken modulo\n *lon_cycle* or *lat_cycle*; in theory this can be any number but\n the implementation actually assumes that it is 360 (if not None);\n other values give nonsensical results.\n\n This is done by "unwrapping" the transformed grid coordinates so\n that jumps are less than a half-cycle; then normalizing the span to\n no more than a full cycle.\n\n For example, if values are in the union of the [0, 2] and\n [358, 360] intervals (typically, angles measured modulo 360), the\n values in the second interval are normalized to [-2, 0] instead so\n that the values now cover [-2, 2]. If values are in a range of\n [5, 1000], this gets normalized to [5, 365].\n\n lon_minmax, lat_minmax : (float, float) or None\n If not None, the computed bounding box is clipped to the given\n range in the corresponding direction.\n """\n self.nx, self.ny = nx, ny\n self.lon_cycle, self.lat_cycle = lon_cycle, lat_cycle\n self.lon_minmax = lon_minmax\n self.lat_minmax = lat_minmax\n\n def __call__(self, transform_xy, x1, y1, x2, y2):\n # docstring inherited\n x, y = np.meshgrid(\n np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny))\n lon, lat = transform_xy(np.ravel(x), np.ravel(y))\n\n # iron out jumps, but algorithm should be improved.\n # This is just naive way of doing and my fail for some cases.\n # Consider replacing this with numpy.unwrap\n # We are ignoring invalid warnings. They are triggered when\n # comparing arrays with NaNs using > We are already handling\n # that correctly using np.nanmin and np.nanmax\n with np.errstate(invalid='ignore'):\n if self.lon_cycle is not None:\n lon0 = np.nanmin(lon)\n lon -= 360. * ((lon - lon0) > 180.)\n if self.lat_cycle is not None:\n lat0 = np.nanmin(lat)\n lat -= 360. * ((lat - lat0) > 180.)\n\n lon_min, lon_max = np.nanmin(lon), np.nanmax(lon)\n lat_min, lat_max = np.nanmin(lat), np.nanmax(lat)\n\n lon_min, lon_max, lat_min, lat_max = \\n self._add_pad(lon_min, lon_max, lat_min, lat_max)\n\n # check cycle\n if self.lon_cycle:\n lon_max = min(lon_max, lon_min + self.lon_cycle)\n if self.lat_cycle:\n lat_max = min(lat_max, lat_min + self.lat_cycle)\n\n if self.lon_minmax is not None:\n min0 = self.lon_minmax[0]\n lon_min = max(min0, lon_min)\n max0 = self.lon_minmax[1]\n lon_max = min(max0, lon_max)\n\n if self.lat_minmax is not None:\n min0 = self.lat_minmax[0]\n lat_min = max(min0, lat_min)\n max0 = self.lat_minmax[1]\n lat_max = min(max0, lat_max)\n\n return lon_min, lon_max, lat_min, lat_max\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\angle_helper.py | angle_helper.py | Python | 12,952 | 0.95 | 0.190355 | 0.075342 | python-kit | 612 | 2023-11-06T12:58:22.303210 | BSD-3-Clause | false | 700322f454f796ebc5b17e8ba7708b3a |
from mpl_toolkits.axes_grid1.axes_divider import ( # noqa\n Divider, SubplotDivider, AxesDivider, make_axes_locatable)\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\axes_divider.py | axes_divider.py | Python | 122 | 0.95 | 0 | 0 | python-kit | 790 | 2024-05-10T05:20:13.046315 | Apache-2.0 | false | 33521ac2dec364811aaf2b5fe09a9704 |
"""\nAxislines includes modified implementation of the Axes class. The\nbiggest difference is that the artists responsible for drawing the axis spine,\nticks, ticklabels and axis labels are separated out from Matplotlib's Axis\nclass. Originally, this change was motivated to support curvilinear\ngrid. Here are a few reasons that I came up with a new axes class:\n\n* "top" and "bottom" x-axis (or "left" and "right" y-axis) can have\n different ticks (tick locations and labels). This is not possible\n with the current Matplotlib, although some twin axes trick can help.\n\n* Curvilinear grid.\n\n* angled ticks.\n\nIn the new axes class, xaxis and yaxis is set to not visible by\ndefault, and new set of artist (AxisArtist) are defined to draw axis\nline, ticks, ticklabels and axis label. Axes.axis attribute serves as\na dictionary of these artists, i.e., ax.axis["left"] is a AxisArtist\ninstance responsible to draw left y-axis. The default Axes.axis contains\n"bottom", "left", "top" and "right".\n\nAxisArtist can be considered as a container artist and has the following\nchildren artists which will draw ticks, labels, etc.\n\n* line\n* major_ticks, major_ticklabels\n* minor_ticks, minor_ticklabels\n* offsetText\n* label\n\nNote that these are separate artists from `matplotlib.axis.Axis`, thus most\ntick-related functions in Matplotlib won't work. For example, color and\nmarkerwidth of the ``ax.axis["bottom"].major_ticks`` will follow those of\nAxes.xaxis unless explicitly specified.\n\nIn addition to AxisArtist, the Axes will have *gridlines* attribute,\nwhich obviously draws grid lines. The gridlines needs to be separated\nfrom the axis as some gridlines can never pass any axis.\n"""\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api\nimport matplotlib.axes as maxes\nfrom matplotlib.path import Path\nfrom mpl_toolkits.axes_grid1 import mpl_axes\nfrom .axisline_style import AxislineStyle # noqa\nfrom .axis_artist import AxisArtist, GridlinesCollection\n\n\nclass _AxisArtistHelperBase:\n """\n Base class for axis helper.\n\n Subclasses should define the methods listed below. The *axes*\n argument will be the ``.axes`` attribute of the caller artist. ::\n\n # Construct the spine.\n\n def get_line_transform(self, axes):\n return transform\n\n def get_line(self, axes):\n return path\n\n # Construct the label.\n\n def get_axislabel_transform(self, axes):\n return transform\n\n def get_axislabel_pos_angle(self, axes):\n return (x, y), angle\n\n # Construct the ticks.\n\n def get_tick_transform(self, axes):\n return transform\n\n def get_tick_iterators(self, axes):\n # A pair of iterables (one for major ticks, one for minor ticks)\n # that yield (tick_position, tick_angle, tick_label).\n return iter_major, iter_minor\n """\n\n def __init__(self, nth_coord):\n self.nth_coord = nth_coord\n\n def update_lim(self, axes):\n pass\n\n def get_nth_coord(self):\n return self.nth_coord\n\n def _to_xy(self, values, const):\n """\n Create a (*values.shape, 2)-shape array representing (x, y) pairs.\n\n The other coordinate is filled with the constant *const*.\n\n Example::\n\n >>> self.nth_coord = 0\n >>> self._to_xy([1, 2, 3], const=0)\n array([[1, 0],\n [2, 0],\n [3, 0]])\n """\n if self.nth_coord == 0:\n return np.stack(np.broadcast_arrays(values, const), axis=-1)\n elif self.nth_coord == 1:\n return np.stack(np.broadcast_arrays(const, values), axis=-1)\n else:\n raise ValueError("Unexpected nth_coord")\n\n\nclass _FixedAxisArtistHelperBase(_AxisArtistHelperBase):\n """Helper class for a fixed (in the axes coordinate) axis."""\n\n @_api.delete_parameter("3.9", "nth_coord")\n def __init__(self, loc, nth_coord=None):\n """``nth_coord = 0``: x-axis; ``nth_coord = 1``: y-axis."""\n super().__init__(_api.check_getitem(\n {"bottom": 0, "top": 0, "left": 1, "right": 1}, loc=loc))\n self._loc = loc\n self._pos = {"bottom": 0, "top": 1, "left": 0, "right": 1}[loc]\n # axis line in transAxes\n self._path = Path(self._to_xy((0, 1), const=self._pos))\n\n # LINE\n\n def get_line(self, axes):\n return self._path\n\n def get_line_transform(self, axes):\n return axes.transAxes\n\n # LABEL\n\n def get_axislabel_transform(self, axes):\n return axes.transAxes\n\n def get_axislabel_pos_angle(self, axes):\n """\n Return the label reference position in transAxes.\n\n get_label_transform() returns a transform of (transAxes+offset)\n """\n return dict(left=((0., 0.5), 90), # (position, angle_tangent)\n right=((1., 0.5), 90),\n bottom=((0.5, 0.), 0),\n top=((0.5, 1.), 0))[self._loc]\n\n # TICK\n\n def get_tick_transform(self, axes):\n return [axes.get_xaxis_transform(), axes.get_yaxis_transform()][self.nth_coord]\n\n\nclass _FloatingAxisArtistHelperBase(_AxisArtistHelperBase):\n def __init__(self, nth_coord, value):\n self._value = value\n super().__init__(nth_coord)\n\n def get_line(self, axes):\n raise RuntimeError("get_line method should be defined by the derived class")\n\n\nclass FixedAxisArtistHelperRectilinear(_FixedAxisArtistHelperBase):\n\n @_api.delete_parameter("3.9", "nth_coord")\n def __init__(self, axes, loc, nth_coord=None):\n """\n nth_coord = along which coordinate value varies\n in 2D, nth_coord = 0 -> x axis, nth_coord = 1 -> y axis\n """\n super().__init__(loc)\n self.axis = [axes.xaxis, axes.yaxis][self.nth_coord]\n\n # TICK\n\n def get_tick_iterators(self, axes):\n """tick_loc, tick_angle, tick_label"""\n angle_normal, angle_tangent = {0: (90, 0), 1: (0, 90)}[self.nth_coord]\n\n major = self.axis.major\n major_locs = major.locator()\n major_labels = major.formatter.format_ticks(major_locs)\n\n minor = self.axis.minor\n minor_locs = minor.locator()\n minor_labels = minor.formatter.format_ticks(minor_locs)\n\n tick_to_axes = self.get_tick_transform(axes) - axes.transAxes\n\n def _f(locs, labels):\n for loc, label in zip(locs, labels):\n c = self._to_xy(loc, const=self._pos)\n # check if the tick point is inside axes\n c2 = tick_to_axes.transform(c)\n if mpl.transforms._interval_contains_close((0, 1), c2[self.nth_coord]):\n yield c, angle_normal, angle_tangent, label\n\n return _f(major_locs, major_labels), _f(minor_locs, minor_labels)\n\n\nclass FloatingAxisArtistHelperRectilinear(_FloatingAxisArtistHelperBase):\n\n def __init__(self, axes, nth_coord,\n passingthrough_point, axis_direction="bottom"):\n super().__init__(nth_coord, passingthrough_point)\n self._axis_direction = axis_direction\n self.axis = [axes.xaxis, axes.yaxis][self.nth_coord]\n\n def get_line(self, axes):\n fixed_coord = 1 - self.nth_coord\n data_to_axes = axes.transData - axes.transAxes\n p = data_to_axes.transform([self._value, self._value])\n return Path(self._to_xy((0, 1), const=p[fixed_coord]))\n\n def get_line_transform(self, axes):\n return axes.transAxes\n\n def get_axislabel_transform(self, axes):\n return axes.transAxes\n\n def get_axislabel_pos_angle(self, axes):\n """\n Return the label reference position in transAxes.\n\n get_label_transform() returns a transform of (transAxes+offset)\n """\n angle = [0, 90][self.nth_coord]\n fixed_coord = 1 - self.nth_coord\n data_to_axes = axes.transData - axes.transAxes\n p = data_to_axes.transform([self._value, self._value])\n verts = self._to_xy(0.5, const=p[fixed_coord])\n return (verts, angle) if 0 <= verts[fixed_coord] <= 1 else (None, None)\n\n def get_tick_transform(self, axes):\n return axes.transData\n\n def get_tick_iterators(self, axes):\n """tick_loc, tick_angle, tick_label"""\n angle_normal, angle_tangent = {0: (90, 0), 1: (0, 90)}[self.nth_coord]\n\n major = self.axis.major\n major_locs = major.locator()\n major_labels = major.formatter.format_ticks(major_locs)\n\n minor = self.axis.minor\n minor_locs = minor.locator()\n minor_labels = minor.formatter.format_ticks(minor_locs)\n\n data_to_axes = axes.transData - axes.transAxes\n\n def _f(locs, labels):\n for loc, label in zip(locs, labels):\n c = self._to_xy(loc, const=self._value)\n c1, c2 = data_to_axes.transform(c)\n if 0 <= c1 <= 1 and 0 <= c2 <= 1:\n yield c, angle_normal, angle_tangent, label\n\n return _f(major_locs, major_labels), _f(minor_locs, minor_labels)\n\n\nclass AxisArtistHelper: # Backcompat.\n Fixed = _FixedAxisArtistHelperBase\n Floating = _FloatingAxisArtistHelperBase\n\n\nclass AxisArtistHelperRectlinear: # Backcompat.\n Fixed = FixedAxisArtistHelperRectilinear\n Floating = FloatingAxisArtistHelperRectilinear\n\n\nclass GridHelperBase:\n\n def __init__(self):\n self._old_limits = None\n super().__init__()\n\n def update_lim(self, axes):\n x1, x2 = axes.get_xlim()\n y1, y2 = axes.get_ylim()\n if self._old_limits != (x1, x2, y1, y2):\n self._update_grid(x1, y1, x2, y2)\n self._old_limits = (x1, x2, y1, y2)\n\n def _update_grid(self, x1, y1, x2, y2):\n """Cache relevant computations when the axes limits have changed."""\n\n def get_gridlines(self, which, axis):\n """\n Return list of grid lines as a list of paths (list of points).\n\n Parameters\n ----------\n which : {"both", "major", "minor"}\n axis : {"both", "x", "y"}\n """\n return []\n\n\nclass GridHelperRectlinear(GridHelperBase):\n\n def __init__(self, axes):\n super().__init__()\n self.axes = axes\n\n @_api.delete_parameter(\n "3.9", "nth_coord", addendum="'nth_coord' is now inferred from 'loc'.")\n def new_fixed_axis(\n self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None):\n if axes is None:\n _api.warn_external(\n "'new_fixed_axis' explicitly requires the axes keyword.")\n axes = self.axes\n if axis_direction is None:\n axis_direction = loc\n return AxisArtist(axes, FixedAxisArtistHelperRectilinear(axes, loc),\n offset=offset, axis_direction=axis_direction)\n\n def new_floating_axis(self, nth_coord, value, axis_direction="bottom", axes=None):\n if axes is None:\n _api.warn_external(\n "'new_floating_axis' explicitly requires the axes keyword.")\n axes = self.axes\n helper = FloatingAxisArtistHelperRectilinear(\n axes, nth_coord, value, axis_direction)\n axisline = AxisArtist(axes, helper, axis_direction=axis_direction)\n axisline.line.set_clip_on(True)\n axisline.line.set_clip_box(axisline.axes.bbox)\n return axisline\n\n def get_gridlines(self, which="major", axis="both"):\n """\n Return list of gridline coordinates in data coordinates.\n\n Parameters\n ----------\n which : {"both", "major", "minor"}\n axis : {"both", "x", "y"}\n """\n _api.check_in_list(["both", "major", "minor"], which=which)\n _api.check_in_list(["both", "x", "y"], axis=axis)\n gridlines = []\n\n if axis in ("both", "x"):\n locs = []\n y1, y2 = self.axes.get_ylim()\n if which in ("both", "major"):\n locs.extend(self.axes.xaxis.major.locator())\n if which in ("both", "minor"):\n locs.extend(self.axes.xaxis.minor.locator())\n gridlines.extend([[x, x], [y1, y2]] for x in locs)\n\n if axis in ("both", "y"):\n x1, x2 = self.axes.get_xlim()\n locs = []\n if self.axes.yaxis._major_tick_kw["gridOn"]:\n locs.extend(self.axes.yaxis.major.locator())\n if self.axes.yaxis._minor_tick_kw["gridOn"]:\n locs.extend(self.axes.yaxis.minor.locator())\n gridlines.extend([[x1, x2], [y, y]] for y in locs)\n\n return gridlines\n\n\nclass Axes(maxes.Axes):\n\n def __init__(self, *args, grid_helper=None, **kwargs):\n self._axisline_on = True\n self._grid_helper = grid_helper if grid_helper else GridHelperRectlinear(self)\n super().__init__(*args, **kwargs)\n self.toggle_axisline(True)\n\n def toggle_axisline(self, b=None):\n if b is None:\n b = not self._axisline_on\n if b:\n self._axisline_on = True\n self.spines[:].set_visible(False)\n self.xaxis.set_visible(False)\n self.yaxis.set_visible(False)\n else:\n self._axisline_on = False\n self.spines[:].set_visible(True)\n self.xaxis.set_visible(True)\n self.yaxis.set_visible(True)\n\n @property\n def axis(self):\n return self._axislines\n\n def clear(self):\n # docstring inherited\n\n # Init gridlines before clear() as clear() calls grid().\n self.gridlines = gridlines = GridlinesCollection(\n [],\n colors=mpl.rcParams['grid.color'],\n linestyles=mpl.rcParams['grid.linestyle'],\n linewidths=mpl.rcParams['grid.linewidth'])\n self._set_artist_props(gridlines)\n gridlines.set_grid_helper(self.get_grid_helper())\n\n super().clear()\n\n # clip_path is set after Axes.clear(): that's when a patch is created.\n gridlines.set_clip_path(self.axes.patch)\n\n # Init axis artists.\n self._axislines = mpl_axes.Axes.AxisDict(self)\n new_fixed_axis = self.get_grid_helper().new_fixed_axis\n self._axislines.update({\n loc: new_fixed_axis(loc=loc, axes=self, axis_direction=loc)\n for loc in ["bottom", "top", "left", "right"]})\n for axisline in [self._axislines["top"], self._axislines["right"]]:\n axisline.label.set_visible(False)\n axisline.major_ticklabels.set_visible(False)\n axisline.minor_ticklabels.set_visible(False)\n\n def get_grid_helper(self):\n return self._grid_helper\n\n def grid(self, visible=None, which='major', axis="both", **kwargs):\n """\n Toggle the gridlines, and optionally set the properties of the lines.\n """\n # There are some discrepancies in the behavior of grid() between\n # axes_grid and Matplotlib, because axes_grid explicitly sets the\n # visibility of the gridlines.\n super().grid(visible, which=which, axis=axis, **kwargs)\n if not self._axisline_on:\n return\n if visible is None:\n visible = (self.axes.xaxis._minor_tick_kw["gridOn"]\n or self.axes.xaxis._major_tick_kw["gridOn"]\n or self.axes.yaxis._minor_tick_kw["gridOn"]\n or self.axes.yaxis._major_tick_kw["gridOn"])\n self.gridlines.set(which=which, axis=axis, visible=visible)\n self.gridlines.set(**kwargs)\n\n def get_children(self):\n if self._axisline_on:\n children = [*self._axislines.values(), self.gridlines]\n else:\n children = []\n children.extend(super().get_children())\n return children\n\n def new_fixed_axis(self, loc, offset=None):\n return self.get_grid_helper().new_fixed_axis(loc, offset=offset, axes=self)\n\n def new_floating_axis(self, nth_coord, value, axis_direction="bottom"):\n return self.get_grid_helper().new_floating_axis(\n nth_coord, value, axis_direction=axis_direction, axes=self)\n\n\nclass AxesZero(Axes):\n\n def clear(self):\n super().clear()\n new_floating_axis = self.get_grid_helper().new_floating_axis\n self._axislines.update(\n xzero=new_floating_axis(\n nth_coord=0, value=0., axis_direction="bottom", axes=self),\n yzero=new_floating_axis(\n nth_coord=1, value=0., axis_direction="left", axes=self),\n )\n for k in ["xzero", "yzero"]:\n self._axislines[k].line.set_clip_path(self.patch)\n self._axislines[k].set_visible(False)\n\n\nSubplot = Axes\nSubplotZero = AxesZero\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\axislines.py | axislines.py | Python | 16,556 | 0.95 | 0.204593 | 0.070461 | vue-tools | 42 | 2025-01-02T05:01:38.199935 | GPL-3.0 | false | e6e82b8b66a8c089cda5a9ef0a4aa7bd |
"""\nProvides classes to style the axis lines.\n"""\nimport math\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib.patches import _Style, FancyArrowPatch\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import IdentityTransform\n\n\nclass _FancyAxislineStyle:\n class SimpleArrow(FancyArrowPatch):\n """The artist class that will be returned for SimpleArrow style."""\n _ARROW_STYLE = "->"\n\n def __init__(self, axis_artist, line_path, transform,\n line_mutation_scale):\n self._axis_artist = axis_artist\n self._line_transform = transform\n self._line_path = line_path\n self._line_mutation_scale = line_mutation_scale\n\n FancyArrowPatch.__init__(self,\n path=self._line_path,\n arrowstyle=self._ARROW_STYLE,\n patchA=None,\n patchB=None,\n shrinkA=0.,\n shrinkB=0.,\n mutation_scale=line_mutation_scale,\n mutation_aspect=None,\n transform=IdentityTransform(),\n )\n\n def set_line_mutation_scale(self, scale):\n self.set_mutation_scale(scale*self._line_mutation_scale)\n\n def _extend_path(self, path, mutation_size=10):\n """\n Extend the path to make a room for drawing arrow.\n """\n (x0, y0), (x1, y1) = path.vertices[-2:]\n theta = math.atan2(y1 - y0, x1 - x0)\n x2 = x1 + math.cos(theta) * mutation_size\n y2 = y1 + math.sin(theta) * mutation_size\n if path.codes is None:\n return Path(np.concatenate([path.vertices, [[x2, y2]]]))\n else:\n return Path(np.concatenate([path.vertices, [[x2, y2]]]),\n np.concatenate([path.codes, [Path.LINETO]]))\n\n def set_path(self, path):\n self._line_path = path\n\n def draw(self, renderer):\n """\n Draw the axis line.\n 1) Transform the path to the display coordinate.\n 2) Extend the path to make a room for arrow.\n 3) Update the path of the FancyArrowPatch.\n 4) Draw.\n """\n path_in_disp = self._line_transform.transform_path(self._line_path)\n mutation_size = self.get_mutation_scale() # line_mutation_scale()\n extended_path = self._extend_path(path_in_disp,\n mutation_size=mutation_size)\n self._path_original = extended_path\n FancyArrowPatch.draw(self, renderer)\n\n def get_window_extent(self, renderer=None):\n\n path_in_disp = self._line_transform.transform_path(self._line_path)\n mutation_size = self.get_mutation_scale() # line_mutation_scale()\n extended_path = self._extend_path(path_in_disp,\n mutation_size=mutation_size)\n self._path_original = extended_path\n return FancyArrowPatch.get_window_extent(self, renderer)\n\n class FilledArrow(SimpleArrow):\n """The artist class that will be returned for FilledArrow style."""\n _ARROW_STYLE = "-|>"\n\n def __init__(self, axis_artist, line_path, transform,\n line_mutation_scale, facecolor):\n super().__init__(axis_artist, line_path, transform,\n line_mutation_scale)\n self.set_facecolor(facecolor)\n\n\nclass AxislineStyle(_Style):\n """\n A container class which defines style classes for AxisArtists.\n\n An instance of any axisline style class is a callable object,\n whose call signature is ::\n\n __call__(self, axis_artist, path, transform)\n\n When called, this should return an `.Artist` with the following methods::\n\n def set_path(self, path):\n # set the path for axisline.\n\n def set_line_mutation_scale(self, scale):\n # set the scale\n\n def draw(self, renderer):\n # draw\n """\n\n _style_list = {}\n\n class _Base:\n # The derived classes are required to be able to be initialized\n # w/o arguments, i.e., all its argument (except self) must have\n # the default values.\n\n def __init__(self):\n """\n initialization.\n """\n super().__init__()\n\n def __call__(self, axis_artist, transform):\n """\n Given the AxisArtist instance, and transform for the path (set_path\n method), return the Matplotlib artist for drawing the axis line.\n """\n return self.new_line(axis_artist, transform)\n\n class SimpleArrow(_Base):\n """\n A simple arrow.\n """\n\n ArrowAxisClass = _FancyAxislineStyle.SimpleArrow\n\n def __init__(self, size=1):\n """\n Parameters\n ----------\n size : float\n Size of the arrow as a fraction of the ticklabel size.\n """\n\n self.size = size\n super().__init__()\n\n def new_line(self, axis_artist, transform):\n\n linepath = Path([(0, 0), (0, 1)])\n axisline = self.ArrowAxisClass(axis_artist, linepath, transform,\n line_mutation_scale=self.size)\n return axisline\n\n _style_list["->"] = SimpleArrow\n\n class FilledArrow(SimpleArrow):\n """\n An arrow with a filled head.\n """\n\n ArrowAxisClass = _FancyAxislineStyle.FilledArrow\n\n def __init__(self, size=1, facecolor=None):\n """\n Parameters\n ----------\n size : float\n Size of the arrow as a fraction of the ticklabel size.\n facecolor : :mpltype:`color`, default: :rc:`axes.edgecolor`\n Fill color.\n\n .. versionadded:: 3.7\n """\n\n if facecolor is None:\n facecolor = mpl.rcParams['axes.edgecolor']\n self.size = size\n self._facecolor = facecolor\n super().__init__(size=size)\n\n def new_line(self, axis_artist, transform):\n linepath = Path([(0, 0), (0, 1)])\n axisline = self.ArrowAxisClass(axis_artist, linepath, transform,\n line_mutation_scale=self.size,\n facecolor=self._facecolor)\n return axisline\n\n _style_list["-|>"] = FilledArrow\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\axisline_style.py | axisline_style.py | Python | 6,723 | 0.95 | 0.19171 | 0.039216 | vue-tools | 355 | 2025-04-21T01:28:12.745439 | GPL-3.0 | false | 8b9031b07cdb3bbaeb0232d851ca2812 |
"""\nThe :mod:`.axis_artist` module implements custom artists to draw axis elements\n(axis lines and labels, tick lines and labels, grid lines).\n\nAxis lines and labels and tick lines and labels are managed by the `AxisArtist`\nclass; grid lines are managed by the `GridlinesCollection` class.\n\nThere is one `AxisArtist` per Axis; it can be accessed through\nthe ``axis`` dictionary of the parent Axes (which should be a\n`mpl_toolkits.axislines.Axes`), e.g. ``ax.axis["bottom"]``.\n\nChildren of the AxisArtist are accessed as attributes: ``.line`` and ``.label``\nfor the axis line and label, ``.major_ticks``, ``.major_ticklabels``,\n``.minor_ticks``, ``.minor_ticklabels`` for the tick lines and labels (e.g.\n``ax.axis["bottom"].line``).\n\nChildren properties (colors, fonts, line widths, etc.) can be set using\nsetters, e.g. ::\n\n # Make the major ticks of the bottom axis red.\n ax.axis["bottom"].major_ticks.set_color("red")\n\nHowever, things like the locations of ticks, and their ticklabels need to be\nchanged from the side of the grid_helper.\n\naxis_direction\n--------------\n\n`AxisArtist`, `AxisLabel`, `TickLabels` have an *axis_direction* attribute,\nwhich adjusts the location, angle, etc. The *axis_direction* must be one of\n"left", "right", "bottom", "top", and follows the Matplotlib convention for\nrectangular axis.\n\nFor example, for the *bottom* axis (the left and right is relative to the\ndirection of the increasing coordinate),\n\n* ticklabels and axislabel are on the right\n* ticklabels and axislabel have text angle of 0\n* ticklabels are baseline, center-aligned\n* axislabel is top, center-aligned\n\nThe text angles are actually relative to (90 + angle of the direction to the\nticklabel), which gives 0 for bottom axis.\n\n=================== ====== ======== ====== ========\nProperty left bottom right top\n=================== ====== ======== ====== ========\nticklabel location left right right left\naxislabel location left right right left\nticklabel angle 90 0 -90 180\naxislabel angle 180 0 0 180\nticklabel va center baseline center baseline\naxislabel va center top center bottom\nticklabel ha right center right center\naxislabel ha right center right center\n=================== ====== ======== ====== ========\n\nTicks are by default direct opposite side of the ticklabels. To make ticks to\nthe same side of the ticklabels, ::\n\n ax.axis["bottom"].major_ticks.set_tick_out(True)\n\nThe following attributes can be customized (use the ``set_xxx`` methods):\n\n* `Ticks`: ticksize, tick_out\n* `TickLabels`: pad\n* `AxisLabel`: pad\n"""\n\n# FIXME :\n# angles are given in data coordinate - need to convert it to canvas coordinate\n\n\nfrom operator import methodcaller\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api, cbook\nimport matplotlib.artist as martist\nimport matplotlib.colors as mcolors\nimport matplotlib.text as mtext\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import PathPatch\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import (\n Affine2D, Bbox, IdentityTransform, ScaledTranslation)\n\nfrom .axisline_style import AxislineStyle\n\n\nclass AttributeCopier:\n def get_ref_artist(self):\n """\n Return the underlying artist that actually defines some properties\n (e.g., color) of this artist.\n """\n raise RuntimeError("get_ref_artist must overridden")\n\n def get_attribute_from_ref_artist(self, attr_name):\n getter = methodcaller("get_" + attr_name)\n prop = getter(super())\n return getter(self.get_ref_artist()) if prop == "auto" else prop\n\n\nclass Ticks(AttributeCopier, Line2D):\n """\n Ticks are derived from `.Line2D`, and note that ticks themselves\n are markers. Thus, you should use set_mec, set_mew, etc.\n\n To change the tick size (length), you need to use\n `set_ticksize`. To change the direction of the ticks (ticks are\n in opposite direction of ticklabels by default), use\n ``set_tick_out(False)``\n """\n\n def __init__(self, ticksize, tick_out=False, *, axis=None, **kwargs):\n self._ticksize = ticksize\n self.locs_angles_labels = []\n\n self.set_tick_out(tick_out)\n\n self._axis = axis\n if self._axis is not None:\n if "color" not in kwargs:\n kwargs["color"] = "auto"\n if "mew" not in kwargs and "markeredgewidth" not in kwargs:\n kwargs["markeredgewidth"] = "auto"\n\n Line2D.__init__(self, [0.], [0.], **kwargs)\n self.set_snap(True)\n\n def get_ref_artist(self):\n # docstring inherited\n return self._axis.majorTicks[0].tick1line\n\n def set_color(self, color):\n # docstring inherited\n # Unlike the base Line2D.set_color, this also supports "auto".\n if not cbook._str_equal(color, "auto"):\n mcolors._check_color_like(color=color)\n self._color = color\n self.stale = True\n\n def get_color(self):\n return self.get_attribute_from_ref_artist("color")\n\n def get_markeredgecolor(self):\n return self.get_attribute_from_ref_artist("markeredgecolor")\n\n def get_markeredgewidth(self):\n return self.get_attribute_from_ref_artist("markeredgewidth")\n\n def set_tick_out(self, b):\n """Set whether ticks are drawn inside or outside the axes."""\n self._tick_out = b\n\n def get_tick_out(self):\n """Return whether ticks are drawn inside or outside the axes."""\n return self._tick_out\n\n def set_ticksize(self, ticksize):\n """Set length of the ticks in points."""\n self._ticksize = ticksize\n\n def get_ticksize(self):\n """Return length of the ticks in points."""\n return self._ticksize\n\n def set_locs_angles(self, locs_angles):\n self.locs_angles = locs_angles\n\n _tickvert_path = Path([[0., 0.], [1., 0.]])\n\n def draw(self, renderer):\n if not self.get_visible():\n return\n\n gc = renderer.new_gc()\n gc.set_foreground(self.get_markeredgecolor())\n gc.set_linewidth(self.get_markeredgewidth())\n gc.set_alpha(self._alpha)\n\n path_trans = self.get_transform()\n marker_transform = (Affine2D()\n .scale(renderer.points_to_pixels(self._ticksize)))\n if self.get_tick_out():\n marker_transform.rotate_deg(180)\n\n for loc, angle in self.locs_angles:\n locs = path_trans.transform_non_affine(np.array([loc]))\n if self.axes and not self.axes.viewLim.contains(*locs[0]):\n continue\n renderer.draw_markers(\n gc, self._tickvert_path,\n marker_transform + Affine2D().rotate_deg(angle),\n Path(locs), path_trans.get_affine())\n\n gc.restore()\n\n\nclass LabelBase(mtext.Text):\n """\n A base class for `.AxisLabel` and `.TickLabels`. The position and\n angle of the text are calculated by the offset_ref_angle,\n text_ref_angle, and offset_radius attributes.\n """\n\n def __init__(self, *args, **kwargs):\n self.locs_angles_labels = []\n self._ref_angle = 0\n self._offset_radius = 0.\n\n super().__init__(*args, **kwargs)\n\n self.set_rotation_mode("anchor")\n self._text_follow_ref_angle = True\n\n @property\n def _text_ref_angle(self):\n if self._text_follow_ref_angle:\n return self._ref_angle + 90\n else:\n return 0\n\n @property\n def _offset_ref_angle(self):\n return self._ref_angle\n\n _get_opposite_direction = {"left": "right",\n "right": "left",\n "top": "bottom",\n "bottom": "top"}.__getitem__\n\n def draw(self, renderer):\n if not self.get_visible():\n return\n\n # save original and adjust some properties\n tr = self.get_transform()\n angle_orig = self.get_rotation()\n theta = np.deg2rad(self._offset_ref_angle)\n dd = self._offset_radius\n dx, dy = dd * np.cos(theta), dd * np.sin(theta)\n\n self.set_transform(tr + Affine2D().translate(dx, dy))\n self.set_rotation(self._text_ref_angle + angle_orig)\n super().draw(renderer)\n # restore original properties\n self.set_transform(tr)\n self.set_rotation(angle_orig)\n\n def get_window_extent(self, renderer=None):\n if renderer is None:\n renderer = self.get_figure(root=True)._get_renderer()\n\n # save original and adjust some properties\n tr = self.get_transform()\n angle_orig = self.get_rotation()\n theta = np.deg2rad(self._offset_ref_angle)\n dd = self._offset_radius\n dx, dy = dd * np.cos(theta), dd * np.sin(theta)\n\n self.set_transform(tr + Affine2D().translate(dx, dy))\n self.set_rotation(self._text_ref_angle + angle_orig)\n bbox = super().get_window_extent(renderer).frozen()\n # restore original properties\n self.set_transform(tr)\n self.set_rotation(angle_orig)\n\n return bbox\n\n\nclass AxisLabel(AttributeCopier, LabelBase):\n """\n Axis label. Derived from `.Text`. The position of the text is updated\n in the fly, so changing text position has no effect. Otherwise, the\n properties can be changed as a normal `.Text`.\n\n To change the pad between tick labels and axis label, use `set_pad`.\n """\n\n def __init__(self, *args, axis_direction="bottom", axis=None, **kwargs):\n self._axis = axis\n self._pad = 5\n self._external_pad = 0 # in pixels\n LabelBase.__init__(self, *args, **kwargs)\n self.set_axis_direction(axis_direction)\n\n def set_pad(self, pad):\n """\n Set the internal pad in points.\n\n The actual pad will be the sum of the internal pad and the\n external pad (the latter is set automatically by the `.AxisArtist`).\n\n Parameters\n ----------\n pad : float\n The internal pad in points.\n """\n self._pad = pad\n\n def get_pad(self):\n """\n Return the internal pad in points.\n\n See `.set_pad` for more details.\n """\n return self._pad\n\n def get_ref_artist(self):\n # docstring inherited\n return self._axis.label\n\n def get_text(self):\n # docstring inherited\n t = super().get_text()\n if t == "__from_axes__":\n return self._axis.label.get_text()\n return self._text\n\n _default_alignments = dict(left=("bottom", "center"),\n right=("top", "center"),\n bottom=("top", "center"),\n top=("bottom", "center"))\n\n def set_default_alignment(self, d):\n """\n Set the default alignment. See `set_axis_direction` for details.\n\n Parameters\n ----------\n d : {"left", "bottom", "right", "top"}\n """\n va, ha = _api.check_getitem(self._default_alignments, d=d)\n self.set_va(va)\n self.set_ha(ha)\n\n _default_angles = dict(left=180,\n right=0,\n bottom=0,\n top=180)\n\n def set_default_angle(self, d):\n """\n Set the default angle. See `set_axis_direction` for details.\n\n Parameters\n ----------\n d : {"left", "bottom", "right", "top"}\n """\n self.set_rotation(_api.check_getitem(self._default_angles, d=d))\n\n def set_axis_direction(self, d):\n """\n Adjust the text angle and text alignment of axis label\n according to the matplotlib convention.\n\n ===================== ========== ========= ========== ==========\n Property left bottom right top\n ===================== ========== ========= ========== ==========\n axislabel angle 180 0 0 180\n axislabel va center top center bottom\n axislabel ha right center right center\n ===================== ========== ========= ========== ==========\n\n Note that the text angles are actually relative to (90 + angle\n of the direction to the ticklabel), which gives 0 for bottom\n axis.\n\n Parameters\n ----------\n d : {"left", "bottom", "right", "top"}\n """\n self.set_default_alignment(d)\n self.set_default_angle(d)\n\n def get_color(self):\n return self.get_attribute_from_ref_artist("color")\n\n def draw(self, renderer):\n if not self.get_visible():\n return\n\n self._offset_radius = \\n self._external_pad + renderer.points_to_pixels(self.get_pad())\n\n super().draw(renderer)\n\n def get_window_extent(self, renderer=None):\n if renderer is None:\n renderer = self.get_figure(root=True)._get_renderer()\n if not self.get_visible():\n return\n\n r = self._external_pad + renderer.points_to_pixels(self.get_pad())\n self._offset_radius = r\n\n bb = super().get_window_extent(renderer)\n\n return bb\n\n\nclass TickLabels(AxisLabel): # mtext.Text\n """\n Tick labels. While derived from `.Text`, this single artist draws all\n ticklabels. As in `.AxisLabel`, the position of the text is updated\n in the fly, so changing text position has no effect. Otherwise,\n the properties can be changed as a normal `.Text`. Unlike the\n ticklabels of the mainline Matplotlib, properties of a single\n ticklabel alone cannot be modified.\n\n To change the pad between ticks and ticklabels, use `~.AxisLabel.set_pad`.\n """\n\n def __init__(self, *, axis_direction="bottom", **kwargs):\n super().__init__(**kwargs)\n self.set_axis_direction(axis_direction)\n self._axislabel_pad = 0\n\n def get_ref_artist(self):\n # docstring inherited\n return self._axis.get_ticklabels()[0]\n\n def set_axis_direction(self, label_direction):\n """\n Adjust the text angle and text alignment of ticklabels\n according to the Matplotlib convention.\n\n The *label_direction* must be one of [left, right, bottom, top].\n\n ===================== ========== ========= ========== ==========\n Property left bottom right top\n ===================== ========== ========= ========== ==========\n ticklabel angle 90 0 -90 180\n ticklabel va center baseline center baseline\n ticklabel ha right center right center\n ===================== ========== ========= ========== ==========\n\n Note that the text angles are actually relative to (90 + angle\n of the direction to the ticklabel), which gives 0 for bottom\n axis.\n\n Parameters\n ----------\n label_direction : {"left", "bottom", "right", "top"}\n\n """\n self.set_default_alignment(label_direction)\n self.set_default_angle(label_direction)\n self._axis_direction = label_direction\n\n def invert_axis_direction(self):\n label_direction = self._get_opposite_direction(self._axis_direction)\n self.set_axis_direction(label_direction)\n\n def _get_ticklabels_offsets(self, renderer, label_direction):\n """\n Calculate the ticklabel offsets from the tick and their total heights.\n\n The offset only takes account the offset due to the vertical alignment\n of the ticklabels: if axis direction is bottom and va is 'top', it will\n return 0; if va is 'baseline', it will return (height-descent).\n """\n whd_list = self.get_texts_widths_heights_descents(renderer)\n\n if not whd_list:\n return 0, 0\n\n r = 0\n va, ha = self.get_va(), self.get_ha()\n\n if label_direction == "left":\n pad = max(w for w, h, d in whd_list)\n if ha == "left":\n r = pad\n elif ha == "center":\n r = .5 * pad\n elif label_direction == "right":\n pad = max(w for w, h, d in whd_list)\n if ha == "right":\n r = pad\n elif ha == "center":\n r = .5 * pad\n elif label_direction == "bottom":\n pad = max(h for w, h, d in whd_list)\n if va == "bottom":\n r = pad\n elif va == "center":\n r = .5 * pad\n elif va == "baseline":\n max_ascent = max(h - d for w, h, d in whd_list)\n max_descent = max(d for w, h, d in whd_list)\n r = max_ascent\n pad = max_ascent + max_descent\n elif label_direction == "top":\n pad = max(h for w, h, d in whd_list)\n if va == "top":\n r = pad\n elif va == "center":\n r = .5 * pad\n elif va == "baseline":\n max_ascent = max(h - d for w, h, d in whd_list)\n max_descent = max(d for w, h, d in whd_list)\n r = max_descent\n pad = max_ascent + max_descent\n\n # r : offset\n # pad : total height of the ticklabels. This will be used to\n # calculate the pad for the axislabel.\n return r, pad\n\n _default_alignments = dict(left=("center", "right"),\n right=("center", "left"),\n bottom=("baseline", "center"),\n top=("baseline", "center"))\n\n _default_angles = dict(left=90,\n right=-90,\n bottom=0,\n top=180)\n\n def draw(self, renderer):\n if not self.get_visible():\n self._axislabel_pad = self._external_pad\n return\n\n r, total_width = self._get_ticklabels_offsets(renderer,\n self._axis_direction)\n\n pad = self._external_pad + renderer.points_to_pixels(self.get_pad())\n self._offset_radius = r + pad\n\n for (x, y), a, l in self._locs_angles_labels:\n if not l.strip():\n continue\n self._ref_angle = a\n self.set_x(x)\n self.set_y(y)\n self.set_text(l)\n LabelBase.draw(self, renderer)\n\n # the value saved will be used to draw axislabel.\n self._axislabel_pad = total_width + pad\n\n def set_locs_angles_labels(self, locs_angles_labels):\n self._locs_angles_labels = locs_angles_labels\n\n def get_window_extents(self, renderer=None):\n if renderer is None:\n renderer = self.get_figure(root=True)._get_renderer()\n\n if not self.get_visible():\n self._axislabel_pad = self._external_pad\n return []\n\n bboxes = []\n\n r, total_width = self._get_ticklabels_offsets(renderer,\n self._axis_direction)\n\n pad = self._external_pad + renderer.points_to_pixels(self.get_pad())\n self._offset_radius = r + pad\n\n for (x, y), a, l in self._locs_angles_labels:\n self._ref_angle = a\n self.set_x(x)\n self.set_y(y)\n self.set_text(l)\n bb = LabelBase.get_window_extent(self, renderer)\n bboxes.append(bb)\n\n # the value saved will be used to draw axislabel.\n self._axislabel_pad = total_width + pad\n\n return bboxes\n\n def get_texts_widths_heights_descents(self, renderer):\n """\n Return a list of ``(width, height, descent)`` tuples for ticklabels.\n\n Empty labels are left out.\n """\n whd_list = []\n for _loc, _angle, label in self._locs_angles_labels:\n if not label.strip():\n continue\n clean_line, ismath = self._preprocess_math(label)\n whd = mtext._get_text_metrics_with_cache(\n renderer, clean_line, self._fontproperties, ismath=ismath,\n dpi=self.get_figure(root=True).dpi)\n whd_list.append(whd)\n return whd_list\n\n\nclass GridlinesCollection(LineCollection):\n def __init__(self, *args, which="major", axis="both", **kwargs):\n """\n Collection of grid lines.\n\n Parameters\n ----------\n which : {"major", "minor"}\n Which grid to consider.\n axis : {"both", "x", "y"}\n Which axis to consider.\n *args, **kwargs\n Passed to `.LineCollection`.\n """\n self._which = which\n self._axis = axis\n super().__init__(*args, **kwargs)\n self.set_grid_helper(None)\n\n def set_which(self, which):\n """\n Select major or minor grid lines.\n\n Parameters\n ----------\n which : {"major", "minor"}\n """\n self._which = which\n\n def set_axis(self, axis):\n """\n Select axis.\n\n Parameters\n ----------\n axis : {"both", "x", "y"}\n """\n self._axis = axis\n\n def set_grid_helper(self, grid_helper):\n """\n Set grid helper.\n\n Parameters\n ----------\n grid_helper : `.GridHelperBase` subclass\n """\n self._grid_helper = grid_helper\n\n def draw(self, renderer):\n if self._grid_helper is not None:\n self._grid_helper.update_lim(self.axes)\n gl = self._grid_helper.get_gridlines(self._which, self._axis)\n self.set_segments([np.transpose(l) for l in gl])\n super().draw(renderer)\n\n\nclass AxisArtist(martist.Artist):\n """\n An artist which draws axis (a line along which the n-th axes coord\n is constant) line, ticks, tick labels, and axis label.\n """\n\n zorder = 2.5\n\n @property\n def LABELPAD(self):\n return self.label.get_pad()\n\n @LABELPAD.setter\n def LABELPAD(self, v):\n self.label.set_pad(v)\n\n def __init__(self, axes,\n helper,\n offset=None,\n axis_direction="bottom",\n **kwargs):\n """\n Parameters\n ----------\n axes : `mpl_toolkits.axisartist.axislines.Axes`\n helper : `~mpl_toolkits.axisartist.axislines.AxisArtistHelper`\n """\n # axes is also used to follow the axis attribute (tick color, etc).\n\n super().__init__(**kwargs)\n\n self.axes = axes\n\n self._axis_artist_helper = helper\n\n if offset is None:\n offset = (0, 0)\n self.offset_transform = ScaledTranslation(\n *offset,\n Affine2D().scale(1 / 72) # points to inches.\n + self.axes.get_figure(root=False).dpi_scale_trans)\n\n if axis_direction in ["left", "right"]:\n self.axis = axes.yaxis\n else:\n self.axis = axes.xaxis\n\n self._axisline_style = None\n self._axis_direction = axis_direction\n\n self._init_line()\n self._init_ticks(**kwargs)\n self._init_offsetText(axis_direction)\n self._init_label()\n\n # axis direction\n self._ticklabel_add_angle = 0.\n self._axislabel_add_angle = 0.\n self.set_axis_direction(axis_direction)\n\n # axis direction\n\n def set_axis_direction(self, axis_direction):\n """\n Adjust the direction, text angle, and text alignment of tick labels\n and axis labels following the Matplotlib convention for the rectangle\n axes.\n\n The *axis_direction* must be one of [left, right, bottom, top].\n\n ===================== ========== ========= ========== ==========\n Property left bottom right top\n ===================== ========== ========= ========== ==========\n ticklabel direction "-" "+" "+" "-"\n axislabel direction "-" "+" "+" "-"\n ticklabel angle 90 0 -90 180\n ticklabel va center baseline center baseline\n ticklabel ha right center right center\n axislabel angle 180 0 0 180\n axislabel va center top center bottom\n axislabel ha right center right center\n ===================== ========== ========= ========== ==========\n\n Note that the direction "+" and "-" are relative to the direction of\n the increasing coordinate. Also, the text angles are actually\n relative to (90 + angle of the direction to the ticklabel),\n which gives 0 for bottom axis.\n\n Parameters\n ----------\n axis_direction : {"left", "bottom", "right", "top"}\n """\n self.major_ticklabels.set_axis_direction(axis_direction)\n self.label.set_axis_direction(axis_direction)\n self._axis_direction = axis_direction\n if axis_direction in ["left", "top"]:\n self.set_ticklabel_direction("-")\n self.set_axislabel_direction("-")\n else:\n self.set_ticklabel_direction("+")\n self.set_axislabel_direction("+")\n\n def set_ticklabel_direction(self, tick_direction):\n r"""\n Adjust the direction of the tick labels.\n\n Note that the *tick_direction*\s '+' and '-' are relative to the\n direction of the increasing coordinate.\n\n Parameters\n ----------\n tick_direction : {"+", "-"}\n """\n self._ticklabel_add_angle = _api.check_getitem(\n {"+": 0, "-": 180}, tick_direction=tick_direction)\n\n def invert_ticklabel_direction(self):\n self._ticklabel_add_angle = (self._ticklabel_add_angle + 180) % 360\n self.major_ticklabels.invert_axis_direction()\n self.minor_ticklabels.invert_axis_direction()\n\n def set_axislabel_direction(self, label_direction):\n r"""\n Adjust the direction of the axis label.\n\n Note that the *label_direction*\s '+' and '-' are relative to the\n direction of the increasing coordinate.\n\n Parameters\n ----------\n label_direction : {"+", "-"}\n """\n self._axislabel_add_angle = _api.check_getitem(\n {"+": 0, "-": 180}, label_direction=label_direction)\n\n def get_transform(self):\n return self.axes.transAxes + self.offset_transform\n\n def get_helper(self):\n """\n Return axis artist helper instance.\n """\n return self._axis_artist_helper\n\n def set_axisline_style(self, axisline_style=None, **kwargs):\n """\n Set the axisline style.\n\n The new style is completely defined by the passed attributes. Existing\n style attributes are forgotten.\n\n Parameters\n ----------\n axisline_style : str or None\n The line style, e.g. '->', optionally followed by a comma-separated\n list of attributes. Alternatively, the attributes can be provided\n as keywords.\n\n If *None* this returns a string containing the available styles.\n\n Examples\n --------\n The following two commands are equal:\n\n >>> set_axisline_style("->,size=1.5")\n >>> set_axisline_style("->", size=1.5)\n """\n if axisline_style is None:\n return AxislineStyle.pprint_styles()\n\n if isinstance(axisline_style, AxislineStyle._Base):\n self._axisline_style = axisline_style\n else:\n self._axisline_style = AxislineStyle(axisline_style, **kwargs)\n\n self._init_line()\n\n def get_axisline_style(self):\n """Return the current axisline style."""\n return self._axisline_style\n\n def _init_line(self):\n """\n Initialize the *line* artist that is responsible to draw the axis line.\n """\n tran = (self._axis_artist_helper.get_line_transform(self.axes)\n + self.offset_transform)\n\n axisline_style = self.get_axisline_style()\n if axisline_style is None:\n self.line = PathPatch(\n self._axis_artist_helper.get_line(self.axes),\n color=mpl.rcParams['axes.edgecolor'],\n fill=False,\n linewidth=mpl.rcParams['axes.linewidth'],\n capstyle=mpl.rcParams['lines.solid_capstyle'],\n joinstyle=mpl.rcParams['lines.solid_joinstyle'],\n transform=tran)\n else:\n self.line = axisline_style(self, transform=tran)\n\n def _draw_line(self, renderer):\n self.line.set_path(self._axis_artist_helper.get_line(self.axes))\n if self.get_axisline_style() is not None:\n self.line.set_line_mutation_scale(self.major_ticklabels.get_size())\n self.line.draw(renderer)\n\n def _init_ticks(self, **kwargs):\n axis_name = self.axis.axis_name\n\n trans = (self._axis_artist_helper.get_tick_transform(self.axes)\n + self.offset_transform)\n\n self.major_ticks = Ticks(\n kwargs.get(\n "major_tick_size",\n mpl.rcParams[f"{axis_name}tick.major.size"]),\n axis=self.axis, transform=trans)\n self.minor_ticks = Ticks(\n kwargs.get(\n "minor_tick_size",\n mpl.rcParams[f"{axis_name}tick.minor.size"]),\n axis=self.axis, transform=trans)\n\n size = mpl.rcParams[f"{axis_name}tick.labelsize"]\n self.major_ticklabels = TickLabels(\n axis=self.axis,\n axis_direction=self._axis_direction,\n figure=self.axes.get_figure(root=False),\n transform=trans,\n fontsize=size,\n pad=kwargs.get(\n "major_tick_pad", mpl.rcParams[f"{axis_name}tick.major.pad"]),\n )\n self.minor_ticklabels = TickLabels(\n axis=self.axis,\n axis_direction=self._axis_direction,\n figure=self.axes.get_figure(root=False),\n transform=trans,\n fontsize=size,\n pad=kwargs.get(\n "minor_tick_pad", mpl.rcParams[f"{axis_name}tick.minor.pad"]),\n )\n\n def _get_tick_info(self, tick_iter):\n """\n Return a pair of:\n\n - list of locs and angles for ticks\n - list of locs, angles and labels for ticklabels.\n """\n ticks_loc_angle = []\n ticklabels_loc_angle_label = []\n\n ticklabel_add_angle = self._ticklabel_add_angle\n\n for loc, angle_normal, angle_tangent, label in tick_iter:\n angle_label = angle_tangent - 90 + ticklabel_add_angle\n angle_tick = (angle_normal\n if 90 <= (angle_label - angle_normal) % 360 <= 270\n else angle_normal + 180)\n ticks_loc_angle.append([loc, angle_tick])\n ticklabels_loc_angle_label.append([loc, angle_label, label])\n\n return ticks_loc_angle, ticklabels_loc_angle_label\n\n def _update_ticks(self, renderer=None):\n # set extra pad for major and minor ticklabels: use ticksize of\n # majorticks even for minor ticks. not clear what is best.\n\n if renderer is None:\n renderer = self.get_figure(root=True)._get_renderer()\n\n dpi_cor = renderer.points_to_pixels(1.)\n if self.major_ticks.get_visible() and self.major_ticks.get_tick_out():\n ticklabel_pad = self.major_ticks._ticksize * dpi_cor\n self.major_ticklabels._external_pad = ticklabel_pad\n self.minor_ticklabels._external_pad = ticklabel_pad\n else:\n self.major_ticklabels._external_pad = 0\n self.minor_ticklabels._external_pad = 0\n\n majortick_iter, minortick_iter = \\n self._axis_artist_helper.get_tick_iterators(self.axes)\n\n tick_loc_angle, ticklabel_loc_angle_label = \\n self._get_tick_info(majortick_iter)\n self.major_ticks.set_locs_angles(tick_loc_angle)\n self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)\n\n tick_loc_angle, ticklabel_loc_angle_label = \\n self._get_tick_info(minortick_iter)\n self.minor_ticks.set_locs_angles(tick_loc_angle)\n self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)\n\n def _draw_ticks(self, renderer):\n self._update_ticks(renderer)\n self.major_ticks.draw(renderer)\n self.major_ticklabels.draw(renderer)\n self.minor_ticks.draw(renderer)\n self.minor_ticklabels.draw(renderer)\n if (self.major_ticklabels.get_visible()\n or self.minor_ticklabels.get_visible()):\n self._draw_offsetText(renderer)\n\n _offsetText_pos = dict(left=(0, 1, "bottom", "right"),\n right=(1, 1, "bottom", "left"),\n bottom=(1, 0, "top", "right"),\n top=(1, 1, "bottom", "right"))\n\n def _init_offsetText(self, direction):\n x, y, va, ha = self._offsetText_pos[direction]\n self.offsetText = mtext.Annotation(\n "",\n xy=(x, y), xycoords="axes fraction",\n xytext=(0, 0), textcoords="offset points",\n color=mpl.rcParams['xtick.color'],\n horizontalalignment=ha, verticalalignment=va,\n )\n self.offsetText.set_transform(IdentityTransform())\n self.axes._set_artist_props(self.offsetText)\n\n def _update_offsetText(self):\n self.offsetText.set_text(self.axis.major.formatter.get_offset())\n self.offsetText.set_size(self.major_ticklabels.get_size())\n offset = (self.major_ticklabels.get_pad()\n + self.major_ticklabels.get_size()\n + 2)\n self.offsetText.xyann = (0, offset)\n\n def _draw_offsetText(self, renderer):\n self._update_offsetText()\n self.offsetText.draw(renderer)\n\n def _init_label(self, **kwargs):\n tr = (self._axis_artist_helper.get_axislabel_transform(self.axes)\n + self.offset_transform)\n self.label = AxisLabel(\n 0, 0, "__from_axes__",\n color="auto",\n fontsize=kwargs.get("labelsize", mpl.rcParams['axes.labelsize']),\n fontweight=mpl.rcParams['axes.labelweight'],\n axis=self.axis,\n transform=tr,\n axis_direction=self._axis_direction,\n )\n self.label.set_figure(self.axes.get_figure(root=False))\n labelpad = kwargs.get("labelpad", 5)\n self.label.set_pad(labelpad)\n\n def _update_label(self, renderer):\n if not self.label.get_visible():\n return\n\n if self._ticklabel_add_angle != self._axislabel_add_angle:\n if ((self.major_ticks.get_visible()\n and not self.major_ticks.get_tick_out())\n or (self.minor_ticks.get_visible()\n and not self.major_ticks.get_tick_out())):\n axislabel_pad = self.major_ticks._ticksize\n else:\n axislabel_pad = 0\n else:\n axislabel_pad = max(self.major_ticklabels._axislabel_pad,\n self.minor_ticklabels._axislabel_pad)\n\n self.label._external_pad = axislabel_pad\n\n xy, angle_tangent = \\n self._axis_artist_helper.get_axislabel_pos_angle(self.axes)\n if xy is None:\n return\n\n angle_label = angle_tangent - 90\n\n x, y = xy\n self.label._ref_angle = angle_label + self._axislabel_add_angle\n self.label.set(x=x, y=y)\n\n def _draw_label(self, renderer):\n self._update_label(renderer)\n self.label.draw(renderer)\n\n def set_label(self, s):\n # docstring inherited\n self.label.set_text(s)\n\n def get_tightbbox(self, renderer=None):\n if not self.get_visible():\n return\n self._axis_artist_helper.update_lim(self.axes)\n self._update_ticks(renderer)\n self._update_label(renderer)\n\n self.line.set_path(self._axis_artist_helper.get_line(self.axes))\n if self.get_axisline_style() is not None:\n self.line.set_line_mutation_scale(self.major_ticklabels.get_size())\n\n bb = [\n *self.major_ticklabels.get_window_extents(renderer),\n *self.minor_ticklabels.get_window_extents(renderer),\n self.label.get_window_extent(renderer),\n self.offsetText.get_window_extent(renderer),\n self.line.get_window_extent(renderer),\n ]\n bb = [b for b in bb if b and (b.width != 0 or b.height != 0)]\n if bb:\n _bbox = Bbox.union(bb)\n return _bbox\n else:\n return None\n\n @martist.allow_rasterization\n def draw(self, renderer):\n # docstring inherited\n if not self.get_visible():\n return\n renderer.open_group(__name__, gid=self.get_gid())\n self._axis_artist_helper.update_lim(self.axes)\n self._draw_ticks(renderer)\n self._draw_line(renderer)\n self._draw_label(renderer)\n renderer.close_group(__name__)\n\n def toggle(self, all=None, ticks=None, ticklabels=None, label=None):\n """\n Toggle visibility of ticks, ticklabels, and (axis) label.\n To turn all off, ::\n\n axis.toggle(all=False)\n\n To turn all off but ticks on ::\n\n axis.toggle(all=False, ticks=True)\n\n To turn all on but (axis) label off ::\n\n axis.toggle(all=True, label=False)\n\n """\n if all:\n _ticks, _ticklabels, _label = True, True, True\n elif all is not None:\n _ticks, _ticklabels, _label = False, False, False\n else:\n _ticks, _ticklabels, _label = None, None, None\n\n if ticks is not None:\n _ticks = ticks\n if ticklabels is not None:\n _ticklabels = ticklabels\n if label is not None:\n _label = label\n\n if _ticks is not None:\n self.major_ticks.set_visible(_ticks)\n self.minor_ticks.set_visible(_ticks)\n if _ticklabels is not None:\n self.major_ticklabels.set_visible(_ticklabels)\n self.minor_ticklabels.set_visible(_ticklabels)\n if _label is not None:\n self.label.set_visible(_label)\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\axis_artist.py | axis_artist.py | Python | 38,328 | 0.95 | 0.153226 | 0.041341 | awesome-app | 313 | 2023-12-30T22:11:23.444635 | BSD-3-Clause | false | 906da41c22d76b2c4b065a165defa2cd |
"""\nAn experimental support for curvilinear grid.\n"""\n\n# TODO :\n# see if tick_iterator method can be simplified by reusing the parent method.\n\nimport functools\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api, cbook\nimport matplotlib.patches as mpatches\nfrom matplotlib.path import Path\n\nfrom mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory\n\nfrom . import axislines, grid_helper_curvelinear\nfrom .axis_artist import AxisArtist\nfrom .grid_finder import ExtremeFinderSimple\n\n\nclass FloatingAxisArtistHelper(\n grid_helper_curvelinear.FloatingAxisArtistHelper):\n pass\n\n\nclass FixedAxisArtistHelper(grid_helper_curvelinear.FloatingAxisArtistHelper):\n\n def __init__(self, grid_helper, side, nth_coord_ticks=None):\n """\n nth_coord = along which coordinate value varies.\n nth_coord = 0 -> x axis, nth_coord = 1 -> y axis\n """\n lon1, lon2, lat1, lat2 = grid_helper.grid_finder.extreme_finder(*[None] * 5)\n value, nth_coord = _api.check_getitem(\n dict(left=(lon1, 0), right=(lon2, 0), bottom=(lat1, 1), top=(lat2, 1)),\n side=side)\n super().__init__(grid_helper, nth_coord, value, axis_direction=side)\n if nth_coord_ticks is None:\n nth_coord_ticks = nth_coord\n self.nth_coord_ticks = nth_coord_ticks\n\n self.value = value\n self.grid_helper = grid_helper\n self._side = side\n\n def update_lim(self, axes):\n self.grid_helper.update_lim(axes)\n self._grid_info = self.grid_helper._grid_info\n\n def get_tick_iterators(self, axes):\n """tick_loc, tick_angle, tick_label, (optionally) tick_label"""\n\n grid_finder = self.grid_helper.grid_finder\n\n lat_levs, lat_n, lat_factor = self._grid_info["lat_info"]\n yy0 = lat_levs / lat_factor\n\n lon_levs, lon_n, lon_factor = self._grid_info["lon_info"]\n xx0 = lon_levs / lon_factor\n\n extremes = self.grid_helper.grid_finder.extreme_finder(*[None] * 5)\n xmin, xmax = sorted(extremes[:2])\n ymin, ymax = sorted(extremes[2:])\n\n def trf_xy(x, y):\n trf = grid_finder.get_transform() + axes.transData\n return trf.transform(np.column_stack(np.broadcast_arrays(x, y))).T\n\n if self.nth_coord == 0:\n mask = (ymin <= yy0) & (yy0 <= ymax)\n (xx1, yy1), (dxx1, dyy1), (dxx2, dyy2) = \\n grid_helper_curvelinear._value_and_jacobian(\n trf_xy, self.value, yy0[mask], (xmin, xmax), (ymin, ymax))\n labels = self._grid_info["lat_labels"]\n\n elif self.nth_coord == 1:\n mask = (xmin <= xx0) & (xx0 <= xmax)\n (xx1, yy1), (dxx2, dyy2), (dxx1, dyy1) = \\n grid_helper_curvelinear._value_and_jacobian(\n trf_xy, xx0[mask], self.value, (xmin, xmax), (ymin, ymax))\n labels = self._grid_info["lon_labels"]\n\n labels = [l for l, m in zip(labels, mask) if m]\n\n angle_normal = np.arctan2(dyy1, dxx1)\n angle_tangent = np.arctan2(dyy2, dxx2)\n mm = (dyy1 == 0) & (dxx1 == 0) # points with degenerate normal\n angle_normal[mm] = angle_tangent[mm] + np.pi / 2\n\n tick_to_axes = self.get_tick_transform(axes) - axes.transAxes\n in_01 = functools.partial(\n mpl.transforms._interval_contains_close, (0, 1))\n\n def f1():\n for x, y, normal, tangent, lab \\n in zip(xx1, yy1, angle_normal, angle_tangent, labels):\n c2 = tick_to_axes.transform((x, y))\n if in_01(c2[0]) and in_01(c2[1]):\n yield [x, y], *np.rad2deg([normal, tangent]), lab\n\n return f1(), iter([])\n\n def get_line(self, axes):\n self.update_lim(axes)\n k, v = dict(left=("lon_lines0", 0),\n right=("lon_lines0", 1),\n bottom=("lat_lines0", 0),\n top=("lat_lines0", 1))[self._side]\n xx, yy = self._grid_info[k][v]\n return Path(np.column_stack([xx, yy]))\n\n\nclass ExtremeFinderFixed(ExtremeFinderSimple):\n # docstring inherited\n\n def __init__(self, extremes):\n """\n This subclass always returns the same bounding box.\n\n Parameters\n ----------\n extremes : (float, float, float, float)\n The bounding box that this helper always returns.\n """\n self._extremes = extremes\n\n def __call__(self, transform_xy, x1, y1, x2, y2):\n # docstring inherited\n return self._extremes\n\n\nclass GridHelperCurveLinear(grid_helper_curvelinear.GridHelperCurveLinear):\n\n def __init__(self, aux_trans, extremes,\n grid_locator1=None,\n grid_locator2=None,\n tick_formatter1=None,\n tick_formatter2=None):\n # docstring inherited\n super().__init__(aux_trans,\n extreme_finder=ExtremeFinderFixed(extremes),\n grid_locator1=grid_locator1,\n grid_locator2=grid_locator2,\n tick_formatter1=tick_formatter1,\n tick_formatter2=tick_formatter2)\n\n def new_fixed_axis(\n self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None):\n if axes is None:\n axes = self.axes\n if axis_direction is None:\n axis_direction = loc\n # This is not the same as the FixedAxisArtistHelper class used by\n # grid_helper_curvelinear.GridHelperCurveLinear.new_fixed_axis!\n helper = FixedAxisArtistHelper(\n self, loc, nth_coord_ticks=nth_coord)\n axisline = AxisArtist(axes, helper, axis_direction=axis_direction)\n # Perhaps should be moved to the base class?\n axisline.line.set_clip_on(True)\n axisline.line.set_clip_box(axisline.axes.bbox)\n return axisline\n\n # new_floating_axis will inherit the grid_helper's extremes.\n\n # def new_floating_axis(self, nth_coord, value, axes=None, axis_direction="bottom"):\n # axis = super(GridHelperCurveLinear,\n # self).new_floating_axis(nth_coord,\n # value, axes=axes,\n # axis_direction=axis_direction)\n # # set extreme values of the axis helper\n # if nth_coord == 1:\n # axis.get_helper().set_extremes(*self._extremes[:2])\n # elif nth_coord == 0:\n # axis.get_helper().set_extremes(*self._extremes[2:])\n # return axis\n\n def _update_grid(self, x1, y1, x2, y2):\n if self._grid_info is None:\n self._grid_info = dict()\n\n grid_info = self._grid_info\n\n grid_finder = self.grid_finder\n extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy,\n x1, y1, x2, y2)\n\n lon_min, lon_max = sorted(extremes[:2])\n lat_min, lat_max = sorted(extremes[2:])\n grid_info["extremes"] = lon_min, lon_max, lat_min, lat_max # extremes\n\n lon_levs, lon_n, lon_factor = \\n grid_finder.grid_locator1(lon_min, lon_max)\n lon_levs = np.asarray(lon_levs)\n lat_levs, lat_n, lat_factor = \\n grid_finder.grid_locator2(lat_min, lat_max)\n lat_levs = np.asarray(lat_levs)\n\n grid_info["lon_info"] = lon_levs, lon_n, lon_factor\n grid_info["lat_info"] = lat_levs, lat_n, lat_factor\n\n grid_info["lon_labels"] = grid_finder._format_ticks(\n 1, "bottom", lon_factor, lon_levs)\n grid_info["lat_labels"] = grid_finder._format_ticks(\n 2, "bottom", lat_factor, lat_levs)\n\n lon_values = lon_levs[:lon_n] / lon_factor\n lat_values = lat_levs[:lat_n] / lat_factor\n\n lon_lines, lat_lines = grid_finder._get_raw_grid_lines(\n lon_values[(lon_min < lon_values) & (lon_values < lon_max)],\n lat_values[(lat_min < lat_values) & (lat_values < lat_max)],\n lon_min, lon_max, lat_min, lat_max)\n\n grid_info["lon_lines"] = lon_lines\n grid_info["lat_lines"] = lat_lines\n\n lon_lines, lat_lines = grid_finder._get_raw_grid_lines(\n # lon_min, lon_max, lat_min, lat_max)\n extremes[:2], extremes[2:], *extremes)\n\n grid_info["lon_lines0"] = lon_lines\n grid_info["lat_lines0"] = lat_lines\n\n def get_gridlines(self, which="major", axis="both"):\n grid_lines = []\n if axis in ["both", "x"]:\n grid_lines.extend(self._grid_info["lon_lines"])\n if axis in ["both", "y"]:\n grid_lines.extend(self._grid_info["lat_lines"])\n return grid_lines\n\n\nclass FloatingAxesBase:\n\n def __init__(self, *args, grid_helper, **kwargs):\n _api.check_isinstance(GridHelperCurveLinear, grid_helper=grid_helper)\n super().__init__(*args, grid_helper=grid_helper, **kwargs)\n self.set_aspect(1.)\n\n def _gen_axes_patch(self):\n # docstring inherited\n x0, x1, y0, y1 = self.get_grid_helper().grid_finder.extreme_finder(*[None] * 5)\n patch = mpatches.Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])\n patch.get_path()._interpolation_steps = 100\n return patch\n\n def clear(self):\n super().clear()\n self.patch.set_transform(\n self.get_grid_helper().grid_finder.get_transform()\n + self.transData)\n # The original patch is not in the draw tree; it is only used for\n # clipping purposes.\n orig_patch = super()._gen_axes_patch()\n orig_patch.set_figure(self.get_figure(root=False))\n orig_patch.set_transform(self.transAxes)\n self.patch.set_clip_path(orig_patch)\n self.gridlines.set_clip_path(orig_patch)\n self.adjust_axes_lim()\n\n def adjust_axes_lim(self):\n bbox = self.patch.get_path().get_extents(\n # First transform to pixel coords, then to parent data coords.\n self.patch.get_transform() - self.transData)\n bbox = bbox.expanded(1.02, 1.02)\n self.set_xlim(bbox.xmin, bbox.xmax)\n self.set_ylim(bbox.ymin, bbox.ymax)\n\n\nfloatingaxes_class_factory = cbook._make_class_factory(FloatingAxesBase, "Floating{}")\nFloatingAxes = floatingaxes_class_factory(host_axes_class_factory(axislines.Axes))\nFloatingSubplot = FloatingAxes\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\floating_axes.py | floating_axes.py | Python | 10,337 | 0.95 | 0.141818 | 0.115741 | awesome-app | 165 | 2024-06-04T07:17:56.970004 | MIT | false | 08eedb31b6b70852c8ec5cd5ad7341ec |
import numpy as np\n\nfrom matplotlib import ticker as mticker, _api\nfrom matplotlib.transforms import Bbox, Transform\n\n\ndef _find_line_box_crossings(xys, bbox):\n """\n Find the points where a polyline crosses a bbox, and the crossing angles.\n\n Parameters\n ----------\n xys : (N, 2) array\n The polyline coordinates.\n bbox : `.Bbox`\n The bounding box.\n\n Returns\n -------\n list of ((float, float), float)\n Four separate lists of crossings, for the left, right, bottom, and top\n sides of the bbox, respectively. For each list, the entries are the\n ``((x, y), ccw_angle_in_degrees)`` of the crossing, where an angle of 0\n means that the polyline is moving to the right at the crossing point.\n\n The entries are computed by linearly interpolating at each crossing\n between the nearest points on either side of the bbox edges.\n """\n crossings = []\n dxys = xys[1:] - xys[:-1]\n for sl in [slice(None), slice(None, None, -1)]:\n us, vs = xys.T[sl] # "this" coord, "other" coord\n dus, dvs = dxys.T[sl]\n umin, vmin = bbox.min[sl]\n umax, vmax = bbox.max[sl]\n for u0, inside in [(umin, us > umin), (umax, us < umax)]:\n cross = []\n idxs, = (inside[:-1] ^ inside[1:]).nonzero()\n for idx in idxs:\n v = vs[idx] + (u0 - us[idx]) * dvs[idx] / dus[idx]\n if not vmin <= v <= vmax:\n continue\n crossing = (u0, v)[sl]\n theta = np.degrees(np.arctan2(*dxys[idx][::-1]))\n cross.append((crossing, theta))\n crossings.append(cross)\n return crossings\n\n\nclass ExtremeFinderSimple:\n """\n A helper class to figure out the range of grid lines that need to be drawn.\n """\n\n def __init__(self, nx, ny):\n """\n Parameters\n ----------\n nx, ny : int\n The number of samples in each direction.\n """\n self.nx = nx\n self.ny = ny\n\n def __call__(self, transform_xy, x1, y1, x2, y2):\n """\n Compute an approximation of the bounding box obtained by applying\n *transform_xy* to the box delimited by ``(x1, y1, x2, y2)``.\n\n The intended use is to have ``(x1, y1, x2, y2)`` in axes coordinates,\n and have *transform_xy* be the transform from axes coordinates to data\n coordinates; this method then returns the range of data coordinates\n that span the actual axes.\n\n The computation is done by sampling ``nx * ny`` equispaced points in\n the ``(x1, y1, x2, y2)`` box and finding the resulting points with\n extremal coordinates; then adding some padding to take into account the\n finite sampling.\n\n As each sampling step covers a relative range of *1/nx* or *1/ny*,\n the padding is computed by expanding the span covered by the extremal\n coordinates by these fractions.\n """\n x, y = np.meshgrid(\n np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny))\n xt, yt = transform_xy(np.ravel(x), np.ravel(y))\n return self._add_pad(xt.min(), xt.max(), yt.min(), yt.max())\n\n def _add_pad(self, x_min, x_max, y_min, y_max):\n """Perform the padding mentioned in `__call__`."""\n dx = (x_max - x_min) / self.nx\n dy = (y_max - y_min) / self.ny\n return x_min - dx, x_max + dx, y_min - dy, y_max + dy\n\n\nclass _User2DTransform(Transform):\n """A transform defined by two user-set functions."""\n\n input_dims = output_dims = 2\n\n def __init__(self, forward, backward):\n """\n Parameters\n ----------\n forward, backward : callable\n The forward and backward transforms, taking ``x`` and ``y`` as\n separate arguments and returning ``(tr_x, tr_y)``.\n """\n # The normal Matplotlib convention would be to take and return an\n # (N, 2) array but axisartist uses the transposed version.\n super().__init__()\n self._forward = forward\n self._backward = backward\n\n def transform_non_affine(self, values):\n # docstring inherited\n return np.transpose(self._forward(*np.transpose(values)))\n\n def inverted(self):\n # docstring inherited\n return type(self)(self._backward, self._forward)\n\n\nclass GridFinder:\n """\n Internal helper for `~.grid_helper_curvelinear.GridHelperCurveLinear`, with\n the same constructor parameters; should not be directly instantiated.\n """\n\n def __init__(self,\n transform,\n extreme_finder=None,\n grid_locator1=None,\n grid_locator2=None,\n tick_formatter1=None,\n tick_formatter2=None):\n if extreme_finder is None:\n extreme_finder = ExtremeFinderSimple(20, 20)\n if grid_locator1 is None:\n grid_locator1 = MaxNLocator()\n if grid_locator2 is None:\n grid_locator2 = MaxNLocator()\n if tick_formatter1 is None:\n tick_formatter1 = FormatterPrettyPrint()\n if tick_formatter2 is None:\n tick_formatter2 = FormatterPrettyPrint()\n self.extreme_finder = extreme_finder\n self.grid_locator1 = grid_locator1\n self.grid_locator2 = grid_locator2\n self.tick_formatter1 = tick_formatter1\n self.tick_formatter2 = tick_formatter2\n self.set_transform(transform)\n\n def _format_ticks(self, idx, direction, factor, levels):\n """\n Helper to support both standard formatters (inheriting from\n `.mticker.Formatter`) and axisartist-specific ones; should be called instead of\n directly calling ``self.tick_formatter1`` and ``self.tick_formatter2``. This\n method should be considered as a temporary workaround which will be removed in\n the future at the same time as axisartist-specific formatters.\n """\n fmt = _api.check_getitem(\n {1: self.tick_formatter1, 2: self.tick_formatter2}, idx=idx)\n return (fmt.format_ticks(levels) if isinstance(fmt, mticker.Formatter)\n else fmt(direction, factor, levels))\n\n def get_grid_info(self, x1, y1, x2, y2):\n """\n lon_values, lat_values : list of grid values. if integer is given,\n rough number of grids in each direction.\n """\n\n extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2)\n\n # min & max rage of lat (or lon) for each grid line will be drawn.\n # i.e., gridline of lon=0 will be drawn from lat_min to lat_max.\n\n lon_min, lon_max, lat_min, lat_max = extremes\n lon_levs, lon_n, lon_factor = self.grid_locator1(lon_min, lon_max)\n lon_levs = np.asarray(lon_levs)\n lat_levs, lat_n, lat_factor = self.grid_locator2(lat_min, lat_max)\n lat_levs = np.asarray(lat_levs)\n\n lon_values = lon_levs[:lon_n] / lon_factor\n lat_values = lat_levs[:lat_n] / lat_factor\n\n lon_lines, lat_lines = self._get_raw_grid_lines(lon_values,\n lat_values,\n lon_min, lon_max,\n lat_min, lat_max)\n\n bb = Bbox.from_extents(x1, y1, x2, y2).expanded(1 + 2e-10, 1 + 2e-10)\n\n grid_info = {\n "extremes": extremes,\n # "lon", "lat", filled below.\n }\n\n for idx, lon_or_lat, levs, factor, values, lines in [\n (1, "lon", lon_levs, lon_factor, lon_values, lon_lines),\n (2, "lat", lat_levs, lat_factor, lat_values, lat_lines),\n ]:\n grid_info[lon_or_lat] = gi = {\n "lines": [[l] for l in lines],\n "ticks": {"left": [], "right": [], "bottom": [], "top": []},\n }\n for (lx, ly), v, level in zip(lines, values, levs):\n all_crossings = _find_line_box_crossings(np.column_stack([lx, ly]), bb)\n for side, crossings in zip(\n ["left", "right", "bottom", "top"], all_crossings):\n for crossing in crossings:\n gi["ticks"][side].append({"level": level, "loc": crossing})\n for side in gi["ticks"]:\n levs = [tick["level"] for tick in gi["ticks"][side]]\n labels = self._format_ticks(idx, side, factor, levs)\n for tick, label in zip(gi["ticks"][side], labels):\n tick["label"] = label\n\n return grid_info\n\n def _get_raw_grid_lines(self,\n lon_values, lat_values,\n lon_min, lon_max, lat_min, lat_max):\n\n lons_i = np.linspace(lon_min, lon_max, 100) # for interpolation\n lats_i = np.linspace(lat_min, lat_max, 100)\n\n lon_lines = [self.transform_xy(np.full_like(lats_i, lon), lats_i)\n for lon in lon_values]\n lat_lines = [self.transform_xy(lons_i, np.full_like(lons_i, lat))\n for lat in lat_values]\n\n return lon_lines, lat_lines\n\n def set_transform(self, aux_trans):\n if isinstance(aux_trans, Transform):\n self._aux_transform = aux_trans\n elif len(aux_trans) == 2 and all(map(callable, aux_trans)):\n self._aux_transform = _User2DTransform(*aux_trans)\n else:\n raise TypeError("'aux_trans' must be either a Transform "\n "instance or a pair of callables")\n\n def get_transform(self):\n return self._aux_transform\n\n update_transform = set_transform # backcompat alias.\n\n def transform_xy(self, x, y):\n return self._aux_transform.transform(np.column_stack([x, y])).T\n\n def inv_transform_xy(self, x, y):\n return self._aux_transform.inverted().transform(\n np.column_stack([x, y])).T\n\n def update(self, **kwargs):\n for k, v in kwargs.items():\n if k in ["extreme_finder",\n "grid_locator1",\n "grid_locator2",\n "tick_formatter1",\n "tick_formatter2"]:\n setattr(self, k, v)\n else:\n raise ValueError(f"Unknown update property {k!r}")\n\n\nclass MaxNLocator(mticker.MaxNLocator):\n def __init__(self, nbins=10, steps=None,\n trim=True,\n integer=False,\n symmetric=False,\n prune=None):\n # trim argument has no effect. It has been left for API compatibility\n super().__init__(nbins, steps=steps, integer=integer,\n symmetric=symmetric, prune=prune)\n self.create_dummy_axis()\n\n def __call__(self, v1, v2):\n locs = super().tick_values(v1, v2)\n return np.array(locs), len(locs), 1 # 1: factor (see angle_helper)\n\n\nclass FixedLocator:\n def __init__(self, locs):\n self._locs = locs\n\n def __call__(self, v1, v2):\n v1, v2 = sorted([v1, v2])\n locs = np.array([l for l in self._locs if v1 <= l <= v2])\n return locs, len(locs), 1 # 1: factor (see angle_helper)\n\n\n# Tick Formatter\n\nclass FormatterPrettyPrint:\n def __init__(self, useMathText=True):\n self._fmt = mticker.ScalarFormatter(\n useMathText=useMathText, useOffset=False)\n self._fmt.create_dummy_axis()\n\n def __call__(self, direction, factor, values):\n return self._fmt.format_ticks(values)\n\n\nclass DictFormatter:\n def __init__(self, format_dict, formatter=None):\n """\n format_dict : dictionary for format strings to be used.\n formatter : fall-back formatter\n """\n super().__init__()\n self._format_dict = format_dict\n self._fallback_formatter = formatter\n\n def __call__(self, direction, factor, values):\n """\n factor is ignored if value is found in the dictionary\n """\n if self._fallback_formatter:\n fallback_strings = self._fallback_formatter(\n direction, factor, values)\n else:\n fallback_strings = [""] * len(values)\n return [self._format_dict.get(k, v)\n for k, v in zip(values, fallback_strings)]\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\grid_finder.py | grid_finder.py | Python | 12,265 | 0.95 | 0.205521 | 0.037175 | react-lib | 235 | 2023-12-05T03:32:47.163309 | Apache-2.0 | false | f8a8b3bc1c1f4b7911aa17d9a859b333 |
"""\nAn experimental support for curvilinear grid.\n"""\n\nimport functools\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import Affine2D, IdentityTransform\nfrom .axislines import (\n _FixedAxisArtistHelperBase, _FloatingAxisArtistHelperBase, GridHelperBase)\nfrom .axis_artist import AxisArtist\nfrom .grid_finder import GridFinder\n\n\ndef _value_and_jacobian(func, xs, ys, xlims, ylims):\n """\n Compute *func* and its derivatives along x and y at positions *xs*, *ys*,\n while ensuring that finite difference calculations don't try to evaluate\n values outside of *xlims*, *ylims*.\n """\n eps = np.finfo(float).eps ** (1/2) # see e.g. scipy.optimize.approx_fprime\n val = func(xs, ys)\n # Take the finite difference step in the direction where the bound is the\n # furthest; the step size is min of epsilon and distance to that bound.\n xlo, xhi = sorted(xlims)\n dxlo = xs - xlo\n dxhi = xhi - xs\n xeps = (np.take([-1, 1], dxhi >= dxlo)\n * np.minimum(eps, np.maximum(dxlo, dxhi)))\n val_dx = func(xs + xeps, ys)\n ylo, yhi = sorted(ylims)\n dylo = ys - ylo\n dyhi = yhi - ys\n yeps = (np.take([-1, 1], dyhi >= dylo)\n * np.minimum(eps, np.maximum(dylo, dyhi)))\n val_dy = func(xs, ys + yeps)\n return (val, (val_dx - val) / xeps, (val_dy - val) / yeps)\n\n\nclass FixedAxisArtistHelper(_FixedAxisArtistHelperBase):\n """\n Helper class for a fixed axis.\n """\n\n def __init__(self, grid_helper, side, nth_coord_ticks=None):\n """\n nth_coord = along which coordinate value varies.\n nth_coord = 0 -> x axis, nth_coord = 1 -> y axis\n """\n\n super().__init__(loc=side)\n\n self.grid_helper = grid_helper\n if nth_coord_ticks is None:\n nth_coord_ticks = self.nth_coord\n self.nth_coord_ticks = nth_coord_ticks\n\n self.side = side\n\n def update_lim(self, axes):\n self.grid_helper.update_lim(axes)\n\n def get_tick_transform(self, axes):\n return axes.transData\n\n def get_tick_iterators(self, axes):\n """tick_loc, tick_angle, tick_label"""\n v1, v2 = axes.get_ylim() if self.nth_coord == 0 else axes.get_xlim()\n if v1 > v2: # Inverted limits.\n side = {"left": "right", "right": "left",\n "top": "bottom", "bottom": "top"}[self.side]\n else:\n side = self.side\n\n angle_tangent = dict(left=90, right=90, bottom=0, top=0)[side]\n\n def iter_major():\n for nth_coord, show_labels in [\n (self.nth_coord_ticks, True), (1 - self.nth_coord_ticks, False)]:\n gi = self.grid_helper._grid_info[["lon", "lat"][nth_coord]]\n for tick in gi["ticks"][side]:\n yield (*tick["loc"], angle_tangent,\n (tick["label"] if show_labels else ""))\n\n return iter_major(), iter([])\n\n\nclass FloatingAxisArtistHelper(_FloatingAxisArtistHelperBase):\n\n def __init__(self, grid_helper, nth_coord, value, axis_direction=None):\n """\n nth_coord = along which coordinate value varies.\n nth_coord = 0 -> x axis, nth_coord = 1 -> y axis\n """\n super().__init__(nth_coord, value)\n self.value = value\n self.grid_helper = grid_helper\n self._extremes = -np.inf, np.inf\n self._line_num_points = 100 # number of points to create a line\n\n def set_extremes(self, e1, e2):\n if e1 is None:\n e1 = -np.inf\n if e2 is None:\n e2 = np.inf\n self._extremes = e1, e2\n\n def update_lim(self, axes):\n self.grid_helper.update_lim(axes)\n\n x1, x2 = axes.get_xlim()\n y1, y2 = axes.get_ylim()\n grid_finder = self.grid_helper.grid_finder\n extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy,\n x1, y1, x2, y2)\n\n lon_min, lon_max, lat_min, lat_max = extremes\n e_min, e_max = self._extremes # ranges of other coordinates\n if self.nth_coord == 0:\n lat_min = max(e_min, lat_min)\n lat_max = min(e_max, lat_max)\n elif self.nth_coord == 1:\n lon_min = max(e_min, lon_min)\n lon_max = min(e_max, lon_max)\n\n lon_levs, lon_n, lon_factor = \\n grid_finder.grid_locator1(lon_min, lon_max)\n lat_levs, lat_n, lat_factor = \\n grid_finder.grid_locator2(lat_min, lat_max)\n\n if self.nth_coord == 0:\n xx0 = np.full(self._line_num_points, self.value)\n yy0 = np.linspace(lat_min, lat_max, self._line_num_points)\n xx, yy = grid_finder.transform_xy(xx0, yy0)\n elif self.nth_coord == 1:\n xx0 = np.linspace(lon_min, lon_max, self._line_num_points)\n yy0 = np.full(self._line_num_points, self.value)\n xx, yy = grid_finder.transform_xy(xx0, yy0)\n\n self._grid_info = {\n "extremes": (lon_min, lon_max, lat_min, lat_max),\n "lon_info": (lon_levs, lon_n, np.asarray(lon_factor)),\n "lat_info": (lat_levs, lat_n, np.asarray(lat_factor)),\n "lon_labels": grid_finder._format_ticks(\n 1, "bottom", lon_factor, lon_levs),\n "lat_labels": grid_finder._format_ticks(\n 2, "bottom", lat_factor, lat_levs),\n "line_xy": (xx, yy),\n }\n\n def get_axislabel_transform(self, axes):\n return Affine2D() # axes.transData\n\n def get_axislabel_pos_angle(self, axes):\n def trf_xy(x, y):\n trf = self.grid_helper.grid_finder.get_transform() + axes.transData\n return trf.transform([x, y]).T\n\n xmin, xmax, ymin, ymax = self._grid_info["extremes"]\n if self.nth_coord == 0:\n xx0 = self.value\n yy0 = (ymin + ymax) / 2\n elif self.nth_coord == 1:\n xx0 = (xmin + xmax) / 2\n yy0 = self.value\n xy1, dxy1_dx, dxy1_dy = _value_and_jacobian(\n trf_xy, xx0, yy0, (xmin, xmax), (ymin, ymax))\n p = axes.transAxes.inverted().transform(xy1)\n if 0 <= p[0] <= 1 and 0 <= p[1] <= 1:\n d = [dxy1_dy, dxy1_dx][self.nth_coord]\n return xy1, np.rad2deg(np.arctan2(*d[::-1]))\n else:\n return None, None\n\n def get_tick_transform(self, axes):\n return IdentityTransform() # axes.transData\n\n def get_tick_iterators(self, axes):\n """tick_loc, tick_angle, tick_label, (optionally) tick_label"""\n\n lat_levs, lat_n, lat_factor = self._grid_info["lat_info"]\n yy0 = lat_levs / lat_factor\n\n lon_levs, lon_n, lon_factor = self._grid_info["lon_info"]\n xx0 = lon_levs / lon_factor\n\n e0, e1 = self._extremes\n\n def trf_xy(x, y):\n trf = self.grid_helper.grid_finder.get_transform() + axes.transData\n return trf.transform(np.column_stack(np.broadcast_arrays(x, y))).T\n\n # find angles\n if self.nth_coord == 0:\n mask = (e0 <= yy0) & (yy0 <= e1)\n (xx1, yy1), (dxx1, dyy1), (dxx2, dyy2) = _value_and_jacobian(\n trf_xy, self.value, yy0[mask], (-np.inf, np.inf), (e0, e1))\n labels = self._grid_info["lat_labels"]\n\n elif self.nth_coord == 1:\n mask = (e0 <= xx0) & (xx0 <= e1)\n (xx1, yy1), (dxx2, dyy2), (dxx1, dyy1) = _value_and_jacobian(\n trf_xy, xx0[mask], self.value, (-np.inf, np.inf), (e0, e1))\n labels = self._grid_info["lon_labels"]\n\n labels = [l for l, m in zip(labels, mask) if m]\n\n angle_normal = np.arctan2(dyy1, dxx1)\n angle_tangent = np.arctan2(dyy2, dxx2)\n mm = (dyy1 == 0) & (dxx1 == 0) # points with degenerate normal\n angle_normal[mm] = angle_tangent[mm] + np.pi / 2\n\n tick_to_axes = self.get_tick_transform(axes) - axes.transAxes\n in_01 = functools.partial(\n mpl.transforms._interval_contains_close, (0, 1))\n\n def iter_major():\n for x, y, normal, tangent, lab \\n in zip(xx1, yy1, angle_normal, angle_tangent, labels):\n c2 = tick_to_axes.transform((x, y))\n if in_01(c2[0]) and in_01(c2[1]):\n yield [x, y], *np.rad2deg([normal, tangent]), lab\n\n return iter_major(), iter([])\n\n def get_line_transform(self, axes):\n return axes.transData\n\n def get_line(self, axes):\n self.update_lim(axes)\n x, y = self._grid_info["line_xy"]\n return Path(np.column_stack([x, y]))\n\n\nclass GridHelperCurveLinear(GridHelperBase):\n def __init__(self, aux_trans,\n extreme_finder=None,\n grid_locator1=None,\n grid_locator2=None,\n tick_formatter1=None,\n tick_formatter2=None):\n """\n Parameters\n ----------\n aux_trans : `.Transform` or tuple[Callable, Callable]\n The transform from curved coordinates to rectilinear coordinate:\n either a `.Transform` instance (which provides also its inverse),\n or a pair of callables ``(trans, inv_trans)`` that define the\n transform and its inverse. The callables should have signature::\n\n x_rect, y_rect = trans(x_curved, y_curved)\n x_curved, y_curved = inv_trans(x_rect, y_rect)\n\n extreme_finder\n\n grid_locator1, grid_locator2\n Grid locators for each axis.\n\n tick_formatter1, tick_formatter2\n Tick formatters for each axis.\n """\n super().__init__()\n self._grid_info = None\n self.grid_finder = GridFinder(aux_trans,\n extreme_finder,\n grid_locator1,\n grid_locator2,\n tick_formatter1,\n tick_formatter2)\n\n def update_grid_finder(self, aux_trans=None, **kwargs):\n if aux_trans is not None:\n self.grid_finder.update_transform(aux_trans)\n self.grid_finder.update(**kwargs)\n self._old_limits = None # Force revalidation.\n\n @_api.make_keyword_only("3.9", "nth_coord")\n def new_fixed_axis(\n self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None):\n if axes is None:\n axes = self.axes\n if axis_direction is None:\n axis_direction = loc\n helper = FixedAxisArtistHelper(self, loc, nth_coord_ticks=nth_coord)\n axisline = AxisArtist(axes, helper, axis_direction=axis_direction)\n # Why is clip not set on axisline, unlike in new_floating_axis or in\n # the floating_axig.GridHelperCurveLinear subclass?\n return axisline\n\n def new_floating_axis(self, nth_coord, value, axes=None, axis_direction="bottom"):\n if axes is None:\n axes = self.axes\n helper = FloatingAxisArtistHelper(\n self, nth_coord, value, axis_direction)\n axisline = AxisArtist(axes, helper)\n axisline.line.set_clip_on(True)\n axisline.line.set_clip_box(axisline.axes.bbox)\n # axisline.major_ticklabels.set_visible(True)\n # axisline.minor_ticklabels.set_visible(False)\n return axisline\n\n def _update_grid(self, x1, y1, x2, y2):\n self._grid_info = self.grid_finder.get_grid_info(x1, y1, x2, y2)\n\n def get_gridlines(self, which="major", axis="both"):\n grid_lines = []\n if axis in ["both", "x"]:\n for gl in self._grid_info["lon"]["lines"]:\n grid_lines.extend(gl)\n if axis in ["both", "y"]:\n for gl in self._grid_info["lat"]["lines"]:\n grid_lines.extend(gl)\n return grid_lines\n\n @_api.deprecated("3.9")\n def get_tick_iterator(self, nth_coord, axis_side, minor=False):\n angle_tangent = dict(left=90, right=90, bottom=0, top=0)[axis_side]\n lon_or_lat = ["lon", "lat"][nth_coord]\n if not minor: # major ticks\n for tick in self._grid_info[lon_or_lat]["ticks"][axis_side]:\n yield *tick["loc"], angle_tangent, tick["label"]\n else:\n for tick in self._grid_info[lon_or_lat]["ticks"][axis_side]:\n yield *tick["loc"], angle_tangent, ""\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\grid_helper_curvelinear.py | grid_helper_curvelinear.py | Python | 12,349 | 0.95 | 0.192073 | 0.03321 | awesome-app | 700 | 2023-11-01T02:35:58.703271 | BSD-3-Clause | false | 0a2d0aaf192ff61c8681ff093f5c0d4c |
from mpl_toolkits.axes_grid1.parasite_axes import (\n host_axes_class_factory, parasite_axes_class_factory)\nfrom .axislines import Axes\n\n\nParasiteAxes = parasite_axes_class_factory(Axes)\nHostAxes = SubplotHost = host_axes_class_factory(Axes)\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\parasite_axes.py | parasite_axes.py | Python | 244 | 0.85 | 0 | 0 | node-utils | 955 | 2024-08-18T07:19:55.944287 | GPL-3.0 | false | 36ea8a2ee09cd8fd45976626ebd89b21 |
from .axislines import Axes\nfrom .axislines import ( # noqa: F401\n AxesZero, AxisArtistHelper, AxisArtistHelperRectlinear,\n GridHelperBase, GridHelperRectlinear, Subplot, SubplotZero)\nfrom .axis_artist import AxisArtist, GridlinesCollection # noqa: F401\nfrom .grid_helper_curvelinear import GridHelperCurveLinear # noqa: F401\nfrom .floating_axes import FloatingAxes, FloatingSubplot # noqa: F401\nfrom mpl_toolkits.axes_grid1.parasite_axes import (\n host_axes_class_factory, parasite_axes_class_factory)\n\n\nParasiteAxes = parasite_axes_class_factory(Axes)\nHostAxes = host_axes_class_factory(Axes)\nSubplotHost = HostAxes\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__init__.py | __init__.py | Python | 631 | 0.95 | 0 | 0 | python-kit | 328 | 2024-09-08T13:56:18.217032 | BSD-3-Clause | false | bd55d494f544c889512397838de7d877 |
from matplotlib.testing.conftest import (mpl_test_settings, # noqa\n pytest_configure, pytest_unconfigure)\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\conftest.py | conftest.py | Python | 147 | 0.95 | 0 | 0 | vue-tools | 603 | 2024-11-30T22:36:51.031989 | BSD-3-Clause | true | a9af9c9b2ae8eefcebb125a652ac4c2b |
import re\n\nimport numpy as np\nimport pytest\n\nfrom mpl_toolkits.axisartist.angle_helper import (\n FormatterDMS, FormatterHMS, select_step, select_step24, select_step360)\n\n\n_MS_RE = (\n r'''\$ # Mathtext\n (\n # The sign sometimes appears on a 0 when a fraction is shown.\n # Check later that there's only one.\n (?P<degree_sign>-)?\n (?P<degree>[0-9.]+) # Degrees value\n {degree} # Degree symbol (to be replaced by format.)\n )?\n (\n (?(degree)\\,) # Separator if degrees are also visible.\n (?P<minute_sign>-)?\n (?P<minute>[0-9.]+) # Minutes value\n {minute} # Minute symbol (to be replaced by format.)\n )?\n (\n (?(minute)\\,) # Separator if minutes are also visible.\n (?P<second_sign>-)?\n (?P<second>[0-9.]+) # Seconds value\n {second} # Second symbol (to be replaced by format.)\n )?\n \$ # Mathtext\n '''\n)\nDMS_RE = re.compile(_MS_RE.format(degree=re.escape(FormatterDMS.deg_mark),\n minute=re.escape(FormatterDMS.min_mark),\n second=re.escape(FormatterDMS.sec_mark)),\n re.VERBOSE)\nHMS_RE = re.compile(_MS_RE.format(degree=re.escape(FormatterHMS.deg_mark),\n minute=re.escape(FormatterHMS.min_mark),\n second=re.escape(FormatterHMS.sec_mark)),\n re.VERBOSE)\n\n\ndef dms2float(degrees, minutes=0, seconds=0):\n return degrees + minutes / 60.0 + seconds / 3600.0\n\n\n@pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [\n ((-180, 180, 10), {'hour': False}, np.arange(-180, 181, 30), 1.0),\n ((-12, 12, 10), {'hour': True}, np.arange(-12, 13, 2), 1.0)\n])\ndef test_select_step(args, kwargs, expected_levels, expected_factor):\n levels, n, factor = select_step(*args, **kwargs)\n\n assert n == len(levels)\n np.testing.assert_array_equal(levels, expected_levels)\n assert factor == expected_factor\n\n\n@pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [\n ((-180, 180, 10), {}, np.arange(-180, 181, 30), 1.0),\n ((-12, 12, 10), {}, np.arange(-750, 751, 150), 60.0)\n])\ndef test_select_step24(args, kwargs, expected_levels, expected_factor):\n levels, n, factor = select_step24(*args, **kwargs)\n\n assert n == len(levels)\n np.testing.assert_array_equal(levels, expected_levels)\n assert factor == expected_factor\n\n\n@pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [\n ((dms2float(20, 21.2), dms2float(21, 33.3), 5), {},\n np.arange(1215, 1306, 15), 60.0),\n ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=33.3), 5), {},\n np.arange(73820, 73835, 2), 3600.0),\n ((dms2float(20, 21.2), dms2float(20, 53.3), 5), {},\n np.arange(1220, 1256, 5), 60.0),\n ((21.2, 33.3, 5), {},\n np.arange(20, 35, 2), 1.0),\n ((dms2float(20, 21.2), dms2float(21, 33.3), 5), {},\n np.arange(1215, 1306, 15), 60.0),\n ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=33.3), 5), {},\n np.arange(73820, 73835, 2), 3600.0),\n ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=21.4), 5), {},\n np.arange(7382120, 7382141, 5), 360000.0),\n # test threshold factor\n ((dms2float(20.5, seconds=11.2), dms2float(20.5, seconds=53.3), 5),\n {'threshold_factor': 60}, np.arange(12301, 12310), 600.0),\n ((dms2float(20.5, seconds=11.2), dms2float(20.5, seconds=53.3), 5),\n {'threshold_factor': 1}, np.arange(20502, 20517, 2), 1000.0),\n])\ndef test_select_step360(args, kwargs, expected_levels, expected_factor):\n levels, n, factor = select_step360(*args, **kwargs)\n\n assert n == len(levels)\n np.testing.assert_array_equal(levels, expected_levels)\n assert factor == expected_factor\n\n\n@pytest.mark.parametrize('Formatter, regex',\n [(FormatterDMS, DMS_RE),\n (FormatterHMS, HMS_RE)],\n ids=['Degree/Minute/Second', 'Hour/Minute/Second'])\n@pytest.mark.parametrize('direction, factor, values', [\n ("left", 60, [0, -30, -60]),\n ("left", 600, [12301, 12302, 12303]),\n ("left", 3600, [0, -30, -60]),\n ("left", 36000, [738210, 738215, 738220]),\n ("left", 360000, [7382120, 7382125, 7382130]),\n ("left", 1., [45, 46, 47]),\n ("left", 10., [452, 453, 454]),\n])\ndef test_formatters(Formatter, regex, direction, factor, values):\n fmt = Formatter()\n result = fmt(direction, factor, values)\n\n prev_degree = prev_minute = prev_second = None\n for tick, value in zip(result, values):\n m = regex.match(tick)\n assert m is not None, f'{tick!r} is not an expected tick format.'\n\n sign = sum(m.group(sign + '_sign') is not None\n for sign in ('degree', 'minute', 'second'))\n assert sign <= 1, f'Only one element of tick {tick!r} may have a sign.'\n sign = 1 if sign == 0 else -1\n\n degree = float(m.group('degree') or prev_degree or 0)\n minute = float(m.group('minute') or prev_minute or 0)\n second = float(m.group('second') or prev_second or 0)\n if Formatter == FormatterHMS:\n # 360 degrees as plot range -> 24 hours as labelled range\n expected_value = pytest.approx((value // 15) / factor)\n else:\n expected_value = pytest.approx(value / factor)\n assert sign * dms2float(degree, minute, second) == expected_value, \\n f'{tick!r} does not match expected tick value.'\n\n prev_degree = degree\n prev_minute = minute\n prev_second = second\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\test_angle_helper.py | test_angle_helper.py | Python | 5,670 | 0.95 | 0.078014 | 0.033333 | awesome-app | 419 | 2025-04-20T18:36:10.128073 | GPL-3.0 | true | 5dc35d5db30bda7219e9ce341f0ffefd |
import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison\nfrom matplotlib.transforms import IdentityTransform\n\nfrom mpl_toolkits.axisartist.axislines import AxesZero, SubplotZero, Subplot\nfrom mpl_toolkits.axisartist import Axes, SubplotHost\n\n\n@image_comparison(['SubplotZero.png'], style='default')\ndef test_SubplotZero():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig = plt.figure()\n\n ax = SubplotZero(fig, 1, 1, 1)\n fig.add_subplot(ax)\n\n ax.axis["xzero"].set_visible(True)\n ax.axis["xzero"].label.set_text("Axis Zero")\n\n for n in ["top", "right"]:\n ax.axis[n].set_visible(False)\n\n xx = np.arange(0, 2 * np.pi, 0.01)\n ax.plot(xx, np.sin(xx))\n ax.set_ylabel("Test")\n\n\n@image_comparison(['Subplot.png'], style='default')\ndef test_Subplot():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig = plt.figure()\n\n ax = Subplot(fig, 1, 1, 1)\n fig.add_subplot(ax)\n\n xx = np.arange(0, 2 * np.pi, 0.01)\n ax.plot(xx, np.sin(xx))\n ax.set_ylabel("Test")\n\n ax.axis["top"].major_ticks.set_tick_out(True)\n ax.axis["bottom"].major_ticks.set_tick_out(True)\n\n ax.axis["bottom"].set_label("Tk0")\n\n\ndef test_Axes():\n fig = plt.figure()\n ax = Axes(fig, [0.15, 0.1, 0.65, 0.8])\n fig.add_axes(ax)\n ax.plot([1, 2, 3], [0, 1, 2])\n ax.set_xscale('log')\n fig.canvas.draw()\n\n\n@image_comparison(['ParasiteAxesAuxTrans_meshplot.png'],\n remove_text=True, style='default', tol=0.075)\ndef test_ParasiteAxesAuxTrans():\n data = np.ones((6, 6))\n data[2, 2] = 2\n data[0, :] = 0\n data[-2, :] = 0\n data[:, 0] = 0\n data[:, -2] = 0\n x = np.arange(6)\n y = np.arange(6)\n xx, yy = np.meshgrid(x, y)\n\n funcnames = ['pcolor', 'pcolormesh', 'contourf']\n\n fig = plt.figure()\n for i, name in enumerate(funcnames):\n\n ax1 = SubplotHost(fig, 1, 3, i+1)\n fig.add_subplot(ax1)\n\n ax2 = ax1.get_aux_axes(IdentityTransform(), viewlim_mode=None)\n if name.startswith('pcolor'):\n getattr(ax2, name)(xx, yy, data[:-1, :-1])\n else:\n getattr(ax2, name)(xx, yy, data)\n ax1.set_xlim((0, 5))\n ax1.set_ylim((0, 5))\n\n ax2.contour(xx, yy, data, colors='k')\n\n\n@image_comparison(['axisline_style.png'], remove_text=True, style='mpl20')\ndef test_axisline_style():\n fig = plt.figure(figsize=(2, 2))\n ax = fig.add_subplot(axes_class=AxesZero)\n ax.axis["xzero"].set_axisline_style("-|>")\n ax.axis["xzero"].set_visible(True)\n ax.axis["yzero"].set_axisline_style("->")\n ax.axis["yzero"].set_visible(True)\n\n for direction in ("left", "right", "bottom", "top"):\n ax.axis[direction].set_visible(False)\n\n\n@image_comparison(['axisline_style_size_color.png'], remove_text=True,\n style='mpl20')\ndef test_axisline_style_size_color():\n fig = plt.figure(figsize=(2, 2))\n ax = fig.add_subplot(axes_class=AxesZero)\n ax.axis["xzero"].set_axisline_style("-|>", size=2.0, facecolor='r')\n ax.axis["xzero"].set_visible(True)\n ax.axis["yzero"].set_axisline_style("->, size=1.5")\n ax.axis["yzero"].set_visible(True)\n\n for direction in ("left", "right", "bottom", "top"):\n ax.axis[direction].set_visible(False)\n\n\n@image_comparison(['axisline_style_tight.png'], remove_text=True,\n style='mpl20')\ndef test_axisline_style_tight():\n fig = plt.figure(figsize=(2, 2), layout='tight')\n ax = fig.add_subplot(axes_class=AxesZero)\n ax.axis["xzero"].set_axisline_style("-|>", size=5, facecolor='g')\n ax.axis["xzero"].set_visible(True)\n ax.axis["yzero"].set_axisline_style("->, size=8")\n ax.axis["yzero"].set_visible(True)\n\n for direction in ("left", "right", "bottom", "top"):\n ax.axis[direction].set_visible(False)\n\n\n@image_comparison(['subplotzero_ylabel.png'], style='mpl20')\ndef test_subplotzero_ylabel():\n fig = plt.figure()\n ax = fig.add_subplot(111, axes_class=SubplotZero)\n\n ax.set(xlim=(-3, 7), ylim=(-3, 7), xlabel="x", ylabel="y")\n\n zero_axis = ax.axis["xzero", "yzero"]\n zero_axis.set_visible(True) # they are hidden by default\n\n ax.axis["left", "right", "bottom", "top"].set_visible(False)\n\n zero_axis.set_axisline_style("->")\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\test_axislines.py | test_axislines.py | Python | 4,353 | 0.95 | 0.096552 | 0.018868 | awesome-app | 865 | 2023-11-17T08:11:11.698620 | MIT | true | bf862a848e37b6889b208c38235eef9c |
import matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison\n\nfrom mpl_toolkits.axisartist import AxisArtistHelperRectlinear\nfrom mpl_toolkits.axisartist.axis_artist import (AxisArtist, AxisLabel,\n LabelBase, Ticks, TickLabels)\n\n\n@image_comparison(['axis_artist_ticks.png'], style='default')\ndef test_ticks():\n fig, ax = plt.subplots()\n\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n locs_angles = [((i / 10, 0.0), i * 30) for i in range(-1, 12)]\n\n ticks_in = Ticks(ticksize=10, axis=ax.xaxis)\n ticks_in.set_locs_angles(locs_angles)\n ax.add_artist(ticks_in)\n\n ticks_out = Ticks(ticksize=10, tick_out=True, color='C3', axis=ax.xaxis)\n ticks_out.set_locs_angles(locs_angles)\n ax.add_artist(ticks_out)\n\n\n@image_comparison(['axis_artist_labelbase.png'], style='default')\ndef test_labelbase():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig, ax = plt.subplots()\n\n ax.plot([0.5], [0.5], "o")\n\n label = LabelBase(0.5, 0.5, "Test")\n label._ref_angle = -90\n label._offset_radius = 50\n label.set_rotation(-90)\n label.set(ha="center", va="top")\n ax.add_artist(label)\n\n\n@image_comparison(['axis_artist_ticklabels.png'], style='default')\ndef test_ticklabels():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig, ax = plt.subplots()\n\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n ax.plot([0.2, 0.4], [0.5, 0.5], "o")\n\n ticks = Ticks(ticksize=10, axis=ax.xaxis)\n ax.add_artist(ticks)\n locs_angles_labels = [((0.2, 0.5), -90, "0.2"),\n ((0.4, 0.5), -120, "0.4")]\n tick_locs_angles = [(xy, a + 180) for xy, a, l in locs_angles_labels]\n ticks.set_locs_angles(tick_locs_angles)\n\n ticklabels = TickLabels(axis_direction="left")\n ticklabels._locs_angles_labels = locs_angles_labels\n ticklabels.set_pad(10)\n ax.add_artist(ticklabels)\n\n ax.plot([0.5], [0.5], "s")\n axislabel = AxisLabel(0.5, 0.5, "Test")\n axislabel._offset_radius = 20\n axislabel._ref_angle = 0\n axislabel.set_axis_direction("bottom")\n ax.add_artist(axislabel)\n\n ax.set_xlim(0, 1)\n ax.set_ylim(0, 1)\n\n\n@image_comparison(['axis_artist.png'], style='default')\ndef test_axis_artist():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig, ax = plt.subplots()\n\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n for loc in ('left', 'right', 'bottom'):\n helper = AxisArtistHelperRectlinear.Fixed(ax, loc=loc)\n axisline = AxisArtist(ax, helper, offset=None, axis_direction=loc)\n ax.add_artist(axisline)\n\n # Settings for bottom AxisArtist.\n axisline.set_label("TTT")\n axisline.major_ticks.set_tick_out(False)\n axisline.label.set_pad(5)\n\n ax.set_ylabel("Test")\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\test_axis_artist.py | test_axis_artist.py | Python | 2,980 | 0.95 | 0.080808 | 0.056338 | react-lib | 712 | 2024-02-03T05:46:39.306750 | BSD-3-Clause | true | 65e49a00307a29e0ca7aa24052951ca8 |
import numpy as np\n\nimport matplotlib.pyplot as plt\nimport matplotlib.projections as mprojections\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.testing.decorators import image_comparison\nfrom mpl_toolkits.axisartist.axislines import Subplot\nfrom mpl_toolkits.axisartist.floating_axes import (\n FloatingAxes, GridHelperCurveLinear)\nfrom mpl_toolkits.axisartist.grid_finder import FixedLocator\nfrom mpl_toolkits.axisartist import angle_helper\n\n\ndef test_subplot():\n fig = plt.figure(figsize=(5, 5))\n ax = Subplot(fig, 111)\n fig.add_subplot(ax)\n\n\n# Rather high tolerance to allow ongoing work with floating axes internals;\n# remove when image is regenerated.\n@image_comparison(['curvelinear3.png'], style='default', tol=5)\ndef test_curvelinear3():\n fig = plt.figure(figsize=(5, 5))\n\n tr = (mtransforms.Affine2D().scale(np.pi / 180, 1) +\n mprojections.PolarAxes.PolarTransform(apply_theta_transforms=False))\n grid_helper = GridHelperCurveLinear(\n tr,\n extremes=(0, 360, 10, 3),\n grid_locator1=angle_helper.LocatorDMS(15),\n grid_locator2=FixedLocator([2, 4, 6, 8, 10]),\n tick_formatter1=angle_helper.FormatterDMS(),\n tick_formatter2=None)\n ax1 = fig.add_subplot(axes_class=FloatingAxes, grid_helper=grid_helper)\n\n r_scale = 10\n tr2 = mtransforms.Affine2D().scale(1, 1 / r_scale) + tr\n grid_helper2 = GridHelperCurveLinear(\n tr2,\n extremes=(0, 360, 10 * r_scale, 3 * r_scale),\n grid_locator2=FixedLocator([30, 60, 90]))\n\n ax1.axis["right"] = axis = grid_helper2.new_fixed_axis("right", axes=ax1)\n\n ax1.axis["left"].label.set_text("Test 1")\n ax1.axis["right"].label.set_text("Test 2")\n ax1.axis["left", "right"].set_visible(False)\n\n axis = grid_helper.new_floating_axis(1, 7, axes=ax1,\n axis_direction="bottom")\n ax1.axis["z"] = axis\n axis.toggle(all=True, label=True)\n axis.label.set_text("z = ?")\n axis.label.set_visible(True)\n axis.line.set_color("0.5")\n\n ax2 = ax1.get_aux_axes(tr)\n\n xx, yy = [67, 90, 75, 30], [2, 5, 8, 4]\n ax2.scatter(xx, yy)\n l, = ax2.plot(xx, yy, "k-")\n l.set_clip_path(ax1.patch)\n\n\n# Rather high tolerance to allow ongoing work with floating axes internals;\n# remove when image is regenerated.\n@image_comparison(['curvelinear4.png'], style='default', tol=0.9)\ndef test_curvelinear4():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig = plt.figure(figsize=(5, 5))\n\n tr = (mtransforms.Affine2D().scale(np.pi / 180, 1) +\n mprojections.PolarAxes.PolarTransform(apply_theta_transforms=False))\n grid_helper = GridHelperCurveLinear(\n tr,\n extremes=(120, 30, 10, 0),\n grid_locator1=angle_helper.LocatorDMS(5),\n grid_locator2=FixedLocator([2, 4, 6, 8, 10]),\n tick_formatter1=angle_helper.FormatterDMS(),\n tick_formatter2=None)\n ax1 = fig.add_subplot(axes_class=FloatingAxes, grid_helper=grid_helper)\n ax1.clear() # Check that clear() also restores the correct limits on ax1.\n\n ax1.axis["left"].label.set_text("Test 1")\n ax1.axis["right"].label.set_text("Test 2")\n ax1.axis["top"].set_visible(False)\n\n axis = grid_helper.new_floating_axis(1, 70, axes=ax1,\n axis_direction="bottom")\n ax1.axis["z"] = axis\n axis.toggle(all=True, label=True)\n axis.label.set_axis_direction("top")\n axis.label.set_text("z = ?")\n axis.label.set_visible(True)\n axis.line.set_color("0.5")\n\n ax2 = ax1.get_aux_axes(tr)\n\n xx, yy = [67, 90, 75, 30], [2, 5, 8, 4]\n ax2.scatter(xx, yy)\n l, = ax2.plot(xx, yy, "k-")\n l.set_clip_path(ax1.patch)\n\n\ndef test_axis_direction():\n # Check that axis direction is propagated on a floating axis\n fig = plt.figure()\n ax = Subplot(fig, 111)\n fig.add_subplot(ax)\n ax.axis['y'] = ax.new_floating_axis(nth_coord=1, value=0,\n axis_direction='left')\n assert ax.axis['y']._axis_direction == 'left'\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\test_floating_axes.py | test_floating_axes.py | Python | 4,083 | 0.95 | 0.034783 | 0.064516 | node-utils | 305 | 2025-05-02T15:38:01.136325 | Apache-2.0 | true | 1677da2a917000a8f16810b8a1b5cf03 |
import numpy as np\nimport pytest\n\nfrom matplotlib.transforms import Bbox\nfrom mpl_toolkits.axisartist.grid_finder import (\n _find_line_box_crossings, FormatterPrettyPrint, MaxNLocator)\n\n\ndef test_find_line_box_crossings():\n x = np.array([-3, -2, -1, 0., 1, 2, 3, 2, 1, 0, -1, -2, -3, 5])\n y = np.arange(len(x))\n bbox = Bbox.from_extents(-2, 3, 2, 12.5)\n left, right, bottom, top = _find_line_box_crossings(\n np.column_stack([x, y]), bbox)\n ((lx0, ly0), la0), ((lx1, ly1), la1), = left\n ((rx0, ry0), ra0), ((rx1, ry1), ra1), = right\n ((bx0, by0), ba0), = bottom\n ((tx0, ty0), ta0), = top\n assert (lx0, ly0, la0) == (-2, 11, 135)\n assert (lx1, ly1, la1) == pytest.approx((-2., 12.125, 7.125016))\n assert (rx0, ry0, ra0) == (2, 5, 45)\n assert (rx1, ry1, ra1) == (2, 7, 135)\n assert (bx0, by0, ba0) == (0, 3, 45)\n assert (tx0, ty0, ta0) == pytest.approx((1., 12.5, 7.125016))\n\n\ndef test_pretty_print_format():\n locator = MaxNLocator()\n locs, nloc, factor = locator(0, 100)\n\n fmt = FormatterPrettyPrint()\n\n assert fmt("left", None, locs) == \\n [r'$\mathdefault{%d}$' % (l, ) for l in locs]\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\test_grid_finder.py | test_grid_finder.py | Python | 1,156 | 0.85 | 0.088235 | 0 | node-utils | 785 | 2023-11-18T17:13:33.241059 | MIT | true | 9c8120ba347f31598bae07cd632a30bd |
import numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nfrom matplotlib.projections import PolarAxes\nfrom matplotlib.ticker import FuncFormatter\nfrom matplotlib.transforms import Affine2D, Transform\nfrom matplotlib.testing.decorators import image_comparison\n\nfrom mpl_toolkits.axisartist import SubplotHost\nfrom mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory\nfrom mpl_toolkits.axisartist import angle_helper\nfrom mpl_toolkits.axisartist.axislines import Axes\nfrom mpl_toolkits.axisartist.grid_helper_curvelinear import \\n GridHelperCurveLinear\n\n\n@image_comparison(['custom_transform.png'], style='default', tol=0.2)\ndef test_custom_transform():\n class MyTransform(Transform):\n input_dims = output_dims = 2\n\n def __init__(self, resolution):\n """\n Resolution is the number of steps to interpolate between each input\n line segment to approximate its path in transformed space.\n """\n Transform.__init__(self)\n self._resolution = resolution\n\n def transform(self, ll):\n x, y = ll.T\n return np.column_stack([x, y - x])\n\n transform_non_affine = transform\n\n def transform_path(self, path):\n ipath = path.interpolated(self._resolution)\n return Path(self.transform(ipath.vertices), ipath.codes)\n\n transform_path_non_affine = transform_path\n\n def inverted(self):\n return MyTransformInv(self._resolution)\n\n class MyTransformInv(Transform):\n input_dims = output_dims = 2\n\n def __init__(self, resolution):\n Transform.__init__(self)\n self._resolution = resolution\n\n def transform(self, ll):\n x, y = ll.T\n return np.column_stack([x, y + x])\n\n def inverted(self):\n return MyTransform(self._resolution)\n\n fig = plt.figure()\n\n SubplotHost = host_axes_class_factory(Axes)\n\n tr = MyTransform(1)\n grid_helper = GridHelperCurveLinear(tr)\n ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)\n fig.add_subplot(ax1)\n\n ax2 = ax1.get_aux_axes(tr, viewlim_mode="equal")\n ax2.plot([3, 6], [5.0, 10.])\n\n ax1.set_aspect(1.)\n ax1.set_xlim(0, 10)\n ax1.set_ylim(0, 10)\n\n ax1.grid(True)\n\n\n@image_comparison(['polar_box.png'], style='default', tol=0.04)\ndef test_polar_box():\n fig = plt.figure(figsize=(5, 5))\n\n # PolarAxes.PolarTransform takes radian. However, we want our coordinate\n # system in degree\n tr = (Affine2D().scale(np.pi / 180., 1.) +\n PolarAxes.PolarTransform(apply_theta_transforms=False))\n\n # polar projection, which involves cycle, and also has limits in\n # its coordinates, needs a special method to find the extremes\n # (min, max of the coordinate within the view).\n extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,\n lon_cycle=360,\n lat_cycle=None,\n lon_minmax=None,\n lat_minmax=(0, np.inf))\n\n grid_helper = GridHelperCurveLinear(\n tr,\n extreme_finder=extreme_finder,\n grid_locator1=angle_helper.LocatorDMS(12),\n tick_formatter1=angle_helper.FormatterDMS(),\n tick_formatter2=FuncFormatter(lambda x, p: "eight" if x == 8 else f"{int(x)}"),\n )\n\n ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)\n\n ax1.axis["right"].major_ticklabels.set_visible(True)\n ax1.axis["top"].major_ticklabels.set_visible(True)\n\n # let right axis shows ticklabels for 1st coordinate (angle)\n ax1.axis["right"].get_helper().nth_coord_ticks = 0\n # let bottom axis shows ticklabels for 2nd coordinate (radius)\n ax1.axis["bottom"].get_helper().nth_coord_ticks = 1\n\n fig.add_subplot(ax1)\n\n ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1)\n axis.label.set_text("Test")\n axis.label.set_visible(True)\n axis.get_helper().set_extremes(2, 12)\n\n ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1)\n axis.label.set_text("Test 2")\n axis.get_helper().set_extremes(-180, 90)\n\n # A parasite axes with given transform\n ax2 = ax1.get_aux_axes(tr, viewlim_mode="equal")\n assert ax2.transData == tr + ax1.transData\n # Anything you draw in ax2 will match the ticks and grids of ax1.\n ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50))\n\n ax1.set_aspect(1.)\n ax1.set_xlim(-5, 12)\n ax1.set_ylim(-5, 10)\n\n ax1.grid(True)\n\n\n# Remove tol & kerning_factor when this test image is regenerated.\n@image_comparison(['axis_direction.png'], style='default', tol=0.13)\ndef test_axis_direction():\n plt.rcParams['text.kerning_factor'] = 6\n\n fig = plt.figure(figsize=(5, 5))\n\n # PolarAxes.PolarTransform takes radian. However, we want our coordinate\n # system in degree\n tr = (Affine2D().scale(np.pi / 180., 1.) +\n PolarAxes.PolarTransform(apply_theta_transforms=False))\n\n # polar projection, which involves cycle, and also has limits in\n # its coordinates, needs a special method to find the extremes\n # (min, max of the coordinate within the view).\n\n # 20, 20 : number of sampling points along x, y direction\n extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,\n lon_cycle=360,\n lat_cycle=None,\n lon_minmax=None,\n lat_minmax=(0, np.inf),\n )\n\n grid_locator1 = angle_helper.LocatorDMS(12)\n tick_formatter1 = angle_helper.FormatterDMS()\n\n grid_helper = GridHelperCurveLinear(tr,\n extreme_finder=extreme_finder,\n grid_locator1=grid_locator1,\n tick_formatter1=tick_formatter1)\n\n ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)\n\n for axis in ax1.axis.values():\n axis.set_visible(False)\n\n fig.add_subplot(ax1)\n\n ax1.axis["lat1"] = axis = grid_helper.new_floating_axis(\n 0, 130,\n axes=ax1, axis_direction="left")\n axis.label.set_text("Test")\n axis.label.set_visible(True)\n axis.get_helper().set_extremes(0.001, 10)\n\n ax1.axis["lat2"] = axis = grid_helper.new_floating_axis(\n 0, 50,\n axes=ax1, axis_direction="right")\n axis.label.set_text("Test")\n axis.label.set_visible(True)\n axis.get_helper().set_extremes(0.001, 10)\n\n ax1.axis["lon"] = axis = grid_helper.new_floating_axis(\n 1, 10,\n axes=ax1, axis_direction="bottom")\n axis.label.set_text("Test 2")\n axis.get_helper().set_extremes(50, 130)\n axis.major_ticklabels.set_axis_direction("top")\n axis.label.set_axis_direction("top")\n\n grid_helper.grid_finder.grid_locator1.set_params(nbins=5)\n grid_helper.grid_finder.grid_locator2.set_params(nbins=5)\n\n ax1.set_aspect(1.)\n ax1.set_xlim(-8, 8)\n ax1.set_ylim(-4, 12)\n\n ax1.grid(True)\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\test_grid_helper_curvelinear.py | test_grid_helper_curvelinear.py | Python | 7,216 | 0.95 | 0.077295 | 0.102564 | node-utils | 554 | 2024-06-07T10:18:29.119506 | BSD-3-Clause | true | cf48e45519fa29e181cebfded21498b4 |
from pathlib import Path\n\n\n# Check that the test directories exist\nif not (Path(__file__).parent / "baseline_images").exists():\n raise OSError(\n 'The baseline image directory does not exist. '\n 'This is most likely because the test data is not installed. '\n 'You may need to install matplotlib from source to get the '\n 'test data.')\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__init__.py | __init__.py | Python | 365 | 0.95 | 0.1 | 0.125 | node-utils | 902 | 2023-11-21T23:24:57.445498 | Apache-2.0 | true | 58fdb0c615f036e99765a61f6b25a3a4 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__pycache__\conftest.cpython-313.pyc | conftest.cpython-313.pyc | Other | 341 | 0.7 | 0 | 0 | python-kit | 311 | 2024-02-25T13:27:43.105081 | GPL-3.0 | true | 5cde906b3e74190757d83237bc99ef06 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__pycache__\test_angle_helper.cpython-313.pyc | test_angle_helper.cpython-313.pyc | Other | 7,911 | 0.8 | 0.033898 | 0.034483 | vue-tools | 615 | 2024-01-05T10:15:24.842777 | MIT | true | 4bcf203da60a15e316d931282375229c |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__pycache__\test_axislines.cpython-313.pyc | test_axislines.cpython-313.pyc | Other | 8,303 | 0.8 | 0 | 0.073171 | react-lib | 306 | 2024-04-19T12:28:22.956311 | MIT | true | 7b135bd74193de3e3ed6e98af5edfe6b |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__pycache__\test_axis_artist.cpython-313.pyc | test_axis_artist.cpython-313.pyc | Other | 5,094 | 0.8 | 0 | 0 | awesome-app | 307 | 2025-05-05T09:54:38.575991 | MIT | true | 4039ab178c7d9b1876124c438d8cadd5 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__pycache__\test_floating_axes.cpython-313.pyc | test_floating_axes.cpython-313.pyc | Other | 6,577 | 0.8 | 0 | 0.059701 | react-lib | 327 | 2024-10-17T23:52:34.525494 | MIT | true | 99a3a55512de7d87f1f876ffa525c301 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__pycache__\test_grid_finder.cpython-313.pyc | test_grid_finder.cpython-313.pyc | Other | 2,297 | 0.8 | 0 | 0.0625 | awesome-app | 632 | 2025-06-02T08:30:00.652123 | Apache-2.0 | true | d0fc5f90bb9869438f40ef6d6cbdadd8 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__pycache__\test_grid_helper_curvelinear.cpython-313.pyc | test_grid_helper_curvelinear.cpython-313.pyc | Other | 10,783 | 0.8 | 0 | 0.033333 | vue-tools | 718 | 2024-10-22T16:57:52.377187 | Apache-2.0 | true | af2d7973d81d1c9151c59e0778210fc7 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\tests\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 622 | 0.7 | 0 | 0 | node-utils | 520 | 2024-05-10T00:53:02.927294 | BSD-3-Clause | true | e5b699443433aa2f33df8539785a7196 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\angle_helper.cpython-313.pyc | angle_helper.cpython-313.pyc | Other | 16,635 | 0.95 | 0.011299 | 0.017751 | python-kit | 245 | 2024-01-12T20:15:39.418098 | BSD-3-Clause | false | 8942245f3e27731c7f60af7107be6b1b |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\axes_divider.cpython-313.pyc | axes_divider.cpython-313.pyc | Other | 357 | 0.7 | 0 | 0 | vue-tools | 384 | 2024-08-23T22:09:30.062510 | Apache-2.0 | false | a8e828d85a45dafe1195a67a2715aa58 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\axislines.cpython-313.pyc | axislines.cpython-313.pyc | Other | 26,253 | 0.95 | 0.075 | 0.061033 | node-utils | 880 | 2025-01-12T14:17:09.783460 | BSD-3-Clause | false | 6a839d11c95441a9563da06054eadf63 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\axisline_style.cpython-313.pyc | axisline_style.cpython-313.pyc | Other | 8,806 | 0.95 | 0.15 | 0.033333 | react-lib | 306 | 2024-12-05T16:08:07.358640 | BSD-3-Clause | false | bdde16a902c3bf7eb95ff537372fba95 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\axis_artist.cpython-313.pyc | axis_artist.cpython-313.pyc | Other | 51,176 | 0.95 | 0.033871 | 0.016917 | node-utils | 842 | 2025-06-06T09:18:11.271307 | BSD-3-Clause | false | e03ba66d7d4afe834164dadcd9a95503 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\floating_axes.cpython-313.pyc | floating_axes.cpython-313.pyc | Other | 13,679 | 0.95 | 0.008 | 0.008621 | python-kit | 36 | 2023-08-31T14:11:28.048399 | GPL-3.0 | false | 84236990ee9d032e0127a15dfb5fbe4d |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\grid_finder.cpython-313.pyc | grid_finder.cpython-313.pyc | Other | 16,619 | 0.95 | 0.032258 | 0.011299 | python-kit | 46 | 2025-04-28T22:02:32.835834 | Apache-2.0 | false | c84bae8f1a3d602cfe6fed6dd6c826cd |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\grid_helper_curvelinear.cpython-313.pyc | grid_helper_curvelinear.cpython-313.pyc | Other | 17,797 | 0.95 | 0.040698 | 0.006211 | react-lib | 940 | 2023-07-20T15:28:56.157005 | BSD-3-Clause | false | df134425e79f88116973b10fab1dce5a |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\parasite_axes.cpython-313.pyc | parasite_axes.cpython-313.pyc | Other | 475 | 0.7 | 0 | 0 | python-kit | 372 | 2024-10-16T22:02:08.171758 | Apache-2.0 | false | c07b7f58780c76a93d14d09aeb74a2a9 |
\n\n | .venv\Lib\site-packages\mpl_toolkits\axisartist\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 903 | 0.7 | 0 | 0 | awesome-app | 476 | 2023-09-01T10:20:32.266179 | Apache-2.0 | false | 6f17edd329358a21bb0498d11746c546 |
# art3d.py, original mplot3d version by John Porter\n# Parts rewritten by Reinier Heeres <reinier@heeres.eu>\n# Minor additions by Ben Axelrod <baxelrod@coroware.com>\n\n"""\nModule containing 3D artist code and functions to convert 2D\nartists into 3D versions which can be added to an Axes3D.\n"""\n\nimport math\n\nimport numpy as np\n\nfrom contextlib import contextmanager\n\nfrom matplotlib import (\n _api, artist, cbook, colors as mcolors, lines, text as mtext,\n path as mpath)\nfrom matplotlib.collections import (\n Collection, LineCollection, PolyCollection, PatchCollection, PathCollection)\nfrom matplotlib.colors import Normalize\nfrom matplotlib.patches import Patch\nfrom . import proj3d\n\n\ndef _norm_angle(a):\n """Return the given angle normalized to -180 < *a* <= 180 degrees."""\n a = (a + 360) % 360\n if a > 180:\n a = a - 360\n return a\n\n\ndef _norm_text_angle(a):\n """Return the given angle normalized to -90 < *a* <= 90 degrees."""\n a = (a + 180) % 180\n if a > 90:\n a = a - 180\n return a\n\n\ndef get_dir_vector(zdir):\n """\n Return a direction vector.\n\n Parameters\n ----------\n zdir : {'x', 'y', 'z', None, 3-tuple}\n The direction. Possible values are:\n\n - 'x': equivalent to (1, 0, 0)\n - 'y': equivalent to (0, 1, 0)\n - 'z': equivalent to (0, 0, 1)\n - *None*: equivalent to (0, 0, 0)\n - an iterable (x, y, z) is converted to an array\n\n Returns\n -------\n x, y, z : array\n The direction vector.\n """\n if zdir == 'x':\n return np.array((1, 0, 0))\n elif zdir == 'y':\n return np.array((0, 1, 0))\n elif zdir == 'z':\n return np.array((0, 0, 1))\n elif zdir is None:\n return np.array((0, 0, 0))\n elif np.iterable(zdir) and len(zdir) == 3:\n return np.array(zdir)\n else:\n raise ValueError("'x', 'y', 'z', None or vector of length 3 expected")\n\n\ndef _viewlim_mask(xs, ys, zs, axes):\n """\n Return original points with points outside the axes view limits masked.\n\n Parameters\n ----------\n xs, ys, zs : array-like\n The points to mask.\n axes : Axes3D\n The axes to use for the view limits.\n\n Returns\n -------\n xs_masked, ys_masked, zs_masked : np.ma.array\n The masked points.\n """\n mask = np.logical_or.reduce((xs < axes.xy_viewLim.xmin,\n xs > axes.xy_viewLim.xmax,\n ys < axes.xy_viewLim.ymin,\n ys > axes.xy_viewLim.ymax,\n zs < axes.zz_viewLim.xmin,\n zs > axes.zz_viewLim.xmax))\n xs_masked = np.ma.array(xs, mask=mask)\n ys_masked = np.ma.array(ys, mask=mask)\n zs_masked = np.ma.array(zs, mask=mask)\n return xs_masked, ys_masked, zs_masked\n\n\nclass Text3D(mtext.Text):\n """\n Text object with 3D position and direction.\n\n Parameters\n ----------\n x, y, z : float\n The position of the text.\n text : str\n The text string to display.\n zdir : {'x', 'y', 'z', None, 3-tuple}\n The direction of the text. See `.get_dir_vector` for a description of\n the values.\n axlim_clip : bool, default: False\n Whether to hide text outside the axes view limits.\n\n Other Parameters\n ----------------\n **kwargs\n All other parameters are passed on to `~matplotlib.text.Text`.\n """\n\n def __init__(self, x=0, y=0, z=0, text='', zdir='z', axlim_clip=False,\n **kwargs):\n mtext.Text.__init__(self, x, y, text, **kwargs)\n self.set_3d_properties(z, zdir, axlim_clip)\n\n def get_position_3d(self):\n """Return the (x, y, z) position of the text."""\n return self._x, self._y, self._z\n\n def set_position_3d(self, xyz, zdir=None):\n """\n Set the (*x*, *y*, *z*) position of the text.\n\n Parameters\n ----------\n xyz : (float, float, float)\n The position in 3D space.\n zdir : {'x', 'y', 'z', None, 3-tuple}\n The direction of the text. If unspecified, the *zdir* will not be\n changed. See `.get_dir_vector` for a description of the values.\n """\n super().set_position(xyz[:2])\n self.set_z(xyz[2])\n if zdir is not None:\n self._dir_vec = get_dir_vector(zdir)\n\n def set_z(self, z):\n """\n Set the *z* position of the text.\n\n Parameters\n ----------\n z : float\n """\n self._z = z\n self.stale = True\n\n def set_3d_properties(self, z=0, zdir='z', axlim_clip=False):\n """\n Set the *z* position and direction of the text.\n\n Parameters\n ----------\n z : float\n The z-position in 3D space.\n zdir : {'x', 'y', 'z', 3-tuple}\n The direction of the text. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide text outside the axes view limits.\n """\n self._z = z\n self._dir_vec = get_dir_vector(zdir)\n self._axlim_clip = axlim_clip\n self.stale = True\n\n @artist.allow_rasterization\n def draw(self, renderer):\n if self._axlim_clip:\n xs, ys, zs = _viewlim_mask(self._x, self._y, self._z, self.axes)\n position3d = np.ma.row_stack((xs, ys, zs)).ravel().filled(np.nan)\n else:\n xs, ys, zs = self._x, self._y, self._z\n position3d = np.asanyarray([xs, ys, zs])\n\n proj = proj3d._proj_trans_points(\n [position3d, position3d + self._dir_vec], self.axes.M)\n dx = proj[0][1] - proj[0][0]\n dy = proj[1][1] - proj[1][0]\n angle = math.degrees(math.atan2(dy, dx))\n with cbook._setattr_cm(self, _x=proj[0][0], _y=proj[1][0],\n _rotation=_norm_text_angle(angle)):\n mtext.Text.draw(self, renderer)\n self.stale = False\n\n def get_tightbbox(self, renderer=None):\n # Overwriting the 2d Text behavior which is not valid for 3d.\n # For now, just return None to exclude from layout calculation.\n return None\n\n\ndef text_2d_to_3d(obj, z=0, zdir='z', axlim_clip=False):\n """\n Convert a `.Text` to a `.Text3D` object.\n\n Parameters\n ----------\n z : float\n The z-position in 3D space.\n zdir : {'x', 'y', 'z', 3-tuple}\n The direction of the text. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide text outside the axes view limits.\n """\n obj.__class__ = Text3D\n obj.set_3d_properties(z, zdir, axlim_clip)\n\n\nclass Line3D(lines.Line2D):\n """\n 3D line object.\n\n .. note:: Use `get_data_3d` to obtain the data associated with the line.\n `~.Line2D.get_data`, `~.Line2D.get_xdata`, and `~.Line2D.get_ydata` return\n the x- and y-coordinates of the projected 2D-line, not the x- and y-data of\n the 3D-line. Similarly, use `set_data_3d` to set the data, not\n `~.Line2D.set_data`, `~.Line2D.set_xdata`, and `~.Line2D.set_ydata`.\n """\n\n def __init__(self, xs, ys, zs, *args, axlim_clip=False, **kwargs):\n """\n\n Parameters\n ----------\n xs : array-like\n The x-data to be plotted.\n ys : array-like\n The y-data to be plotted.\n zs : array-like\n The z-data to be plotted.\n *args, **kwargs\n Additional arguments are passed to `~matplotlib.lines.Line2D`.\n """\n super().__init__([], [], *args, **kwargs)\n self.set_data_3d(xs, ys, zs)\n self._axlim_clip = axlim_clip\n\n def set_3d_properties(self, zs=0, zdir='z', axlim_clip=False):\n """\n Set the *z* position and direction of the line.\n\n Parameters\n ----------\n zs : float or array of floats\n The location along the *zdir* axis in 3D space to position the\n line.\n zdir : {'x', 'y', 'z'}\n Plane to plot line orthogonal to. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide lines with an endpoint outside the axes view limits.\n """\n xs = self.get_xdata()\n ys = self.get_ydata()\n zs = cbook._to_unmasked_float_array(zs).ravel()\n zs = np.broadcast_to(zs, len(xs))\n self._verts3d = juggle_axes(xs, ys, zs, zdir)\n self._axlim_clip = axlim_clip\n self.stale = True\n\n def set_data_3d(self, *args):\n """\n Set the x, y and z data\n\n Parameters\n ----------\n x : array-like\n The x-data to be plotted.\n y : array-like\n The y-data to be plotted.\n z : array-like\n The z-data to be plotted.\n\n Notes\n -----\n Accepts x, y, z arguments or a single array-like (x, y, z)\n """\n if len(args) == 1:\n args = args[0]\n for name, xyz in zip('xyz', args):\n if not np.iterable(xyz):\n raise RuntimeError(f'{name} must be a sequence')\n self._verts3d = args\n self.stale = True\n\n def get_data_3d(self):\n """\n Get the current data\n\n Returns\n -------\n verts3d : length-3 tuple or array-like\n The current data as a tuple or array-like.\n """\n return self._verts3d\n\n @artist.allow_rasterization\n def draw(self, renderer):\n if self._axlim_clip:\n xs3d, ys3d, zs3d = _viewlim_mask(*self._verts3d, self.axes)\n else:\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs, tis = proj3d._proj_transform_clip(xs3d, ys3d, zs3d,\n self.axes.M,\n self.axes._focal_length)\n self.set_data(xs, ys)\n super().draw(renderer)\n self.stale = False\n\n\ndef line_2d_to_3d(line, zs=0, zdir='z', axlim_clip=False):\n """\n Convert a `.Line2D` to a `.Line3D` object.\n\n Parameters\n ----------\n zs : float\n The location along the *zdir* axis in 3D space to position the line.\n zdir : {'x', 'y', 'z'}\n Plane to plot line orthogonal to. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide lines with an endpoint outside the axes view limits.\n """\n\n line.__class__ = Line3D\n line.set_3d_properties(zs, zdir, axlim_clip)\n\n\ndef _path_to_3d_segment(path, zs=0, zdir='z'):\n """Convert a path to a 3D segment."""\n\n zs = np.broadcast_to(zs, len(path))\n pathsegs = path.iter_segments(simplify=False, curves=False)\n seg = [(x, y, z) for (((x, y), code), z) in zip(pathsegs, zs)]\n seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg]\n return seg3d\n\n\ndef _paths_to_3d_segments(paths, zs=0, zdir='z'):\n """Convert paths from a collection object to 3D segments."""\n\n if not np.iterable(zs):\n zs = np.broadcast_to(zs, len(paths))\n else:\n if len(zs) != len(paths):\n raise ValueError('Number of z-coordinates does not match paths.')\n\n segs = [_path_to_3d_segment(path, pathz, zdir)\n for path, pathz in zip(paths, zs)]\n return segs\n\n\ndef _path_to_3d_segment_with_codes(path, zs=0, zdir='z'):\n """Convert a path to a 3D segment with path codes."""\n\n zs = np.broadcast_to(zs, len(path))\n pathsegs = path.iter_segments(simplify=False, curves=False)\n seg_codes = [((x, y, z), code) for ((x, y), code), z in zip(pathsegs, zs)]\n if seg_codes:\n seg, codes = zip(*seg_codes)\n seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg]\n else:\n seg3d = []\n codes = []\n return seg3d, list(codes)\n\n\ndef _paths_to_3d_segments_with_codes(paths, zs=0, zdir='z'):\n """\n Convert paths from a collection object to 3D segments with path codes.\n """\n\n zs = np.broadcast_to(zs, len(paths))\n segments_codes = [_path_to_3d_segment_with_codes(path, pathz, zdir)\n for path, pathz in zip(paths, zs)]\n if segments_codes:\n segments, codes = zip(*segments_codes)\n else:\n segments, codes = [], []\n return list(segments), list(codes)\n\n\nclass Collection3D(Collection):\n """A collection of 3D paths."""\n\n def do_3d_projection(self):\n """Project the points according to renderer matrix."""\n vs_list = [vs for vs, _ in self._3dverts_codes]\n if self._axlim_clip:\n vs_list = [np.ma.row_stack(_viewlim_mask(*vs.T, self.axes)).T\n for vs in vs_list]\n xyzs_list = [proj3d.proj_transform(*vs.T, self.axes.M) for vs in vs_list]\n self._paths = [mpath.Path(np.ma.column_stack([xs, ys]), cs)\n for (xs, ys, _), (_, cs) in zip(xyzs_list, self._3dverts_codes)]\n zs = np.concatenate([zs for _, _, zs in xyzs_list])\n return zs.min() if len(zs) else 1e9\n\n\ndef collection_2d_to_3d(col, zs=0, zdir='z', axlim_clip=False):\n """Convert a `.Collection` to a `.Collection3D` object."""\n zs = np.broadcast_to(zs, len(col.get_paths()))\n col._3dverts_codes = [\n (np.column_stack(juggle_axes(\n *np.column_stack([p.vertices, np.broadcast_to(z, len(p.vertices))]).T,\n zdir)),\n p.codes)\n for p, z in zip(col.get_paths(), zs)]\n col.__class__ = cbook._make_class_factory(Collection3D, "{}3D")(type(col))\n col._axlim_clip = axlim_clip\n\n\nclass Line3DCollection(LineCollection):\n """\n A collection of 3D lines.\n """\n def __init__(self, lines, axlim_clip=False, **kwargs):\n super().__init__(lines, **kwargs)\n self._axlim_clip = axlim_clip\n\n def set_sort_zpos(self, val):\n """Set the position to use for z-sorting."""\n self._sort_zpos = val\n self.stale = True\n\n def set_segments(self, segments):\n """\n Set 3D segments.\n """\n self._segments3d = segments\n super().set_segments([])\n\n def do_3d_projection(self):\n """\n Project the points according to renderer matrix.\n """\n segments = self._segments3d\n if self._axlim_clip:\n all_points = np.ma.vstack(segments)\n masked_points = np.ma.column_stack([*_viewlim_mask(*all_points.T,\n self.axes)])\n segment_lengths = [np.shape(segment)[0] for segment in segments]\n segments = np.split(masked_points, np.cumsum(segment_lengths[:-1]))\n xyslist = [proj3d._proj_trans_points(points, self.axes.M)\n for points in segments]\n segments_2d = [np.ma.column_stack([xs, ys]) for xs, ys, zs in xyslist]\n LineCollection.set_segments(self, segments_2d)\n\n # FIXME\n minz = 1e9\n for xs, ys, zs in xyslist:\n minz = min(minz, min(zs))\n return minz\n\n\ndef line_collection_2d_to_3d(col, zs=0, zdir='z', axlim_clip=False):\n """Convert a `.LineCollection` to a `.Line3DCollection` object."""\n segments3d = _paths_to_3d_segments(col.get_paths(), zs, zdir)\n col.__class__ = Line3DCollection\n col.set_segments(segments3d)\n col._axlim_clip = axlim_clip\n\n\nclass Patch3D(Patch):\n """\n 3D patch object.\n """\n\n def __init__(self, *args, zs=(), zdir='z', axlim_clip=False, **kwargs):\n """\n Parameters\n ----------\n verts :\n zs : float\n The location along the *zdir* axis in 3D space to position the\n patch.\n zdir : {'x', 'y', 'z'}\n Plane to plot patch orthogonal to. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide patches with a vertex outside the axes view limits.\n """\n super().__init__(*args, **kwargs)\n self.set_3d_properties(zs, zdir, axlim_clip)\n\n def set_3d_properties(self, verts, zs=0, zdir='z', axlim_clip=False):\n """\n Set the *z* position and direction of the patch.\n\n Parameters\n ----------\n verts :\n zs : float\n The location along the *zdir* axis in 3D space to position the\n patch.\n zdir : {'x', 'y', 'z'}\n Plane to plot patch orthogonal to. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide patches with a vertex outside the axes view limits.\n """\n zs = np.broadcast_to(zs, len(verts))\n self._segment3d = [juggle_axes(x, y, z, zdir)\n for ((x, y), z) in zip(verts, zs)]\n self._axlim_clip = axlim_clip\n\n def get_path(self):\n # docstring inherited\n # self._path2d is not initialized until do_3d_projection\n if not hasattr(self, '_path2d'):\n self.axes.M = self.axes.get_proj()\n self.do_3d_projection()\n return self._path2d\n\n def do_3d_projection(self):\n s = self._segment3d\n if self._axlim_clip:\n xs, ys, zs = _viewlim_mask(*zip(*s), self.axes)\n else:\n xs, ys, zs = zip(*s)\n vxs, vys, vzs, vis = proj3d._proj_transform_clip(xs, ys, zs,\n self.axes.M,\n self.axes._focal_length)\n self._path2d = mpath.Path(np.ma.column_stack([vxs, vys]))\n return min(vzs)\n\n\nclass PathPatch3D(Patch3D):\n """\n 3D PathPatch object.\n """\n\n def __init__(self, path, *, zs=(), zdir='z', axlim_clip=False, **kwargs):\n """\n Parameters\n ----------\n path :\n zs : float\n The location along the *zdir* axis in 3D space to position the\n path patch.\n zdir : {'x', 'y', 'z', 3-tuple}\n Plane to plot path patch orthogonal to. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide path patches with a point outside the axes view limits.\n """\n # Not super().__init__!\n Patch.__init__(self, **kwargs)\n self.set_3d_properties(path, zs, zdir, axlim_clip)\n\n def set_3d_properties(self, path, zs=0, zdir='z', axlim_clip=False):\n """\n Set the *z* position and direction of the path patch.\n\n Parameters\n ----------\n path :\n zs : float\n The location along the *zdir* axis in 3D space to position the\n path patch.\n zdir : {'x', 'y', 'z', 3-tuple}\n Plane to plot path patch orthogonal to. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide path patches with a point outside the axes view limits.\n """\n Patch3D.set_3d_properties(self, path.vertices, zs=zs, zdir=zdir,\n axlim_clip=axlim_clip)\n self._code3d = path.codes\n\n def do_3d_projection(self):\n s = self._segment3d\n if self._axlim_clip:\n xs, ys, zs = _viewlim_mask(*zip(*s), self.axes)\n else:\n xs, ys, zs = zip(*s)\n vxs, vys, vzs, vis = proj3d._proj_transform_clip(xs, ys, zs,\n self.axes.M,\n self.axes._focal_length)\n self._path2d = mpath.Path(np.ma.column_stack([vxs, vys]), self._code3d)\n return min(vzs)\n\n\ndef _get_patch_verts(patch):\n """Return a list of vertices for the path of a patch."""\n trans = patch.get_patch_transform()\n path = patch.get_path()\n polygons = path.to_polygons(trans)\n return polygons[0] if len(polygons) else np.array([])\n\n\ndef patch_2d_to_3d(patch, z=0, zdir='z', axlim_clip=False):\n """Convert a `.Patch` to a `.Patch3D` object."""\n verts = _get_patch_verts(patch)\n patch.__class__ = Patch3D\n patch.set_3d_properties(verts, z, zdir, axlim_clip)\n\n\ndef pathpatch_2d_to_3d(pathpatch, z=0, zdir='z'):\n """Convert a `.PathPatch` to a `.PathPatch3D` object."""\n path = pathpatch.get_path()\n trans = pathpatch.get_patch_transform()\n\n mpath = trans.transform_path(path)\n pathpatch.__class__ = PathPatch3D\n pathpatch.set_3d_properties(mpath, z, zdir)\n\n\nclass Patch3DCollection(PatchCollection):\n """\n A collection of 3D patches.\n """\n\n def __init__(self, *args,\n zs=0, zdir='z', depthshade=True, axlim_clip=False, **kwargs):\n """\n Create a collection of flat 3D patches with its normal vector\n pointed in *zdir* direction, and located at *zs* on the *zdir*\n axis. 'zs' can be a scalar or an array-like of the same length as\n the number of patches in the collection.\n\n Constructor arguments are the same as for\n :class:`~matplotlib.collections.PatchCollection`. In addition,\n keywords *zs=0* and *zdir='z'* are available.\n\n Also, the keyword argument *depthshade* is available to indicate\n whether to shade the patches in order to give the appearance of depth\n (default is *True*). This is typically desired in scatter plots.\n """\n self._depthshade = depthshade\n super().__init__(*args, **kwargs)\n self.set_3d_properties(zs, zdir, axlim_clip)\n\n def get_depthshade(self):\n return self._depthshade\n\n def set_depthshade(self, depthshade):\n """\n Set whether depth shading is performed on collection members.\n\n Parameters\n ----------\n depthshade : bool\n Whether to shade the patches in order to give the appearance of\n depth.\n """\n self._depthshade = depthshade\n self.stale = True\n\n def set_sort_zpos(self, val):\n """Set the position to use for z-sorting."""\n self._sort_zpos = val\n self.stale = True\n\n def set_3d_properties(self, zs, zdir, axlim_clip=False):\n """\n Set the *z* positions and direction of the patches.\n\n Parameters\n ----------\n zs : float or array of floats\n The location or locations to place the patches in the collection\n along the *zdir* axis.\n zdir : {'x', 'y', 'z'}\n Plane to plot patches orthogonal to.\n All patches must have the same direction.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide patches with a vertex outside the axes view limits.\n """\n # Force the collection to initialize the face and edgecolors\n # just in case it is a scalarmappable with a colormap.\n self.update_scalarmappable()\n offsets = self.get_offsets()\n if len(offsets) > 0:\n xs, ys = offsets.T\n else:\n xs = []\n ys = []\n self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)\n self._z_markers_idx = slice(-1)\n self._vzs = None\n self._axlim_clip = axlim_clip\n self.stale = True\n\n def do_3d_projection(self):\n if self._axlim_clip:\n xs, ys, zs = _viewlim_mask(*self._offsets3d, self.axes)\n else:\n xs, ys, zs = self._offsets3d\n vxs, vys, vzs, vis = proj3d._proj_transform_clip(xs, ys, zs,\n self.axes.M,\n self.axes._focal_length)\n self._vzs = vzs\n super().set_offsets(np.ma.column_stack([vxs, vys]))\n\n if vzs.size > 0:\n return min(vzs)\n else:\n return np.nan\n\n def _maybe_depth_shade_and_sort_colors(self, color_array):\n color_array = (\n _zalpha(color_array, self._vzs)\n if self._vzs is not None and self._depthshade\n else color_array\n )\n if len(color_array) > 1:\n color_array = color_array[self._z_markers_idx]\n return mcolors.to_rgba_array(color_array, self._alpha)\n\n def get_facecolor(self):\n return self._maybe_depth_shade_and_sort_colors(super().get_facecolor())\n\n def get_edgecolor(self):\n # We need this check here to make sure we do not double-apply the depth\n # based alpha shading when the edge color is "face" which means the\n # edge colour should be identical to the face colour.\n if cbook._str_equal(self._edgecolors, 'face'):\n return self.get_facecolor()\n return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor())\n\n\nclass Path3DCollection(PathCollection):\n """\n A collection of 3D paths.\n """\n\n def __init__(self, *args,\n zs=0, zdir='z', depthshade=True, axlim_clip=False, **kwargs):\n """\n Create a collection of flat 3D paths with its normal vector\n pointed in *zdir* direction, and located at *zs* on the *zdir*\n axis. 'zs' can be a scalar or an array-like of the same length as\n the number of paths in the collection.\n\n Constructor arguments are the same as for\n :class:`~matplotlib.collections.PathCollection`. In addition,\n keywords *zs=0* and *zdir='z'* are available.\n\n Also, the keyword argument *depthshade* is available to indicate\n whether to shade the patches in order to give the appearance of depth\n (default is *True*). This is typically desired in scatter plots.\n """\n self._depthshade = depthshade\n self._in_draw = False\n super().__init__(*args, **kwargs)\n self.set_3d_properties(zs, zdir, axlim_clip)\n self._offset_zordered = None\n\n def draw(self, renderer):\n with self._use_zordered_offset():\n with cbook._setattr_cm(self, _in_draw=True):\n super().draw(renderer)\n\n def set_sort_zpos(self, val):\n """Set the position to use for z-sorting."""\n self._sort_zpos = val\n self.stale = True\n\n def set_3d_properties(self, zs, zdir, axlim_clip=False):\n """\n Set the *z* positions and direction of the paths.\n\n Parameters\n ----------\n zs : float or array of floats\n The location or locations to place the paths in the collection\n along the *zdir* axis.\n zdir : {'x', 'y', 'z'}\n Plane to plot paths orthogonal to.\n All paths must have the same direction.\n See `.get_dir_vector` for a description of the values.\n axlim_clip : bool, default: False\n Whether to hide paths with a vertex outside the axes view limits.\n """\n # Force the collection to initialize the face and edgecolors\n # just in case it is a scalarmappable with a colormap.\n self.update_scalarmappable()\n offsets = self.get_offsets()\n if len(offsets) > 0:\n xs, ys = offsets.T\n else:\n xs = []\n ys = []\n self._zdir = zdir\n self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)\n # In the base draw methods we access the attributes directly which\n # means we cannot resolve the shuffling in the getter methods like\n # we do for the edge and face colors.\n #\n # This means we need to carry around a cache of the unsorted sizes and\n # widths (postfixed with 3d) and in `do_3d_projection` set the\n # depth-sorted version of that data into the private state used by the\n # base collection class in its draw method.\n #\n # Grab the current sizes and linewidths to preserve them.\n self._sizes3d = self._sizes\n self._linewidths3d = np.array(self._linewidths)\n xs, ys, zs = self._offsets3d\n\n # Sort the points based on z coordinates\n # Performance optimization: Create a sorted index array and reorder\n # points and point properties according to the index array\n self._z_markers_idx = slice(-1)\n self._vzs = None\n\n self._axlim_clip = axlim_clip\n self.stale = True\n\n def set_sizes(self, sizes, dpi=72.0):\n super().set_sizes(sizes, dpi)\n if not self._in_draw:\n self._sizes3d = sizes\n\n def set_linewidth(self, lw):\n super().set_linewidth(lw)\n if not self._in_draw:\n self._linewidths3d = np.array(self._linewidths)\n\n def get_depthshade(self):\n return self._depthshade\n\n def set_depthshade(self, depthshade):\n """\n Set whether depth shading is performed on collection members.\n\n Parameters\n ----------\n depthshade : bool\n Whether to shade the patches in order to give the appearance of\n depth.\n """\n self._depthshade = depthshade\n self.stale = True\n\n def do_3d_projection(self):\n if self._axlim_clip:\n xs, ys, zs = _viewlim_mask(*self._offsets3d, self.axes)\n else:\n xs, ys, zs = self._offsets3d\n vxs, vys, vzs, vis = proj3d._proj_transform_clip(xs, ys, zs,\n self.axes.M,\n self.axes._focal_length)\n # Sort the points based on z coordinates\n # Performance optimization: Create a sorted index array and reorder\n # points and point properties according to the index array\n z_markers_idx = self._z_markers_idx = np.ma.argsort(vzs)[::-1]\n self._vzs = vzs\n\n # we have to special case the sizes because of code in collections.py\n # as the draw method does\n # self.set_sizes(self._sizes, self.figure.dpi)\n # so we cannot rely on doing the sorting on the way out via get_*\n\n if len(self._sizes3d) > 1:\n self._sizes = self._sizes3d[z_markers_idx]\n\n if len(self._linewidths3d) > 1:\n self._linewidths = self._linewidths3d[z_markers_idx]\n\n PathCollection.set_offsets(self, np.ma.column_stack((vxs, vys)))\n\n # Re-order items\n vzs = vzs[z_markers_idx]\n vxs = vxs[z_markers_idx]\n vys = vys[z_markers_idx]\n\n # Store ordered offset for drawing purpose\n self._offset_zordered = np.ma.column_stack((vxs, vys))\n\n return np.min(vzs) if vzs.size else np.nan\n\n @contextmanager\n def _use_zordered_offset(self):\n if self._offset_zordered is None:\n # Do nothing\n yield\n else:\n # Swap offset with z-ordered offset\n old_offset = self._offsets\n super().set_offsets(self._offset_zordered)\n try:\n yield\n finally:\n self._offsets = old_offset\n\n def _maybe_depth_shade_and_sort_colors(self, color_array):\n color_array = (\n _zalpha(color_array, self._vzs)\n if self._vzs is not None and self._depthshade\n else color_array\n )\n if len(color_array) > 1:\n color_array = color_array[self._z_markers_idx]\n return mcolors.to_rgba_array(color_array, self._alpha)\n\n def get_facecolor(self):\n return self._maybe_depth_shade_and_sort_colors(super().get_facecolor())\n\n def get_edgecolor(self):\n # We need this check here to make sure we do not double-apply the depth\n # based alpha shading when the edge color is "face" which means the\n # edge colour should be identical to the face colour.\n if cbook._str_equal(self._edgecolors, 'face'):\n return self.get_facecolor()\n return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor())\n\n\ndef patch_collection_2d_to_3d(col, zs=0, zdir='z', depthshade=True, axlim_clip=False):\n """\n Convert a `.PatchCollection` into a `.Patch3DCollection` object\n (or a `.PathCollection` into a `.Path3DCollection` object).\n\n Parameters\n ----------\n col : `~matplotlib.collections.PatchCollection` or \\n`~matplotlib.collections.PathCollection`\n The collection to convert.\n zs : float or array of floats\n The location or locations to place the patches in the collection along\n the *zdir* axis. Default: 0.\n zdir : {'x', 'y', 'z'}\n The axis in which to place the patches. Default: "z".\n See `.get_dir_vector` for a description of the values.\n depthshade : bool, default: True\n Whether to shade the patches to give a sense of depth.\n axlim_clip : bool, default: False\n Whether to hide patches with a vertex outside the axes view limits.\n """\n if isinstance(col, PathCollection):\n col.__class__ = Path3DCollection\n col._offset_zordered = None\n elif isinstance(col, PatchCollection):\n col.__class__ = Patch3DCollection\n col._depthshade = depthshade\n col._in_draw = False\n col.set_3d_properties(zs, zdir, axlim_clip)\n\n\nclass Poly3DCollection(PolyCollection):\n """\n A collection of 3D polygons.\n\n .. note::\n **Filling of 3D polygons**\n\n There is no simple definition of the enclosed surface of a 3D polygon\n unless the polygon is planar.\n\n In practice, Matplotlib fills the 2D projection of the polygon. This\n gives a correct filling appearance only for planar polygons. For all\n other polygons, you'll find orientations in which the edges of the\n polygon intersect in the projection. This will lead to an incorrect\n visualization of the 3D area.\n\n If you need filled areas, it is recommended to create them via\n `~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_trisurf`, which creates a\n triangulation and thus generates consistent surfaces.\n """\n\n def __init__(self, verts, *args, zsort='average', shade=False,\n lightsource=None, axlim_clip=False, **kwargs):\n """\n Parameters\n ----------\n verts : list of (N, 3) array-like\n The sequence of polygons [*verts0*, *verts1*, ...] where each\n element *verts_i* defines the vertices of polygon *i* as a 2D\n array-like of shape (N, 3).\n zsort : {'average', 'min', 'max'}, default: 'average'\n The calculation method for the z-order.\n See `~.Poly3DCollection.set_zsort` for details.\n shade : bool, default: False\n Whether to shade *facecolors* and *edgecolors*. When activating\n *shade*, *facecolors* and/or *edgecolors* must be provided.\n\n .. versionadded:: 3.7\n\n lightsource : `~matplotlib.colors.LightSource`, optional\n The lightsource to use when *shade* is True.\n\n .. versionadded:: 3.7\n\n axlim_clip : bool, default: False\n Whether to hide polygons with a vertex outside the view limits.\n\n *args, **kwargs\n All other parameters are forwarded to `.PolyCollection`.\n\n Notes\n -----\n Note that this class does a bit of magic with the _facecolors\n and _edgecolors properties.\n """\n if shade:\n normals = _generate_normals(verts)\n facecolors = kwargs.get('facecolors', None)\n if facecolors is not None:\n kwargs['facecolors'] = _shade_colors(\n facecolors, normals, lightsource\n )\n\n edgecolors = kwargs.get('edgecolors', None)\n if edgecolors is not None:\n kwargs['edgecolors'] = _shade_colors(\n edgecolors, normals, lightsource\n )\n if facecolors is None and edgecolors is None:\n raise ValueError(\n "You must provide facecolors, edgecolors, or both for "\n "shade to work.")\n super().__init__(verts, *args, **kwargs)\n if isinstance(verts, np.ndarray):\n if verts.ndim != 3:\n raise ValueError('verts must be a list of (N, 3) array-like')\n else:\n if any(len(np.shape(vert)) != 2 for vert in verts):\n raise ValueError('verts must be a list of (N, 3) array-like')\n self.set_zsort(zsort)\n self._codes3d = None\n self._axlim_clip = axlim_clip\n\n _zsort_functions = {\n 'average': np.average,\n 'min': np.min,\n 'max': np.max,\n }\n\n def set_zsort(self, zsort):\n """\n Set the calculation method for the z-order.\n\n Parameters\n ----------\n zsort : {'average', 'min', 'max'}\n The function applied on the z-coordinates of the vertices in the\n viewer's coordinate system, to determine the z-order.\n """\n self._zsortfunc = self._zsort_functions[zsort]\n self._sort_zpos = None\n self.stale = True\n\n @_api.deprecated("3.10")\n def get_vector(self, segments3d):\n return self._get_vector(segments3d)\n\n def _get_vector(self, segments3d):\n """Optimize points for projection."""\n if len(segments3d):\n xs, ys, zs = np.vstack(segments3d).T\n else: # vstack can't stack zero arrays.\n xs, ys, zs = [], [], []\n ones = np.ones(len(xs))\n self._vec = np.array([xs, ys, zs, ones])\n\n indices = [0, *np.cumsum([len(segment) for segment in segments3d])]\n self._segslices = [*map(slice, indices[:-1], indices[1:])]\n\n def set_verts(self, verts, closed=True):\n """\n Set 3D vertices.\n\n Parameters\n ----------\n verts : list of (N, 3) array-like\n The sequence of polygons [*verts0*, *verts1*, ...] where each\n element *verts_i* defines the vertices of polygon *i* as a 2D\n array-like of shape (N, 3).\n closed : bool, default: True\n Whether the polygon should be closed by adding a CLOSEPOLY\n connection at the end.\n """\n self._get_vector(verts)\n # 2D verts will be updated at draw time\n super().set_verts([], False)\n self._closed = closed\n\n def set_verts_and_codes(self, verts, codes):\n """Set 3D vertices with path codes."""\n # set vertices with closed=False to prevent PolyCollection from\n # setting path codes\n self.set_verts(verts, closed=False)\n # and set our own codes instead.\n self._codes3d = codes\n\n def set_3d_properties(self, axlim_clip=False):\n # Force the collection to initialize the face and edgecolors\n # just in case it is a scalarmappable with a colormap.\n self.update_scalarmappable()\n self._sort_zpos = None\n self.set_zsort('average')\n self._facecolor3d = PolyCollection.get_facecolor(self)\n self._edgecolor3d = PolyCollection.get_edgecolor(self)\n self._alpha3d = PolyCollection.get_alpha(self)\n self.stale = True\n\n def set_sort_zpos(self, val):\n """Set the position to use for z-sorting."""\n self._sort_zpos = val\n self.stale = True\n\n def do_3d_projection(self):\n """\n Perform the 3D projection for this object.\n """\n if self._A is not None:\n # force update of color mapping because we re-order them\n # below. If we do not do this here, the 2D draw will call\n # this, but we will never port the color mapped values back\n # to the 3D versions.\n #\n # We hold the 3D versions in a fixed order (the order the user\n # passed in) and sort the 2D version by view depth.\n self.update_scalarmappable()\n if self._face_is_mapped:\n self._facecolor3d = self._facecolors\n if self._edge_is_mapped:\n self._edgecolor3d = self._edgecolors\n if self._axlim_clip:\n xs, ys, zs = _viewlim_mask(*self._vec[0:3], self.axes)\n if self._vec.shape[0] == 4: # Will be 3 (xyz) or 4 (xyzw)\n w_masked = np.ma.masked_where(zs.mask, self._vec[3])\n vec = np.ma.array([xs, ys, zs, w_masked])\n else:\n vec = np.ma.array([xs, ys, zs])\n else:\n vec = self._vec\n txs, tys, tzs = proj3d._proj_transform_vec(vec, self.axes.M)\n xyzlist = [(txs[sl], tys[sl], tzs[sl]) for sl in self._segslices]\n\n # This extra fuss is to re-order face / edge colors\n cface = self._facecolor3d\n cedge = self._edgecolor3d\n if len(cface) != len(xyzlist):\n cface = cface.repeat(len(xyzlist), axis=0)\n if len(cedge) != len(xyzlist):\n if len(cedge) == 0:\n cedge = cface\n else:\n cedge = cedge.repeat(len(xyzlist), axis=0)\n\n if xyzlist:\n # sort by depth (furthest drawn first)\n z_segments_2d = sorted(\n ((self._zsortfunc(zs.data), np.ma.column_stack([xs, ys]), fc, ec, idx)\n for idx, ((xs, ys, zs), fc, ec)\n in enumerate(zip(xyzlist, cface, cedge))),\n key=lambda x: x[0], reverse=True)\n\n _, segments_2d, self._facecolors2d, self._edgecolors2d, idxs = \\n zip(*z_segments_2d)\n else:\n segments_2d = []\n self._facecolors2d = np.empty((0, 4))\n self._edgecolors2d = np.empty((0, 4))\n idxs = []\n\n if self._codes3d is not None:\n codes = [self._codes3d[idx] for idx in idxs]\n PolyCollection.set_verts_and_codes(self, segments_2d, codes)\n else:\n PolyCollection.set_verts(self, segments_2d, self._closed)\n\n if len(self._edgecolor3d) != len(cface):\n self._edgecolors2d = self._edgecolor3d\n\n # Return zorder value\n if self._sort_zpos is not None:\n zvec = np.array([[0], [0], [self._sort_zpos], [1]])\n ztrans = proj3d._proj_transform_vec(zvec, self.axes.M)\n return ztrans[2][0]\n elif tzs.size > 0:\n # FIXME: Some results still don't look quite right.\n # In particular, examine contourf3d_demo2.py\n # with az = -54 and elev = -45.\n return np.min(tzs)\n else:\n return np.nan\n\n def set_facecolor(self, colors):\n # docstring inherited\n super().set_facecolor(colors)\n self._facecolor3d = PolyCollection.get_facecolor(self)\n\n def set_edgecolor(self, colors):\n # docstring inherited\n super().set_edgecolor(colors)\n self._edgecolor3d = PolyCollection.get_edgecolor(self)\n\n def set_alpha(self, alpha):\n # docstring inherited\n artist.Artist.set_alpha(self, alpha)\n try:\n self._facecolor3d = mcolors.to_rgba_array(\n self._facecolor3d, self._alpha)\n except (AttributeError, TypeError, IndexError):\n pass\n try:\n self._edgecolors = mcolors.to_rgba_array(\n self._edgecolor3d, self._alpha)\n except (AttributeError, TypeError, IndexError):\n pass\n self.stale = True\n\n def get_facecolor(self):\n # docstring inherited\n # self._facecolors2d is not initialized until do_3d_projection\n if not hasattr(self, '_facecolors2d'):\n self.axes.M = self.axes.get_proj()\n self.do_3d_projection()\n return np.asarray(self._facecolors2d)\n\n def get_edgecolor(self):\n # docstring inherited\n # self._edgecolors2d is not initialized until do_3d_projection\n if not hasattr(self, '_edgecolors2d'):\n self.axes.M = self.axes.get_proj()\n self.do_3d_projection()\n return np.asarray(self._edgecolors2d)\n\n\ndef poly_collection_2d_to_3d(col, zs=0, zdir='z', axlim_clip=False):\n """\n Convert a `.PolyCollection` into a `.Poly3DCollection` object.\n\n Parameters\n ----------\n col : `~matplotlib.collections.PolyCollection`\n The collection to convert.\n zs : float or array of floats\n The location or locations to place the polygons in the collection along\n the *zdir* axis. Default: 0.\n zdir : {'x', 'y', 'z'}\n The axis in which to place the patches. Default: 'z'.\n See `.get_dir_vector` for a description of the values.\n """\n segments_3d, codes = _paths_to_3d_segments_with_codes(\n col.get_paths(), zs, zdir)\n col.__class__ = Poly3DCollection\n col.set_verts_and_codes(segments_3d, codes)\n col.set_3d_properties()\n col._axlim_clip = axlim_clip\n\n\ndef juggle_axes(xs, ys, zs, zdir):\n """\n Reorder coordinates so that 2D *xs*, *ys* can be plotted in the plane\n orthogonal to *zdir*. *zdir* is normally 'x', 'y' or 'z'. However, if\n *zdir* starts with a '-' it is interpreted as a compensation for\n `rotate_axes`.\n """\n if zdir == 'x':\n return zs, xs, ys\n elif zdir == 'y':\n return xs, zs, ys\n elif zdir[0] == '-':\n return rotate_axes(xs, ys, zs, zdir)\n else:\n return xs, ys, zs\n\n\ndef rotate_axes(xs, ys, zs, zdir):\n """\n Reorder coordinates so that the axes are rotated with *zdir* along\n the original z axis. Prepending the axis with a '-' does the\n inverse transform, so *zdir* can be 'x', '-x', 'y', '-y', 'z' or '-z'.\n """\n if zdir in ('x', '-y'):\n return ys, zs, xs\n elif zdir in ('-x', 'y'):\n return zs, xs, ys\n else:\n return xs, ys, zs\n\n\ndef _zalpha(colors, zs):\n """Modify the alphas of the color list according to depth."""\n # FIXME: This only works well if the points for *zs* are well-spaced\n # in all three dimensions. Otherwise, at certain orientations,\n # the min and max zs are very close together.\n # Should really normalize against the viewing depth.\n if len(colors) == 0 or len(zs) == 0:\n return np.zeros((0, 4))\n norm = Normalize(min(zs), max(zs))\n sats = 1 - norm(zs) * 0.7\n rgba = np.broadcast_to(mcolors.to_rgba_array(colors), (len(zs), 4))\n return np.column_stack([rgba[:, :3], rgba[:, 3] * sats])\n\n\ndef _all_points_on_plane(xs, ys, zs, atol=1e-8):\n """\n Check if all points are on the same plane. Note that NaN values are\n ignored.\n\n Parameters\n ----------\n xs, ys, zs : array-like\n The x, y, and z coordinates of the points.\n atol : float, default: 1e-8\n The tolerance for the equality check.\n """\n xs, ys, zs = np.asarray(xs), np.asarray(ys), np.asarray(zs)\n points = np.column_stack([xs, ys, zs])\n points = points[~np.isnan(points).any(axis=1)]\n # Check for the case where we have less than 3 unique points\n points = np.unique(points, axis=0)\n if len(points) <= 3:\n return True\n # Calculate the vectors from the first point to all other points\n vs = (points - points[0])[1:]\n vs = vs / np.linalg.norm(vs, axis=1)[:, np.newaxis]\n # Filter out parallel vectors\n vs = np.unique(vs, axis=0)\n if len(vs) <= 2:\n return True\n # Filter out parallel and antiparallel vectors to the first vector\n cross_norms = np.linalg.norm(np.cross(vs[0], vs[1:]), axis=1)\n zero_cross_norms = np.where(np.isclose(cross_norms, 0, atol=atol))[0] + 1\n vs = np.delete(vs, zero_cross_norms, axis=0)\n if len(vs) <= 2:\n return True\n # Calculate the normal vector from the first three points\n n = np.cross(vs[0], vs[1])\n n = n / np.linalg.norm(n)\n # If the dot product of the normal vector and all other vectors is zero,\n # all points are on the same plane\n dots = np.dot(n, vs.transpose())\n return np.allclose(dots, 0, atol=atol)\n\n\ndef _generate_normals(polygons):\n """\n Compute the normals of a list of polygons, one normal per polygon.\n\n Normals point towards the viewer for a face with its vertices in\n counterclockwise order, following the right hand rule.\n\n Uses three points equally spaced around the polygon. This method assumes\n that the points are in a plane. Otherwise, more than one shade is required,\n which is not supported.\n\n Parameters\n ----------\n polygons : list of (M_i, 3) array-like, or (..., M, 3) array-like\n A sequence of polygons to compute normals for, which can have\n varying numbers of vertices. If the polygons all have the same\n number of vertices and array is passed, then the operation will\n be vectorized.\n\n Returns\n -------\n normals : (..., 3) array\n A normal vector estimated for the polygon.\n """\n if isinstance(polygons, np.ndarray):\n # optimization: polygons all have the same number of points, so can\n # vectorize\n n = polygons.shape[-2]\n i1, i2, i3 = 0, n//3, 2*n//3\n v1 = polygons[..., i1, :] - polygons[..., i2, :]\n v2 = polygons[..., i2, :] - polygons[..., i3, :]\n else:\n # The subtraction doesn't vectorize because polygons is jagged.\n v1 = np.empty((len(polygons), 3))\n v2 = np.empty((len(polygons), 3))\n for poly_i, ps in enumerate(polygons):\n n = len(ps)\n ps = np.asarray(ps)\n i1, i2, i3 = 0, n//3, 2*n//3\n v1[poly_i, :] = ps[i1, :] - ps[i2, :]\n v2[poly_i, :] = ps[i2, :] - ps[i3, :]\n return np.cross(v1, v2)\n\n\ndef _shade_colors(color, normals, lightsource=None):\n """\n Shade *color* using normal vectors given by *normals*,\n assuming a *lightsource* (using default position if not given).\n *color* can also be an array of the same length as *normals*.\n """\n if lightsource is None:\n # chosen for backwards-compatibility\n lightsource = mcolors.LightSource(azdeg=225, altdeg=19.4712)\n\n with np.errstate(invalid="ignore"):\n shade = ((normals / np.linalg.norm(normals, axis=1, keepdims=True))\n @ lightsource.direction)\n mask = ~np.isnan(shade)\n\n if mask.any():\n # convert dot product to allowed shading fractions\n in_norm = mcolors.Normalize(-1, 1)\n out_norm = mcolors.Normalize(0.3, 1).inverse\n\n def norm(x):\n return out_norm(in_norm(x))\n\n shade[~mask] = 0\n\n color = mcolors.to_rgba_array(color)\n # shape of color should be (M, 4) (where M is number of faces)\n # shape of shade should be (M,)\n # colors should have final shape of (M, 4)\n alpha = color[:, 3]\n colors = norm(shade)[:, np.newaxis] * color\n colors[:, 3] = alpha\n else:\n colors = np.asanyarray(color).copy()\n\n return colors\n | .venv\Lib\site-packages\mpl_toolkits\mplot3d\art3d.py | art3d.py | Python | 50,548 | 0.75 | 0.166083 | 0.079639 | python-kit | 401 | 2024-11-04T03:08:40.630410 | Apache-2.0 | false | c7895c08aef3c664429b1c0d439f4ede |
# axis3d.py, original mplot3d version by John Porter\n# Created: 23 Sep 2005\n# Parts rewritten by Reinier Heeres <reinier@heeres.eu>\n\nimport inspect\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import (\n _api, artist, lines as mlines, axis as maxis, patches as mpatches,\n transforms as mtransforms, colors as mcolors)\nfrom . import art3d, proj3d\n\n\ndef _move_from_center(coord, centers, deltas, axmask=(True, True, True)):\n """\n For each coordinate where *axmask* is True, move *coord* away from\n *centers* by *deltas*.\n """\n coord = np.asarray(coord)\n return coord + axmask * np.copysign(1, coord - centers) * deltas\n\n\ndef _tick_update_position(tick, tickxs, tickys, labelpos):\n """Update tick line and label position and style."""\n\n tick.label1.set_position(labelpos)\n tick.label2.set_position(labelpos)\n tick.tick1line.set_visible(True)\n tick.tick2line.set_visible(False)\n tick.tick1line.set_linestyle('-')\n tick.tick1line.set_marker('')\n tick.tick1line.set_data(tickxs, tickys)\n tick.gridline.set_data([0], [0])\n\n\nclass Axis(maxis.XAxis):\n """An Axis class for the 3D plots."""\n # These points from the unit cube make up the x, y and z-planes\n _PLANES = (\n (0, 3, 7, 4), (1, 2, 6, 5), # yz planes\n (0, 1, 5, 4), (3, 2, 6, 7), # xz planes\n (0, 1, 2, 3), (4, 5, 6, 7), # xy planes\n )\n\n # Some properties for the axes\n _AXINFO = {\n 'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2)},\n 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2)},\n 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1)},\n }\n\n def _old_init(self, adir, v_intervalx, d_intervalx, axes, *args,\n rotate_label=None, **kwargs):\n return locals()\n\n def _new_init(self, axes, *, rotate_label=None, **kwargs):\n return locals()\n\n def __init__(self, *args, **kwargs):\n params = _api.select_matching_signature(\n [self._old_init, self._new_init], *args, **kwargs)\n if "adir" in params:\n _api.warn_deprecated(\n "3.6", message=f"The signature of 3D Axis constructors has "\n f"changed in %(since)s; the new signature is "\n f"{inspect.signature(type(self).__init__)}", pending=True)\n if params["adir"] != self.axis_name:\n raise ValueError(f"Cannot instantiate {type(self).__name__} "\n f"with adir={params['adir']!r}")\n axes = params["axes"]\n rotate_label = params["rotate_label"]\n args = params.get("args", ())\n kwargs = params["kwargs"]\n\n name = self.axis_name\n\n self._label_position = 'default'\n self._tick_position = 'default'\n\n # This is a temporary member variable.\n # Do not depend on this existing in future releases!\n self._axinfo = self._AXINFO[name].copy()\n # Common parts\n self._axinfo.update({\n 'label': {'va': 'center', 'ha': 'center',\n 'rotation_mode': 'anchor'},\n 'color': mpl.rcParams[f'axes3d.{name}axis.panecolor'],\n 'tick': {\n 'inward_factor': 0.2,\n 'outward_factor': 0.1,\n },\n })\n\n if mpl.rcParams['_internal.classic_mode']:\n self._axinfo.update({\n 'axisline': {'linewidth': 0.75, 'color': (0, 0, 0, 1)},\n 'grid': {\n 'color': (0.9, 0.9, 0.9, 1),\n 'linewidth': 1.0,\n 'linestyle': '-',\n },\n })\n self._axinfo['tick'].update({\n 'linewidth': {\n True: mpl.rcParams['lines.linewidth'], # major\n False: mpl.rcParams['lines.linewidth'], # minor\n }\n })\n else:\n self._axinfo.update({\n 'axisline': {\n 'linewidth': mpl.rcParams['axes.linewidth'],\n 'color': mpl.rcParams['axes.edgecolor'],\n },\n 'grid': {\n 'color': mpl.rcParams['grid.color'],\n 'linewidth': mpl.rcParams['grid.linewidth'],\n 'linestyle': mpl.rcParams['grid.linestyle'],\n },\n })\n self._axinfo['tick'].update({\n 'linewidth': {\n True: ( # major\n mpl.rcParams['xtick.major.width'] if name in 'xz'\n else mpl.rcParams['ytick.major.width']),\n False: ( # minor\n mpl.rcParams['xtick.minor.width'] if name in 'xz'\n else mpl.rcParams['ytick.minor.width']),\n }\n })\n\n super().__init__(axes, *args, **kwargs)\n\n # data and viewing intervals for this direction\n if "d_intervalx" in params:\n self.set_data_interval(*params["d_intervalx"])\n if "v_intervalx" in params:\n self.set_view_interval(*params["v_intervalx"])\n self.set_rotate_label(rotate_label)\n self._init3d() # Inline after init3d deprecation elapses.\n\n __init__.__signature__ = inspect.signature(_new_init)\n adir = _api.deprecated("3.6", pending=True)(\n property(lambda self: self.axis_name))\n\n def _init3d(self):\n self.line = mlines.Line2D(\n xdata=(0, 0), ydata=(0, 0),\n linewidth=self._axinfo['axisline']['linewidth'],\n color=self._axinfo['axisline']['color'],\n antialiased=True)\n\n # Store dummy data in Polygon object\n self.pane = mpatches.Polygon([[0, 0], [0, 1]], closed=False)\n self.set_pane_color(self._axinfo['color'])\n\n self.axes._set_artist_props(self.line)\n self.axes._set_artist_props(self.pane)\n self.gridlines = art3d.Line3DCollection([])\n self.axes._set_artist_props(self.gridlines)\n self.axes._set_artist_props(self.label)\n self.axes._set_artist_props(self.offsetText)\n # Need to be able to place the label at the correct location\n self.label._transform = self.axes.transData\n self.offsetText._transform = self.axes.transData\n\n @_api.deprecated("3.6", pending=True)\n def init3d(self): # After deprecation elapses, inline _init3d to __init__.\n self._init3d()\n\n def get_major_ticks(self, numticks=None):\n ticks = super().get_major_ticks(numticks)\n for t in ticks:\n for obj in [\n t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]:\n obj.set_transform(self.axes.transData)\n return ticks\n\n def get_minor_ticks(self, numticks=None):\n ticks = super().get_minor_ticks(numticks)\n for t in ticks:\n for obj in [\n t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]:\n obj.set_transform(self.axes.transData)\n return ticks\n\n def set_ticks_position(self, position):\n """\n Set the ticks position.\n\n Parameters\n ----------\n position : {'lower', 'upper', 'both', 'default', 'none'}\n The position of the bolded axis lines, ticks, and tick labels.\n """\n _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'],\n position=position)\n self._tick_position = position\n\n def get_ticks_position(self):\n """\n Get the ticks position.\n\n Returns\n -------\n str : {'lower', 'upper', 'both', 'default', 'none'}\n The position of the bolded axis lines, ticks, and tick labels.\n """\n return self._tick_position\n\n def set_label_position(self, position):\n """\n Set the label position.\n\n Parameters\n ----------\n position : {'lower', 'upper', 'both', 'default', 'none'}\n The position of the axis label.\n """\n _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'],\n position=position)\n self._label_position = position\n\n def get_label_position(self):\n """\n Get the label position.\n\n Returns\n -------\n str : {'lower', 'upper', 'both', 'default', 'none'}\n The position of the axis label.\n """\n return self._label_position\n\n def set_pane_color(self, color, alpha=None):\n """\n Set pane color.\n\n Parameters\n ----------\n color : :mpltype:`color`\n Color for axis pane.\n alpha : float, optional\n Alpha value for axis pane. If None, base it on *color*.\n """\n color = mcolors.to_rgba(color, alpha)\n self._axinfo['color'] = color\n self.pane.set_edgecolor(color)\n self.pane.set_facecolor(color)\n self.pane.set_alpha(color[-1])\n self.stale = True\n\n def set_rotate_label(self, val):\n """\n Whether to rotate the axis label: True, False or None.\n If set to None the label will be rotated if longer than 4 chars.\n """\n self._rotate_label = val\n self.stale = True\n\n def get_rotate_label(self, text):\n if self._rotate_label is not None:\n return self._rotate_label\n else:\n return len(text) > 4\n\n def _get_coord_info(self):\n mins, maxs = np.array([\n self.axes.get_xbound(),\n self.axes.get_ybound(),\n self.axes.get_zbound(),\n ]).T\n\n # Project the bounds along the current position of the cube:\n bounds = mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2]\n bounds_proj = self.axes._transformed_cube(bounds)\n\n # Determine which one of the parallel planes are higher up:\n means_z0 = np.zeros(3)\n means_z1 = np.zeros(3)\n for i in range(3):\n means_z0[i] = np.mean(bounds_proj[self._PLANES[2 * i], 2])\n means_z1[i] = np.mean(bounds_proj[self._PLANES[2 * i + 1], 2])\n highs = means_z0 < means_z1\n\n # Special handling for edge-on views\n equals = np.abs(means_z0 - means_z1) <= np.finfo(float).eps\n if np.sum(equals) == 2:\n vertical = np.where(~equals)[0][0]\n if vertical == 2: # looking at XY plane\n highs = np.array([True, True, highs[2]])\n elif vertical == 1: # looking at XZ plane\n highs = np.array([True, highs[1], False])\n elif vertical == 0: # looking at YZ plane\n highs = np.array([highs[0], False, False])\n\n return mins, maxs, bounds_proj, highs\n\n def _calc_centers_deltas(self, maxs, mins):\n centers = 0.5 * (maxs + mins)\n # In mpl3.8, the scale factor was 1/12. mpl3.9 changes this to\n # 1/12 * 24/25 = 0.08 to compensate for the change in automargin\n # behavior and keep appearance the same. The 24/25 factor is from the\n # 1/48 padding added to each side of the axis in mpl3.8.\n scale = 0.08\n deltas = (maxs - mins) * scale\n return centers, deltas\n\n def _get_axis_line_edge_points(self, minmax, maxmin, position=None):\n """Get the edge points for the black bolded axis line."""\n # When changing vertical axis some of the axes has to be\n # moved to the other plane so it looks the same as if the z-axis\n # was the vertical axis.\n mb = [minmax, maxmin] # line from origin to nearest corner to camera\n mb_rev = mb[::-1]\n mm = [[mb, mb_rev, mb_rev], [mb_rev, mb_rev, mb], [mb, mb, mb]]\n mm = mm[self.axes._vertical_axis][self._axinfo["i"]]\n\n juggled = self._axinfo["juggled"]\n edge_point_0 = mm[0].copy() # origin point\n\n if ((position == 'lower' and mm[1][juggled[-1]] < mm[0][juggled[-1]]) or\n (position == 'upper' and mm[1][juggled[-1]] > mm[0][juggled[-1]])):\n edge_point_0[juggled[-1]] = mm[1][juggled[-1]]\n else:\n edge_point_0[juggled[0]] = mm[1][juggled[0]]\n\n edge_point_1 = edge_point_0.copy()\n edge_point_1[juggled[1]] = mm[1][juggled[1]]\n\n return edge_point_0, edge_point_1\n\n def _get_all_axis_line_edge_points(self, minmax, maxmin, axis_position=None):\n # Determine edge points for the axis lines\n edgep1s = []\n edgep2s = []\n position = []\n if axis_position in (None, 'default'):\n edgep1, edgep2 = self._get_axis_line_edge_points(minmax, maxmin)\n edgep1s = [edgep1]\n edgep2s = [edgep2]\n position = ['default']\n else:\n edgep1_l, edgep2_l = self._get_axis_line_edge_points(minmax, maxmin,\n position='lower')\n edgep1_u, edgep2_u = self._get_axis_line_edge_points(minmax, maxmin,\n position='upper')\n if axis_position in ('lower', 'both'):\n edgep1s.append(edgep1_l)\n edgep2s.append(edgep2_l)\n position.append('lower')\n if axis_position in ('upper', 'both'):\n edgep1s.append(edgep1_u)\n edgep2s.append(edgep2_u)\n position.append('upper')\n return edgep1s, edgep2s, position\n\n def _get_tickdir(self, position):\n """\n Get the direction of the tick.\n\n Parameters\n ----------\n position : str, optional : {'upper', 'lower', 'default'}\n The position of the axis.\n\n Returns\n -------\n tickdir : int\n Index which indicates which coordinate the tick line will\n align with.\n """\n _api.check_in_list(('upper', 'lower', 'default'), position=position)\n\n # TODO: Move somewhere else where it's triggered less:\n tickdirs_base = [v["tickdir"] for v in self._AXINFO.values()] # default\n elev_mod = np.mod(self.axes.elev + 180, 360) - 180\n azim_mod = np.mod(self.axes.azim, 360)\n if position == 'upper':\n if elev_mod >= 0:\n tickdirs_base = [2, 2, 0]\n else:\n tickdirs_base = [1, 0, 0]\n if 0 <= azim_mod < 180:\n tickdirs_base[2] = 1\n elif position == 'lower':\n if elev_mod >= 0:\n tickdirs_base = [1, 0, 1]\n else:\n tickdirs_base = [2, 2, 1]\n if 0 <= azim_mod < 180:\n tickdirs_base[2] = 0\n info_i = [v["i"] for v in self._AXINFO.values()]\n\n i = self._axinfo["i"]\n vert_ax = self.axes._vertical_axis\n j = vert_ax - 2\n # default: tickdir = [[1, 2, 1], [2, 2, 0], [1, 0, 0]][vert_ax][i]\n tickdir = np.roll(info_i, -j)[np.roll(tickdirs_base, j)][i]\n return tickdir\n\n def active_pane(self):\n mins, maxs, tc, highs = self._get_coord_info()\n info = self._axinfo\n index = info['i']\n if not highs[index]:\n loc = mins[index]\n plane = self._PLANES[2 * index]\n else:\n loc = maxs[index]\n plane = self._PLANES[2 * index + 1]\n xys = np.array([tc[p] for p in plane])\n return xys, loc\n\n def draw_pane(self, renderer):\n """\n Draw pane.\n\n Parameters\n ----------\n renderer : `~matplotlib.backend_bases.RendererBase` subclass\n """\n renderer.open_group('pane3d', gid=self.get_gid())\n xys, loc = self.active_pane()\n self.pane.xy = xys[:, :2]\n self.pane.draw(renderer)\n renderer.close_group('pane3d')\n\n def _axmask(self):\n axmask = [True, True, True]\n axmask[self._axinfo["i"]] = False\n return axmask\n\n def _draw_ticks(self, renderer, edgep1, centers, deltas, highs,\n deltas_per_point, pos):\n ticks = self._update_ticks()\n info = self._axinfo\n index = info["i"]\n juggled = info["juggled"]\n\n mins, maxs, tc, highs = self._get_coord_info()\n centers, deltas = self._calc_centers_deltas(maxs, mins)\n\n # Draw ticks:\n tickdir = self._get_tickdir(pos)\n tickdelta = deltas[tickdir] if highs[tickdir] else -deltas[tickdir]\n\n tick_info = info['tick']\n tick_out = tick_info['outward_factor'] * tickdelta\n tick_in = tick_info['inward_factor'] * tickdelta\n tick_lw = tick_info['linewidth']\n edgep1_tickdir = edgep1[tickdir]\n out_tickdir = edgep1_tickdir + tick_out\n in_tickdir = edgep1_tickdir - tick_in\n\n default_label_offset = 8. # A rough estimate\n points = deltas_per_point * deltas\n for tick in ticks:\n # Get tick line positions\n pos = edgep1.copy()\n pos[index] = tick.get_loc()\n pos[tickdir] = out_tickdir\n x1, y1, z1 = proj3d.proj_transform(*pos, self.axes.M)\n pos[tickdir] = in_tickdir\n x2, y2, z2 = proj3d.proj_transform(*pos, self.axes.M)\n\n # Get position of label\n labeldeltas = (tick.get_pad() + default_label_offset) * points\n\n pos[tickdir] = edgep1_tickdir\n pos = _move_from_center(pos, centers, labeldeltas, self._axmask())\n lx, ly, lz = proj3d.proj_transform(*pos, self.axes.M)\n\n _tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly))\n tick.tick1line.set_linewidth(tick_lw[tick._major])\n tick.draw(renderer)\n\n def _draw_offset_text(self, renderer, edgep1, edgep2, labeldeltas, centers,\n highs, pep, dx, dy):\n # Get general axis information:\n info = self._axinfo\n index = info["i"]\n juggled = info["juggled"]\n tickdir = info["tickdir"]\n\n # Which of the two edge points do we want to\n # use for locating the offset text?\n if juggled[2] == 2:\n outeredgep = edgep1\n outerindex = 0\n else:\n outeredgep = edgep2\n outerindex = 1\n\n pos = _move_from_center(outeredgep, centers, labeldeltas,\n self._axmask())\n olx, oly, olz = proj3d.proj_transform(*pos, self.axes.M)\n self.offsetText.set_text(self.major.formatter.get_offset())\n self.offsetText.set_position((olx, oly))\n angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))\n self.offsetText.set_rotation(angle)\n # Must set rotation mode to "anchor" so that\n # the alignment point is used as the "fulcrum" for rotation.\n self.offsetText.set_rotation_mode('anchor')\n\n # ----------------------------------------------------------------------\n # Note: the following statement for determining the proper alignment of\n # the offset text. This was determined entirely by trial-and-error\n # and should not be in any way considered as "the way". There are\n # still some edge cases where alignment is not quite right, but this\n # seems to be more of a geometry issue (in other words, I might be\n # using the wrong reference points).\n #\n # (TT, FF, TF, FT) are the shorthand for the tuple of\n # (centpt[tickdir] <= pep[tickdir, outerindex],\n # centpt[index] <= pep[index, outerindex])\n #\n # Three-letters (e.g., TFT, FTT) are short-hand for the array of bools\n # from the variable 'highs'.\n # ---------------------------------------------------------------------\n centpt = proj3d.proj_transform(*centers, self.axes.M)\n if centpt[tickdir] > pep[tickdir, outerindex]:\n # if FT and if highs has an even number of Trues\n if (centpt[index] <= pep[index, outerindex]\n and np.count_nonzero(highs) % 2 == 0):\n # Usually, this means align right, except for the FTT case,\n # in which offset for axis 1 and 2 are aligned left.\n if highs.tolist() == [False, True, True] and index in (1, 2):\n align = 'left'\n else:\n align = 'right'\n else:\n # The FF case\n align = 'left'\n else:\n # if TF and if highs has an even number of Trues\n if (centpt[index] > pep[index, outerindex]\n and np.count_nonzero(highs) % 2 == 0):\n # Usually mean align left, except if it is axis 2\n align = 'right' if index == 2 else 'left'\n else:\n # The TT case\n align = 'right'\n\n self.offsetText.set_va('center')\n self.offsetText.set_ha(align)\n self.offsetText.draw(renderer)\n\n def _draw_labels(self, renderer, edgep1, edgep2, labeldeltas, centers, dx, dy):\n label = self._axinfo["label"]\n\n # Draw labels\n lxyz = 0.5 * (edgep1 + edgep2)\n lxyz = _move_from_center(lxyz, centers, labeldeltas, self._axmask())\n tlx, tly, tlz = proj3d.proj_transform(*lxyz, self.axes.M)\n self.label.set_position((tlx, tly))\n if self.get_rotate_label(self.label.get_text()):\n angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))\n self.label.set_rotation(angle)\n self.label.set_va(label['va'])\n self.label.set_ha(label['ha'])\n self.label.set_rotation_mode(label['rotation_mode'])\n self.label.draw(renderer)\n\n @artist.allow_rasterization\n def draw(self, renderer):\n self.label._transform = self.axes.transData\n self.offsetText._transform = self.axes.transData\n renderer.open_group("axis3d", gid=self.get_gid())\n\n # Get general axis information:\n mins, maxs, tc, highs = self._get_coord_info()\n centers, deltas = self._calc_centers_deltas(maxs, mins)\n\n # Calculate offset distances\n # A rough estimate; points are ambiguous since 3D plots rotate\n reltoinches = self.get_figure(root=False).dpi_scale_trans.inverted()\n ax_inches = reltoinches.transform(self.axes.bbox.size)\n ax_points_estimate = sum(72. * ax_inches)\n deltas_per_point = 48 / ax_points_estimate\n default_offset = 21.\n labeldeltas = (self.labelpad + default_offset) * deltas_per_point * deltas\n\n # Determine edge points for the axis lines\n minmax = np.where(highs, maxs, mins) # "origin" point\n maxmin = np.where(~highs, maxs, mins) # "opposite" corner near camera\n\n for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points(\n minmax, maxmin, self._tick_position)):\n # Project the edge points along the current position\n pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M)\n pep = np.asarray(pep)\n\n # The transAxes transform is used because the Text object\n # rotates the text relative to the display coordinate system.\n # Therefore, if we want the labels to remain parallel to the\n # axis regardless of the aspect ratio, we need to convert the\n # edge points of the plane to display coordinates and calculate\n # an angle from that.\n # TODO: Maybe Text objects should handle this themselves?\n dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) -\n self.axes.transAxes.transform([pep[0:2, 0]]))[0]\n\n # Draw the lines\n self.line.set_data(pep[0], pep[1])\n self.line.draw(renderer)\n\n # Draw ticks\n self._draw_ticks(renderer, edgep1, centers, deltas, highs,\n deltas_per_point, pos)\n\n # Draw Offset text\n self._draw_offset_text(renderer, edgep1, edgep2, labeldeltas,\n centers, highs, pep, dx, dy)\n\n for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points(\n minmax, maxmin, self._label_position)):\n # See comments above\n pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M)\n pep = np.asarray(pep)\n dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) -\n self.axes.transAxes.transform([pep[0:2, 0]]))[0]\n\n # Draw labels\n self._draw_labels(renderer, edgep1, edgep2, labeldeltas, centers, dx, dy)\n\n renderer.close_group('axis3d')\n self.stale = False\n\n @artist.allow_rasterization\n def draw_grid(self, renderer):\n if not self.axes._draw_grid:\n return\n\n renderer.open_group("grid3d", gid=self.get_gid())\n\n ticks = self._update_ticks()\n if len(ticks):\n # Get general axis information:\n info = self._axinfo\n index = info["i"]\n\n mins, maxs, tc, highs = self._get_coord_info()\n\n minmax = np.where(highs, maxs, mins)\n maxmin = np.where(~highs, maxs, mins)\n\n # Grid points where the planes meet\n xyz0 = np.tile(minmax, (len(ticks), 1))\n xyz0[:, index] = [tick.get_loc() for tick in ticks]\n\n # Grid lines go from the end of one plane through the plane\n # intersection (at xyz0) to the end of the other plane. The first\n # point (0) differs along dimension index-2 and the last (2) along\n # dimension index-1.\n lines = np.stack([xyz0, xyz0, xyz0], axis=1)\n lines[:, 0, index - 2] = maxmin[index - 2]\n lines[:, 2, index - 1] = maxmin[index - 1]\n self.gridlines.set_segments(lines)\n gridinfo = info['grid']\n self.gridlines.set_color(gridinfo['color'])\n self.gridlines.set_linewidth(gridinfo['linewidth'])\n self.gridlines.set_linestyle(gridinfo['linestyle'])\n self.gridlines.do_3d_projection()\n self.gridlines.draw(renderer)\n\n renderer.close_group('grid3d')\n\n # TODO: Get this to work (more) properly when mplot3d supports the\n # transforms framework.\n def get_tightbbox(self, renderer=None, *, for_layout_only=False):\n # docstring inherited\n if not self.get_visible():\n return\n # We have to directly access the internal data structures\n # (and hope they are up to date) because at draw time we\n # shift the ticks and their labels around in (x, y) space\n # based on the projection, the current view port, and their\n # position in 3D space. If we extend the transforms framework\n # into 3D we would not need to do this different book keeping\n # than we do in the normal axis\n major_locs = self.get_majorticklocs()\n minor_locs = self.get_minorticklocs()\n\n ticks = [*self.get_minor_ticks(len(minor_locs)),\n *self.get_major_ticks(len(major_locs))]\n view_low, view_high = self.get_view_interval()\n if view_low > view_high:\n view_low, view_high = view_high, view_low\n interval_t = self.get_transform().transform([view_low, view_high])\n\n ticks_to_draw = []\n for tick in ticks:\n try:\n loc_t = self.get_transform().transform(tick.get_loc())\n except AssertionError:\n # Transform.transform doesn't allow masked values but\n # some scales might make them, so we need this try/except.\n pass\n else:\n if mtransforms._interval_contains_close(interval_t, loc_t):\n ticks_to_draw.append(tick)\n\n ticks = ticks_to_draw\n\n bb_1, bb_2 = self._get_ticklabel_bboxes(ticks, renderer)\n other = []\n\n if self.line.get_visible():\n other.append(self.line.get_window_extent(renderer))\n if (self.label.get_visible() and not for_layout_only and\n self.label.get_text()):\n other.append(self.label.get_window_extent(renderer))\n\n return mtransforms.Bbox.union([*bb_1, *bb_2, *other])\n\n d_interval = _api.deprecated(\n "3.6", alternative="get_data_interval", pending=True)(\n property(lambda self: self.get_data_interval(),\n lambda self, minmax: self.set_data_interval(*minmax)))\n v_interval = _api.deprecated(\n "3.6", alternative="get_view_interval", pending=True)(\n property(lambda self: self.get_view_interval(),\n lambda self, minmax: self.set_view_interval(*minmax)))\n\n\nclass XAxis(Axis):\n axis_name = "x"\n get_view_interval, set_view_interval = maxis._make_getset_interval(\n "view", "xy_viewLim", "intervalx")\n get_data_interval, set_data_interval = maxis._make_getset_interval(\n "data", "xy_dataLim", "intervalx")\n\n\nclass YAxis(Axis):\n axis_name = "y"\n get_view_interval, set_view_interval = maxis._make_getset_interval(\n "view", "xy_viewLim", "intervaly")\n get_data_interval, set_data_interval = maxis._make_getset_interval(\n "data", "xy_dataLim", "intervaly")\n\n\nclass ZAxis(Axis):\n axis_name = "z"\n get_view_interval, set_view_interval = maxis._make_getset_interval(\n "view", "zz_viewLim", "intervalx")\n get_data_interval, set_data_interval = maxis._make_getset_interval(\n "data", "zz_dataLim", "intervalx")\n | .venv\Lib\site-packages\mpl_toolkits\mplot3d\axis3d.py | axis3d.py | Python | 29,327 | 0.95 | 0.146667 | 0.143526 | react-lib | 350 | 2025-02-06T01:32:05.099612 | Apache-2.0 | false | 6ec22476095927561afa83491283d24d |
"""\nVarious transforms used for by the 3D code\n"""\n\nimport numpy as np\n\nfrom matplotlib import _api\n\n\ndef world_transformation(xmin, xmax,\n ymin, ymax,\n zmin, zmax, pb_aspect=None):\n """\n Produce a matrix that scales homogeneous coords in the specified ranges\n to [0, 1], or [0, pb_aspect[i]] if the plotbox aspect ratio is specified.\n """\n dx = xmax - xmin\n dy = ymax - ymin\n dz = zmax - zmin\n if pb_aspect is not None:\n ax, ay, az = pb_aspect\n dx /= ax\n dy /= ay\n dz /= az\n\n return np.array([[1/dx, 0, 0, -xmin/dx],\n [ 0, 1/dy, 0, -ymin/dy],\n [ 0, 0, 1/dz, -zmin/dz],\n [ 0, 0, 0, 1]])\n\n\ndef _rotation_about_vector(v, angle):\n """\n Produce a rotation matrix for an angle in radians about a vector.\n """\n vx, vy, vz = v / np.linalg.norm(v)\n s = np.sin(angle)\n c = np.cos(angle)\n t = 2*np.sin(angle/2)**2 # more numerically stable than t = 1-c\n\n R = np.array([\n [t*vx*vx + c, t*vx*vy - vz*s, t*vx*vz + vy*s],\n [t*vy*vx + vz*s, t*vy*vy + c, t*vy*vz - vx*s],\n [t*vz*vx - vy*s, t*vz*vy + vx*s, t*vz*vz + c]])\n\n return R\n\n\ndef _view_axes(E, R, V, roll):\n """\n Get the unit viewing axes in data coordinates.\n\n Parameters\n ----------\n E : 3-element numpy array\n The coordinates of the eye/camera.\n R : 3-element numpy array\n The coordinates of the center of the view box.\n V : 3-element numpy array\n Unit vector in the direction of the vertical axis.\n roll : float\n The roll angle in radians.\n\n Returns\n -------\n u : 3-element numpy array\n Unit vector pointing towards the right of the screen.\n v : 3-element numpy array\n Unit vector pointing towards the top of the screen.\n w : 3-element numpy array\n Unit vector pointing out of the screen.\n """\n w = (E - R)\n w = w/np.linalg.norm(w)\n u = np.cross(V, w)\n u = u/np.linalg.norm(u)\n v = np.cross(w, u) # Will be a unit vector\n\n # Save some computation for the default roll=0\n if roll != 0:\n # A positive rotation of the camera is a negative rotation of the world\n Rroll = _rotation_about_vector(w, -roll)\n u = np.dot(Rroll, u)\n v = np.dot(Rroll, v)\n return u, v, w\n\n\ndef _view_transformation_uvw(u, v, w, E):\n """\n Return the view transformation matrix.\n\n Parameters\n ----------\n u : 3-element numpy array\n Unit vector pointing towards the right of the screen.\n v : 3-element numpy array\n Unit vector pointing towards the top of the screen.\n w : 3-element numpy array\n Unit vector pointing out of the screen.\n E : 3-element numpy array\n The coordinates of the eye/camera.\n """\n Mr = np.eye(4)\n Mt = np.eye(4)\n Mr[:3, :3] = [u, v, w]\n Mt[:3, -1] = -E\n M = np.dot(Mr, Mt)\n return M\n\n\ndef _persp_transformation(zfront, zback, focal_length):\n e = focal_length\n a = 1 # aspect ratio\n b = (zfront+zback)/(zfront-zback)\n c = -2*(zfront*zback)/(zfront-zback)\n proj_matrix = np.array([[e, 0, 0, 0],\n [0, e/a, 0, 0],\n [0, 0, b, c],\n [0, 0, -1, 0]])\n return proj_matrix\n\n\ndef _ortho_transformation(zfront, zback):\n # note: w component in the resulting vector will be (zback-zfront), not 1\n a = -(zfront + zback)\n b = -(zfront - zback)\n proj_matrix = np.array([[2, 0, 0, 0],\n [0, 2, 0, 0],\n [0, 0, -2, 0],\n [0, 0, a, b]])\n return proj_matrix\n\n\ndef _proj_transform_vec(vec, M):\n vecw = np.dot(M, vec.data)\n w = vecw[3]\n txs, tys, tzs = vecw[0]/w, vecw[1]/w, vecw[2]/w\n if np.ma.isMA(vec[0]): # we check each to protect for scalars\n txs = np.ma.array(txs, mask=vec[0].mask)\n if np.ma.isMA(vec[1]):\n tys = np.ma.array(tys, mask=vec[1].mask)\n if np.ma.isMA(vec[2]):\n tzs = np.ma.array(tzs, mask=vec[2].mask)\n return txs, tys, tzs\n\n\ndef _proj_transform_vec_clip(vec, M, focal_length):\n vecw = np.dot(M, vec.data)\n w = vecw[3]\n txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w\n if np.isinf(focal_length): # don't clip orthographic projection\n tis = np.ones(txs.shape, dtype=bool)\n else:\n tis = (-1 <= txs) & (txs <= 1) & (-1 <= tys) & (tys <= 1) & (tzs <= 0)\n if np.ma.isMA(vec[0]):\n tis = tis & ~vec[0].mask\n if np.ma.isMA(vec[1]):\n tis = tis & ~vec[1].mask\n if np.ma.isMA(vec[2]):\n tis = tis & ~vec[2].mask\n\n txs = np.ma.masked_array(txs, ~tis)\n tys = np.ma.masked_array(tys, ~tis)\n tzs = np.ma.masked_array(tzs, ~tis)\n return txs, tys, tzs, tis\n\n\ndef inv_transform(xs, ys, zs, invM):\n """\n Transform the points by the inverse of the projection matrix, *invM*.\n """\n vec = _vec_pad_ones(xs, ys, zs)\n vecr = np.dot(invM, vec)\n if vecr.shape == (4,):\n vecr = vecr.reshape((4, 1))\n for i in range(vecr.shape[1]):\n if vecr[3][i] != 0:\n vecr[:, i] = vecr[:, i] / vecr[3][i]\n return vecr[0], vecr[1], vecr[2]\n\n\ndef _vec_pad_ones(xs, ys, zs):\n if np.ma.isMA(xs) or np.ma.isMA(ys) or np.ma.isMA(zs):\n return np.ma.array([xs, ys, zs, np.ones_like(xs)])\n else:\n return np.array([xs, ys, zs, np.ones_like(xs)])\n\n\ndef proj_transform(xs, ys, zs, M):\n """\n Transform the points by the projection matrix *M*.\n """\n vec = _vec_pad_ones(xs, ys, zs)\n return _proj_transform_vec(vec, M)\n\n\n@_api.deprecated("3.10")\ndef proj_transform_clip(xs, ys, zs, M):\n return _proj_transform_clip(xs, ys, zs, M, focal_length=np.inf)\n\n\ndef _proj_transform_clip(xs, ys, zs, M, focal_length):\n """\n Transform the points by the projection matrix\n and return the clipping result\n returns txs, tys, tzs, tis\n """\n vec = _vec_pad_ones(xs, ys, zs)\n return _proj_transform_vec_clip(vec, M, focal_length)\n\n\ndef _proj_points(points, M):\n return np.column_stack(_proj_trans_points(points, M))\n\n\ndef _proj_trans_points(points, M):\n points = np.asanyarray(points)\n xs, ys, zs = points[:, 0], points[:, 1], points[:, 2]\n return proj_transform(xs, ys, zs, M)\n | .venv\Lib\site-packages\mpl_toolkits\mplot3d\proj3d.py | proj3d.py | Python | 6,349 | 0.95 | 0.150685 | 0.01676 | react-lib | 750 | 2024-12-07T14:41:33.823216 | MIT | false | 31115df53ea7d7288d5a387cf257d850 |
from .axes3d import Axes3D\n\n__all__ = ['Axes3D']\n | .venv\Lib\site-packages\mpl_toolkits\mplot3d\__init__.py | __init__.py | Python | 49 | 0.65 | 0 | 0 | react-lib | 20 | 2024-02-19T02:33:00.245426 | GPL-3.0 | false | d48e3080576282f5ecc89eed679ecd48 |
from matplotlib.testing.conftest import (mpl_test_settings, # noqa\n pytest_configure, pytest_unconfigure)\n | .venv\Lib\site-packages\mpl_toolkits\mplot3d\tests\conftest.py | conftest.py | Python | 147 | 0.95 | 0 | 0 | node-utils | 371 | 2025-04-23T06:11:49.386142 | Apache-2.0 | true | a9af9c9b2ae8eefcebb125a652ac4c2b |
import numpy as np\n\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.backend_bases import MouseEvent\nfrom mpl_toolkits.mplot3d.art3d import (\n Line3DCollection,\n Poly3DCollection,\n _all_points_on_plane,\n)\n\n\ndef test_scatter_3d_projection_conservation():\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n # fix axes3d projection\n ax.roll = 0\n ax.elev = 0\n ax.azim = -45\n ax.stale = True\n\n x = [0, 1, 2, 3, 4]\n scatter_collection = ax.scatter(x, x, x)\n fig.canvas.draw_idle()\n\n # Get scatter location on canvas and freeze the data\n scatter_offset = scatter_collection.get_offsets()\n scatter_location = ax.transData.transform(scatter_offset)\n\n # Yaw -44 and -46 are enough to produce two set of scatter\n # with opposite z-order without moving points too far\n for azim in (-44, -46):\n ax.azim = azim\n ax.stale = True\n fig.canvas.draw_idle()\n\n for i in range(5):\n # Create a mouse event used to locate and to get index\n # from each dots\n event = MouseEvent("button_press_event", fig.canvas,\n *scatter_location[i, :])\n contains, ind = scatter_collection.contains(event)\n assert contains is True\n assert len(ind["ind"]) == 1\n assert ind["ind"][0] == i\n\n\ndef test_zordered_error():\n # Smoke test for https://github.com/matplotlib/matplotlib/issues/26497\n lc = [(np.fromiter([0.0, 0.0, 0.0], dtype="float"),\n np.fromiter([1.0, 1.0, 1.0], dtype="float"))]\n pc = [np.fromiter([0.0, 0.0], dtype="float"),\n np.fromiter([0.0, 1.0], dtype="float"),\n np.fromiter([1.0, 1.0], dtype="float")]\n\n fig = plt.figure()\n ax = fig.add_subplot(projection="3d")\n ax.add_collection(Line3DCollection(lc))\n ax.scatter(*pc, visible=False)\n plt.draw()\n\n\ndef test_all_points_on_plane():\n # Non-coplanar points\n points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]])\n assert not _all_points_on_plane(*points.T)\n\n # Duplicate points\n points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0]])\n assert _all_points_on_plane(*points.T)\n\n # NaN values\n points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, np.nan]])\n assert _all_points_on_plane(*points.T)\n\n # Less than 3 unique points\n points = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n assert _all_points_on_plane(*points.T)\n\n # All points lie on a line\n points = np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0]])\n assert _all_points_on_plane(*points.T)\n\n # All points lie on two lines, with antiparallel vectors\n points = np.array([[-2, 2, 0], [-1, 1, 0], [1, -1, 0],\n [0, 0, 0], [2, 0, 0], [1, 0, 0]])\n assert _all_points_on_plane(*points.T)\n\n # All points lie on a plane\n points = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 2, 0]])\n assert _all_points_on_plane(*points.T)\n\n\ndef test_generate_normals():\n # Smoke test for https://github.com/matplotlib/matplotlib/issues/29156\n vertices = ((0, 0, 0), (0, 5, 0), (5, 5, 0), (5, 0, 0))\n shape = Poly3DCollection([vertices], edgecolors='r', shade=True)\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n ax.add_collection3d(shape)\n plt.draw()\n | .venv\Lib\site-packages\mpl_toolkits\mplot3d\tests\test_art3d.py | test_art3d.py | Python | 3,317 | 0.95 | 0.078431 | 0.2 | python-kit | 835 | 2025-05-25T03:00:24.769234 | GPL-3.0 | true | d3340912b4fa96421bc49c2986f29da7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.