diff --git a/.gitattributes b/.gitattributes index 1d02c292d7aacfbe4856daaa607f4760a3c8f81d..6496895a39f4137df793d01990a7699abfd91d9d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -914,3 +914,4 @@ videochat2/lib/python3.10/site-packages/torch/_inductor/__pycache__/lowering.cpy videochat2/lib/python3.10/site-packages/torch/_inductor/__pycache__/ir.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text videochat2/lib/python3.10/site-packages/torch/lib/libc10_cuda.so filter=lfs diff=lfs merge=lfs -text videochat2/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/parrot/lib/python3.10/site-packages/matplotlib/_mathtext.py b/parrot/lib/python3.10/site-packages/matplotlib/_mathtext.py new file mode 100644 index 0000000000000000000000000000000000000000..6e4df209b1f91cbcb45b534e835431ddfce730b5 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/_mathtext.py @@ -0,0 +1,2861 @@ +""" +Implementation details for :mod:`.mathtext`. +""" + +from __future__ import annotations + +import abc +import copy +import enum +import functools +import logging +import os +import re +import types +import unicodedata +import string +import typing as T +from typing import NamedTuple + +import numpy as np +from pyparsing import ( + Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional, + ParseBaseException, ParseException, ParseExpression, ParseFatalException, + ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore, + pyparsing_common, Group) + +import matplotlib as mpl +from . import cbook +from ._mathtext_data import ( + latex_to_bakoma, stix_glyph_fixes, stix_virtual_fonts, tex2uni) +from .font_manager import FontProperties, findfont, get_font +from .ft2font import FT2Font, FT2Image, KERNING_DEFAULT + +from packaging.version import parse as parse_version +from pyparsing import __version__ as pyparsing_version +if parse_version(pyparsing_version).major < 3: + from pyparsing import nestedExpr as nested_expr +else: + from pyparsing import nested_expr + +if T.TYPE_CHECKING: + from collections.abc import Iterable + from .ft2font import Glyph + +ParserElement.enablePackrat() +_log = logging.getLogger("matplotlib.mathtext") + + +############################################################################## +# FONTS + + +def get_unicode_index(symbol: str) -> int: # Publicly exported. + r""" + Return the integer index (from the Unicode table) of *symbol*. + + Parameters + ---------- + symbol : str + A single (Unicode) character, a TeX command (e.g. r'\pi') or a Type1 + symbol name (e.g. 'phi'). + """ + try: # This will succeed if symbol is a single Unicode char + return ord(symbol) + except TypeError: + pass + try: # Is symbol a TeX symbol (i.e. \alpha) + return tex2uni[symbol.strip("\\")] + except KeyError as err: + raise ValueError( + f"{symbol!r} is not a valid Unicode character or TeX/Type1 symbol" + ) from err + + +class VectorParse(NamedTuple): + """ + The namedtuple type returned by ``MathTextParser("path").parse(...)``. + + Attributes + ---------- + width, height, depth : float + The global metrics. + glyphs : list + The glyphs including their positions. + rect : list + The list of rectangles. + """ + width: float + height: float + depth: float + glyphs: list[tuple[FT2Font, float, int, float, float]] + rects: list[tuple[float, float, float, float]] + +VectorParse.__module__ = "matplotlib.mathtext" + + +class RasterParse(NamedTuple): + """ + The namedtuple type returned by ``MathTextParser("agg").parse(...)``. + + Attributes + ---------- + ox, oy : float + The offsets are always zero. + width, height, depth : float + The global metrics. + image : FT2Image + A raster image. + """ + ox: float + oy: float + width: float + height: float + depth: float + image: FT2Image + +RasterParse.__module__ = "matplotlib.mathtext" + + +class Output: + r""" + Result of `ship`\ping a box: lists of positioned glyphs and rectangles. + + This class is not exposed to end users, but converted to a `VectorParse` or + a `RasterParse` by `.MathTextParser.parse`. + """ + + def __init__(self, box: Box): + self.box = box + self.glyphs: list[tuple[float, float, FontInfo]] = [] # (ox, oy, info) + self.rects: list[tuple[float, float, float, float]] = [] # (x1, y1, x2, y2) + + def to_vector(self) -> VectorParse: + w, h, d = map( + np.ceil, [self.box.width, self.box.height, self.box.depth]) + gs = [(info.font, info.fontsize, info.num, ox, h - oy + info.offset) + for ox, oy, info in self.glyphs] + rs = [(x1, h - y2, x2 - x1, y2 - y1) + for x1, y1, x2, y2 in self.rects] + return VectorParse(w, h + d, d, gs, rs) + + def to_raster(self, *, antialiased: bool) -> RasterParse: + # Metrics y's and mathtext y's are oriented in opposite directions, + # hence the switch between ymin and ymax. + xmin = min([*[ox + info.metrics.xmin for ox, oy, info in self.glyphs], + *[x1 for x1, y1, x2, y2 in self.rects], 0]) - 1 + ymin = min([*[oy - info.metrics.ymax for ox, oy, info in self.glyphs], + *[y1 for x1, y1, x2, y2 in self.rects], 0]) - 1 + xmax = max([*[ox + info.metrics.xmax for ox, oy, info in self.glyphs], + *[x2 for x1, y1, x2, y2 in self.rects], 0]) + 1 + ymax = max([*[oy - info.metrics.ymin for ox, oy, info in self.glyphs], + *[y2 for x1, y1, x2, y2 in self.rects], 0]) + 1 + w = xmax - xmin + h = ymax - ymin - self.box.depth + d = ymax - ymin - self.box.height + image = FT2Image(np.ceil(w), np.ceil(h + max(d, 0))) + + # Ideally, we could just use self.glyphs and self.rects here, shifting + # their coordinates by (-xmin, -ymin), but this yields slightly + # different results due to floating point slop; shipping twice is the + # old approach and keeps baseline images backcompat. + shifted = ship(self.box, (-xmin, -ymin)) + + for ox, oy, info in shifted.glyphs: + info.font.draw_glyph_to_bitmap( + image, ox, oy - info.metrics.iceberg, info.glyph, + antialiased=antialiased) + for x1, y1, x2, y2 in shifted.rects: + height = max(int(y2 - y1) - 1, 0) + if height == 0: + center = (y2 + y1) / 2 + y = int(center - (height + 1) / 2) + else: + y = int(y1) + image.draw_rect_filled(int(x1), y, np.ceil(x2), y + height) + return RasterParse(0, 0, w, h + d, d, image) + + +class FontMetrics(NamedTuple): + """ + Metrics of a font. + + Attributes + ---------- + advance : float + The advance distance (in points) of the glyph. + height : float + The height of the glyph in points. + width : float + The width of the glyph in points. + xmin, xmax, ymin, ymax : float + The ink rectangle of the glyph. + iceberg : float + The distance from the baseline to the top of the glyph. (This corresponds to + TeX's definition of "height".) + slanted : bool + Whether the glyph should be considered as "slanted" (currently used for kerning + sub/superscripts). + """ + advance: float + height: float + width: float + xmin: float + xmax: float + ymin: float + ymax: float + iceberg: float + slanted: bool + + +class FontInfo(NamedTuple): + font: FT2Font + fontsize: float + postscript_name: str + metrics: FontMetrics + num: int + glyph: Glyph + offset: float + + +class Fonts(abc.ABC): + """ + An abstract base class for a system of fonts to use for mathtext. + + The class must be able to take symbol keys and font file names and + return the character metrics. It also delegates to a backend class + to do the actual drawing. + """ + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + """ + Parameters + ---------- + default_font_prop : `~.font_manager.FontProperties` + The default non-math font, or the base font for Unicode (generic) + font rendering. + load_glyph_flags : int + Flags passed to the glyph loader (e.g. ``FT_Load_Glyph`` and + ``FT_Load_Char`` for FreeType-based fonts). + """ + self.default_font_prop = default_font_prop + self.load_glyph_flags = load_glyph_flags + + def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float, + font2: str, fontclass2: str, sym2: str, fontsize2: float, + dpi: float) -> float: + """ + Get the kerning distance for font between *sym1* and *sym2*. + + See `~.Fonts.get_metrics` for a detailed description of the parameters. + """ + return 0. + + def _get_font(self, font: str) -> FT2Font: + raise NotImplementedError + + def _get_info(self, font: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontInfo: + raise NotImplementedError + + def get_metrics(self, font: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontMetrics: + r""" + Parameters + ---------- + font : str + One of the TeX font names: "tt", "it", "rm", "cal", "sf", "bf", + "default", "regular", "bb", "frak", "scr". "default" and "regular" + are synonyms and use the non-math font. + font_class : str + One of the TeX font names (as for *font*), but **not** "bb", + "frak", or "scr". This is used to combine two font classes. The + only supported combination currently is ``get_metrics("frak", "bf", + ...)``. + sym : str + A symbol in raw TeX form, e.g., "1", "x", or "\sigma". + fontsize : float + Font size in points. + dpi : float + Rendering dots-per-inch. + + Returns + ------- + FontMetrics + """ + info = self._get_info(font, font_class, sym, fontsize, dpi) + return info.metrics + + def render_glyph(self, output: Output, ox: float, oy: float, font: str, + font_class: str, sym: str, fontsize: float, dpi: float) -> None: + """ + At position (*ox*, *oy*), draw the glyph specified by the remaining + parameters (see `get_metrics` for their detailed description). + """ + info = self._get_info(font, font_class, sym, fontsize, dpi) + output.glyphs.append((ox, oy, info)) + + def render_rect_filled(self, output: Output, + x1: float, y1: float, x2: float, y2: float) -> None: + """ + Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*). + """ + output.rects.append((x1, y1, x2, y2)) + + def get_xheight(self, font: str, fontsize: float, dpi: float) -> float: + """ + Get the xheight for the given *font* and *fontsize*. + """ + raise NotImplementedError() + + def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float: + """ + Get the line thickness that matches the given font. Used as a + base unit for drawing lines such as in a fraction or radical. + """ + raise NotImplementedError() + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + """ + Override if your font provides multiple sizes of the same + symbol. Should return a list of symbols matching *sym* in + various sizes. The expression renderer will select the most + appropriate size for a given situation from this list. + """ + return [(fontname, sym)] + + +class TruetypeFonts(Fonts, metaclass=abc.ABCMeta): + """ + A generic base class for all font setups that use Truetype fonts + (through FT2Font). + """ + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + super().__init__(default_font_prop, load_glyph_flags) + # Per-instance cache. + self._get_info = functools.cache(self._get_info) # type: ignore[method-assign] + self._fonts = {} + self.fontmap: dict[str | int, str] = {} + + filename = findfont(self.default_font_prop) + default_font = get_font(filename) + self._fonts['default'] = default_font + self._fonts['regular'] = default_font + + def _get_font(self, font: str | int) -> FT2Font: + if font in self.fontmap: + basename = self.fontmap[font] + else: + # NOTE: An int is only passed by subclasses which have placed int keys into + # `self.fontmap`, so we must cast this to confirm it to typing. + basename = T.cast(str, font) + cached_font = self._fonts.get(basename) + if cached_font is None and os.path.exists(basename): + cached_font = get_font(basename) + self._fonts[basename] = cached_font + self._fonts[cached_font.postscript_name] = cached_font + self._fonts[cached_font.postscript_name.lower()] = cached_font + return T.cast(FT2Font, cached_font) # FIXME: Not sure this is guaranteed. + + def _get_offset(self, font: FT2Font, glyph: Glyph, fontsize: float, + dpi: float) -> float: + if font.postscript_name == 'Cmex10': + return (glyph.height / 64 / 2) + (fontsize/3 * dpi/72) + return 0. + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + raise NotImplementedError + + # The return value of _get_info is cached per-instance. + def _get_info(self, fontname: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontInfo: + font, num, slanted = self._get_glyph(fontname, font_class, sym) + font.set_size(fontsize, dpi) + glyph = font.load_char(num, flags=self.load_glyph_flags) + + xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox] + offset = self._get_offset(font, glyph, fontsize, dpi) + metrics = FontMetrics( + advance = glyph.linearHoriAdvance/65536.0, + height = glyph.height/64.0, + width = glyph.width/64.0, + xmin = xmin, + xmax = xmax, + ymin = ymin+offset, + ymax = ymax+offset, + # iceberg is the equivalent of TeX's "height" + iceberg = glyph.horiBearingY/64.0 + offset, + slanted = slanted + ) + + return FontInfo( + font = font, + fontsize = fontsize, + postscript_name = font.postscript_name, + metrics = metrics, + num = num, + glyph = glyph, + offset = offset + ) + + def get_xheight(self, fontname: str, fontsize: float, dpi: float) -> float: + font = self._get_font(fontname) + font.set_size(fontsize, dpi) + pclt = font.get_sfnt_table('pclt') + if pclt is None: + # Some fonts don't store the xHeight, so we do a poor man's xHeight + metrics = self.get_metrics( + fontname, mpl.rcParams['mathtext.default'], 'x', fontsize, dpi) + return metrics.iceberg + xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0) + return xHeight + + def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float: + # This function used to grab underline thickness from the font + # metrics, but that information is just too un-reliable, so it + # is now hardcoded. + return ((0.75 / 12.0) * fontsize * dpi) / 72.0 + + def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float, + font2: str, fontclass2: str, sym2: str, fontsize2: float, + dpi: float) -> float: + if font1 == font2 and fontsize1 == fontsize2: + info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) + info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) + font = info1.font + return font.get_kerning(info1.num, info2.num, KERNING_DEFAULT) / 64 + return super().get_kern(font1, fontclass1, sym1, fontsize1, + font2, fontclass2, sym2, fontsize2, dpi) + + +class BakomaFonts(TruetypeFonts): + """ + Use the Bakoma TrueType fonts for rendering. + + Symbols are strewn about a number of font files, each of which has + its own proprietary 8-bit encoding. + """ + _fontmap = { + 'cal': 'cmsy10', + 'rm': 'cmr10', + 'tt': 'cmtt10', + 'it': 'cmmi10', + 'bf': 'cmb10', + 'sf': 'cmss10', + 'ex': 'cmex10', + } + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + self._stix_fallback = StixFonts(default_font_prop, load_glyph_flags) + + super().__init__(default_font_prop, load_glyph_flags) + for key, val in self._fontmap.items(): + fullpath = findfont(val) + self.fontmap[key] = fullpath + self.fontmap[val] = fullpath + + _slanted_symbols = set(r"\int \oint".split()) + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + font = None + if fontname in self.fontmap and sym in latex_to_bakoma: + basename, num = latex_to_bakoma[sym] + slanted = (basename == "cmmi10") or sym in self._slanted_symbols + font = self._get_font(basename) + elif len(sym) == 1: + slanted = (fontname == "it") + font = self._get_font(fontname) + if font is not None: + num = ord(sym) + if font is not None and font.get_char_index(num) != 0: + return font, num, slanted + else: + return self._stix_fallback._get_glyph(fontname, font_class, sym) + + # The Bakoma fonts contain many pre-sized alternatives for the + # delimiters. The AutoSizedChar class will use these alternatives + # and select the best (closest sized) glyph. + _size_alternatives = { + '(': [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'), + ('ex', '\xb5'), ('ex', '\xc3')], + ')': [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'), + ('ex', '\xb6'), ('ex', '\x21')], + '{': [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'), + ('ex', '\xbd'), ('ex', '\x28')], + '}': [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'), + ('ex', '\xbe'), ('ex', '\x29')], + # The fourth size of '[' is mysteriously missing from the BaKoMa + # font, so I've omitted it for both '[' and ']' + '[': [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'), + ('ex', '\x22')], + ']': [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'), + ('ex', '\x23')], + r'\lfloor': [('ex', '\xa5'), ('ex', '\x6a'), + ('ex', '\xb9'), ('ex', '\x24')], + r'\rfloor': [('ex', '\xa6'), ('ex', '\x6b'), + ('ex', '\xba'), ('ex', '\x25')], + r'\lceil': [('ex', '\xa7'), ('ex', '\x6c'), + ('ex', '\xbb'), ('ex', '\x26')], + r'\rceil': [('ex', '\xa8'), ('ex', '\x6d'), + ('ex', '\xbc'), ('ex', '\x27')], + r'\langle': [('ex', '\xad'), ('ex', '\x44'), + ('ex', '\xbf'), ('ex', '\x2a')], + r'\rangle': [('ex', '\xae'), ('ex', '\x45'), + ('ex', '\xc0'), ('ex', '\x2b')], + r'\__sqrt__': [('ex', '\x70'), ('ex', '\x71'), + ('ex', '\x72'), ('ex', '\x73')], + r'\backslash': [('ex', '\xb2'), ('ex', '\x2f'), + ('ex', '\xc2'), ('ex', '\x2d')], + r'/': [('rm', '/'), ('ex', '\xb1'), ('ex', '\x2e'), + ('ex', '\xcb'), ('ex', '\x2c')], + r'\widehat': [('rm', '\x5e'), ('ex', '\x62'), ('ex', '\x63'), + ('ex', '\x64')], + r'\widetilde': [('rm', '\x7e'), ('ex', '\x65'), ('ex', '\x66'), + ('ex', '\x67')], + r'<': [('cal', 'h'), ('ex', 'D')], + r'>': [('cal', 'i'), ('ex', 'E')] + } + + for alias, target in [(r'\leftparen', '('), + (r'\rightparent', ')'), + (r'\leftbrace', '{'), + (r'\rightbrace', '}'), + (r'\leftbracket', '['), + (r'\rightbracket', ']'), + (r'\{', '{'), + (r'\}', '}'), + (r'\[', '['), + (r'\]', ']')]: + _size_alternatives[alias] = _size_alternatives[target] + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + return self._size_alternatives.get(sym, [(fontname, sym)]) + + +class UnicodeFonts(TruetypeFonts): + """ + An abstract base class for handling Unicode fonts. + + While some reasonably complete Unicode fonts (such as DejaVu) may + work in some situations, the only Unicode font I'm aware of with a + complete set of math symbols is STIX. + + This class will "fallback" on the Bakoma fonts when a required + symbol cannot be found in the font. + """ + + # Some glyphs are not present in the `cmr10` font, and must be brought in + # from `cmsy10`. Map the Unicode indices of those glyphs to the indices at + # which they are found in `cmsy10`. + _cmr10_substitutions = { + 0x00D7: 0x00A3, # Multiplication sign. + 0x2212: 0x00A1, # Minus sign. + } + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + # This must come first so the backend's owner is set correctly + fallback_rc = mpl.rcParams['mathtext.fallback'] + font_cls: type[TruetypeFonts] | None = { + 'stix': StixFonts, + 'stixsans': StixSansFonts, + 'cm': BakomaFonts + }.get(fallback_rc) + self._fallback_font = (font_cls(default_font_prop, load_glyph_flags) + if font_cls else None) + + super().__init__(default_font_prop, load_glyph_flags) + for texfont in "cal rm tt it bf sf bfit".split(): + prop = mpl.rcParams['mathtext.' + texfont] + font = findfont(prop) + self.fontmap[texfont] = font + prop = FontProperties('cmex10') + font = findfont(prop) + self.fontmap['ex'] = font + + # include STIX sized alternatives for glyphs if fallback is STIX + if isinstance(self._fallback_font, StixFonts): + stixsizedaltfonts = { + 0: 'STIXGeneral', + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym'} + + for size, name in stixsizedaltfonts.items(): + fullpath = findfont(name) + self.fontmap[size] = fullpath + self.fontmap[name] = fullpath + + _slanted_symbols = set(r"\int \oint".split()) + + def _map_virtual_font(self, fontname: str, font_class: str, + uniindex: int) -> tuple[str, int]: + return fontname, uniindex + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + try: + uniindex = get_unicode_index(sym) + found_symbol = True + except ValueError: + uniindex = ord('?') + found_symbol = False + _log.warning("No TeX to Unicode mapping for %a.", sym) + + fontname, uniindex = self._map_virtual_font( + fontname, font_class, uniindex) + + new_fontname = fontname + + # Only characters in the "Letter" class should be italicized in 'it' + # mode. Greek capital letters should be Roman. + if found_symbol: + if fontname == 'it' and uniindex < 0x10000: + char = chr(uniindex) + if (unicodedata.category(char)[0] != "L" + or unicodedata.name(char).startswith("GREEK CAPITAL")): + new_fontname = 'rm' + + slanted = (new_fontname == 'it') or sym in self._slanted_symbols + found_symbol = False + font = self._get_font(new_fontname) + if font is not None: + if (uniindex in self._cmr10_substitutions + and font.family_name == "cmr10"): + font = get_font( + cbook._get_data_path("fonts/ttf/cmsy10.ttf")) + uniindex = self._cmr10_substitutions[uniindex] + glyphindex = font.get_char_index(uniindex) + if glyphindex != 0: + found_symbol = True + + if not found_symbol: + if self._fallback_font: + if (fontname in ('it', 'regular') + and isinstance(self._fallback_font, StixFonts)): + fontname = 'rm' + + g = self._fallback_font._get_glyph(fontname, font_class, sym) + family = g[0].family_name + if family in list(BakomaFonts._fontmap.values()): + family = "Computer Modern" + _log.info("Substituting symbol %s from %s", sym, family) + return g + + else: + if (fontname in ('it', 'regular') + and isinstance(self, StixFonts)): + return self._get_glyph('rm', font_class, sym) + _log.warning("Font %r does not have a glyph for %a [U+%x], " + "substituting with a dummy symbol.", + new_fontname, sym, uniindex) + font = self._get_font('rm') + uniindex = 0xA4 # currency char, for lack of anything better + slanted = False + + return font, uniindex, slanted + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + if self._fallback_font: + return self._fallback_font.get_sized_alternatives_for_symbol( + fontname, sym) + return [(fontname, sym)] + + +class DejaVuFonts(UnicodeFonts, metaclass=abc.ABCMeta): + _fontmap: dict[str | int, str] = {} + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + # This must come first so the backend's owner is set correctly + if isinstance(self, DejaVuSerifFonts): + self._fallback_font = StixFonts(default_font_prop, load_glyph_flags) + else: + self._fallback_font = StixSansFonts(default_font_prop, load_glyph_flags) + self.bakoma = BakomaFonts(default_font_prop, load_glyph_flags) + TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) + # Include Stix sized alternatives for glyphs + self._fontmap.update({ + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym', + }) + for key, name in self._fontmap.items(): + fullpath = findfont(name) + self.fontmap[key] = fullpath + self.fontmap[name] = fullpath + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + # Override prime symbol to use Bakoma. + if sym == r'\prime': + return self.bakoma._get_glyph(fontname, font_class, sym) + else: + # check whether the glyph is available in the display font + uniindex = get_unicode_index(sym) + font = self._get_font('ex') + if font is not None: + glyphindex = font.get_char_index(uniindex) + if glyphindex != 0: + return super()._get_glyph('ex', font_class, sym) + # otherwise return regular glyph + return super()._get_glyph(fontname, font_class, sym) + + +class DejaVuSerifFonts(DejaVuFonts): + """ + A font handling class for the DejaVu Serif fonts + + If a glyph is not found it will fallback to Stix Serif + """ + _fontmap = { + 'rm': 'DejaVu Serif', + 'it': 'DejaVu Serif:italic', + 'bf': 'DejaVu Serif:weight=bold', + 'bfit': 'DejaVu Serif:italic:bold', + 'sf': 'DejaVu Sans', + 'tt': 'DejaVu Sans Mono', + 'ex': 'DejaVu Serif Display', + 0: 'DejaVu Serif', + } + + +class DejaVuSansFonts(DejaVuFonts): + """ + A font handling class for the DejaVu Sans fonts + + If a glyph is not found it will fallback to Stix Sans + """ + _fontmap = { + 'rm': 'DejaVu Sans', + 'it': 'DejaVu Sans:italic', + 'bf': 'DejaVu Sans:weight=bold', + 'bfit': 'DejaVu Sans:italic:bold', + 'sf': 'DejaVu Sans', + 'tt': 'DejaVu Sans Mono', + 'ex': 'DejaVu Sans Display', + 0: 'DejaVu Sans', + } + + +class StixFonts(UnicodeFonts): + """ + A font handling class for the STIX fonts. + + In addition to what UnicodeFonts provides, this class: + + - supports "virtual fonts" which are complete alpha numeric + character sets with different font styles at special Unicode + code points, such as "Blackboard". + + - handles sized alternative characters for the STIXSizeX fonts. + """ + _fontmap: dict[str | int, str] = { + 'rm': 'STIXGeneral', + 'it': 'STIXGeneral:italic', + 'bf': 'STIXGeneral:weight=bold', + 'bfit': 'STIXGeneral:italic:bold', + 'nonunirm': 'STIXNonUnicode', + 'nonuniit': 'STIXNonUnicode:italic', + 'nonunibf': 'STIXNonUnicode:weight=bold', + 0: 'STIXGeneral', + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym', + } + _fallback_font = None + _sans = False + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) + for key, name in self._fontmap.items(): + fullpath = findfont(name) + self.fontmap[key] = fullpath + self.fontmap[name] = fullpath + + def _map_virtual_font(self, fontname: str, font_class: str, + uniindex: int) -> tuple[str, int]: + # Handle these "fonts" that are actually embedded in + # other fonts. + font_mapping = stix_virtual_fonts.get(fontname) + if (self._sans and font_mapping is None + and fontname not in ('regular', 'default')): + font_mapping = stix_virtual_fonts['sf'] + doing_sans_conversion = True + else: + doing_sans_conversion = False + + if isinstance(font_mapping, dict): + try: + mapping = font_mapping[font_class] + except KeyError: + mapping = font_mapping['rm'] + elif isinstance(font_mapping, list): + mapping = font_mapping + else: + mapping = None + + if mapping is not None: + # Binary search for the source glyph + lo = 0 + hi = len(mapping) + while lo < hi: + mid = (lo+hi)//2 + range = mapping[mid] + if uniindex < range[0]: + hi = mid + elif uniindex <= range[1]: + break + else: + lo = mid + 1 + + if range[0] <= uniindex <= range[1]: + uniindex = uniindex - range[0] + range[3] + fontname = range[2] + elif not doing_sans_conversion: + # This will generate a dummy character + uniindex = 0x1 + fontname = mpl.rcParams['mathtext.default'] + + # Fix some incorrect glyphs. + if fontname in ('rm', 'it'): + uniindex = stix_glyph_fixes.get(uniindex, uniindex) + + # Handle private use area glyphs + if fontname in ('it', 'rm', 'bf', 'bfit') and 0xe000 <= uniindex <= 0xf8ff: + fontname = 'nonuni' + fontname + + return fontname, uniindex + + @functools.cache + def get_sized_alternatives_for_symbol( # type: ignore[override] + self, + fontname: str, + sym: str) -> list[tuple[str, str]] | list[tuple[int, str]]: + fixes = { + '\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']', + '<': '\N{MATHEMATICAL LEFT ANGLE BRACKET}', + '>': '\N{MATHEMATICAL RIGHT ANGLE BRACKET}', + } + sym = fixes.get(sym, sym) + try: + uniindex = get_unicode_index(sym) + except ValueError: + return [(fontname, sym)] + alternatives = [(i, chr(uniindex)) for i in range(6) + if self._get_font(i).get_char_index(uniindex) != 0] + # The largest size of the radical symbol in STIX has incorrect + # metrics that cause it to be disconnected from the stem. + if sym == r'\__sqrt__': + alternatives = alternatives[:-1] + return alternatives + + +class StixSansFonts(StixFonts): + """ + A font handling class for the STIX fonts (that uses sans-serif + characters by default). + """ + _sans = True + + +############################################################################## +# TeX-LIKE BOX MODEL + +# The following is based directly on the document 'woven' from the +# TeX82 source code. This information is also available in printed +# form: +# +# Knuth, Donald E.. 1986. Computers and Typesetting, Volume B: +# TeX: The Program. Addison-Wesley Professional. +# +# The most relevant "chapters" are: +# Data structures for boxes and their friends +# Shipping pages out (ship()) +# Packaging (hpack() and vpack()) +# Data structures for math mode +# Subroutines for math mode +# Typesetting math formulas +# +# Many of the docstrings below refer to a numbered "node" in that +# book, e.g., node123 +# +# Note that (as TeX) y increases downward, unlike many other parts of +# matplotlib. + +# How much text shrinks when going to the next-smallest level. +SHRINK_FACTOR = 0.7 +# The number of different sizes of chars to use, beyond which they will not +# get any smaller +NUM_SIZE_LEVELS = 6 + + +class FontConstantsBase: + """ + A set of constants that controls how certain things, such as sub- + and superscripts are laid out. These are all metrics that can't + be reliably retrieved from the font metrics in the font itself. + """ + # Percentage of x-height of additional horiz. space after sub/superscripts + script_space: T.ClassVar[float] = 0.05 + + # Percentage of x-height that sub/superscripts drop below the baseline + subdrop: T.ClassVar[float] = 0.4 + + # Percentage of x-height that superscripts are raised from the baseline + sup1: T.ClassVar[float] = 0.7 + + # Percentage of x-height that subscripts drop below the baseline + sub1: T.ClassVar[float] = 0.3 + + # Percentage of x-height that subscripts drop below the baseline when a + # superscript is present + sub2: T.ClassVar[float] = 0.5 + + # Percentage of x-height that sub/superscripts are offset relative to the + # nucleus edge for non-slanted nuclei + delta: T.ClassVar[float] = 0.025 + + # Additional percentage of last character height above 2/3 of the + # x-height that superscripts are offset relative to the subscript + # for slanted nuclei + delta_slanted: T.ClassVar[float] = 0.2 + + # Percentage of x-height that superscripts and subscripts are offset for + # integrals + delta_integral: T.ClassVar[float] = 0.1 + + +class ComputerModernFontConstants(FontConstantsBase): + script_space = 0.075 + subdrop = 0.2 + sup1 = 0.45 + sub1 = 0.2 + sub2 = 0.3 + delta = 0.075 + delta_slanted = 0.3 + delta_integral = 0.3 + + +class STIXFontConstants(FontConstantsBase): + script_space = 0.1 + sup1 = 0.8 + sub2 = 0.6 + delta = 0.05 + delta_slanted = 0.3 + delta_integral = 0.3 + + +class STIXSansFontConstants(FontConstantsBase): + script_space = 0.05 + sup1 = 0.8 + delta_slanted = 0.6 + delta_integral = 0.3 + + +class DejaVuSerifFontConstants(FontConstantsBase): + pass + + +class DejaVuSansFontConstants(FontConstantsBase): + pass + + +# Maps font family names to the FontConstantBase subclass to use +_font_constant_mapping = { + 'DejaVu Sans': DejaVuSansFontConstants, + 'DejaVu Sans Mono': DejaVuSansFontConstants, + 'DejaVu Serif': DejaVuSerifFontConstants, + 'cmb10': ComputerModernFontConstants, + 'cmex10': ComputerModernFontConstants, + 'cmmi10': ComputerModernFontConstants, + 'cmr10': ComputerModernFontConstants, + 'cmss10': ComputerModernFontConstants, + 'cmsy10': ComputerModernFontConstants, + 'cmtt10': ComputerModernFontConstants, + 'STIXGeneral': STIXFontConstants, + 'STIXNonUnicode': STIXFontConstants, + 'STIXSizeFiveSym': STIXFontConstants, + 'STIXSizeFourSym': STIXFontConstants, + 'STIXSizeThreeSym': STIXFontConstants, + 'STIXSizeTwoSym': STIXFontConstants, + 'STIXSizeOneSym': STIXFontConstants, + # Map the fonts we used to ship, just for good measure + 'Bitstream Vera Sans': DejaVuSansFontConstants, + 'Bitstream Vera': DejaVuSansFontConstants, + } + + +def _get_font_constant_set(state: ParserState) -> type[FontConstantsBase]: + constants = _font_constant_mapping.get( + state.fontset._get_font(state.font).family_name, FontConstantsBase) + # STIX sans isn't really its own fonts, just different code points + # in the STIX fonts, so we have to detect this one separately. + if (constants is STIXFontConstants and + isinstance(state.fontset, StixSansFonts)): + return STIXSansFontConstants + return constants + + +class Node: + """A node in the TeX box model.""" + + def __init__(self) -> None: + self.size = 0 + + def __repr__(self) -> str: + return type(self).__name__ + + def get_kerning(self, next: Node | None) -> float: + return 0.0 + + def shrink(self) -> None: + """ + Shrinks one level smaller. There are only three levels of + sizes, after which things will no longer get smaller. + """ + self.size += 1 + + def render(self, output: Output, x: float, y: float) -> None: + """Render this node.""" + + +class Box(Node): + """A node with a physical location.""" + + def __init__(self, width: float, height: float, depth: float) -> None: + super().__init__() + self.width = width + self.height = height + self.depth = depth + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.width *= SHRINK_FACTOR + self.height *= SHRINK_FACTOR + self.depth *= SHRINK_FACTOR + + def render(self, output: Output, # type: ignore[override] + x1: float, y1: float, x2: float, y2: float) -> None: + pass + + +class Vbox(Box): + """A box with only height (zero width).""" + + def __init__(self, height: float, depth: float): + super().__init__(0., height, depth) + + +class Hbox(Box): + """A box with only width (zero height and depth).""" + + def __init__(self, width: float): + super().__init__(width, 0., 0.) + + +class Char(Node): + """ + A single character. + + Unlike TeX, the font information and metrics are stored with each `Char` + to make it easier to lookup the font metrics when needed. Note that TeX + boxes have a width, height, and depth, unlike Type1 and TrueType which use + a full bounding box and an advance in the x-direction. The metrics must + be converted to the TeX model, and the advance (if different from width) + must be converted into a `Kern` node when the `Char` is added to its parent + `Hlist`. + """ + + def __init__(self, c: str, state: ParserState): + super().__init__() + self.c = c + self.fontset = state.fontset + self.font = state.font + self.font_class = state.font_class + self.fontsize = state.fontsize + self.dpi = state.dpi + # The real width, height and depth will be set during the + # pack phase, after we know the real fontsize + self._update_metrics() + + def __repr__(self) -> str: + return '`%s`' % self.c + + def _update_metrics(self) -> None: + metrics = self._metrics = self.fontset.get_metrics( + self.font, self.font_class, self.c, self.fontsize, self.dpi) + if self.c == ' ': + self.width = metrics.advance + else: + self.width = metrics.width + self.height = metrics.iceberg + self.depth = -(metrics.iceberg - metrics.height) + + def is_slanted(self) -> bool: + return self._metrics.slanted + + def get_kerning(self, next: Node | None) -> float: + """ + Return the amount of kerning between this and the given character. + + This method is called when characters are strung together into `Hlist` + to create `Kern` nodes. + """ + advance = self._metrics.advance - self.width + kern = 0. + if isinstance(next, Char): + kern = self.fontset.get_kern( + self.font, self.font_class, self.c, self.fontsize, + next.font, next.font_class, next.c, next.fontsize, + self.dpi) + return advance + kern + + def render(self, output: Output, x: float, y: float) -> None: + self.fontset.render_glyph( + output, x, y, + self.font, self.font_class, self.c, self.fontsize, self.dpi) + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.fontsize *= SHRINK_FACTOR + self.width *= SHRINK_FACTOR + self.height *= SHRINK_FACTOR + self.depth *= SHRINK_FACTOR + + +class Accent(Char): + """ + The font metrics need to be dealt with differently for accents, + since they are already offset correctly from the baseline in + TrueType fonts. + """ + def _update_metrics(self) -> None: + metrics = self._metrics = self.fontset.get_metrics( + self.font, self.font_class, self.c, self.fontsize, self.dpi) + self.width = metrics.xmax - metrics.xmin + self.height = metrics.ymax - metrics.ymin + self.depth = 0 + + def shrink(self) -> None: + super().shrink() + self._update_metrics() + + def render(self, output: Output, x: float, y: float) -> None: + self.fontset.render_glyph( + output, x - self._metrics.xmin, y + self._metrics.ymin, + self.font, self.font_class, self.c, self.fontsize, self.dpi) + + +class List(Box): + """A list of nodes (either horizontal or vertical).""" + + def __init__(self, elements: T.Sequence[Node]): + super().__init__(0., 0., 0.) + self.shift_amount = 0. # An arbitrary offset + self.children = [*elements] # The child nodes of this list + # The following parameters are set in the vpack and hpack functions + self.glue_set = 0. # The glue setting of this list + self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching + self.glue_order = 0 # The order of infinity (0 - 3) for the glue + + def __repr__(self) -> str: + return '{}[{}]'.format( + super().__repr__(), + self.width, self.height, + self.depth, self.shift_amount, + ', '.join([repr(x) for x in self.children])) + + def _set_glue(self, x: float, sign: int, totals: list[float], + error_type: str) -> None: + self.glue_order = o = next( + # Highest order of glue used by the members of this list. + (i for i in range(len(totals))[::-1] if totals[i] != 0), 0) + self.glue_sign = sign + if totals[o] != 0.: + self.glue_set = x / totals[o] + else: + self.glue_sign = 0 + self.glue_ratio = 0. + if o == 0: + if len(self.children): + _log.warning("%s %s: %r", + error_type, type(self).__name__, self) + + def shrink(self) -> None: + for child in self.children: + child.shrink() + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.shift_amount *= SHRINK_FACTOR + self.glue_set *= SHRINK_FACTOR + + +class Hlist(List): + """A horizontal list of boxes.""" + + def __init__(self, elements: T.Sequence[Node], w: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional', + do_kern: bool = True): + super().__init__(elements) + if do_kern: + self.kern() + self.hpack(w=w, m=m) + + def kern(self) -> None: + """ + Insert `Kern` nodes between `Char` nodes to set kerning. + + The `Char` nodes themselves determine the amount of kerning they need + (in `~Char.get_kerning`), and this function just creates the correct + linked list. + """ + new_children = [] + num_children = len(self.children) + if num_children: + for i in range(num_children): + elem = self.children[i] + if i < num_children - 1: + next = self.children[i + 1] + else: + next = None + + new_children.append(elem) + kerning_distance = elem.get_kerning(next) + if kerning_distance != 0.: + kern = Kern(kerning_distance) + new_children.append(kern) + self.children = new_children + + def hpack(self, w: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional') -> None: + r""" + Compute the dimensions of the resulting boxes, and adjust the glue if + one of those dimensions is pre-specified. The computed sizes normally + enclose all of the material inside the new box; but some items may + stick out if negative glue is used, if the box is overfull, or if a + ``\vbox`` includes other boxes that have been shifted left. + + Parameters + ---------- + w : float, default: 0 + A width. + m : {'exactly', 'additional'}, default: 'additional' + Whether to produce a box whose width is 'exactly' *w*; or a box + with the natural width of the contents, plus *w* ('additional'). + + Notes + ----- + The defaults produce a box with the natural width of the contents. + """ + # I don't know why these get reset in TeX. Shift_amount is pretty + # much useless if we do. + # self.shift_amount = 0. + h = 0. + d = 0. + x = 0. + total_stretch = [0.] * 4 + total_shrink = [0.] * 4 + for p in self.children: + if isinstance(p, Char): + x += p.width + h = max(h, p.height) + d = max(d, p.depth) + elif isinstance(p, Box): + x += p.width + if not np.isinf(p.height) and not np.isinf(p.depth): + s = getattr(p, 'shift_amount', 0.) + h = max(h, p.height - s) + d = max(d, p.depth + s) + elif isinstance(p, Glue): + glue_spec = p.glue_spec + x += glue_spec.width + total_stretch[glue_spec.stretch_order] += glue_spec.stretch + total_shrink[glue_spec.shrink_order] += glue_spec.shrink + elif isinstance(p, Kern): + x += p.width + self.height = h + self.depth = d + + if m == 'additional': + w += x + self.width = w + x = w - x + + if x == 0.: + self.glue_sign = 0 + self.glue_order = 0 + self.glue_ratio = 0. + return + if x > 0.: + self._set_glue(x, 1, total_stretch, "Overful") + else: + self._set_glue(x, -1, total_shrink, "Underful") + + +class Vlist(List): + """A vertical list of boxes.""" + + def __init__(self, elements: T.Sequence[Node], h: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional'): + super().__init__(elements) + self.vpack(h=h, m=m) + + def vpack(self, h: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional', + l: float = np.inf) -> None: + """ + Compute the dimensions of the resulting boxes, and to adjust the glue + if one of those dimensions is pre-specified. + + Parameters + ---------- + h : float, default: 0 + A height. + m : {'exactly', 'additional'}, default: 'additional' + Whether to produce a box whose height is 'exactly' *h*; or a box + with the natural height of the contents, plus *h* ('additional'). + l : float, default: np.inf + The maximum height. + + Notes + ----- + The defaults produce a box with the natural height of the contents. + """ + # I don't know why these get reset in TeX. Shift_amount is pretty + # much useless if we do. + # self.shift_amount = 0. + w = 0. + d = 0. + x = 0. + total_stretch = [0.] * 4 + total_shrink = [0.] * 4 + for p in self.children: + if isinstance(p, Box): + x += d + p.height + d = p.depth + if not np.isinf(p.width): + s = getattr(p, 'shift_amount', 0.) + w = max(w, p.width + s) + elif isinstance(p, Glue): + x += d + d = 0. + glue_spec = p.glue_spec + x += glue_spec.width + total_stretch[glue_spec.stretch_order] += glue_spec.stretch + total_shrink[glue_spec.shrink_order] += glue_spec.shrink + elif isinstance(p, Kern): + x += d + p.width + d = 0. + elif isinstance(p, Char): + raise RuntimeError( + "Internal mathtext error: Char node found in Vlist") + + self.width = w + if d > l: + x += d - l + self.depth = l + else: + self.depth = d + + if m == 'additional': + h += x + self.height = h + x = h - x + + if x == 0: + self.glue_sign = 0 + self.glue_order = 0 + self.glue_ratio = 0. + return + + if x > 0.: + self._set_glue(x, 1, total_stretch, "Overful") + else: + self._set_glue(x, -1, total_shrink, "Underful") + + +class Rule(Box): + """ + A solid black rectangle. + + It has *width*, *depth*, and *height* fields just as in an `Hlist`. + However, if any of these dimensions is inf, the actual value will be + determined by running the rule up to the boundary of the innermost + enclosing box. This is called a "running dimension". The width is never + running in an `Hlist`; the height and depth are never running in a `Vlist`. + """ + + def __init__(self, width: float, height: float, depth: float, state: ParserState): + super().__init__(width, height, depth) + self.fontset = state.fontset + + def render(self, output: Output, # type: ignore[override] + x: float, y: float, w: float, h: float) -> None: + self.fontset.render_rect_filled(output, x, y, x + w, y + h) + + +class Hrule(Rule): + """Convenience class to create a horizontal rule.""" + + def __init__(self, state: ParserState, thickness: float | None = None): + if thickness is None: + thickness = state.get_current_underline_thickness() + height = depth = thickness * 0.5 + super().__init__(np.inf, height, depth, state) + + +class Vrule(Rule): + """Convenience class to create a vertical rule.""" + + def __init__(self, state: ParserState): + thickness = state.get_current_underline_thickness() + super().__init__(thickness, np.inf, np.inf, state) + + +class _GlueSpec(NamedTuple): + width: float + stretch: float + stretch_order: int + shrink: float + shrink_order: int + + +_GlueSpec._named = { # type: ignore[attr-defined] + 'fil': _GlueSpec(0., 1., 1, 0., 0), + 'fill': _GlueSpec(0., 1., 2, 0., 0), + 'filll': _GlueSpec(0., 1., 3, 0., 0), + 'neg_fil': _GlueSpec(0., 0., 0, 1., 1), + 'neg_fill': _GlueSpec(0., 0., 0, 1., 2), + 'neg_filll': _GlueSpec(0., 0., 0, 1., 3), + 'empty': _GlueSpec(0., 0., 0, 0., 0), + 'ss': _GlueSpec(0., 1., 1, -1., 1), +} + + +class Glue(Node): + """ + Most of the information in this object is stored in the underlying + ``_GlueSpec`` class, which is shared between multiple glue objects. + (This is a memory optimization which probably doesn't matter anymore, but + it's easier to stick to what TeX does.) + """ + + def __init__(self, + glue_type: _GlueSpec | T.Literal["fil", "fill", "filll", + "neg_fil", "neg_fill", "neg_filll", + "empty", "ss"]): + super().__init__() + if isinstance(glue_type, str): + glue_spec = _GlueSpec._named[glue_type] # type: ignore[attr-defined] + elif isinstance(glue_type, _GlueSpec): + glue_spec = glue_type + else: + raise ValueError("glue_type must be a glue spec name or instance") + self.glue_spec = glue_spec + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + g = self.glue_spec + self.glue_spec = g._replace(width=g.width * SHRINK_FACTOR) + + +class HCentered(Hlist): + """ + A convenience class to create an `Hlist` whose contents are + centered within its enclosing box. + """ + + def __init__(self, elements: list[Node]): + super().__init__([Glue('ss'), *elements, Glue('ss')], do_kern=False) + + +class VCentered(Vlist): + """ + A convenience class to create a `Vlist` whose contents are + centered within its enclosing box. + """ + + def __init__(self, elements: list[Node]): + super().__init__([Glue('ss'), *elements, Glue('ss')]) + + +class Kern(Node): + """ + A `Kern` node has a width field to specify a (normally + negative) amount of spacing. This spacing correction appears in + horizontal lists between letters like A and V when the font + designer said that it looks better to move them closer together or + further apart. A kern node can also appear in a vertical list, + when its *width* denotes additional spacing in the vertical + direction. + """ + + height = 0 + depth = 0 + + def __init__(self, width: float): + super().__init__() + self.width = width + + def __repr__(self) -> str: + return "k%.02f" % self.width + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.width *= SHRINK_FACTOR + + +class AutoHeightChar(Hlist): + """ + A character as close to the given height and depth as possible. + + When using a font with multiple height versions of some characters (such as + the BaKoMa fonts), the correct glyph will be selected, otherwise this will + always just return a scaled version of the glyph. + """ + + def __init__(self, c: str, height: float, depth: float, state: ParserState, + always: bool = False, factor: float | None = None): + alternatives = state.fontset.get_sized_alternatives_for_symbol( + state.font, c) + + xHeight = state.fontset.get_xheight( + state.font, state.fontsize, state.dpi) + + state = state.copy() + target_total = height + depth + for fontname, sym in alternatives: + state.font = fontname + char = Char(sym, state) + # Ensure that size 0 is chosen when the text is regular sized but + # with descender glyphs by subtracting 0.2 * xHeight + if char.height + char.depth >= target_total - 0.2 * xHeight: + break + + shift = 0.0 + if state.font != 0 or len(alternatives) == 1: + if factor is None: + factor = target_total / (char.height + char.depth) + state.fontsize *= factor + char = Char(sym, state) + + shift = (depth - char.depth) + + super().__init__([char]) + self.shift_amount = shift + + +class AutoWidthChar(Hlist): + """ + A character as close to the given width as possible. + + When using a font with multiple width versions of some characters (such as + the BaKoMa fonts), the correct glyph will be selected, otherwise this will + always just return a scaled version of the glyph. + """ + + def __init__(self, c: str, width: float, state: ParserState, always: bool = False, + char_class: type[Char] = Char): + alternatives = state.fontset.get_sized_alternatives_for_symbol( + state.font, c) + + state = state.copy() + for fontname, sym in alternatives: + state.font = fontname + char = char_class(sym, state) + if char.width >= width: + break + + factor = width / char.width + state.fontsize *= factor + char = char_class(sym, state) + + super().__init__([char]) + self.width = char.width + + +def ship(box: Box, xy: tuple[float, float] = (0, 0)) -> Output: + """ + Ship out *box* at offset *xy*, converting it to an `Output`. + + Since boxes can be inside of boxes inside of boxes, the main work of `ship` + is done by two mutually recursive routines, `hlist_out` and `vlist_out`, + which traverse the `Hlist` nodes and `Vlist` nodes inside of horizontal + and vertical boxes. The global variables used in TeX to store state as it + processes have become local variables here. + """ + ox, oy = xy + cur_v = 0. + cur_h = 0. + off_h = ox + off_v = oy + box.height + output = Output(box) + + def clamp(value: float) -> float: + return -1e9 if value < -1e9 else +1e9 if value > +1e9 else value + + def hlist_out(box: Hlist) -> None: + nonlocal cur_v, cur_h, off_h, off_v + + cur_g = 0 + cur_glue = 0. + glue_order = box.glue_order + glue_sign = box.glue_sign + base_line = cur_v + left_edge = cur_h + + for p in box.children: + if isinstance(p, Char): + p.render(output, cur_h + off_h, cur_v + off_v) + cur_h += p.width + elif isinstance(p, Kern): + cur_h += p.width + elif isinstance(p, List): + # node623 + if len(p.children) == 0: + cur_h += p.width + else: + edge = cur_h + cur_v = base_line + p.shift_amount + if isinstance(p, Hlist): + hlist_out(p) + elif isinstance(p, Vlist): + # p.vpack(box.height + box.depth, 'exactly') + vlist_out(p) + else: + assert False, "unreachable code" + cur_h = edge + p.width + cur_v = base_line + elif isinstance(p, Box): + # node624 + rule_height = p.height + rule_depth = p.depth + rule_width = p.width + if np.isinf(rule_height): + rule_height = box.height + if np.isinf(rule_depth): + rule_depth = box.depth + if rule_height > 0 and rule_width > 0: + cur_v = base_line + rule_depth + p.render(output, + cur_h + off_h, cur_v + off_v, + rule_width, rule_height) + cur_v = base_line + cur_h += rule_width + elif isinstance(p, Glue): + # node625 + glue_spec = p.glue_spec + rule_width = glue_spec.width - cur_g + if glue_sign != 0: # normal + if glue_sign == 1: # stretching + if glue_spec.stretch_order == glue_order: + cur_glue += glue_spec.stretch + cur_g = round(clamp(box.glue_set * cur_glue)) + elif glue_spec.shrink_order == glue_order: + cur_glue += glue_spec.shrink + cur_g = round(clamp(box.glue_set * cur_glue)) + rule_width += cur_g + cur_h += rule_width + + def vlist_out(box: Vlist) -> None: + nonlocal cur_v, cur_h, off_h, off_v + + cur_g = 0 + cur_glue = 0. + glue_order = box.glue_order + glue_sign = box.glue_sign + left_edge = cur_h + cur_v -= box.height + top_edge = cur_v + + for p in box.children: + if isinstance(p, Kern): + cur_v += p.width + elif isinstance(p, List): + if len(p.children) == 0: + cur_v += p.height + p.depth + else: + cur_v += p.height + cur_h = left_edge + p.shift_amount + save_v = cur_v + p.width = box.width + if isinstance(p, Hlist): + hlist_out(p) + elif isinstance(p, Vlist): + vlist_out(p) + else: + assert False, "unreachable code" + cur_v = save_v + p.depth + cur_h = left_edge + elif isinstance(p, Box): + rule_height = p.height + rule_depth = p.depth + rule_width = p.width + if np.isinf(rule_width): + rule_width = box.width + rule_height += rule_depth + if rule_height > 0 and rule_depth > 0: + cur_v += rule_height + p.render(output, + cur_h + off_h, cur_v + off_v, + rule_width, rule_height) + elif isinstance(p, Glue): + glue_spec = p.glue_spec + rule_height = glue_spec.width - cur_g + if glue_sign != 0: # normal + if glue_sign == 1: # stretching + if glue_spec.stretch_order == glue_order: + cur_glue += glue_spec.stretch + cur_g = round(clamp(box.glue_set * cur_glue)) + elif glue_spec.shrink_order == glue_order: # shrinking + cur_glue += glue_spec.shrink + cur_g = round(clamp(box.glue_set * cur_glue)) + rule_height += cur_g + cur_v += rule_height + elif isinstance(p, Char): + raise RuntimeError( + "Internal mathtext error: Char node found in vlist") + + assert isinstance(box, Hlist) + hlist_out(box) + return output + + +############################################################################## +# PARSER + + +def Error(msg: str) -> ParserElement: + """Helper class to raise parser errors.""" + def raise_error(s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, loc, msg) + + return Empty().setParseAction(raise_error) + + +class ParserState: + """ + Parser state. + + States are pushed and popped from a stack as necessary, and the "current" + state is always at the top of the stack. + + Upon entering and leaving a group { } or math/non-math, the stack is pushed + and popped accordingly. + """ + + def __init__(self, fontset: Fonts, font: str, font_class: str, fontsize: float, + dpi: float): + self.fontset = fontset + self._font = font + self.font_class = font_class + self.fontsize = fontsize + self.dpi = dpi + + def copy(self) -> ParserState: + return copy.copy(self) + + @property + def font(self) -> str: + return self._font + + @font.setter + def font(self, name: str) -> None: + if name in ('rm', 'it', 'bf', 'bfit'): + self.font_class = name + self._font = name + + def get_current_underline_thickness(self) -> float: + """Return the underline thickness for this state.""" + return self.fontset.get_underline_thickness( + self.font, self.fontsize, self.dpi) + + +def cmd(expr: str, args: ParserElement) -> ParserElement: + r""" + Helper to define TeX commands. + + ``cmd("\cmd", args)`` is equivalent to + ``"\cmd" - (args | Error("Expected \cmd{arg}{...}"))`` where the names in + the error message are taken from element names in *args*. If *expr* + already includes arguments (e.g. "\cmd{arg}{...}"), then they are stripped + when constructing the parse element, but kept (and *expr* is used as is) in + the error message. + """ + + def names(elt: ParserElement) -> T.Generator[str, None, None]: + if isinstance(elt, ParseExpression): + for expr in elt.exprs: + yield from names(expr) + elif elt.resultsName: + yield elt.resultsName + + csname = expr.split("{", 1)[0] + err = (csname + "".join("{%s}" % name for name in names(args)) + if expr == csname else expr) + return csname - (args | Error(f"Expected {err}")) + + +class Parser: + """ + A pyparsing-based parser for strings containing math expressions. + + Raw text may also appear outside of pairs of ``$``. + + The grammar is based directly on that in TeX, though it cuts a few corners. + """ + + class _MathStyle(enum.Enum): + DISPLAYSTYLE = 0 + TEXTSTYLE = 1 + SCRIPTSTYLE = 2 + SCRIPTSCRIPTSTYLE = 3 + + _binary_operators = set( + '+ * - \N{MINUS SIGN}' + r''' + \pm \sqcap \rhd + \mp \sqcup \unlhd + \times \vee \unrhd + \div \wedge \oplus + \ast \setminus \ominus + \star \wr \otimes + \circ \diamond \oslash + \bullet \bigtriangleup \odot + \cdot \bigtriangledown \bigcirc + \cap \triangleleft \dagger + \cup \triangleright \ddagger + \uplus \lhd \amalg + \dotplus \dotminus \Cap + \Cup \barwedge \boxdot + \boxminus \boxplus \boxtimes + \curlyvee \curlywedge \divideontimes + \doublebarwedge \leftthreetimes \rightthreetimes + \slash \veebar \barvee + \cupdot \intercal \amalg + \circledcirc \circleddash \circledast + \boxbar \obar \merge + \minuscolon \dotsminusdots + '''.split()) + + _relation_symbols = set(r''' + = < > : + \leq \geq \equiv \models + \prec \succ \sim \perp + \preceq \succeq \simeq \mid + \ll \gg \asymp \parallel + \subset \supset \approx \bowtie + \subseteq \supseteq \cong \Join + \sqsubset \sqsupset \neq \smile + \sqsubseteq \sqsupseteq \doteq \frown + \in \ni \propto \vdash + \dashv \dots \doteqdot \leqq + \geqq \lneqq \gneqq \lessgtr + \leqslant \geqslant \eqgtr \eqless + \eqslantless \eqslantgtr \lesseqgtr \backsim + \backsimeq \lesssim \gtrsim \precsim + \precnsim \gnsim \lnsim \succsim + \succnsim \nsim \lesseqqgtr \gtreqqless + \gtreqless \subseteqq \supseteqq \subsetneqq + \supsetneqq \lessapprox \approxeq \gtrapprox + \precapprox \succapprox \precnapprox \succnapprox + \npreccurlyeq \nsucccurlyeq \nsqsubseteq \nsqsupseteq + \sqsubsetneq \sqsupsetneq \nlesssim \ngtrsim + \nlessgtr \ngtrless \lnapprox \gnapprox + \napprox \approxeq \approxident \lll + \ggg \nparallel \Vdash \Vvdash + \nVdash \nvdash \vDash \nvDash + \nVDash \oequal \simneqq \triangle + \triangleq \triangleeq \triangleleft + \triangleright \ntriangleleft \ntriangleright + \trianglelefteq \ntrianglelefteq \trianglerighteq + \ntrianglerighteq \blacktriangleleft \blacktriangleright + \equalparallel \measuredrightangle \varlrtriangle + \Doteq \Bumpeq \Subset \Supset + \backepsilon \because \therefore \bot + \top \bumpeq \circeq \coloneq + \curlyeqprec \curlyeqsucc \eqcirc \eqcolon + \eqsim \fallingdotseq \gtrdot \gtrless + \ltimes \rtimes \lessdot \ne + \ncong \nequiv \ngeq \ngtr + \nleq \nless \nmid \notin + \nprec \nsubset \nsubseteq \nsucc + \nsupset \nsupseteq \pitchfork \preccurlyeq + \risingdotseq \subsetneq \succcurlyeq \supsetneq + \varpropto \vartriangleleft \scurel + \vartriangleright \rightangle \equal \backcong + \eqdef \wedgeq \questeq \between + \veeeq \disin \varisins \isins + \isindot \varisinobar \isinobar \isinvb + \isinE \nisd \varnis \nis + \varniobar \niobar \bagmember \ratio + \Equiv \stareq \measeq \arceq + \rightassert \rightModels \smallin \smallowns + \notsmallowns \nsimeq'''.split()) + + _arrow_symbols = set(r""" + \leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow + \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow + \Longrightarrow \Downarrow \leftrightarrow \updownarrow + \longleftrightarrow \updownarrow \Leftrightarrow + \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow + \hookleftarrow \hookrightarrow \searrow \leftharpoonup + \rightharpoonup \swarrow \leftharpoondown \rightharpoondown + \nwarrow \rightleftharpoons \leadsto \dashrightarrow + \dashleftarrow \leftleftarrows \leftrightarrows \Lleftarrow + \Rrightarrow \twoheadleftarrow \leftarrowtail \looparrowleft + \leftrightharpoons \curvearrowleft \circlearrowleft \Lsh + \upuparrows \upharpoonleft \downharpoonleft \multimap + \leftrightsquigarrow \rightrightarrows \rightleftarrows + \rightrightarrows \rightleftarrows \twoheadrightarrow + \rightarrowtail \looparrowright \rightleftharpoons + \curvearrowright \circlearrowright \Rsh \downdownarrows + \upharpoonright \downharpoonright \rightsquigarrow \nleftarrow + \nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow + \nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow + \leftsquigarrow \overleftarrow \overleftrightarrow \cwopencirclearrow + \downzigzagarrow \cupleftarrow \rightzigzagarrow \twoheaddownarrow + \updownarrowbar \twoheaduparrow \rightarrowbar \updownarrows + \barleftarrow \mapsfrom \mapsdown \mapsup \Ldsh \Rdsh + """.split()) + + _spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols + + _punctuation_symbols = set(r', ; . ! \ldotp \cdotp'.split()) + + _overunder_symbols = set(r''' + \sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee + \bigwedge \bigodot \bigotimes \bigoplus \biguplus + '''.split()) + + _overunder_functions = set("lim liminf limsup sup max min".split()) + + _dropsub_symbols = set(r'\int \oint \iint \oiint \iiint \oiiint \iiiint'.split()) + + _fontnames = set("rm cal it tt sf bf bfit " + "default bb frak scr regular".split()) + + _function_names = set(""" + arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim + liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan + coth inf max tanh""".split()) + + _ambi_delims = set(r""" + | \| / \backslash \uparrow \downarrow \updownarrow \Uparrow + \Downarrow \Updownarrow . \vert \Vert""".split()) + _left_delims = set(r""" + ( [ \{ < \lfloor \langle \lceil \lbrace \leftbrace \lbrack \leftparen \lgroup + """.split()) + _right_delims = set(r""" + ) ] \} > \rfloor \rangle \rceil \rbrace \rightbrace \rbrack \rightparen \rgroup + """.split()) + _delims = _left_delims | _right_delims | _ambi_delims + + _small_greek = set([unicodedata.name(chr(i)).split()[-1].lower() for i in + range(ord('\N{GREEK SMALL LETTER ALPHA}'), + ord('\N{GREEK SMALL LETTER OMEGA}') + 1)]) + _latin_alphabets = set(string.ascii_letters) + + def __init__(self) -> None: + p = types.SimpleNamespace() + + def set_names_and_parse_actions() -> None: + for key, val in vars(p).items(): + if not key.startswith('_'): + # Set names on (almost) everything -- very useful for debugging + # token, placeable, and auto_delim are forward references which + # are left without names to ensure useful error messages + if key not in ("token", "placeable", "auto_delim"): + val.setName(key) + # Set actions + if hasattr(self, key): + val.setParseAction(getattr(self, key)) + + # Root definitions. + + # In TeX parlance, a csname is a control sequence name (a "\foo"). + def csnames(group: str, names: Iterable[str]) -> Regex: + ends_with_alpha = [] + ends_with_nonalpha = [] + for name in names: + if name[-1].isalpha(): + ends_with_alpha.append(name) + else: + ends_with_nonalpha.append(name) + return Regex( + r"\\(?P<{group}>(?:{alpha})(?![A-Za-z]){additional}{nonalpha})".format( + group=group, + alpha="|".join(map(re.escape, ends_with_alpha)), + additional="|" if ends_with_nonalpha else "", + nonalpha="|".join(map(re.escape, ends_with_nonalpha)), + ) + ) + + p.float_literal = Regex(r"[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)") + p.space = oneOf(self._space_widths)("space") + + p.style_literal = oneOf( + [str(e.value) for e in self._MathStyle])("style_literal") + + p.symbol = Regex( + r"[a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|\U00000080-\U0001ffff]" + r"|\\[%${}\[\]_|]" + + r"|\\(?:{})(?![A-Za-z])".format( + "|".join(map(re.escape, tex2uni))) + )("sym").leaveWhitespace() + p.unknown_symbol = Regex(r"\\[A-Za-z]+")("name") + + p.font = csnames("font", self._fontnames) + p.start_group = Optional(r"\math" + oneOf(self._fontnames)("font")) + "{" + p.end_group = Literal("}") + + p.delim = oneOf(self._delims) + + # Mutually recursive definitions. (Minimizing the number of Forward + # elements is important for speed.) + p.auto_delim = Forward() + p.placeable = Forward() + p.named_placeable = Forward() + p.required_group = Forward() + p.optional_group = Forward() + p.token = Forward() + + # Workaround for placable being part of a cycle of definitions + # calling `p.placeable("name")` results in a copy, so not guaranteed + # to get the definition added after it is used. + # ref https://github.com/matplotlib/matplotlib/issues/25204 + # xref https://github.com/pyparsing/pyparsing/issues/95 + p.named_placeable <<= p.placeable + + set_names_and_parse_actions() # for mutually recursive definitions. + + p.optional_group <<= "{" + ZeroOrMore(p.token)("group") + "}" + p.required_group <<= "{" + OneOrMore(p.token)("group") + "}" + + p.customspace = cmd(r"\hspace", "{" + p.float_literal("space") + "}") + + p.accent = ( + csnames("accent", [*self._accent_map, *self._wide_accents]) + - p.named_placeable("sym")) + + p.function = csnames("name", self._function_names) + + p.group = p.start_group + ZeroOrMore(p.token)("group") + p.end_group + p.unclosed_group = (p.start_group + ZeroOrMore(p.token)("group") + StringEnd()) + + p.frac = cmd(r"\frac", p.required_group("num") + p.required_group("den")) + p.dfrac = cmd(r"\dfrac", p.required_group("num") + p.required_group("den")) + p.binom = cmd(r"\binom", p.required_group("num") + p.required_group("den")) + + p.genfrac = cmd( + r"\genfrac", + "{" + Optional(p.delim)("ldelim") + "}" + + "{" + Optional(p.delim)("rdelim") + "}" + + "{" + p.float_literal("rulesize") + "}" + + "{" + Optional(p.style_literal)("style") + "}" + + p.required_group("num") + + p.required_group("den")) + + p.sqrt = cmd( + r"\sqrt{value}", + Optional("[" + OneOrMore(NotAny("]") + p.token)("root") + "]") + + p.required_group("value")) + + p.overline = cmd(r"\overline", p.required_group("body")) + + p.overset = cmd( + r"\overset", + p.optional_group("annotation") + p.optional_group("body")) + p.underset = cmd( + r"\underset", + p.optional_group("annotation") + p.optional_group("body")) + + p.text = cmd(r"\text", QuotedString('{', '\\', endQuoteChar="}")) + + p.substack = cmd(r"\substack", + nested_expr(opener="{", closer="}", + content=Group(OneOrMore(p.token)) + + ZeroOrMore(Literal("\\\\").suppress()))("parts")) + + p.subsuper = ( + (Optional(p.placeable)("nucleus") + + OneOrMore(oneOf(["_", "^"]) - p.placeable)("subsuper") + + Regex("'*")("apostrophes")) + | Regex("'+")("apostrophes") + | (p.named_placeable("nucleus") + Regex("'*")("apostrophes")) + ) + + p.simple = p.space | p.customspace | p.font | p.subsuper + + p.token <<= ( + p.simple + | p.auto_delim + | p.unclosed_group + | p.unknown_symbol # Must be last + ) + + p.operatorname = cmd(r"\operatorname", "{" + ZeroOrMore(p.simple)("name") + "}") + + p.boldsymbol = cmd( + r"\boldsymbol", "{" + ZeroOrMore(p.simple)("value") + "}") + + p.placeable <<= ( + p.accent # Must be before symbol as all accents are symbols + | p.symbol # Must be second to catch all named symbols and single + # chars not in a group + | p.function + | p.operatorname + | p.group + | p.frac + | p.dfrac + | p.binom + | p.genfrac + | p.overset + | p.underset + | p.sqrt + | p.overline + | p.text + | p.boldsymbol + | p.substack + ) + + mdelim = r"\middle" - (p.delim("mdelim") | Error("Expected a delimiter")) + p.auto_delim <<= ( + r"\left" - (p.delim("left") | Error("Expected a delimiter")) + + ZeroOrMore(p.simple | p.auto_delim | mdelim)("mid") + + r"\right" - (p.delim("right") | Error("Expected a delimiter")) + ) + + # Leaf definitions. + p.math = OneOrMore(p.token) + p.math_string = QuotedString('$', '\\', unquoteResults=False) + p.non_math = Regex(r"(?:(?:\\[$])|[^$])*").leaveWhitespace() + p.main = ( + p.non_math + ZeroOrMore(p.math_string + p.non_math) + StringEnd() + ) + set_names_and_parse_actions() # for leaf definitions. + + self._expression = p.main + self._math_expression = p.math + + # To add space to nucleus operators after sub/superscripts + self._in_subscript_or_superscript = False + + def parse(self, s: str, fonts_object: Fonts, fontsize: float, dpi: float) -> Hlist: + """ + Parse expression *s* using the given *fonts_object* for + output, at the given *fontsize* and *dpi*. + + Returns the parse tree of `Node` instances. + """ + self._state_stack = [ + ParserState(fonts_object, 'default', 'rm', fontsize, dpi)] + self._em_width_cache: dict[tuple[str, float, float], float] = {} + try: + result = self._expression.parseString(s) + except ParseBaseException as err: + # explain becomes a plain method on pyparsing 3 (err.explain(0)). + raise ValueError("\n" + ParseException.explain(err, 0)) from None + self._state_stack = [] + self._in_subscript_or_superscript = False + # prevent operator spacing from leaking into a new expression + self._em_width_cache = {} + ParserElement.resetCache() + return T.cast(Hlist, result[0]) # Known return type from main. + + def get_state(self) -> ParserState: + """Get the current `State` of the parser.""" + return self._state_stack[-1] + + def pop_state(self) -> None: + """Pop a `State` off of the stack.""" + self._state_stack.pop() + + def push_state(self) -> None: + """Push a new `State` onto the stack, copying the current state.""" + self._state_stack.append(self.get_state().copy()) + + def main(self, toks: ParseResults) -> list[Hlist]: + return [Hlist(toks.asList())] + + def math_string(self, toks: ParseResults) -> ParseResults: + return self._math_expression.parseString(toks[0][1:-1], parseAll=True) + + def math(self, toks: ParseResults) -> T.Any: + hlist = Hlist(toks.asList()) + self.pop_state() + return [hlist] + + def non_math(self, toks: ParseResults) -> T.Any: + s = toks[0].replace(r'\$', '$') + symbols = [Char(c, self.get_state()) for c in s] + hlist = Hlist(symbols) + # We're going into math now, so set font to 'it' + self.push_state() + self.get_state().font = mpl.rcParams['mathtext.default'] + return [hlist] + + float_literal = staticmethod(pyparsing_common.convertToFloat) + + def text(self, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + state.font = 'rm' + hlist = Hlist([Char(c, state) for c in toks[1]]) + self.pop_state() + return [hlist] + + def _make_space(self, percentage: float) -> Kern: + # In TeX, an em (the unit usually used to measure horizontal lengths) + # is not the width of the character 'm'; it is the same in different + # font styles (e.g. roman or italic). Mathtext, however, uses 'm' in + # the italic style so that horizontal spaces don't depend on the + # current font style. + state = self.get_state() + key = (state.font, state.fontsize, state.dpi) + width = self._em_width_cache.get(key) + if width is None: + metrics = state.fontset.get_metrics( + 'it', mpl.rcParams['mathtext.default'], 'm', + state.fontsize, state.dpi) + width = metrics.advance + self._em_width_cache[key] = width + return Kern(width * percentage) + + _space_widths = { + r'\,': 0.16667, # 3/18 em = 3 mu + r'\thinspace': 0.16667, # 3/18 em = 3 mu + r'\/': 0.16667, # 3/18 em = 3 mu + r'\>': 0.22222, # 4/18 em = 4 mu + r'\:': 0.22222, # 4/18 em = 4 mu + r'\;': 0.27778, # 5/18 em = 5 mu + r'\ ': 0.33333, # 6/18 em = 6 mu + r'~': 0.33333, # 6/18 em = 6 mu, nonbreakable + r'\enspace': 0.5, # 9/18 em = 9 mu + r'\quad': 1, # 1 em = 18 mu + r'\qquad': 2, # 2 em = 36 mu + r'\!': -0.16667, # -3/18 em = -3 mu + } + + def space(self, toks: ParseResults) -> T.Any: + num = self._space_widths[toks["space"]] + box = self._make_space(num) + return [box] + + def customspace(self, toks: ParseResults) -> T.Any: + return [self._make_space(toks["space"])] + + def symbol(self, s: str, loc: int, + toks: ParseResults | dict[str, str]) -> T.Any: + c = toks["sym"] + if c == "-": + # "U+2212 minus sign is the preferred representation of the unary + # and binary minus sign rather than the ASCII-derived U+002D + # hyphen-minus, because minus sign is unambiguous and because it + # is rendered with a more desirable length, usually longer than a + # hyphen." (https://www.unicode.org/reports/tr25/) + c = "\N{MINUS SIGN}" + try: + char = Char(c, self.get_state()) + except ValueError as err: + raise ParseFatalException(s, loc, + "Unknown symbol: %s" % c) from err + + if c in self._spaced_symbols: + # iterate until we find previous character, needed for cases + # such as ${ -2}$, $ -2$, or $ -2$. + prev_char = next((c for c in s[:loc][::-1] if c != ' '), '') + # Binary operators at start of string should not be spaced + # Also, operators in sub- or superscripts should not be spaced + if (self._in_subscript_or_superscript or ( + c in self._binary_operators and ( + len(s[:loc].split()) == 0 or prev_char == '{' or + prev_char in self._left_delims))): + return [char] + else: + return [Hlist([self._make_space(0.2), + char, + self._make_space(0.2)], + do_kern=True)] + elif c in self._punctuation_symbols: + prev_char = next((c for c in s[:loc][::-1] if c != ' '), '') + next_char = next((c for c in s[loc + 1:] if c != ' '), '') + + # Do not space commas between brackets + if c == ',': + if prev_char == '{' and next_char == '}': + return [char] + + # Do not space dots as decimal separators + if c == '.' and prev_char.isdigit() and next_char.isdigit(): + return [char] + else: + return [Hlist([char, self._make_space(0.2)], do_kern=True)] + return [char] + + def unknown_symbol(self, s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, loc, f"Unknown symbol: {toks['name']}") + + _accent_map = { + r'hat': r'\circumflexaccent', + r'breve': r'\combiningbreve', + r'bar': r'\combiningoverline', + r'grave': r'\combininggraveaccent', + r'acute': r'\combiningacuteaccent', + r'tilde': r'\combiningtilde', + r'dot': r'\combiningdotabove', + r'ddot': r'\combiningdiaeresis', + r'dddot': r'\combiningthreedotsabove', + r'ddddot': r'\combiningfourdotsabove', + r'vec': r'\combiningrightarrowabove', + r'"': r'\combiningdiaeresis', + r"`": r'\combininggraveaccent', + r"'": r'\combiningacuteaccent', + r'~': r'\combiningtilde', + r'.': r'\combiningdotabove', + r'^': r'\circumflexaccent', + r'overrightarrow': r'\rightarrow', + r'overleftarrow': r'\leftarrow', + r'mathring': r'\circ', + } + + _wide_accents = set(r"widehat widetilde widebar".split()) + + def accent(self, toks: ParseResults) -> T.Any: + state = self.get_state() + thickness = state.get_current_underline_thickness() + accent = toks["accent"] + sym = toks["sym"] + accent_box: Node + if accent in self._wide_accents: + accent_box = AutoWidthChar( + '\\' + accent, sym.width, state, char_class=Accent) + else: + accent_box = Accent(self._accent_map[accent], state) + if accent == 'mathring': + accent_box.shrink() + accent_box.shrink() + centered = HCentered([Hbox(sym.width / 4.0), accent_box]) + centered.hpack(sym.width, 'exactly') + return Vlist([ + centered, + Vbox(0., thickness * 2.0), + Hlist([sym]) + ]) + + def function(self, s: str, loc: int, toks: ParseResults) -> T.Any: + hlist = self.operatorname(s, loc, toks) + hlist.function_name = toks["name"] + return hlist + + def operatorname(self, s: str, loc: int, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + state.font = 'rm' + hlist_list: list[Node] = [] + # Change the font of Chars, but leave Kerns alone + name = toks["name"] + for c in name: + if isinstance(c, Char): + c.font = 'rm' + c._update_metrics() + hlist_list.append(c) + elif isinstance(c, str): + hlist_list.append(Char(c, state)) + else: + hlist_list.append(c) + next_char_loc = loc + len(name) + 1 + if isinstance(name, ParseResults): + next_char_loc += len('operatorname{}') + next_char = next((c for c in s[next_char_loc:] if c != ' '), '') + delimiters = self._delims | {'^', '_'} + if (next_char not in delimiters and + name not in self._overunder_functions): + # Add thin space except when followed by parenthesis, bracket, etc. + hlist_list += [self._make_space(self._space_widths[r'\,'])] + self.pop_state() + # if followed by a super/subscript, set flag to true + # This flag tells subsuper to add space after this operator + if next_char in {'^', '_'}: + self._in_subscript_or_superscript = True + else: + self._in_subscript_or_superscript = False + + return Hlist(hlist_list) + + def start_group(self, toks: ParseResults) -> T.Any: + self.push_state() + # Deal with LaTeX-style font tokens + if toks.get("font"): + self.get_state().font = toks.get("font") + return [] + + def group(self, toks: ParseResults) -> T.Any: + grp = Hlist(toks.get("group", [])) + return [grp] + + def required_group(self, toks: ParseResults) -> T.Any: + return Hlist(toks.get("group", [])) + + optional_group = required_group + + def end_group(self) -> T.Any: + self.pop_state() + return [] + + def unclosed_group(self, s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, len(s), "Expected '}'") + + def font(self, toks: ParseResults) -> T.Any: + self.get_state().font = toks["font"] + return [] + + def is_overunder(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.c in self._overunder_symbols + elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'): + return nucleus.function_name in self._overunder_functions + return False + + def is_dropsub(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.c in self._dropsub_symbols + return False + + def is_slanted(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.is_slanted() + return False + + def subsuper(self, s: str, loc: int, toks: ParseResults) -> T.Any: + nucleus = toks.get("nucleus", Hbox(0)) + subsuper = toks.get("subsuper", []) + napostrophes = len(toks.get("apostrophes", [])) + + if not subsuper and not napostrophes: + return nucleus + + sub = super = None + while subsuper: + op, arg, *subsuper = subsuper + if op == '_': + if sub is not None: + raise ParseFatalException("Double subscript") + sub = arg + else: + if super is not None: + raise ParseFatalException("Double superscript") + super = arg + + state = self.get_state() + rule_thickness = state.fontset.get_underline_thickness( + state.font, state.fontsize, state.dpi) + xHeight = state.fontset.get_xheight( + state.font, state.fontsize, state.dpi) + + if napostrophes: + if super is None: + super = Hlist([]) + for i in range(napostrophes): + super.children.extend(self.symbol(s, loc, {"sym": "\\prime"})) + # kern() and hpack() needed to get the metrics right after + # extending + super.kern() + super.hpack() + + # Handle over/under symbols, such as sum or prod + if self.is_overunder(nucleus): + vlist = [] + shift = 0. + width = nucleus.width + if super is not None: + super.shrink() + width = max(width, super.width) + if sub is not None: + sub.shrink() + width = max(width, sub.width) + + vgap = rule_thickness * 3.0 + if super is not None: + hlist = HCentered([super]) + hlist.hpack(width, 'exactly') + vlist.extend([hlist, Vbox(0, vgap)]) + hlist = HCentered([nucleus]) + hlist.hpack(width, 'exactly') + vlist.append(hlist) + if sub is not None: + hlist = HCentered([sub]) + hlist.hpack(width, 'exactly') + vlist.extend([Vbox(0, vgap), hlist]) + shift = hlist.height + vgap + nucleus.depth + vlt = Vlist(vlist) + vlt.shift_amount = shift + result = Hlist([vlt]) + return [result] + + # We remove kerning on the last character for consistency (otherwise + # it will compute kerning based on non-shrunk characters and may put + # them too close together when superscripted) + # We change the width of the last character to match the advance to + # consider some fonts with weird metrics: e.g. stix's f has a width of + # 7.75 and a kerning of -4.0 for an advance of 3.72, and we want to put + # the superscript at the advance + last_char = nucleus + if isinstance(nucleus, Hlist): + new_children = nucleus.children + if len(new_children): + # remove last kern + if (isinstance(new_children[-1], Kern) and + hasattr(new_children[-2], '_metrics')): + new_children = new_children[:-1] + last_char = new_children[-1] + if hasattr(last_char, '_metrics'): + last_char.width = last_char._metrics.advance + # create new Hlist without kerning + nucleus = Hlist(new_children, do_kern=False) + else: + if isinstance(nucleus, Char): + last_char.width = last_char._metrics.advance + nucleus = Hlist([nucleus]) + + # Handle regular sub/superscripts + constants = _get_font_constant_set(state) + lc_height = last_char.height + lc_baseline = 0 + if self.is_dropsub(last_char): + lc_baseline = last_char.depth + + # Compute kerning for sub and super + superkern = constants.delta * xHeight + subkern = constants.delta * xHeight + if self.is_slanted(last_char): + superkern += constants.delta * xHeight + superkern += (constants.delta_slanted * + (lc_height - xHeight * 2. / 3.)) + if self.is_dropsub(last_char): + subkern = (3 * constants.delta - + constants.delta_integral) * lc_height + superkern = (3 * constants.delta + + constants.delta_integral) * lc_height + else: + subkern = 0 + + x: List + if super is None: + # node757 + # Note: One of super or sub must be a Node if we're in this function, but + # mypy can't know this, since it can't interpret pyparsing expressions, + # hence the cast. + x = Hlist([Kern(subkern), T.cast(Node, sub)]) + x.shrink() + if self.is_dropsub(last_char): + shift_down = lc_baseline + constants.subdrop * xHeight + else: + shift_down = constants.sub1 * xHeight + x.shift_amount = shift_down + else: + x = Hlist([Kern(superkern), super]) + x.shrink() + if self.is_dropsub(last_char): + shift_up = lc_height - constants.subdrop * xHeight + else: + shift_up = constants.sup1 * xHeight + if sub is None: + x.shift_amount = -shift_up + else: # Both sub and superscript + y = Hlist([Kern(subkern), sub]) + y.shrink() + if self.is_dropsub(last_char): + shift_down = lc_baseline + constants.subdrop * xHeight + else: + shift_down = constants.sub2 * xHeight + # If sub and superscript collide, move super up + clr = (2.0 * rule_thickness - + ((shift_up - x.depth) - (y.height - shift_down))) + if clr > 0.: + shift_up += clr + x = Vlist([ + x, + Kern((shift_up - x.depth) - (y.height - shift_down)), + y]) + x.shift_amount = shift_down + + if not self.is_dropsub(last_char): + x.width += constants.script_space * xHeight + + # Do we need to add a space after the nucleus? + # To find out, check the flag set by operatorname + spaced_nucleus = [nucleus, x] + if self._in_subscript_or_superscript: + spaced_nucleus += [self._make_space(self._space_widths[r'\,'])] + self._in_subscript_or_superscript = False + + result = Hlist(spaced_nucleus) + return [result] + + def _genfrac(self, ldelim: str, rdelim: str, rule: float | None, style: _MathStyle, + num: Hlist, den: Hlist) -> T.Any: + state = self.get_state() + thickness = state.get_current_underline_thickness() + + for _ in range(style.value): + num.shrink() + den.shrink() + cnum = HCentered([num]) + cden = HCentered([den]) + width = max(num.width, den.width) + cnum.hpack(width, 'exactly') + cden.hpack(width, 'exactly') + vlist = Vlist([cnum, # numerator + Vbox(0, thickness * 2.0), # space + Hrule(state, rule), # rule + Vbox(0, thickness * 2.0), # space + cden # denominator + ]) + + # Shift so the fraction line sits in the middle of the + # equals sign + metrics = state.fontset.get_metrics( + state.font, mpl.rcParams['mathtext.default'], + '=', state.fontsize, state.dpi) + shift = (cden.height - + ((metrics.ymax + metrics.ymin) / 2 - + thickness * 3.0)) + vlist.shift_amount = shift + + result = [Hlist([vlist, Hbox(thickness * 2.)])] + if ldelim or rdelim: + if ldelim == '': + ldelim = '.' + if rdelim == '': + rdelim = '.' + return self._auto_sized_delimiter(ldelim, + T.cast(list[T.Union[Box, Char, str]], + result), + rdelim) + return result + + def style_literal(self, toks: ParseResults) -> T.Any: + return self._MathStyle(int(toks["style_literal"])) + + def genfrac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + toks.get("ldelim", ""), toks.get("rdelim", ""), + toks["rulesize"], toks.get("style", self._MathStyle.TEXTSTYLE), + toks["num"], toks["den"]) + + def frac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "", "", self.get_state().get_current_underline_thickness(), + self._MathStyle.TEXTSTYLE, toks["num"], toks["den"]) + + def dfrac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "", "", self.get_state().get_current_underline_thickness(), + self._MathStyle.DISPLAYSTYLE, toks["num"], toks["den"]) + + def binom(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "(", ")", 0, + self._MathStyle.TEXTSTYLE, toks["num"], toks["den"]) + + def _genset(self, s: str, loc: int, toks: ParseResults) -> T.Any: + annotation = toks["annotation"] + body = toks["body"] + thickness = self.get_state().get_current_underline_thickness() + + annotation.shrink() + centered_annotation = HCentered([annotation]) + centered_body = HCentered([body]) + width = max(centered_annotation.width, centered_body.width) + centered_annotation.hpack(width, 'exactly') + centered_body.hpack(width, 'exactly') + + vgap = thickness * 3 + if s[loc + 1] == "u": # \underset + vlist = Vlist([ + centered_body, # body + Vbox(0, vgap), # space + centered_annotation # annotation + ]) + # Shift so the body sits in the same vertical position + vlist.shift_amount = centered_body.depth + centered_annotation.height + vgap + else: # \overset + vlist = Vlist([ + centered_annotation, # annotation + Vbox(0, vgap), # space + centered_body # body + ]) + + # To add horizontal gap between symbols: wrap the Vlist into + # an Hlist and extend it with an Hbox(0, horizontal_gap) + return vlist + + overset = underset = _genset + + def sqrt(self, toks: ParseResults) -> T.Any: + root = toks.get("root") + body = toks["value"] + state = self.get_state() + thickness = state.get_current_underline_thickness() + + # Determine the height of the body, and add a little extra to + # the height so it doesn't seem cramped + height = body.height - body.shift_amount + thickness * 5.0 + depth = body.depth + body.shift_amount + check = AutoHeightChar(r'\__sqrt__', height, depth, state, always=True) + height = check.height - check.shift_amount + depth = check.depth + check.shift_amount + + # Put a little extra space to the left and right of the body + padded_body = Hlist([Hbox(2 * thickness), body, Hbox(2 * thickness)]) + rightside = Vlist([Hrule(state), Glue('fill'), padded_body]) + # Stretch the glue between the hrule and the body + rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), + 'exactly', depth) + + # Add the root and shift it upward so it is above the tick. + # The value of 0.6 is a hard-coded hack ;) + if not root: + root = Box(check.width * 0.5, 0., 0.) + else: + root = Hlist(root) + root.shrink() + root.shrink() + + root_vlist = Vlist([Hlist([root])]) + root_vlist.shift_amount = -height * 0.6 + + hlist = Hlist([root_vlist, # Root + # Negative kerning to put root over tick + Kern(-check.width * 0.5), + check, # Check + rightside]) # Body + return [hlist] + + def overline(self, toks: ParseResults) -> T.Any: + body = toks["body"] + + state = self.get_state() + thickness = state.get_current_underline_thickness() + + height = body.height - body.shift_amount + thickness * 3.0 + depth = body.depth + body.shift_amount + + # Place overline above body + rightside = Vlist([Hrule(state), Glue('fill'), Hlist([body])]) + + # Stretch the glue between the hrule and the body + rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), + 'exactly', depth) + + hlist = Hlist([rightside]) + return [hlist] + + def _auto_sized_delimiter(self, front: str, + middle: list[Box | Char | str], + back: str) -> T.Any: + state = self.get_state() + if len(middle): + height = max([x.height for x in middle if not isinstance(x, str)]) + depth = max([x.depth for x in middle if not isinstance(x, str)]) + factor = None + for idx, el in enumerate(middle): + if el == r'\middle': + c = T.cast(str, middle[idx + 1]) # Should be one of p.delims. + if c != '.': + middle[idx + 1] = AutoHeightChar( + c, height, depth, state, factor=factor) + else: + middle.remove(c) + del middle[idx] + # There should only be \middle and its delimiter as str, which have + # just been removed. + middle_part = T.cast(list[T.Union[Box, Char]], middle) + else: + height = 0 + depth = 0 + factor = 1.0 + middle_part = [] + + parts: list[Node] = [] + # \left. and \right. aren't supposed to produce any symbols + if front != '.': + parts.append( + AutoHeightChar(front, height, depth, state, factor=factor)) + parts.extend(middle_part) + if back != '.': + parts.append( + AutoHeightChar(back, height, depth, state, factor=factor)) + hlist = Hlist(parts) + return hlist + + def auto_delim(self, toks: ParseResults) -> T.Any: + return self._auto_sized_delimiter( + toks["left"], + # if "mid" in toks ... can be removed when requiring pyparsing 3. + toks["mid"].asList() if "mid" in toks else [], + toks["right"]) + + def boldsymbol(self, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + hlist: list[Node] = [] + name = toks["value"] + for c in name: + if isinstance(c, Hlist): + k = c.children[1] + if isinstance(k, Char): + k.font = "bf" + k._update_metrics() + hlist.append(c) + elif isinstance(c, Char): + c.font = "bf" + if (c.c in self._latin_alphabets or + c.c[1:] in self._small_greek): + c.font = "bfit" + c._update_metrics() + c._update_metrics() + hlist.append(c) + else: + hlist.append(c) + self.pop_state() + + return Hlist(hlist) + + def substack(self, toks: ParseResults) -> T.Any: + parts = toks["parts"] + state = self.get_state() + thickness = state.get_current_underline_thickness() + + hlist = [Hlist(k) for k in parts[0]] + max_width = max(map(lambda c: c.width, hlist)) + + vlist = [] + for sub in hlist: + cp = HCentered([sub]) + cp.hpack(max_width, 'exactly') + vlist.append(cp) + + stack = [val + for pair in zip(vlist, [Vbox(0, thickness * 2)] * len(vlist)) + for val in pair] + del stack[-1] + vlt = Vlist(stack) + result = [Hlist([vlt])] + return result diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.py b/parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2913957194022d85297aae9083eea4740f23ba --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.py @@ -0,0 +1,18 @@ +from . import _base +from ._axes import Axes # noqa: F401 + +# Backcompat. +Subplot = Axes + + +class _SubplotBaseMeta(type): + def __instancecheck__(self, obj): + return (isinstance(obj, _base._AxesBase) + and obj.get_subplotspec() is not None) + + +class SubplotBase(metaclass=_SubplotBaseMeta): + pass + + +def subplot_class_factory(cls): return cls diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.pyi b/parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7df38b8bde9edc06720e08f41c245ab8d61fc091 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.pyi @@ -0,0 +1,16 @@ +from typing import TypeVar + +from ._axes import Axes as Axes + + +_T = TypeVar("_T") + +# Backcompat. +Subplot = Axes + +class _SubplotBaseMeta(type): + def __instancecheck__(self, obj) -> bool: ... + +class SubplotBase(metaclass=_SubplotBaseMeta): ... + +def subplot_class_factory(cls: type[_T]) -> type[_T]: ... diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3918dc90fde9c62829a0fea6157680c31e2c0d70 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_secondary_axes.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_secondary_axes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35e0f0687b4f0d091b6dfb41f9b9183ca4e443c3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_secondary_axes.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.py b/parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..040c5a4ba4e95dd76aa077681f36c23367d0edd2 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.py @@ -0,0 +1,8634 @@ +import functools +import itertools +import logging +import math +from numbers import Integral, Number, Real + +import re +import numpy as np +from numpy import ma + +import matplotlib as mpl +import matplotlib.category # Register category unit converter as side effect. +import matplotlib.cbook as cbook +import matplotlib.collections as mcoll +import matplotlib.colors as mcolors +import matplotlib.contour as mcontour +import matplotlib.dates # noqa # Register date unit converter as side effect. +import matplotlib.image as mimage +import matplotlib.legend as mlegend +import matplotlib.lines as mlines +import matplotlib.markers as mmarkers +import matplotlib.mlab as mlab +import matplotlib.patches as mpatches +import matplotlib.path as mpath +import matplotlib.quiver as mquiver +import matplotlib.stackplot as mstack +import matplotlib.streamplot as mstream +import matplotlib.table as mtable +import matplotlib.text as mtext +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms +import matplotlib.tri as mtri +import matplotlib.units as munits +from matplotlib import _api, _docstring, _preprocess_data +from matplotlib.axes._base import ( + _AxesBase, _TransformedBoundsLocator, _process_plot_format) +from matplotlib.axes._secondary_axes import SecondaryAxis +from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer + +_log = logging.getLogger(__name__) + + +# The axes module contains all the wrappers to plotting functions. +# All the other methods should go in the _AxesBase class. + + +def _make_axes_method(func): + """ + Patch the qualname for functions that are directly added to Axes. + + Some Axes functionality is defined in functions in other submodules. + These are simply added as attributes to Axes. As a result, their + ``__qualname__`` is e.g. only "table" and not "Axes.table". This + function fixes that. + + Note that the function itself is patched, so that + ``matplotlib.table.table.__qualname__` will also show "Axes.table". + However, since these functions are not intended to be standalone, + this is bearable. + """ + func.__qualname__ = f"Axes.{func.__name__}" + return func + + +@_docstring.interpd +class Axes(_AxesBase): + """ + An Axes object encapsulates all the elements of an individual (sub-)plot in + a figure. + + It contains most of the (sub-)plot elements: `~.axis.Axis`, + `~.axis.Tick`, `~.lines.Line2D`, `~.text.Text`, `~.patches.Polygon`, etc., + and sets the coordinate system. + + Like all visible elements in a figure, Axes is an `.Artist` subclass. + + The `Axes` instance supports callbacks through a callbacks attribute which + is a `~.cbook.CallbackRegistry` instance. The events you can connect to + are 'xlim_changed' and 'ylim_changed' and the callback will be called with + func(*ax*) where *ax* is the `Axes` instance. + + .. note:: + + As a user, you do not instantiate Axes directly, but use Axes creation + methods instead; e.g. from `.pyplot` or `.Figure`: + `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` or `.Figure.add_axes`. + + Attributes + ---------- + dataLim : `.Bbox` + The bounding box enclosing all data displayed in the Axes. + viewLim : `.Bbox` + The view limits in data coordinates. + + """ + ### Labelling, legend and texts + + def get_title(self, loc="center"): + """ + Get an Axes title. + + Get one of the three available Axes titles. The available titles + are positioned above the Axes in the center, flush with the left + edge, and flush with the right edge. + + Parameters + ---------- + loc : {'center', 'left', 'right'}, str, default: 'center' + Which title to return. + + Returns + ------- + str + The title text string. + + """ + titles = {'left': self._left_title, + 'center': self.title, + 'right': self._right_title} + title = _api.check_getitem(titles, loc=loc.lower()) + return title.get_text() + + def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, + **kwargs): + """ + Set a title for the Axes. + + Set one of the three available Axes titles. The available titles + are positioned above the Axes in the center, flush with the left + edge, and flush with the right edge. + + Parameters + ---------- + label : str + Text to use for the title + + fontdict : dict + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``set_title(..., **fontdict)``. + + A dictionary controlling the appearance of the title text, + the default *fontdict* is:: + + {'fontsize': rcParams['axes.titlesize'], + 'fontweight': rcParams['axes.titleweight'], + 'color': rcParams['axes.titlecolor'], + 'verticalalignment': 'baseline', + 'horizontalalignment': loc} + + loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation` + Which title to set. + + y : float, default: :rc:`axes.titley` + Vertical Axes location for the title (1.0 is the top). If + None (the default) and :rc:`axes.titley` is also None, y is + determined automatically to avoid decorators on the Axes. + + pad : float, default: :rc:`axes.titlepad` + The offset of the title from the top of the Axes, in points. + + Returns + ------- + `.Text` + The matplotlib text instance representing the title + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + Other keyword arguments are text properties, see `.Text` for a list + of valid text properties. + """ + if loc is None: + loc = mpl.rcParams['axes.titlelocation'] + + if y is None: + y = mpl.rcParams['axes.titley'] + if y is None: + y = 1.0 + else: + self._autotitlepos = False + kwargs['y'] = y + + titles = {'left': self._left_title, + 'center': self.title, + 'right': self._right_title} + title = _api.check_getitem(titles, loc=loc.lower()) + default = { + 'fontsize': mpl.rcParams['axes.titlesize'], + 'fontweight': mpl.rcParams['axes.titleweight'], + 'verticalalignment': 'baseline', + 'horizontalalignment': loc.lower()} + titlecolor = mpl.rcParams['axes.titlecolor'] + if not cbook._str_lower_equal(titlecolor, 'auto'): + default["color"] = titlecolor + if pad is None: + pad = mpl.rcParams['axes.titlepad'] + self._set_title_offset_trans(float(pad)) + title.set_text(label) + title.update(default) + if fontdict is not None: + title.update(fontdict) + title._internal_update(kwargs) + return title + + def get_legend_handles_labels(self, legend_handler_map=None): + """ + Return handles and labels for legend + + ``ax.legend()`` is equivalent to :: + + h, l = ax.get_legend_handles_labels() + ax.legend(h, l) + """ + # pass through to legend. + handles, labels = mlegend._get_legend_handles_labels( + [self], legend_handler_map) + return handles, labels + + @_docstring.dedent_interpd + def legend(self, *args, **kwargs): + """ + Place a legend on the Axes. + + Call signatures:: + + legend() + legend(handles, labels) + legend(handles=handles) + legend(labels) + + The call signatures correspond to the following different ways to use + this method: + + **1. Automatic detection of elements to be shown in the legend** + + The elements to be added to the legend are automatically determined, + when you do not pass in any extra arguments. + + In this case, the labels are taken from the artist. You can specify + them either at artist creation or by calling the + :meth:`~.Artist.set_label` method on the artist:: + + ax.plot([1, 2, 3], label='Inline label') + ax.legend() + + or:: + + line, = ax.plot([1, 2, 3]) + line.set_label('Label via method') + ax.legend() + + .. note:: + Specific artists can be excluded from the automatic legend element + selection by using a label starting with an underscore, "_". + A string starting with an underscore is the default label for all + artists, so calling `.Axes.legend` without any arguments and + without setting the labels manually will result in a ``UserWarning`` + and an empty legend being drawn. + + + **2. Explicitly listing the artists and labels in the legend** + + For full control of which artists have a legend entry, it is possible + to pass an iterable of legend artists followed by an iterable of + legend labels respectively:: + + ax.legend([line1, line2, line3], ['label1', 'label2', 'label3']) + + + **3. Explicitly listing the artists in the legend** + + This is similar to 2, but the labels are taken from the artists' + label properties. Example:: + + line1, = ax.plot([1, 2, 3], label='label1') + line2, = ax.plot([1, 2, 3], label='label2') + ax.legend(handles=[line1, line2]) + + + **4. Labeling existing plot elements** + + .. admonition:: Discouraged + + This call signature is discouraged, because the relation between + plot elements and labels is only implicit by their order and can + easily be mixed up. + + To make a legend for all artists on an Axes, call this function with + an iterable of strings, one for each legend item. For example:: + + ax.plot([1, 2, 3]) + ax.plot([5, 6, 7]) + ax.legend(['First line', 'Second line']) + + + Parameters + ---------- + handles : list of (`.Artist` or tuple of `.Artist`), optional + A list of Artists (lines, patches) to be added to the legend. + Use this together with *labels*, if you need full control on what + is shown in the legend and the automatic mechanism described above + is not sufficient. + + The length of handles and labels should be the same in this + case. If they are not, they are truncated to the smaller length. + + If an entry contains a tuple, then the legend handler for all Artists in the + tuple will be placed alongside a single label. + + labels : list of str, optional + A list of labels to show next to the artists. + Use this together with *handles*, if you need full control on what + is shown in the legend and the automatic mechanism described above + is not sufficient. + + Returns + ------- + `~matplotlib.legend.Legend` + + Other Parameters + ---------------- + %(_legend_kw_axes)s + + See Also + -------- + .Figure.legend + + Notes + ----- + Some artists are not supported by this function. See + :ref:`legend_guide` for details. + + Examples + -------- + .. plot:: gallery/text_labels_and_annotations/legend.py + """ + handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs) + self.legend_ = mlegend.Legend(self, handles, labels, **kwargs) + self.legend_._remove_method = self._remove_legend + return self.legend_ + + def _remove_legend(self, legend): + self.legend_ = None + + def inset_axes(self, bounds, *, transform=None, zorder=5, **kwargs): + """ + Add a child inset Axes to this existing Axes. + + + Parameters + ---------- + bounds : [x0, y0, width, height] + Lower-left corner of inset Axes, and its width and height. + + transform : `.Transform` + Defaults to `ax.transAxes`, i.e. the units of *rect* are in + Axes-relative coordinates. + + projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ +'polar', 'rectilinear', str}, optional + The projection type of the inset `~.axes.Axes`. *str* is the name + of a custom projection, see `~matplotlib.projections`. The default + None results in a 'rectilinear' projection. + + polar : bool, default: False + If True, equivalent to projection='polar'. + + axes_class : subclass type of `~.axes.Axes`, optional + The `.axes.Axes` subclass that is instantiated. This parameter + is incompatible with *projection* and *polar*. See + :ref:`axisartist_users-guide-index` for examples. + + zorder : number + Defaults to 5 (same as `.Axes.legend`). Adjust higher or lower + to change whether it is above or below data plotted on the + parent Axes. + + **kwargs + Other keyword arguments are passed on to the inset Axes class. + + Returns + ------- + ax + The created `~.axes.Axes` instance. + + Examples + -------- + This example makes two inset Axes, the first is in Axes-relative + coordinates, and the second in data-coordinates:: + + fig, ax = plt.subplots() + ax.plot(range(10)) + axin1 = ax.inset_axes([0.8, 0.1, 0.15, 0.15]) + axin2 = ax.inset_axes( + [5, 7, 2.3, 2.3], transform=ax.transData) + + """ + if transform is None: + transform = self.transAxes + kwargs.setdefault('label', 'inset_axes') + + # This puts the rectangle into figure-relative coordinates. + inset_locator = _TransformedBoundsLocator(bounds, transform) + bounds = inset_locator(self, None).bounds + projection_class, pkw = self.figure._process_projection_requirements(**kwargs) + inset_ax = projection_class(self.figure, bounds, zorder=zorder, **pkw) + + # this locator lets the axes move if in data coordinates. + # it gets called in `ax.apply_aspect() (of all places) + inset_ax.set_axes_locator(inset_locator) + + self.add_child_axes(inset_ax) + + return inset_ax + + @_docstring.dedent_interpd + def indicate_inset(self, bounds, inset_ax=None, *, transform=None, + facecolor='none', edgecolor='0.5', alpha=0.5, + zorder=4.99, **kwargs): + """ + Add an inset indicator to the Axes. This is a rectangle on the plot + at the position indicated by *bounds* that optionally has lines that + connect the rectangle to an inset Axes (`.Axes.inset_axes`). + + Warnings + -------- + This method is experimental as of 3.0, and the API may change. + + Parameters + ---------- + bounds : [x0, y0, width, height] + Lower-left corner of rectangle to be marked, and its width + and height. + + inset_ax : `.Axes` + An optional inset Axes to draw connecting lines to. Two lines are + drawn connecting the indicator box to the inset Axes on corners + chosen so as to not overlap with the indicator box. + + transform : `.Transform` + Transform for the rectangle coordinates. Defaults to + `ax.transAxes`, i.e. the units of *rect* are in Axes-relative + coordinates. + + facecolor : :mpltype:`color`, default: 'none' + Facecolor of the rectangle. + + edgecolor : :mpltype:`color`, default: '0.5' + Color of the rectangle and color of the connecting lines. + + alpha : float, default: 0.5 + Transparency of the rectangle and connector lines. + + zorder : float, default: 4.99 + Drawing order of the rectangle and connector lines. The default, + 4.99, is just below the default level of inset Axes. + + **kwargs + Other keyword arguments are passed on to the `.Rectangle` patch: + + %(Rectangle:kwdoc)s + + Returns + ------- + rectangle_patch : `.patches.Rectangle` + The indicator frame. + + connector_lines : 4-tuple of `.patches.ConnectionPatch` + The four connector lines connecting to (lower_left, upper_left, + lower_right upper_right) corners of *inset_ax*. Two lines are + set with visibility to *False*, but the user can set the + visibility to True if the automatic choice is not deemed correct. + + """ + # to make the Axes connectors work, we need to apply the aspect to + # the parent Axes. + self.apply_aspect() + + if transform is None: + transform = self.transData + kwargs.setdefault('label', '_indicate_inset') + + x, y, width, height = bounds + rectangle_patch = mpatches.Rectangle( + (x, y), width, height, + facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, + zorder=zorder, transform=transform, **kwargs) + self.add_patch(rectangle_patch) + + connects = [] + + if inset_ax is not None: + # connect the inset_axes to the rectangle + for xy_inset_ax in [(0, 0), (0, 1), (1, 0), (1, 1)]: + # inset_ax positions are in axes coordinates + # The 0, 1 values define the four edges if the inset_ax + # lower_left, upper_left, lower_right upper_right. + ex, ey = xy_inset_ax + if self.xaxis.get_inverted(): + ex = 1 - ex + if self.yaxis.get_inverted(): + ey = 1 - ey + xy_data = x + ex * width, y + ey * height + p = mpatches.ConnectionPatch( + xyA=xy_inset_ax, coordsA=inset_ax.transAxes, + xyB=xy_data, coordsB=self.transData, + arrowstyle="-", zorder=zorder, + edgecolor=edgecolor, alpha=alpha) + connects.append(p) + self.add_patch(p) + + # decide which two of the lines to keep visible.... + pos = inset_ax.get_position() + bboxins = pos.transformed(self.figure.transSubfigure) + rectbbox = mtransforms.Bbox.from_bounds( + *bounds + ).transformed(transform) + x0 = rectbbox.x0 < bboxins.x0 + x1 = rectbbox.x1 < bboxins.x1 + y0 = rectbbox.y0 < bboxins.y0 + y1 = rectbbox.y1 < bboxins.y1 + connects[0].set_visible(x0 ^ y0) + connects[1].set_visible(x0 == y1) + connects[2].set_visible(x1 == y0) + connects[3].set_visible(x1 ^ y1) + + return rectangle_patch, tuple(connects) if connects else None + + def indicate_inset_zoom(self, inset_ax, **kwargs): + """ + Add an inset indicator rectangle to the Axes based on the axis + limits for an *inset_ax* and draw connectors between *inset_ax* + and the rectangle. + + Warnings + -------- + This method is experimental as of 3.0, and the API may change. + + Parameters + ---------- + inset_ax : `.Axes` + Inset Axes to draw connecting lines to. Two lines are + drawn connecting the indicator box to the inset Axes on corners + chosen so as to not overlap with the indicator box. + + **kwargs + Other keyword arguments are passed on to `.Axes.indicate_inset` + + Returns + ------- + rectangle_patch : `.patches.Rectangle` + Rectangle artist. + + connector_lines : 4-tuple of `.patches.ConnectionPatch` + Each of four connector lines coming from the rectangle drawn on + this axis, in the order lower left, upper left, lower right, + upper right. + Two are set with visibility to *False*, but the user can + set the visibility to *True* if the automatic choice is not deemed + correct. + """ + + xlim = inset_ax.get_xlim() + ylim = inset_ax.get_ylim() + rect = (xlim[0], ylim[0], xlim[1] - xlim[0], ylim[1] - ylim[0]) + return self.indicate_inset(rect, inset_ax, **kwargs) + + @_docstring.dedent_interpd + def secondary_xaxis(self, location, *, functions=None, transform=None, **kwargs): + """ + Add a second x-axis to this `~.axes.Axes`. + + For example if we want to have a second scale for the data plotted on + the xaxis. + + %(_secax_docstring)s + + Examples + -------- + The main axis shows frequency, and the secondary axis shows period. + + .. plot:: + + fig, ax = plt.subplots() + ax.loglog(range(1, 360, 5), range(1, 360, 5)) + ax.set_xlabel('frequency [Hz]') + + def invert(x): + # 1/x with special treatment of x == 0 + x = np.array(x).astype(float) + near_zero = np.isclose(x, 0) + x[near_zero] = np.inf + x[~near_zero] = 1 / x[~near_zero] + return x + + # the inverse of 1/x is itself + secax = ax.secondary_xaxis('top', functions=(invert, invert)) + secax.set_xlabel('Period [s]') + plt.show() + + To add a secondary axis relative to your data, you can pass a transform + to the new axis. + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(0, 5), range(-1, 4)) + + # Pass 'ax.transData' as a transform to place the axis + # relative to your data at y=0 + secax = ax.secondary_xaxis(0, transform=ax.transData) + """ + if not (location in ['top', 'bottom'] or isinstance(location, Real)): + raise ValueError('secondary_xaxis location must be either ' + 'a float or "top"/"bottom"') + + secondary_ax = SecondaryAxis(self, 'x', location, functions, + transform, **kwargs) + self.add_child_axes(secondary_ax) + return secondary_ax + + @_docstring.dedent_interpd + def secondary_yaxis(self, location, *, functions=None, transform=None, **kwargs): + """ + Add a second y-axis to this `~.axes.Axes`. + + For example if we want to have a second scale for the data plotted on + the yaxis. + + %(_secax_docstring)s + + Examples + -------- + Add a secondary Axes that converts from radians to degrees + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(1, 360, 5), range(1, 360, 5)) + ax.set_ylabel('degrees') + secax = ax.secondary_yaxis('right', functions=(np.deg2rad, + np.rad2deg)) + secax.set_ylabel('radians') + + To add a secondary axis relative to your data, you can pass a transform + to the new axis. + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(0, 5), range(-1, 4)) + + # Pass 'ax.transData' as a transform to place the axis + # relative to your data at x=3 + secax = ax.secondary_yaxis(3, transform=ax.transData) + """ + if not (location in ['left', 'right'] or isinstance(location, Real)): + raise ValueError('secondary_yaxis location must be either ' + 'a float or "left"/"right"') + + secondary_ax = SecondaryAxis(self, 'y', location, functions, + transform, **kwargs) + self.add_child_axes(secondary_ax) + return secondary_ax + + @_docstring.dedent_interpd + def text(self, x, y, s, fontdict=None, **kwargs): + """ + Add text to the Axes. + + Add the text *s* to the Axes at location *x*, *y* in data coordinates, + with a default ``horizontalalignment`` on the ``left`` and + ``verticalalignment`` at the ``baseline``. See + :doc:`/gallery/text_labels_and_annotations/text_alignment`. + + Parameters + ---------- + x, y : float + The position to place the text. By default, this is in data + coordinates. The coordinate system can be changed using the + *transform* parameter. + + s : str + The text. + + fontdict : dict, default: None + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``text(..., **fontdict)``. + + A dictionary to override the default text properties. If fontdict + is None, the defaults are determined by `.rcParams`. + + Returns + ------- + `.Text` + The created `.Text` instance. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties. + Other miscellaneous text parameters. + + %(Text:kwdoc)s + + Examples + -------- + Individual keyword arguments can be used to override any given + parameter:: + + >>> text(x, y, s, fontsize=12) + + The default transform specifies that text is in data coords, + alternatively, you can specify text in axis coords ((0, 0) is + lower-left and (1, 1) is upper-right). The example below places + text in the center of the Axes:: + + >>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center', + ... verticalalignment='center', transform=ax.transAxes) + + You can put a rectangular box around the text instance (e.g., to + set a background color) by using the keyword *bbox*. *bbox* is + a dictionary of `~matplotlib.patches.Rectangle` + properties. For example:: + + >>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5)) + """ + effective_kwargs = { + 'verticalalignment': 'baseline', + 'horizontalalignment': 'left', + 'transform': self.transData, + 'clip_on': False, + **(fontdict if fontdict is not None else {}), + **kwargs, + } + t = mtext.Text(x, y, text=s, **effective_kwargs) + if t.get_clip_path() is None: + t.set_clip_path(self.patch) + self._add_text(t) + return t + + @_docstring.dedent_interpd + def annotate(self, text, xy, xytext=None, xycoords='data', textcoords=None, + arrowprops=None, annotation_clip=None, **kwargs): + # Signature must match Annotation. This is verified in + # test_annotate_signature(). + a = mtext.Annotation(text, xy, xytext=xytext, xycoords=xycoords, + textcoords=textcoords, arrowprops=arrowprops, + annotation_clip=annotation_clip, **kwargs) + a.set_transform(mtransforms.IdentityTransform()) + if kwargs.get('clip_on', False) and a.get_clip_path() is None: + a.set_clip_path(self.patch) + self._add_text(a) + return a + annotate.__doc__ = mtext.Annotation.__init__.__doc__ + #### Lines and spans + + @_docstring.dedent_interpd + def axhline(self, y=0, xmin=0, xmax=1, **kwargs): + """ + Add a horizontal line across the Axes. + + Parameters + ---------- + y : float, default: 0 + y position in data coordinates of the horizontal line. + + xmin : float, default: 0 + Should be between 0 and 1, 0 being the far left of the plot, 1 the + far right of the plot. + + xmax : float, default: 1 + Should be between 0 and 1, 0 being the far left of the plot, 1 the + far right of the plot. + + Returns + ------- + `~matplotlib.lines.Line2D` + + Other Parameters + ---------------- + **kwargs + Valid keyword arguments are `.Line2D` properties, except for + 'transform': + + %(Line2D:kwdoc)s + + See Also + -------- + hlines : Add horizontal lines in data coordinates. + axhspan : Add a horizontal span (rectangle) across the axis. + axline : Add a line with an arbitrary slope. + + Examples + -------- + * draw a thick red hline at 'y' = 0 that spans the xrange:: + + >>> axhline(linewidth=4, color='r') + + * draw a default hline at 'y' = 1 that spans the xrange:: + + >>> axhline(y=1) + + * draw a default hline at 'y' = .5 that spans the middle half of + the xrange:: + + >>> axhline(y=.5, xmin=0.25, xmax=0.75) + """ + self._check_no_units([xmin, xmax], ['xmin', 'xmax']) + if "transform" in kwargs: + raise ValueError("'transform' is not allowed as a keyword " + "argument; axhline generates its own transform.") + ymin, ymax = self.get_ybound() + + # Strip away the units for comparison with non-unitized bounds. + yy, = self._process_unit_info([("y", y)], kwargs) + scaley = (yy < ymin) or (yy > ymax) + + trans = self.get_yaxis_transform(which='grid') + l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs) + self.add_line(l) + l.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + if scaley: + self._request_autoscale_view("y") + return l + + @_docstring.dedent_interpd + def axvline(self, x=0, ymin=0, ymax=1, **kwargs): + """ + Add a vertical line across the Axes. + + Parameters + ---------- + x : float, default: 0 + x position in data coordinates of the vertical line. + + ymin : float, default: 0 + Should be between 0 and 1, 0 being the bottom of the plot, 1 the + top of the plot. + + ymax : float, default: 1 + Should be between 0 and 1, 0 being the bottom of the plot, 1 the + top of the plot. + + Returns + ------- + `~matplotlib.lines.Line2D` + + Other Parameters + ---------------- + **kwargs + Valid keyword arguments are `.Line2D` properties, except for + 'transform': + + %(Line2D:kwdoc)s + + See Also + -------- + vlines : Add vertical lines in data coordinates. + axvspan : Add a vertical span (rectangle) across the axis. + axline : Add a line with an arbitrary slope. + + Examples + -------- + * draw a thick red vline at *x* = 0 that spans the yrange:: + + >>> axvline(linewidth=4, color='r') + + * draw a default vline at *x* = 1 that spans the yrange:: + + >>> axvline(x=1) + + * draw a default vline at *x* = .5 that spans the middle half of + the yrange:: + + >>> axvline(x=.5, ymin=0.25, ymax=0.75) + """ + self._check_no_units([ymin, ymax], ['ymin', 'ymax']) + if "transform" in kwargs: + raise ValueError("'transform' is not allowed as a keyword " + "argument; axvline generates its own transform.") + xmin, xmax = self.get_xbound() + + # Strip away the units for comparison with non-unitized bounds. + xx, = self._process_unit_info([("x", x)], kwargs) + scalex = (xx < xmin) or (xx > xmax) + + trans = self.get_xaxis_transform(which='grid') + l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs) + self.add_line(l) + l.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + if scalex: + self._request_autoscale_view("x") + return l + + @staticmethod + def _check_no_units(vals, names): + # Helper method to check that vals are not unitized + for val, name in zip(vals, names): + if not munits._is_natively_supported(val): + raise ValueError(f"{name} must be a single scalar value, " + f"but got {val}") + + @_docstring.dedent_interpd + def axline(self, xy1, xy2=None, *, slope=None, **kwargs): + """ + Add an infinitely long straight line. + + The line can be defined either by two points *xy1* and *xy2*, or + by one point *xy1* and a *slope*. + + This draws a straight line "on the screen", regardless of the x and y + scales, and is thus also suitable for drawing exponential decays in + semilog plots, power laws in loglog plots, etc. However, *slope* + should only be used with linear scales; It has no clear meaning for + all other scales, and thus the behavior is undefined. Please specify + the line using the points *xy1*, *xy2* for non-linear scales. + + The *transform* keyword argument only applies to the points *xy1*, + *xy2*. The *slope* (if given) is always in data coordinates. This can + be used e.g. with ``ax.transAxes`` for drawing grid lines with a fixed + slope. + + Parameters + ---------- + xy1, xy2 : (float, float) + Points for the line to pass through. + Either *xy2* or *slope* has to be given. + slope : float, optional + The slope of the line. Either *xy2* or *slope* has to be given. + + Returns + ------- + `.AxLine` + + Other Parameters + ---------------- + **kwargs + Valid kwargs are `.Line2D` properties + + %(Line2D:kwdoc)s + + See Also + -------- + axhline : for horizontal lines + axvline : for vertical lines + + Examples + -------- + Draw a thick red line passing through (0, 0) and (1, 1):: + + >>> axline((0, 0), (1, 1), linewidth=4, color='r') + """ + if slope is not None and (self.get_xscale() != 'linear' or + self.get_yscale() != 'linear'): + raise TypeError("'slope' cannot be used with non-linear scales") + + datalim = [xy1] if xy2 is None else [xy1, xy2] + if "transform" in kwargs: + # if a transform is passed (i.e. line points not in data space), + # data limits should not be adjusted. + datalim = [] + + line = mlines.AxLine(xy1, xy2, slope, **kwargs) + # Like add_line, but correctly handling data limits. + self._set_artist_props(line) + if line.get_clip_path() is None: + line.set_clip_path(self.patch) + if not line.get_label(): + line.set_label(f"_child{len(self._children)}") + self._children.append(line) + line._remove_method = self._children.remove + self.update_datalim(datalim) + + self._request_autoscale_view() + return line + + @_docstring.dedent_interpd + def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs): + """ + Add a horizontal span (rectangle) across the Axes. + + The rectangle spans from *ymin* to *ymax* vertically, and, by default, + the whole x-axis horizontally. The x-span can be set using *xmin* + (default: 0) and *xmax* (default: 1) which are in axis units; e.g. + ``xmin = 0.5`` always refers to the middle of the x-axis regardless of + the limits set by `~.Axes.set_xlim`. + + Parameters + ---------- + ymin : float + Lower y-coordinate of the span, in data units. + ymax : float + Upper y-coordinate of the span, in data units. + xmin : float, default: 0 + Lower x-coordinate of the span, in x-axis (0-1) units. + xmax : float, default: 1 + Upper x-coordinate of the span, in x-axis (0-1) units. + + Returns + ------- + `~matplotlib.patches.Rectangle` + Horizontal span (rectangle) from (xmin, ymin) to (xmax, ymax). + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + axvspan : Add a vertical span across the Axes. + """ + # Strip units away. + self._check_no_units([xmin, xmax], ['xmin', 'xmax']) + (ymin, ymax), = self._process_unit_info([("y", [ymin, ymax])], kwargs) + + p = mpatches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, **kwargs) + p.set_transform(self.get_yaxis_transform(which="grid")) + # For Rectangles and non-separable transforms, add_patch can be buggy + # and update the x limits even though it shouldn't do so for an + # yaxis_transformed patch, so undo that update. + ix = self.dataLim.intervalx.copy() + mx = self.dataLim.minposx + self.add_patch(p) + self.dataLim.intervalx = ix + self.dataLim.minposx = mx + p.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + self._request_autoscale_view("y") + return p + + @_docstring.dedent_interpd + def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs): + """ + Add a vertical span (rectangle) across the Axes. + + The rectangle spans from *xmin* to *xmax* horizontally, and, by + default, the whole y-axis vertically. The y-span can be set using + *ymin* (default: 0) and *ymax* (default: 1) which are in axis units; + e.g. ``ymin = 0.5`` always refers to the middle of the y-axis + regardless of the limits set by `~.Axes.set_ylim`. + + Parameters + ---------- + xmin : float + Lower x-coordinate of the span, in data units. + xmax : float + Upper x-coordinate of the span, in data units. + ymin : float, default: 0 + Lower y-coordinate of the span, in y-axis units (0-1). + ymax : float, default: 1 + Upper y-coordinate of the span, in y-axis units (0-1). + + Returns + ------- + `~matplotlib.patches.Rectangle` + Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax). + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + axhspan : Add a horizontal span across the Axes. + + Examples + -------- + Draw a vertical, green, translucent rectangle from x = 1.25 to + x = 1.55 that spans the yrange of the Axes. + + >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5) + + """ + # Strip units away. + self._check_no_units([ymin, ymax], ['ymin', 'ymax']) + (xmin, xmax), = self._process_unit_info([("x", [xmin, xmax])], kwargs) + + p = mpatches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, **kwargs) + p.set_transform(self.get_xaxis_transform(which="grid")) + # For Rectangles and non-separable transforms, add_patch can be buggy + # and update the y limits even though it shouldn't do so for an + # xaxis_transformed patch, so undo that update. + iy = self.dataLim.intervaly.copy() + my = self.dataLim.minposy + self.add_patch(p) + self.dataLim.intervaly = iy + self.dataLim.minposy = my + p.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + self._request_autoscale_view("x") + return p + + @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], + label_namer="y") + def hlines(self, y, xmin, xmax, colors=None, linestyles='solid', + label='', **kwargs): + """ + Plot horizontal lines at each *y* from *xmin* to *xmax*. + + Parameters + ---------- + y : float or array-like + y-indexes where to plot the lines. + + xmin, xmax : float or array-like + Respective beginning and end of each line. If scalars are + provided, all lines will have the same length. + + colors : :mpltype:`color` or list of color , default: :rc:`lines.color` + + linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid' + + label : str, default: '' + + Returns + ------- + `~matplotlib.collections.LineCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.LineCollection` properties. + + See Also + -------- + vlines : vertical lines + axhline : horizontal line across the Axes + """ + + # We do the conversion first since not all unitized data is uniform + xmin, xmax, y = self._process_unit_info( + [("x", xmin), ("x", xmax), ("y", y)], kwargs) + + if not np.iterable(y): + y = [y] + if not np.iterable(xmin): + xmin = [xmin] + if not np.iterable(xmax): + xmax = [xmax] + + # Create and combine masked_arrays from input + y, xmin, xmax = cbook._combine_masks(y, xmin, xmax) + y = np.ravel(y) + xmin = np.ravel(xmin) + xmax = np.ravel(xmax) + + masked_verts = np.ma.empty((len(y), 2, 2)) + masked_verts[:, 0, 0] = xmin + masked_verts[:, 0, 1] = y + masked_verts[:, 1, 0] = xmax + masked_verts[:, 1, 1] = y + + lines = mcoll.LineCollection(masked_verts, colors=colors, + linestyles=linestyles, label=label) + self.add_collection(lines, autolim=False) + lines._internal_update(kwargs) + + if len(y) > 0: + # Extreme values of xmin/xmax/y. Using masked_verts here handles + # the case of y being a masked *object* array (as can be generated + # e.g. by errorbar()), which would make nanmin/nanmax stumble. + updatex = True + updatey = True + if self.name == "rectilinear": + datalim = lines.get_datalim(self.transData) + t = lines.get_transform() + updatex, updatey = t.contains_branch_seperately(self.transData) + minx = np.nanmin(datalim.xmin) + maxx = np.nanmax(datalim.xmax) + miny = np.nanmin(datalim.ymin) + maxy = np.nanmax(datalim.ymax) + else: + minx = np.nanmin(masked_verts[..., 0]) + maxx = np.nanmax(masked_verts[..., 0]) + miny = np.nanmin(masked_verts[..., 1]) + maxy = np.nanmax(masked_verts[..., 1]) + + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners, updatex, updatey) + self._request_autoscale_view() + return lines + + @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], + label_namer="x") + def vlines(self, x, ymin, ymax, colors=None, linestyles='solid', + label='', **kwargs): + """ + Plot vertical lines at each *x* from *ymin* to *ymax*. + + Parameters + ---------- + x : float or array-like + x-indexes where to plot the lines. + + ymin, ymax : float or array-like + Respective beginning and end of each line. If scalars are + provided, all lines will have the same length. + + colors : :mpltype:`color` or list of color, default: :rc:`lines.color` + + linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid' + + label : str, default: '' + + Returns + ------- + `~matplotlib.collections.LineCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.LineCollection` properties. + + See Also + -------- + hlines : horizontal lines + axvline : vertical line across the Axes + """ + + # We do the conversion first since not all unitized data is uniform + x, ymin, ymax = self._process_unit_info( + [("x", x), ("y", ymin), ("y", ymax)], kwargs) + + if not np.iterable(x): + x = [x] + if not np.iterable(ymin): + ymin = [ymin] + if not np.iterable(ymax): + ymax = [ymax] + + # Create and combine masked_arrays from input + x, ymin, ymax = cbook._combine_masks(x, ymin, ymax) + x = np.ravel(x) + ymin = np.ravel(ymin) + ymax = np.ravel(ymax) + + masked_verts = np.ma.empty((len(x), 2, 2)) + masked_verts[:, 0, 0] = x + masked_verts[:, 0, 1] = ymin + masked_verts[:, 1, 0] = x + masked_verts[:, 1, 1] = ymax + + lines = mcoll.LineCollection(masked_verts, colors=colors, + linestyles=linestyles, label=label) + self.add_collection(lines, autolim=False) + lines._internal_update(kwargs) + + if len(x) > 0: + # Extreme values of x/ymin/ymax. Using masked_verts here handles + # the case of x being a masked *object* array (as can be generated + # e.g. by errorbar()), which would make nanmin/nanmax stumble. + updatex = True + updatey = True + if self.name == "rectilinear": + datalim = lines.get_datalim(self.transData) + t = lines.get_transform() + updatex, updatey = t.contains_branch_seperately(self.transData) + minx = np.nanmin(datalim.xmin) + maxx = np.nanmax(datalim.xmax) + miny = np.nanmin(datalim.ymin) + maxy = np.nanmax(datalim.ymax) + else: + minx = np.nanmin(masked_verts[..., 0]) + maxx = np.nanmax(masked_verts[..., 0]) + miny = np.nanmin(masked_verts[..., 1]) + maxy = np.nanmax(masked_verts[..., 1]) + + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners, updatex, updatey) + self._request_autoscale_view() + return lines + + @_preprocess_data(replace_names=["positions", "lineoffsets", + "linelengths", "linewidths", + "colors", "linestyles"]) + @_docstring.dedent_interpd + def eventplot(self, positions, orientation='horizontal', lineoffsets=1, + linelengths=1, linewidths=None, colors=None, alpha=None, + linestyles='solid', **kwargs): + """ + Plot identical parallel lines at the given positions. + + This type of plot is commonly used in neuroscience for representing + neural events, where it is usually called a spike raster, dot raster, + or raster plot. + + However, it is useful in any situation where you wish to show the + timing or position of multiple sets of discrete events, such as the + arrival times of people to a business on each day of the month or the + date of hurricanes each year of the last century. + + Parameters + ---------- + positions : array-like or list of array-like + A 1D array-like defines the positions of one sequence of events. + + Multiple groups of events may be passed as a list of array-likes. + Each group can be styled independently by passing lists of values + to *lineoffsets*, *linelengths*, *linewidths*, *colors* and + *linestyles*. + + Note that *positions* can be a 2D array, but in practice different + event groups usually have different counts so that one will use a + list of different-length arrays rather than a 2D array. + + orientation : {'horizontal', 'vertical'}, default: 'horizontal' + The direction of the event sequence: + + - 'horizontal': the events are arranged horizontally. + The indicator lines are vertical. + - 'vertical': the events are arranged vertically. + The indicator lines are horizontal. + + lineoffsets : float or array-like, default: 1 + The offset of the center of the lines from the origin, in the + direction orthogonal to *orientation*. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linelengths : float or array-like, default: 1 + The total height of the lines (i.e. the lines stretches from + ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``). + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linewidths : float or array-like, default: :rc:`lines.linewidth` + The line width(s) of the event lines, in points. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + colors : :mpltype:`color` or list of color, default: :rc:`lines.color` + The color(s) of the event lines. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + alpha : float or array-like, default: 1 + The alpha blending value(s), between 0 (transparent) and 1 + (opaque). + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linestyles : str or tuple or list of such values, default: 'solid' + Default is 'solid'. Valid strings are ['solid', 'dashed', + 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples + should be of the form:: + + (offset, onoffseq), + + where *onoffseq* is an even length tuple of on and off ink + in points. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Other keyword arguments are line collection properties. See + `.LineCollection` for a list of the valid properties. + + Returns + ------- + list of `.EventCollection` + The `.EventCollection` that were added. + + Notes + ----- + For *linelengths*, *linewidths*, *colors*, *alpha* and *linestyles*, if + only a single value is given, that value is applied to all lines. If an + array-like is given, it must have the same length as *positions*, and + each value will be applied to the corresponding row of the array. + + Examples + -------- + .. plot:: gallery/lines_bars_and_markers/eventplot_demo.py + """ + + lineoffsets, linelengths = self._process_unit_info( + [("y", lineoffsets), ("y", linelengths)], kwargs) + + # fix positions, noting that it can be a list of lists: + if not np.iterable(positions): + positions = [positions] + elif any(np.iterable(position) for position in positions): + positions = [np.asanyarray(position) for position in positions] + else: + positions = [np.asanyarray(positions)] + + poss = [] + for position in positions: + poss += self._process_unit_info([("x", position)], kwargs) + positions = poss + + # prevent 'singular' keys from **kwargs dict from overriding the effect + # of 'plural' keyword arguments (e.g. 'color' overriding 'colors') + colors = cbook._local_over_kwdict(colors, kwargs, 'color') + linewidths = cbook._local_over_kwdict(linewidths, kwargs, 'linewidth') + linestyles = cbook._local_over_kwdict(linestyles, kwargs, 'linestyle') + + if not np.iterable(lineoffsets): + lineoffsets = [lineoffsets] + if not np.iterable(linelengths): + linelengths = [linelengths] + if not np.iterable(linewidths): + linewidths = [linewidths] + if not np.iterable(colors): + colors = [colors] + if not np.iterable(alpha): + alpha = [alpha] + if hasattr(linestyles, 'lower') or not np.iterable(linestyles): + linestyles = [linestyles] + + lineoffsets = np.asarray(lineoffsets) + linelengths = np.asarray(linelengths) + linewidths = np.asarray(linewidths) + + if len(lineoffsets) == 0: + raise ValueError('lineoffsets cannot be empty') + if len(linelengths) == 0: + raise ValueError('linelengths cannot be empty') + if len(linestyles) == 0: + raise ValueError('linestyles cannot be empty') + if len(linewidths) == 0: + raise ValueError('linewidths cannot be empty') + if len(alpha) == 0: + raise ValueError('alpha cannot be empty') + if len(colors) == 0: + colors = [None] + try: + # Early conversion of the colors into RGBA values to take care + # of cases like colors='0.5' or colors='C1'. (Issue #8193) + colors = mcolors.to_rgba_array(colors) + except ValueError: + # Will fail if any element of *colors* is None. But as long + # as len(colors) == 1 or len(positions), the rest of the + # code should process *colors* properly. + pass + + if len(lineoffsets) == 1 and len(positions) != 1: + lineoffsets = np.tile(lineoffsets, len(positions)) + lineoffsets[0] = 0 + lineoffsets = np.cumsum(lineoffsets) + if len(linelengths) == 1: + linelengths = np.tile(linelengths, len(positions)) + if len(linewidths) == 1: + linewidths = np.tile(linewidths, len(positions)) + if len(colors) == 1: + colors = list(colors) * len(positions) + if len(alpha) == 1: + alpha = list(alpha) * len(positions) + if len(linestyles) == 1: + linestyles = [linestyles] * len(positions) + + if len(lineoffsets) != len(positions): + raise ValueError('lineoffsets and positions are unequal sized ' + 'sequences') + if len(linelengths) != len(positions): + raise ValueError('linelengths and positions are unequal sized ' + 'sequences') + if len(linewidths) != len(positions): + raise ValueError('linewidths and positions are unequal sized ' + 'sequences') + if len(colors) != len(positions): + raise ValueError('colors and positions are unequal sized ' + 'sequences') + if len(alpha) != len(positions): + raise ValueError('alpha and positions are unequal sized ' + 'sequences') + if len(linestyles) != len(positions): + raise ValueError('linestyles and positions are unequal sized ' + 'sequences') + + colls = [] + for position, lineoffset, linelength, linewidth, color, alpha_, \ + linestyle in \ + zip(positions, lineoffsets, linelengths, linewidths, + colors, alpha, linestyles): + coll = mcoll.EventCollection(position, + orientation=orientation, + lineoffset=lineoffset, + linelength=linelength, + linewidth=linewidth, + color=color, + alpha=alpha_, + linestyle=linestyle) + self.add_collection(coll, autolim=False) + coll._internal_update(kwargs) + colls.append(coll) + + if len(positions) > 0: + # try to get min/max + min_max = [(np.min(_p), np.max(_p)) for _p in positions + if len(_p) > 0] + # if we have any non-empty positions, try to autoscale + if len(min_max) > 0: + mins, maxes = zip(*min_max) + minpos = np.min(mins) + maxpos = np.max(maxes) + + minline = (lineoffsets - linelengths).min() + maxline = (lineoffsets + linelengths).max() + + if orientation == "vertical": + corners = (minline, minpos), (maxline, maxpos) + else: # "horizontal" + corners = (minpos, minline), (maxpos, maxline) + self.update_datalim(corners) + self._request_autoscale_view() + + return colls + + #### Basic plotting + + # Uses a custom implementation of data-kwarg handling in + # _process_plot_var_args. + @_docstring.dedent_interpd + def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs): + """ + Plot y versus x as lines and/or markers. + + Call signatures:: + + plot([x], y, [fmt], *, data=None, **kwargs) + plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + The coordinates of the points or line nodes are given by *x*, *y*. + + The optional parameter *fmt* is a convenient way for defining basic + formatting like color, marker and linestyle. It's a shortcut string + notation described in the *Notes* section below. + + >>> plot(x, y) # plot x and y using default line style and color + >>> plot(x, y, 'bo') # plot x and y using blue circle markers + >>> plot(y) # plot y using x as index array 0..N-1 + >>> plot(y, 'r+') # ditto, but with red plusses + + You can use `.Line2D` properties as keyword arguments for more + control on the appearance. Line properties and *fmt* can be mixed. + The following two calls yield identical results: + + >>> plot(x, y, 'go--', linewidth=2, markersize=12) + >>> plot(x, y, color='green', marker='o', linestyle='dashed', + ... linewidth=2, markersize=12) + + When conflicting with *fmt*, keyword arguments take precedence. + + + **Plotting labelled data** + + There's a convenient way for plotting objects with labelled data (i.e. + data that can be accessed by index ``obj['y']``). Instead of giving + the data in *x* and *y*, you can provide the object in the *data* + parameter and just give the labels for *x* and *y*:: + + >>> plot('xlabel', 'ylabel', data=obj) + + All indexable objects are supported. This could e.g. be a `dict`, a + `pandas.DataFrame` or a structured numpy array. + + + **Plotting multiple sets of data** + + There are various ways to plot multiple sets of data. + + - The most straight forward way is just to call `plot` multiple times. + Example: + + >>> plot(x1, y1, 'bo') + >>> plot(x2, y2, 'go') + + - If *x* and/or *y* are 2D arrays, a separate data set will be drawn + for every column. If both *x* and *y* are 2D, they must have the + same shape. If only one of them is 2D with shape (N, m) the other + must have length N and will be used for every data set m. + + Example: + + >>> x = [1, 2, 3] + >>> y = np.array([[1, 2], [3, 4], [5, 6]]) + >>> plot(x, y) + + is equivalent to: + + >>> for col in range(y.shape[1]): + ... plot(x, y[:, col]) + + - The third way is to specify multiple sets of *[x]*, *y*, *[fmt]* + groups:: + + >>> plot(x1, y1, 'g^', x2, y2, 'g-') + + In this case, any additional keyword argument applies to all + datasets. Also, this syntax cannot be combined with the *data* + parameter. + + By default, each line is assigned a different style specified by a + 'style cycle'. The *fmt* and line property parameters are only + necessary if you want explicit deviations from these defaults. + Alternatively, you can also change the style cycle using + :rc:`axes.prop_cycle`. + + + Parameters + ---------- + x, y : array-like or scalar + The horizontal / vertical coordinates of the data points. + *x* values are optional and default to ``range(len(y))``. + + Commonly, these parameters are 1D arrays. + + They can also be scalars, or two-dimensional (in that case, the + columns represent separate data sets). + + These arguments cannot be passed as keywords. + + fmt : str, optional + A format string, e.g. 'ro' for red circles. See the *Notes* + section for a full description of the format strings. + + Format strings are just an abbreviation for quickly setting + basic line properties. All of these and more can also be + controlled by keyword arguments. + + This argument cannot be passed as keyword. + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*. + + .. note:: + Technically there's a slight ambiguity in calls where the + second label is a valid *fmt*. ``plot('n', 'o', data=obj)`` + could be ``plt(x, y)`` or ``plt(y, fmt)``. In such cases, + the former interpretation is chosen, but a warning is issued. + You may suppress the warning by adding an empty format string + ``plot('n', 'o', '', data=obj)``. + + Returns + ------- + list of `.Line2D` + A list of lines representing the plotted data. + + Other Parameters + ---------------- + scalex, scaley : bool, default: True + These parameters determine if the view limits are adapted to the + data limits. The values are passed on to + `~.axes.Axes.autoscale_view`. + + **kwargs : `~matplotlib.lines.Line2D` properties, optional + *kwargs* are used to specify properties like a line label (for + auto legends), linewidth, antialiasing, marker face color. + Example:: + + >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2) + >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2') + + If you specify multiple lines with one plot call, the kwargs apply + to all those lines. In case the label object is iterable, each + element is used as labels for each set of data. + + Here is a list of available `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + scatter : XY scatter plot with markers of varying size and/or color ( + sometimes also called bubble chart). + + Notes + ----- + **Format Strings** + + A format string consists of a part for color, marker and line:: + + fmt = '[marker][line][color]' + + Each of them is optional. If not provided, the value from the style + cycle is used. Exception: If ``line`` is given, but no ``marker``, + the data will be a line without markers. + + Other combinations such as ``[color][marker][line]`` are also + supported, but note that their parsing may be ambiguous. + + **Markers** + + ============= =============================== + character description + ============= =============================== + ``'.'`` point marker + ``','`` pixel marker + ``'o'`` circle marker + ``'v'`` triangle_down marker + ``'^'`` triangle_up marker + ``'<'`` triangle_left marker + ``'>'`` triangle_right marker + ``'1'`` tri_down marker + ``'2'`` tri_up marker + ``'3'`` tri_left marker + ``'4'`` tri_right marker + ``'8'`` octagon marker + ``'s'`` square marker + ``'p'`` pentagon marker + ``'P'`` plus (filled) marker + ``'*'`` star marker + ``'h'`` hexagon1 marker + ``'H'`` hexagon2 marker + ``'+'`` plus marker + ``'x'`` x marker + ``'X'`` x (filled) marker + ``'D'`` diamond marker + ``'d'`` thin_diamond marker + ``'|'`` vline marker + ``'_'`` hline marker + ============= =============================== + + **Line Styles** + + ============= =============================== + character description + ============= =============================== + ``'-'`` solid line style + ``'--'`` dashed line style + ``'-.'`` dash-dot line style + ``':'`` dotted line style + ============= =============================== + + Example format strings:: + + 'b' # blue markers with default shape + 'or' # red circles + '-g' # green solid line + '--' # dashed line with default color + '^k:' # black triangle_up markers connected by a dotted line + + **Colors** + + The supported color abbreviations are the single letter codes + + ============= =============================== + character color + ============= =============================== + ``'b'`` blue + ``'g'`` green + ``'r'`` red + ``'c'`` cyan + ``'m'`` magenta + ``'y'`` yellow + ``'k'`` black + ``'w'`` white + ============= =============================== + + and the ``'CN'`` colors that index into the default property cycle. + + If the color is the only part of the format string, you can + additionally use any `matplotlib.colors` spec, e.g. full names + (``'green'``) or hex strings (``'#008000'``). + """ + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + lines = [*self._get_lines(self, *args, data=data, **kwargs)] + for line in lines: + self.add_line(line) + if scalex: + self._request_autoscale_view("x") + if scaley: + self._request_autoscale_view("y") + return lines + + @_api.deprecated("3.9", alternative="plot") + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + @_docstring.dedent_interpd + def plot_date(self, x, y, fmt='o', tz=None, xdate=True, ydate=False, + **kwargs): + """ + Plot coercing the axis to treat floats as dates. + + .. deprecated:: 3.9 + + This method exists for historic reasons and will be removed in version 3.11. + + - ``datetime``-like data should directly be plotted using + `~.Axes.plot`. + - If you need to plot plain numeric data as :ref:`date-format` or + need to set a timezone, call ``ax.xaxis.axis_date`` / + ``ax.yaxis.axis_date`` before `~.Axes.plot`. See + `.Axis.axis_date`. + + Similar to `.plot`, this plots *y* vs. *x* as lines or markers. + However, the axis labels are formatted as dates depending on *xdate* + and *ydate*. Note that `.plot` will work with `datetime` and + `numpy.datetime64` objects without resorting to this method. + + Parameters + ---------- + x, y : array-like + The coordinates of the data points. If *xdate* or *ydate* is + *True*, the respective values *x* or *y* are interpreted as + :ref:`Matplotlib dates `. + + fmt : str, optional + The plot format string. For details, see the corresponding + parameter in `.plot`. + + tz : timezone string or `datetime.tzinfo`, default: :rc:`timezone` + The time zone to use in labeling dates. + + xdate : bool, default: True + If *True*, the *x*-axis will be interpreted as Matplotlib dates. + + ydate : bool, default: False + If *True*, the *y*-axis will be interpreted as Matplotlib dates. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + matplotlib.dates : Helper functions on dates. + matplotlib.dates.date2num : Convert dates to num. + matplotlib.dates.num2date : Convert num to dates. + matplotlib.dates.drange : Create an equally spaced sequence of dates. + + Notes + ----- + If you are using custom date tickers and formatters, it may be + necessary to set the formatters/locators after the call to + `.plot_date`. `.plot_date` will set the default tick locator to + `.AutoDateLocator` (if the tick locator is not already set to a + `.DateLocator` instance) and the default tick formatter to + `.AutoDateFormatter` (if the tick formatter is not already set to a + `.DateFormatter` instance). + """ + if xdate: + self.xaxis_date(tz) + if ydate: + self.yaxis_date(tz) + return self.plot(x, y, fmt, **kwargs) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.dedent_interpd + def loglog(self, *args, **kwargs): + """ + Make a plot with log scaling on both the x- and y-axis. + + Call signatures:: + + loglog([x], y, [fmt], data=None, **kwargs) + loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + both the x-axis and the y-axis to log scaling. All the concepts and + parameters of plot can be used here as well. + + The additional parameters *base*, *subs* and *nonpositive* control the + x/y-axis properties. They are just forwarded to `.Axes.set_xscale` and + `.Axes.set_yscale`. To use different properties on the x-axis and the + y-axis, use e.g. + ``ax.set_xscale("log", base=10); ax.set_yscale("log", base=2)``. + + Parameters + ---------- + base : float, default: 10 + Base of the logarithm. + + subs : sequence, optional + The location of the minor ticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_xscale`/`.Axes.set_yscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values can be masked as invalid, or clipped to a very + small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + dx = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basex', 'subsx', 'nonposx']} + self.set_xscale('log', **dx) + dy = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basey', 'subsy', 'nonposy']} + self.set_yscale('log', **dy) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in {*dx, *dy}}) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.dedent_interpd + def semilogx(self, *args, **kwargs): + """ + Make a plot with log scaling on the x-axis. + + Call signatures:: + + semilogx([x], y, [fmt], data=None, **kwargs) + semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + the x-axis to log scaling. All the concepts and parameters of plot can + be used here as well. + + The additional parameters *base*, *subs*, and *nonpositive* control the + x-axis properties. They are just forwarded to `.Axes.set_xscale`. + + Parameters + ---------- + base : float, default: 10 + Base of the x logarithm. + + subs : array-like, optional + The location of the minor xticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_xscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values in x can be masked as invalid, or clipped to a + very small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + d = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basex', 'subsx', 'nonposx']} + self.set_xscale('log', **d) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in d}) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.dedent_interpd + def semilogy(self, *args, **kwargs): + """ + Make a plot with log scaling on the y-axis. + + Call signatures:: + + semilogy([x], y, [fmt], data=None, **kwargs) + semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + the y-axis to log scaling. All the concepts and parameters of plot can + be used here as well. + + The additional parameters *base*, *subs*, and *nonpositive* control the + y-axis properties. They are just forwarded to `.Axes.set_yscale`. + + Parameters + ---------- + base : float, default: 10 + Base of the y logarithm. + + subs : array-like, optional + The location of the minor yticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_yscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values in y can be masked as invalid, or clipped to a + very small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + d = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basey', 'subsy', 'nonposy']} + self.set_yscale('log', **d) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in d}) + + @_preprocess_data(replace_names=["x"], label_namer="x") + def acorr(self, x, **kwargs): + """ + Plot the autocorrelation of *x*. + + Parameters + ---------- + x : array-like + Not run through Matplotlib's unit conversion, so this should + be a unit-less array. + + detrend : callable, default: `.mlab.detrend_none` (no detrending) + A detrending function applied to *x*. It must have the + signature :: + + detrend(x: np.ndarray) -> np.ndarray + + normed : bool, default: True + If ``True``, input vectors are normalised to unit length. + + usevlines : bool, default: True + Determines the plot style. + + If ``True``, vertical lines are plotted from 0 to the acorr value + using `.Axes.vlines`. Additionally, a horizontal line is plotted + at y=0 using `.Axes.axhline`. + + If ``False``, markers are plotted at the acorr values using + `.Axes.plot`. + + maxlags : int, default: 10 + Number of lags to show. If ``None``, will return all + ``2 * len(x) - 1`` lags. + + Returns + ------- + lags : array (length ``2*maxlags+1``) + The lag vector. + c : array (length ``2*maxlags+1``) + The auto correlation vector. + line : `.LineCollection` or `.Line2D` + `.Artist` added to the Axes of the correlation: + + - `.LineCollection` if *usevlines* is True. + - `.Line2D` if *usevlines* is False. + b : `~matplotlib.lines.Line2D` or None + Horizontal line at 0 if *usevlines* is True + None *usevlines* is False. + + Other Parameters + ---------------- + linestyle : `~matplotlib.lines.Line2D` property, optional + The linestyle for plotting the data points. + Only used if *usevlines* is ``False``. + + marker : str, default: 'o' + The marker for plotting the data points. + Only used if *usevlines* is ``False``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed to `.Axes.vlines` and + `.Axes.axhline` if *usevlines* is ``True``; otherwise they are + passed to `.Axes.plot`. + + Notes + ----- + The cross correlation is performed with `numpy.correlate` with + ``mode = "full"``. + """ + return self.xcorr(x, x, **kwargs) + + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none, + usevlines=True, maxlags=10, **kwargs): + r""" + Plot the cross correlation between *x* and *y*. + + The correlation with lag k is defined as + :math:`\sum_n x[n+k] \cdot y^*[n]`, where :math:`y^*` is the complex + conjugate of :math:`y`. + + Parameters + ---------- + x, y : array-like of length n + Neither *x* nor *y* are run through Matplotlib's unit conversion, so + these should be unit-less arrays. + + detrend : callable, default: `.mlab.detrend_none` (no detrending) + A detrending function applied to *x* and *y*. It must have the + signature :: + + detrend(x: np.ndarray) -> np.ndarray + + normed : bool, default: True + If ``True``, input vectors are normalised to unit length. + + usevlines : bool, default: True + Determines the plot style. + + If ``True``, vertical lines are plotted from 0 to the xcorr value + using `.Axes.vlines`. Additionally, a horizontal line is plotted + at y=0 using `.Axes.axhline`. + + If ``False``, markers are plotted at the xcorr values using + `.Axes.plot`. + + maxlags : int, default: 10 + Number of lags to show. If None, will return all ``2 * len(x) - 1`` + lags. + + Returns + ------- + lags : array (length ``2*maxlags+1``) + The lag vector. + c : array (length ``2*maxlags+1``) + The auto correlation vector. + line : `.LineCollection` or `.Line2D` + `.Artist` added to the Axes of the correlation: + + - `.LineCollection` if *usevlines* is True. + - `.Line2D` if *usevlines* is False. + b : `~matplotlib.lines.Line2D` or None + Horizontal line at 0 if *usevlines* is True + None *usevlines* is False. + + Other Parameters + ---------------- + linestyle : `~matplotlib.lines.Line2D` property, optional + The linestyle for plotting the data points. + Only used if *usevlines* is ``False``. + + marker : str, default: 'o' + The marker for plotting the data points. + Only used if *usevlines* is ``False``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed to `.Axes.vlines` and + `.Axes.axhline` if *usevlines* is ``True``; otherwise they are + passed to `.Axes.plot`. + + Notes + ----- + The cross correlation is performed with `numpy.correlate` with + ``mode = "full"``. + """ + Nx = len(x) + if Nx != len(y): + raise ValueError('x and y must be equal length') + + x = detrend(np.asarray(x)) + y = detrend(np.asarray(y)) + + correls = np.correlate(x, y, mode="full") + + if normed: + correls = correls / np.sqrt(np.dot(x, x) * np.dot(y, y)) + + if maxlags is None: + maxlags = Nx - 1 + + if maxlags >= Nx or maxlags < 1: + raise ValueError('maxlags must be None or strictly ' + 'positive < %d' % Nx) + + lags = np.arange(-maxlags, maxlags + 1) + correls = correls[Nx - 1 - maxlags:Nx + maxlags] + + if usevlines: + a = self.vlines(lags, [0], correls, **kwargs) + # Make label empty so only vertical lines get a legend entry + kwargs.pop('label', '') + b = self.axhline(**kwargs) + else: + kwargs.setdefault('marker', 'o') + kwargs.setdefault('linestyle', 'None') + a, = self.plot(lags, correls, **kwargs) + b = None + return lags, correls, a, b + + #### Specialized plotting + + # @_preprocess_data() # let 'plot' do the unpacking.. + def step(self, x, y, *args, where='pre', data=None, **kwargs): + """ + Make a step plot. + + Call signatures:: + + step(x, y, [fmt], *, data=None, where='pre', **kwargs) + step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs) + + This is just a thin wrapper around `.plot` which changes some + formatting options. Most of the concepts and parameters of plot can be + used here as well. + + .. note:: + + This method uses a standard plot with a step drawstyle: The *x* + values are the reference positions and steps extend left/right/both + directions depending on *where*. + + For the common case where you know the values and edges of the + steps, use `~.Axes.stairs` instead. + + Parameters + ---------- + x : array-like + 1D sequence of x positions. It is assumed, but not checked, that + it is uniformly increasing. + + y : array-like + 1D sequence of y levels. + + fmt : str, optional + A format string, e.g. 'g' for a green line. See `.plot` for a more + detailed description. + + Note: While full format strings are accepted, it is recommended to + only specify the color. Line styles are currently ignored (use + the keyword argument *linestyle* instead). Markers are accepted + and plotted on the given positions, however, this is a rarely + needed feature for step plots. + + where : {'pre', 'post', 'mid'}, default: 'pre' + Define where the steps should be placed: + + - 'pre': The y value is continued constantly to the left from + every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the + value ``y[i]``. + - 'post': The y value is continued constantly to the right from + every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the + value ``y[i]``. + - 'mid': Steps occur half-way between the *x* positions. + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*. + + **kwargs + Additional parameters are the same as those for `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + _api.check_in_list(('pre', 'post', 'mid'), where=where) + kwargs['drawstyle'] = 'steps-' + where + return self.plot(x, y, *args, data=data, **kwargs) + + @staticmethod + def _convert_dx(dx, x0, xconv, convert): + """ + Small helper to do logic of width conversion flexibly. + + *dx* and *x0* have units, but *xconv* has already been converted + to unitless (and is an ndarray). This allows the *dx* to have units + that are different from *x0*, but are still accepted by the + ``__add__`` operator of *x0*. + """ + + # x should be an array... + assert type(xconv) is np.ndarray + + if xconv.size == 0: + # xconv has already been converted, but maybe empty... + return convert(dx) + + try: + # attempt to add the width to x0; this works for + # datetime+timedelta, for instance + + # only use the first element of x and x0. This saves + # having to be sure addition works across the whole + # vector. This is particularly an issue if + # x0 and dx are lists so x0 + dx just concatenates the lists. + # We can't just cast x0 and dx to numpy arrays because that + # removes the units from unit packages like `pint` that + # wrap numpy arrays. + try: + x0 = cbook._safe_first_finite(x0) + except (TypeError, IndexError, KeyError): + pass + + try: + x = cbook._safe_first_finite(xconv) + except (TypeError, IndexError, KeyError): + x = xconv + + delist = False + if not np.iterable(dx): + dx = [dx] + delist = True + dx = [convert(x0 + ddx) - x for ddx in dx] + if delist: + dx = dx[0] + except (ValueError, TypeError, AttributeError): + # if the above fails (for any reason) just fallback to what + # we do by default and convert dx by itself. + dx = convert(dx) + return dx + + @_preprocess_data() + @_docstring.dedent_interpd + def bar(self, x, height, width=0.8, bottom=None, *, align="center", + **kwargs): + r""" + Make a bar plot. + + The bars are positioned at *x* with the given *align*\ment. Their + dimensions are given by *height* and *width*. The vertical baseline + is *bottom* (default 0). + + Many parameters can take either a single value applying to all bars + or a sequence of values, one for each bar. + + Parameters + ---------- + x : float or array-like + The x coordinates of the bars. See also *align* for the + alignment of the bars to the coordinates. + + height : float or array-like + The height(s) of the bars. + + Note that if *bottom* has units (e.g. datetime), *height* should be in + units that are a difference from the value of *bottom* (e.g. timedelta). + + width : float or array-like, default: 0.8 + The width(s) of the bars. + + Note that if *x* has units (e.g. datetime), then *width* should be in + units that are a difference (e.g. timedelta) around the *x* values. + + bottom : float or array-like, default: 0 + The y coordinate(s) of the bottom side(s) of the bars. + + Note that if *bottom* has units, then the y-axis will get a Locator and + Formatter appropriate for the units (e.g. dates, or categorical). + + align : {'center', 'edge'}, default: 'center' + Alignment of the bars to the *x* coordinates: + + - 'center': Center the base on the *x* positions. + - 'edge': Align the left edges of the bars with the *x* positions. + + To align the bars on the right edge pass a negative *width* and + ``align='edge'``. + + Returns + ------- + `.BarContainer` + Container with all the bars and optionally errorbars. + + Other Parameters + ---------------- + color : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar faces. + + edgecolor : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar edges. + + linewidth : float or array-like, optional + Width of the bar edge(s). If 0, don't draw edges. + + tick_label : str or list of str, optional + The tick labels of the bars. + Default: None (Use default numeric labels.) + + label : str or list of str, optional + A single label is attached to the resulting `.BarContainer` as a + label for the whole dataset. + If a list is provided, it must be the same length as *x* and + labels the individual bars. Repeated labels are not de-duplicated + and will cause repeated label entries, so this is best used when + bars also differ in style (e.g., by passing a list to *color*.) + + xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional + If not *None*, add horizontal / vertical errorbars to the bar tips. + The values are +/- sizes relative to the data: + + - scalar: symmetric +/- values for all bars + - shape(N,): symmetric +/- values for each bar + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. (Default) + + See :doc:`/gallery/statistics/errorbar_features` for an example on + the usage of *xerr* and *yerr*. + + ecolor : :mpltype:`color` or list of :mpltype:`color`, default: 'black' + The line color of the errorbars. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + error_kw : dict, optional + Dictionary of keyword arguments to be passed to the + `~.Axes.errorbar` method. Values of *ecolor* or *capsize* defined + here take precedence over the independent keyword arguments. + + log : bool, default: False + If *True*, set the y-axis to be log scale. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + barh : Plot a horizontal bar plot. + + Notes + ----- + Stacked bars can be achieved by passing individual *bottom* values per + bar. See :doc:`/gallery/lines_bars_and_markers/bar_stacked`. + """ + kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch) + color = kwargs.pop('color', None) + if color is None: + color = self._get_patches_for_fill.get_next_color() + edgecolor = kwargs.pop('edgecolor', None) + linewidth = kwargs.pop('linewidth', None) + hatch = kwargs.pop('hatch', None) + + # Because xerr and yerr will be passed to errorbar, most dimension + # checking and processing will be left to the errorbar method. + xerr = kwargs.pop('xerr', None) + yerr = kwargs.pop('yerr', None) + error_kw = kwargs.pop('error_kw', None) + error_kw = {} if error_kw is None else error_kw.copy() + ezorder = error_kw.pop('zorder', None) + if ezorder is None: + ezorder = kwargs.get('zorder', None) + if ezorder is not None: + # If using the bar zorder, increment slightly to make sure + # errorbars are drawn on top of bars + ezorder += 0.01 + error_kw.setdefault('zorder', ezorder) + ecolor = kwargs.pop('ecolor', 'k') + capsize = kwargs.pop('capsize', mpl.rcParams["errorbar.capsize"]) + error_kw.setdefault('ecolor', ecolor) + error_kw.setdefault('capsize', capsize) + + # The keyword argument *orientation* is used by barh() to defer all + # logic and drawing to bar(). It is considered internal and is + # intentionally not mentioned in the docstring. + orientation = kwargs.pop('orientation', 'vertical') + _api.check_in_list(['vertical', 'horizontal'], orientation=orientation) + log = kwargs.pop('log', False) + label = kwargs.pop('label', '') + tick_labels = kwargs.pop('tick_label', None) + + y = bottom # Matches barh call signature. + if orientation == 'vertical': + if y is None: + y = 0 + else: # horizontal + if x is None: + x = 0 + + if orientation == 'vertical': + # It is possible for y (bottom) to contain unit information. + # However, it is also possible for y=0 for the default and height + # to contain unit information. This will prioritize the units of y. + self._process_unit_info( + [("x", x), ("y", y), ("y", height)], kwargs, convert=False) + if log: + self.set_yscale('log', nonpositive='clip') + else: # horizontal + # It is possible for x (left) to contain unit information. + # However, it is also possible for x=0 for the default and width + # to contain unit information. This will prioritize the units of x. + self._process_unit_info( + [("x", x), ("x", width), ("y", y)], kwargs, convert=False) + if log: + self.set_xscale('log', nonpositive='clip') + + # lets do some conversions now since some types cannot be + # subtracted uniformly + if self.xaxis is not None: + x0 = x + x = np.asarray(self.convert_xunits(x)) + width = self._convert_dx(width, x0, x, self.convert_xunits) + if xerr is not None: + xerr = self._convert_dx(xerr, x0, x, self.convert_xunits) + if self.yaxis is not None: + y0 = y + y = np.asarray(self.convert_yunits(y)) + height = self._convert_dx(height, y0, y, self.convert_yunits) + if yerr is not None: + yerr = self._convert_dx(yerr, y0, y, self.convert_yunits) + + x, height, width, y, linewidth, hatch = np.broadcast_arrays( + # Make args iterable too. + np.atleast_1d(x), height, width, y, linewidth, hatch) + + # Now that units have been converted, set the tick locations. + if orientation == 'vertical': + tick_label_axis = self.xaxis + tick_label_position = x + else: # horizontal + tick_label_axis = self.yaxis + tick_label_position = y + + if not isinstance(label, str) and np.iterable(label): + bar_container_label = '_nolegend_' + patch_labels = label + else: + bar_container_label = label + patch_labels = ['_nolegend_'] * len(x) + if len(patch_labels) != len(x): + raise ValueError(f'number of labels ({len(patch_labels)}) ' + f'does not match number of bars ({len(x)}).') + + linewidth = itertools.cycle(np.atleast_1d(linewidth)) + hatch = itertools.cycle(np.atleast_1d(hatch)) + color = itertools.chain(itertools.cycle(mcolors.to_rgba_array(color)), + # Fallback if color == "none". + itertools.repeat('none')) + if edgecolor is None: + edgecolor = itertools.repeat(None) + else: + edgecolor = itertools.chain( + itertools.cycle(mcolors.to_rgba_array(edgecolor)), + # Fallback if edgecolor == "none". + itertools.repeat('none')) + + # We will now resolve the alignment and really have + # left, bottom, width, height vectors + _api.check_in_list(['center', 'edge'], align=align) + if align == 'center': + if orientation == 'vertical': + try: + left = x - width / 2 + except TypeError as e: + raise TypeError(f'the dtypes of parameters x ({x.dtype}) ' + f'and width ({width.dtype}) ' + f'are incompatible') from e + bottom = y + else: # horizontal + try: + bottom = y - height / 2 + except TypeError as e: + raise TypeError(f'the dtypes of parameters y ({y.dtype}) ' + f'and height ({height.dtype}) ' + f'are incompatible') from e + left = x + else: # edge + left = x + bottom = y + + patches = [] + args = zip(left, bottom, width, height, color, edgecolor, linewidth, + hatch, patch_labels) + for l, b, w, h, c, e, lw, htch, lbl in args: + r = mpatches.Rectangle( + xy=(l, b), width=w, height=h, + facecolor=c, + edgecolor=e, + linewidth=lw, + label=lbl, + hatch=htch, + ) + r._internal_update(kwargs) + r.get_path()._interpolation_steps = 100 + if orientation == 'vertical': + r.sticky_edges.y.append(b) + else: # horizontal + r.sticky_edges.x.append(l) + self.add_patch(r) + patches.append(r) + + if xerr is not None or yerr is not None: + if orientation == 'vertical': + # using list comps rather than arrays to preserve unit info + ex = [l + 0.5 * w for l, w in zip(left, width)] + ey = [b + h for b, h in zip(bottom, height)] + + else: # horizontal + # using list comps rather than arrays to preserve unit info + ex = [l + w for l, w in zip(left, width)] + ey = [b + 0.5 * h for b, h in zip(bottom, height)] + + error_kw.setdefault("label", '_nolegend_') + + errorbar = self.errorbar(ex, ey, yerr=yerr, xerr=xerr, fmt='none', + **error_kw) + else: + errorbar = None + + self._request_autoscale_view() + + if orientation == 'vertical': + datavalues = height + else: # horizontal + datavalues = width + + bar_container = BarContainer(patches, errorbar, datavalues=datavalues, + orientation=orientation, + label=bar_container_label) + self.add_container(bar_container) + + if tick_labels is not None: + tick_labels = np.broadcast_to(tick_labels, len(patches)) + tick_label_axis.set_ticks(tick_label_position) + tick_label_axis.set_ticklabels(tick_labels) + + return bar_container + + # @_preprocess_data() # let 'bar' do the unpacking.. + @_docstring.dedent_interpd + def barh(self, y, width, height=0.8, left=None, *, align="center", + data=None, **kwargs): + r""" + Make a horizontal bar plot. + + The bars are positioned at *y* with the given *align*\ment. Their + dimensions are given by *width* and *height*. The horizontal baseline + is *left* (default 0). + + Many parameters can take either a single value applying to all bars + or a sequence of values, one for each bar. + + Parameters + ---------- + y : float or array-like + The y coordinates of the bars. See also *align* for the + alignment of the bars to the coordinates. + + width : float or array-like + The width(s) of the bars. + + Note that if *left* has units (e.g. datetime), *width* should be in + units that are a difference from the value of *left* (e.g. timedelta). + + height : float or array-like, default: 0.8 + The heights of the bars. + + Note that if *y* has units (e.g. datetime), then *height* should be in + units that are a difference (e.g. timedelta) around the *y* values. + + left : float or array-like, default: 0 + The x coordinates of the left side(s) of the bars. + + Note that if *left* has units, then the x-axis will get a Locator and + Formatter appropriate for the units (e.g. dates, or categorical). + + align : {'center', 'edge'}, default: 'center' + Alignment of the base to the *y* coordinates*: + + - 'center': Center the bars on the *y* positions. + - 'edge': Align the bottom edges of the bars with the *y* + positions. + + To align the bars on the top edge pass a negative *height* and + ``align='edge'``. + + Returns + ------- + `.BarContainer` + Container with all the bars and optionally errorbars. + + Other Parameters + ---------------- + color : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar faces. + + edgecolor : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar edges. + + linewidth : float or array-like, optional + Width of the bar edge(s). If 0, don't draw edges. + + tick_label : str or list of str, optional + The tick labels of the bars. + Default: None (Use default numeric labels.) + + label : str or list of str, optional + A single label is attached to the resulting `.BarContainer` as a + label for the whole dataset. + If a list is provided, it must be the same length as *y* and + labels the individual bars. Repeated labels are not de-duplicated + and will cause repeated label entries, so this is best used when + bars also differ in style (e.g., by passing a list to *color*.) + + xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional + If not *None*, add horizontal / vertical errorbars to the bar tips. + The values are +/- sizes relative to the data: + + - scalar: symmetric +/- values for all bars + - shape(N,): symmetric +/- values for each bar + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. (default) + + See :doc:`/gallery/statistics/errorbar_features` for an example on + the usage of *xerr* and *yerr*. + + ecolor : :mpltype:`color` or list of :mpltype:`color`, default: 'black' + The line color of the errorbars. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + error_kw : dict, optional + Dictionary of keyword arguments to be passed to the + `~.Axes.errorbar` method. Values of *ecolor* or *capsize* defined + here take precedence over the independent keyword arguments. + + log : bool, default: False + If ``True``, set the x-axis to be log scale. + + data : indexable object, optional + If given, all parameters also accept a string ``s``, which is + interpreted as ``data[s]`` (unless this raises an exception). + + **kwargs : `.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + bar : Plot a vertical bar plot. + + Notes + ----- + Stacked bars can be achieved by passing individual *left* values per + bar. See + :doc:`/gallery/lines_bars_and_markers/horizontal_barchart_distribution`. + """ + kwargs.setdefault('orientation', 'horizontal') + patches = self.bar(x=left, height=height, width=width, bottom=y, + align=align, data=data, **kwargs) + return patches + + def bar_label(self, container, labels=None, *, fmt="%g", label_type="edge", + padding=0, **kwargs): + """ + Label a bar plot. + + Adds labels to bars in the given `.BarContainer`. + You may need to adjust the axis limits to fit the labels. + + Parameters + ---------- + container : `.BarContainer` + Container with all the bars and optionally errorbars, likely + returned from `.bar` or `.barh`. + + labels : array-like, optional + A list of label texts, that should be displayed. If not given, the + label texts will be the data values formatted with *fmt*. + + fmt : str or callable, default: '%g' + An unnamed %-style or {}-style format string for the label or a + function to call with the value as the first argument. + When *fmt* is a string and can be interpreted in both formats, + %-style takes precedence over {}-style. + + .. versionadded:: 3.7 + Support for {}-style format string and callables. + + label_type : {'edge', 'center'}, default: 'edge' + The label type. Possible values: + + - 'edge': label placed at the end-point of the bar segment, and the + value displayed will be the position of that end-point. + - 'center': label placed in the center of the bar segment, and the + value displayed will be the length of that segment. + (useful for stacked bars, i.e., + :doc:`/gallery/lines_bars_and_markers/bar_label_demo`) + + padding : float, default: 0 + Distance of label from the end of the bar, in points. + + **kwargs + Any remaining keyword arguments are passed through to + `.Axes.annotate`. The alignment parameters ( + *horizontalalignment* / *ha*, *verticalalignment* / *va*) are + not supported because the labels are automatically aligned to + the bars. + + Returns + ------- + list of `.Annotation` + A list of `.Annotation` instances for the labels. + """ + for key in ['horizontalalignment', 'ha', 'verticalalignment', 'va']: + if key in kwargs: + raise ValueError( + f"Passing {key!r} to bar_label() is not supported.") + + a, b = self.yaxis.get_view_interval() + y_inverted = a > b + c, d = self.xaxis.get_view_interval() + x_inverted = c > d + + # want to know whether to put label on positive or negative direction + # cannot use np.sign here because it will return 0 if x == 0 + def sign(x): + return 1 if x >= 0 else -1 + + _api.check_in_list(['edge', 'center'], label_type=label_type) + + bars = container.patches + errorbar = container.errorbar + datavalues = container.datavalues + orientation = container.orientation + + if errorbar: + # check "ErrorbarContainer" for the definition of these elements + lines = errorbar.lines # attribute of "ErrorbarContainer" (tuple) + barlinecols = lines[2] # 0: data_line, 1: caplines, 2: barlinecols + barlinecol = barlinecols[0] # the "LineCollection" of error bars + errs = barlinecol.get_segments() + else: + errs = [] + + if labels is None: + labels = [] + + annotations = [] + + for bar, err, dat, lbl in itertools.zip_longest( + bars, errs, datavalues, labels + ): + (x0, y0), (x1, y1) = bar.get_bbox().get_points() + xc, yc = (x0 + x1) / 2, (y0 + y1) / 2 + + if orientation == "vertical": + extrema = max(y0, y1) if dat >= 0 else min(y0, y1) + length = abs(y0 - y1) + else: # horizontal + extrema = max(x0, x1) if dat >= 0 else min(x0, x1) + length = abs(x0 - x1) + + if err is None or np.size(err) == 0: + endpt = extrema + elif orientation == "vertical": + endpt = err[:, 1].max() if dat >= 0 else err[:, 1].min() + else: # horizontal + endpt = err[:, 0].max() if dat >= 0 else err[:, 0].min() + + if label_type == "center": + value = sign(dat) * length + else: # edge + value = extrema + + if label_type == "center": + xy = (0.5, 0.5) + kwargs["xycoords"] = ( + lambda r, b=bar: + mtransforms.Bbox.intersection( + b.get_window_extent(r), b.get_clip_box() + ) or mtransforms.Bbox.null() + ) + else: # edge + if orientation == "vertical": + xy = xc, endpt + else: # horizontal + xy = endpt, yc + + if orientation == "vertical": + y_direction = -1 if y_inverted else 1 + xytext = 0, y_direction * sign(dat) * padding + else: # horizontal + x_direction = -1 if x_inverted else 1 + xytext = x_direction * sign(dat) * padding, 0 + + if label_type == "center": + ha, va = "center", "center" + else: # edge + if orientation == "vertical": + ha = 'center' + if y_inverted: + va = 'top' if dat > 0 else 'bottom' # also handles NaN + else: + va = 'top' if dat < 0 else 'bottom' # also handles NaN + else: # horizontal + if x_inverted: + ha = 'right' if dat > 0 else 'left' # also handles NaN + else: + ha = 'right' if dat < 0 else 'left' # also handles NaN + va = 'center' + + if np.isnan(dat): + lbl = '' + + if lbl is None: + if isinstance(fmt, str): + lbl = cbook._auto_format_str(fmt, value) + elif callable(fmt): + lbl = fmt(value) + else: + raise TypeError("fmt must be a str or callable") + annotation = self.annotate(lbl, + xy, xytext, textcoords="offset points", + ha=ha, va=va, **kwargs) + annotations.append(annotation) + + return annotations + + @_preprocess_data() + @_docstring.dedent_interpd + def broken_barh(self, xranges, yrange, **kwargs): + """ + Plot a horizontal sequence of rectangles. + + A rectangle is drawn for each element of *xranges*. All rectangles + have the same vertical position and size defined by *yrange*. + + Parameters + ---------- + xranges : sequence of tuples (*xmin*, *xwidth*) + The x-positions and extents of the rectangles. For each tuple + (*xmin*, *xwidth*) a rectangle is drawn from *xmin* to *xmin* + + *xwidth*. + yrange : (*ymin*, *yheight*) + The y-position and extent for all the rectangles. + + Returns + ------- + `~.collections.PolyCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `.PolyCollection` properties + + Each *kwarg* can be either a single argument applying to all + rectangles, e.g.:: + + facecolors='black' + + or a sequence of arguments over which is cycled, e.g.:: + + facecolors=('black', 'blue') + + would create interleaving black and blue rectangles. + + Supported keywords: + + %(PolyCollection:kwdoc)s + """ + # process the unit information + xdata = cbook._safe_first_finite(xranges) if len(xranges) else None + ydata = cbook._safe_first_finite(yrange) if len(yrange) else None + self._process_unit_info( + [("x", xdata), ("y", ydata)], kwargs, convert=False) + + vertices = [] + y0, dy = yrange + y0, y1 = self.convert_yunits((y0, y0 + dy)) + for xr in xranges: # convert the absolute values, not the x and dx + try: + x0, dx = xr + except Exception: + raise ValueError( + "each range in xrange must be a sequence with two " + "elements (i.e. xrange must be an (N, 2) array)") from None + x0, x1 = self.convert_xunits((x0, x0 + dx)) + vertices.append([(x0, y0), (x0, y1), (x1, y1), (x1, y0)]) + + col = mcoll.PolyCollection(np.array(vertices), **kwargs) + self.add_collection(col, autolim=True) + self._request_autoscale_view() + + return col + + @_preprocess_data() + def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, + label=None, orientation='vertical'): + """ + Create a stem plot. + + A stem plot draws lines perpendicular to a baseline at each location + *locs* from the baseline to *heads*, and places a marker there. For + vertical stem plots (the default), the *locs* are *x* positions, and + the *heads* are *y* values. For horizontal stem plots, the *locs* are + *y* positions, and the *heads* are *x* values. + + Call signature:: + + stem([locs,] heads, linefmt=None, markerfmt=None, basefmt=None) + + The *locs*-positions are optional. *linefmt* may be provided as + positional, but all other formats must be provided as keyword + arguments. + + Parameters + ---------- + locs : array-like, default: (0, 1, ..., len(heads) - 1) + For vertical stem plots, the x-positions of the stems. + For horizontal stem plots, the y-positions of the stems. + + heads : array-like + For vertical stem plots, the y-values of the stem heads. + For horizontal stem plots, the x-values of the stem heads. + + linefmt : str, optional + A string defining the color and/or linestyle of the vertical lines: + + ========= ============= + Character Line Style + ========= ============= + ``'-'`` solid line + ``'--'`` dashed line + ``'-.'`` dash-dot line + ``':'`` dotted line + ========= ============= + + Default: 'C0-', i.e. solid line with the first color of the color + cycle. + + Note: Markers specified through this parameter (e.g. 'x') will be + silently ignored. Instead, markers should be specified using + *markerfmt*. + + markerfmt : str, optional + A string defining the color and/or shape of the markers at the stem + heads. If the marker is not given, use the marker 'o', i.e. filled + circles. If the color is not given, use the color from *linefmt*. + + basefmt : str, default: 'C3-' ('C2-' in classic mode) + A format string defining the properties of the baseline. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + The orientation of the stems. + + bottom : float, default: 0 + The y/x-position of the baseline (depending on *orientation*). + + label : str, optional + The label to use for the stems in legends. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + `.StemContainer` + The container may be treated like a tuple + (*markerline*, *stemlines*, *baseline*) + + Notes + ----- + .. seealso:: + The MATLAB function + `stem `_ + which inspired this method. + """ + if not 1 <= len(args) <= 3: + raise _api.nargs_error('stem', '1-3', len(args)) + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + if len(args) == 1: + heads, = args + locs = np.arange(len(heads)) + args = () + elif isinstance(args[1], str): + heads, *args = args + locs = np.arange(len(heads)) + else: + locs, heads, *args = args + + if orientation == 'vertical': + locs, heads = self._process_unit_info([("x", locs), ("y", heads)]) + else: # horizontal + heads, locs = self._process_unit_info([("x", heads), ("y", locs)]) + + # resolve line format + if linefmt is None: + linefmt = args[0] if len(args) > 0 else "C0-" + linestyle, linemarker, linecolor = _process_plot_format(linefmt) + + # resolve marker format + if markerfmt is None: + # if not given as kwarg, fall back to 'o' + markerfmt = "o" + if markerfmt == '': + markerfmt = ' ' # = empty line style; '' would resolve rcParams + markerstyle, markermarker, markercolor = \ + _process_plot_format(markerfmt) + if markermarker is None: + markermarker = 'o' + if markerstyle is None: + markerstyle = 'None' + if markercolor is None: + markercolor = linecolor + + # resolve baseline format + if basefmt is None: + basefmt = ("C2-" if mpl.rcParams["_internal.classic_mode"] else + "C3-") + basestyle, basemarker, basecolor = _process_plot_format(basefmt) + + # New behaviour in 3.1 is to use a LineCollection for the stemlines + if linestyle is None: + linestyle = mpl.rcParams['lines.linestyle'] + xlines = self.vlines if orientation == "vertical" else self.hlines + stemlines = xlines( + locs, bottom, heads, + colors=linecolor, linestyles=linestyle, label="_nolegend_") + + if orientation == 'horizontal': + marker_x = heads + marker_y = locs + baseline_x = [bottom, bottom] + baseline_y = [np.min(locs), np.max(locs)] + else: + marker_x = locs + marker_y = heads + baseline_x = [np.min(locs), np.max(locs)] + baseline_y = [bottom, bottom] + + markerline, = self.plot(marker_x, marker_y, + color=markercolor, linestyle=markerstyle, + marker=markermarker, label="_nolegend_") + + baseline, = self.plot(baseline_x, baseline_y, + color=basecolor, linestyle=basestyle, + marker=basemarker, label="_nolegend_") + + stem_container = StemContainer((markerline, stemlines, baseline), + label=label) + self.add_container(stem_container) + return stem_container + + @_preprocess_data(replace_names=["x", "explode", "labels", "colors"]) + def pie(self, x, explode=None, labels=None, colors=None, + autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, + startangle=0, radius=1, counterclock=True, + wedgeprops=None, textprops=None, center=(0, 0), + frame=False, rotatelabels=False, *, normalize=True, hatch=None): + """ + Plot a pie chart. + + Make a pie chart of array *x*. The fractional area of each wedge is + given by ``x/sum(x)``. + + The wedges are plotted counterclockwise, by default starting from the + x-axis. + + Parameters + ---------- + x : 1D array-like + The wedge sizes. + + explode : array-like, default: None + If not *None*, is a ``len(x)`` array which specifies the fraction + of the radius with which to offset each wedge. + + labels : list, default: None + A sequence of strings providing the labels for each wedge + + colors : :mpltype:`color` or list of :mpltype:`color`, default: None + A sequence of colors through which the pie chart will cycle. If + *None*, will use the colors in the currently active cycle. + + hatch : str or list, default: None + Hatching pattern applied to all pie wedges or sequence of patterns + through which the chart will cycle. For a list of valid patterns, + see :doc:`/gallery/shapes_and_collections/hatch_style_reference`. + + .. versionadded:: 3.7 + + autopct : None or str or callable, default: None + If not *None*, *autopct* is a string or function used to label the + wedges with their numeric value. The label will be placed inside + the wedge. If *autopct* is a format string, the label will be + ``fmt % pct``. If *autopct* is a function, then it will be called. + + pctdistance : float, default: 0.6 + The relative distance along the radius at which the text + generated by *autopct* is drawn. To draw the text outside the pie, + set *pctdistance* > 1. This parameter is ignored if *autopct* is + ``None``. + + labeldistance : float or None, default: 1.1 + The relative distance along the radius at which the labels are + drawn. To draw the labels inside the pie, set *labeldistance* < 1. + If set to ``None``, labels are not drawn but are still stored for + use in `.legend`. + + shadow : bool or dict, default: False + If bool, whether to draw a shadow beneath the pie. If dict, draw a shadow + passing the properties in the dict to `.Shadow`. + + .. versionadded:: 3.8 + *shadow* can be a dict. + + startangle : float, default: 0 degrees + The angle by which the start of the pie is rotated, + counterclockwise from the x-axis. + + radius : float, default: 1 + The radius of the pie. + + counterclock : bool, default: True + Specify fractions direction, clockwise or counterclockwise. + + wedgeprops : dict, default: None + Dict of arguments passed to each `.patches.Wedge` of the pie. + For example, ``wedgeprops = {'linewidth': 3}`` sets the width of + the wedge border lines equal to 3. By default, ``clip_on=False``. + When there is a conflict between these properties and other + keywords, properties passed to *wedgeprops* take precedence. + + textprops : dict, default: None + Dict of arguments to pass to the text objects. + + center : (float, float), default: (0, 0) + The coordinates of the center of the chart. + + frame : bool, default: False + Plot Axes frame with the chart if true. + + rotatelabels : bool, default: False + Rotate each label to the angle of the corresponding slice if true. + + normalize : bool, default: True + When *True*, always make a full pie by normalizing x so that + ``sum(x) == 1``. *False* makes a partial pie if ``sum(x) <= 1`` + and raises a `ValueError` for ``sum(x) > 1``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + patches : list + A sequence of `matplotlib.patches.Wedge` instances + + texts : list + A list of the label `.Text` instances. + + autotexts : list + A list of `.Text` instances for the numeric labels. This will only + be returned if the parameter *autopct* is not *None*. + + Notes + ----- + The pie chart will probably look best if the figure and Axes are + square, or the Axes aspect is equal. + This method sets the aspect ratio of the axis to "equal". + The Axes aspect ratio can be controlled with `.Axes.set_aspect`. + """ + self.set_aspect('equal') + # The use of float32 is "historical", but can't be changed without + # regenerating the test baselines. + x = np.asarray(x, np.float32) + if x.ndim > 1: + raise ValueError("x must be 1D") + + if np.any(x < 0): + raise ValueError("Wedge sizes 'x' must be non negative values") + + sx = x.sum() + + if normalize: + x = x / sx + elif sx > 1: + raise ValueError('Cannot plot an unnormalized pie with sum(x) > 1') + if labels is None: + labels = [''] * len(x) + if explode is None: + explode = [0] * len(x) + if len(x) != len(labels): + raise ValueError("'label' must be of length 'x'") + if len(x) != len(explode): + raise ValueError("'explode' must be of length 'x'") + if colors is None: + get_next_color = self._get_patches_for_fill.get_next_color + else: + color_cycle = itertools.cycle(colors) + + def get_next_color(): + return next(color_cycle) + + hatch_cycle = itertools.cycle(np.atleast_1d(hatch)) + + _api.check_isinstance(Real, radius=radius, startangle=startangle) + if radius <= 0: + raise ValueError(f'radius must be a positive number, not {radius}') + + # Starting theta1 is the start fraction of the circle + theta1 = startangle / 360 + + if wedgeprops is None: + wedgeprops = {} + if textprops is None: + textprops = {} + + texts = [] + slices = [] + autotexts = [] + + for frac, label, expl in zip(x, labels, explode): + x, y = center + theta2 = (theta1 + frac) if counterclock else (theta1 - frac) + thetam = 2 * np.pi * 0.5 * (theta1 + theta2) + x += expl * math.cos(thetam) + y += expl * math.sin(thetam) + + w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2), + 360. * max(theta1, theta2), + facecolor=get_next_color(), + hatch=next(hatch_cycle), + clip_on=False, + label=label) + w.set(**wedgeprops) + slices.append(w) + self.add_patch(w) + + if shadow: + # Make sure to add a shadow after the call to add_patch so the + # figure and transform props will be set. + shadow_dict = {'ox': -0.02, 'oy': -0.02, 'label': '_nolegend_'} + if isinstance(shadow, dict): + shadow_dict.update(shadow) + self.add_patch(mpatches.Shadow(w, **shadow_dict)) + + if labeldistance is not None: + xt = x + labeldistance * radius * math.cos(thetam) + yt = y + labeldistance * radius * math.sin(thetam) + label_alignment_h = 'left' if xt > 0 else 'right' + label_alignment_v = 'center' + label_rotation = 'horizontal' + if rotatelabels: + label_alignment_v = 'bottom' if yt > 0 else 'top' + label_rotation = (np.rad2deg(thetam) + + (0 if xt > 0 else 180)) + t = self.text(xt, yt, label, + clip_on=False, + horizontalalignment=label_alignment_h, + verticalalignment=label_alignment_v, + rotation=label_rotation, + size=mpl.rcParams['xtick.labelsize']) + t.set(**textprops) + texts.append(t) + + if autopct is not None: + xt = x + pctdistance * radius * math.cos(thetam) + yt = y + pctdistance * radius * math.sin(thetam) + if isinstance(autopct, str): + s = autopct % (100. * frac) + elif callable(autopct): + s = autopct(100. * frac) + else: + raise TypeError( + 'autopct must be callable or a format string') + if mpl._val_or_rc(textprops.get("usetex"), "text.usetex"): + # escape % (i.e. \%) if it is not already escaped + s = re.sub(r"([^\\])%", r"\1\\%", s) + t = self.text(xt, yt, s, + clip_on=False, + horizontalalignment='center', + verticalalignment='center') + t.set(**textprops) + autotexts.append(t) + + theta1 = theta2 + + if frame: + self._request_autoscale_view() + else: + self.set(frame_on=False, xticks=[], yticks=[], + xlim=(-1.25 + center[0], 1.25 + center[0]), + ylim=(-1.25 + center[1], 1.25 + center[1])) + + if autopct is None: + return slices, texts + else: + return slices, texts, autotexts + + @staticmethod + def _errorevery_to_mask(x, errorevery): + """ + Normalize `errorbar`'s *errorevery* to be a boolean mask for data *x*. + + This function is split out to be usable both by 2D and 3D errorbars. + """ + if isinstance(errorevery, Integral): + errorevery = (0, errorevery) + if isinstance(errorevery, tuple): + if (len(errorevery) == 2 and + isinstance(errorevery[0], Integral) and + isinstance(errorevery[1], Integral)): + errorevery = slice(errorevery[0], None, errorevery[1]) + else: + raise ValueError( + f'{errorevery=!r} is a not a tuple of two integers') + elif isinstance(errorevery, slice): + pass + elif not isinstance(errorevery, str) and np.iterable(errorevery): + try: + x[errorevery] # fancy indexing + except (ValueError, IndexError) as err: + raise ValueError( + f"{errorevery=!r} is iterable but not a valid NumPy fancy " + "index to match 'xerr'/'yerr'") from err + else: + raise ValueError(f"{errorevery=!r} is not a recognized value") + everymask = np.zeros(len(x), bool) + everymask[errorevery] = True + return everymask + + @_preprocess_data(replace_names=["x", "y", "xerr", "yerr"], + label_namer="y") + @_docstring.dedent_interpd + def errorbar(self, x, y, yerr=None, xerr=None, + fmt='', ecolor=None, elinewidth=None, capsize=None, + barsabove=False, lolims=False, uplims=False, + xlolims=False, xuplims=False, errorevery=1, capthick=None, + **kwargs): + """ + Plot y versus x as lines and/or markers with attached errorbars. + + *x*, *y* define the data locations, *xerr*, *yerr* define the errorbar + sizes. By default, this draws the data markers/lines as well as the + errorbars. Use fmt='none' to draw errorbars without any data markers. + + .. versionadded:: 3.7 + Caps and error lines are drawn in polar coordinates on polar plots. + + + Parameters + ---------- + x, y : float or array-like + The data positions. + + xerr, yerr : float or array-like, shape(N,) or shape(2, N), optional + The errorbar sizes: + + - scalar: Symmetric +/- values for all data points. + - shape(N,): Symmetric +/-values for each data point. + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. + + All values must be >= 0. + + See :doc:`/gallery/statistics/errorbar_features` + for an example on the usage of ``xerr`` and ``yerr``. + + fmt : str, default: '' + The format for the data points / data lines. See `.plot` for + details. + + Use 'none' (case-insensitive) to plot errorbars without any data + markers. + + ecolor : :mpltype:`color`, default: None + The color of the errorbar lines. If None, use the color of the + line connecting the markers. + + elinewidth : float, default: None + The linewidth of the errorbar lines. If None, the linewidth of + the current style is used. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + capthick : float, default: None + An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*). + This setting is a more sensible name for the property that + controls the thickness of the error bar cap in points. For + backwards compatibility, if *mew* or *markeredgewidth* are given, + then they will over-ride *capthick*. This may change in future + releases. + + barsabove : bool, default: False + If True, will plot the errorbars above the plot + symbols. Default is below. + + lolims, uplims, xlolims, xuplims : bool or array-like, default: False + These arguments can be used to indicate that a value gives only + upper/lower limits. In that case a caret symbol is used to + indicate this. *lims*-arguments may be scalars, or array-likes of + the same length as *xerr* and *yerr*. To use limits with inverted + axes, `~.Axes.set_xlim` or `~.Axes.set_ylim` must be called before + :meth:`errorbar`. Note the tricky parameter names: setting e.g. + *lolims* to True means that the y-value is a *lower* limit of the + True value, so, only an *upward*-pointing arrow will be drawn! + + errorevery : int or (int, int), default: 1 + draws error bars on a subset of the data. *errorevery* =N draws + error bars on the points (x[::N], y[::N]). + *errorevery* =(start, N) draws error bars on the points + (x[start::N], y[start::N]). e.g. errorevery=(6, 3) + adds error bars to the data at (x[6], x[9], x[12], x[15], ...). + Used to avoid overlapping error bars when two series share x-axis + values. + + Returns + ------- + `.ErrorbarContainer` + The container contains: + + - data_line : A `~matplotlib.lines.Line2D` instance of x, y plot markers + and/or line. + - caplines : A tuple of `~matplotlib.lines.Line2D` instances of the error + bar caps. + - barlinecols : A tuple of `.LineCollection` with the horizontal and + vertical error ranges. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + All other keyword arguments are passed on to the `~.Axes.plot` call + drawing the markers. For example, this code makes big red squares + with thick green edges:: + + x, y, yerr = rand(3, 10) + errorbar(x, y, yerr, marker='s', mfc='red', + mec='green', ms=20, mew=4) + + where *mfc*, *mec*, *ms* and *mew* are aliases for the longer + property names, *markerfacecolor*, *markeredgecolor*, *markersize* + and *markeredgewidth*. + + Valid kwargs for the marker properties are: + + - *dashes* + - *dash_capstyle* + - *dash_joinstyle* + - *drawstyle* + - *fillstyle* + - *linestyle* + - *marker* + - *markeredgecolor* + - *markeredgewidth* + - *markerfacecolor* + - *markerfacecoloralt* + - *markersize* + - *markevery* + - *solid_capstyle* + - *solid_joinstyle* + + Refer to the corresponding `.Line2D` property for more details: + + %(Line2D:kwdoc)s + """ + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + # Drop anything that comes in as None to use the default instead. + kwargs = {k: v for k, v in kwargs.items() if v is not None} + kwargs.setdefault('zorder', 2) + + # Casting to object arrays preserves units. + if not isinstance(x, np.ndarray): + x = np.asarray(x, dtype=object) + if not isinstance(y, np.ndarray): + y = np.asarray(y, dtype=object) + + def _upcast_err(err): + """ + Safely handle tuple of containers that carry units. + + This function covers the case where the input to the xerr/yerr is a + length 2 tuple of equal length ndarray-subclasses that carry the + unit information in the container. + + If we have a tuple of nested numpy array (subclasses), we defer + coercing the units to be consistent to the underlying unit + library (and implicitly the broadcasting). + + Otherwise, fallback to casting to an object array. + """ + + if ( + # make sure it is not a scalar + np.iterable(err) and + # and it is not empty + len(err) > 0 and + # and the first element is an array sub-class use + # safe_first_element because getitem is index-first not + # location first on pandas objects so err[0] almost always + # fails. + isinstance(cbook._safe_first_finite(err), np.ndarray) + ): + # Get the type of the first element + atype = type(cbook._safe_first_finite(err)) + # Promote the outer container to match the inner container + if atype is np.ndarray: + # Converts using np.asarray, because data cannot + # be directly passed to init of np.ndarray + return np.asarray(err, dtype=object) + # If atype is not np.ndarray, directly pass data to init. + # This works for types such as unyts and astropy units + return atype(err) + # Otherwise wrap it in an object array + return np.asarray(err, dtype=object) + + if xerr is not None and not isinstance(xerr, np.ndarray): + xerr = _upcast_err(xerr) + if yerr is not None and not isinstance(yerr, np.ndarray): + yerr = _upcast_err(yerr) + x, y = np.atleast_1d(x, y) # Make sure all the args are iterable. + if len(x) != len(y): + raise ValueError("'x' and 'y' must have the same size") + + everymask = self._errorevery_to_mask(x, errorevery) + + label = kwargs.pop("label", None) + kwargs['label'] = '_nolegend_' + + # Create the main line and determine overall kwargs for child artists. + # We avoid calling self.plot() directly, or self._get_lines(), because + # that would call self._process_unit_info again, and do other indirect + # data processing. + (data_line, base_style), = self._get_lines._plot_args( + self, (x, y) if fmt == '' else (x, y, fmt), kwargs, return_kwargs=True) + + # Do this after creating `data_line` to avoid modifying `base_style`. + if barsabove: + data_line.set_zorder(kwargs['zorder'] - .1) + else: + data_line.set_zorder(kwargs['zorder'] + .1) + + # Add line to plot, or throw it away and use it to determine kwargs. + if fmt.lower() != 'none': + self.add_line(data_line) + else: + data_line = None + # Remove alpha=0 color that _get_lines._plot_args returns for + # 'none' format, and replace it with user-specified color, if + # supplied. + base_style.pop('color') + if 'color' in kwargs: + base_style['color'] = kwargs.pop('color') + + if 'color' not in base_style: + base_style['color'] = 'C0' + if ecolor is None: + ecolor = base_style['color'] + + # Eject any line-specific information from format string, as it's not + # needed for bars or caps. + for key in ['marker', 'markersize', 'markerfacecolor', + 'markerfacecoloralt', + 'markeredgewidth', 'markeredgecolor', 'markevery', + 'linestyle', 'fillstyle', 'drawstyle', 'dash_capstyle', + 'dash_joinstyle', 'solid_capstyle', 'solid_joinstyle', + 'dashes']: + base_style.pop(key, None) + + # Make the style dict for the line collections (the bars). + eb_lines_style = {**base_style, 'color': ecolor} + + if elinewidth is not None: + eb_lines_style['linewidth'] = elinewidth + elif 'linewidth' in kwargs: + eb_lines_style['linewidth'] = kwargs['linewidth'] + + for key in ('transform', 'alpha', 'zorder', 'rasterized'): + if key in kwargs: + eb_lines_style[key] = kwargs[key] + + # Make the style dict for caps (the "hats"). + eb_cap_style = {**base_style, 'linestyle': 'none'} + if capsize is None: + capsize = mpl.rcParams["errorbar.capsize"] + if capsize > 0: + eb_cap_style['markersize'] = 2. * capsize + if capthick is not None: + eb_cap_style['markeredgewidth'] = capthick + + # For backwards-compat, allow explicit setting of + # 'markeredgewidth' to over-ride capthick. + for key in ('markeredgewidth', 'transform', 'alpha', + 'zorder', 'rasterized'): + if key in kwargs: + eb_cap_style[key] = kwargs[key] + eb_cap_style['color'] = ecolor + + barcols = [] + caplines = {'x': [], 'y': []} + + # Vectorized fancy-indexer. + def apply_mask(arrays, mask): + return [array[mask] for array in arrays] + + # dep: dependent dataset, indep: independent dataset + for (dep_axis, dep, err, lolims, uplims, indep, lines_func, + marker, lomarker, himarker) in [ + ("x", x, xerr, xlolims, xuplims, y, self.hlines, + "|", mlines.CARETRIGHTBASE, mlines.CARETLEFTBASE), + ("y", y, yerr, lolims, uplims, x, self.vlines, + "_", mlines.CARETUPBASE, mlines.CARETDOWNBASE), + ]: + if err is None: + continue + lolims = np.broadcast_to(lolims, len(dep)).astype(bool) + uplims = np.broadcast_to(uplims, len(dep)).astype(bool) + try: + np.broadcast_to(err, (2, len(dep))) + except ValueError: + raise ValueError( + f"'{dep_axis}err' (shape: {np.shape(err)}) must be a " + f"scalar or a 1D or (2, n) array-like whose shape matches " + f"'{dep_axis}' (shape: {np.shape(dep)})") from None + if err.dtype is np.dtype(object) and np.any(err == None): # noqa: E711 + raise ValueError( + f"'{dep_axis}err' must not contain None. " + "Use NaN if you want to skip a value.") + + res = np.zeros(err.shape, dtype=bool) # Default in case of nan + if np.any(np.less(err, -err, out=res, where=(err == err))): + # like err<0, but also works for timedelta and nan. + raise ValueError( + f"'{dep_axis}err' must not contain negative values") + # This is like + # elow, ehigh = np.broadcast_to(...) + # return dep - elow * ~lolims, dep + ehigh * ~uplims + # except that broadcast_to would strip units. + low, high = dep + np.vstack([-(1 - lolims), 1 - uplims]) * err + barcols.append(lines_func( + *apply_mask([indep, low, high], everymask), **eb_lines_style)) + if self.name == "polar" and dep_axis == "x": + for b in barcols: + for p in b.get_paths(): + p._interpolation_steps = 2 + # Normal errorbars for points without upper/lower limits. + nolims = ~(lolims | uplims) + if nolims.any() and capsize > 0: + indep_masked, lo_masked, hi_masked = apply_mask( + [indep, low, high], nolims & everymask) + for lh_masked in [lo_masked, hi_masked]: + # Since this has to work for x and y as dependent data, we + # first set both x and y to the independent variable and + # overwrite the respective dependent data in a second step. + line = mlines.Line2D(indep_masked, indep_masked, + marker=marker, **eb_cap_style) + line.set(**{f"{dep_axis}data": lh_masked}) + caplines[dep_axis].append(line) + for idx, (lims, hl) in enumerate([(lolims, high), (uplims, low)]): + if not lims.any(): + continue + hlmarker = ( + himarker + if self._axis_map[dep_axis].get_inverted() ^ idx + else lomarker) + x_masked, y_masked, hl_masked = apply_mask( + [x, y, hl], lims & everymask) + # As above, we set the dependent data in a second step. + line = mlines.Line2D(x_masked, y_masked, + marker=hlmarker, **eb_cap_style) + line.set(**{f"{dep_axis}data": hl_masked}) + caplines[dep_axis].append(line) + if capsize > 0: + caplines[dep_axis].append(mlines.Line2D( + x_masked, y_masked, marker=marker, **eb_cap_style)) + if self.name == 'polar': + for axis in caplines: + for l in caplines[axis]: + # Rotate caps to be perpendicular to the error bars + for theta, r in zip(l.get_xdata(), l.get_ydata()): + rotation = mtransforms.Affine2D().rotate(theta) + if axis == 'y': + rotation.rotate(-np.pi / 2) + ms = mmarkers.MarkerStyle(marker=marker, + transform=rotation) + self.add_line(mlines.Line2D([theta], [r], marker=ms, + **eb_cap_style)) + else: + for axis in caplines: + for l in caplines[axis]: + self.add_line(l) + + self._request_autoscale_view() + caplines = caplines['x'] + caplines['y'] + errorbar_container = ErrorbarContainer( + (data_line, tuple(caplines), tuple(barcols)), + has_xerr=(xerr is not None), has_yerr=(yerr is not None), + label=label) + self.containers.append(errorbar_container) + + return errorbar_container # (l0, caplines, barcols) + + @_preprocess_data() + @_api.rename_parameter("3.9", "labels", "tick_labels") + def boxplot(self, x, notch=None, sym=None, vert=None, whis=None, + positions=None, widths=None, patch_artist=None, + bootstrap=None, usermedians=None, conf_intervals=None, + meanline=None, showmeans=None, showcaps=None, + showbox=None, showfliers=None, boxprops=None, + tick_labels=None, flierprops=None, medianprops=None, + meanprops=None, capprops=None, whiskerprops=None, + manage_ticks=True, autorange=False, zorder=None, + capwidths=None, label=None): + """ + Draw a box and whisker plot. + + The box extends from the first quartile (Q1) to the third + quartile (Q3) of the data, with a line at the median. + The whiskers extend from the box to the farthest data point + lying within 1.5x the inter-quartile range (IQR) from the box. + Flier points are those past the end of the whiskers. + See https://en.wikipedia.org/wiki/Box_plot for reference. + + .. code-block:: none + + Q1-1.5IQR Q1 median Q3 Q3+1.5IQR + |-----:-----| + o |--------| : |--------| o o + |-----:-----| + flier <-----------> fliers + IQR + + + Parameters + ---------- + x : Array or a sequence of vectors. + The input data. If a 2D array, a boxplot is drawn for each column + in *x*. If a sequence of 1D arrays, a boxplot is drawn for each + array in *x*. + + notch : bool, default: :rc:`boxplot.notch` + Whether to draw a notched boxplot (`True`), or a rectangular + boxplot (`False`). The notches represent the confidence interval + (CI) around the median. The documentation for *bootstrap* + describes how the locations of the notches are computed by + default, but their locations may also be overridden by setting the + *conf_intervals* parameter. + + .. note:: + + In cases where the values of the CI are less than the + lower quartile or greater than the upper quartile, the + notches will extend beyond the box, giving it a + distinctive "flipped" appearance. This is expected + behavior and consistent with other statistical + visualization packages. + + sym : str, optional + The default symbol for flier points. An empty string ('') hides + the fliers. If `None`, then the fliers default to 'b+'. More + control is provided by the *flierprops* parameter. + + vert : bool, default: :rc:`boxplot.vertical` + If `True`, draws vertical boxes. + If `False`, draw horizontal boxes. + + whis : float or (float, float), default: 1.5 + The position of the whiskers. + + If a float, the lower whisker is at the lowest datum above + ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum + below ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and + third quartiles. The default value of ``whis = 1.5`` corresponds + to Tukey's original definition of boxplots. + + If a pair of floats, they indicate the percentiles at which to + draw the whiskers (e.g., (5, 95)). In particular, setting this to + (0, 100) results in whiskers covering the whole range of the data. + + In the edge case where ``Q1 == Q3``, *whis* is automatically set + to (0, 100) (cover the whole range of the data) if *autorange* is + True. + + Beyond the whiskers, data are considered outliers and are plotted + as individual points. + + bootstrap : int, optional + Specifies whether to bootstrap the confidence intervals + around the median for notched boxplots. If *bootstrap* is + None, no bootstrapping is performed, and notches are + calculated using a Gaussian-based asymptotic approximation + (see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and + Kendall and Stuart, 1967). Otherwise, bootstrap specifies + the number of times to bootstrap the median to determine its + 95% confidence intervals. Values between 1000 and 10000 are + recommended. + + usermedians : 1D array-like, optional + A 1D array-like of length ``len(x)``. Each entry that is not + `None` forces the value of the median for the corresponding + dataset. For entries that are `None`, the medians are computed + by Matplotlib as normal. + + conf_intervals : array-like, optional + A 2D array-like of shape ``(len(x), 2)``. Each entry that is not + None forces the location of the corresponding notch (which is + only drawn if *notch* is `True`). For entries that are `None`, + the notches are computed by the method specified by the other + parameters (e.g., *bootstrap*). + + positions : array-like, optional + The positions of the boxes. The ticks and limits are + automatically set to match the positions. Defaults to + ``range(1, N+1)`` where N is the number of boxes to be drawn. + + widths : float or array-like + The widths of the boxes. The default is 0.5, or ``0.15*(distance + between extreme positions)``, if that is smaller. + + patch_artist : bool, default: :rc:`boxplot.patchartist` + If `False` produces boxes with the Line2D artist. Otherwise, + boxes are drawn with Patch artists. + + tick_labels : list of str, optional + The tick labels of each boxplot. + Ticks are always placed at the box *positions*. If *tick_labels* is given, + the ticks are labelled accordingly. Otherwise, they keep their numeric + values. + + .. versionchanged:: 3.9 + Renamed from *labels*, which is deprecated since 3.9 + and will be removed in 3.11. + + manage_ticks : bool, default: True + If True, the tick locations and labels will be adjusted to match + the boxplot positions. + + autorange : bool, default: False + When `True` and the data are distributed such that the 25th and + 75th percentiles are equal, *whis* is set to (0, 100) such + that the whisker ends are at the minimum and maximum of the data. + + meanline : bool, default: :rc:`boxplot.meanline` + If `True` (and *showmeans* is `True`), will try to render the + mean as a line spanning the full width of the box according to + *meanprops* (see below). Not recommended if *shownotches* is also + True. Otherwise, means will be shown as points. + + zorder : float, default: ``Line2D.zorder = 2`` + The zorder of the boxplot. + + Returns + ------- + dict + A dictionary mapping each component of the boxplot to a list + of the `.Line2D` instances created. That dictionary has the + following keys (assuming vertical boxplots): + + - ``boxes``: the main body of the boxplot showing the + quartiles and the median's confidence intervals if + enabled. + + - ``medians``: horizontal lines at the median of each box. + + - ``whiskers``: the vertical lines extending to the most + extreme, non-outlier data points. + + - ``caps``: the horizontal lines at the ends of the + whiskers. + + - ``fliers``: points representing data that extend beyond + the whiskers (fliers). + + - ``means``: points or lines representing the means. + + Other Parameters + ---------------- + showcaps : bool, default: :rc:`boxplot.showcaps` + Show the caps on the ends of whiskers. + showbox : bool, default: :rc:`boxplot.showbox` + Show the central box. + showfliers : bool, default: :rc:`boxplot.showfliers` + Show the outliers beyond the caps. + showmeans : bool, default: :rc:`boxplot.showmeans` + Show the arithmetic means. + capprops : dict, default: None + The style of the caps. + capwidths : float or array, default: None + The widths of the caps. + boxprops : dict, default: None + The style of the box. + whiskerprops : dict, default: None + The style of the whiskers. + flierprops : dict, default: None + The style of the fliers. + medianprops : dict, default: None + The style of the median. + meanprops : dict, default: None + The style of the mean. + label : str or list of str, optional + Legend labels. Use a single string when all boxes have the same style and + you only want a single legend entry for them. Use a list of strings to + label all boxes individually. To be distinguishable, the boxes should be + styled individually, which is currently only possible by modifying the + returned artists, see e.g. :doc:`/gallery/statistics/boxplot_demo`. + + In the case of a single string, the legend entry will technically be + associated with the first box only. By default, the legend will show the + median line (``result["medians"]``); if *patch_artist* is True, the legend + will show the box `.Patch` artists (``result["boxes"]``) instead. + + .. versionadded:: 3.9 + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + See Also + -------- + .Axes.bxp : Draw a boxplot from pre-computed statistics. + violinplot : Draw an estimate of the probability density function. + """ + + # Missing arguments default to rcParams. + if whis is None: + whis = mpl.rcParams['boxplot.whiskers'] + if bootstrap is None: + bootstrap = mpl.rcParams['boxplot.bootstrap'] + + bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap, + labels=tick_labels, autorange=autorange) + if notch is None: + notch = mpl.rcParams['boxplot.notch'] + if vert is None: + vert = mpl.rcParams['boxplot.vertical'] + if patch_artist is None: + patch_artist = mpl.rcParams['boxplot.patchartist'] + if meanline is None: + meanline = mpl.rcParams['boxplot.meanline'] + if showmeans is None: + showmeans = mpl.rcParams['boxplot.showmeans'] + if showcaps is None: + showcaps = mpl.rcParams['boxplot.showcaps'] + if showbox is None: + showbox = mpl.rcParams['boxplot.showbox'] + if showfliers is None: + showfliers = mpl.rcParams['boxplot.showfliers'] + + if boxprops is None: + boxprops = {} + if whiskerprops is None: + whiskerprops = {} + if capprops is None: + capprops = {} + if medianprops is None: + medianprops = {} + if meanprops is None: + meanprops = {} + if flierprops is None: + flierprops = {} + + if patch_artist: + boxprops['linestyle'] = 'solid' # Not consistent with bxp. + if 'color' in boxprops: + boxprops['edgecolor'] = boxprops.pop('color') + + # if non-default sym value, put it into the flier dictionary + # the logic for providing the default symbol ('b+') now lives + # in bxp in the initial value of flierkw + # handle all of the *sym* related logic here so we only have to pass + # on the flierprops dict. + if sym is not None: + # no-flier case, which should really be done with + # 'showfliers=False' but none-the-less deal with it to keep back + # compatibility + if sym == '': + # blow away existing dict and make one for invisible markers + flierprops = dict(linestyle='none', marker='', color='none') + # turn the fliers off just to be safe + showfliers = False + # now process the symbol string + else: + # process the symbol string + # discarded linestyle + _, marker, color = _process_plot_format(sym) + # if we have a marker, use it + if marker is not None: + flierprops['marker'] = marker + # if we have a color, use it + if color is not None: + # assume that if color is passed in the user want + # filled symbol, if the users want more control use + # flierprops + flierprops['color'] = color + flierprops['markerfacecolor'] = color + flierprops['markeredgecolor'] = color + + # replace medians if necessary: + if usermedians is not None: + if (len(np.ravel(usermedians)) != len(bxpstats) or + np.shape(usermedians)[0] != len(bxpstats)): + raise ValueError( + "'usermedians' and 'x' have different lengths") + else: + # reassign medians as necessary + for stats, med in zip(bxpstats, usermedians): + if med is not None: + stats['med'] = med + + if conf_intervals is not None: + if len(conf_intervals) != len(bxpstats): + raise ValueError( + "'conf_intervals' and 'x' have different lengths") + else: + for stats, ci in zip(bxpstats, conf_intervals): + if ci is not None: + if len(ci) != 2: + raise ValueError('each confidence interval must ' + 'have two values') + else: + if ci[0] is not None: + stats['cilo'] = ci[0] + if ci[1] is not None: + stats['cihi'] = ci[1] + + artists = self.bxp(bxpstats, positions=positions, widths=widths, + vert=vert, patch_artist=patch_artist, + shownotches=notch, showmeans=showmeans, + showcaps=showcaps, showbox=showbox, + boxprops=boxprops, flierprops=flierprops, + medianprops=medianprops, meanprops=meanprops, + meanline=meanline, showfliers=showfliers, + capprops=capprops, whiskerprops=whiskerprops, + manage_ticks=manage_ticks, zorder=zorder, + capwidths=capwidths, label=label) + return artists + + def bxp(self, bxpstats, positions=None, widths=None, vert=True, + patch_artist=False, shownotches=False, showmeans=False, + showcaps=True, showbox=True, showfliers=True, + boxprops=None, whiskerprops=None, flierprops=None, + medianprops=None, capprops=None, meanprops=None, + meanline=False, manage_ticks=True, zorder=None, + capwidths=None, label=None): + """ + Draw a box and whisker plot from pre-computed statistics. + + The box extends from the first quartile *q1* to the third + quartile *q3* of the data, with a line at the median (*med*). + The whiskers extend from *whislow* to *whishi*. + Flier points are markers past the end of the whiskers. + See https://en.wikipedia.org/wiki/Box_plot for reference. + + .. code-block:: none + + whislow q1 med q3 whishi + |-----:-----| + o |--------| : |--------| o o + |-----:-----| + flier fliers + + .. note:: + This is a low-level drawing function for when you already + have the statistical parameters. If you want a boxplot based + on a dataset, use `~.Axes.boxplot` instead. + + Parameters + ---------- + bxpstats : list of dicts + A list of dictionaries containing stats for each boxplot. + Required keys are: + + - ``med``: Median (scalar). + - ``q1``, ``q3``: First & third quartiles (scalars). + - ``whislo``, ``whishi``: Lower & upper whisker positions (scalars). + + Optional keys are: + + - ``mean``: Mean (scalar). Needed if ``showmeans=True``. + - ``fliers``: Data beyond the whiskers (array-like). + Needed if ``showfliers=True``. + - ``cilo``, ``cihi``: Lower & upper confidence intervals + about the median. Needed if ``shownotches=True``. + - ``label``: Name of the dataset (str). If available, + this will be used a tick label for the boxplot + + positions : array-like, default: [1, 2, ..., n] + The positions of the boxes. The ticks and limits + are automatically set to match the positions. + + widths : float or array-like, default: None + The widths of the boxes. The default is + ``clip(0.15*(distance between extreme positions), 0.15, 0.5)``. + + capwidths : float or array-like, default: None + Either a scalar or a vector and sets the width of each cap. + The default is ``0.5*(width of the box)``, see *widths*. + + vert : bool, default: True + If `True` (default), makes the boxes vertical. + If `False`, makes horizontal boxes. + + patch_artist : bool, default: False + If `False` produces boxes with the `.Line2D` artist. + If `True` produces boxes with the `~matplotlib.patches.Patch` artist. + + shownotches, showmeans, showcaps, showbox, showfliers : bool + Whether to draw the CI notches, the mean value (both default to + False), the caps, the box, and the fliers (all three default to + True). + + boxprops, whiskerprops, capprops, flierprops, medianprops, meanprops :\ + dict, optional + Artist properties for the boxes, whiskers, caps, fliers, medians, and + means. + + meanline : bool, default: False + If `True` (and *showmeans* is `True`), will try to render the mean + as a line spanning the full width of the box according to + *meanprops*. Not recommended if *shownotches* is also True. + Otherwise, means will be shown as points. + + manage_ticks : bool, default: True + If True, the tick locations and labels will be adjusted to match the + boxplot positions. + + label : str or list of str, optional + Legend labels. Use a single string when all boxes have the same style and + you only want a single legend entry for them. Use a list of strings to + label all boxes individually. To be distinguishable, the boxes should be + styled individually, which is currently only possible by modifying the + returned artists, see e.g. :doc:`/gallery/statistics/boxplot_demo`. + + In the case of a single string, the legend entry will technically be + associated with the first box only. By default, the legend will show the + median line (``result["medians"]``); if *patch_artist* is True, the legend + will show the box `.Patch` artists (``result["boxes"]``) instead. + + .. versionadded:: 3.9 + + zorder : float, default: ``Line2D.zorder = 2`` + The zorder of the resulting boxplot. + + Returns + ------- + dict + A dictionary mapping each component of the boxplot to a list + of the `.Line2D` instances created. That dictionary has the + following keys (assuming vertical boxplots): + + - ``boxes``: main bodies of the boxplot showing the quartiles, and + the median's confidence intervals if enabled. + - ``medians``: horizontal lines at the median of each box. + - ``whiskers``: vertical lines up to the last non-outlier data. + - ``caps``: horizontal lines at the ends of the whiskers. + - ``fliers``: points representing data beyond the whiskers (fliers). + - ``means``: points or lines representing the means. + + See Also + -------- + boxplot : Draw a boxplot from data instead of pre-computed statistics. + """ + # Clamp median line to edge of box by default. + medianprops = { + "solid_capstyle": "butt", + "dash_capstyle": "butt", + **(medianprops or {}), + } + meanprops = { + "solid_capstyle": "butt", + "dash_capstyle": "butt", + **(meanprops or {}), + } + + # lists of artists to be output + whiskers = [] + caps = [] + boxes = [] + medians = [] + means = [] + fliers = [] + + # empty list of xticklabels + datalabels = [] + + # Use default zorder if none specified + if zorder is None: + zorder = mlines.Line2D.zorder + + zdelta = 0.1 + + def merge_kw_rc(subkey, explicit, zdelta=0, usemarker=True): + d = {k.split('.')[-1]: v for k, v in mpl.rcParams.items() + if k.startswith(f'boxplot.{subkey}props')} + d['zorder'] = zorder + zdelta + if not usemarker: + d['marker'] = '' + d.update(cbook.normalize_kwargs(explicit, mlines.Line2D)) + return d + + box_kw = { + 'linestyle': mpl.rcParams['boxplot.boxprops.linestyle'], + 'linewidth': mpl.rcParams['boxplot.boxprops.linewidth'], + 'edgecolor': mpl.rcParams['boxplot.boxprops.color'], + 'facecolor': ('white' if mpl.rcParams['_internal.classic_mode'] + else mpl.rcParams['patch.facecolor']), + 'zorder': zorder, + **cbook.normalize_kwargs(boxprops, mpatches.PathPatch) + } if patch_artist else merge_kw_rc('box', boxprops, usemarker=False) + whisker_kw = merge_kw_rc('whisker', whiskerprops, usemarker=False) + cap_kw = merge_kw_rc('cap', capprops, usemarker=False) + flier_kw = merge_kw_rc('flier', flierprops) + median_kw = merge_kw_rc('median', medianprops, zdelta, usemarker=False) + mean_kw = merge_kw_rc('mean', meanprops, zdelta) + removed_prop = 'marker' if meanline else 'linestyle' + # Only remove the property if it's not set explicitly as a parameter. + if meanprops is None or removed_prop not in meanprops: + mean_kw[removed_prop] = '' + + # vertical or horizontal plot? + maybe_swap = slice(None) if vert else slice(None, None, -1) + + def do_plot(xs, ys, **kwargs): + return self.plot(*[xs, ys][maybe_swap], **kwargs)[0] + + def do_patch(xs, ys, **kwargs): + path = mpath.Path._create_closed( + np.column_stack([xs, ys][maybe_swap])) + patch = mpatches.PathPatch(path, **kwargs) + self.add_artist(patch) + return patch + + # input validation + N = len(bxpstats) + datashape_message = ("List of boxplot statistics and `{0}` " + "values must have same the length") + # check position + if positions is None: + positions = list(range(1, N + 1)) + elif len(positions) != N: + raise ValueError(datashape_message.format("positions")) + + positions = np.array(positions) + if len(positions) > 0 and not all(isinstance(p, Real) for p in positions): + raise TypeError("positions should be an iterable of numbers") + + # width + if widths is None: + widths = [np.clip(0.15 * np.ptp(positions), 0.15, 0.5)] * N + elif np.isscalar(widths): + widths = [widths] * N + elif len(widths) != N: + raise ValueError(datashape_message.format("widths")) + + # capwidth + if capwidths is None: + capwidths = 0.5 * np.array(widths) + elif np.isscalar(capwidths): + capwidths = [capwidths] * N + elif len(capwidths) != N: + raise ValueError(datashape_message.format("capwidths")) + + for pos, width, stats, capwidth in zip(positions, widths, bxpstats, + capwidths): + # try to find a new label + datalabels.append(stats.get('label', pos)) + + # whisker coords + whis_x = [pos, pos] + whislo_y = [stats['q1'], stats['whislo']] + whishi_y = [stats['q3'], stats['whishi']] + # cap coords + cap_left = pos - capwidth * 0.5 + cap_right = pos + capwidth * 0.5 + cap_x = [cap_left, cap_right] + cap_lo = np.full(2, stats['whislo']) + cap_hi = np.full(2, stats['whishi']) + # box and median coords + box_left = pos - width * 0.5 + box_right = pos + width * 0.5 + med_y = [stats['med'], stats['med']] + # notched boxes + if shownotches: + notch_left = pos - width * 0.25 + notch_right = pos + width * 0.25 + box_x = [box_left, box_right, box_right, notch_right, + box_right, box_right, box_left, box_left, notch_left, + box_left, box_left] + box_y = [stats['q1'], stats['q1'], stats['cilo'], + stats['med'], stats['cihi'], stats['q3'], + stats['q3'], stats['cihi'], stats['med'], + stats['cilo'], stats['q1']] + med_x = [notch_left, notch_right] + # plain boxes + else: + box_x = [box_left, box_right, box_right, box_left, box_left] + box_y = [stats['q1'], stats['q1'], stats['q3'], stats['q3'], + stats['q1']] + med_x = [box_left, box_right] + + # maybe draw the box + if showbox: + do_box = do_patch if patch_artist else do_plot + boxes.append(do_box(box_x, box_y, **box_kw)) + median_kw.setdefault('label', '_nolegend_') + # draw the whiskers + whisker_kw.setdefault('label', '_nolegend_') + whiskers.append(do_plot(whis_x, whislo_y, **whisker_kw)) + whiskers.append(do_plot(whis_x, whishi_y, **whisker_kw)) + # maybe draw the caps + if showcaps: + cap_kw.setdefault('label', '_nolegend_') + caps.append(do_plot(cap_x, cap_lo, **cap_kw)) + caps.append(do_plot(cap_x, cap_hi, **cap_kw)) + # draw the medians + medians.append(do_plot(med_x, med_y, **median_kw)) + # maybe draw the means + if showmeans: + if meanline: + means.append(do_plot( + [box_left, box_right], [stats['mean'], stats['mean']], + **mean_kw + )) + else: + means.append(do_plot([pos], [stats['mean']], **mean_kw)) + # maybe draw the fliers + if showfliers: + flier_kw.setdefault('label', '_nolegend_') + flier_x = np.full(len(stats['fliers']), pos, dtype=np.float64) + flier_y = stats['fliers'] + fliers.append(do_plot(flier_x, flier_y, **flier_kw)) + + # Set legend labels + if label: + box_or_med = boxes if showbox and patch_artist else medians + if cbook.is_scalar_or_string(label): + # assign the label only to the first box + box_or_med[0].set_label(label) + else: # label is a sequence + if len(box_or_med) != len(label): + raise ValueError(datashape_message.format("label")) + for artist, lbl in zip(box_or_med, label): + artist.set_label(lbl) + + if manage_ticks: + axis_name = "x" if vert else "y" + interval = getattr(self.dataLim, f"interval{axis_name}") + axis = self._axis_map[axis_name] + positions = axis.convert_units(positions) + # The 0.5 additional padding ensures reasonable-looking boxes + # even when drawing a single box. We set the sticky edge to + # prevent margins expansion, in order to match old behavior (back + # when separate calls to boxplot() would completely reset the axis + # limits regardless of what was drawn before). The sticky edges + # are attached to the median lines, as they are always present. + interval[:] = (min(interval[0], min(positions) - .5), + max(interval[1], max(positions) + .5)) + for median, position in zip(medians, positions): + getattr(median.sticky_edges, axis_name).extend( + [position - .5, position + .5]) + # Modified from Axis.set_ticks and Axis.set_ticklabels. + locator = axis.get_major_locator() + if not isinstance(axis.get_major_locator(), + mticker.FixedLocator): + locator = mticker.FixedLocator([]) + axis.set_major_locator(locator) + locator.locs = np.array([*locator.locs, *positions]) + formatter = axis.get_major_formatter() + if not isinstance(axis.get_major_formatter(), + mticker.FixedFormatter): + formatter = mticker.FixedFormatter([]) + axis.set_major_formatter(formatter) + formatter.seq = [*formatter.seq, *datalabels] + + self._request_autoscale_view() + + return dict(whiskers=whiskers, caps=caps, boxes=boxes, + medians=medians, fliers=fliers, means=means) + + @staticmethod + def _parse_scatter_color_args(c, edgecolors, kwargs, xsize, + get_next_color_func): + """ + Helper function to process color related arguments of `.Axes.scatter`. + + Argument precedence for facecolors: + + - c (if not None) + - kwargs['facecolor'] + - kwargs['facecolors'] + - kwargs['color'] (==kwcolor) + - 'b' if in classic mode else the result of ``get_next_color_func()`` + + Argument precedence for edgecolors: + + - kwargs['edgecolor'] + - edgecolors (is an explicit kw argument in scatter()) + - kwargs['color'] (==kwcolor) + - 'face' if not in classic mode else None + + Parameters + ---------- + c : :mpltype:`color` or array-like or list of :mpltype:`color` or None + See argument description of `.Axes.scatter`. + edgecolors : :mpltype:`color` or sequence of color or {'face', 'none'} or None + See argument description of `.Axes.scatter`. + kwargs : dict + Additional kwargs. If these keys exist, we pop and process them: + 'facecolors', 'facecolor', 'edgecolor', 'color' + Note: The dict is modified by this function. + xsize : int + The size of the x and y arrays passed to `.Axes.scatter`. + get_next_color_func : callable + A callable that returns a color. This color is used as facecolor + if no other color is provided. + + Note, that this is a function rather than a fixed color value to + support conditional evaluation of the next color. As of the + current implementation obtaining the next color from the + property cycle advances the cycle. This must only happen if we + actually use the color, which will only be decided within this + method. + + Returns + ------- + c + The input *c* if it was not *None*, else a color derived from the + other inputs or defaults. + colors : array(N, 4) or None + The facecolors as RGBA values, or *None* if a colormap is used. + edgecolors + The edgecolor. + + """ + facecolors = kwargs.pop('facecolors', None) + facecolors = kwargs.pop('facecolor', facecolors) + edgecolors = kwargs.pop('edgecolor', edgecolors) + + kwcolor = kwargs.pop('color', None) + + if kwcolor is not None and c is not None: + raise ValueError("Supply a 'c' argument or a 'color'" + " kwarg but not both; they differ but" + " their functionalities overlap.") + + if kwcolor is not None: + try: + mcolors.to_rgba_array(kwcolor) + except ValueError as err: + raise ValueError( + "'color' kwarg must be a color or sequence of color " + "specs. For a sequence of values to be color-mapped, use " + "the 'c' argument instead.") from err + if edgecolors is None: + edgecolors = kwcolor + if facecolors is None: + facecolors = kwcolor + + if edgecolors is None and not mpl.rcParams['_internal.classic_mode']: + edgecolors = mpl.rcParams['scatter.edgecolors'] + + c_was_none = c is None + if c is None: + c = (facecolors if facecolors is not None + else "b" if mpl.rcParams['_internal.classic_mode'] + else get_next_color_func()) + c_is_string_or_strings = ( + isinstance(c, str) + or (np.iterable(c) and len(c) > 0 + and isinstance(cbook._safe_first_finite(c), str))) + + def invalid_shape_exception(csize, xsize): + return ValueError( + f"'c' argument has {csize} elements, which is inconsistent " + f"with 'x' and 'y' with size {xsize}.") + + c_is_mapped = False # Unless proven otherwise below. + valid_shape = True # Unless proven otherwise below. + if not c_was_none and kwcolor is None and not c_is_string_or_strings: + try: # First, does 'c' look suitable for value-mapping? + c = np.asanyarray(c, dtype=float) + except ValueError: + pass # Failed to convert to float array; must be color specs. + else: + # handle the documented special case of a 2D array with 1 + # row which as RGB(A) to broadcast. + if c.shape == (1, 4) or c.shape == (1, 3): + c_is_mapped = False + if c.size != xsize: + valid_shape = False + # If c can be either mapped values or an RGB(A) color, prefer + # the former if shapes match, the latter otherwise. + elif c.size == xsize: + c = c.ravel() + c_is_mapped = True + else: # Wrong size; it must not be intended for mapping. + if c.shape in ((3,), (4,)): + _api.warn_external( + "*c* argument looks like a single numeric RGB or " + "RGBA sequence, which should be avoided as value-" + "mapping will have precedence in case its length " + "matches with *x* & *y*. Please use the *color* " + "keyword-argument or provide a 2D array " + "with a single row if you intend to specify " + "the same RGB or RGBA value for all points.") + valid_shape = False + if not c_is_mapped: + try: # Is 'c' acceptable as PathCollection facecolors? + colors = mcolors.to_rgba_array(c) + except (TypeError, ValueError) as err: + if "RGBA values should be within 0-1 range" in str(err): + raise + else: + if not valid_shape: + raise invalid_shape_exception(c.size, xsize) from err + # Both the mapping *and* the RGBA conversion failed: pretty + # severe failure => one may appreciate a verbose feedback. + raise ValueError( + f"'c' argument must be a color, a sequence of colors, " + f"or a sequence of numbers, not {c!r}") from err + else: + if len(colors) not in (0, 1, xsize): + # NB: remember that a single color is also acceptable. + # Besides *colors* will be an empty array if c == 'none'. + raise invalid_shape_exception(len(colors), xsize) + else: + colors = None # use cmap, norm after collection is created + return c, colors, edgecolors + + @_preprocess_data(replace_names=["x", "y", "s", "linewidths", + "edgecolors", "c", "facecolor", + "facecolors", "color"], + label_namer="y") + @_docstring.interpd + def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, + vmin=None, vmax=None, alpha=None, linewidths=None, *, + edgecolors=None, plotnonfinite=False, **kwargs): + """ + A scatter plot of *y* vs. *x* with varying marker size and/or color. + + Parameters + ---------- + x, y : float or array-like, shape (n, ) + The data positions. + + s : float or array-like, shape (n, ), optional + The marker size in points**2 (typographic points are 1/72 in.). + Default is ``rcParams['lines.markersize'] ** 2``. + + The linewidth and edgecolor can visually interact with the marker + size, and can lead to artifacts if the marker size is smaller than + the linewidth. + + If the linewidth is greater than 0 and the edgecolor is anything + but *'none'*, then the effective size of the marker will be + increased by half the linewidth because the stroke will be centered + on the edge of the shape. + + To eliminate the marker edge either set *linewidth=0* or + *edgecolor='none'*. + + c : array-like or list of :mpltype:`color` or :mpltype:`color`, optional + The marker colors. Possible values: + + - A scalar or sequence of n numbers to be mapped to colors using + *cmap* and *norm*. + - A 2D array in which the rows are RGB or RGBA. + - A sequence of colors of length n. + - A single color format string. + + Note that *c* should not be a single numeric RGB or RGBA sequence + because that is indistinguishable from an array of values to be + colormapped. If you want to specify the same RGB or RGBA value for + all points, use a 2D array with a single row. Otherwise, + value-matching will have precedence in case of a size matching with + *x* and *y*. + + If you wish to specify a single color for all points + prefer the *color* keyword argument. + + Defaults to `None`. In that case the marker color is determined + by the value of *color*, *facecolor* or *facecolors*. In case + those are not specified or `None`, the marker color is determined + by the next color of the ``Axes``' current "shape and fill" color + cycle. This cycle defaults to :rc:`axes.prop_cycle`. + + marker : `~.markers.MarkerStyle`, default: :rc:`scatter.marker` + The marker style. *marker* can be either an instance of the class + or the text shorthand for a particular marker. + See :mod:`matplotlib.markers` for more information about marker + styles. + + %(cmap_doc)s + + This parameter is ignored if *c* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *c* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *c* is RGB(A). + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + linewidths : float or array-like, default: :rc:`lines.linewidth` + The linewidth of the marker edges. Note: The default *edgecolors* + is 'face'. You may want to change this as well. + + edgecolors : {'face', 'none', *None*} or :mpltype:`color` or list of \ +:mpltype:`color`, default: :rc:`scatter.edgecolors` + The edge color of the marker. Possible values: + + - 'face': The edge color will always be the same as the face color. + - 'none': No patch boundary will be drawn. + - A color or sequence of colors. + + For non-filled markers, *edgecolors* is ignored. Instead, the color + is determined like with 'face', i.e. from *c*, *colors*, or + *facecolors*. + + plotnonfinite : bool, default: False + Whether to plot points with nonfinite *c* (i.e. ``inf``, ``-inf`` + or ``nan``). If ``True`` the points are drawn with the *bad* + colormap color (see `.Colormap.set_bad`). + + Returns + ------- + `~matplotlib.collections.PathCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.Collection` properties + + See Also + -------- + plot : To plot scatter plots when markers are identical in size and + color. + + Notes + ----- + * The `.plot` function will be faster for scatterplots where markers + don't vary in size or color. + + * Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in which + case all masks will be combined and only unmasked points will be + plotted. + + * Fundamentally, scatter works with 1D arrays; *x*, *y*, *s*, and *c* + may be input as N-D arrays, but within scatter they will be + flattened. The exception is *c*, which will be flattened only if its + size matches the size of *x* and *y*. + + """ + # add edgecolors and linewidths to kwargs so they + # can be processed by normailze_kwargs + if edgecolors is not None: + kwargs.update({'edgecolors': edgecolors}) + if linewidths is not None: + kwargs.update({'linewidths': linewidths}) + + kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) + # re direct linewidth and edgecolor so it can be + # further processed by the rest of the function + linewidths = kwargs.pop('linewidth', None) + edgecolors = kwargs.pop('edgecolor', None) + # Process **kwargs to handle aliases, conflicts with explicit kwargs: + x, y = self._process_unit_info([("x", x), ("y", y)], kwargs) + # np.ma.ravel yields an ndarray, not a masked array, + # unless its argument is a masked array. + x = np.ma.ravel(x) + y = np.ma.ravel(y) + if x.size != y.size: + raise ValueError("x and y must be the same size") + + if s is None: + s = (20 if mpl.rcParams['_internal.classic_mode'] else + mpl.rcParams['lines.markersize'] ** 2.0) + s = np.ma.ravel(s) + if (len(s) not in (1, x.size) or + (not np.issubdtype(s.dtype, np.floating) and + not np.issubdtype(s.dtype, np.integer))): + raise ValueError( + "s must be a scalar, " + "or float array-like with the same size as x and y") + + # get the original edgecolor the user passed before we normalize + orig_edgecolor = edgecolors + if edgecolors is None: + orig_edgecolor = kwargs.get('edgecolor', None) + c, colors, edgecolors = \ + self._parse_scatter_color_args( + c, edgecolors, kwargs, x.size, + get_next_color_func=self._get_patches_for_fill.get_next_color) + + if plotnonfinite and colors is None: + c = np.ma.masked_invalid(c) + x, y, s, edgecolors, linewidths = \ + cbook._combine_masks(x, y, s, edgecolors, linewidths) + else: + x, y, s, c, colors, edgecolors, linewidths = \ + cbook._combine_masks( + x, y, s, c, colors, edgecolors, linewidths) + # Unmask edgecolors if it was actually a single RGB or RGBA. + if (x.size in (3, 4) + and np.ma.is_masked(edgecolors) + and not np.ma.is_masked(orig_edgecolor)): + edgecolors = edgecolors.data + + scales = s # Renamed for readability below. + + # load default marker from rcParams + if marker is None: + marker = mpl.rcParams['scatter.marker'] + + if isinstance(marker, mmarkers.MarkerStyle): + marker_obj = marker + else: + marker_obj = mmarkers.MarkerStyle(marker) + + path = marker_obj.get_path().transformed( + marker_obj.get_transform()) + if not marker_obj.is_filled(): + if orig_edgecolor is not None: + _api.warn_external( + f"You passed a edgecolor/edgecolors ({orig_edgecolor!r}) " + f"for an unfilled marker ({marker!r}). Matplotlib is " + "ignoring the edgecolor in favor of the facecolor. This " + "behavior may change in the future." + ) + # We need to handle markers that cannot be filled (like + # '+' and 'x') differently than markers that can be + # filled, but have their fillstyle set to 'none'. This is + # to get: + # + # - respecting the fillestyle if set + # - maintaining back-compatibility for querying the facecolor of + # the un-fillable markers. + # + # While not an ideal situation, but is better than the + # alternatives. + if marker_obj.get_fillstyle() == 'none': + # promote the facecolor to be the edgecolor + edgecolors = colors + # set the facecolor to 'none' (at the last chance) because + # we cannot fill a path if the facecolor is non-null + # (which is defendable at the renderer level). + colors = 'none' + else: + # if we are not nulling the face color we can do this + # simpler + edgecolors = 'face' + + if linewidths is None: + linewidths = mpl.rcParams['lines.linewidth'] + elif np.iterable(linewidths): + linewidths = [ + lw if lw is not None else mpl.rcParams['lines.linewidth'] + for lw in linewidths] + + offsets = np.ma.column_stack([x, y]) + + collection = mcoll.PathCollection( + (path,), scales, + facecolors=colors, + edgecolors=edgecolors, + linewidths=linewidths, + offsets=offsets, + offset_transform=kwargs.pop('transform', self.transData), + alpha=alpha, + ) + collection.set_transform(mtransforms.IdentityTransform()) + if colors is None: + collection.set_array(c) + collection.set_cmap(cmap) + collection.set_norm(norm) + collection._scale_norm(norm, vmin, vmax) + else: + extra_kwargs = { + 'cmap': cmap, 'norm': norm, 'vmin': vmin, 'vmax': vmax + } + extra_keys = [k for k, v in extra_kwargs.items() if v is not None] + if any(extra_keys): + keys_str = ", ".join(f"'{k}'" for k in extra_keys) + _api.warn_external( + "No data for colormapping provided via 'c'. " + f"Parameters {keys_str} will be ignored") + collection._internal_update(kwargs) + + # Classic mode only: + # ensure there are margins to allow for the + # finite size of the symbols. In v2.x, margins + # are present by default, so we disable this + # scatter-specific override. + if mpl.rcParams['_internal.classic_mode']: + if self._xmargin < 0.05 and x.size > 0: + self.set_xmargin(0.05) + if self._ymargin < 0.05 and x.size > 0: + self.set_ymargin(0.05) + + self.add_collection(collection) + self._request_autoscale_view() + + return collection + + @_preprocess_data(replace_names=["x", "y", "C"], label_namer="y") + @_docstring.dedent_interpd + def hexbin(self, x, y, C=None, gridsize=100, bins=None, + xscale='linear', yscale='linear', extent=None, + cmap=None, norm=None, vmin=None, vmax=None, + alpha=None, linewidths=None, edgecolors='face', + reduce_C_function=np.mean, mincnt=None, marginals=False, + **kwargs): + """ + Make a 2D hexagonal binning plot of points *x*, *y*. + + If *C* is *None*, the value of the hexagon is determined by the number + of points in the hexagon. Otherwise, *C* specifies values at the + coordinate (x[i], y[i]). For each hexagon, these values are reduced + using *reduce_C_function*. + + Parameters + ---------- + x, y : array-like + The data positions. *x* and *y* must be of the same length. + + C : array-like, optional + If given, these values are accumulated in the bins. Otherwise, + every point has a value of 1. Must be of the same length as *x* + and *y*. + + gridsize : int or (int, int), default: 100 + If a single int, the number of hexagons in the *x*-direction. + The number of hexagons in the *y*-direction is chosen such that + the hexagons are approximately regular. + + Alternatively, if a tuple (*nx*, *ny*), the number of hexagons + in the *x*-direction and the *y*-direction. In the + *y*-direction, counting is done along vertically aligned + hexagons, not along the zig-zag chains of hexagons; see the + following illustration. + + .. plot:: + + import numpy + import matplotlib.pyplot as plt + + np.random.seed(19680801) + n= 300 + x = np.random.standard_normal(n) + y = np.random.standard_normal(n) + + fig, ax = plt.subplots(figsize=(4, 4)) + h = ax.hexbin(x, y, gridsize=(5, 3)) + hx, hy = h.get_offsets().T + ax.plot(hx[24::3], hy[24::3], 'ro-') + ax.plot(hx[-3:], hy[-3:], 'ro-') + ax.set_title('gridsize=(5, 3)') + ax.axis('off') + + To get approximately regular hexagons, choose + :math:`n_x = \\sqrt{3}\\,n_y`. + + bins : 'log' or int or sequence, default: None + Discretization of the hexagon values. + + - If *None*, no binning is applied; the color of each hexagon + directly corresponds to its count value. + - If 'log', use a logarithmic scale for the colormap. + Internally, :math:`log_{10}(i+1)` is used to determine the + hexagon color. This is equivalent to ``norm=LogNorm()``. + - If an integer, divide the counts in the specified number + of bins, and color the hexagons accordingly. + - If a sequence of values, the values of the lower bound of + the bins to be used. + + xscale : {'linear', 'log'}, default: 'linear' + Use a linear or log10 scale on the horizontal axis. + + yscale : {'linear', 'log'}, default: 'linear' + Use a linear or log10 scale on the vertical axis. + + mincnt : int >= 0, default: *None* + If not *None*, only display cells with at least *mincnt* + number of points in the cell. + + marginals : bool, default: *False* + If marginals is *True*, plot the marginal density as + colormapped rectangles along the bottom of the x-axis and + left of the y-axis. + + extent : 4-tuple of float, default: *None* + The limits of the bins (xmin, xmax, ymin, ymax). + The default assigns the limits based on + *gridsize*, *x*, *y*, *xscale* and *yscale*. + + If *xscale* or *yscale* is set to 'log', the limits are + expected to be the exponent for a power of 10. E.g. for + x-limits of 1 and 50 in 'linear' scale and y-limits + of 10 and 1000 in 'log' scale, enter (1, 50, 1, 3). + + Returns + ------- + `~matplotlib.collections.PolyCollection` + A `.PolyCollection` defining the hexagonal bins. + + - `.PolyCollection.get_offsets` contains a Mx2 array containing + the x, y positions of the M hexagon centers. + - `.PolyCollection.get_array` contains the values of the M + hexagons. + + If *marginals* is *True*, horizontal + bar and vertical bar (both PolyCollections) will be attached + to the return collection as attributes *hbar* and *vbar*. + + Other Parameters + ---------------- + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + alpha : float between 0 and 1, optional + The alpha blending value, between 0 (transparent) and 1 (opaque). + + linewidths : float, default: *None* + If *None*, defaults to :rc:`patch.linewidth`. + + edgecolors : {'face', 'none', *None*} or color, default: 'face' + The color of the hexagon edges. Possible values are: + + - 'face': Draw the edges in the same color as the fill color. + - 'none': No edges are drawn. This can sometimes lead to unsightly + unpainted pixels between the hexagons. + - *None*: Draw outlines in the default color. + - An explicit color. + + reduce_C_function : callable, default: `numpy.mean` + The function to aggregate *C* within the bins. It is ignored if + *C* is not given. This must have the signature:: + + def reduce_C_function(C: array) -> float + + Commonly used functions are: + + - `numpy.mean`: average of the points + - `numpy.sum`: integral of the point values + - `numpy.amax`: value taken from the largest point + + By default will only reduce cells with at least 1 point because some + reduction functions (such as `numpy.amax`) will error/warn with empty + input. Changing *mincnt* will adjust the cutoff, and if set to 0 will + pass empty input to the reduction function. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `~matplotlib.collections.PolyCollection` properties + All other keyword arguments are passed on to `.PolyCollection`: + + %(PolyCollection:kwdoc)s + + See Also + -------- + hist2d : 2D histogram rectangular bins + """ + self._process_unit_info([("x", x), ("y", y)], kwargs, convert=False) + + x, y, C = cbook.delete_masked_points(x, y, C) + + # Set the size of the hexagon grid + if np.iterable(gridsize): + nx, ny = gridsize + else: + nx = gridsize + ny = int(nx / math.sqrt(3)) + # Count the number of data in each hexagon + x = np.asarray(x, float) + y = np.asarray(y, float) + + # Will be log()'d if necessary, and then rescaled. + tx = x + ty = y + + if xscale == 'log': + if np.any(x <= 0.0): + raise ValueError( + "x contains non-positive values, so cannot be log-scaled") + tx = np.log10(tx) + if yscale == 'log': + if np.any(y <= 0.0): + raise ValueError( + "y contains non-positive values, so cannot be log-scaled") + ty = np.log10(ty) + if extent is not None: + xmin, xmax, ymin, ymax = extent + if xmin > xmax: + raise ValueError("In extent, xmax must be greater than xmin") + if ymin > ymax: + raise ValueError("In extent, ymax must be greater than ymin") + else: + xmin, xmax = (tx.min(), tx.max()) if len(x) else (0, 1) + ymin, ymax = (ty.min(), ty.max()) if len(y) else (0, 1) + + # to avoid issues with singular data, expand the min/max pairs + xmin, xmax = mtransforms.nonsingular(xmin, xmax, expander=0.1) + ymin, ymax = mtransforms.nonsingular(ymin, ymax, expander=0.1) + + nx1 = nx + 1 + ny1 = ny + 1 + nx2 = nx + ny2 = ny + n = nx1 * ny1 + nx2 * ny2 + + # In the x-direction, the hexagons exactly cover the region from + # xmin to xmax. Need some padding to avoid roundoff errors. + padding = 1.e-9 * (xmax - xmin) + xmin -= padding + xmax += padding + sx = (xmax - xmin) / nx + sy = (ymax - ymin) / ny + # Positions in hexagon index coordinates. + ix = (tx - xmin) / sx + iy = (ty - ymin) / sy + ix1 = np.round(ix).astype(int) + iy1 = np.round(iy).astype(int) + ix2 = np.floor(ix).astype(int) + iy2 = np.floor(iy).astype(int) + # flat indices, plus one so that out-of-range points go to position 0. + i1 = np.where((0 <= ix1) & (ix1 < nx1) & (0 <= iy1) & (iy1 < ny1), + ix1 * ny1 + iy1 + 1, 0) + i2 = np.where((0 <= ix2) & (ix2 < nx2) & (0 <= iy2) & (iy2 < ny2), + ix2 * ny2 + iy2 + 1, 0) + + d1 = (ix - ix1) ** 2 + 3.0 * (iy - iy1) ** 2 + d2 = (ix - ix2 - 0.5) ** 2 + 3.0 * (iy - iy2 - 0.5) ** 2 + bdist = (d1 < d2) + + if C is None: # [1:] drops out-of-range points. + counts1 = np.bincount(i1[bdist], minlength=1 + nx1 * ny1)[1:] + counts2 = np.bincount(i2[~bdist], minlength=1 + nx2 * ny2)[1:] + accum = np.concatenate([counts1, counts2]).astype(float) + if mincnt is not None: + accum[accum < mincnt] = np.nan + C = np.ones(len(x)) + else: + # store the C values in a list per hexagon index + Cs_at_i1 = [[] for _ in range(1 + nx1 * ny1)] + Cs_at_i2 = [[] for _ in range(1 + nx2 * ny2)] + for i in range(len(x)): + if bdist[i]: + Cs_at_i1[i1[i]].append(C[i]) + else: + Cs_at_i2[i2[i]].append(C[i]) + if mincnt is None: + mincnt = 1 + accum = np.array( + [reduce_C_function(acc) if len(acc) >= mincnt else np.nan + for Cs_at_i in [Cs_at_i1, Cs_at_i2] + for acc in Cs_at_i[1:]], # [1:] drops out-of-range points. + float) + + good_idxs = ~np.isnan(accum) + + offsets = np.zeros((n, 2), float) + offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1) + offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1) + offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2) + offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5 + offsets[:, 0] *= sx + offsets[:, 1] *= sy + offsets[:, 0] += xmin + offsets[:, 1] += ymin + # remove accumulation bins with no data + offsets = offsets[good_idxs, :] + accum = accum[good_idxs] + + polygon = [sx, sy / 3] * np.array( + [[.5, -.5], [.5, .5], [0., 1.], [-.5, .5], [-.5, -.5], [0., -1.]]) + + if linewidths is None: + linewidths = [mpl.rcParams['patch.linewidth']] + + if xscale == 'log' or yscale == 'log': + polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1) + if xscale == 'log': + polygons[:, :, 0] = 10.0 ** polygons[:, :, 0] + xmin = 10.0 ** xmin + xmax = 10.0 ** xmax + self.set_xscale(xscale) + if yscale == 'log': + polygons[:, :, 1] = 10.0 ** polygons[:, :, 1] + ymin = 10.0 ** ymin + ymax = 10.0 ** ymax + self.set_yscale(yscale) + collection = mcoll.PolyCollection( + polygons, + edgecolors=edgecolors, + linewidths=linewidths, + ) + else: + collection = mcoll.PolyCollection( + [polygon], + edgecolors=edgecolors, + linewidths=linewidths, + offsets=offsets, + offset_transform=mtransforms.AffineDeltaTransform( + self.transData), + ) + + # Set normalizer if bins is 'log' + if cbook._str_equal(bins, 'log'): + if norm is not None: + _api.warn_external("Only one of 'bins' and 'norm' arguments " + f"can be supplied, ignoring {bins=}") + else: + norm = mcolors.LogNorm(vmin=vmin, vmax=vmax) + vmin = vmax = None + bins = None + + # autoscale the norm with current accum values if it hasn't been set + if norm is not None: + if norm.vmin is None and norm.vmax is None: + norm.autoscale(accum) + + if bins is not None: + if not np.iterable(bins): + minimum, maximum = min(accum), max(accum) + bins -= 1 # one less edge than bins + bins = minimum + (maximum - minimum) * np.arange(bins) / bins + bins = np.sort(bins) + accum = bins.searchsorted(accum) + + collection.set_array(accum) + collection.set_cmap(cmap) + collection.set_norm(norm) + collection.set_alpha(alpha) + collection._internal_update(kwargs) + collection._scale_norm(norm, vmin, vmax) + + corners = ((xmin, ymin), (xmax, ymax)) + self.update_datalim(corners) + self._request_autoscale_view(tight=True) + + # add the collection last + self.add_collection(collection, autolim=False) + if not marginals: + return collection + + # Process marginals + bars = [] + for zname, z, zmin, zmax, zscale, nbins in [ + ("x", x, xmin, xmax, xscale, nx), + ("y", y, ymin, ymax, yscale, 2 * ny), + ]: + + if zscale == "log": + bin_edges = np.geomspace(zmin, zmax, nbins + 1) + else: + bin_edges = np.linspace(zmin, zmax, nbins + 1) + + verts = np.empty((nbins, 4, 2)) + verts[:, 0, 0] = verts[:, 1, 0] = bin_edges[:-1] + verts[:, 2, 0] = verts[:, 3, 0] = bin_edges[1:] + verts[:, 0, 1] = verts[:, 3, 1] = .00 + verts[:, 1, 1] = verts[:, 2, 1] = .05 + if zname == "y": + verts = verts[:, :, ::-1] # Swap x and y. + + # Sort z-values into bins defined by bin_edges. + bin_idxs = np.searchsorted(bin_edges, z) - 1 + values = np.empty(nbins) + for i in range(nbins): + # Get C-values for each bin, and compute bin value with + # reduce_C_function. + ci = C[bin_idxs == i] + values[i] = reduce_C_function(ci) if len(ci) > 0 else np.nan + + mask = ~np.isnan(values) + verts = verts[mask] + values = values[mask] + + trans = getattr(self, f"get_{zname}axis_transform")(which="grid") + bar = mcoll.PolyCollection( + verts, transform=trans, edgecolors="face") + bar.set_array(values) + bar.set_cmap(cmap) + bar.set_norm(norm) + bar.set_alpha(alpha) + bar._internal_update(kwargs) + bars.append(self.add_collection(bar, autolim=False)) + + collection.hbar, collection.vbar = bars + + def on_changed(collection): + collection.hbar.set_cmap(collection.get_cmap()) + collection.hbar.set_cmap(collection.get_cmap()) + collection.vbar.set_clim(collection.get_clim()) + collection.vbar.set_clim(collection.get_clim()) + + collection.callbacks.connect('changed', on_changed) + + return collection + + @_docstring.dedent_interpd + def arrow(self, x, y, dx, dy, **kwargs): + """ + Add an arrow to the Axes. + + This draws an arrow from ``(x, y)`` to ``(x+dx, y+dy)``. + + Parameters + ---------- + %(FancyArrow)s + + Returns + ------- + `.FancyArrow` + The created `.FancyArrow` object. + + Notes + ----- + The resulting arrow is affected by the Axes aspect ratio and limits. + This may produce an arrow whose head is not square with its stem. To + create an arrow whose head is square with its stem, + use :meth:`annotate` for example: + + >>> ax.annotate("", xy=(0.5, 0.5), xytext=(0, 0), + ... arrowprops=dict(arrowstyle="->")) + + """ + # Strip away units for the underlying patch since units + # do not make sense to most patch-like code + x = self.convert_xunits(x) + y = self.convert_yunits(y) + dx = self.convert_xunits(dx) + dy = self.convert_yunits(dy) + + a = mpatches.FancyArrow(x, y, dx, dy, **kwargs) + self.add_patch(a) + self._request_autoscale_view() + return a + + @_docstring.copy(mquiver.QuiverKey.__init__) + def quiverkey(self, Q, X, Y, U, label, **kwargs): + qk = mquiver.QuiverKey(Q, X, Y, U, label, **kwargs) + self.add_artist(qk) + return qk + + # Handle units for x and y, if they've been passed + def _quiver_units(self, args, kwargs): + if len(args) > 3: + x, y = args[0:2] + x, y = self._process_unit_info([("x", x), ("y", y)], kwargs) + return (x, y) + args[2:] + return args + + # args can be a combination of X, Y, U, V, C and all should be replaced + @_preprocess_data() + @_docstring.dedent_interpd + def quiver(self, *args, **kwargs): + """%(quiver_doc)s""" + # Make sure units are handled for x and y values + args = self._quiver_units(args, kwargs) + q = mquiver.Quiver(self, *args, **kwargs) + self.add_collection(q, autolim=True) + self._request_autoscale_view() + return q + + # args can be some combination of X, Y, U, V, C and all should be replaced + @_preprocess_data() + @_docstring.dedent_interpd + def barbs(self, *args, **kwargs): + """%(barbs_doc)s""" + # Make sure units are handled for x and y values + args = self._quiver_units(args, kwargs) + b = mquiver.Barbs(self, *args, **kwargs) + self.add_collection(b, autolim=True) + self._request_autoscale_view() + return b + + # Uses a custom implementation of data-kwarg handling in + # _process_plot_var_args. + def fill(self, *args, data=None, **kwargs): + """ + Plot filled polygons. + + Parameters + ---------- + *args : sequence of x, y, [color] + Each polygon is defined by the lists of *x* and *y* positions of + its nodes, optionally followed by a *color* specifier. See + :mod:`matplotlib.colors` for supported color specifiers. The + standard color cycle is used for polygons without a color + specifier. + + You can plot multiple polygons by providing multiple *x*, *y*, + *[color]* groups. + + For example, each of the following is legal:: + + ax.fill(x, y) # a polygon with default color + ax.fill(x, y, "b") # a blue polygon + ax.fill(x, y, x2, y2) # two polygons + ax.fill(x, y, "b", x2, y2, "r") # a blue and a red polygon + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*, e.g.:: + + ax.fill("time", "signal", + data={"time": [0, 1, 2], "signal": [0, 1, 0]}) + + Returns + ------- + list of `~matplotlib.patches.Polygon` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Polygon` properties + + Notes + ----- + Use :meth:`fill_between` if you would like to fill the region between + two curves. + """ + # For compatibility(!), get aliases from Line2D rather than Patch. + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + # _get_patches_for_fill returns a generator, convert it to a list. + patches = [*self._get_patches_for_fill(self, *args, data=data, **kwargs)] + for poly in patches: + self.add_patch(poly) + self._request_autoscale_view() + return patches + + def _fill_between_x_or_y( + self, ind_dir, ind, dep1, dep2=0, *, + where=None, interpolate=False, step=None, **kwargs): + # Common implementation between fill_between (*ind_dir*="x") and + # fill_betweenx (*ind_dir*="y"). *ind* is the independent variable, + # *dep* the dependent variable. The docstring below is interpolated + # to generate both methods' docstrings. + """ + Fill the area between two {dir} curves. + + The curves are defined by the points (*{ind}*, *{dep}1*) and (*{ind}*, + *{dep}2*). This creates one or multiple polygons describing the filled + area. + + You may exclude some {dir} sections from filling using *where*. + + By default, the edges connect the given points directly. Use *step* + if the filling should be a step function, i.e. constant in between + *{ind}*. + + Parameters + ---------- + {ind} : array (length N) + The {ind} coordinates of the nodes defining the curves. + + {dep}1 : array (length N) or scalar + The {dep} coordinates of the nodes defining the first curve. + + {dep}2 : array (length N) or scalar, default: 0 + The {dep} coordinates of the nodes defining the second curve. + + where : array of bool (length N), optional + Define *where* to exclude some {dir} regions from being filled. + The filled regions are defined by the coordinates ``{ind}[where]``. + More precisely, fill between ``{ind}[i]`` and ``{ind}[i+1]`` if + ``where[i] and where[i+1]``. Note that this definition implies + that an isolated *True* value between two *False* values in *where* + will not result in filling. Both sides of the *True* position + remain unfilled due to the adjacent *False* values. + + interpolate : bool, default: False + This option is only relevant if *where* is used and the two curves + are crossing each other. + + Semantically, *where* is often used for *{dep}1* > *{dep}2* or + similar. By default, the nodes of the polygon defining the filled + region will only be placed at the positions in the *{ind}* array. + Such a polygon cannot describe the above semantics close to the + intersection. The {ind}-sections containing the intersection are + simply clipped. + + Setting *interpolate* to *True* will calculate the actual + intersection point and extend the filled region up to this point. + + step : {{'pre', 'post', 'mid'}}, optional + Define *step* if the filling should be a step function, + i.e. constant in between *{ind}*. The value determines where the + step will occur: + + - 'pre': The y value is continued constantly to the left from + every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the + value ``y[i]``. + - 'post': The y value is continued constantly to the right from + every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the + value ``y[i]``. + - 'mid': Steps occur half-way between the *x* positions. + + Returns + ------- + `.PolyCollection` + A `.PolyCollection` containing the plotted polygons. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + All other keyword arguments are passed on to `.PolyCollection`. + They control the `.Polygon` properties: + + %(PolyCollection:kwdoc)s + + See Also + -------- + fill_between : Fill between two sets of y-values. + fill_betweenx : Fill between two sets of x-values. + """ + + dep_dir = {"x": "y", "y": "x"}[ind_dir] + + if not mpl.rcParams["_internal.classic_mode"]: + kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) + if not any(c in kwargs for c in ("color", "facecolor")): + kwargs["facecolor"] = \ + self._get_patches_for_fill.get_next_color() + + # Handle united data, such as dates + ind, dep1, dep2 = map( + ma.masked_invalid, self._process_unit_info( + [(ind_dir, ind), (dep_dir, dep1), (dep_dir, dep2)], kwargs)) + + for name, array in [ + (ind_dir, ind), (f"{dep_dir}1", dep1), (f"{dep_dir}2", dep2)]: + if array.ndim > 1: + raise ValueError(f"{name!r} is not 1-dimensional") + + if where is None: + where = True + else: + where = np.asarray(where, dtype=bool) + if where.size != ind.size: + raise ValueError(f"where size ({where.size}) does not match " + f"{ind_dir} size ({ind.size})") + where = where & ~functools.reduce( + np.logical_or, map(np.ma.getmaskarray, [ind, dep1, dep2])) + + ind, dep1, dep2 = np.broadcast_arrays( + np.atleast_1d(ind), dep1, dep2, subok=True) + + polys = [] + for idx0, idx1 in cbook.contiguous_regions(where): + indslice = ind[idx0:idx1] + dep1slice = dep1[idx0:idx1] + dep2slice = dep2[idx0:idx1] + if step is not None: + step_func = cbook.STEP_LOOKUP_MAP["steps-" + step] + indslice, dep1slice, dep2slice = \ + step_func(indslice, dep1slice, dep2slice) + + if not len(indslice): + continue + + N = len(indslice) + pts = np.zeros((2 * N + 2, 2)) + + if interpolate: + def get_interp_point(idx): + im1 = max(idx - 1, 0) + ind_values = ind[im1:idx+1] + diff_values = dep1[im1:idx+1] - dep2[im1:idx+1] + dep1_values = dep1[im1:idx+1] + + if len(diff_values) == 2: + if np.ma.is_masked(diff_values[1]): + return ind[im1], dep1[im1] + elif np.ma.is_masked(diff_values[0]): + return ind[idx], dep1[idx] + + diff_order = diff_values.argsort() + diff_root_ind = np.interp( + 0, diff_values[diff_order], ind_values[diff_order]) + ind_order = ind_values.argsort() + diff_root_dep = np.interp( + diff_root_ind, + ind_values[ind_order], dep1_values[ind_order]) + return diff_root_ind, diff_root_dep + + start = get_interp_point(idx0) + end = get_interp_point(idx1) + else: + # Handle scalar dep2 (e.g. 0): the fill should go all + # the way down to 0 even if none of the dep1 sample points do. + start = indslice[0], dep2slice[0] + end = indslice[-1], dep2slice[-1] + + pts[0] = start + pts[N + 1] = end + + pts[1:N+1, 0] = indslice + pts[1:N+1, 1] = dep1slice + pts[N+2:, 0] = indslice[::-1] + pts[N+2:, 1] = dep2slice[::-1] + + if ind_dir == "y": + pts = pts[:, ::-1] + + polys.append(pts) + + collection = mcoll.PolyCollection(polys, **kwargs) + + # now update the datalim and autoscale + pts = np.vstack([np.hstack([ind[where, None], dep1[where, None]]), + np.hstack([ind[where, None], dep2[where, None]])]) + if ind_dir == "y": + pts = pts[:, ::-1] + + up_x = up_y = True + if "transform" in kwargs: + up_x, up_y = kwargs["transform"].contains_branch_seperately(self.transData) + self.update_datalim(pts, updatex=up_x, updatey=up_y) + + self.add_collection(collection, autolim=False) + self._request_autoscale_view() + return collection + + def fill_between(self, x, y1, y2=0, where=None, interpolate=False, + step=None, **kwargs): + return self._fill_between_x_or_y( + "x", x, y1, y2, + where=where, interpolate=interpolate, step=step, **kwargs) + + if _fill_between_x_or_y.__doc__: + fill_between.__doc__ = _fill_between_x_or_y.__doc__.format( + dir="horizontal", ind="x", dep="y" + ) + fill_between = _preprocess_data( + _docstring.dedent_interpd(fill_between), + replace_names=["x", "y1", "y2", "where"]) + + def fill_betweenx(self, y, x1, x2=0, where=None, + step=None, interpolate=False, **kwargs): + return self._fill_between_x_or_y( + "y", y, x1, x2, + where=where, interpolate=interpolate, step=step, **kwargs) + + if _fill_between_x_or_y.__doc__: + fill_betweenx.__doc__ = _fill_between_x_or_y.__doc__.format( + dir="vertical", ind="y", dep="x" + ) + fill_betweenx = _preprocess_data( + _docstring.dedent_interpd(fill_betweenx), + replace_names=["y", "x1", "x2", "where"]) + + #### plotting z(x, y): imshow, pcolor and relatives, contour + + @_preprocess_data() + @_docstring.interpd + def imshow(self, X, cmap=None, norm=None, *, aspect=None, + interpolation=None, alpha=None, + vmin=None, vmax=None, origin=None, extent=None, + interpolation_stage=None, filternorm=True, filterrad=4.0, + resample=None, url=None, **kwargs): + """ + Display data as an image, i.e., on a 2D regular raster. + + The input may either be actual RGB(A) data, or 2D scalar data, which + will be rendered as a pseudocolor image. For displaying a grayscale + image, set up the colormapping using the parameters + ``cmap='gray', vmin=0, vmax=255``. + + The number of pixels used to render an image is set by the Axes size + and the figure *dpi*. This can lead to aliasing artifacts when + the image is resampled, because the displayed image size will usually + not match the size of *X* (see + :doc:`/gallery/images_contours_and_fields/image_antialiasing`). + The resampling can be controlled via the *interpolation* parameter + and/or :rc:`image.interpolation`. + + Parameters + ---------- + X : array-like or PIL image + The image data. Supported array shapes are: + + - (M, N): an image with scalar data. The values are mapped to + colors using normalization and a colormap. See parameters *norm*, + *cmap*, *vmin*, *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the image. + + Out-of-range RGB(A) values are clipped. + + %(cmap_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *X* is RGB(A). + + aspect : {'equal', 'auto'} or float or None, default: None + The aspect ratio of the Axes. This parameter is particularly + relevant for images since it determines whether data pixels are + square. + + This parameter is a shortcut for explicitly calling + `.Axes.set_aspect`. See there for further details. + + - 'equal': Ensures an aspect ratio of 1. Pixels will be square + (unless pixel sizes are explicitly made non-square in data + coordinates using *extent*). + - 'auto': The Axes is kept fixed and the aspect is adjusted so + that the data fit in the Axes. In general, this will result in + non-square pixels. + + Normally, None (the default) means to use :rc:`image.aspect`. However, if + the image uses a transform that does not contain the axes data transform, + then None means to not modify the axes aspect at all (in that case, directly + call `.Axes.set_aspect` if desired). + + interpolation : str, default: :rc:`image.interpolation` + The interpolation method used. + + Supported values are 'none', 'antialiased', 'nearest', 'bilinear', + 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', + 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', + 'sinc', 'lanczos', 'blackman'. + + The data *X* is resampled to the pixel size of the image on the + figure canvas, using the interpolation method to either up- or + downsample the data. + + If *interpolation* is 'none', then for the ps, pdf, and svg + backends no down- or upsampling occurs, and the image data is + passed to the backend as a native image. Note that different ps, + pdf, and svg viewers may display these raw pixels differently. On + other backends, 'none' is the same as 'nearest'. + + If *interpolation* is the default 'antialiased', then 'nearest' + interpolation is used if the image is upsampled by more than a + factor of three (i.e. the number of display pixels is at least + three times the size of the data array). If the upsampling rate is + smaller than 3, or the image is downsampled, then 'hanning' + interpolation is used to act as an anti-aliasing filter, unless the + image happens to be upsampled by exactly a factor of two or one. + + See + :doc:`/gallery/images_contours_and_fields/interpolation_methods` + for an overview of the supported interpolation methods, and + :doc:`/gallery/images_contours_and_fields/image_antialiasing` for + a discussion of image antialiasing. + + Some interpolation methods require an additional radius parameter, + which can be set by *filterrad*. Additionally, the antigrain image + resize filter is controlled by the parameter *filternorm*. + + interpolation_stage : {'data', 'rgba'}, default: 'data' + If 'data', interpolation + is carried out on the data provided by the user. If 'rgba', the + interpolation is carried out after the colormapping has been + applied (visual interpolation). + + alpha : float or array-like, optional + The alpha blending value, between 0 (transparent) and 1 (opaque). + If *alpha* is an array, the alpha blending values are applied pixel + by pixel, and *alpha* must have the same shape as *X*. + + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Place the [0, 0] index of the array in the upper left or lower + left corner of the Axes. The convention (the default) 'upper' is + typically used for matrices and images. + + Note that the vertical axis points upward for 'lower' + but downward for 'upper'. + + See the :ref:`imshow_extent` tutorial for + examples and a more detailed description. + + extent : floats (left, right, bottom, top), optional + The bounding box in data coordinates that the image will fill. + These values may be unitful and match the units of the Axes. + The image is stretched individually along x and y to fill the box. + + The default extent is determined by the following conditions. + Pixels have unit size in data coordinates. Their centers are on + integer coordinates, and their center coordinates range from 0 to + columns-1 horizontally and from 0 to rows-1 vertically. + + Note that the direction of the vertical axis and thus the default + values for top and bottom depend on *origin*: + + - For ``origin == 'upper'`` the default is + ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``. + - For ``origin == 'lower'`` the default is + ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``. + + See the :ref:`imshow_extent` tutorial for + examples and a more detailed description. + + filternorm : bool, default: True + A parameter for the antigrain image resize filter (see the + antigrain documentation). If *filternorm* is set, the filter + normalizes integer values and corrects the rounding errors. It + doesn't do anything with the source floating point values, it + corrects only integers according to the rule of 1.0 which means + that any sum of pixel weights must be equal to 1.0. So, the + filter function must produce a graph of the proper shape. + + filterrad : float > 0, default: 4.0 + The filter radius for filters that have a radius parameter, i.e. + when interpolation is one of: 'sinc', 'lanczos' or 'blackman'. + + resample : bool, default: :rc:`image.resample` + When *True*, use a full resampling method. When *False*, only + resample when the output image is larger than the input image. + + url : str, optional + Set the url of the created `.AxesImage`. See `.Artist.set_url`. + + Returns + ------- + `~matplotlib.image.AxesImage` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `~matplotlib.artist.Artist` properties + These parameters are passed on to the constructor of the + `.AxesImage` artist. + + See Also + -------- + matshow : Plot a matrix or an array as an image. + + Notes + ----- + Unless *extent* is used, pixel centers will be located at integer + coordinates. In other words: the origin will coincide with the center + of pixel (0, 0). + + There are two common representations for RGB images with an alpha + channel: + + - Straight (unassociated) alpha: R, G, and B channels represent the + color of the pixel, disregarding its opacity. + - Premultiplied (associated) alpha: R, G, and B channels represent + the color of the pixel, adjusted for its opacity by multiplication. + + `~matplotlib.pyplot.imshow` expects RGB images adopting the straight + (unassociated) alpha representation. + """ + im = mimage.AxesImage(self, cmap=cmap, norm=norm, + interpolation=interpolation, origin=origin, + extent=extent, filternorm=filternorm, + filterrad=filterrad, resample=resample, + interpolation_stage=interpolation_stage, + **kwargs) + + if aspect is None and not ( + im.is_transform_set() + and not im.get_transform().contains_branch(self.transData)): + aspect = mpl.rcParams['image.aspect'] + if aspect is not None: + self.set_aspect(aspect) + + im.set_data(X) + im.set_alpha(alpha) + if im.get_clip_path() is None: + # image does not already have clipping set, clip to Axes patch + im.set_clip_path(self.patch) + im._scale_norm(norm, vmin, vmax) + im.set_url(url) + + # update ax.dataLim, and, if autoscaling, set viewLim + # to tightly fit the image, regardless of dataLim. + im.set_extent(im.get_extent()) + + self.add_image(im) + return im + + def _pcolorargs(self, funcname, *args, shading='auto', **kwargs): + # - create X and Y if not present; + # - reshape X and Y as needed if they are 1-D; + # - check for proper sizes based on `shading` kwarg; + # - reset shading if shading='auto' to flat or nearest + # depending on size; + + _valid_shading = ['gouraud', 'nearest', 'flat', 'auto'] + try: + _api.check_in_list(_valid_shading, shading=shading) + except ValueError: + _api.warn_external(f"shading value '{shading}' not in list of " + f"valid values {_valid_shading}. Setting " + "shading='auto'.") + shading = 'auto' + + if len(args) == 1: + C = np.asanyarray(args[0]) + nrows, ncols = C.shape[:2] + if shading in ['gouraud', 'nearest']: + X, Y = np.meshgrid(np.arange(ncols), np.arange(nrows)) + else: + X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1)) + shading = 'flat' + C = cbook.safe_masked_invalid(C, copy=True) + return X, Y, C, shading + + if len(args) == 3: + # Check x and y for bad data... + C = np.asanyarray(args[2]) + # unit conversion allows e.g. datetime objects as axis values + X, Y = args[:2] + X, Y = self._process_unit_info([("x", X), ("y", Y)], kwargs) + X, Y = [cbook.safe_masked_invalid(a, copy=True) for a in [X, Y]] + + if funcname == 'pcolormesh': + if np.ma.is_masked(X) or np.ma.is_masked(Y): + raise ValueError( + 'x and y arguments to pcolormesh cannot have ' + 'non-finite values or be of type ' + 'numpy.ma.MaskedArray with masked values') + nrows, ncols = C.shape[:2] + else: + raise _api.nargs_error(funcname, takes="1 or 3", given=len(args)) + + Nx = X.shape[-1] + Ny = Y.shape[0] + if X.ndim != 2 or X.shape[0] == 1: + x = X.reshape(1, Nx) + X = x.repeat(Ny, axis=0) + if Y.ndim != 2 or Y.shape[1] == 1: + y = Y.reshape(Ny, 1) + Y = y.repeat(Nx, axis=1) + if X.shape != Y.shape: + raise TypeError(f'Incompatible X, Y inputs to {funcname}; ' + f'see help({funcname})') + + if shading == 'auto': + if ncols == Nx and nrows == Ny: + shading = 'nearest' + else: + shading = 'flat' + + if shading == 'flat': + if (Nx, Ny) != (ncols + 1, nrows + 1): + raise TypeError(f"Dimensions of C {C.shape} should" + f" be one smaller than X({Nx}) and Y({Ny})" + f" while using shading='flat'" + f" see help({funcname})") + else: # ['nearest', 'gouraud']: + if (Nx, Ny) != (ncols, nrows): + raise TypeError('Dimensions of C %s are incompatible with' + ' X (%d) and/or Y (%d); see help(%s)' % ( + C.shape, Nx, Ny, funcname)) + if shading == 'nearest': + # grid is specified at the center, so define corners + # at the midpoints between the grid centers and then use the + # flat algorithm. + def _interp_grid(X): + # helper for below + if np.shape(X)[1] > 1: + dX = np.diff(X, axis=1) * 0.5 + if not (np.all(dX >= 0) or np.all(dX <= 0)): + _api.warn_external( + f"The input coordinates to {funcname} are " + "interpreted as cell centers, but are not " + "monotonically increasing or decreasing. " + "This may lead to incorrectly calculated cell " + "edges, in which case, please supply " + f"explicit cell edges to {funcname}.") + + hstack = np.ma.hstack if np.ma.isMA(X) else np.hstack + X = hstack((X[:, [0]] - dX[:, [0]], + X[:, :-1] + dX, + X[:, [-1]] + dX[:, [-1]])) + else: + # This is just degenerate, but we can't reliably guess + # a dX if there is just one value. + X = np.hstack((X, X)) + return X + + if ncols == Nx: + X = _interp_grid(X) + Y = _interp_grid(Y) + if nrows == Ny: + X = _interp_grid(X.T).T + Y = _interp_grid(Y.T).T + shading = 'flat' + + C = cbook.safe_masked_invalid(C, copy=True) + return X, Y, C, shading + + @_preprocess_data() + @_docstring.dedent_interpd + def pcolor(self, *args, shading=None, alpha=None, norm=None, cmap=None, + vmin=None, vmax=None, **kwargs): + r""" + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + pcolor([X, Y,] C, **kwargs) + + *X* and *Y* can be used to specify the corners of the quadrilaterals. + + .. hint:: + + ``pcolor()`` can be very slow for large arrays. In most + cases you should use the similar but much faster + `~.Axes.pcolormesh` instead. See + :ref:`Differences between pcolor() and pcolormesh() + ` for a discussion of the + differences. + + Parameters + ---------- + C : 2D array-like + The color-mapped values. Color-mapping is controlled by *cmap*, + *norm*, *vmin*, and *vmax*. + + X, Y : array-like, optional + The coordinates of the corners of quadrilaterals of a pcolormesh:: + + (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) + ●╶───╴● + │ │ + ●╶───╴● + (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1]) + + Note that the column index corresponds to the x-coordinate, and + the row index corresponds to y. For details, see the + :ref:`Notes ` section below. + + If ``shading='flat'`` the dimensions of *X* and *Y* should be one + greater than those of *C*, and the quadrilateral is colored due + to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal + dimensions, a warning will be raised and the last row and column + of *C* will be ignored. + + If ``shading='nearest'``, the dimensions of *X* and *Y* should be + the same as those of *C* (if not, a ValueError will be raised). The + color ``C[i, j]`` will be centered on ``(X[i, j], Y[i, j])``. + + If *X* and/or *Y* are 1-D arrays or column vectors they will be + expanded as needed into the appropriate 2D arrays, making a + rectangular grid. + + shading : {'flat', 'nearest', 'auto'}, default: :rc:`pcolor.shading` + The fill style for the quadrilateral. Possible values: + + - 'flat': A solid color is used for each quad. The color of the + quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by + ``C[i, j]``. The dimensions of *X* and *Y* should be + one greater than those of *C*; if they are the same as *C*, + then a deprecation warning is raised, and the last row + and column of *C* are dropped. + - 'nearest': Each grid point will have a color centered on it, + extending halfway between the adjacent grid centers. The + dimensions of *X* and *Y* must be the same as *C*. + - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one + larger than *C*. Choose 'nearest' if dimensions are the same. + + See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids` + for more description. + + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + edgecolors : {'none', None, 'face', color, color sequence}, optional + The color of the edges. Defaults to 'none'. Possible values: + + - 'none' or '': No edge. + - *None*: :rc:`patch.edgecolor` will be used. Note that currently + :rc:`patch.force_edgecolor` has to be True for this to work. + - 'face': Use the adjacent face color. + - A color or sequence of colors will set the edge color. + + The singular form *edgecolor* works as an alias. + + alpha : float, default: None + The alpha blending value of the face color, between 0 (transparent) + and 1 (opaque). Note: The edgecolor is currently not affected by + this. + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + Returns + ------- + `matplotlib.collections.PolyQuadMesh` + + Other Parameters + ---------------- + antialiaseds : bool, default: False + The default *antialiaseds* is False if the default + *edgecolors*\ ="none" is used. This eliminates artificial lines + at patch boundaries, and works regardless of the value of alpha. + If *edgecolors* is not "none", then the default *antialiaseds* + is taken from :rc:`patch.antialiased`. + Stroking the edges may be preferred if *alpha* is 1, but will + cause artifacts otherwise. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additionally, the following arguments are allowed. They are passed + along to the `~matplotlib.collections.PolyQuadMesh` constructor: + + %(PolyCollection:kwdoc)s + + See Also + -------- + pcolormesh : for an explanation of the differences between + pcolor and pcolormesh. + imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a + faster alternative. + + Notes + ----- + **Masked arrays** + + *X*, *Y* and *C* may be masked arrays. If either ``C[i, j]``, or one + of the vertices surrounding ``C[i, j]`` (*X* or *Y* at + ``[i, j], [i+1, j], [i, j+1], [i+1, j+1]``) is masked, nothing is + plotted. + + .. _axes-pcolor-grid-orientation: + + **Grid orientation** + + The grid orientation follows the standard matrix convention: An array + *C* with shape (nrows, ncolumns) is plotted with the column number as + *X* and the row number as *Y*. + """ + + if shading is None: + shading = mpl.rcParams['pcolor.shading'] + shading = shading.lower() + X, Y, C, shading = self._pcolorargs('pcolor', *args, shading=shading, + kwargs=kwargs) + linewidths = (0.25,) + if 'linewidth' in kwargs: + kwargs['linewidths'] = kwargs.pop('linewidth') + kwargs.setdefault('linewidths', linewidths) + + if 'edgecolor' in kwargs: + kwargs['edgecolors'] = kwargs.pop('edgecolor') + ec = kwargs.setdefault('edgecolors', 'none') + + # aa setting will default via collections to patch.antialiased + # unless the boundary is not stroked, in which case the + # default will be False; with unstroked boundaries, aa + # makes artifacts that are often disturbing. + if 'antialiaseds' in kwargs: + kwargs['antialiased'] = kwargs.pop('antialiaseds') + if 'antialiased' not in kwargs and cbook._str_lower_equal(ec, "none"): + kwargs['antialiased'] = False + + kwargs.setdefault('snap', False) + + if np.ma.isMaskedArray(X) or np.ma.isMaskedArray(Y): + stack = np.ma.stack + X = np.ma.asarray(X) + Y = np.ma.asarray(Y) + # For bounds collections later + x = X.compressed() + y = Y.compressed() + else: + stack = np.stack + x = X + y = Y + coords = stack([X, Y], axis=-1) + + collection = mcoll.PolyQuadMesh( + coords, array=C, cmap=cmap, norm=norm, alpha=alpha, **kwargs) + collection._scale_norm(norm, vmin, vmax) + + # Transform from native to data coordinates? + t = collection._transform + if (not isinstance(t, mtransforms.Transform) and + hasattr(t, '_as_mpl_transform')): + t = t._as_mpl_transform(self.axes) + + if t and any(t.contains_branch_seperately(self.transData)): + trans_to_data = t - self.transData + pts = np.vstack([x, y]).T.astype(float) + transformed_pts = trans_to_data.transform(pts) + x = transformed_pts[..., 0] + y = transformed_pts[..., 1] + + self.add_collection(collection, autolim=False) + + minx = np.min(x) + maxx = np.max(x) + miny = np.min(y) + maxy = np.max(y) + collection.sticky_edges.x[:] = [minx, maxx] + collection.sticky_edges.y[:] = [miny, maxy] + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners) + self._request_autoscale_view() + return collection + + @_preprocess_data() + @_docstring.dedent_interpd + def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None, + vmax=None, shading=None, antialiased=False, **kwargs): + """ + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + pcolormesh([X, Y,] C, **kwargs) + + *X* and *Y* can be used to specify the corners of the quadrilaterals. + + .. hint:: + + `~.Axes.pcolormesh` is similar to `~.Axes.pcolor`. It is much faster + and preferred in most cases. For a detailed discussion on the + differences see :ref:`Differences between pcolor() and pcolormesh() + `. + + Parameters + ---------- + C : array-like + The mesh data. Supported array shapes are: + + - (M, N) or M*N: a mesh with scalar data. The values are mapped to + colors using normalization and a colormap. See parameters *norm*, + *cmap*, *vmin*, *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the mesh data. + + X, Y : array-like, optional + The coordinates of the corners of quadrilaterals of a pcolormesh:: + + (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) + ●╶───╴● + │ │ + ●╶───╴● + (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1]) + + Note that the column index corresponds to the x-coordinate, and + the row index corresponds to y. For details, see the + :ref:`Notes ` section below. + + If ``shading='flat'`` the dimensions of *X* and *Y* should be one + greater than those of *C*, and the quadrilateral is colored due + to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal + dimensions, a warning will be raised and the last row and column + of *C* will be ignored. + + If ``shading='nearest'`` or ``'gouraud'``, the dimensions of *X* + and *Y* should be the same as those of *C* (if not, a ValueError + will be raised). For ``'nearest'`` the color ``C[i, j]`` is + centered on ``(X[i, j], Y[i, j])``. For ``'gouraud'``, a smooth + interpolation is carried out between the quadrilateral corners. + + If *X* and/or *Y* are 1-D arrays or column vectors they will be + expanded as needed into the appropriate 2D arrays, making a + rectangular grid. + + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + edgecolors : {'none', None, 'face', color, color sequence}, optional + The color of the edges. Defaults to 'none'. Possible values: + + - 'none' or '': No edge. + - *None*: :rc:`patch.edgecolor` will be used. Note that currently + :rc:`patch.force_edgecolor` has to be True for this to work. + - 'face': Use the adjacent face color. + - A color or sequence of colors will set the edge color. + + The singular form *edgecolor* works as an alias. + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + shading : {'flat', 'nearest', 'gouraud', 'auto'}, optional + The fill style for the quadrilateral; defaults to + :rc:`pcolor.shading`. Possible values: + + - 'flat': A solid color is used for each quad. The color of the + quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by + ``C[i, j]``. The dimensions of *X* and *Y* should be + one greater than those of *C*; if they are the same as *C*, + then a deprecation warning is raised, and the last row + and column of *C* are dropped. + - 'nearest': Each grid point will have a color centered on it, + extending halfway between the adjacent grid centers. The + dimensions of *X* and *Y* must be the same as *C*. + - 'gouraud': Each quad will be Gouraud shaded: The color of the + corners (i', j') are given by ``C[i', j']``. The color values of + the area in between is interpolated from the corner values. + The dimensions of *X* and *Y* must be the same as *C*. When + Gouraud shading is used, *edgecolors* is ignored. + - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one + larger than *C*. Choose 'nearest' if dimensions are the same. + + See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids` + for more description. + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + rasterized : bool, optional + Rasterize the pcolormesh when drawing vector graphics. This can + speed up rendering and produce smaller files for large data sets. + See also :doc:`/gallery/misc/rasterization_demo`. + + Returns + ------- + `matplotlib.collections.QuadMesh` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additionally, the following arguments are allowed. They are passed + along to the `~matplotlib.collections.QuadMesh` constructor: + + %(QuadMesh:kwdoc)s + + See Also + -------- + pcolor : An alternative implementation with slightly different + features. For a detailed discussion on the differences see + :ref:`Differences between pcolor() and pcolormesh() + `. + imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a + faster alternative. + + Notes + ----- + **Masked arrays** + + *C* may be a masked array. If ``C[i, j]`` is masked, the corresponding + quadrilateral will be transparent. Masking of *X* and *Y* is not + supported. Use `~.Axes.pcolor` if you need this functionality. + + .. _axes-pcolormesh-grid-orientation: + + **Grid orientation** + + The grid orientation follows the standard matrix convention: An array + *C* with shape (nrows, ncolumns) is plotted with the column number as + *X* and the row number as *Y*. + + .. _differences-pcolor-pcolormesh: + + **Differences between pcolor() and pcolormesh()** + + Both methods are used to create a pseudocolor plot of a 2D array + using quadrilaterals. + + The main difference lies in the created object and internal data + handling: + While `~.Axes.pcolor` returns a `.PolyQuadMesh`, `~.Axes.pcolormesh` + returns a `.QuadMesh`. The latter is more specialized for the given + purpose and thus is faster. It should almost always be preferred. + + There is also a slight difference in the handling of masked arrays. + Both `~.Axes.pcolor` and `~.Axes.pcolormesh` support masked arrays + for *C*. However, only `~.Axes.pcolor` supports masked arrays for *X* + and *Y*. The reason lies in the internal handling of the masked values. + `~.Axes.pcolor` leaves out the respective polygons from the + PolyQuadMesh. `~.Axes.pcolormesh` sets the facecolor of the masked + elements to transparent. You can see the difference when using + edgecolors. While all edges are drawn irrespective of masking in a + QuadMesh, the edge between two adjacent masked quadrilaterals in + `~.Axes.pcolor` is not drawn as the corresponding polygons do not + exist in the PolyQuadMesh. Because PolyQuadMesh draws each individual + polygon, it also supports applying hatches and linestyles to the collection. + + Another difference is the support of Gouraud shading in + `~.Axes.pcolormesh`, which is not available with `~.Axes.pcolor`. + + """ + if shading is None: + shading = mpl.rcParams['pcolor.shading'] + shading = shading.lower() + kwargs.setdefault('edgecolors', 'none') + + X, Y, C, shading = self._pcolorargs('pcolormesh', *args, + shading=shading, kwargs=kwargs) + coords = np.stack([X, Y], axis=-1) + + kwargs.setdefault('snap', mpl.rcParams['pcolormesh.snap']) + + collection = mcoll.QuadMesh( + coords, antialiased=antialiased, shading=shading, + array=C, cmap=cmap, norm=norm, alpha=alpha, **kwargs) + collection._scale_norm(norm, vmin, vmax) + + coords = coords.reshape(-1, 2) # flatten the grid structure; keep x, y + + # Transform from native to data coordinates? + t = collection._transform + if (not isinstance(t, mtransforms.Transform) and + hasattr(t, '_as_mpl_transform')): + t = t._as_mpl_transform(self.axes) + + if t and any(t.contains_branch_seperately(self.transData)): + trans_to_data = t - self.transData + coords = trans_to_data.transform(coords) + + self.add_collection(collection, autolim=False) + + minx, miny = np.min(coords, axis=0) + maxx, maxy = np.max(coords, axis=0) + collection.sticky_edges.x[:] = [minx, maxx] + collection.sticky_edges.y[:] = [miny, maxy] + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners) + self._request_autoscale_view() + return collection + + @_preprocess_data() + @_docstring.dedent_interpd + def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None, + vmax=None, **kwargs): + """ + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + ax.pcolorfast([X, Y], C, /, **kwargs) + + This method is similar to `~.Axes.pcolor` and `~.Axes.pcolormesh`. + It's designed to provide the fastest pcolor-type plotting with the + Agg backend. To achieve this, it uses different algorithms internally + depending on the complexity of the input grid (regular rectangular, + non-regular rectangular or arbitrary quadrilateral). + + .. warning:: + + This method is experimental. Compared to `~.Axes.pcolor` or + `~.Axes.pcolormesh` it has some limitations: + + - It supports only flat shading (no outlines) + - It lacks support for log scaling of the axes. + - It does not have a pyplot wrapper. + + Parameters + ---------- + C : array-like + The image data. Supported array shapes are: + + - (M, N): an image with scalar data. Color-mapping is controlled + by *cmap*, *norm*, *vmin*, and *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the image. + + This parameter can only be passed positionally. + + X, Y : tuple or array-like, default: ``(0, N)``, ``(0, M)`` + *X* and *Y* are used to specify the coordinates of the + quadrilaterals. There are different ways to do this: + + - Use tuples ``X=(xmin, xmax)`` and ``Y=(ymin, ymax)`` to define + a *uniform rectangular grid*. + + The tuples define the outer edges of the grid. All individual + quadrilaterals will be of the same size. This is the fastest + version. + + - Use 1D arrays *X*, *Y* to specify a *non-uniform rectangular + grid*. + + In this case *X* and *Y* have to be monotonic 1D arrays of length + *N+1* and *M+1*, specifying the x and y boundaries of the cells. + + The speed is intermediate. Note: The grid is checked, and if + found to be uniform the fast version is used. + + - Use 2D arrays *X*, *Y* if you need an *arbitrary quadrilateral + grid* (i.e. if the quadrilaterals are not rectangular). + + In this case *X* and *Y* are 2D arrays with shape (M + 1, N + 1), + specifying the x and y coordinates of the corners of the colored + quadrilaterals. + + This is the most general, but the slowest to render. It may + produce faster and more compact output using ps, pdf, and + svg backends, however. + + These arguments can only be passed positionally. + + %(cmap_doc)s + + This parameter is ignored if *C* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *C* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *C* is RGB(A). + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + Returns + ------- + `.AxesImage` or `.PcolorImage` or `.QuadMesh` + The return type depends on the type of grid: + + - `.AxesImage` for a regular rectangular grid. + - `.PcolorImage` for a non-regular rectangular grid. + - `.QuadMesh` for a non-rectangular grid. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Supported additional parameters depend on the type of grid. + See return types of *image* for further description. + """ + + C = args[-1] + nr, nc = np.shape(C)[:2] + if len(args) == 1: + style = "image" + x = [0, nc] + y = [0, nr] + elif len(args) == 3: + x, y = args[:2] + x = np.asarray(x) + y = np.asarray(y) + if x.ndim == 1 and y.ndim == 1: + if x.size == 2 and y.size == 2: + style = "image" + else: + dx = np.diff(x) + dy = np.diff(y) + if (np.ptp(dx) < 0.01 * abs(dx.mean()) and + np.ptp(dy) < 0.01 * abs(dy.mean())): + style = "image" + else: + style = "pcolorimage" + elif x.ndim == 2 and y.ndim == 2: + style = "quadmesh" + else: + raise TypeError( + f"When 3 positional parameters are passed to pcolorfast, the first " + f"two (X and Y) must be both 1D or both 2D; the given X was " + f"{x.ndim}D and the given Y was {y.ndim}D") + else: + raise _api.nargs_error('pcolorfast', '1 or 3', len(args)) + + if style == "quadmesh": + # data point in each cell is value at lower left corner + coords = np.stack([x, y], axis=-1) + if np.ndim(C) not in {2, 3}: + raise ValueError("C must be 2D or 3D") + collection = mcoll.QuadMesh( + coords, array=C, + alpha=alpha, cmap=cmap, norm=norm, + antialiased=False, edgecolors="none") + self.add_collection(collection, autolim=False) + xl, xr, yb, yt = x.min(), x.max(), y.min(), y.max() + ret = collection + + else: # It's one of the two image styles. + extent = xl, xr, yb, yt = x[0], x[-1], y[0], y[-1] + if style == "image": + im = mimage.AxesImage( + self, cmap=cmap, norm=norm, + data=C, alpha=alpha, extent=extent, + interpolation='nearest', origin='lower', + **kwargs) + elif style == "pcolorimage": + im = mimage.PcolorImage( + self, x, y, C, + cmap=cmap, norm=norm, alpha=alpha, extent=extent, + **kwargs) + self.add_image(im) + ret = im + + if np.ndim(C) == 2: # C.ndim == 3 is RGB(A) so doesn't need scaling. + ret._scale_norm(norm, vmin, vmax) + + if ret.get_clip_path() is None: + # image does not already have clipping set, clip to Axes patch + ret.set_clip_path(self.patch) + + ret.sticky_edges.x[:] = [xl, xr] + ret.sticky_edges.y[:] = [yb, yt] + self.update_datalim(np.array([[xl, yb], [xr, yt]])) + self._request_autoscale_view(tight=True) + return ret + + @_preprocess_data() + @_docstring.dedent_interpd + def contour(self, *args, **kwargs): + """ + Plot contour lines. + + Call signature:: + + contour([X, Y,] Z, [levels], **kwargs) + %(contour_doc)s + """ + kwargs['filled'] = False + contours = mcontour.QuadContourSet(self, *args, **kwargs) + self._request_autoscale_view() + return contours + + @_preprocess_data() + @_docstring.dedent_interpd + def contourf(self, *args, **kwargs): + """ + Plot filled contours. + + Call signature:: + + contourf([X, Y,] Z, [levels], **kwargs) + %(contour_doc)s + """ + kwargs['filled'] = True + contours = mcontour.QuadContourSet(self, *args, **kwargs) + self._request_autoscale_view() + return contours + + def clabel(self, CS, levels=None, **kwargs): + """ + Label a contour plot. + + Adds labels to line contours in given `.ContourSet`. + + Parameters + ---------- + CS : `.ContourSet` instance + Line contours to label. + + levels : array-like, optional + A list of level values, that should be labeled. The list must be + a subset of ``CS.levels``. If not given, all levels are labeled. + + **kwargs + All other parameters are documented in `~.ContourLabeler.clabel`. + """ + return CS.clabel(levels, **kwargs) + + #### Data analysis + + @_preprocess_data(replace_names=["x", 'weights'], label_namer="x") + def hist(self, x, bins=None, range=None, density=False, weights=None, + cumulative=False, bottom=None, histtype='bar', align='mid', + orientation='vertical', rwidth=None, log=False, + color=None, label=None, stacked=False, **kwargs): + """ + Compute and plot a histogram. + + This method uses `numpy.histogram` to bin the data in *x* and count the + number of values in each bin, then draws the distribution either as a + `.BarContainer` or `.Polygon`. The *bins*, *range*, *density*, and + *weights* parameters are forwarded to `numpy.histogram`. + + If the data has already been binned and counted, use `~.bar` or + `~.stairs` to plot the distribution:: + + counts, bins = np.histogram(x) + plt.stairs(counts, bins) + + Alternatively, plot pre-computed bins and counts using ``hist()`` by + treating each bin as a single point with a weight equal to its count:: + + plt.hist(bins[:-1], bins, weights=counts) + + The data input *x* can be a singular array, a list of datasets of + potentially different lengths ([*x0*, *x1*, ...]), or a 2D ndarray in + which each column is a dataset. Note that the ndarray form is + transposed relative to the list form. If the input is an array, then + the return value is a tuple (*n*, *bins*, *patches*); if the input is a + sequence of arrays, then the return value is a tuple + ([*n0*, *n1*, ...], *bins*, [*patches0*, *patches1*, ...]). + + Masked arrays are not supported. + + Parameters + ---------- + x : (n,) array or sequence of (n,) arrays + Input values, this takes either a single array or a sequence of + arrays which are not required to be of the same length. + + bins : int or sequence or str, default: :rc:`hist.bins` + If *bins* is an integer, it defines the number of equal-width bins + in the range. + + If *bins* is a sequence, it defines the bin edges, including the + left edge of the first bin and the right edge of the last bin; + in this case, bins may be unequally spaced. All but the last + (righthand-most) bin is half-open. In other words, if *bins* is:: + + [1, 2, 3, 4] + + then the first bin is ``[1, 2)`` (including 1, but excluding 2) and + the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which + *includes* 4. + + If *bins* is a string, it is one of the binning strategies + supported by `numpy.histogram_bin_edges`: 'auto', 'fd', 'doane', + 'scott', 'stone', 'rice', 'sturges', or 'sqrt'. + + range : tuple or None, default: None + The lower and upper range of the bins. Lower and upper outliers + are ignored. If not provided, *range* is ``(x.min(), x.max())``. + Range has no effect if *bins* is a sequence. + + If *bins* is a sequence or *range* is specified, autoscaling + is based on the specified bin range instead of the + range of x. + + density : bool, default: False + If ``True``, draw and return a probability density: each bin + will display the bin's raw count divided by the total number of + counts *and the bin width* + (``density = counts / (sum(counts) * np.diff(bins))``), + so that the area under the histogram integrates to 1 + (``np.sum(density * np.diff(bins)) == 1``). + + If *stacked* is also ``True``, the sum of the histograms is + normalized to 1. + + weights : (n,) array-like or None, default: None + An array of weights, of the same shape as *x*. Each value in + *x* only contributes its associated weight towards the bin count + (instead of 1). If *density* is ``True``, the weights are + normalized, so that the integral of the density over the range + remains 1. + + cumulative : bool or -1, default: False + If ``True``, then a histogram is computed where each bin gives the + counts in that bin plus all bins for smaller values. The last bin + gives the total number of datapoints. + + If *density* is also ``True`` then the histogram is normalized such + that the last bin equals 1. + + If *cumulative* is a number less than 0 (e.g., -1), the direction + of accumulation is reversed. In this case, if *density* is also + ``True``, then the histogram is normalized such that the first bin + equals 1. + + bottom : array-like, scalar, or None, default: None + Location of the bottom of each bin, i.e. bins are drawn from + ``bottom`` to ``bottom + hist(x, bins)`` If a scalar, the bottom + of each bin is shifted by the same amount. If an array, each bin + is shifted independently and the length of bottom must match the + number of bins. If None, defaults to 0. + + histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar' + The type of histogram to draw. + + - 'bar' is a traditional bar-type histogram. If multiple data + are given the bars are arranged side by side. + - 'barstacked' is a bar-type histogram where multiple + data are stacked on top of each other. + - 'step' generates a lineplot that is by default unfilled. + - 'stepfilled' generates a lineplot that is by default filled. + + align : {'left', 'mid', 'right'}, default: 'mid' + The horizontal alignment of the histogram bars. + + - 'left': bars are centered on the left bin edges. + - 'mid': bars are centered between the bin edges. + - 'right': bars are centered on the right bin edges. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', `~.Axes.barh` will be used for bar-type histograms + and the *bottom* kwarg will be the left edges. + + rwidth : float or None, default: None + The relative width of the bars as a fraction of the bin width. If + ``None``, automatically compute the width. + + Ignored if *histtype* is 'step' or 'stepfilled'. + + log : bool, default: False + If ``True``, the histogram axis will be set to a log scale. + + color : :mpltype:`color` or list of :mpltype:`color` or None, default: None + Color or sequence of colors, one per dataset. Default (``None``) + uses the standard line color sequence. + + label : str or list of str, optional + String, or sequence of strings to match multiple datasets. Bar + charts yield multiple patches per dataset, but only the first gets + the label, so that `~.Axes.legend` will work as expected. + + stacked : bool, default: False + If ``True``, multiple data are stacked on top of each other If + ``False`` multiple data are arranged side by side if histtype is + 'bar' or on top of each other if histtype is 'step' + + Returns + ------- + n : array or list of arrays + The values of the histogram bins. See *density* and *weights* for a + description of the possible semantics. If input *x* is an array, + then this is an array of length *nbins*. If input is a sequence of + arrays ``[data1, data2, ...]``, then this is a list of arrays with + the values of the histograms for each of the arrays in the same + order. The dtype of the array *n* (or of its element arrays) will + always be float even if no weighting or normalization is used. + + bins : array + The edges of the bins. Length nbins + 1 (nbins left edges and right + edge of last bin). Always a single array even when multiple data + sets are passed in. + + patches : `.BarContainer` or list of a single `.Polygon` or list of \ +such objects + Container of individual artists used to create the histogram + or list of such containers if there are multiple input datasets. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + `~matplotlib.patches.Patch` properties + + See Also + -------- + hist2d : 2D histogram with rectangular bins + hexbin : 2D histogram with hexagonal bins + stairs : Plot a pre-computed histogram + bar : Plot a pre-computed histogram + + Notes + ----- + For large numbers of bins (>1000), plotting can be significantly + accelerated by using `~.Axes.stairs` to plot a pre-computed histogram + (``plt.stairs(*np.histogram(data))``), or by setting *histtype* to + 'step' or 'stepfilled' rather than 'bar' or 'barstacked'. + """ + # Avoid shadowing the builtin. + bin_range = range + from builtins import range + + if np.isscalar(x): + x = [x] + + if bins is None: + bins = mpl.rcParams['hist.bins'] + + # Validate string inputs here to avoid cluttering subsequent code. + _api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'], + histtype=histtype) + _api.check_in_list(['left', 'mid', 'right'], align=align) + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + if histtype == 'barstacked' and not stacked: + stacked = True + + # Massage 'x' for processing. + x = cbook._reshape_2D(x, 'x') + nx = len(x) # number of datasets + + # Process unit information. _process_unit_info sets the unit and + # converts the first dataset; then we convert each following dataset + # one at a time. + if orientation == "vertical": + convert_units = self.convert_xunits + x = [*self._process_unit_info([("x", x[0])], kwargs), + *map(convert_units, x[1:])] + else: # horizontal + convert_units = self.convert_yunits + x = [*self._process_unit_info([("y", x[0])], kwargs), + *map(convert_units, x[1:])] + + if bin_range is not None: + bin_range = convert_units(bin_range) + + if not cbook.is_scalar_or_string(bins): + bins = convert_units(bins) + + # We need to do to 'weights' what was done to 'x' + if weights is not None: + w = cbook._reshape_2D(weights, 'weights') + else: + w = [None] * nx + + if len(w) != nx: + raise ValueError('weights should have the same shape as x') + + input_empty = True + for xi, wi in zip(x, w): + len_xi = len(xi) + if wi is not None and len(wi) != len_xi: + raise ValueError('weights should have the same shape as x') + if len_xi: + input_empty = False + + if color is None: + colors = [self._get_lines.get_next_color() for i in range(nx)] + else: + colors = mcolors.to_rgba_array(color) + if len(colors) != nx: + raise ValueError(f"The 'color' keyword argument must have one " + f"color per dataset, but {nx} datasets and " + f"{len(colors)} colors were provided") + + hist_kwargs = dict() + + # if the bin_range is not given, compute without nan numpy + # does not do this for us when guessing the range (but will + # happily ignore nans when computing the histogram). + if bin_range is None: + xmin = np.inf + xmax = -np.inf + for xi in x: + if len(xi): + # python's min/max ignore nan, + # np.minnan returns nan for all nan input + xmin = min(xmin, np.nanmin(xi)) + xmax = max(xmax, np.nanmax(xi)) + if xmin <= xmax: # Only happens if we have seen a finite value. + bin_range = (xmin, xmax) + + # If bins are not specified either explicitly or via range, + # we need to figure out the range required for all datasets, + # and supply that to np.histogram. + if not input_empty and len(x) > 1: + if weights is not None: + _w = np.concatenate(w) + else: + _w = None + bins = np.histogram_bin_edges( + np.concatenate(x), bins, bin_range, _w) + else: + hist_kwargs['range'] = bin_range + + density = bool(density) + if density and not stacked: + hist_kwargs['density'] = density + + # List to store all the top coordinates of the histograms + tops = [] # Will have shape (n_datasets, n_bins). + # Loop through datasets + for i in range(nx): + # this will automatically overwrite bins, + # so that each histogram uses the same bins + m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs) + tops.append(m) + tops = np.array(tops, float) # causes problems later if it's an int + bins = np.array(bins, float) # causes problems if float16 + if stacked: + tops = tops.cumsum(axis=0) + # If a stacked density plot, normalize so the area of all the + # stacked histograms together is 1 + if density: + tops = (tops / np.diff(bins)) / tops[-1].sum() + if cumulative: + slc = slice(None) + if isinstance(cumulative, Number) and cumulative < 0: + slc = slice(None, None, -1) + if density: + tops = (tops * np.diff(bins))[:, slc].cumsum(axis=1)[:, slc] + else: + tops = tops[:, slc].cumsum(axis=1)[:, slc] + + patches = [] + + if histtype.startswith('bar'): + + totwidth = np.diff(bins) + + if rwidth is not None: + dr = np.clip(rwidth, 0, 1) + elif (len(tops) > 1 and + ((not stacked) or mpl.rcParams['_internal.classic_mode'])): + dr = 0.8 + else: + dr = 1.0 + + if histtype == 'bar' and not stacked: + width = dr * totwidth / nx + dw = width + boffset = -0.5 * dr * totwidth * (1 - 1 / nx) + elif histtype == 'barstacked' or stacked: + width = dr * totwidth + boffset, dw = 0.0, 0.0 + + if align == 'mid': + boffset += 0.5 * totwidth + elif align == 'right': + boffset += totwidth + + if orientation == 'horizontal': + _barfunc = self.barh + bottom_kwarg = 'left' + else: # orientation == 'vertical' + _barfunc = self.bar + bottom_kwarg = 'bottom' + + for top, color in zip(tops, colors): + if bottom is None: + bottom = np.zeros(len(top)) + if stacked: + height = top - bottom + else: + height = top + bars = _barfunc(bins[:-1]+boffset, height, width, + align='center', log=log, + color=color, **{bottom_kwarg: bottom}) + patches.append(bars) + if stacked: + bottom = top + boffset += dw + # Remove stickies from all bars but the lowest ones, as otherwise + # margin expansion would be unable to cross the stickies in the + # middle of the bars. + for bars in patches[1:]: + for patch in bars: + patch.sticky_edges.x[:] = patch.sticky_edges.y[:] = [] + + elif histtype.startswith('step'): + # these define the perimeter of the polygon + x = np.zeros(4 * len(bins) - 3) + y = np.zeros(4 * len(bins) - 3) + + x[0:2*len(bins)-1:2], x[1:2*len(bins)-1:2] = bins, bins[:-1] + x[2*len(bins)-1:] = x[1:2*len(bins)-1][::-1] + + if bottom is None: + bottom = 0 + + y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = bottom + y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1] + + if log: + if orientation == 'horizontal': + self.set_xscale('log', nonpositive='clip') + else: # orientation == 'vertical' + self.set_yscale('log', nonpositive='clip') + + if align == 'left': + x -= 0.5*(bins[1]-bins[0]) + elif align == 'right': + x += 0.5*(bins[1]-bins[0]) + + # If fill kwarg is set, it will be passed to the patch collection, + # overriding this + fill = (histtype == 'stepfilled') + + xvals, yvals = [], [] + for top in tops: + if stacked: + # top of the previous polygon becomes the bottom + y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1] + # set the top of this polygon + y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = top + bottom + + # The starting point of the polygon has not yet been + # updated. So far only the endpoint was adjusted. This + # assignment closes the polygon. The redundant endpoint is + # later discarded (for step and stepfilled). + y[0] = y[-1] + + if orientation == 'horizontal': + xvals.append(y.copy()) + yvals.append(x.copy()) + else: + xvals.append(x.copy()) + yvals.append(y.copy()) + + # stepfill is closed, step is not + split = -1 if fill else 2 * len(bins) + # add patches in reverse order so that when stacking, + # items lower in the stack are plotted on top of + # items higher in the stack + for x, y, color in reversed(list(zip(xvals, yvals, colors))): + patches.append(self.fill( + x[:split], y[:split], + closed=True if fill else None, + facecolor=color, + edgecolor=None if fill else color, + fill=fill if fill else None, + zorder=None if fill else mlines.Line2D.zorder)) + for patch_list in patches: + for patch in patch_list: + if orientation == 'vertical': + patch.sticky_edges.y.append(0) + elif orientation == 'horizontal': + patch.sticky_edges.x.append(0) + + # we return patches, so put it back in the expected order + patches.reverse() + + # If None, make all labels None (via zip_longest below); otherwise, + # cast each element to str, but keep a single str as it. + labels = [] if label is None else np.atleast_1d(np.asarray(label, str)) + for patch, lbl in itertools.zip_longest(patches, labels): + if patch: + p = patch[0] + p._internal_update(kwargs) + if lbl is not None: + p.set_label(lbl) + for p in patch[1:]: + p._internal_update(kwargs) + p.set_label('_nolegend_') + + if nx == 1: + return tops[0], bins, patches[0] + else: + patch_type = ("BarContainer" if histtype.startswith("bar") + else "list[Polygon]") + return tops, bins, cbook.silent_list(patch_type, patches) + + @_preprocess_data() + def stairs(self, values, edges=None, *, + orientation='vertical', baseline=0, fill=False, **kwargs): + """ + Draw a stepwise constant function as a line or a filled plot. + + *edges* define the x-axis positions of the steps. *values* the function values + between these steps. Depending on *fill*, the function is drawn either as a + continuous line with vertical segments at the edges, or as a filled area. + + Parameters + ---------- + values : array-like + The step heights. + + edges : array-like + The step positions, with ``len(edges) == len(vals) + 1``, + between which the curve takes on vals values. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + The direction of the steps. Vertical means that *values* are along + the y-axis, and edges are along the x-axis. + + baseline : float, array-like or None, default: 0 + The bottom value of the bounding edges or when + ``fill=True``, position of lower edge. If *fill* is + True or an array is passed to *baseline*, a closed + path is drawn. + + fill : bool, default: False + Whether the area under the step curve should be filled. + + Returns + ------- + StepPatch : `~matplotlib.patches.StepPatch` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + `~matplotlib.patches.StepPatch` properties + + """ + + if 'color' in kwargs: + _color = kwargs.pop('color') + else: + _color = self._get_lines.get_next_color() + if fill: + kwargs.setdefault('linewidth', 0) + kwargs.setdefault('facecolor', _color) + else: + kwargs.setdefault('edgecolor', _color) + + if edges is None: + edges = np.arange(len(values) + 1) + + edges, values, baseline = self._process_unit_info( + [("x", edges), ("y", values), ("y", baseline)], kwargs) + + patch = mpatches.StepPatch(values, + edges, + baseline=baseline, + orientation=orientation, + fill=fill, + **kwargs) + self.add_patch(patch) + if baseline is None: + baseline = 0 + if orientation == 'vertical': + patch.sticky_edges.y.append(np.min(baseline)) + self.update_datalim([(edges[0], np.min(baseline))]) + else: + patch.sticky_edges.x.append(np.min(baseline)) + self.update_datalim([(np.min(baseline), edges[0])]) + self._request_autoscale_view() + return patch + + @_preprocess_data(replace_names=["x", "y", "weights"]) + @_docstring.dedent_interpd + def hist2d(self, x, y, bins=10, range=None, density=False, weights=None, + cmin=None, cmax=None, **kwargs): + """ + Make a 2D histogram plot. + + Parameters + ---------- + x, y : array-like, shape (n, ) + Input values + + bins : None or int or [int, int] or array-like or [array, array] + + The bin specification: + + - If int, the number of bins for the two dimensions + (``nx = ny = bins``). + - If ``[int, int]``, the number of bins in each dimension + (``nx, ny = bins``). + - If array-like, the bin edges for the two dimensions + (``x_edges = y_edges = bins``). + - If ``[array, array]``, the bin edges in each dimension + (``x_edges, y_edges = bins``). + + The default value is 10. + + range : array-like shape(2, 2), optional + The leftmost and rightmost edges of the bins along each dimension + (if not specified explicitly in the bins parameters): ``[[xmin, + xmax], [ymin, ymax]]``. All values outside of this range will be + considered outliers and not tallied in the histogram. + + density : bool, default: False + Normalize histogram. See the documentation for the *density* + parameter of `~.Axes.hist` for more details. + + weights : array-like, shape (n, ), optional + An array of values w_i weighing each sample (x_i, y_i). + + cmin, cmax : float, default: None + All bins that has count less than *cmin* or more than *cmax* will not be + displayed (set to NaN before passing to `~.Axes.pcolormesh`) and these count + values in the return value count histogram will also be set to nan upon + return. + + Returns + ------- + h : 2D array + The bi-dimensional histogram of samples x and y. Values in x are + histogrammed along the first dimension and values in y are + histogrammed along the second dimension. + xedges : 1D array + The bin edges along the x-axis. + yedges : 1D array + The bin edges along the y-axis. + image : `~.matplotlib.collections.QuadMesh` + + Other Parameters + ---------------- + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + alpha : ``0 <= scalar <= 1`` or ``None``, optional + The alpha blending value. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed along to the + `~.Axes.pcolormesh` method and `~matplotlib.collections.QuadMesh` + constructor. + + See Also + -------- + hist : 1D histogram plotting + hexbin : 2D histogram with hexagonal bins + + Notes + ----- + - Currently ``hist2d`` calculates its own axis limits, and any limits + previously set are ignored. + - Rendering the histogram with a logarithmic color scale is + accomplished by passing a `.colors.LogNorm` instance to the *norm* + keyword argument. Likewise, power-law normalization (similar + in effect to gamma correction) can be accomplished with + `.colors.PowerNorm`. + """ + + h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=range, + density=density, weights=weights) + + if cmin is not None: + h[h < cmin] = None + if cmax is not None: + h[h > cmax] = None + + pc = self.pcolormesh(xedges, yedges, h.T, **kwargs) + self.set_xlim(xedges[0], xedges[-1]) + self.set_ylim(yedges[0], yedges[-1]) + + return h, xedges, yedges, pc + + @_preprocess_data(replace_names=["x", "weights"], label_namer="x") + @_docstring.dedent_interpd + def ecdf(self, x, weights=None, *, complementary=False, + orientation="vertical", compress=False, **kwargs): + """ + Compute and plot the empirical cumulative distribution function of *x*. + + .. versionadded:: 3.8 + + Parameters + ---------- + x : 1d array-like + The input data. Infinite entries are kept (and move the relevant + end of the ecdf from 0/1), but NaNs and masked values are errors. + + weights : 1d array-like or None, default: None + The weights of the entries; must have the same shape as *x*. + Weights corresponding to NaN data points are dropped, and then the + remaining weights are normalized to sum to 1. If unset, all + entries have the same weight. + + complementary : bool, default: False + Whether to plot a cumulative distribution function, which increases + from 0 to 1 (the default), or a complementary cumulative + distribution function, which decreases from 1 to 0. + + orientation : {"vertical", "horizontal"}, default: "vertical" + Whether the entries are plotted along the x-axis ("vertical", the + default) or the y-axis ("horizontal"). This parameter takes the + same values as in `~.Axes.hist`. + + compress : bool, default: False + Whether multiple entries with the same values are grouped together + (with a summed weight) before plotting. This is mainly useful if + *x* contains many identical data points, to decrease the rendering + complexity of the plot. If *x* contains no duplicate points, this + has no effect and just uses some time and memory. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + Returns + ------- + `.Line2D` + + Notes + ----- + The ecdf plot can be thought of as a cumulative histogram with one bin + per data entry; i.e. it reports on the entire dataset without any + arbitrary binning. + + If *x* contains NaNs or masked entries, either remove them first from + the array (if they should not taken into account), or replace them by + -inf or +inf (if they should be sorted at the beginning or the end of + the array). + """ + _api.check_in_list(["horizontal", "vertical"], orientation=orientation) + if "drawstyle" in kwargs or "ds" in kwargs: + raise TypeError("Cannot pass 'drawstyle' or 'ds' to ecdf()") + if np.ma.getmask(x).any(): + raise ValueError("ecdf() does not support masked entries") + x = np.asarray(x) + if np.isnan(x).any(): + raise ValueError("ecdf() does not support NaNs") + argsort = np.argsort(x) + x = x[argsort] + if weights is None: + # Ensure that we end at exactly 1, avoiding floating point errors. + cum_weights = (1 + np.arange(len(x))) / len(x) + else: + weights = np.take(weights, argsort) # Reorder weights like we reordered x. + cum_weights = np.cumsum(weights / np.sum(weights)) + if compress: + # Get indices of unique x values. + compress_idxs = [0, *(x[:-1] != x[1:]).nonzero()[0] + 1] + x = x[compress_idxs] + cum_weights = cum_weights[compress_idxs] + if orientation == "vertical": + if not complementary: + line, = self.plot([x[0], *x], [0, *cum_weights], + drawstyle="steps-post", **kwargs) + else: + line, = self.plot([*x, x[-1]], [1, *1 - cum_weights], + drawstyle="steps-pre", **kwargs) + line.sticky_edges.y[:] = [0, 1] + else: # orientation == "horizontal": + if not complementary: + line, = self.plot([0, *cum_weights], [x[0], *x], + drawstyle="steps-pre", **kwargs) + else: + line, = self.plot([1, *1 - cum_weights], [*x, x[-1]], + drawstyle="steps-post", **kwargs) + line.sticky_edges.x[:] = [0, 1] + return line + + @_preprocess_data(replace_names=["x"]) + @_docstring.dedent_interpd + def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, pad_to=None, + sides=None, scale_by_freq=None, return_line=None, **kwargs): + r""" + Plot the power spectral density. + + The power spectral density :math:`P_{xx}` by Welch's average + periodogram method. The vector *x* is divided into *NFFT* length + segments. Each segment is detrended by function *detrend* and + windowed by function *window*. *noverlap* gives the length of + the overlap between segments. The :math:`|\mathrm{fft}(i)|^2` + of each segment :math:`i` are averaged to compute :math:`P_{xx}`, + with a scaling to correct for power loss due to windowing. + + If len(*x*) < *NFFT*, it will be zero padded to *NFFT*. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data + + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between segments. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + return_line : bool, default: False + Whether to include the line object plotted in the returned values. + + Returns + ------- + Pxx : 1-D array + The values for the power spectrum :math:`P_{xx}` before scaling + (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *Pxx*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + Only returned if *return_line* is True. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + specgram + Differs in the default overlap; in not returning the mean of the + segment periodograms; in returning the times of the segments; and + in plotting a colormap instead of a line. + magnitude_spectrum + Plots the magnitude spectrum. + csd + Plots the spectral density between two signals. + + Notes + ----- + For plotting, the power is plotted as + :math:`10\log_{10}(P_{xx})` for decibels, though *Pxx* itself + is returned. + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + if Fc is None: + Fc = 0 + + pxx, freqs = mlab.psd(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, pad_to=pad_to, + sides=sides, scale_by_freq=scale_by_freq) + freqs += Fc + + if scale_by_freq in (None, True): + psd_units = 'dB/Hz' + else: + psd_units = 'dB' + + line = self.plot(freqs, 10 * np.log10(pxx), **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Power Spectral Density (%s)' % psd_units) + self.grid(True) + + vmin, vmax = self.get_ybound() + step = max(10 * int(np.log10(vmax - vmin)), 1) + ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) + self.set_yticks(ticks) + + if return_line is None or not return_line: + return pxx, freqs + else: + return pxx, freqs, line + + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + @_docstring.dedent_interpd + def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, pad_to=None, + sides=None, scale_by_freq=None, return_line=None, **kwargs): + r""" + Plot the cross-spectral density. + + The cross spectral density :math:`P_{xy}` by Welch's average + periodogram method. The vectors *x* and *y* are divided into + *NFFT* length segments. Each segment is detrended by function + *detrend* and windowed by function *window*. *noverlap* gives + the length of the overlap between segments. The product of + the direct FFTs of *x* and *y* are averaged over each segment + to compute :math:`P_{xy}`, with a scaling to correct for power + loss due to windowing. + + If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero + padded to *NFFT*. + + Parameters + ---------- + x, y : 1-D arrays or sequences + Arrays or sequences containing the data. + + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between segments. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + return_line : bool, default: False + Whether to include the line object plotted in the returned values. + + Returns + ------- + Pxy : 1-D array + The values for the cross spectrum :math:`P_{xy}` before scaling + (complex valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *Pxy*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + Only returned if *return_line* is True. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + psd : is equivalent to setting ``y = x``. + + Notes + ----- + For plotting, the power is plotted as + :math:`10 \log_{10}(P_{xy})` for decibels, though :math:`P_{xy}` itself + is returned. + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + if Fc is None: + Fc = 0 + + pxy, freqs = mlab.csd(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, pad_to=pad_to, + sides=sides, scale_by_freq=scale_by_freq) + # pxy is complex + freqs += Fc + + line = self.plot(freqs, 10 * np.log10(np.abs(pxy)), **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Cross Spectrum Magnitude (dB)') + self.grid(True) + + vmin, vmax = self.get_ybound() + step = max(10 * int(np.log10(vmax - vmin)), 1) + ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) + self.set_yticks(ticks) + + if return_line is None or not return_line: + return pxy, freqs + else: + return pxy, freqs, line + + @_preprocess_data(replace_names=["x"]) + @_docstring.dedent_interpd + def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, scale=None, + **kwargs): + """ + Plot the magnitude spectrum. + + Compute the magnitude spectrum of *x*. Data is padded to a + length of *pad_to* and the windowing function *window* is applied to + the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(Single_Spectrum)s + + scale : {'default', 'linear', 'dB'} + The scaling of the values in the *spec*. 'linear' is no scaling. + 'dB' returns the values in dB scale, i.e., the dB amplitude + (20 * log10). 'default' is 'linear'. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the magnitude spectrum before scaling (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + psd + Plots the power spectral density. + angle_spectrum + Plots the angles of the corresponding frequencies. + phase_spectrum + Plots the phase (unwrapped angle) of the corresponding frequencies. + specgram + Can plot the magnitude spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.magnitude_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + yunits = _api.check_getitem( + {None: 'energy', 'default': 'energy', 'linear': 'energy', + 'dB': 'dB'}, + scale=scale) + if yunits == 'energy': + Z = spec + else: # yunits == 'dB' + Z = 20. * np.log10(spec) + + line, = self.plot(freqs, Z, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Magnitude (%s)' % yunits) + + return spec, freqs, line + + @_preprocess_data(replace_names=["x"]) + @_docstring.dedent_interpd + def angle_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, **kwargs): + """ + Plot the angle spectrum. + + Compute the angle spectrum (wrapped phase spectrum) of *x*. + Data is padded to a length of *pad_to* and the windowing function + *window* is applied to the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(Single_Spectrum)s + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the angle spectrum in radians (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + magnitude_spectrum + Plots the magnitudes of the corresponding frequencies. + phase_spectrum + Plots the unwrapped version of this function. + specgram + Can plot the angle spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.angle_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + lines = self.plot(freqs, spec, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Angle (radians)') + + return spec, freqs, lines[0] + + @_preprocess_data(replace_names=["x"]) + @_docstring.dedent_interpd + def phase_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, **kwargs): + """ + Plot the phase spectrum. + + Compute the phase spectrum (unwrapped angle spectrum) of *x*. + Data is padded to a length of *pad_to* and the windowing function + *window* is applied to the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data + + %(Spectral)s + + %(Single_Spectrum)s + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the phase spectrum in radians (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + magnitude_spectrum + Plots the magnitudes of the corresponding frequencies. + angle_spectrum + Plots the wrapped version of this function. + specgram + Can plot the phase spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.phase_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + lines = self.plot(freqs, spec, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Phase (radians)') + + return spec, freqs, lines[0] + + @_preprocess_data(replace_names=["x", "y"]) + @_docstring.dedent_interpd + def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, + window=mlab.window_hanning, noverlap=0, pad_to=None, + sides='default', scale_by_freq=None, **kwargs): + r""" + Plot the coherence between *x* and *y*. + + Coherence is the normalized cross spectral density: + + .. math:: + + C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}} + + Parameters + ---------- + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between blocks. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + Cxy : 1-D array + The coherence vector. + + freqs : 1-D array + The frequencies for the elements in *Cxy*. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + cxy, freqs = mlab.cohere(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, + scale_by_freq=scale_by_freq, sides=sides, + pad_to=pad_to) + freqs += Fc + + self.plot(freqs, cxy, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Coherence') + self.grid(True) + + return cxy, freqs + + @_preprocess_data(replace_names=["x"]) + @_docstring.dedent_interpd + def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, + cmap=None, xextent=None, pad_to=None, sides=None, + scale_by_freq=None, mode=None, scale=None, + vmin=None, vmax=None, **kwargs): + """ + Plot a spectrogram. + + Compute and plot a spectrogram of data in *x*. Data are split into + *NFFT* length segments and the spectrum of each section is + computed. The windowing function *window* is applied to each + segment, and the amount of overlap of each segment is + specified with *noverlap*. The spectrogram is plotted as a colormap + (using imshow). + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(PSD)s + + mode : {'default', 'psd', 'magnitude', 'angle', 'phase'} + What sort of spectrum to use. Default is 'psd', which takes the + power spectral density. 'magnitude' returns the magnitude + spectrum. 'angle' returns the phase spectrum without unwrapping. + 'phase' returns the phase spectrum with unwrapping. + + noverlap : int, default: 128 + The number of points of overlap between blocks. + + scale : {'default', 'linear', 'dB'} + The scaling of the values in the *spec*. 'linear' is no scaling. + 'dB' returns the values in dB scale. When *mode* is 'psd', + this is dB power (10 * log10). Otherwise, this is dB amplitude + (20 * log10). 'default' is 'dB' if *mode* is 'psd' or + 'magnitude' and 'linear' otherwise. This must be 'linear' + if *mode* is 'angle' or 'phase'. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + cmap : `.Colormap`, default: :rc:`image.cmap` + + xextent : *None* or (xmin, xmax) + The image extent along the x-axis. The default sets *xmin* to the + left border of the first bin (*spectrum* column) and *xmax* to the + right border of the last bin. Note that for *noverlap>0* the width + of the bins is smaller than those of the segments. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional keyword arguments are passed on to `~.axes.Axes.imshow` + which makes the specgram image. The origin keyword argument + is not supported. + + Returns + ------- + spectrum : 2D array + Columns are the periodograms of successive segments. + + freqs : 1-D array + The frequencies corresponding to the rows in *spectrum*. + + t : 1-D array + The times corresponding to midpoints of segments (i.e., the columns + in *spectrum*). + + im : `.AxesImage` + The image created by imshow containing the spectrogram. + + See Also + -------- + psd + Differs in the default overlap; in returning the mean of the + segment periodograms; in not returning times; and in generating a + line plot instead of colormap. + magnitude_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'magnitude'. Plots a line instead of a colormap. + angle_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'angle'. Plots a line instead of a colormap. + phase_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'phase'. Plots a line instead of a colormap. + + Notes + ----- + The parameters *detrend* and *scale_by_freq* do only apply when *mode* + is set to 'psd'. + """ + if NFFT is None: + NFFT = 256 # same default as in mlab.specgram() + if Fc is None: + Fc = 0 # same default as in mlab._spectral_helper() + if noverlap is None: + noverlap = 128 # same default as in mlab.specgram() + if Fs is None: + Fs = 2 # same default as in mlab._spectral_helper() + + if mode == 'complex': + raise ValueError('Cannot plot a complex specgram') + + if scale is None or scale == 'default': + if mode in ['angle', 'phase']: + scale = 'linear' + else: + scale = 'dB' + elif mode in ['angle', 'phase'] and scale == 'dB': + raise ValueError('Cannot use dB scale with angle or phase mode') + + spec, freqs, t = mlab.specgram(x=x, NFFT=NFFT, Fs=Fs, + detrend=detrend, window=window, + noverlap=noverlap, pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + mode=mode) + + if scale == 'linear': + Z = spec + elif scale == 'dB': + if mode is None or mode == 'default' or mode == 'psd': + Z = 10. * np.log10(spec) + else: + Z = 20. * np.log10(spec) + else: + raise ValueError(f'Unknown scale {scale!r}') + + Z = np.flipud(Z) + + if xextent is None: + # padding is needed for first and last segment: + pad_xextent = (NFFT-noverlap) / Fs / 2 + xextent = np.min(t) - pad_xextent, np.max(t) + pad_xextent + xmin, xmax = xextent + freqs += Fc + extent = xmin, xmax, freqs[0], freqs[-1] + + if 'origin' in kwargs: + raise _api.kwarg_error("specgram", "origin") + + im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax, + origin='upper', **kwargs) + self.axis('auto') + + return spec, freqs, t, im + + @_docstring.dedent_interpd + def spy(self, Z, precision=0, marker=None, markersize=None, + aspect='equal', origin="upper", **kwargs): + """ + Plot the sparsity pattern of a 2D array. + + This visualizes the non-zero values of the array. + + Two plotting styles are available: image and marker. Both + are available for full arrays, but only the marker style + works for `scipy.sparse.spmatrix` instances. + + **Image style** + + If *marker* and *markersize* are *None*, `~.Axes.imshow` is used. Any + extra remaining keyword arguments are passed to this method. + + **Marker style** + + If *Z* is a `scipy.sparse.spmatrix` or *marker* or *markersize* are + *None*, a `.Line2D` object will be returned with the value of marker + determining the marker type, and any remaining keyword arguments + passed to `~.Axes.plot`. + + Parameters + ---------- + Z : (M, N) array-like + The array to be plotted. + + precision : float or 'present', default: 0 + If *precision* is 0, any non-zero value will be plotted. Otherwise, + values of :math:`|Z| > precision` will be plotted. + + For `scipy.sparse.spmatrix` instances, you can also + pass 'present'. In this case any value present in the array + will be plotted, even if it is identically zero. + + aspect : {'equal', 'auto', None} or float, default: 'equal' + The aspect ratio of the Axes. This parameter is particularly + relevant for images since it determines whether data pixels are + square. + + This parameter is a shortcut for explicitly calling + `.Axes.set_aspect`. See there for further details. + + - 'equal': Ensures an aspect ratio of 1. Pixels will be square. + - 'auto': The Axes is kept fixed and the aspect is adjusted so + that the data fit in the Axes. In general, this will result in + non-square pixels. + - *None*: Use :rc:`image.aspect`. + + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Place the [0, 0] index of the array in the upper left or lower left + corner of the Axes. The convention 'upper' is typically used for + matrices and images. + + Returns + ------- + `~matplotlib.image.AxesImage` or `.Line2D` + The return type depends on the plotting style (see above). + + Other Parameters + ---------------- + **kwargs + The supported additional parameters depend on the plotting style. + + For the image style, you can pass the following additional + parameters of `~.Axes.imshow`: + + - *cmap* + - *alpha* + - *url* + - any `.Artist` properties (passed on to the `.AxesImage`) + + For the marker style, you can pass any `.Line2D` property except + for *linestyle*: + + %(Line2D:kwdoc)s + """ + if marker is None and markersize is None and hasattr(Z, 'tocoo'): + marker = 's' + _api.check_in_list(["upper", "lower"], origin=origin) + if marker is None and markersize is None: + Z = np.asarray(Z) + mask = np.abs(Z) > precision + + if 'cmap' not in kwargs: + kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'], + name='binary') + if 'interpolation' in kwargs: + raise _api.kwarg_error("spy", "interpolation") + if 'norm' not in kwargs: + kwargs['norm'] = mcolors.NoNorm() + ret = self.imshow(mask, interpolation='nearest', + aspect=aspect, origin=origin, + **kwargs) + else: + if hasattr(Z, 'tocoo'): + c = Z.tocoo() + if precision == 'present': + y = c.row + x = c.col + else: + nonzero = np.abs(c.data) > precision + y = c.row[nonzero] + x = c.col[nonzero] + else: + Z = np.asarray(Z) + nonzero = np.abs(Z) > precision + y, x = np.nonzero(nonzero) + if marker is None: + marker = 's' + if markersize is None: + markersize = 10 + if 'linestyle' in kwargs: + raise _api.kwarg_error("spy", "linestyle") + ret = mlines.Line2D( + x, y, linestyle='None', marker=marker, markersize=markersize, + **kwargs) + self.add_line(ret) + nr, nc = Z.shape + self.set_xlim(-0.5, nc - 0.5) + if origin == "upper": + self.set_ylim(nr - 0.5, -0.5) + else: + self.set_ylim(-0.5, nr - 0.5) + self.set_aspect(aspect) + self.title.set_y(1.05) + if origin == "upper": + self.xaxis.tick_top() + else: # lower + self.xaxis.tick_bottom() + self.xaxis.set_ticks_position('both') + self.xaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + self.yaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + return ret + + def matshow(self, Z, **kwargs): + """ + Plot the values of a 2D matrix or array as color-coded image. + + The matrix will be shown the way it would be printed, with the first + row at the top. Row and column numbering is zero-based. + + Parameters + ---------- + Z : (M, N) array-like + The matrix to be displayed. + + Returns + ------- + `~matplotlib.image.AxesImage` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.axes.Axes.imshow` arguments + + See Also + -------- + imshow : More general function to plot data on a 2D regular raster. + + Notes + ----- + This is just a convenience function wrapping `.imshow` to set useful + defaults for displaying a matrix. In particular: + + - Set ``origin='upper'``. + - Set ``interpolation='nearest'``. + - Set ``aspect='equal'``. + - Ticks are placed to the left and above. + - Ticks are formatted to show integer indices. + + """ + Z = np.asanyarray(Z) + kw = {'origin': 'upper', + 'interpolation': 'nearest', + 'aspect': 'equal', # (already the imshow default) + **kwargs} + im = self.imshow(Z, **kw) + self.title.set_y(1.05) + self.xaxis.tick_top() + self.xaxis.set_ticks_position('both') + self.xaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + self.yaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + return im + + @_preprocess_data(replace_names=["dataset"]) + def violinplot(self, dataset, positions=None, vert=True, widths=0.5, + showmeans=False, showextrema=True, showmedians=False, + quantiles=None, points=100, bw_method=None, side='both'): + """ + Make a violin plot. + + Make a violin plot for each column of *dataset* or each vector in + sequence *dataset*. Each filled area extends to represent the + entire data range, with optional lines at the mean, the median, + the minimum, the maximum, and user-specified quantiles. + + Parameters + ---------- + dataset : Array or a sequence of vectors. + The input data. + + positions : array-like, default: [1, 2, ..., n] + The positions of the violins; i.e. coordinates on the x-axis for + vertical violins (or y-axis for horizontal violins). + + vert : bool, default: True. + If true, creates a vertical violin plot. + Otherwise, creates a horizontal violin plot. + + widths : float or array-like, default: 0.5 + The maximum width of each violin in units of the *positions* axis. + The default is 0.5, which is half the available space when using default + *positions*. + + showmeans : bool, default: False + Whether to show the mean with a line. + + showextrema : bool, default: True + Whether to show extrema with a line. + + showmedians : bool, default: False + Whether to show the median with a line. + + quantiles : array-like, default: None + If not None, set a list of floats in interval [0, 1] for each violin, + which stands for the quantiles that will be rendered for that + violin. + + points : int, default: 100 + The number of points to evaluate each of the gaussian kernel density + estimations at. + + bw_method : {'scott', 'silverman'} or float or callable, default: 'scott' + The method used to calculate the estimator bandwidth. If a + float, this will be used directly as `kde.factor`. If a + callable, it should take a `matplotlib.mlab.GaussianKDE` instance as + its only parameter and return a float. + + side : {'both', 'low', 'high'}, default: 'both' + 'both' plots standard violins. 'low'/'high' only + plots the side below/above the positions value. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + dict + A dictionary mapping each component of the violinplot to a + list of the corresponding collection instances created. The + dictionary has the following keys: + + - ``bodies``: A list of the `~.collections.PolyCollection` + instances containing the filled area of each violin. + + - ``cmeans``: A `~.collections.LineCollection` instance that marks + the mean values of each of the violin's distribution. + + - ``cmins``: A `~.collections.LineCollection` instance that marks + the bottom of each violin's distribution. + + - ``cmaxes``: A `~.collections.LineCollection` instance that marks + the top of each violin's distribution. + + - ``cbars``: A `~.collections.LineCollection` instance that marks + the centers of each violin's distribution. + + - ``cmedians``: A `~.collections.LineCollection` instance that + marks the median values of each of the violin's distribution. + + - ``cquantiles``: A `~.collections.LineCollection` instance created + to identify the quantile values of each of the violin's + distribution. + + See Also + -------- + .Axes.violin : Draw a violin from pre-computed statistics. + boxplot : Draw a box and whisker plot. + """ + + def _kde_method(X, coords): + # Unpack in case of e.g. Pandas or xarray object + X = cbook._unpack_to_numpy(X) + # fallback gracefully if the vector contains only one value + if np.all(X[0] == X): + return (X[0] == coords).astype(float) + kde = mlab.GaussianKDE(X, bw_method) + return kde.evaluate(coords) + + vpstats = cbook.violin_stats(dataset, _kde_method, points=points, + quantiles=quantiles) + return self.violin(vpstats, positions=positions, vert=vert, + widths=widths, showmeans=showmeans, + showextrema=showextrema, showmedians=showmedians, side=side) + + def violin(self, vpstats, positions=None, vert=True, widths=0.5, + showmeans=False, showextrema=True, showmedians=False, side='both'): + """ + Draw a violin plot from pre-computed statistics. + + Draw a violin plot for each column of *vpstats*. Each filled area + extends to represent the entire data range, with optional lines at the + mean, the median, the minimum, the maximum, and the quantiles values. + + Parameters + ---------- + vpstats : list of dicts + A list of dictionaries containing stats for each violin plot. + Required keys are: + + - ``coords``: A list of scalars containing the coordinates that + the violin's kernel density estimate were evaluated at. + + - ``vals``: A list of scalars containing the values of the + kernel density estimate at each of the coordinates given + in *coords*. + + - ``mean``: The mean value for this violin's dataset. + + - ``median``: The median value for this violin's dataset. + + - ``min``: The minimum value for this violin's dataset. + + - ``max``: The maximum value for this violin's dataset. + + Optional keys are: + + - ``quantiles``: A list of scalars containing the quantile values + for this violin's dataset. + + positions : array-like, default: [1, 2, ..., n] + The positions of the violins; i.e. coordinates on the x-axis for + vertical violins (or y-axis for horizontal violins). + + vert : bool, default: True. + If true, plots the violins vertically. + Otherwise, plots the violins horizontally. + + widths : float or array-like, default: 0.5 + The maximum width of each violin in units of the *positions* axis. + The default is 0.5, which is half available space when using default + *positions*. + + showmeans : bool, default: False + Whether to show the mean with a line. + + showextrema : bool, default: True + Whether to show extrema with a line. + + showmedians : bool, default: False + Whether to show the median with a line. + + side : {'both', 'low', 'high'}, default: 'both' + 'both' plots standard violins. 'low'/'high' only + plots the side below/above the positions value. + + Returns + ------- + dict + A dictionary mapping each component of the violinplot to a + list of the corresponding collection instances created. The + dictionary has the following keys: + + - ``bodies``: A list of the `~.collections.PolyCollection` + instances containing the filled area of each violin. + + - ``cmeans``: A `~.collections.LineCollection` instance that marks + the mean values of each of the violin's distribution. + + - ``cmins``: A `~.collections.LineCollection` instance that marks + the bottom of each violin's distribution. + + - ``cmaxes``: A `~.collections.LineCollection` instance that marks + the top of each violin's distribution. + + - ``cbars``: A `~.collections.LineCollection` instance that marks + the centers of each violin's distribution. + + - ``cmedians``: A `~.collections.LineCollection` instance that + marks the median values of each of the violin's distribution. + + - ``cquantiles``: A `~.collections.LineCollection` instance created + to identify the quantiles values of each of the violin's + distribution. + + See Also + -------- + violin : + Draw a violin plot from data instead of pre-computed statistics. + """ + + # Statistical quantities to be plotted on the violins + means = [] + mins = [] + maxes = [] + medians = [] + quantiles = [] + + qlens = [] # Number of quantiles in each dataset. + + artists = {} # Collections to be returned + + N = len(vpstats) + datashape_message = ("List of violinplot statistics and `{0}` " + "values must have the same length") + + # Validate positions + if positions is None: + positions = range(1, N + 1) + elif len(positions) != N: + raise ValueError(datashape_message.format("positions")) + + # Validate widths + if np.isscalar(widths): + widths = [widths] * N + elif len(widths) != N: + raise ValueError(datashape_message.format("widths")) + + # Validate side + _api.check_in_list(["both", "low", "high"], side=side) + + # Calculate ranges for statistics lines (shape (2, N)). + line_ends = [[-0.25 if side in ['both', 'low'] else 0], + [0.25 if side in ['both', 'high'] else 0]] \ + * np.array(widths) + positions + + # Colors. + if mpl.rcParams['_internal.classic_mode']: + fillcolor = 'y' + linecolor = 'r' + else: + fillcolor = linecolor = self._get_lines.get_next_color() + + # Check whether we are rendering vertically or horizontally + if vert: + fill = self.fill_betweenx + if side in ['low', 'high']: + perp_lines = functools.partial(self.hlines, colors=linecolor, + capstyle='projecting') + par_lines = functools.partial(self.vlines, colors=linecolor, + capstyle='projecting') + else: + perp_lines = functools.partial(self.hlines, colors=linecolor) + par_lines = functools.partial(self.vlines, colors=linecolor) + else: + fill = self.fill_between + if side in ['low', 'high']: + perp_lines = functools.partial(self.vlines, colors=linecolor, + capstyle='projecting') + par_lines = functools.partial(self.hlines, colors=linecolor, + capstyle='projecting') + else: + perp_lines = functools.partial(self.vlines, colors=linecolor) + par_lines = functools.partial(self.hlines, colors=linecolor) + + # Render violins + bodies = [] + for stats, pos, width in zip(vpstats, positions, widths): + # The 0.5 factor reflects the fact that we plot from v-p to v+p. + vals = np.array(stats['vals']) + vals = 0.5 * width * vals / vals.max() + bodies += [fill(stats['coords'], + -vals + pos if side in ['both', 'low'] else pos, + vals + pos if side in ['both', 'high'] else pos, + facecolor=fillcolor, alpha=0.3)] + means.append(stats['mean']) + mins.append(stats['min']) + maxes.append(stats['max']) + medians.append(stats['median']) + q = stats.get('quantiles') # a list of floats, or None + if q is None: + q = [] + quantiles.extend(q) + qlens.append(len(q)) + artists['bodies'] = bodies + + if showmeans: # Render means + artists['cmeans'] = perp_lines(means, *line_ends) + if showextrema: # Render extrema + artists['cmaxes'] = perp_lines(maxes, *line_ends) + artists['cmins'] = perp_lines(mins, *line_ends) + artists['cbars'] = par_lines(positions, mins, maxes) + if showmedians: # Render medians + artists['cmedians'] = perp_lines(medians, *line_ends) + if quantiles: # Render quantiles: each width is repeated qlen times. + artists['cquantiles'] = perp_lines( + quantiles, *np.repeat(line_ends, qlens, axis=1)) + + return artists + + # Methods that are entirely implemented in other modules. + + table = _make_axes_method(mtable.table) + + # args can be either Y or y1, y2, ... and all should be replaced + stackplot = _preprocess_data()(_make_axes_method(mstack.stackplot)) + + streamplot = _preprocess_data( + replace_names=["x", "y", "u", "v", "start_points"])( + _make_axes_method(mstream.streamplot)) + + tricontour = _make_axes_method(mtri.tricontour) + tricontourf = _make_axes_method(mtri.tricontourf) + tripcolor = _make_axes_method(mtri.tripcolor) + triplot = _make_axes_method(mtri.triplot) + + def _get_aspect_ratio(self): + """ + Convenience method to calculate the aspect ratio of the Axes in + the display coordinate system. + """ + figure_size = self.get_figure().get_size_inches() + ll, ur = self.get_position() * figure_size + width, height = ur - ll + return height / (width * self.get_data_ratio()) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.pyi b/parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..76aaee77aff86498188d2534f3b214bde7e9d905 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.pyi @@ -0,0 +1,772 @@ +from matplotlib.axes._base import _AxesBase +from matplotlib.axes._secondary_axes import SecondaryAxis + +from matplotlib.artist import Artist +from matplotlib.backend_bases import RendererBase +from matplotlib.collections import ( + Collection, + LineCollection, + PathCollection, + PolyCollection, + EventCollection, + QuadMesh, +) +from matplotlib.colors import Colormap, Normalize +from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer +from matplotlib.contour import ContourSet, QuadContourSet +from matplotlib.image import AxesImage, PcolorImage +from matplotlib.legend import Legend +from matplotlib.legend_handler import HandlerBase +from matplotlib.lines import Line2D, AxLine +from matplotlib.mlab import GaussianKDE +from matplotlib.patches import Rectangle, FancyArrow, Polygon, StepPatch, Wedge +from matplotlib.quiver import Quiver, QuiverKey, Barbs +from matplotlib.text import Annotation, Text +from matplotlib.transforms import Transform, Bbox +import matplotlib.tri as mtri +import matplotlib.table as mtable +import matplotlib.stackplot as mstack +import matplotlib.streamplot as mstream + +import datetime +import PIL.Image +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Literal, overload +import numpy as np +from numpy.typing import ArrayLike +from matplotlib.typing import ColorType, MarkerType, LineStyleType + +class Axes(_AxesBase): + def get_title(self, loc: Literal["left", "center", "right"] = ...) -> str: ... + def set_title( + self, + label: str, + fontdict: dict[str, Any] | None = ..., + loc: Literal["left", "center", "right"] | None = ..., + pad: float | None = ..., + *, + y: float | None = ..., + **kwargs + ) -> Text: ... + def get_legend_handles_labels( + self, legend_handler_map: dict[type, HandlerBase] | None = ... + ) -> tuple[list[Artist], list[Any]]: ... + legend_: Legend | None + + @overload + def legend(self) -> Legend: ... + @overload + def legend(self, handles: Iterable[Artist | tuple[Artist, ...]], labels: Iterable[str], **kwargs) -> Legend: ... + @overload + def legend(self, *, handles: Iterable[Artist | tuple[Artist, ...]], **kwargs) -> Legend: ... + @overload + def legend(self, labels: Iterable[str], **kwargs) -> Legend: ... + @overload + def legend(self, **kwargs) -> Legend: ... + + def inset_axes( + self, + bounds: tuple[float, float, float, float], + *, + transform: Transform | None = ..., + zorder: float = ..., + **kwargs + ) -> Axes: ... + def indicate_inset( + self, + bounds: tuple[float, float, float, float], + inset_ax: Axes | None = ..., + *, + transform: Transform | None = ..., + facecolor: ColorType = ..., + edgecolor: ColorType = ..., + alpha: float = ..., + zorder: float = ..., + **kwargs + ) -> Rectangle: ... + def indicate_inset_zoom(self, inset_ax: Axes, **kwargs) -> Rectangle: ... + def secondary_xaxis( + self, + location: Literal["top", "bottom"] | float, + *, + functions: tuple[ + Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] + ] + | Transform + | None = ..., + transform: Transform | None = ..., + **kwargs + ) -> SecondaryAxis: ... + def secondary_yaxis( + self, + location: Literal["left", "right"] | float, + *, + functions: tuple[ + Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] + ] + | Transform + | None = ..., + transform: Transform | None = ..., + **kwargs + ) -> SecondaryAxis: ... + def text( + self, + x: float, + y: float, + s: str, + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> Text: ... + def annotate( + self, + text: str, + xy: tuple[float, float], + xytext: tuple[float, float] | None = ..., + xycoords: str + | Artist + | Transform + | Callable[[RendererBase], Bbox | Transform] + | tuple[float, float] = ..., + textcoords: str + | Artist + | Transform + | Callable[[RendererBase], Bbox | Transform] + | tuple[float, float] + | None = ..., + arrowprops: dict[str, Any] | None = ..., + annotation_clip: bool | None = ..., + **kwargs + ) -> Annotation: ... + def axhline( + self, y: float = ..., xmin: float = ..., xmax: float = ..., **kwargs + ) -> Line2D: ... + def axvline( + self, x: float = ..., ymin: float = ..., ymax: float = ..., **kwargs + ) -> Line2D: ... + + # TODO: Could separate the xy2 and slope signatures + def axline( + self, + xy1: tuple[float, float], + xy2: tuple[float, float] | None = ..., + *, + slope: float | None = ..., + **kwargs + ) -> AxLine: ... + def axhspan( + self, ymin: float, ymax: float, xmin: float = ..., xmax: float = ..., **kwargs + ) -> Rectangle: ... + def axvspan( + self, xmin: float, xmax: float, ymin: float = ..., ymax: float = ..., **kwargs + ) -> Rectangle: ... + def hlines( + self, + y: float | ArrayLike, + xmin: float | ArrayLike, + xmax: float | ArrayLike, + colors: ColorType | Sequence[ColorType] | None = ..., + linestyles: LineStyleType = ..., + label: str = ..., + *, + data=..., + **kwargs + ) -> LineCollection: ... + def vlines( + self, + x: float | ArrayLike, + ymin: float | ArrayLike, + ymax: float | ArrayLike, + colors: ColorType | Sequence[ColorType] | None = ..., + linestyles: LineStyleType = ..., + label: str = ..., + *, + data=..., + **kwargs + ) -> LineCollection: ... + def eventplot( + self, + positions: ArrayLike | Sequence[ArrayLike], + orientation: Literal["horizontal", "vertical"] = ..., + lineoffsets: float | Sequence[float] = ..., + linelengths: float | Sequence[float] = ..., + linewidths: float | Sequence[float] | None = ..., + colors: ColorType | Sequence[ColorType] | None = ..., + alpha: float | Sequence[float] | None = ..., + linestyles: LineStyleType | Sequence[LineStyleType] = ..., + *, + data=..., + **kwargs + ) -> EventCollection: ... + def plot( + self, + *args: float | ArrayLike | str, + scalex: bool = ..., + scaley: bool = ..., + data = ..., + **kwargs + ) -> list[Line2D]: ... + def plot_date( + self, + x: ArrayLike, + y: ArrayLike, + fmt: str = ..., + tz: str | datetime.tzinfo | None = ..., + xdate: bool = ..., + ydate: bool = ..., + *, + data=..., + **kwargs + ) -> list[Line2D]: ... + def loglog(self, *args, **kwargs) -> list[Line2D]: ... + def semilogx(self, *args, **kwargs) -> list[Line2D]: ... + def semilogy(self, *args, **kwargs) -> list[Line2D]: ... + def acorr( + self, x: ArrayLike, *, data=..., **kwargs + ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ... + def xcorr( + self, + x: ArrayLike, + y: ArrayLike, + normed: bool = ..., + detrend: Callable[[ArrayLike], ArrayLike] = ..., + usevlines: bool = ..., + maxlags: int = ..., + *, + data = ..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ... + def step( + self, + x: ArrayLike, + y: ArrayLike, + *args, + where: Literal["pre", "post", "mid"] = ..., + data = ..., + **kwargs + ) -> list[Line2D]: ... + def bar( + self, + x: float | ArrayLike, + height: float | ArrayLike, + width: float | ArrayLike = ..., + bottom: float | ArrayLike | None = ..., + *, + align: Literal["center", "edge"] = ..., + data = ..., + **kwargs + ) -> BarContainer: ... + def barh( + self, + y: float | ArrayLike, + width: float | ArrayLike, + height: float | ArrayLike = ..., + left: float | ArrayLike | None = ..., + *, + align: Literal["center", "edge"] = ..., + data = ..., + **kwargs + ) -> BarContainer: ... + def bar_label( + self, + container: BarContainer, + labels: ArrayLike | None = ..., + *, + fmt: str | Callable[[float], str] = ..., + label_type: Literal["center", "edge"] = ..., + padding: float = ..., + **kwargs + ) -> list[Annotation]: ... + def broken_barh( + self, + xranges: Sequence[tuple[float, float]], + yrange: tuple[float, float], + *, + data=..., + **kwargs + ) -> PolyCollection: ... + def stem( + self, + *args: ArrayLike | str, + linefmt: str | None = ..., + markerfmt: str | None = ..., + basefmt: str | None = ..., + bottom: float = ..., + label: str | None = ..., + orientation: Literal["vertical", "horizontal"] = ..., + data=..., + ) -> StemContainer: ... + + # TODO: data kwarg preprocessor? + def pie( + self, + x: ArrayLike, + explode: ArrayLike | None = ..., + labels: Sequence[str] | None = ..., + colors: ColorType | Sequence[ColorType] | None = ..., + autopct: str | Callable[[float], str] | None = ..., + pctdistance: float = ..., + shadow: bool = ..., + labeldistance: float | None = ..., + startangle: float = ..., + radius: float = ..., + counterclock: bool = ..., + wedgeprops: dict[str, Any] | None = ..., + textprops: dict[str, Any] | None = ..., + center: tuple[float, float] = ..., + frame: bool = ..., + rotatelabels: bool = ..., + *, + normalize: bool = ..., + hatch: str | Sequence[str] | None = ..., + data=..., + ) -> tuple[list[Wedge], list[Text]] | tuple[ + list[Wedge], list[Text], list[Text] + ]: ... + def errorbar( + self, + x: float | ArrayLike, + y: float | ArrayLike, + yerr: float | ArrayLike | None = ..., + xerr: float | ArrayLike | None = ..., + fmt: str = ..., + ecolor: ColorType | None = ..., + elinewidth: float | None = ..., + capsize: float | None = ..., + barsabove: bool = ..., + lolims: bool | ArrayLike = ..., + uplims: bool | ArrayLike = ..., + xlolims: bool | ArrayLike = ..., + xuplims: bool | ArrayLike = ..., + errorevery: int | tuple[int, int] = ..., + capthick: float | None = ..., + *, + data=..., + **kwargs + ) -> ErrorbarContainer: ... + def boxplot( + self, + x: ArrayLike | Sequence[ArrayLike], + notch: bool | None = ..., + sym: str | None = ..., + vert: bool | None = ..., + whis: float | tuple[float, float] | None = ..., + positions: ArrayLike | None = ..., + widths: float | ArrayLike | None = ..., + patch_artist: bool | None = ..., + bootstrap: int | None = ..., + usermedians: ArrayLike | None = ..., + conf_intervals: ArrayLike | None = ..., + meanline: bool | None = ..., + showmeans: bool | None = ..., + showcaps: bool | None = ..., + showbox: bool | None = ..., + showfliers: bool | None = ..., + boxprops: dict[str, Any] | None = ..., + tick_labels: Sequence[str] | None = ..., + flierprops: dict[str, Any] | None = ..., + medianprops: dict[str, Any] | None = ..., + meanprops: dict[str, Any] | None = ..., + capprops: dict[str, Any] | None = ..., + whiskerprops: dict[str, Any] | None = ..., + manage_ticks: bool = ..., + autorange: bool = ..., + zorder: float | None = ..., + capwidths: float | ArrayLike | None = ..., + label: Sequence[str] | None = ..., + *, + data=..., + ) -> dict[str, Any]: ... + def bxp( + self, + bxpstats: Sequence[dict[str, Any]], + positions: ArrayLike | None = ..., + widths: float | ArrayLike | None = ..., + vert: bool = ..., + patch_artist: bool = ..., + shownotches: bool = ..., + showmeans: bool = ..., + showcaps: bool = ..., + showbox: bool = ..., + showfliers: bool = ..., + boxprops: dict[str, Any] | None = ..., + whiskerprops: dict[str, Any] | None = ..., + flierprops: dict[str, Any] | None = ..., + medianprops: dict[str, Any] | None = ..., + capprops: dict[str, Any] | None = ..., + meanprops: dict[str, Any] | None = ..., + meanline: bool = ..., + manage_ticks: bool = ..., + zorder: float | None = ..., + capwidths: float | ArrayLike | None = ..., + label: Sequence[str] | None = ..., + ) -> dict[str, Any]: ... + def scatter( + self, + x: float | ArrayLike, + y: float | ArrayLike, + s: float | ArrayLike | None = ..., + c: ArrayLike | Sequence[ColorType] | ColorType | None = ..., + marker: MarkerType | None = ..., + cmap: str | Colormap | None = ..., + norm: str | Normalize | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + alpha: float | None = ..., + linewidths: float | Sequence[float] | None = ..., + *, + edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = ..., + plotnonfinite: bool = ..., + data=..., + **kwargs + ) -> PathCollection: ... + def hexbin( + self, + x: ArrayLike, + y: ArrayLike, + C: ArrayLike | None = ..., + gridsize: int | tuple[int, int] = ..., + bins: Literal["log"] | int | Sequence[float] | None = ..., + xscale: Literal["linear", "log"] = ..., + yscale: Literal["linear", "log"] = ..., + extent: tuple[float, float, float, float] | None = ..., + cmap: str | Colormap | None = ..., + norm: str | Normalize | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + alpha: float | None = ..., + linewidths: float | None = ..., + edgecolors: Literal["face", "none"] | ColorType = ..., + reduce_C_function: Callable[[np.ndarray | list[float]], float] = ..., + mincnt: int | None = ..., + marginals: bool = ..., + *, + data=..., + **kwargs + ) -> PolyCollection: ... + def arrow( + self, x: float, y: float, dx: float, dy: float, **kwargs + ) -> FancyArrow: ... + def quiverkey( + self, Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs + ) -> QuiverKey: ... + def quiver(self, *args, data=..., **kwargs) -> Quiver: ... + def barbs(self, *args, data=..., **kwargs) -> Barbs: ... + def fill(self, *args, data=..., **kwargs) -> list[Polygon]: ... + def fill_between( + self, + x: ArrayLike, + y1: ArrayLike | float, + y2: ArrayLike | float = ..., + where: Sequence[bool] | None = ..., + interpolate: bool = ..., + step: Literal["pre", "post", "mid"] | None = ..., + *, + data=..., + **kwargs + ) -> PolyCollection: ... + def fill_betweenx( + self, + y: ArrayLike, + x1: ArrayLike | float, + x2: ArrayLike | float = ..., + where: Sequence[bool] | None = ..., + step: Literal["pre", "post", "mid"] | None = ..., + interpolate: bool = ..., + *, + data=..., + **kwargs + ) -> PolyCollection: ... + def imshow( + self, + X: ArrayLike | PIL.Image.Image, + cmap: str | Colormap | None = ..., + norm: str | Normalize | None = ..., + *, + aspect: Literal["equal", "auto"] | float | None = ..., + interpolation: str | None = ..., + alpha: float | ArrayLike | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + origin: Literal["upper", "lower"] | None = ..., + extent: tuple[float, float, float, float] | None = ..., + interpolation_stage: Literal["data", "rgba"] | None = ..., + filternorm: bool = ..., + filterrad: float = ..., + resample: bool | None = ..., + url: str | None = ..., + data=..., + **kwargs + ) -> AxesImage: ... + def pcolor( + self, + *args: ArrayLike, + shading: Literal["flat", "nearest", "auto"] | None = ..., + alpha: float | None = ..., + norm: str | Normalize | None = ..., + cmap: str | Colormap | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + data=..., + **kwargs + ) -> Collection: ... + def pcolormesh( + self, + *args: ArrayLike, + alpha: float | None = ..., + norm: str | Normalize | None = ..., + cmap: str | Colormap | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + shading: Literal["flat", "nearest", "gouraud", "auto"] | None = ..., + antialiased: bool = ..., + data=..., + **kwargs + ) -> QuadMesh: ... + def pcolorfast( + self, + *args: ArrayLike | tuple[float, float], + alpha: float | None = ..., + norm: str | Normalize | None = ..., + cmap: str | Colormap | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + data=..., + **kwargs + ) -> AxesImage | PcolorImage | QuadMesh: ... + def contour(self, *args, data=..., **kwargs) -> QuadContourSet: ... + def contourf(self, *args, data=..., **kwargs) -> QuadContourSet: ... + def clabel( + self, CS: ContourSet, levels: ArrayLike | None = ..., **kwargs + ) -> list[Text]: ... + def hist( + self, + x: ArrayLike | Sequence[ArrayLike], + bins: int | Sequence[float] | str | None = ..., + range: tuple[float, float] | None = ..., + density: bool = ..., + weights: ArrayLike | None = ..., + cumulative: bool | float = ..., + bottom: ArrayLike | float | None = ..., + histtype: Literal["bar", "barstacked", "step", "stepfilled"] = ..., + align: Literal["left", "mid", "right"] = ..., + orientation: Literal["vertical", "horizontal"] = ..., + rwidth: float | None = ..., + log: bool = ..., + color: ColorType | Sequence[ColorType] | None = ..., + label: str | Sequence[str] | None = ..., + stacked: bool = ..., + *, + data=..., + **kwargs + ) -> tuple[ + np.ndarray | list[np.ndarray], + np.ndarray, + BarContainer | Polygon | list[BarContainer | Polygon], + ]: ... + def stairs( + self, + values: ArrayLike, + edges: ArrayLike | None = ..., + *, + orientation: Literal["vertical", "horizontal"] = ..., + baseline: float | ArrayLike | None = ..., + fill: bool = ..., + data=..., + **kwargs + ) -> StepPatch: ... + def hist2d( + self, + x: ArrayLike, + y: ArrayLike, + bins: None + | int + | tuple[int, int] + | ArrayLike + | tuple[ArrayLike, ArrayLike] = ..., + range: ArrayLike | None = ..., + density: bool = ..., + weights: ArrayLike | None = ..., + cmin: float | None = ..., + cmax: float | None = ..., + *, + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: ... + def ecdf( + self, + x: ArrayLike, + weights: ArrayLike | None = ..., + *, + complementary: bool=..., + orientation: Literal["vertical", "horizonatal"]=..., + compress: bool=..., + data=..., + **kwargs + ) -> Line2D: ... + def psd( + self, + x: ArrayLike, + NFFT: int | None = ..., + Fs: float | None = ..., + Fc: int | None = ..., + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + noverlap: int | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + scale_by_freq: bool | None = ..., + return_line: bool | None = ..., + *, + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ... + def csd( + self, + x: ArrayLike, + y: ArrayLike, + NFFT: int | None = ..., + Fs: float | None = ..., + Fc: int | None = ..., + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + noverlap: int | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + scale_by_freq: bool | None = ..., + return_line: bool | None = ..., + *, + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ... + def magnitude_spectrum( + self, + x: ArrayLike, + Fs: float | None = ..., + Fc: int | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + scale: Literal["default", "linear", "dB"] | None = ..., + *, + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, Line2D]: ... + def angle_spectrum( + self, + x: ArrayLike, + Fs: float | None = ..., + Fc: int | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + *, + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, Line2D]: ... + def phase_spectrum( + self, + x: ArrayLike, + Fs: float | None = ..., + Fc: int | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + *, + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, Line2D]: ... + def cohere( + self, + x: ArrayLike, + y: ArrayLike, + NFFT: int = ..., + Fs: float = ..., + Fc: int = ..., + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike = ..., + noverlap: int = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] = ..., + scale_by_freq: bool | None = ..., + *, + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray]: ... + def specgram( + self, + x: ArrayLike, + NFFT: int | None = ..., + Fs: float | None = ..., + Fc: int | None = ..., + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + noverlap: int | None = ..., + cmap: str | Colormap | None = ..., + xextent: tuple[float, float] | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + scale_by_freq: bool | None = ..., + mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = ..., + scale: Literal["default", "linear", "dB"] | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + *, + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: ... + def spy( + self, + Z: ArrayLike, + precision: float | Literal["present"] = ..., + marker: str | None = ..., + markersize: float | None = ..., + aspect: Literal["equal", "auto"] | float | None = ..., + origin: Literal["upper", "lower"] = ..., + **kwargs + ) -> AxesImage: ... + def matshow(self, Z: ArrayLike, **kwargs) -> AxesImage: ... + def violinplot( + self, + dataset: ArrayLike | Sequence[ArrayLike], + positions: ArrayLike | None = ..., + vert: bool = ..., + widths: float | ArrayLike = ..., + showmeans: bool = ..., + showextrema: bool = ..., + showmedians: bool = ..., + quantiles: Sequence[float | Sequence[float]] | None = ..., + points: int = ..., + bw_method: Literal["scott", "silverman"] + | float + | Callable[[GaussianKDE], float] + | None = ..., + side: Literal["both", "low", "high"] = ..., + *, + data=..., + ) -> dict[str, Collection]: ... + def violin( + self, + vpstats: Sequence[dict[str, Any]], + positions: ArrayLike | None = ..., + vert: bool = ..., + widths: float | ArrayLike = ..., + showmeans: bool = ..., + showextrema: bool = ..., + showmedians: bool = ..., + side: Literal["both", "low", "high"] = ..., + ) -> dict[str, Collection]: ... + + table = mtable.table + stackplot = mstack.stackplot + streamplot = mstream.streamplot + tricontour = mtri.tricontour + tricontourf = mtri.tricontourf + tripcolor = mtri.tripcolor + triplot = mtri.triplot diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/_base.py b/parrot/lib/python3.10/site-packages/matplotlib/axes/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..6b3f2750575cc379b942156bc3f6043a446fa2a9 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/axes/_base.py @@ -0,0 +1,4752 @@ +from collections.abc import Iterable, Sequence +from contextlib import ExitStack +import functools +import inspect +import logging +from numbers import Real +from operator import attrgetter +import re +import types + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, _docstring, offsetbox +import matplotlib.artist as martist +import matplotlib.axis as maxis +from matplotlib.cbook import _OrderedSet, _check_1d, index_of +import matplotlib.collections as mcoll +import matplotlib.colors as mcolors +import matplotlib.font_manager as font_manager +from matplotlib.gridspec import SubplotSpec +import matplotlib.image as mimage +import matplotlib.lines as mlines +import matplotlib.patches as mpatches +from matplotlib.rcsetup import cycler, validate_axisbelow +import matplotlib.spines as mspines +import matplotlib.table as mtable +import matplotlib.text as mtext +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms + +_log = logging.getLogger(__name__) + + +class _axis_method_wrapper: + """ + Helper to generate Axes methods wrapping Axis methods. + + After :: + + get_foo = _axis_method_wrapper("xaxis", "get_bar") + + (in the body of a class) ``get_foo`` is a method that forwards it arguments + to the ``get_bar`` method of the ``xaxis`` attribute, and gets its + signature and docstring from ``Axis.get_bar``. + + The docstring of ``get_foo`` is built by replacing "this Axis" by "the + {attr_name}" (i.e., "the xaxis", "the yaxis") in the wrapped method's + dedented docstring; additional replacements can be given in *doc_sub*. + """ + + def __init__(self, attr_name, method_name, *, doc_sub=None): + self.attr_name = attr_name + self.method_name = method_name + # Immediately put the docstring in ``self.__doc__`` so that docstring + # manipulations within the class body work as expected. + doc = inspect.getdoc(getattr(maxis.Axis, method_name)) + self._missing_subs = [] + if doc: + doc_sub = {"this Axis": f"the {self.attr_name}", **(doc_sub or {})} + for k, v in doc_sub.items(): + if k not in doc: # Delay raising error until we know qualname. + self._missing_subs.append(k) + doc = doc.replace(k, v) + self.__doc__ = doc + + def __set_name__(self, owner, name): + # This is called at the end of the class body as + # ``self.__set_name__(cls, name_under_which_self_is_assigned)``; we + # rely on that to give the wrapper the correct __name__/__qualname__. + get_method = attrgetter(f"{self.attr_name}.{self.method_name}") + + def wrapper(self, *args, **kwargs): + return get_method(self)(*args, **kwargs) + + wrapper.__module__ = owner.__module__ + wrapper.__name__ = name + wrapper.__qualname__ = f"{owner.__qualname__}.{name}" + wrapper.__doc__ = self.__doc__ + # Manually copy the signature instead of using functools.wraps because + # displaying the Axis method source when asking for the Axes method + # source would be confusing. + wrapper.__signature__ = inspect.signature( + getattr(maxis.Axis, self.method_name)) + + if self._missing_subs: + raise ValueError( + "The definition of {} expected that the docstring of Axis.{} " + "contains {!r} as substrings".format( + wrapper.__qualname__, self.method_name, + ", ".join(map(repr, self._missing_subs)))) + + setattr(owner, name, wrapper) + + +class _TransformedBoundsLocator: + """ + Axes locator for `.Axes.inset_axes` and similarly positioned Axes. + + The locator is a callable object used in `.Axes.set_aspect` to compute the + Axes location depending on the renderer. + """ + + def __init__(self, bounds, transform): + """ + *bounds* (a ``[l, b, w, h]`` rectangle) and *transform* together + specify the position of the inset Axes. + """ + self._bounds = bounds + self._transform = transform + + def __call__(self, ax, renderer): + # Subtracting transSubfigure will typically rely on inverted(), + # freezing the transform; thus, this needs to be delayed until draw + # time as transSubfigure may otherwise change after this is evaluated. + return mtransforms.TransformedBbox( + mtransforms.Bbox.from_bounds(*self._bounds), + self._transform - ax.figure.transSubfigure) + + +def _process_plot_format(fmt, *, ambiguous_fmt_datakey=False): + """ + Convert a MATLAB style color/line style format string to a (*linestyle*, + *marker*, *color*) tuple. + + Example format strings include: + + * 'ko': black circles + * '.b': blue dots + * 'r--': red dashed lines + * 'C2--': the third color in the color cycle, dashed lines + + The format is absolute in the sense that if a linestyle or marker is not + defined in *fmt*, there is no line or marker. This is expressed by + returning 'None' for the respective quantity. + + See Also + -------- + matplotlib.Line2D.lineStyles, matplotlib.colors.cnames + All possible styles and color format strings. + """ + + linestyle = None + marker = None + color = None + + # First check whether fmt is just a colorspec, but specifically exclude the + # grayscale string "1" (not "1.0"), which is interpreted as the tri_down + # marker "1". The grayscale string "0" could be unambiguously understood + # as a color (black) but also excluded for consistency. + if fmt not in ["0", "1"]: + try: + color = mcolors.to_rgba(fmt) + return linestyle, marker, color + except ValueError: + pass + + errfmt = ("{!r} is neither a data key nor a valid format string ({})" + if ambiguous_fmt_datakey else + "{!r} is not a valid format string ({})") + + i = 0 + while i < len(fmt): + c = fmt[i] + if fmt[i:i+2] in mlines.lineStyles: # First, the two-char styles. + if linestyle is not None: + raise ValueError(errfmt.format(fmt, "two linestyle symbols")) + linestyle = fmt[i:i+2] + i += 2 + elif c in mlines.lineStyles: + if linestyle is not None: + raise ValueError(errfmt.format(fmt, "two linestyle symbols")) + linestyle = c + i += 1 + elif c in mlines.lineMarkers: + if marker is not None: + raise ValueError(errfmt.format(fmt, "two marker symbols")) + marker = c + i += 1 + elif c in mcolors.get_named_colors_mapping(): + if color is not None: + raise ValueError(errfmt.format(fmt, "two color symbols")) + color = c + i += 1 + elif c == "C": + cn_color = re.match(r"C\d+", fmt[i:]) + if not cn_color: + raise ValueError(errfmt.format(fmt, "'C' must be followed by a number")) + color = mcolors.to_rgba(cn_color[0]) + i += len(cn_color[0]) + else: + raise ValueError(errfmt.format(fmt, f"unrecognized character {c!r}")) + + if linestyle is None and marker is None: + linestyle = mpl.rcParams['lines.linestyle'] + if linestyle is None: + linestyle = 'None' + if marker is None: + marker = 'None' + + return linestyle, marker, color + + +class _process_plot_var_args: + """ + Process variable length arguments to `~.Axes.plot`, to support :: + + plot(t, s) + plot(t1, s1, t2, s2) + plot(t1, s1, 'ko', t2, s2) + plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3) + + an arbitrary number of *x*, *y*, *fmt* are allowed + """ + + def __init__(self, command='plot'): + self.command = command + self.set_prop_cycle(None) + + def set_prop_cycle(self, cycler): + if cycler is None: + cycler = mpl.rcParams['axes.prop_cycle'] + self._idx = 0 + self._cycler_items = [*cycler] + + def __call__(self, axes, *args, data=None, **kwargs): + axes._process_unit_info(kwargs=kwargs) + + for pos_only in "xy": + if pos_only in kwargs: + raise _api.kwarg_error(self.command, pos_only) + + if not args: + return + + if data is None: # Process dict views + args = [cbook.sanitize_sequence(a) for a in args] + else: # Process the 'data' kwarg. + replaced = [mpl._replacer(data, arg) for arg in args] + if len(args) == 1: + label_namer_idx = 0 + elif len(args) == 2: # Can be x, y or y, c. + # Figure out what the second argument is. + # 1) If the second argument cannot be a format shorthand, the + # second argument is the label_namer. + # 2) Otherwise (it could have been a format shorthand), + # a) if we did perform a substitution, emit a warning, and + # use it as label_namer. + # b) otherwise, it is indeed a format shorthand; use the + # first argument as label_namer. + try: + _process_plot_format(args[1]) + except ValueError: # case 1) + label_namer_idx = 1 + else: + if replaced[1] is not args[1]: # case 2a) + _api.warn_external( + f"Second argument {args[1]!r} is ambiguous: could " + f"be a format string but is in 'data'; using as " + f"data. If it was intended as data, set the " + f"format string to an empty string to suppress " + f"this warning. If it was intended as a format " + f"string, explicitly pass the x-values as well. " + f"Alternatively, rename the entry in 'data'.", + RuntimeWarning) + label_namer_idx = 1 + else: # case 2b) + label_namer_idx = 0 + elif len(args) == 3: + label_namer_idx = 1 + else: + raise ValueError( + "Using arbitrary long args with data is not supported due " + "to ambiguity of arguments; use multiple plotting calls " + "instead") + if kwargs.get("label") is None: + kwargs["label"] = mpl._label_from_arg( + replaced[label_namer_idx], args[label_namer_idx]) + args = replaced + ambiguous_fmt_datakey = data is not None and len(args) == 2 + + if len(args) >= 4 and not cbook.is_scalar_or_string( + kwargs.get("label")): + raise ValueError("plot() with multiple groups of data (i.e., " + "pairs of x and y) does not support multiple " + "labels") + + # Repeatedly grab (x, y) or (x, y, format) from the front of args and + # massage them into arguments to plot() or fill(). + + while args: + this, args = args[:2], args[2:] + if args and isinstance(args[0], str): + this += args[0], + args = args[1:] + yield from self._plot_args( + axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey) + + def get_next_color(self): + """Return the next color in the cycle.""" + entry = self._cycler_items[self._idx] + if "color" in entry: + self._idx = (self._idx + 1) % len(self._cycler_items) # Advance cycler. + return entry["color"] + else: + return "k" + + def _getdefaults(self, kw, ignore=frozenset()): + """ + If some keys in the property cycle (excluding those in the set + *ignore*) are absent or set to None in the dict *kw*, return a copy + of the next entry in the property cycle, excluding keys in *ignore*. + Otherwise, don't advance the property cycle, and return an empty dict. + """ + defaults = self._cycler_items[self._idx] + if any(kw.get(k, None) is None for k in {*defaults} - ignore): + self._idx = (self._idx + 1) % len(self._cycler_items) # Advance cycler. + # Return a new dict to avoid exposing _cycler_items entries to mutation. + return {k: v for k, v in defaults.items() if k not in ignore} + else: + return {} + + def _setdefaults(self, defaults, kw): + """ + Add to the dict *kw* the entries in the dict *default* that are absent + or set to None in *kw*. + """ + for k in defaults: + if kw.get(k, None) is None: + kw[k] = defaults[k] + + def _makeline(self, axes, x, y, kw, kwargs): + kw = {**kw, **kwargs} # Don't modify the original kw. + self._setdefaults(self._getdefaults(kw), kw) + seg = mlines.Line2D(x, y, **kw) + return seg, kw + + def _makefill(self, axes, x, y, kw, kwargs): + # Polygon doesn't directly support unitized inputs. + x = axes.convert_xunits(x) + y = axes.convert_yunits(y) + + kw = kw.copy() # Don't modify the original kw. + kwargs = kwargs.copy() + + # Ignore 'marker'-related properties as they aren't Polygon + # properties, but they are Line2D properties, and so they are + # likely to appear in the default cycler construction. + # This is done here to the defaults dictionary as opposed to the + # other two dictionaries because we do want to capture when a + # *user* explicitly specifies a marker which should be an error. + # We also want to prevent advancing the cycler if there are no + # defaults needed after ignoring the given properties. + ignores = ({'marker', 'markersize', 'markeredgecolor', + 'markerfacecolor', 'markeredgewidth'} + # Also ignore anything provided by *kwargs*. + | {k for k, v in kwargs.items() if v is not None}) + + # Only using the first dictionary to use as basis + # for getting defaults for back-compat reasons. + # Doing it with both seems to mess things up in + # various places (probably due to logic bugs elsewhere). + default_dict = self._getdefaults(kw, ignores) + self._setdefaults(default_dict, kw) + + # Looks like we don't want "color" to be interpreted to + # mean both facecolor and edgecolor for some reason. + # So the "kw" dictionary is thrown out, and only its + # 'color' value is kept and translated as a 'facecolor'. + # This design should probably be revisited as it increases + # complexity. + facecolor = kw.get('color', None) + + # Throw out 'color' as it is now handled as a facecolor + default_dict.pop('color', None) + + # To get other properties set from the cycler + # modify the kwargs dictionary. + self._setdefaults(default_dict, kwargs) + + seg = mpatches.Polygon(np.column_stack((x, y)), + facecolor=facecolor, + fill=kwargs.get('fill', True), + closed=kw['closed']) + seg.set(**kwargs) + return seg, kwargs + + def _plot_args(self, axes, tup, kwargs, *, + return_kwargs=False, ambiguous_fmt_datakey=False): + """ + Process the arguments of ``plot([x], y, [fmt], **kwargs)`` calls. + + This processes a single set of ([x], y, [fmt]) parameters; i.e. for + ``plot(x, y, x2, y2)`` it will be called twice. Once for (x, y) and + once for (x2, y2). + + x and y may be 2D and thus can still represent multiple datasets. + + For multiple datasets, if the keyword argument *label* is a list, this + will unpack the list and assign the individual labels to the datasets. + + Parameters + ---------- + tup : tuple + A tuple of the positional parameters. This can be one of + + - (y,) + - (x, y) + - (y, fmt) + - (x, y, fmt) + + kwargs : dict + The keyword arguments passed to ``plot()``. + + return_kwargs : bool + Whether to also return the effective keyword arguments after label + unpacking as well. + + ambiguous_fmt_datakey : bool + Whether the format string in *tup* could also have been a + misspelled data key. + + Returns + ------- + result + If *return_kwargs* is false, a list of Artists representing the + dataset(s). + If *return_kwargs* is true, a list of (Artist, effective_kwargs) + representing the dataset(s). See *return_kwargs*. + The Artist is either `.Line2D` (if called from ``plot()``) or + `.Polygon` otherwise. + """ + if len(tup) > 1 and isinstance(tup[-1], str): + # xy is tup with fmt stripped (could still be (y,) only) + *xy, fmt = tup + linestyle, marker, color = _process_plot_format( + fmt, ambiguous_fmt_datakey=ambiguous_fmt_datakey) + elif len(tup) == 3: + raise ValueError('third arg must be a format string') + else: + xy = tup + linestyle, marker, color = None, None, None + + # Don't allow any None value; these would be up-converted to one + # element array of None which causes problems downstream. + if any(v is None for v in tup): + raise ValueError("x, y, and format string must not be None") + + kw = {} + for prop_name, val in zip(('linestyle', 'marker', 'color'), + (linestyle, marker, color)): + if val is not None: + # check for conflicts between fmt and kwargs + if (fmt.lower() != 'none' + and prop_name in kwargs + and val != 'None'): + # Technically ``plot(x, y, 'o', ls='--')`` is a conflict + # because 'o' implicitly unsets the linestyle + # (linestyle='None'). + # We'll gracefully not warn in this case because an + # explicit set via kwargs can be seen as intention to + # override an implicit unset. + # Note: We don't val.lower() != 'none' because val is not + # necessarily a string (can be a tuple for colors). This + # is safe, because *val* comes from _process_plot_format() + # which only returns 'None'. + _api.warn_external( + f"{prop_name} is redundantly defined by the " + f"'{prop_name}' keyword argument and the fmt string " + f'"{fmt}" (-> {prop_name}={val!r}). The keyword ' + f"argument will take precedence.") + kw[prop_name] = val + + if len(xy) == 2: + x = _check_1d(xy[0]) + y = _check_1d(xy[1]) + else: + x, y = index_of(xy[-1]) + + if axes.xaxis is not None: + axes.xaxis.update_units(x) + if axes.yaxis is not None: + axes.yaxis.update_units(y) + + if x.shape[0] != y.shape[0]: + raise ValueError(f"x and y must have same first dimension, but " + f"have shapes {x.shape} and {y.shape}") + if x.ndim > 2 or y.ndim > 2: + raise ValueError(f"x and y can be no greater than 2D, but have " + f"shapes {x.shape} and {y.shape}") + if x.ndim == 1: + x = x[:, np.newaxis] + if y.ndim == 1: + y = y[:, np.newaxis] + + if self.command == 'plot': + make_artist = self._makeline + else: + kw['closed'] = kwargs.get('closed', True) + make_artist = self._makefill + + ncx, ncy = x.shape[1], y.shape[1] + if ncx > 1 and ncy > 1 and ncx != ncy: + raise ValueError(f"x has {ncx} columns but y has {ncy} columns") + if ncx == 0 or ncy == 0: + return [] + + label = kwargs.get('label') + n_datasets = max(ncx, ncy) + + if cbook.is_scalar_or_string(label): + labels = [label] * n_datasets + elif len(label) == n_datasets: + labels = label + elif n_datasets == 1: + msg = (f'Passing label as a length {len(label)} sequence when ' + 'plotting a single dataset is deprecated in Matplotlib 3.9 ' + 'and will error in 3.11. To keep the current behavior, ' + 'cast the sequence to string before passing.') + _api.warn_deprecated('3.9', message=msg) + labels = [label] + else: + raise ValueError( + f"label must be scalar or have the same length as the input " + f"data, but found {len(label)} for {n_datasets} datasets.") + + result = (make_artist(axes, x[:, j % ncx], y[:, j % ncy], kw, + {**kwargs, 'label': label}) + for j, label in enumerate(labels)) + + if return_kwargs: + return list(result) + else: + return [l[0] for l in result] + + +@_api.define_aliases({"facecolor": ["fc"]}) +class _AxesBase(martist.Artist): + name = "rectilinear" + + # axis names are the prefixes for the attributes that contain the + # respective axis; e.g. 'x' <-> self.xaxis, containing an XAxis. + # Note that PolarAxes uses these attributes as well, so that we have + # 'x' <-> self.xaxis, containing a ThetaAxis. In particular we do not + # have 'theta' in _axis_names. + # In practice, this is ('x', 'y') for all 2D Axes and ('x', 'y', 'z') + # for Axes3D. + _axis_names = ("x", "y") + _shared_axes = {name: cbook.Grouper() for name in _axis_names} + _twinned_axes = cbook.Grouper() + + _subclass_uses_cla = False + + @property + def _axis_map(self): + """A mapping of axis names, e.g. 'x', to `Axis` instances.""" + return {name: getattr(self, f"{name}axis") + for name in self._axis_names} + + def __str__(self): + return "{0}({1[0]:g},{1[1]:g};{1[2]:g}x{1[3]:g})".format( + type(self).__name__, self._position.bounds) + + def __init__(self, fig, + *args, + facecolor=None, # defaults to rc axes.facecolor + frameon=True, + sharex=None, # use Axes instance's xaxis info + sharey=None, # use Axes instance's yaxis info + label='', + xscale=None, + yscale=None, + box_aspect=None, + forward_navigation_events="auto", + **kwargs + ): + """ + Build an Axes in a figure. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + The Axes is built in the `.Figure` *fig*. + + *args + ``*args`` can be a single ``(left, bottom, width, height)`` + rectangle or a single `.Bbox`. This specifies the rectangle (in + figure coordinates) where the Axes is positioned. + + ``*args`` can also consist of three numbers or a single three-digit + number; in the latter case, the digits are considered as + independent numbers. The numbers are interpreted as ``(nrows, + ncols, index)``: ``(nrows, ncols)`` specifies the size of an array + of subplots, and ``index`` is the 1-based index of the subplot + being created. Finally, ``*args`` can also directly be a + `.SubplotSpec` instance. + + sharex, sharey : `~matplotlib.axes.Axes`, optional + The x- or y-`~.matplotlib.axis` is shared with the x- or y-axis in + the input `~.axes.Axes`. Note that it is not possible to unshare + axes. + + frameon : bool, default: True + Whether the Axes frame is visible. + + box_aspect : float, optional + Set a fixed aspect for the Axes box, i.e. the ratio of height to + width. See `~.axes.Axes.set_box_aspect` for details. + + forward_navigation_events : bool or "auto", default: "auto" + Control whether pan/zoom events are passed through to Axes below + this one. "auto" is *True* for axes with an invisible patch and + *False* otherwise. + + **kwargs + Other optional keyword arguments: + + %(Axes:kwdoc)s + + Returns + ------- + `~.axes.Axes` + The new `~.axes.Axes` object. + """ + + super().__init__() + if "rect" in kwargs: + if args: + raise TypeError( + "'rect' cannot be used together with positional arguments") + rect = kwargs.pop("rect") + _api.check_isinstance((mtransforms.Bbox, Iterable), rect=rect) + args = (rect,) + subplotspec = None + if len(args) == 1 and isinstance(args[0], mtransforms.Bbox): + self._position = args[0] + elif len(args) == 1 and np.iterable(args[0]): + self._position = mtransforms.Bbox.from_bounds(*args[0]) + else: + self._position = self._originalPosition = mtransforms.Bbox.unit() + subplotspec = SubplotSpec._from_subplot_args(fig, args) + if self._position.width < 0 or self._position.height < 0: + raise ValueError('Width and height specified must be non-negative') + self._originalPosition = self._position.frozen() + self.axes = self + self._aspect = 'auto' + self._adjustable = 'box' + self._anchor = 'C' + self._stale_viewlims = {name: False for name in self._axis_names} + self._forward_navigation_events = forward_navigation_events + self._sharex = sharex + self._sharey = sharey + self.set_label(label) + self.set_figure(fig) + # The subplotspec needs to be set after the figure (so that + # figure-level subplotpars are taken into account), but the figure + # needs to be set after self._position is initialized. + if subplotspec: + self.set_subplotspec(subplotspec) + else: + self._subplotspec = None + self.set_box_aspect(box_aspect) + self._axes_locator = None # Optionally set via update(kwargs). + + self._children = [] + + # placeholder for any colorbars added that use this Axes. + # (see colorbar.py): + self._colorbars = [] + self.spines = mspines.Spines.from_dict(self._gen_axes_spines()) + + # this call may differ for non-sep axes, e.g., polar + self._init_axis() + if facecolor is None: + facecolor = mpl.rcParams['axes.facecolor'] + self._facecolor = facecolor + self._frameon = frameon + self.set_axisbelow(mpl.rcParams['axes.axisbelow']) + + self._rasterization_zorder = None + self.clear() + + # funcs used to format x and y - fall back on major formatters + self.fmt_xdata = None + self.fmt_ydata = None + + self.set_navigate(True) + self.set_navigate_mode(None) + + if xscale: + self.set_xscale(xscale) + if yscale: + self.set_yscale(yscale) + + self._internal_update(kwargs) + + for name, axis in self._axis_map.items(): + axis.callbacks._connect_picklable( + 'units', self._unit_change_handler(name)) + + rcParams = mpl.rcParams + self.tick_params( + top=rcParams['xtick.top'] and rcParams['xtick.minor.top'], + bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'], + labeltop=(rcParams['xtick.labeltop'] and + rcParams['xtick.minor.top']), + labelbottom=(rcParams['xtick.labelbottom'] and + rcParams['xtick.minor.bottom']), + left=rcParams['ytick.left'] and rcParams['ytick.minor.left'], + right=rcParams['ytick.right'] and rcParams['ytick.minor.right'], + labelleft=(rcParams['ytick.labelleft'] and + rcParams['ytick.minor.left']), + labelright=(rcParams['ytick.labelright'] and + rcParams['ytick.minor.right']), + which='minor') + + self.tick_params( + top=rcParams['xtick.top'] and rcParams['xtick.major.top'], + bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'], + labeltop=(rcParams['xtick.labeltop'] and + rcParams['xtick.major.top']), + labelbottom=(rcParams['xtick.labelbottom'] and + rcParams['xtick.major.bottom']), + left=rcParams['ytick.left'] and rcParams['ytick.major.left'], + right=rcParams['ytick.right'] and rcParams['ytick.major.right'], + labelleft=(rcParams['ytick.labelleft'] and + rcParams['ytick.major.left']), + labelright=(rcParams['ytick.labelright'] and + rcParams['ytick.major.right']), + which='major') + + def __init_subclass__(cls, **kwargs): + parent_uses_cla = super(cls, cls)._subclass_uses_cla + if 'cla' in cls.__dict__: + _api.warn_deprecated( + '3.6', + pending=True, + message=f'Overriding `Axes.cla` in {cls.__qualname__} is ' + 'pending deprecation in %(since)s and will be fully ' + 'deprecated in favor of `Axes.clear` in the future. ' + 'Please report ' + f'this to the {cls.__module__!r} author.') + cls._subclass_uses_cla = 'cla' in cls.__dict__ or parent_uses_cla + super().__init_subclass__(**kwargs) + + def __getstate__(self): + state = super().__getstate__() + # Prune the sharing & twinning info to only contain the current group. + state["_shared_axes"] = { + name: self._shared_axes[name].get_siblings(self) + for name in self._axis_names if self in self._shared_axes[name]} + state["_twinned_axes"] = (self._twinned_axes.get_siblings(self) + if self in self._twinned_axes else None) + return state + + def __setstate__(self, state): + # Merge the grouping info back into the global groupers. + shared_axes = state.pop("_shared_axes") + for name, shared_siblings in shared_axes.items(): + self._shared_axes[name].join(*shared_siblings) + twinned_siblings = state.pop("_twinned_axes") + if twinned_siblings: + self._twinned_axes.join(*twinned_siblings) + self.__dict__ = state + self._stale = True + + def __repr__(self): + fields = [] + if self.get_label(): + fields += [f"label={self.get_label()!r}"] + if hasattr(self, "get_title"): + titles = {} + for k in ["left", "center", "right"]: + title = self.get_title(loc=k) + if title: + titles[k] = title + if titles: + fields += [f"title={titles}"] + for name, axis in self._axis_map.items(): + if axis.get_label() and axis.get_label().get_text(): + fields += [f"{name}label={axis.get_label().get_text()!r}"] + return f"<{self.__class__.__name__}: " + ", ".join(fields) + ">" + + def get_subplotspec(self): + """Return the `.SubplotSpec` associated with the subplot, or None.""" + return self._subplotspec + + def set_subplotspec(self, subplotspec): + """Set the `.SubplotSpec`. associated with the subplot.""" + self._subplotspec = subplotspec + self._set_position(subplotspec.get_position(self.figure)) + + def get_gridspec(self): + """Return the `.GridSpec` associated with the subplot, or None.""" + return self._subplotspec.get_gridspec() if self._subplotspec else None + + def get_window_extent(self, renderer=None): + """ + Return the Axes bounding box in display space. + + This bounding box does not include the spines, ticks, ticklabels, + or other labels. For a bounding box including these elements use + `~matplotlib.axes.Axes.get_tightbbox`. + + See Also + -------- + matplotlib.axes.Axes.get_tightbbox + matplotlib.axis.Axis.get_tightbbox + matplotlib.spines.Spine.get_window_extent + """ + return self.bbox + + def _init_axis(self): + # This is moved out of __init__ because non-separable axes don't use it + self.xaxis = maxis.XAxis(self, clear=False) + self.spines.bottom.register_axis(self.xaxis) + self.spines.top.register_axis(self.xaxis) + self.yaxis = maxis.YAxis(self, clear=False) + self.spines.left.register_axis(self.yaxis) + self.spines.right.register_axis(self.yaxis) + + def set_figure(self, fig): + # docstring inherited + super().set_figure(fig) + + self.bbox = mtransforms.TransformedBbox(self._position, + fig.transSubfigure) + # these will be updated later as data is added + self.dataLim = mtransforms.Bbox.null() + self._viewLim = mtransforms.Bbox.unit() + self.transScale = mtransforms.TransformWrapper( + mtransforms.IdentityTransform()) + + self._set_lim_and_transforms() + + def _unstale_viewLim(self): + # We should arrange to store this information once per share-group + # instead of on every axis. + need_scale = { + name: any(ax._stale_viewlims[name] + for ax in self._shared_axes[name].get_siblings(self)) + for name in self._axis_names} + if any(need_scale.values()): + for name in need_scale: + for ax in self._shared_axes[name].get_siblings(self): + ax._stale_viewlims[name] = False + self.autoscale_view(**{f"scale{name}": scale + for name, scale in need_scale.items()}) + + @property + def viewLim(self): + self._unstale_viewLim() + return self._viewLim + + def _request_autoscale_view(self, axis="all", tight=None): + """ + Mark a single axis, or all of them, as stale wrt. autoscaling. + + No computation is performed until the next autoscaling; thus, separate + calls to control individual axises incur negligible performance cost. + + Parameters + ---------- + axis : str, default: "all" + Either an element of ``self._axis_names``, or "all". + tight : bool or None, default: None + """ + axis_names = _api.check_getitem( + {**{k: [k] for k in self._axis_names}, "all": self._axis_names}, + axis=axis) + for name in axis_names: + self._stale_viewlims[name] = True + if tight is not None: + self._tight = tight + + def _set_lim_and_transforms(self): + """ + Set the *_xaxis_transform*, *_yaxis_transform*, *transScale*, + *transData*, *transLimits* and *transAxes* transformations. + + .. note:: + + This method is primarily used by rectilinear projections of the + `~matplotlib.axes.Axes` class, and is meant to be overridden by + new kinds of projection Axes that need different transformations + and limits. (See `~matplotlib.projections.polar.PolarAxes` for an + example.) + """ + self.transAxes = mtransforms.BboxTransformTo(self.bbox) + + # Transforms the x and y axis separately by a scale factor. + # It is assumed that this part will have non-linear components + # (e.g., for a log scale). + self.transScale = mtransforms.TransformWrapper( + mtransforms.IdentityTransform()) + + # An affine transformation on the data, generally to limit the + # range of the axes + self.transLimits = mtransforms.BboxTransformFrom( + mtransforms.TransformedBbox(self._viewLim, self.transScale)) + + # The parentheses are important for efficiency here -- they + # group the last two (which are usually affines) separately + # from the first (which, with log-scaling can be non-affine). + self.transData = self.transScale + (self.transLimits + self.transAxes) + + self._xaxis_transform = mtransforms.blended_transform_factory( + self.transData, self.transAxes) + self._yaxis_transform = mtransforms.blended_transform_factory( + self.transAxes, self.transData) + + def get_xaxis_transform(self, which='grid'): + """ + Get the transformation used for drawing x-axis labels, ticks + and gridlines. The x-direction is in data coordinates and the + y-direction is in axis coordinates. + + .. note:: + + This transformation is primarily used by the + `~matplotlib.axis.Axis` class, and is meant to be + overridden by new kinds of projections that may need to + place axis elements in different locations. + + Parameters + ---------- + which : {'grid', 'tick1', 'tick2'} + """ + if which == 'grid': + return self._xaxis_transform + elif which == 'tick1': + # for cartesian projection, this is bottom spine + return self.spines.bottom.get_spine_transform() + elif which == 'tick2': + # for cartesian projection, this is top spine + return self.spines.top.get_spine_transform() + else: + raise ValueError(f'unknown value for which: {which!r}') + + def get_xaxis_text1_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing x-axis labels, which will add + *pad_points* of padding (in points) between the axis and the label. + The x-direction is in data coordinates and the y-direction is in + axis coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["xtick.alignment"] + return (self.get_xaxis_transform(which='tick1') + + mtransforms.ScaledTranslation(0, -1 * pad_points / 72, + self.figure.dpi_scale_trans), + "top", labels_align) + + def get_xaxis_text2_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing secondary x-axis labels, which will + add *pad_points* of padding (in points) between the axis and the + label. The x-direction is in data coordinates and the y-direction + is in axis coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["xtick.alignment"] + return (self.get_xaxis_transform(which='tick2') + + mtransforms.ScaledTranslation(0, pad_points / 72, + self.figure.dpi_scale_trans), + "bottom", labels_align) + + def get_yaxis_transform(self, which='grid'): + """ + Get the transformation used for drawing y-axis labels, ticks + and gridlines. The x-direction is in axis coordinates and the + y-direction is in data coordinates. + + .. note:: + + This transformation is primarily used by the + `~matplotlib.axis.Axis` class, and is meant to be + overridden by new kinds of projections that may need to + place axis elements in different locations. + + Parameters + ---------- + which : {'grid', 'tick1', 'tick2'} + """ + if which == 'grid': + return self._yaxis_transform + elif which == 'tick1': + # for cartesian projection, this is bottom spine + return self.spines.left.get_spine_transform() + elif which == 'tick2': + # for cartesian projection, this is top spine + return self.spines.right.get_spine_transform() + else: + raise ValueError(f'unknown value for which: {which!r}') + + def get_yaxis_text1_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing y-axis labels, which will add + *pad_points* of padding (in points) between the axis and the label. + The x-direction is in axis coordinates and the y-direction is in + data coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["ytick.alignment"] + return (self.get_yaxis_transform(which='tick1') + + mtransforms.ScaledTranslation(-1 * pad_points / 72, 0, + self.figure.dpi_scale_trans), + labels_align, "right") + + def get_yaxis_text2_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing secondart y-axis labels, which will + add *pad_points* of padding (in points) between the axis and the + label. The x-direction is in axis coordinates and the y-direction + is in data coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["ytick.alignment"] + return (self.get_yaxis_transform(which='tick2') + + mtransforms.ScaledTranslation(pad_points / 72, 0, + self.figure.dpi_scale_trans), + labels_align, "left") + + def _update_transScale(self): + self.transScale.set( + mtransforms.blended_transform_factory( + self.xaxis.get_transform(), self.yaxis.get_transform())) + + def get_position(self, original=False): + """ + Return the position of the Axes within the figure as a `.Bbox`. + + Parameters + ---------- + original : bool + If ``True``, return the original position. Otherwise, return the + active position. For an explanation of the positions see + `.set_position`. + + Returns + ------- + `.Bbox` + + """ + if original: + return self._originalPosition.frozen() + else: + locator = self.get_axes_locator() + if not locator: + self.apply_aspect() + return self._position.frozen() + + def set_position(self, pos, which='both'): + """ + Set the Axes position. + + Axes have two position attributes. The 'original' position is the + position allocated for the Axes. The 'active' position is the + position the Axes is actually drawn at. These positions are usually + the same unless a fixed aspect is set to the Axes. See + `.Axes.set_aspect` for details. + + Parameters + ---------- + pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox` + The new position of the Axes in `.Figure` coordinates. + + which : {'both', 'active', 'original'}, default: 'both' + Determines which position variables to change. + + See Also + -------- + matplotlib.transforms.Bbox.from_bounds + matplotlib.transforms.Bbox.from_extents + """ + self._set_position(pos, which=which) + # because this is being called externally to the library we + # don't let it be in the layout. + self.set_in_layout(False) + + def _set_position(self, pos, which='both'): + """ + Private version of set_position. + + Call this internally to get the same functionality of `set_position`, + but not to take the axis out of the constrained_layout hierarchy. + """ + if not isinstance(pos, mtransforms.BboxBase): + pos = mtransforms.Bbox.from_bounds(*pos) + for ax in self._twinned_axes.get_siblings(self): + if which in ('both', 'active'): + ax._position.set(pos) + if which in ('both', 'original'): + ax._originalPosition.set(pos) + self.stale = True + + def reset_position(self): + """ + Reset the active position to the original position. + + This undoes changes to the active position (as defined in + `.set_position`) which may have been performed to satisfy fixed-aspect + constraints. + """ + for ax in self._twinned_axes.get_siblings(self): + pos = ax.get_position(original=True) + ax.set_position(pos, which='active') + + def set_axes_locator(self, locator): + """ + Set the Axes locator. + + Parameters + ---------- + locator : Callable[[Axes, Renderer], Bbox] + """ + self._axes_locator = locator + self.stale = True + + def get_axes_locator(self): + """ + Return the axes_locator. + """ + return self._axes_locator + + def _set_artist_props(self, a): + """Set the boilerplate props for artists added to Axes.""" + a.set_figure(self.figure) + if not a.is_transform_set(): + a.set_transform(self.transData) + + a.axes = self + if a.get_mouseover(): + self._mouseover_set.add(a) + + def _gen_axes_patch(self): + """ + Returns + ------- + Patch + The patch used to draw the background of the Axes. It is also used + as the clipping path for any data elements on the Axes. + + In the standard Axes, this is a rectangle, but in other projections + it may not be. + + Notes + ----- + Intended to be overridden by new projection types. + """ + return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0) + + def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'): + """ + Returns + ------- + dict + Mapping of spine names to `.Line2D` or `.Patch` instances that are + used to draw Axes spines. + + In the standard Axes, spines are single line segments, but in other + projections they may not be. + + Notes + ----- + Intended to be overridden by new projection types. + """ + return {side: mspines.Spine.linear_spine(self, side) + for side in ['left', 'right', 'bottom', 'top']} + + def sharex(self, other): + """ + Share the x-axis with *other*. + + This is equivalent to passing ``sharex=other`` when constructing the + Axes, and cannot be used if the x-axis is already being shared with + another Axes. Note that it is not possible to unshare axes. + """ + _api.check_isinstance(_AxesBase, other=other) + if self._sharex is not None and other is not self._sharex: + raise ValueError("x-axis is already shared") + self._shared_axes["x"].join(self, other) + self._sharex = other + self.xaxis.major = other.xaxis.major # Ticker instances holding + self.xaxis.minor = other.xaxis.minor # locator and formatter. + x0, x1 = other.get_xlim() + self.set_xlim(x0, x1, emit=False, auto=other.get_autoscalex_on()) + self.xaxis._scale = other.xaxis._scale + + def sharey(self, other): + """ + Share the y-axis with *other*. + + This is equivalent to passing ``sharey=other`` when constructing the + Axes, and cannot be used if the y-axis is already being shared with + another Axes. Note that it is not possible to unshare axes. + """ + _api.check_isinstance(_AxesBase, other=other) + if self._sharey is not None and other is not self._sharey: + raise ValueError("y-axis is already shared") + self._shared_axes["y"].join(self, other) + self._sharey = other + self.yaxis.major = other.yaxis.major # Ticker instances holding + self.yaxis.minor = other.yaxis.minor # locator and formatter. + y0, y1 = other.get_ylim() + self.set_ylim(y0, y1, emit=False, auto=other.get_autoscaley_on()) + self.yaxis._scale = other.yaxis._scale + + def __clear(self): + """Clear the Axes.""" + # The actual implementation of clear() as long as clear() has to be + # an adapter delegating to the correct implementation. + # The implementation can move back into clear() when the + # deprecation on cla() subclassing expires. + + # stash the current visibility state + if hasattr(self, 'patch'): + patch_visible = self.patch.get_visible() + else: + patch_visible = True + + xaxis_visible = self.xaxis.get_visible() + yaxis_visible = self.yaxis.get_visible() + + for axis in self._axis_map.values(): + axis.clear() # Also resets the scale to linear. + for spine in self.spines.values(): + spine._clear() # Use _clear to not clear Axis again + + self.ignore_existing_data_limits = True + self.callbacks = cbook.CallbackRegistry( + signals=["xlim_changed", "ylim_changed", "zlim_changed"]) + + # update the minor locator for x and y axis based on rcParams + if mpl.rcParams['xtick.minor.visible']: + self.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + if mpl.rcParams['ytick.minor.visible']: + self.yaxis.set_minor_locator(mticker.AutoMinorLocator()) + + self._xmargin = mpl.rcParams['axes.xmargin'] + self._ymargin = mpl.rcParams['axes.ymargin'] + self._tight = None + self._use_sticky_edges = True + + self._get_lines = _process_plot_var_args() + self._get_patches_for_fill = _process_plot_var_args('fill') + + self._gridOn = mpl.rcParams['axes.grid'] + old_children, self._children = self._children, [] + for chld in old_children: + chld.axes = chld.figure = None + self._mouseover_set = _OrderedSet() + self.child_axes = [] + self._current_image = None # strictly for pyplot via _sci, _gci + self._projection_init = None # strictly for pyplot.subplot + self.legend_ = None + self.containers = [] + + self.grid(False) # Disable grid on init to use rcParameter + self.grid(self._gridOn, which=mpl.rcParams['axes.grid.which'], + axis=mpl.rcParams['axes.grid.axis']) + props = font_manager.FontProperties( + size=mpl.rcParams['axes.titlesize'], + weight=mpl.rcParams['axes.titleweight']) + + y = mpl.rcParams['axes.titley'] + if y is None: + y = 1.0 + self._autotitlepos = True + else: + self._autotitlepos = False + + self.title = mtext.Text( + x=0.5, y=y, text='', + fontproperties=props, + verticalalignment='baseline', + horizontalalignment='center', + ) + self._left_title = mtext.Text( + x=0.0, y=y, text='', + fontproperties=props.copy(), + verticalalignment='baseline', + horizontalalignment='left', ) + self._right_title = mtext.Text( + x=1.0, y=y, text='', + fontproperties=props.copy(), + verticalalignment='baseline', + horizontalalignment='right', + ) + title_offset_points = mpl.rcParams['axes.titlepad'] + # refactor this out so it can be called in ax.set_title if + # pad argument used... + self._set_title_offset_trans(title_offset_points) + + for _title in (self.title, self._left_title, self._right_title): + self._set_artist_props(_title) + + # The patch draws the background of the Axes. We want this to be below + # the other artists. We use the frame to draw the edges so we are + # setting the edgecolor to None. + self.patch = self._gen_axes_patch() + self.patch.set_figure(self.figure) + self.patch.set_facecolor(self._facecolor) + self.patch.set_edgecolor('none') + self.patch.set_linewidth(0) + self.patch.set_transform(self.transAxes) + + self.set_axis_on() + + self.xaxis.set_clip_path(self.patch) + self.yaxis.set_clip_path(self.patch) + + if self._sharex is not None: + self.xaxis.set_visible(xaxis_visible) + self.patch.set_visible(patch_visible) + if self._sharey is not None: + self.yaxis.set_visible(yaxis_visible) + self.patch.set_visible(patch_visible) + + # This comes last, as the call to _set_lim may trigger an autoscale (in + # case of shared axes), requiring children to be already set up. + for name, axis in self._axis_map.items(): + share = getattr(self, f"_share{name}") + if share is not None: + getattr(self, f"share{name}")(share) + else: + # Although the scale was set to linear as part of clear, + # polar requires that _set_scale is called again + if self.name == "polar": + axis._set_scale("linear") + axis._set_lim(0, 1, auto=True) + self._update_transScale() + + self.stale = True + + def clear(self): + """Clear the Axes.""" + # Act as an alias, or as the superclass implementation depending on the + # subclass implementation. + if self._subclass_uses_cla: + self.cla() + else: + self.__clear() + + def cla(self): + """Clear the Axes.""" + # Act as an alias, or as the superclass implementation depending on the + # subclass implementation. + if self._subclass_uses_cla: + self.__clear() + else: + self.clear() + + class ArtistList(Sequence): + """ + A sublist of Axes children based on their type. + + The type-specific children sublists were made immutable in Matplotlib + 3.7. In the future these artist lists may be replaced by tuples. Use + as if this is a tuple already. + """ + def __init__(self, axes, prop_name, + valid_types=None, invalid_types=None): + """ + Parameters + ---------- + axes : `~matplotlib.axes.Axes` + The Axes from which this sublist will pull the children + Artists. + prop_name : str + The property name used to access this sublist from the Axes; + used to generate deprecation warnings. + valid_types : list of type, optional + A list of types that determine which children will be returned + by this sublist. If specified, then the Artists in the sublist + must be instances of any of these types. If unspecified, then + any type of Artist is valid (unless limited by + *invalid_types*.) + invalid_types : tuple, optional + A list of types that determine which children will *not* be + returned by this sublist. If specified, then Artists in the + sublist will never be an instance of these types. Otherwise, no + types will be excluded. + """ + self._axes = axes + self._prop_name = prop_name + self._type_check = lambda artist: ( + (not valid_types or isinstance(artist, valid_types)) and + (not invalid_types or not isinstance(artist, invalid_types)) + ) + + def __repr__(self): + return f'' + + def __len__(self): + return sum(self._type_check(artist) + for artist in self._axes._children) + + def __iter__(self): + for artist in list(self._axes._children): + if self._type_check(artist): + yield artist + + def __getitem__(self, key): + return [artist + for artist in self._axes._children + if self._type_check(artist)][key] + + def __add__(self, other): + if isinstance(other, (list, _AxesBase.ArtistList)): + return [*self, *other] + if isinstance(other, (tuple, _AxesBase.ArtistList)): + return (*self, *other) + return NotImplemented + + def __radd__(self, other): + if isinstance(other, list): + return other + list(self) + if isinstance(other, tuple): + return other + tuple(self) + return NotImplemented + + @property + def artists(self): + return self.ArtistList(self, 'artists', invalid_types=( + mcoll.Collection, mimage.AxesImage, mlines.Line2D, mpatches.Patch, + mtable.Table, mtext.Text)) + + @property + def collections(self): + return self.ArtistList(self, 'collections', + valid_types=mcoll.Collection) + + @property + def images(self): + return self.ArtistList(self, 'images', valid_types=mimage.AxesImage) + + @property + def lines(self): + return self.ArtistList(self, 'lines', valid_types=mlines.Line2D) + + @property + def patches(self): + return self.ArtistList(self, 'patches', valid_types=mpatches.Patch) + + @property + def tables(self): + return self.ArtistList(self, 'tables', valid_types=mtable.Table) + + @property + def texts(self): + return self.ArtistList(self, 'texts', valid_types=mtext.Text) + + def get_facecolor(self): + """Get the facecolor of the Axes.""" + return self.patch.get_facecolor() + + def set_facecolor(self, color): + """ + Set the facecolor of the Axes. + + Parameters + ---------- + color : :mpltype:`color` + """ + self._facecolor = color + self.stale = True + return self.patch.set_facecolor(color) + + def _set_title_offset_trans(self, title_offset_points): + """ + Set the offset for the title either from :rc:`axes.titlepad` + or from set_title kwarg ``pad``. + """ + self.titleOffsetTrans = mtransforms.ScaledTranslation( + 0.0, title_offset_points / 72, + self.figure.dpi_scale_trans) + for _title in (self.title, self._left_title, self._right_title): + _title.set_transform(self.transAxes + self.titleOffsetTrans) + _title.set_clip_box(None) + + def set_prop_cycle(self, *args, **kwargs): + """ + Set the property cycle of the Axes. + + The property cycle controls the style properties such as color, + marker and linestyle of future plot commands. The style properties + of data already added to the Axes are not modified. + + Call signatures:: + + set_prop_cycle(cycler) + set_prop_cycle(label=values[, label2=values2[, ...]]) + set_prop_cycle(label, values) + + Form 1 sets given `~cycler.Cycler` object. + + Form 2 creates a `~cycler.Cycler` which cycles over one or more + properties simultaneously and set it as the property cycle of the + Axes. If multiple properties are given, their value lists must have + the same length. This is just a shortcut for explicitly creating a + cycler and passing it to the function, i.e. it's short for + ``set_prop_cycle(cycler(label=values, label2=values2, ...))``. + + Form 3 creates a `~cycler.Cycler` for a single property and set it + as the property cycle of the Axes. This form exists for compatibility + with the original `cycler.cycler` interface. Its use is discouraged + in favor of the kwarg form, i.e. ``set_prop_cycle(label=values)``. + + Parameters + ---------- + cycler : `~cycler.Cycler` + Set the given Cycler. *None* resets to the cycle defined by the + current style. + + .. ACCEPTS: `~cycler.Cycler` + + label : str + The property key. Must be a valid `.Artist` property. + For example, 'color' or 'linestyle'. Aliases are allowed, + such as 'c' for 'color' and 'lw' for 'linewidth'. + + values : iterable + Finite-length iterable of the property values. These values + are validated and will raise a ValueError if invalid. + + See Also + -------- + matplotlib.rcsetup.cycler + Convenience function for creating validated cyclers for properties. + cycler.cycler + The original function for creating unvalidated cyclers. + + Examples + -------- + Setting the property cycle for a single property: + + >>> ax.set_prop_cycle(color=['red', 'green', 'blue']) + + Setting the property cycle for simultaneously cycling over multiple + properties (e.g. red circle, green plus, blue cross): + + >>> ax.set_prop_cycle(color=['red', 'green', 'blue'], + ... marker=['o', '+', 'x']) + + """ + if args and kwargs: + raise TypeError("Cannot supply both positional and keyword " + "arguments to this method.") + # Can't do `args == (None,)` as that crashes cycler. + if len(args) == 1 and args[0] is None: + prop_cycle = None + else: + prop_cycle = cycler(*args, **kwargs) + self._get_lines.set_prop_cycle(prop_cycle) + self._get_patches_for_fill.set_prop_cycle(prop_cycle) + + def get_aspect(self): + """ + Return the aspect ratio of the Axes scaling. + + This is either "auto" or a float giving the ratio of y/x-scale. + """ + return self._aspect + + def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): + """ + Set the aspect ratio of the Axes scaling, i.e. y/x-scale. + + Parameters + ---------- + aspect : {'auto', 'equal'} or float + Possible values: + + - 'auto': fill the position rectangle with data. + - 'equal': same as ``aspect=1``, i.e. same scaling for x and y. + - *float*: The displayed size of 1 unit in y-data coordinates will + be *aspect* times the displayed size of 1 unit in x-data + coordinates; e.g. for ``aspect=2`` a square in data coordinates + will be rendered with a height of twice its width. + + adjustable : None or {'box', 'datalim'}, optional + If not ``None``, this defines which parameter will be adjusted to + meet the required aspect. See `.set_adjustable` for further + details. + + anchor : None or str or (float, float), optional + If not ``None``, this defines where the Axes will be drawn if there + is extra space due to aspect constraints. The most common way + to specify the anchor are abbreviations of cardinal directions: + + ===== ===================== + value description + ===== ===================== + 'C' centered + 'SW' lower left corner + 'S' middle of bottom edge + 'SE' lower right corner + etc. + ===== ===================== + + See `~.Axes.set_anchor` for further details. + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_anchor + Set the position in case of extra space. + """ + if cbook._str_equal(aspect, 'equal'): + aspect = 1 + if not cbook._str_equal(aspect, 'auto'): + aspect = float(aspect) # raise ValueError if necessary + if aspect <= 0 or not np.isfinite(aspect): + raise ValueError("aspect must be finite and positive ") + + if share: + axes = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axes = [self] + + for ax in axes: + ax._aspect = aspect + + if adjustable is None: + adjustable = self._adjustable + self.set_adjustable(adjustable, share=share) # Handle sharing. + + if anchor is not None: + self.set_anchor(anchor, share=share) + self.stale = True + + def get_adjustable(self): + """ + Return whether the Axes will adjust its physical dimension ('box') or + its data limits ('datalim') to achieve the desired aspect ratio. + + See Also + -------- + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_aspect + For a description of aspect handling. + """ + return self._adjustable + + def set_adjustable(self, adjustable, share=False): + """ + Set how the Axes adjusts to achieve the required aspect ratio. + + Parameters + ---------- + adjustable : {'box', 'datalim'} + If 'box', change the physical dimensions of the Axes. + If 'datalim', change the ``x`` or ``y`` data limits. + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + For a description of aspect handling. + + Notes + ----- + Shared Axes (of which twinned Axes are a special case) + impose restrictions on how aspect ratios can be imposed. + For twinned Axes, use 'datalim'. For Axes that share both + x and y, use 'box'. Otherwise, either 'datalim' or 'box' + may be used. These limitations are partly a requirement + to avoid over-specification, and partly a result of the + particular implementation we are currently using, in + which the adjustments for aspect ratios are done sequentially + and independently on each Axes as it is drawn. + """ + _api.check_in_list(["box", "datalim"], adjustable=adjustable) + if share: + axs = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axs = [self] + if (adjustable == "datalim" + and any(getattr(ax.get_data_ratio, "__func__", None) + != _AxesBase.get_data_ratio + for ax in axs)): + # Limits adjustment by apply_aspect assumes that the axes' aspect + # ratio can be computed from the data limits and scales. + raise ValueError("Cannot set Axes adjustable to 'datalim' for " + "Axes which override 'get_data_ratio'") + for ax in axs: + ax._adjustable = adjustable + self.stale = True + + def get_box_aspect(self): + """ + Return the Axes box aspect, i.e. the ratio of height to width. + + The box aspect is ``None`` (i.e. chosen depending on the available + figure space) unless explicitly specified. + + See Also + -------- + matplotlib.axes.Axes.set_box_aspect + for a description of box aspect. + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + return self._box_aspect + + def set_box_aspect(self, aspect=None): + """ + Set the Axes box aspect, i.e. the ratio of height to width. + + This defines the aspect of the Axes in figure space and is not to be + confused with the data aspect (see `~.Axes.set_aspect`). + + Parameters + ---------- + aspect : float or None + Changes the physical dimensions of the Axes, such that the ratio + of the Axes height to the Axes width in physical units is equal to + *aspect*. Defining a box aspect will change the *adjustable* + property to 'datalim' (see `~.Axes.set_adjustable`). + + *None* will disable a fixed box aspect so that height and width + of the Axes are chosen independently. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + axs = {*self._twinned_axes.get_siblings(self), + *self._twinned_axes.get_siblings(self)} + + if aspect is not None: + aspect = float(aspect) + # when box_aspect is set to other than ´None`, + # adjustable must be "datalim" + for ax in axs: + ax.set_adjustable("datalim") + + for ax in axs: + ax._box_aspect = aspect + ax.stale = True + + def get_anchor(self): + """ + Get the anchor location. + + See Also + -------- + matplotlib.axes.Axes.set_anchor + for a description of the anchor. + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + return self._anchor + + def set_anchor(self, anchor, share=False): + """ + Define the anchor location. + + The actual drawing area (active position) of the Axes may be smaller + than the Bbox (original position) when a fixed aspect is required. The + anchor defines where the drawing area will be located within the + available space. + + Parameters + ---------- + anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} + Either an (*x*, *y*) pair of relative coordinates (0 is left or + bottom, 1 is right or top), 'C' (center), or a cardinal direction + ('SW', southwest, is bottom left, etc.). str inputs are shorthands + for (*x*, *y*) coordinates, as shown in the following diagram:: + + ┌─────────────────┬─────────────────┬─────────────────┐ + │ 'NW' (0.0, 1.0) │ 'N' (0.5, 1.0) │ 'NE' (1.0, 1.0) │ + ├─────────────────┼─────────────────┼─────────────────┤ + │ 'W' (0.0, 0.5) │ 'C' (0.5, 0.5) │ 'E' (1.0, 0.5) │ + ├─────────────────┼─────────────────┼─────────────────┤ + │ 'SW' (0.0, 0.0) │ 'S' (0.5, 0.0) │ 'SE' (1.0, 0.0) │ + └─────────────────┴─────────────────┴─────────────────┘ + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + if not (anchor in mtransforms.Bbox.coefs or len(anchor) == 2): + raise ValueError('argument must be among %s' % + ', '.join(mtransforms.Bbox.coefs)) + if share: + axes = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axes = [self] + for ax in axes: + ax._anchor = anchor + + self.stale = True + + def get_data_ratio(self): + """ + Return the aspect ratio of the scaled data. + + Notes + ----- + This method is intended to be overridden by new projection types. + """ + txmin, txmax = self.xaxis.get_transform().transform(self.get_xbound()) + tymin, tymax = self.yaxis.get_transform().transform(self.get_ybound()) + xsize = max(abs(txmax - txmin), 1e-30) + ysize = max(abs(tymax - tymin), 1e-30) + return ysize / xsize + + def apply_aspect(self, position=None): + """ + Adjust the Axes for a specified data aspect ratio. + + Depending on `.get_adjustable` this will modify either the + Axes box (position) or the view limits. In the former case, + `~matplotlib.axes.Axes.get_anchor` will affect the position. + + Parameters + ---------- + position : None or .Bbox + + .. note:: + This parameter exists for historic reasons and is considered + internal. End users should not use it. + + If not ``None``, this defines the position of the + Axes within the figure as a Bbox. See `~.Axes.get_position` + for further details. + + Notes + ----- + This is called automatically when each Axes is drawn. You may need + to call it yourself if you need to update the Axes position and/or + view limits before the Figure is drawn. + + An alternative with a broader scope is `.Figure.draw_without_rendering`, + which updates all stale components of a figure, not only the positioning / + view limits of a single Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + For a description of aspect ratio handling. + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_anchor + Set the position in case of extra space. + matplotlib.figure.Figure.draw_without_rendering + Update all stale components of a figure. + + Examples + -------- + A typical usage example would be the following. `~.Axes.imshow` sets the + aspect to 1, but adapting the Axes position and extent to reflect this is + deferred until rendering for performance reasons. If you want to know the + Axes size before, you need to call `.apply_aspect` to get the correct + values. + + >>> fig, ax = plt.subplots() + >>> ax.imshow(np.zeros((3, 3))) + >>> ax.bbox.width, ax.bbox.height + (496.0, 369.59999999999997) + >>> ax.apply_aspect() + >>> ax.bbox.width, ax.bbox.height + (369.59999999999997, 369.59999999999997) + """ + if position is None: + position = self.get_position(original=True) + + aspect = self.get_aspect() + + if aspect == 'auto' and self._box_aspect is None: + self._set_position(position, which='active') + return + + trans = self.get_figure().transSubfigure + bb = mtransforms.Bbox.unit().transformed(trans) + # this is the physical aspect of the panel (or figure): + fig_aspect = bb.height / bb.width + + if self._adjustable == 'box': + if self in self._twinned_axes: + raise RuntimeError("Adjustable 'box' is not allowed in a " + "twinned Axes; use 'datalim' instead") + box_aspect = aspect * self.get_data_ratio() + pb = position.frozen() + pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect) + self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') + return + + # The following is only seen if self._adjustable == 'datalim' + if self._box_aspect is not None: + pb = position.frozen() + pb1 = pb.shrunk_to_aspect(self._box_aspect, pb, fig_aspect) + self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') + if aspect == "auto": + return + + # reset active to original in case it had been changed by prior use + # of 'box' + if self._box_aspect is None: + self._set_position(position, which='active') + else: + position = pb1.anchored(self.get_anchor(), pb) + + x_trf = self.xaxis.get_transform() + y_trf = self.yaxis.get_transform() + xmin, xmax = x_trf.transform(self.get_xbound()) + ymin, ymax = y_trf.transform(self.get_ybound()) + xsize = max(abs(xmax - xmin), 1e-30) + ysize = max(abs(ymax - ymin), 1e-30) + + box_aspect = fig_aspect * (position.height / position.width) + data_ratio = box_aspect / aspect + + y_expander = data_ratio * xsize / ysize - 1 + # If y_expander > 0, the dy/dx viewLim ratio needs to increase + if abs(y_expander) < 0.005: + return + + dL = self.dataLim + x0, x1 = x_trf.transform(dL.intervalx) + y0, y1 = y_trf.transform(dL.intervaly) + xr = 1.05 * (x1 - x0) + yr = 1.05 * (y1 - y0) + + xmarg = xsize - xr + ymarg = ysize - yr + Ysize = data_ratio * xsize + Xsize = ysize / data_ratio + Xmarg = Xsize - xr + Ymarg = Ysize - yr + # Setting these targets to, e.g., 0.05*xr does not seem to help. + xm = 0 + ym = 0 + + shared_x = self in self._shared_axes["x"] + shared_y = self in self._shared_axes["y"] + + if shared_x and shared_y: + raise RuntimeError("set_aspect(..., adjustable='datalim') or " + "axis('equal') are not allowed when both axes " + "are shared. Try set_aspect(..., " + "adjustable='box').") + + # If y is shared, then we are only allowed to change x, etc. + if shared_y: + adjust_y = False + else: + if xmarg > xm and ymarg > ym: + adjy = ((Ymarg > 0 and y_expander < 0) or + (Xmarg < 0 and y_expander > 0)) + else: + adjy = y_expander > 0 + adjust_y = shared_x or adjy # (Ymarg > xmarg) + + if adjust_y: + yc = 0.5 * (ymin + ymax) + y0 = yc - Ysize / 2.0 + y1 = yc + Ysize / 2.0 + self.set_ybound(y_trf.inverted().transform([y0, y1])) + else: + xc = 0.5 * (xmin + xmax) + x0 = xc - Xsize / 2.0 + x1 = xc + Xsize / 2.0 + self.set_xbound(x_trf.inverted().transform([x0, x1])) + + def axis(self, arg=None, /, *, emit=True, **kwargs): + """ + Convenience method to get or set some axis properties. + + Call signatures:: + + xmin, xmax, ymin, ymax = axis() + xmin, xmax, ymin, ymax = axis([xmin, xmax, ymin, ymax]) + xmin, xmax, ymin, ymax = axis(option) + xmin, xmax, ymin, ymax = axis(**kwargs) + + Parameters + ---------- + xmin, xmax, ymin, ymax : float, optional + The axis limits to be set. This can also be achieved using :: + + ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax)) + + option : bool or str + If a bool, turns axis lines and labels on or off. If a string, + possible values are: + + ================ =========================================================== + Value Description + ================ =========================================================== + 'off' or `False` Hide all axis decorations, i.e. axis labels, spines, + tick marks, tick labels, and grid lines. + This is the same as `~.Axes.set_axis_off()`. + 'on' or `True` Do not hide all axis decorations, i.e. axis labels, spines, + tick marks, tick labels, and grid lines. + This is the same as `~.Axes.set_axis_on()`. + 'equal' Set equal scaling (i.e., make circles circular) by + changing the axis limits. This is the same as + ``ax.set_aspect('equal', adjustable='datalim')``. + Explicit data limits may not be respected in this case. + 'scaled' Set equal scaling (i.e., make circles circular) by + changing dimensions of the plot box. This is the same as + ``ax.set_aspect('equal', adjustable='box', anchor='C')``. + Additionally, further autoscaling will be disabled. + 'tight' Set limits just large enough to show all data, then + disable further autoscaling. + 'auto' Automatic scaling (fill plot box with data). + 'image' 'scaled' with axis limits equal to data limits. + 'square' Square plot; similar to 'scaled', but initially forcing + ``xmax-xmin == ymax-ymin``. + ================ =========================================================== + + emit : bool, default: True + Whether observers are notified of the axis limit change. + This option is passed on to `~.Axes.set_xlim` and + `~.Axes.set_ylim`. + + Returns + ------- + xmin, xmax, ymin, ymax : float + The axis limits. + + See Also + -------- + matplotlib.axes.Axes.set_xlim + matplotlib.axes.Axes.set_ylim + + Notes + ----- + For 3D Axes, this method additionally takes *zmin*, *zmax* as + parameters and likewise returns them. + """ + if isinstance(arg, (str, bool)): + if arg is True: + arg = 'on' + if arg is False: + arg = 'off' + arg = arg.lower() + if arg == 'on': + self.set_axis_on() + elif arg == 'off': + self.set_axis_off() + elif arg in [ + 'equal', 'tight', 'scaled', 'auto', 'image', 'square']: + self.set_autoscale_on(True) + self.set_aspect('auto') + self.autoscale_view(tight=False) + if arg == 'equal': + self.set_aspect('equal', adjustable='datalim') + elif arg == 'scaled': + self.set_aspect('equal', adjustable='box', anchor='C') + self.set_autoscale_on(False) # Req. by Mark Bakker + elif arg == 'tight': + self.autoscale_view(tight=True) + self.set_autoscale_on(False) + elif arg == 'image': + self.autoscale_view(tight=True) + self.set_autoscale_on(False) + self.set_aspect('equal', adjustable='box', anchor='C') + elif arg == 'square': + self.set_aspect('equal', adjustable='box', anchor='C') + self.set_autoscale_on(False) + xlim = self.get_xlim() + ylim = self.get_ylim() + edge_size = max(np.diff(xlim), np.diff(ylim))[0] + self.set_xlim([xlim[0], xlim[0] + edge_size], + emit=emit, auto=False) + self.set_ylim([ylim[0], ylim[0] + edge_size], + emit=emit, auto=False) + else: + raise ValueError(f"Unrecognized string {arg!r} to axis; " + "try 'on' or 'off'") + else: + if arg is not None: + if len(arg) != 2*len(self._axis_names): + raise TypeError( + "The first argument to axis() must be an iterable of the form " + "[{}]".format(", ".join( + f"{name}min, {name}max" for name in self._axis_names))) + limits = { + name: arg[2*i:2*(i+1)] + for i, name in enumerate(self._axis_names) + } + else: + limits = {} + for name in self._axis_names: + ax_min = kwargs.pop(f'{name}min', None) + ax_max = kwargs.pop(f'{name}max', None) + limits[name] = (ax_min, ax_max) + for name, (ax_min, ax_max) in limits.items(): + ax_auto = (None # Keep autoscale state as is. + if ax_min is None and ax_max is None + else False) # Turn off autoscale. + set_ax_lim = getattr(self, f'set_{name}lim') + set_ax_lim(ax_min, ax_max, emit=emit, auto=ax_auto) + if kwargs: + raise _api.kwarg_error("axis", kwargs) + lims = () + for name in self._axis_names: + get_ax_lim = getattr(self, f'get_{name}lim') + lims += get_ax_lim() + return lims + + def get_legend(self): + """Return the `.Legend` instance, or None if no legend is defined.""" + return self.legend_ + + def get_images(self): + r"""Return a list of `.AxesImage`\s contained by the Axes.""" + return cbook.silent_list('AxesImage', self.images) + + def get_lines(self): + """Return a list of lines contained by the Axes.""" + return cbook.silent_list('Line2D', self.lines) + + def get_xaxis(self): + """ + [*Discouraged*] Return the XAxis instance. + + .. admonition:: Discouraged + + The use of this function is discouraged. You should instead + directly access the attribute ``ax.xaxis``. + """ + return self.xaxis + + def get_yaxis(self): + """ + [*Discouraged*] Return the YAxis instance. + + .. admonition:: Discouraged + + The use of this function is discouraged. You should instead + directly access the attribute ``ax.yaxis``. + """ + return self.yaxis + + get_xgridlines = _axis_method_wrapper("xaxis", "get_gridlines") + get_xticklines = _axis_method_wrapper("xaxis", "get_ticklines") + get_ygridlines = _axis_method_wrapper("yaxis", "get_gridlines") + get_yticklines = _axis_method_wrapper("yaxis", "get_ticklines") + + # Adding and tracking artists + + def _sci(self, im): + """ + Set the current image. + + This image will be the target of colormap functions like + ``pyplot.viridis``, and other functions such as `~.pyplot.clim`. The + current image is an attribute of the current Axes. + """ + _api.check_isinstance((mcoll.Collection, mimage.AxesImage), im=im) + if im not in self._children: + raise ValueError("Argument must be an image or collection in this Axes") + self._current_image = im + + def _gci(self): + """Helper for `~matplotlib.pyplot.gci`; do not use elsewhere.""" + return self._current_image + + def has_data(self): + """ + Return whether any artists have been added to the Axes. + + This should not be used to determine whether the *dataLim* + need to be updated, and may not actually be useful for + anything. + """ + return any(isinstance(a, (mcoll.Collection, mimage.AxesImage, + mlines.Line2D, mpatches.Patch)) + for a in self._children) + + def add_artist(self, a): + """ + Add an `.Artist` to the Axes; return the artist. + + Use `add_artist` only for artists for which there is no dedicated + "add" method; and if necessary, use a method such as `update_datalim` + to manually update the dataLim if the artist is to be included in + autoscaling. + + If no ``transform`` has been specified when creating the artist (e.g. + ``artist.get_transform() == None``) then the transform is set to + ``ax.transData``. + """ + a.axes = self + self._children.append(a) + a._remove_method = self._children.remove + self._set_artist_props(a) + if a.get_clip_path() is None: + a.set_clip_path(self.patch) + self.stale = True + return a + + def add_child_axes(self, ax): + """ + Add an `.AxesBase` to the Axes' children; return the child Axes. + + This is the lowlevel version. See `.axes.Axes.inset_axes`. + """ + + # normally Axes have themselves as the Axes, but these need to have + # their parent... + # Need to bypass the getter... + ax._axes = self + ax.stale_callback = martist._stale_axes_callback + + self.child_axes.append(ax) + ax._remove_method = functools.partial( + self.figure._remove_axes, owners=[self.child_axes]) + self.stale = True + return ax + + def add_collection(self, collection, autolim=True): + """ + Add a `.Collection` to the Axes; return the collection. + """ + _api.check_isinstance(mcoll.Collection, collection=collection) + if not collection.get_label(): + collection.set_label(f'_child{len(self._children)}') + self._children.append(collection) + collection._remove_method = self._children.remove + self._set_artist_props(collection) + + if collection.get_clip_path() is None: + collection.set_clip_path(self.patch) + + if autolim: + # Make sure viewLim is not stale (mostly to match + # pre-lazy-autoscale behavior, which is not really better). + self._unstale_viewLim() + datalim = collection.get_datalim(self.transData) + points = datalim.get_points() + if not np.isinf(datalim.minpos).all(): + # By definition, if minpos (minimum positive value) is set + # (i.e., non-inf), then min(points) <= minpos <= max(points), + # and minpos would be superfluous. However, we add minpos to + # the call so that self.dataLim will update its own minpos. + # This ensures that log scales see the correct minimum. + points = np.concatenate([points, [datalim.minpos]]) + self.update_datalim(points) + + self.stale = True + return collection + + def add_image(self, image): + """ + Add an `.AxesImage` to the Axes; return the image. + """ + _api.check_isinstance(mimage.AxesImage, image=image) + self._set_artist_props(image) + if not image.get_label(): + image.set_label(f'_child{len(self._children)}') + self._children.append(image) + image._remove_method = self._children.remove + self.stale = True + return image + + def _update_image_limits(self, image): + xmin, xmax, ymin, ymax = image.get_extent() + self.axes.update_datalim(((xmin, ymin), (xmax, ymax))) + + def add_line(self, line): + """ + Add a `.Line2D` to the Axes; return the line. + """ + _api.check_isinstance(mlines.Line2D, line=line) + self._set_artist_props(line) + if line.get_clip_path() is None: + line.set_clip_path(self.patch) + + self._update_line_limits(line) + if not line.get_label(): + line.set_label(f'_child{len(self._children)}') + self._children.append(line) + line._remove_method = self._children.remove + self.stale = True + return line + + def _add_text(self, txt): + """ + Add a `.Text` to the Axes; return the text. + """ + _api.check_isinstance(mtext.Text, txt=txt) + self._set_artist_props(txt) + self._children.append(txt) + txt._remove_method = self._children.remove + self.stale = True + return txt + + def _update_line_limits(self, line): + """ + Figures out the data limit of the given line, updating self.dataLim. + """ + path = line.get_path() + if path.vertices.size == 0: + return + + line_trf = line.get_transform() + + if line_trf == self.transData: + data_path = path + elif any(line_trf.contains_branch_seperately(self.transData)): + # Compute the transform from line coordinates to data coordinates. + trf_to_data = line_trf - self.transData + # If transData is affine we can use the cached non-affine component + # of line's path (since the non-affine part of line_trf is + # entirely encapsulated in trf_to_data). + if self.transData.is_affine: + line_trans_path = line._get_transformed_path() + na_path, _ = line_trans_path.get_transformed_path_and_affine() + data_path = trf_to_data.transform_path_affine(na_path) + else: + data_path = trf_to_data.transform_path(path) + else: + # For backwards compatibility we update the dataLim with the + # coordinate range of the given path, even though the coordinate + # systems are completely different. This may occur in situations + # such as when ax.transAxes is passed through for absolute + # positioning. + data_path = path + + if not data_path.vertices.size: + return + + updatex, updatey = line_trf.contains_branch_seperately(self.transData) + if self.name != "rectilinear": + # This block is mostly intended to handle axvline in polar plots, + # for which updatey would otherwise be True. + if updatex and line_trf == self.get_yaxis_transform(): + updatex = False + if updatey and line_trf == self.get_xaxis_transform(): + updatey = False + self.dataLim.update_from_path(data_path, + self.ignore_existing_data_limits, + updatex=updatex, updatey=updatey) + self.ignore_existing_data_limits = False + + def add_patch(self, p): + """ + Add a `.Patch` to the Axes; return the patch. + """ + _api.check_isinstance(mpatches.Patch, p=p) + self._set_artist_props(p) + if p.get_clip_path() is None: + p.set_clip_path(self.patch) + self._update_patch_limits(p) + self._children.append(p) + p._remove_method = self._children.remove + return p + + def _update_patch_limits(self, patch): + """Update the data limits for the given patch.""" + # hist can add zero height Rectangles, which is useful to keep + # the bins, counts and patches lined up, but it throws off log + # scaling. We'll ignore rects with zero height or width in + # the auto-scaling + + # cannot check for '==0' since unitized data may not compare to zero + # issue #2150 - we update the limits if patch has non zero width + # or height. + if (isinstance(patch, mpatches.Rectangle) and + ((not patch.get_width()) and (not patch.get_height()))): + return + p = patch.get_path() + # Get all vertices on the path + # Loop through each segment to get extrema for Bezier curve sections + vertices = [] + for curve, code in p.iter_bezier(simplify=False): + # Get distance along the curve of any extrema + _, dzeros = curve.axis_aligned_extrema() + # Calculate vertices of start, end and any extrema in between + vertices.append(curve([0, *dzeros, 1])) + + if len(vertices): + vertices = np.vstack(vertices) + + patch_trf = patch.get_transform() + updatex, updatey = patch_trf.contains_branch_seperately(self.transData) + if not (updatex or updatey): + return + if self.name != "rectilinear": + # As in _update_line_limits, but for axvspan. + if updatex and patch_trf == self.get_yaxis_transform(): + updatex = False + if updatey and patch_trf == self.get_xaxis_transform(): + updatey = False + trf_to_data = patch_trf - self.transData + xys = trf_to_data.transform(vertices) + self.update_datalim(xys, updatex=updatex, updatey=updatey) + + def add_table(self, tab): + """ + Add a `.Table` to the Axes; return the table. + """ + _api.check_isinstance(mtable.Table, tab=tab) + self._set_artist_props(tab) + self._children.append(tab) + if tab.get_clip_path() is None: + tab.set_clip_path(self.patch) + tab._remove_method = self._children.remove + return tab + + def add_container(self, container): + """ + Add a `.Container` to the Axes' containers; return the container. + """ + label = container.get_label() + if not label: + container.set_label('_container%d' % len(self.containers)) + self.containers.append(container) + container._remove_method = self.containers.remove + return container + + def _unit_change_handler(self, axis_name, event=None): + """ + Process axis units changes: requests updates to data and view limits. + """ + if event is None: # Allow connecting `self._unit_change_handler(name)` + return functools.partial( + self._unit_change_handler, axis_name, event=object()) + _api.check_in_list(self._axis_map, axis_name=axis_name) + for line in self.lines: + line.recache_always() + self.relim() + self._request_autoscale_view(axis_name) + + def relim(self, visible_only=False): + """ + Recompute the data limits based on current artists. + + At present, `.Collection` instances are not supported. + + Parameters + ---------- + visible_only : bool, default: False + Whether to exclude invisible artists. + """ + # Collections are deliberately not supported (yet); see + # the TODO note in artists.py. + self.dataLim.ignore(True) + self.dataLim.set_points(mtransforms.Bbox.null().get_points()) + self.ignore_existing_data_limits = True + + for artist in self._children: + if not visible_only or artist.get_visible(): + if isinstance(artist, mlines.Line2D): + self._update_line_limits(artist) + elif isinstance(artist, mpatches.Patch): + self._update_patch_limits(artist) + elif isinstance(artist, mimage.AxesImage): + self._update_image_limits(artist) + + def update_datalim(self, xys, updatex=True, updatey=True): + """ + Extend the `~.Axes.dataLim` Bbox to include the given points. + + If no data is set currently, the Bbox will ignore its limits and set + the bound to be the bounds of the xydata (*xys*). Otherwise, it will + compute the bounds of the union of its current data and the data in + *xys*. + + Parameters + ---------- + xys : 2D array-like + The points to include in the data limits Bbox. This can be either + a list of (x, y) tuples or a (N, 2) array. + + updatex, updatey : bool, default: True + Whether to update the x/y limits. + """ + xys = np.asarray(xys) + if not np.any(np.isfinite(xys)): + return + self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits, + updatex=updatex, updatey=updatey) + self.ignore_existing_data_limits = False + + def _process_unit_info(self, datasets=None, kwargs=None, *, convert=True): + """ + Set axis units based on *datasets* and *kwargs*, and optionally apply + unit conversions to *datasets*. + + Parameters + ---------- + datasets : list + List of (axis_name, dataset) pairs (where the axis name is defined + as in `._axis_map`). Individual datasets can also be None + (which gets passed through). + kwargs : dict + Other parameters from which unit info (i.e., the *xunits*, + *yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for + polar) entries) is popped, if present. Note that this dict is + mutated in-place! + convert : bool, default: True + Whether to return the original datasets or the converted ones. + + Returns + ------- + list + Either the original datasets if *convert* is False, or the + converted ones if *convert* is True (the default). + """ + # The API makes datasets a list of pairs rather than an axis_name to + # dataset mapping because it is sometimes necessary to process multiple + # datasets for a single axis, and concatenating them may be tricky + # (e.g. if some are scalars, etc.). + datasets = datasets or [] + kwargs = kwargs or {} + axis_map = self._axis_map + for axis_name, data in datasets: + try: + axis = axis_map[axis_name] + except KeyError: + raise ValueError(f"Invalid axis name: {axis_name!r}") from None + # Update from data if axis is already set but no unit is set yet. + if axis is not None and data is not None and not axis.have_units(): + axis.update_units(data) + for axis_name, axis in axis_map.items(): + # Return if no axis is set. + if axis is None: + continue + # Check for units in the kwargs, and if present update axis. + units = kwargs.pop(f"{axis_name}units", axis.units) + if self.name == "polar": + # Special case: polar supports "thetaunits"/"runits". + polar_units = {"x": "thetaunits", "y": "runits"} + units = kwargs.pop(polar_units[axis_name], units) + if units != axis.units and units is not None: + axis.set_units(units) + # If the units being set imply a different converter, + # we need to update again. + for dataset_axis_name, data in datasets: + if dataset_axis_name == axis_name and data is not None: + axis.update_units(data) + return [axis_map[axis_name].convert_units(data) + if convert and data is not None else data + for axis_name, data in datasets] + + def in_axes(self, mouseevent): + """ + Return whether the given event (in display coords) is in the Axes. + """ + return self.patch.contains(mouseevent)[0] + + get_autoscalex_on = _axis_method_wrapper("xaxis", "_get_autoscale_on") + get_autoscaley_on = _axis_method_wrapper("yaxis", "_get_autoscale_on") + set_autoscalex_on = _axis_method_wrapper("xaxis", "_set_autoscale_on") + set_autoscaley_on = _axis_method_wrapper("yaxis", "_set_autoscale_on") + + def get_autoscale_on(self): + """Return True if each axis is autoscaled, False otherwise.""" + return all(axis._get_autoscale_on() + for axis in self._axis_map.values()) + + def set_autoscale_on(self, b): + """ + Set whether autoscaling is applied to each axis on the next draw or + call to `.Axes.autoscale_view`. + + Parameters + ---------- + b : bool + """ + for axis in self._axis_map.values(): + axis._set_autoscale_on(b) + + @property + def use_sticky_edges(self): + """ + When autoscaling, whether to obey all `Artist.sticky_edges`. + + Default is ``True``. + + Setting this to ``False`` ensures that the specified margins + will be applied, even if the plot includes an image, for + example, which would otherwise force a view limit to coincide + with its data limit. + + The changing this property does not change the plot until + `autoscale` or `autoscale_view` is called. + """ + return self._use_sticky_edges + + @use_sticky_edges.setter + def use_sticky_edges(self, b): + self._use_sticky_edges = bool(b) + # No effect until next autoscaling, which will mark the Axes as stale. + + def get_xmargin(self): + """ + Retrieve autoscaling margin of the x-axis. + + .. versionadded:: 3.9 + + Returns + ------- + xmargin : float + + See Also + -------- + matplotlib.axes.Axes.set_xmargin + """ + return self._xmargin + + def get_ymargin(self): + """ + Retrieve autoscaling margin of the y-axis. + + .. versionadded:: 3.9 + + Returns + ------- + ymargin : float + + See Also + -------- + matplotlib.axes.Axes.set_ymargin + """ + return self._ymargin + + def set_xmargin(self, m): + """ + Set padding of X data limits prior to autoscaling. + + *m* times the data interval will be added to each end of that interval + before it is used in autoscaling. If *m* is negative, this will clip + the data range instead of expanding it. + + For example, if your data is in the range [0, 2], a margin of 0.1 will + result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range + of [0.2, 1.8]. + + Parameters + ---------- + m : float greater than -0.5 + """ + if m <= -0.5: + raise ValueError("margin must be greater than -0.5") + self._xmargin = m + self._request_autoscale_view("x") + self.stale = True + + def set_ymargin(self, m): + """ + Set padding of Y data limits prior to autoscaling. + + *m* times the data interval will be added to each end of that interval + before it is used in autoscaling. If *m* is negative, this will clip + the data range instead of expanding it. + + For example, if your data is in the range [0, 2], a margin of 0.1 will + result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range + of [0.2, 1.8]. + + Parameters + ---------- + m : float greater than -0.5 + """ + if m <= -0.5: + raise ValueError("margin must be greater than -0.5") + self._ymargin = m + self._request_autoscale_view("y") + self.stale = True + + def margins(self, *margins, x=None, y=None, tight=True): + """ + Set or retrieve autoscaling margins. + + The padding added to each limit of the Axes is the *margin* + times the data interval. All input parameters must be floats + greater than -0.5. Passing both positional and keyword + arguments is invalid and will raise a TypeError. If no + arguments (positional or otherwise) are provided, the current + margins will remain unchanged and simply be returned. + + Specifying any margin changes only the autoscaling; for example, + if *xmargin* is not None, then *xmargin* times the X data + interval will be added to each end of that interval before + it is used in autoscaling. + + Parameters + ---------- + *margins : float, optional + If a single positional argument is provided, it specifies + both margins of the x-axis and y-axis limits. If two + positional arguments are provided, they will be interpreted + as *xmargin*, *ymargin*. If setting the margin on a single + axis is desired, use the keyword arguments described below. + + x, y : float, optional + Specific margin values for the x-axis and y-axis, + respectively. These cannot be used with positional + arguments, but can be used individually to alter on e.g., + only the y-axis. + + tight : bool or None, default: True + The *tight* parameter is passed to `~.axes.Axes.autoscale_view`, + which is executed after a margin is changed; the default + here is *True*, on the assumption that when margins are + specified, no additional padding to match tick marks is + usually desired. Setting *tight* to *None* preserves + the previous setting. + + Returns + ------- + xmargin, ymargin : float + + Notes + ----- + If a previously used Axes method such as :meth:`pcolor` has set + :attr:`use_sticky_edges` to `True`, only the limits not set by + the "sticky artists" will be modified. To force all of the + margins to be set, set :attr:`use_sticky_edges` to `False` + before calling :meth:`margins`. + """ + + if margins and (x is not None or y is not None): + raise TypeError('Cannot pass both positional and keyword ' + 'arguments for x and/or y.') + elif len(margins) == 1: + x = y = margins[0] + elif len(margins) == 2: + x, y = margins + elif margins: + raise TypeError('Must pass a single positional argument for all ' + 'margins, or one for each margin (x, y).') + + if x is None and y is None: + if tight is not True: + _api.warn_external(f'ignoring tight={tight!r} in get mode') + return self._xmargin, self._ymargin + + if tight is not None: + self._tight = tight + if x is not None: + self.set_xmargin(x) + if y is not None: + self.set_ymargin(y) + + def set_rasterization_zorder(self, z): + """ + Set the zorder threshold for rasterization for vector graphics output. + + All artists with a zorder below the given value will be rasterized if + they support rasterization. + + This setting is ignored for pixel-based output. + + See also :doc:`/gallery/misc/rasterization_demo`. + + Parameters + ---------- + z : float or None + The zorder below which artists are rasterized. + If ``None`` rasterization based on zorder is deactivated. + """ + self._rasterization_zorder = z + self.stale = True + + def get_rasterization_zorder(self): + """Return the zorder value below which artists will be rasterized.""" + return self._rasterization_zorder + + def autoscale(self, enable=True, axis='both', tight=None): + """ + Autoscale the axis view to the data (toggle). + + Convenience method for simple axis view autoscaling. + It turns autoscaling on or off, and then, + if autoscaling for either axis is on, it performs + the autoscaling on the specified axis or Axes. + + Parameters + ---------- + enable : bool or None, default: True + True turns autoscaling on, False turns it off. + None leaves the autoscaling state unchanged. + axis : {'both', 'x', 'y'}, default: 'both' + The axis on which to operate. (For 3D Axes, *axis* can also be set + to 'z', and 'both' refers to all three Axes.) + tight : bool or None, default: None + If True, first set the margins to zero. Then, this argument is + forwarded to `~.axes.Axes.autoscale_view` (regardless of + its value); see the description of its behavior there. + """ + if enable is None: + scalex = True + scaley = True + else: + if axis in ['x', 'both']: + self.set_autoscalex_on(bool(enable)) + scalex = self.get_autoscalex_on() + else: + scalex = False + if axis in ['y', 'both']: + self.set_autoscaley_on(bool(enable)) + scaley = self.get_autoscaley_on() + else: + scaley = False + if tight and scalex: + self._xmargin = 0 + if tight and scaley: + self._ymargin = 0 + if scalex: + self._request_autoscale_view("x", tight=tight) + if scaley: + self._request_autoscale_view("y", tight=tight) + + def autoscale_view(self, tight=None, scalex=True, scaley=True): + """ + Autoscale the view limits using the data limits. + + Parameters + ---------- + tight : bool or None + If *True*, only expand the axis limits using the margins. Note + that unlike for `autoscale`, ``tight=True`` does *not* set the + margins to zero. + + If *False* and :rc:`axes.autolimit_mode` is 'round_numbers', then + after expansion by the margins, further expand the axis limits + using the axis major locator. + + If None (the default), reuse the value set in the previous call to + `autoscale_view` (the initial value is False, but the default style + sets :rc:`axes.autolimit_mode` to 'data', in which case this + behaves like True). + + scalex : bool, default: True + Whether to autoscale the x-axis. + + scaley : bool, default: True + Whether to autoscale the y-axis. + + Notes + ----- + The autoscaling preserves any preexisting axis direction reversal. + + The data limits are not updated automatically when artist data are + changed after the artist has been added to an Axes instance. In that + case, use :meth:`matplotlib.axes.Axes.relim` prior to calling + autoscale_view. + + If the views of the Axes are fixed, e.g. via `set_xlim`, they will + not be changed by autoscale_view(). + See :meth:`matplotlib.axes.Axes.autoscale` for an alternative. + """ + if tight is not None: + self._tight = bool(tight) + + x_stickies = y_stickies = np.array([]) + if self.use_sticky_edges: + if self._xmargin and scalex and self.get_autoscalex_on(): + x_stickies = np.sort(np.concatenate([ + artist.sticky_edges.x + for ax in self._shared_axes["x"].get_siblings(self) + for artist in ax.get_children()])) + if self._ymargin and scaley and self.get_autoscaley_on(): + y_stickies = np.sort(np.concatenate([ + artist.sticky_edges.y + for ax in self._shared_axes["y"].get_siblings(self) + for artist in ax.get_children()])) + if self.get_xscale() == 'log': + x_stickies = x_stickies[x_stickies > 0] + if self.get_yscale() == 'log': + y_stickies = y_stickies[y_stickies > 0] + + def handle_single_axis( + scale, shared_axes, name, axis, margin, stickies, set_bound): + + if not (scale and axis._get_autoscale_on()): + return # nothing to do... + + shared = shared_axes.get_siblings(self) + # Base autoscaling on finite data limits when there is at least one + # finite data limit among all the shared_axes and intervals. + values = [val for ax in shared + for val in getattr(ax.dataLim, f"interval{name}") + if np.isfinite(val)] + if values: + x0, x1 = (min(values), max(values)) + elif getattr(self._viewLim, f"mutated{name}")(): + # No data, but explicit viewLims already set: + # in mutatedx or mutatedy. + return + else: + x0, x1 = (-np.inf, np.inf) + # If x0 and x1 are nonfinite, get default limits from the locator. + locator = axis.get_major_locator() + x0, x1 = locator.nonsingular(x0, x1) + # Find the minimum minpos for use in the margin calculation. + minimum_minpos = min( + getattr(ax.dataLim, f"minpos{name}") for ax in shared) + + # Prevent margin addition from crossing a sticky value. A small + # tolerance must be added due to floating point issues with + # streamplot; it is defined relative to x1-x0 but has + # no absolute term (e.g. "+1e-8") to avoid issues when working with + # datasets where all values are tiny (less than 1e-8). + tol = 1e-5 * abs(x1 - x0) + # Index of largest element < x0 + tol, if any. + i0 = stickies.searchsorted(x0 + tol) - 1 + x0bound = stickies[i0] if i0 != -1 else None + # Index of smallest element > x1 - tol, if any. + i1 = stickies.searchsorted(x1 - tol) + x1bound = stickies[i1] if i1 != len(stickies) else None + + # Add the margin in figure space and then transform back, to handle + # non-linear scales. + transform = axis.get_transform() + inverse_trans = transform.inverted() + x0, x1 = axis._scale.limit_range_for_scale(x0, x1, minimum_minpos) + x0t, x1t = transform.transform([x0, x1]) + delta = (x1t - x0t) * margin + if not np.isfinite(delta): + delta = 0 # If a bound isn't finite, set margin to zero. + x0, x1 = inverse_trans.transform([x0t - delta, x1t + delta]) + + # Apply sticky bounds. + if x0bound is not None: + x0 = max(x0, x0bound) + if x1bound is not None: + x1 = min(x1, x1bound) + + if not self._tight: + x0, x1 = locator.view_limits(x0, x1) + set_bound(x0, x1) + # End of definition of internal function 'handle_single_axis'. + + handle_single_axis( + scalex, self._shared_axes["x"], 'x', self.xaxis, self._xmargin, + x_stickies, self.set_xbound) + handle_single_axis( + scaley, self._shared_axes["y"], 'y', self.yaxis, self._ymargin, + y_stickies, self.set_ybound) + + def _update_title_position(self, renderer): + """ + Update the title position based on the bounding box enclosing + all the ticklabels and x-axis spine and xlabel... + """ + if self._autotitlepos is not None and not self._autotitlepos: + _log.debug('title position was updated manually, not adjusting') + return + + titles = (self.title, self._left_title, self._right_title) + + # Need to check all our twins too, aligned axes, and all the children + # as well. + axs = set() + axs.update(self.child_axes) + axs.update(self._twinned_axes.get_siblings(self)) + axs.update(self.figure._align_label_groups['title'].get_siblings(self)) + + for ax in self.child_axes: # Child positions must be updated first. + locator = ax.get_axes_locator() + ax.apply_aspect(locator(self, renderer) if locator else None) + + for title in titles: + x, _ = title.get_position() + # need to start again in case of window resizing + title.set_position((x, 1.0)) + top = -np.inf + for ax in axs: + bb = None + if (ax.xaxis.get_ticks_position() in ['top', 'unknown'] + or ax.xaxis.get_label_position() == 'top'): + bb = ax.xaxis.get_tightbbox(renderer) + if bb is None: + if 'outline' in ax.spines: + # Special case for colorbars: + bb = ax.spines['outline'].get_window_extent() + else: + bb = ax.get_window_extent(renderer) + top = max(top, bb.ymax) + if title.get_text(): + ax.yaxis.get_tightbbox(renderer) # update offsetText + if ax.yaxis.offsetText.get_text(): + bb = ax.yaxis.offsetText.get_tightbbox(renderer) + if bb.intersection(title.get_tightbbox(renderer), bb): + top = bb.ymax + if top < 0: + # the top of Axes is not even on the figure, so don't try and + # automatically place it. + _log.debug('top of Axes not in the figure, so title not moved') + return + if title.get_window_extent(renderer).ymin < top: + _, y = self.transAxes.inverted().transform((0, top)) + title.set_position((x, y)) + # empirically, this doesn't always get the min to top, + # so we need to adjust again. + if title.get_window_extent(renderer).ymin < top: + _, y = self.transAxes.inverted().transform( + (0., 2 * top - title.get_window_extent(renderer).ymin)) + title.set_position((x, y)) + + ymax = max(title.get_position()[1] for title in titles) + for title in titles: + # now line up all the titles at the highest baseline. + x, _ = title.get_position() + title.set_position((x, ymax)) + + # Drawing + @martist.allow_rasterization + def draw(self, renderer): + # docstring inherited + if renderer is None: + raise RuntimeError('No renderer defined') + if not self.get_visible(): + return + self._unstale_viewLim() + + renderer.open_group('axes', gid=self.get_gid()) + + # prevent triggering call backs during the draw process + self._stale = True + + # loop over self and child Axes... + locator = self.get_axes_locator() + self.apply_aspect(locator(self, renderer) if locator else None) + + artists = self.get_children() + artists.remove(self.patch) + + # the frame draws the edges around the Axes patch -- we + # decouple these so the patch can be in the background and the + # frame in the foreground. Do this before drawing the axis + # objects so that the spine has the opportunity to update them. + if not (self.axison and self._frameon): + for spine in self.spines.values(): + artists.remove(spine) + + self._update_title_position(renderer) + + if not self.axison: + for _axis in self._axis_map.values(): + artists.remove(_axis) + + if not self.figure.canvas.is_saving(): + artists = [ + a for a in artists + if not a.get_animated() or isinstance(a, mimage.AxesImage)] + artists = sorted(artists, key=attrgetter('zorder')) + + # rasterize artists with negative zorder + # if the minimum zorder is negative, start rasterization + rasterization_zorder = self._rasterization_zorder + + if (rasterization_zorder is not None and + artists and artists[0].zorder < rasterization_zorder): + split_index = np.searchsorted( + [art.zorder for art in artists], + rasterization_zorder, side='right' + ) + artists_rasterized = artists[:split_index] + artists = artists[split_index:] + else: + artists_rasterized = [] + + if self.axison and self._frameon: + if artists_rasterized: + artists_rasterized = [self.patch] + artists_rasterized + else: + artists = [self.patch] + artists + + if artists_rasterized: + _draw_rasterized(self.figure, artists_rasterized, renderer) + + mimage._draw_list_compositing_images( + renderer, self, artists, self.figure.suppressComposite) + + renderer.close_group('axes') + self.stale = False + + def draw_artist(self, a): + """ + Efficiently redraw a single artist. + """ + a.draw(self.figure.canvas.get_renderer()) + + def redraw_in_frame(self): + """ + Efficiently redraw Axes data, but not axis ticks, labels, etc. + """ + with ExitStack() as stack: + for artist in [*self._axis_map.values(), + self.title, self._left_title, self._right_title]: + stack.enter_context(artist._cm_set(visible=False)) + self.draw(self.figure.canvas.get_renderer()) + + # Axes rectangle characteristics + + def get_frame_on(self): + """Get whether the Axes rectangle patch is drawn.""" + return self._frameon + + def set_frame_on(self, b): + """ + Set whether the Axes rectangle patch is drawn. + + Parameters + ---------- + b : bool + """ + self._frameon = b + self.stale = True + + def get_axisbelow(self): + """ + Get whether axis ticks and gridlines are above or below most artists. + + Returns + ------- + bool or 'line' + + See Also + -------- + set_axisbelow + """ + return self._axisbelow + + def set_axisbelow(self, b): + """ + Set whether axis ticks and gridlines are above or below most artists. + + This controls the zorder of the ticks and gridlines. For more + information on the zorder see :doc:`/gallery/misc/zorder_demo`. + + Parameters + ---------- + b : bool or 'line' + Possible values: + + - *True* (zorder = 0.5): Ticks and gridlines are below patches and + lines, though still above images. + - 'line' (zorder = 1.5): Ticks and gridlines are above patches + (e.g. rectangles, with default zorder = 1) but still below lines + and markers (with their default zorder = 2). + - *False* (zorder = 2.5): Ticks and gridlines are above patches + and lines / markers. + + Notes + ----- + For more control, call the `~.Artist.set_zorder` method of each axis. + + See Also + -------- + get_axisbelow + """ + # Check that b is True, False or 'line' + self._axisbelow = axisbelow = validate_axisbelow(b) + zorder = { + True: 0.5, + 'line': 1.5, + False: 2.5, + }[axisbelow] + for axis in self._axis_map.values(): + axis.set_zorder(zorder) + self.stale = True + + @_docstring.dedent_interpd + def grid(self, visible=None, which='major', axis='both', **kwargs): + """ + Configure the grid lines. + + Parameters + ---------- + visible : bool or None, optional + Whether to show the grid lines. If any *kwargs* are supplied, it + is assumed you want the grid on and *visible* will be set to True. + + If *visible* is *None* and there are no *kwargs*, this toggles the + visibility of the lines. + + which : {'major', 'minor', 'both'}, optional + The grid lines to apply the changes on. + + axis : {'both', 'x', 'y'}, optional + The axis to apply the changes on. + + **kwargs : `~matplotlib.lines.Line2D` properties + Define the line properties of the grid, e.g.:: + + grid(color='r', linestyle='-', linewidth=2) + + Valid keyword arguments are: + + %(Line2D:kwdoc)s + + Notes + ----- + The axis is drawn as a unit, so the effective zorder for drawing the + grid is determined by the zorder of each axis, not by the zorder of the + `.Line2D` objects comprising the grid. Therefore, to set grid zorder, + use `.set_axisbelow` or, for more control, call the + `~.Artist.set_zorder` method of each axis. + """ + _api.check_in_list(['x', 'y', 'both'], axis=axis) + if axis in ['x', 'both']: + self.xaxis.grid(visible, which=which, **kwargs) + if axis in ['y', 'both']: + self.yaxis.grid(visible, which=which, **kwargs) + + def ticklabel_format(self, *, axis='both', style=None, scilimits=None, + useOffset=None, useLocale=None, useMathText=None): + r""" + Configure the `.ScalarFormatter` used by default for linear Axes. + + If a parameter is not set, the corresponding property of the formatter + is left unchanged. + + Parameters + ---------- + axis : {'x', 'y', 'both'}, default: 'both' + The axis to configure. Only major ticks are affected. + + style : {'sci', 'scientific', 'plain'} + Whether to use scientific notation. + The formatter default is to use scientific notation. + 'sci' is equivalent to 'scientific'. + + scilimits : pair of ints (m, n) + Scientific notation is used only for numbers outside the range + 10\ :sup:`m` to 10\ :sup:`n` (and only if the formatter is + configured to use scientific notation at all). Use (0, 0) to + include all numbers. Use (m, m) where m != 0 to fix the order of + magnitude to 10\ :sup:`m`. + The formatter default is :rc:`axes.formatter.limits`. + + useOffset : bool or float + If True, the offset is calculated as needed. + If False, no offset is used. + If a numeric value, it sets the offset. + The formatter default is :rc:`axes.formatter.useoffset`. + + useLocale : bool + Whether to format the number using the current locale or using the + C (English) locale. This affects e.g. the decimal separator. The + formatter default is :rc:`axes.formatter.use_locale`. + + useMathText : bool + Render the offset and scientific notation in mathtext. + The formatter default is :rc:`axes.formatter.use_mathtext`. + + Raises + ------ + AttributeError + If the current formatter is not a `.ScalarFormatter`. + """ + if isinstance(style, str): + style = style.lower() + axis = axis.lower() + if scilimits is not None: + try: + m, n = scilimits + m + n + 1 # check that both are numbers + except (ValueError, TypeError) as err: + raise ValueError("scilimits must be a sequence of 2 integers" + ) from err + STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None, None: None} + # The '' option is included for backwards-compatibility. + is_sci_style = _api.check_getitem(STYLES, style=style) + axis_map = {**{k: [v] for k, v in self._axis_map.items()}, + 'both': list(self._axis_map.values())} + axises = _api.check_getitem(axis_map, axis=axis) + try: + for axis in axises: + if is_sci_style is not None: + axis.major.formatter.set_scientific(is_sci_style) + if scilimits is not None: + axis.major.formatter.set_powerlimits(scilimits) + if useOffset is not None: + axis.major.formatter.set_useOffset(useOffset) + if useLocale is not None: + axis.major.formatter.set_useLocale(useLocale) + if useMathText is not None: + axis.major.formatter.set_useMathText(useMathText) + except AttributeError as err: + raise AttributeError( + "This method only works with the ScalarFormatter") from err + + def locator_params(self, axis='both', tight=None, **kwargs): + """ + Control behavior of major tick locators. + + Because the locator is involved in autoscaling, `~.Axes.autoscale_view` + is called automatically after the parameters are changed. + + Parameters + ---------- + axis : {'both', 'x', 'y'}, default: 'both' + The axis on which to operate. (For 3D Axes, *axis* can also be + set to 'z', and 'both' refers to all three axes.) + tight : bool or None, optional + Parameter passed to `~.Axes.autoscale_view`. + Default is None, for no change. + + Other Parameters + ---------------- + **kwargs + Remaining keyword arguments are passed to directly to the + ``set_params()`` method of the locator. Supported keywords depend + on the type of the locator. See for example + `~.ticker.MaxNLocator.set_params` for the `.ticker.MaxNLocator` + used by default for linear. + + Examples + -------- + When plotting small subplots, one might want to reduce the maximum + number of ticks and use tight bounds, for example:: + + ax.locator_params(tight=True, nbins=4) + + """ + _api.check_in_list([*self._axis_names, "both"], axis=axis) + for name in self._axis_names: + if axis in [name, "both"]: + loc = self._axis_map[name].get_major_locator() + loc.set_params(**kwargs) + self._request_autoscale_view(name, tight=tight) + self.stale = True + + def tick_params(self, axis='both', **kwargs): + """ + Change the appearance of ticks, tick labels, and gridlines. + + Tick properties that are not explicitly set using the keyword + arguments remain unchanged unless *reset* is True. For the current + style settings, see `.Axis.get_tick_params`. + + Parameters + ---------- + axis : {'x', 'y', 'both'}, default: 'both' + The axis to which the parameters are applied. + which : {'major', 'minor', 'both'}, default: 'major' + The group of ticks to which the parameters are applied. + reset : bool, default: False + Whether to reset the ticks to defaults before updating them. + + Other Parameters + ---------------- + direction : {'in', 'out', 'inout'} + Puts ticks inside the Axes, outside the Axes, or both. + length : float + Tick length in points. + width : float + Tick width in points. + color : :mpltype:`color` + Tick color. + pad : float + Distance in points between tick and label. + labelsize : float or str + Tick label font size in points or as a string (e.g., 'large'). + labelcolor : :mpltype:`color` + Tick label color. + labelfontfamily : str + Tick label font. + colors : :mpltype:`color` + Tick color and label color. + zorder : float + Tick and label zorder. + bottom, top, left, right : bool + Whether to draw the respective ticks. + labelbottom, labeltop, labelleft, labelright : bool + Whether to draw the respective tick labels. + labelrotation : float + Tick label rotation + grid_color : :mpltype:`color` + Gridline color. + grid_alpha : float + Transparency of gridlines: 0 (transparent) to 1 (opaque). + grid_linewidth : float + Width of gridlines in points. + grid_linestyle : str + Any valid `.Line2D` line style spec. + + Examples + -------- + :: + + ax.tick_params(direction='out', length=6, width=2, colors='r', + grid_color='r', grid_alpha=0.5) + + This will make all major ticks be red, pointing out of the box, + and with dimensions 6 points by 2 points. Tick labels will + also be red. Gridlines will be red and translucent. + + """ + _api.check_in_list(['x', 'y', 'both'], axis=axis) + if axis in ['x', 'both']: + xkw = dict(kwargs) + xkw.pop('left', None) + xkw.pop('right', None) + xkw.pop('labelleft', None) + xkw.pop('labelright', None) + self.xaxis.set_tick_params(**xkw) + if axis in ['y', 'both']: + ykw = dict(kwargs) + ykw.pop('top', None) + ykw.pop('bottom', None) + ykw.pop('labeltop', None) + ykw.pop('labelbottom', None) + self.yaxis.set_tick_params(**ykw) + + def set_axis_off(self): + """ + Hide all visual components of the x- and y-axis. + + This sets a flag to suppress drawing of all axis decorations, i.e. + axis labels, axis spines, and the axis tick component (tick markers, + tick labels, and grid lines). Individual visibility settings of these + components are ignored as long as `set_axis_off()` is in effect. + """ + self.axison = False + self.stale = True + + def set_axis_on(self): + """ + Do not hide all visual components of the x- and y-axis. + + This reverts the effect of a prior `.set_axis_off()` call. Whether the + individual axis decorations are drawn is controlled by their respective + visibility settings. + + This is on by default. + """ + self.axison = True + self.stale = True + + # data limits, ticks, tick labels, and formatting + + def get_xlabel(self): + """ + Get the xlabel text string. + """ + label = self.xaxis.get_label() + return label.get_text() + + def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, + loc=None, **kwargs): + """ + Set the label for the x-axis. + + Parameters + ---------- + xlabel : str + The label text. + + labelpad : float, default: :rc:`axes.labelpad` + Spacing in points from the Axes bounding box including ticks + and tick labels. If None, the previous value is left as is. + + loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation` + The label position. This is a high-level alternative for passing + parameters *x* and *horizontalalignment*. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + `.Text` properties control the appearance of the label. + + See Also + -------- + text : Documents the properties supported by `.Text`. + """ + if labelpad is not None: + self.xaxis.labelpad = labelpad + protected_kw = ['x', 'horizontalalignment', 'ha'] + if {*kwargs} & {*protected_kw}: + if loc is not None: + raise TypeError(f"Specifying 'loc' is disallowed when any of " + f"its corresponding low level keyword " + f"arguments ({protected_kw}) are also " + f"supplied") + + else: + loc = (loc if loc is not None + else mpl.rcParams['xaxis.labellocation']) + _api.check_in_list(('left', 'center', 'right'), loc=loc) + + x = { + 'left': 0, + 'center': 0.5, + 'right': 1, + }[loc] + kwargs.update(x=x, horizontalalignment=loc) + + return self.xaxis.set_label_text(xlabel, fontdict, **kwargs) + + def invert_xaxis(self): + """ + Invert the x-axis. + + See Also + -------- + xaxis_inverted + get_xlim, set_xlim + get_xbound, set_xbound + """ + self.xaxis.set_inverted(not self.xaxis.get_inverted()) + + xaxis_inverted = _axis_method_wrapper("xaxis", "get_inverted") + + def get_xbound(self): + """ + Return the lower and upper x-axis bounds, in increasing order. + + See Also + -------- + set_xbound + get_xlim, set_xlim + invert_xaxis, xaxis_inverted + """ + left, right = self.get_xlim() + if left < right: + return left, right + else: + return right, left + + def set_xbound(self, lower=None, upper=None): + """ + Set the lower and upper numerical bounds of the x-axis. + + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscalex_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + + .. ACCEPTS: (lower: float, upper: float) + + See Also + -------- + get_xbound + get_xlim, set_xlim + invert_xaxis, xaxis_inverted + """ + if upper is None and np.iterable(lower): + lower, upper = lower + + old_lower, old_upper = self.get_xbound() + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper + + self.set_xlim(sorted((lower, upper), + reverse=bool(self.xaxis_inverted())), + auto=None) + + def get_xlim(self): + """ + Return the x-axis view limits. + + Returns + ------- + left, right : (float, float) + The current x-axis limits in data coordinates. + + See Also + -------- + .Axes.set_xlim + .Axes.set_xbound, .Axes.get_xbound + .Axes.invert_xaxis, .Axes.xaxis_inverted + + Notes + ----- + The x-axis may be inverted, in which case the *left* value will + be greater than the *right* value. + """ + return tuple(self.viewLim.intervalx) + + def _validate_converted_limits(self, limit, convert): + """ + Raise ValueError if converted limits are non-finite. + + Note that this function also accepts None as a limit argument. + + Returns + ------- + The limit value after call to convert(), or None if limit is None. + """ + if limit is not None: + converted_limit = convert(limit) + if isinstance(converted_limit, np.ndarray): + converted_limit = converted_limit.squeeze() + if (isinstance(converted_limit, Real) + and not np.isfinite(converted_limit)): + raise ValueError("Axis limits cannot be NaN or Inf") + return converted_limit + + def set_xlim(self, left=None, right=None, *, emit=True, auto=False, + xmin=None, xmax=None): + """ + Set the x-axis view limits. + + Parameters + ---------- + left : float, optional + The left xlim in data coordinates. Passing *None* leaves the + limit unchanged. + + The left and right xlims may also be passed as the tuple + (*left*, *right*) as the first positional argument (or as + the *left* keyword argument). + + .. ACCEPTS: (left: float, right: float) + + right : float, optional + The right xlim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the x-axis. True turns on, + False turns off, None leaves unchanged. + + xmin, xmax : float, optional + They are equivalent to left and right respectively, and it is an + error to pass both *xmin* and *left* or *xmax* and *right*. + + Returns + ------- + left, right : (float, float) + The new x-axis limits in data coordinates. + + See Also + -------- + get_xlim + set_xbound, get_xbound + invert_xaxis, xaxis_inverted + + Notes + ----- + The *left* value may be greater than the *right* value, in which + case the x-axis values will decrease from left to right. + + Examples + -------- + >>> set_xlim(left, right) + >>> set_xlim((left, right)) + >>> left, right = set_xlim(left, right) + + One limit may be left unchanged. + + >>> set_xlim(right=right_lim) + + Limits may be passed in reverse order to flip the direction of + the x-axis. For example, suppose *x* represents the number of + years before present. The x-axis limits might be set like the + following so 5000 years ago is on the left of the plot and the + present is on the right. + + >>> set_xlim(5000, 0) + """ + if right is None and np.iterable(left): + left, right = left + if xmin is not None: + if left is not None: + raise TypeError("Cannot pass both 'left' and 'xmin'") + left = xmin + if xmax is not None: + if right is not None: + raise TypeError("Cannot pass both 'right' and 'xmax'") + right = xmax + return self.xaxis._set_lim(left, right, emit=emit, auto=auto) + + get_xscale = _axis_method_wrapper("xaxis", "get_scale") + set_xscale = _axis_method_wrapper("xaxis", "_set_axes_scale") + get_xticks = _axis_method_wrapper("xaxis", "get_ticklocs") + set_xticks = _axis_method_wrapper("xaxis", "set_ticks", + doc_sub={'set_ticks': 'set_xticks'}) + get_xmajorticklabels = _axis_method_wrapper("xaxis", "get_majorticklabels") + get_xminorticklabels = _axis_method_wrapper("xaxis", "get_minorticklabels") + get_xticklabels = _axis_method_wrapper("xaxis", "get_ticklabels") + set_xticklabels = _axis_method_wrapper( + "xaxis", "set_ticklabels", + doc_sub={"Axis.set_ticks": "Axes.set_xticks"}) + + def get_ylabel(self): + """ + Get the ylabel text string. + """ + label = self.yaxis.get_label() + return label.get_text() + + def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *, + loc=None, **kwargs): + """ + Set the label for the y-axis. + + Parameters + ---------- + ylabel : str + The label text. + + labelpad : float, default: :rc:`axes.labelpad` + Spacing in points from the Axes bounding box including ticks + and tick labels. If None, the previous value is left as is. + + loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation` + The label position. This is a high-level alternative for passing + parameters *y* and *horizontalalignment*. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + `.Text` properties control the appearance of the label. + + See Also + -------- + text : Documents the properties supported by `.Text`. + """ + if labelpad is not None: + self.yaxis.labelpad = labelpad + protected_kw = ['y', 'horizontalalignment', 'ha'] + if {*kwargs} & {*protected_kw}: + if loc is not None: + raise TypeError(f"Specifying 'loc' is disallowed when any of " + f"its corresponding low level keyword " + f"arguments ({protected_kw}) are also " + f"supplied") + + else: + loc = (loc if loc is not None + else mpl.rcParams['yaxis.labellocation']) + _api.check_in_list(('bottom', 'center', 'top'), loc=loc) + + y, ha = { + 'bottom': (0, 'left'), + 'center': (0.5, 'center'), + 'top': (1, 'right') + }[loc] + kwargs.update(y=y, horizontalalignment=ha) + + return self.yaxis.set_label_text(ylabel, fontdict, **kwargs) + + def invert_yaxis(self): + """ + Invert the y-axis. + + See Also + -------- + yaxis_inverted + get_ylim, set_ylim + get_ybound, set_ybound + """ + self.yaxis.set_inverted(not self.yaxis.get_inverted()) + + yaxis_inverted = _axis_method_wrapper("yaxis", "get_inverted") + + def get_ybound(self): + """ + Return the lower and upper y-axis bounds, in increasing order. + + See Also + -------- + set_ybound + get_ylim, set_ylim + invert_yaxis, yaxis_inverted + """ + bottom, top = self.get_ylim() + if bottom < top: + return bottom, top + else: + return top, bottom + + def set_ybound(self, lower=None, upper=None): + """ + Set the lower and upper numerical bounds of the y-axis. + + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscaley_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + + .. ACCEPTS: (lower: float, upper: float) + + See Also + -------- + get_ybound + get_ylim, set_ylim + invert_yaxis, yaxis_inverted + """ + if upper is None and np.iterable(lower): + lower, upper = lower + + old_lower, old_upper = self.get_ybound() + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper + + self.set_ylim(sorted((lower, upper), + reverse=bool(self.yaxis_inverted())), + auto=None) + + def get_ylim(self): + """ + Return the y-axis view limits. + + Returns + ------- + bottom, top : (float, float) + The current y-axis limits in data coordinates. + + See Also + -------- + .Axes.set_ylim + .Axes.set_ybound, .Axes.get_ybound + .Axes.invert_yaxis, .Axes.yaxis_inverted + + Notes + ----- + The y-axis may be inverted, in which case the *bottom* value + will be greater than the *top* value. + """ + return tuple(self.viewLim.intervaly) + + def set_ylim(self, bottom=None, top=None, *, emit=True, auto=False, + ymin=None, ymax=None): + """ + Set the y-axis view limits. + + Parameters + ---------- + bottom : float, optional + The bottom ylim in data coordinates. Passing *None* leaves the + limit unchanged. + + The bottom and top ylims may also be passed as the tuple + (*bottom*, *top*) as the first positional argument (or as + the *bottom* keyword argument). + + .. ACCEPTS: (bottom: float, top: float) + + top : float, optional + The top ylim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the y-axis. *True* turns on, + *False* turns off, *None* leaves unchanged. + + ymin, ymax : float, optional + They are equivalent to bottom and top respectively, and it is an + error to pass both *ymin* and *bottom* or *ymax* and *top*. + + Returns + ------- + bottom, top : (float, float) + The new y-axis limits in data coordinates. + + See Also + -------- + get_ylim + set_ybound, get_ybound + invert_yaxis, yaxis_inverted + + Notes + ----- + The *bottom* value may be greater than the *top* value, in which + case the y-axis values will decrease from *bottom* to *top*. + + Examples + -------- + >>> set_ylim(bottom, top) + >>> set_ylim((bottom, top)) + >>> bottom, top = set_ylim(bottom, top) + + One limit may be left unchanged. + + >>> set_ylim(top=top_lim) + + Limits may be passed in reverse order to flip the direction of + the y-axis. For example, suppose ``y`` represents depth of the + ocean in m. The y-axis limits might be set like the following + so 5000 m depth is at the bottom of the plot and the surface, + 0 m, is at the top. + + >>> set_ylim(5000, 0) + """ + if top is None and np.iterable(bottom): + bottom, top = bottom + if ymin is not None: + if bottom is not None: + raise TypeError("Cannot pass both 'bottom' and 'ymin'") + bottom = ymin + if ymax is not None: + if top is not None: + raise TypeError("Cannot pass both 'top' and 'ymax'") + top = ymax + return self.yaxis._set_lim(bottom, top, emit=emit, auto=auto) + + get_yscale = _axis_method_wrapper("yaxis", "get_scale") + set_yscale = _axis_method_wrapper("yaxis", "_set_axes_scale") + get_yticks = _axis_method_wrapper("yaxis", "get_ticklocs") + set_yticks = _axis_method_wrapper("yaxis", "set_ticks", + doc_sub={'set_ticks': 'set_yticks'}) + get_ymajorticklabels = _axis_method_wrapper("yaxis", "get_majorticklabels") + get_yminorticklabels = _axis_method_wrapper("yaxis", "get_minorticklabels") + get_yticklabels = _axis_method_wrapper("yaxis", "get_ticklabels") + set_yticklabels = _axis_method_wrapper( + "yaxis", "set_ticklabels", + doc_sub={"Axis.set_ticks": "Axes.set_yticks"}) + + xaxis_date = _axis_method_wrapper("xaxis", "axis_date") + yaxis_date = _axis_method_wrapper("yaxis", "axis_date") + + def format_xdata(self, x): + """ + Return *x* formatted as an x-value. + + This function will use the `.fmt_xdata` attribute if it is not None, + else will fall back on the xaxis major formatter. + """ + return (self.fmt_xdata if self.fmt_xdata is not None + else self.xaxis.get_major_formatter().format_data_short)(x) + + def format_ydata(self, y): + """ + Return *y* formatted as a y-value. + + This function will use the `.fmt_ydata` attribute if it is not None, + else will fall back on the yaxis major formatter. + """ + return (self.fmt_ydata if self.fmt_ydata is not None + else self.yaxis.get_major_formatter().format_data_short)(y) + + def format_coord(self, x, y): + """Return a format string formatting the *x*, *y* coordinates.""" + twins = self._twinned_axes.get_siblings(self) + if len(twins) == 1: + return "(x, y) = ({}, {})".format( + "???" if x is None else self.format_xdata(x), + "???" if y is None else self.format_ydata(y)) + screen_xy = self.transData.transform((x, y)) + xy_strs = [] + # Retrieve twins in the order of self.figure.axes to sort tied zorders (which is + # the common case) by the order in which they are added to the figure. + for ax in sorted(twins, key=attrgetter("zorder")): + data_x, data_y = ax.transData.inverted().transform(screen_xy) + xy_strs.append( + "({}, {})".format(ax.format_xdata(data_x), ax.format_ydata(data_y))) + return "(x, y) = {}".format(" | ".join(xy_strs)) + + def minorticks_on(self): + """ + Display minor ticks on the Axes. + + Displaying minor ticks may reduce performance; you may turn them off + using `minorticks_off()` if drawing speed is a problem. + """ + self.xaxis.minorticks_on() + self.yaxis.minorticks_on() + + def minorticks_off(self): + """Remove minor ticks from the Axes.""" + self.xaxis.minorticks_off() + self.yaxis.minorticks_off() + + # Interactive manipulation + + def can_zoom(self): + """ + Return whether this Axes supports the zoom box button functionality. + """ + return True + + def can_pan(self): + """ + Return whether this Axes supports any pan/zoom button functionality. + """ + return True + + def get_navigate(self): + """ + Get whether the Axes responds to navigation commands. + """ + return self._navigate + + def set_navigate(self, b): + """ + Set whether the Axes responds to navigation toolbar commands. + + Parameters + ---------- + b : bool + + See Also + -------- + matplotlib.axes.Axes.set_forward_navigation_events + + """ + self._navigate = b + + def get_navigate_mode(self): + """ + Get the navigation toolbar button status: 'PAN', 'ZOOM', or None. + """ + return self._navigate_mode + + def set_navigate_mode(self, b): + """ + Set the navigation toolbar button status. + + .. warning:: + This is not a user-API function. + + """ + self._navigate_mode = b + + def _get_view(self): + """ + Save information required to reproduce the current view. + + This method is called before a view is changed, such as during a pan or zoom + initiated by the user. It returns an opaque object that describes the current + view, in a format compatible with :meth:`_set_view`. + + The default implementation saves the view limits and autoscaling state. + Subclasses may override this as needed, as long as :meth:`_set_view` is also + adjusted accordingly. + """ + return { + "xlim": self.get_xlim(), "autoscalex_on": self.get_autoscalex_on(), + "ylim": self.get_ylim(), "autoscaley_on": self.get_autoscaley_on(), + } + + def _set_view(self, view): + """ + Apply a previously saved view. + + This method is called when restoring a view (with the return value of + :meth:`_get_view` as argument), such as with the navigation buttons. + + Subclasses that override :meth:`_get_view` also need to override this method + accordingly. + """ + self.set(**view) + + def _prepare_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + """ + Helper function to prepare the new bounds from a bbox. + + This helper function returns the new x and y bounds from the zoom + bbox. This a convenience method to abstract the bbox logic + out of the base setter. + """ + if len(bbox) == 3: + xp, yp, scl = bbox # Zooming code + if scl == 0: # Should not happen + scl = 1. + if scl > 1: + direction = 'in' + else: + direction = 'out' + scl = 1/scl + # get the limits of the axes + (xmin, ymin), (xmax, ymax) = self.transData.transform( + np.transpose([self.get_xlim(), self.get_ylim()])) + # set the range + xwidth = xmax - xmin + ywidth = ymax - ymin + xcen = (xmax + xmin)*.5 + ycen = (ymax + ymin)*.5 + xzc = (xp*(scl - 1) + xcen)/scl + yzc = (yp*(scl - 1) + ycen)/scl + bbox = [xzc - xwidth/2./scl, yzc - ywidth/2./scl, + xzc + xwidth/2./scl, yzc + ywidth/2./scl] + elif len(bbox) != 4: + # should be len 3 or 4 but nothing else + _api.warn_external( + "Warning in _set_view_from_bbox: bounding box is not a tuple " + "of length 3 or 4. Ignoring the view change.") + return + + # Original limits. + xmin0, xmax0 = self.get_xbound() + ymin0, ymax0 = self.get_ybound() + # The zoom box in screen coords. + startx, starty, stopx, stopy = bbox + # Convert to data coords. + (startx, starty), (stopx, stopy) = self.transData.inverted().transform( + [(startx, starty), (stopx, stopy)]) + # Clip to axes limits. + xmin, xmax = np.clip(sorted([startx, stopx]), xmin0, xmax0) + ymin, ymax = np.clip(sorted([starty, stopy]), ymin0, ymax0) + # Don't double-zoom twinned axes or if zooming only the other axis. + if twinx or mode == "y": + xmin, xmax = xmin0, xmax0 + if twiny or mode == "x": + ymin, ymax = ymin0, ymax0 + + if direction == "in": + new_xbound = xmin, xmax + new_ybound = ymin, ymax + + elif direction == "out": + x_trf = self.xaxis.get_transform() + sxmin0, sxmax0, sxmin, sxmax = x_trf.transform( + [xmin0, xmax0, xmin, xmax]) # To screen space. + factor = (sxmax0 - sxmin0) / (sxmax - sxmin) # Unzoom factor. + # Move original bounds away by + # (factor) x (distance between unzoom box and Axes bbox). + sxmin1 = sxmin0 - factor * (sxmin - sxmin0) + sxmax1 = sxmax0 + factor * (sxmax0 - sxmax) + # And back to data space. + new_xbound = x_trf.inverted().transform([sxmin1, sxmax1]) + + y_trf = self.yaxis.get_transform() + symin0, symax0, symin, symax = y_trf.transform( + [ymin0, ymax0, ymin, ymax]) + factor = (symax0 - symin0) / (symax - symin) + symin1 = symin0 - factor * (symin - symin0) + symax1 = symax0 + factor * (symax0 - symax) + new_ybound = y_trf.inverted().transform([symin1, symax1]) + + return new_xbound, new_ybound + + def _set_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + """ + Update view from a selection bbox. + + .. note:: + + Intended to be overridden by new projection types, but if not, the + default implementation sets the view limits to the bbox directly. + + Parameters + ---------- + bbox : 4-tuple or 3 tuple + * If bbox is a 4 tuple, it is the selected bounding box limits, + in *display* coordinates. + * If bbox is a 3 tuple, it is an (xp, yp, scl) triple, where + (xp, yp) is the center of zooming and scl the scale factor to + zoom by. + + direction : str + The direction to apply the bounding box. + * `'in'` - The bounding box describes the view directly, i.e., + it zooms in. + * `'out'` - The bounding box describes the size to make the + existing view, i.e., it zooms out. + + mode : str or None + The selection mode, whether to apply the bounding box in only the + `'x'` direction, `'y'` direction or both (`None`). + + twinx : bool + Whether this axis is twinned in the *x*-direction. + + twiny : bool + Whether this axis is twinned in the *y*-direction. + """ + new_xbound, new_ybound = self._prepare_view_from_bbox( + bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny) + if not twinx and mode != "y": + self.set_xbound(new_xbound) + self.set_autoscalex_on(False) + if not twiny and mode != "x": + self.set_ybound(new_ybound) + self.set_autoscaley_on(False) + + def start_pan(self, x, y, button): + """ + Called when a pan operation has started. + + Parameters + ---------- + x, y : float + The mouse coordinates in display coords. + button : `.MouseButton` + The pressed mouse button. + + Notes + ----- + This is intended to be overridden by new projection types. + """ + self._pan_start = types.SimpleNamespace( + lim=self.viewLim.frozen(), + trans=self.transData.frozen(), + trans_inverse=self.transData.inverted().frozen(), + bbox=self.bbox.frozen(), + x=x, + y=y) + + def end_pan(self): + """ + Called when a pan operation completes (when the mouse button is up.) + + Notes + ----- + This is intended to be overridden by new projection types. + """ + del self._pan_start + + def _get_pan_points(self, button, key, x, y): + """ + Helper function to return the new points after a pan. + + This helper function returns the points on the axis after a pan has + occurred. This is a convenience method to abstract the pan logic + out of the base setter. + """ + def format_deltas(key, dx, dy): + if key == 'control': + if abs(dx) > abs(dy): + dy = dx + else: + dx = dy + elif key == 'x': + dy = 0 + elif key == 'y': + dx = 0 + elif key == 'shift': + if 2 * abs(dx) < abs(dy): + dx = 0 + elif 2 * abs(dy) < abs(dx): + dy = 0 + elif abs(dx) > abs(dy): + dy = dy / abs(dy) * abs(dx) + else: + dx = dx / abs(dx) * abs(dy) + return dx, dy + + p = self._pan_start + dx = x - p.x + dy = y - p.y + if dx == dy == 0: + return + if button == 1: + dx, dy = format_deltas(key, dx, dy) + result = p.bbox.translated(-dx, -dy).transformed(p.trans_inverse) + elif button == 3: + try: + dx = -dx / self.bbox.width + dy = -dy / self.bbox.height + dx, dy = format_deltas(key, dx, dy) + if self.get_aspect() != 'auto': + dx = dy = 0.5 * (dx + dy) + alpha = np.power(10.0, (dx, dy)) + start = np.array([p.x, p.y]) + oldpoints = p.lim.transformed(p.trans) + newpoints = start + alpha * (oldpoints - start) + result = (mtransforms.Bbox(newpoints) + .transformed(p.trans_inverse)) + except OverflowError: + _api.warn_external('Overflow while panning') + return + else: + return + + valid = np.isfinite(result.transformed(p.trans)) + points = result.get_points().astype(object) + # Just ignore invalid limits (typically, underflow in log-scale). + points[~valid] = None + return points + + def drag_pan(self, button, key, x, y): + """ + Called when the mouse moves during a pan operation. + + Parameters + ---------- + button : `.MouseButton` + The pressed mouse button. + key : str or None + The pressed key, if any. + x, y : float + The mouse coordinates in display coords. + + Notes + ----- + This is intended to be overridden by new projection types. + """ + points = self._get_pan_points(button, key, x, y) + if points is not None: + self.set_xlim(points[:, 0]) + self.set_ylim(points[:, 1]) + + def get_children(self): + # docstring inherited. + return [ + *self._children, + *self.spines.values(), + *self._axis_map.values(), + self.title, self._left_title, self._right_title, + *self.child_axes, + *([self.legend_] if self.legend_ is not None else []), + self.patch, + ] + + def contains(self, mouseevent): + # docstring inherited. + return self.patch.contains(mouseevent) + + def contains_point(self, point): + """ + Return whether *point* (pair of pixel coordinates) is inside the Axes + patch. + """ + return self.patch.contains_point(point, radius=1.0) + + def get_default_bbox_extra_artists(self): + """ + Return a default list of artists that are used for the bounding box + calculation. + + Artists are excluded either by not being visible or + ``artist.set_in_layout(False)``. + """ + + artists = self.get_children() + + for axis in self._axis_map.values(): + # axis tight bboxes are calculated separately inside + # Axes.get_tightbbox() using for_layout_only=True + artists.remove(axis) + if not (self.axison and self._frameon): + # don't do bbox on spines if frame not on. + for spine in self.spines.values(): + artists.remove(spine) + + artists.remove(self.title) + artists.remove(self._left_title) + artists.remove(self._right_title) + + # always include types that do not internally implement clipping + # to Axes. may have clip_on set to True and clip_box equivalent + # to ax.bbox but then ignore these properties during draws. + noclip = (_AxesBase, maxis.Axis, + offsetbox.AnnotationBbox, offsetbox.OffsetBox) + return [a for a in artists if a.get_visible() and a.get_in_layout() + and (isinstance(a, noclip) or not a._fully_clipped_to_axes())] + + @_api.make_keyword_only("3.8", "call_axes_locator") + def get_tightbbox(self, renderer=None, call_axes_locator=True, + bbox_extra_artists=None, *, for_layout_only=False): + """ + Return the tight bounding box of the Axes, including axis and their + decorators (xlabel, title, etc). + + Artists that have ``artist.set_in_layout(False)`` are not included + in the bbox. + + Parameters + ---------- + renderer : `.RendererBase` subclass + renderer that will be used to draw the figures (i.e. + ``fig.canvas.get_renderer()``) + + bbox_extra_artists : list of `.Artist` or ``None`` + List of artists to include in the tight bounding box. If + ``None`` (default), then all artist children of the Axes are + included in the tight bounding box. + + call_axes_locator : bool, default: True + If *call_axes_locator* is ``False``, it does not call the + ``_axes_locator`` attribute, which is necessary to get the correct + bounding box. ``call_axes_locator=False`` can be used if the + caller is only interested in the relative size of the tightbbox + compared to the Axes bbox. + + for_layout_only : default: False + The bounding box will *not* include the x-extent of the title and + the xlabel, or the y-extent of the ylabel. + + Returns + ------- + `.BboxBase` + Bounding box in figure pixel coordinates. + + See Also + -------- + matplotlib.axes.Axes.get_window_extent + matplotlib.axis.Axis.get_tightbbox + matplotlib.spines.Spine.get_window_extent + """ + + bb = [] + if renderer is None: + renderer = self.figure._get_renderer() + + if not self.get_visible(): + return None + + locator = self.get_axes_locator() + self.apply_aspect( + locator(self, renderer) if locator and call_axes_locator else None) + + for axis in self._axis_map.values(): + if self.axison and axis.get_visible(): + ba = martist._get_tightbbox_for_layout_only(axis, renderer) + if ba: + bb.append(ba) + self._update_title_position(renderer) + axbbox = self.get_window_extent(renderer) + bb.append(axbbox) + + for title in [self.title, self._left_title, self._right_title]: + if title.get_visible(): + bt = title.get_window_extent(renderer) + if for_layout_only and bt.width > 0: + # make the title bbox 1 pixel wide so its width + # is not accounted for in bbox calculations in + # tight/constrained_layout + bt.x0 = (bt.x0 + bt.x1) / 2 - 0.5 + bt.x1 = bt.x0 + 1.0 + bb.append(bt) + + bbox_artists = bbox_extra_artists + if bbox_artists is None: + bbox_artists = self.get_default_bbox_extra_artists() + + for a in bbox_artists: + bbox = a.get_tightbbox(renderer) + if (bbox is not None + and 0 < bbox.width < np.inf + and 0 < bbox.height < np.inf): + bb.append(bbox) + return mtransforms.Bbox.union( + [b for b in bb if b.width != 0 or b.height != 0]) + + def _make_twin_axes(self, *args, **kwargs): + """Make a twinx Axes of self. This is used for twinx and twiny.""" + if 'sharex' in kwargs and 'sharey' in kwargs: + # The following line is added in v2.2 to avoid breaking Seaborn, + # which currently uses this internal API. + if kwargs["sharex"] is not self and kwargs["sharey"] is not self: + raise ValueError("Twinned Axes may share only one axis") + ss = self.get_subplotspec() + if ss: + twin = self.figure.add_subplot(ss, *args, **kwargs) + else: + twin = self.figure.add_axes( + self.get_position(True), *args, **kwargs, + axes_locator=_TransformedBoundsLocator( + [0, 0, 1, 1], self.transAxes)) + self.set_adjustable('datalim') + twin.set_adjustable('datalim') + twin.set_zorder(self.zorder) + + self._twinned_axes.join(self, twin) + return twin + + def twinx(self): + """ + Create a twin Axes sharing the xaxis. + + Create a new Axes with an invisible x-axis and an independent + y-axis positioned opposite to the original one (i.e. at right). The + x-axis autoscale setting will be inherited from the original + Axes. To ensure that the tick marks of both y-axes align, see + `~matplotlib.ticker.LinearLocator`. + + Returns + ------- + Axes + The newly created Axes instance + + Notes + ----- + For those who are 'picking' artists while using twinx, pick + events are only called for the artists in the top-most Axes. + """ + ax2 = self._make_twin_axes(sharex=self) + ax2.yaxis.tick_right() + ax2.yaxis.set_label_position('right') + ax2.yaxis.set_offset_position('right') + ax2.set_autoscalex_on(self.get_autoscalex_on()) + self.yaxis.tick_left() + ax2.xaxis.set_visible(False) + ax2.patch.set_visible(False) + ax2.xaxis.units = self.xaxis.units + return ax2 + + def twiny(self): + """ + Create a twin Axes sharing the yaxis. + + Create a new Axes with an invisible y-axis and an independent + x-axis positioned opposite to the original one (i.e. at top). The + y-axis autoscale setting will be inherited from the original Axes. + To ensure that the tick marks of both x-axes align, see + `~matplotlib.ticker.LinearLocator`. + + Returns + ------- + Axes + The newly created Axes instance + + Notes + ----- + For those who are 'picking' artists while using twiny, pick + events are only called for the artists in the top-most Axes. + """ + ax2 = self._make_twin_axes(sharey=self) + ax2.xaxis.tick_top() + ax2.xaxis.set_label_position('top') + ax2.set_autoscaley_on(self.get_autoscaley_on()) + self.xaxis.tick_bottom() + ax2.yaxis.set_visible(False) + ax2.patch.set_visible(False) + ax2.yaxis.units = self.yaxis.units + return ax2 + + def get_shared_x_axes(self): + """Return an immutable view on the shared x-axes Grouper.""" + return cbook.GrouperView(self._shared_axes["x"]) + + def get_shared_y_axes(self): + """Return an immutable view on the shared y-axes Grouper.""" + return cbook.GrouperView(self._shared_axes["y"]) + + def label_outer(self, remove_inner_ticks=False): + """ + Only show "outer" labels and tick labels. + + x-labels are only kept for subplots on the last row (or first row, if + labels are on the top side); y-labels only for subplots on the first + column (or last column, if labels are on the right side). + + Parameters + ---------- + remove_inner_ticks : bool, default: False + If True, remove the inner ticks as well (not only tick labels). + + .. versionadded:: 3.8 + """ + self._label_outer_xaxis(skip_non_rectangular_axes=False, + remove_inner_ticks=remove_inner_ticks) + self._label_outer_yaxis(skip_non_rectangular_axes=False, + remove_inner_ticks=remove_inner_ticks) + + def _label_outer_xaxis(self, *, skip_non_rectangular_axes, + remove_inner_ticks=False): + # see documentation in label_outer. + if skip_non_rectangular_axes and not isinstance(self.patch, + mpl.patches.Rectangle): + return + ss = self.get_subplotspec() + if not ss: + return + label_position = self.xaxis.get_label_position() + if not ss.is_first_row(): # Remove top label/ticklabels/offsettext. + if label_position == "top": + self.set_xlabel("") + top_kw = {'top': False} if remove_inner_ticks else {} + self.xaxis.set_tick_params( + which="both", labeltop=False, **top_kw) + if self.xaxis.offsetText.get_position()[1] == 1: + self.xaxis.offsetText.set_visible(False) + if not ss.is_last_row(): # Remove bottom label/ticklabels/offsettext. + if label_position == "bottom": + self.set_xlabel("") + bottom_kw = {'bottom': False} if remove_inner_ticks else {} + self.xaxis.set_tick_params( + which="both", labelbottom=False, **bottom_kw) + if self.xaxis.offsetText.get_position()[1] == 0: + self.xaxis.offsetText.set_visible(False) + + def _label_outer_yaxis(self, *, skip_non_rectangular_axes, + remove_inner_ticks=False): + # see documentation in label_outer. + if skip_non_rectangular_axes and not isinstance(self.patch, + mpl.patches.Rectangle): + return + ss = self.get_subplotspec() + if not ss: + return + label_position = self.yaxis.get_label_position() + if not ss.is_first_col(): # Remove left label/ticklabels/offsettext. + if label_position == "left": + self.set_ylabel("") + left_kw = {'left': False} if remove_inner_ticks else {} + self.yaxis.set_tick_params( + which="both", labelleft=False, **left_kw) + if self.yaxis.offsetText.get_position()[0] == 0: + self.yaxis.offsetText.set_visible(False) + if not ss.is_last_col(): # Remove right label/ticklabels/offsettext. + if label_position == "right": + self.set_ylabel("") + right_kw = {'right': False} if remove_inner_ticks else {} + self.yaxis.set_tick_params( + which="both", labelright=False, **right_kw) + if self.yaxis.offsetText.get_position()[0] == 1: + self.yaxis.offsetText.set_visible(False) + + def set_forward_navigation_events(self, forward): + """ + Set how pan/zoom events are forwarded to Axes below this one. + + Parameters + ---------- + forward : bool or "auto" + Possible values: + + - True: Forward events to other axes with lower or equal zorder. + - False: Events are only executed on this axes. + - "auto": Default behaviour (*True* for axes with an invisible + patch and *False* otherwise) + + See Also + -------- + matplotlib.axes.Axes.set_navigate + + """ + self._forward_navigation_events = forward + + def get_forward_navigation_events(self): + """Get how pan/zoom events are forwarded to Axes below this one.""" + return self._forward_navigation_events + + +def _draw_rasterized(figure, artists, renderer): + """ + A helper function for rasterizing the list of artists. + + The bookkeeping to track if we are or are not in rasterizing mode + with the mixed-mode backends is relatively complicated and is now + handled in the matplotlib.artist.allow_rasterization decorator. + + This helper defines the absolute minimum methods and attributes on a + shim class to be compatible with that decorator and then uses it to + rasterize the list of artists. + + This is maybe too-clever, but allows us to reuse the same code that is + used on normal artists to participate in the "are we rasterizing" + accounting. + + Please do not use this outside of the "rasterize below a given zorder" + functionality of Axes. + + Parameters + ---------- + figure : matplotlib.figure.Figure + The figure all of the artists belong to (not checked). We need this + because we can at the figure level suppress composition and insert each + rasterized artist as its own image. + + artists : List[matplotlib.artist.Artist] + The list of Artists to be rasterized. These are assumed to all + be in the same Figure. + + renderer : matplotlib.backendbases.RendererBase + The currently active renderer + + Returns + ------- + None + + """ + class _MinimalArtist: + def get_rasterized(self): + return True + + def get_agg_filter(self): + return None + + def __init__(self, figure, artists): + self.figure = figure + self.artists = artists + + @martist.allow_rasterization + def draw(self, renderer): + for a in self.artists: + a.draw(renderer) + + return _MinimalArtist(figure, artists).draw(renderer) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/_base.pyi b/parrot/lib/python3.10/site-packages/matplotlib/axes/_base.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8cd88a92cc09728901482ef2fb0e5f348c87f5f0 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/axes/_base.pyi @@ -0,0 +1,459 @@ +import matplotlib.artist as martist + +import datetime +from collections.abc import Callable, Iterable, Iterator, Sequence +from matplotlib import cbook +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.axis import XAxis, YAxis, Tick +from matplotlib.backend_bases import RendererBase, MouseButton, MouseEvent +from matplotlib.cbook import CallbackRegistry +from matplotlib.container import Container +from matplotlib.collections import Collection +from matplotlib.cm import ScalarMappable +from matplotlib.legend import Legend +from matplotlib.lines import Line2D +from matplotlib.gridspec import SubplotSpec, GridSpec +from matplotlib.figure import Figure +from matplotlib.image import AxesImage +from matplotlib.patches import Patch +from matplotlib.scale import ScaleBase +from matplotlib.spines import Spines +from matplotlib.table import Table +from matplotlib.text import Text +from matplotlib.transforms import Transform, Bbox + +from cycler import Cycler + +import numpy as np +from numpy.typing import ArrayLike +from typing import Any, Literal, TypeVar, overload +from matplotlib.typing import ColorType + +_T = TypeVar("_T", bound=Artist) + +class _axis_method_wrapper: + attr_name: str + method_name: str + __doc__: str + def __init__( + self, attr_name: str, method_name: str, *, doc_sub: dict[str, str] | None = ... + ) -> None: ... + def __set_name__(self, owner: Any, name: str) -> None: ... + +class _AxesBase(martist.Artist): + name: str + patch: Patch + spines: Spines + fmt_xdata: Callable[[float], str] | None + fmt_ydata: Callable[[float], str] | None + xaxis: XAxis + yaxis: YAxis + bbox: Bbox + dataLim: Bbox + transAxes: Transform + transScale: Transform + transLimits: Transform + transData: Transform + ignore_existing_data_limits: bool + axison: bool + containers: list[Container] + callbacks: CallbackRegistry + child_axes: list[_AxesBase] + legend_: Legend | None + title: Text + _projection_init: Any + + def __init__( + self, + fig: Figure, + *args: tuple[float, float, float, float] | Bbox | int, + facecolor: ColorType | None = ..., + frameon: bool = ..., + sharex: _AxesBase | None = ..., + sharey: _AxesBase | None = ..., + label: Any = ..., + xscale: str | ScaleBase | None = ..., + yscale: str | ScaleBase | None = ..., + box_aspect: float | None = ..., + forward_navigation_events: bool | Literal["auto"] = ..., + **kwargs + ) -> None: ... + def get_subplotspec(self) -> SubplotSpec | None: ... + def set_subplotspec(self, subplotspec: SubplotSpec) -> None: ... + def get_gridspec(self) -> GridSpec | None: ... + def set_figure(self, fig: Figure) -> None: ... + @property + def viewLim(self) -> Bbox: ... + def get_xaxis_transform( + self, which: Literal["grid", "tick1", "tick2"] = ... + ) -> Transform: ... + def get_xaxis_text1_transform( + self, pad_points: float + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_xaxis_text2_transform( + self, pad_points + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_yaxis_transform( + self, which: Literal["grid", "tick1", "tick2"] = ... + ) -> Transform: ... + def get_yaxis_text1_transform( + self, pad_points + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_yaxis_text2_transform( + self, pad_points + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_position(self, original: bool = ...) -> Bbox: ... + def set_position( + self, + pos: Bbox | tuple[float, float, float, float], + which: Literal["both", "active", "original"] = ..., + ) -> None: ... + def reset_position(self) -> None: ... + def set_axes_locator( + self, locator: Callable[[_AxesBase, RendererBase], Bbox] + ) -> None: ... + def get_axes_locator(self) -> Callable[[_AxesBase, RendererBase], Bbox]: ... + def sharex(self, other: _AxesBase) -> None: ... + def sharey(self, other: _AxesBase) -> None: ... + def clear(self) -> None: ... + def cla(self) -> None: ... + + class ArtistList(Sequence[_T]): + def __init__( + self, + axes: _AxesBase, + prop_name: str, + valid_types: type | Iterable[type] | None = ..., + invalid_types: type | Iterable[type] | None = ..., + ) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + @overload + def __getitem__(self, key: int) -> _T: ... + @overload + def __getitem__(self, key: slice) -> list[_T]: ... + + @overload + def __add__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ... + @overload + def __add__(self, other: list[Any]) -> list[Any]: ... + @overload + def __add__(self, other: tuple[Any]) -> tuple[Any]: ... + + @overload + def __radd__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ... + @overload + def __radd__(self, other: list[Any]) -> list[Any]: ... + @overload + def __radd__(self, other: tuple[Any]) -> tuple[Any]: ... + + @property + def artists(self) -> _AxesBase.ArtistList[Artist]: ... + @property + def collections(self) -> _AxesBase.ArtistList[Collection]: ... + @property + def images(self) -> _AxesBase.ArtistList[AxesImage]: ... + @property + def lines(self) -> _AxesBase.ArtistList[Line2D]: ... + @property + def patches(self) -> _AxesBase.ArtistList[Patch]: ... + @property + def tables(self) -> _AxesBase.ArtistList[Table]: ... + @property + def texts(self) -> _AxesBase.ArtistList[Text]: ... + def get_facecolor(self) -> ColorType: ... + def set_facecolor(self, color: ColorType | None) -> None: ... + @overload + def set_prop_cycle(self, cycler: Cycler) -> None: ... + @overload + def set_prop_cycle(self, label: str, values: Iterable[Any]) -> None: ... + @overload + def set_prop_cycle(self, **kwargs: Iterable[Any]) -> None: ... + def get_aspect(self) -> float | Literal["auto"]: ... + def set_aspect( + self, + aspect: float | Literal["auto", "equal"], + adjustable: Literal["box", "datalim"] | None = ..., + anchor: str | tuple[float, float] | None = ..., + share: bool = ..., + ) -> None: ... + def get_adjustable(self) -> Literal["box", "datalim"]: ... + def set_adjustable( + self, adjustable: Literal["box", "datalim"], share: bool = ... + ) -> None: ... + def get_box_aspect(self) -> float | None: ... + def set_box_aspect(self, aspect: float | None = ...) -> None: ... + def get_anchor(self) -> str | tuple[float, float]: ... + def set_anchor( + self, anchor: str | tuple[float, float], share: bool = ... + ) -> None: ... + def get_data_ratio(self) -> float: ... + def apply_aspect(self, position: Bbox | None = ...) -> None: ... + @overload + def axis( + self, + arg: tuple[float, float, float, float] | bool | str | None = ..., + /, + *, + emit: bool = ... + ) -> tuple[float, float, float, float]: ... + @overload + def axis( + self, + *, + emit: bool = ..., + xmin: float | None = ..., + xmax: float | None = ..., + ymin: float | None = ..., + ymax: float | None = ... + ) -> tuple[float, float, float, float]: ... + def get_legend(self) -> Legend: ... + def get_images(self) -> list[AxesImage]: ... + def get_lines(self) -> list[Line2D]: ... + def get_xaxis(self) -> XAxis: ... + def get_yaxis(self) -> YAxis: ... + def has_data(self) -> bool: ... + def add_artist(self, a: Artist) -> Artist: ... + def add_child_axes(self, ax: _AxesBase) -> _AxesBase: ... + def add_collection( + self, collection: Collection, autolim: bool = ... + ) -> Collection: ... + def add_image(self, image: AxesImage) -> AxesImage: ... + def add_line(self, line: Line2D) -> Line2D: ... + def add_patch(self, p: Patch) -> Patch: ... + def add_table(self, tab: Table) -> Table: ... + def add_container(self, container: Container) -> Container: ... + def relim(self, visible_only: bool = ...) -> None: ... + def update_datalim( + self, xys: ArrayLike, updatex: bool = ..., updatey: bool = ... + ) -> None: ... + def in_axes(self, mouseevent: MouseEvent) -> bool: ... + def get_autoscale_on(self) -> bool: ... + def set_autoscale_on(self, b: bool) -> None: ... + @property + def use_sticky_edges(self) -> bool: ... + @use_sticky_edges.setter + def use_sticky_edges(self, b: bool) -> None: ... + def get_xmargin(self) -> float: ... + def get_ymargin(self) -> float: ... + def set_xmargin(self, m: float) -> None: ... + def set_ymargin(self, m: float) -> None: ... + + # Probably could be made better with overloads + def margins( + self, + *margins: float, + x: float | None = ..., + y: float | None = ..., + tight: bool | None = ... + ) -> tuple[float, float] | None: ... + def set_rasterization_zorder(self, z: float | None) -> None: ... + def get_rasterization_zorder(self) -> float | None: ... + def autoscale( + self, + enable: bool = ..., + axis: Literal["both", "x", "y"] = ..., + tight: bool | None = ..., + ) -> None: ... + def autoscale_view( + self, tight: bool | None = ..., scalex: bool = ..., scaley: bool = ... + ) -> None: ... + def draw_artist(self, a: Artist) -> None: ... + def redraw_in_frame(self) -> None: ... + def get_frame_on(self) -> bool: ... + def set_frame_on(self, b: bool) -> None: ... + def get_axisbelow(self) -> bool | Literal["line"]: ... + def set_axisbelow(self, b: bool | Literal["line"]) -> None: ... + def grid( + self, + visible: bool | None = ..., + which: Literal["major", "minor", "both"] = ..., + axis: Literal["both", "x", "y"] = ..., + **kwargs + ) -> None: ... + def ticklabel_format( + self, + *, + axis: Literal["both", "x", "y"] = ..., + style: Literal["", "sci", "scientific", "plain"] | None = ..., + scilimits: tuple[int, int] | None = ..., + useOffset: bool | float | None = ..., + useLocale: bool | None = ..., + useMathText: bool | None = ... + ) -> None: ... + def locator_params( + self, axis: Literal["both", "x", "y"] = ..., tight: bool | None = ..., **kwargs + ) -> None: ... + def tick_params(self, axis: Literal["both", "x", "y"] = ..., **kwargs) -> None: ... + def set_axis_off(self) -> None: ... + def set_axis_on(self) -> None: ... + def get_xlabel(self) -> str: ... + def set_xlabel( + self, + xlabel: str, + fontdict: dict[str, Any] | None = ..., + labelpad: float | None = ..., + *, + loc: Literal["left", "center", "right"] | None = ..., + **kwargs + ) -> Text: ... + def invert_xaxis(self) -> None: ... + def get_xbound(self) -> tuple[float, float]: ... + def set_xbound( + self, lower: float | None = ..., upper: float | None = ... + ) -> None: ... + def get_xlim(self) -> tuple[float, float]: ... + def set_xlim( + self, + left: float | tuple[float, float] | None = ..., + right: float | None = ..., + *, + emit: bool = ..., + auto: bool | None = ..., + xmin: float | None = ..., + xmax: float | None = ... + ) -> tuple[float, float]: ... + def get_ylabel(self) -> str: ... + def set_ylabel( + self, + ylabel: str, + fontdict: dict[str, Any] | None = ..., + labelpad: float | None = ..., + *, + loc: Literal["bottom", "center", "top"] | None = ..., + **kwargs + ) -> Text: ... + def invert_yaxis(self) -> None: ... + def get_ybound(self) -> tuple[float, float]: ... + def set_ybound( + self, lower: float | None = ..., upper: float | None = ... + ) -> None: ... + def get_ylim(self) -> tuple[float, float]: ... + def set_ylim( + self, + bottom: float | tuple[float, float] | None = ..., + top: float | None = ..., + *, + emit: bool = ..., + auto: bool | None = ..., + ymin: float | None = ..., + ymax: float | None = ... + ) -> tuple[float, float]: ... + def format_xdata(self, x: float) -> str: ... + def format_ydata(self, y: float) -> str: ... + def format_coord(self, x: float, y: float) -> str: ... + def minorticks_on(self) -> None: ... + def minorticks_off(self) -> None: ... + def can_zoom(self) -> bool: ... + def can_pan(self) -> bool: ... + def get_navigate(self) -> bool: ... + def set_navigate(self, b: bool) -> None: ... + def get_forward_navigation_events(self) -> bool | Literal["auto"]: ... + def set_forward_navigation_events(self, forward: bool | Literal["auto"]) -> None: ... + def get_navigate_mode(self) -> Literal["PAN", "ZOOM"] | None: ... + def set_navigate_mode(self, b: Literal["PAN", "ZOOM"] | None) -> None: ... + def start_pan(self, x: float, y: float, button: MouseButton) -> None: ... + def end_pan(self) -> None: ... + def drag_pan( + self, button: MouseButton, key: str | None, x: float, y: float + ) -> None: ... + def get_children(self) -> list[Artist]: ... + def contains_point(self, point: tuple[int, int]) -> bool: ... + def get_default_bbox_extra_artists(self) -> list[Artist]: ... + def get_tightbbox( + self, + renderer: RendererBase | None = ..., + *, + call_axes_locator: bool = ..., + bbox_extra_artists: Sequence[Artist] | None = ..., + for_layout_only: bool = ... + ) -> Bbox | None: ... + def twinx(self) -> Axes: ... + def twiny(self) -> Axes: ... + def get_shared_x_axes(self) -> cbook.GrouperView: ... + def get_shared_y_axes(self) -> cbook.GrouperView: ... + def label_outer(self, remove_inner_ticks: bool = ...) -> None: ... + + # The methods underneath this line are added via the `_axis_method_wrapper` class + # Initially they are set to an object, but that object uses `__set_name__` to override + # itself with a method modified from the Axis methods for the x or y Axis. + # As such, they are typed according to the resultant method rather than as that object. + + def get_xgridlines(self) -> list[Line2D]: ... + def get_xticklines(self, minor: bool = ...) -> list[Line2D]: ... + def get_ygridlines(self) -> list[Line2D]: ... + def get_yticklines(self, minor: bool = ...) -> list[Line2D]: ... + def _sci(self, im: ScalarMappable) -> None: ... + def get_autoscalex_on(self) -> bool: ... + def get_autoscaley_on(self) -> bool: ... + def set_autoscalex_on(self, b: bool) -> None: ... + def set_autoscaley_on(self, b: bool) -> None: ... + def xaxis_inverted(self) -> bool: ... + def get_xscale(self) -> str: ... + def set_xscale(self, value: str | ScaleBase, **kwargs) -> None: ... + def get_xticks(self, *, minor: bool = ...) -> np.ndarray: ... + def set_xticks( + self, + ticks: ArrayLike, + labels: Iterable[str] | None = ..., + *, + minor: bool = ..., + **kwargs + ) -> list[Tick]: ... + def get_xmajorticklabels(self) -> list[Text]: ... + def get_xminorticklabels(self) -> list[Text]: ... + def get_xticklabels( + self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ... + ) -> list[Text]: ... + def set_xticklabels( + self, + labels: Iterable[str | Text], + *, + minor: bool = ..., + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> list[Text]: ... + def yaxis_inverted(self) -> bool: ... + def get_yscale(self) -> str: ... + def set_yscale(self, value: str | ScaleBase, **kwargs) -> None: ... + def get_yticks(self, *, minor: bool = ...) -> np.ndarray: ... + def set_yticks( + self, + ticks: ArrayLike, + labels: Iterable[str] | None = ..., + *, + minor: bool = ..., + **kwargs + ) -> list[Tick]: ... + def get_ymajorticklabels(self) -> list[Text]: ... + def get_yminorticklabels(self) -> list[Text]: ... + def get_yticklabels( + self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ... + ) -> list[Text]: ... + def set_yticklabels( + self, + labels: Iterable[str | Text], + *, + minor: bool = ..., + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> list[Text]: ... + def xaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ... + def yaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ... diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.py b/parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..3fabf49ebb38ccf5f7cd16c7aa4bcfd32b5ffc77 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.py @@ -0,0 +1,321 @@ +import numbers + +import numpy as np + +from matplotlib import _api, _docstring, transforms +import matplotlib.ticker as mticker +from matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator +from matplotlib.axis import Axis +from matplotlib.transforms import Transform + + +class SecondaryAxis(_AxesBase): + """ + General class to hold a Secondary_X/Yaxis. + """ + + def __init__(self, parent, orientation, location, functions, transform=None, + **kwargs): + """ + See `.secondary_xaxis` and `.secondary_yaxis` for the doc string. + While there is no need for this to be private, it should really be + called by those higher level functions. + """ + _api.check_in_list(["x", "y"], orientation=orientation) + self._functions = functions + self._parent = parent + self._orientation = orientation + self._ticks_set = False + + if self._orientation == 'x': + super().__init__(self._parent.figure, [0, 1., 1, 0.0001], **kwargs) + self._axis = self.xaxis + self._locstrings = ['top', 'bottom'] + self._otherstrings = ['left', 'right'] + else: # 'y' + super().__init__(self._parent.figure, [0, 1., 0.0001, 1], **kwargs) + self._axis = self.yaxis + self._locstrings = ['right', 'left'] + self._otherstrings = ['top', 'bottom'] + self._parentscale = None + # this gets positioned w/o constrained_layout so exclude: + + self.set_location(location, transform) + self.set_functions(functions) + + # styling: + otheraxis = self.yaxis if self._orientation == 'x' else self.xaxis + otheraxis.set_major_locator(mticker.NullLocator()) + otheraxis.set_ticks_position('none') + + self.spines[self._otherstrings].set_visible(False) + self.spines[self._locstrings].set_visible(True) + + if self._pos < 0.5: + # flip the location strings... + self._locstrings = self._locstrings[::-1] + self.set_alignment(self._locstrings[0]) + + def set_alignment(self, align): + """ + Set if axes spine and labels are drawn at top or bottom (or left/right) + of the Axes. + + Parameters + ---------- + align : {'top', 'bottom', 'left', 'right'} + Either 'top' or 'bottom' for orientation='x' or + 'left' or 'right' for orientation='y' axis. + """ + _api.check_in_list(self._locstrings, align=align) + if align == self._locstrings[1]: # Need to change the orientation. + self._locstrings = self._locstrings[::-1] + self.spines[self._locstrings[0]].set_visible(True) + self.spines[self._locstrings[1]].set_visible(False) + self._axis.set_ticks_position(align) + self._axis.set_label_position(align) + + def set_location(self, location, transform=None): + """ + Set the vertical or horizontal location of the axes in + parent-normalized coordinates. + + Parameters + ---------- + location : {'top', 'bottom', 'left', 'right'} or float + The position to put the secondary axis. Strings can be 'top' or + 'bottom' for orientation='x' and 'right' or 'left' for + orientation='y'. A float indicates the relative position on the + parent Axes to put the new Axes, 0.0 being the bottom (or left) + and 1.0 being the top (or right). + + transform : `.Transform`, optional + Transform for the location to use. Defaults to + the parent's ``transAxes``, so locations are normally relative to + the parent axes. + + .. versionadded:: 3.9 + """ + + _api.check_isinstance((transforms.Transform, None), transform=transform) + + # This puts the rectangle into figure-relative coordinates. + if isinstance(location, str): + _api.check_in_list(self._locstrings, location=location) + self._pos = 1. if location in ('top', 'right') else 0. + elif isinstance(location, numbers.Real): + self._pos = location + else: + raise ValueError( + f"location must be {self._locstrings[0]!r}, " + f"{self._locstrings[1]!r}, or a float, not {location!r}") + + self._loc = location + + if self._orientation == 'x': + # An x-secondary axes is like an inset axes from x = 0 to x = 1 and + # from y = pos to y = pos + eps, in the parent's transAxes coords. + bounds = [0, self._pos, 1., 1e-10] + + # If a transformation is provided, use its y component rather than + # the parent's transAxes. This can be used to place axes in the data + # coords, for instance. + if transform is not None: + transform = transforms.blended_transform_factory( + self._parent.transAxes, transform) + else: # 'y' + bounds = [self._pos, 0, 1e-10, 1] + if transform is not None: + transform = transforms.blended_transform_factory( + transform, self._parent.transAxes) # Use provided x axis + + # If no transform is provided, use the parent's transAxes + if transform is None: + transform = self._parent.transAxes + + # this locator lets the axes move in the parent axes coordinates. + # so it never needs to know where the parent is explicitly in + # figure coordinates. + # it gets called in ax.apply_aspect() (of all places) + self.set_axes_locator(_TransformedBoundsLocator(bounds, transform)) + + def apply_aspect(self, position=None): + # docstring inherited. + self._set_lims() + super().apply_aspect(position) + + @_docstring.copy(Axis.set_ticks) + def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs): + ret = self._axis.set_ticks(ticks, labels, minor=minor, **kwargs) + self.stale = True + self._ticks_set = True + return ret + + def set_functions(self, functions): + """ + Set how the secondary axis converts limits from the parent Axes. + + Parameters + ---------- + functions : 2-tuple of func, or `Transform` with an inverse. + Transform between the parent axis values and the secondary axis + values. + + If supplied as a 2-tuple of functions, the first function is + the forward transform function and the second is the inverse + transform. + + If a transform is supplied, then the transform must have an + inverse. + """ + + if (isinstance(functions, tuple) and len(functions) == 2 and + callable(functions[0]) and callable(functions[1])): + # make an arbitrary convert from a two-tuple of functions + # forward and inverse. + self._functions = functions + elif isinstance(functions, Transform): + self._functions = ( + functions.transform, + lambda x: functions.inverted().transform(x) + ) + elif functions is None: + self._functions = (lambda x: x, lambda x: x) + else: + raise ValueError('functions argument of secondary Axes ' + 'must be a two-tuple of callable functions ' + 'with the first function being the transform ' + 'and the second being the inverse') + self._set_scale() + + def draw(self, renderer): + """ + Draw the secondary Axes. + + Consults the parent Axes for its limits and converts them + using the converter specified by + `~.axes._secondary_axes.set_functions` (or *functions* + parameter when Axes initialized.) + """ + self._set_lims() + # this sets the scale in case the parent has set its scale. + self._set_scale() + super().draw(renderer) + + def _set_scale(self): + """ + Check if parent has set its scale + """ + + if self._orientation == 'x': + pscale = self._parent.xaxis.get_scale() + set_scale = self.set_xscale + else: # 'y' + pscale = self._parent.yaxis.get_scale() + set_scale = self.set_yscale + if pscale == self._parentscale: + return + + if self._ticks_set: + ticks = self._axis.get_ticklocs() + + # need to invert the roles here for the ticks to line up. + set_scale('functionlog' if pscale == 'log' else 'function', + functions=self._functions[::-1]) + + # OK, set_scale sets the locators, but if we've called + # axsecond.set_ticks, we want to keep those. + if self._ticks_set: + self._axis.set_major_locator(mticker.FixedLocator(ticks)) + + # If the parent scale doesn't change, we can skip this next time. + self._parentscale = pscale + + def _set_lims(self): + """ + Set the limits based on parent limits and the convert method + between the parent and this secondary Axes. + """ + if self._orientation == 'x': + lims = self._parent.get_xlim() + set_lim = self.set_xlim + else: # 'y' + lims = self._parent.get_ylim() + set_lim = self.set_ylim + order = lims[0] < lims[1] + lims = self._functions[0](np.array(lims)) + neworder = lims[0] < lims[1] + if neworder != order: + # Flip because the transform will take care of the flipping. + lims = lims[::-1] + set_lim(lims) + + def set_aspect(self, *args, **kwargs): + """ + Secondary Axes cannot set the aspect ratio, so calling this just + sets a warning. + """ + _api.warn_external("Secondary Axes can't set the aspect ratio") + + def set_color(self, color): + """ + Change the color of the secondary Axes and all decorators. + + Parameters + ---------- + color : :mpltype:`color` + """ + axis = self._axis_map[self._orientation] + axis.set_tick_params(colors=color) + for spine in self.spines.values(): + if spine.axis is axis: + spine.set_color(color) + axis.label.set_color(color) + + +_secax_docstring = ''' +Warnings +-------- +This method is experimental as of 3.1, and the API may change. + +Parameters +---------- +location : {'top', 'bottom', 'left', 'right'} or float + The position to put the secondary axis. Strings can be 'top' or + 'bottom' for orientation='x' and 'right' or 'left' for + orientation='y'. A float indicates the relative position on the + parent Axes to put the new Axes, 0.0 being the bottom (or left) + and 1.0 being the top (or right). + +functions : 2-tuple of func, or Transform with an inverse + + If a 2-tuple of functions, the user specifies the transform + function and its inverse. i.e. + ``functions=(lambda x: 2 / x, lambda x: 2 / x)`` would be an + reciprocal transform with a factor of 2. Both functions must accept + numpy arrays as input. + + The user can also directly supply a subclass of + `.transforms.Transform` so long as it has an inverse. + + See :doc:`/gallery/subplots_axes_and_figures/secondary_axis` + for examples of making these conversions. + +transform : `.Transform`, optional + If specified, *location* will be + placed relative to this transform (in the direction of the axis) + rather than the parent's axis. i.e. a secondary x-axis will + use the provided y transform and the x transform of the parent. + + .. versionadded:: 3.9 + +Returns +------- +ax : axes._secondary_axes.SecondaryAxis + +Other Parameters +---------------- +**kwargs : `~matplotlib.axes.Axes` properties. + Other miscellaneous Axes parameters. +''' +_docstring.interpd.update(_secax_docstring=_secax_docstring) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.pyi b/parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..afb429f740c4aa58a42b64f9209e1e0bd9ee57f7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.pyi @@ -0,0 +1,45 @@ +from matplotlib.axes._base import _AxesBase +from matplotlib.axis import Tick + +from matplotlib.transforms import Transform + +from collections.abc import Callable, Iterable +from typing import Literal +from numpy.typing import ArrayLike +from matplotlib.typing import ColorType + +class SecondaryAxis(_AxesBase): + def __init__( + self, + parent: _AxesBase, + orientation: Literal["x", "y"], + location: Literal["top", "bottom", "right", "left"] | float, + functions: tuple[ + Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] + ] + | Transform, + transform: Transform | None = ..., + **kwargs + ) -> None: ... + def set_alignment( + self, align: Literal["top", "bottom", "right", "left"] + ) -> None: ... + def set_location( + self, + location: Literal["top", "bottom", "right", "left"] | float, + transform: Transform | None = ... + ) -> None: ... + def set_ticks( + self, + ticks: ArrayLike, + labels: Iterable[str] | None = ..., + *, + minor: bool = ..., + **kwargs + ) -> list[Tick]: ... + def set_functions( + self, + functions: tuple[Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]] | Transform, + ) -> None: ... + def set_aspect(self, *args, **kwargs) -> None: ... + def set_color(self, color: ColorType) -> None: ... diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/__init__.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cf0f682d5d4b4772426ea2ff0e62251ce947a827 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/__init__.py @@ -0,0 +1,5 @@ +from .registry import BackendFilter, backend_registry # noqa: F401 + +# NOTE: plt.switch_backend() (called at import time) will add a "backend" +# attribute here for backcompat. +_QT_FORCE_QT5_BINDING = False diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_agg.pyi b/parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_agg.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_pdf_ps.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_pdf_ps.py new file mode 100644 index 0000000000000000000000000000000000000000..ce55df523d9d0b336424b4b609ba51af59c5fb32 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_pdf_ps.py @@ -0,0 +1,145 @@ +""" +Common functionality between the PDF and PS backends. +""" + +from io import BytesIO +import functools + +from fontTools import subset + +import matplotlib as mpl +from .. import font_manager, ft2font +from .._afm import AFM +from ..backend_bases import RendererBase + + +@functools.lru_cache(50) +def _cached_get_afm_from_fname(fname): + with open(fname, "rb") as fh: + return AFM(fh) + + +def get_glyphs_subset(fontfile, characters): + """ + Subset a TTF font + + Reads the named fontfile and restricts the font to the characters. + Returns a serialization of the subset font as file-like object. + + Parameters + ---------- + fontfile : str + Path to the font file + characters : str + Continuous set of characters to include in subset + """ + + options = subset.Options(glyph_names=True, recommended_glyphs=True) + + # Prevent subsetting extra tables. + options.drop_tables += [ + 'FFTM', # FontForge Timestamp. + 'PfEd', # FontForge personal table. + 'BDF', # X11 BDF header. + 'meta', # Metadata stores design/supported languages (meaningless for subsets). + ] + + # if fontfile is a ttc, specify font number + if fontfile.endswith(".ttc"): + options.font_number = 0 + + with subset.load_font(fontfile, options) as font: + subsetter = subset.Subsetter(options=options) + subsetter.populate(text=characters) + subsetter.subset(font) + fh = BytesIO() + font.save(fh, reorderTables=False) + return fh + + +class CharacterTracker: + """ + Helper for font subsetting by the pdf and ps backends. + + Maintains a mapping of font paths to the set of character codepoints that + are being used from that font. + """ + + def __init__(self): + self.used = {} + + def track(self, font, s): + """Record that string *s* is being typeset using font *font*.""" + char_to_font = font._get_fontmap(s) + for _c, _f in char_to_font.items(): + self.used.setdefault(_f.fname, set()).add(ord(_c)) + + def track_glyph(self, font, glyph): + """Record that codepoint *glyph* is being typeset using font *font*.""" + self.used.setdefault(font.fname, set()).add(glyph) + + +class RendererPDFPSBase(RendererBase): + # The following attributes must be defined by the subclasses: + # - _afm_font_dir + # - _use_afm_rc_name + + def __init__(self, width, height): + super().__init__() + self.width = width + self.height = height + + def flipy(self): + # docstring inherited + return False # y increases from bottom to top. + + def option_scale_image(self): + # docstring inherited + return True # PDF and PS support arbitrary image scaling. + + def option_image_nocomposite(self): + # docstring inherited + # Decide whether to composite image based on rcParam value. + return not mpl.rcParams["image.composite_image"] + + def get_canvas_width_height(self): + # docstring inherited + return self.width * 72.0, self.height * 72.0 + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + if ismath == "TeX": + return super().get_text_width_height_descent(s, prop, ismath) + elif ismath: + parse = self._text2path.mathtext_parser.parse(s, 72, prop) + return parse.width, parse.height, parse.depth + elif mpl.rcParams[self._use_afm_rc_name]: + font = self._get_font_afm(prop) + l, b, w, h, d = font.get_str_bbox_and_descent(s) + scale = prop.get_size_in_points() / 1000 + w *= scale + h *= scale + d *= scale + return w, h, d + else: + font = self._get_font_ttf(prop) + font.set_text(s, 0.0, flags=ft2font.LOAD_NO_HINTING) + w, h = font.get_width_height() + d = font.get_descent() + scale = 1 / 64 + w *= scale + h *= scale + d *= scale + return w, h, d + + def _get_font_afm(self, prop): + fname = font_manager.findfont( + prop, fontext="afm", directory=self._afm_font_dir) + return _cached_get_afm_from_fname(fname) + + def _get_font_ttf(self, prop): + fnames = font_manager.fontManager._find_fonts_by_props(prop) + font = font_manager.get_font(fnames) + font.clear() + font.set_size(prop.get_size_in_points(), 72) + return font diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3.py new file mode 100644 index 0000000000000000000000000000000000000000..49d34f5794e43423d45b2e43de96e1b332cf308e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3.py @@ -0,0 +1,582 @@ +import functools +import logging +import os +from pathlib import Path + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook +from matplotlib.backend_bases import ( + ToolContainerBase, CloseEvent, KeyEvent, LocationEvent, MouseEvent, + ResizeEvent) + +try: + import gi +except ImportError as err: + raise ImportError("The GTK3 backends require PyGObject") from err + +try: + # :raises ValueError: If module/version is already loaded, already + # required, or unavailable. + gi.require_version("Gtk", "3.0") +except ValueError as e: + # in this case we want to re-raise as ImportError so the + # auto-backend selection logic correctly skips. + raise ImportError(e) from e + +from gi.repository import Gio, GLib, GObject, Gtk, Gdk +from . import _backend_gtk +from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611 + _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK, + TimerGTK as TimerGTK3, +) + + +_log = logging.getLogger(__name__) + + +@functools.cache +def _mpl_to_gtk_cursor(mpl_cursor): + return Gdk.Cursor.new_from_name( + Gdk.Display.get_default(), + _backend_gtk.mpl_to_gtk_cursor_name(mpl_cursor)) + + +class FigureCanvasGTK3(_FigureCanvasGTK, Gtk.DrawingArea): + required_interactive_framework = "gtk3" + manager_class = _api.classproperty(lambda cls: FigureManagerGTK3) + # Setting this as a static constant prevents + # this resulting expression from leaking + event_mask = (Gdk.EventMask.BUTTON_PRESS_MASK + | Gdk.EventMask.BUTTON_RELEASE_MASK + | Gdk.EventMask.EXPOSURE_MASK + | Gdk.EventMask.KEY_PRESS_MASK + | Gdk.EventMask.KEY_RELEASE_MASK + | Gdk.EventMask.ENTER_NOTIFY_MASK + | Gdk.EventMask.LEAVE_NOTIFY_MASK + | Gdk.EventMask.POINTER_MOTION_MASK + | Gdk.EventMask.SCROLL_MASK) + + def __init__(self, figure=None): + super().__init__(figure=figure) + + self._idle_draw_id = 0 + self._rubberband_rect = None + + self.connect('scroll_event', self.scroll_event) + self.connect('button_press_event', self.button_press_event) + self.connect('button_release_event', self.button_release_event) + self.connect('configure_event', self.configure_event) + self.connect('screen-changed', self._update_device_pixel_ratio) + self.connect('notify::scale-factor', self._update_device_pixel_ratio) + self.connect('draw', self.on_draw_event) + self.connect('draw', self._post_draw) + self.connect('key_press_event', self.key_press_event) + self.connect('key_release_event', self.key_release_event) + self.connect('motion_notify_event', self.motion_notify_event) + self.connect('enter_notify_event', self.enter_notify_event) + self.connect('leave_notify_event', self.leave_notify_event) + self.connect('size_allocate', self.size_allocate) + + self.set_events(self.__class__.event_mask) + + self.set_can_focus(True) + + css = Gtk.CssProvider() + css.load_from_data(b".matplotlib-canvas { background-color: white; }") + style_ctx = self.get_style_context() + style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) + style_ctx.add_class("matplotlib-canvas") + + def destroy(self): + CloseEvent("close_event", self)._process() + + def set_cursor(self, cursor): + # docstring inherited + window = self.get_property("window") + if window is not None: + window.set_cursor(_mpl_to_gtk_cursor(cursor)) + context = GLib.MainContext.default() + context.iteration(True) + + def _mpl_coords(self, event=None): + """ + Convert the position of a GTK event, or of the current cursor position + if *event* is None, to Matplotlib coordinates. + + GTK use logical pixels, but the figure is scaled to physical pixels for + rendering. Transform to physical pixels so that all of the down-stream + transforms work as expected. + + Also, the origin is different and needs to be corrected. + """ + if event is None: + window = self.get_window() + t, x, y, state = window.get_device_position( + window.get_display().get_device_manager().get_client_pointer()) + else: + x, y = event.x, event.y + x = x * self.device_pixel_ratio + # flip y so y=0 is bottom of canvas + y = self.figure.bbox.height - y * self.device_pixel_ratio + return x, y + + def scroll_event(self, widget, event): + step = 1 if event.direction == Gdk.ScrollDirection.UP else -1 + MouseEvent("scroll_event", self, + *self._mpl_coords(event), step=step, + modifiers=self._mpl_modifiers(event.state), + guiEvent=event)._process() + return False # finish event propagation? + + def button_press_event(self, widget, event): + MouseEvent("button_press_event", self, + *self._mpl_coords(event), event.button, + modifiers=self._mpl_modifiers(event.state), + guiEvent=event)._process() + return False # finish event propagation? + + def button_release_event(self, widget, event): + MouseEvent("button_release_event", self, + *self._mpl_coords(event), event.button, + modifiers=self._mpl_modifiers(event.state), + guiEvent=event)._process() + return False # finish event propagation? + + def key_press_event(self, widget, event): + KeyEvent("key_press_event", self, + self._get_key(event), *self._mpl_coords(), + guiEvent=event)._process() + return True # stop event propagation + + def key_release_event(self, widget, event): + KeyEvent("key_release_event", self, + self._get_key(event), *self._mpl_coords(), + guiEvent=event)._process() + return True # stop event propagation + + def motion_notify_event(self, widget, event): + MouseEvent("motion_notify_event", self, *self._mpl_coords(event), + modifiers=self._mpl_modifiers(event.state), + guiEvent=event)._process() + return False # finish event propagation? + + def enter_notify_event(self, widget, event): + gtk_mods = Gdk.Keymap.get_for_display( + self.get_display()).get_modifier_state() + LocationEvent("figure_enter_event", self, *self._mpl_coords(event), + modifiers=self._mpl_modifiers(gtk_mods), + guiEvent=event)._process() + + def leave_notify_event(self, widget, event): + gtk_mods = Gdk.Keymap.get_for_display( + self.get_display()).get_modifier_state() + LocationEvent("figure_leave_event", self, *self._mpl_coords(event), + modifiers=self._mpl_modifiers(gtk_mods), + guiEvent=event)._process() + + def size_allocate(self, widget, allocation): + dpival = self.figure.dpi + winch = allocation.width * self.device_pixel_ratio / dpival + hinch = allocation.height * self.device_pixel_ratio / dpival + self.figure.set_size_inches(winch, hinch, forward=False) + ResizeEvent("resize_event", self)._process() + self.draw_idle() + + @staticmethod + def _mpl_modifiers(event_state, *, exclude=None): + modifiers = [ + ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"), + ("alt", Gdk.ModifierType.MOD1_MASK, "alt"), + ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"), + ("super", Gdk.ModifierType.MOD4_MASK, "super"), + ] + return [name for name, mask, key in modifiers + if exclude != key and event_state & mask] + + def _get_key(self, event): + unikey = chr(Gdk.keyval_to_unicode(event.keyval)) + key = cbook._unikey_or_keysym_to_mplkey( + unikey, Gdk.keyval_name(event.keyval)) + mods = self._mpl_modifiers(event.state, exclude=key) + if "shift" in mods and unikey.isprintable(): + mods.remove("shift") + return "+".join([*mods, key]) + + def _update_device_pixel_ratio(self, *args, **kwargs): + # We need to be careful in cases with mixed resolution displays if + # device_pixel_ratio changes. + if self._set_device_pixel_ratio(self.get_scale_factor()): + # The easiest way to resize the canvas is to emit a resize event + # since we implement all the logic for resizing the canvas for that + # event. + self.queue_resize() + self.queue_draw() + + def configure_event(self, widget, event): + if widget.get_property("window") is None: + return + w = event.width * self.device_pixel_ratio + h = event.height * self.device_pixel_ratio + if w < 3 or h < 3: + return # empty fig + # resize the figure (in inches) + dpi = self.figure.dpi + self.figure.set_size_inches(w / dpi, h / dpi, forward=False) + return False # finish event propagation? + + def _draw_rubberband(self, rect): + self._rubberband_rect = rect + # TODO: Only update the rubberband area. + self.queue_draw() + + def _post_draw(self, widget, ctx): + if self._rubberband_rect is None: + return + + x0, y0, w, h = (dim / self.device_pixel_ratio + for dim in self._rubberband_rect) + x1 = x0 + w + y1 = y0 + h + + # Draw the lines from x0, y0 towards x1, y1 so that the + # dashes don't "jump" when moving the zoom box. + ctx.move_to(x0, y0) + ctx.line_to(x0, y1) + ctx.move_to(x0, y0) + ctx.line_to(x1, y0) + ctx.move_to(x0, y1) + ctx.line_to(x1, y1) + ctx.move_to(x1, y0) + ctx.line_to(x1, y1) + + ctx.set_antialias(1) + ctx.set_line_width(1) + ctx.set_dash((3, 3), 0) + ctx.set_source_rgb(0, 0, 0) + ctx.stroke_preserve() + + ctx.set_dash((3, 3), 3) + ctx.set_source_rgb(1, 1, 1) + ctx.stroke() + + def on_draw_event(self, widget, ctx): + # to be overwritten by GTK3Agg or GTK3Cairo + pass + + def draw(self): + # docstring inherited + if self.is_drawable(): + self.queue_draw() + + def draw_idle(self): + # docstring inherited + if self._idle_draw_id != 0: + return + def idle_draw(*args): + try: + self.draw() + finally: + self._idle_draw_id = 0 + return False + self._idle_draw_id = GLib.idle_add(idle_draw) + + def flush_events(self): + # docstring inherited + context = GLib.MainContext.default() + while context.pending(): + context.iteration(True) + + +class NavigationToolbar2GTK3(_NavigationToolbar2GTK, Gtk.Toolbar): + def __init__(self, canvas): + GObject.GObject.__init__(self) + + self.set_style(Gtk.ToolbarStyle.ICONS) + + self._gtk_ids = {} + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + self.insert(Gtk.SeparatorToolItem(), -1) + continue + image = Gtk.Image.new_from_gicon( + Gio.Icon.new_for_string( + str(cbook._get_data_path('images', + f'{image_file}-symbolic.svg'))), + Gtk.IconSize.LARGE_TOOLBAR) + self._gtk_ids[text] = button = ( + Gtk.ToggleToolButton() if callback in ['zoom', 'pan'] else + Gtk.ToolButton()) + button.set_label(text) + button.set_icon_widget(image) + # Save the handler id, so that we can block it as needed. + button._signal_handler = button.connect( + 'clicked', getattr(self, callback)) + button.set_tooltip_text(tooltip_text) + self.insert(button, -1) + + # This filler item ensures the toolbar is always at least two text + # lines high. Otherwise the canvas gets redrawn as the mouse hovers + # over images because those use two-line messages which resize the + # toolbar. + toolitem = Gtk.ToolItem() + self.insert(toolitem, -1) + label = Gtk.Label() + label.set_markup( + '\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}') + toolitem.set_expand(True) # Push real message to the right. + toolitem.add(label) + + toolitem = Gtk.ToolItem() + self.insert(toolitem, -1) + self.message = Gtk.Label() + self.message.set_justify(Gtk.Justification.RIGHT) + toolitem.add(self.message) + + self.show_all() + + _NavigationToolbar2GTK.__init__(self, canvas) + + def save_figure(self, *args): + dialog = Gtk.FileChooserDialog( + title="Save the figure", + parent=self.canvas.get_toplevel(), + action=Gtk.FileChooserAction.SAVE, + buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, + Gtk.STOCK_SAVE, Gtk.ResponseType.OK), + ) + for name, fmts \ + in self.canvas.get_supported_filetypes_grouped().items(): + ff = Gtk.FileFilter() + ff.set_name(name) + for fmt in fmts: + ff.add_pattern(f'*.{fmt}') + dialog.add_filter(ff) + if self.canvas.get_default_filetype() in fmts: + dialog.set_filter(ff) + + @functools.partial(dialog.connect, "notify::filter") + def on_notify_filter(*args): + name = dialog.get_filter().get_name() + fmt = self.canvas.get_supported_filetypes_grouped()[name][0] + dialog.set_current_name( + str(Path(dialog.get_current_name()).with_suffix(f'.{fmt}'))) + + dialog.set_current_folder(mpl.rcParams["savefig.directory"]) + dialog.set_current_name(self.canvas.get_default_filename()) + dialog.set_do_overwrite_confirmation(True) + + response = dialog.run() + fname = dialog.get_filename() + ff = dialog.get_filter() # Doesn't autoadjust to filename :/ + fmt = self.canvas.get_supported_filetypes_grouped()[ff.get_name()][0] + dialog.destroy() + if response != Gtk.ResponseType.OK: + return + # Save dir for next time, unless empty str (which means use cwd). + if mpl.rcParams['savefig.directory']: + mpl.rcParams['savefig.directory'] = os.path.dirname(fname) + try: + self.canvas.figure.savefig(fname, format=fmt) + except Exception as e: + dialog = Gtk.MessageDialog( + parent=self.canvas.get_toplevel(), message_format=str(e), + type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK) + dialog.run() + dialog.destroy() + + +class ToolbarGTK3(ToolContainerBase, Gtk.Box): + _icon_extension = '-symbolic.svg' + + def __init__(self, toolmanager): + ToolContainerBase.__init__(self, toolmanager) + Gtk.Box.__init__(self) + self.set_property('orientation', Gtk.Orientation.HORIZONTAL) + self._message = Gtk.Label() + self._message.set_justify(Gtk.Justification.RIGHT) + self.pack_end(self._message, False, False, 0) + self.show_all() + self._groups = {} + self._toolitems = {} + + def add_toolitem(self, name, group, position, image_file, description, + toggle): + if toggle: + button = Gtk.ToggleToolButton() + else: + button = Gtk.ToolButton() + button.set_label(name) + + if image_file is not None: + image = Gtk.Image.new_from_gicon( + Gio.Icon.new_for_string(image_file), + Gtk.IconSize.LARGE_TOOLBAR) + button.set_icon_widget(image) + + if position is None: + position = -1 + + self._add_button(button, group, position) + signal = button.connect('clicked', self._call_tool, name) + button.set_tooltip_text(description) + button.show_all() + self._toolitems.setdefault(name, []) + self._toolitems[name].append((button, signal)) + + def _add_button(self, button, group, position): + if group not in self._groups: + if self._groups: + self._add_separator() + toolbar = Gtk.Toolbar() + toolbar.set_style(Gtk.ToolbarStyle.ICONS) + self.pack_start(toolbar, False, False, 0) + toolbar.show_all() + self._groups[group] = toolbar + self._groups[group].insert(button, position) + + def _call_tool(self, btn, name): + self.trigger_tool(name) + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for toolitem, signal in self._toolitems[name]: + toolitem.handler_block(signal) + toolitem.set_active(toggled) + toolitem.handler_unblock(signal) + + def remove_toolitem(self, name): + for toolitem, _signal in self._toolitems.pop(name, []): + for group in self._groups: + if toolitem in self._groups[group]: + self._groups[group].remove(toolitem) + + def _add_separator(self): + sep = Gtk.Separator() + sep.set_property("orientation", Gtk.Orientation.VERTICAL) + self.pack_start(sep, False, True, 0) + sep.show_all() + + def set_message(self, s): + self._message.set_label(s) + + +@backend_tools._register_tool_class(FigureCanvasGTK3) +class SaveFigureGTK3(backend_tools.SaveFigureBase): + def trigger(self, *args, **kwargs): + NavigationToolbar2GTK3.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasGTK3) +class HelpGTK3(backend_tools.ToolHelpBase): + def _normalize_shortcut(self, key): + """ + Convert Matplotlib key presses to GTK+ accelerator identifiers. + + Related to `FigureCanvasGTK3._get_key`. + """ + special = { + 'backspace': 'BackSpace', + 'pagedown': 'Page_Down', + 'pageup': 'Page_Up', + 'scroll_lock': 'Scroll_Lock', + } + + parts = key.split('+') + mods = ['<' + mod + '>' for mod in parts[:-1]] + key = parts[-1] + + if key in special: + key = special[key] + elif len(key) > 1: + key = key.capitalize() + elif key.isupper(): + mods += [''] + + return ''.join(mods) + key + + def _is_valid_shortcut(self, key): + """ + Check for a valid shortcut to be displayed. + + - GTK will never send 'cmd+' (see `FigureCanvasGTK3._get_key`). + - The shortcut window only shows keyboard shortcuts, not mouse buttons. + """ + return 'cmd+' not in key and not key.startswith('MouseButton.') + + def _show_shortcuts_window(self): + section = Gtk.ShortcutsSection() + + for name, tool in sorted(self.toolmanager.tools.items()): + if not tool.description: + continue + + # Putting everything in a separate group allows GTK to + # automatically split them into separate columns/pages, which is + # useful because we have lots of shortcuts, some with many keys + # that are very wide. + group = Gtk.ShortcutsGroup() + section.add(group) + # A hack to remove the title since we have no group naming. + group.forall(lambda widget, data: widget.set_visible(False), None) + + shortcut = Gtk.ShortcutsShortcut( + accelerator=' '.join( + self._normalize_shortcut(key) + for key in self.toolmanager.get_tool_keymap(name) + if self._is_valid_shortcut(key)), + title=tool.name, + subtitle=tool.description) + group.add(shortcut) + + window = Gtk.ShortcutsWindow( + title='Help', + modal=True, + transient_for=self._figure.canvas.get_toplevel()) + section.show() # Must be done explicitly before add! + window.add(section) + + window.show_all() + + def _show_shortcuts_dialog(self): + dialog = Gtk.MessageDialog( + self._figure.canvas.get_toplevel(), + 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, self._get_help_text(), + title="Help") + dialog.run() + dialog.destroy() + + def trigger(self, *args): + if Gtk.check_version(3, 20, 0) is None: + self._show_shortcuts_window() + else: + self._show_shortcuts_dialog() + + +@backend_tools._register_tool_class(FigureCanvasGTK3) +class ToolCopyToClipboardGTK3(backend_tools.ToolCopyToClipboardBase): + def trigger(self, *args, **kwargs): + clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) + window = self.canvas.get_window() + x, y, width, height = window.get_geometry() + pb = Gdk.pixbuf_get_from_window(window, x, y, width, height) + clipboard.set_image(pb) + + +Toolbar = ToolbarGTK3 +backend_tools._register_tool_class( + FigureCanvasGTK3, _backend_gtk.ConfigureSubplotsGTK) +backend_tools._register_tool_class( + FigureCanvasGTK3, _backend_gtk.RubberbandGTK) + + +class FigureManagerGTK3(_FigureManagerGTK): + _toolbar2_class = NavigationToolbar2GTK3 + _toolmanager_toolbar_class = ToolbarGTK3 + + +@_BackendGTK.export +class _BackendGTK3(_BackendGTK): + FigureCanvas = FigureCanvasGTK3 + FigureManager = FigureManagerGTK3 diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3agg.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3agg.py new file mode 100644 index 0000000000000000000000000000000000000000..90b38ffa4ec3d2f6195a178c8b177a4d13448f1e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3agg.py @@ -0,0 +1,74 @@ +import numpy as np + +from .. import cbook, transforms +from . import backend_agg, backend_gtk3 +from .backend_gtk3 import GLib, Gtk, _BackendGTK3 + +import cairo # Presence of cairo is already checked by _backend_gtk. + + +class FigureCanvasGTK3Agg(backend_agg.FigureCanvasAgg, + backend_gtk3.FigureCanvasGTK3): + def __init__(self, figure): + super().__init__(figure=figure) + self._bbox_queue = [] + + def on_draw_event(self, widget, ctx): + if self._idle_draw_id: + GLib.source_remove(self._idle_draw_id) + self._idle_draw_id = 0 + self.draw() + + scale = self.device_pixel_ratio + allocation = self.get_allocation() + w = allocation.width * scale + h = allocation.height * scale + + if not len(self._bbox_queue): + Gtk.render_background( + self.get_style_context(), ctx, + allocation.x, allocation.y, + allocation.width, allocation.height) + bbox_queue = [transforms.Bbox([[0, 0], [w, h]])] + else: + bbox_queue = self._bbox_queue + + for bbox in bbox_queue: + x = int(bbox.x0) + y = h - int(bbox.y1) + width = int(bbox.x1) - int(bbox.x0) + height = int(bbox.y1) - int(bbox.y0) + + buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32( + np.asarray(self.copy_from_bbox(bbox))) + image = cairo.ImageSurface.create_for_data( + buf.ravel().data, cairo.FORMAT_ARGB32, width, height) + image.set_device_scale(scale, scale) + ctx.set_source_surface(image, x / scale, y / scale) + ctx.paint() + + if len(self._bbox_queue): + self._bbox_queue = [] + + return False + + def blit(self, bbox=None): + # If bbox is None, blit the entire canvas to gtk. Otherwise + # blit only the area defined by the bbox. + if bbox is None: + bbox = self.figure.bbox + + scale = self.device_pixel_ratio + allocation = self.get_allocation() + x = int(bbox.x0 / scale) + y = allocation.height - int(bbox.y1 / scale) + width = (int(bbox.x1) - int(bbox.x0)) // scale + height = (int(bbox.y1) - int(bbox.y0)) // scale + + self._bbox_queue.append(bbox) + self.queue_draw_area(x, y, width, height) + + +@_BackendGTK3.export +class _BackendGTK3Cairo(_BackendGTK3): + FigureCanvas = FigureCanvasGTK3Agg diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3cairo.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3cairo.py new file mode 100644 index 0000000000000000000000000000000000000000..371b8dc1b31fb96dd823eeed65592d1692d5b8f2 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3cairo.py @@ -0,0 +1,35 @@ +from contextlib import nullcontext + +from .backend_cairo import FigureCanvasCairo +from .backend_gtk3 import GLib, Gtk, FigureCanvasGTK3, _BackendGTK3 + + +class FigureCanvasGTK3Cairo(FigureCanvasCairo, FigureCanvasGTK3): + def on_draw_event(self, widget, ctx): + if self._idle_draw_id: + GLib.source_remove(self._idle_draw_id) + self._idle_draw_id = 0 + self.draw() + + with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar + else nullcontext()): + allocation = self.get_allocation() + # Render the background before scaling, as the allocated size here is in + # logical pixels. + Gtk.render_background( + self.get_style_context(), ctx, + 0, 0, allocation.width, allocation.height) + scale = self.device_pixel_ratio + # Scale physical drawing to logical size. + ctx.scale(1 / scale, 1 / scale) + self._renderer.set_context(ctx) + # Set renderer to physical size so it renders in full resolution. + self._renderer.width = allocation.width * scale + self._renderer.height = allocation.height * scale + self._renderer.dpi = self.figure.dpi + self.figure.draw(self._renderer) + + +@_BackendGTK3.export +class _BackendGTK3Cairo(_BackendGTK3): + FigureCanvas = FigureCanvasGTK3Cairo diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4.py new file mode 100644 index 0000000000000000000000000000000000000000..dd86ab628ce73ff583841172a3f6ade376868e68 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4.py @@ -0,0 +1,595 @@ +import functools +import io +import os + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook +from matplotlib.backend_bases import ( + ToolContainerBase, KeyEvent, LocationEvent, MouseEvent, ResizeEvent, + CloseEvent) + +try: + import gi +except ImportError as err: + raise ImportError("The GTK4 backends require PyGObject") from err + +try: + # :raises ValueError: If module/version is already loaded, already + # required, or unavailable. + gi.require_version("Gtk", "4.0") +except ValueError as e: + # in this case we want to re-raise as ImportError so the + # auto-backend selection logic correctly skips. + raise ImportError(e) from e + +from gi.repository import Gio, GLib, Gtk, Gdk, GdkPixbuf +from . import _backend_gtk +from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611 + _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK, + TimerGTK as TimerGTK4, +) + + +class FigureCanvasGTK4(_FigureCanvasGTK, Gtk.DrawingArea): + required_interactive_framework = "gtk4" + supports_blit = False + manager_class = _api.classproperty(lambda cls: FigureManagerGTK4) + + def __init__(self, figure=None): + super().__init__(figure=figure) + + self.set_hexpand(True) + self.set_vexpand(True) + + self._idle_draw_id = 0 + self._rubberband_rect = None + + self.set_draw_func(self._draw_func) + self.connect('resize', self.resize_event) + self.connect('notify::scale-factor', self._update_device_pixel_ratio) + + click = Gtk.GestureClick() + click.set_button(0) # All buttons. + click.connect('pressed', self.button_press_event) + click.connect('released', self.button_release_event) + self.add_controller(click) + + key = Gtk.EventControllerKey() + key.connect('key-pressed', self.key_press_event) + key.connect('key-released', self.key_release_event) + self.add_controller(key) + + motion = Gtk.EventControllerMotion() + motion.connect('motion', self.motion_notify_event) + motion.connect('enter', self.enter_notify_event) + motion.connect('leave', self.leave_notify_event) + self.add_controller(motion) + + scroll = Gtk.EventControllerScroll.new( + Gtk.EventControllerScrollFlags.VERTICAL) + scroll.connect('scroll', self.scroll_event) + self.add_controller(scroll) + + self.set_focusable(True) + + css = Gtk.CssProvider() + style = '.matplotlib-canvas { background-color: white; }' + if Gtk.check_version(4, 9, 3) is None: + css.load_from_data(style, -1) + else: + css.load_from_data(style.encode('utf-8')) + style_ctx = self.get_style_context() + style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) + style_ctx.add_class("matplotlib-canvas") + + def destroy(self): + CloseEvent("close_event", self)._process() + + def set_cursor(self, cursor): + # docstring inherited + self.set_cursor_from_name(_backend_gtk.mpl_to_gtk_cursor_name(cursor)) + + def _mpl_coords(self, xy=None): + """ + Convert the *xy* position of a GTK event, or of the current cursor + position if *xy* is None, to Matplotlib coordinates. + + GTK use logical pixels, but the figure is scaled to physical pixels for + rendering. Transform to physical pixels so that all of the down-stream + transforms work as expected. + + Also, the origin is different and needs to be corrected. + """ + if xy is None: + surface = self.get_native().get_surface() + is_over, x, y, mask = surface.get_device_position( + self.get_display().get_default_seat().get_pointer()) + else: + x, y = xy + x = x * self.device_pixel_ratio + # flip y so y=0 is bottom of canvas + y = self.figure.bbox.height - y * self.device_pixel_ratio + return x, y + + def scroll_event(self, controller, dx, dy): + MouseEvent( + "scroll_event", self, *self._mpl_coords(), step=dy, + modifiers=self._mpl_modifiers(controller), + )._process() + return True + + def button_press_event(self, controller, n_press, x, y): + MouseEvent( + "button_press_event", self, *self._mpl_coords((x, y)), + controller.get_current_button(), + modifiers=self._mpl_modifiers(controller), + )._process() + self.grab_focus() + + def button_release_event(self, controller, n_press, x, y): + MouseEvent( + "button_release_event", self, *self._mpl_coords((x, y)), + controller.get_current_button(), + modifiers=self._mpl_modifiers(controller), + )._process() + + def key_press_event(self, controller, keyval, keycode, state): + KeyEvent( + "key_press_event", self, self._get_key(keyval, keycode, state), + *self._mpl_coords(), + )._process() + return True + + def key_release_event(self, controller, keyval, keycode, state): + KeyEvent( + "key_release_event", self, self._get_key(keyval, keycode, state), + *self._mpl_coords(), + )._process() + return True + + def motion_notify_event(self, controller, x, y): + MouseEvent( + "motion_notify_event", self, *self._mpl_coords((x, y)), + modifiers=self._mpl_modifiers(controller), + )._process() + + def enter_notify_event(self, controller, x, y): + LocationEvent( + "figure_enter_event", self, *self._mpl_coords((x, y)), + modifiers=self._mpl_modifiers(), + )._process() + + def leave_notify_event(self, controller): + LocationEvent( + "figure_leave_event", self, *self._mpl_coords(), + modifiers=self._mpl_modifiers(), + )._process() + + def resize_event(self, area, width, height): + self._update_device_pixel_ratio() + dpi = self.figure.dpi + winch = width * self.device_pixel_ratio / dpi + hinch = height * self.device_pixel_ratio / dpi + self.figure.set_size_inches(winch, hinch, forward=False) + ResizeEvent("resize_event", self)._process() + self.draw_idle() + + def _mpl_modifiers(self, controller=None): + if controller is None: + surface = self.get_native().get_surface() + is_over, x, y, event_state = surface.get_device_position( + self.get_display().get_default_seat().get_pointer()) + else: + event_state = controller.get_current_event_state() + mod_table = [ + ("ctrl", Gdk.ModifierType.CONTROL_MASK), + ("alt", Gdk.ModifierType.ALT_MASK), + ("shift", Gdk.ModifierType.SHIFT_MASK), + ("super", Gdk.ModifierType.SUPER_MASK), + ] + return [name for name, mask in mod_table if event_state & mask] + + def _get_key(self, keyval, keycode, state): + unikey = chr(Gdk.keyval_to_unicode(keyval)) + key = cbook._unikey_or_keysym_to_mplkey( + unikey, + Gdk.keyval_name(keyval)) + modifiers = [ + ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"), + ("alt", Gdk.ModifierType.ALT_MASK, "alt"), + ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"), + ("super", Gdk.ModifierType.SUPER_MASK, "super"), + ] + mods = [ + mod for mod, mask, mod_key in modifiers + if (mod_key != key and state & mask + and not (mod == "shift" and unikey.isprintable()))] + return "+".join([*mods, key]) + + def _update_device_pixel_ratio(self, *args, **kwargs): + # We need to be careful in cases with mixed resolution displays if + # device_pixel_ratio changes. + if self._set_device_pixel_ratio(self.get_scale_factor()): + self.draw() + + def _draw_rubberband(self, rect): + self._rubberband_rect = rect + # TODO: Only update the rubberband area. + self.queue_draw() + + def _draw_func(self, drawing_area, ctx, width, height): + self.on_draw_event(self, ctx) + self._post_draw(self, ctx) + + def _post_draw(self, widget, ctx): + if self._rubberband_rect is None: + return + + lw = 1 + dash = 3 + x0, y0, w, h = (dim / self.device_pixel_ratio + for dim in self._rubberband_rect) + x1 = x0 + w + y1 = y0 + h + + # Draw the lines from x0, y0 towards x1, y1 so that the + # dashes don't "jump" when moving the zoom box. + ctx.move_to(x0, y0) + ctx.line_to(x0, y1) + ctx.move_to(x0, y0) + ctx.line_to(x1, y0) + ctx.move_to(x0, y1) + ctx.line_to(x1, y1) + ctx.move_to(x1, y0) + ctx.line_to(x1, y1) + + ctx.set_antialias(1) + ctx.set_line_width(lw) + ctx.set_dash((dash, dash), 0) + ctx.set_source_rgb(0, 0, 0) + ctx.stroke_preserve() + + ctx.set_dash((dash, dash), dash) + ctx.set_source_rgb(1, 1, 1) + ctx.stroke() + + def on_draw_event(self, widget, ctx): + # to be overwritten by GTK4Agg or GTK4Cairo + pass + + def draw(self): + # docstring inherited + if self.is_drawable(): + self.queue_draw() + + def draw_idle(self): + # docstring inherited + if self._idle_draw_id != 0: + return + def idle_draw(*args): + try: + self.draw() + finally: + self._idle_draw_id = 0 + return False + self._idle_draw_id = GLib.idle_add(idle_draw) + + def flush_events(self): + # docstring inherited + context = GLib.MainContext.default() + while context.pending(): + context.iteration(True) + + +class NavigationToolbar2GTK4(_NavigationToolbar2GTK, Gtk.Box): + def __init__(self, canvas): + Gtk.Box.__init__(self) + + self.add_css_class('toolbar') + + self._gtk_ids = {} + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + self.append(Gtk.Separator()) + continue + image = Gtk.Image.new_from_gicon( + Gio.Icon.new_for_string( + str(cbook._get_data_path('images', + f'{image_file}-symbolic.svg')))) + self._gtk_ids[text] = button = ( + Gtk.ToggleButton() if callback in ['zoom', 'pan'] else + Gtk.Button()) + button.set_child(image) + button.add_css_class('flat') + button.add_css_class('image-button') + # Save the handler id, so that we can block it as needed. + button._signal_handler = button.connect( + 'clicked', getattr(self, callback)) + button.set_tooltip_text(tooltip_text) + self.append(button) + + # This filler item ensures the toolbar is always at least two text + # lines high. Otherwise the canvas gets redrawn as the mouse hovers + # over images because those use two-line messages which resize the + # toolbar. + label = Gtk.Label() + label.set_markup( + '\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}') + label.set_hexpand(True) # Push real message to the right. + self.append(label) + + self.message = Gtk.Label() + self.message.set_justify(Gtk.Justification.RIGHT) + self.append(self.message) + + _NavigationToolbar2GTK.__init__(self, canvas) + + def save_figure(self, *args): + dialog = Gtk.FileChooserNative( + title='Save the figure', + transient_for=self.canvas.get_root(), + action=Gtk.FileChooserAction.SAVE, + modal=True) + self._save_dialog = dialog # Must keep a reference. + + ff = Gtk.FileFilter() + ff.set_name('All files') + ff.add_pattern('*') + dialog.add_filter(ff) + dialog.set_filter(ff) + + formats = [] + default_format = None + for i, (name, fmts) in enumerate( + self.canvas.get_supported_filetypes_grouped().items()): + ff = Gtk.FileFilter() + ff.set_name(name) + for fmt in fmts: + ff.add_pattern(f'*.{fmt}') + dialog.add_filter(ff) + formats.append(name) + if self.canvas.get_default_filetype() in fmts: + default_format = i + # Setting the choice doesn't always work, so make sure the default + # format is first. + formats = [formats[default_format], *formats[:default_format], + *formats[default_format+1:]] + dialog.add_choice('format', 'File format', formats, formats) + dialog.set_choice('format', formats[0]) + + dialog.set_current_folder(Gio.File.new_for_path( + os.path.expanduser(mpl.rcParams['savefig.directory']))) + dialog.set_current_name(self.canvas.get_default_filename()) + + @functools.partial(dialog.connect, 'response') + def on_response(dialog, response): + file = dialog.get_file() + fmt = dialog.get_choice('format') + fmt = self.canvas.get_supported_filetypes_grouped()[fmt][0] + dialog.destroy() + self._save_dialog = None + if response != Gtk.ResponseType.ACCEPT: + return + # Save dir for next time, unless empty str (which means use cwd). + if mpl.rcParams['savefig.directory']: + parent = file.get_parent() + mpl.rcParams['savefig.directory'] = parent.get_path() + try: + self.canvas.figure.savefig(file.get_path(), format=fmt) + except Exception as e: + msg = Gtk.MessageDialog( + transient_for=self.canvas.get_root(), + message_type=Gtk.MessageType.ERROR, + buttons=Gtk.ButtonsType.OK, modal=True, + text=str(e)) + msg.show() + + dialog.show() + + +class ToolbarGTK4(ToolContainerBase, Gtk.Box): + _icon_extension = '-symbolic.svg' + + def __init__(self, toolmanager): + ToolContainerBase.__init__(self, toolmanager) + Gtk.Box.__init__(self) + self.set_property('orientation', Gtk.Orientation.HORIZONTAL) + + # Tool items are created later, but must appear before the message. + self._tool_box = Gtk.Box() + self.append(self._tool_box) + self._groups = {} + self._toolitems = {} + + # This filler item ensures the toolbar is always at least two text + # lines high. Otherwise the canvas gets redrawn as the mouse hovers + # over images because those use two-line messages which resize the + # toolbar. + label = Gtk.Label() + label.set_markup( + '\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}') + label.set_hexpand(True) # Push real message to the right. + self.append(label) + + self._message = Gtk.Label() + self._message.set_justify(Gtk.Justification.RIGHT) + self.append(self._message) + + def add_toolitem(self, name, group, position, image_file, description, + toggle): + if toggle: + button = Gtk.ToggleButton() + else: + button = Gtk.Button() + button.set_label(name) + button.add_css_class('flat') + + if image_file is not None: + image = Gtk.Image.new_from_gicon( + Gio.Icon.new_for_string(image_file)) + button.set_child(image) + button.add_css_class('image-button') + + if position is None: + position = -1 + + self._add_button(button, group, position) + signal = button.connect('clicked', self._call_tool, name) + button.set_tooltip_text(description) + self._toolitems.setdefault(name, []) + self._toolitems[name].append((button, signal)) + + def _find_child_at_position(self, group, position): + children = [None] + child = self._groups[group].get_first_child() + while child is not None: + children.append(child) + child = child.get_next_sibling() + return children[position] + + def _add_button(self, button, group, position): + if group not in self._groups: + if self._groups: + self._add_separator() + group_box = Gtk.Box() + self._tool_box.append(group_box) + self._groups[group] = group_box + self._groups[group].insert_child_after( + button, self._find_child_at_position(group, position)) + + def _call_tool(self, btn, name): + self.trigger_tool(name) + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for toolitem, signal in self._toolitems[name]: + toolitem.handler_block(signal) + toolitem.set_active(toggled) + toolitem.handler_unblock(signal) + + def remove_toolitem(self, name): + for toolitem, _signal in self._toolitems.pop(name, []): + for group in self._groups: + if toolitem in self._groups[group]: + self._groups[group].remove(toolitem) + + def _add_separator(self): + sep = Gtk.Separator() + sep.set_property("orientation", Gtk.Orientation.VERTICAL) + self._tool_box.append(sep) + + def set_message(self, s): + self._message.set_label(s) + + +@backend_tools._register_tool_class(FigureCanvasGTK4) +class SaveFigureGTK4(backend_tools.SaveFigureBase): + def trigger(self, *args, **kwargs): + NavigationToolbar2GTK4.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasGTK4) +class HelpGTK4(backend_tools.ToolHelpBase): + def _normalize_shortcut(self, key): + """ + Convert Matplotlib key presses to GTK+ accelerator identifiers. + + Related to `FigureCanvasGTK4._get_key`. + """ + special = { + 'backspace': 'BackSpace', + 'pagedown': 'Page_Down', + 'pageup': 'Page_Up', + 'scroll_lock': 'Scroll_Lock', + } + + parts = key.split('+') + mods = ['<' + mod + '>' for mod in parts[:-1]] + key = parts[-1] + + if key in special: + key = special[key] + elif len(key) > 1: + key = key.capitalize() + elif key.isupper(): + mods += [''] + + return ''.join(mods) + key + + def _is_valid_shortcut(self, key): + """ + Check for a valid shortcut to be displayed. + + - GTK will never send 'cmd+' (see `FigureCanvasGTK4._get_key`). + - The shortcut window only shows keyboard shortcuts, not mouse buttons. + """ + return 'cmd+' not in key and not key.startswith('MouseButton.') + + def trigger(self, *args): + section = Gtk.ShortcutsSection() + + for name, tool in sorted(self.toolmanager.tools.items()): + if not tool.description: + continue + + # Putting everything in a separate group allows GTK to + # automatically split them into separate columns/pages, which is + # useful because we have lots of shortcuts, some with many keys + # that are very wide. + group = Gtk.ShortcutsGroup() + section.append(group) + # A hack to remove the title since we have no group naming. + child = group.get_first_child() + while child is not None: + child.set_visible(False) + child = child.get_next_sibling() + + shortcut = Gtk.ShortcutsShortcut( + accelerator=' '.join( + self._normalize_shortcut(key) + for key in self.toolmanager.get_tool_keymap(name) + if self._is_valid_shortcut(key)), + title=tool.name, + subtitle=tool.description) + group.append(shortcut) + + window = Gtk.ShortcutsWindow( + title='Help', + modal=True, + transient_for=self._figure.canvas.get_root()) + window.set_child(section) + + window.show() + + +@backend_tools._register_tool_class(FigureCanvasGTK4) +class ToolCopyToClipboardGTK4(backend_tools.ToolCopyToClipboardBase): + def trigger(self, *args, **kwargs): + with io.BytesIO() as f: + self.canvas.print_rgba(f) + w, h = self.canvas.get_width_height() + pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(), + GdkPixbuf.Colorspace.RGB, True, + 8, w, h, w*4) + clipboard = self.canvas.get_clipboard() + clipboard.set(pb) + + +backend_tools._register_tool_class( + FigureCanvasGTK4, _backend_gtk.ConfigureSubplotsGTK) +backend_tools._register_tool_class( + FigureCanvasGTK4, _backend_gtk.RubberbandGTK) +Toolbar = ToolbarGTK4 + + +class FigureManagerGTK4(_FigureManagerGTK): + _toolbar2_class = NavigationToolbar2GTK4 + _toolmanager_toolbar_class = ToolbarGTK4 + + +@_BackendGTK.export +class _BackendGTK4(_BackendGTK): + FigureCanvas = FigureCanvasGTK4 + FigureManager = FigureManagerGTK4 diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4cairo.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4cairo.py new file mode 100644 index 0000000000000000000000000000000000000000..838ea03fcce6b4aec68de3baf876b876a1085803 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4cairo.py @@ -0,0 +1,32 @@ +from contextlib import nullcontext + +from .backend_cairo import FigureCanvasCairo +from .backend_gtk4 import GLib, Gtk, FigureCanvasGTK4, _BackendGTK4 + + +class FigureCanvasGTK4Cairo(FigureCanvasCairo, FigureCanvasGTK4): + def _set_device_pixel_ratio(self, ratio): + # Cairo in GTK4 always uses logical pixels, so we don't need to do anything for + # changes to the device pixel ratio. + return False + + def on_draw_event(self, widget, ctx): + if self._idle_draw_id: + GLib.source_remove(self._idle_draw_id) + self._idle_draw_id = 0 + self.draw() + + with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar + else nullcontext()): + self._renderer.set_context(ctx) + allocation = self.get_allocation() + Gtk.render_background( + self.get_style_context(), ctx, + allocation.x, allocation.y, + allocation.width, allocation.height) + self.figure.draw(self._renderer) + + +@_BackendGTK4.export +class _BackendGTK4Cairo(_BackendGTK4): + FigureCanvas = FigureCanvasGTK4Cairo diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_mixed.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_mixed.py new file mode 100644 index 0000000000000000000000000000000000000000..6571d1928c0de222292cb0360918707049856359 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_mixed.py @@ -0,0 +1,119 @@ +import numpy as np + +from matplotlib import cbook +from .backend_agg import RendererAgg +from matplotlib._tight_bbox import process_figure_for_rasterizing + + +class MixedModeRenderer: + """ + A helper class to implement a renderer that switches between + vector and raster drawing. An example may be a PDF writer, where + most things are drawn with PDF vector commands, but some very + complex objects, such as quad meshes, are rasterised and then + output as images. + """ + def __init__(self, figure, width, height, dpi, vector_renderer, + raster_renderer_class=None, + bbox_inches_restore=None): + """ + Parameters + ---------- + figure : `~matplotlib.figure.Figure` + The figure instance. + width : scalar + The width of the canvas in logical units + height : scalar + The height of the canvas in logical units + dpi : float + The dpi of the canvas + vector_renderer : `~matplotlib.backend_bases.RendererBase` + An instance of a subclass of + `~matplotlib.backend_bases.RendererBase` that will be used for the + vector drawing. + raster_renderer_class : `~matplotlib.backend_bases.RendererBase` + The renderer class to use for the raster drawing. If not provided, + this will use the Agg backend (which is currently the only viable + option anyway.) + + """ + if raster_renderer_class is None: + raster_renderer_class = RendererAgg + + self._raster_renderer_class = raster_renderer_class + self._width = width + self._height = height + self.dpi = dpi + + self._vector_renderer = vector_renderer + + self._raster_renderer = None + + # A reference to the figure is needed as we need to change + # the figure dpi before and after the rasterization. Although + # this looks ugly, I couldn't find a better solution. -JJL + self.figure = figure + self._figdpi = figure.dpi + + self._bbox_inches_restore = bbox_inches_restore + + self._renderer = vector_renderer + + def __getattr__(self, attr): + # Proxy everything that hasn't been overridden to the base + # renderer. Things that *are* overridden can call methods + # on self._renderer directly, but must not cache/store + # methods (because things like RendererAgg change their + # methods on the fly in order to optimise proxying down + # to the underlying C implementation). + return getattr(self._renderer, attr) + + def start_rasterizing(self): + """ + Enter "raster" mode. All subsequent drawing commands (until + `stop_rasterizing` is called) will be drawn with the raster backend. + """ + # change the dpi of the figure temporarily. + self.figure.dpi = self.dpi + if self._bbox_inches_restore: # when tight bbox is used + r = process_figure_for_rasterizing(self.figure, + self._bbox_inches_restore) + self._bbox_inches_restore = r + + self._raster_renderer = self._raster_renderer_class( + self._width*self.dpi, self._height*self.dpi, self.dpi) + self._renderer = self._raster_renderer + + def stop_rasterizing(self): + """ + Exit "raster" mode. All of the drawing that was done since + the last `start_rasterizing` call will be copied to the + vector backend by calling draw_image. + """ + + self._renderer = self._vector_renderer + + height = self._height * self.dpi + img = np.asarray(self._raster_renderer.buffer_rgba()) + slice_y, slice_x = cbook._get_nonzero_slices(img[..., 3]) + cropped_img = img[slice_y, slice_x] + if cropped_img.size: + gc = self._renderer.new_gc() + # TODO: If the mixedmode resolution differs from the figure's + # dpi, the image must be scaled (dpi->_figdpi). Not all + # backends support this. + self._renderer.draw_image( + gc, + slice_x.start * self._figdpi / self.dpi, + (height - slice_y.stop) * self._figdpi / self.dpi, + cropped_img[::-1]) + self._raster_renderer = None + + # restore the figure dpi. + self.figure.dpi = self._figdpi + + if self._bbox_inches_restore: # when tight bbox is used + r = process_figure_for_rasterizing(self.figure, + self._bbox_inches_restore, + self._figdpi) + self._bbox_inches_restore = r diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_pdf.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3e09f034f58a3fd337a71dc3a32bef202be94a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_pdf.py @@ -0,0 +1,2819 @@ +""" +A PDF Matplotlib backend. + +Author: Jouni K Seppänen and others. +""" + +import codecs +from datetime import timezone +from datetime import datetime +from enum import Enum +from functools import total_ordering +from io import BytesIO +import itertools +import logging +import math +import os +import string +import struct +import sys +import time +import types +import warnings +import zlib + +import numpy as np +from PIL import Image + +import matplotlib as mpl +from matplotlib import _api, _text_helpers, _type1font, cbook, dviread +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, + RendererBase) +from matplotlib.backends.backend_mixed import MixedModeRenderer +from matplotlib.figure import Figure +from matplotlib.font_manager import get_font, fontManager as _fontManager +from matplotlib._afm import AFM +from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE, + LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font) +from matplotlib.transforms import Affine2D, BboxBase +from matplotlib.path import Path +from matplotlib.dates import UTC +from matplotlib import _path +from . import _backend_pdf_ps + +_log = logging.getLogger(__name__) + +# Overview +# +# The low-level knowledge about pdf syntax lies mainly in the pdfRepr +# function and the classes Reference, Name, Operator, and Stream. The +# PdfFile class knows about the overall structure of pdf documents. +# It provides a "write" method for writing arbitrary strings in the +# file, and an "output" method that passes objects through the pdfRepr +# function before writing them in the file. The output method is +# called by the RendererPdf class, which contains the various draw_foo +# methods. RendererPdf contains a GraphicsContextPdf instance, and +# each draw_foo calls self.check_gc before outputting commands. This +# method checks whether the pdf graphics state needs to be modified +# and outputs the necessary commands. GraphicsContextPdf represents +# the graphics state, and its "delta" method returns the commands that +# modify the state. + +# Add "pdf.use14corefonts: True" in your configuration file to use only +# the 14 PDF core fonts. These fonts do not need to be embedded; every +# PDF viewing application is required to have them. This results in very +# light PDF files you can use directly in LaTeX or ConTeXt documents +# generated with pdfTeX, without any conversion. + +# These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique, +# Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique, +# Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic, +# Times-BoldItalic, Symbol, ZapfDingbats. +# +# Some tricky points: +# +# 1. The clip path can only be widened by popping from the state +# stack. Thus the state must be pushed onto the stack before narrowing +# the clip path. This is taken care of by GraphicsContextPdf. +# +# 2. Sometimes it is necessary to refer to something (e.g., font, +# image, or extended graphics state, which contains the alpha value) +# in the page stream by a name that needs to be defined outside the +# stream. PdfFile provides the methods fontName, imageObject, and +# alphaState for this purpose. The implementations of these methods +# should perhaps be generalized. + +# TODOs: +# +# * encoding of fonts, including mathtext fonts and Unicode support +# * TTF support has lots of small TODOs, e.g., how do you know if a font +# is serif/sans-serif, or symbolic/non-symbolic? +# * draw_quad_mesh + + +def _fill(strings, linelen=75): + """ + Make one string from sequence of strings, with whitespace in between. + + The whitespace is chosen to form lines of at most *linelen* characters, + if possible. + """ + currpos = 0 + lasti = 0 + result = [] + for i, s in enumerate(strings): + length = len(s) + if currpos + length < linelen: + currpos += length + 1 + else: + result.append(b' '.join(strings[lasti:i])) + lasti = i + currpos = length + result.append(b' '.join(strings[lasti:])) + return b'\n'.join(result) + + +def _create_pdf_info_dict(backend, metadata): + """ + Create a PDF infoDict based on user-supplied metadata. + + A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though + the user metadata may override it. The date may be the current time, or a + time set by the ``SOURCE_DATE_EPOCH`` environment variable. + + Metadata is verified to have the correct keys and their expected types. Any + unknown keys/types will raise a warning. + + Parameters + ---------- + backend : str + The name of the backend to use in the Producer value. + + metadata : dict[str, Union[str, datetime, Name]] + A dictionary of metadata supplied by the user with information + following the PDF specification, also defined in + `~.backend_pdf.PdfPages` below. + + If any value is *None*, then the key will be removed. This can be used + to remove any pre-defined values. + + Returns + ------- + dict[str, Union[str, datetime, Name]] + A validated dictionary of metadata. + """ + + # get source date from SOURCE_DATE_EPOCH, if set + # See https://reproducible-builds.org/specs/source-date-epoch/ + source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") + if source_date_epoch: + source_date = datetime.fromtimestamp(int(source_date_epoch), timezone.utc) + source_date = source_date.replace(tzinfo=UTC) + else: + source_date = datetime.today() + + info = { + 'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', + 'Producer': f'Matplotlib {backend} backend v{mpl.__version__}', + 'CreationDate': source_date, + **metadata + } + info = {k: v for (k, v) in info.items() if v is not None} + + def is_string_like(x): + return isinstance(x, str) + is_string_like.text_for_warning = "an instance of str" + + def is_date(x): + return isinstance(x, datetime) + is_date.text_for_warning = "an instance of datetime.datetime" + + def check_trapped(x): + if isinstance(x, Name): + return x.name in (b'True', b'False', b'Unknown') + else: + return x in ('True', 'False', 'Unknown') + check_trapped.text_for_warning = 'one of {"True", "False", "Unknown"}' + + keywords = { + 'Title': is_string_like, + 'Author': is_string_like, + 'Subject': is_string_like, + 'Keywords': is_string_like, + 'Creator': is_string_like, + 'Producer': is_string_like, + 'CreationDate': is_date, + 'ModDate': is_date, + 'Trapped': check_trapped, + } + for k in info: + if k not in keywords: + _api.warn_external(f'Unknown infodict keyword: {k!r}. ' + f'Must be one of {set(keywords)!r}.') + elif not keywords[k](info[k]): + _api.warn_external(f'Bad value for infodict keyword {k}. ' + f'Got {info[k]!r} which is not ' + f'{keywords[k].text_for_warning}.') + if 'Trapped' in info: + info['Trapped'] = Name(info['Trapped']) + + return info + + +def _datetime_to_pdf(d): + """ + Convert a datetime to a PDF string representing it. + + Used for PDF and PGF. + """ + r = d.strftime('D:%Y%m%d%H%M%S') + z = d.utcoffset() + if z is not None: + z = z.seconds + else: + if time.daylight: + z = time.altzone + else: + z = time.timezone + if z == 0: + r += 'Z' + elif z < 0: + r += "+%02d'%02d'" % ((-z) // 3600, (-z) % 3600) + else: + r += "-%02d'%02d'" % (z // 3600, z % 3600) + return r + + +def _calculate_quad_point_coordinates(x, y, width, height, angle=0): + """ + Calculate the coordinates of rectangle when rotated by angle around x, y + """ + + angle = math.radians(-angle) + sin_angle = math.sin(angle) + cos_angle = math.cos(angle) + a = x + height * sin_angle + b = y + height * cos_angle + c = x + width * cos_angle + height * sin_angle + d = y - width * sin_angle + height * cos_angle + e = x + width * cos_angle + f = y - width * sin_angle + return ((x, y), (e, f), (c, d), (a, b)) + + +def _get_coordinates_of_block(x, y, width, height, angle=0): + """ + Get the coordinates of rotated rectangle and rectangle that covers the + rotated rectangle. + """ + + vertices = _calculate_quad_point_coordinates(x, y, width, + height, angle) + + # Find min and max values for rectangle + # adjust so that QuadPoints is inside Rect + # PDF docs says that QuadPoints should be ignored if any point lies + # outside Rect, but for Acrobat it is enough that QuadPoints is on the + # border of Rect. + + pad = 0.00001 if angle % 90 else 0 + min_x = min(v[0] for v in vertices) - pad + min_y = min(v[1] for v in vertices) - pad + max_x = max(v[0] for v in vertices) + pad + max_y = max(v[1] for v in vertices) + pad + return (tuple(itertools.chain.from_iterable(vertices)), + (min_x, min_y, max_x, max_y)) + + +def _get_link_annotation(gc, x, y, width, height, angle=0): + """ + Create a link annotation object for embedding URLs. + """ + quadpoints, rect = _get_coordinates_of_block(x, y, width, height, angle) + link_annotation = { + 'Type': Name('Annot'), + 'Subtype': Name('Link'), + 'Rect': rect, + 'Border': [0, 0, 0], + 'A': { + 'S': Name('URI'), + 'URI': gc.get_url(), + }, + } + if angle % 90: + # Add QuadPoints + link_annotation['QuadPoints'] = quadpoints + return link_annotation + + +# PDF strings are supposed to be able to include any eight-bit data, except +# that unbalanced parens and backslashes must be escaped by a backslash. +# However, sf bug #2708559 shows that the carriage return character may get +# read as a newline; these characters correspond to \gamma and \Omega in TeX's +# math font encoding. Escaping them fixes the bug. +_str_escapes = str.maketrans({ + '\\': '\\\\', '(': '\\(', ')': '\\)', '\n': '\\n', '\r': '\\r'}) + + +def pdfRepr(obj): + """Map Python objects to PDF syntax.""" + + # Some objects defined later have their own pdfRepr method. + if hasattr(obj, 'pdfRepr'): + return obj.pdfRepr() + + # Floats. PDF does not have exponential notation (1.0e-10) so we + # need to use %f with some precision. Perhaps the precision + # should adapt to the magnitude of the number? + elif isinstance(obj, (float, np.floating)): + if not np.isfinite(obj): + raise ValueError("Can only output finite numbers in PDF") + r = b"%.10f" % obj + return r.rstrip(b'0').rstrip(b'.') + + # Booleans. Needs to be tested before integers since + # isinstance(True, int) is true. + elif isinstance(obj, bool): + return [b'false', b'true'][obj] + + # Integers are written as such. + elif isinstance(obj, (int, np.integer)): + return b"%d" % obj + + # Non-ASCII Unicode strings are encoded in UTF-16BE with byte-order mark. + elif isinstance(obj, str): + return pdfRepr(obj.encode('ascii') if obj.isascii() + else codecs.BOM_UTF16_BE + obj.encode('UTF-16BE')) + + # Strings are written in parentheses, with backslashes and parens + # escaped. Actually balanced parens are allowed, but it is + # simpler to escape them all. TODO: cut long strings into lines; + # I believe there is some maximum line length in PDF. + # Despite the extra decode/encode, translate is faster than regex. + elif isinstance(obj, bytes): + return ( + b'(' + + obj.decode('latin-1').translate(_str_escapes).encode('latin-1') + + b')') + + # Dictionaries. The keys must be PDF names, so if we find strings + # there, we make Name objects from them. The values may be + # anything, so the caller must ensure that PDF names are + # represented as Name objects. + elif isinstance(obj, dict): + return _fill([ + b"<<", + *[Name(k).pdfRepr() + b" " + pdfRepr(v) for k, v in obj.items()], + b">>", + ]) + + # Lists. + elif isinstance(obj, (list, tuple)): + return _fill([b"[", *[pdfRepr(val) for val in obj], b"]"]) + + # The null keyword. + elif obj is None: + return b'null' + + # A date. + elif isinstance(obj, datetime): + return pdfRepr(_datetime_to_pdf(obj)) + + # A bounding box + elif isinstance(obj, BboxBase): + return _fill([pdfRepr(val) for val in obj.bounds]) + + else: + raise TypeError(f"Don't know a PDF representation for {type(obj)} " + "objects") + + +def _font_supports_glyph(fonttype, glyph): + """ + Returns True if the font is able to provide codepoint *glyph* in a PDF. + + For a Type 3 font, this method returns True only for single-byte + characters. For Type 42 fonts this method return True if the character is + from the Basic Multilingual Plane. + """ + if fonttype == 3: + return glyph <= 255 + if fonttype == 42: + return glyph <= 65535 + raise NotImplementedError() + + +class Reference: + """ + PDF reference object. + + Use PdfFile.reserveObject() to create References. + """ + + def __init__(self, id): + self.id = id + + def __repr__(self): + return "" % self.id + + def pdfRepr(self): + return b"%d 0 R" % self.id + + def write(self, contents, file): + write = file.write + write(b"%d 0 obj\n" % self.id) + write(pdfRepr(contents)) + write(b"\nendobj\n") + + +@total_ordering +class Name: + """PDF name object.""" + __slots__ = ('name',) + _hexify = {c: '#%02x' % c + for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}} + + def __init__(self, name): + if isinstance(name, Name): + self.name = name.name + else: + if isinstance(name, bytes): + name = name.decode('ascii') + self.name = name.translate(self._hexify).encode('ascii') + + def __repr__(self): + return "" % self.name + + def __str__(self): + return '/' + self.name.decode('ascii') + + def __eq__(self, other): + return isinstance(other, Name) and self.name == other.name + + def __lt__(self, other): + return isinstance(other, Name) and self.name < other.name + + def __hash__(self): + return hash(self.name) + + def pdfRepr(self): + return b'/' + self.name + + +class Verbatim: + """Store verbatim PDF command content for later inclusion in the stream.""" + def __init__(self, x): + self._x = x + + def pdfRepr(self): + return self._x + + +class Op(Enum): + """PDF operators (not an exhaustive list).""" + + close_fill_stroke = b'b' + fill_stroke = b'B' + fill = b'f' + closepath = b'h' + close_stroke = b's' + stroke = b'S' + endpath = b'n' + begin_text = b'BT' + end_text = b'ET' + curveto = b'c' + rectangle = b're' + lineto = b'l' + moveto = b'm' + concat_matrix = b'cm' + use_xobject = b'Do' + setgray_stroke = b'G' + setgray_nonstroke = b'g' + setrgb_stroke = b'RG' + setrgb_nonstroke = b'rg' + setcolorspace_stroke = b'CS' + setcolorspace_nonstroke = b'cs' + setcolor_stroke = b'SCN' + setcolor_nonstroke = b'scn' + setdash = b'd' + setlinejoin = b'j' + setlinecap = b'J' + setgstate = b'gs' + gsave = b'q' + grestore = b'Q' + textpos = b'Td' + selectfont = b'Tf' + textmatrix = b'Tm' + show = b'Tj' + showkern = b'TJ' + setlinewidth = b'w' + clip = b'W' + shading = b'sh' + + def pdfRepr(self): + return self.value + + @classmethod + def paint_path(cls, fill, stroke): + """ + Return the PDF operator to paint a path. + + Parameters + ---------- + fill : bool + Fill the path with the fill color. + stroke : bool + Stroke the outline of the path with the line color. + """ + if stroke: + if fill: + return cls.fill_stroke + else: + return cls.stroke + else: + if fill: + return cls.fill + else: + return cls.endpath + + +class Stream: + """ + PDF stream object. + + This has no pdfRepr method. Instead, call begin(), then output the + contents of the stream by calling write(), and finally call end(). + """ + __slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos') + + def __init__(self, id, len, file, extra=None, png=None): + """ + Parameters + ---------- + id : int + Object id of the stream. + len : Reference or None + An unused Reference object for the length of the stream; + None means to use a memory buffer so the length can be inlined. + file : PdfFile + The underlying object to write the stream to. + extra : dict from Name to anything, or None + Extra key-value pairs to include in the stream header. + png : dict or None + If the data is already png encoded, the decode parameters. + """ + self.id = id # object id + self.len = len # id of length object + self.pdfFile = file + self.file = file.fh # file to which the stream is written + self.compressobj = None # compression object + if extra is None: + self.extra = dict() + else: + self.extra = extra.copy() + if png is not None: + self.extra.update({'Filter': Name('FlateDecode'), + 'DecodeParms': png}) + + self.pdfFile.recordXref(self.id) + if mpl.rcParams['pdf.compression'] and not png: + self.compressobj = zlib.compressobj( + mpl.rcParams['pdf.compression']) + if self.len is None: + self.file = BytesIO() + else: + self._writeHeader() + self.pos = self.file.tell() + + def _writeHeader(self): + write = self.file.write + write(b"%d 0 obj\n" % self.id) + dict = self.extra + dict['Length'] = self.len + if mpl.rcParams['pdf.compression']: + dict['Filter'] = Name('FlateDecode') + + write(pdfRepr(dict)) + write(b"\nstream\n") + + def end(self): + """Finalize stream.""" + + self._flush() + if self.len is None: + contents = self.file.getvalue() + self.len = len(contents) + self.file = self.pdfFile.fh + self._writeHeader() + self.file.write(contents) + self.file.write(b"\nendstream\nendobj\n") + else: + length = self.file.tell() - self.pos + self.file.write(b"\nendstream\nendobj\n") + self.pdfFile.writeObject(self.len, length) + + def write(self, data): + """Write some data on the stream.""" + + if self.compressobj is None: + self.file.write(data) + else: + compressed = self.compressobj.compress(data) + self.file.write(compressed) + + def _flush(self): + """Flush the compression object.""" + + if self.compressobj is not None: + compressed = self.compressobj.flush() + self.file.write(compressed) + self.compressobj = None + + +def _get_pdf_charprocs(font_path, glyph_ids): + font = get_font(font_path, hinting_factor=1) + conv = 1000 / font.units_per_EM # Conversion to PS units (1/1000's). + procs = {} + for glyph_id in glyph_ids: + g = font.load_glyph(glyph_id, LOAD_NO_SCALE) + # NOTE: We should be using round(), but instead use + # "(x+.5).astype(int)" to keep backcompat with the old ttconv code + # (this is different for negative x's). + d1 = (np.array([g.horiAdvance, 0, *g.bbox]) * conv + .5).astype(int) + v, c = font.get_path() + v = (v * 64).astype(int) # Back to TrueType's internal units (1/64's). + # Backcompat with old ttconv code: control points between two quads are + # omitted if they are exactly at the midpoint between the control of + # the quad before and the quad after, but ttconv used to interpolate + # *after* conversion to PS units, causing floating point errors. Here + # we reproduce ttconv's logic, detecting these "implicit" points and + # re-interpolating them. Note that occasionally (e.g. with DejaVu Sans + # glyph "0") a point detected as "implicit" is actually explicit, and + # will thus be shifted by 1. + quads, = np.nonzero(c == 3) + quads_on = quads[1::2] + quads_mid_on = np.array( + sorted({*quads_on} & {*(quads - 1)} & {*(quads + 1)}), int) + implicit = quads_mid_on[ + (v[quads_mid_on] # As above, use astype(int), not // division + == ((v[quads_mid_on - 1] + v[quads_mid_on + 1]) / 2).astype(int)) + .all(axis=1)] + if (font.postscript_name, glyph_id) in [ + ("DejaVuSerif-Italic", 77), # j + ("DejaVuSerif-Italic", 135), # \AA + ]: + v[:, 0] -= 1 # Hard-coded backcompat (FreeType shifts glyph by 1). + v = (v * conv + .5).astype(int) # As above re: truncation vs rounding. + v[implicit] = (( # Fix implicit points; again, truncate. + (v[implicit - 1] + v[implicit + 1]) / 2).astype(int)) + procs[font.get_glyph_name(glyph_id)] = ( + " ".join(map(str, d1)).encode("ascii") + b" d1\n" + + _path.convert_to_string( + Path(v, c), None, None, False, None, -1, + # no code for quad Beziers triggers auto-conversion to cubics. + [b"m", b"l", b"", b"c", b"h"], True) + + b"f") + return procs + + +class PdfFile: + """PDF file object.""" + + def __init__(self, filename, metadata=None): + """ + Parameters + ---------- + filename : str or path-like or file-like + Output target; if a string, a file will be opened for writing. + + metadata : dict from strings to strings and dates + Information dictionary object (see PDF reference section 10.2.1 + 'Document Information Dictionary'), e.g.: + ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``. + + The standard keys are 'Title', 'Author', 'Subject', 'Keywords', + 'Creator', 'Producer', 'CreationDate', 'ModDate', and + 'Trapped'. Values have been predefined for 'Creator', 'Producer' + and 'CreationDate'. They can be removed by setting them to `None`. + """ + super().__init__() + + self._object_seq = itertools.count(1) # consumed by reserveObject + self.xrefTable = [[0, 65535, 'the zero object']] + self.passed_in_file_object = False + self.original_file_like = None + self.tell_base = 0 + fh, opened = cbook.to_filehandle(filename, "wb", return_opened=True) + if not opened: + try: + self.tell_base = filename.tell() + except OSError: + fh = BytesIO() + self.original_file_like = filename + else: + fh = filename + self.passed_in_file_object = True + + self.fh = fh + self.currentstream = None # stream object to write to, if any + fh.write(b"%PDF-1.4\n") # 1.4 is the first version to have alpha + # Output some eight-bit chars as a comment so various utilities + # recognize the file as binary by looking at the first few + # lines (see note in section 3.4.1 of the PDF reference). + fh.write(b"%\254\334 \253\272\n") + + self.rootObject = self.reserveObject('root') + self.pagesObject = self.reserveObject('pages') + self.pageList = [] + self.fontObject = self.reserveObject('fonts') + self._extGStateObject = self.reserveObject('extended graphics states') + self.hatchObject = self.reserveObject('tiling patterns') + self.gouraudObject = self.reserveObject('Gouraud triangles') + self.XObjectObject = self.reserveObject('external objects') + self.resourceObject = self.reserveObject('resources') + + root = {'Type': Name('Catalog'), + 'Pages': self.pagesObject} + self.writeObject(self.rootObject, root) + + self.infoDict = _create_pdf_info_dict('pdf', metadata or {}) + + self.fontNames = {} # maps filenames to internal font names + self._internal_font_seq = (Name(f'F{i}') for i in itertools.count(1)) + self.dviFontInfo = {} # maps dvi font names to embedding information + # differently encoded Type-1 fonts may share the same descriptor + self.type1Descriptors = {} + self._character_tracker = _backend_pdf_ps.CharacterTracker() + + self.alphaStates = {} # maps alpha values to graphics state objects + self._alpha_state_seq = (Name(f'A{i}') for i in itertools.count(1)) + self._soft_mask_states = {} + self._soft_mask_seq = (Name(f'SM{i}') for i in itertools.count(1)) + self._soft_mask_groups = [] + self.hatchPatterns = {} + self._hatch_pattern_seq = (Name(f'H{i}') for i in itertools.count(1)) + self.gouraudTriangles = [] + + self._images = {} + self._image_seq = (Name(f'I{i}') for i in itertools.count(1)) + + self.markers = {} + self.multi_byte_charprocs = {} + + self.paths = [] + + # A list of annotations for each page. Each entry is a tuple of the + # overall Annots object reference that's inserted into the page object, + # followed by a list of the actual annotations. + self._annotations = [] + # For annotations added before a page is created; mostly for the + # purpose of newTextnote. + self.pageAnnotations = [] + + # The PDF spec recommends to include every procset + procsets = [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()] + + # Write resource dictionary. + # Possibly TODO: more general ExtGState (graphics state dictionaries) + # ColorSpace Pattern Shading Properties + resources = {'Font': self.fontObject, + 'XObject': self.XObjectObject, + 'ExtGState': self._extGStateObject, + 'Pattern': self.hatchObject, + 'Shading': self.gouraudObject, + 'ProcSet': procsets} + self.writeObject(self.resourceObject, resources) + + def newPage(self, width, height): + self.endStream() + + self.width, self.height = width, height + contentObject = self.reserveObject('page contents') + annotsObject = self.reserveObject('annotations') + thePage = {'Type': Name('Page'), + 'Parent': self.pagesObject, + 'Resources': self.resourceObject, + 'MediaBox': [0, 0, 72 * width, 72 * height], + 'Contents': contentObject, + 'Annots': annotsObject, + } + pageObject = self.reserveObject('page') + self.writeObject(pageObject, thePage) + self.pageList.append(pageObject) + self._annotations.append((annotsObject, self.pageAnnotations)) + + self.beginStream(contentObject.id, + self.reserveObject('length of content stream')) + # Initialize the pdf graphics state to match the default Matplotlib + # graphics context (colorspace and joinstyle). + self.output(Name('DeviceRGB'), Op.setcolorspace_stroke) + self.output(Name('DeviceRGB'), Op.setcolorspace_nonstroke) + self.output(GraphicsContextPdf.joinstyles['round'], Op.setlinejoin) + + # Clear the list of annotations for the next page + self.pageAnnotations = [] + + def newTextnote(self, text, positionRect=[-100, -100, 0, 0]): + # Create a new annotation of type text + theNote = {'Type': Name('Annot'), + 'Subtype': Name('Text'), + 'Contents': text, + 'Rect': positionRect, + } + self.pageAnnotations.append(theNote) + + def _get_subsetted_psname(self, ps_name, charmap): + def toStr(n, base): + if n < base: + return string.ascii_uppercase[n] + else: + return ( + toStr(n // base, base) + string.ascii_uppercase[n % base] + ) + + # encode to string using base 26 + hashed = hash(frozenset(charmap.keys())) % ((sys.maxsize + 1) * 2) + prefix = toStr(hashed, 26) + + # get first 6 characters from prefix + return prefix[:6] + "+" + ps_name + + def finalize(self): + """Write out the various deferred objects and the pdf end matter.""" + + self.endStream() + self._write_annotations() + self.writeFonts() + self.writeExtGSTates() + self._write_soft_mask_groups() + self.writeHatches() + self.writeGouraudTriangles() + xobjects = { + name: ob for image, name, ob in self._images.values()} + for tup in self.markers.values(): + xobjects[tup[0]] = tup[1] + for name, value in self.multi_byte_charprocs.items(): + xobjects[name] = value + for name, path, trans, ob, join, cap, padding, filled, stroked \ + in self.paths: + xobjects[name] = ob + self.writeObject(self.XObjectObject, xobjects) + self.writeImages() + self.writeMarkers() + self.writePathCollectionTemplates() + self.writeObject(self.pagesObject, + {'Type': Name('Pages'), + 'Kids': self.pageList, + 'Count': len(self.pageList)}) + self.writeInfoDict() + + # Finalize the file + self.writeXref() + self.writeTrailer() + + def close(self): + """Flush all buffers and free all resources.""" + + self.endStream() + if self.passed_in_file_object: + self.fh.flush() + else: + if self.original_file_like is not None: + self.original_file_like.write(self.fh.getvalue()) + self.fh.close() + + def write(self, data): + if self.currentstream is None: + self.fh.write(data) + else: + self.currentstream.write(data) + + def output(self, *data): + self.write(_fill([pdfRepr(x) for x in data])) + self.write(b'\n') + + def beginStream(self, id, len, extra=None, png=None): + assert self.currentstream is None + self.currentstream = Stream(id, len, self, extra, png) + + def endStream(self): + if self.currentstream is not None: + self.currentstream.end() + self.currentstream = None + + def outputStream(self, ref, data, *, extra=None): + self.beginStream(ref.id, None, extra) + self.currentstream.write(data) + self.endStream() + + def _write_annotations(self): + for annotsObject, annotations in self._annotations: + self.writeObject(annotsObject, annotations) + + def fontName(self, fontprop): + """ + Select a font based on fontprop and return a name suitable for + Op.selectfont. If fontprop is a string, it will be interpreted + as the filename of the font. + """ + + if isinstance(fontprop, str): + filenames = [fontprop] + elif mpl.rcParams['pdf.use14corefonts']: + filenames = _fontManager._find_fonts_by_props( + fontprop, fontext='afm', directory=RendererPdf._afm_font_dir + ) + else: + filenames = _fontManager._find_fonts_by_props(fontprop) + first_Fx = None + for fname in filenames: + Fx = self.fontNames.get(fname) + if not first_Fx: + first_Fx = Fx + if Fx is None: + Fx = next(self._internal_font_seq) + self.fontNames[fname] = Fx + _log.debug('Assigning font %s = %r', Fx, fname) + if not first_Fx: + first_Fx = Fx + + # find_fontsprop's first value always adheres to + # findfont's value, so technically no behaviour change + return first_Fx + + def dviFontName(self, dvifont): + """ + Given a dvi font object, return a name suitable for Op.selectfont. + This registers the font information in ``self.dviFontInfo`` if not yet + registered. + """ + + dvi_info = self.dviFontInfo.get(dvifont.texname) + if dvi_info is not None: + return dvi_info.pdfname + + tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) + psfont = tex_font_map[dvifont.texname] + if psfont.filename is None: + raise ValueError( + "No usable font file found for {} (TeX: {}); " + "the font may lack a Type-1 version" + .format(psfont.psname, dvifont.texname)) + + pdfname = next(self._internal_font_seq) + _log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname) + self.dviFontInfo[dvifont.texname] = types.SimpleNamespace( + dvifont=dvifont, + pdfname=pdfname, + fontfile=psfont.filename, + basefont=psfont.psname, + encodingfile=psfont.encoding, + effects=psfont.effects) + return pdfname + + def writeFonts(self): + fonts = {} + for dviname, info in sorted(self.dviFontInfo.items()): + Fx = info.pdfname + _log.debug('Embedding Type-1 font %s from dvi.', dviname) + fonts[Fx] = self._embedTeXFont(info) + for filename in sorted(self.fontNames): + Fx = self.fontNames[filename] + _log.debug('Embedding font %s.', filename) + if filename.endswith('.afm'): + # from pdf.use14corefonts + _log.debug('Writing AFM font.') + fonts[Fx] = self._write_afm_font(filename) + else: + # a normal TrueType font + _log.debug('Writing TrueType font.') + chars = self._character_tracker.used.get(filename) + if chars: + fonts[Fx] = self.embedTTF(filename, chars) + self.writeObject(self.fontObject, fonts) + + def _write_afm_font(self, filename): + with open(filename, 'rb') as fh: + font = AFM(fh) + fontname = font.get_fontname() + fontdict = {'Type': Name('Font'), + 'Subtype': Name('Type1'), + 'BaseFont': Name(fontname), + 'Encoding': Name('WinAnsiEncoding')} + fontdictObject = self.reserveObject('font dictionary') + self.writeObject(fontdictObject, fontdict) + return fontdictObject + + def _embedTeXFont(self, fontinfo): + _log.debug('Embedding TeX font %s - fontinfo=%s', + fontinfo.dvifont.texname, fontinfo.__dict__) + + # Widths + widthsObject = self.reserveObject('font widths') + self.writeObject(widthsObject, fontinfo.dvifont.widths) + + # Font dictionary + fontdictObject = self.reserveObject('font dictionary') + fontdict = { + 'Type': Name('Font'), + 'Subtype': Name('Type1'), + 'FirstChar': 0, + 'LastChar': len(fontinfo.dvifont.widths) - 1, + 'Widths': widthsObject, + } + + # Encoding (if needed) + if fontinfo.encodingfile is not None: + fontdict['Encoding'] = { + 'Type': Name('Encoding'), + 'Differences': [ + 0, *map(Name, dviread._parse_enc(fontinfo.encodingfile))], + } + + # If no file is specified, stop short + if fontinfo.fontfile is None: + _log.warning( + "Because of TeX configuration (pdftex.map, see updmap option " + "pdftexDownloadBase14) the font %s is not embedded. This is " + "deprecated as of PDF 1.5 and it may cause the consumer " + "application to show something that was not intended.", + fontinfo.basefont) + fontdict['BaseFont'] = Name(fontinfo.basefont) + self.writeObject(fontdictObject, fontdict) + return fontdictObject + + # We have a font file to embed - read it in and apply any effects + t1font = _type1font.Type1Font(fontinfo.fontfile) + if fontinfo.effects: + t1font = t1font.transform(fontinfo.effects) + fontdict['BaseFont'] = Name(t1font.prop['FontName']) + + # Font descriptors may be shared between differently encoded + # Type-1 fonts, so only create a new descriptor if there is no + # existing descriptor for this font. + effects = (fontinfo.effects.get('slant', 0.0), + fontinfo.effects.get('extend', 1.0)) + fontdesc = self.type1Descriptors.get((fontinfo.fontfile, effects)) + if fontdesc is None: + fontdesc = self.createType1Descriptor(t1font, fontinfo.fontfile) + self.type1Descriptors[(fontinfo.fontfile, effects)] = fontdesc + fontdict['FontDescriptor'] = fontdesc + + self.writeObject(fontdictObject, fontdict) + return fontdictObject + + def createType1Descriptor(self, t1font, fontfile): + # Create and write the font descriptor and the font file + # of a Type-1 font + fontdescObject = self.reserveObject('font descriptor') + fontfileObject = self.reserveObject('font file') + + italic_angle = t1font.prop['ItalicAngle'] + fixed_pitch = t1font.prop['isFixedPitch'] + + flags = 0 + # fixed width + if fixed_pitch: + flags |= 1 << 0 + # TODO: serif + if 0: + flags |= 1 << 1 + # TODO: symbolic (most TeX fonts are) + if 1: + flags |= 1 << 2 + # non-symbolic + else: + flags |= 1 << 5 + # italic + if italic_angle: + flags |= 1 << 6 + # TODO: all caps + if 0: + flags |= 1 << 16 + # TODO: small caps + if 0: + flags |= 1 << 17 + # TODO: force bold + if 0: + flags |= 1 << 18 + + ft2font = get_font(fontfile) + + descriptor = { + 'Type': Name('FontDescriptor'), + 'FontName': Name(t1font.prop['FontName']), + 'Flags': flags, + 'FontBBox': ft2font.bbox, + 'ItalicAngle': italic_angle, + 'Ascent': ft2font.ascender, + 'Descent': ft2font.descender, + 'CapHeight': 1000, # TODO: find this out + 'XHeight': 500, # TODO: this one too + 'FontFile': fontfileObject, + 'FontFamily': t1font.prop['FamilyName'], + 'StemV': 50, # TODO + # (see also revision 3874; but not all TeX distros have AFM files!) + # 'FontWeight': a number where 400 = Regular, 700 = Bold + } + + self.writeObject(fontdescObject, descriptor) + + self.outputStream(fontfileObject, b"".join(t1font.parts[:2]), + extra={'Length1': len(t1font.parts[0]), + 'Length2': len(t1font.parts[1]), + 'Length3': 0}) + + return fontdescObject + + def _get_xobject_glyph_name(self, filename, glyph_name): + Fx = self.fontName(filename) + return "-".join([ + Fx.name.decode(), + os.path.splitext(os.path.basename(filename))[0], + glyph_name]) + + _identityToUnicodeCMap = b"""/CIDInit /ProcSet findresource begin +12 dict begin +begincmap +/CIDSystemInfo +<< /Registry (Adobe) + /Ordering (UCS) + /Supplement 0 +>> def +/CMapName /Adobe-Identity-UCS def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +%d beginbfrange +%s +endbfrange +endcmap +CMapName currentdict /CMap defineresource pop +end +end""" + + def embedTTF(self, filename, characters): + """Embed the TTF font from the named file into the document.""" + + font = get_font(filename) + fonttype = mpl.rcParams['pdf.fonttype'] + + def cvt(length, upe=font.units_per_EM, nearest=True): + """Convert font coordinates to PDF glyph coordinates.""" + value = length / upe * 1000 + if nearest: + return round(value) + # Best(?) to round away from zero for bounding boxes and the like. + if value < 0: + return math.floor(value) + else: + return math.ceil(value) + + def embedTTFType3(font, characters, descriptor): + """The Type 3-specific part of embedding a Truetype font""" + widthsObject = self.reserveObject('font widths') + fontdescObject = self.reserveObject('font descriptor') + fontdictObject = self.reserveObject('font dictionary') + charprocsObject = self.reserveObject('character procs') + differencesArray = [] + firstchar, lastchar = 0, 255 + bbox = [cvt(x, nearest=False) for x in font.bbox] + + fontdict = { + 'Type': Name('Font'), + 'BaseFont': ps_name, + 'FirstChar': firstchar, + 'LastChar': lastchar, + 'FontDescriptor': fontdescObject, + 'Subtype': Name('Type3'), + 'Name': descriptor['FontName'], + 'FontBBox': bbox, + 'FontMatrix': [.001, 0, 0, .001, 0, 0], + 'CharProcs': charprocsObject, + 'Encoding': { + 'Type': Name('Encoding'), + 'Differences': differencesArray}, + 'Widths': widthsObject + } + + from encodings import cp1252 + + # Make the "Widths" array + def get_char_width(charcode): + s = ord(cp1252.decoding_table[charcode]) + width = font.load_char( + s, flags=LOAD_NO_SCALE | LOAD_NO_HINTING).horiAdvance + return cvt(width) + with warnings.catch_warnings(): + # Ignore 'Required glyph missing from current font' warning + # from ft2font: here we're just building the widths table, but + # the missing glyphs may not even be used in the actual string. + warnings.filterwarnings("ignore") + widths = [get_char_width(charcode) + for charcode in range(firstchar, lastchar+1)] + descriptor['MaxWidth'] = max(widths) + + # Make the "Differences" array, sort the ccodes < 255 from + # the multi-byte ccodes, and build the whole set of glyph ids + # that we need from this font. + glyph_ids = [] + differences = [] + multi_byte_chars = set() + for c in characters: + ccode = c + gind = font.get_char_index(ccode) + glyph_ids.append(gind) + glyph_name = font.get_glyph_name(gind) + if ccode <= 255: + differences.append((ccode, glyph_name)) + else: + multi_byte_chars.add(glyph_name) + differences.sort() + + last_c = -2 + for c, name in differences: + if c != last_c + 1: + differencesArray.append(c) + differencesArray.append(Name(name)) + last_c = c + + # Make the charprocs array. + rawcharprocs = _get_pdf_charprocs(filename, glyph_ids) + charprocs = {} + for charname in sorted(rawcharprocs): + stream = rawcharprocs[charname] + charprocDict = {} + # The 2-byte characters are used as XObjects, so they + # need extra info in their dictionary + if charname in multi_byte_chars: + charprocDict = {'Type': Name('XObject'), + 'Subtype': Name('Form'), + 'BBox': bbox} + # Each glyph includes bounding box information, + # but xpdf and ghostscript can't handle it in a + # Form XObject (they segfault!!!), so we remove it + # from the stream here. It's not needed anyway, + # since the Form XObject includes it in its BBox + # value. + stream = stream[stream.find(b"d1") + 2:] + charprocObject = self.reserveObject('charProc') + self.outputStream(charprocObject, stream, extra=charprocDict) + + # Send the glyphs with ccode > 255 to the XObject dictionary, + # and the others to the font itself + if charname in multi_byte_chars: + name = self._get_xobject_glyph_name(filename, charname) + self.multi_byte_charprocs[name] = charprocObject + else: + charprocs[charname] = charprocObject + + # Write everything out + self.writeObject(fontdictObject, fontdict) + self.writeObject(fontdescObject, descriptor) + self.writeObject(widthsObject, widths) + self.writeObject(charprocsObject, charprocs) + + return fontdictObject + + def embedTTFType42(font, characters, descriptor): + """The Type 42-specific part of embedding a Truetype font""" + fontdescObject = self.reserveObject('font descriptor') + cidFontDictObject = self.reserveObject('CID font dictionary') + type0FontDictObject = self.reserveObject('Type 0 font dictionary') + cidToGidMapObject = self.reserveObject('CIDToGIDMap stream') + fontfileObject = self.reserveObject('font file stream') + wObject = self.reserveObject('Type 0 widths') + toUnicodeMapObject = self.reserveObject('ToUnicode map') + + subset_str = "".join(chr(c) for c in characters) + _log.debug("SUBSET %s characters: %s", filename, subset_str) + fontdata = _backend_pdf_ps.get_glyphs_subset(filename, subset_str) + _log.debug( + "SUBSET %s %d -> %d", filename, + os.stat(filename).st_size, fontdata.getbuffer().nbytes + ) + + # We need this ref for XObjects + full_font = font + + # reload the font object from the subset + # (all the necessary data could probably be obtained directly + # using fontLib.ttLib) + font = FT2Font(fontdata) + + cidFontDict = { + 'Type': Name('Font'), + 'Subtype': Name('CIDFontType2'), + 'BaseFont': ps_name, + 'CIDSystemInfo': { + 'Registry': 'Adobe', + 'Ordering': 'Identity', + 'Supplement': 0}, + 'FontDescriptor': fontdescObject, + 'W': wObject, + 'CIDToGIDMap': cidToGidMapObject + } + + type0FontDict = { + 'Type': Name('Font'), + 'Subtype': Name('Type0'), + 'BaseFont': ps_name, + 'Encoding': Name('Identity-H'), + 'DescendantFonts': [cidFontDictObject], + 'ToUnicode': toUnicodeMapObject + } + + # Make fontfile stream + descriptor['FontFile2'] = fontfileObject + self.outputStream( + fontfileObject, fontdata.getvalue(), + extra={'Length1': fontdata.getbuffer().nbytes}) + + # Make the 'W' (Widths) array, CidToGidMap and ToUnicode CMap + # at the same time + cid_to_gid_map = ['\0'] * 65536 + widths = [] + max_ccode = 0 + for c in characters: + ccode = c + gind = font.get_char_index(ccode) + glyph = font.load_char(ccode, + flags=LOAD_NO_SCALE | LOAD_NO_HINTING) + widths.append((ccode, cvt(glyph.horiAdvance))) + if ccode < 65536: + cid_to_gid_map[ccode] = chr(gind) + max_ccode = max(ccode, max_ccode) + widths.sort() + cid_to_gid_map = cid_to_gid_map[:max_ccode + 1] + + last_ccode = -2 + w = [] + max_width = 0 + unicode_groups = [] + for ccode, width in widths: + if ccode != last_ccode + 1: + w.append(ccode) + w.append([width]) + unicode_groups.append([ccode, ccode]) + else: + w[-1].append(width) + unicode_groups[-1][1] = ccode + max_width = max(max_width, width) + last_ccode = ccode + + unicode_bfrange = [] + for start, end in unicode_groups: + # Ensure the CID map contains only chars from BMP + if start > 65535: + continue + end = min(65535, end) + + unicode_bfrange.append( + b"<%04x> <%04x> [%s]" % + (start, end, + b" ".join(b"<%04x>" % x for x in range(start, end+1)))) + unicode_cmap = (self._identityToUnicodeCMap % + (len(unicode_groups), b"\n".join(unicode_bfrange))) + + # Add XObjects for unsupported chars + glyph_ids = [] + for ccode in characters: + if not _font_supports_glyph(fonttype, ccode): + gind = full_font.get_char_index(ccode) + glyph_ids.append(gind) + + bbox = [cvt(x, nearest=False) for x in full_font.bbox] + rawcharprocs = _get_pdf_charprocs(filename, glyph_ids) + for charname in sorted(rawcharprocs): + stream = rawcharprocs[charname] + charprocDict = {'Type': Name('XObject'), + 'Subtype': Name('Form'), + 'BBox': bbox} + # Each glyph includes bounding box information, + # but xpdf and ghostscript can't handle it in a + # Form XObject (they segfault!!!), so we remove it + # from the stream here. It's not needed anyway, + # since the Form XObject includes it in its BBox + # value. + stream = stream[stream.find(b"d1") + 2:] + charprocObject = self.reserveObject('charProc') + self.outputStream(charprocObject, stream, extra=charprocDict) + + name = self._get_xobject_glyph_name(filename, charname) + self.multi_byte_charprocs[name] = charprocObject + + # CIDToGIDMap stream + cid_to_gid_map = "".join(cid_to_gid_map).encode("utf-16be") + self.outputStream(cidToGidMapObject, cid_to_gid_map) + + # ToUnicode CMap + self.outputStream(toUnicodeMapObject, unicode_cmap) + + descriptor['MaxWidth'] = max_width + + # Write everything out + self.writeObject(cidFontDictObject, cidFontDict) + self.writeObject(type0FontDictObject, type0FontDict) + self.writeObject(fontdescObject, descriptor) + self.writeObject(wObject, w) + + return type0FontDictObject + + # Beginning of main embedTTF function... + + ps_name = self._get_subsetted_psname( + font.postscript_name, + font.get_charmap() + ) + ps_name = ps_name.encode('ascii', 'replace') + ps_name = Name(ps_name) + pclt = font.get_sfnt_table('pclt') or {'capHeight': 0, 'xHeight': 0} + post = font.get_sfnt_table('post') or {'italicAngle': (0, 0)} + ff = font.face_flags + sf = font.style_flags + + flags = 0 + symbolic = False # ps_name.name in ('Cmsy10', 'Cmmi10', 'Cmex10') + if ff & FIXED_WIDTH: + flags |= 1 << 0 + if 0: # TODO: serif + flags |= 1 << 1 + if symbolic: + flags |= 1 << 2 + else: + flags |= 1 << 5 + if sf & ITALIC: + flags |= 1 << 6 + if 0: # TODO: all caps + flags |= 1 << 16 + if 0: # TODO: small caps + flags |= 1 << 17 + if 0: # TODO: force bold + flags |= 1 << 18 + + descriptor = { + 'Type': Name('FontDescriptor'), + 'FontName': ps_name, + 'Flags': flags, + 'FontBBox': [cvt(x, nearest=False) for x in font.bbox], + 'Ascent': cvt(font.ascender, nearest=False), + 'Descent': cvt(font.descender, nearest=False), + 'CapHeight': cvt(pclt['capHeight'], nearest=False), + 'XHeight': cvt(pclt['xHeight']), + 'ItalicAngle': post['italicAngle'][1], # ??? + 'StemV': 0 # ??? + } + + if fonttype == 3: + return embedTTFType3(font, characters, descriptor) + elif fonttype == 42: + return embedTTFType42(font, characters, descriptor) + + def alphaState(self, alpha): + """Return name of an ExtGState that sets alpha to the given value.""" + + state = self.alphaStates.get(alpha, None) + if state is not None: + return state[0] + + name = next(self._alpha_state_seq) + self.alphaStates[alpha] = \ + (name, {'Type': Name('ExtGState'), + 'CA': alpha[0], 'ca': alpha[1]}) + return name + + def _soft_mask_state(self, smask): + """ + Return an ExtGState that sets the soft mask to the given shading. + + Parameters + ---------- + smask : Reference + Reference to a shading in DeviceGray color space, whose luminosity + is to be used as the alpha channel. + + Returns + ------- + Name + """ + + state = self._soft_mask_states.get(smask, None) + if state is not None: + return state[0] + + name = next(self._soft_mask_seq) + groupOb = self.reserveObject('transparency group for soft mask') + self._soft_mask_states[smask] = ( + name, + { + 'Type': Name('ExtGState'), + 'AIS': False, + 'SMask': { + 'Type': Name('Mask'), + 'S': Name('Luminosity'), + 'BC': [1], + 'G': groupOb + } + } + ) + self._soft_mask_groups.append(( + groupOb, + { + 'Type': Name('XObject'), + 'Subtype': Name('Form'), + 'FormType': 1, + 'Group': { + 'S': Name('Transparency'), + 'CS': Name('DeviceGray') + }, + 'Matrix': [1, 0, 0, 1, 0, 0], + 'Resources': {'Shading': {'S': smask}}, + 'BBox': [0, 0, 1, 1] + }, + [Name('S'), Op.shading] + )) + return name + + def writeExtGSTates(self): + self.writeObject( + self._extGStateObject, + dict([ + *self.alphaStates.values(), + *self._soft_mask_states.values() + ]) + ) + + def _write_soft_mask_groups(self): + for ob, attributes, content in self._soft_mask_groups: + self.beginStream(ob.id, None, attributes) + self.output(*content) + self.endStream() + + def hatchPattern(self, hatch_style): + # The colors may come in as numpy arrays, which aren't hashable + if hatch_style is not None: + edge, face, hatch = hatch_style + if edge is not None: + edge = tuple(edge) + if face is not None: + face = tuple(face) + hatch_style = (edge, face, hatch) + + pattern = self.hatchPatterns.get(hatch_style, None) + if pattern is not None: + return pattern + + name = next(self._hatch_pattern_seq) + self.hatchPatterns[hatch_style] = name + return name + + def writeHatches(self): + hatchDict = dict() + sidelen = 72.0 + for hatch_style, name in self.hatchPatterns.items(): + ob = self.reserveObject('hatch pattern') + hatchDict[name] = ob + res = {'Procsets': + [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()]} + self.beginStream( + ob.id, None, + {'Type': Name('Pattern'), + 'PatternType': 1, 'PaintType': 1, 'TilingType': 1, + 'BBox': [0, 0, sidelen, sidelen], + 'XStep': sidelen, 'YStep': sidelen, + 'Resources': res, + # Change origin to match Agg at top-left. + 'Matrix': [1, 0, 0, 1, 0, self.height * 72]}) + + stroke_rgb, fill_rgb, hatch = hatch_style + self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2], + Op.setrgb_stroke) + if fill_rgb is not None: + self.output(fill_rgb[0], fill_rgb[1], fill_rgb[2], + Op.setrgb_nonstroke, + 0, 0, sidelen, sidelen, Op.rectangle, + Op.fill) + + self.output(mpl.rcParams['hatch.linewidth'], Op.setlinewidth) + + self.output(*self.pathOperations( + Path.hatch(hatch), + Affine2D().scale(sidelen), + simplify=False)) + self.output(Op.fill_stroke) + + self.endStream() + self.writeObject(self.hatchObject, hatchDict) + + def addGouraudTriangles(self, points, colors): + """ + Add a Gouraud triangle shading. + + Parameters + ---------- + points : np.ndarray + Triangle vertices, shape (n, 3, 2) + where n = number of triangles, 3 = vertices, 2 = x, y. + colors : np.ndarray + Vertex colors, shape (n, 3, 1) or (n, 3, 4) + as with points, but last dimension is either (gray,) + or (r, g, b, alpha). + + Returns + ------- + Name, Reference + """ + name = Name('GT%d' % len(self.gouraudTriangles)) + ob = self.reserveObject(f'Gouraud triangle {name}') + self.gouraudTriangles.append((name, ob, points, colors)) + return name, ob + + def writeGouraudTriangles(self): + gouraudDict = dict() + for name, ob, points, colors in self.gouraudTriangles: + gouraudDict[name] = ob + shape = points.shape + flat_points = points.reshape((shape[0] * shape[1], 2)) + colordim = colors.shape[2] + assert colordim in (1, 4) + flat_colors = colors.reshape((shape[0] * shape[1], colordim)) + if colordim == 4: + # strip the alpha channel + colordim = 3 + points_min = np.min(flat_points, axis=0) - (1 << 8) + points_max = np.max(flat_points, axis=0) + (1 << 8) + factor = 0xffffffff / (points_max - points_min) + + self.beginStream( + ob.id, None, + {'ShadingType': 4, + 'BitsPerCoordinate': 32, + 'BitsPerComponent': 8, + 'BitsPerFlag': 8, + 'ColorSpace': Name( + 'DeviceRGB' if colordim == 3 else 'DeviceGray' + ), + 'AntiAlias': False, + 'Decode': ([points_min[0], points_max[0], + points_min[1], points_max[1]] + + [0, 1] * colordim), + }) + + streamarr = np.empty( + (shape[0] * shape[1],), + dtype=[('flags', 'u1'), + ('points', '>u4', (2,)), + ('colors', 'u1', (colordim,))]) + streamarr['flags'] = 0 + streamarr['points'] = (flat_points - points_min) * factor + streamarr['colors'] = flat_colors[:, :colordim] * 255.0 + + self.write(streamarr.tobytes()) + self.endStream() + self.writeObject(self.gouraudObject, gouraudDict) + + def imageObject(self, image): + """Return name of an image XObject representing the given image.""" + + entry = self._images.get(id(image), None) + if entry is not None: + return entry[1] + + name = next(self._image_seq) + ob = self.reserveObject(f'image {name}') + self._images[id(image)] = (image, name, ob) + return name + + def _unpack(self, im): + """ + Unpack image array *im* into ``(data, alpha)``, which have shape + ``(height, width, 3)`` (RGB) or ``(height, width, 1)`` (grayscale or + alpha), except that alpha is None if the image is fully opaque. + """ + im = im[::-1] + if im.ndim == 2: + return im, None + else: + rgb = im[:, :, :3] + rgb = np.array(rgb, order='C') + # PDF needs a separate alpha image + if im.shape[2] == 4: + alpha = im[:, :, 3][..., None] + if np.all(alpha == 255): + alpha = None + else: + alpha = np.array(alpha, order='C') + else: + alpha = None + return rgb, alpha + + def _writePng(self, img): + """ + Write the image *img* into the pdf file using png + predictors with Flate compression. + """ + buffer = BytesIO() + img.save(buffer, format="png") + buffer.seek(8) + png_data = b'' + bit_depth = palette = None + while True: + length, type = struct.unpack(b'!L4s', buffer.read(8)) + if type in [b'IHDR', b'PLTE', b'IDAT']: + data = buffer.read(length) + if len(data) != length: + raise RuntimeError("truncated data") + if type == b'IHDR': + bit_depth = int(data[8]) + elif type == b'PLTE': + palette = data + elif type == b'IDAT': + png_data += data + elif type == b'IEND': + break + else: + buffer.seek(length, 1) + buffer.seek(4, 1) # skip CRC + return png_data, bit_depth, palette + + def _writeImg(self, data, id, smask=None): + """ + Write the image *data*, of shape ``(height, width, 1)`` (grayscale) or + ``(height, width, 3)`` (RGB), as pdf object *id* and with the soft mask + (alpha channel) *smask*, which should be either None or a ``(height, + width, 1)`` array. + """ + height, width, color_channels = data.shape + obj = {'Type': Name('XObject'), + 'Subtype': Name('Image'), + 'Width': width, + 'Height': height, + 'ColorSpace': Name({1: 'DeviceGray', 3: 'DeviceRGB'}[color_channels]), + 'BitsPerComponent': 8} + if smask: + obj['SMask'] = smask + if mpl.rcParams['pdf.compression']: + if data.shape[-1] == 1: + data = data.squeeze(axis=-1) + png = {'Predictor': 10, 'Colors': color_channels, 'Columns': width} + img = Image.fromarray(data) + img_colors = img.getcolors(maxcolors=256) + if color_channels == 3 and img_colors is not None: + # Convert to indexed color if there are 256 colors or fewer. This can + # significantly reduce the file size. + num_colors = len(img_colors) + palette = np.array([comp for _, color in img_colors for comp in color], + dtype=np.uint8) + palette24 = ((palette[0::3].astype(np.uint32) << 16) | + (palette[1::3].astype(np.uint32) << 8) | + palette[2::3]) + rgb24 = ((data[:, :, 0].astype(np.uint32) << 16) | + (data[:, :, 1].astype(np.uint32) << 8) | + data[:, :, 2]) + indices = np.argsort(palette24).astype(np.uint8) + rgb8 = indices[np.searchsorted(palette24, rgb24, sorter=indices)] + img = Image.fromarray(rgb8, mode='P') + img.putpalette(palette) + png_data, bit_depth, palette = self._writePng(img) + if bit_depth is None or palette is None: + raise RuntimeError("invalid PNG header") + palette = palette[:num_colors * 3] # Trim padding; remove for Pillow>=9 + obj['ColorSpace'] = [Name('Indexed'), Name('DeviceRGB'), + num_colors - 1, palette] + obj['BitsPerComponent'] = bit_depth + png['Colors'] = 1 + png['BitsPerComponent'] = bit_depth + else: + png_data, _, _ = self._writePng(img) + else: + png = None + self.beginStream( + id, + self.reserveObject('length of image stream'), + obj, + png=png + ) + if png: + self.currentstream.write(png_data) + else: + self.currentstream.write(data.tobytes()) + self.endStream() + + def writeImages(self): + for img, name, ob in self._images.values(): + data, adata = self._unpack(img) + if adata is not None: + smaskObject = self.reserveObject("smask") + self._writeImg(adata, smaskObject.id) + else: + smaskObject = None + self._writeImg(data, ob.id, smaskObject) + + def markerObject(self, path, trans, fill, stroke, lw, joinstyle, + capstyle): + """Return name of a marker XObject representing the given path.""" + # self.markers used by markerObject, writeMarkers, close: + # mapping from (path operations, fill?, stroke?) to + # [name, object reference, bounding box, linewidth] + # This enables different draw_markers calls to share the XObject + # if the gc is sufficiently similar: colors etc can vary, but + # the choices of whether to fill and whether to stroke cannot. + # We need a bounding box enclosing all of the XObject path, + # but since line width may vary, we store the maximum of all + # occurring line widths in self.markers. + # close() is somewhat tightly coupled in that it expects the + # first two components of each value in self.markers to be the + # name and object reference. + pathops = self.pathOperations(path, trans, simplify=False) + key = (tuple(pathops), bool(fill), bool(stroke), joinstyle, capstyle) + result = self.markers.get(key) + if result is None: + name = Name('M%d' % len(self.markers)) + ob = self.reserveObject('marker %d' % len(self.markers)) + bbox = path.get_extents(trans) + self.markers[key] = [name, ob, bbox, lw] + else: + if result[-1] < lw: + result[-1] = lw + name = result[0] + return name + + def writeMarkers(self): + for ((pathops, fill, stroke, joinstyle, capstyle), + (name, ob, bbox, lw)) in self.markers.items(): + # bbox wraps the exact limits of the control points, so half a line + # will appear outside it. If the join style is miter and the line + # is not parallel to the edge, then the line will extend even + # further. From the PDF specification, Section 8.4.3.5, the miter + # limit is miterLength / lineWidth and from Table 52, the default + # is 10. With half the miter length outside, that works out to the + # following padding: + bbox = bbox.padded(lw * 5) + self.beginStream( + ob.id, None, + {'Type': Name('XObject'), 'Subtype': Name('Form'), + 'BBox': list(bbox.extents)}) + self.output(GraphicsContextPdf.joinstyles[joinstyle], + Op.setlinejoin) + self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap) + self.output(*pathops) + self.output(Op.paint_path(fill, stroke)) + self.endStream() + + def pathCollectionObject(self, gc, path, trans, padding, filled, stroked): + name = Name('P%d' % len(self.paths)) + ob = self.reserveObject('path %d' % len(self.paths)) + self.paths.append( + (name, path, trans, ob, gc.get_joinstyle(), gc.get_capstyle(), + padding, filled, stroked)) + return name + + def writePathCollectionTemplates(self): + for (name, path, trans, ob, joinstyle, capstyle, padding, filled, + stroked) in self.paths: + pathops = self.pathOperations(path, trans, simplify=False) + bbox = path.get_extents(trans) + if not np.all(np.isfinite(bbox.extents)): + extents = [0, 0, 0, 0] + else: + bbox = bbox.padded(padding) + extents = list(bbox.extents) + self.beginStream( + ob.id, None, + {'Type': Name('XObject'), 'Subtype': Name('Form'), + 'BBox': extents}) + self.output(GraphicsContextPdf.joinstyles[joinstyle], + Op.setlinejoin) + self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap) + self.output(*pathops) + self.output(Op.paint_path(filled, stroked)) + self.endStream() + + @staticmethod + def pathOperations(path, transform, clip=None, simplify=None, sketch=None): + return [Verbatim(_path.convert_to_string( + path, transform, clip, simplify, sketch, + 6, + [Op.moveto.value, Op.lineto.value, b'', Op.curveto.value, + Op.closepath.value], + True))] + + def writePath(self, path, transform, clip=False, sketch=None): + if clip: + clip = (0.0, 0.0, self.width * 72, self.height * 72) + simplify = path.should_simplify + else: + clip = None + simplify = False + cmds = self.pathOperations(path, transform, clip, simplify=simplify, + sketch=sketch) + self.output(*cmds) + + def reserveObject(self, name=''): + """ + Reserve an ID for an indirect object. + + The name is used for debugging in case we forget to print out + the object with writeObject. + """ + id = next(self._object_seq) + self.xrefTable.append([None, 0, name]) + return Reference(id) + + def recordXref(self, id): + self.xrefTable[id][0] = self.fh.tell() - self.tell_base + + def writeObject(self, object, contents): + self.recordXref(object.id) + object.write(contents, self) + + def writeXref(self): + """Write out the xref table.""" + self.startxref = self.fh.tell() - self.tell_base + self.write(b"xref\n0 %d\n" % len(self.xrefTable)) + for i, (offset, generation, name) in enumerate(self.xrefTable): + if offset is None: + raise AssertionError( + 'No offset for object %d (%s)' % (i, name)) + else: + key = b"f" if name == 'the zero object' else b"n" + text = b"%010d %05d %b \n" % (offset, generation, key) + self.write(text) + + def writeInfoDict(self): + """Write out the info dictionary, checking it for good form""" + + self.infoObject = self.reserveObject('info') + self.writeObject(self.infoObject, self.infoDict) + + def writeTrailer(self): + """Write out the PDF trailer.""" + + self.write(b"trailer\n") + self.write(pdfRepr( + {'Size': len(self.xrefTable), + 'Root': self.rootObject, + 'Info': self.infoObject})) + # Could add 'ID' + self.write(b"\nstartxref\n%d\n%%%%EOF\n" % self.startxref) + + +class RendererPdf(_backend_pdf_ps.RendererPDFPSBase): + + _afm_font_dir = cbook._get_data_path("fonts/pdfcorefonts") + _use_afm_rc_name = "pdf.use14corefonts" + + def __init__(self, file, image_dpi, height, width): + super().__init__(width, height) + self.file = file + self.gc = self.new_gc() + self.image_dpi = image_dpi + + def finalize(self): + self.file.output(*self.gc.finalize()) + + def check_gc(self, gc, fillcolor=None): + orig_fill = getattr(gc, '_fillcolor', (0., 0., 0.)) + gc._fillcolor = fillcolor + + orig_alphas = getattr(gc, '_effective_alphas', (1.0, 1.0)) + + if gc.get_rgb() is None: + # It should not matter what color here since linewidth should be + # 0 unless affected by global settings in rcParams, hence setting + # zero alpha just in case. + gc.set_foreground((0, 0, 0, 0), isRGBA=True) + + if gc._forced_alpha: + gc._effective_alphas = (gc._alpha, gc._alpha) + elif fillcolor is None or len(fillcolor) < 4: + gc._effective_alphas = (gc._rgb[3], 1.0) + else: + gc._effective_alphas = (gc._rgb[3], fillcolor[3]) + + delta = self.gc.delta(gc) + if delta: + self.file.output(*delta) + + # Restore gc to avoid unwanted side effects + gc._fillcolor = orig_fill + gc._effective_alphas = orig_alphas + + def get_image_magnification(self): + return self.image_dpi/72.0 + + def draw_image(self, gc, x, y, im, transform=None): + # docstring inherited + + h, w = im.shape[:2] + if w == 0 or h == 0: + return + + if transform is None: + # If there's no transform, alpha has already been applied + gc.set_alpha(1.0) + + self.check_gc(gc) + + w = 72.0 * w / self.image_dpi + h = 72.0 * h / self.image_dpi + + imob = self.file.imageObject(im) + + if transform is None: + self.file.output(Op.gsave, + w, 0, 0, h, x, y, Op.concat_matrix, + imob, Op.use_xobject, Op.grestore) + else: + tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() + + self.file.output(Op.gsave, + 1, 0, 0, 1, x, y, Op.concat_matrix, + tr1, tr2, tr3, tr4, tr5, tr6, Op.concat_matrix, + imob, Op.use_xobject, Op.grestore) + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + self.check_gc(gc, rgbFace) + self.file.writePath( + path, transform, + rgbFace is None and gc.get_hatch_path() is None, + gc.get_sketch_params()) + self.file.output(self.gc.paint()) + + def draw_path_collection(self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position): + # We can only reuse the objects if the presence of fill and + # stroke (and the amount of alpha for each) is the same for + # all of them + can_do_optimization = True + facecolors = np.asarray(facecolors) + edgecolors = np.asarray(edgecolors) + + if not len(facecolors): + filled = False + can_do_optimization = not gc.get_hatch() + else: + if np.all(facecolors[:, 3] == facecolors[0, 3]): + filled = facecolors[0, 3] != 0.0 + else: + can_do_optimization = False + + if not len(edgecolors): + stroked = False + else: + if np.all(np.asarray(linewidths) == 0.0): + stroked = False + elif np.all(edgecolors[:, 3] == edgecolors[0, 3]): + stroked = edgecolors[0, 3] != 0.0 + else: + can_do_optimization = False + + # Is the optimization worth it? Rough calculation: + # cost of emitting a path in-line is len_path * uses_per_path + # cost of XObject is len_path + 5 for the definition, + # uses_per_path for the uses + len_path = len(paths[0].vertices) if len(paths) > 0 else 0 + uses_per_path = self._iter_collection_uses_per_path( + paths, all_transforms, offsets, facecolors, edgecolors) + should_do_optimization = \ + len_path + uses_per_path + 5 < len_path * uses_per_path + + if (not can_do_optimization) or (not should_do_optimization): + return RendererBase.draw_path_collection( + self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position) + + padding = np.max(linewidths) + path_codes = [] + for i, (path, transform) in enumerate(self._iter_collection_raw_paths( + master_transform, paths, all_transforms)): + name = self.file.pathCollectionObject( + gc, path, transform, padding, filled, stroked) + path_codes.append(name) + + output = self.file.output + output(*self.gc.push()) + lastx, lasty = 0, 0 + for xo, yo, path_id, gc0, rgbFace in self._iter_collection( + gc, path_codes, offsets, offset_trans, + facecolors, edgecolors, linewidths, linestyles, + antialiaseds, urls, offset_position): + + self.check_gc(gc0, rgbFace) + dx, dy = xo - lastx, yo - lasty + output(1, 0, 0, 1, dx, dy, Op.concat_matrix, path_id, + Op.use_xobject) + lastx, lasty = xo, yo + output(*self.gc.pop()) + + def draw_markers(self, gc, marker_path, marker_trans, path, trans, + rgbFace=None): + # docstring inherited + + # Same logic as in draw_path_collection + len_marker_path = len(marker_path) + uses = len(path) + if len_marker_path * uses < len_marker_path + uses + 5: + RendererBase.draw_markers(self, gc, marker_path, marker_trans, + path, trans, rgbFace) + return + + self.check_gc(gc, rgbFace) + fill = gc.fill(rgbFace) + stroke = gc.stroke() + + output = self.file.output + marker = self.file.markerObject( + marker_path, marker_trans, fill, stroke, self.gc._linewidth, + gc.get_joinstyle(), gc.get_capstyle()) + + output(Op.gsave) + lastx, lasty = 0, 0 + for vertices, code in path.iter_segments( + trans, + clip=(0, 0, self.file.width*72, self.file.height*72), + simplify=False): + if len(vertices): + x, y = vertices[-2:] + if not (0 <= x <= self.file.width * 72 + and 0 <= y <= self.file.height * 72): + continue + dx, dy = x - lastx, y - lasty + output(1, 0, 0, 1, dx, dy, Op.concat_matrix, + marker, Op.use_xobject) + lastx, lasty = x, y + output(Op.grestore) + + def draw_gouraud_triangles(self, gc, points, colors, trans): + assert len(points) == len(colors) + if len(points) == 0: + return + assert points.ndim == 3 + assert points.shape[1] == 3 + assert points.shape[2] == 2 + assert colors.ndim == 3 + assert colors.shape[1] == 3 + assert colors.shape[2] in (1, 4) + + shape = points.shape + points = points.reshape((shape[0] * shape[1], 2)) + tpoints = trans.transform(points) + tpoints = tpoints.reshape(shape) + name, _ = self.file.addGouraudTriangles(tpoints, colors) + output = self.file.output + + if colors.shape[2] == 1: + # grayscale + gc.set_alpha(1.0) + self.check_gc(gc) + output(name, Op.shading) + return + + alpha = colors[0, 0, 3] + if np.allclose(alpha, colors[:, :, 3]): + # single alpha value + gc.set_alpha(alpha) + self.check_gc(gc) + output(name, Op.shading) + else: + # varying alpha: use a soft mask + alpha = colors[:, :, 3][:, :, None] + _, smask_ob = self.file.addGouraudTriangles(tpoints, alpha) + gstate = self.file._soft_mask_state(smask_ob) + output(Op.gsave, gstate, Op.setgstate, + name, Op.shading, + Op.grestore) + + def _setup_textpos(self, x, y, angle, oldx=0, oldy=0, oldangle=0): + if angle == oldangle == 0: + self.file.output(x - oldx, y - oldy, Op.textpos) + else: + angle = math.radians(angle) + self.file.output(math.cos(angle), math.sin(angle), + -math.sin(angle), math.cos(angle), + x, y, Op.textmatrix) + self.file.output(0, 0, Op.textpos) + + def draw_mathtext(self, gc, x, y, s, prop, angle): + # TODO: fix positioning and encoding + width, height, descent, glyphs, rects = \ + self._text2path.mathtext_parser.parse(s, 72, prop) + + if gc.get_url() is not None: + self.file._annotations[-1][1].append(_get_link_annotation( + gc, x, y, width, height, angle)) + + fonttype = mpl.rcParams['pdf.fonttype'] + + # Set up a global transformation matrix for the whole math expression + a = math.radians(angle) + self.file.output(Op.gsave) + self.file.output(math.cos(a), math.sin(a), + -math.sin(a), math.cos(a), + x, y, Op.concat_matrix) + + self.check_gc(gc, gc._rgb) + prev_font = None, None + oldx, oldy = 0, 0 + unsupported_chars = [] + + self.file.output(Op.begin_text) + for font, fontsize, num, ox, oy in glyphs: + self.file._character_tracker.track_glyph(font, num) + fontname = font.fname + if not _font_supports_glyph(fonttype, num): + # Unsupported chars (i.e. multibyte in Type 3 or beyond BMP in + # Type 42) must be emitted separately (below). + unsupported_chars.append((font, fontsize, ox, oy, num)) + else: + self._setup_textpos(ox, oy, 0, oldx, oldy) + oldx, oldy = ox, oy + if (fontname, fontsize) != prev_font: + self.file.output(self.file.fontName(fontname), fontsize, + Op.selectfont) + prev_font = fontname, fontsize + self.file.output(self.encode_string(chr(num), fonttype), + Op.show) + self.file.output(Op.end_text) + + for font, fontsize, ox, oy, num in unsupported_chars: + self._draw_xobject_glyph( + font, fontsize, font.get_char_index(num), ox, oy) + + # Draw any horizontal lines in the math layout + for ox, oy, width, height in rects: + self.file.output(Op.gsave, ox, oy, width, height, + Op.rectangle, Op.fill, Op.grestore) + + # Pop off the global transformation + self.file.output(Op.grestore) + + def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): + # docstring inherited + texmanager = self.get_texmanager() + fontsize = prop.get_size_in_points() + dvifile = texmanager.make_dvi(s, fontsize) + with dviread.Dvi(dvifile, 72) as dvi: + page, = dvi + + if gc.get_url() is not None: + self.file._annotations[-1][1].append(_get_link_annotation( + gc, x, y, page.width, page.height, angle)) + + # Gather font information and do some setup for combining + # characters into strings. The variable seq will contain a + # sequence of font and text entries. A font entry is a list + # ['font', name, size] where name is a Name object for the + # font. A text entry is ['text', x, y, glyphs, x+w] where x + # and y are the starting coordinates, w is the width, and + # glyphs is a list; in this phase it will always contain just + # one single-character string, but later it may have longer + # strings interspersed with kern amounts. + oldfont, seq = None, [] + for x1, y1, dvifont, glyph, width in page.text: + if dvifont != oldfont: + pdfname = self.file.dviFontName(dvifont) + seq += [['font', pdfname, dvifont.size]] + oldfont = dvifont + seq += [['text', x1, y1, [bytes([glyph])], x1+width]] + + # Find consecutive text strings with constant y coordinate and + # combine into a sequence of strings and kerns, or just one + # string (if any kerns would be less than 0.1 points). + i, curx, fontsize = 0, 0, None + while i < len(seq)-1: + elt, nxt = seq[i:i+2] + if elt[0] == 'font': + fontsize = elt[2] + elif elt[0] == nxt[0] == 'text' and elt[2] == nxt[2]: + offset = elt[4] - nxt[1] + if abs(offset) < 0.1: + elt[3][-1] += nxt[3][0] + elt[4] += nxt[4]-nxt[1] + else: + elt[3] += [offset*1000.0/fontsize, nxt[3][0]] + elt[4] = nxt[4] + del seq[i+1] + continue + i += 1 + + # Create a transform to map the dvi contents to the canvas. + mytrans = Affine2D().rotate_deg(angle).translate(x, y) + + # Output the text. + self.check_gc(gc, gc._rgb) + self.file.output(Op.begin_text) + curx, cury, oldx, oldy = 0, 0, 0, 0 + for elt in seq: + if elt[0] == 'font': + self.file.output(elt[1], elt[2], Op.selectfont) + elif elt[0] == 'text': + curx, cury = mytrans.transform((elt[1], elt[2])) + self._setup_textpos(curx, cury, angle, oldx, oldy) + oldx, oldy = curx, cury + if len(elt[3]) == 1: + self.file.output(elt[3][0], Op.show) + else: + self.file.output(elt[3], Op.showkern) + else: + assert False + self.file.output(Op.end_text) + + # Then output the boxes (e.g., variable-length lines of square + # roots). + boxgc = self.new_gc() + boxgc.copy_properties(gc) + boxgc.set_linewidth(0) + pathops = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, + Path.CLOSEPOLY] + for x1, y1, h, w in page.boxes: + path = Path([[x1, y1], [x1+w, y1], [x1+w, y1+h], [x1, y1+h], + [0, 0]], pathops) + self.draw_path(boxgc, path, mytrans, gc._rgb) + + def encode_string(self, s, fonttype): + if fonttype in (1, 3): + return s.encode('cp1252', 'replace') + return s.encode('utf-16be', 'replace') + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + # TODO: combine consecutive texts into one BT/ET delimited section + + self.check_gc(gc, gc._rgb) + if ismath: + return self.draw_mathtext(gc, x, y, s, prop, angle) + + fontsize = prop.get_size_in_points() + + if mpl.rcParams['pdf.use14corefonts']: + font = self._get_font_afm(prop) + fonttype = 1 + else: + font = self._get_font_ttf(prop) + self.file._character_tracker.track(font, s) + fonttype = mpl.rcParams['pdf.fonttype'] + + if gc.get_url() is not None: + font.set_text(s) + width, height = font.get_width_height() + self.file._annotations[-1][1].append(_get_link_annotation( + gc, x, y, width / 64, height / 64, angle)) + + # If fonttype is neither 3 nor 42, emit the whole string at once + # without manual kerning. + if fonttype not in [3, 42]: + self.file.output(Op.begin_text, + self.file.fontName(prop), fontsize, Op.selectfont) + self._setup_textpos(x, y, angle) + self.file.output(self.encode_string(s, fonttype), + Op.show, Op.end_text) + + # A sequence of characters is broken into multiple chunks. The chunking + # serves two purposes: + # - For Type 3 fonts, there is no way to access multibyte characters, + # as they cannot have a CIDMap. Therefore, in this case we break + # the string into chunks, where each chunk contains either a string + # of consecutive 1-byte characters or a single multibyte character. + # - A sequence of 1-byte characters is split into chunks to allow for + # kerning adjustments between consecutive chunks. + # + # Each chunk is emitted with a separate command: 1-byte characters use + # the regular text show command (TJ) with appropriate kerning between + # chunks, whereas multibyte characters use the XObject command (Do). + else: + # List of (ft_object, start_x, [prev_kern, char, char, ...]), + # w/o zero kerns. + singlebyte_chunks = [] + # List of (ft_object, start_x, glyph_index). + multibyte_glyphs = [] + prev_was_multibyte = True + prev_font = font + for item in _text_helpers.layout(s, font, kern_mode=KERNING_UNFITTED): + if _font_supports_glyph(fonttype, ord(item.char)): + if prev_was_multibyte or item.ft_object != prev_font: + singlebyte_chunks.append((item.ft_object, item.x, [])) + prev_font = item.ft_object + if item.prev_kern: + singlebyte_chunks[-1][2].append(item.prev_kern) + singlebyte_chunks[-1][2].append(item.char) + prev_was_multibyte = False + else: + multibyte_glyphs.append((item.ft_object, item.x, item.glyph_idx)) + prev_was_multibyte = True + # Do the rotation and global translation as a single matrix + # concatenation up front + self.file.output(Op.gsave) + a = math.radians(angle) + self.file.output(math.cos(a), math.sin(a), + -math.sin(a), math.cos(a), + x, y, Op.concat_matrix) + # Emit all the 1-byte characters in a BT/ET group. + + self.file.output(Op.begin_text) + prev_start_x = 0 + for ft_object, start_x, kerns_or_chars in singlebyte_chunks: + ft_name = self.file.fontName(ft_object.fname) + self.file.output(ft_name, fontsize, Op.selectfont) + self._setup_textpos(start_x, 0, 0, prev_start_x, 0, 0) + self.file.output( + # See pdf spec "Text space details" for the 1000/fontsize + # (aka. 1000/T_fs) factor. + [-1000 * next(group) / fontsize if tp == float # a kern + else self.encode_string("".join(group), fonttype) + for tp, group in itertools.groupby(kerns_or_chars, type)], + Op.showkern) + prev_start_x = start_x + self.file.output(Op.end_text) + # Then emit all the multibyte characters, one at a time. + for ft_object, start_x, glyph_idx in multibyte_glyphs: + self._draw_xobject_glyph( + ft_object, fontsize, glyph_idx, start_x, 0 + ) + self.file.output(Op.grestore) + + def _draw_xobject_glyph(self, font, fontsize, glyph_idx, x, y): + """Draw a multibyte character from a Type 3 font as an XObject.""" + glyph_name = font.get_glyph_name(glyph_idx) + name = self.file._get_xobject_glyph_name(font.fname, glyph_name) + self.file.output( + Op.gsave, + 0.001 * fontsize, 0, 0, 0.001 * fontsize, x, y, Op.concat_matrix, + Name(name), Op.use_xobject, + Op.grestore, + ) + + def new_gc(self): + # docstring inherited + return GraphicsContextPdf(self.file) + + +class GraphicsContextPdf(GraphicsContextBase): + + def __init__(self, file): + super().__init__() + self._fillcolor = (0.0, 0.0, 0.0) + self._effective_alphas = (1.0, 1.0) + self.file = file + self.parent = None + + def __repr__(self): + d = dict(self.__dict__) + del d['file'] + del d['parent'] + return repr(d) + + def stroke(self): + """ + Predicate: does the path need to be stroked (its outline drawn)? + This tests for the various conditions that disable stroking + the path, in which case it would presumably be filled. + """ + # _linewidth > 0: in pdf a line of width 0 is drawn at minimum + # possible device width, but e.g., agg doesn't draw at all + return (self._linewidth > 0 and self._alpha > 0 and + (len(self._rgb) <= 3 or self._rgb[3] != 0.0)) + + def fill(self, *args): + """ + Predicate: does the path need to be filled? + + An optional argument can be used to specify an alternative + _fillcolor, as needed by RendererPdf.draw_markers. + """ + if len(args): + _fillcolor = args[0] + else: + _fillcolor = self._fillcolor + return (self._hatch or + (_fillcolor is not None and + (len(_fillcolor) <= 3 or _fillcolor[3] != 0.0))) + + def paint(self): + """ + Return the appropriate pdf operator to cause the path to be + stroked, filled, or both. + """ + return Op.paint_path(self.fill(), self.stroke()) + + capstyles = {'butt': 0, 'round': 1, 'projecting': 2} + joinstyles = {'miter': 0, 'round': 1, 'bevel': 2} + + def capstyle_cmd(self, style): + return [self.capstyles[style], Op.setlinecap] + + def joinstyle_cmd(self, style): + return [self.joinstyles[style], Op.setlinejoin] + + def linewidth_cmd(self, width): + return [width, Op.setlinewidth] + + def dash_cmd(self, dashes): + offset, dash = dashes + if dash is None: + dash = [] + offset = 0 + return [list(dash), offset, Op.setdash] + + def alpha_cmd(self, alpha, forced, effective_alphas): + name = self.file.alphaState(effective_alphas) + return [name, Op.setgstate] + + def hatch_cmd(self, hatch, hatch_color): + if not hatch: + if self._fillcolor is not None: + return self.fillcolor_cmd(self._fillcolor) + else: + return [Name('DeviceRGB'), Op.setcolorspace_nonstroke] + else: + hatch_style = (hatch_color, self._fillcolor, hatch) + name = self.file.hatchPattern(hatch_style) + return [Name('Pattern'), Op.setcolorspace_nonstroke, + name, Op.setcolor_nonstroke] + + def rgb_cmd(self, rgb): + if mpl.rcParams['pdf.inheritcolor']: + return [] + if rgb[0] == rgb[1] == rgb[2]: + return [rgb[0], Op.setgray_stroke] + else: + return [*rgb[:3], Op.setrgb_stroke] + + def fillcolor_cmd(self, rgb): + if rgb is None or mpl.rcParams['pdf.inheritcolor']: + return [] + elif rgb[0] == rgb[1] == rgb[2]: + return [rgb[0], Op.setgray_nonstroke] + else: + return [*rgb[:3], Op.setrgb_nonstroke] + + def push(self): + parent = GraphicsContextPdf(self.file) + parent.copy_properties(self) + parent.parent = self.parent + self.parent = parent + return [Op.gsave] + + def pop(self): + assert self.parent is not None + self.copy_properties(self.parent) + self.parent = self.parent.parent + return [Op.grestore] + + def clip_cmd(self, cliprect, clippath): + """Set clip rectangle. Calls `.pop()` and `.push()`.""" + cmds = [] + # Pop graphics state until we hit the right one or the stack is empty + while ((self._cliprect, self._clippath) != (cliprect, clippath) + and self.parent is not None): + cmds.extend(self.pop()) + # Unless we hit the right one, set the clip polygon + if ((self._cliprect, self._clippath) != (cliprect, clippath) or + self.parent is None): + cmds.extend(self.push()) + if self._cliprect != cliprect: + cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath]) + if self._clippath != clippath: + path, affine = clippath.get_transformed_path_and_affine() + cmds.extend( + PdfFile.pathOperations(path, affine, simplify=False) + + [Op.clip, Op.endpath]) + return cmds + + commands = ( + # must come first since may pop + (('_cliprect', '_clippath'), clip_cmd), + (('_alpha', '_forced_alpha', '_effective_alphas'), alpha_cmd), + (('_capstyle',), capstyle_cmd), + (('_fillcolor',), fillcolor_cmd), + (('_joinstyle',), joinstyle_cmd), + (('_linewidth',), linewidth_cmd), + (('_dashes',), dash_cmd), + (('_rgb',), rgb_cmd), + # must come after fillcolor and rgb + (('_hatch', '_hatch_color'), hatch_cmd), + ) + + def delta(self, other): + """ + Copy properties of other into self and return PDF commands + needed to transform *self* into *other*. + """ + cmds = [] + fill_performed = False + for params, cmd in self.commands: + different = False + for p in params: + ours = getattr(self, p) + theirs = getattr(other, p) + try: + if ours is None or theirs is None: + different = ours is not theirs + else: + different = bool(ours != theirs) + except ValueError: + ours = np.asarray(ours) + theirs = np.asarray(theirs) + different = (ours.shape != theirs.shape or + np.any(ours != theirs)) + if different: + break + + # Need to update hatching if we also updated fillcolor + if params == ('_hatch', '_hatch_color') and fill_performed: + different = True + + if different: + if params == ('_fillcolor',): + fill_performed = True + theirs = [getattr(other, p) for p in params] + cmds.extend(cmd(self, *theirs)) + for p in params: + setattr(self, p, getattr(other, p)) + return cmds + + def copy_properties(self, other): + """ + Copy properties of other into self. + """ + super().copy_properties(other) + fillcolor = getattr(other, '_fillcolor', self._fillcolor) + effective_alphas = getattr(other, '_effective_alphas', + self._effective_alphas) + self._fillcolor = fillcolor + self._effective_alphas = effective_alphas + + def finalize(self): + """ + Make sure every pushed graphics state is popped. + """ + cmds = [] + while self.parent is not None: + cmds.extend(self.pop()) + return cmds + + +class PdfPages: + """ + A multi-page PDF file. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> # Initialize: + >>> with PdfPages('foo.pdf') as pdf: + ... # As many times as you like, create a figure fig and save it: + ... fig = plt.figure() + ... pdf.savefig(fig) + ... # When no figure is specified the current figure is saved + ... pdf.savefig() + + Notes + ----- + In reality `PdfPages` is a thin wrapper around `PdfFile`, in order to avoid + confusion when using `~.pyplot.savefig` and forgetting the format argument. + """ + + _UNSET = object() + + def __init__(self, filename, keep_empty=_UNSET, metadata=None): + """ + Create a new PdfPages object. + + Parameters + ---------- + filename : str or path-like or file-like + Plots using `PdfPages.savefig` will be written to a file at this location. + The file is opened when a figure is saved for the first time (overwriting + any older file with the same name). + + keep_empty : bool, optional + If set to False, then empty pdf files will be deleted automatically + when closed. + + metadata : dict, optional + Information dictionary object (see PDF reference section 10.2.1 + 'Document Information Dictionary'), e.g.: + ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``. + + The standard keys are 'Title', 'Author', 'Subject', 'Keywords', + 'Creator', 'Producer', 'CreationDate', 'ModDate', and + 'Trapped'. Values have been predefined for 'Creator', 'Producer' + and 'CreationDate'. They can be removed by setting them to `None`. + """ + self._filename = filename + self._metadata = metadata + self._file = None + if keep_empty and keep_empty is not self._UNSET: + _api.warn_deprecated("3.8", message=( + "Keeping empty pdf files is deprecated since %(since)s and support " + "will be removed %(removal)s.")) + self._keep_empty = keep_empty + + keep_empty = _api.deprecate_privatize_attribute("3.8") + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def _ensure_file(self): + if self._file is None: + self._file = PdfFile(self._filename, metadata=self._metadata) # init. + return self._file + + def close(self): + """ + Finalize this object, making the underlying file a complete + PDF file. + """ + if self._file is not None: + self._file.finalize() + self._file.close() + self._file = None + elif self._keep_empty: # True *or* UNSET. + _api.warn_deprecated("3.8", message=( + "Keeping empty pdf files is deprecated since %(since)s and support " + "will be removed %(removal)s.")) + PdfFile(self._filename, metadata=self._metadata).close() # touch the file. + + def infodict(self): + """ + Return a modifiable information dictionary object + (see PDF reference section 10.2.1 'Document Information + Dictionary'). + """ + return self._ensure_file().infoDict + + def savefig(self, figure=None, **kwargs): + """ + Save a `.Figure` to this file as a new page. + + Any other keyword arguments are passed to `~.Figure.savefig`. + + Parameters + ---------- + figure : `.Figure` or int, default: the active figure + The figure, or index of the figure, that is saved to the file. + """ + if not isinstance(figure, Figure): + if figure is None: + manager = Gcf.get_active() + else: + manager = Gcf.get_fig_manager(figure) + if manager is None: + raise ValueError(f"No figure {figure}") + figure = manager.canvas.figure + # Force use of pdf backend, as PdfPages is tightly coupled with it. + figure.savefig(self, format="pdf", backend="pdf", **kwargs) + + def get_pagecount(self): + """Return the current number of pages in the multipage pdf file.""" + return len(self._ensure_file().pageList) + + def attach_note(self, text, positionRect=[-100, -100, 0, 0]): + """ + Add a new text note to the page to be saved next. The optional + positionRect specifies the position of the new note on the + page. It is outside the page per default to make sure it is + invisible on printouts. + """ + self._ensure_file().newTextnote(text, positionRect) + + +class FigureCanvasPdf(FigureCanvasBase): + # docstring inherited + + fixed_dpi = 72 + filetypes = {'pdf': 'Portable Document Format'} + + def get_default_filetype(self): + return 'pdf' + + def print_pdf(self, filename, *, + bbox_inches_restore=None, metadata=None): + + dpi = self.figure.dpi + self.figure.dpi = 72 # there are 72 pdf points to an inch + width, height = self.figure.get_size_inches() + if isinstance(filename, PdfPages): + file = filename._ensure_file() + else: + file = PdfFile(filename, metadata=metadata) + try: + file.newPage(width, height) + renderer = MixedModeRenderer( + self.figure, width, height, dpi, + RendererPdf(file, dpi, height, width), + bbox_inches_restore=bbox_inches_restore) + self.figure.draw(renderer) + renderer.finalize() + if not isinstance(filename, PdfPages): + file.finalize() + finally: + if isinstance(filename, PdfPages): # finish off this page + file.endStream() + else: # we opened the file above; now finish it off + file.close() + + def draw(self): + self.figure.draw_without_rendering() + return super().draw() + + +FigureManagerPdf = FigureManagerBase + + +@_Backend.export +class _BackendPdf(_Backend): + FigureCanvas = FigureCanvasPdf diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_ps.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_ps.py new file mode 100644 index 0000000000000000000000000000000000000000..5f224f38af1e14cf6adebc3188cb4f1890c391b7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_ps.py @@ -0,0 +1,1326 @@ +""" +A PostScript backend, which can produce both PostScript .ps and .eps. +""" + +import codecs +import datetime +from enum import Enum +import functools +from io import StringIO +import itertools +import logging +import math +import os +import pathlib +import shutil +from tempfile import TemporaryDirectory +import time + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, _path, _text_helpers +from matplotlib._afm import AFM +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) +from matplotlib.cbook import is_writable_file_like, file_requires_unicode +from matplotlib.font_manager import get_font +from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font +from matplotlib._ttconv import convert_ttf_to_ps +from matplotlib._mathtext_data import uni2type1 +from matplotlib.path import Path +from matplotlib.texmanager import TexManager +from matplotlib.transforms import Affine2D +from matplotlib.backends.backend_mixed import MixedModeRenderer +from . import _backend_pdf_ps + + +_log = logging.getLogger(__name__) +debugPS = False + + +@_api.caching_module_getattr +class __getattr__: + # module-level deprecations + psDefs = _api.deprecated("3.8", obj_type="")(property(lambda self: _psDefs)) + + +papersize = {'letter': (8.5, 11), + 'legal': (8.5, 14), + 'ledger': (11, 17), + 'a0': (33.11, 46.81), + 'a1': (23.39, 33.11), + 'a2': (16.54, 23.39), + 'a3': (11.69, 16.54), + 'a4': (8.27, 11.69), + 'a5': (5.83, 8.27), + 'a6': (4.13, 5.83), + 'a7': (2.91, 4.13), + 'a8': (2.05, 2.91), + 'a9': (1.46, 2.05), + 'a10': (1.02, 1.46), + 'b0': (40.55, 57.32), + 'b1': (28.66, 40.55), + 'b2': (20.27, 28.66), + 'b3': (14.33, 20.27), + 'b4': (10.11, 14.33), + 'b5': (7.16, 10.11), + 'b6': (5.04, 7.16), + 'b7': (3.58, 5.04), + 'b8': (2.51, 3.58), + 'b9': (1.76, 2.51), + 'b10': (1.26, 1.76)} + + +def _get_papertype(w, h): + for key, (pw, ph) in sorted(papersize.items(), reverse=True): + if key.startswith('l'): + continue + if w < pw and h < ph: + return key + return 'a0' + + +def _nums_to_str(*args, sep=" "): + return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args) + + +def _move_path_to_path_or_stream(src, dst): + """ + Move the contents of file at *src* to path-or-filelike *dst*. + + If *dst* is a path, the metadata of *src* are *not* copied. + """ + if is_writable_file_like(dst): + fh = (open(src, encoding='latin-1') + if file_requires_unicode(dst) + else open(src, 'rb')) + with fh: + shutil.copyfileobj(fh, dst) + else: + shutil.move(src, dst, copy_function=shutil.copyfile) + + +def _font_to_ps_type3(font_path, chars): + """ + Subset *chars* from the font at *font_path* into a Type 3 font. + + Parameters + ---------- + font_path : path-like + Path to the font to be subsetted. + chars : str + The characters to include in the subsetted font. + + Returns + ------- + str + The string representation of a Type 3 font, which can be included + verbatim into a PostScript file. + """ + font = get_font(font_path, hinting_factor=1) + glyph_ids = [font.get_char_index(c) for c in chars] + + preamble = """\ +%!PS-Adobe-3.0 Resource-Font +%%Creator: Converted from TrueType to Type 3 by Matplotlib. +10 dict begin +/FontName /{font_name} def +/PaintType 0 def +/FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def +/FontBBox [{bbox}] def +/FontType 3 def +/Encoding [{encoding}] def +/CharStrings {num_glyphs} dict dup begin +/.notdef 0 def +""".format(font_name=font.postscript_name, + inv_units_per_em=1 / font.units_per_EM, + bbox=" ".join(map(str, font.bbox)), + encoding=" ".join(f"/{font.get_glyph_name(glyph_id)}" + for glyph_id in glyph_ids), + num_glyphs=len(glyph_ids) + 1) + postamble = """ +end readonly def + +/BuildGlyph { + exch begin + CharStrings exch + 2 copy known not {pop /.notdef} if + true 3 1 roll get exec + end +} _d + +/BuildChar { + 1 index /Encoding get exch get + 1 index /BuildGlyph get exec +} _d + +FontName currentdict end definefont pop +""" + + entries = [] + for glyph_id in glyph_ids: + g = font.load_glyph(glyph_id, LOAD_NO_SCALE) + v, c = font.get_path() + entries.append( + "/%(name)s{%(bbox)s sc\n" % { + "name": font.get_glyph_name(glyph_id), + "bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])), + } + + _path.convert_to_string( + # Convert back to TrueType's internal units (1/64's). + # (Other dimensions are already in these units.) + Path(v * 64, c), None, None, False, None, 0, + # No code for quad Beziers triggers auto-conversion to cubics. + # Drop intermediate closepolys (relying on the outline + # decomposer always explicitly moving to the closing point + # first). + [b"m", b"l", b"", b"c", b""], True).decode("ascii") + + "ce} _d" + ) + + return preamble + "\n".join(entries) + postamble + + +def _font_to_ps_type42(font_path, chars, fh): + """ + Subset *chars* from the font at *font_path* into a Type 42 font at *fh*. + + Parameters + ---------- + font_path : path-like + Path to the font to be subsetted. + chars : str + The characters to include in the subsetted font. + fh : file-like + Where to write the font. + """ + subset_str = ''.join(chr(c) for c in chars) + _log.debug("SUBSET %s characters: %s", font_path, subset_str) + try: + fontdata = _backend_pdf_ps.get_glyphs_subset(font_path, subset_str) + _log.debug("SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size, + fontdata.getbuffer().nbytes) + + # Give ttconv a subsetted font along with updated glyph_ids. + font = FT2Font(fontdata) + glyph_ids = [font.get_char_index(c) for c in chars] + with TemporaryDirectory() as tmpdir: + tmpfile = os.path.join(tmpdir, "tmp.ttf") + + with open(tmpfile, 'wb') as tmp: + tmp.write(fontdata.getvalue()) + + # TODO: allow convert_ttf_to_ps to input file objects (BytesIO) + convert_ttf_to_ps(os.fsencode(tmpfile), fh, 42, glyph_ids) + except RuntimeError: + _log.warning( + "The PostScript backend does not currently " + "support the selected font.") + raise + + +def _log_if_debug_on(meth): + """ + Wrap `RendererPS` method *meth* to emit a PS comment with the method name, + if the global flag `debugPS` is set. + """ + @functools.wraps(meth) + def wrapper(self, *args, **kwargs): + if debugPS: + self._pswriter.write(f"% {meth.__name__}\n") + return meth(self, *args, **kwargs) + + return wrapper + + +class RendererPS(_backend_pdf_ps.RendererPDFPSBase): + """ + The renderer handles all the drawing primitives using a graphics + context instance that controls the colors/styles. + """ + + _afm_font_dir = cbook._get_data_path("fonts/afm") + _use_afm_rc_name = "ps.useafm" + + def __init__(self, width, height, pswriter, imagedpi=72): + # Although postscript itself is dpi independent, we need to inform the + # image code about a requested dpi to generate high resolution images + # and them scale them before embedding them. + super().__init__(width, height) + self._pswriter = pswriter + if mpl.rcParams['text.usetex']: + self.textcnt = 0 + self.psfrag = [] + self.imagedpi = imagedpi + + # current renderer state (None=uninitialised) + self.color = None + self.linewidth = None + self.linejoin = None + self.linecap = None + self.linedash = None + self.fontname = None + self.fontsize = None + self._hatches = {} + self.image_magnification = imagedpi / 72 + self._clip_paths = {} + self._path_collection_id = 0 + + self._character_tracker = _backend_pdf_ps.CharacterTracker() + self._logwarn_once = functools.cache(_log.warning) + + def _is_transparent(self, rgb_or_rgba): + if rgb_or_rgba is None: + return True # Consistent with rgbFace semantics. + elif len(rgb_or_rgba) == 4: + if rgb_or_rgba[3] == 0: + return True + if rgb_or_rgba[3] != 1: + self._logwarn_once( + "The PostScript backend does not support transparency; " + "partially transparent artists will be rendered opaque.") + return False + else: # len() == 3. + return False + + def set_color(self, r, g, b, store=True): + if (r, g, b) != self.color: + self._pswriter.write(f"{_nums_to_str(r)} setgray\n" + if r == g == b else + f"{_nums_to_str(r, g, b)} setrgbcolor\n") + if store: + self.color = (r, g, b) + + def set_linewidth(self, linewidth, store=True): + linewidth = float(linewidth) + if linewidth != self.linewidth: + self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n") + if store: + self.linewidth = linewidth + + @staticmethod + def _linejoin_cmd(linejoin): + # Support for directly passing integer values is for backcompat. + linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[ + linejoin] + return f"{linejoin:d} setlinejoin\n" + + def set_linejoin(self, linejoin, store=True): + if linejoin != self.linejoin: + self._pswriter.write(self._linejoin_cmd(linejoin)) + if store: + self.linejoin = linejoin + + @staticmethod + def _linecap_cmd(linecap): + # Support for directly passing integer values is for backcompat. + linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[ + linecap] + return f"{linecap:d} setlinecap\n" + + def set_linecap(self, linecap, store=True): + if linecap != self.linecap: + self._pswriter.write(self._linecap_cmd(linecap)) + if store: + self.linecap = linecap + + def set_linedash(self, offset, seq, store=True): + if self.linedash is not None: + oldo, oldseq = self.linedash + if np.array_equal(seq, oldseq) and oldo == offset: + return + + self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n" + if seq is not None and len(seq) else + "[] 0 setdash\n") + if store: + self.linedash = (offset, seq) + + def set_font(self, fontname, fontsize, store=True): + if (fontname, fontsize) != (self.fontname, self.fontsize): + self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n") + if store: + self.fontname = fontname + self.fontsize = fontsize + + def create_hatch(self, hatch): + sidelen = 72 + if hatch in self._hatches: + return self._hatches[hatch] + name = 'H%d' % len(self._hatches) + linewidth = mpl.rcParams['hatch.linewidth'] + pageheight = self.height * 72 + self._pswriter.write(f"""\ + << /PatternType 1 + /PaintType 2 + /TilingType 2 + /BBox[0 0 {sidelen:d} {sidelen:d}] + /XStep {sidelen:d} + /YStep {sidelen:d} + + /PaintProc {{ + pop + {linewidth:g} setlinewidth +{self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)} + gsave + fill + grestore + stroke + }} bind + >> + matrix + 0 {pageheight:g} translate + makepattern + /{name} exch def +""") + self._hatches[hatch] = name + return name + + def get_image_magnification(self): + """ + Get the factor by which to magnify images passed to draw_image. + Allows a backend to have images at a different resolution to other + artists. + """ + return self.image_magnification + + def _convert_path(self, path, transform, clip=False, simplify=None): + if clip: + clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0) + else: + clip = None + return _path.convert_to_string( + path, transform, clip, simplify, None, + 6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii") + + def _get_clip_cmd(self, gc): + clip = [] + rect = gc.get_clip_rectangle() + if rect is not None: + clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n") + path, trf = gc.get_clip_path() + if path is not None: + key = (path, id(trf)) + custom_clip_cmd = self._clip_paths.get(key) + if custom_clip_cmd is None: + custom_clip_cmd = "c%d" % len(self._clip_paths) + self._pswriter.write(f"""\ +/{custom_clip_cmd} {{ +{self._convert_path(path, trf, simplify=False)} +clip +newpath +}} bind def +""") + self._clip_paths[key] = custom_clip_cmd + clip.append(f"{custom_clip_cmd}\n") + return "".join(clip) + + @_log_if_debug_on + def draw_image(self, gc, x, y, im, transform=None): + # docstring inherited + + h, w = im.shape[:2] + imagecmd = "false 3 colorimage" + data = im[::-1, :, :3] # Vertically flipped rgb values. + hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars. + + if transform is None: + matrix = "1 0 0 1 0 0" + xscale = w / self.image_magnification + yscale = h / self.image_magnification + else: + matrix = " ".join(map(str, transform.frozen().to_values())) + xscale = 1.0 + yscale = 1.0 + + self._pswriter.write(f"""\ +gsave +{self._get_clip_cmd(gc)} +{x:g} {y:g} translate +[{matrix}] concat +{xscale:g} {yscale:g} scale +/DataString {w:d} string def +{w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ] +{{ +currentfile DataString readhexstring pop +}} bind {imagecmd} +{hexdata} +grestore +""") + + @_log_if_debug_on + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + clip = rgbFace is None and gc.get_hatch_path() is None + simplify = path.should_simplify and clip + ps = self._convert_path(path, transform, clip=clip, simplify=simplify) + self._draw_ps(ps, gc, rgbFace) + + @_log_if_debug_on + def draw_markers( + self, gc, marker_path, marker_trans, path, trans, rgbFace=None): + # docstring inherited + + ps_color = ( + None + if self._is_transparent(rgbFace) + else f'{_nums_to_str(rgbFace[0])} setgray' + if rgbFace[0] == rgbFace[1] == rgbFace[2] + else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor') + + # construct the generic marker command: + + # don't want the translate to be global + ps_cmd = ['/o {', 'gsave', 'newpath', 'translate'] + + lw = gc.get_linewidth() + alpha = (gc.get_alpha() + if gc.get_forced_alpha() or len(gc.get_rgb()) == 3 + else gc.get_rgb()[3]) + stroke = lw > 0 and alpha > 0 + if stroke: + ps_cmd.append('%.1f setlinewidth' % lw) + ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle())) + ps_cmd.append(self._linecap_cmd(gc.get_capstyle())) + + ps_cmd.append(self._convert_path(marker_path, marker_trans, + simplify=False)) + + if rgbFace: + if stroke: + ps_cmd.append('gsave') + if ps_color: + ps_cmd.extend([ps_color, 'fill']) + if stroke: + ps_cmd.append('grestore') + + if stroke: + ps_cmd.append('stroke') + ps_cmd.extend(['grestore', '} bind def']) + + for vertices, code in path.iter_segments( + trans, + clip=(0, 0, self.width*72, self.height*72), + simplify=False): + if len(vertices): + x, y = vertices[-2:] + ps_cmd.append(f"{x:g} {y:g} o") + + ps = '\n'.join(ps_cmd) + self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False) + + @_log_if_debug_on + def draw_path_collection(self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position): + # Is the optimization worth it? Rough calculation: + # cost of emitting a path in-line is + # (len_path + 2) * uses_per_path + # cost of definition+use is + # (len_path + 3) + 3 * uses_per_path + len_path = len(paths[0].vertices) if len(paths) > 0 else 0 + uses_per_path = self._iter_collection_uses_per_path( + paths, all_transforms, offsets, facecolors, edgecolors) + should_do_optimization = \ + len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path + if not should_do_optimization: + return RendererBase.draw_path_collection( + self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position) + + path_codes = [] + for i, (path, transform) in enumerate(self._iter_collection_raw_paths( + master_transform, paths, all_transforms)): + name = 'p%d_%d' % (self._path_collection_id, i) + path_bytes = self._convert_path(path, transform, simplify=False) + self._pswriter.write(f"""\ +/{name} {{ +newpath +translate +{path_bytes} +}} bind def +""") + path_codes.append(name) + + for xo, yo, path_id, gc0, rgbFace in self._iter_collection( + gc, path_codes, offsets, offset_trans, + facecolors, edgecolors, linewidths, linestyles, + antialiaseds, urls, offset_position): + ps = f"{xo:g} {yo:g} {path_id}" + self._draw_ps(ps, gc0, rgbFace) + + self._path_collection_id += 1 + + @_log_if_debug_on + def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): + # docstring inherited + if self._is_transparent(gc.get_rgb()): + return # Special handling for fully transparent. + + if not hasattr(self, "psfrag"): + self._logwarn_once( + "The PS backend determines usetex status solely based on " + "rcParams['text.usetex'] and does not support having " + "usetex=True only for some elements; this element will thus " + "be rendered as if usetex=False.") + self.draw_text(gc, x, y, s, prop, angle, False, mtext) + return + + w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX") + fontsize = prop.get_size_in_points() + thetext = 'psmarker%d' % self.textcnt + color = _nums_to_str(*gc.get_rgb()[:3], sep=',') + fontcmd = {'sans-serif': r'{\sffamily %s}', + 'monospace': r'{\ttfamily %s}'}.get( + mpl.rcParams['font.family'][0], r'{\rmfamily %s}') + s = fontcmd % s + tex = r'\color[rgb]{%s} %s' % (color, s) + + # Stick to bottom-left alignment, so subtract descent from the text-normal + # direction since text is normally positioned by its baseline. + rangle = np.radians(angle + 90) + pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle)) + self.psfrag.append( + r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % ( + thetext, angle, fontsize, fontsize*1.25, tex)) + + self._pswriter.write(f"""\ +gsave +{pos} moveto +({thetext}) +show +grestore +""") + self.textcnt += 1 + + @_log_if_debug_on + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + if self._is_transparent(gc.get_rgb()): + return # Special handling for fully transparent. + + if ismath == 'TeX': + return self.draw_tex(gc, x, y, s, prop, angle) + + if ismath: + return self.draw_mathtext(gc, x, y, s, prop, angle) + + stream = [] # list of (ps_name, x, char_name) + + if mpl.rcParams['ps.useafm']: + font = self._get_font_afm(prop) + ps_name = (font.postscript_name.encode("ascii", "replace") + .decode("ascii")) + scale = 0.001 * prop.get_size_in_points() + thisx = 0 + last_name = None # kerns returns 0 for None. + for c in s: + name = uni2type1.get(ord(c), f"uni{ord(c):04X}") + try: + width = font.get_width_from_char_name(name) + except KeyError: + name = 'question' + width = font.get_width_char('?') + kern = font.get_kern_dist_from_name(last_name, name) + last_name = name + thisx += kern * scale + stream.append((ps_name, thisx, name)) + thisx += width * scale + + else: + font = self._get_font_ttf(prop) + self._character_tracker.track(font, s) + for item in _text_helpers.layout(s, font): + ps_name = (item.ft_object.postscript_name + .encode("ascii", "replace").decode("ascii")) + glyph_name = item.ft_object.get_glyph_name(item.glyph_idx) + stream.append((ps_name, item.x, glyph_name)) + self.set_color(*gc.get_rgb()) + + for ps_name, group in itertools. \ + groupby(stream, lambda entry: entry[0]): + self.set_font(ps_name, prop.get_size_in_points(), False) + thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow" + for _, x, name in group) + self._pswriter.write(f"""\ +gsave +{self._get_clip_cmd(gc)} +{x:g} {y:g} translate +{angle:g} rotate +{thetext} +grestore +""") + + @_log_if_debug_on + def draw_mathtext(self, gc, x, y, s, prop, angle): + """Draw the math text using matplotlib.mathtext.""" + width, height, descent, glyphs, rects = \ + self._text2path.mathtext_parser.parse(s, 72, prop) + self.set_color(*gc.get_rgb()) + self._pswriter.write( + f"gsave\n" + f"{x:g} {y:g} translate\n" + f"{angle:g} rotate\n") + lastfont = None + for font, fontsize, num, ox, oy in glyphs: + self._character_tracker.track_glyph(font, num) + if (font.postscript_name, fontsize) != lastfont: + lastfont = font.postscript_name, fontsize + self._pswriter.write( + f"/{font.postscript_name} {fontsize} selectfont\n") + glyph_name = ( + font.get_name_char(chr(num)) if isinstance(font, AFM) else + font.get_glyph_name(font.get_char_index(num))) + self._pswriter.write( + f"{ox:g} {oy:g} moveto\n" + f"/{glyph_name} glyphshow\n") + for ox, oy, w, h in rects: + self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n") + self._pswriter.write("grestore\n") + + @_log_if_debug_on + def draw_gouraud_triangles(self, gc, points, colors, trans): + assert len(points) == len(colors) + if len(points) == 0: + return + assert points.ndim == 3 + assert points.shape[1] == 3 + assert points.shape[2] == 2 + assert colors.ndim == 3 + assert colors.shape[1] == 3 + assert colors.shape[2] == 4 + + shape = points.shape + flat_points = points.reshape((shape[0] * shape[1], 2)) + flat_points = trans.transform(flat_points) + flat_colors = colors.reshape((shape[0] * shape[1], 4)) + points_min = np.min(flat_points, axis=0) - (1 << 12) + points_max = np.max(flat_points, axis=0) + (1 << 12) + factor = np.ceil((2 ** 32 - 1) / (points_max - points_min)) + + xmin, ymin = points_min + xmax, ymax = points_max + + data = np.empty( + shape[0] * shape[1], + dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')]) + data['flags'] = 0 + data['points'] = (flat_points - points_min) * factor + data['colors'] = flat_colors[:, :3] * 255.0 + hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars. + + self._pswriter.write(f"""\ +gsave +<< /ShadingType 4 + /ColorSpace [/DeviceRGB] + /BitsPerCoordinate 32 + /BitsPerComponent 8 + /BitsPerFlag 8 + /AntiAlias true + /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ] + /DataSource < +{hexdata} +> +>> +shfill +grestore +""") + + def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True): + """ + Emit the PostScript snippet *ps* with all the attributes from *gc* + applied. *ps* must consist of PostScript commands to construct a path. + + The *fill* and/or *stroke* kwargs can be set to False if the *ps* + string already includes filling and/or stroking, in which case + `_draw_ps` is just supplying properties and clipping. + """ + write = self._pswriter.write + mightstroke = (gc.get_linewidth() > 0 + and not self._is_transparent(gc.get_rgb())) + if not mightstroke: + stroke = False + if self._is_transparent(rgbFace): + fill = False + hatch = gc.get_hatch() + + if mightstroke: + self.set_linewidth(gc.get_linewidth()) + self.set_linejoin(gc.get_joinstyle()) + self.set_linecap(gc.get_capstyle()) + self.set_linedash(*gc.get_dashes()) + if mightstroke or hatch: + self.set_color(*gc.get_rgb()[:3]) + write('gsave\n') + + write(self._get_clip_cmd(gc)) + + write(ps.strip()) + write("\n") + + if fill: + if stroke or hatch: + write("gsave\n") + self.set_color(*rgbFace[:3], store=False) + write("fill\n") + if stroke or hatch: + write("grestore\n") + + if hatch: + hatch_name = self.create_hatch(hatch) + write("gsave\n") + write(_nums_to_str(*gc.get_hatch_color()[:3])) + write(f" {hatch_name} setpattern fill grestore\n") + + if stroke: + write("stroke\n") + + write("grestore\n") + + +class _Orientation(Enum): + portrait, landscape = range(2) + + def swap_if_landscape(self, shape): + return shape[::-1] if self.name == "landscape" else shape + + +class FigureCanvasPS(FigureCanvasBase): + fixed_dpi = 72 + filetypes = {'ps': 'Postscript', + 'eps': 'Encapsulated Postscript'} + + def get_default_filetype(self): + return 'ps' + + def _print_ps( + self, fmt, outfile, *, + metadata=None, papertype=None, orientation='portrait', + bbox_inches_restore=None, **kwargs): + + dpi = self.figure.dpi + self.figure.dpi = 72 # Override the dpi kwarg + + dsc_comments = {} + if isinstance(outfile, (str, os.PathLike)): + filename = pathlib.Path(outfile).name + dsc_comments["Title"] = \ + filename.encode("ascii", "replace").decode("ascii") + dsc_comments["Creator"] = (metadata or {}).get( + "Creator", + f"Matplotlib v{mpl.__version__}, https://matplotlib.org/") + # See https://reproducible-builds.org/specs/source-date-epoch/ + source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") + dsc_comments["CreationDate"] = ( + datetime.datetime.fromtimestamp( + int(source_date_epoch), + datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y") + if source_date_epoch + else time.ctime()) + dsc_comments = "\n".join( + f"%%{k}: {v}" for k, v in dsc_comments.items()) + + if papertype is None: + papertype = mpl.rcParams['ps.papersize'] + papertype = papertype.lower() + _api.check_in_list(['figure', 'auto', *papersize], papertype=papertype) + + orientation = _api.check_getitem( + _Orientation, orientation=orientation.lower()) + + printer = (self._print_figure_tex + if mpl.rcParams['text.usetex'] else + self._print_figure) + printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments, + orientation=orientation, papertype=papertype, + bbox_inches_restore=bbox_inches_restore, **kwargs) + + def _print_figure( + self, fmt, outfile, *, + dpi, dsc_comments, orientation, papertype, + bbox_inches_restore=None): + """ + Render the figure to a filesystem path or a file-like object. + + Parameters are as for `.print_figure`, except that *dsc_comments* is a + string containing Document Structuring Convention comments, + generated from the *metadata* parameter to `.print_figure`. + """ + is_eps = fmt == 'eps' + if not (isinstance(outfile, (str, os.PathLike)) + or is_writable_file_like(outfile)): + raise ValueError("outfile must be a path or a file-like object") + + # find the appropriate papertype + width, height = self.figure.get_size_inches() + if papertype == 'auto': + papertype = _get_papertype(*orientation.swap_if_landscape((width, height))) + + if is_eps or papertype == 'figure': + paper_width, paper_height = width, height + else: + paper_width, paper_height = orientation.swap_if_landscape( + papersize[papertype]) + + # center the figure on the paper + xo = 72 * 0.5 * (paper_width - width) + yo = 72 * 0.5 * (paper_height - height) + + llx = xo + lly = yo + urx = llx + self.figure.bbox.width + ury = lly + self.figure.bbox.height + rotation = 0 + if orientation is _Orientation.landscape: + llx, lly, urx, ury = lly, llx, ury, urx + xo, yo = 72 * paper_height - yo, xo + rotation = 90 + bbox = (llx, lly, urx, ury) + + self._pswriter = StringIO() + + # mixed mode rendering + ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) + renderer = MixedModeRenderer( + self.figure, width, height, dpi, ps_renderer, + bbox_inches_restore=bbox_inches_restore) + + self.figure.draw(renderer) + + def print_figure_impl(fh): + # write the PostScript headers + if is_eps: + print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) + else: + print("%!PS-Adobe-3.0", file=fh) + if papertype != 'figure': + print(f"%%DocumentPaperSizes: {papertype}", file=fh) + print("%%Pages: 1", file=fh) + print(f"%%LanguageLevel: 3\n" + f"{dsc_comments}\n" + f"%%Orientation: {orientation.name}\n" + f"{_get_bbox_header(bbox)}\n" + f"%%EndComments\n", + end="", file=fh) + + Ndict = len(_psDefs) + print("%%BeginProlog", file=fh) + if not mpl.rcParams['ps.useafm']: + Ndict += len(ps_renderer._character_tracker.used) + print("/mpldict %d dict def" % Ndict, file=fh) + print("mpldict begin", file=fh) + print("\n".join(_psDefs), file=fh) + if not mpl.rcParams['ps.useafm']: + for font_path, chars \ + in ps_renderer._character_tracker.used.items(): + if not chars: + continue + fonttype = mpl.rcParams['ps.fonttype'] + # Can't use more than 255 chars from a single Type 3 font. + if len(chars) > 255: + fonttype = 42 + fh.flush() + if fonttype == 3: + fh.write(_font_to_ps_type3(font_path, chars)) + else: # Type 42 only. + _font_to_ps_type42(font_path, chars, fh) + print("end", file=fh) + print("%%EndProlog", file=fh) + + if not is_eps: + print("%%Page: 1 1", file=fh) + print("mpldict begin", file=fh) + + print("%s translate" % _nums_to_str(xo, yo), file=fh) + if rotation: + print("%d rotate" % rotation, file=fh) + print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh) + + # write the figure + print(self._pswriter.getvalue(), file=fh) + + # write the trailer + print("end", file=fh) + print("showpage", file=fh) + if not is_eps: + print("%%EOF", file=fh) + fh.flush() + + if mpl.rcParams['ps.usedistiller']: + # We are going to use an external program to process the output. + # Write to a temporary file. + with TemporaryDirectory() as tmpdir: + tmpfile = os.path.join(tmpdir, "tmp.ps") + with open(tmpfile, 'w', encoding='latin-1') as fh: + print_figure_impl(fh) + if mpl.rcParams['ps.usedistiller'] == 'ghostscript': + _try_distill(gs_distill, + tmpfile, is_eps, ptype=papertype, bbox=bbox) + elif mpl.rcParams['ps.usedistiller'] == 'xpdf': + _try_distill(xpdf_distill, + tmpfile, is_eps, ptype=papertype, bbox=bbox) + _move_path_to_path_or_stream(tmpfile, outfile) + + else: # Write directly to outfile. + with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file: + if not file_requires_unicode(file): + file = codecs.getwriter("latin-1")(file) + print_figure_impl(file) + + def _print_figure_tex( + self, fmt, outfile, *, + dpi, dsc_comments, orientation, papertype, + bbox_inches_restore=None): + """ + If :rc:`text.usetex` is True, a temporary pair of tex/eps files + are created to allow tex to manage the text layout via the PSFrags + package. These files are processed to yield the final ps or eps file. + + The rest of the behavior is as for `._print_figure`. + """ + is_eps = fmt == 'eps' + + width, height = self.figure.get_size_inches() + xo = 0 + yo = 0 + + llx = xo + lly = yo + urx = llx + self.figure.bbox.width + ury = lly + self.figure.bbox.height + bbox = (llx, lly, urx, ury) + + self._pswriter = StringIO() + + # mixed mode rendering + ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) + renderer = MixedModeRenderer(self.figure, + width, height, dpi, ps_renderer, + bbox_inches_restore=bbox_inches_restore) + + self.figure.draw(renderer) + + # write to a temp file, we'll move it to outfile when done + with TemporaryDirectory() as tmpdir: + tmppath = pathlib.Path(tmpdir, "tmp.ps") + tmppath.write_text( + f"""\ +%!PS-Adobe-3.0 EPSF-3.0 +%%LanguageLevel: 3 +{dsc_comments} +{_get_bbox_header(bbox)} +%%EndComments +%%BeginProlog +/mpldict {len(_psDefs)} dict def +mpldict begin +{"".join(_psDefs)} +end +%%EndProlog +mpldict begin +{_nums_to_str(xo, yo)} translate +0 0 {_nums_to_str(width*72, height*72)} rectclip +{self._pswriter.getvalue()} +end +showpage +""", + encoding="latin-1") + + if orientation is _Orientation.landscape: # now, ready to rotate + width, height = height, width + bbox = (lly, llx, ury, urx) + + # set the paper size to the figure size if is_eps. The + # resulting ps file has the given size with correct bounding + # box so that there is no need to call 'pstoeps' + if is_eps or papertype == 'figure': + paper_width, paper_height = orientation.swap_if_landscape( + self.figure.get_size_inches()) + else: + if papertype == 'auto': + papertype = _get_papertype(width, height) + paper_width, paper_height = papersize[papertype] + + psfrag_rotated = _convert_psfrags( + tmppath, ps_renderer.psfrag, paper_width, paper_height, + orientation.name) + + if (mpl.rcParams['ps.usedistiller'] == 'ghostscript' + or mpl.rcParams['text.usetex']): + _try_distill(gs_distill, + tmppath, is_eps, ptype=papertype, bbox=bbox, + rotated=psfrag_rotated) + elif mpl.rcParams['ps.usedistiller'] == 'xpdf': + _try_distill(xpdf_distill, + tmppath, is_eps, ptype=papertype, bbox=bbox, + rotated=psfrag_rotated) + + _move_path_to_path_or_stream(tmppath, outfile) + + print_ps = functools.partialmethod(_print_ps, "ps") + print_eps = functools.partialmethod(_print_ps, "eps") + + def draw(self): + self.figure.draw_without_rendering() + return super().draw() + + +def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation): + """ + When we want to use the LaTeX backend with postscript, we write PSFrag tags + to a temporary postscript file, each one marking a position for LaTeX to + render some text. convert_psfrags generates a LaTeX document containing the + commands to convert those tags to text. LaTeX/dvips produces the postscript + file that includes the actual text. + """ + with mpl.rc_context({ + "text.latex.preamble": + mpl.rcParams["text.latex.preamble"] + + mpl.texmanager._usepackage_if_not_loaded("color") + + mpl.texmanager._usepackage_if_not_loaded("graphicx") + + mpl.texmanager._usepackage_if_not_loaded("psfrag") + + r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}" + % {"width": paper_width, "height": paper_height} + }): + dvifile = TexManager().make_dvi( + "\n" + r"\begin{figure}""\n" + r" \centering\leavevmode""\n" + r" %(psfrags)s""\n" + r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n" + r"\end{figure}" + % { + "psfrags": "\n".join(psfrags), + "angle": 90 if orientation == 'landscape' else 0, + "epsfile": tmppath.resolve().as_posix(), + }, + fontsize=10) # tex's default fontsize. + + with TemporaryDirectory() as tmpdir: + psfile = os.path.join(tmpdir, "tmp.ps") + cbook._check_and_log_subprocess( + ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log) + shutil.move(psfile, tmppath) + + # check if the dvips created a ps in landscape paper. Somehow, + # above latex+dvips results in a ps file in a landscape mode for a + # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the + # bounding box of the final output got messed up. We check see if + # the generated ps file is in landscape and return this + # information. The return value is used in pstoeps step to recover + # the correct bounding box. 2010-06-05 JJL + with open(tmppath) as fh: + psfrag_rotated = "Landscape" in fh.read(1000) + return psfrag_rotated + + +def _try_distill(func, tmppath, *args, **kwargs): + try: + func(str(tmppath), *args, **kwargs) + except mpl.ExecutableNotFoundError as exc: + _log.warning("%s. Distillation step skipped.", exc) + + +def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): + """ + Use ghostscript's pswrite or epswrite device to distill a file. + This yields smaller files without illegal encapsulated postscript + operators. The output is low-level, converting text to outlines. + """ + + if eps: + paper_option = ["-dEPSCrop"] + elif ptype == "figure": + # The bbox will have its lower-left corner at (0, 0), so upper-right + # corner corresponds with paper size. + paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}", + f"-dDEVICEHEIGHTPOINTS={bbox[3]}"] + else: + paper_option = [f"-sPAPERSIZE={ptype}"] + + psfile = tmpfile + '.ps' + dpi = mpl.rcParams['ps.distiller.res'] + + cbook._check_and_log_subprocess( + [mpl._get_executable_info("gs").executable, + "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write", + *paper_option, f"-sOutputFile={psfile}", tmpfile], + _log) + + os.remove(tmpfile) + shutil.move(psfile, tmpfile) + + # While it is best if above steps preserve the original bounding + # box, there seem to be cases when it is not. For those cases, + # the original bbox can be restored during the pstoeps step. + + if eps: + # For some versions of gs, above steps result in a ps file where the + # original bbox is no more correct. Do not adjust bbox for now. + pstoeps(tmpfile, bbox, rotated=rotated) + + +def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): + """ + Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file. + This yields smaller files without illegal encapsulated postscript + operators. This distiller is preferred, generating high-level postscript + output that treats text as text. + """ + mpl._get_executable_info("gs") # Effectively checks for ps2pdf. + mpl._get_executable_info("pdftops") + + if eps: + paper_option = ["-dEPSCrop"] + elif ptype == "figure": + # The bbox will have its lower-left corner at (0, 0), so upper-right + # corner corresponds with paper size. + paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}", + f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"] + else: + paper_option = [f"-sPAPERSIZE#{ptype}"] + + with TemporaryDirectory() as tmpdir: + tmppdf = pathlib.Path(tmpdir, "tmp.pdf") + tmpps = pathlib.Path(tmpdir, "tmp.ps") + # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows + # happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows). + cbook._check_and_log_subprocess( + ["ps2pdf", + "-dAutoFilterColorImages#false", + "-dAutoFilterGrayImages#false", + "-sAutoRotatePages#None", + "-sGrayImageFilter#FlateEncode", + "-sColorImageFilter#FlateEncode", + *paper_option, + tmpfile, tmppdf], _log) + cbook._check_and_log_subprocess( + ["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log) + shutil.move(tmpps, tmpfile) + if eps: + pstoeps(tmpfile) + + +@_api.deprecated("3.9") +def get_bbox_header(lbrt, rotated=False): + """ + Return a postscript header string for the given bbox lbrt=(l, b, r, t). + Optionally, return rotate command. + """ + return _get_bbox_header(lbrt), (_get_rotate_command(lbrt) if rotated else "") + + +def _get_bbox_header(lbrt): + """Return a PostScript header string for bounding box *lbrt*=(l, b, r, t).""" + l, b, r, t = lbrt + return (f"%%BoundingBox: {int(l)} {int(b)} {math.ceil(r)} {math.ceil(t)}\n" + f"%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}") + + +def _get_rotate_command(lbrt): + """Return a PostScript 90° rotation command for bounding box *lbrt*=(l, b, r, t).""" + l, b, r, t = lbrt + return f"{l+r:.2f} {0:.2f} translate\n90 rotate" + + +def pstoeps(tmpfile, bbox=None, rotated=False): + """ + Convert the postscript to encapsulated postscript. The bbox of + the eps file will be replaced with the given *bbox* argument. If + None, original bbox will be used. + """ + + epsfile = tmpfile + '.eps' + with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph: + write = epsh.write + # Modify the header: + for line in tmph: + if line.startswith(b'%!PS'): + write(b"%!PS-Adobe-3.0 EPSF-3.0\n") + if bbox: + write(_get_bbox_header(bbox).encode('ascii') + b'\n') + elif line.startswith(b'%%EndComments'): + write(line) + write(b'%%BeginProlog\n' + b'save\n' + b'countdictstack\n' + b'mark\n' + b'newpath\n' + b'/showpage {} def\n' + b'/setpagedevice {pop} def\n' + b'%%EndProlog\n' + b'%%Page 1 1\n') + if rotated: # The output eps file need to be rotated. + write(_get_rotate_command(bbox).encode('ascii') + b'\n') + break + elif bbox and line.startswith((b'%%Bound', b'%%HiResBound', + b'%%DocumentMedia', b'%%Pages')): + pass + else: + write(line) + # Now rewrite the rest of the file, and modify the trailer. + # This is done in a second loop such that the header of the embedded + # eps file is not modified. + for line in tmph: + if line.startswith(b'%%EOF'): + write(b'cleartomark\n' + b'countdictstack\n' + b'exch sub { end } repeat\n' + b'restore\n' + b'showpage\n' + b'%%EOF\n') + elif line.startswith(b'%%PageBoundingBox'): + pass + else: + write(line) + + os.remove(tmpfile) + shutil.move(epsfile, tmpfile) + + +FigureManagerPS = FigureManagerBase + + +# The following Python dictionary psDefs contains the entries for the +# PostScript dictionary mpldict. This dictionary implements most of +# the matplotlib primitives and some abbreviations. +# +# References: +# https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf +# http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial +# http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/ +# + +# The usage comments use the notation of the operator summary +# in the PostScript Language reference manual. +_psDefs = [ + # name proc *_d* - + # Note that this cannot be bound to /d, because when embedding a Type3 font + # we may want to define a "d" glyph using "/d{...} d" which would locally + # overwrite the definition. + "/_d { bind def } bind def", + # x y *m* - + "/m { moveto } _d", + # x y *l* - + "/l { lineto } _d", + # x y *r* - + "/r { rlineto } _d", + # x1 y1 x2 y2 x y *c* - + "/c { curveto } _d", + # *cl* - + "/cl { closepath } _d", + # *ce* - + "/ce { closepath eofill } _d", + # wx wy llx lly urx ury *setcachedevice* - + "/sc { setcachedevice } _d", +] + + +@_Backend.export +class _BackendPS(_Backend): + backend_version = 'Level II' + FigureCanvas = FigureCanvasPS diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt.py new file mode 100644 index 0000000000000000000000000000000000000000..6603883075d4362d05021a151709945e6ed1eba6 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt.py @@ -0,0 +1,1067 @@ +import functools +import os +import sys +import traceback + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, + TimerBase, cursors, ToolContainerBase, MouseButton, + CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent, + _allow_interrupt) +import matplotlib.backends.qt_editor.figureoptions as figureoptions +from . import qt_compat +from .qt_compat import ( + QtCore, QtGui, QtWidgets, __version__, QT_API, _to_int, _isdeleted) + + +# SPECIAL_KEYS are Qt::Key that do *not* return their Unicode name +# instead they have manually specified names. +SPECIAL_KEYS = { + _to_int(getattr(QtCore.Qt.Key, k)): v for k, v in [ + ("Key_Escape", "escape"), + ("Key_Tab", "tab"), + ("Key_Backspace", "backspace"), + ("Key_Return", "enter"), + ("Key_Enter", "enter"), + ("Key_Insert", "insert"), + ("Key_Delete", "delete"), + ("Key_Pause", "pause"), + ("Key_SysReq", "sysreq"), + ("Key_Clear", "clear"), + ("Key_Home", "home"), + ("Key_End", "end"), + ("Key_Left", "left"), + ("Key_Up", "up"), + ("Key_Right", "right"), + ("Key_Down", "down"), + ("Key_PageUp", "pageup"), + ("Key_PageDown", "pagedown"), + ("Key_Shift", "shift"), + # In macOS, the control and super (aka cmd/apple) keys are switched. + ("Key_Control", "control" if sys.platform != "darwin" else "cmd"), + ("Key_Meta", "meta" if sys.platform != "darwin" else "control"), + ("Key_Alt", "alt"), + ("Key_CapsLock", "caps_lock"), + ("Key_F1", "f1"), + ("Key_F2", "f2"), + ("Key_F3", "f3"), + ("Key_F4", "f4"), + ("Key_F5", "f5"), + ("Key_F6", "f6"), + ("Key_F7", "f7"), + ("Key_F8", "f8"), + ("Key_F9", "f9"), + ("Key_F10", "f10"), + ("Key_F10", "f11"), + ("Key_F12", "f12"), + ("Key_Super_L", "super"), + ("Key_Super_R", "super"), + ] +} +# Define which modifier keys are collected on keyboard events. +# Elements are (Qt::KeyboardModifiers, Qt::Key) tuples. +# Order determines the modifier order (ctrl+alt+...) reported by Matplotlib. +_MODIFIER_KEYS = [ + (_to_int(getattr(QtCore.Qt.KeyboardModifier, mod)), + _to_int(getattr(QtCore.Qt.Key, key))) + for mod, key in [ + ("ControlModifier", "Key_Control"), + ("AltModifier", "Key_Alt"), + ("ShiftModifier", "Key_Shift"), + ("MetaModifier", "Key_Meta"), + ] +] +cursord = { + k: getattr(QtCore.Qt.CursorShape, v) for k, v in [ + (cursors.MOVE, "SizeAllCursor"), + (cursors.HAND, "PointingHandCursor"), + (cursors.POINTER, "ArrowCursor"), + (cursors.SELECT_REGION, "CrossCursor"), + (cursors.WAIT, "WaitCursor"), + (cursors.RESIZE_HORIZONTAL, "SizeHorCursor"), + (cursors.RESIZE_VERTICAL, "SizeVerCursor"), + ] +} + + +# lru_cache keeps a reference to the QApplication instance, keeping it from +# being GC'd. +@functools.lru_cache(1) +def _create_qApp(): + app = QtWidgets.QApplication.instance() + + # Create a new QApplication and configure it if none exists yet, as only + # one QApplication can exist at a time. + if app is None: + # display_is_valid returns False only if on Linux and neither X11 + # nor Wayland display can be opened. + if not mpl._c_internal_utils.display_is_valid(): + raise RuntimeError('Invalid DISPLAY variable') + + # Check to make sure a QApplication from a different major version + # of Qt is not instantiated in the process + if QT_API in {'PyQt6', 'PySide6'}: + other_bindings = ('PyQt5', 'PySide2') + qt_version = 6 + elif QT_API in {'PyQt5', 'PySide2'}: + other_bindings = ('PyQt6', 'PySide6') + qt_version = 5 + else: + raise RuntimeError("Should never be here") + + for binding in other_bindings: + mod = sys.modules.get(f'{binding}.QtWidgets') + if mod is not None and mod.QApplication.instance() is not None: + other_core = sys.modules.get(f'{binding}.QtCore') + _api.warn_external( + f'Matplotlib is using {QT_API} which wraps ' + f'{QtCore.qVersion()} however an instantiated ' + f'QApplication from {binding} which wraps ' + f'{other_core.qVersion()} exists. Mixing Qt major ' + 'versions may not work as expected.' + ) + break + if qt_version == 5: + try: + QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) + except AttributeError: # Only for Qt>=5.6, <6. + pass + try: + QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy( + QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) + except AttributeError: # Only for Qt>=5.14. + pass + app = QtWidgets.QApplication(["matplotlib"]) + if sys.platform == "darwin": + image = str(cbook._get_data_path('images/matplotlib.svg')) + icon = QtGui.QIcon(image) + app.setWindowIcon(icon) + app.setQuitOnLastWindowClosed(True) + cbook._setup_new_guiapp() + if qt_version == 5: + app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) + + return app + + +def _allow_interrupt_qt(qapp_or_eventloop): + """A context manager that allows terminating a plot by sending a SIGINT.""" + + # Use QSocketNotifier to read the socketpair while the Qt event loop runs. + + def prepare_notifier(rsock): + sn = QtCore.QSocketNotifier(rsock.fileno(), QtCore.QSocketNotifier.Type.Read) + + @sn.activated.connect + def _may_clear_sock(): + # Running a Python function on socket activation gives the interpreter a + # chance to handle the signal in Python land. We also need to drain the + # socket with recv() to re-arm it, because it will be written to as part of + # the wakeup. (We need this in case set_wakeup_fd catches a signal other + # than SIGINT and we shall continue waiting.) + try: + rsock.recv(1) + except BlockingIOError: + # This may occasionally fire too soon or more than once on Windows, so + # be forgiving about reading an empty socket. + pass + + return sn # Actually keep the notifier alive. + + def handle_sigint(): + if hasattr(qapp_or_eventloop, 'closeAllWindows'): + qapp_or_eventloop.closeAllWindows() + qapp_or_eventloop.quit() + + return _allow_interrupt(prepare_notifier, handle_sigint) + + +class TimerQT(TimerBase): + """Subclass of `.TimerBase` using QTimer events.""" + + def __init__(self, *args, **kwargs): + # Create a new timer and connect the timeout() signal to the + # _on_timer method. + self._timer = QtCore.QTimer() + self._timer.timeout.connect(self._on_timer) + super().__init__(*args, **kwargs) + + def __del__(self): + # The check for deletedness is needed to avoid an error at animation + # shutdown with PySide2. + if not _isdeleted(self._timer): + self._timer_stop() + + def _timer_set_single_shot(self): + self._timer.setSingleShot(self._single) + + def _timer_set_interval(self): + self._timer.setInterval(self._interval) + + def _timer_start(self): + self._timer.start() + + def _timer_stop(self): + self._timer.stop() + + +class FigureCanvasQT(FigureCanvasBase, QtWidgets.QWidget): + required_interactive_framework = "qt" + _timer_cls = TimerQT + manager_class = _api.classproperty(lambda cls: FigureManagerQT) + + buttond = { + getattr(QtCore.Qt.MouseButton, k): v for k, v in [ + ("LeftButton", MouseButton.LEFT), + ("RightButton", MouseButton.RIGHT), + ("MiddleButton", MouseButton.MIDDLE), + ("XButton1", MouseButton.BACK), + ("XButton2", MouseButton.FORWARD), + ] + } + + def __init__(self, figure=None): + _create_qApp() + super().__init__(figure=figure) + + self._draw_pending = False + self._is_drawing = False + self._draw_rect_callback = lambda painter: None + self._in_resize_event = False + + self.setAttribute(QtCore.Qt.WidgetAttribute.WA_OpaquePaintEvent) + self.setMouseTracking(True) + self.resize(*self.get_width_height()) + + palette = QtGui.QPalette(QtGui.QColor("white")) + self.setPalette(palette) + + def _update_pixel_ratio(self): + if self._set_device_pixel_ratio( + self.devicePixelRatioF() or 1): # rarely, devicePixelRatioF=0 + # The easiest way to resize the canvas is to emit a resizeEvent + # since we implement all the logic for resizing the canvas for + # that event. + event = QtGui.QResizeEvent(self.size(), self.size()) + self.resizeEvent(event) + + def _update_screen(self, screen): + # Handler for changes to a window's attached screen. + self._update_pixel_ratio() + if screen is not None: + screen.physicalDotsPerInchChanged.connect(self._update_pixel_ratio) + screen.logicalDotsPerInchChanged.connect(self._update_pixel_ratio) + + def showEvent(self, event): + # Set up correct pixel ratio, and connect to any signal changes for it, + # once the window is shown (and thus has these attributes). + window = self.window().windowHandle() + window.screenChanged.connect(self._update_screen) + self._update_screen(window.screen()) + + def set_cursor(self, cursor): + # docstring inherited + self.setCursor(_api.check_getitem(cursord, cursor=cursor)) + + def mouseEventCoords(self, pos=None): + """ + Calculate mouse coordinates in physical pixels. + + Qt uses logical pixels, but the figure is scaled to physical + pixels for rendering. Transform to physical pixels so that + all of the down-stream transforms work as expected. + + Also, the origin is different and needs to be corrected. + """ + if pos is None: + pos = self.mapFromGlobal(QtGui.QCursor.pos()) + elif hasattr(pos, "position"): # qt6 QtGui.QEvent + pos = pos.position() + elif hasattr(pos, "pos"): # qt5 QtCore.QEvent + pos = pos.pos() + # (otherwise, it's already a QPoint) + x = pos.x() + # flip y so y=0 is bottom of canvas + y = self.figure.bbox.height / self.device_pixel_ratio - pos.y() + return x * self.device_pixel_ratio, y * self.device_pixel_ratio + + def enterEvent(self, event): + # Force querying of the modifiers, as the cached modifier state can + # have been invalidated while the window was out of focus. + mods = QtWidgets.QApplication.instance().queryKeyboardModifiers() + if self.figure is None: + return + LocationEvent("figure_enter_event", self, + *self.mouseEventCoords(event), + modifiers=self._mpl_modifiers(mods), + guiEvent=event)._process() + + def leaveEvent(self, event): + QtWidgets.QApplication.restoreOverrideCursor() + if self.figure is None: + return + LocationEvent("figure_leave_event", self, + *self.mouseEventCoords(), + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mousePressEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_press_event", self, + *self.mouseEventCoords(event), button, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseDoubleClickEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_press_event", self, + *self.mouseEventCoords(event), button, dblclick=True, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseMoveEvent(self, event): + if self.figure is None: + return + MouseEvent("motion_notify_event", self, + *self.mouseEventCoords(event), + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseReleaseEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_release_event", self, + *self.mouseEventCoords(event), button, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def wheelEvent(self, event): + # from QWheelEvent::pixelDelta doc: pixelDelta is sometimes not + # provided (`isNull()`) and is unreliable on X11 ("xcb"). + if (event.pixelDelta().isNull() + or QtWidgets.QApplication.instance().platformName() == "xcb"): + steps = event.angleDelta().y() / 120 + else: + steps = event.pixelDelta().y() + if steps and self.figure is not None: + MouseEvent("scroll_event", self, + *self.mouseEventCoords(event), step=steps, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def keyPressEvent(self, event): + key = self._get_key(event) + if key is not None and self.figure is not None: + KeyEvent("key_press_event", self, + key, *self.mouseEventCoords(), + guiEvent=event)._process() + + def keyReleaseEvent(self, event): + key = self._get_key(event) + if key is not None and self.figure is not None: + KeyEvent("key_release_event", self, + key, *self.mouseEventCoords(), + guiEvent=event)._process() + + def resizeEvent(self, event): + if self._in_resize_event: # Prevent PyQt6 recursion + return + if self.figure is None: + return + self._in_resize_event = True + try: + w = event.size().width() * self.device_pixel_ratio + h = event.size().height() * self.device_pixel_ratio + dpival = self.figure.dpi + winch = w / dpival + hinch = h / dpival + self.figure.set_size_inches(winch, hinch, forward=False) + # pass back into Qt to let it finish + QtWidgets.QWidget.resizeEvent(self, event) + # emit our resize events + ResizeEvent("resize_event", self)._process() + self.draw_idle() + finally: + self._in_resize_event = False + + def sizeHint(self): + w, h = self.get_width_height() + return QtCore.QSize(w, h) + + def minumumSizeHint(self): + return QtCore.QSize(10, 10) + + @staticmethod + def _mpl_modifiers(modifiers=None, *, exclude=None): + if modifiers is None: + modifiers = QtWidgets.QApplication.instance().keyboardModifiers() + modifiers = _to_int(modifiers) + # get names of the pressed modifier keys + # 'control' is named 'control' when a standalone key, but 'ctrl' when a + # modifier + # bit twiddling to pick out modifier keys from modifiers bitmask, + # if exclude is a MODIFIER, it should not be duplicated in mods + return [SPECIAL_KEYS[key].replace('control', 'ctrl') + for mask, key in _MODIFIER_KEYS + if exclude != key and modifiers & mask] + + def _get_key(self, event): + event_key = event.key() + mods = self._mpl_modifiers(exclude=event_key) + try: + # for certain keys (enter, left, backspace, etc) use a word for the + # key, rather than Unicode + key = SPECIAL_KEYS[event_key] + except KeyError: + # Unicode defines code points up to 0x10ffff (sys.maxunicode) + # QT will use Key_Codes larger than that for keyboard keys that are + # not Unicode characters (like multimedia keys) + # skip these + # if you really want them, you should add them to SPECIAL_KEYS + if event_key > sys.maxunicode: + return None + + key = chr(event_key) + # qt delivers capitalized letters. fix capitalization + # note that capslock is ignored + if 'shift' in mods: + mods.remove('shift') + else: + key = key.lower() + + return '+'.join(mods + [key]) + + def flush_events(self): + # docstring inherited + QtWidgets.QApplication.instance().processEvents() + + def start_event_loop(self, timeout=0): + # docstring inherited + if hasattr(self, "_event_loop") and self._event_loop.isRunning(): + raise RuntimeError("Event loop already running") + self._event_loop = event_loop = QtCore.QEventLoop() + if timeout > 0: + _ = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit) + + with _allow_interrupt_qt(event_loop): + qt_compat._exec(event_loop) + + def stop_event_loop(self, event=None): + # docstring inherited + if hasattr(self, "_event_loop"): + self._event_loop.quit() + + def draw(self): + """Render the figure, and queue a request for a Qt draw.""" + # The renderer draw is done here; delaying causes problems with code + # that uses the result of the draw() to update plot elements. + if self._is_drawing: + return + with cbook._setattr_cm(self, _is_drawing=True): + super().draw() + self.update() + + def draw_idle(self): + """Queue redraw of the Agg buffer and request Qt paintEvent.""" + # The Agg draw needs to be handled by the same thread Matplotlib + # modifies the scene graph from. Post Agg draw request to the + # current event loop in order to ensure thread affinity and to + # accumulate multiple draw requests from event handling. + # TODO: queued signal connection might be safer than singleShot + if not (getattr(self, '_draw_pending', False) or + getattr(self, '_is_drawing', False)): + self._draw_pending = True + QtCore.QTimer.singleShot(0, self._draw_idle) + + def blit(self, bbox=None): + # docstring inherited + if bbox is None and self.figure: + bbox = self.figure.bbox # Blit the entire canvas if bbox is None. + # repaint uses logical pixels, not physical pixels like the renderer. + l, b, w, h = [int(pt / self.device_pixel_ratio) for pt in bbox.bounds] + t = b + h + self.repaint(l, self.rect().height() - t, w, h) + + def _draw_idle(self): + with self._idle_draw_cntx(): + if not self._draw_pending: + return + self._draw_pending = False + if self.height() <= 0 or self.width() <= 0: + return + try: + self.draw() + except Exception: + # Uncaught exceptions are fatal for PyQt5, so catch them. + traceback.print_exc() + + def drawRectangle(self, rect): + # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs + # to be called at the end of paintEvent. + if rect is not None: + x0, y0, w, h = [int(pt / self.device_pixel_ratio) for pt in rect] + x1 = x0 + w + y1 = y0 + h + def _draw_rect_callback(painter): + pen = QtGui.QPen( + QtGui.QColor("black"), + 1 / self.device_pixel_ratio + ) + + pen.setDashPattern([3, 3]) + for color, offset in [ + (QtGui.QColor("black"), 0), + (QtGui.QColor("white"), 3), + ]: + pen.setDashOffset(offset) + pen.setColor(color) + painter.setPen(pen) + # Draw the lines from x0, y0 towards x1, y1 so that the + # dashes don't "jump" when moving the zoom box. + painter.drawLine(x0, y0, x0, y1) + painter.drawLine(x0, y0, x1, y0) + painter.drawLine(x0, y1, x1, y1) + painter.drawLine(x1, y0, x1, y1) + else: + def _draw_rect_callback(painter): + return + self._draw_rect_callback = _draw_rect_callback + self.update() + + +class MainWindow(QtWidgets.QMainWindow): + closing = QtCore.Signal() + + def closeEvent(self, event): + self.closing.emit() + super().closeEvent(event) + + +class FigureManagerQT(FigureManagerBase): + """ + Attributes + ---------- + canvas : `FigureCanvas` + The FigureCanvas instance + num : int or str + The Figure number + toolbar : qt.QToolBar + The qt.QToolBar + window : qt.QMainWindow + The qt.QMainWindow + """ + + def __init__(self, canvas, num): + self.window = MainWindow() + super().__init__(canvas, num) + self.window.closing.connect(self._widgetclosed) + + if sys.platform != "darwin": + image = str(cbook._get_data_path('images/matplotlib.svg')) + icon = QtGui.QIcon(image) + self.window.setWindowIcon(icon) + + self.window._destroying = False + + if self.toolbar: + self.window.addToolBar(self.toolbar) + tbs_height = self.toolbar.sizeHint().height() + else: + tbs_height = 0 + + # resize the main window so it will display the canvas with the + # requested size: + cs = canvas.sizeHint() + cs_height = cs.height() + height = cs_height + tbs_height + self.window.resize(cs.width(), height) + + self.window.setCentralWidget(self.canvas) + + if mpl.is_interactive(): + self.window.show() + self.canvas.draw_idle() + + # Give the keyboard focus to the figure instead of the manager: + # StrongFocus accepts both tab and click to focus and will enable the + # canvas to process event without clicking. + # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum + self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) + self.canvas.setFocus() + + self.window.raise_() + + def full_screen_toggle(self): + if self.window.isFullScreen(): + self.window.showNormal() + else: + self.window.showFullScreen() + + def _widgetclosed(self): + CloseEvent("close_event", self.canvas)._process() + if self.window._destroying: + return + self.window._destroying = True + try: + Gcf.destroy(self) + except AttributeError: + pass + # It seems that when the python session is killed, + # Gcf can get destroyed before the Gcf.destroy + # line is run, leading to a useless AttributeError. + + def resize(self, width, height): + # The Qt methods return sizes in 'virtual' pixels so we do need to + # rescale from physical to logical pixels. + width = int(width / self.canvas.device_pixel_ratio) + height = int(height / self.canvas.device_pixel_ratio) + extra_width = self.window.width() - self.canvas.width() + extra_height = self.window.height() - self.canvas.height() + self.canvas.resize(width, height) + self.window.resize(width + extra_width, height + extra_height) + + @classmethod + def start_main_loop(cls): + qapp = QtWidgets.QApplication.instance() + if qapp: + with _allow_interrupt_qt(qapp): + qt_compat._exec(qapp) + + def show(self): + self.window._destroying = False + self.window.show() + if mpl.rcParams['figure.raise_window']: + self.window.activateWindow() + self.window.raise_() + + def destroy(self, *args): + # check for qApp first, as PySide deletes it in its atexit handler + if QtWidgets.QApplication.instance() is None: + return + if self.window._destroying: + return + self.window._destroying = True + if self.toolbar: + self.toolbar.destroy() + self.window.close() + + def get_window_title(self): + return self.window.windowTitle() + + def set_window_title(self, title): + self.window.setWindowTitle(title) + + +class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar): + _message = QtCore.Signal(str) # Remove once deprecation below elapses. + message = _api.deprecate_privatize_attribute("3.8") + + toolitems = [*NavigationToolbar2.toolitems] + toolitems.insert( + # Add 'customize' action after 'subplots' + [name for name, *_ in toolitems].index("Subplots") + 1, + ("Customize", "Edit axis, curve and image parameters", + "qt4_editor_options", "edit_parameters")) + + def __init__(self, canvas, parent=None, coordinates=True): + """coordinates: should we show the coordinates on the right?""" + QtWidgets.QToolBar.__init__(self, parent) + self.setAllowedAreas(QtCore.Qt.ToolBarArea( + _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | + _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) + self.coordinates = coordinates + self._actions = {} # mapping of toolitem method names to QActions. + self._subplot_dialog = None + + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + self.addSeparator() + else: + slot = getattr(self, callback) + # https://bugreports.qt.io/browse/PYSIDE-2512 + slot = functools.wraps(slot)(functools.partial(slot)) + slot = QtCore.Slot()(slot) + + a = self.addAction(self._icon(image_file + '.png'), + text, slot) + self._actions[callback] = a + if callback in ['zoom', 'pan']: + a.setCheckable(True) + if tooltip_text is not None: + a.setToolTip(tooltip_text) + + # Add the (x, y) location widget at the right side of the toolbar + # The stretch factor is 1 which means any resizing of the toolbar + # will resize this label instead of the buttons. + if self.coordinates: + self.locLabel = QtWidgets.QLabel("", self) + self.locLabel.setAlignment(QtCore.Qt.AlignmentFlag( + _to_int(QtCore.Qt.AlignmentFlag.AlignRight) | + _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) + + self.locLabel.setSizePolicy(QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Policy.Expanding, + QtWidgets.QSizePolicy.Policy.Ignored, + )) + labelAction = self.addWidget(self.locLabel) + labelAction.setVisible(True) + + NavigationToolbar2.__init__(self, canvas) + + def _icon(self, name): + """ + Construct a `.QIcon` from an image file *name*, including the extension + and relative to Matplotlib's "images" data directory. + """ + # use a high-resolution icon with suffix '_large' if available + # note: user-provided icons may not have '_large' versions + path_regular = cbook._get_data_path('images', name) + path_large = path_regular.with_name( + path_regular.name.replace('.png', '_large.png')) + filename = str(path_large if path_large.exists() else path_regular) + + pm = QtGui.QPixmap(filename) + pm.setDevicePixelRatio( + self.devicePixelRatioF() or 1) # rarely, devicePixelRatioF=0 + if self.palette().color(self.backgroundRole()).value() < 128: + icon_color = self.palette().color(self.foregroundRole()) + mask = pm.createMaskFromColor( + QtGui.QColor('black'), + QtCore.Qt.MaskMode.MaskOutColor) + pm.fill(icon_color) + pm.setMask(mask) + return QtGui.QIcon(pm) + + def edit_parameters(self): + axes = self.canvas.figure.get_axes() + if not axes: + QtWidgets.QMessageBox.warning( + self.canvas.parent(), "Error", "There are no Axes to edit.") + return + elif len(axes) == 1: + ax, = axes + else: + titles = [ + ax.get_label() or + ax.get_title() or + ax.get_title("left") or + ax.get_title("right") or + " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or + f"" + for ax in axes] + duplicate_titles = [ + title for title in titles if titles.count(title) > 1] + for i, ax in enumerate(axes): + if titles[i] in duplicate_titles: + titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles. + item, ok = QtWidgets.QInputDialog.getItem( + self.canvas.parent(), + 'Customize', 'Select Axes:', titles, 0, False) + if not ok: + return + ax = axes[titles.index(item)] + figureoptions.figure_edit(ax, self) + + def _update_buttons_checked(self): + # sync button checkstates to match active mode + if 'pan' in self._actions: + self._actions['pan'].setChecked(self.mode.name == 'PAN') + if 'zoom' in self._actions: + self._actions['zoom'].setChecked(self.mode.name == 'ZOOM') + + def pan(self, *args): + super().pan(*args) + self._update_buttons_checked() + + def zoom(self, *args): + super().zoom(*args) + self._update_buttons_checked() + + def set_message(self, s): + self._message.emit(s) + if self.coordinates: + self.locLabel.setText(s) + + def draw_rubberband(self, event, x0, y0, x1, y1): + height = self.canvas.figure.bbox.height + y1 = height - y1 + y0 = height - y0 + rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] + self.canvas.drawRectangle(rect) + + def remove_rubberband(self): + self.canvas.drawRectangle(None) + + def configure_subplots(self): + if self._subplot_dialog is None: + self._subplot_dialog = SubplotToolQt( + self.canvas.figure, self.canvas.parent()) + self.canvas.mpl_connect( + "close_event", lambda e: self._subplot_dialog.reject()) + self._subplot_dialog.update_from_current_subplotpars() + self._subplot_dialog.setModal(True) + self._subplot_dialog.show() + return self._subplot_dialog + + def save_figure(self, *args): + filetypes = self.canvas.get_supported_filetypes_grouped() + sorted_filetypes = sorted(filetypes.items()) + default_filetype = self.canvas.get_default_filetype() + + startpath = os.path.expanduser(mpl.rcParams['savefig.directory']) + start = os.path.join(startpath, self.canvas.get_default_filename()) + filters = [] + selectedFilter = None + for name, exts in sorted_filetypes: + exts_list = " ".join(['*.%s' % ext for ext in exts]) + filter = f'{name} ({exts_list})' + if default_filetype in exts: + selectedFilter = filter + filters.append(filter) + filters = ';;'.join(filters) + + fname, filter = QtWidgets.QFileDialog.getSaveFileName( + self.canvas.parent(), "Choose a filename to save to", start, + filters, selectedFilter) + if fname: + # Save dir for next time, unless empty str (i.e., use cwd). + if startpath != "": + mpl.rcParams['savefig.directory'] = os.path.dirname(fname) + try: + self.canvas.figure.savefig(fname) + except Exception as e: + QtWidgets.QMessageBox.critical( + self, "Error saving file", str(e), + QtWidgets.QMessageBox.StandardButton.Ok, + QtWidgets.QMessageBox.StandardButton.NoButton) + + def set_history_buttons(self): + can_backward = self._nav_stack._pos > 0 + can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 + if 'back' in self._actions: + self._actions['back'].setEnabled(can_backward) + if 'forward' in self._actions: + self._actions['forward'].setEnabled(can_forward) + + +class SubplotToolQt(QtWidgets.QDialog): + def __init__(self, targetfig, parent): + super().__init__() + self.setWindowIcon(QtGui.QIcon( + str(cbook._get_data_path("images/matplotlib.png")))) + self.setObjectName("SubplotTool") + self._spinboxes = {} + main_layout = QtWidgets.QHBoxLayout() + self.setLayout(main_layout) + for group, spinboxes, buttons in [ + ("Borders", + ["top", "bottom", "left", "right"], + [("Export values", self._export_values)]), + ("Spacings", + ["hspace", "wspace"], + [("Tight layout", self._tight_layout), + ("Reset", self._reset), + ("Close", self.close)])]: + layout = QtWidgets.QVBoxLayout() + main_layout.addLayout(layout) + box = QtWidgets.QGroupBox(group) + layout.addWidget(box) + inner = QtWidgets.QFormLayout(box) + for name in spinboxes: + self._spinboxes[name] = spinbox = QtWidgets.QDoubleSpinBox() + spinbox.setRange(0, 1) + spinbox.setDecimals(3) + spinbox.setSingleStep(0.005) + spinbox.setKeyboardTracking(False) + spinbox.valueChanged.connect(self._on_value_changed) + inner.addRow(name, spinbox) + layout.addStretch(1) + for name, method in buttons: + button = QtWidgets.QPushButton(name) + # Don't trigger on , which is used to input values. + button.setAutoDefault(False) + button.clicked.connect(method) + layout.addWidget(button) + if name == "Close": + button.setFocus() + self._figure = targetfig + self._defaults = {} + self._export_values_dialog = None + self.update_from_current_subplotpars() + + def update_from_current_subplotpars(self): + self._defaults = {spinbox: getattr(self._figure.subplotpars, name) + for name, spinbox in self._spinboxes.items()} + self._reset() # Set spinbox current values without triggering signals. + + def _export_values(self): + # Explicitly round to 3 decimals (which is also the spinbox precision) + # to avoid numbers of the form 0.100...001. + self._export_values_dialog = QtWidgets.QDialog() + layout = QtWidgets.QVBoxLayout() + self._export_values_dialog.setLayout(layout) + text = QtWidgets.QPlainTextEdit() + text.setReadOnly(True) + layout.addWidget(text) + text.setPlainText( + ",\n".join(f"{attr}={spinbox.value():.3}" + for attr, spinbox in self._spinboxes.items())) + # Adjust the height of the text widget to fit the whole text, plus + # some padding. + size = text.maximumSize() + size.setHeight( + QtGui.QFontMetrics(text.document().defaultFont()) + .size(0, text.toPlainText()).height() + 20) + text.setMaximumSize(size) + self._export_values_dialog.show() + + def _on_value_changed(self): + spinboxes = self._spinboxes + # Set all mins and maxes, so that this can also be used in _reset(). + for lower, higher in [("bottom", "top"), ("left", "right")]: + spinboxes[higher].setMinimum(spinboxes[lower].value() + .001) + spinboxes[lower].setMaximum(spinboxes[higher].value() - .001) + self._figure.subplots_adjust( + **{attr: spinbox.value() for attr, spinbox in spinboxes.items()}) + self._figure.canvas.draw_idle() + + def _tight_layout(self): + self._figure.tight_layout() + for attr, spinbox in self._spinboxes.items(): + spinbox.blockSignals(True) + spinbox.setValue(getattr(self._figure.subplotpars, attr)) + spinbox.blockSignals(False) + self._figure.canvas.draw_idle() + + def _reset(self): + for spinbox, value in self._defaults.items(): + spinbox.setRange(0, 1) + spinbox.blockSignals(True) + spinbox.setValue(value) + spinbox.blockSignals(False) + self._on_value_changed() + + +class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar): + def __init__(self, toolmanager, parent=None): + ToolContainerBase.__init__(self, toolmanager) + QtWidgets.QToolBar.__init__(self, parent) + self.setAllowedAreas(QtCore.Qt.ToolBarArea( + _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | + _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) + message_label = QtWidgets.QLabel("") + message_label.setAlignment(QtCore.Qt.AlignmentFlag( + _to_int(QtCore.Qt.AlignmentFlag.AlignRight) | + _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) + message_label.setSizePolicy(QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Policy.Expanding, + QtWidgets.QSizePolicy.Policy.Ignored, + )) + self._message_action = self.addWidget(message_label) + self._toolitems = {} + self._groups = {} + + def add_toolitem( + self, name, group, position, image_file, description, toggle): + + button = QtWidgets.QToolButton(self) + if image_file: + button.setIcon(NavigationToolbar2QT._icon(self, image_file)) + button.setText(name) + if description: + button.setToolTip(description) + + def handler(): + self.trigger_tool(name) + if toggle: + button.setCheckable(True) + button.toggled.connect(handler) + else: + button.clicked.connect(handler) + + self._toolitems.setdefault(name, []) + self._add_to_group(group, name, button, position) + self._toolitems[name].append((button, handler)) + + def _add_to_group(self, group, name, button, position): + gr = self._groups.get(group, []) + if not gr: + sep = self.insertSeparator(self._message_action) + gr.append(sep) + before = gr[position] + widget = self.insertWidget(before, button) + gr.insert(position, widget) + self._groups[group] = gr + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for button, handler in self._toolitems[name]: + button.toggled.disconnect(handler) + button.setChecked(toggled) + button.toggled.connect(handler) + + def remove_toolitem(self, name): + for button, handler in self._toolitems.pop(name, []): + button.setParent(None) + + def set_message(self, s): + self.widgetForAction(self._message_action).setText(s) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._subplot_dialog = None + + def trigger(self, *args): + NavigationToolbar2QT.configure_subplots(self) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class SaveFigureQt(backend_tools.SaveFigureBase): + def trigger(self, *args): + NavigationToolbar2QT.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class RubberbandQt(backend_tools.RubberbandBase): + def draw_rubberband(self, x0, y0, x1, y1): + NavigationToolbar2QT.draw_rubberband( + self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) + + def remove_rubberband(self): + NavigationToolbar2QT.remove_rubberband( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class HelpQt(backend_tools.ToolHelpBase): + def trigger(self, *args): + QtWidgets.QMessageBox.information(None, "Help", self._get_help_html()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase): + def trigger(self, *args, **kwargs): + pixmap = self.canvas.grab() + QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap) + + +FigureManagerQT._toolbar2_class = NavigationToolbar2QT +FigureManagerQT._toolmanager_toolbar_class = ToolbarQt + + +@_Backend.export +class _BackendQT(_Backend): + backend_version = __version__ + FigureCanvas = FigureCanvasQT + FigureManager = FigureManagerQT + mainloop = FigureManagerQT.start_main_loop diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5.py new file mode 100644 index 0000000000000000000000000000000000000000..d94062b723f49aa1ff2fb0621748232684feef72 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5.py @@ -0,0 +1,28 @@ +from .. import backends + +backends._QT_FORCE_QT5_BINDING = True + + +from .backend_qt import ( # noqa + SPECIAL_KEYS, + # Public API + cursord, _create_qApp, _BackendQT, TimerQT, MainWindow, FigureCanvasQT, + FigureManagerQT, ToolbarQt, NavigationToolbar2QT, SubplotToolQt, + SaveFigureQt, ConfigureSubplotsQt, RubberbandQt, + HelpQt, ToolCopyToClipboardQT, + # internal re-exports + FigureCanvasBase, FigureManagerBase, MouseButton, NavigationToolbar2, + TimerBase, ToolContainerBase, figureoptions, Gcf +) +from . import backend_qt as _backend_qt # noqa + + +@_BackendQT.export +class _BackendQT5(_BackendQT): + pass + + +def __getattr__(name): + if name == 'qApp': + return _backend_qt.qApp + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5agg.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5agg.py new file mode 100644 index 0000000000000000000000000000000000000000..8a92fd5135d5a3f4b05b3a71d1089e15d031fd59 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5agg.py @@ -0,0 +1,14 @@ +""" +Render to qt from agg +""" +from .. import backends + +backends._QT_FORCE_QT5_BINDING = True +from .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611 + _BackendQTAgg, FigureCanvasQTAgg, FigureManagerQT, NavigationToolbar2QT, + FigureCanvasAgg, FigureCanvasQT) + + +@_BackendQTAgg.export +class _BackendQT5Agg(_BackendQTAgg): + pass diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5cairo.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5cairo.py new file mode 100644 index 0000000000000000000000000000000000000000..a4263f5971191a26d849a741a24cf40f7ea8b9ac --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5cairo.py @@ -0,0 +1,11 @@ +from .. import backends + +backends._QT_FORCE_QT5_BINDING = True +from .backend_qtcairo import ( # noqa: F401, E402 # pylint: disable=W0611 + _BackendQTCairo, FigureCanvasQTCairo, FigureCanvasCairo, FigureCanvasQT +) + + +@_BackendQTCairo.export +class _BackendQT5Cairo(_BackendQTCairo): + pass diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qtagg.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qtagg.py new file mode 100644 index 0000000000000000000000000000000000000000..256e50a3d1c3305be1b5fd5e9da9cb9807f4ec1f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qtagg.py @@ -0,0 +1,86 @@ +""" +Render to qt from agg. +""" + +import ctypes + +from matplotlib.transforms import Bbox + +from .qt_compat import QT_API, QtCore, QtGui +from .backend_agg import FigureCanvasAgg +from .backend_qt import _BackendQT, FigureCanvasQT +from .backend_qt import ( # noqa: F401 # pylint: disable=W0611 + FigureManagerQT, NavigationToolbar2QT) + + +class FigureCanvasQTAgg(FigureCanvasAgg, FigureCanvasQT): + + def paintEvent(self, event): + """ + Copy the image from the Agg canvas to the qt.drawable. + + In Qt, all drawing should be done inside of here when a widget is + shown onscreen. + """ + self._draw_idle() # Only does something if a draw is pending. + + # If the canvas does not have a renderer, then give up and wait for + # FigureCanvasAgg.draw(self) to be called. + if not hasattr(self, 'renderer'): + return + + painter = QtGui.QPainter(self) + try: + # See documentation of QRect: bottom() and right() are off + # by 1, so use left() + width() and top() + height(). + rect = event.rect() + # scale rect dimensions using the screen dpi ratio to get + # correct values for the Figure coordinates (rather than + # QT5's coords) + width = rect.width() * self.device_pixel_ratio + height = rect.height() * self.device_pixel_ratio + left, top = self.mouseEventCoords(rect.topLeft()) + # shift the "top" by the height of the image to get the + # correct corner for our coordinate system + bottom = top - height + # same with the right side of the image + right = left + width + # create a buffer using the image bounding box + bbox = Bbox([[left, bottom], [right, top]]) + buf = memoryview(self.copy_from_bbox(bbox)) + + if QT_API == "PyQt6": + from PyQt6 import sip + ptr = int(sip.voidptr(buf)) + else: + ptr = buf + + painter.eraseRect(rect) # clear the widget canvas + qimage = QtGui.QImage(ptr, buf.shape[1], buf.shape[0], + QtGui.QImage.Format.Format_RGBA8888) + qimage.setDevicePixelRatio(self.device_pixel_ratio) + # set origin using original QT coordinates + origin = QtCore.QPoint(rect.left(), rect.top()) + painter.drawImage(origin, qimage) + # Adjust the buf reference count to work around a memory + # leak bug in QImage under PySide. + if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12): + ctypes.c_long.from_address(id(buf)).value = 1 + + self._draw_rect_callback(painter) + finally: + painter.end() + + def print_figure(self, *args, **kwargs): + super().print_figure(*args, **kwargs) + # In some cases, Qt will itself trigger a paint event after closing the file + # save dialog. When that happens, we need to be sure that the internal canvas is + # re-drawn. However, if the user is using an automatically-chosen Qt backend but + # saving with a different backend (such as pgf), we do not want to trigger a + # full draw in Qt, so just set the flag for next time. + self._draw_pending = True + + +@_BackendQT.export +class _BackendQTAgg(_BackendQT): + FigureCanvas = FigureCanvasQTAgg diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_svg.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_svg.py new file mode 100644 index 0000000000000000000000000000000000000000..72354b81862beb839910eb8002693e42bb47f77a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_svg.py @@ -0,0 +1,1368 @@ +import base64 +import codecs +import datetime +import gzip +import hashlib +from io import BytesIO +import itertools +import logging +import os +import re +import uuid + +import numpy as np +from PIL import Image + +import matplotlib as mpl +from matplotlib import cbook, font_manager as fm +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) +from matplotlib.backends.backend_mixed import MixedModeRenderer +from matplotlib.colors import rgb2hex +from matplotlib.dates import UTC +from matplotlib.path import Path +from matplotlib import _path +from matplotlib.transforms import Affine2D, Affine2DBase + + +_log = logging.getLogger(__name__) + + +# ---------------------------------------------------------------------- +# SimpleXMLWriter class +# +# Based on an original by Fredrik Lundh, but modified here to: +# 1. Support modern Python idioms +# 2. Remove encoding support (it's handled by the file writer instead) +# 3. Support proper indentation +# 4. Minify things a little bit + +# -------------------------------------------------------------------- +# The SimpleXMLWriter module is +# +# Copyright (c) 2001-2004 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +# OF THIS SOFTWARE. +# -------------------------------------------------------------------- + + +def _escape_cdata(s): + s = s.replace("&", "&") + s = s.replace("<", "<") + s = s.replace(">", ">") + return s + + +_escape_xml_comment = re.compile(r'-(?=-)') + + +def _escape_comment(s): + s = _escape_cdata(s) + return _escape_xml_comment.sub('- ', s) + + +def _escape_attrib(s): + s = s.replace("&", "&") + s = s.replace("'", "'") + s = s.replace('"', """) + s = s.replace("<", "<") + s = s.replace(">", ">") + return s + + +def _quote_escape_attrib(s): + return ('"' + _escape_cdata(s) + '"' if '"' not in s else + "'" + _escape_cdata(s) + "'" if "'" not in s else + '"' + _escape_attrib(s) + '"') + + +def _short_float_fmt(x): + """ + Create a short string representation of a float, which is %f + formatting with trailing zeros and the decimal point removed. + """ + return f'{x:f}'.rstrip('0').rstrip('.') + + +class XMLWriter: + """ + Parameters + ---------- + file : writable text file-like object + """ + + def __init__(self, file): + self.__write = file.write + if hasattr(file, "flush"): + self.flush = file.flush + self.__open = 0 # true if start tag is open + self.__tags = [] + self.__data = [] + self.__indentation = " " * 64 + + def __flush(self, indent=True): + # flush internal buffers + if self.__open: + if indent: + self.__write(">\n") + else: + self.__write(">") + self.__open = 0 + if self.__data: + data = ''.join(self.__data) + self.__write(_escape_cdata(data)) + self.__data = [] + + def start(self, tag, attrib={}, **extra): + """ + Open a new element. Attributes can be given as keyword + arguments, or as a string/string dictionary. The method returns + an opaque identifier that can be passed to the :meth:`close` + method, to close all open elements up to and including this one. + + Parameters + ---------- + tag + Element tag. + attrib + Attribute dictionary. Alternatively, attributes can be given as + keyword arguments. + + Returns + ------- + An element identifier. + """ + self.__flush() + tag = _escape_cdata(tag) + self.__data = [] + self.__tags.append(tag) + self.__write(self.__indentation[:len(self.__tags) - 1]) + self.__write(f"<{tag}") + for k, v in {**attrib, **extra}.items(): + if v: + k = _escape_cdata(k) + v = _quote_escape_attrib(v) + self.__write(f' {k}={v}') + self.__open = 1 + return len(self.__tags) - 1 + + def comment(self, comment): + """ + Add a comment to the output stream. + + Parameters + ---------- + comment : str + Comment text. + """ + self.__flush() + self.__write(self.__indentation[:len(self.__tags)]) + self.__write(f"\n") + + def data(self, text): + """ + Add character data to the output stream. + + Parameters + ---------- + text : str + Character data. + """ + self.__data.append(text) + + def end(self, tag=None, indent=True): + """ + Close the current element (opened by the most recent call to + :meth:`start`). + + Parameters + ---------- + tag + Element tag. If given, the tag must match the start tag. If + omitted, the current element is closed. + indent : bool, default: True + """ + if tag: + assert self.__tags, f"unbalanced end({tag})" + assert _escape_cdata(tag) == self.__tags[-1], \ + f"expected end({self.__tags[-1]}), got {tag}" + else: + assert self.__tags, "unbalanced end()" + tag = self.__tags.pop() + if self.__data: + self.__flush(indent) + elif self.__open: + self.__open = 0 + self.__write("/>\n") + return + if indent: + self.__write(self.__indentation[:len(self.__tags)]) + self.__write(f"\n") + + def close(self, id): + """ + Close open elements, up to (and including) the element identified + by the given identifier. + + Parameters + ---------- + id + Element identifier, as returned by the :meth:`start` method. + """ + while len(self.__tags) > id: + self.end() + + def element(self, tag, text=None, attrib={}, **extra): + """ + Add an entire element. This is the same as calling :meth:`start`, + :meth:`data`, and :meth:`end` in sequence. The *text* argument can be + omitted. + """ + self.start(tag, attrib, **extra) + if text: + self.data(text) + self.end(indent=False) + + def flush(self): + """Flush the output stream.""" + pass # replaced by the constructor + + +def _generate_transform(transform_list): + parts = [] + for type, value in transform_list: + if (type == 'scale' and (value == (1,) or value == (1, 1)) + or type == 'translate' and value == (0, 0) + or type == 'rotate' and value == (0,)): + continue + if type == 'matrix' and isinstance(value, Affine2DBase): + value = value.to_values() + parts.append('{}({})'.format( + type, ' '.join(_short_float_fmt(x) for x in value))) + return ' '.join(parts) + + +def _generate_css(attrib): + return "; ".join(f"{k}: {v}" for k, v in attrib.items()) + + +_capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'} + + +def _check_is_str(info, key): + if not isinstance(info, str): + raise TypeError(f'Invalid type for {key} metadata. Expected str, not ' + f'{type(info)}.') + + +def _check_is_iterable_of_str(infos, key): + if np.iterable(infos): + for info in infos: + if not isinstance(info, str): + raise TypeError(f'Invalid type for {key} metadata. Expected ' + f'iterable of str, not {type(info)}.') + else: + raise TypeError(f'Invalid type for {key} metadata. Expected str or ' + f'iterable of str, not {type(infos)}.') + + +class RendererSVG(RendererBase): + def __init__(self, width, height, svgwriter, basename=None, image_dpi=72, + *, metadata=None): + self.width = width + self.height = height + self.writer = XMLWriter(svgwriter) + self.image_dpi = image_dpi # actual dpi at which we rasterize stuff + + if basename is None: + basename = getattr(svgwriter, "name", "") + if not isinstance(basename, str): + basename = "" + self.basename = basename + + self._groupd = {} + self._image_counter = itertools.count() + self._clipd = {} + self._markers = {} + self._path_collection_id = 0 + self._hatchd = {} + self._has_gouraud = False + self._n_gradients = 0 + + super().__init__() + self._glyph_map = dict() + str_height = _short_float_fmt(height) + str_width = _short_float_fmt(width) + svgwriter.write(svgProlog) + self._start_id = self.writer.start( + 'svg', + width=f'{str_width}pt', + height=f'{str_height}pt', + viewBox=f'0 0 {str_width} {str_height}', + xmlns="http://www.w3.org/2000/svg", + version="1.1", + attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"}) + self._write_metadata(metadata) + self._write_default_style() + + def finalize(self): + self._write_clips() + self._write_hatches() + self.writer.close(self._start_id) + self.writer.flush() + + def _write_metadata(self, metadata): + # Add metadata following the Dublin Core Metadata Initiative, and the + # Creative Commons Rights Expression Language. This is mainly for + # compatibility with Inkscape. + if metadata is None: + metadata = {} + metadata = { + 'Format': 'image/svg+xml', + 'Type': 'http://purl.org/dc/dcmitype/StillImage', + 'Creator': + f'Matplotlib v{mpl.__version__}, https://matplotlib.org/', + **metadata + } + writer = self.writer + + if 'Title' in metadata: + title = metadata['Title'] + _check_is_str(title, 'Title') + writer.element('title', text=title) + + # Special handling. + date = metadata.get('Date', None) + if date is not None: + if isinstance(date, str): + dates = [date] + elif isinstance(date, (datetime.datetime, datetime.date)): + dates = [date.isoformat()] + elif np.iterable(date): + dates = [] + for d in date: + if isinstance(d, str): + dates.append(d) + elif isinstance(d, (datetime.datetime, datetime.date)): + dates.append(d.isoformat()) + else: + raise TypeError( + f'Invalid type for Date metadata. ' + f'Expected iterable of str, date, or datetime, ' + f'not {type(d)}.') + else: + raise TypeError(f'Invalid type for Date metadata. ' + f'Expected str, date, datetime, or iterable ' + f'of the same, not {type(date)}.') + metadata['Date'] = '/'.join(dates) + elif 'Date' not in metadata: + # Do not add `Date` if the user explicitly set `Date` to `None` + # Get source date from SOURCE_DATE_EPOCH, if set. + # See https://reproducible-builds.org/specs/source-date-epoch/ + date = os.getenv("SOURCE_DATE_EPOCH") + if date: + date = datetime.datetime.fromtimestamp(int(date), datetime.timezone.utc) + metadata['Date'] = date.replace(tzinfo=UTC).isoformat() + else: + metadata['Date'] = datetime.datetime.today().isoformat() + + mid = None + def ensure_metadata(mid): + if mid is not None: + return mid + mid = writer.start('metadata') + writer.start('rdf:RDF', attrib={ + 'xmlns:dc': "http://purl.org/dc/elements/1.1/", + 'xmlns:cc': "http://creativecommons.org/ns#", + 'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + }) + writer.start('cc:Work') + return mid + + uri = metadata.pop('Type', None) + if uri is not None: + mid = ensure_metadata(mid) + writer.element('dc:type', attrib={'rdf:resource': uri}) + + # Single value only. + for key in ['Title', 'Coverage', 'Date', 'Description', 'Format', + 'Identifier', 'Language', 'Relation', 'Source']: + info = metadata.pop(key, None) + if info is not None: + mid = ensure_metadata(mid) + _check_is_str(info, key) + writer.element(f'dc:{key.lower()}', text=info) + + # Multiple Agent values. + for key in ['Creator', 'Contributor', 'Publisher', 'Rights']: + agents = metadata.pop(key, None) + if agents is None: + continue + + if isinstance(agents, str): + agents = [agents] + + _check_is_iterable_of_str(agents, key) + # Now we know that we have an iterable of str + mid = ensure_metadata(mid) + writer.start(f'dc:{key.lower()}') + for agent in agents: + writer.start('cc:Agent') + writer.element('dc:title', text=agent) + writer.end('cc:Agent') + writer.end(f'dc:{key.lower()}') + + # Multiple values. + keywords = metadata.pop('Keywords', None) + if keywords is not None: + if isinstance(keywords, str): + keywords = [keywords] + _check_is_iterable_of_str(keywords, 'Keywords') + # Now we know that we have an iterable of str + mid = ensure_metadata(mid) + writer.start('dc:subject') + writer.start('rdf:Bag') + for keyword in keywords: + writer.element('rdf:li', text=keyword) + writer.end('rdf:Bag') + writer.end('dc:subject') + + if mid is not None: + writer.close(mid) + + if metadata: + raise ValueError('Unknown metadata key(s) passed to SVG writer: ' + + ','.join(metadata)) + + def _write_default_style(self): + writer = self.writer + default_style = _generate_css({ + 'stroke-linejoin': 'round', + 'stroke-linecap': 'butt'}) + writer.start('defs') + writer.element('style', type='text/css', text='*{%s}' % default_style) + writer.end('defs') + + def _make_id(self, type, content): + salt = mpl.rcParams['svg.hashsalt'] + if salt is None: + salt = str(uuid.uuid4()) + m = hashlib.sha256() + m.update(salt.encode('utf8')) + m.update(str(content).encode('utf8')) + return f'{type}{m.hexdigest()[:10]}' + + def _make_flip_transform(self, transform): + return transform + Affine2D().scale(1, -1).translate(0, self.height) + + def _get_hatch(self, gc, rgbFace): + """ + Create a new hatch pattern + """ + if rgbFace is not None: + rgbFace = tuple(rgbFace) + edge = gc.get_hatch_color() + if edge is not None: + edge = tuple(edge) + dictkey = (gc.get_hatch(), rgbFace, edge) + oid = self._hatchd.get(dictkey) + if oid is None: + oid = self._make_id('h', dictkey) + self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge), oid) + else: + _, oid = oid + return oid + + def _write_hatches(self): + if not len(self._hatchd): + return + HATCH_SIZE = 72 + writer = self.writer + writer.start('defs') + for (path, face, stroke), oid in self._hatchd.values(): + writer.start( + 'pattern', + id=oid, + patternUnits="userSpaceOnUse", + x="0", y="0", width=str(HATCH_SIZE), + height=str(HATCH_SIZE)) + path_data = self._convert_path( + path, + Affine2D() + .scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE), + simplify=False) + if face is None: + fill = 'none' + else: + fill = rgb2hex(face) + writer.element( + 'rect', + x="0", y="0", width=str(HATCH_SIZE+1), + height=str(HATCH_SIZE+1), + fill=fill) + hatch_style = { + 'fill': rgb2hex(stroke), + 'stroke': rgb2hex(stroke), + 'stroke-width': str(mpl.rcParams['hatch.linewidth']), + 'stroke-linecap': 'butt', + 'stroke-linejoin': 'miter' + } + if stroke[3] < 1: + hatch_style['stroke-opacity'] = str(stroke[3]) + writer.element( + 'path', + d=path_data, + style=_generate_css(hatch_style) + ) + writer.end('pattern') + writer.end('defs') + + def _get_style_dict(self, gc, rgbFace): + """Generate a style string from the GraphicsContext and rgbFace.""" + attrib = {} + + forced_alpha = gc.get_forced_alpha() + + if gc.get_hatch() is not None: + attrib['fill'] = f"url(#{self._get_hatch(gc, rgbFace)})" + if (rgbFace is not None and len(rgbFace) == 4 and rgbFace[3] != 1.0 + and not forced_alpha): + attrib['fill-opacity'] = _short_float_fmt(rgbFace[3]) + else: + if rgbFace is None: + attrib['fill'] = 'none' + else: + if tuple(rgbFace[:3]) != (0, 0, 0): + attrib['fill'] = rgb2hex(rgbFace) + if (len(rgbFace) == 4 and rgbFace[3] != 1.0 + and not forced_alpha): + attrib['fill-opacity'] = _short_float_fmt(rgbFace[3]) + + if forced_alpha and gc.get_alpha() != 1.0: + attrib['opacity'] = _short_float_fmt(gc.get_alpha()) + + offset, seq = gc.get_dashes() + if seq is not None: + attrib['stroke-dasharray'] = ','.join( + _short_float_fmt(val) for val in seq) + attrib['stroke-dashoffset'] = _short_float_fmt(float(offset)) + + linewidth = gc.get_linewidth() + if linewidth: + rgb = gc.get_rgb() + attrib['stroke'] = rgb2hex(rgb) + if not forced_alpha and rgb[3] != 1.0: + attrib['stroke-opacity'] = _short_float_fmt(rgb[3]) + if linewidth != 1.0: + attrib['stroke-width'] = _short_float_fmt(linewidth) + if gc.get_joinstyle() != 'round': + attrib['stroke-linejoin'] = gc.get_joinstyle() + if gc.get_capstyle() != 'butt': + attrib['stroke-linecap'] = _capstyle_d[gc.get_capstyle()] + + return attrib + + def _get_style(self, gc, rgbFace): + return _generate_css(self._get_style_dict(gc, rgbFace)) + + def _get_clip_attrs(self, gc): + cliprect = gc.get_clip_rectangle() + clippath, clippath_trans = gc.get_clip_path() + if clippath is not None: + clippath_trans = self._make_flip_transform(clippath_trans) + dictkey = (id(clippath), str(clippath_trans)) + elif cliprect is not None: + x, y, w, h = cliprect.bounds + y = self.height-(y+h) + dictkey = (x, y, w, h) + else: + return {} + clip = self._clipd.get(dictkey) + if clip is None: + oid = self._make_id('p', dictkey) + if clippath is not None: + self._clipd[dictkey] = ((clippath, clippath_trans), oid) + else: + self._clipd[dictkey] = (dictkey, oid) + else: + clip, oid = clip + return {'clip-path': f'url(#{oid})'} + + def _write_clips(self): + if not len(self._clipd): + return + writer = self.writer + writer.start('defs') + for clip, oid in self._clipd.values(): + writer.start('clipPath', id=oid) + if len(clip) == 2: + clippath, clippath_trans = clip + path_data = self._convert_path( + clippath, clippath_trans, simplify=False) + writer.element('path', d=path_data) + else: + x, y, w, h = clip + writer.element( + 'rect', + x=_short_float_fmt(x), + y=_short_float_fmt(y), + width=_short_float_fmt(w), + height=_short_float_fmt(h)) + writer.end('clipPath') + writer.end('defs') + + def open_group(self, s, gid=None): + # docstring inherited + if gid: + self.writer.start('g', id=gid) + else: + self._groupd[s] = self._groupd.get(s, 0) + 1 + self.writer.start('g', id=f"{s}_{self._groupd[s]:d}") + + def close_group(self, s): + # docstring inherited + self.writer.end('g') + + def option_image_nocomposite(self): + # docstring inherited + return not mpl.rcParams['image.composite_image'] + + def _convert_path(self, path, transform=None, clip=None, simplify=None, + sketch=None): + if clip: + clip = (0.0, 0.0, self.width, self.height) + else: + clip = None + return _path.convert_to_string( + path, transform, clip, simplify, sketch, 6, + [b'M', b'L', b'Q', b'C', b'z'], False).decode('ascii') + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + trans_and_flip = self._make_flip_transform(transform) + clip = (rgbFace is None and gc.get_hatch_path() is None) + simplify = path.should_simplify and clip + path_data = self._convert_path( + path, trans_and_flip, clip=clip, simplify=simplify, + sketch=gc.get_sketch_params()) + + if gc.get_url() is not None: + self.writer.start('a', {'xlink:href': gc.get_url()}) + self.writer.element('path', d=path_data, **self._get_clip_attrs(gc), + style=self._get_style(gc, rgbFace)) + if gc.get_url() is not None: + self.writer.end('a') + + def draw_markers( + self, gc, marker_path, marker_trans, path, trans, rgbFace=None): + # docstring inherited + + if not len(path.vertices): + return + + writer = self.writer + path_data = self._convert_path( + marker_path, + marker_trans + Affine2D().scale(1.0, -1.0), + simplify=False) + style = self._get_style_dict(gc, rgbFace) + dictkey = (path_data, _generate_css(style)) + oid = self._markers.get(dictkey) + style = _generate_css({k: v for k, v in style.items() + if k.startswith('stroke')}) + + if oid is None: + oid = self._make_id('m', dictkey) + writer.start('defs') + writer.element('path', id=oid, d=path_data, style=style) + writer.end('defs') + self._markers[dictkey] = oid + + writer.start('g', **self._get_clip_attrs(gc)) + trans_and_flip = self._make_flip_transform(trans) + attrib = {'xlink:href': f'#{oid}'} + clip = (0, 0, self.width*72, self.height*72) + for vertices, code in path.iter_segments( + trans_and_flip, clip=clip, simplify=False): + if len(vertices): + x, y = vertices[-2:] + attrib['x'] = _short_float_fmt(x) + attrib['y'] = _short_float_fmt(y) + attrib['style'] = self._get_style(gc, rgbFace) + writer.element('use', attrib=attrib) + writer.end('g') + + def draw_path_collection(self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position): + # Is the optimization worth it? Rough calculation: + # cost of emitting a path in-line is + # (len_path + 5) * uses_per_path + # cost of definition+use is + # (len_path + 3) + 9 * uses_per_path + len_path = len(paths[0].vertices) if len(paths) > 0 else 0 + uses_per_path = self._iter_collection_uses_per_path( + paths, all_transforms, offsets, facecolors, edgecolors) + should_do_optimization = \ + len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path + if not should_do_optimization: + return super().draw_path_collection( + gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position) + + writer = self.writer + path_codes = [] + writer.start('defs') + for i, (path, transform) in enumerate(self._iter_collection_raw_paths( + master_transform, paths, all_transforms)): + transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0) + d = self._convert_path(path, transform, simplify=False) + oid = 'C{:x}_{:x}_{}'.format( + self._path_collection_id, i, self._make_id('', d)) + writer.element('path', id=oid, d=d) + path_codes.append(oid) + writer.end('defs') + + for xo, yo, path_id, gc0, rgbFace in self._iter_collection( + gc, path_codes, offsets, offset_trans, + facecolors, edgecolors, linewidths, linestyles, + antialiaseds, urls, offset_position): + url = gc0.get_url() + if url is not None: + writer.start('a', attrib={'xlink:href': url}) + clip_attrs = self._get_clip_attrs(gc0) + if clip_attrs: + writer.start('g', **clip_attrs) + attrib = { + 'xlink:href': f'#{path_id}', + 'x': _short_float_fmt(xo), + 'y': _short_float_fmt(self.height - yo), + 'style': self._get_style(gc0, rgbFace) + } + writer.element('use', attrib=attrib) + if clip_attrs: + writer.end('g') + if url is not None: + writer.end('a') + + self._path_collection_id += 1 + + def _draw_gouraud_triangle(self, transformed_points, colors): + # This uses a method described here: + # + # http://www.svgopen.org/2005/papers/Converting3DFaceToSVG/index.html + # + # that uses three overlapping linear gradients to simulate a + # Gouraud triangle. Each gradient goes from fully opaque in + # one corner to fully transparent along the opposite edge. + # The line between the stop points is perpendicular to the + # opposite edge. Underlying these three gradients is a solid + # triangle whose color is the average of all three points. + + avg_color = np.average(colors, axis=0) + if avg_color[-1] == 0: + # Skip fully-transparent triangles + return + + writer = self.writer + writer.start('defs') + for i in range(3): + x1, y1 = transformed_points[i] + x2, y2 = transformed_points[(i + 1) % 3] + x3, y3 = transformed_points[(i + 2) % 3] + rgba_color = colors[i] + + if x2 == x3: + xb = x2 + yb = y1 + elif y2 == y3: + xb = x1 + yb = y2 + else: + m1 = (y2 - y3) / (x2 - x3) + b1 = y2 - (m1 * x2) + m2 = -(1.0 / m1) + b2 = y1 - (m2 * x1) + xb = (-b1 + b2) / (m1 - m2) + yb = m2 * xb + b2 + + writer.start( + 'linearGradient', + id=f"GR{self._n_gradients:x}_{i:d}", + gradientUnits="userSpaceOnUse", + x1=_short_float_fmt(x1), y1=_short_float_fmt(y1), + x2=_short_float_fmt(xb), y2=_short_float_fmt(yb)) + writer.element( + 'stop', + offset='1', + style=_generate_css({ + 'stop-color': rgb2hex(avg_color), + 'stop-opacity': _short_float_fmt(rgba_color[-1])})) + writer.element( + 'stop', + offset='0', + style=_generate_css({'stop-color': rgb2hex(rgba_color), + 'stop-opacity': "0"})) + + writer.end('linearGradient') + + writer.end('defs') + + # triangle formation using "path" + dpath = (f"M {_short_float_fmt(x1)},{_short_float_fmt(y1)}" + f" L {_short_float_fmt(x2)},{_short_float_fmt(y2)}" + f" {_short_float_fmt(x3)},{_short_float_fmt(y3)} Z") + + writer.element( + 'path', + attrib={'d': dpath, + 'fill': rgb2hex(avg_color), + 'fill-opacity': '1', + 'shape-rendering': "crispEdges"}) + + writer.start( + 'g', + attrib={'stroke': "none", + 'stroke-width': "0", + 'shape-rendering': "crispEdges", + 'filter': "url(#colorMat)"}) + + writer.element( + 'path', + attrib={'d': dpath, + 'fill': f'url(#GR{self._n_gradients:x}_0)', + 'shape-rendering': "crispEdges"}) + + writer.element( + 'path', + attrib={'d': dpath, + 'fill': f'url(#GR{self._n_gradients:x}_1)', + 'filter': 'url(#colorAdd)', + 'shape-rendering': "crispEdges"}) + + writer.element( + 'path', + attrib={'d': dpath, + 'fill': f'url(#GR{self._n_gradients:x}_2)', + 'filter': 'url(#colorAdd)', + 'shape-rendering': "crispEdges"}) + + writer.end('g') + + self._n_gradients += 1 + + def draw_gouraud_triangles(self, gc, triangles_array, colors_array, + transform): + writer = self.writer + writer.start('g', **self._get_clip_attrs(gc)) + transform = transform.frozen() + trans_and_flip = self._make_flip_transform(transform) + + if not self._has_gouraud: + self._has_gouraud = True + writer.start( + 'filter', + id='colorAdd') + writer.element( + 'feComposite', + attrib={'in': 'SourceGraphic'}, + in2='BackgroundImage', + operator='arithmetic', + k2="1", k3="1") + writer.end('filter') + # feColorMatrix filter to correct opacity + writer.start( + 'filter', + id='colorMat') + writer.element( + 'feColorMatrix', + attrib={'type': 'matrix'}, + values='1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n1 1 1 1 0 \n0 0 0 0 1 ') + writer.end('filter') + + for points, colors in zip(triangles_array, colors_array): + self._draw_gouraud_triangle(trans_and_flip.transform(points), colors) + writer.end('g') + + def option_scale_image(self): + # docstring inherited + return True + + def get_image_magnification(self): + return self.image_dpi / 72.0 + + def draw_image(self, gc, x, y, im, transform=None): + # docstring inherited + + h, w = im.shape[:2] + + if w == 0 or h == 0: + return + + clip_attrs = self._get_clip_attrs(gc) + if clip_attrs: + # Can't apply clip-path directly to the image because the image has + # a transformation, which would also be applied to the clip-path. + self.writer.start('g', **clip_attrs) + + url = gc.get_url() + if url is not None: + self.writer.start('a', attrib={'xlink:href': url}) + + attrib = {} + oid = gc.get_gid() + if mpl.rcParams['svg.image_inline']: + buf = BytesIO() + Image.fromarray(im).save(buf, format="png") + oid = oid or self._make_id('image', buf.getvalue()) + attrib['xlink:href'] = ( + "data:image/png;base64,\n" + + base64.b64encode(buf.getvalue()).decode('ascii')) + else: + if self.basename is None: + raise ValueError("Cannot save image data to filesystem when " + "writing SVG to an in-memory buffer") + filename = f'{self.basename}.image{next(self._image_counter)}.png' + _log.info('Writing image file for inclusion: %s', filename) + Image.fromarray(im).save(filename) + oid = oid or 'Im_' + self._make_id('image', filename) + attrib['xlink:href'] = filename + attrib['id'] = oid + + if transform is None: + w = 72.0 * w / self.image_dpi + h = 72.0 * h / self.image_dpi + + self.writer.element( + 'image', + transform=_generate_transform([ + ('scale', (1, -1)), ('translate', (0, -h))]), + x=_short_float_fmt(x), + y=_short_float_fmt(-(self.height - y - h)), + width=_short_float_fmt(w), height=_short_float_fmt(h), + attrib=attrib) + else: + alpha = gc.get_alpha() + if alpha != 1.0: + attrib['opacity'] = _short_float_fmt(alpha) + + flipped = ( + Affine2D().scale(1.0 / w, 1.0 / h) + + transform + + Affine2D() + .translate(x, y) + .scale(1.0, -1.0) + .translate(0.0, self.height)) + + attrib['transform'] = _generate_transform( + [('matrix', flipped.frozen())]) + attrib['style'] = ( + 'image-rendering:crisp-edges;' + 'image-rendering:pixelated') + self.writer.element( + 'image', + width=_short_float_fmt(w), height=_short_float_fmt(h), + attrib=attrib) + + if url is not None: + self.writer.end('a') + if clip_attrs: + self.writer.end('g') + + def _update_glyph_map_defs(self, glyph_map_new): + """ + Emit definitions for not-yet-defined glyphs, and record them as having + been defined. + """ + writer = self.writer + if glyph_map_new: + writer.start('defs') + for char_id, (vertices, codes) in glyph_map_new.items(): + char_id = self._adjust_char_id(char_id) + # x64 to go back to FreeType's internal (integral) units. + path_data = self._convert_path( + Path(vertices * 64, codes), simplify=False) + writer.element( + 'path', id=char_id, d=path_data, + transform=_generate_transform([('scale', (1 / 64,))])) + writer.end('defs') + self._glyph_map.update(glyph_map_new) + + def _adjust_char_id(self, char_id): + return char_id.replace("%20", "_") + + def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None): + # docstring inherited + writer = self.writer + + writer.comment(s) + + glyph_map = self._glyph_map + + text2path = self._text2path + color = rgb2hex(gc.get_rgb()) + fontsize = prop.get_size_in_points() + + style = {} + if color != '#000000': + style['fill'] = color + alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3] + if alpha != 1: + style['opacity'] = _short_float_fmt(alpha) + font_scale = fontsize / text2path.FONT_SCALE + attrib = { + 'style': _generate_css(style), + 'transform': _generate_transform([ + ('translate', (x, y)), + ('rotate', (-angle,)), + ('scale', (font_scale, -font_scale))]), + } + writer.start('g', attrib=attrib) + + if not ismath: + font = text2path._get_font(prop) + _glyphs = text2path.get_glyphs_with_font( + font, s, glyph_map=glyph_map, return_new_glyphs_only=True) + glyph_info, glyph_map_new, rects = _glyphs + self._update_glyph_map_defs(glyph_map_new) + + for glyph_id, xposition, yposition, scale in glyph_info: + attrib = {'xlink:href': f'#{glyph_id}'} + if xposition != 0.0: + attrib['x'] = _short_float_fmt(xposition) + if yposition != 0.0: + attrib['y'] = _short_float_fmt(yposition) + writer.element('use', attrib=attrib) + + else: + if ismath == "TeX": + _glyphs = text2path.get_glyphs_tex( + prop, s, glyph_map=glyph_map, return_new_glyphs_only=True) + else: + _glyphs = text2path.get_glyphs_mathtext( + prop, s, glyph_map=glyph_map, return_new_glyphs_only=True) + glyph_info, glyph_map_new, rects = _glyphs + self._update_glyph_map_defs(glyph_map_new) + + for char_id, xposition, yposition, scale in glyph_info: + char_id = self._adjust_char_id(char_id) + writer.element( + 'use', + transform=_generate_transform([ + ('translate', (xposition, yposition)), + ('scale', (scale,)), + ]), + attrib={'xlink:href': f'#{char_id}'}) + + for verts, codes in rects: + path = Path(verts, codes) + path_data = self._convert_path(path, simplify=False) + writer.element('path', d=path_data) + + writer.end('g') + + def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None): + # NOTE: If you change the font styling CSS, then be sure the check for + # svg.fonttype = none in `lib/matplotlib/testing/compare.py::convert` remains in + # sync. Also be sure to re-generate any SVG using this mode, or else such tests + # will fail to use the right converter for the expected images, and they will + # fail strangely. + writer = self.writer + + color = rgb2hex(gc.get_rgb()) + style = {} + if color != '#000000': + style['fill'] = color + + alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3] + if alpha != 1: + style['opacity'] = _short_float_fmt(alpha) + + if not ismath: + attrib = {} + + font_parts = [] + if prop.get_style() != 'normal': + font_parts.append(prop.get_style()) + if prop.get_variant() != 'normal': + font_parts.append(prop.get_variant()) + weight = fm.weight_dict[prop.get_weight()] + if weight != 400: + font_parts.append(f'{weight}') + + def _normalize_sans(name): + return 'sans-serif' if name in ['sans', 'sans serif'] else name + + def _expand_family_entry(fn): + fn = _normalize_sans(fn) + # prepend generic font families with all configured font names + if fn in fm.font_family_aliases: + # get all of the font names and fix spelling of sans-serif + # (we accept 3 ways CSS only supports 1) + for name in fm.FontManager._expand_aliases(fn): + yield _normalize_sans(name) + # whether a generic name or a family name, it must appear at + # least once + yield fn + + def _get_all_quoted_names(prop): + # only quote specific names, not generic names + return [name if name in fm.font_family_aliases else repr(name) + for entry in prop.get_family() + for name in _expand_family_entry(entry)] + + font_parts.extend([ + f'{_short_float_fmt(prop.get_size())}px', + # ensure expansion, quoting, and dedupe of font names + ", ".join(dict.fromkeys(_get_all_quoted_names(prop))) + ]) + style['font'] = ' '.join(font_parts) + if prop.get_stretch() != 'normal': + style['font-stretch'] = prop.get_stretch() + attrib['style'] = _generate_css(style) + + if mtext and (angle == 0 or mtext.get_rotation_mode() == "anchor"): + # If text anchoring can be supported, get the original + # coordinates and add alignment information. + + # Get anchor coordinates. + transform = mtext.get_transform() + ax, ay = transform.transform(mtext.get_unitless_position()) + ay = self.height - ay + + # Don't do vertical anchor alignment. Most applications do not + # support 'alignment-baseline' yet. Apply the vertical layout + # to the anchor point manually for now. + angle_rad = np.deg2rad(angle) + dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)]) + v_offset = np.dot(dir_vert, [(x - ax), (y - ay)]) + ax = ax + v_offset * dir_vert[0] + ay = ay + v_offset * dir_vert[1] + + ha_mpl_to_svg = {'left': 'start', 'right': 'end', + 'center': 'middle'} + style['text-anchor'] = ha_mpl_to_svg[mtext.get_ha()] + + attrib['x'] = _short_float_fmt(ax) + attrib['y'] = _short_float_fmt(ay) + attrib['style'] = _generate_css(style) + attrib['transform'] = _generate_transform([ + ("rotate", (-angle, ax, ay))]) + + else: + attrib['transform'] = _generate_transform([ + ('translate', (x, y)), + ('rotate', (-angle,))]) + + writer.element('text', s, attrib=attrib) + + else: + writer.comment(s) + + width, height, descent, glyphs, rects = \ + self._text2path.mathtext_parser.parse(s, 72, prop) + + # Apply attributes to 'g', not 'text', because we likely have some + # rectangles as well with the same style and transformation. + writer.start('g', + style=_generate_css(style), + transform=_generate_transform([ + ('translate', (x, y)), + ('rotate', (-angle,))]), + ) + + writer.start('text') + + # Sort the characters by font, and output one tspan for each. + spans = {} + for font, fontsize, thetext, new_x, new_y in glyphs: + entry = fm.ttfFontProperty(font) + font_parts = [] + if entry.style != 'normal': + font_parts.append(entry.style) + if entry.variant != 'normal': + font_parts.append(entry.variant) + if entry.weight != 400: + font_parts.append(f'{entry.weight}') + font_parts.extend([ + f'{_short_float_fmt(fontsize)}px', + f'{entry.name!r}', # ensure quoting + ]) + style = {'font': ' '.join(font_parts)} + if entry.stretch != 'normal': + style['font-stretch'] = entry.stretch + style = _generate_css(style) + if thetext == 32: + thetext = 0xa0 # non-breaking space + spans.setdefault(style, []).append((new_x, -new_y, thetext)) + + for style, chars in spans.items(): + chars.sort() + + if len({y for x, y, t in chars}) == 1: # Are all y's the same? + ys = str(chars[0][1]) + else: + ys = ' '.join(str(c[1]) for c in chars) + + attrib = { + 'style': style, + 'x': ' '.join(_short_float_fmt(c[0]) for c in chars), + 'y': ys + } + + writer.element( + 'tspan', + ''.join(chr(c[2]) for c in chars), + attrib=attrib) + + writer.end('text') + + for x, y, width, height in rects: + writer.element( + 'rect', + x=_short_float_fmt(x), + y=_short_float_fmt(-y-1), + width=_short_float_fmt(width), + height=_short_float_fmt(height) + ) + + writer.end('g') + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + clip_attrs = self._get_clip_attrs(gc) + if clip_attrs: + # Cannot apply clip-path directly to the text, because + # it has a transformation + self.writer.start('g', **clip_attrs) + + if gc.get_url() is not None: + self.writer.start('a', {'xlink:href': gc.get_url()}) + + if mpl.rcParams['svg.fonttype'] == 'path': + self._draw_text_as_path(gc, x, y, s, prop, angle, ismath, mtext) + else: + self._draw_text_as_text(gc, x, y, s, prop, angle, ismath, mtext) + + if gc.get_url() is not None: + self.writer.end('a') + + if clip_attrs: + self.writer.end('g') + + def flipy(self): + # docstring inherited + return True + + def get_canvas_width_height(self): + # docstring inherited + return self.width, self.height + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + return self._text2path.get_text_width_height_descent(s, prop, ismath) + + +class FigureCanvasSVG(FigureCanvasBase): + filetypes = {'svg': 'Scalable Vector Graphics', + 'svgz': 'Scalable Vector Graphics'} + + fixed_dpi = 72 + + def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None): + """ + Parameters + ---------- + filename : str or path-like or file-like + Output target; if a string, a file will be opened for writing. + + metadata : dict[str, Any], optional + Metadata in the SVG file defined as key-value pairs of strings, + datetimes, or lists of strings, e.g., ``{'Creator': 'My software', + 'Contributor': ['Me', 'My Friend'], 'Title': 'Awesome'}``. + + The standard keys and their value types are: + + * *str*: ``'Coverage'``, ``'Description'``, ``'Format'``, + ``'Identifier'``, ``'Language'``, ``'Relation'``, ``'Source'``, + ``'Title'``, and ``'Type'``. + * *str* or *list of str*: ``'Contributor'``, ``'Creator'``, + ``'Keywords'``, ``'Publisher'``, and ``'Rights'``. + * *str*, *date*, *datetime*, or *tuple* of same: ``'Date'``. If a + non-*str*, then it will be formatted as ISO 8601. + + Values have been predefined for ``'Creator'``, ``'Date'``, + ``'Format'``, and ``'Type'``. They can be removed by setting them + to `None`. + + Information is encoded as `Dublin Core Metadata`__. + + .. _DC: https://www.dublincore.org/specifications/dublin-core/ + + __ DC_ + """ + with cbook.open_file_cm(filename, "w", encoding="utf-8") as fh: + if not cbook.file_requires_unicode(fh): + fh = codecs.getwriter('utf-8')(fh) + dpi = self.figure.dpi + self.figure.dpi = 72 + width, height = self.figure.get_size_inches() + w, h = width * 72, height * 72 + renderer = MixedModeRenderer( + self.figure, width, height, dpi, + RendererSVG(w, h, fh, image_dpi=dpi, metadata=metadata), + bbox_inches_restore=bbox_inches_restore) + self.figure.draw(renderer) + renderer.finalize() + + def print_svgz(self, filename, **kwargs): + with cbook.open_file_cm(filename, "wb") as fh, \ + gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter: + return self.print_svg(gzipwriter, **kwargs) + + def get_default_filetype(self): + return 'svg' + + def draw(self): + self.figure.draw_without_rendering() + return super().draw() + + +FigureManagerSVG = FigureManagerBase + + +svgProlog = """\ + + +""" + + +@_Backend.export +class _BackendSVG(_Backend): + backend_version = mpl.__version__ + FigureCanvas = FigureCanvasSVG diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_template.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_template.py new file mode 100644 index 0000000000000000000000000000000000000000..d997ec160a53cb64b92a1ab2511fde7eceeb42e6 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_template.py @@ -0,0 +1,213 @@ +""" +A fully functional, do-nothing backend intended as a template for backend +writers. It is fully functional in that you can select it as a backend e.g. +with :: + + import matplotlib + matplotlib.use("template") + +and your program will (should!) run without error, though no output is +produced. This provides a starting point for backend writers; you can +selectively implement drawing methods (`~.RendererTemplate.draw_path`, +`~.RendererTemplate.draw_image`, etc.) and slowly see your figure come to life +instead having to have a full-blown implementation before getting any results. + +Copy this file to a directory outside the Matplotlib source tree, somewhere +where Python can import it (by adding the directory to your ``sys.path`` or by +packaging it as a normal Python package); if the backend is importable as +``import my.backend`` you can then select it using :: + + import matplotlib + matplotlib.use("module://my.backend") + +If your backend implements support for saving figures (i.e. has a `print_xyz` +method), you can register it as the default handler for a given file type:: + + from matplotlib.backend_bases import register_backend + register_backend('xyz', 'my_backend', 'XYZ File Format') + ... + plt.savefig("figure.xyz") +""" + +from matplotlib import _api +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import ( + FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) +from matplotlib.figure import Figure + + +class RendererTemplate(RendererBase): + """ + The renderer handles drawing/rendering operations. + + This is a minimal do-nothing class that can be used to get started when + writing a new backend. Refer to `.backend_bases.RendererBase` for + documentation of the methods. + """ + + def __init__(self, dpi): + super().__init__() + self.dpi = dpi + + def draw_path(self, gc, path, transform, rgbFace=None): + pass + + # draw_markers is optional, and we get more correct relative + # timings by leaving it out. backend implementers concerned with + # performance will probably want to implement it +# def draw_markers(self, gc, marker_path, marker_trans, path, trans, +# rgbFace=None): +# pass + + # draw_path_collection is optional, and we get more correct + # relative timings by leaving it out. backend implementers concerned with + # performance will probably want to implement it +# def draw_path_collection(self, gc, master_transform, paths, +# all_transforms, offsets, offset_trans, +# facecolors, edgecolors, linewidths, linestyles, +# antialiaseds): +# pass + + # draw_quad_mesh is optional, and we get more correct + # relative timings by leaving it out. backend implementers concerned with + # performance will probably want to implement it +# def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight, +# coordinates, offsets, offsetTrans, facecolors, +# antialiased, edgecolors): +# pass + + def draw_image(self, gc, x, y, im): + pass + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + pass + + def flipy(self): + # docstring inherited + return True + + def get_canvas_width_height(self): + # docstring inherited + return 100, 100 + + def get_text_width_height_descent(self, s, prop, ismath): + return 1, 1, 1 + + def new_gc(self): + # docstring inherited + return GraphicsContextTemplate() + + def points_to_pixels(self, points): + # if backend doesn't have dpi, e.g., postscript or svg + return points + # elif backend assumes a value for pixels_per_inch + # return points/72.0 * self.dpi.get() * pixels_per_inch/72.0 + # else + # return points/72.0 * self.dpi.get() + + +class GraphicsContextTemplate(GraphicsContextBase): + """ + The graphics context provides the color, line styles, etc. See the cairo + and postscript backends for examples of mapping the graphics context + attributes (cap styles, join styles, line widths, colors) to a particular + backend. In cairo this is done by wrapping a cairo.Context object and + forwarding the appropriate calls to it using a dictionary mapping styles + to gdk constants. In Postscript, all the work is done by the renderer, + mapping line styles to postscript calls. + + If it's more appropriate to do the mapping at the renderer level (as in + the postscript backend), you don't need to override any of the GC methods. + If it's more appropriate to wrap an instance (as in the cairo backend) and + do the mapping here, you'll need to override several of the setter + methods. + + The base GraphicsContext stores colors as an RGB tuple on the unit + interval, e.g., (0.5, 0.0, 1.0). You may need to map this to colors + appropriate for your backend. + """ + + +######################################################################## +# +# The following functions and classes are for pyplot and implement +# window/figure managers, etc. +# +######################################################################## + + +class FigureManagerTemplate(FigureManagerBase): + """ + Helper class for pyplot mode, wraps everything up into a neat bundle. + + For non-interactive backends, the base class is sufficient. For + interactive backends, see the documentation of the `.FigureManagerBase` + class for the list of methods that can/should be overridden. + """ + + +class FigureCanvasTemplate(FigureCanvasBase): + """ + The canvas the figure renders into. Calls the draw and print fig + methods, creates the renderers, etc. + + Note: GUI templates will want to connect events for button presses, + mouse movements and key presses to functions that call the base + class methods button_press_event, button_release_event, + motion_notify_event, key_press_event, and key_release_event. See the + implementations of the interactive backends for examples. + + Attributes + ---------- + figure : `~matplotlib.figure.Figure` + A high-level Figure instance + """ + + # The instantiated manager class. For further customization, + # ``FigureManager.create_with_canvas`` can also be overridden; see the + # wx-based backends for an example. + manager_class = FigureManagerTemplate + + def draw(self): + """ + Draw the figure using the renderer. + + It is important that this method actually walk the artist tree + even if not output is produced because this will trigger + deferred work (like computing limits auto-limits and tick + values) that users may want access to before saving to disk. + """ + renderer = RendererTemplate(self.figure.dpi) + self.figure.draw(renderer) + + # You should provide a print_xxx function for every file format + # you can write. + + # If the file type is not in the base set of filetypes, + # you should add it to the class-scope filetypes dictionary as follows: + filetypes = {**FigureCanvasBase.filetypes, 'foo': 'My magic Foo format'} + + def print_foo(self, filename, **kwargs): + """ + Write out format foo. + + This method is normally called via `.Figure.savefig` and + `.FigureCanvasBase.print_figure`, which take care of setting the figure + facecolor, edgecolor, and dpi to the desired output values, and will + restore them to the original values. Therefore, `print_foo` does not + need to handle these settings. + """ + self.draw() + + def get_default_filetype(self): + return 'foo' + + +######################################################################## +# +# Now just provide the standard names that backend.__init__ is expecting +# +######################################################################## + +FigureCanvas = FigureCanvasTemplate +FigureManager = FigureManagerTemplate diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_webagg_core.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_webagg_core.py new file mode 100644 index 0000000000000000000000000000000000000000..4ceac1699543fd655f84f4e3c328a9acbae22354 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_webagg_core.py @@ -0,0 +1,517 @@ +"""Displays Agg images in the browser, with interactivity.""" +# The WebAgg backend is divided into two modules: +# +# - `backend_webagg_core.py` contains code necessary to embed a WebAgg +# plot inside of a web application, and communicate in an abstract +# way over a web socket. +# +# - `backend_webagg.py` contains a concrete implementation of a basic +# application, implemented with asyncio. + +import asyncio +import datetime +from io import BytesIO, StringIO +import json +import logging +import os +from pathlib import Path + +import numpy as np +from PIL import Image + +from matplotlib import _api, backend_bases, backend_tools +from matplotlib.backends import backend_agg +from matplotlib.backend_bases import ( + _Backend, KeyEvent, LocationEvent, MouseEvent, ResizeEvent) + +_log = logging.getLogger(__name__) + +_SPECIAL_KEYS_LUT = {'Alt': 'alt', + 'AltGraph': 'alt', + 'CapsLock': 'caps_lock', + 'Control': 'control', + 'Meta': 'meta', + 'NumLock': 'num_lock', + 'ScrollLock': 'scroll_lock', + 'Shift': 'shift', + 'Super': 'super', + 'Enter': 'enter', + 'Tab': 'tab', + 'ArrowDown': 'down', + 'ArrowLeft': 'left', + 'ArrowRight': 'right', + 'ArrowUp': 'up', + 'End': 'end', + 'Home': 'home', + 'PageDown': 'pagedown', + 'PageUp': 'pageup', + 'Backspace': 'backspace', + 'Delete': 'delete', + 'Insert': 'insert', + 'Escape': 'escape', + 'Pause': 'pause', + 'Select': 'select', + 'Dead': 'dead', + 'F1': 'f1', + 'F2': 'f2', + 'F3': 'f3', + 'F4': 'f4', + 'F5': 'f5', + 'F6': 'f6', + 'F7': 'f7', + 'F8': 'f8', + 'F9': 'f9', + 'F10': 'f10', + 'F11': 'f11', + 'F12': 'f12'} + + +def _handle_key(key): + """Handle key values""" + value = key[key.index('k') + 1:] + if 'shift+' in key: + if len(value) == 1: + key = key.replace('shift+', '') + if value in _SPECIAL_KEYS_LUT: + value = _SPECIAL_KEYS_LUT[value] + key = key[:key.index('k')] + value + return key + + +class TimerTornado(backend_bases.TimerBase): + def __init__(self, *args, **kwargs): + self._timer = None + super().__init__(*args, **kwargs) + + def _timer_start(self): + import tornado + + self._timer_stop() + if self._single: + ioloop = tornado.ioloop.IOLoop.instance() + self._timer = ioloop.add_timeout( + datetime.timedelta(milliseconds=self.interval), + self._on_timer) + else: + self._timer = tornado.ioloop.PeriodicCallback( + self._on_timer, + max(self.interval, 1e-6)) + self._timer.start() + + def _timer_stop(self): + import tornado + + if self._timer is None: + return + elif self._single: + ioloop = tornado.ioloop.IOLoop.instance() + ioloop.remove_timeout(self._timer) + else: + self._timer.stop() + self._timer = None + + def _timer_set_interval(self): + # Only stop and restart it if the timer has already been started + if self._timer is not None: + self._timer_stop() + self._timer_start() + + +class TimerAsyncio(backend_bases.TimerBase): + def __init__(self, *args, **kwargs): + self._task = None + super().__init__(*args, **kwargs) + + async def _timer_task(self, interval): + while True: + try: + await asyncio.sleep(interval) + self._on_timer() + + if self._single: + break + except asyncio.CancelledError: + break + + def _timer_start(self): + self._timer_stop() + + self._task = asyncio.ensure_future( + self._timer_task(max(self.interval / 1_000., 1e-6)) + ) + + def _timer_stop(self): + if self._task is not None: + self._task.cancel() + self._task = None + + def _timer_set_interval(self): + # Only stop and restart it if the timer has already been started + if self._task is not None: + self._timer_stop() + self._timer_start() + + +class FigureCanvasWebAggCore(backend_agg.FigureCanvasAgg): + manager_class = _api.classproperty(lambda cls: FigureManagerWebAgg) + _timer_cls = TimerAsyncio + # Webagg and friends having the right methods, but still + # having bugs in practice. Do not advertise that it works until + # we can debug this. + supports_blit = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Set to True when the renderer contains data that is newer + # than the PNG buffer. + self._png_is_old = True + # Set to True by the `refresh` message so that the next frame + # sent to the clients will be a full frame. + self._force_full = True + # The last buffer, for diff mode. + self._last_buff = np.empty((0, 0)) + # Store the current image mode so that at any point, clients can + # request the information. This should be changed by calling + # self.set_image_mode(mode) so that the notification can be given + # to the connected clients. + self._current_image_mode = 'full' + # Track mouse events to fill in the x, y position of key events. + self._last_mouse_xy = (None, None) + + def show(self): + # show the figure window + from matplotlib.pyplot import show + show() + + def draw(self): + self._png_is_old = True + try: + super().draw() + finally: + self.manager.refresh_all() # Swap the frames. + + def blit(self, bbox=None): + self._png_is_old = True + self.manager.refresh_all() + + def draw_idle(self): + self.send_event("draw") + + def set_cursor(self, cursor): + # docstring inherited + cursor = _api.check_getitem({ + backend_tools.Cursors.HAND: 'pointer', + backend_tools.Cursors.POINTER: 'default', + backend_tools.Cursors.SELECT_REGION: 'crosshair', + backend_tools.Cursors.MOVE: 'move', + backend_tools.Cursors.WAIT: 'wait', + backend_tools.Cursors.RESIZE_HORIZONTAL: 'ew-resize', + backend_tools.Cursors.RESIZE_VERTICAL: 'ns-resize', + }, cursor=cursor) + self.send_event('cursor', cursor=cursor) + + def set_image_mode(self, mode): + """ + Set the image mode for any subsequent images which will be sent + to the clients. The modes may currently be either 'full' or 'diff'. + + Note: diff images may not contain transparency, therefore upon + draw this mode may be changed if the resulting image has any + transparent component. + """ + _api.check_in_list(['full', 'diff'], mode=mode) + if self._current_image_mode != mode: + self._current_image_mode = mode + self.handle_send_image_mode(None) + + def get_diff_image(self): + if self._png_is_old: + renderer = self.get_renderer() + + pixels = np.asarray(renderer.buffer_rgba()) + # The buffer is created as type uint32 so that entire + # pixels can be compared in one numpy call, rather than + # needing to compare each plane separately. + buff = pixels.view(np.uint32).squeeze(2) + + if (self._force_full + # If the buffer has changed size we need to do a full draw. + or buff.shape != self._last_buff.shape + # If any pixels have transparency, we need to force a full + # draw as we cannot overlay new on top of old. + or (pixels[:, :, 3] != 255).any()): + self.set_image_mode('full') + output = buff + else: + self.set_image_mode('diff') + diff = buff != self._last_buff + output = np.where(diff, buff, 0) + + # Store the current buffer so we can compute the next diff. + self._last_buff = buff.copy() + self._force_full = False + self._png_is_old = False + + data = output.view(dtype=np.uint8).reshape((*output.shape, 4)) + with BytesIO() as png: + Image.fromarray(data).save(png, format="png") + return png.getvalue() + + def handle_event(self, event): + e_type = event['type'] + handler = getattr(self, f'handle_{e_type}', + self.handle_unknown_event) + return handler(event) + + def handle_unknown_event(self, event): + _log.warning('Unhandled message type %s. %s', event["type"], event) + + def handle_ack(self, event): + # Network latency tends to decrease if traffic is flowing + # in both directions. Therefore, the browser sends back + # an "ack" message after each image frame is received. + # This could also be used as a simple sanity check in the + # future, but for now the performance increase is enough + # to justify it, even if the server does nothing with it. + pass + + def handle_draw(self, event): + self.draw() + + def _handle_mouse(self, event): + x = event['x'] + y = event['y'] + y = self.get_renderer().height - y + self._last_mouse_xy = x, y + # JavaScript button numbers and Matplotlib button numbers are off by 1. + button = event['button'] + 1 + + e_type = event['type'] + modifiers = event['modifiers'] + guiEvent = event.get('guiEvent') + if e_type in ['button_press', 'button_release']: + MouseEvent(e_type + '_event', self, x, y, button, + modifiers=modifiers, guiEvent=guiEvent)._process() + elif e_type == 'dblclick': + MouseEvent('button_press_event', self, x, y, button, dblclick=True, + modifiers=modifiers, guiEvent=guiEvent)._process() + elif e_type == 'scroll': + MouseEvent('scroll_event', self, x, y, step=event['step'], + modifiers=modifiers, guiEvent=guiEvent)._process() + elif e_type == 'motion_notify': + MouseEvent(e_type + '_event', self, x, y, + modifiers=modifiers, guiEvent=guiEvent)._process() + elif e_type in ['figure_enter', 'figure_leave']: + LocationEvent(e_type + '_event', self, x, y, + modifiers=modifiers, guiEvent=guiEvent)._process() + handle_button_press = handle_button_release = handle_dblclick = \ + handle_figure_enter = handle_figure_leave = handle_motion_notify = \ + handle_scroll = _handle_mouse + + def _handle_key(self, event): + KeyEvent(event['type'] + '_event', self, + _handle_key(event['key']), *self._last_mouse_xy, + guiEvent=event.get('guiEvent'))._process() + handle_key_press = handle_key_release = _handle_key + + def handle_toolbar_button(self, event): + # TODO: Be more suspicious of the input + getattr(self.toolbar, event['name'])() + + def handle_refresh(self, event): + figure_label = self.figure.get_label() + if not figure_label: + figure_label = f"Figure {self.manager.num}" + self.send_event('figure_label', label=figure_label) + self._force_full = True + if self.toolbar: + # Normal toolbar init would refresh this, but it happens before the + # browser canvas is set up. + self.toolbar.set_history_buttons() + self.draw_idle() + + def handle_resize(self, event): + x = int(event.get('width', 800)) * self.device_pixel_ratio + y = int(event.get('height', 800)) * self.device_pixel_ratio + fig = self.figure + # An attempt at approximating the figure size in pixels. + fig.set_size_inches(x / fig.dpi, y / fig.dpi, forward=False) + # Acknowledge the resize, and force the viewer to update the + # canvas size to the figure's new size (which is hopefully + # identical or within a pixel or so). + self._png_is_old = True + self.manager.resize(*fig.bbox.size, forward=False) + ResizeEvent('resize_event', self)._process() + self.draw_idle() + + def handle_send_image_mode(self, event): + # The client requests notification of what the current image mode is. + self.send_event('image_mode', mode=self._current_image_mode) + + def handle_set_device_pixel_ratio(self, event): + self._handle_set_device_pixel_ratio(event.get('device_pixel_ratio', 1)) + + def handle_set_dpi_ratio(self, event): + # This handler is for backwards-compatibility with older ipympl. + self._handle_set_device_pixel_ratio(event.get('dpi_ratio', 1)) + + def _handle_set_device_pixel_ratio(self, device_pixel_ratio): + if self._set_device_pixel_ratio(device_pixel_ratio): + self._force_full = True + self.draw_idle() + + def send_event(self, event_type, **kwargs): + if self.manager: + self.manager._send_event(event_type, **kwargs) + + +_ALLOWED_TOOL_ITEMS = { + 'home', + 'back', + 'forward', + 'pan', + 'zoom', + 'download', + None, +} + + +class NavigationToolbar2WebAgg(backend_bases.NavigationToolbar2): + + # Use the standard toolbar items + download button + toolitems = [ + (text, tooltip_text, image_file, name_of_method) + for text, tooltip_text, image_file, name_of_method + in (*backend_bases.NavigationToolbar2.toolitems, + ('Download', 'Download plot', 'filesave', 'download')) + if name_of_method in _ALLOWED_TOOL_ITEMS + ] + + def __init__(self, canvas): + self.message = '' + super().__init__(canvas) + + def set_message(self, message): + if message != self.message: + self.canvas.send_event("message", message=message) + self.message = message + + def draw_rubberband(self, event, x0, y0, x1, y1): + self.canvas.send_event("rubberband", x0=x0, y0=y0, x1=x1, y1=y1) + + def remove_rubberband(self): + self.canvas.send_event("rubberband", x0=-1, y0=-1, x1=-1, y1=-1) + + def save_figure(self, *args): + """Save the current figure""" + self.canvas.send_event('save') + + def pan(self): + super().pan() + self.canvas.send_event('navigate_mode', mode=self.mode.name) + + def zoom(self): + super().zoom() + self.canvas.send_event('navigate_mode', mode=self.mode.name) + + def set_history_buttons(self): + can_backward = self._nav_stack._pos > 0 + can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 + self.canvas.send_event('history_buttons', + Back=can_backward, Forward=can_forward) + + +class FigureManagerWebAgg(backend_bases.FigureManagerBase): + # This must be None to not break ipympl + _toolbar2_class = None + ToolbarCls = NavigationToolbar2WebAgg + _window_title = "Matplotlib" + + def __init__(self, canvas, num): + self.web_sockets = set() + super().__init__(canvas, num) + + def show(self): + pass + + def resize(self, w, h, forward=True): + self._send_event( + 'resize', + size=(w / self.canvas.device_pixel_ratio, + h / self.canvas.device_pixel_ratio), + forward=forward) + + def set_window_title(self, title): + self._send_event('figure_label', label=title) + self._window_title = title + + def get_window_title(self): + return self._window_title + + # The following methods are specific to FigureManagerWebAgg + + def add_web_socket(self, web_socket): + assert hasattr(web_socket, 'send_binary') + assert hasattr(web_socket, 'send_json') + self.web_sockets.add(web_socket) + self.resize(*self.canvas.figure.bbox.size) + self._send_event('refresh') + + def remove_web_socket(self, web_socket): + self.web_sockets.remove(web_socket) + + def handle_json(self, content): + self.canvas.handle_event(content) + + def refresh_all(self): + if self.web_sockets: + diff = self.canvas.get_diff_image() + if diff is not None: + for s in self.web_sockets: + s.send_binary(diff) + + @classmethod + def get_javascript(cls, stream=None): + if stream is None: + output = StringIO() + else: + output = stream + + output.write((Path(__file__).parent / "web_backend/js/mpl.js") + .read_text(encoding="utf-8")) + + toolitems = [] + for name, tooltip, image, method in cls.ToolbarCls.toolitems: + if name is None: + toolitems.append(['', '', '', '']) + else: + toolitems.append([name, tooltip, image, method]) + output.write(f"mpl.toolbar_items = {json.dumps(toolitems)};\n\n") + + extensions = [] + for filetype, ext in sorted(FigureCanvasWebAggCore. + get_supported_filetypes_grouped(). + items()): + extensions.append(ext[0]) + output.write(f"mpl.extensions = {json.dumps(extensions)};\n\n") + + output.write("mpl.default_extension = {};".format( + json.dumps(FigureCanvasWebAggCore.get_default_filetype()))) + + if stream is None: + return output.getvalue() + + @classmethod + def get_static_file_path(cls): + return os.path.join(os.path.dirname(__file__), 'web_backend') + + def _send_event(self, event_type, **kwargs): + payload = {'type': event_type, **kwargs} + for s in self.web_sockets: + s.send_json(payload) + + +@_Backend.export +class _BackendWebAggCoreAgg(_Backend): + FigureCanvas = FigureCanvasWebAggCore + FigureManager = FigureManagerWebAgg diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_wxagg.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_wxagg.py new file mode 100644 index 0000000000000000000000000000000000000000..ab7703ffa02b8e85b845321f52a9ecdc09b2dfa8 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/backend_wxagg.py @@ -0,0 +1,45 @@ +import wx + +from .backend_agg import FigureCanvasAgg +from .backend_wx import _BackendWx, _FigureCanvasWxBase +from .backend_wx import ( # noqa: F401 # pylint: disable=W0611 + NavigationToolbar2Wx as NavigationToolbar2WxAgg) + + +class FigureCanvasWxAgg(FigureCanvasAgg, _FigureCanvasWxBase): + def draw(self, drawDC=None): + """ + Render the figure using agg. + """ + FigureCanvasAgg.draw(self) + self.bitmap = self._create_bitmap() + self._isDrawn = True + self.gui_repaint(drawDC=drawDC) + + def blit(self, bbox=None): + # docstring inherited + bitmap = self._create_bitmap() + if bbox is None: + self.bitmap = bitmap + else: + srcDC = wx.MemoryDC(bitmap) + destDC = wx.MemoryDC(self.bitmap) + x = int(bbox.x0) + y = int(self.bitmap.GetHeight() - bbox.y1) + destDC.Blit(x, y, int(bbox.width), int(bbox.height), srcDC, x, y) + destDC.SelectObject(wx.NullBitmap) + srcDC.SelectObject(wx.NullBitmap) + self.gui_repaint() + + def _create_bitmap(self): + """Create a wx.Bitmap from the renderer RGBA buffer""" + rgba = self.get_renderer().buffer_rgba() + h, w, _ = rgba.shape + bitmap = wx.Bitmap.FromBufferRGBA(w, h, rgba) + bitmap.SetScaleFactor(self.GetDPIScaleFactor()) + return bitmap + + +@_BackendWx.export +class _BackendWxAgg(_BackendWx): + FigureCanvas = FigureCanvasWxAgg diff --git a/parrot/lib/python3.10/site-packages/matplotlib/backends/registry.py b/parrot/lib/python3.10/site-packages/matplotlib/backends/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..e08817bb089bda286a3d6e7c406bd98fdcc734b3 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/backends/registry.py @@ -0,0 +1,420 @@ +from enum import Enum +import importlib + + +class BackendFilter(Enum): + """ + Filter used with :meth:`~matplotlib.backends.registry.BackendRegistry.list_builtin` + + .. versionadded:: 3.9 + """ + INTERACTIVE = 0 + NON_INTERACTIVE = 1 + + +class BackendRegistry: + """ + Registry of backends available within Matplotlib. + + This is the single source of truth for available backends. + + All use of ``BackendRegistry`` should be via the singleton instance + ``backend_registry`` which can be imported from ``matplotlib.backends``. + + Each backend has a name, a module name containing the backend code, and an + optional GUI framework that must be running if the backend is interactive. + There are three sources of backends: built-in (source code is within the + Matplotlib repository), explicit ``module://some.backend`` syntax (backend is + obtained by loading the module), or via an entry point (self-registering + backend in an external package). + + .. versionadded:: 3.9 + """ + # Mapping of built-in backend name to GUI framework, or "headless" for no + # GUI framework. Built-in backends are those which are included in the + # Matplotlib repo. A backend with name 'name' is located in the module + # f"matplotlib.backends.backend_{name.lower()}" + _BUILTIN_BACKEND_TO_GUI_FRAMEWORK = { + "gtk3agg": "gtk3", + "gtk3cairo": "gtk3", + "gtk4agg": "gtk4", + "gtk4cairo": "gtk4", + "macosx": "macosx", + "nbagg": "nbagg", + "notebook": "nbagg", + "qtagg": "qt", + "qtcairo": "qt", + "qt5agg": "qt5", + "qt5cairo": "qt5", + "tkagg": "tk", + "tkcairo": "tk", + "webagg": "webagg", + "wx": "wx", + "wxagg": "wx", + "wxcairo": "wx", + "agg": "headless", + "cairo": "headless", + "pdf": "headless", + "pgf": "headless", + "ps": "headless", + "svg": "headless", + "template": "headless", + } + + # Reverse mapping of gui framework to preferred built-in backend. + _GUI_FRAMEWORK_TO_BACKEND = { + "gtk3": "gtk3agg", + "gtk4": "gtk4agg", + "headless": "agg", + "macosx": "macosx", + "qt": "qtagg", + "qt5": "qt5agg", + "qt6": "qtagg", + "tk": "tkagg", + "wx": "wxagg", + } + + def __init__(self): + # Only load entry points when first needed. + self._loaded_entry_points = False + + # Mapping of non-built-in backend to GUI framework, added dynamically from + # entry points and from matplotlib.use("module://some.backend") format. + # New entries have an "unknown" GUI framework that is determined when first + # needed by calling _get_gui_framework_by_loading. + self._backend_to_gui_framework = {} + + # Mapping of backend name to module name, where different from + # f"matplotlib.backends.backend_{backend_name.lower()}". These are either + # hardcoded for backward compatibility, or loaded from entry points or + # "module://some.backend" syntax. + self._name_to_module = { + "notebook": "nbagg", + } + + def _backend_module_name(self, backend): + if backend.startswith("module://"): + return backend[9:] + + # Return name of module containing the specified backend. + # Does not check if the backend is valid, use is_valid_backend for that. + backend = backend.lower() + + # Check if have specific name to module mapping. + backend = self._name_to_module.get(backend, backend) + + return (backend[9:] if backend.startswith("module://") + else f"matplotlib.backends.backend_{backend}") + + def _clear(self): + # Clear all dynamically-added data, used for testing only. + self.__init__() + + def _ensure_entry_points_loaded(self): + # Load entry points, if they have not already been loaded. + if not self._loaded_entry_points: + entries = self._read_entry_points() + self._validate_and_store_entry_points(entries) + self._loaded_entry_points = True + + def _get_gui_framework_by_loading(self, backend): + # Determine GUI framework for a backend by loading its module and reading the + # FigureCanvas.required_interactive_framework attribute. + # Returns "headless" if there is no GUI framework. + module = self.load_backend_module(backend) + canvas_class = module.FigureCanvas + return canvas_class.required_interactive_framework or "headless" + + def _read_entry_points(self): + # Read entry points of modules that self-advertise as Matplotlib backends. + # Expects entry points like this one from matplotlib-inline (in pyproject.toml + # format): + # [project.entry-points."matplotlib.backend"] + # inline = "matplotlib_inline.backend_inline" + import importlib.metadata as im + import sys + + # entry_points group keyword not available before Python 3.10 + group = "matplotlib.backend" + if sys.version_info >= (3, 10): + entry_points = im.entry_points(group=group) + else: + entry_points = im.entry_points().get(group, ()) + entries = [(entry.name, entry.value) for entry in entry_points] + + # For backward compatibility, if matplotlib-inline and/or ipympl are installed + # but too old to include entry points, create them. Do not import ipympl + # directly as this calls matplotlib.use() whilst in this function. + def backward_compatible_entry_points( + entries, module_name, threshold_version, names, target): + from matplotlib import _parse_to_version_info + try: + module_version = im.version(module_name) + if _parse_to_version_info(module_version) < threshold_version: + for name in names: + entries.append((name, target)) + except im.PackageNotFoundError: + pass + + names = [entry[0] for entry in entries] + if "inline" not in names: + backward_compatible_entry_points( + entries, "matplotlib_inline", (0, 1, 7), ["inline"], + "matplotlib_inline.backend_inline") + if "ipympl" not in names: + backward_compatible_entry_points( + entries, "ipympl", (0, 9, 4), ["ipympl", "widget"], + "ipympl.backend_nbagg") + + return entries + + def _validate_and_store_entry_points(self, entries): + # Validate and store entry points so that they can be used via matplotlib.use() + # in the normal manner. Entry point names cannot be of module:// format, cannot + # shadow a built-in backend name, and there cannot be multiple entry points + # with the same name but different modules. Multiple entry points with the same + # name and value are permitted (it can sometimes happen outside of our control, + # see https://github.com/matplotlib/matplotlib/issues/28367). + for name, module in set(entries): + name = name.lower() + if name.startswith("module://"): + raise RuntimeError( + f"Entry point name '{name}' cannot start with 'module://'") + if name in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK: + raise RuntimeError(f"Entry point name '{name}' is a built-in backend") + if name in self._backend_to_gui_framework: + raise RuntimeError(f"Entry point name '{name}' duplicated") + + self._name_to_module[name] = "module://" + module + # Do not yet know backend GUI framework, determine it only when necessary. + self._backend_to_gui_framework[name] = "unknown" + + def backend_for_gui_framework(self, framework): + """ + Return the name of the backend corresponding to the specified GUI framework. + + Parameters + ---------- + framework : str + GUI framework such as "qt". + + Returns + ------- + str or None + Backend name or None if GUI framework not recognised. + """ + return self._GUI_FRAMEWORK_TO_BACKEND.get(framework.lower()) + + def is_valid_backend(self, backend): + """ + Return True if the backend name is valid, False otherwise. + + A backend name is valid if it is one of the built-in backends or has been + dynamically added via an entry point. Those beginning with ``module://`` are + always considered valid and are added to the current list of all backends + within this function. + + Even if a name is valid, it may not be importable or usable. This can only be + determined by loading and using the backend module. + + Parameters + ---------- + backend : str + Name of backend. + + Returns + ------- + bool + True if backend is valid, False otherwise. + """ + if not backend.startswith("module://"): + backend = backend.lower() + + # For backward compatibility, convert ipympl and matplotlib-inline long + # module:// names to their shortened forms. + backwards_compat = { + "module://ipympl.backend_nbagg": "widget", + "module://matplotlib_inline.backend_inline": "inline", + } + backend = backwards_compat.get(backend, backend) + + if (backend in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK or + backend in self._backend_to_gui_framework): + return True + + if backend.startswith("module://"): + self._backend_to_gui_framework[backend] = "unknown" + return True + + # Only load entry points if really need to and not already done so. + self._ensure_entry_points_loaded() + if backend in self._backend_to_gui_framework: + return True + + return False + + def list_all(self): + """ + Return list of all known backends. + + These include built-in backends and those obtained at runtime either from entry + points or explicit ``module://some.backend`` syntax. + + Entry points will be loaded if they haven't been already. + + Returns + ------- + list of str + Backend names. + """ + self._ensure_entry_points_loaded() + return [*self.list_builtin(), *self._backend_to_gui_framework] + + def list_builtin(self, filter_=None): + """ + Return list of backends that are built into Matplotlib. + + Parameters + ---------- + filter_ : `~.BackendFilter`, optional + Filter to apply to returned backends. For example, to return only + non-interactive backends use `.BackendFilter.NON_INTERACTIVE`. + + Returns + ------- + list of str + Backend names. + """ + if filter_ == BackendFilter.INTERACTIVE: + return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items() + if v != "headless"] + elif filter_ == BackendFilter.NON_INTERACTIVE: + return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items() + if v == "headless"] + + return [*self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK] + + def list_gui_frameworks(self): + """ + Return list of GUI frameworks used by Matplotlib backends. + + Returns + ------- + list of str + GUI framework names. + """ + return [k for k in self._GUI_FRAMEWORK_TO_BACKEND if k != "headless"] + + def load_backend_module(self, backend): + """ + Load and return the module containing the specified backend. + + Parameters + ---------- + backend : str + Name of backend to load. + + Returns + ------- + Module + Module containing backend. + """ + module_name = self._backend_module_name(backend) + return importlib.import_module(module_name) + + def resolve_backend(self, backend): + """ + Return the backend and GUI framework for the specified backend name. + + If the GUI framework is not yet known then it will be determined by loading the + backend module and checking the ``FigureCanvas.required_interactive_framework`` + attribute. + + This function only loads entry points if they have not already been loaded and + the backend is not built-in and not of ``module://some.backend`` format. + + Parameters + ---------- + backend : str or None + Name of backend, or None to use the default backend. + + Returns + ------- + backend : str + The backend name. + framework : str or None + The GUI framework, which will be None for a backend that is non-interactive. + """ + if isinstance(backend, str): + if not backend.startswith("module://"): + backend = backend.lower() + else: # Might be _auto_backend_sentinel or None + # Use whatever is already running... + from matplotlib import get_backend + backend = get_backend() + + # Is backend already known (built-in or dynamically loaded)? + gui = (self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.get(backend) or + self._backend_to_gui_framework.get(backend)) + + # Is backend "module://something"? + if gui is None and isinstance(backend, str) and backend.startswith("module://"): + gui = "unknown" + + # Is backend a possible entry point? + if gui is None and not self._loaded_entry_points: + self._ensure_entry_points_loaded() + gui = self._backend_to_gui_framework.get(backend) + + # Backend known but not its gui framework. + if gui == "unknown": + gui = self._get_gui_framework_by_loading(backend) + self._backend_to_gui_framework[backend] = gui + + if gui is None: + raise RuntimeError(f"'{backend}' is not a recognised backend name") + + return backend, gui if gui != "headless" else None + + def resolve_gui_or_backend(self, gui_or_backend): + """ + Return the backend and GUI framework for the specified string that may be + either a GUI framework or a backend name, tested in that order. + + This is for use with the IPython %matplotlib magic command which may be a GUI + framework such as ``%matplotlib qt`` or a backend name such as + ``%matplotlib qtagg``. + + This function only loads entry points if they have not already been loaded and + the backend is not built-in and not of ``module://some.backend`` format. + + Parameters + ---------- + gui_or_backend : str or None + Name of GUI framework or backend, or None to use the default backend. + + Returns + ------- + backend : str + The backend name. + framework : str or None + The GUI framework, which will be None for a backend that is non-interactive. + """ + if not gui_or_backend.startswith("module://"): + gui_or_backend = gui_or_backend.lower() + + # First check if it is a gui loop name. + backend = self.backend_for_gui_framework(gui_or_backend) + if backend is not None: + return backend, gui_or_backend if gui_or_backend != "headless" else None + + # Then check if it is a backend name. + try: + return self.resolve_backend(gui_or_backend) + except Exception: # KeyError ? + raise RuntimeError( + f"'{gui_or_backend} is not a recognised GUI loop or backend name") + + +# Singleton +backend_registry = BackendRegistry() diff --git a/parrot/lib/python3.10/site-packages/matplotlib/pyplot.py b/parrot/lib/python3.10/site-packages/matplotlib/pyplot.py new file mode 100644 index 0000000000000000000000000000000000000000..442013f7d21a88b5f549bd17249304bc6da57424 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/pyplot.py @@ -0,0 +1,4597 @@ +# Note: The first part of this file can be modified in place, but the latter +# part is autogenerated by the boilerplate.py script. + +""" +`matplotlib.pyplot` is a state-based interface to matplotlib. It provides +an implicit, MATLAB-like, way of plotting. It also opens figures on your +screen, and acts as the figure GUI manager. + +pyplot is mainly intended for interactive plots and simple cases of +programmatic plot generation:: + + import numpy as np + import matplotlib.pyplot as plt + + x = np.arange(0, 5, 0.1) + y = np.sin(x) + plt.plot(x, y) + +The explicit object-oriented API is recommended for complex plots, though +pyplot is still usually used to create the figure and often the Axes in the +figure. See `.pyplot.figure`, `.pyplot.subplots`, and +`.pyplot.subplot_mosaic` to create figures, and +:doc:`Axes API ` for the plotting methods on an Axes:: + + import numpy as np + import matplotlib.pyplot as plt + + x = np.arange(0, 5, 0.1) + y = np.sin(x) + fig, ax = plt.subplots() + ax.plot(x, y) + + +See :ref:`api_interfaces` for an explanation of the tradeoffs between the +implicit and explicit interfaces. +""" + +# fmt: off + +from __future__ import annotations + +from contextlib import AbstractContextManager, ExitStack +from enum import Enum +import functools +import importlib +import inspect +import logging +import sys +import threading +import time +from typing import TYPE_CHECKING, cast, overload + +from cycler import cycler # noqa: F401 +import matplotlib +import matplotlib.colorbar +import matplotlib.image +from matplotlib import _api +from matplotlib import ( # noqa: F401 Re-exported for typing. + cm as cm, get_backend as get_backend, rcParams as rcParams, style as style) +from matplotlib import _pylab_helpers +from matplotlib import interactive # noqa: F401 +from matplotlib import cbook +from matplotlib import _docstring +from matplotlib.backend_bases import ( + FigureCanvasBase, FigureManagerBase, MouseButton) +from matplotlib.figure import Figure, FigureBase, figaspect +from matplotlib.gridspec import GridSpec, SubplotSpec +from matplotlib import rcsetup, rcParamsDefault, rcParamsOrig +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.axes import Subplot # noqa: F401 +from matplotlib.backends import BackendFilter, backend_registry +from matplotlib.projections import PolarAxes +from matplotlib import mlab # for detrend_none, window_hanning +from matplotlib.scale import get_scale_names # noqa: F401 + +from matplotlib.cm import _colormaps +from matplotlib.colors import _color_sequences, Colormap + +import numpy as np + +if TYPE_CHECKING: + from collections.abc import Callable, Hashable, Iterable, Sequence + import datetime + import pathlib + import os + from typing import Any, BinaryIO, Literal, TypeVar + from typing_extensions import ParamSpec + + import PIL.Image + from numpy.typing import ArrayLike + + import matplotlib.axes + import matplotlib.artist + import matplotlib.backend_bases + from matplotlib.axis import Tick + from matplotlib.axes._base import _AxesBase + from matplotlib.backend_bases import RendererBase, Event + from matplotlib.cm import ScalarMappable + from matplotlib.contour import ContourSet, QuadContourSet + from matplotlib.collections import ( + Collection, + LineCollection, + PolyCollection, + PathCollection, + EventCollection, + QuadMesh, + ) + from matplotlib.colorbar import Colorbar + from matplotlib.container import ( + BarContainer, + ErrorbarContainer, + StemContainer, + ) + from matplotlib.figure import SubFigure + from matplotlib.legend import Legend + from matplotlib.mlab import GaussianKDE + from matplotlib.image import AxesImage, FigureImage + from matplotlib.patches import FancyArrow, StepPatch, Wedge + from matplotlib.quiver import Barbs, Quiver, QuiverKey + from matplotlib.scale import ScaleBase + from matplotlib.transforms import Transform, Bbox + from matplotlib.typing import ColorType, LineStyleType, MarkerType, HashableList + from matplotlib.widgets import SubplotTool + + _P = ParamSpec('_P') + _R = TypeVar('_R') + _T = TypeVar('_T') + + +# We may not need the following imports here: +from matplotlib.colors import Normalize +from matplotlib.lines import Line2D, AxLine +from matplotlib.text import Text, Annotation +from matplotlib.patches import Arrow, Circle, Rectangle # noqa: F401 +from matplotlib.patches import Polygon +from matplotlib.widgets import Button, Slider, Widget # noqa: F401 + +from .ticker import ( # noqa: F401 + TickHelper, Formatter, FixedFormatter, NullFormatter, FuncFormatter, + FormatStrFormatter, ScalarFormatter, LogFormatter, LogFormatterExponent, + LogFormatterMathtext, Locator, IndexLocator, FixedLocator, NullLocator, + LinearLocator, LogLocator, AutoLocator, MultipleLocator, MaxNLocator) + +_log = logging.getLogger(__name__) + + +# Explicit rename instead of import-as for typing's sake. +colormaps = _colormaps +color_sequences = _color_sequences + + +@overload +def _copy_docstring_and_deprecators( + method: Any, + func: Literal[None] = None +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... + + +@overload +def _copy_docstring_and_deprecators( + method: Any, func: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +def _copy_docstring_and_deprecators( + method: Any, + func: Callable[_P, _R] | None = None +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[_P, _R]: + if func is None: + return cast('Callable[[Callable[_P, _R]], Callable[_P, _R]]', + functools.partial(_copy_docstring_and_deprecators, method)) + decorators: list[Callable[[Callable[_P, _R]], Callable[_P, _R]]] = [ + _docstring.copy(method) + ] + # Check whether the definition of *method* includes @_api.rename_parameter + # or @_api.make_keyword_only decorators; if so, propagate them to the + # pyplot wrapper as well. + while hasattr(method, "__wrapped__"): + potential_decorator = _api.deprecation.DECORATORS.get(method) + if potential_decorator: + decorators.append(potential_decorator) + method = method.__wrapped__ + for decorator in decorators[::-1]: + func = decorator(func) + _add_pyplot_note(func, method) + return func + + +_NO_PYPLOT_NOTE = [ + 'FigureBase._gci', # wrapped_func is private + '_AxesBase._sci', # wrapped_func is private + 'Artist.findobj', # not a standard pyplot wrapper because it does not operate + # on the current Figure / Axes. Explanation of relation would + # be more complex and is not too important. +] + + +def _add_pyplot_note(func, wrapped_func): + """ + Add a note to the docstring of *func* that it is a pyplot wrapper. + + The note is added to the "Notes" section of the docstring. If that does + not exist, a "Notes" section is created. In numpydoc, the "Notes" + section is the third last possible section, only potentially followed by + "References" and "Examples". + """ + if not func.__doc__: + return # nothing to do + + qualname = wrapped_func.__qualname__ + if qualname in _NO_PYPLOT_NOTE: + return + + wrapped_func_is_method = True + if "." not in qualname: + # method qualnames are prefixed by the class and ".", e.g. "Axes.plot" + wrapped_func_is_method = False + link = f"{wrapped_func.__module__}.{qualname}" + elif qualname.startswith("Axes."): # e.g. "Axes.plot" + link = ".axes." + qualname + elif qualname.startswith("_AxesBase."): # e.g. "_AxesBase.set_xlabel" + link = ".axes.Axes" + qualname[9:] + elif qualname.startswith("Figure."): # e.g. "Figure.figimage" + link = "." + qualname + elif qualname.startswith("FigureBase."): # e.g. "FigureBase.gca" + link = ".Figure" + qualname[10:] + elif qualname.startswith("FigureCanvasBase."): # "FigureBaseCanvas.mpl_connect" + link = "." + qualname + else: + raise RuntimeError(f"Wrapped method from unexpected class: {qualname}") + + if wrapped_func_is_method: + message = f"This is the :ref:`pyplot wrapper ` for `{link}`." + else: + message = f"This is equivalent to `{link}`." + + # Find the correct insert position: + # - either we already have a "Notes" section into which we can insert + # - or we create one before the next present section. Note that in numpydoc, the + # "Notes" section is the third last possible section, only potentially followed + # by "References" and "Examples". + # - or we append a new "Notes" section at the end. + doc = inspect.cleandoc(func.__doc__) + if "\nNotes\n-----" in doc: + before, after = doc.split("\nNotes\n-----", 1) + elif (index := doc.find("\nReferences\n----------")) != -1: + before, after = doc[:index], doc[index:] + elif (index := doc.find("\nExamples\n--------")) != -1: + before, after = doc[:index], doc[index:] + else: + # No "Notes", "References", or "Examples" --> append to the end. + before = doc + "\n" + after = "" + + func.__doc__ = f"{before}\nNotes\n-----\n\n.. note::\n\n {message}\n{after}" + + +## Global ## + + +# The state controlled by {,un}install_repl_displayhook(). +_ReplDisplayHook = Enum("_ReplDisplayHook", ["NONE", "PLAIN", "IPYTHON"]) +_REPL_DISPLAYHOOK = _ReplDisplayHook.NONE + + +def _draw_all_if_interactive() -> None: + if matplotlib.is_interactive(): + draw_all() + + +def install_repl_displayhook() -> None: + """ + Connect to the display hook of the current shell. + + The display hook gets called when the read-evaluate-print-loop (REPL) of + the shell has finished the execution of a command. We use this callback + to be able to automatically update a figure in interactive mode. + + This works both with IPython and with vanilla python shells. + """ + global _REPL_DISPLAYHOOK + + if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON: + return + + # See if we have IPython hooks around, if so use them. + # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as + # entries can also have been explicitly set to None. + mod_ipython = sys.modules.get("IPython") + if not mod_ipython: + _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN + return + ip = mod_ipython.get_ipython() + if not ip: + _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN + return + + ip.events.register("post_execute", _draw_all_if_interactive) + _REPL_DISPLAYHOOK = _ReplDisplayHook.IPYTHON + + if mod_ipython.version_info[:2] < (8, 24): + # Use of backend2gui is not needed for IPython >= 8.24 as that functionality + # has been moved to Matplotlib. + # This code can be removed when Python 3.12, the latest version supported by + # IPython < 8.24, reaches end-of-life in late 2028. + from IPython.core.pylabtools import backend2gui + ipython_gui_name = backend2gui.get(get_backend()) + else: + _, ipython_gui_name = backend_registry.resolve_backend(get_backend()) + # trigger IPython's eventloop integration, if available + if ipython_gui_name: + ip.enable_gui(ipython_gui_name) + + +def uninstall_repl_displayhook() -> None: + """Disconnect from the display hook of the current shell.""" + global _REPL_DISPLAYHOOK + if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON: + from IPython import get_ipython + ip = get_ipython() + ip.events.unregister("post_execute", _draw_all_if_interactive) + _REPL_DISPLAYHOOK = _ReplDisplayHook.NONE + + +draw_all = _pylab_helpers.Gcf.draw_all + + +# Ensure this appears in the pyplot docs. +@_copy_docstring_and_deprecators(matplotlib.set_loglevel) +def set_loglevel(*args, **kwargs) -> None: + return matplotlib.set_loglevel(*args, **kwargs) + + +@_copy_docstring_and_deprecators(Artist.findobj) +def findobj( + o: Artist | None = None, + match: Callable[[Artist], bool] | type[Artist] | None = None, + include_self: bool = True +) -> list[Artist]: + if o is None: + o = gcf() + return o.findobj(match, include_self=include_self) + + +_backend_mod: type[matplotlib.backend_bases._Backend] | None = None + + +def _get_backend_mod() -> type[matplotlib.backend_bases._Backend]: + """ + Ensure that a backend is selected and return it. + + This is currently private, but may be made public in the future. + """ + if _backend_mod is None: + # Use rcParams._get("backend") to avoid going through the fallback + # logic (which will (re)import pyplot and then call switch_backend if + # we need to resolve the auto sentinel) + switch_backend(rcParams._get("backend")) + return cast(type[matplotlib.backend_bases._Backend], _backend_mod) + + +def switch_backend(newbackend: str) -> None: + """ + Set the pyplot backend. + + Switching to an interactive backend is possible only if no event loop for + another interactive backend has started. Switching to and from + non-interactive backends is always possible. + + If the new backend is different than the current backend then all open + Figures will be closed via ``plt.close('all')``. + + Parameters + ---------- + newbackend : str + The case-insensitive name of the backend to use. + + """ + global _backend_mod + # make sure the init is pulled up so we can assign to it later + import matplotlib.backends + + if newbackend is rcsetup._auto_backend_sentinel: + current_framework = cbook._get_running_interactive_framework() + + if (current_framework and + (backend := backend_registry.backend_for_gui_framework( + current_framework))): + candidates = [backend] + else: + candidates = [] + candidates += [ + "macosx", "qtagg", "gtk4agg", "gtk3agg", "tkagg", "wxagg"] + + # Don't try to fallback on the cairo-based backends as they each have + # an additional dependency (pycairo) over the agg-based backend, and + # are of worse quality. + for candidate in candidates: + try: + switch_backend(candidate) + except ImportError: + continue + else: + rcParamsOrig['backend'] = candidate + return + else: + # Switching to Agg should always succeed; if it doesn't, let the + # exception propagate out. + switch_backend("agg") + rcParamsOrig["backend"] = "agg" + return + # have to escape the switch on access logic + old_backend = dict.__getitem__(rcParams, 'backend') + + module = backend_registry.load_backend_module(newbackend) + canvas_class = module.FigureCanvas + + required_framework = canvas_class.required_interactive_framework + if required_framework is not None: + current_framework = cbook._get_running_interactive_framework() + if (current_framework and required_framework + and current_framework != required_framework): + raise ImportError( + "Cannot load backend {!r} which requires the {!r} interactive " + "framework, as {!r} is currently running".format( + newbackend, required_framework, current_framework)) + + # Load the new_figure_manager() and show() functions from the backend. + + # Classically, backends can directly export these functions. This should + # keep working for backcompat. + new_figure_manager = getattr(module, "new_figure_manager", None) + show = getattr(module, "show", None) + + # In that classical approach, backends are implemented as modules, but + # "inherit" default method implementations from backend_bases._Backend. + # This is achieved by creating a "class" that inherits from + # backend_bases._Backend and whose body is filled with the module globals. + class backend_mod(matplotlib.backend_bases._Backend): + locals().update(vars(module)) + + # However, the newer approach for defining new_figure_manager and + # show is to derive them from canvas methods. In that case, also + # update backend_mod accordingly; also, per-backend customization of + # draw_if_interactive is disabled. + if new_figure_manager is None: + + def new_figure_manager_given_figure(num, figure): + return canvas_class.new_manager(figure, num) + + def new_figure_manager(num, *args, FigureClass=Figure, **kwargs): + fig = FigureClass(*args, **kwargs) + return new_figure_manager_given_figure(num, fig) + + def draw_if_interactive() -> None: + if matplotlib.is_interactive(): + manager = _pylab_helpers.Gcf.get_active() + if manager: + manager.canvas.draw_idle() + + backend_mod.new_figure_manager_given_figure = ( # type: ignore[method-assign] + new_figure_manager_given_figure) + backend_mod.new_figure_manager = ( # type: ignore[method-assign] + new_figure_manager) + backend_mod.draw_if_interactive = ( # type: ignore[method-assign] + draw_if_interactive) + + # If the manager explicitly overrides pyplot_show, use it even if a global + # show is already present, as the latter may be here for backcompat. + manager_class = getattr(canvas_class, "manager_class", None) + # We can't compare directly manager_class.pyplot_show and FMB.pyplot_show because + # pyplot_show is a classmethod so the above constructs are bound classmethods, and + # thus always different (being bound to different classes). We also have to use + # getattr_static instead of vars as manager_class could have no __dict__. + manager_pyplot_show = inspect.getattr_static(manager_class, "pyplot_show", None) + base_pyplot_show = inspect.getattr_static(FigureManagerBase, "pyplot_show", None) + if (show is None + or (manager_pyplot_show is not None + and manager_pyplot_show != base_pyplot_show)): + if not manager_pyplot_show: + raise ValueError( + f"Backend {newbackend} defines neither FigureCanvas.manager_class nor " + f"a toplevel show function") + _pyplot_show = cast('Any', manager_class).pyplot_show + backend_mod.show = _pyplot_show # type: ignore[method-assign] + + _log.debug("Loaded backend %s version %s.", + newbackend, backend_mod.backend_version) + + if newbackend in ("ipympl", "widget"): + # ipympl < 0.9.4 expects rcParams["backend"] to be the fully-qualified backend + # name "module://ipympl.backend_nbagg" not short names "ipympl" or "widget". + import importlib.metadata as im + from matplotlib import _parse_to_version_info # type: ignore[attr-defined] + try: + module_version = im.version("ipympl") + if _parse_to_version_info(module_version) < (0, 9, 4): + newbackend = "module://ipympl.backend_nbagg" + except im.PackageNotFoundError: + pass + + rcParams['backend'] = rcParamsDefault['backend'] = newbackend + _backend_mod = backend_mod + for func_name in ["new_figure_manager", "draw_if_interactive", "show"]: + globals()[func_name].__signature__ = inspect.signature( + getattr(backend_mod, func_name)) + + # Need to keep a global reference to the backend for compatibility reasons. + # See https://github.com/matplotlib/matplotlib/issues/6092 + matplotlib.backends.backend = newbackend # type: ignore[attr-defined] + + if not cbook._str_equal(old_backend, newbackend): + if get_fignums(): + _api.warn_deprecated("3.8", message=( + "Auto-close()ing of figures upon backend switching is deprecated since " + "%(since)s and will be removed %(removal)s. To suppress this warning, " + "explicitly call plt.close('all') first.")) + close("all") + + # Make sure the repl display hook is installed in case we become interactive. + install_repl_displayhook() + + +def _warn_if_gui_out_of_main_thread() -> None: + warn = False + canvas_class = cast(type[FigureCanvasBase], _get_backend_mod().FigureCanvas) + if canvas_class.required_interactive_framework: + if hasattr(threading, 'get_native_id'): + # This compares native thread ids because even if Python-level + # Thread objects match, the underlying OS thread (which is what + # really matters) may be different on Python implementations with + # green threads. + if threading.get_native_id() != threading.main_thread().native_id: + warn = True + else: + # Fall back to Python-level Thread if native IDs are unavailable, + # mainly for PyPy. + if threading.current_thread() is not threading.main_thread(): + warn = True + if warn: + _api.warn_external( + "Starting a Matplotlib GUI outside of the main thread will likely " + "fail.") + + +# This function's signature is rewritten upon backend-load by switch_backend. +def new_figure_manager(*args, **kwargs): + """Create a new figure manager instance.""" + _warn_if_gui_out_of_main_thread() + return _get_backend_mod().new_figure_manager(*args, **kwargs) + + +# This function's signature is rewritten upon backend-load by switch_backend. +def draw_if_interactive(*args, **kwargs): + """ + Redraw the current figure if in interactive mode. + + .. warning:: + + End users will typically not have to call this function because the + the interactive mode takes care of this. + """ + return _get_backend_mod().draw_if_interactive(*args, **kwargs) + + +# This function's signature is rewritten upon backend-load by switch_backend. +def show(*args, **kwargs) -> None: + """ + Display all open figures. + + Parameters + ---------- + block : bool, optional + Whether to wait for all figures to be closed before returning. + + If `True` block and run the GUI main loop until all figure windows + are closed. + + If `False` ensure that all figure windows are displayed and return + immediately. In this case, you are responsible for ensuring + that the event loop is running to have responsive figures. + + Defaults to True in non-interactive mode and to False in interactive + mode (see `.pyplot.isinteractive`). + + See Also + -------- + ion : Enable interactive mode, which shows / updates the figure after + every plotting command, so that calling ``show()`` is not necessary. + ioff : Disable interactive mode. + savefig : Save the figure to an image file instead of showing it on screen. + + Notes + ----- + **Saving figures to file and showing a window at the same time** + + If you want an image file as well as a user interface window, use + `.pyplot.savefig` before `.pyplot.show`. At the end of (a blocking) + ``show()`` the figure is closed and thus unregistered from pyplot. Calling + `.pyplot.savefig` afterwards would save a new and thus empty figure. This + limitation of command order does not apply if the show is non-blocking or + if you keep a reference to the figure and use `.Figure.savefig`. + + **Auto-show in jupyter notebooks** + + The jupyter backends (activated via ``%matplotlib inline``, + ``%matplotlib notebook``, or ``%matplotlib widget``), call ``show()`` at + the end of every cell by default. Thus, you usually don't have to call it + explicitly there. + """ + _warn_if_gui_out_of_main_thread() + return _get_backend_mod().show(*args, **kwargs) + + +def isinteractive() -> bool: + """ + Return whether plots are updated after every plotting command. + + The interactive mode is mainly useful if you build plots from the command + line and want to see the effect of each command while you are building the + figure. + + In interactive mode: + + - newly created figures will be shown immediately; + - figures will automatically redraw on change; + - `.pyplot.show` will not block by default. + + In non-interactive mode: + + - newly created figures and changes to figures will not be reflected until + explicitly asked to be; + - `.pyplot.show` will block by default. + + See Also + -------- + ion : Enable interactive mode. + ioff : Disable interactive mode. + show : Show all figures (and maybe block). + pause : Show all figures, and block for a time. + """ + return matplotlib.is_interactive() + + +# Note: The return type of ioff being AbstractContextManager +# instead of ExitStack is deliberate. +# See https://github.com/matplotlib/matplotlib/issues/27659 +# and https://github.com/matplotlib/matplotlib/pull/27667 for more info. +def ioff() -> AbstractContextManager: + """ + Disable interactive mode. + + See `.pyplot.isinteractive` for more details. + + See Also + -------- + ion : Enable interactive mode. + isinteractive : Whether interactive mode is enabled. + show : Show all figures (and maybe block). + pause : Show all figures, and block for a time. + + Notes + ----- + For a temporary change, this can be used as a context manager:: + + # if interactive mode is on + # then figures will be shown on creation + plt.ion() + # This figure will be shown immediately + fig = plt.figure() + + with plt.ioff(): + # interactive mode will be off + # figures will not automatically be shown + fig2 = plt.figure() + # ... + + To enable optional usage as a context manager, this function returns a + context manager object, which is not intended to be stored or + accessed by the user. + """ + stack = ExitStack() + stack.callback(ion if isinteractive() else ioff) + matplotlib.interactive(False) + uninstall_repl_displayhook() + return stack + + +# Note: The return type of ion being AbstractContextManager +# instead of ExitStack is deliberate. +# See https://github.com/matplotlib/matplotlib/issues/27659 +# and https://github.com/matplotlib/matplotlib/pull/27667 for more info. +def ion() -> AbstractContextManager: + """ + Enable interactive mode. + + See `.pyplot.isinteractive` for more details. + + See Also + -------- + ioff : Disable interactive mode. + isinteractive : Whether interactive mode is enabled. + show : Show all figures (and maybe block). + pause : Show all figures, and block for a time. + + Notes + ----- + For a temporary change, this can be used as a context manager:: + + # if interactive mode is off + # then figures will not be shown on creation + plt.ioff() + # This figure will not be shown immediately + fig = plt.figure() + + with plt.ion(): + # interactive mode will be on + # figures will automatically be shown + fig2 = plt.figure() + # ... + + To enable optional usage as a context manager, this function returns a + context manager object, which is not intended to be stored or + accessed by the user. + """ + stack = ExitStack() + stack.callback(ion if isinteractive() else ioff) + matplotlib.interactive(True) + install_repl_displayhook() + return stack + + +def pause(interval: float) -> None: + """ + Run the GUI event loop for *interval* seconds. + + If there is an active figure, it will be updated and displayed before the + pause, and the GUI event loop (if any) will run during the pause. + + This can be used for crude animation. For more complex animation use + :mod:`matplotlib.animation`. + + If there is no active figure, sleep for *interval* seconds instead. + + See Also + -------- + matplotlib.animation : Proper animations + show : Show all figures and optional block until all figures are closed. + """ + manager = _pylab_helpers.Gcf.get_active() + if manager is not None: + canvas = manager.canvas + if canvas.figure.stale: + canvas.draw_idle() + show(block=False) + canvas.start_event_loop(interval) + else: + time.sleep(interval) + + +@_copy_docstring_and_deprecators(matplotlib.rc) +def rc(group: str, **kwargs) -> None: + matplotlib.rc(group, **kwargs) + + +@_copy_docstring_and_deprecators(matplotlib.rc_context) +def rc_context( + rc: dict[str, Any] | None = None, + fname: str | pathlib.Path | os.PathLike | None = None, +) -> AbstractContextManager[None]: + return matplotlib.rc_context(rc, fname) + + +@_copy_docstring_and_deprecators(matplotlib.rcdefaults) +def rcdefaults() -> None: + matplotlib.rcdefaults() + if matplotlib.is_interactive(): + draw_all() + + +# getp/get/setp are explicitly reexported so that they show up in pyplot docs. + + +@_copy_docstring_and_deprecators(matplotlib.artist.getp) +def getp(obj, *args, **kwargs): + return matplotlib.artist.getp(obj, *args, **kwargs) + + +@_copy_docstring_and_deprecators(matplotlib.artist.get) +def get(obj, *args, **kwargs): + return matplotlib.artist.get(obj, *args, **kwargs) + + +@_copy_docstring_and_deprecators(matplotlib.artist.setp) +def setp(obj, *args, **kwargs): + return matplotlib.artist.setp(obj, *args, **kwargs) + + +def xkcd( + scale: float = 1, length: float = 100, randomness: float = 2 +) -> ExitStack: + """ + Turn on `xkcd `_ sketch-style drawing mode. + + This will only have an effect on things drawn after this function is called. + + For best results, install the `xkcd script `_ + font; xkcd fonts are not packaged with Matplotlib. + + Parameters + ---------- + scale : float, optional + The amplitude of the wiggle perpendicular to the source line. + length : float, optional + The length of the wiggle along the line. + randomness : float, optional + The scale factor by which the length is shrunken or expanded. + + Notes + ----- + This function works by a number of rcParams, so it will probably + override others you have set before. + + If you want the effects of this function to be temporary, it can + be used as a context manager, for example:: + + with plt.xkcd(): + # This figure will be in XKCD-style + fig1 = plt.figure() + # ... + + # This figure will be in regular style + fig2 = plt.figure() + """ + # This cannot be implemented in terms of contextmanager() or rc_context() + # because this needs to work as a non-contextmanager too. + + if rcParams['text.usetex']: + raise RuntimeError( + "xkcd mode is not compatible with text.usetex = True") + + stack = ExitStack() + stack.callback(dict.update, rcParams, rcParams.copy()) # type: ignore[arg-type] + + from matplotlib import patheffects + rcParams.update({ + 'font.family': ['xkcd', 'xkcd Script', 'Comic Neue', 'Comic Sans MS'], + 'font.size': 14.0, + 'path.sketch': (scale, length, randomness), + 'path.effects': [ + patheffects.withStroke(linewidth=4, foreground="w")], + 'axes.linewidth': 1.5, + 'lines.linewidth': 2.0, + 'figure.facecolor': 'white', + 'grid.linewidth': 0.0, + 'axes.grid': False, + 'axes.unicode_minus': False, + 'axes.edgecolor': 'black', + 'xtick.major.size': 8, + 'xtick.major.width': 3, + 'ytick.major.size': 8, + 'ytick.major.width': 3, + }) + + return stack + + +## Figures ## + +def figure( + # autoincrement if None, else integer from 1-N + num: int | str | Figure | SubFigure | None = None, + # defaults to rc figure.figsize + figsize: tuple[float, float] | None = None, + # defaults to rc figure.dpi + dpi: float | None = None, + *, + # defaults to rc figure.facecolor + facecolor: ColorType | None = None, + # defaults to rc figure.edgecolor + edgecolor: ColorType | None = None, + frameon: bool = True, + FigureClass: type[Figure] = Figure, + clear: bool = False, + **kwargs +) -> Figure: + """ + Create a new figure, or activate an existing figure. + + Parameters + ---------- + num : int or str or `.Figure` or `.SubFigure`, optional + A unique identifier for the figure. + + If a figure with that identifier already exists, this figure is made + active and returned. An integer refers to the ``Figure.number`` + attribute, a string refers to the figure label. + + If there is no figure with the identifier or *num* is not given, a new + figure is created, made active and returned. If *num* is an int, it + will be used for the ``Figure.number`` attribute, otherwise, an + auto-generated integer value is used (starting at 1 and incremented + for each new figure). If *num* is a string, the figure label and the + window title is set to this value. If num is a ``SubFigure``, its + parent ``Figure`` is activated. + + figsize : (float, float), default: :rc:`figure.figsize` + Width, height in inches. + + dpi : float, default: :rc:`figure.dpi` + The resolution of the figure in dots-per-inch. + + facecolor : :mpltype:`color`, default: :rc:`figure.facecolor` + The background color. + + edgecolor : :mpltype:`color`, default: :rc:`figure.edgecolor` + The border color. + + frameon : bool, default: True + If False, suppress drawing the figure frame. + + FigureClass : subclass of `~matplotlib.figure.Figure` + If set, an instance of this subclass will be created, rather than a + plain `.Figure`. + + clear : bool, default: False + If True and the figure already exists, then it is cleared. + + layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None}, \ +default: None + The layout mechanism for positioning of plot elements to avoid + overlapping Axes decorations (labels, ticks, etc). Note that layout + managers can measurably slow down figure display. + + - 'constrained': The constrained layout solver adjusts Axes sizes + to avoid overlapping Axes decorations. Can handle complex plot + layouts and colorbars, and is thus recommended. + + See :ref:`constrainedlayout_guide` + for examples. + + - 'compressed': uses the same algorithm as 'constrained', but + removes extra space between fixed-aspect-ratio Axes. Best for + simple grids of Axes. + + - 'tight': Use the tight layout mechanism. This is a relatively + simple algorithm that adjusts the subplot parameters so that + decorations do not overlap. See `.Figure.set_tight_layout` for + further details. + + - 'none': Do not use a layout engine. + + - A `.LayoutEngine` instance. Builtin layout classes are + `.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily + accessible by 'constrained' and 'tight'. Passing an instance + allows third parties to provide their own layout engine. + + If not given, fall back to using the parameters *tight_layout* and + *constrained_layout*, including their config defaults + :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`. + + **kwargs + Additional keyword arguments are passed to the `.Figure` constructor. + + Returns + ------- + `~matplotlib.figure.Figure` + + Notes + ----- + A newly created figure is passed to the `~.FigureCanvasBase.new_manager` + method or the `new_figure_manager` function provided by the current + backend, which install a canvas and a manager on the figure. + + Once this is done, :rc:`figure.hooks` are called, one at a time, on the + figure; these hooks allow arbitrary customization of the figure (e.g., + attaching callbacks) or of associated elements (e.g., modifying the + toolbar). See :doc:`/gallery/user_interfaces/mplcvd` for an example of + toolbar customization. + + If you are creating many figures, make sure you explicitly call + `.pyplot.close` on the figures you are not using, because this will + enable pyplot to properly clean up the memory. + + `~matplotlib.rcParams` defines the default values, which can be modified + in the matplotlibrc file. + """ + if isinstance(num, FigureBase): + # type narrowed to `Figure | SubFigure` by combination of input and isinstance + if num.canvas.manager is None: + raise ValueError("The passed figure is not managed by pyplot") + _pylab_helpers.Gcf.set_active(num.canvas.manager) + return num.figure + + allnums = get_fignums() + next_num = max(allnums) + 1 if allnums else 1 + fig_label = '' + if num is None: + num = next_num + elif isinstance(num, str): + fig_label = num + all_labels = get_figlabels() + if fig_label not in all_labels: + if fig_label == 'all': + _api.warn_external("close('all') closes all existing figures.") + num = next_num + else: + inum = all_labels.index(fig_label) + num = allnums[inum] + else: + num = int(num) # crude validation of num argument + + # Type of "num" has narrowed to int, but mypy can't quite see it + manager = _pylab_helpers.Gcf.get_fig_manager(num) # type: ignore[arg-type] + if manager is None: + max_open_warning = rcParams['figure.max_open_warning'] + if len(allnums) == max_open_warning >= 1: + _api.warn_external( + f"More than {max_open_warning} figures have been opened. " + f"Figures created through the pyplot interface " + f"(`matplotlib.pyplot.figure`) are retained until explicitly " + f"closed and may consume too much memory. (To control this " + f"warning, see the rcParam `figure.max_open_warning`). " + f"Consider using `matplotlib.pyplot.close()`.", + RuntimeWarning) + + manager = new_figure_manager( + num, figsize=figsize, dpi=dpi, + facecolor=facecolor, edgecolor=edgecolor, frameon=frameon, + FigureClass=FigureClass, **kwargs) + fig = manager.canvas.figure + if fig_label: + fig.set_label(fig_label) + + for hookspecs in rcParams["figure.hooks"]: + module_name, dotted_name = hookspecs.split(":") + obj: Any = importlib.import_module(module_name) + for part in dotted_name.split("."): + obj = getattr(obj, part) + obj(fig) + + _pylab_helpers.Gcf._set_new_active_manager(manager) + + # make sure backends (inline) that we don't ship that expect this + # to be called in plotting commands to make the figure call show + # still work. There is probably a better way to do this in the + # FigureManager base class. + draw_if_interactive() + + if _REPL_DISPLAYHOOK is _ReplDisplayHook.PLAIN: + fig.stale_callback = _auto_draw_if_interactive + + if clear: + manager.canvas.figure.clear() + + return manager.canvas.figure + + +def _auto_draw_if_interactive(fig, val): + """ + An internal helper function for making sure that auto-redrawing + works as intended in the plain python repl. + + Parameters + ---------- + fig : Figure + A figure object which is assumed to be associated with a canvas + """ + if (val and matplotlib.is_interactive() + and not fig.canvas.is_saving() + and not fig.canvas._is_idle_drawing): + # Some artists can mark themselves as stale in the middle of drawing + # (e.g. axes position & tick labels being computed at draw time), but + # this shouldn't trigger a redraw because the current redraw will + # already take them into account. + with fig.canvas._idle_draw_cntx(): + fig.canvas.draw_idle() + + +def gcf() -> Figure: + """ + Get the current figure. + + If there is currently no figure on the pyplot figure stack, a new one is + created using `~.pyplot.figure()`. (To test whether there is currently a + figure on the pyplot figure stack, check whether `~.pyplot.get_fignums()` + is empty.) + """ + manager = _pylab_helpers.Gcf.get_active() + if manager is not None: + return manager.canvas.figure + else: + return figure() + + +def fignum_exists(num: int | str) -> bool: + """ + Return whether the figure with the given id exists. + + Parameters + ---------- + num : int or str + A figure identifier. + + Returns + ------- + bool + Whether or not a figure with id *num* exists. + """ + return ( + _pylab_helpers.Gcf.has_fignum(num) + if isinstance(num, int) + else num in get_figlabels() + ) + + +def get_fignums() -> list[int]: + """Return a list of existing figure numbers.""" + return sorted(_pylab_helpers.Gcf.figs) + + +def get_figlabels() -> list[Any]: + """Return a list of existing figure labels.""" + managers = _pylab_helpers.Gcf.get_all_fig_managers() + managers.sort(key=lambda m: m.num) + return [m.canvas.figure.get_label() for m in managers] + + +def get_current_fig_manager() -> FigureManagerBase | None: + """ + Return the figure manager of the current figure. + + The figure manager is a container for the actual backend-depended window + that displays the figure on screen. + + If no current figure exists, a new one is created, and its figure + manager is returned. + + Returns + ------- + `.FigureManagerBase` or backend-dependent subclass thereof + """ + return gcf().canvas.manager + + +@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect) +def connect(s: str, func: Callable[[Event], Any]) -> int: + return gcf().canvas.mpl_connect(s, func) + + +@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect) +def disconnect(cid: int) -> None: + gcf().canvas.mpl_disconnect(cid) + + +def close(fig: None | int | str | Figure | Literal["all"] = None) -> None: + """ + Close a figure window. + + Parameters + ---------- + fig : None or int or str or `.Figure` + The figure to close. There are a number of ways to specify this: + + - *None*: the current figure + - `.Figure`: the given `.Figure` instance + - ``int``: a figure number + - ``str``: a figure name + - 'all': all figures + + """ + if fig is None: + manager = _pylab_helpers.Gcf.get_active() + if manager is None: + return + else: + _pylab_helpers.Gcf.destroy(manager) + elif fig == 'all': + _pylab_helpers.Gcf.destroy_all() + elif isinstance(fig, int): + _pylab_helpers.Gcf.destroy(fig) + elif hasattr(fig, 'int'): + # if we are dealing with a type UUID, we + # can use its integer representation + _pylab_helpers.Gcf.destroy(fig.int) + elif isinstance(fig, str): + all_labels = get_figlabels() + if fig in all_labels: + num = get_fignums()[all_labels.index(fig)] + _pylab_helpers.Gcf.destroy(num) + elif isinstance(fig, Figure): + _pylab_helpers.Gcf.destroy_fig(fig) + else: + raise TypeError("close() argument must be a Figure, an int, a string, " + "or None, not %s" % type(fig)) + + +def clf() -> None: + """Clear the current figure.""" + gcf().clear() + + +def draw() -> None: + """ + Redraw the current figure. + + This is used to update a figure that has been altered, but not + automatically re-drawn. If interactive mode is on (via `.ion()`), this + should be only rarely needed, but there may be ways to modify the state of + a figure without marking it as "stale". Please report these cases as bugs. + + This is equivalent to calling ``fig.canvas.draw_idle()``, where ``fig`` is + the current figure. + + See Also + -------- + .FigureCanvasBase.draw_idle + .FigureCanvasBase.draw + """ + gcf().canvas.draw_idle() + + +@_copy_docstring_and_deprecators(Figure.savefig) +def savefig(*args, **kwargs) -> None: + fig = gcf() + # savefig default implementation has no return, so mypy is unhappy + # presumably this is here because subclasses can return? + res = fig.savefig(*args, **kwargs) # type: ignore[func-returns-value] + fig.canvas.draw_idle() # Need this if 'transparent=True', to reset colors. + return res + + +## Putting things in figures ## + + +def figlegend(*args, **kwargs) -> Legend: + return gcf().legend(*args, **kwargs) +if Figure.legend.__doc__: + figlegend.__doc__ = Figure.legend.__doc__ \ + .replace(" legend(", " figlegend(") \ + .replace("fig.legend(", "plt.figlegend(") \ + .replace("ax.plot(", "plt.plot(") + + +## Axes ## + +@_docstring.dedent_interpd +def axes( + arg: None | tuple[float, float, float, float] = None, + **kwargs +) -> matplotlib.axes.Axes: + """ + Add an Axes to the current figure and make it the current Axes. + + Call signatures:: + + plt.axes() + plt.axes(rect, projection=None, polar=False, **kwargs) + plt.axes(ax) + + Parameters + ---------- + arg : None or 4-tuple + The exact behavior of this function depends on the type: + + - *None*: A new full window Axes is added using + ``subplot(**kwargs)``. + - 4-tuple of floats *rect* = ``(left, bottom, width, height)``. + A new Axes is added with dimensions *rect* in normalized + (0, 1) units using `~.Figure.add_axes` on the current figure. + + projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ +'polar', 'rectilinear', str}, optional + The projection type of the `~.axes.Axes`. *str* is the name of + a custom projection, see `~matplotlib.projections`. The default + None results in a 'rectilinear' projection. + + polar : bool, default: False + If True, equivalent to projection='polar'. + + sharex, sharey : `~matplotlib.axes.Axes`, optional + Share the x or y `~matplotlib.axis` with sharex and/or sharey. + The axis will have the same limits, ticks, and scale as the axis + of the shared Axes. + + label : str + A label for the returned Axes. + + Returns + ------- + `~.axes.Axes`, or a subclass of `~.axes.Axes` + The returned Axes class depends on the projection used. It is + `~.axes.Axes` if rectilinear projection is used and + `.projections.polar.PolarAxes` if polar projection is used. + + Other Parameters + ---------------- + **kwargs + This method also takes the keyword arguments for + the returned Axes class. The keyword arguments for the + rectilinear Axes class `~.axes.Axes` can be found in + the following table but there might also be other keyword + arguments if another projection is used, see the actual Axes + class. + + %(Axes:kwdoc)s + + See Also + -------- + .Figure.add_axes + .pyplot.subplot + .Figure.add_subplot + .Figure.subplots + .pyplot.subplots + + Examples + -------- + :: + + # Creating a new full window Axes + plt.axes() + + # Creating a new Axes with specified dimensions and a grey background + plt.axes((left, bottom, width, height), facecolor='grey') + """ + fig = gcf() + pos = kwargs.pop('position', None) + if arg is None: + if pos is None: + return fig.add_subplot(**kwargs) + else: + return fig.add_axes(pos, **kwargs) + else: + return fig.add_axes(arg, **kwargs) + + +def delaxes(ax: matplotlib.axes.Axes | None = None) -> None: + """ + Remove an `~.axes.Axes` (defaulting to the current Axes) from its figure. + """ + if ax is None: + ax = gca() + ax.remove() + + +def sca(ax: Axes) -> None: + """ + Set the current Axes to *ax* and the current Figure to the parent of *ax*. + """ + # Mypy sees ax.figure as potentially None, + # but if you are calling this, it won't be None + # Additionally the slight difference between `Figure` and `FigureBase` mypy catches + figure(ax.figure) # type: ignore[arg-type] + ax.figure.sca(ax) # type: ignore[union-attr] + + +def cla() -> None: + """Clear the current Axes.""" + # Not generated via boilerplate.py to allow a different docstring. + return gca().cla() + + +## More ways of creating Axes ## + +@_docstring.dedent_interpd +def subplot(*args, **kwargs) -> Axes: + """ + Add an Axes to the current figure or retrieve an existing Axes. + + This is a wrapper of `.Figure.add_subplot` which provides additional + behavior when working with the implicit API (see the notes section). + + Call signatures:: + + subplot(nrows, ncols, index, **kwargs) + subplot(pos, **kwargs) + subplot(**kwargs) + subplot(ax) + + Parameters + ---------- + *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1) + The position of the subplot described by one of + + - Three integers (*nrows*, *ncols*, *index*). The subplot will take the + *index* position on a grid with *nrows* rows and *ncols* columns. + *index* starts at 1 in the upper left corner and increases to the + right. *index* can also be a two-tuple specifying the (*first*, + *last*) indices (1-based, and including *last*) of the subplot, e.g., + ``fig.add_subplot(3, 1, (1, 2))`` makes a subplot that spans the + upper 2/3 of the figure. + - A 3-digit integer. The digits are interpreted as if given separately + as three single-digit integers, i.e. ``fig.add_subplot(235)`` is the + same as ``fig.add_subplot(2, 3, 5)``. Note that this can only be used + if there are no more than 9 subplots. + - A `.SubplotSpec`. + + projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ +'polar', 'rectilinear', str}, optional + The projection type of the subplot (`~.axes.Axes`). *str* is the name + of a custom projection, see `~matplotlib.projections`. The default + None results in a 'rectilinear' projection. + + polar : bool, default: False + If True, equivalent to projection='polar'. + + sharex, sharey : `~matplotlib.axes.Axes`, optional + Share the x or y `~matplotlib.axis` with sharex and/or sharey. The + axis will have the same limits, ticks, and scale as the axis of the + shared Axes. + + label : str + A label for the returned Axes. + + Returns + ------- + `~.axes.Axes` + + The Axes of the subplot. The returned Axes can actually be an instance + of a subclass, such as `.projections.polar.PolarAxes` for polar + projections. + + Other Parameters + ---------------- + **kwargs + This method also takes the keyword arguments for the returned Axes + base class; except for the *figure* argument. The keyword arguments + for the rectilinear base class `~.axes.Axes` can be found in + the following table but there might also be other keyword + arguments if another projection is used. + + %(Axes:kwdoc)s + + Notes + ----- + Creating a new Axes will delete any preexisting Axes that + overlaps with it beyond sharing a boundary:: + + import matplotlib.pyplot as plt + # plot a line, implicitly creating a subplot(111) + plt.plot([1, 2, 3]) + # now create a subplot which represents the top plot of a grid + # with 2 rows and 1 column. Since this subplot will overlap the + # first, the plot (and its Axes) previously created, will be removed + plt.subplot(211) + + If you do not want this behavior, use the `.Figure.add_subplot` method + or the `.pyplot.axes` function instead. + + If no *kwargs* are passed and there exists an Axes in the location + specified by *args* then that Axes will be returned rather than a new + Axes being created. + + If *kwargs* are passed and there exists an Axes in the location + specified by *args*, the projection type is the same, and the + *kwargs* match with the existing Axes, then the existing Axes is + returned. Otherwise a new Axes is created with the specified + parameters. We save a reference to the *kwargs* which we use + for this comparison. If any of the values in *kwargs* are + mutable we will not detect the case where they are mutated. + In these cases we suggest using `.Figure.add_subplot` and the + explicit Axes API rather than the implicit pyplot API. + + See Also + -------- + .Figure.add_subplot + .pyplot.subplots + .pyplot.axes + .Figure.subplots + + Examples + -------- + :: + + plt.subplot(221) + + # equivalent but more general + ax1 = plt.subplot(2, 2, 1) + + # add a subplot with no frame + ax2 = plt.subplot(222, frameon=False) + + # add a polar subplot + plt.subplot(223, projection='polar') + + # add a red subplot that shares the x-axis with ax1 + plt.subplot(224, sharex=ax1, facecolor='red') + + # delete ax2 from the figure + plt.delaxes(ax2) + + # add ax2 to the figure again + plt.subplot(ax2) + + # make the first Axes "current" again + plt.subplot(221) + + """ + # Here we will only normalize `polar=True` vs `projection='polar'` and let + # downstream code deal with the rest. + unset = object() + projection = kwargs.get('projection', unset) + polar = kwargs.pop('polar', unset) + if polar is not unset and polar: + # if we got mixed messages from the user, raise + if projection is not unset and projection != 'polar': + raise ValueError( + f"polar={polar}, yet projection={projection!r}. " + "Only one of these arguments should be supplied." + ) + kwargs['projection'] = projection = 'polar' + + # if subplot called without arguments, create subplot(1, 1, 1) + if len(args) == 0: + args = (1, 1, 1) + + # This check was added because it is very easy to type subplot(1, 2, False) + # when subplots(1, 2, False) was intended (sharex=False, that is). In most + # cases, no error will ever occur, but mysterious behavior can result + # because what was intended to be the sharex argument is instead treated as + # a subplot index for subplot() + if len(args) >= 3 and isinstance(args[2], bool): + _api.warn_external("The subplot index argument to subplot() appears " + "to be a boolean. Did you intend to use " + "subplots()?") + # Check for nrows and ncols, which are not valid subplot args: + if 'nrows' in kwargs or 'ncols' in kwargs: + raise TypeError("subplot() got an unexpected keyword argument 'ncols' " + "and/or 'nrows'. Did you intend to call subplots()?") + + fig = gcf() + + # First, search for an existing subplot with a matching spec. + key = SubplotSpec._from_subplot_args(fig, args) + + for ax in fig.axes: + # If we found an Axes at the position, we can reuse it if the user passed no + # kwargs or if the Axes class and kwargs are identical. + if (ax.get_subplotspec() == key + and (kwargs == {} + or (ax._projection_init + == fig._process_projection_requirements(**kwargs)))): + break + else: + # we have exhausted the known Axes and none match, make a new one! + ax = fig.add_subplot(*args, **kwargs) + + fig.sca(ax) + + return ax + + +@overload +def subplots( + nrows: Literal[1] = ..., + ncols: Literal[1] = ..., + *, + sharex: bool | Literal["none", "all", "row", "col"] = ..., + sharey: bool | Literal["none", "all", "row", "col"] = ..., + squeeze: Literal[True] = ..., + width_ratios: Sequence[float] | None = ..., + height_ratios: Sequence[float] | None = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + **fig_kw +) -> tuple[Figure, Axes]: + ... + + +@overload +def subplots( + nrows: int = ..., + ncols: int = ..., + *, + sharex: bool | Literal["none", "all", "row", "col"] = ..., + sharey: bool | Literal["none", "all", "row", "col"] = ..., + squeeze: Literal[False], + width_ratios: Sequence[float] | None = ..., + height_ratios: Sequence[float] | None = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + **fig_kw +) -> tuple[Figure, np.ndarray]: # TODO numpy/numpy#24738 + ... + + +@overload +def subplots( + nrows: int = ..., + ncols: int = ..., + *, + sharex: bool | Literal["none", "all", "row", "col"] = ..., + sharey: bool | Literal["none", "all", "row", "col"] = ..., + squeeze: bool = ..., + width_ratios: Sequence[float] | None = ..., + height_ratios: Sequence[float] | None = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + **fig_kw +) -> tuple[Figure, Any]: + ... + + +def subplots( + nrows: int = 1, ncols: int = 1, *, + sharex: bool | Literal["none", "all", "row", "col"] = False, + sharey: bool | Literal["none", "all", "row", "col"] = False, + squeeze: bool = True, + width_ratios: Sequence[float] | None = None, + height_ratios: Sequence[float] | None = None, + subplot_kw: dict[str, Any] | None = None, + gridspec_kw: dict[str, Any] | None = None, + **fig_kw +) -> tuple[Figure, Any]: + """ + Create a figure and a set of subplots. + + This utility wrapper makes it convenient to create common layouts of + subplots, including the enclosing figure object, in a single call. + + Parameters + ---------- + nrows, ncols : int, default: 1 + Number of rows/columns of the subplot grid. + + sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False + Controls sharing of properties among x (*sharex*) or y (*sharey*) + axes: + + - True or 'all': x- or y-axis will be shared among all subplots. + - False or 'none': each subplot x- or y-axis will be independent. + - 'row': each subplot row will share an x- or y-axis. + - 'col': each subplot column will share an x- or y-axis. + + When subplots have a shared x-axis along a column, only the x tick + labels of the bottom subplot are created. Similarly, when subplots + have a shared y-axis along a row, only the y tick labels of the first + column subplot are created. To later turn other subplots' ticklabels + on, use `~matplotlib.axes.Axes.tick_params`. + + When subplots have a shared axis that has units, calling + `.Axis.set_units` will update each axis with the new units. + + Note that it is not possible to unshare axes. + + squeeze : bool, default: True + - If True, extra dimensions are squeezed out from the returned + array of `~matplotlib.axes.Axes`: + + - if only one subplot is constructed (nrows=ncols=1), the + resulting single Axes object is returned as a scalar. + - for Nx1 or 1xM subplots, the returned object is a 1D numpy + object array of Axes objects. + - for NxM, subplots with N>1 and M>1 are returned as a 2D array. + + - If False, no squeezing at all is done: the returned Axes object is + always a 2D array containing Axes instances, even if it ends up + being 1x1. + + width_ratios : array-like of length *ncols*, optional + Defines the relative widths of the columns. Each column gets a + relative width of ``width_ratios[i] / sum(width_ratios)``. + If not given, all columns will have the same width. Equivalent + to ``gridspec_kw={'width_ratios': [...]}``. + + height_ratios : array-like of length *nrows*, optional + Defines the relative heights of the rows. Each row gets a + relative height of ``height_ratios[i] / sum(height_ratios)``. + If not given, all rows will have the same height. Convenience + for ``gridspec_kw={'height_ratios': [...]}``. + + subplot_kw : dict, optional + Dict with keywords passed to the + `~matplotlib.figure.Figure.add_subplot` call used to create each + subplot. + + gridspec_kw : dict, optional + Dict with keywords passed to the `~matplotlib.gridspec.GridSpec` + constructor used to create the grid the subplots are placed on. + + **fig_kw + All additional keyword arguments are passed to the + `.pyplot.figure` call. + + Returns + ------- + fig : `.Figure` + + ax : `~matplotlib.axes.Axes` or array of Axes + *ax* can be either a single `~.axes.Axes` object, or an array of Axes + objects if more than one subplot was created. The dimensions of the + resulting array can be controlled with the squeeze keyword, see above. + + Typical idioms for handling the return value are:: + + # using the variable ax for single a Axes + fig, ax = plt.subplots() + + # using the variable axs for multiple Axes + fig, axs = plt.subplots(2, 2) + + # using tuple unpacking for multiple Axes + fig, (ax1, ax2) = plt.subplots(1, 2) + fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) + + The names ``ax`` and pluralized ``axs`` are preferred over ``axes`` + because for the latter it's not clear if it refers to a single + `~.axes.Axes` instance or a collection of these. + + See Also + -------- + .pyplot.figure + .pyplot.subplot + .pyplot.axes + .Figure.subplots + .Figure.add_subplot + + Examples + -------- + :: + + # First create some toy data: + x = np.linspace(0, 2*np.pi, 400) + y = np.sin(x**2) + + # Create just a figure and only one subplot + fig, ax = plt.subplots() + ax.plot(x, y) + ax.set_title('Simple plot') + + # Create two subplots and unpack the output array immediately + f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) + ax1.plot(x, y) + ax1.set_title('Sharing Y axis') + ax2.scatter(x, y) + + # Create four polar Axes and access them through the returned array + fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar")) + axs[0, 0].plot(x, y) + axs[1, 1].scatter(x, y) + + # Share a X axis with each column of subplots + plt.subplots(2, 2, sharex='col') + + # Share a Y axis with each row of subplots + plt.subplots(2, 2, sharey='row') + + # Share both X and Y axes with all subplots + plt.subplots(2, 2, sharex='all', sharey='all') + + # Note that this is the same as + plt.subplots(2, 2, sharex=True, sharey=True) + + # Create figure number 10 with a single subplot + # and clears it if it already exists. + fig, ax = plt.subplots(num=10, clear=True) + + """ + fig = figure(**fig_kw) + axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey, + squeeze=squeeze, subplot_kw=subplot_kw, + gridspec_kw=gridspec_kw, height_ratios=height_ratios, + width_ratios=width_ratios) + return fig, axs + + +@overload +def subplot_mosaic( + mosaic: str, + *, + sharex: bool = ..., + sharey: bool = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + empty_sentinel: str = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | None = ..., + **fig_kw: Any +) -> tuple[Figure, dict[str, matplotlib.axes.Axes]]: ... + + +@overload +def subplot_mosaic( + mosaic: list[HashableList[_T]], + *, + sharex: bool = ..., + sharey: bool = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + empty_sentinel: _T = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[_T | tuple[_T, ...], dict[str, Any]] | None = ..., + **fig_kw: Any +) -> tuple[Figure, dict[_T, matplotlib.axes.Axes]]: ... + + +@overload +def subplot_mosaic( + mosaic: list[HashableList[Hashable]], + *, + sharex: bool = ..., + sharey: bool = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + empty_sentinel: Any = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = ..., + **fig_kw: Any +) -> tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]: ... + + +def subplot_mosaic( + mosaic: str | list[HashableList[_T]] | list[HashableList[Hashable]], + *, + sharex: bool = False, + sharey: bool = False, + width_ratios: ArrayLike | None = None, + height_ratios: ArrayLike | None = None, + empty_sentinel: Any = '.', + subplot_kw: dict[str, Any] | None = None, + gridspec_kw: dict[str, Any] | None = None, + per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | + dict[_T | tuple[_T, ...], dict[str, Any]] | + dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = None, + **fig_kw: Any +) -> tuple[Figure, dict[str, matplotlib.axes.Axes]] | \ + tuple[Figure, dict[_T, matplotlib.axes.Axes]] | \ + tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]: + """ + Build a layout of Axes based on ASCII art or nested lists. + + This is a helper function to build complex GridSpec layouts visually. + + See :ref:`mosaic` + for an example and full API documentation + + Parameters + ---------- + mosaic : list of list of {hashable or nested} or str + + A visual layout of how you want your Axes to be arranged + labeled as strings. For example :: + + x = [['A panel', 'A panel', 'edge'], + ['C panel', '.', 'edge']] + + produces 4 Axes: + + - 'A panel' which is 1 row high and spans the first two columns + - 'edge' which is 2 rows high and is on the right edge + - 'C panel' which in 1 row and 1 column wide in the bottom left + - a blank space 1 row and 1 column wide in the bottom center + + Any of the entries in the layout can be a list of lists + of the same form to create nested layouts. + + If input is a str, then it must be of the form :: + + ''' + AAE + C.E + ''' + + where each character is a column and each line is a row. + This only allows only single character Axes labels and does + not allow nesting but is very terse. + + sharex, sharey : bool, default: False + If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared + among all subplots. In that case, tick label visibility and axis units + behave as for `subplots`. If False, each subplot's x- or y-axis will + be independent. + + width_ratios : array-like of length *ncols*, optional + Defines the relative widths of the columns. Each column gets a + relative width of ``width_ratios[i] / sum(width_ratios)``. + If not given, all columns will have the same width. Convenience + for ``gridspec_kw={'width_ratios': [...]}``. + + height_ratios : array-like of length *nrows*, optional + Defines the relative heights of the rows. Each row gets a + relative height of ``height_ratios[i] / sum(height_ratios)``. + If not given, all rows will have the same height. Convenience + for ``gridspec_kw={'height_ratios': [...]}``. + + empty_sentinel : object, optional + Entry in the layout to mean "leave this space empty". Defaults + to ``'.'``. Note, if *layout* is a string, it is processed via + `inspect.cleandoc` to remove leading white space, which may + interfere with using white-space as the empty sentinel. + + subplot_kw : dict, optional + Dictionary with keywords passed to the `.Figure.add_subplot` call + used to create each subplot. These values may be overridden by + values in *per_subplot_kw*. + + per_subplot_kw : dict, optional + A dictionary mapping the Axes identifiers or tuples of identifiers + to a dictionary of keyword arguments to be passed to the + `.Figure.add_subplot` call used to create each subplot. The values + in these dictionaries have precedence over the values in + *subplot_kw*. + + If *mosaic* is a string, and thus all keys are single characters, + it is possible to use a single string instead of a tuple as keys; + i.e. ``"AB"`` is equivalent to ``("A", "B")``. + + .. versionadded:: 3.7 + + gridspec_kw : dict, optional + Dictionary with keywords passed to the `.GridSpec` constructor used + to create the grid the subplots are placed on. + + **fig_kw + All additional keyword arguments are passed to the + `.pyplot.figure` call. + + Returns + ------- + fig : `.Figure` + The new figure + + dict[label, Axes] + A dictionary mapping the labels to the Axes objects. The order of + the Axes is left-to-right and top-to-bottom of their position in the + total layout. + + """ + fig = figure(**fig_kw) + ax_dict = fig.subplot_mosaic( # type: ignore[misc] + mosaic, # type: ignore[arg-type] + sharex=sharex, sharey=sharey, + height_ratios=height_ratios, width_ratios=width_ratios, + subplot_kw=subplot_kw, gridspec_kw=gridspec_kw, + empty_sentinel=empty_sentinel, + per_subplot_kw=per_subplot_kw, # type: ignore[arg-type] + ) + return fig, ax_dict + + +def subplot2grid( + shape: tuple[int, int], loc: tuple[int, int], + rowspan: int = 1, colspan: int = 1, + fig: Figure | None = None, + **kwargs +) -> matplotlib.axes.Axes: + """ + Create a subplot at a specific location inside a regular grid. + + Parameters + ---------- + shape : (int, int) + Number of rows and of columns of the grid in which to place axis. + loc : (int, int) + Row number and column number of the axis location within the grid. + rowspan : int, default: 1 + Number of rows for the axis to span downwards. + colspan : int, default: 1 + Number of columns for the axis to span to the right. + fig : `.Figure`, optional + Figure to place the subplot in. Defaults to the current figure. + **kwargs + Additional keyword arguments are handed to `~.Figure.add_subplot`. + + Returns + ------- + `~.axes.Axes` + + The Axes of the subplot. The returned Axes can actually be an instance + of a subclass, such as `.projections.polar.PolarAxes` for polar + projections. + + Notes + ----- + The following call :: + + ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan) + + is identical to :: + + fig = gcf() + gs = fig.add_gridspec(nrows, ncols) + ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan]) + """ + if fig is None: + fig = gcf() + rows, cols = shape + gs = GridSpec._check_gridspec_exists(fig, rows, cols) + subplotspec = gs.new_subplotspec(loc, rowspan=rowspan, colspan=colspan) + return fig.add_subplot(subplotspec, **kwargs) + + +def twinx(ax: matplotlib.axes.Axes | None = None) -> _AxesBase: + """ + Make and return a second Axes that shares the *x*-axis. The new Axes will + overlay *ax* (or the current Axes if *ax* is *None*), and its ticks will be + on the right. + + Examples + -------- + :doc:`/gallery/subplots_axes_and_figures/two_scales` + """ + if ax is None: + ax = gca() + ax1 = ax.twinx() + return ax1 + + +def twiny(ax: matplotlib.axes.Axes | None = None) -> _AxesBase: + """ + Make and return a second Axes that shares the *y*-axis. The new Axes will + overlay *ax* (or the current Axes if *ax* is *None*), and its ticks will be + on the top. + + Examples + -------- + :doc:`/gallery/subplots_axes_and_figures/two_scales` + """ + if ax is None: + ax = gca() + ax1 = ax.twiny() + return ax1 + + +def subplot_tool(targetfig: Figure | None = None) -> SubplotTool | None: + """ + Launch a subplot tool window for a figure. + + Returns + ------- + `matplotlib.widgets.SubplotTool` + """ + if targetfig is None: + targetfig = gcf() + tb = targetfig.canvas.manager.toolbar # type: ignore[union-attr] + if hasattr(tb, "configure_subplots"): # toolbar2 + from matplotlib.backend_bases import NavigationToolbar2 + return cast(NavigationToolbar2, tb).configure_subplots() + elif hasattr(tb, "trigger_tool"): # toolmanager + from matplotlib.backend_bases import ToolContainerBase + cast(ToolContainerBase, tb).trigger_tool("subplots") + return None + else: + raise ValueError("subplot_tool can only be launched for figures with " + "an associated toolbar") + + +def box(on: bool | None = None) -> None: + """ + Turn the Axes box on or off on the current Axes. + + Parameters + ---------- + on : bool or None + The new `~matplotlib.axes.Axes` box state. If ``None``, toggle + the state. + + See Also + -------- + :meth:`matplotlib.axes.Axes.set_frame_on` + :meth:`matplotlib.axes.Axes.get_frame_on` + """ + ax = gca() + if on is None: + on = not ax.get_frame_on() + ax.set_frame_on(on) + +## Axis ## + + +def xlim(*args, **kwargs) -> tuple[float, float]: + """ + Get or set the x limits of the current Axes. + + Call signatures:: + + left, right = xlim() # return the current xlim + xlim((left, right)) # set the xlim to left, right + xlim(left, right) # set the xlim to left, right + + If you do not specify args, you can pass *left* or *right* as kwargs, + i.e.:: + + xlim(right=3) # adjust the right leaving left unchanged + xlim(left=1) # adjust the left leaving right unchanged + + Setting limits turns autoscaling off for the x-axis. + + Returns + ------- + left, right + A tuple of the new x-axis limits. + + Notes + ----- + Calling this function with no arguments (e.g. ``xlim()``) is the pyplot + equivalent of calling `~.Axes.get_xlim` on the current Axes. + Calling this function with arguments is the pyplot equivalent of calling + `~.Axes.set_xlim` on the current Axes. All arguments are passed though. + """ + ax = gca() + if not args and not kwargs: + return ax.get_xlim() + ret = ax.set_xlim(*args, **kwargs) + return ret + + +def ylim(*args, **kwargs) -> tuple[float, float]: + """ + Get or set the y-limits of the current Axes. + + Call signatures:: + + bottom, top = ylim() # return the current ylim + ylim((bottom, top)) # set the ylim to bottom, top + ylim(bottom, top) # set the ylim to bottom, top + + If you do not specify args, you can alternatively pass *bottom* or + *top* as kwargs, i.e.:: + + ylim(top=3) # adjust the top leaving bottom unchanged + ylim(bottom=1) # adjust the bottom leaving top unchanged + + Setting limits turns autoscaling off for the y-axis. + + Returns + ------- + bottom, top + A tuple of the new y-axis limits. + + Notes + ----- + Calling this function with no arguments (e.g. ``ylim()``) is the pyplot + equivalent of calling `~.Axes.get_ylim` on the current Axes. + Calling this function with arguments is the pyplot equivalent of calling + `~.Axes.set_ylim` on the current Axes. All arguments are passed though. + """ + ax = gca() + if not args and not kwargs: + return ax.get_ylim() + ret = ax.set_ylim(*args, **kwargs) + return ret + + +def xticks( + ticks: ArrayLike | None = None, + labels: Sequence[str] | None = None, + *, + minor: bool = False, + **kwargs +) -> tuple[list[Tick] | np.ndarray, list[Text]]: + """ + Get or set the current tick locations and labels of the x-axis. + + Pass no arguments to return the current values without modifying them. + + Parameters + ---------- + ticks : array-like, optional + The list of xtick locations. Passing an empty list removes all xticks. + labels : array-like, optional + The labels to place at the given *ticks* locations. This argument can + only be passed if *ticks* is passed as well. + minor : bool, default: False + If ``False``, get/set the major ticks/labels; if ``True``, the minor + ticks/labels. + **kwargs + `.Text` properties can be used to control the appearance of the labels. + + .. warning:: + + This only sets the properties of the current ticks, which is + only sufficient if you either pass *ticks*, resulting in a + fixed list of ticks, or if the plot is static. + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that these settings can get lost if you work on + the figure further (including also panning/zooming on a + displayed figure). + + Use `~.pyplot.tick_params` instead if possible. + + + Returns + ------- + locs + The list of xtick locations. + labels + The list of xlabel `.Text` objects. + + Notes + ----- + Calling this function with no arguments (e.g. ``xticks()``) is the pyplot + equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on + the current Axes. + Calling this function with arguments is the pyplot equivalent of calling + `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current Axes. + + Examples + -------- + >>> locs, labels = xticks() # Get the current locations and labels. + >>> xticks(np.arange(0, 1, step=0.2)) # Set label locations. + >>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels. + >>> xticks([0, 1, 2], ['January', 'February', 'March'], + ... rotation=20) # Set text labels and properties. + >>> xticks([]) # Disable xticks. + """ + ax = gca() + + locs: list[Tick] | np.ndarray + if ticks is None: + locs = ax.get_xticks(minor=minor) + if labels is not None: + raise TypeError("xticks(): Parameter 'labels' can't be set " + "without setting 'ticks'") + else: + locs = ax.set_xticks(ticks, minor=minor) + + labels_out: list[Text] = [] + if labels is None: + labels_out = ax.get_xticklabels(minor=minor) + for l in labels_out: + l._internal_update(kwargs) + else: + labels_out = ax.set_xticklabels(labels, minor=minor, **kwargs) + + return locs, labels_out + + +def yticks( + ticks: ArrayLike | None = None, + labels: Sequence[str] | None = None, + *, + minor: bool = False, + **kwargs +) -> tuple[list[Tick] | np.ndarray, list[Text]]: + """ + Get or set the current tick locations and labels of the y-axis. + + Pass no arguments to return the current values without modifying them. + + Parameters + ---------- + ticks : array-like, optional + The list of ytick locations. Passing an empty list removes all yticks. + labels : array-like, optional + The labels to place at the given *ticks* locations. This argument can + only be passed if *ticks* is passed as well. + minor : bool, default: False + If ``False``, get/set the major ticks/labels; if ``True``, the minor + ticks/labels. + **kwargs + `.Text` properties can be used to control the appearance of the labels. + + .. warning:: + + This only sets the properties of the current ticks, which is + only sufficient if you either pass *ticks*, resulting in a + fixed list of ticks, or if the plot is static. + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that these settings can get lost if you work on + the figure further (including also panning/zooming on a + displayed figure). + + Use `~.pyplot.tick_params` instead if possible. + + Returns + ------- + locs + The list of ytick locations. + labels + The list of ylabel `.Text` objects. + + Notes + ----- + Calling this function with no arguments (e.g. ``yticks()``) is the pyplot + equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on + the current Axes. + Calling this function with arguments is the pyplot equivalent of calling + `~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current Axes. + + Examples + -------- + >>> locs, labels = yticks() # Get the current locations and labels. + >>> yticks(np.arange(0, 1, step=0.2)) # Set label locations. + >>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels. + >>> yticks([0, 1, 2], ['January', 'February', 'March'], + ... rotation=45) # Set text labels and properties. + >>> yticks([]) # Disable yticks. + """ + ax = gca() + + locs: list[Tick] | np.ndarray + if ticks is None: + locs = ax.get_yticks(minor=minor) + if labels is not None: + raise TypeError("yticks(): Parameter 'labels' can't be set " + "without setting 'ticks'") + else: + locs = ax.set_yticks(ticks, minor=minor) + + labels_out: list[Text] = [] + if labels is None: + labels_out = ax.get_yticklabels(minor=minor) + for l in labels_out: + l._internal_update(kwargs) + else: + labels_out = ax.set_yticklabels(labels, minor=minor, **kwargs) + + return locs, labels_out + + +def rgrids( + radii: ArrayLike | None = None, + labels: Sequence[str | Text] | None = None, + angle: float | None = None, + fmt: str | None = None, + **kwargs +) -> tuple[list[Line2D], list[Text]]: + """ + Get or set the radial gridlines on the current polar plot. + + Call signatures:: + + lines, labels = rgrids() + lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs) + + When called with no arguments, `.rgrids` simply returns the tuple + (*lines*, *labels*). When called with arguments, the labels will + appear at the specified radial distances and angle. + + Parameters + ---------- + radii : tuple with floats + The radii for the radial gridlines + + labels : tuple with strings or None + The labels to use at each radial gridline. The + `matplotlib.ticker.ScalarFormatter` will be used if None. + + angle : float + The angular position of the radius labels in degrees. + + fmt : str or None + Format string used in `matplotlib.ticker.FormatStrFormatter`. + For example '%f'. + + Returns + ------- + lines : list of `.lines.Line2D` + The radial gridlines. + + labels : list of `.text.Text` + The tick labels. + + Other Parameters + ---------------- + **kwargs + *kwargs* are optional `.Text` properties for the labels. + + See Also + -------- + .pyplot.thetagrids + .projections.polar.PolarAxes.set_rgrids + .Axis.get_gridlines + .Axis.get_ticklabels + + Examples + -------- + :: + + # set the locations of the radial gridlines + lines, labels = rgrids( (0.25, 0.5, 1.0) ) + + # set the locations and labels of the radial gridlines + lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' )) + """ + ax = gca() + if not isinstance(ax, PolarAxes): + raise RuntimeError('rgrids only defined for polar Axes') + if all(p is None for p in [radii, labels, angle, fmt]) and not kwargs: + lines_out: list[Line2D] = ax.yaxis.get_gridlines() + labels_out: list[Text] = ax.yaxis.get_ticklabels() + elif radii is None: + raise TypeError("'radii' cannot be None when other parameters are passed") + else: + lines_out, labels_out = ax.set_rgrids( + radii, labels=labels, angle=angle, fmt=fmt, **kwargs) + return lines_out, labels_out + + +def thetagrids( + angles: ArrayLike | None = None, + labels: Sequence[str | Text] | None = None, + fmt: str | None = None, + **kwargs +) -> tuple[list[Line2D], list[Text]]: + """ + Get or set the theta gridlines on the current polar plot. + + Call signatures:: + + lines, labels = thetagrids() + lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs) + + When called with no arguments, `.thetagrids` simply returns the tuple + (*lines*, *labels*). When called with arguments, the labels will + appear at the specified angles. + + Parameters + ---------- + angles : tuple with floats, degrees + The angles of the theta gridlines. + + labels : tuple with strings or None + The labels to use at each radial gridline. The + `.projections.polar.ThetaFormatter` will be used if None. + + fmt : str or None + Format string used in `matplotlib.ticker.FormatStrFormatter`. + For example '%f'. Note that the angle in radians will be used. + + Returns + ------- + lines : list of `.lines.Line2D` + The theta gridlines. + + labels : list of `.text.Text` + The tick labels. + + Other Parameters + ---------------- + **kwargs + *kwargs* are optional `.Text` properties for the labels. + + See Also + -------- + .pyplot.rgrids + .projections.polar.PolarAxes.set_thetagrids + .Axis.get_gridlines + .Axis.get_ticklabels + + Examples + -------- + :: + + # set the locations of the angular gridlines + lines, labels = thetagrids(range(45, 360, 90)) + + # set the locations and labels of the angular gridlines + lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE')) + """ + ax = gca() + if not isinstance(ax, PolarAxes): + raise RuntimeError('thetagrids only defined for polar Axes') + if all(param is None for param in [angles, labels, fmt]) and not kwargs: + lines_out: list[Line2D] = ax.xaxis.get_ticklines() + labels_out: list[Text] = ax.xaxis.get_ticklabels() + elif angles is None: + raise TypeError("'angles' cannot be None when other parameters are passed") + else: + lines_out, labels_out = ax.set_thetagrids(angles, + labels=labels, fmt=fmt, + **kwargs) + return lines_out, labels_out + + +@_api.deprecated("3.7", pending=True) +def get_plot_commands() -> list[str]: + """ + Get a sorted list of all of the plotting commands. + """ + NON_PLOT_COMMANDS = { + 'connect', 'disconnect', 'get_current_fig_manager', 'ginput', + 'new_figure_manager', 'waitforbuttonpress'} + return [name for name in _get_pyplot_commands() + if name not in NON_PLOT_COMMANDS] + + +def _get_pyplot_commands() -> list[str]: + # This works by searching for all functions in this module and removing + # a few hard-coded exclusions, as well as all of the colormap-setting + # functions, and anything marked as private with a preceding underscore. + exclude = {'colormaps', 'colors', 'get_plot_commands', *colormaps} + this_module = inspect.getmodule(get_plot_commands) + return sorted( + name for name, obj in globals().items() + if not name.startswith('_') and name not in exclude + and inspect.isfunction(obj) + and inspect.getmodule(obj) is this_module) + + +## Plotting part 1: manually generated functions and wrappers ## + + +@_copy_docstring_and_deprecators(Figure.colorbar) +def colorbar( + mappable: ScalarMappable | None = None, + cax: matplotlib.axes.Axes | None = None, + ax: matplotlib.axes.Axes | Iterable[matplotlib.axes.Axes] | None = None, + **kwargs +) -> Colorbar: + if mappable is None: + mappable = gci() + if mappable is None: + raise RuntimeError('No mappable was found to use for colorbar ' + 'creation. First define a mappable such as ' + 'an image (with imshow) or a contour set (' + 'with contourf).') + ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kwargs) + return ret + + +def clim(vmin: float | None = None, vmax: float | None = None) -> None: + """ + Set the color limits of the current image. + + If either *vmin* or *vmax* is None, the image min/max respectively + will be used for color scaling. + + If you want to set the clim of multiple images, use + `~.ScalarMappable.set_clim` on every image, for example:: + + for im in gca().get_images(): + im.set_clim(0, 0.5) + + """ + im = gci() + if im is None: + raise RuntimeError('You must first define an image, e.g., with imshow') + + im.set_clim(vmin, vmax) + + +def get_cmap(name: Colormap | str | None = None, lut: int | None = None) -> Colormap: + """ + Get a colormap instance, defaulting to rc values if *name* is None. + + Parameters + ---------- + name : `~matplotlib.colors.Colormap` or str or None, default: None + If a `.Colormap` instance, it will be returned. Otherwise, the name of + a colormap known to Matplotlib, which will be resampled by *lut*. The + default, None, means :rc:`image.cmap`. + lut : int or None, default: None + If *name* is not already a Colormap instance and *lut* is not None, the + colormap will be resampled to have *lut* entries in the lookup table. + + Returns + ------- + Colormap + """ + if name is None: + name = rcParams['image.cmap'] + if isinstance(name, Colormap): + return name + _api.check_in_list(sorted(_colormaps), name=name) + if lut is None: + return _colormaps[name] + else: + return _colormaps[name].resampled(lut) + + +def set_cmap(cmap: Colormap | str) -> None: + """ + Set the default colormap, and applies it to the current image if any. + + Parameters + ---------- + cmap : `~matplotlib.colors.Colormap` or str + A colormap instance or the name of a registered colormap. + + See Also + -------- + colormaps + get_cmap + """ + cmap = get_cmap(cmap) + + rc('image', cmap=cmap.name) + im = gci() + + if im is not None: + im.set_cmap(cmap) + + +@_copy_docstring_and_deprecators(matplotlib.image.imread) +def imread( + fname: str | pathlib.Path | BinaryIO, format: str | None = None +) -> np.ndarray: + return matplotlib.image.imread(fname, format) + + +@_copy_docstring_and_deprecators(matplotlib.image.imsave) +def imsave( + fname: str | os.PathLike | BinaryIO, arr: ArrayLike, **kwargs +) -> None: + matplotlib.image.imsave(fname, arr, **kwargs) + + +def matshow(A: ArrayLike, fignum: None | int = None, **kwargs) -> AxesImage: + """ + Display a 2D array as a matrix in a new figure window. + + The origin is set at the upper left hand corner. + The indexing is ``(row, column)`` so that the first index runs vertically + and the second index runs horizontally in the figure: + + .. code-block:: none + + A[0, 0] ⋯ A[0, M-1] + ⋮ ⋮ + A[N-1, 0] ⋯ A[N-1, M-1] + + The aspect ratio of the figure window is that of the array, + unless this would make an excessively short or narrow figure. + + Tick labels for the xaxis are placed on top. + + Parameters + ---------- + A : 2D array-like + The matrix to be displayed. + + fignum : None or int + If *None*, create a new, appropriately sized figure window. + + If 0, use the current Axes (creating one if there is none, without ever + adjusting the figure size). + + Otherwise, create a new Axes on the figure with the given number + (creating it at the appropriate size if it does not exist, but not + adjusting the figure size otherwise). Note that this will be drawn on + top of any preexisting Axes on the figure. + + Returns + ------- + `~matplotlib.image.AxesImage` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.axes.Axes.imshow` arguments + + """ + A = np.asanyarray(A) + if fignum == 0: + ax = gca() + else: + # Extract actual aspect ratio of array and make appropriately sized + # figure. + fig = figure(fignum, figsize=figaspect(A)) + ax = fig.add_axes((0.15, 0.09, 0.775, 0.775)) + im = ax.matshow(A, **kwargs) + sci(im) + return im + + +def polar(*args, **kwargs) -> list[Line2D]: + """ + Make a polar plot. + + call signature:: + + polar(theta, r, **kwargs) + + Multiple *theta*, *r* arguments are supported, with format strings, as in + `plot`. + """ + # If an axis already exists, check if it has a polar projection + if gcf().get_axes(): + ax = gca() + if not isinstance(ax, PolarAxes): + _api.warn_external('Trying to create polar plot on an Axes ' + 'that does not have a polar projection.') + else: + ax = axes(projection="polar") + return ax.plot(*args, **kwargs) + + +# If rcParams['backend_fallback'] is true, and an interactive backend is +# requested, ignore rcParams['backend'] and force selection of a backend that +# is compatible with the current running interactive framework. +if (rcParams["backend_fallback"] + and rcParams._get_backend_or_none() in ( # type: ignore[attr-defined] + set(backend_registry.list_builtin(BackendFilter.INTERACTIVE)) - + {'webagg', 'nbagg'}) + and cbook._get_running_interactive_framework()): + rcParams._set("backend", rcsetup._auto_backend_sentinel) + +# fmt: on + +################# REMAINING CONTENT GENERATED BY boilerplate.py ############## + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.figimage) +def figimage( + X: ArrayLike, + xo: int = 0, + yo: int = 0, + alpha: float | None = None, + norm: str | Normalize | None = None, + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, + origin: Literal["upper", "lower"] | None = None, + resize: bool = False, + **kwargs, +) -> FigureImage: + return gcf().figimage( + X, + xo=xo, + yo=yo, + alpha=alpha, + norm=norm, + cmap=cmap, + vmin=vmin, + vmax=vmax, + origin=origin, + resize=resize, + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.text) +def figtext( + x: float, y: float, s: str, fontdict: dict[str, Any] | None = None, **kwargs +) -> Text: + return gcf().text(x, y, s, fontdict=fontdict, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.gca) +def gca() -> Axes: + return gcf().gca() + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure._gci) +def gci() -> ScalarMappable | None: + return gcf()._gci() + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.ginput) +def ginput( + n: int = 1, + timeout: float = 30, + show_clicks: bool = True, + mouse_add: MouseButton = MouseButton.LEFT, + mouse_pop: MouseButton = MouseButton.RIGHT, + mouse_stop: MouseButton = MouseButton.MIDDLE, +) -> list[tuple[int, int]]: + return gcf().ginput( + n=n, + timeout=timeout, + show_clicks=show_clicks, + mouse_add=mouse_add, + mouse_pop=mouse_pop, + mouse_stop=mouse_stop, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.subplots_adjust) +def subplots_adjust( + left: float | None = None, + bottom: float | None = None, + right: float | None = None, + top: float | None = None, + wspace: float | None = None, + hspace: float | None = None, +) -> None: + gcf().subplots_adjust( + left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.suptitle) +def suptitle(t: str, **kwargs) -> Text: + return gcf().suptitle(t, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.tight_layout) +def tight_layout( + *, + pad: float = 1.08, + h_pad: float | None = None, + w_pad: float | None = None, + rect: tuple[float, float, float, float] | None = None, +) -> None: + gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.waitforbuttonpress) +def waitforbuttonpress(timeout: float = -1) -> None | bool: + return gcf().waitforbuttonpress(timeout=timeout) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.acorr) +def acorr( + x: ArrayLike, *, data=None, **kwargs +) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: + return gca().acorr(x, **({"data": data} if data is not None else {}), **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.angle_spectrum) +def angle_spectrum( + x: ArrayLike, + Fs: float | None = None, + Fc: int | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, Line2D]: + return gca().angle_spectrum( + x, + Fs=Fs, + Fc=Fc, + window=window, + pad_to=pad_to, + sides=sides, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.annotate) +def annotate( + text: str, + xy: tuple[float, float], + xytext: tuple[float, float] | None = None, + xycoords: str + | Artist + | Transform + | Callable[[RendererBase], Bbox | Transform] + | tuple[float, float] = "data", + textcoords: str + | Artist + | Transform + | Callable[[RendererBase], Bbox | Transform] + | tuple[float, float] + | None = None, + arrowprops: dict[str, Any] | None = None, + annotation_clip: bool | None = None, + **kwargs, +) -> Annotation: + return gca().annotate( + text, + xy, + xytext=xytext, + xycoords=xycoords, + textcoords=textcoords, + arrowprops=arrowprops, + annotation_clip=annotation_clip, + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.arrow) +def arrow(x: float, y: float, dx: float, dy: float, **kwargs) -> FancyArrow: + return gca().arrow(x, y, dx, dy, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.autoscale) +def autoscale( + enable: bool = True, + axis: Literal["both", "x", "y"] = "both", + tight: bool | None = None, +) -> None: + gca().autoscale(enable=enable, axis=axis, tight=tight) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axhline) +def axhline(y: float = 0, xmin: float = 0, xmax: float = 1, **kwargs) -> Line2D: + return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axhspan) +def axhspan( + ymin: float, ymax: float, xmin: float = 0, xmax: float = 1, **kwargs +) -> Rectangle: + return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axis) +def axis( + arg: tuple[float, float, float, float] | bool | str | None = None, + /, + *, + emit: bool = True, + **kwargs, +) -> tuple[float, float, float, float]: + return gca().axis(arg, emit=emit, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axline) +def axline( + xy1: tuple[float, float], + xy2: tuple[float, float] | None = None, + *, + slope: float | None = None, + **kwargs, +) -> AxLine: + return gca().axline(xy1, xy2=xy2, slope=slope, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axvline) +def axvline(x: float = 0, ymin: float = 0, ymax: float = 1, **kwargs) -> Line2D: + return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axvspan) +def axvspan( + xmin: float, xmax: float, ymin: float = 0, ymax: float = 1, **kwargs +) -> Rectangle: + return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.bar) +def bar( + x: float | ArrayLike, + height: float | ArrayLike, + width: float | ArrayLike = 0.8, + bottom: float | ArrayLike | None = None, + *, + align: Literal["center", "edge"] = "center", + data=None, + **kwargs, +) -> BarContainer: + return gca().bar( + x, + height, + width=width, + bottom=bottom, + align=align, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.barbs) +def barbs(*args, data=None, **kwargs) -> Barbs: + return gca().barbs(*args, **({"data": data} if data is not None else {}), **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.barh) +def barh( + y: float | ArrayLike, + width: float | ArrayLike, + height: float | ArrayLike = 0.8, + left: float | ArrayLike | None = None, + *, + align: Literal["center", "edge"] = "center", + data=None, + **kwargs, +) -> BarContainer: + return gca().barh( + y, + width, + height=height, + left=left, + align=align, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.bar_label) +def bar_label( + container: BarContainer, + labels: ArrayLike | None = None, + *, + fmt: str | Callable[[float], str] = "%g", + label_type: Literal["center", "edge"] = "edge", + padding: float = 0, + **kwargs, +) -> list[Annotation]: + return gca().bar_label( + container, + labels=labels, + fmt=fmt, + label_type=label_type, + padding=padding, + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.boxplot) +def boxplot( + x: ArrayLike | Sequence[ArrayLike], + notch: bool | None = None, + sym: str | None = None, + vert: bool | None = None, + whis: float | tuple[float, float] | None = None, + positions: ArrayLike | None = None, + widths: float | ArrayLike | None = None, + patch_artist: bool | None = None, + bootstrap: int | None = None, + usermedians: ArrayLike | None = None, + conf_intervals: ArrayLike | None = None, + meanline: bool | None = None, + showmeans: bool | None = None, + showcaps: bool | None = None, + showbox: bool | None = None, + showfliers: bool | None = None, + boxprops: dict[str, Any] | None = None, + tick_labels: Sequence[str] | None = None, + flierprops: dict[str, Any] | None = None, + medianprops: dict[str, Any] | None = None, + meanprops: dict[str, Any] | None = None, + capprops: dict[str, Any] | None = None, + whiskerprops: dict[str, Any] | None = None, + manage_ticks: bool = True, + autorange: bool = False, + zorder: float | None = None, + capwidths: float | ArrayLike | None = None, + label: Sequence[str] | None = None, + *, + data=None, +) -> dict[str, Any]: + return gca().boxplot( + x, + notch=notch, + sym=sym, + vert=vert, + whis=whis, + positions=positions, + widths=widths, + patch_artist=patch_artist, + bootstrap=bootstrap, + usermedians=usermedians, + conf_intervals=conf_intervals, + meanline=meanline, + showmeans=showmeans, + showcaps=showcaps, + showbox=showbox, + showfliers=showfliers, + boxprops=boxprops, + tick_labels=tick_labels, + flierprops=flierprops, + medianprops=medianprops, + meanprops=meanprops, + capprops=capprops, + whiskerprops=whiskerprops, + manage_ticks=manage_ticks, + autorange=autorange, + zorder=zorder, + capwidths=capwidths, + label=label, + **({"data": data} if data is not None else {}), + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.broken_barh) +def broken_barh( + xranges: Sequence[tuple[float, float]], + yrange: tuple[float, float], + *, + data=None, + **kwargs, +) -> PolyCollection: + return gca().broken_barh( + xranges, yrange, **({"data": data} if data is not None else {}), **kwargs + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.clabel) +def clabel(CS: ContourSet, levels: ArrayLike | None = None, **kwargs) -> list[Text]: + return gca().clabel(CS, levels=levels, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.cohere) +def cohere( + x: ArrayLike, + y: ArrayLike, + NFFT: int = 256, + Fs: float = 2, + Fc: int = 0, + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] = mlab.detrend_none, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike = mlab.window_hanning, + noverlap: int = 0, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] = "default", + scale_by_freq: bool | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray]: + return gca().cohere( + x, + y, + NFFT=NFFT, + Fs=Fs, + Fc=Fc, + detrend=detrend, + window=window, + noverlap=noverlap, + pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.contour) +def contour(*args, data=None, **kwargs) -> QuadContourSet: + __ret = gca().contour( + *args, **({"data": data} if data is not None else {}), **kwargs + ) + if __ret._A is not None: # type: ignore[attr-defined] + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.contourf) +def contourf(*args, data=None, **kwargs) -> QuadContourSet: + __ret = gca().contourf( + *args, **({"data": data} if data is not None else {}), **kwargs + ) + if __ret._A is not None: # type: ignore[attr-defined] + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.csd) +def csd( + x: ArrayLike, + y: ArrayLike, + NFFT: int | None = None, + Fs: float | None = None, + Fc: int | None = None, + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + noverlap: int | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + scale_by_freq: bool | None = None, + return_line: bool | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: + return gca().csd( + x, + y, + NFFT=NFFT, + Fs=Fs, + Fc=Fc, + detrend=detrend, + window=window, + noverlap=noverlap, + pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + return_line=return_line, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.ecdf) +def ecdf( + x: ArrayLike, + weights: ArrayLike | None = None, + *, + complementary: bool = False, + orientation: Literal["vertical", "horizonatal"] = "vertical", + compress: bool = False, + data=None, + **kwargs, +) -> Line2D: + return gca().ecdf( + x, + weights=weights, + complementary=complementary, + orientation=orientation, + compress=compress, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.errorbar) +def errorbar( + x: float | ArrayLike, + y: float | ArrayLike, + yerr: float | ArrayLike | None = None, + xerr: float | ArrayLike | None = None, + fmt: str = "", + ecolor: ColorType | None = None, + elinewidth: float | None = None, + capsize: float | None = None, + barsabove: bool = False, + lolims: bool | ArrayLike = False, + uplims: bool | ArrayLike = False, + xlolims: bool | ArrayLike = False, + xuplims: bool | ArrayLike = False, + errorevery: int | tuple[int, int] = 1, + capthick: float | None = None, + *, + data=None, + **kwargs, +) -> ErrorbarContainer: + return gca().errorbar( + x, + y, + yerr=yerr, + xerr=xerr, + fmt=fmt, + ecolor=ecolor, + elinewidth=elinewidth, + capsize=capsize, + barsabove=barsabove, + lolims=lolims, + uplims=uplims, + xlolims=xlolims, + xuplims=xuplims, + errorevery=errorevery, + capthick=capthick, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.eventplot) +def eventplot( + positions: ArrayLike | Sequence[ArrayLike], + orientation: Literal["horizontal", "vertical"] = "horizontal", + lineoffsets: float | Sequence[float] = 1, + linelengths: float | Sequence[float] = 1, + linewidths: float | Sequence[float] | None = None, + colors: ColorType | Sequence[ColorType] | None = None, + alpha: float | Sequence[float] | None = None, + linestyles: LineStyleType | Sequence[LineStyleType] = "solid", + *, + data=None, + **kwargs, +) -> EventCollection: + return gca().eventplot( + positions, + orientation=orientation, + lineoffsets=lineoffsets, + linelengths=linelengths, + linewidths=linewidths, + colors=colors, + alpha=alpha, + linestyles=linestyles, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.fill) +def fill(*args, data=None, **kwargs) -> list[Polygon]: + return gca().fill(*args, **({"data": data} if data is not None else {}), **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.fill_between) +def fill_between( + x: ArrayLike, + y1: ArrayLike | float, + y2: ArrayLike | float = 0, + where: Sequence[bool] | None = None, + interpolate: bool = False, + step: Literal["pre", "post", "mid"] | None = None, + *, + data=None, + **kwargs, +) -> PolyCollection: + return gca().fill_between( + x, + y1, + y2=y2, + where=where, + interpolate=interpolate, + step=step, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.fill_betweenx) +def fill_betweenx( + y: ArrayLike, + x1: ArrayLike | float, + x2: ArrayLike | float = 0, + where: Sequence[bool] | None = None, + step: Literal["pre", "post", "mid"] | None = None, + interpolate: bool = False, + *, + data=None, + **kwargs, +) -> PolyCollection: + return gca().fill_betweenx( + y, + x1, + x2=x2, + where=where, + step=step, + interpolate=interpolate, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.grid) +def grid( + visible: bool | None = None, + which: Literal["major", "minor", "both"] = "major", + axis: Literal["both", "x", "y"] = "both", + **kwargs, +) -> None: + gca().grid(visible=visible, which=which, axis=axis, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.hexbin) +def hexbin( + x: ArrayLike, + y: ArrayLike, + C: ArrayLike | None = None, + gridsize: int | tuple[int, int] = 100, + bins: Literal["log"] | int | Sequence[float] | None = None, + xscale: Literal["linear", "log"] = "linear", + yscale: Literal["linear", "log"] = "linear", + extent: tuple[float, float, float, float] | None = None, + cmap: str | Colormap | None = None, + norm: str | Normalize | None = None, + vmin: float | None = None, + vmax: float | None = None, + alpha: float | None = None, + linewidths: float | None = None, + edgecolors: Literal["face", "none"] | ColorType = "face", + reduce_C_function: Callable[[np.ndarray | list[float]], float] = np.mean, + mincnt: int | None = None, + marginals: bool = False, + *, + data=None, + **kwargs, +) -> PolyCollection: + __ret = gca().hexbin( + x, + y, + C=C, + gridsize=gridsize, + bins=bins, + xscale=xscale, + yscale=yscale, + extent=extent, + cmap=cmap, + norm=norm, + vmin=vmin, + vmax=vmax, + alpha=alpha, + linewidths=linewidths, + edgecolors=edgecolors, + reduce_C_function=reduce_C_function, + mincnt=mincnt, + marginals=marginals, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.hist) +def hist( + x: ArrayLike | Sequence[ArrayLike], + bins: int | Sequence[float] | str | None = None, + range: tuple[float, float] | None = None, + density: bool = False, + weights: ArrayLike | None = None, + cumulative: bool | float = False, + bottom: ArrayLike | float | None = None, + histtype: Literal["bar", "barstacked", "step", "stepfilled"] = "bar", + align: Literal["left", "mid", "right"] = "mid", + orientation: Literal["vertical", "horizontal"] = "vertical", + rwidth: float | None = None, + log: bool = False, + color: ColorType | Sequence[ColorType] | None = None, + label: str | Sequence[str] | None = None, + stacked: bool = False, + *, + data=None, + **kwargs, +) -> tuple[ + np.ndarray | list[np.ndarray], + np.ndarray, + BarContainer | Polygon | list[BarContainer | Polygon], +]: + return gca().hist( + x, + bins=bins, + range=range, + density=density, + weights=weights, + cumulative=cumulative, + bottom=bottom, + histtype=histtype, + align=align, + orientation=orientation, + rwidth=rwidth, + log=log, + color=color, + label=label, + stacked=stacked, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.stairs) +def stairs( + values: ArrayLike, + edges: ArrayLike | None = None, + *, + orientation: Literal["vertical", "horizontal"] = "vertical", + baseline: float | ArrayLike | None = 0, + fill: bool = False, + data=None, + **kwargs, +) -> StepPatch: + return gca().stairs( + values, + edges=edges, + orientation=orientation, + baseline=baseline, + fill=fill, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.hist2d) +def hist2d( + x: ArrayLike, + y: ArrayLike, + bins: None | int | tuple[int, int] | ArrayLike | tuple[ArrayLike, ArrayLike] = 10, + range: ArrayLike | None = None, + density: bool = False, + weights: ArrayLike | None = None, + cmin: float | None = None, + cmax: float | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: + __ret = gca().hist2d( + x, + y, + bins=bins, + range=range, + density=density, + weights=weights, + cmin=cmin, + cmax=cmax, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret[-1]) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.hlines) +def hlines( + y: float | ArrayLike, + xmin: float | ArrayLike, + xmax: float | ArrayLike, + colors: ColorType | Sequence[ColorType] | None = None, + linestyles: LineStyleType = "solid", + label: str = "", + *, + data=None, + **kwargs, +) -> LineCollection: + return gca().hlines( + y, + xmin, + xmax, + colors=colors, + linestyles=linestyles, + label=label, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.imshow) +def imshow( + X: ArrayLike | PIL.Image.Image, + cmap: str | Colormap | None = None, + norm: str | Normalize | None = None, + *, + aspect: Literal["equal", "auto"] | float | None = None, + interpolation: str | None = None, + alpha: float | ArrayLike | None = None, + vmin: float | None = None, + vmax: float | None = None, + origin: Literal["upper", "lower"] | None = None, + extent: tuple[float, float, float, float] | None = None, + interpolation_stage: Literal["data", "rgba"] | None = None, + filternorm: bool = True, + filterrad: float = 4.0, + resample: bool | None = None, + url: str | None = None, + data=None, + **kwargs, +) -> AxesImage: + __ret = gca().imshow( + X, + cmap=cmap, + norm=norm, + aspect=aspect, + interpolation=interpolation, + alpha=alpha, + vmin=vmin, + vmax=vmax, + origin=origin, + extent=extent, + interpolation_stage=interpolation_stage, + filternorm=filternorm, + filterrad=filterrad, + resample=resample, + url=url, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.legend) +def legend(*args, **kwargs) -> Legend: + return gca().legend(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.locator_params) +def locator_params( + axis: Literal["both", "x", "y"] = "both", tight: bool | None = None, **kwargs +) -> None: + gca().locator_params(axis=axis, tight=tight, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.loglog) +def loglog(*args, **kwargs) -> list[Line2D]: + return gca().loglog(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.magnitude_spectrum) +def magnitude_spectrum( + x: ArrayLike, + Fs: float | None = None, + Fc: int | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + scale: Literal["default", "linear", "dB"] | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, Line2D]: + return gca().magnitude_spectrum( + x, + Fs=Fs, + Fc=Fc, + window=window, + pad_to=pad_to, + sides=sides, + scale=scale, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.margins) +def margins( + *margins: float, + x: float | None = None, + y: float | None = None, + tight: bool | None = True, +) -> tuple[float, float] | None: + return gca().margins(*margins, x=x, y=y, tight=tight) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.minorticks_off) +def minorticks_off() -> None: + gca().minorticks_off() + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.minorticks_on) +def minorticks_on() -> None: + gca().minorticks_on() + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.pcolor) +def pcolor( + *args: ArrayLike, + shading: Literal["flat", "nearest", "auto"] | None = None, + alpha: float | None = None, + norm: str | Normalize | None = None, + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, + data=None, + **kwargs, +) -> Collection: + __ret = gca().pcolor( + *args, + shading=shading, + alpha=alpha, + norm=norm, + cmap=cmap, + vmin=vmin, + vmax=vmax, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.pcolormesh) +def pcolormesh( + *args: ArrayLike, + alpha: float | None = None, + norm: str | Normalize | None = None, + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, + shading: Literal["flat", "nearest", "gouraud", "auto"] | None = None, + antialiased: bool = False, + data=None, + **kwargs, +) -> QuadMesh: + __ret = gca().pcolormesh( + *args, + alpha=alpha, + norm=norm, + cmap=cmap, + vmin=vmin, + vmax=vmax, + shading=shading, + antialiased=antialiased, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.phase_spectrum) +def phase_spectrum( + x: ArrayLike, + Fs: float | None = None, + Fc: int | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, Line2D]: + return gca().phase_spectrum( + x, + Fs=Fs, + Fc=Fc, + window=window, + pad_to=pad_to, + sides=sides, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.pie) +def pie( + x: ArrayLike, + explode: ArrayLike | None = None, + labels: Sequence[str] | None = None, + colors: ColorType | Sequence[ColorType] | None = None, + autopct: str | Callable[[float], str] | None = None, + pctdistance: float = 0.6, + shadow: bool = False, + labeldistance: float | None = 1.1, + startangle: float = 0, + radius: float = 1, + counterclock: bool = True, + wedgeprops: dict[str, Any] | None = None, + textprops: dict[str, Any] | None = None, + center: tuple[float, float] = (0, 0), + frame: bool = False, + rotatelabels: bool = False, + *, + normalize: bool = True, + hatch: str | Sequence[str] | None = None, + data=None, +) -> tuple[list[Wedge], list[Text]] | tuple[list[Wedge], list[Text], list[Text]]: + return gca().pie( + x, + explode=explode, + labels=labels, + colors=colors, + autopct=autopct, + pctdistance=pctdistance, + shadow=shadow, + labeldistance=labeldistance, + startangle=startangle, + radius=radius, + counterclock=counterclock, + wedgeprops=wedgeprops, + textprops=textprops, + center=center, + frame=frame, + rotatelabels=rotatelabels, + normalize=normalize, + hatch=hatch, + **({"data": data} if data is not None else {}), + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.plot) +def plot( + *args: float | ArrayLike | str, + scalex: bool = True, + scaley: bool = True, + data=None, + **kwargs, +) -> list[Line2D]: + return gca().plot( + *args, + scalex=scalex, + scaley=scaley, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.plot_date) +def plot_date( + x: ArrayLike, + y: ArrayLike, + fmt: str = "o", + tz: str | datetime.tzinfo | None = None, + xdate: bool = True, + ydate: bool = False, + *, + data=None, + **kwargs, +) -> list[Line2D]: + return gca().plot_date( + x, + y, + fmt=fmt, + tz=tz, + xdate=xdate, + ydate=ydate, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.psd) +def psd( + x: ArrayLike, + NFFT: int | None = None, + Fs: float | None = None, + Fc: int | None = None, + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + noverlap: int | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + scale_by_freq: bool | None = None, + return_line: bool | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: + return gca().psd( + x, + NFFT=NFFT, + Fs=Fs, + Fc=Fc, + detrend=detrend, + window=window, + noverlap=noverlap, + pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + return_line=return_line, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.quiver) +def quiver(*args, data=None, **kwargs) -> Quiver: + __ret = gca().quiver( + *args, **({"data": data} if data is not None else {}), **kwargs + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.quiverkey) +def quiverkey( + Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs +) -> QuiverKey: + return gca().quiverkey(Q, X, Y, U, label, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.scatter) +def scatter( + x: float | ArrayLike, + y: float | ArrayLike, + s: float | ArrayLike | None = None, + c: ArrayLike | Sequence[ColorType] | ColorType | None = None, + marker: MarkerType | None = None, + cmap: str | Colormap | None = None, + norm: str | Normalize | None = None, + vmin: float | None = None, + vmax: float | None = None, + alpha: float | None = None, + linewidths: float | Sequence[float] | None = None, + *, + edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = None, + plotnonfinite: bool = False, + data=None, + **kwargs, +) -> PathCollection: + __ret = gca().scatter( + x, + y, + s=s, + c=c, + marker=marker, + cmap=cmap, + norm=norm, + vmin=vmin, + vmax=vmax, + alpha=alpha, + linewidths=linewidths, + edgecolors=edgecolors, + plotnonfinite=plotnonfinite, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.semilogx) +def semilogx(*args, **kwargs) -> list[Line2D]: + return gca().semilogx(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.semilogy) +def semilogy(*args, **kwargs) -> list[Line2D]: + return gca().semilogy(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.specgram) +def specgram( + x: ArrayLike, + NFFT: int | None = None, + Fs: float | None = None, + Fc: int | None = None, + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + noverlap: int | None = None, + cmap: str | Colormap | None = None, + xextent: tuple[float, float] | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + scale_by_freq: bool | None = None, + mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = None, + scale: Literal["default", "linear", "dB"] | None = None, + vmin: float | None = None, + vmax: float | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: + __ret = gca().specgram( + x, + NFFT=NFFT, + Fs=Fs, + Fc=Fc, + detrend=detrend, + window=window, + noverlap=noverlap, + cmap=cmap, + xextent=xextent, + pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + mode=mode, + scale=scale, + vmin=vmin, + vmax=vmax, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret[-1]) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.spy) +def spy( + Z: ArrayLike, + precision: float | Literal["present"] = 0, + marker: str | None = None, + markersize: float | None = None, + aspect: Literal["equal", "auto"] | float | None = "equal", + origin: Literal["upper", "lower"] = "upper", + **kwargs, +) -> AxesImage: + __ret = gca().spy( + Z, + precision=precision, + marker=marker, + markersize=markersize, + aspect=aspect, + origin=origin, + **kwargs, + ) + if isinstance(__ret, cm.ScalarMappable): + sci(__ret) # noqa + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.stackplot) +def stackplot( + x, *args, labels=(), colors=None, hatch=None, baseline="zero", data=None, **kwargs +): + return gca().stackplot( + x, + *args, + labels=labels, + colors=colors, + hatch=hatch, + baseline=baseline, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.stem) +def stem( + *args: ArrayLike | str, + linefmt: str | None = None, + markerfmt: str | None = None, + basefmt: str | None = None, + bottom: float = 0, + label: str | None = None, + orientation: Literal["vertical", "horizontal"] = "vertical", + data=None, +) -> StemContainer: + return gca().stem( + *args, + linefmt=linefmt, + markerfmt=markerfmt, + basefmt=basefmt, + bottom=bottom, + label=label, + orientation=orientation, + **({"data": data} if data is not None else {}), + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.step) +def step( + x: ArrayLike, + y: ArrayLike, + *args, + where: Literal["pre", "post", "mid"] = "pre", + data=None, + **kwargs, +) -> list[Line2D]: + return gca().step( + x, + y, + *args, + where=where, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.streamplot) +def streamplot( + x, + y, + u, + v, + density=1, + linewidth=None, + color=None, + cmap=None, + norm=None, + arrowsize=1, + arrowstyle="-|>", + minlength=0.1, + transform=None, + zorder=None, + start_points=None, + maxlength=4.0, + integration_direction="both", + broken_streamlines=True, + *, + data=None, +): + __ret = gca().streamplot( + x, + y, + u, + v, + density=density, + linewidth=linewidth, + color=color, + cmap=cmap, + norm=norm, + arrowsize=arrowsize, + arrowstyle=arrowstyle, + minlength=minlength, + transform=transform, + zorder=zorder, + start_points=start_points, + maxlength=maxlength, + integration_direction=integration_direction, + broken_streamlines=broken_streamlines, + **({"data": data} if data is not None else {}), + ) + sci(__ret.lines) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.table) +def table( + cellText=None, + cellColours=None, + cellLoc="right", + colWidths=None, + rowLabels=None, + rowColours=None, + rowLoc="left", + colLabels=None, + colColours=None, + colLoc="center", + loc="bottom", + bbox=None, + edges="closed", + **kwargs, +): + return gca().table( + cellText=cellText, + cellColours=cellColours, + cellLoc=cellLoc, + colWidths=colWidths, + rowLabels=rowLabels, + rowColours=rowColours, + rowLoc=rowLoc, + colLabels=colLabels, + colColours=colColours, + colLoc=colLoc, + loc=loc, + bbox=bbox, + edges=edges, + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.text) +def text( + x: float, y: float, s: str, fontdict: dict[str, Any] | None = None, **kwargs +) -> Text: + return gca().text(x, y, s, fontdict=fontdict, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.tick_params) +def tick_params(axis: Literal["both", "x", "y"] = "both", **kwargs) -> None: + gca().tick_params(axis=axis, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.ticklabel_format) +def ticklabel_format( + *, + axis: Literal["both", "x", "y"] = "both", + style: Literal["", "sci", "scientific", "plain"] | None = None, + scilimits: tuple[int, int] | None = None, + useOffset: bool | float | None = None, + useLocale: bool | None = None, + useMathText: bool | None = None, +) -> None: + gca().ticklabel_format( + axis=axis, + style=style, + scilimits=scilimits, + useOffset=useOffset, + useLocale=useLocale, + useMathText=useMathText, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.tricontour) +def tricontour(*args, **kwargs): + __ret = gca().tricontour(*args, **kwargs) + if __ret._A is not None: # type: ignore[attr-defined] + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.tricontourf) +def tricontourf(*args, **kwargs): + __ret = gca().tricontourf(*args, **kwargs) + if __ret._A is not None: # type: ignore[attr-defined] + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.tripcolor) +def tripcolor( + *args, + alpha=1.0, + norm=None, + cmap=None, + vmin=None, + vmax=None, + shading="flat", + facecolors=None, + **kwargs, +): + __ret = gca().tripcolor( + *args, + alpha=alpha, + norm=norm, + cmap=cmap, + vmin=vmin, + vmax=vmax, + shading=shading, + facecolors=facecolors, + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.triplot) +def triplot(*args, **kwargs): + return gca().triplot(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.violinplot) +def violinplot( + dataset: ArrayLike | Sequence[ArrayLike], + positions: ArrayLike | None = None, + vert: bool = True, + widths: float | ArrayLike = 0.5, + showmeans: bool = False, + showextrema: bool = True, + showmedians: bool = False, + quantiles: Sequence[float | Sequence[float]] | None = None, + points: int = 100, + bw_method: Literal["scott", "silverman"] + | float + | Callable[[GaussianKDE], float] + | None = None, + side: Literal["both", "low", "high"] = "both", + *, + data=None, +) -> dict[str, Collection]: + return gca().violinplot( + dataset, + positions=positions, + vert=vert, + widths=widths, + showmeans=showmeans, + showextrema=showextrema, + showmedians=showmedians, + quantiles=quantiles, + points=points, + bw_method=bw_method, + side=side, + **({"data": data} if data is not None else {}), + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.vlines) +def vlines( + x: float | ArrayLike, + ymin: float | ArrayLike, + ymax: float | ArrayLike, + colors: ColorType | Sequence[ColorType] | None = None, + linestyles: LineStyleType = "solid", + label: str = "", + *, + data=None, + **kwargs, +) -> LineCollection: + return gca().vlines( + x, + ymin, + ymax, + colors=colors, + linestyles=linestyles, + label=label, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.xcorr) +def xcorr( + x: ArrayLike, + y: ArrayLike, + normed: bool = True, + detrend: Callable[[ArrayLike], ArrayLike] = mlab.detrend_none, + usevlines: bool = True, + maxlags: int = 10, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: + return gca().xcorr( + x, + y, + normed=normed, + detrend=detrend, + usevlines=usevlines, + maxlags=maxlags, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes._sci) +def sci(im: ScalarMappable) -> None: + gca()._sci(im) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_title) +def title( + label: str, + fontdict: dict[str, Any] | None = None, + loc: Literal["left", "center", "right"] | None = None, + pad: float | None = None, + *, + y: float | None = None, + **kwargs, +) -> Text: + return gca().set_title(label, fontdict=fontdict, loc=loc, pad=pad, y=y, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_xlabel) +def xlabel( + xlabel: str, + fontdict: dict[str, Any] | None = None, + labelpad: float | None = None, + *, + loc: Literal["left", "center", "right"] | None = None, + **kwargs, +) -> Text: + return gca().set_xlabel( + xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_ylabel) +def ylabel( + ylabel: str, + fontdict: dict[str, Any] | None = None, + labelpad: float | None = None, + *, + loc: Literal["bottom", "center", "top"] | None = None, + **kwargs, +) -> Text: + return gca().set_ylabel( + ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_xscale) +def xscale(value: str | ScaleBase, **kwargs) -> None: + gca().set_xscale(value, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_yscale) +def yscale(value: str | ScaleBase, **kwargs) -> None: + gca().set_yscale(value, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def autumn() -> None: + """ + Set the colormap to 'autumn'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("autumn") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def bone() -> None: + """ + Set the colormap to 'bone'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("bone") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def cool() -> None: + """ + Set the colormap to 'cool'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("cool") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def copper() -> None: + """ + Set the colormap to 'copper'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("copper") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def flag() -> None: + """ + Set the colormap to 'flag'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("flag") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def gray() -> None: + """ + Set the colormap to 'gray'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("gray") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def hot() -> None: + """ + Set the colormap to 'hot'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("hot") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def hsv() -> None: + """ + Set the colormap to 'hsv'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("hsv") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def jet() -> None: + """ + Set the colormap to 'jet'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("jet") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def pink() -> None: + """ + Set the colormap to 'pink'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("pink") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def prism() -> None: + """ + Set the colormap to 'prism'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("prism") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def spring() -> None: + """ + Set the colormap to 'spring'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("spring") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def summer() -> None: + """ + Set the colormap to 'summer'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("summer") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def winter() -> None: + """ + Set the colormap to 'winter'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("winter") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def magma() -> None: + """ + Set the colormap to 'magma'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("magma") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def inferno() -> None: + """ + Set the colormap to 'inferno'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("inferno") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def plasma() -> None: + """ + Set the colormap to 'plasma'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("plasma") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def viridis() -> None: + """ + Set the colormap to 'viridis'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("viridis") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def nipy_spectral() -> None: + """ + Set the colormap to 'nipy_spectral'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("nipy_spectral") diff --git a/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04f30796a10e8da2e65782c67f0673769b724181 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/_markers.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/_markers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce46f11ec337f1841db191a322df6f81dc253c39 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/_markers.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/compare.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/compare.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fde0fa8f2ebe7fb07690a86a57b452388a44ade7 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/compare.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/conftest.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/conftest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0484c327e44c457c28c5f951a957d55d4b02760 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/conftest.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/decorators.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/decorators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd567fd852a91cf77641e7db9df8d896335efd4d Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/decorators.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Epoch.py b/parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Epoch.py new file mode 100644 index 0000000000000000000000000000000000000000..501b7fa38c792d5bc3c7c683e62e1393a63a4ff7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Epoch.py @@ -0,0 +1,211 @@ +"""Epoch module.""" + +import functools +import operator +import math +import datetime as DT + +from matplotlib import _api +from matplotlib.dates import date2num + + +class Epoch: + # Frame conversion offsets in seconds + # t(TO) = t(FROM) + allowed[ FROM ][ TO ] + allowed = { + "ET": { + "UTC": +64.1839, + }, + "UTC": { + "ET": -64.1839, + }, + } + + def __init__(self, frame, sec=None, jd=None, daynum=None, dt=None): + """ + Create a new Epoch object. + + Build an epoch 1 of 2 ways: + + Using seconds past a Julian date: + # Epoch('ET', sec=1e8, jd=2451545) + + or using a matplotlib day number + # Epoch('ET', daynum=730119.5) + + = ERROR CONDITIONS + - If the input units are not in the allowed list, an error is thrown. + + = INPUT VARIABLES + - frame The frame of the epoch. Must be 'ET' or 'UTC' + - sec The number of seconds past the input JD. + - jd The Julian date of the epoch. + - daynum The matplotlib day number of the epoch. + - dt A python datetime instance. + """ + if ((sec is None and jd is not None) or + (sec is not None and jd is None) or + (daynum is not None and + (sec is not None or jd is not None)) or + (daynum is None and dt is None and + (sec is None or jd is None)) or + (daynum is not None and dt is not None) or + (dt is not None and (sec is not None or jd is not None)) or + ((dt is not None) and not isinstance(dt, DT.datetime))): + raise ValueError( + "Invalid inputs. Must enter sec and jd together, " + "daynum by itself, or dt (must be a python datetime).\n" + "Sec = %s\n" + "JD = %s\n" + "dnum= %s\n" + "dt = %s" % (sec, jd, daynum, dt)) + + _api.check_in_list(self.allowed, frame=frame) + self._frame = frame + + if dt is not None: + daynum = date2num(dt) + + if daynum is not None: + # 1-JAN-0001 in JD = 1721425.5 + jd = float(daynum) + 1721425.5 + self._jd = math.floor(jd) + self._seconds = (jd - self._jd) * 86400.0 + + else: + self._seconds = float(sec) + self._jd = float(jd) + + # Resolve seconds down to [ 0, 86400) + deltaDays = math.floor(self._seconds / 86400) + self._jd += deltaDays + self._seconds -= deltaDays * 86400.0 + + def convert(self, frame): + if self._frame == frame: + return self + + offset = self.allowed[self._frame][frame] + + return Epoch(frame, self._seconds + offset, self._jd) + + def frame(self): + return self._frame + + def julianDate(self, frame): + t = self + if frame != self._frame: + t = self.convert(frame) + + return t._jd + t._seconds / 86400.0 + + def secondsPast(self, frame, jd): + t = self + if frame != self._frame: + t = self.convert(frame) + + delta = t._jd - jd + return t._seconds + delta * 86400 + + def _cmp(self, op, rhs): + """Compare Epochs *self* and *rhs* using operator *op*.""" + t = self + if self._frame != rhs._frame: + t = self.convert(rhs._frame) + if t._jd != rhs._jd: + return op(t._jd, rhs._jd) + return op(t._seconds, rhs._seconds) + + __eq__ = functools.partialmethod(_cmp, operator.eq) + __ne__ = functools.partialmethod(_cmp, operator.ne) + __lt__ = functools.partialmethod(_cmp, operator.lt) + __le__ = functools.partialmethod(_cmp, operator.le) + __gt__ = functools.partialmethod(_cmp, operator.gt) + __ge__ = functools.partialmethod(_cmp, operator.ge) + + def __add__(self, rhs): + """ + Add a duration to an Epoch. + + = INPUT VARIABLES + - rhs The Epoch to subtract. + + = RETURN VALUE + - Returns the difference of ourselves and the input Epoch. + """ + t = self + if self._frame != rhs.frame(): + t = self.convert(rhs._frame) + + sec = t._seconds + rhs.seconds() + + return Epoch(t._frame, sec, t._jd) + + def __sub__(self, rhs): + """ + Subtract two Epoch's or a Duration from an Epoch. + + Valid: + Duration = Epoch - Epoch + Epoch = Epoch - Duration + + = INPUT VARIABLES + - rhs The Epoch to subtract. + + = RETURN VALUE + - Returns either the duration between to Epoch's or the a new + Epoch that is the result of subtracting a duration from an epoch. + """ + # Delay-load due to circular dependencies. + import matplotlib.testing.jpl_units as U + + # Handle Epoch - Duration + if isinstance(rhs, U.Duration): + return self + -rhs + + t = self + if self._frame != rhs._frame: + t = self.convert(rhs._frame) + + days = t._jd - rhs._jd + sec = t._seconds - rhs._seconds + + return U.Duration(rhs._frame, days*86400 + sec) + + def __str__(self): + """Print the Epoch.""" + return f"{self.julianDate(self._frame):22.15e} {self._frame}" + + def __repr__(self): + """Print the Epoch.""" + return str(self) + + @staticmethod + def range(start, stop, step): + """ + Generate a range of Epoch objects. + + Similar to the Python range() method. Returns the range [ + start, stop) at the requested step. Each element will be a + Epoch object. + + = INPUT VARIABLES + - start The starting value of the range. + - stop The stop value of the range. + - step Step to use. + + = RETURN VALUE + - Returns a list containing the requested Epoch values. + """ + elems = [] + + i = 0 + while True: + d = start + i * step + if d >= stop: + break + + elems.append(d) + i += 1 + + return elems diff --git a/parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3db72495fe63e37c2a01dd4152989417ae63c34f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so b/parrot/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ce7d9ea8552206a5e6a73f7926f1e404107b428f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f41871d4f27ecbddbff09e268203fb6938c59c2b7d36ff313d05b42530f39a77 +size 617056 diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_adaptive_avg_pool2d_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_adaptive_avg_pool2d_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e173e65104b68e2fae33f7b501402fcc0a21a1ef --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_adaptive_avg_pool2d_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor _adaptive_avg_pool2d(const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API at::Tensor _adaptive_avg_pool2d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_efficientzerotensor_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_efficientzerotensor_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..11ba35679dc57b303b0f4c4af5d83f6d6e0900af --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_efficientzerotensor_compositeexplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _efficientzerotensor_out(at::Tensor & out, at::IntArrayRef size); +TORCH_API at::Tensor & _efficientzerotensor_outf(at::IntArrayRef size, at::Tensor & out); +TORCH_API at::Tensor & _efficientzerotensor_symint_out(at::Tensor & out, c10::SymIntArrayRef size); +TORCH_API at::Tensor & _efficientzerotensor_symint_outf(c10::SymIntArrayRef size, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_div_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_div_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a97528c8505429e4d9ef7d040bbc9a55196397c6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_div_ops.h @@ -0,0 +1,149 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _foreach_div_Scalar { + using schema = ::std::vector (at::TensorList, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]") + static ::std::vector call(at::TensorList self, const at::Scalar & scalar); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar); +}; + +struct TORCH_API _foreach_div__Scalar { + using schema = void (at::TensorList, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()") + static void call(at::TensorList self, const at::Scalar & scalar); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar); +}; + +struct TORCH_API _foreach_div_List { + using schema = ::std::vector (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.List(Tensor[] self, Tensor[] other) -> Tensor[]") + static ::std::vector call(at::TensorList self, at::TensorList other); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other); +}; + +struct TORCH_API _foreach_div__List { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.List(Tensor(a!)[] self, Tensor[] other) -> ()") + static void call(at::TensorList self, at::TensorList other); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other); +}; + +struct TORCH_API _foreach_div_ScalarList { + using schema = ::std::vector (at::TensorList, at::ArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]") + static ::std::vector call(at::TensorList self, at::ArrayRef scalars); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars); +}; + +struct TORCH_API _foreach_div__ScalarList { + using schema = void (at::TensorList, at::ArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()") + static void call(at::TensorList self, at::ArrayRef scalars); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars); +}; + +struct TORCH_API _foreach_div_Tensor { + using schema = ::std::vector (at::TensorList, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Tensor(Tensor[] self, Tensor other) -> Tensor[]") + static ::std::vector call(at::TensorList self, const at::Tensor & other); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other); +}; + +struct TORCH_API _foreach_div__Tensor { + using schema = void (at::TensorList, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.Tensor(Tensor(a!)[] self, Tensor other) -> ()") + static void call(at::TensorList self, const at::Tensor & other); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other); +}; + +struct TORCH_API _foreach_div_Scalar_out { + using schema = void (at::TensorList, const at::Scalar &, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, const at::Scalar & scalar, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar, at::TensorList out); +}; + +struct TORCH_API _foreach_div_List_out { + using schema = void (at::TensorList, at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, at::TensorList other, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other, at::TensorList out); +}; + +struct TORCH_API _foreach_div_ScalarList_out { + using schema = void (at::TensorList, at::ArrayRef, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, at::ArrayRef scalars, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars, at::TensorList out); +}; + +struct TORCH_API _foreach_div_Tensor_out { + using schema = void (at::TensorList, const at::Tensor &, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Tensor_out(Tensor[] self, Tensor other, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, const at::Tensor & other, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_max_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_max_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..af17fad00ab3117be6a774ccf3319cf81ea92c51 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_max_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _foreach_max { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_max") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_max(Tensor[] self) -> Tensor[]") + static ::std::vector call(at::TensorList self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_max_out { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_max") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_max.out(Tensor[] self, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_is_zerotensor_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_is_zerotensor_native.h new file mode 100644 index 0000000000000000000000000000000000000000..33ed3d7c5edb93bf35da90c4abd1a1496bdb0d56 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_is_zerotensor_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API bool _is_zerotensor(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_copy_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_copy_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b8668ad456185eac24242e80f3f77bc5229d8a38 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_copy_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _neg_view_copy_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor _neg_view_copy(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_get_min_seqlen_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_get_min_seqlen_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b9d2e5fd5be542077158871f57ae9c937e4f7895 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_get_min_seqlen_native.h @@ -0,0 +1,20 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_jagged_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_jagged_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b9d2e5fd5be542077158871f57ae9c937e4f7895 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_jagged_native.h @@ -0,0 +1,20 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_test_optional_intlist_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_test_optional_intlist_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f3ed4f5b973c1456d314a72d2ef2e758d8cad526 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_test_optional_intlist_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _test_optional_intlist { + using schema = at::Tensor (const at::Tensor &, at::OptionalIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_test_optional_intlist") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_test_optional_intlist(Tensor values, int[]? addends) -> Tensor") + static at::Tensor call(const at::Tensor & values, at::OptionalIntArrayRef addends); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & values, at::OptionalIntArrayRef addends); +}; + +struct TORCH_API _test_optional_intlist_out { + using schema = at::Tensor & (const at::Tensor &, at::OptionalIntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_test_optional_intlist") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_test_optional_intlist.out(Tensor values, int[]? addends, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & values, at::OptionalIntArrayRef addends, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & values, at::OptionalIntArrayRef addends, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_weight_int8pack_mm.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_weight_int8pack_mm.h new file mode 100644 index 0000000000000000000000000000000000000000..5879eae7dc38bc3f34b2ba2762cea5a60e7f0358 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_weight_int8pack_mm.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_weight_int8pack_mm(Tensor self, Tensor mat2, Tensor scales) -> Tensor +inline at::Tensor _weight_int8pack_mm(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & scales) { + return at::_ops::_weight_int8pack_mm::call(self, mat2, scales); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/argmax_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/argmax_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..3d48bb1ec74cc7946d45939d47bfff16ab4ca955 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/argmax_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_argmax : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, ::std::optional dim, bool keepdim); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_update_stats_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_update_stats_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..5eb13d29fd346e7d5b117a22654f5449cc89812f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_update_stats_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple batch_norm_update_stats_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & input, const ::std::optional & running_mean, const ::std::optional & running_var, double momentum); +TORCH_API ::std::tuple batch_norm_update_stats_outf(const at::Tensor & input, const ::std::optional & running_mean, const ::std::optional & running_var, double momentum, at::Tensor & out0, at::Tensor & out1); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bucketize_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bucketize_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..cf70f00000d8c3c874ec9e525a5fb32c38d494f3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bucketize_cpu_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor bucketize(const at::Tensor & self, const at::Tensor & boundaries, bool out_int32=false, bool right=false); +TORCH_API at::Tensor & bucketize_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & boundaries, bool out_int32=false, bool right=false); +TORCH_API at::Tensor & bucketize_outf(const at::Tensor & self, const at::Tensor & boundaries, bool out_int32, bool right, at::Tensor & out); +TORCH_API at::Tensor bucketize(const at::Scalar & self, const at::Tensor & boundaries, bool out_int32=false, bool right=false); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/einsum_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/einsum_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..74b577c528f9eb37b3bfc5142013669cdce983a7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/einsum_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor einsum(c10::string_view equation, at::TensorList tensors, at::OptionalIntArrayRef path=::std::nullopt); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expand.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expand.h new file mode 100644 index 0000000000000000000000000000000000000000..9d87bebf6b744362e41d409568f4ed1b1b8afbfe --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expand.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +namespace symint { + template ::value>> + at::Tensor expand(const at::Tensor & self, at::IntArrayRef size, bool implicit=false) { + return at::_ops::expand::call(self, c10::fromIntArrayRefSlow(size), implicit); + } +} + +namespace symint { + template ::value>> + at::Tensor expand(const at::Tensor & self, c10::SymIntArrayRef size, bool implicit=false) { + return at::_ops::expand::call(self, size, implicit); + } +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/index_add_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/index_add_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..ea869bbee7c07a7d52aea4c5f77b7c181a8cb82e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/index_add_meta.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_index_add : public at::impl::MetaBase { + + template + struct TORCH_API precompute_out { + + precompute_out set_dim(int64_t value) { + static_assert(DIM == false, "dim already set"); + precompute_out ret; +ret.dim = value; +return ret; + } + + int64_t dim; + }; + using meta_return_ty = precompute_out ; + meta_return_ty meta(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/kthvalue_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/kthvalue_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8c4d8f91146198cccd658af25b8f644742c82a5a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/kthvalue_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple kthvalue_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t k, int64_t dim=-1, bool keepdim=false); +TORCH_API ::std::tuple kthvalue_outf(const at::Tensor & self, int64_t k, int64_t dim, bool keepdim, at::Tensor & values, at::Tensor & indices); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/leaky_relu_backward_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/leaky_relu_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ad2cb96cfb236417ae26f851cbac7143aba3c709 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/leaky_relu_backward_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API leaky_relu_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Scalar &, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::leaky_relu_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "leaky_relu_backward.grad_input(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result, *, Tensor(a!) grad_input) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result, at::Tensor & grad_input); +}; + +struct TORCH_API leaky_relu_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Scalar &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::leaky_relu_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_vector_norm_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_vector_norm_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..2851ca3d6a5a59d1df769f65f85cccbd6b6f18d7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_vector_norm_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_linalg_vector_norm : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, const at::Scalar & ord, at::OptionalIntArrayRef dim, bool keepdim, ::std::optional dtype); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/logit.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/logit.h new file mode 100644 index 0000000000000000000000000000000000000000..073ecf7dcdf9d1a7d9c55d599f571bd7cbca4e9e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/logit.h @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::logit(Tensor self, float? eps=None) -> Tensor +inline at::Tensor logit(const at::Tensor & self, ::std::optional eps=::std::nullopt) { + return at::_ops::logit::call(self, eps); +} + +// aten::logit_(Tensor(a!) self, float? eps=None) -> Tensor(a!) +inline at::Tensor & logit_(at::Tensor & self, ::std::optional eps=::std::nullopt) { + return at::_ops::logit_::call(self, eps); +} + +// aten::logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logit_out(at::Tensor & out, const at::Tensor & self, ::std::optional eps=::std::nullopt) { + return at::_ops::logit_out::call(self, eps, out); +} +// aten::logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logit_outf(const at::Tensor & self, ::std::optional eps, at::Tensor & out) { + return at::_ops::logit_out::call(self, eps, out); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mish.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mish.h new file mode 100644 index 0000000000000000000000000000000000000000..a9cdcb37ae67b88f3af6a33a477686235d3324a1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mish.h @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::mish(Tensor self) -> Tensor +inline at::Tensor mish(const at::Tensor & self) { + return at::_ops::mish::call(self); +} + +// aten::mish_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & mish_(at::Tensor & self) { + return at::_ops::mish_::call(self); +} + +// aten::mish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mish_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::mish_out::call(self, out); +} +// aten::mish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mish_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::mish_out::call(self, out); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_linear_backward_weights_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_linear_backward_weights_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ce9ae3041d664f991cc4f62a4a6697c5595f5d3f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_linear_backward_weights_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API mkldnn_linear_backward_weights { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mkldnn_linear_backward_weights") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mkldnn_linear_backward_weights(Tensor grad_output, Tensor input, Tensor weight, bool bias_defined) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, bool bias_defined); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, bool bias_defined); +}; + +struct TORCH_API mkldnn_linear_backward_weights_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mkldnn_linear_backward_weights") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mkldnn_linear_backward_weights.out(Tensor grad_output, Tensor input, Tensor weight, bool bias_defined, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))") + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, bool bias_defined, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, bool bias_defined, at::Tensor & out0, at::Tensor & out1); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/multiply_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/multiply_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a7c3737e20c0daba70dd8f2375d55205c6bd7275 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/multiply_ops.h @@ -0,0 +1,72 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API multiply_Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::multiply") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "multiply.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API multiply__Tensor { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::multiply_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "multiply_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API multiply_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::multiply") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "multiply.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API multiply_Scalar { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::multiply") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "multiply.Scalar(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API multiply__Scalar { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::multiply_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "multiply_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/neg_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/neg_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b446677f12be9af27fffd74a179ec1b449cd9aca --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/neg_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API neg { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::neg") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "neg(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API neg_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::neg_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "neg_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API neg_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::neg") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "neg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/norm_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/norm_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1abaf46ac38d67c672cf0ea408bb3afc894e466d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/norm_compositeexplicitautograd_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor norm(const at::Tensor & self, const ::std::optional & p, at::ScalarType dtype); +TORCH_API at::Tensor & norm_out(at::Tensor & out, const at::Tensor & self, const ::std::optional & p, at::ScalarType dtype); +TORCH_API at::Tensor & norm_outf(const at::Tensor & self, const ::std::optional & p, at::ScalarType dtype, at::Tensor & out); +TORCH_API at::Tensor norm(const at::Tensor & self, const at::Scalar & p=2); +TORCH_API at::Tensor & norm_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & p=2); +TORCH_API at::Tensor & norm_outf(const at::Tensor & self, const at::Scalar & p, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantized_max_pool1d_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantized_max_pool1d_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9ba69e90ecf528054d2f712d37f16dccfafd02cb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantized_max_pool1d_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & quantized_max_pool1d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false); +TORCH_API at::Tensor & quantized_max_pool1d_outf(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/resize_as_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/resize_as_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..eaef6cfa1e4d4b51a8b28f8289c2f0907c2ba736 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/resize_as_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API resize_as_ { + using schema = const at::Tensor & (const at::Tensor &, const at::Tensor &, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::resize_as_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "resize_as_(Tensor(a!) self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor(a!)") + static const at::Tensor & call(const at::Tensor & self, const at::Tensor & the_template, ::std::optional memory_format); + static const at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & the_template, ::std::optional memory_format); +}; + +struct TORCH_API resize_as_out { + using schema = const at::Tensor & (const at::Tensor &, const at::Tensor &, ::std::optional, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::resize_as") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "resize_as.out(Tensor self, Tensor the_template, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)") + static const at::Tensor & call(const at::Tensor & self, const at::Tensor & the_template, ::std::optional memory_format, const at::Tensor & out); + static const at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & the_template, ::std::optional memory_format, const at::Tensor & out); +}; + +struct TORCH_API resize_as { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::resize_as") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "resize_as(Tensor self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & the_template, ::std::optional memory_format); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & the_template, ::std::optional memory_format); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/selu_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/selu_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..bdc19ad8102e7aba653b21f59f2eeef8d3a4d3e3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/selu_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API selu { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::selu") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "selu(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API selu_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::selu_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "selu_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/signbit_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/signbit_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e1210ea2aae6503bcedd287583cbfe09438fcf8a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/signbit_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor signbit(const at::Tensor & self); +TORCH_API at::Tensor & signbit_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & signbit_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slice_scatter_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slice_scatter_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..721837de96b90eab6ca3256221fb56b98330c979 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slice_scatter_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor slice_scatter(const at::Tensor & self, const at::Tensor & src, int64_t dim=0, ::std::optional start=::std::nullopt, ::std::optional end=::std::nullopt, int64_t step=1); +TORCH_API at::Tensor slice_scatter_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim=0, ::std::optional start=::std::nullopt, ::std::optional end=::std::nullopt, c10::SymInt step=1); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/softshrink.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/softshrink.h new file mode 100644 index 0000000000000000000000000000000000000000..76ec5dae863312f5cc2366186ad728163ca2590d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/softshrink.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::softshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & softshrink_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & lambd=0.5) { + return at::_ops::softshrink_out::call(self, lambd, out); +} +// aten::softshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & softshrink_outf(const at::Tensor & self, const at::Scalar & lambd, at::Tensor & out) { + return at::_ops::softshrink_out::call(self, lambd, out); +} + +// aten::softshrink(Tensor self, Scalar lambd=0.5) -> Tensor +inline at::Tensor softshrink(const at::Tensor & self, const at::Scalar & lambd=0.5) { + return at::_ops::softshrink::call(self, lambd); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_scaled_modified_bessel_k0_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_scaled_modified_bessel_k0_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f2b3f8ddf071b56969ecfa467d4a162e5ca3ceb6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_scaled_modified_bessel_k0_cpu_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor special_scaled_modified_bessel_k0(const at::Tensor & x); +TORCH_API at::Tensor & special_scaled_modified_bessel_k0_out(at::Tensor & out, const at::Tensor & x); +TORCH_API at::Tensor & special_scaled_modified_bessel_k0_outf(const at::Tensor & x, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_zeta_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_zeta_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..047a25d5eeed6446e96653f7ab461f18c8bee9d2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_zeta_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor special_zeta(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & special_zeta_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & special_zeta_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unique_dim_consecutive_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unique_dim_consecutive_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8ac20e4a3b77b9b5e2ff35de21e45b84ea0c24c1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unique_dim_consecutive_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple unique_dim_consecutive_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & self, int64_t dim, bool return_inverse=false, bool return_counts=false); +TORCH_API ::std::tuple unique_dim_consecutive_outf(const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/view_as_complex_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/view_as_complex_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0547319778f01264a924783f72fad970d45c0136 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/view_as_complex_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API view_as_complex { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::view_as_complex") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "view_as_complex(Tensor(a) self) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops