id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
171,010
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler _validate_named_linestyle = ValidateInStrings( 'linestyle', [*ls_mapper.keys(), *ls_mapper.values(), 'None', 'none', ' ', ''], ignorecase=True) class Number(metaclass=ABCMeta): def __hash__(self) -> int: ... The provided code snippet includes necessary dependencies for implementing the `_validate_linestyle` function. Write a Python function `def _validate_linestyle(ls)` to solve the following problem: A validator for all possible line styles, the named ones *and* the on-off ink sequences. Here is the function: def _validate_linestyle(ls): """ A validator for all possible line styles, the named ones *and* the on-off ink sequences. """ if isinstance(ls, str): try: # Look first for a valid named line style, like '--' or 'solid'. return _validate_named_linestyle(ls) except ValueError: pass try: ls = ast.literal_eval(ls) # Parsing matplotlibrc. except (SyntaxError, ValueError): pass # Will error with the ValueError at the end. def _is_iterable_not_string_like(x): # Explicitly exclude bytes/bytearrays so that they are not # nonsensically interpreted as sequences of numbers (codepoints). return np.iterable(x) and not isinstance(x, (str, bytes, bytearray)) if _is_iterable_not_string_like(ls): if len(ls) == 2 and _is_iterable_not_string_like(ls[1]): # (offset, (on, off, on, off, ...)) offset, onoff = ls else: # For backcompat: (on, off, on, off, ...); the offset is implicit. offset = 0 onoff = ls if (isinstance(offset, Number) and len(onoff) % 2 == 0 and all(isinstance(elem, Number) for elem in onoff)): return (offset, onoff) raise ValueError(f"linestyle {ls!r} is not a valid on-off ink sequence.")
A validator for all possible line styles, the named ones *and* the on-off ink sequences.
171,011
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler The provided code snippet includes necessary dependencies for implementing the `validate_markevery` function. Write a Python function `def validate_markevery(s)` to solve the following problem: Validate the markevery property of a Line2D object. Parameters ---------- s : None, int, (int, int), slice, float, (float, float), or list[int] Returns ------- None, int, (int, int), slice, float, (float, float), or list[int] Here is the function: def validate_markevery(s): """ Validate the markevery property of a Line2D object. Parameters ---------- s : None, int, (int, int), slice, float, (float, float), or list[int] Returns ------- None, int, (int, int), slice, float, (float, float), or list[int] """ # Validate s against type slice float int and None if isinstance(s, (slice, float, int, type(None))): return s # Validate s against type tuple if isinstance(s, tuple): if (len(s) == 2 and (all(isinstance(e, int) for e in s) or all(isinstance(e, float) for e in s))): return s else: raise TypeError( "'markevery' tuple must be pair of ints or of floats") # Validate s against type list if isinstance(s, list): if all(isinstance(e, int) for e in s): return s else: raise TypeError( "'markevery' list must have all elements of type int") raise TypeError("'markevery' is of an invalid type")
Validate the markevery property of a Line2D object. Parameters ---------- s : None, int, (int, int), slice, float, (float, float), or list[int] Returns ------- None, int, (int, int), slice, float, (float, float), or list[int]
171,012
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler def validate_bbox(s): if isinstance(s, str): s = s.lower() if s == 'tight': return s if s == 'standard': return None raise ValueError("bbox should be 'tight' or 'standard'") elif s is not None: # Backwards compatibility. None is equivalent to 'standard'. raise ValueError("bbox should be 'tight' or 'standard'") return s
null
171,013
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler def _listify_validator(scalar_validator, allow_stringlist=False, *, n=None, doc=None): def f(s): if isinstance(s, str): try: val = [scalar_validator(v.strip()) for v in s.split(',') if v.strip()] except Exception: if allow_stringlist: # Sometimes, a list of colors might be a single string # of single-letter colornames. So give that a shot. val = [scalar_validator(v.strip()) for v in s if v.strip()] else: raise # Allow any ordered sequence type -- generators, np.ndarray, pd.Series # -- but not sets, whose iteration order is non-deterministic. elif np.iterable(s) and not isinstance(s, (set, frozenset)): # The condition on this list comprehension will preserve the # behavior of filtering out any empty strings (behavior was # from the original validate_stringlist()), while allowing # any non-string/text scalar values such as numbers and arrays. val = [scalar_validator(v) for v in s if not isinstance(v, str) or v] else: raise ValueError( f"Expected str or other non-set iterable, but got {s}") if n is not None and len(val) != n: raise ValueError( f"Expected {n} values, but there are {len(val)} values in {s}") return val try: f.__name__ = "{}list".format(scalar_validator.__name__) except AttributeError: # class instance. f.__name__ = "{}List".format(type(scalar_validator).__name__) f.__qualname__ = f.__qualname__.rsplit(".", 1)[0] + "." + f.__name__ f.__doc__ = doc if doc is not None else scalar_validator.__doc__ return f validate_float = _make_type_validator(float) def validate_sketch(s): if isinstance(s, str): s = s.lower() if s == 'none' or s is None: return None try: return tuple(_listify_validator(validate_float, n=3)(s)) except ValueError: raise ValueError("Expected a (scale, length, randomness) triplet")
null
171,014
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler validate_float = _make_type_validator(float) def _validate_greaterequal0_lessthan1(s): s = validate_float(s) if 0 <= s < 1: return s else: raise RuntimeError(f'Value must be >=0 and <1; got {s}')
null
171,015
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler validate_float = _make_type_validator(float) def _validate_greaterequal0_lessequal1(s): s = validate_float(s) if 0 <= s <= 1: return s else: raise RuntimeError(f'Value must be >=0 and <=1; got {s}')
null
171,016
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler The provided code snippet includes necessary dependencies for implementing the `validate_hatch` function. Write a Python function `def validate_hatch(s)` to solve the following problem: r""" Validate a hatch pattern. A hatch pattern string can have any sequence of the following characters: ``\ / | - + * . x o O``. Here is the function: def validate_hatch(s): r""" Validate a hatch pattern. A hatch pattern string can have any sequence of the following characters: ``\ / | - + * . x o O``. """ if not isinstance(s, str): raise ValueError("Hatch pattern must be a string") _api.check_isinstance(str, hatch_pattern=s) unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'} if unknown: raise ValueError("Unknown hatch symbol(s): %s" % list(unknown)) return s
r""" Validate a hatch pattern. A hatch pattern string can have any sequence of the following characters: ``\ / | - + * . x o O``.
171,017
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler validate_floatlist = _listify_validator( validate_float, doc='return a list of floats') def validate_hist_bins(s): valid_strs = ["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"] if isinstance(s, str) and s in valid_strs: return s try: return int(s) except (TypeError, ValueError): pass try: return validate_floatlist(s) except ValueError: pass raise ValueError("'hist.bins' must be one of {}, an int or" " a sequence of floats".format(valid_strs))
null
171,018
import ast from functools import lru_cache, reduce from numbers import Number import operator import os import re import numpy as np from matplotlib import _api, cbook from matplotlib.cbook import ls_mapper from matplotlib.colors import Colormap, is_color_like from matplotlib._fontconfig_pattern import parse_fontconfig_pattern from matplotlib._enums import JoinStyle, CapStyle from cycler import Cycler, cycler as ccycler class ValidateInStrings: def __init__(self, key, valid, ignorecase=False, *, _deprecated_since=None): """*valid* is a list of legal strings.""" self.key = key self.ignorecase = ignorecase self._deprecated_since = _deprecated_since def func(s): if ignorecase: return s.lower() else: return s self.valid = {func(k): k for k in valid} def __call__(self, s): if self._deprecated_since: name, = (k for k, v in globals().items() if v is self) _api.warn_deprecated( self._deprecated_since, name=name, obj_type="function") if self.ignorecase and isinstance(s, str): s = s.lower() if s in self.valid: return self.valid[s] msg = (f"{s!r} is not a valid value for {self.key}; supported values " f"are {[*self.valid.values()]}") if (isinstance(s, str) and (s.startswith('"') and s.endswith('"') or s.startswith("'") and s.endswith("'")) and s[1:-1] in self.valid): msg += "; remove quotes surrounding your string" raise ValueError(msg) class _ignorecase(list): """A marker class indicating that a list-of-str is case-insensitive.""" def _convert_validator_spec(key, conv): if isinstance(conv, list): ignorecase = isinstance(conv, _ignorecase) return ValidateInStrings(key, conv, ignorecase=ignorecase) else: return conv
null
171,019
from base64 import b64encode import copy import dataclasses from functools import lru_cache from io import BytesIO import json import logging from numbers import Number import os from pathlib import Path import re import subprocess import sys import threading import matplotlib as mpl from matplotlib import _api, _afm, cbook, ft2font from matplotlib._fontconfig_pattern import ( parse_fontconfig_pattern, generate_fontconfig_pattern) from matplotlib.rcsetup import _validators X11FontDirectories = [ # an old standard installation point "/usr/X11R6/lib/X11/fonts/TTF/", "/usr/X11/lib/X11/fonts", # here is the new standard location for fonts "/usr/share/fonts/", # documented as a good place to install new fonts "/usr/local/share/fonts/", # common application, not really useful "/usr/lib/openoffice/share/fonts/truetype/", # user fonts str((Path(os.environ.get('XDG_DATA_HOME') or _HOME / ".local/share")) / "fonts"), str(_HOME / ".fonts"), ] OSXFontDirectories = [ "/Library/Fonts/", "/Network/Library/Fonts/", "/System/Library/Fonts/", # fonts installed via MacPorts "/opt/local/share/fonts", # user fonts str(_HOME / "Library/Fonts"), ] def get_fontext_synonyms(fontext): """ Return a list of file extensions that are synonyms for the given file extension *fileext*. """ return { 'afm': ['afm'], 'otf': ['otf', 'ttc', 'ttf'], 'ttc': ['otf', 'ttc', 'ttf'], 'ttf': ['otf', 'ttc', 'ttf'], }[fontext] def list_fonts(directory, extensions): """ Return a list of all fonts matching any of the extensions, found recursively under the directory. """ extensions = ["." + ext for ext in extensions] return [os.path.join(dirpath, filename) # os.walk ignores access errors, unlike Path.glob. for dirpath, _, filenames in os.walk(directory) for filename in filenames if Path(filename).suffix.lower() in extensions] def _get_win32_installed_fonts(): """List the font paths known to the Windows registry.""" import winreg items = set() # Search and resolve fonts listed in the registry. for domain, base_dirs in [ (winreg.HKEY_LOCAL_MACHINE, [win32FontDirectory()]), # System. (winreg.HKEY_CURRENT_USER, MSUserFontDirectories), # User. ]: for base_dir in base_dirs: for reg_path in MSFontDirectories: try: with winreg.OpenKey(domain, reg_path) as local: for j in range(winreg.QueryInfoKey(local)[1]): # value may contain the filename of the font or its # absolute path. key, value, tp = winreg.EnumValue(local, j) if not isinstance(value, str): continue try: # If value contains already an absolute path, # then it is not changed further. path = Path(base_dir, value).resolve() except RuntimeError: # Don't fail with invalid entries. continue items.add(path) except (OSError, MemoryError): continue return items def _get_fontconfig_fonts(): """Cache and list the font paths known to ``fc-list``.""" try: if b'--format' not in subprocess.check_output(['fc-list', '--help']): _log.warning( # fontconfig 2.7 implemented --format. 'Matplotlib needs fontconfig>=2.7 to query system fonts.') return [] out = subprocess.check_output(['fc-list', '--format=%{file}\\n']) except (OSError, subprocess.CalledProcessError): return [] return [Path(os.fsdecode(fname)) for fname in out.split(b'\n')] import os ) if os.environ.get('MPLBACKEND'): rcParams['backend'] = os.environ.get('MPLBACKEND') The provided code snippet includes necessary dependencies for implementing the `findSystemFonts` function. Write a Python function `def findSystemFonts(fontpaths=None, fontext='ttf')` to solve the following problem: Search for fonts in the specified font paths. If no paths are given, will use a standard set of system paths, as well as the list of fonts tracked by fontconfig if fontconfig is installed and available. A list of TrueType fonts are returned by default with AFM fonts as an option. Here is the function: def findSystemFonts(fontpaths=None, fontext='ttf'): """ Search for fonts in the specified font paths. If no paths are given, will use a standard set of system paths, as well as the list of fonts tracked by fontconfig if fontconfig is installed and available. A list of TrueType fonts are returned by default with AFM fonts as an option. """ fontfiles = set() fontexts = get_fontext_synonyms(fontext) if fontpaths is None: if sys.platform == 'win32': installed_fonts = _get_win32_installed_fonts() fontpaths = [] else: installed_fonts = _get_fontconfig_fonts() if sys.platform == 'darwin': fontpaths = [*X11FontDirectories, *OSXFontDirectories] else: fontpaths = X11FontDirectories fontfiles.update(str(path) for path in installed_fonts if path.suffix.lower()[1:] in fontexts) elif isinstance(fontpaths, str): fontpaths = [fontpaths] for path in fontpaths: fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts))) return [fname for fname in fontfiles if os.path.exists(fname)]
Search for fonts in the specified font paths. If no paths are given, will use a standard set of system paths, as well as the list of fonts tracked by fontconfig if fontconfig is installed and available. A list of TrueType fonts are returned by default with AFM fonts as an option.
171,020
from base64 import b64encode import copy import dataclasses from functools import lru_cache from io import BytesIO import json import logging from numbers import Number import os from pathlib import Path import re import subprocess import sys import threading import matplotlib as mpl from matplotlib import _api, _afm, cbook, ft2font from matplotlib._fontconfig_pattern import ( parse_fontconfig_pattern, generate_fontconfig_pattern) from matplotlib.rcsetup import _validators def _fontentry_helper_repr_png(fontent): from matplotlib.figure import Figure # Circular import. fig = Figure() font_path = Path(fontent.fname) if fontent.fname != '' else None fig.text(0, 0, fontent.name, font=font_path) with BytesIO() as buf: fig.savefig(buf, bbox_inches='tight', transparent=True) return buf.getvalue() def b64encode(s: _encodable, altchars: Optional[bytes] = ...) -> bytes: ... def _fontentry_helper_repr_html(fontent): png_stream = _fontentry_helper_repr_png(fontent) png_b64 = b64encode(png_stream).decode() return f"<img src=\"data:image/png;base64, {png_b64}\" />"
null
171,021
from base64 import b64encode import copy import dataclasses from functools import lru_cache from io import BytesIO import json import logging from numbers import Number import os from pathlib import Path import re import subprocess import sys import threading import matplotlib as mpl from matplotlib import _api, _afm, cbook, ft2font from matplotlib._fontconfig_pattern import ( parse_fontconfig_pattern, generate_fontconfig_pattern) from matplotlib.rcsetup import _validators _weight_regexes = [ # From fontconfig's FcFreeTypeQueryFaceInternal; not the same as # weight_dict! ("thin", 100), ("extralight", 200), ("ultralight", 200), ("demilight", 350), ("semilight", 350), ("light", 300), # Needs to come *after* demi/semilight! ("book", 380), ("regular", 400), ("normal", 400), ("medium", 500), ("demibold", 600), ("demi", 600), ("semibold", 600), ("extrabold", 800), ("superbold", 800), ("ultrabold", 800), ("bold", 700), # Needs to come *after* extra/super/ultrabold! ("ultrablack", 1000), ("superblack", 1000), ("extrablack", 1000), (r"\bultra", 1000), ("black", 900), # Needs to come *after* ultra/super/extrablack! ("heavy", 900), ] FontEntry = dataclasses.make_dataclass( 'FontEntry', [ ('fname', str, dataclasses.field(default='')), ('name', str, dataclasses.field(default='')), ('style', str, dataclasses.field(default='normal')), ('variant', str, dataclasses.field(default='normal')), ('weight', str, dataclasses.field(default='normal')), ('stretch', str, dataclasses.field(default='normal')), ('size', str, dataclasses.field(default='medium')), ], namespace={ '__doc__': """ A class for storing Font properties. It is used when populating the font lookup dictionary. """, '_repr_html_': lambda self: _fontentry_helper_repr_html(self), '_repr_png_': lambda self: _fontentry_helper_repr_png(self), } ) The provided code snippet includes necessary dependencies for implementing the `ttfFontProperty` function. Write a Python function `def ttfFontProperty(font)` to solve the following problem: Extract information from a TrueType font file. Parameters ---------- font : `.FT2Font` The TrueType font file from which information will be extracted. Returns ------- `FontEntry` The extracted font properties. Here is the function: def ttfFontProperty(font): """ Extract information from a TrueType font file. Parameters ---------- font : `.FT2Font` The TrueType font file from which information will be extracted. Returns ------- `FontEntry` The extracted font properties. """ name = font.family_name # Styles are: italic, oblique, and normal (default) sfnt = font.get_sfnt() mac_key = (1, # platform: macintosh 0, # id: roman 0) # langid: english ms_key = (3, # platform: microsoft 1, # id: unicode_cs 0x0409) # langid: english_united_states # These tables are actually mac_roman-encoded, but mac_roman support may be # missing in some alternative Python implementations and we are only going # to look for ASCII substrings, where any ASCII-compatible encoding works # - or big-endian UTF-16, since important Microsoft fonts use that. sfnt2 = (sfnt.get((*mac_key, 2), b'').decode('latin-1').lower() or sfnt.get((*ms_key, 2), b'').decode('utf_16_be').lower()) sfnt4 = (sfnt.get((*mac_key, 4), b'').decode('latin-1').lower() or sfnt.get((*ms_key, 4), b'').decode('utf_16_be').lower()) if sfnt4.find('oblique') >= 0: style = 'oblique' elif sfnt4.find('italic') >= 0: style = 'italic' elif sfnt2.find('regular') >= 0: style = 'normal' elif font.style_flags & ft2font.ITALIC: style = 'italic' else: style = 'normal' # Variants are: small-caps and normal (default) # !!!! Untested if name.lower() in ['capitals', 'small-caps']: variant = 'small-caps' else: variant = 'normal' # The weight-guessing algorithm is directly translated from fontconfig # 2.13.1's FcFreeTypeQueryFaceInternal (fcfreetype.c). wws_subfamily = 22 typographic_subfamily = 16 font_subfamily = 2 styles = [ sfnt.get((*mac_key, wws_subfamily), b'').decode('latin-1'), sfnt.get((*mac_key, typographic_subfamily), b'').decode('latin-1'), sfnt.get((*mac_key, font_subfamily), b'').decode('latin-1'), sfnt.get((*ms_key, wws_subfamily), b'').decode('utf-16-be'), sfnt.get((*ms_key, typographic_subfamily), b'').decode('utf-16-be'), sfnt.get((*ms_key, font_subfamily), b'').decode('utf-16-be'), ] styles = [*filter(None, styles)] or [font.style_name] def get_weight(): # From fontconfig's FcFreeTypeQueryFaceInternal. # OS/2 table weight. os2 = font.get_sfnt_table("OS/2") if os2 and os2["version"] != 0xffff: return os2["usWeightClass"] # PostScript font info weight. try: ps_font_info_weight = ( font.get_ps_font_info()["weight"].replace(" ", "") or "") except ValueError: pass else: for regex, weight in _weight_regexes: if re.fullmatch(regex, ps_font_info_weight, re.I): return weight # Style name weight. for style in styles: style = style.replace(" ", "") for regex, weight in _weight_regexes: if re.search(regex, style, re.I): return weight if font.style_flags & ft2font.BOLD: return 700 # "bold" return 500 # "medium", not "regular"! weight = int(get_weight()) # Stretch can be absolute and relative # Absolute stretches are: ultra-condensed, extra-condensed, condensed, # semi-condensed, normal, semi-expanded, expanded, extra-expanded, # and ultra-expanded. # Relative stretches are: wider, narrower # Child value is: inherit if any(word in sfnt4 for word in ['narrow', 'condensed', 'cond']): stretch = 'condensed' elif 'demi cond' in sfnt4: stretch = 'semi-condensed' elif any(word in sfnt4 for word in ['wide', 'expanded', 'extended']): stretch = 'expanded' else: stretch = 'normal' # Sizes can be absolute and relative. # Absolute sizes are: xx-small, x-small, small, medium, large, x-large, # and xx-large. # Relative sizes are: larger, smaller # Length value is an absolute font size, e.g., 12pt # Percentage values are in 'em's. Most robust specification. if not font.scalable: raise NotImplementedError("Non-scalable fonts are not supported") size = 'scalable' return FontEntry(font.fname, name, style, variant, weight, stretch, size)
Extract information from a TrueType font file. Parameters ---------- font : `.FT2Font` The TrueType font file from which information will be extracted. Returns ------- `FontEntry` The extracted font properties.
171,022
from base64 import b64encode import copy import dataclasses from functools import lru_cache from io import BytesIO import json import logging from numbers import Number import os from pathlib import Path import re import subprocess import sys import threading import matplotlib as mpl from matplotlib import _api, _afm, cbook, ft2font from matplotlib._fontconfig_pattern import ( parse_fontconfig_pattern, generate_fontconfig_pattern) from matplotlib.rcsetup import _validators weight_dict = { 'ultralight': 100, 'light': 200, 'normal': 400, 'regular': 400, 'book': 400, 'medium': 500, 'roman': 500, 'semibold': 600, 'demibold': 600, 'demi': 600, 'bold': 700, 'heavy': 800, 'extra bold': 800, 'black': 900, } FontEntry = dataclasses.make_dataclass( 'FontEntry', [ ('fname', str, dataclasses.field(default='')), ('name', str, dataclasses.field(default='')), ('style', str, dataclasses.field(default='normal')), ('variant', str, dataclasses.field(default='normal')), ('weight', str, dataclasses.field(default='normal')), ('stretch', str, dataclasses.field(default='normal')), ('size', str, dataclasses.field(default='medium')), ], namespace={ '__doc__': """ A class for storing Font properties. It is used when populating the font lookup dictionary. """, '_repr_html_': lambda self: _fontentry_helper_repr_html(self), '_repr_png_': lambda self: _fontentry_helper_repr_png(self), } ) The provided code snippet includes necessary dependencies for implementing the `afmFontProperty` function. Write a Python function `def afmFontProperty(fontpath, font)` to solve the following problem: Extract information from an AFM font file. Parameters ---------- font : AFM The AFM font file from which information will be extracted. Returns ------- `FontEntry` The extracted font properties. Here is the function: def afmFontProperty(fontpath, font): """ Extract information from an AFM font file. Parameters ---------- font : AFM The AFM font file from which information will be extracted. Returns ------- `FontEntry` The extracted font properties. """ name = font.get_familyname() fontname = font.get_fontname().lower() # Styles are: italic, oblique, and normal (default) if font.get_angle() != 0 or 'italic' in name.lower(): style = 'italic' elif 'oblique' in name.lower(): style = 'oblique' else: style = 'normal' # Variants are: small-caps and normal (default) # !!!! Untested if name.lower() in ['capitals', 'small-caps']: variant = 'small-caps' else: variant = 'normal' weight = font.get_weight().lower() if weight not in weight_dict: weight = 'normal' # Stretch can be absolute and relative # Absolute stretches are: ultra-condensed, extra-condensed, condensed, # semi-condensed, normal, semi-expanded, expanded, extra-expanded, # and ultra-expanded. # Relative stretches are: wider, narrower # Child value is: inherit if 'demi cond' in fontname: stretch = 'semi-condensed' elif any(word in fontname for word in ['narrow', 'cond']): stretch = 'condensed' elif any(word in fontname for word in ['wide', 'expanded', 'extended']): stretch = 'expanded' else: stretch = 'normal' # Sizes can be absolute and relative. # Absolute sizes are: xx-small, x-small, small, medium, large, x-large, # and xx-large. # Relative sizes are: larger, smaller # Length value is an absolute font size, e.g., 12pt # Percentage values are in 'em's. Most robust specification. # All AFM fonts are apparently scalable. size = 'scalable' return FontEntry(fontpath, name, style, variant, weight, stretch, size)
Extract information from an AFM font file. Parameters ---------- font : AFM The AFM font file from which information will be extracted. Returns ------- `FontEntry` The extracted font properties.
171,023
from base64 import b64encode import copy import dataclasses from functools import lru_cache from io import BytesIO import json import logging from numbers import Number import os from pathlib import Path import re import subprocess import sys import threading import matplotlib as mpl from matplotlib import _api, _afm, cbook, ft2font from matplotlib._fontconfig_pattern import ( parse_fontconfig_pattern, generate_fontconfig_pattern) from matplotlib.rcsetup import _validators import os ) if os.environ.get('MPLBACKEND'): rcParams['backend'] = os.environ.get('MPLBACKEND') The provided code snippet includes necessary dependencies for implementing the `is_opentype_cff_font` function. Write a Python function `def is_opentype_cff_font(filename)` to solve the following problem: Return whether the given font is a Postscript Compact Font Format Font embedded in an OpenType wrapper. Used by the PostScript and PDF backends that can not subset these fonts. Here is the function: def is_opentype_cff_font(filename): """ Return whether the given font is a Postscript Compact Font Format Font embedded in an OpenType wrapper. Used by the PostScript and PDF backends that can not subset these fonts. """ if os.path.splitext(filename)[1].lower() == '.otf': with open(filename, 'rb') as fd: return fd.read(4) == b"OTTO" else: return False
Return whether the given font is a Postscript Compact Font Format Font embedded in an OpenType wrapper. Used by the PostScript and PDF backends that can not subset these fonts.
171,024
from base64 import b64encode import copy import dataclasses from functools import lru_cache from io import BytesIO import json import logging from numbers import Number import os from pathlib import Path import re import subprocess import sys import threading import matplotlib as mpl from matplotlib import _api, _afm, cbook, ft2font from matplotlib._fontconfig_pattern import ( parse_fontconfig_pattern, generate_fontconfig_pattern) from matplotlib.rcsetup import _validators _log = logging.getLogger(__name__) def json_dump(data, filename): def json_load(filename): class FontManager: def __init__(self, size=None, weight='normal'): def addfont(self, path): def defaultFont(self): def get_default_weight(self): def get_default_size(): def set_default_weight(self, weight): def _expand_aliases(family): def score_family(self, families, family2): def score_style(self, style1, style2): def score_variant(self, variant1, variant2): def score_stretch(self, stretch1, stretch2): def score_weight(self, weight1, weight2): def score_size(self, size1, size2): def findfont(self, prop, fontext='ttf', directory=None, fallback_to_default=True, rebuild_if_missing=True): def get_font_names(self): def _find_fonts_by_props(self, prop, fontext='ttf', directory=None, fallback_to_default=True, rebuild_if_missing=True): def _findfont_cached(self, prop, fontext, directory, fallback_to_default, rebuild_if_missing, rc_params): class Path(PurePath): def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: def __enter__(self: _P) -> _P: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> Optional[bool]: def cwd(cls: Type[_P]) -> _P: def stat(self) -> os.stat_result: def chmod(self, mode: int) -> None: def exists(self) -> bool: def glob(self: _P, pattern: str) -> Generator[_P, None, None]: def group(self) -> str: def is_dir(self) -> bool: def is_file(self) -> bool: def is_mount(self) -> bool: def is_symlink(self) -> bool: def is_socket(self) -> bool: def is_fifo(self) -> bool: def is_block_device(self) -> bool: def is_char_device(self) -> bool: def iterdir(self: _P) -> Generator[_P, None, None]: def lchmod(self, mode: int) -> None: def lstat(self) -> os.stat_result: def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: def open( self, mode: OpenTextMode = ..., buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> TextIOWrapper: def open( self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ... ) -> FileIO: def open( self, mode: OpenBinaryModeUpdating, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedRandom: def open( self, mode: OpenBinaryModeWriting, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedWriter: def open( self, mode: OpenBinaryModeReading, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedReader: def open( self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... ) -> BinaryIO: def open( self, mode: str, buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> IO[Any]: def owner(self) -> str: def readlink(self: _P) -> _P: def rename(self: _P, target: Union[str, PurePath]) -> _P: def replace(self: _P, target: Union[str, PurePath]) -> _P: def rename(self, target: Union[str, PurePath]) -> None: def replace(self, target: Union[str, PurePath]) -> None: def resolve(self: _P, strict: bool = ...) -> _P: def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: def rmdir(self) -> None: def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: def unlink(self, missing_ok: bool = ...) -> None: def unlink(self) -> None: def home(cls: Type[_P]) -> _P: def absolute(self: _P) -> _P: def expanduser(self: _P) -> _P: def read_bytes(self) -> bytes: def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: def write_bytes(self, data: bytes) -> int: def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: def _load_fontmanager(*, try_read_cache=True): fm_path = Path( mpl.get_cachedir(), f"fontlist-v{FontManager.__version__}.json") if try_read_cache: try: fm = json_load(fm_path) except Exception: pass else: if getattr(fm, "_version", object()) == FontManager.__version__: _log.debug("Using fontManager instance from %s", fm_path) return fm fm = FontManager() json_dump(fm, fm_path) _log.info("generated new fontManager") return fm
null
171,025
import datetime import functools import logging from numbers import Number import numpy as np import matplotlib as mpl from matplotlib import _api, cbook import matplotlib.artist as martist import matplotlib.colors as mcolors import matplotlib.lines as mlines import matplotlib.scale as mscale import matplotlib.text as mtext import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.units as munits The provided code snippet includes necessary dependencies for implementing the `_make_getset_interval` function. Write a Python function `def _make_getset_interval(method_name, lim_name, attr_name)` to solve the following problem: Helper to generate ``get_{data,view}_interval`` and ``set_{data,view}_interval`` implementations. Here is the function: def _make_getset_interval(method_name, lim_name, attr_name): """ Helper to generate ``get_{data,view}_interval`` and ``set_{data,view}_interval`` implementations. """ def getter(self): # docstring inherited. return getattr(getattr(self.axes, lim_name), attr_name) def setter(self, vmin, vmax, ignore=False): # docstring inherited. if ignore: setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax)) else: oldmin, oldmax = getter(self) if oldmin < oldmax: setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), ignore=True) else: setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax), ignore=True) self.stale = True getter.__name__ = f"get_{method_name}_interval" setter.__name__ = f"set_{method_name}_interval" return getter, setter
Helper to generate ``get_{data,view}_interval`` and ``set_{data,view}_interval`` implementations.
171,026
from . import _api, _docstring from .artist import Artist, allow_rasterization from .patches import Rectangle from .text import Text from .transforms import Bbox from .path import Path class Table(Artist): """ A table of cells. The table consists of a grid of cells, which are indexed by (row, column). For a simple table, you'll have a full grid of cells with indices from (0, 0) to (num_rows-1, num_cols-1), in which the cell (0, 0) is positioned at the top left. However, you can also add cells with negative indices. You don't have to add a cell to every grid position, so you can create tables that have holes. *Note*: You'll usually not create an empty table from scratch. Instead use `~matplotlib.table.table` to create a table from data. """ codes = {'best': 0, 'upper right': 1, # default 'upper left': 2, 'lower left': 3, 'lower right': 4, 'center left': 5, 'center right': 6, 'lower center': 7, 'upper center': 8, 'center': 9, 'top right': 10, 'top left': 11, 'bottom left': 12, 'bottom right': 13, 'right': 14, 'left': 15, 'top': 16, 'bottom': 17, } """Possible values where to place the table relative to the Axes.""" FONTSIZE = 10 AXESPAD = 0.02 """The border between the Axes and the table edge in Axes units.""" def __init__(self, ax, loc=None, bbox=None, **kwargs): """ Parameters ---------- ax : `matplotlib.axes.Axes` The `~.axes.Axes` to plot the table into. loc : str The position of the cell with respect to *ax*. This must be one of the `~.Table.codes`. bbox : `.Bbox` or [xmin, ymin, width, height], optional A bounding box to draw the table into. If this is not *None*, this overrides *loc*. Other Parameters ---------------- **kwargs `.Artist` properties. """ super().__init__() if isinstance(loc, str): if loc not in self.codes: raise ValueError( "Unrecognized location {!r}. Valid locations are\n\t{}" .format(loc, '\n\t'.join(self.codes))) loc = self.codes[loc] self.set_figure(ax.figure) self._axes = ax self._loc = loc self._bbox = bbox # use axes coords ax._unstale_viewLim() self.set_transform(ax.transAxes) self._cells = {} self._edges = None self._autoColumns = [] self._autoFontsize = True self._internal_update(kwargs) self.set_clip_on(False) def add_cell(self, row, col, *args, **kwargs): """ Create a cell and add it to the table. Parameters ---------- row : int Row index. col : int Column index. *args, **kwargs All other parameters are passed on to `Cell`. Returns ------- `.Cell` The created cell. """ xy = (0, 0) cell = Cell(xy, visible_edges=self.edges, *args, **kwargs) self[row, col] = cell return cell def __setitem__(self, position, cell): """ Set a custom cell in a given position. """ _api.check_isinstance(Cell, cell=cell) try: row, col = position[0], position[1] except Exception as err: raise KeyError('Only tuples length 2 are accepted as ' 'coordinates') from err cell.set_figure(self.figure) cell.set_transform(self.get_transform()) cell.set_clip_on(False) self._cells[row, col] = cell self.stale = True def __getitem__(self, position): """Retrieve a custom cell from a given position.""" return self._cells[position] def edges(self): """ The default value of `~.Cell.visible_edges` for newly added cells using `.add_cell`. Notes ----- This setting does currently only affect newly created cells using `.add_cell`. To change existing cells, you have to set their edges explicitly:: for c in tab.get_celld().values(): c.visible_edges = 'horizontal' """ return self._edges def edges(self, value): self._edges = value self.stale = True def _approx_text_height(self): return (self.FONTSIZE / 72.0 * self.figure.dpi / self._axes.bbox.height * 1.2) def draw(self, renderer): # docstring inherited # Need a renderer to do hit tests on mouseevent; assume the last one # will do if renderer is None: renderer = self.figure._get_renderer() if renderer is None: raise RuntimeError('No renderer defined') if not self.get_visible(): return renderer.open_group('table', gid=self.get_gid()) self._update_positions(renderer) for key in sorted(self._cells): self._cells[key].draw(renderer) renderer.close_group('table') self.stale = False def _get_grid_bbox(self, renderer): """ Get a bbox, in axes coordinates for the cells. Only include those in the range (0, 0) to (maxRow, maxCol). """ boxes = [cell.get_window_extent(renderer) for (row, col), cell in self._cells.items() if row >= 0 and col >= 0] bbox = Bbox.union(boxes) return bbox.transformed(self.get_transform().inverted()) def contains(self, mouseevent): # docstring inherited inside, info = self._default_contains(mouseevent) if inside is not None: return inside, info # TODO: Return index of the cell containing the cursor so that the user # doesn't have to bind to each one individually. renderer = self.figure._get_renderer() if renderer is not None: boxes = [cell.get_window_extent(renderer) for (row, col), cell in self._cells.items() if row >= 0 and col >= 0] bbox = Bbox.union(boxes) return bbox.contains(mouseevent.x, mouseevent.y), {} else: return False, {} def get_children(self): """Return the Artists contained by the table.""" return list(self._cells.values()) def get_window_extent(self, renderer=None): # docstring inherited if renderer is None: renderer = self.figure._get_renderer() self._update_positions(renderer) boxes = [cell.get_window_extent(renderer) for cell in self._cells.values()] return Bbox.union(boxes) def _do_cell_alignment(self): """ Calculate row heights and column widths; position cells accordingly. """ # Calculate row/column widths widths = {} heights = {} for (row, col), cell in self._cells.items(): height = heights.setdefault(row, 0.0) heights[row] = max(height, cell.get_height()) width = widths.setdefault(col, 0.0) widths[col] = max(width, cell.get_width()) # work out left position for each column xpos = 0 lefts = {} for col in sorted(widths): lefts[col] = xpos xpos += widths[col] ypos = 0 bottoms = {} for row in sorted(heights, reverse=True): bottoms[row] = ypos ypos += heights[row] # set cell positions for (row, col), cell in self._cells.items(): cell.set_x(lefts[col]) cell.set_y(bottoms[row]) def auto_set_column_width(self, col): """ Automatically set the widths of given columns to optimal sizes. Parameters ---------- col : int or sequence of ints The indices of the columns to auto-scale. """ # check for col possibility on iteration try: iter(col) except (TypeError, AttributeError): self._autoColumns.append(col) else: for cell in col: self._autoColumns.append(cell) self.stale = True def _auto_set_column_width(self, col, renderer): """Automatically set width for column.""" cells = [cell for key, cell in self._cells.items() if key[1] == col] max_width = max((cell.get_required_width(renderer) for cell in cells), default=0) for cell in cells: cell.set_width(max_width) def auto_set_font_size(self, value=True): """Automatically set font size.""" self._autoFontsize = value self.stale = True def _auto_set_font_size(self, renderer): if len(self._cells) == 0: return fontsize = next(iter(self._cells.values())).get_fontsize() cells = [] for key, cell in self._cells.items(): # ignore auto-sized columns if key[1] in self._autoColumns: continue size = cell.auto_set_font_size(renderer) fontsize = min(fontsize, size) cells.append(cell) # now set all fontsizes equal for cell in self._cells.values(): cell.set_fontsize(fontsize) def scale(self, xscale, yscale): """Scale column widths by *xscale* and row heights by *yscale*.""" for c in self._cells.values(): c.set_width(c.get_width() * xscale) c.set_height(c.get_height() * yscale) def set_fontsize(self, size): """ Set the font size, in points, of the cell text. Parameters ---------- size : float Notes ----- As long as auto font size has not been disabled, the value will be clipped such that the text fits horizontally into the cell. You can disable this behavior using `.auto_set_font_size`. >>> the_table.auto_set_font_size(False) >>> the_table.set_fontsize(20) However, there is no automatic scaling of the row height so that the text may exceed the cell boundary. """ for cell in self._cells.values(): cell.set_fontsize(size) self.stale = True def _offset(self, ox, oy): """Move all the artists by ox, oy (axes coords).""" for c in self._cells.values(): x, y = c.get_x(), c.get_y() c.set_x(x + ox) c.set_y(y + oy) def _update_positions(self, renderer): # called from renderer to allow more precise estimates of # widths and heights with get_window_extent # Do any auto width setting for col in self._autoColumns: self._auto_set_column_width(col, renderer) if self._autoFontsize: self._auto_set_font_size(renderer) # Align all the cells self._do_cell_alignment() bbox = self._get_grid_bbox(renderer) l, b, w, h = bbox.bounds if self._bbox is not None: # Position according to bbox if isinstance(self._bbox, Bbox): rl, rb, rw, rh = self._bbox.bounds else: rl, rb, rw, rh = self._bbox self.scale(rw / w, rh / h) ox = rl - l oy = rb - b self._do_cell_alignment() else: # Position using loc (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C, TR, TL, BL, BR, R, L, T, B) = range(len(self.codes)) # defaults for center ox = (0.5 - w / 2) - l oy = (0.5 - h / 2) - b if self._loc in (UL, LL, CL): # left ox = self.AXESPAD - l if self._loc in (BEST, UR, LR, R, CR): # right ox = 1 - (l + w + self.AXESPAD) if self._loc in (BEST, UR, UL, UC): # upper oy = 1 - (b + h + self.AXESPAD) if self._loc in (LL, LR, LC): # lower oy = self.AXESPAD - b if self._loc in (LC, UC, C): # center x ox = (0.5 - w / 2) - l if self._loc in (CL, CR, C): # center y oy = (0.5 - h / 2) - b if self._loc in (TL, BL, L): # out left ox = - (l + w) if self._loc in (TR, BR, R): # out right ox = 1.0 - l if self._loc in (TR, TL, T): # out top oy = 1.0 - b if self._loc in (BL, BR, B): # out bottom oy = - (b + h) self._offset(ox, oy) def get_celld(self): r""" Return a dict of cells in the table mapping *(row, column)* to `.Cell`\s. Notes ----- You can also directly index into the Table object to access individual cells:: cell = table[row, col] """ return self._cells The provided code snippet includes necessary dependencies for implementing the `table` function. Write a Python function `def table(ax, 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)` to solve the following problem: Add a table to an `~.axes.Axes`. At least one of *cellText* or *cellColours* must be specified. These parameters must be 2D lists, in which the outer lists define the rows and the inner list define the column values per row. Each row must have the same number of elements. The table can optionally have row and column headers, which are configured using *rowLabels*, *rowColours*, *rowLoc* and *colLabels*, *colColours*, *colLoc* respectively. For finer grained control over tables, use the `.Table` class and add it to the axes with `.Axes.add_table`. Parameters ---------- cellText : 2D list of str, optional The texts to place into the table cells. *Note*: Line breaks in the strings are currently not accounted for and will result in the text exceeding the cell boundaries. cellColours : 2D list of colors, optional The background colors of the cells. cellLoc : {'left', 'center', 'right'}, default: 'right' The alignment of the text within the cells. colWidths : list of float, optional The column widths in units of the axes. If not given, all columns will have a width of *1 / ncols*. rowLabels : list of str, optional The text of the row header cells. rowColours : list of colors, optional The colors of the row header cells. rowLoc : {'left', 'center', 'right'}, default: 'left' The text alignment of the row header cells. colLabels : list of str, optional The text of the column header cells. colColours : list of colors, optional The colors of the column header cells. colLoc : {'left', 'center', 'right'}, default: 'left' The text alignment of the column header cells. loc : str, optional The position of the cell with respect to *ax*. This must be one of the `~.Table.codes`. bbox : `.Bbox` or [xmin, ymin, width, height], optional A bounding box to draw the table into. If this is not *None*, this overrides *loc*. edges : substring of 'BRTL' or {'open', 'closed', 'horizontal', 'vertical'} The cell edges to be drawn with a line. See also `~.Cell.visible_edges`. Returns ------- `~matplotlib.table.Table` The created table. Other Parameters ---------------- **kwargs `.Table` properties. %(Table:kwdoc)s Here is the function: def table(ax, 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): """ Add a table to an `~.axes.Axes`. At least one of *cellText* or *cellColours* must be specified. These parameters must be 2D lists, in which the outer lists define the rows and the inner list define the column values per row. Each row must have the same number of elements. The table can optionally have row and column headers, which are configured using *rowLabels*, *rowColours*, *rowLoc* and *colLabels*, *colColours*, *colLoc* respectively. For finer grained control over tables, use the `.Table` class and add it to the axes with `.Axes.add_table`. Parameters ---------- cellText : 2D list of str, optional The texts to place into the table cells. *Note*: Line breaks in the strings are currently not accounted for and will result in the text exceeding the cell boundaries. cellColours : 2D list of colors, optional The background colors of the cells. cellLoc : {'left', 'center', 'right'}, default: 'right' The alignment of the text within the cells. colWidths : list of float, optional The column widths in units of the axes. If not given, all columns will have a width of *1 / ncols*. rowLabels : list of str, optional The text of the row header cells. rowColours : list of colors, optional The colors of the row header cells. rowLoc : {'left', 'center', 'right'}, default: 'left' The text alignment of the row header cells. colLabels : list of str, optional The text of the column header cells. colColours : list of colors, optional The colors of the column header cells. colLoc : {'left', 'center', 'right'}, default: 'left' The text alignment of the column header cells. loc : str, optional The position of the cell with respect to *ax*. This must be one of the `~.Table.codes`. bbox : `.Bbox` or [xmin, ymin, width, height], optional A bounding box to draw the table into. If this is not *None*, this overrides *loc*. edges : substring of 'BRTL' or {'open', 'closed', 'horizontal', 'vertical'} The cell edges to be drawn with a line. See also `~.Cell.visible_edges`. Returns ------- `~matplotlib.table.Table` The created table. Other Parameters ---------------- **kwargs `.Table` properties. %(Table:kwdoc)s """ if cellColours is None and cellText is None: raise ValueError('At least one argument from "cellColours" or ' '"cellText" must be provided to create a table.') # Check we have some cellText if cellText is None: # assume just colours are needed rows = len(cellColours) cols = len(cellColours[0]) cellText = [[''] * cols] * rows rows = len(cellText) cols = len(cellText[0]) for row in cellText: if len(row) != cols: raise ValueError("Each row in 'cellText' must have {} columns" .format(cols)) if cellColours is not None: if len(cellColours) != rows: raise ValueError("'cellColours' must have {} rows".format(rows)) for row in cellColours: if len(row) != cols: raise ValueError("Each row in 'cellColours' must have {} " "columns".format(cols)) else: cellColours = ['w' * cols] * rows # Set colwidths if not given if colWidths is None: colWidths = [1.0 / cols] * cols # Fill in missing information for column # and row labels rowLabelWidth = 0 if rowLabels is None: if rowColours is not None: rowLabels = [''] * rows rowLabelWidth = colWidths[0] elif rowColours is None: rowColours = 'w' * rows if rowLabels is not None: if len(rowLabels) != rows: raise ValueError("'rowLabels' must be of length {0}".format(rows)) # If we have column labels, need to shift # the text and colour arrays down 1 row offset = 1 if colLabels is None: if colColours is not None: colLabels = [''] * cols else: offset = 0 elif colColours is None: colColours = 'w' * cols # Set up cell colours if not given if cellColours is None: cellColours = ['w' * cols] * rows # Now create the table table = Table(ax, loc, bbox, **kwargs) table.edges = edges height = table._approx_text_height() # Add the cells for row in range(rows): for col in range(cols): table.add_cell(row + offset, col, width=colWidths[col], height=height, text=cellText[row][col], facecolor=cellColours[row][col], loc=cellLoc) # Do column labels if colLabels is not None: for col in range(cols): table.add_cell(0, col, width=colWidths[col], height=height, text=colLabels[col], facecolor=colColours[col], loc=colLoc) # Do row labels if rowLabels is not None: for row in range(rows): table.add_cell(row + offset, -1, width=rowLabelWidth or 1e-15, height=height, text=rowLabels[row], facecolor=rowColours[row], loc=rowLoc) if rowLabelWidth == 0: table.auto_set_column_width(-1) ax.add_table(table) return table
Add a table to an `~.axes.Axes`. At least one of *cellText* or *cellColours* must be specified. These parameters must be 2D lists, in which the outer lists define the rows and the inner list define the column values per row. Each row must have the same number of elements. The table can optionally have row and column headers, which are configured using *rowLabels*, *rowColours*, *rowLoc* and *colLabels*, *colColours*, *colLoc* respectively. For finer grained control over tables, use the `.Table` class and add it to the axes with `.Axes.add_table`. Parameters ---------- cellText : 2D list of str, optional The texts to place into the table cells. *Note*: Line breaks in the strings are currently not accounted for and will result in the text exceeding the cell boundaries. cellColours : 2D list of colors, optional The background colors of the cells. cellLoc : {'left', 'center', 'right'}, default: 'right' The alignment of the text within the cells. colWidths : list of float, optional The column widths in units of the axes. If not given, all columns will have a width of *1 / ncols*. rowLabels : list of str, optional The text of the row header cells. rowColours : list of colors, optional The colors of the row header cells. rowLoc : {'left', 'center', 'right'}, default: 'left' The text alignment of the row header cells. colLabels : list of str, optional The text of the column header cells. colColours : list of colors, optional The colors of the column header cells. colLoc : {'left', 'center', 'right'}, default: 'left' The text alignment of the column header cells. loc : str, optional The position of the cell with respect to *ax*. This must be one of the `~.Table.codes`. bbox : `.Bbox` or [xmin, ymin, width, height], optional A bounding box to draw the table into. If this is not *None*, this overrides *loc*. edges : substring of 'BRTL' or {'open', 'closed', 'horizontal', 'vertical'} The cell edges to be drawn with a line. See also `~.Cell.visible_edges`. Returns ------- `~matplotlib.table.Table` The created table. Other Parameters ---------------- **kwargs `.Table` properties. %(Table:kwdoc)s
171,027
import functools import inspect import math from numbers import Number import textwrap from types import SimpleNamespace from collections import namedtuple from matplotlib.transforms import Affine2D import numpy as np import matplotlib as mpl from . import (_api, artist, cbook, colors, _docstring, hatch as mhatch, lines as mlines, transforms) from .bezier import ( NonIntersectingPathException, get_cos_sin, get_intersection, get_parallels, inside_circle, make_wedged_bezier2, split_bezier_intersecting_with_closedpath, split_path_inout) from .path import Path from ._enums import JoinStyle, CapStyle class Rectangle(Patch): """ A rectangle defined via an anchor point *xy* and its *width* and *height*. The rectangle extends from ``xy[0]`` to ``xy[0] + width`` in x-direction and from ``xy[1]`` to ``xy[1] + height`` in y-direction. :: : +------------------+ : | | : height | : | | : (xy)---- width -----+ One may picture *xy* as the bottom left corner, but which corner *xy* is actually depends on the direction of the axis and the sign of *width* and *height*; e.g. *xy* would be the bottom right corner if the x-axis was inverted or if *width* was negative. """ def __str__(self): pars = self._x0, self._y0, self._width, self._height, self.angle fmt = "Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)" return fmt % pars def __init__(self, xy, width, height, angle=0.0, *, rotation_point='xy', **kwargs): """ Parameters ---------- xy : (float, float) The anchor point. width : float Rectangle width. height : float Rectangle height. angle : float, default: 0 Rotation in degrees anti-clockwise about the rotation point. rotation_point : {'xy', 'center', (number, number)}, default: 'xy' If ``'xy'``, rotate around the anchor point. If ``'center'`` rotate around the center. If 2-tuple of number, rotate around this coordinate. Other Parameters ---------------- **kwargs : `.Patch` properties %(Patch:kwdoc)s """ super().__init__(**kwargs) self._x0 = xy[0] self._y0 = xy[1] self._width = width self._height = height self.angle = float(angle) self.rotation_point = rotation_point # Required for RectangleSelector with axes aspect ratio != 1 # The patch is defined in data coordinates and when changing the # selector with square modifier and not in data coordinates, we need # to correct for the aspect ratio difference between the data and # display coordinate systems. Its value is typically provide by # Axes._get_aspect_ratio() self._aspect_ratio_correction = 1.0 self._convert_units() # Validate the inputs. def get_path(self): """Return the vertices of the rectangle.""" return Path.unit_rectangle() def _convert_units(self): """Convert bounds of the rectangle.""" x0 = self.convert_xunits(self._x0) y0 = self.convert_yunits(self._y0) x1 = self.convert_xunits(self._x0 + self._width) y1 = self.convert_yunits(self._y0 + self._height) return x0, y0, x1, y1 def get_patch_transform(self): # Note: This cannot be called until after this has been added to # an Axes, otherwise unit conversion will fail. This makes it very # important to call the accessor method and not directly access the # transformation member variable. bbox = self.get_bbox() if self.rotation_point == 'center': width, height = bbox.x1 - bbox.x0, bbox.y1 - bbox.y0 rotation_point = bbox.x0 + width / 2., bbox.y0 + height / 2. elif self.rotation_point == 'xy': rotation_point = bbox.x0, bbox.y0 else: rotation_point = self.rotation_point return transforms.BboxTransformTo(bbox) \ + transforms.Affine2D() \ .translate(-rotation_point[0], -rotation_point[1]) \ .scale(1, self._aspect_ratio_correction) \ .rotate_deg(self.angle) \ .scale(1, 1 / self._aspect_ratio_correction) \ .translate(*rotation_point) def rotation_point(self): """The rotation point of the patch.""" return self._rotation_point def rotation_point(self, value): if value in ['center', 'xy'] or ( isinstance(value, tuple) and len(value) == 2 and isinstance(value[0], Number) and isinstance(value[1], Number) ): self._rotation_point = value else: raise ValueError("`rotation_point` must be one of " "{'xy', 'center', (number, number)}.") def get_x(self): """Return the left coordinate of the rectangle.""" return self._x0 def get_y(self): """Return the bottom coordinate of the rectangle.""" return self._y0 def get_xy(self): """Return the left and bottom coords of the rectangle as a tuple.""" return self._x0, self._y0 def get_corners(self): """ Return the corners of the rectangle, moving anti-clockwise from (x0, y0). """ return self.get_patch_transform().transform( [(0, 0), (1, 0), (1, 1), (0, 1)]) def get_center(self): """Return the centre of the rectangle.""" return self.get_patch_transform().transform((0.5, 0.5)) def get_width(self): """Return the width of the rectangle.""" return self._width def get_height(self): """Return the height of the rectangle.""" return self._height def get_angle(self): """Get the rotation angle in degrees.""" return self.angle def set_x(self, x): """Set the left coordinate of the rectangle.""" self._x0 = x self.stale = True def set_y(self, y): """Set the bottom coordinate of the rectangle.""" self._y0 = y self.stale = True def set_angle(self, angle): """ Set the rotation angle in degrees. The rotation is performed anti-clockwise around *xy*. """ self.angle = angle self.stale = True def set_xy(self, xy): """ Set the left and bottom coordinates of the rectangle. Parameters ---------- xy : (float, float) """ self._x0, self._y0 = xy self.stale = True def set_width(self, w): """Set the width of the rectangle.""" self._width = w self.stale = True def set_height(self, h): """Set the height of the rectangle.""" self._height = h self.stale = True def set_bounds(self, *args): """ Set the bounds of the rectangle as *left*, *bottom*, *width*, *height*. The values may be passed as separate parameters or as a tuple:: set_bounds(left, bottom, width, height) set_bounds((left, bottom, width, height)) .. ACCEPTS: (left, bottom, width, height) """ if len(args) == 1: l, b, w, h = args[0] else: l, b, w, h = args self._x0 = l self._y0 = b self._width = w self._height = h self.stale = True def get_bbox(self): """Return the `.Bbox`.""" x0, y0, x1, y1 = self._convert_units() return transforms.Bbox.from_extents(x0, y0, x1, y1) xy = property(get_xy, set_xy) The provided code snippet includes necessary dependencies for implementing the `bbox_artist` function. Write a Python function `def bbox_artist(artist, renderer, props=None, fill=True)` to solve the following problem: A debug function to draw a rectangle around the bounding box returned by an artist's `.Artist.get_window_extent` to test whether the artist is returning the correct bbox. *props* is a dict of rectangle props with the additional property 'pad' that sets the padding around the bbox in points. Here is the function: def bbox_artist(artist, renderer, props=None, fill=True): """ A debug function to draw a rectangle around the bounding box returned by an artist's `.Artist.get_window_extent` to test whether the artist is returning the correct bbox. *props* is a dict of rectangle props with the additional property 'pad' that sets the padding around the bbox in points. """ if props is None: props = {} props = props.copy() # don't want to alter the pad externally pad = props.pop('pad', 4) pad = renderer.points_to_pixels(pad) bbox = artist.get_window_extent(renderer) r = Rectangle( xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2), width=bbox.width + pad, height=bbox.height + pad, fill=fill, transform=transforms.IdentityTransform(), clip_on=False) r.update(props) r.draw(renderer)
A debug function to draw a rectangle around the bounding box returned by an artist's `.Artist.get_window_extent` to test whether the artist is returning the correct bbox. *props* is a dict of rectangle props with the additional property 'pad' that sets the padding around the bbox in points.
171,028
import functools import inspect import math from numbers import Number import textwrap from types import SimpleNamespace from collections import namedtuple from matplotlib.transforms import Affine2D import numpy as np import matplotlib as mpl from . import (_api, artist, cbook, colors, _docstring, hatch as mhatch, lines as mlines, transforms) from .bezier import ( NonIntersectingPathException, get_cos_sin, get_intersection, get_parallels, inside_circle, make_wedged_bezier2, split_bezier_intersecting_with_closedpath, split_path_inout) from .path import Path from ._enums import JoinStyle, CapStyle class Rectangle(Patch): """ A rectangle defined via an anchor point *xy* and its *width* and *height*. The rectangle extends from ``xy[0]`` to ``xy[0] + width`` in x-direction and from ``xy[1]`` to ``xy[1] + height`` in y-direction. :: : +------------------+ : | | : height | : | | : (xy)---- width -----+ One may picture *xy* as the bottom left corner, but which corner *xy* is actually depends on the direction of the axis and the sign of *width* and *height*; e.g. *xy* would be the bottom right corner if the x-axis was inverted or if *width* was negative. """ def __str__(self): pars = self._x0, self._y0, self._width, self._height, self.angle fmt = "Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)" return fmt % pars def __init__(self, xy, width, height, angle=0.0, *, rotation_point='xy', **kwargs): """ Parameters ---------- xy : (float, float) The anchor point. width : float Rectangle width. height : float Rectangle height. angle : float, default: 0 Rotation in degrees anti-clockwise about the rotation point. rotation_point : {'xy', 'center', (number, number)}, default: 'xy' If ``'xy'``, rotate around the anchor point. If ``'center'`` rotate around the center. If 2-tuple of number, rotate around this coordinate. Other Parameters ---------------- **kwargs : `.Patch` properties %(Patch:kwdoc)s """ super().__init__(**kwargs) self._x0 = xy[0] self._y0 = xy[1] self._width = width self._height = height self.angle = float(angle) self.rotation_point = rotation_point # Required for RectangleSelector with axes aspect ratio != 1 # The patch is defined in data coordinates and when changing the # selector with square modifier and not in data coordinates, we need # to correct for the aspect ratio difference between the data and # display coordinate systems. Its value is typically provide by # Axes._get_aspect_ratio() self._aspect_ratio_correction = 1.0 self._convert_units() # Validate the inputs. def get_path(self): """Return the vertices of the rectangle.""" return Path.unit_rectangle() def _convert_units(self): """Convert bounds of the rectangle.""" x0 = self.convert_xunits(self._x0) y0 = self.convert_yunits(self._y0) x1 = self.convert_xunits(self._x0 + self._width) y1 = self.convert_yunits(self._y0 + self._height) return x0, y0, x1, y1 def get_patch_transform(self): # Note: This cannot be called until after this has been added to # an Axes, otherwise unit conversion will fail. This makes it very # important to call the accessor method and not directly access the # transformation member variable. bbox = self.get_bbox() if self.rotation_point == 'center': width, height = bbox.x1 - bbox.x0, bbox.y1 - bbox.y0 rotation_point = bbox.x0 + width / 2., bbox.y0 + height / 2. elif self.rotation_point == 'xy': rotation_point = bbox.x0, bbox.y0 else: rotation_point = self.rotation_point return transforms.BboxTransformTo(bbox) \ + transforms.Affine2D() \ .translate(-rotation_point[0], -rotation_point[1]) \ .scale(1, self._aspect_ratio_correction) \ .rotate_deg(self.angle) \ .scale(1, 1 / self._aspect_ratio_correction) \ .translate(*rotation_point) def rotation_point(self): """The rotation point of the patch.""" return self._rotation_point def rotation_point(self, value): if value in ['center', 'xy'] or ( isinstance(value, tuple) and len(value) == 2 and isinstance(value[0], Number) and isinstance(value[1], Number) ): self._rotation_point = value else: raise ValueError("`rotation_point` must be one of " "{'xy', 'center', (number, number)}.") def get_x(self): """Return the left coordinate of the rectangle.""" return self._x0 def get_y(self): """Return the bottom coordinate of the rectangle.""" return self._y0 def get_xy(self): """Return the left and bottom coords of the rectangle as a tuple.""" return self._x0, self._y0 def get_corners(self): """ Return the corners of the rectangle, moving anti-clockwise from (x0, y0). """ return self.get_patch_transform().transform( [(0, 0), (1, 0), (1, 1), (0, 1)]) def get_center(self): """Return the centre of the rectangle.""" return self.get_patch_transform().transform((0.5, 0.5)) def get_width(self): """Return the width of the rectangle.""" return self._width def get_height(self): """Return the height of the rectangle.""" return self._height def get_angle(self): """Get the rotation angle in degrees.""" return self.angle def set_x(self, x): """Set the left coordinate of the rectangle.""" self._x0 = x self.stale = True def set_y(self, y): """Set the bottom coordinate of the rectangle.""" self._y0 = y self.stale = True def set_angle(self, angle): """ Set the rotation angle in degrees. The rotation is performed anti-clockwise around *xy*. """ self.angle = angle self.stale = True def set_xy(self, xy): """ Set the left and bottom coordinates of the rectangle. Parameters ---------- xy : (float, float) """ self._x0, self._y0 = xy self.stale = True def set_width(self, w): """Set the width of the rectangle.""" self._width = w self.stale = True def set_height(self, h): """Set the height of the rectangle.""" self._height = h self.stale = True def set_bounds(self, *args): """ Set the bounds of the rectangle as *left*, *bottom*, *width*, *height*. The values may be passed as separate parameters or as a tuple:: set_bounds(left, bottom, width, height) set_bounds((left, bottom, width, height)) .. ACCEPTS: (left, bottom, width, height) """ if len(args) == 1: l, b, w, h = args[0] else: l, b, w, h = args self._x0 = l self._y0 = b self._width = w self._height = h self.stale = True def get_bbox(self): """Return the `.Bbox`.""" x0, y0, x1, y1 = self._convert_units() return transforms.Bbox.from_extents(x0, y0, x1, y1) xy = property(get_xy, set_xy) The provided code snippet includes necessary dependencies for implementing the `draw_bbox` function. Write a Python function `def draw_bbox(bbox, renderer, color='k', trans=None)` to solve the following problem: A debug function to draw a rectangle around the bounding box returned by an artist's `.Artist.get_window_extent` to test whether the artist is returning the correct bbox. Here is the function: def draw_bbox(bbox, renderer, color='k', trans=None): """ A debug function to draw a rectangle around the bounding box returned by an artist's `.Artist.get_window_extent` to test whether the artist is returning the correct bbox. """ r = Rectangle(xy=bbox.p0, width=bbox.width, height=bbox.height, edgecolor=color, fill=False, clip_on=False) if trans is not None: r.set_transform(trans) r.draw(renderer)
A debug function to draw a rectangle around the bounding box returned by an artist's `.Artist.get_window_extent` to test whether the artist is returning the correct bbox.
171,029
import functools import inspect import math from numbers import Number import textwrap from types import SimpleNamespace from collections import namedtuple from matplotlib.transforms import Affine2D import numpy as np import matplotlib as mpl from . import (_api, artist, cbook, colors, _docstring, hatch as mhatch, lines as mlines, transforms) from .bezier import ( NonIntersectingPathException, get_cos_sin, get_intersection, get_parallels, inside_circle, make_wedged_bezier2, split_bezier_intersecting_with_closedpath, split_path_inout) from .path import Path from ._enums import JoinStyle, CapStyle The provided code snippet includes necessary dependencies for implementing the `_register_style` function. Write a Python function `def _register_style(style_list, cls=None, *, name=None)` to solve the following problem: Class decorator that stashes a class in a (style) dictionary. Here is the function: def _register_style(style_list, cls=None, *, name=None): """Class decorator that stashes a class in a (style) dictionary.""" if cls is None: return functools.partial(_register_style, style_list, name=name) style_list[name or cls.__name__.lower()] = cls return cls
Class decorator that stashes a class in a (style) dictionary.
171,030
import functools import inspect import math from numbers import Number import textwrap from types import SimpleNamespace from collections import namedtuple from matplotlib.transforms import Affine2D import numpy as np import matplotlib as mpl from . import (_api, artist, cbook, colors, _docstring, hatch as mhatch, lines as mlines, transforms) from .bezier import ( NonIntersectingPathException, get_cos_sin, get_intersection, get_parallels, inside_circle, make_wedged_bezier2, split_bezier_intersecting_with_closedpath, split_path_inout) from .path import Path from ._enums import JoinStyle, CapStyle The provided code snippet includes necessary dependencies for implementing the `_point_along_a_line` function. Write a Python function `def _point_along_a_line(x0, y0, x1, y1, d)` to solve the following problem: Return the point on the line connecting (*x0*, *y0*) -- (*x1*, *y1*) whose distance from (*x0*, *y0*) is *d*. Here is the function: def _point_along_a_line(x0, y0, x1, y1, d): """ Return the point on the line connecting (*x0*, *y0*) -- (*x1*, *y1*) whose distance from (*x0*, *y0*) is *d*. """ dx, dy = x0 - x1, y0 - y1 ff = d / (dx * dx + dy * dy) ** .5 x2, y2 = x0 - ff * dx, y0 - ff * dy return x2, y2
Return the point on the line connecting (*x0*, *y0*) -- (*x1*, *y1*) whose distance from (*x0*, *y0*) is *d*.
171,031
import copy from functools import lru_cache from weakref import WeakValueDictionary import numpy as np import matplotlib as mpl from . import _api, _path from .cbook import _to_unmasked_float_array, simple_linear_interpolation from .bezier import BezierSegment class Bbox(BboxBase): """ A mutable bounding box. Examples -------- **Create from known bounds** The default constructor takes the boundary "points" ``[[xmin, ymin], [xmax, ymax]]``. >>> Bbox([[1, 1], [3, 7]]) Bbox([[1.0, 1.0], [3.0, 7.0]]) Alternatively, a Bbox can be created from the flattened points array, the so-called "extents" ``(xmin, ymin, xmax, ymax)`` >>> Bbox.from_extents(1, 1, 3, 7) Bbox([[1.0, 1.0], [3.0, 7.0]]) or from the "bounds" ``(xmin, ymin, width, height)``. >>> Bbox.from_bounds(1, 1, 2, 6) Bbox([[1.0, 1.0], [3.0, 7.0]]) **Create from collections of points** The "empty" object for accumulating Bboxs is the null bbox, which is a stand-in for the empty set. >>> Bbox.null() Bbox([[inf, inf], [-inf, -inf]]) Adding points to the null bbox will give you the bbox of those points. >>> box = Bbox.null() >>> box.update_from_data_xy([[1, 1]]) >>> box Bbox([[1.0, 1.0], [1.0, 1.0]]) >>> box.update_from_data_xy([[2, 3], [3, 2]], ignore=False) >>> box Bbox([[1.0, 1.0], [3.0, 3.0]]) Setting ``ignore=True`` is equivalent to starting over from a null bbox. >>> box.update_from_data_xy([[1, 1]], ignore=True) >>> box Bbox([[1.0, 1.0], [1.0, 1.0]]) .. warning:: It is recommended to always specify ``ignore`` explicitly. If not, the default value of ``ignore`` can be changed at any time by code with access to your Bbox, for example using the method `~.Bbox.ignore`. **Properties of the ``null`` bbox** .. note:: The current behavior of `Bbox.null()` may be surprising as it does not have all of the properties of the "empty set", and as such does not behave like a "zero" object in the mathematical sense. We may change that in the future (with a deprecation period). The null bbox is the identity for intersections >>> Bbox.intersection(Bbox([[1, 1], [3, 7]]), Bbox.null()) Bbox([[1.0, 1.0], [3.0, 7.0]]) except with itself, where it returns the full space. >>> Bbox.intersection(Bbox.null(), Bbox.null()) Bbox([[-inf, -inf], [inf, inf]]) A union containing null will always return the full space (not the other set!) >>> Bbox.union([Bbox([[0, 0], [0, 0]]), Bbox.null()]) Bbox([[-inf, -inf], [inf, inf]]) """ def __init__(self, points, **kwargs): """ Parameters ---------- points : `~numpy.ndarray` A 2x2 numpy array of the form ``[[x0, y0], [x1, y1]]``. """ super().__init__(**kwargs) points = np.asarray(points, float) if points.shape != (2, 2): raise ValueError('Bbox points must be of the form ' '"[[x0, y0], [x1, y1]]".') self._points = points self._minpos = np.array([np.inf, np.inf]) self._ignore = True # it is helpful in some contexts to know if the bbox is a # default or has been mutated; we store the orig points to # support the mutated methods self._points_orig = self._points.copy() if DEBUG: ___init__ = __init__ def __init__(self, points, **kwargs): self._check(points) self.___init__(points, **kwargs) def invalidate(self): self._check(self._points) super().invalidate() def frozen(self): # docstring inherited frozen_bbox = super().frozen() frozen_bbox._minpos = self.minpos.copy() return frozen_bbox def unit(): """Create a new unit `Bbox` from (0, 0) to (1, 1).""" return Bbox([[0, 0], [1, 1]]) def null(): """Create a new null `Bbox` from (inf, inf) to (-inf, -inf).""" return Bbox([[np.inf, np.inf], [-np.inf, -np.inf]]) def from_bounds(x0, y0, width, height): """ Create a new `Bbox` from *x0*, *y0*, *width* and *height*. *width* and *height* may be negative. """ return Bbox.from_extents(x0, y0, x0 + width, y0 + height) def from_extents(*args, minpos=None): """ Create a new Bbox from *left*, *bottom*, *right* and *top*. The *y*-axis increases upwards. Parameters ---------- left, bottom, right, top : float The four extents of the bounding box. minpos : float or None If this is supplied, the Bbox will have a minimum positive value set. This is useful when dealing with logarithmic scales and other scales where negative bounds result in floating point errors. """ bbox = Bbox(np.reshape(args, (2, 2))) if minpos is not None: bbox._minpos[:] = minpos return bbox def __format__(self, fmt): return ( 'Bbox(x0={0.x0:{1}}, y0={0.y0:{1}}, x1={0.x1:{1}}, y1={0.y1:{1}})'. format(self, fmt)) def __str__(self): return format(self, '') def __repr__(self): return 'Bbox([[{0.x0}, {0.y0}], [{0.x1}, {0.y1}]])'.format(self) def ignore(self, value): """ Set whether the existing bounds of the box should be ignored by subsequent calls to :meth:`update_from_data_xy`. value : bool - When ``True``, subsequent calls to :meth:`update_from_data_xy` will ignore the existing bounds of the `Bbox`. - When ``False``, subsequent calls to :meth:`update_from_data_xy` will include the existing bounds of the `Bbox`. """ self._ignore = value def update_from_path(self, path, ignore=None, updatex=True, updatey=True): """ Update the bounds of the `Bbox` to contain the vertices of the provided path. After updating, the bounds will have positive *width* and *height*; *x0* and *y0* will be the minimal values. Parameters ---------- path : `~matplotlib.path.Path` ignore : bool, optional - when ``True``, ignore the existing bounds of the `Bbox`. - when ``False``, include the existing bounds of the `Bbox`. - when ``None``, use the last value passed to :meth:`ignore`. updatex, updatey : bool, default: True When ``True``, update the x/y values. """ if ignore is None: ignore = self._ignore if path.vertices.size == 0: return points, minpos, changed = update_path_extents( path, None, self._points, self._minpos, ignore) if changed: self.invalidate() if updatex: self._points[:, 0] = points[:, 0] self._minpos[0] = minpos[0] if updatey: self._points[:, 1] = points[:, 1] self._minpos[1] = minpos[1] def update_from_data_x(self, x, ignore=None): """ Update the x-bounds of the `Bbox` based on the passed in data. After updating, the bounds will have positive *width*, and *x0* will be the minimal value. Parameters ---------- x : `~numpy.ndarray` Array of x-values. ignore : bool, optional - When ``True``, ignore the existing bounds of the `Bbox`. - When ``False``, include the existing bounds of the `Bbox`. - When ``None``, use the last value passed to :meth:`ignore`. """ x = np.ravel(x) self.update_from_data_xy(np.column_stack([x, np.ones(x.size)]), ignore=ignore, updatey=False) def update_from_data_y(self, y, ignore=None): """ Update the y-bounds of the `Bbox` based on the passed in data. After updating, the bounds will have positive *height*, and *y0* will be the minimal value. Parameters ---------- y : `~numpy.ndarray` Array of y-values. ignore : bool, optional - When ``True``, ignore the existing bounds of the `Bbox`. - When ``False``, include the existing bounds of the `Bbox`. - When ``None``, use the last value passed to :meth:`ignore`. """ y = np.ravel(y) self.update_from_data_xy(np.column_stack([np.ones(y.size), y]), ignore=ignore, updatex=False) def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True): """ Update the bounds of the `Bbox` based on the passed in data. After updating, the bounds will have positive *width* and *height*; *x0* and *y0* will be the minimal values. Parameters ---------- xy : `~numpy.ndarray` A numpy array of 2D points. ignore : bool, optional - When ``True``, ignore the existing bounds of the `Bbox`. - When ``False``, include the existing bounds of the `Bbox`. - When ``None``, use the last value passed to :meth:`ignore`. updatex, updatey : bool, default: True When ``True``, update the x/y values. """ if len(xy) == 0: return path = Path(xy) self.update_from_path(path, ignore=ignore, updatex=updatex, updatey=updatey) def x0(self, val): self._points[0, 0] = val self.invalidate() def y0(self, val): self._points[0, 1] = val self.invalidate() def x1(self, val): self._points[1, 0] = val self.invalidate() def y1(self, val): self._points[1, 1] = val self.invalidate() def p0(self, val): self._points[0] = val self.invalidate() def p1(self, val): self._points[1] = val self.invalidate() def intervalx(self, interval): self._points[:, 0] = interval self.invalidate() def intervaly(self, interval): self._points[:, 1] = interval self.invalidate() def bounds(self, bounds): l, b, w, h = bounds points = np.array([[l, b], [l + w, b + h]], float) if np.any(self._points != points): self._points = points self.invalidate() def minpos(self): """ The minimum positive value in both directions within the Bbox. This is useful when dealing with logarithmic scales and other scales where negative bounds result in floating point errors, and will be used as the minimum extent instead of *p0*. """ return self._minpos def minposx(self): """ The minimum positive value in the *x*-direction within the Bbox. This is useful when dealing with logarithmic scales and other scales where negative bounds result in floating point errors, and will be used as the minimum *x*-extent instead of *x0*. """ return self._minpos[0] def minposy(self): """ The minimum positive value in the *y*-direction within the Bbox. This is useful when dealing with logarithmic scales and other scales where negative bounds result in floating point errors, and will be used as the minimum *y*-extent instead of *y0*. """ return self._minpos[1] def get_points(self): """ Get the points of the bounding box directly as a numpy array of the form: ``[[x0, y0], [x1, y1]]``. """ self._invalid = 0 return self._points def set_points(self, points): """ Set the points of the bounding box directly from a numpy array of the form: ``[[x0, y0], [x1, y1]]``. No error checking is performed, as this method is mainly for internal use. """ if np.any(self._points != points): self._points = points self.invalidate() def set(self, other): """ Set this bounding box from the "frozen" bounds of another `Bbox`. """ if np.any(self._points != other.get_points()): self._points = other.get_points() self.invalidate() def mutated(self): """Return whether the bbox has changed since init.""" return self.mutatedx() or self.mutatedy() def mutatedx(self): """Return whether the x-limits have changed since init.""" return (self._points[0, 0] != self._points_orig[0, 0] or self._points[1, 0] != self._points_orig[1, 0]) def mutatedy(self): """Return whether the y-limits have changed since init.""" return (self._points[0, 1] != self._points_orig[0, 1] or self._points[1, 1] != self._points_orig[1, 1]) The provided code snippet includes necessary dependencies for implementing the `get_path_collection_extents` function. Write a Python function `def get_path_collection_extents( master_transform, paths, transforms, offsets, offset_transform)` to solve the following problem: r""" Given a sequence of `Path`\s, `.Transform`\s objects, and offsets, as found in a `.PathCollection`, returns the bounding box that encapsulates all of them. Parameters ---------- master_transform : `.Transform` Global transformation applied to all paths. paths : list of `Path` transforms : list of `.Affine2D` offsets : (N, 2) array-like offset_transform : `.Affine2D` Transform applied to the offsets before offsetting the path. Notes ----- The way that *paths*, *transforms* and *offsets* are combined follows the same method as for collections: Each is iterated over independently, so if you have 3 paths, 2 transforms and 1 offset, their combinations are as follows: (A, A, A), (B, B, A), (C, A, A) Here is the function: def get_path_collection_extents( master_transform, paths, transforms, offsets, offset_transform): r""" Given a sequence of `Path`\s, `.Transform`\s objects, and offsets, as found in a `.PathCollection`, returns the bounding box that encapsulates all of them. Parameters ---------- master_transform : `.Transform` Global transformation applied to all paths. paths : list of `Path` transforms : list of `.Affine2D` offsets : (N, 2) array-like offset_transform : `.Affine2D` Transform applied to the offsets before offsetting the path. Notes ----- The way that *paths*, *transforms* and *offsets* are combined follows the same method as for collections: Each is iterated over independently, so if you have 3 paths, 2 transforms and 1 offset, their combinations are as follows: (A, A, A), (B, B, A), (C, A, A) """ from .transforms import Bbox if len(paths) == 0: raise ValueError("No paths provided") extents, minpos = _path.get_path_collection_extents( master_transform, paths, np.atleast_3d(transforms), offsets, offset_transform) return Bbox.from_extents(*extents, minpos=minpos)
r""" Given a sequence of `Path`\s, `.Transform`\s objects, and offsets, as found in a `.PathCollection`, returns the bounding box that encapsulates all of them. Parameters ---------- master_transform : `.Transform` Global transformation applied to all paths. paths : list of `Path` transforms : list of `.Affine2D` offsets : (N, 2) array-like offset_transform : `.Affine2D` Transform applied to the offsets before offsetting the path. Notes ----- The way that *paths*, *transforms* and *offsets* are combined follows the same method as for collections: Each is iterated over independently, so if you have 3 paths, 2 transforms and 1 offset, their combinations are as follows: (A, A, A), (B, B, A), (C, A, A)
171,032
import math import os import logging from pathlib import Path import warnings import numpy as np import PIL.PngImagePlugin import matplotlib as mpl from matplotlib import _api, cbook, cm from matplotlib import _image from matplotlib._image import * import matplotlib.artist as martist from matplotlib.backend_bases import FigureCanvasBase import matplotlib.colors as mcolors from matplotlib.transforms import ( Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo, IdentityTransform, TransformedBbox) def composite_images(images, renderer, magnification=1.0): """ Composite a number of RGBA images into one. The images are composited in the order in which they appear in the *images* list. Parameters ---------- images : list of Images Each must have a `make_image` method. For each image, `can_composite` should return `True`, though this is not enforced by this function. Each image must have a purely affine transformation with no shear. renderer : `.RendererBase` magnification : float, default: 1 The additional magnification to apply for the renderer in use. Returns ------- image : uint8 array (M, N, 4) The composited RGBA image. offset_x, offset_y : float The (left, bottom) offset where the composited image should be placed in the output figure. """ if len(images) == 0: return np.empty((0, 0, 4), dtype=np.uint8), 0, 0 parts = [] bboxes = [] for image in images: data, x, y, trans = image.make_image(renderer, magnification) if data is not None: x *= magnification y *= magnification parts.append((data, x, y, image._get_scalar_alpha())) bboxes.append( Bbox([[x, y], [x + data.shape[1], y + data.shape[0]]])) if len(parts) == 0: return np.empty((0, 0, 4), dtype=np.uint8), 0, 0 bbox = Bbox.union(bboxes) output = np.zeros( (int(bbox.height), int(bbox.width), 4), dtype=np.uint8) for data, x, y, alpha in parts: trans = Affine2D().translate(x - bbox.x0, y - bbox.y0) _image.resample(data, output, trans, _image.NEAREST, resample=False, alpha=alpha) return output, bbox.x0 / magnification, bbox.y0 / magnification class _ImageBase(martist.Artist, cm.ScalarMappable): """ Base class for images. interpolation and cmap default to their rc settings cmap is a colors.Colormap instance norm is a colors.Normalize instance to map luminance to 0-1 extent is data axes (left, right, bottom, top) for making image plots registered with data plots. Default is to label the pixel centers with the zero-based row and column indices. Additional kwargs are matplotlib.artist properties """ zorder = 0 def __init__(self, ax, cmap=None, norm=None, interpolation=None, origin=None, filternorm=True, filterrad=4.0, resample=False, *, interpolation_stage=None, **kwargs ): martist.Artist.__init__(self) cm.ScalarMappable.__init__(self, norm, cmap) if origin is None: origin = mpl.rcParams['image.origin'] _api.check_in_list(["upper", "lower"], origin=origin) self.origin = origin self.set_filternorm(filternorm) self.set_filterrad(filterrad) self.set_interpolation(interpolation) self.set_interpolation_stage(interpolation_stage) self.set_resample(resample) self.axes = ax self._imcache = None self._internal_update(kwargs) def __str__(self): try: size = self.get_size() return f"{type(self).__name__}(size={size!r})" except RuntimeError: return type(self).__name__ def __getstate__(self): # Save some space on the pickle by not saving the cache. return {**super().__getstate__(), "_imcache": None} def get_size(self): """Return the size of the image as tuple (numrows, numcols).""" if self._A is None: raise RuntimeError('You must first set the image array') return self._A.shape[:2] def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on all backends. Parameters ---------- alpha : float or 2D array-like or None """ martist.Artist._set_alpha_for_array(self, alpha) if np.ndim(alpha) not in (0, 2): raise TypeError('alpha must be a float, two-dimensional ' 'array, or None') self._imcache = None def _get_scalar_alpha(self): """ Get a scalar alpha value to be applied to the artist as a whole. If the alpha value is a matrix, the method returns 1.0 because pixels have individual alpha values (see `~._ImageBase._make_image` for details). If the alpha value is a scalar, the method returns said value to be applied to the artist as a whole because pixels do not have individual alpha values. """ return 1.0 if self._alpha is None or np.ndim(self._alpha) > 0 \ else self._alpha def changed(self): """ Call this whenever the mappable is changed so observers can update. """ self._imcache = None cm.ScalarMappable.changed(self) def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0, unsampled=False, round_to_pixel_border=True): """ Normalize, rescale, and colormap the image *A* from the given *in_bbox* (in data space), to the given *out_bbox* (in pixel space) clipped to the given *clip_bbox* (also in pixel space), and magnified by the *magnification* factor. *A* may be a greyscale image (M, N) with a dtype of float32, float64, float128, uint16 or uint8, or an (M, N, 4) RGBA image with a dtype of float32, float64, float128, or uint8. If *unsampled* is True, the image will not be scaled, but an appropriate affine transformation will be returned instead. If *round_to_pixel_border* is True, the output image size will be rounded to the nearest pixel boundary. This makes the images align correctly with the axes. It should not be used if exact scaling is needed, such as for `FigureImage`. Returns ------- image : (M, N, 4) uint8 array The RGBA image, resampled unless *unsampled* is True. x, y : float The upper left corner where the image should be drawn, in pixel space. trans : Affine2D The affine transformation from image to pixel space. """ if A is None: raise RuntimeError('You must first set the image ' 'array or the image attribute') if A.size == 0: raise RuntimeError("_make_image must get a non-empty image. " "Your Artist's draw method must filter before " "this method is called.") clipped_bbox = Bbox.intersection(out_bbox, clip_bbox) if clipped_bbox is None: return None, 0, 0, None out_width_base = clipped_bbox.width * magnification out_height_base = clipped_bbox.height * magnification if out_width_base == 0 or out_height_base == 0: return None, 0, 0, None if self.origin == 'upper': # Flip the input image using a transform. This avoids the # problem with flipping the array, which results in a copy # when it is converted to contiguous in the C wrapper t0 = Affine2D().translate(0, -A.shape[0]).scale(1, -1) else: t0 = IdentityTransform() t0 += ( Affine2D() .scale( in_bbox.width / A.shape[1], in_bbox.height / A.shape[0]) .translate(in_bbox.x0, in_bbox.y0) + self.get_transform()) t = (t0 + (Affine2D() .translate(-clipped_bbox.x0, -clipped_bbox.y0) .scale(magnification))) # So that the image is aligned with the edge of the axes, we want to # round up the output width to the next integer. This also means # scaling the transform slightly to account for the extra subpixel. if (t.is_affine and round_to_pixel_border and (out_width_base % 1.0 != 0.0 or out_height_base % 1.0 != 0.0)): out_width = math.ceil(out_width_base) out_height = math.ceil(out_height_base) extra_width = (out_width - out_width_base) / out_width_base extra_height = (out_height - out_height_base) / out_height_base t += Affine2D().scale(1.0 + extra_width, 1.0 + extra_height) else: out_width = int(out_width_base) out_height = int(out_height_base) out_shape = (out_height, out_width) if not unsampled: if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in (3, 4)): raise ValueError(f"Invalid shape {A.shape} for image data") if A.ndim == 2 and self._interpolation_stage != 'rgba': # if we are a 2D array, then we are running through the # norm + colormap transformation. However, in general the # input data is not going to match the size on the screen so we # have to resample to the correct number of pixels # TODO slice input array first a_min = A.min() a_max = A.max() if a_min is np.ma.masked: # All masked; values don't matter. a_min, a_max = np.int32(0), np.int32(1) if A.dtype.kind == 'f': # Float dtype: scale to same dtype. scaled_dtype = np.dtype( np.float64 if A.dtype.itemsize > 4 else np.float32) if scaled_dtype.itemsize < A.dtype.itemsize: _api.warn_external(f"Casting input data from {A.dtype}" f" to {scaled_dtype} for imshow.") else: # Int dtype, likely. # Scale to appropriately sized float: use float32 if the # dynamic range is small, to limit the memory footprint. da = a_max.astype(np.float64) - a_min.astype(np.float64) scaled_dtype = np.float64 if da > 1e8 else np.float32 # Scale the input data to [.1, .9]. The Agg interpolators clip # to [0, 1] internally, and we use a smaller input scale to # identify the interpolated points that need to be flagged as # over/under. This may introduce numeric instabilities in very # broadly scaled data. # Always copy, and don't allow array subtypes. A_scaled = np.array(A, dtype=scaled_dtype) # Clip scaled data around norm if necessary. This is necessary # for big numbers at the edge of float64's ability to represent # changes. Applying a norm first would be good, but ruins the # interpolation of over numbers. self.norm.autoscale_None(A) dv = np.float64(self.norm.vmax) - np.float64(self.norm.vmin) vmid = np.float64(self.norm.vmin) + dv / 2 fact = 1e7 if scaled_dtype == np.float64 else 1e4 newmin = vmid - dv * fact if newmin < a_min: newmin = None else: a_min = np.float64(newmin) newmax = vmid + dv * fact if newmax > a_max: newmax = None else: a_max = np.float64(newmax) if newmax is not None or newmin is not None: np.clip(A_scaled, newmin, newmax, out=A_scaled) # Rescale the raw data to [offset, 1-offset] so that the # resampling code will run cleanly. Using dyadic numbers here # could reduce the error, but would not fully eliminate it and # breaks a number of tests (due to the slightly different # error bouncing some pixels across a boundary in the (very # quantized) colormapping step). offset = .1 frac = .8 # Run vmin/vmax through the same rescaling as the raw data; # otherwise, data values close or equal to the boundaries can # end up on the wrong side due to floating point error. vmin, vmax = self.norm.vmin, self.norm.vmax if vmin is np.ma.masked: vmin, vmax = a_min, a_max vrange = np.array([vmin, vmax], dtype=scaled_dtype) A_scaled -= a_min vrange -= a_min # .item() handles a_min/a_max being ndarray subclasses. a_min = a_min.astype(scaled_dtype).item() a_max = a_max.astype(scaled_dtype).item() if a_min != a_max: A_scaled /= ((a_max - a_min) / frac) vrange /= ((a_max - a_min) / frac) A_scaled += offset vrange += offset # resample the input data to the correct resolution and shape A_resampled = _resample(self, A_scaled, out_shape, t) del A_scaled # Make sure we don't use A_scaled anymore! # Un-scale the resampled data to approximately the original # range. Things that interpolated to outside the original range # will still be outside, but possibly clipped in the case of # higher order interpolation + drastically changing data. A_resampled -= offset vrange -= offset if a_min != a_max: A_resampled *= ((a_max - a_min) / frac) vrange *= ((a_max - a_min) / frac) A_resampled += a_min vrange += a_min # if using NoNorm, cast back to the original datatype if isinstance(self.norm, mcolors.NoNorm): A_resampled = A_resampled.astype(A.dtype) mask = (np.where(A.mask, np.float32(np.nan), np.float32(1)) if A.mask.shape == A.shape # nontrivial mask else np.ones_like(A, np.float32)) # we always have to interpolate the mask to account for # non-affine transformations out_alpha = _resample(self, mask, out_shape, t, resample=True) del mask # Make sure we don't use mask anymore! # Agg updates out_alpha in place. If the pixel has no image # data it will not be updated (and still be 0 as we initialized # it), if input data that would go into that output pixel than # it will be `nan`, if all the input data for a pixel is good # it will be 1, and if there is _some_ good data in that output # pixel it will be between [0, 1] (such as a rotated image). out_mask = np.isnan(out_alpha) out_alpha[out_mask] = 1 # Apply the pixel-by-pixel alpha values if present alpha = self.get_alpha() if alpha is not None and np.ndim(alpha) > 0: out_alpha *= _resample(self, alpha, out_shape, t, resample=True) # mask and run through the norm resampled_masked = np.ma.masked_array(A_resampled, out_mask) # we have re-set the vmin/vmax to account for small errors # that may have moved input values in/out of range s_vmin, s_vmax = vrange if isinstance(self.norm, mcolors.LogNorm) and s_vmin <= 0: # Don't give 0 or negative values to LogNorm s_vmin = np.finfo(scaled_dtype).eps # Block the norm from sending an update signal during the # temporary vmin/vmax change with self.norm.callbacks.blocked(), \ cbook._setattr_cm(self.norm, vmin=s_vmin, vmax=s_vmax): output = self.norm(resampled_masked) else: if A.ndim == 2: # _interpolation_stage == 'rgba' self.norm.autoscale_None(A) A = self.to_rgba(A) if A.shape[2] == 3: A = _rgb_to_rgba(A) alpha = self._get_scalar_alpha() output_alpha = _resample( # resample alpha channel self, A[..., 3], out_shape, t, alpha=alpha) output = _resample( # resample rgb channels self, _rgb_to_rgba(A[..., :3]), out_shape, t, alpha=alpha) output[..., 3] = output_alpha # recombine rgb and alpha # output is now either a 2D array of normed (int or float) data # or an RGBA array of re-sampled input output = self.to_rgba(output, bytes=True, norm=False) # output is now a correctly sized RGBA array of uint8 # Apply alpha *after* if the input was greyscale without a mask if A.ndim == 2: alpha = self._get_scalar_alpha() alpha_channel = output[:, :, 3] alpha_channel[:] = ( # Assignment will cast to uint8. alpha_channel.astype(np.float32) * out_alpha * alpha) else: if self._imcache is None: self._imcache = self.to_rgba(A, bytes=True, norm=(A.ndim == 2)) output = self._imcache # Subset the input image to only the part that will be displayed. subset = TransformedBbox(clip_bbox, t0.inverted()).frozen() output = output[ int(max(subset.ymin, 0)): int(min(subset.ymax + 1, output.shape[0])), int(max(subset.xmin, 0)): int(min(subset.xmax + 1, output.shape[1]))] t = Affine2D().translate( int(max(subset.xmin, 0)), int(max(subset.ymin, 0))) + t return output, clipped_bbox.x0, clipped_bbox.y0, t def make_image(self, renderer, magnification=1.0, unsampled=False): """ Normalize, rescale, and colormap this image's data for rendering using *renderer*, with the given *magnification*. If *unsampled* is True, the image will not be scaled, but an appropriate affine transformation will be returned instead. Returns ------- image : (M, N, 4) uint8 array The RGBA image, resampled unless *unsampled* is True. x, y : float The upper left corner where the image should be drawn, in pixel space. trans : Affine2D The affine transformation from image to pixel space. """ raise NotImplementedError('The make_image method must be overridden') def _check_unsampled_image(self): """ Return whether the image is better to be drawn unsampled. The derived class needs to override it. """ return False def draw(self, renderer, *args, **kwargs): # if not visible, declare victory and return if not self.get_visible(): self.stale = False return # for empty images, there is nothing to draw! if self.get_array().size == 0: self.stale = False return # actually render the image. gc = renderer.new_gc() self._set_gc_clip(gc) gc.set_alpha(self._get_scalar_alpha()) gc.set_url(self.get_url()) gc.set_gid(self.get_gid()) if (renderer.option_scale_image() # Renderer supports transform kwarg. and self._check_unsampled_image() and self.get_transform().is_affine): im, l, b, trans = self.make_image(renderer, unsampled=True) if im is not None: trans = Affine2D().scale(im.shape[1], im.shape[0]) + trans renderer.draw_image(gc, l, b, im, trans) else: im, l, b, trans = self.make_image( renderer, renderer.get_image_magnification()) if im is not None: renderer.draw_image(gc, l, b, im) gc.restore() self.stale = False def contains(self, mouseevent): """Test whether the mouse event occurred within the image.""" inside, info = self._default_contains(mouseevent) if inside is not None: return inside, info # 1) This doesn't work for figimage; but figimage also needs a fix # below (as the check cannot use x/ydata and extents). # 2) As long as the check below uses x/ydata, we need to test axes # identity instead of `self.axes.contains(event)` because even if # axes overlap, x/ydata is only valid for event.inaxes anyways. if self.axes is not mouseevent.inaxes: return False, {} # TODO: make sure this is consistent with patch and patch # collection on nonlinear transformed coordinates. # TODO: consider returning image coordinates (shouldn't # be too difficult given that the image is rectilinear trans = self.get_transform().inverted() x, y = trans.transform([mouseevent.x, mouseevent.y]) xmin, xmax, ymin, ymax = self.get_extent() if xmin > xmax: xmin, xmax = xmax, xmin if ymin > ymax: ymin, ymax = ymax, ymin if x is not None and y is not None: inside = (xmin <= x <= xmax) and (ymin <= y <= ymax) else: inside = False return inside, {} def write_png(self, fname): """Write the image to png file *fname*.""" im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A, bytes=True, norm=True) PIL.Image.fromarray(im).save(fname, format="png") def set_data(self, A): """ Set the image array. Note that this function does *not* update the normalization used. Parameters ---------- A : array-like or `PIL.Image.Image` """ if isinstance(A, PIL.Image.Image): A = pil_to_array(A) # Needed e.g. to apply png palette. self._A = cbook.safe_masked_invalid(A, copy=True) if (self._A.dtype != np.uint8 and not np.can_cast(self._A.dtype, float, "same_kind")): raise TypeError("Image data of dtype {} cannot be converted to " "float".format(self._A.dtype)) if self._A.ndim == 3 and self._A.shape[-1] == 1: # If just one dimension assume scalar and apply colormap self._A = self._A[:, :, 0] if not (self._A.ndim == 2 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]): raise TypeError("Invalid shape {} for image data" .format(self._A.shape)) if self._A.ndim == 3: # If the input data has values outside the valid range (after # normalisation), we issue a warning and then clip X to the bounds # - otherwise casting wraps extreme values, hiding outliers and # making reliable interpretation impossible. high = 255 if np.issubdtype(self._A.dtype, np.integer) else 1 if self._A.min() < 0 or high < self._A.max(): _log.warning( 'Clipping input data to the valid range for imshow with ' 'RGB data ([0..1] for floats or [0..255] for integers).' ) self._A = np.clip(self._A, 0, high) # Cast unsupported integer types to uint8 if self._A.dtype != np.uint8 and np.issubdtype(self._A.dtype, np.integer): self._A = self._A.astype(np.uint8) self._imcache = None self.stale = True def set_array(self, A): """ Retained for backwards compatibility - use set_data instead. Parameters ---------- A : array-like """ # This also needs to be here to override the inherited # cm.ScalarMappable.set_array method so it is not invoked by mistake. self.set_data(A) def get_interpolation(self): """ Return the interpolation method the image uses when resizing. One of 'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', or 'none'. """ return self._interpolation def set_interpolation(self, s): """ Set the interpolation method the image uses when resizing. If None, use :rc:`image.interpolation`. If 'none', the image is shown as is without interpolating. 'none' is only supported in agg, ps and pdf backends and will fall back to 'nearest' mode for other backends. Parameters ---------- s : {'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', \ 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', \ 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'} or None """ if s is None: s = mpl.rcParams['image.interpolation'] s = s.lower() _api.check_in_list(_interpd_, interpolation=s) self._interpolation = s self.stale = True def set_interpolation_stage(self, s): """ Set when interpolation happens during the transform to RGBA. Parameters ---------- s : {'data', 'rgba'} or None Whether to apply up/downsampling interpolation in data or rgba space. """ if s is None: s = "data" # placeholder for maybe having rcParam _api.check_in_list(['data', 'rgba'], s=s) self._interpolation_stage = s self.stale = True def can_composite(self): """Return whether the image can be composited with its neighbors.""" trans = self.get_transform() return ( self._interpolation != 'none' and trans.is_affine and trans.is_separable) def set_resample(self, v): """ Set whether image resampling is used. Parameters ---------- v : bool or None If None, use :rc:`image.resample`. """ if v is None: v = mpl.rcParams['image.resample'] self._resample = v self.stale = True def get_resample(self): """Return whether image resampling is used.""" return self._resample def set_filternorm(self, filternorm): """ Set whether the resize filter normalizes the weights. See help for `~.Axes.imshow`. Parameters ---------- filternorm : bool """ self._filternorm = bool(filternorm) self.stale = True def get_filternorm(self): """Return whether the resize filter normalizes the weights.""" return self._filternorm def set_filterrad(self, filterrad): """ Set the resize filter radius only applicable to some interpolation schemes -- see help for imshow Parameters ---------- filterrad : positive float """ r = float(filterrad) if r <= 0: raise ValueError("The filter radius must be a positive number") self._filterrad = r self.stale = True def get_filterrad(self): """Return the filterrad setting.""" return self._filterrad The provided code snippet includes necessary dependencies for implementing the `_draw_list_compositing_images` function. Write a Python function `def _draw_list_compositing_images( renderer, parent, artists, suppress_composite=None)` to solve the following problem: Draw a sorted list of artists, compositing images into a single image where possible. For internal Matplotlib use only: It is here to reduce duplication between `Figure.draw` and `Axes.draw`, but otherwise should not be generally useful. Here is the function: def _draw_list_compositing_images( renderer, parent, artists, suppress_composite=None): """ Draw a sorted list of artists, compositing images into a single image where possible. For internal Matplotlib use only: It is here to reduce duplication between `Figure.draw` and `Axes.draw`, but otherwise should not be generally useful. """ has_images = any(isinstance(x, _ImageBase) for x in artists) # override the renderer default if suppressComposite is not None not_composite = (suppress_composite if suppress_composite is not None else renderer.option_image_nocomposite()) if not_composite or not has_images: for a in artists: a.draw(renderer) else: # Composite any adjacent images together image_group = [] mag = renderer.get_image_magnification() def flush_images(): if len(image_group) == 1: image_group[0].draw(renderer) elif len(image_group) > 1: data, l, b = composite_images(image_group, renderer, mag) if data.size != 0: gc = renderer.new_gc() gc.set_clip_rectangle(parent.bbox) gc.set_clip_path(parent.get_clip_path()) renderer.draw_image(gc, round(l), round(b), data) gc.restore() del image_group[:] for a in artists: if (isinstance(a, _ImageBase) and a.can_composite() and a.get_clip_on() and not a.get_clip_path()): image_group.append(a) else: flush_images() a.draw(renderer) flush_images()
Draw a sorted list of artists, compositing images into a single image where possible. For internal Matplotlib use only: It is here to reduce duplication between `Figure.draw` and `Axes.draw`, but otherwise should not be generally useful.
171,033
import math import os import logging from pathlib import Path import warnings import numpy as np import PIL.PngImagePlugin import matplotlib as mpl from matplotlib import _api, cbook, cm from matplotlib import _image from matplotlib._image import * import matplotlib.artist as martist from matplotlib.backend_bases import FigureCanvasBase import matplotlib.colors as mcolors from matplotlib.transforms import ( Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo, IdentityTransform, TransformedBbox) _interpd_ = { 'antialiased': _image.NEAREST, # this will use nearest or Hanning... 'none': _image.NEAREST, # fall back to nearest when not supported 'nearest': _image.NEAREST, 'bilinear': _image.BILINEAR, 'bicubic': _image.BICUBIC, 'spline16': _image.SPLINE16, 'spline36': _image.SPLINE36, 'hanning': _image.HANNING, 'hamming': _image.HAMMING, 'hermite': _image.HERMITE, 'kaiser': _image.KAISER, 'quadric': _image.QUADRIC, 'catrom': _image.CATROM, 'gaussian': _image.GAUSSIAN, 'bessel': _image.BESSEL, 'mitchell': _image.MITCHELL, 'sinc': _image.SINC, 'lanczos': _image.LANCZOS, 'blackman': _image.BLACKMAN, } class Affine2D(Affine2DBase): """ A mutable 2D affine transformation. """ def __init__(self, matrix=None, **kwargs): """ Initialize an Affine transform from a 3x3 numpy float array:: a c e b d f 0 0 1 If *matrix* is None, initialize with the identity transform. """ super().__init__(**kwargs) if matrix is None: # A bit faster than np.identity(3). matrix = IdentityTransform._mtx self._mtx = matrix.copy() self._invalid = 0 _base_str = _make_str_method("_mtx") def __str__(self): return (self._base_str() if (self._mtx != np.diag(np.diag(self._mtx))).any() else f"Affine2D().scale({self._mtx[0, 0]}, {self._mtx[1, 1]})" if self._mtx[0, 0] != self._mtx[1, 1] else f"Affine2D().scale({self._mtx[0, 0]})") def from_values(a, b, c, d, e, f): """ Create a new Affine2D instance from the given values:: a c e b d f 0 0 1 . """ return Affine2D( np.array([a, c, e, b, d, f, 0.0, 0.0, 1.0], float).reshape((3, 3))) def get_matrix(self): """ Get the underlying transformation matrix as a 3x3 numpy array:: a c e b d f 0 0 1 . """ if self._invalid: self._inverted = None self._invalid = 0 return self._mtx def set_matrix(self, mtx): """ Set the underlying transformation matrix from a 3x3 numpy array:: a c e b d f 0 0 1 . """ self._mtx = mtx self.invalidate() def set(self, other): """ Set this transformation from the frozen copy of another `Affine2DBase` object. """ _api.check_isinstance(Affine2DBase, other=other) self._mtx = other.get_matrix() self.invalidate() def identity(): """ Return a new `Affine2D` object that is the identity transform. Unless this transform will be mutated later on, consider using the faster `IdentityTransform` class instead. """ return Affine2D() def clear(self): """ Reset the underlying matrix to the identity transform. """ # A bit faster than np.identity(3). self._mtx = IdentityTransform._mtx.copy() self.invalidate() return self def rotate(self, theta): """ Add a rotation (in radians) to this transform in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ a = math.cos(theta) b = math.sin(theta) mtx = self._mtx # Operating and assigning one scalar at a time is much faster. (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist() # mtx = [[a -b 0], [b a 0], [0 0 1]] * mtx mtx[0, 0] = a * xx - b * yx mtx[0, 1] = a * xy - b * yy mtx[0, 2] = a * x0 - b * y0 mtx[1, 0] = b * xx + a * yx mtx[1, 1] = b * xy + a * yy mtx[1, 2] = b * x0 + a * y0 self.invalidate() return self def rotate_deg(self, degrees): """ Add a rotation (in degrees) to this transform in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ return self.rotate(math.radians(degrees)) def rotate_around(self, x, y, theta): """ Add a rotation (in radians) around the point (x, y) in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ return self.translate(-x, -y).rotate(theta).translate(x, y) def rotate_deg_around(self, x, y, degrees): """ Add a rotation (in degrees) around the point (x, y) in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ # Cast to float to avoid wraparound issues with uint8's x, y = float(x), float(y) return self.translate(-x, -y).rotate_deg(degrees).translate(x, y) def translate(self, tx, ty): """ Add a translation in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ self._mtx[0, 2] += tx self._mtx[1, 2] += ty self.invalidate() return self def scale(self, sx, sy=None): """ Add a scale in place. If *sy* is None, the same scale is applied in both the *x*- and *y*-directions. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ if sy is None: sy = sx # explicit element-wise scaling is fastest self._mtx[0, 0] *= sx self._mtx[0, 1] *= sx self._mtx[0, 2] *= sx self._mtx[1, 0] *= sy self._mtx[1, 1] *= sy self._mtx[1, 2] *= sy self.invalidate() return self def skew(self, xShear, yShear): """ Add a skew in place. *xShear* and *yShear* are the shear angles along the *x*- and *y*-axes, respectively, in radians. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ rx = math.tan(xShear) ry = math.tan(yShear) mtx = self._mtx # Operating and assigning one scalar at a time is much faster. (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist() # mtx = [[1 rx 0], [ry 1 0], [0 0 1]] * mtx mtx[0, 0] += rx * yx mtx[0, 1] += rx * yy mtx[0, 2] += rx * y0 mtx[1, 0] += ry * xx mtx[1, 1] += ry * xy mtx[1, 2] += ry * x0 self.invalidate() return self def skew_deg(self, xShear, yShear): """ Add a skew in place. *xShear* and *yShear* are the shear angles along the *x*- and *y*-axes, respectively, in degrees. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ return self.skew(math.radians(xShear), math.radians(yShear)) The provided code snippet includes necessary dependencies for implementing the `_resample` function. Write a Python function `def _resample( image_obj, data, out_shape, transform, *, resample=None, alpha=1)` to solve the following problem: Convenience wrapper around `._image.resample` to resample *data* to *out_shape* (with a third dimension if *data* is RGBA) that takes care of allocating the output array and fetching the relevant properties from the Image object *image_obj*. Here is the function: def _resample( image_obj, data, out_shape, transform, *, resample=None, alpha=1): """ Convenience wrapper around `._image.resample` to resample *data* to *out_shape* (with a third dimension if *data* is RGBA) that takes care of allocating the output array and fetching the relevant properties from the Image object *image_obj*. """ # AGG can only handle coordinates smaller than 24-bit signed integers, # so raise errors if the input data is larger than _image.resample can # handle. msg = ('Data with more than {n} cannot be accurately displayed. ' 'Downsampling to less than {n} before displaying. ' 'To remove this warning, manually downsample your data.') if data.shape[1] > 2**23: warnings.warn(msg.format(n='2**23 columns')) step = int(np.ceil(data.shape[1] / 2**23)) data = data[:, ::step] transform = Affine2D().scale(step, 1) + transform if data.shape[0] > 2**24: warnings.warn(msg.format(n='2**24 rows')) step = int(np.ceil(data.shape[0] / 2**24)) data = data[::step, :] transform = Affine2D().scale(1, step) + transform # decide if we need to apply anti-aliasing if the data is upsampled: # compare the number of displayed pixels to the number of # the data pixels. interpolation = image_obj.get_interpolation() if interpolation == 'antialiased': # don't antialias if upsampling by an integer number or # if zooming in more than a factor of 3 pos = np.array([[0, 0], [data.shape[1], data.shape[0]]]) disp = transform.transform(pos) dispx = np.abs(np.diff(disp[:, 0])) dispy = np.abs(np.diff(disp[:, 1])) if ((dispx > 3 * data.shape[1] or dispx == data.shape[1] or dispx == 2 * data.shape[1]) and (dispy > 3 * data.shape[0] or dispy == data.shape[0] or dispy == 2 * data.shape[0])): interpolation = 'nearest' else: interpolation = 'hanning' out = np.zeros(out_shape + data.shape[2:], data.dtype) # 2D->2D, 3D->3D. if resample is None: resample = image_obj.get_resample() _image.resample(data, out, transform, _interpd_[interpolation], resample, alpha, image_obj.get_filternorm(), image_obj.get_filterrad()) return out
Convenience wrapper around `._image.resample` to resample *data* to *out_shape* (with a third dimension if *data* is RGBA) that takes care of allocating the output array and fetching the relevant properties from the Image object *image_obj*.
171,034
import math import os import logging from pathlib import Path import warnings import numpy as np import PIL.PngImagePlugin import matplotlib as mpl from matplotlib import _api, cbook, cm from matplotlib import _image from matplotlib._image import * import matplotlib.artist as martist from matplotlib.backend_bases import FigureCanvasBase import matplotlib.colors as mcolors from matplotlib.transforms import ( Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo, IdentityTransform, TransformedBbox) The provided code snippet includes necessary dependencies for implementing the `_rgb_to_rgba` function. Write a Python function `def _rgb_to_rgba(A)` to solve the following problem: Convert an RGB image to RGBA, as required by the image resample C++ extension. Here is the function: def _rgb_to_rgba(A): """ Convert an RGB image to RGBA, as required by the image resample C++ extension. """ rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype) rgba[:, :, :3] = A if rgba.dtype == np.uint8: rgba[:, :, 3] = 255 else: rgba[:, :, 3] = 1.0 return rgba
Convert an RGB image to RGBA, as required by the image resample C++ extension.
171,035
import math import os import logging from pathlib import Path import warnings import numpy as np import PIL.PngImagePlugin import matplotlib as mpl from matplotlib import _api, cbook, cm from matplotlib import _image from matplotlib._image import * import matplotlib.artist as martist from matplotlib.backend_bases import FigureCanvasBase import matplotlib.colors as mcolors from matplotlib.transforms import ( Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo, IdentityTransform, TransformedBbox) import os ) if os.environ.get('MPLBACKEND'): rcParams['backend'] = os.environ.get('MPLBACKEND') class Path(PurePath): def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ... def __enter__(self: _P) -> _P: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> Optional[bool]: ... def cwd(cls: Type[_P]) -> _P: ... def stat(self) -> os.stat_result: ... def chmod(self, mode: int) -> None: ... def exists(self) -> bool: ... def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def group(self) -> str: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... if sys.version_info >= (3, 7): def is_mount(self) -> bool: ... def is_symlink(self) -> bool: ... def is_socket(self) -> bool: ... def is_fifo(self) -> bool: ... def is_block_device(self) -> bool: ... def is_char_device(self) -> bool: ... def iterdir(self: _P) -> Generator[_P, None, None]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> os.stat_result: ... def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... # Adapted from builtins.open # Text mode: always returns a TextIOWrapper def open( self, mode: OpenTextMode = ..., buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> TextIOWrapper: ... # Unbuffered binary mode: returns a FileIO def open( self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ... ) -> FileIO: ... # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter def open( self, mode: OpenBinaryModeUpdating, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedRandom: ... def open( self, mode: OpenBinaryModeWriting, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedWriter: ... def open( self, mode: OpenBinaryModeReading, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedReader: ... # Buffering cannot be determined: fall back to BinaryIO def open( self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... ) -> BinaryIO: ... # Fallback if mode is not specified def open( self, mode: str, buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> IO[Any]: ... def owner(self) -> str: ... if sys.version_info >= (3, 9): def readlink(self: _P) -> _P: ... if sys.version_info >= (3, 8): def rename(self: _P, target: Union[str, PurePath]) -> _P: ... def replace(self: _P, target: Union[str, PurePath]) -> _P: ... else: def rename(self, target: Union[str, PurePath]) -> None: ... def replace(self, target: Union[str, PurePath]) -> None: ... def resolve(self: _P, strict: bool = ...) -> _P: ... def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def rmdir(self) -> None: ... def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ... def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... if sys.version_info >= (3, 8): def unlink(self, missing_ok: bool = ...) -> None: ... else: def unlink(self) -> None: ... def home(cls: Type[_P]) -> _P: ... def absolute(self: _P) -> _P: ... def expanduser(self: _P) -> _P: ... def read_bytes(self) -> bytes: ... def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ... def write_bytes(self, data: bytes) -> int: ... def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ... if sys.version_info >= (3, 8): def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ... class Figure(FigureBase): """ The top level container for all the plot elements. Attributes ---------- patch The `.Rectangle` instance representing the figure background patch. suppressComposite For multiple images, the figure will make composite images depending on the renderer option_image_nocomposite function. If *suppressComposite* is a boolean, this will override the renderer. """ # Remove the self._fig_callbacks properties on figure and subfigure # after the deprecation expires. callbacks = _api.deprecated( "3.6", alternative=("the 'resize_event' signal in " "Figure.canvas.callbacks") )(property(lambda self: self._fig_callbacks)) def __str__(self): return "Figure(%gx%g)" % tuple(self.bbox.size) def __repr__(self): return "<{clsname} size {h:g}x{w:g} with {naxes} Axes>".format( clsname=self.__class__.__name__, h=self.bbox.size[0], w=self.bbox.size[1], naxes=len(self.axes), ) def __init__(self, figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, # rc figure.subplot.* tight_layout=None, # rc figure.autolayout constrained_layout=None, # rc figure.constrained_layout.use *, layout=None, **kwargs ): """ Parameters ---------- figsize : 2-tuple of floats, default: :rc:`figure.figsize` Figure dimension ``(width, height)`` in inches. dpi : float, default: :rc:`figure.dpi` Dots per inch. facecolor : default: :rc:`figure.facecolor` The figure patch facecolor. edgecolor : default: :rc:`figure.edgecolor` The figure patch edge color. linewidth : float The linewidth of the frame (i.e. the edge linewidth of the figure patch). frameon : bool, default: :rc:`figure.frameon` If ``False``, suppress drawing the figure background patch. subplotpars : `SubplotParams` Subplot parameters. If not given, the default subplot parameters :rc:`figure.subplot.*` are used. tight_layout : bool or dict, default: :rc:`figure.autolayout` Whether to use the tight layout mechanism. See `.set_tight_layout`. .. admonition:: Discouraged The use of this parameter is discouraged. Please use ``layout='tight'`` instead for the common case of ``tight_layout=True`` and use `.set_tight_layout` otherwise. constrained_layout : bool, default: :rc:`figure.constrained_layout.use` This is equal to ``layout='constrained'``. .. admonition:: Discouraged The use of this parameter is discouraged. Please use ``layout='constrained'`` instead. 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 have significant performance penalties. - '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 :doc:`/tutorials/intermediate/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`. Other Parameters ---------------- **kwargs : `.Figure` properties, optional %(Figure:kwdoc)s """ super().__init__(**kwargs) self._layout_engine = None if layout is not None: if (tight_layout is not None): _api.warn_external( "The Figure parameters 'layout' and 'tight_layout' cannot " "be used together. Please use 'layout' only.") if (constrained_layout is not None): _api.warn_external( "The Figure parameters 'layout' and 'constrained_layout' " "cannot be used together. Please use 'layout' only.") self.set_layout_engine(layout=layout) elif tight_layout is not None: if constrained_layout is not None: _api.warn_external( "The Figure parameters 'tight_layout' and " "'constrained_layout' cannot be used together. Please use " "'layout' parameter") self.set_layout_engine(layout='tight') if isinstance(tight_layout, dict): self.get_layout_engine().set(**tight_layout) elif constrained_layout is not None: if isinstance(constrained_layout, dict): self.set_layout_engine(layout='constrained') self.get_layout_engine().set(**constrained_layout) elif constrained_layout: self.set_layout_engine(layout='constrained') else: # everything is None, so use default: self.set_layout_engine(layout=layout) self._fig_callbacks = cbook.CallbackRegistry(signals=["dpi_changed"]) # Callbacks traditionally associated with the canvas (and exposed with # a proxy property), but that actually need to be on the figure for # pickling. self._canvas_callbacks = cbook.CallbackRegistry( signals=FigureCanvasBase.events) connect = self._canvas_callbacks._connect_picklable self._mouse_key_ids = [ connect('key_press_event', backend_bases._key_handler), connect('key_release_event', backend_bases._key_handler), connect('key_release_event', backend_bases._key_handler), connect('button_press_event', backend_bases._mouse_handler), connect('button_release_event', backend_bases._mouse_handler), connect('scroll_event', backend_bases._mouse_handler), connect('motion_notify_event', backend_bases._mouse_handler), ] self._button_pick_id = connect('button_press_event', self.pick) self._scroll_pick_id = connect('scroll_event', self.pick) if figsize is None: figsize = mpl.rcParams['figure.figsize'] if dpi is None: dpi = mpl.rcParams['figure.dpi'] if facecolor is None: facecolor = mpl.rcParams['figure.facecolor'] if edgecolor is None: edgecolor = mpl.rcParams['figure.edgecolor'] if frameon is None: frameon = mpl.rcParams['figure.frameon'] if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any(): raise ValueError('figure size must be positive finite not ' f'{figsize}') self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) self.dpi_scale_trans = Affine2D().scale(dpi) # do not use property as it will trigger self._dpi = dpi self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans) self.figbbox = self.bbox self.transFigure = BboxTransformTo(self.bbox) self.transSubfigure = self.transFigure self.patch = Rectangle( xy=(0, 0), width=1, height=1, visible=frameon, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, # Don't let the figure patch influence bbox calculation. in_layout=False) self._set_artist_props(self.patch) self.patch.set_antialiased(False) FigureCanvasBase(self) # Set self.canvas. if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self._axstack = _AxesStack() # track all figure axes and current axes self.clear() def pick(self, mouseevent): if not self.canvas.widgetlock.locked(): super().pick(mouseevent) def _check_layout_engines_compat(self, old, new): """ Helper for set_layout engine If the figure has used the old engine and added a colorbar then the value of colorbar_gridspec must be the same on the new engine. """ if old is None or new is None: return True if old.colorbar_gridspec == new.colorbar_gridspec: return True # colorbar layout different, so check if any colorbars are on the # figure... for ax in self.axes: if hasattr(ax, '_colorbar'): # colorbars list themselves as a colorbar. return False return True def set_layout_engine(self, layout=None, **kwargs): """ Set the layout engine for this figure. Parameters ---------- layout: {'constrained', 'compressed', 'tight', 'none'} or \ `LayoutEngine` or None - 'constrained' will use `~.ConstrainedLayoutEngine` - 'compressed' will also use `~.ConstrainedLayoutEngine`, but with a correction that attempts to make a good layout for fixed-aspect ratio Axes. - 'tight' uses `~.TightLayoutEngine` - 'none' removes layout engine. If `None`, the behavior is controlled by :rc:`figure.autolayout` (which if `True` behaves as if 'tight' was passed) and :rc:`figure.constrained_layout.use` (which if `True` behaves as if 'constrained' was passed). If both are `True`, :rc:`figure.autolayout` takes priority. Users and libraries can define their own layout engines and pass the instance directly as well. kwargs: dict The keyword arguments are passed to the layout engine to set things like padding and margin sizes. Only used if *layout* is a string. """ if layout is None: if mpl.rcParams['figure.autolayout']: layout = 'tight' elif mpl.rcParams['figure.constrained_layout.use']: layout = 'constrained' else: self._layout_engine = None return if layout == 'tight': new_layout_engine = TightLayoutEngine(**kwargs) elif layout == 'constrained': new_layout_engine = ConstrainedLayoutEngine(**kwargs) elif layout == 'compressed': new_layout_engine = ConstrainedLayoutEngine(compress=True, **kwargs) elif layout == 'none': if self._layout_engine is not None: new_layout_engine = PlaceHolderLayoutEngine( self._layout_engine.adjust_compatible, self._layout_engine.colorbar_gridspec ) else: new_layout_engine = None elif isinstance(layout, LayoutEngine): new_layout_engine = layout else: raise ValueError(f"Invalid value for 'layout': {layout!r}") if self._check_layout_engines_compat(self._layout_engine, new_layout_engine): self._layout_engine = new_layout_engine else: raise RuntimeError('Colorbar layout of new layout engine not ' 'compatible with old engine, and a colorbar ' 'has been created. Engine not changed.') def get_layout_engine(self): return self._layout_engine # TODO: I'd like to dynamically add the _repr_html_ method # to the figure in the right context, but then IPython doesn't # use it, for some reason. def _repr_html_(self): # We can't use "isinstance" here, because then we'd end up importing # webagg unconditionally. if 'WebAgg' in type(self.canvas).__name__: from matplotlib.backends import backend_webagg return backend_webagg.ipython_inline_display(self) def show(self, warn=True): """ If using a GUI backend with pyplot, display the figure window. If the figure was not created using `~.pyplot.figure`, it will lack a `~.backend_bases.FigureManagerBase`, and this method will raise an AttributeError. .. warning:: This does not manage an GUI event loop. Consequently, the figure may only be shown briefly or not shown at all if you or your environment are not managing an event loop. Use cases for `.Figure.show` include running this from a GUI application (where there is persistently an event loop running) or from a shell, like IPython, that install an input hook to allow the interactive shell to accept input while the figure is also being shown and interactive. Some, but not all, GUI toolkits will register an input hook on import. See :ref:`cp_integration` for more details. If you're in a shell without input hook integration or executing a python script, you should use `matplotlib.pyplot.show` with ``block=True`` instead, which takes care of starting and running the event loop for you. Parameters ---------- warn : bool, default: True If ``True`` and we are not running headless (i.e. on Linux with an unset DISPLAY), issue warning when called on a non-GUI backend. """ if self.canvas.manager is None: raise AttributeError( "Figure.show works only for figures managed by pyplot, " "normally created by pyplot.figure()") try: self.canvas.manager.show() except NonGuiException as exc: if warn: _api.warn_external(str(exc)) def axes(self): """ List of Axes in the Figure. You can access and modify the Axes in the Figure through this list. Do not modify the list itself. Instead, use `~Figure.add_axes`, `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an Axes. Note: The `.Figure.axes` property and `~.Figure.get_axes` method are equivalent. """ return self._axstack.as_list() get_axes = axes.fget def _get_renderer(self): if hasattr(self.canvas, 'get_renderer'): return self.canvas.get_renderer() else: return _get_renderer(self) def _get_dpi(self): return self._dpi def _set_dpi(self, dpi, forward=True): """ Parameters ---------- dpi : float forward : bool Passed on to `~.Figure.set_size_inches` """ if dpi == self._dpi: # We don't want to cause undue events in backends. return self._dpi = dpi self.dpi_scale_trans.clear().scale(dpi) w, h = self.get_size_inches() self.set_size_inches(w, h, forward=forward) self._fig_callbacks.process('dpi_changed', self) dpi = property(_get_dpi, _set_dpi, doc="The resolution in dots per inch.") def get_tight_layout(self): """Return whether `.tight_layout` is called when drawing.""" return isinstance(self.get_layout_engine(), TightLayoutEngine) pending=True) def set_tight_layout(self, tight): """ [*Discouraged*] Set whether and how `.tight_layout` is called when drawing. .. admonition:: Discouraged This method is discouraged in favor of `~.set_layout_engine`. Parameters ---------- tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None If a bool, sets whether to call `.tight_layout` upon drawing. If ``None``, use :rc:`figure.autolayout` instead. If a dict, pass it as kwargs to `.tight_layout`, overriding the default paddings. """ if tight is None: tight = mpl.rcParams['figure.autolayout'] _tight = 'tight' if bool(tight) else 'none' _tight_parameters = tight if isinstance(tight, dict) else {} self.set_layout_engine(_tight, **_tight_parameters) self.stale = True def get_constrained_layout(self): """ Return whether constrained layout is being used. See :doc:`/tutorials/intermediate/constrainedlayout_guide`. """ return isinstance(self.get_layout_engine(), ConstrainedLayoutEngine) pending=True) def set_constrained_layout(self, constrained): """ [*Discouraged*] Set whether ``constrained_layout`` is used upon drawing. If None, :rc:`figure.constrained_layout.use` value will be used. When providing a dict containing the keys ``w_pad``, ``h_pad`` the default ``constrained_layout`` paddings will be overridden. These pads are in inches and default to 3.0/72.0. ``w_pad`` is the width padding and ``h_pad`` is the height padding. .. admonition:: Discouraged This method is discouraged in favor of `~.set_layout_engine`. Parameters ---------- constrained : bool or dict or None """ if constrained is None: constrained = mpl.rcParams['figure.constrained_layout.use'] _constrained = 'constrained' if bool(constrained) else 'none' _parameters = constrained if isinstance(constrained, dict) else {} self.set_layout_engine(_constrained, **_parameters) self.stale = True "3.6", alternative="figure.get_layout_engine().set()", pending=True) def set_constrained_layout_pads(self, **kwargs): """ Set padding for ``constrained_layout``. Tip: The parameters can be passed from a dictionary by using ``fig.set_constrained_layout(**pad_dict)``. See :doc:`/tutorials/intermediate/constrainedlayout_guide`. Parameters ---------- w_pad : float, default: :rc:`figure.constrained_layout.w_pad` Width padding in inches. This is the pad around Axes and is meant to make sure there is enough room for fonts to look good. Defaults to 3 pts = 0.04167 inches h_pad : float, default: :rc:`figure.constrained_layout.h_pad` Height padding in inches. Defaults to 3 pts. wspace : float, default: :rc:`figure.constrained_layout.wspace` Width padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being w_pad + wspace. hspace : float, default: :rc:`figure.constrained_layout.hspace` Height padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being h_pad + hspace. """ if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): self.get_layout_engine().set(**kwargs) pending=True) def get_constrained_layout_pads(self, relative=False): """ Get padding for ``constrained_layout``. Returns a list of ``w_pad, h_pad`` in inches and ``wspace`` and ``hspace`` as fractions of the subplot. All values are None if ``constrained_layout`` is not used. See :doc:`/tutorials/intermediate/constrainedlayout_guide`. Parameters ---------- relative : bool If `True`, then convert from inches to figure relative. """ if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): return None, None, None, None info = self.get_layout_engine().get_info() w_pad = info['w_pad'] h_pad = info['h_pad'] wspace = info['wspace'] hspace = info['hspace'] if relative and (w_pad is not None or h_pad is not None): renderer = self._get_renderer() dpi = renderer.dpi w_pad = w_pad * dpi / renderer.width h_pad = h_pad * dpi / renderer.height return w_pad, h_pad, wspace, hspace def set_canvas(self, canvas): """ Set the canvas that contains the figure Parameters ---------- canvas : FigureCanvas """ self.canvas = canvas def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs): """ Add a non-resampled image to the figure. The image is attached to the lower or upper left corner depending on *origin*. Parameters ---------- X The image data. This is an array of one of the following shapes: - (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. xo, yo : int The *x*/*y* image offset in pixels. alpha : None or float The alpha blending value. %(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). origin : {'upper', 'lower'}, default: :rc:`image.origin` Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes. resize : bool If *True*, resize the figure to match the given image size. Returns ------- `matplotlib.image.FigureImage` Other Parameters ---------------- **kwargs Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`. Notes ----- figimage complements the Axes image (`~matplotlib.axes.Axes.imshow`) which will be resampled to fit the current Axes. If you want a resampled image to fill the entire figure, you can define an `~matplotlib.axes.Axes` with extent [0, 0, 1, 1]. Examples -------- :: f = plt.figure() nx = int(f.get_figwidth() * f.dpi) ny = int(f.get_figheight() * f.dpi) data = np.random.random((ny, nx)) f.figimage(data) plt.show() """ if resize: dpi = self.get_dpi() figsize = [x / dpi for x in (X.shape[1], X.shape[0])] self.set_size_inches(figsize, forward=True) im = mimage.FigureImage(self, cmap=cmap, norm=norm, offsetx=xo, offsety=yo, origin=origin, **kwargs) im.stale_callback = _stale_figure_callback im.set_array(X) im.set_alpha(alpha) if norm is None: im.set_clim(vmin, vmax) self.images.append(im) im._remove_method = self.images.remove self.stale = True return im def set_size_inches(self, w, h=None, forward=True): """ Set the figure size in inches. Call signatures:: fig.set_size_inches(w, h) # OR fig.set_size_inches((w, h)) Parameters ---------- w : (float, float) or float Width and height in inches (if height not specified as a separate argument) or width. h : float Height in inches. forward : bool, default: True If ``True``, the canvas size is automatically updated, e.g., you can resize the figure window from the shell. See Also -------- matplotlib.figure.Figure.get_size_inches matplotlib.figure.Figure.set_figwidth matplotlib.figure.Figure.set_figheight Notes ----- To transform from pixels to inches divide by `Figure.dpi`. """ if h is None: # Got called with a single pair as argument. w, h = w size = np.array([w, h]) if not np.isfinite(size).all() or (size < 0).any(): raise ValueError(f'figure size must be positive finite not {size}') self.bbox_inches.p1 = size if forward: manager = self.canvas.manager if manager is not None: manager.resize(*(size * self.dpi).astype(int)) self.stale = True def get_size_inches(self): """ Return the current size of the figure in inches. Returns ------- ndarray The size (width, height) of the figure in inches. See Also -------- matplotlib.figure.Figure.set_size_inches matplotlib.figure.Figure.get_figwidth matplotlib.figure.Figure.get_figheight Notes ----- The size in pixels can be obtained by multiplying with `Figure.dpi`. """ return np.array(self.bbox_inches.p1) def get_figwidth(self): """Return the figure width in inches.""" return self.bbox_inches.width def get_figheight(self): """Return the figure height in inches.""" return self.bbox_inches.height def get_dpi(self): """Return the resolution in dots per inch as a float.""" return self.dpi def set_dpi(self, val): """ Set the resolution of the figure in dots-per-inch. Parameters ---------- val : float """ self.dpi = val self.stale = True def set_figwidth(self, val, forward=True): """ Set the width of the figure in inches. Parameters ---------- val : float forward : bool See `set_size_inches`. See Also -------- matplotlib.figure.Figure.set_figheight matplotlib.figure.Figure.set_size_inches """ self.set_size_inches(val, self.get_figheight(), forward=forward) def set_figheight(self, val, forward=True): """ Set the height of the figure in inches. Parameters ---------- val : float forward : bool See `set_size_inches`. See Also -------- matplotlib.figure.Figure.set_figwidth matplotlib.figure.Figure.set_size_inches """ self.set_size_inches(self.get_figwidth(), val, forward=forward) def clear(self, keep_observers=False): # docstring inherited super().clear(keep_observers=keep_observers) # FigureBase.clear does not clear toolbars, as # only Figure can have toolbars toolbar = self.canvas.toolbar if toolbar is not None: toolbar.update() def draw(self, renderer): # docstring inherited # draw the figure bounding box, perhaps none for white figure if not self.get_visible(): return artists = self._get_draw_artists(renderer) try: renderer.open_group('figure', gid=self.get_gid()) if self.axes and self.get_layout_engine() is not None: try: self.get_layout_engine().execute(self) except ValueError: pass # ValueError can occur when resizing a window. self.patch.draw(renderer) mimage._draw_list_compositing_images( renderer, self, artists, self.suppressComposite) for sfig in self.subfigs: sfig.draw(renderer) renderer.close_group('figure') finally: self.stale = False DrawEvent("draw_event", self.canvas, renderer)._process() def draw_without_rendering(self): """ Draw the figure with no output. Useful to get the final size of artists that require a draw before their size is known (e.g. text). """ renderer = _get_renderer(self) with renderer._draw_disabled(): self.draw(renderer) def draw_artist(self, a): """ Draw `.Artist` *a* only. """ a.draw(self.canvas.get_renderer()) def __getstate__(self): state = super().__getstate__() # The canvas cannot currently be pickled, but this has the benefit # of meaning that a figure can be detached from one canvas, and # re-attached to another. state.pop("canvas") # discard any changes to the dpi due to pixel ratio changes state["_dpi"] = state.get('_original_dpi', state['_dpi']) # add version information to the state state['__mpl_version__'] = mpl.__version__ # check whether the figure manager (if any) is registered with pyplot from matplotlib import _pylab_helpers if self.canvas.manager in _pylab_helpers.Gcf.figs.values(): state['_restore_to_pylab'] = True return state def __setstate__(self, state): version = state.pop('__mpl_version__') restore_to_pylab = state.pop('_restore_to_pylab', False) if version != mpl.__version__: _api.warn_external( f"This figure was saved with matplotlib version {version} and " f"is unlikely to function correctly.") self.__dict__ = state # re-initialise some of the unstored state information FigureCanvasBase(self) # Set self.canvas. if restore_to_pylab: # lazy import to avoid circularity import matplotlib.pyplot as plt import matplotlib._pylab_helpers as pylab_helpers allnums = plt.get_fignums() num = max(allnums) + 1 if allnums else 1 backend = plt._get_backend_mod() mgr = backend.new_figure_manager_given_figure(num, self) pylab_helpers.Gcf._set_new_active_manager(mgr) plt.draw_if_interactive() self.stale = True def add_axobserver(self, func): """Whenever the Axes state change, ``func(self)`` will be called.""" # Connect a wrapper lambda and not func itself, to avoid it being # weakref-collected. self._axobservers.connect("_axes_change_event", lambda arg: func(arg)) def savefig(self, fname, *, transparent=None, **kwargs): """ Save the current figure. Call signature:: savefig(fname, *, dpi='figure', format=None, metadata=None, bbox_inches=None, pad_inches=0.1, facecolor='auto', edgecolor='auto', backend=None, **kwargs ) The available output formats depend on the backend being used. Parameters ---------- fname : str or path-like or binary file-like A path, or a Python file-like object, or possibly some backend-dependent object such as `matplotlib.backends.backend_pdf.PdfPages`. If *format* is set, it determines the output format, and the file is saved as *fname*. Note that *fname* is used verbatim, and there is no attempt to make the extension, if any, of *fname* match *format*, and no extension is appended. If *format* is not set, then the format is inferred from the extension of *fname*, if there is one. If *format* is not set and *fname* has no extension, then the file is saved with :rc:`savefig.format` and the appropriate extension is appended to *fname*. Other Parameters ---------------- dpi : float or 'figure', default: :rc:`savefig.dpi` The resolution in dots per inch. If 'figure', use the figure's dpi value. format : str The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under *fname*. metadata : dict, optional Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend: - 'png' with Agg backend: See the parameter ``metadata`` of `~.FigureCanvasAgg.print_png`. - 'pdf' with pdf backend: See the parameter ``metadata`` of `~.backend_pdf.PdfPages`. - 'svg' with svg backend: See the parameter ``metadata`` of `~.FigureCanvasSVG.print_svg`. - 'eps' and 'ps' with PS backend: Only 'Creator' is supported. bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox` Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure. pad_inches : float, default: :rc:`savefig.pad_inches` Amount of padding around the figure when bbox_inches is 'tight'. facecolor : color or 'auto', default: :rc:`savefig.facecolor` The facecolor of the figure. If 'auto', use the current figure facecolor. edgecolor : color or 'auto', default: :rc:`savefig.edgecolor` The edgecolor of the figure. If 'auto', use the current figure edgecolor. backend : str, optional Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See :ref:`the-builtin-backends` for a list of valid backends for each file format. Custom backends can be referenced as "module://...". orientation : {'landscape', 'portrait'} Currently only supported by the postscript backend. papertype : str One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output. transparent : bool If *True*, the Axes patches will all be transparent; the Figure patch will also be transparent unless *facecolor* and/or *edgecolor* are specified via kwargs. If *False* has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the *facecolor* and/or *edgecolor* keyword arguments in which case those colors are used). The transparency of these patches will be restored to their original values upon exit of this function. This is useful, for example, for displaying a plot on top of a colored background on a web page. bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional A list of extra artists that will be considered when the tight bbox is calculated. pil_kwargs : dict, optional Additional keyword arguments that are passed to `PIL.Image.Image.save` when saving the figure. """ kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi']) if transparent is None: transparent = mpl.rcParams['savefig.transparent'] with ExitStack() as stack: if transparent: kwargs.setdefault('facecolor', 'none') kwargs.setdefault('edgecolor', 'none') for ax in self.axes: stack.enter_context( ax.patch._cm_set(facecolor='none', edgecolor='none')) self.canvas.print_figure(fname, **kwargs) def ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE): """ Blocking call to interact with a figure. Wait until the user clicks *n* times on the figure, and return the coordinates of each click in a list. There are three possible interactions: - Add a point. - Remove the most recently added point. - Stop the interaction and return the points added so far. The actions are assigned to mouse buttons via the arguments *mouse_add*, *mouse_pop* and *mouse_stop*. Parameters ---------- n : int, default: 1 Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually. timeout : float, default: 30 seconds Number of seconds to wait before timing out. If zero or negative will never time out. show_clicks : bool, default: True If True, show a red cross at the location of each click. mouse_add : `.MouseButton` or None, default: `.MouseButton.LEFT` Mouse button used to add points. mouse_pop : `.MouseButton` or None, default: `.MouseButton.RIGHT` Mouse button used to remove the most recently added point. mouse_stop : `.MouseButton` or None, default: `.MouseButton.MIDDLE` Mouse button used to stop input. Returns ------- list of tuples A list of the clicked (x, y) coordinates. Notes ----- The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right-clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point. """ clicks = [] marks = [] def handler(event): is_button = event.name == "button_press_event" is_key = event.name == "key_press_event" # Quit (even if not in infinite mode; this is consistent with # MATLAB and sometimes quite useful, but will require the user to # test how many points were actually returned before using data). if (is_button and event.button == mouse_stop or is_key and event.key in ["escape", "enter"]): self.canvas.stop_event_loop() # Pop last click. elif (is_button and event.button == mouse_pop or is_key and event.key in ["backspace", "delete"]): if clicks: clicks.pop() if show_clicks: marks.pop().remove() self.canvas.draw() # Add new click. elif (is_button and event.button == mouse_add # On macOS/gtk, some keys return None. or is_key and event.key is not None): if event.inaxes: clicks.append((event.xdata, event.ydata)) _log.info("input %i: %f, %f", len(clicks), event.xdata, event.ydata) if show_clicks: line = mpl.lines.Line2D([event.xdata], [event.ydata], marker="+", color="r") event.inaxes.add_line(line) marks.append(line) self.canvas.draw() if len(clicks) == n and n > 0: self.canvas.stop_event_loop() _blocking_input.blocking_input_loop( self, ["button_press_event", "key_press_event"], timeout, handler) # Cleanup. for mark in marks: mark.remove() self.canvas.draw() return clicks def waitforbuttonpress(self, timeout=-1): """ Blocking call to interact with the figure. Wait for user input and return True if a key was pressed, False if a mouse button was pressed and None if no input was given within *timeout* seconds. Negative values deactivate *timeout*. """ event = None def handler(ev): nonlocal event event = ev self.canvas.stop_event_loop() _blocking_input.blocking_input_loop( self, ["button_press_event", "key_press_event"], timeout, handler) return None if event is None else event.name == "key_press_event" def execute_constrained_layout(self, renderer=None): """ Use ``layoutgrid`` to determine pos positions within Axes. See also `.set_constrained_layout_pads`. Returns ------- layoutgrid : private debugging object """ if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): return None return self.get_layout_engine().execute(self) def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None): """ Adjust the padding between and around subplots. To exclude an artist on the Axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), set ``a.set_in_layout(False)`` for that artist. Parameters ---------- pad : float, default: 1.08 Padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad : float, default: *pad* Padding (height/width) between edges of adjacent subplots, as a fraction of the font size. rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1) A rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit. See Also -------- .Figure.set_layout_engine .pyplot.tight_layout """ # note that here we do not permanently set the figures engine to # tight_layout but rather just perform the layout in place and remove # any previous engines. engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) try: previous_engine = self.get_layout_engine() self.set_layout_engine(engine) engine.execute(self) if not isinstance(previous_engine, TightLayoutEngine) \ and previous_engine is not None: _api.warn_external('The figure layout has changed to tight') finally: self.set_layout_engine(None) The provided code snippet includes necessary dependencies for implementing the `imsave` function. Write a Python function `def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None, dpi=100, *, metadata=None, pil_kwargs=None)` to solve the following problem: Colormap and save an array as an image file. RGB(A) images are passed through. Single channel images will be colormapped according to *cmap* and *norm*. .. note:: If you want to save a single channel image as gray scale please use an image I/O library (such as pillow, tifffile, or imageio) directly. Parameters ---------- fname : str or path-like or file-like A path or a file-like object to store the image in. If *format* is not set, then the output format is inferred from the extension of *fname*, if any, and from :rc:`savefig.format` otherwise. If *format* is set, it determines the output format. arr : array-like The image data. The shape can be one of MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA). vmin, vmax : float, optional *vmin* and *vmax* set the color scaling for the image by fixing the values that map to the colormap color limits. If either *vmin* or *vmax* is None, that limit is determined from the *arr* min/max value. cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` A Colormap instance or registered colormap name. The colormap maps scalar data to colors. It is ignored for RGB(A) data. format : str, optional The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under *fname*. origin : {'upper', 'lower'}, default: :rc:`image.origin` Indicates whether the ``(0, 0)`` index of the array is in the upper left or lower left corner of the axes. dpi : float The DPI to store in the metadata of the file. This does not affect the resolution of the output image. Depending on file format, this may be rounded to the nearest integer. metadata : dict, optional Metadata in the image file. The supported keys depend on the output format, see the documentation of the respective backends for more information. pil_kwargs : dict, optional Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo' key is present, it completely overrides *metadata*, including the default 'Software' key. Here is the function: def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None, dpi=100, *, metadata=None, pil_kwargs=None): """ Colormap and save an array as an image file. RGB(A) images are passed through. Single channel images will be colormapped according to *cmap* and *norm*. .. note:: If you want to save a single channel image as gray scale please use an image I/O library (such as pillow, tifffile, or imageio) directly. Parameters ---------- fname : str or path-like or file-like A path or a file-like object to store the image in. If *format* is not set, then the output format is inferred from the extension of *fname*, if any, and from :rc:`savefig.format` otherwise. If *format* is set, it determines the output format. arr : array-like The image data. The shape can be one of MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA). vmin, vmax : float, optional *vmin* and *vmax* set the color scaling for the image by fixing the values that map to the colormap color limits. If either *vmin* or *vmax* is None, that limit is determined from the *arr* min/max value. cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` A Colormap instance or registered colormap name. The colormap maps scalar data to colors. It is ignored for RGB(A) data. format : str, optional The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under *fname*. origin : {'upper', 'lower'}, default: :rc:`image.origin` Indicates whether the ``(0, 0)`` index of the array is in the upper left or lower left corner of the axes. dpi : float The DPI to store in the metadata of the file. This does not affect the resolution of the output image. Depending on file format, this may be rounded to the nearest integer. metadata : dict, optional Metadata in the image file. The supported keys depend on the output format, see the documentation of the respective backends for more information. pil_kwargs : dict, optional Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo' key is present, it completely overrides *metadata*, including the default 'Software' key. """ from matplotlib.figure import Figure if isinstance(fname, os.PathLike): fname = os.fspath(fname) if format is None: format = (Path(fname).suffix[1:] if isinstance(fname, str) else mpl.rcParams["savefig.format"]).lower() if format in ["pdf", "ps", "eps", "svg"]: # Vector formats that are not handled by PIL. if pil_kwargs is not None: raise ValueError( f"Cannot use 'pil_kwargs' when saving to {format}") fig = Figure(dpi=dpi, frameon=False) fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin, resize=True) fig.savefig(fname, dpi=dpi, format=format, transparent=True, metadata=metadata) else: # Don't bother creating an image; this avoids rounding errors on the # size when dividing and then multiplying by dpi. if origin is None: origin = mpl.rcParams["image.origin"] if origin == "lower": arr = arr[::-1] if (isinstance(arr, memoryview) and arr.format == "B" and arr.ndim == 3 and arr.shape[-1] == 4): # Such an ``arr`` would also be handled fine by sm.to_rgba below # (after casting with asarray), but it is useful to special-case it # because that's what backend_agg passes, and can be in fact used # as is, saving a few operations. rgba = arr else: sm = cm.ScalarMappable(cmap=cmap) sm.set_clim(vmin, vmax) rgba = sm.to_rgba(arr, bytes=True) if pil_kwargs is None: pil_kwargs = {} else: # we modify this below, so make a copy (don't modify caller's dict) pil_kwargs = pil_kwargs.copy() pil_shape = (rgba.shape[1], rgba.shape[0]) image = PIL.Image.frombuffer( "RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1) if format == "png": # Only use the metadata kwarg if pnginfo is not set, because the # semantics of duplicate keys in pnginfo is unclear. if "pnginfo" in pil_kwargs: if metadata: _api.warn_external("'metadata' is overridden by the " "'pnginfo' entry in 'pil_kwargs'.") else: metadata = { "Software": (f"Matplotlib version{mpl.__version__}, " f"https://matplotlib.org/"), **(metadata if metadata is not None else {}), } pil_kwargs["pnginfo"] = pnginfo = PIL.PngImagePlugin.PngInfo() for k, v in metadata.items(): if v is not None: pnginfo.add_text(k, v) if format in ["jpg", "jpeg"]: format = "jpeg" # Pillow doesn't recognize "jpg". facecolor = mpl.rcParams["savefig.facecolor"] if cbook._str_equal(facecolor, "auto"): facecolor = mpl.rcParams["figure.facecolor"] color = tuple(int(x * 255) for x in mcolors.to_rgb(facecolor)) background = PIL.Image.new("RGB", pil_shape, color) background.paste(image, image) image = background pil_kwargs.setdefault("format", format) pil_kwargs.setdefault("dpi", (dpi, dpi)) image.save(fname, **pil_kwargs)
Colormap and save an array as an image file. RGB(A) images are passed through. Single channel images will be colormapped according to *cmap* and *norm*. .. note:: If you want to save a single channel image as gray scale please use an image I/O library (such as pillow, tifffile, or imageio) directly. Parameters ---------- fname : str or path-like or file-like A path or a file-like object to store the image in. If *format* is not set, then the output format is inferred from the extension of *fname*, if any, and from :rc:`savefig.format` otherwise. If *format* is set, it determines the output format. arr : array-like The image data. The shape can be one of MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA). vmin, vmax : float, optional *vmin* and *vmax* set the color scaling for the image by fixing the values that map to the colormap color limits. If either *vmin* or *vmax* is None, that limit is determined from the *arr* min/max value. cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` A Colormap instance or registered colormap name. The colormap maps scalar data to colors. It is ignored for RGB(A) data. format : str, optional The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under *fname*. origin : {'upper', 'lower'}, default: :rc:`image.origin` Indicates whether the ``(0, 0)`` index of the array is in the upper left or lower left corner of the axes. dpi : float The DPI to store in the metadata of the file. This does not affect the resolution of the output image. Depending on file format, this may be rounded to the nearest integer. metadata : dict, optional Metadata in the image file. The supported keys depend on the output format, see the documentation of the respective backends for more information. pil_kwargs : dict, optional Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo' key is present, it completely overrides *metadata*, including the default 'Software' key.
171,036
import math import os import logging from pathlib import Path import warnings import numpy as np import PIL.PngImagePlugin import matplotlib as mpl from matplotlib import _api, cbook, cm from matplotlib import _image from matplotlib._image import * import matplotlib.artist as martist from matplotlib.backend_bases import FigureCanvasBase import matplotlib.colors as mcolors from matplotlib.transforms import ( Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo, IdentityTransform, TransformedBbox) def imread(fname, format=None): """ Read an image from a file into an array. .. note:: This function exists for historical reasons. It is recommended to use `PIL.Image.open` instead for loading images. Parameters ---------- fname : str or file-like The image file to read: a filename, a URL or a file-like object opened in read-binary mode. Passing a URL is deprecated. Please open the URL for reading and pass the result to Pillow, e.g. with ``np.array(PIL.Image.open(urllib.request.urlopen(url)))``. format : str, optional The image file format assumed for reading the data. The image is loaded as a PNG file if *format* is set to "png", if *fname* is a path or opened file with a ".png" extension, or if it is a URL. In all other cases, *format* is ignored and the format is auto-detected by `PIL.Image.open`. Returns ------- `numpy.array` The image data. The returned array has shape - (M, N) for grayscale images. - (M, N, 3) for RGB images. - (M, N, 4) for RGBA images. PNG images are returned as float arrays (0-1). All other formats are returned as int arrays, with a bit depth determined by the file's contents. """ # hide imports to speed initial import on systems with slow linkers from urllib import parse if format is None: if isinstance(fname, str): parsed = parse.urlparse(fname) # If the string is a URL (Windows paths appear as if they have a # length-1 scheme), assume png. if len(parsed.scheme) > 1: ext = 'png' else: ext = Path(fname).suffix.lower()[1:] elif hasattr(fname, 'geturl'): # Returned by urlopen(). # We could try to parse the url's path and use the extension, but # returning png is consistent with the block above. Note that this # if clause has to come before checking for fname.name as # urlopen("file:///...") also has a name attribute (with the fixed # value "<urllib response>"). ext = 'png' elif hasattr(fname, 'name'): ext = Path(fname.name).suffix.lower()[1:] else: ext = 'png' else: ext = format img_open = ( PIL.PngImagePlugin.PngImageFile if ext == 'png' else PIL.Image.open) if isinstance(fname, str) and len(parse.urlparse(fname).scheme) > 1: # Pillow doesn't handle URLs directly. raise ValueError( "Please open the URL for reading and pass the " "result to Pillow, e.g. with " "``np.array(PIL.Image.open(urllib.request.urlopen(url)))``." ) with img_open(fname) as image: return (_pil_png_to_float_array(image) if isinstance(image, PIL.PngImagePlugin.PngImageFile) else pil_to_array(image)) class FigureCanvasBase: """ The canvas the figure renders into. Attributes ---------- figure : `matplotlib.figure.Figure` A high-level figure instance. """ # Set to one of {"qt", "gtk3", "gtk4", "wx", "tk", "macosx"} if an # interactive framework is required, or None otherwise. required_interactive_framework = None # The manager class instantiated by new_manager. # (This is defined as a classproperty because the manager class is # currently defined *after* the canvas class, but one could also assign # ``FigureCanvasBase.manager_class = FigureManagerBase`` # after defining both classes.) manager_class = _api.classproperty(lambda cls: FigureManagerBase) events = [ 'resize_event', 'draw_event', 'key_press_event', 'key_release_event', 'button_press_event', 'button_release_event', 'scroll_event', 'motion_notify_event', 'pick_event', 'figure_enter_event', 'figure_leave_event', 'axes_enter_event', 'axes_leave_event', 'close_event' ] fixed_dpi = None filetypes = _default_filetypes def supports_blit(cls): """If this Canvas sub-class supports blitting.""" return (hasattr(cls, "copy_from_bbox") and hasattr(cls, "restore_region")) def __init__(self, figure=None): from matplotlib.figure import Figure self._fix_ipython_backend2gui() self._is_idle_drawing = True self._is_saving = False if figure is None: figure = Figure() figure.set_canvas(self) self.figure = figure self.manager = None self.widgetlock = widgets.LockDraw() self._button = None # the button pressed self._key = None # the key pressed self._lastx, self._lasty = None, None self.mouse_grabber = None # the Axes currently grabbing mouse self.toolbar = None # NavigationToolbar2 will set me self._is_idle_drawing = False # We don't want to scale up the figure DPI more than once. figure._original_dpi = figure.dpi self._device_pixel_ratio = 1 super().__init__() # Typically the GUI widget init (if any). callbacks = property(lambda self: self.figure._canvas_callbacks) button_pick_id = property(lambda self: self.figure._button_pick_id) scroll_pick_id = property(lambda self: self.figure._scroll_pick_id) def _fix_ipython_backend2gui(cls): # Fix hard-coded module -> toolkit mapping in IPython (used for # `ipython --auto`). This cannot be done at import time due to # ordering issues, so we do it when creating a canvas, and should only # be done once per class (hence the `lru_cache(1)`). if sys.modules.get("IPython") is None: return import IPython ip = IPython.get_ipython() if not ip: return from IPython.core import pylabtools as pt if (not hasattr(pt, "backend2gui") or not hasattr(ip, "enable_matplotlib")): # In case we ever move the patch to IPython and remove these APIs, # don't break on our side. return backend2gui_rif = { "qt": "qt", "gtk3": "gtk3", "gtk4": "gtk4", "wx": "wx", "macosx": "osx", }.get(cls.required_interactive_framework) if backend2gui_rif: if _is_non_interactive_terminal_ipython(ip): ip.enable_gui(backend2gui_rif) def new_manager(cls, figure, num): """ Create a new figure manager for *figure*, using this canvas class. Notes ----- This method should not be reimplemented in subclasses. If custom manager creation logic is needed, please reimplement ``FigureManager.create_with_canvas``. """ return cls.manager_class.create_with_canvas(cls, figure, num) def _idle_draw_cntx(self): self._is_idle_drawing = True try: yield finally: self._is_idle_drawing = False def is_saving(self): """ Return whether the renderer is in the process of saving to a file, rather than rendering for an on-screen buffer. """ return self._is_saving def pick(self, mouseevent): if not self.widgetlock.locked(): self.figure.pick(mouseevent) def blit(self, bbox=None): """Blit the canvas in bbox (default entire canvas).""" def resize(self, w, h): """ UNUSED: Set the canvas size in pixels. Certain backends may implement a similar method internally, but this is not a requirement of, nor is it used by, Matplotlib itself. """ # The entire method is actually deprecated, but we allow pass-through # to a parent class to support e.g. QWidget.resize. if hasattr(super(), "resize"): return super().resize(w, h) else: _api.warn_deprecated("3.6", name="resize", obj_type="method", alternative="FigureManagerBase.resize") "callbacks.process('draw_event', DrawEvent(...))")) def draw_event(self, renderer): """Pass a `DrawEvent` to all functions connected to ``draw_event``.""" s = 'draw_event' event = DrawEvent(s, self, renderer) self.callbacks.process(s, event) "callbacks.process('resize_event', ResizeEvent(...))")) def resize_event(self): """ Pass a `ResizeEvent` to all functions connected to ``resize_event``. """ s = 'resize_event' event = ResizeEvent(s, self) self.callbacks.process(s, event) self.draw_idle() "callbacks.process('close_event', CloseEvent(...))")) def close_event(self, guiEvent=None): """ Pass a `CloseEvent` to all functions connected to ``close_event``. """ s = 'close_event' try: event = CloseEvent(s, self, guiEvent=guiEvent) self.callbacks.process(s, event) except (TypeError, AttributeError): pass # Suppress the TypeError when the python session is being killed. # It may be that a better solution would be a mechanism to # disconnect all callbacks upon shutdown. # AttributeError occurs on OSX with qt4agg upon exiting # with an open window; 'callbacks' attribute no longer exists. "callbacks.process('key_press_event', KeyEvent(...))")) def key_press_event(self, key, guiEvent=None): """ Pass a `KeyEvent` to all functions connected to ``key_press_event``. """ self._key = key s = 'key_press_event' event = KeyEvent( s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event) "callbacks.process('key_release_event', KeyEvent(...))")) def key_release_event(self, key, guiEvent=None): """ Pass a `KeyEvent` to all functions connected to ``key_release_event``. """ s = 'key_release_event' event = KeyEvent( s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event) self._key = None "callbacks.process('pick_event', PickEvent(...))")) def pick_event(self, mouseevent, artist, **kwargs): """ Callback processing for pick events. This method will be called by artists who are picked and will fire off `PickEvent` callbacks registered listeners. Note that artists are not pickable by default (see `.Artist.set_picker`). """ s = 'pick_event' event = PickEvent(s, self, mouseevent, artist, guiEvent=mouseevent.guiEvent, **kwargs) self.callbacks.process(s, event) "callbacks.process('scroll_event', MouseEvent(...))")) def scroll_event(self, x, y, step, guiEvent=None): """ Callback processing for scroll events. Backend derived classes should call this function on any scroll wheel event. (*x*, *y*) are the canvas coords ((0, 0) is lower left). button and key are as defined in `MouseEvent`. This method will call all functions connected to the 'scroll_event' with a `MouseEvent` instance. """ if step >= 0: self._button = 'up' else: self._button = 'down' s = 'scroll_event' mouseevent = MouseEvent(s, self, x, y, self._button, self._key, step=step, guiEvent=guiEvent) self.callbacks.process(s, mouseevent) "callbacks.process('button_press_event', MouseEvent(...))")) def button_press_event(self, x, y, button, dblclick=False, guiEvent=None): """ Callback processing for mouse button press events. Backend derived classes should call this function on any mouse button press. (*x*, *y*) are the canvas coords ((0, 0) is lower left). button and key are as defined in `MouseEvent`. This method will call all functions connected to the 'button_press_event' with a `MouseEvent` instance. """ self._button = button s = 'button_press_event' mouseevent = MouseEvent(s, self, x, y, button, self._key, dblclick=dblclick, guiEvent=guiEvent) self.callbacks.process(s, mouseevent) "callbacks.process('button_release_event', MouseEvent(...))")) def button_release_event(self, x, y, button, guiEvent=None): """ Callback processing for mouse button release events. Backend derived classes should call this function on any mouse button release. This method will call all functions connected to the 'button_release_event' with a `MouseEvent` instance. Parameters ---------- x : float The canvas coordinates where 0=left. y : float The canvas coordinates where 0=bottom. guiEvent The native UI event that generated the Matplotlib event. """ s = 'button_release_event' event = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent) self.callbacks.process(s, event) self._button = None # Also remove _lastx, _lasty when this goes away. "callbacks.process('motion_notify_event', MouseEvent(...))")) def motion_notify_event(self, x, y, guiEvent=None): """ Callback processing for mouse movement events. Backend derived classes should call this function on any motion-notify-event. This method will call all functions connected to the 'motion_notify_event' with a `MouseEvent` instance. Parameters ---------- x : float The canvas coordinates where 0=left. y : float The canvas coordinates where 0=bottom. guiEvent The native UI event that generated the Matplotlib event. """ self._lastx, self._lasty = x, y s = 'motion_notify_event' event = MouseEvent(s, self, x, y, self._button, self._key, guiEvent=guiEvent) self.callbacks.process(s, event) "callbacks.process('leave_notify_event', LocationEvent(...))")) def leave_notify_event(self, guiEvent=None): """ Callback processing for the mouse cursor leaving the canvas. Backend derived classes should call this function when leaving canvas. Parameters ---------- guiEvent The native UI event that generated the Matplotlib event. """ self.callbacks.process('figure_leave_event', LocationEvent.lastevent) LocationEvent.lastevent = None self._lastx, self._lasty = None, None "callbacks.process('enter_notify_event', LocationEvent(...))")) def enter_notify_event(self, guiEvent=None, *, xy): """ Callback processing for the mouse cursor entering the canvas. Backend derived classes should call this function when entering canvas. Parameters ---------- guiEvent The native UI event that generated the Matplotlib event. xy : (float, float) The coordinate location of the pointer when the canvas is entered. """ self._lastx, self._lasty = x, y = xy event = LocationEvent('figure_enter_event', self, x, y, guiEvent) self.callbacks.process('figure_enter_event', event) def inaxes(self, xy): """ Return the topmost visible `~.axes.Axes` containing the point *xy*. Parameters ---------- xy : (float, float) (x, y) pixel positions from left/bottom of the canvas. Returns ------- `~matplotlib.axes.Axes` or None The topmost visible Axes containing the point, or None if there is no Axes at the point. """ axes_list = [a for a in self.figure.get_axes() if a.patch.contains_point(xy) and a.get_visible()] if axes_list: axes = cbook._topmost_artist(axes_list) else: axes = None return axes def grab_mouse(self, ax): """ Set the child `~.axes.Axes` which is grabbing the mouse events. Usually called by the widgets themselves. It is an error to call this if the mouse is already grabbed by another Axes. """ if self.mouse_grabber not in (None, ax): raise RuntimeError("Another Axes already grabs mouse input") self.mouse_grabber = ax def release_mouse(self, ax): """ Release the mouse grab held by the `~.axes.Axes` *ax*. Usually called by the widgets. It is ok to call this even if *ax* doesn't have the mouse grab currently. """ if self.mouse_grabber is ax: self.mouse_grabber = None def set_cursor(self, cursor): """ Set the current cursor. This may have no effect if the backend does not display anything. If required by the backend, this method should trigger an update in the backend event loop after the cursor is set, as this method may be called e.g. before a long-running task during which the GUI is not updated. Parameters ---------- cursor : `.Cursors` The cursor to display over the canvas. Note: some backends may change the cursor for the entire window. """ def draw(self, *args, **kwargs): """ Render the `.Figure`. This method must walk the artist tree, even if no output is produced, because it triggers deferred work that users may want to access before saving output to disk. For example computing limits, auto-limits, and tick values. """ def draw_idle(self, *args, **kwargs): """ Request a widget redraw once control returns to the GUI event loop. Even if multiple calls to `draw_idle` occur before control returns to the GUI event loop, the figure will only be rendered once. Notes ----- Backends may choose to override the method and implement their own strategy to prevent multiple renderings. """ if not self._is_idle_drawing: with self._idle_draw_cntx(): self.draw(*args, **kwargs) def device_pixel_ratio(self): """ The ratio of physical to logical pixels used for the canvas on screen. By default, this is 1, meaning physical and logical pixels are the same size. Subclasses that support High DPI screens may set this property to indicate that said ratio is different. All Matplotlib interaction, unless working directly with the canvas, remains in logical pixels. """ return self._device_pixel_ratio def _set_device_pixel_ratio(self, ratio): """ Set the ratio of physical to logical pixels used for the canvas. Subclasses that support High DPI screens can set this property to indicate that said ratio is different. The canvas itself will be created at the physical size, while the client side will use the logical size. Thus the DPI of the Figure will change to be scaled by this ratio. Implementations that support High DPI screens should use physical pixels for events so that transforms back to Axes space are correct. By default, this is 1, meaning physical and logical pixels are the same size. Parameters ---------- ratio : float The ratio of logical to physical pixels used for the canvas. Returns ------- bool Whether the ratio has changed. Backends may interpret this as a signal to resize the window, repaint the canvas, or change any other relevant properties. """ if self._device_pixel_ratio == ratio: return False # In cases with mixed resolution displays, we need to be careful if the # device pixel ratio changes - in this case we need to resize the # canvas accordingly. Some backends provide events that indicate a # change in DPI, but those that don't will update this before drawing. dpi = ratio * self.figure._original_dpi self.figure._set_dpi(dpi, forward=False) self._device_pixel_ratio = ratio return True def get_width_height(self, *, physical=False): """ Return the figure width and height in integral points or pixels. When the figure is used on High DPI screens (and the backend supports it), the truncation to integers occurs after scaling by the device pixel ratio. Parameters ---------- physical : bool, default: False Whether to return true physical pixels or logical pixels. Physical pixels may be used by backends that support HiDPI, but still configure the canvas using its actual size. Returns ------- width, height : int The size of the figure, in points or pixels, depending on the backend. """ return tuple(int(size / (1 if physical else self.device_pixel_ratio)) for size in self.figure.bbox.max) def get_supported_filetypes(cls): """Return dict of savefig file formats supported by this backend.""" return cls.filetypes def get_supported_filetypes_grouped(cls): """ Return a dict of savefig file formats supported by this backend, where the keys are a file type name, such as 'Joint Photographic Experts Group', and the values are a list of filename extensions used for that filetype, such as ['jpg', 'jpeg']. """ groupings = {} for ext, name in cls.filetypes.items(): groupings.setdefault(name, []).append(ext) groupings[name].sort() return groupings def _switch_canvas_and_return_print_method(self, fmt, backend=None): """ Context manager temporarily setting the canvas for saving the figure:: with canvas._switch_canvas_and_return_print_method(fmt, backend) \\ as print_method: # ``print_method`` is a suitable ``print_{fmt}`` method, and # the figure's canvas is temporarily switched to the method's # canvas within the with... block. ``print_method`` is also # wrapped to suppress extra kwargs passed by ``print_figure``. Parameters ---------- fmt : str If *backend* is None, then determine a suitable canvas class for saving to format *fmt* -- either the current canvas class, if it supports *fmt*, or whatever `get_registered_canvas_class` returns; switch the figure canvas to that canvas class. backend : str or None, default: None If not None, switch the figure canvas to the ``FigureCanvas`` class of the given backend. """ canvas = None if backend is not None: # Return a specific canvas class, if requested. canvas_class = ( importlib.import_module(cbook._backend_module_name(backend)) .FigureCanvas) if not hasattr(canvas_class, f"print_{fmt}"): raise ValueError( f"The {backend!r} backend does not support {fmt} output") elif hasattr(self, f"print_{fmt}"): # Return the current canvas if it supports the requested format. canvas = self canvas_class = None # Skip call to switch_backends. else: # Return a default canvas for the requested format, if it exists. canvas_class = get_registered_canvas_class(fmt) if canvas_class: canvas = self.switch_backends(canvas_class) if canvas is None: raise ValueError( "Format {!r} is not supported (supported formats: {})".format( fmt, ", ".join(sorted(self.get_supported_filetypes())))) meth = getattr(canvas, f"print_{fmt}") mod = (meth.func.__module__ if hasattr(meth, "func") # partialmethod, e.g. backend_wx. else meth.__module__) if mod.startswith(("matplotlib.", "mpl_toolkits.")): optional_kws = { # Passed by print_figure for other renderers. "dpi", "facecolor", "edgecolor", "orientation", "bbox_inches_restore"} skip = optional_kws - {*inspect.signature(meth).parameters} print_method = functools.wraps(meth)(lambda *args, **kwargs: meth( *args, **{k: v for k, v in kwargs.items() if k not in skip})) else: # Let third-parties do as they see fit. print_method = meth try: yield print_method finally: self.figure.canvas = self def print_figure( self, filename, dpi=None, facecolor=None, edgecolor=None, orientation='portrait', format=None, *, bbox_inches=None, pad_inches=None, bbox_extra_artists=None, backend=None, **kwargs): """ Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you'll probably want to override this on hardcopy. Parameters ---------- filename : str or path-like or file-like The file where the figure is saved. dpi : float, default: :rc:`savefig.dpi` The dots per inch to save the figure in. facecolor : color or 'auto', default: :rc:`savefig.facecolor` The facecolor of the figure. If 'auto', use the current figure facecolor. edgecolor : color or 'auto', default: :rc:`savefig.edgecolor` The edgecolor of the figure. If 'auto', use the current figure edgecolor. orientation : {'landscape', 'portrait'}, default: 'portrait' Only currently applies to PostScript printing. format : str, optional Force a specific file format. If not given, the format is inferred from the *filename* extension, and if that fails from :rc:`savefig.format`. bbox_inches : 'tight' or `.Bbox`, default: :rc:`savefig.bbox` Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure. pad_inches : float, default: :rc:`savefig.pad_inches` Amount of padding around the figure when *bbox_inches* is 'tight'. bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional A list of extra artists that will be considered when the tight bbox is calculated. backend : str, optional Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See :ref:`the-builtin-backends` for a list of valid backends for each file format. Custom backends can be referenced as "module://...". """ if format is None: # get format from filename, or from backend's default filetype if isinstance(filename, os.PathLike): filename = os.fspath(filename) if isinstance(filename, str): format = os.path.splitext(filename)[1][1:] if format is None or format == '': format = self.get_default_filetype() if isinstance(filename, str): filename = filename.rstrip('.') + '.' + format format = format.lower() if dpi is None: dpi = rcParams['savefig.dpi'] if dpi == 'figure': dpi = getattr(self.figure, '_original_dpi', self.figure.dpi) # Remove the figure manager, if any, to avoid resizing the GUI widget. with cbook._setattr_cm(self, manager=None), \ self._switch_canvas_and_return_print_method(format, backend) \ as print_method, \ cbook._setattr_cm(self.figure, dpi=dpi), \ cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1), \ cbook._setattr_cm(self.figure.canvas, _is_saving=True), \ ExitStack() as stack: for prop in ["facecolor", "edgecolor"]: color = locals()[prop] if color is None: color = rcParams[f"savefig.{prop}"] if not cbook._str_equal(color, "auto"): stack.enter_context(self.figure._cm_set(**{prop: color})) if bbox_inches is None: bbox_inches = rcParams['savefig.bbox'] if (self.figure.get_layout_engine() is not None or bbox_inches == "tight"): # we need to trigger a draw before printing to make sure # CL works. "tight" also needs a draw to get the right # locations: renderer = _get_renderer( self.figure, functools.partial( print_method, orientation=orientation) ) with getattr(renderer, "_draw_disabled", nullcontext)(): self.figure.draw(renderer) if bbox_inches: if bbox_inches == "tight": bbox_inches = self.figure.get_tightbbox( renderer, bbox_extra_artists=bbox_extra_artists) if pad_inches is None: pad_inches = rcParams['savefig.pad_inches'] bbox_inches = bbox_inches.padded(pad_inches) # call adjust_bbox to save only the given area restore_bbox = _tight_bbox.adjust_bbox( self.figure, bbox_inches, self.figure.canvas.fixed_dpi) _bbox_inches_restore = (bbox_inches, restore_bbox) else: _bbox_inches_restore = None # we have already done layout above, so turn it off: stack.enter_context(self.figure._cm_set(layout_engine='none')) try: # _get_renderer may change the figure dpi (as vector formats # force the figure dpi to 72), so we need to set it again here. with cbook._setattr_cm(self.figure, dpi=dpi): result = print_method( filename, facecolor=facecolor, edgecolor=edgecolor, orientation=orientation, bbox_inches_restore=_bbox_inches_restore, **kwargs) finally: if bbox_inches and restore_bbox: restore_bbox() return result def get_default_filetype(cls): """ Return the default savefig file format as specified in :rc:`savefig.format`. The returned string does not include a period. This method is overridden in backends that only support a single file type. """ return rcParams['savefig.format'] def get_default_filename(self): """ Return a string, which includes extension, suitable for use as a default filename. """ basename = (self.manager.get_window_title() if self.manager is not None else '') basename = (basename or 'image').replace(' ', '_') filetype = self.get_default_filetype() filename = basename + '.' + filetype return filename def switch_backends(self, FigureCanvasClass): """ Instantiate an instance of FigureCanvasClass This is used for backend switching, e.g., to instantiate a FigureCanvasPS from a FigureCanvasGTK. Note, deep copying is not done, so any changes to one of the instances (e.g., setting figure size or line props), will be reflected in the other """ newCanvas = FigureCanvasClass(self.figure) newCanvas._is_saving = self._is_saving return newCanvas def mpl_connect(self, s, func): """ Bind function *func* to event *s*. Parameters ---------- s : str One of the following events ids: - 'button_press_event' - 'button_release_event' - 'draw_event' - 'key_press_event' - 'key_release_event' - 'motion_notify_event' - 'pick_event' - 'resize_event' - 'scroll_event' - 'figure_enter_event', - 'figure_leave_event', - 'axes_enter_event', - 'axes_leave_event' - 'close_event'. func : callable The callback function to be executed, which must have the signature:: def func(event: Event) -> Any For the location events (button and key press/release), if the mouse is over the Axes, the ``inaxes`` attribute of the event will be set to the `~matplotlib.axes.Axes` the event occurs is over, and additionally, the variables ``xdata`` and ``ydata`` attributes will be set to the mouse location in data coordinates. See `.KeyEvent` and `.MouseEvent` for more info. .. note:: If func is a method, this only stores a weak reference to the method. Thus, the figure does not influence the lifetime of the associated object. Usually, you want to make sure that the object is kept alive throughout the lifetime of the figure by holding a reference to it. Returns ------- cid A connection id that can be used with `.FigureCanvasBase.mpl_disconnect`. Examples -------- :: def on_press(event): print('you pressed', event.button, event.xdata, event.ydata) cid = canvas.mpl_connect('button_press_event', on_press) """ return self.callbacks.connect(s, func) def mpl_disconnect(self, cid): """ Disconnect the callback with id *cid*. Examples -------- :: cid = canvas.mpl_connect('button_press_event', on_press) # ... later canvas.mpl_disconnect(cid) """ return self.callbacks.disconnect(cid) # Internal subclasses can override _timer_cls instead of new_timer, though # this is not a public API for third-party subclasses. _timer_cls = TimerBase def new_timer(self, interval=None, callbacks=None): """ Create a new backend-specific subclass of `.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. Parameters ---------- interval : int Timer interval in milliseconds. callbacks : list[tuple[callable, tuple, dict]] Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. Callbacks which return ``False`` or ``0`` will be removed from the timer. Examples -------- >>> timer = fig.canvas.new_timer(callbacks=[(f1, (1,), {'a': 3})]) """ return self._timer_cls(interval=interval, callbacks=callbacks) def flush_events(self): """ Flush the GUI events for the figure. Interactive backends need to reimplement this method. """ def start_event_loop(self, timeout=0): """ Start a blocking event loop. Such an event loop is used by interactive functions, such as `~.Figure.ginput` and `~.Figure.waitforbuttonpress`, to wait for events. The event loop blocks until a callback function triggers `stop_event_loop`, or *timeout* is reached. If *timeout* is 0 or negative, never timeout. Only interactive backends need to reimplement this method and it relies on `flush_events` being properly implemented. Interactive backends should implement this in a more native way. """ if timeout <= 0: timeout = np.inf timestep = 0.01 counter = 0 self._looping = True while self._looping and counter * timestep < timeout: self.flush_events() time.sleep(timestep) counter += 1 def stop_event_loop(self): """ Stop the current blocking event loop. Interactive backends need to reimplement this to match `start_event_loop` """ self._looping = False class Figure(FigureBase): """ The top level container for all the plot elements. Attributes ---------- patch The `.Rectangle` instance representing the figure background patch. suppressComposite For multiple images, the figure will make composite images depending on the renderer option_image_nocomposite function. If *suppressComposite* is a boolean, this will override the renderer. """ # Remove the self._fig_callbacks properties on figure and subfigure # after the deprecation expires. callbacks = _api.deprecated( "3.6", alternative=("the 'resize_event' signal in " "Figure.canvas.callbacks") )(property(lambda self: self._fig_callbacks)) def __str__(self): return "Figure(%gx%g)" % tuple(self.bbox.size) def __repr__(self): return "<{clsname} size {h:g}x{w:g} with {naxes} Axes>".format( clsname=self.__class__.__name__, h=self.bbox.size[0], w=self.bbox.size[1], naxes=len(self.axes), ) def __init__(self, figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, # rc figure.subplot.* tight_layout=None, # rc figure.autolayout constrained_layout=None, # rc figure.constrained_layout.use *, layout=None, **kwargs ): """ Parameters ---------- figsize : 2-tuple of floats, default: :rc:`figure.figsize` Figure dimension ``(width, height)`` in inches. dpi : float, default: :rc:`figure.dpi` Dots per inch. facecolor : default: :rc:`figure.facecolor` The figure patch facecolor. edgecolor : default: :rc:`figure.edgecolor` The figure patch edge color. linewidth : float The linewidth of the frame (i.e. the edge linewidth of the figure patch). frameon : bool, default: :rc:`figure.frameon` If ``False``, suppress drawing the figure background patch. subplotpars : `SubplotParams` Subplot parameters. If not given, the default subplot parameters :rc:`figure.subplot.*` are used. tight_layout : bool or dict, default: :rc:`figure.autolayout` Whether to use the tight layout mechanism. See `.set_tight_layout`. .. admonition:: Discouraged The use of this parameter is discouraged. Please use ``layout='tight'`` instead for the common case of ``tight_layout=True`` and use `.set_tight_layout` otherwise. constrained_layout : bool, default: :rc:`figure.constrained_layout.use` This is equal to ``layout='constrained'``. .. admonition:: Discouraged The use of this parameter is discouraged. Please use ``layout='constrained'`` instead. 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 have significant performance penalties. - '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 :doc:`/tutorials/intermediate/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`. Other Parameters ---------------- **kwargs : `.Figure` properties, optional %(Figure:kwdoc)s """ super().__init__(**kwargs) self._layout_engine = None if layout is not None: if (tight_layout is not None): _api.warn_external( "The Figure parameters 'layout' and 'tight_layout' cannot " "be used together. Please use 'layout' only.") if (constrained_layout is not None): _api.warn_external( "The Figure parameters 'layout' and 'constrained_layout' " "cannot be used together. Please use 'layout' only.") self.set_layout_engine(layout=layout) elif tight_layout is not None: if constrained_layout is not None: _api.warn_external( "The Figure parameters 'tight_layout' and " "'constrained_layout' cannot be used together. Please use " "'layout' parameter") self.set_layout_engine(layout='tight') if isinstance(tight_layout, dict): self.get_layout_engine().set(**tight_layout) elif constrained_layout is not None: if isinstance(constrained_layout, dict): self.set_layout_engine(layout='constrained') self.get_layout_engine().set(**constrained_layout) elif constrained_layout: self.set_layout_engine(layout='constrained') else: # everything is None, so use default: self.set_layout_engine(layout=layout) self._fig_callbacks = cbook.CallbackRegistry(signals=["dpi_changed"]) # Callbacks traditionally associated with the canvas (and exposed with # a proxy property), but that actually need to be on the figure for # pickling. self._canvas_callbacks = cbook.CallbackRegistry( signals=FigureCanvasBase.events) connect = self._canvas_callbacks._connect_picklable self._mouse_key_ids = [ connect('key_press_event', backend_bases._key_handler), connect('key_release_event', backend_bases._key_handler), connect('key_release_event', backend_bases._key_handler), connect('button_press_event', backend_bases._mouse_handler), connect('button_release_event', backend_bases._mouse_handler), connect('scroll_event', backend_bases._mouse_handler), connect('motion_notify_event', backend_bases._mouse_handler), ] self._button_pick_id = connect('button_press_event', self.pick) self._scroll_pick_id = connect('scroll_event', self.pick) if figsize is None: figsize = mpl.rcParams['figure.figsize'] if dpi is None: dpi = mpl.rcParams['figure.dpi'] if facecolor is None: facecolor = mpl.rcParams['figure.facecolor'] if edgecolor is None: edgecolor = mpl.rcParams['figure.edgecolor'] if frameon is None: frameon = mpl.rcParams['figure.frameon'] if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any(): raise ValueError('figure size must be positive finite not ' f'{figsize}') self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) self.dpi_scale_trans = Affine2D().scale(dpi) # do not use property as it will trigger self._dpi = dpi self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans) self.figbbox = self.bbox self.transFigure = BboxTransformTo(self.bbox) self.transSubfigure = self.transFigure self.patch = Rectangle( xy=(0, 0), width=1, height=1, visible=frameon, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, # Don't let the figure patch influence bbox calculation. in_layout=False) self._set_artist_props(self.patch) self.patch.set_antialiased(False) FigureCanvasBase(self) # Set self.canvas. if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self._axstack = _AxesStack() # track all figure axes and current axes self.clear() def pick(self, mouseevent): if not self.canvas.widgetlock.locked(): super().pick(mouseevent) def _check_layout_engines_compat(self, old, new): """ Helper for set_layout engine If the figure has used the old engine and added a colorbar then the value of colorbar_gridspec must be the same on the new engine. """ if old is None or new is None: return True if old.colorbar_gridspec == new.colorbar_gridspec: return True # colorbar layout different, so check if any colorbars are on the # figure... for ax in self.axes: if hasattr(ax, '_colorbar'): # colorbars list themselves as a colorbar. return False return True def set_layout_engine(self, layout=None, **kwargs): """ Set the layout engine for this figure. Parameters ---------- layout: {'constrained', 'compressed', 'tight', 'none'} or \ `LayoutEngine` or None - 'constrained' will use `~.ConstrainedLayoutEngine` - 'compressed' will also use `~.ConstrainedLayoutEngine`, but with a correction that attempts to make a good layout for fixed-aspect ratio Axes. - 'tight' uses `~.TightLayoutEngine` - 'none' removes layout engine. If `None`, the behavior is controlled by :rc:`figure.autolayout` (which if `True` behaves as if 'tight' was passed) and :rc:`figure.constrained_layout.use` (which if `True` behaves as if 'constrained' was passed). If both are `True`, :rc:`figure.autolayout` takes priority. Users and libraries can define their own layout engines and pass the instance directly as well. kwargs: dict The keyword arguments are passed to the layout engine to set things like padding and margin sizes. Only used if *layout* is a string. """ if layout is None: if mpl.rcParams['figure.autolayout']: layout = 'tight' elif mpl.rcParams['figure.constrained_layout.use']: layout = 'constrained' else: self._layout_engine = None return if layout == 'tight': new_layout_engine = TightLayoutEngine(**kwargs) elif layout == 'constrained': new_layout_engine = ConstrainedLayoutEngine(**kwargs) elif layout == 'compressed': new_layout_engine = ConstrainedLayoutEngine(compress=True, **kwargs) elif layout == 'none': if self._layout_engine is not None: new_layout_engine = PlaceHolderLayoutEngine( self._layout_engine.adjust_compatible, self._layout_engine.colorbar_gridspec ) else: new_layout_engine = None elif isinstance(layout, LayoutEngine): new_layout_engine = layout else: raise ValueError(f"Invalid value for 'layout': {layout!r}") if self._check_layout_engines_compat(self._layout_engine, new_layout_engine): self._layout_engine = new_layout_engine else: raise RuntimeError('Colorbar layout of new layout engine not ' 'compatible with old engine, and a colorbar ' 'has been created. Engine not changed.') def get_layout_engine(self): return self._layout_engine # TODO: I'd like to dynamically add the _repr_html_ method # to the figure in the right context, but then IPython doesn't # use it, for some reason. def _repr_html_(self): # We can't use "isinstance" here, because then we'd end up importing # webagg unconditionally. if 'WebAgg' in type(self.canvas).__name__: from matplotlib.backends import backend_webagg return backend_webagg.ipython_inline_display(self) def show(self, warn=True): """ If using a GUI backend with pyplot, display the figure window. If the figure was not created using `~.pyplot.figure`, it will lack a `~.backend_bases.FigureManagerBase`, and this method will raise an AttributeError. .. warning:: This does not manage an GUI event loop. Consequently, the figure may only be shown briefly or not shown at all if you or your environment are not managing an event loop. Use cases for `.Figure.show` include running this from a GUI application (where there is persistently an event loop running) or from a shell, like IPython, that install an input hook to allow the interactive shell to accept input while the figure is also being shown and interactive. Some, but not all, GUI toolkits will register an input hook on import. See :ref:`cp_integration` for more details. If you're in a shell without input hook integration or executing a python script, you should use `matplotlib.pyplot.show` with ``block=True`` instead, which takes care of starting and running the event loop for you. Parameters ---------- warn : bool, default: True If ``True`` and we are not running headless (i.e. on Linux with an unset DISPLAY), issue warning when called on a non-GUI backend. """ if self.canvas.manager is None: raise AttributeError( "Figure.show works only for figures managed by pyplot, " "normally created by pyplot.figure()") try: self.canvas.manager.show() except NonGuiException as exc: if warn: _api.warn_external(str(exc)) def axes(self): """ List of Axes in the Figure. You can access and modify the Axes in the Figure through this list. Do not modify the list itself. Instead, use `~Figure.add_axes`, `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an Axes. Note: The `.Figure.axes` property and `~.Figure.get_axes` method are equivalent. """ return self._axstack.as_list() get_axes = axes.fget def _get_renderer(self): if hasattr(self.canvas, 'get_renderer'): return self.canvas.get_renderer() else: return _get_renderer(self) def _get_dpi(self): return self._dpi def _set_dpi(self, dpi, forward=True): """ Parameters ---------- dpi : float forward : bool Passed on to `~.Figure.set_size_inches` """ if dpi == self._dpi: # We don't want to cause undue events in backends. return self._dpi = dpi self.dpi_scale_trans.clear().scale(dpi) w, h = self.get_size_inches() self.set_size_inches(w, h, forward=forward) self._fig_callbacks.process('dpi_changed', self) dpi = property(_get_dpi, _set_dpi, doc="The resolution in dots per inch.") def get_tight_layout(self): """Return whether `.tight_layout` is called when drawing.""" return isinstance(self.get_layout_engine(), TightLayoutEngine) pending=True) def set_tight_layout(self, tight): """ [*Discouraged*] Set whether and how `.tight_layout` is called when drawing. .. admonition:: Discouraged This method is discouraged in favor of `~.set_layout_engine`. Parameters ---------- tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None If a bool, sets whether to call `.tight_layout` upon drawing. If ``None``, use :rc:`figure.autolayout` instead. If a dict, pass it as kwargs to `.tight_layout`, overriding the default paddings. """ if tight is None: tight = mpl.rcParams['figure.autolayout'] _tight = 'tight' if bool(tight) else 'none' _tight_parameters = tight if isinstance(tight, dict) else {} self.set_layout_engine(_tight, **_tight_parameters) self.stale = True def get_constrained_layout(self): """ Return whether constrained layout is being used. See :doc:`/tutorials/intermediate/constrainedlayout_guide`. """ return isinstance(self.get_layout_engine(), ConstrainedLayoutEngine) pending=True) def set_constrained_layout(self, constrained): """ [*Discouraged*] Set whether ``constrained_layout`` is used upon drawing. If None, :rc:`figure.constrained_layout.use` value will be used. When providing a dict containing the keys ``w_pad``, ``h_pad`` the default ``constrained_layout`` paddings will be overridden. These pads are in inches and default to 3.0/72.0. ``w_pad`` is the width padding and ``h_pad`` is the height padding. .. admonition:: Discouraged This method is discouraged in favor of `~.set_layout_engine`. Parameters ---------- constrained : bool or dict or None """ if constrained is None: constrained = mpl.rcParams['figure.constrained_layout.use'] _constrained = 'constrained' if bool(constrained) else 'none' _parameters = constrained if isinstance(constrained, dict) else {} self.set_layout_engine(_constrained, **_parameters) self.stale = True "3.6", alternative="figure.get_layout_engine().set()", pending=True) def set_constrained_layout_pads(self, **kwargs): """ Set padding for ``constrained_layout``. Tip: The parameters can be passed from a dictionary by using ``fig.set_constrained_layout(**pad_dict)``. See :doc:`/tutorials/intermediate/constrainedlayout_guide`. Parameters ---------- w_pad : float, default: :rc:`figure.constrained_layout.w_pad` Width padding in inches. This is the pad around Axes and is meant to make sure there is enough room for fonts to look good. Defaults to 3 pts = 0.04167 inches h_pad : float, default: :rc:`figure.constrained_layout.h_pad` Height padding in inches. Defaults to 3 pts. wspace : float, default: :rc:`figure.constrained_layout.wspace` Width padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being w_pad + wspace. hspace : float, default: :rc:`figure.constrained_layout.hspace` Height padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being h_pad + hspace. """ if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): self.get_layout_engine().set(**kwargs) pending=True) def get_constrained_layout_pads(self, relative=False): """ Get padding for ``constrained_layout``. Returns a list of ``w_pad, h_pad`` in inches and ``wspace`` and ``hspace`` as fractions of the subplot. All values are None if ``constrained_layout`` is not used. See :doc:`/tutorials/intermediate/constrainedlayout_guide`. Parameters ---------- relative : bool If `True`, then convert from inches to figure relative. """ if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): return None, None, None, None info = self.get_layout_engine().get_info() w_pad = info['w_pad'] h_pad = info['h_pad'] wspace = info['wspace'] hspace = info['hspace'] if relative and (w_pad is not None or h_pad is not None): renderer = self._get_renderer() dpi = renderer.dpi w_pad = w_pad * dpi / renderer.width h_pad = h_pad * dpi / renderer.height return w_pad, h_pad, wspace, hspace def set_canvas(self, canvas): """ Set the canvas that contains the figure Parameters ---------- canvas : FigureCanvas """ self.canvas = canvas def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs): """ Add a non-resampled image to the figure. The image is attached to the lower or upper left corner depending on *origin*. Parameters ---------- X The image data. This is an array of one of the following shapes: - (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. xo, yo : int The *x*/*y* image offset in pixels. alpha : None or float The alpha blending value. %(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). origin : {'upper', 'lower'}, default: :rc:`image.origin` Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes. resize : bool If *True*, resize the figure to match the given image size. Returns ------- `matplotlib.image.FigureImage` Other Parameters ---------------- **kwargs Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`. Notes ----- figimage complements the Axes image (`~matplotlib.axes.Axes.imshow`) which will be resampled to fit the current Axes. If you want a resampled image to fill the entire figure, you can define an `~matplotlib.axes.Axes` with extent [0, 0, 1, 1]. Examples -------- :: f = plt.figure() nx = int(f.get_figwidth() * f.dpi) ny = int(f.get_figheight() * f.dpi) data = np.random.random((ny, nx)) f.figimage(data) plt.show() """ if resize: dpi = self.get_dpi() figsize = [x / dpi for x in (X.shape[1], X.shape[0])] self.set_size_inches(figsize, forward=True) im = mimage.FigureImage(self, cmap=cmap, norm=norm, offsetx=xo, offsety=yo, origin=origin, **kwargs) im.stale_callback = _stale_figure_callback im.set_array(X) im.set_alpha(alpha) if norm is None: im.set_clim(vmin, vmax) self.images.append(im) im._remove_method = self.images.remove self.stale = True return im def set_size_inches(self, w, h=None, forward=True): """ Set the figure size in inches. Call signatures:: fig.set_size_inches(w, h) # OR fig.set_size_inches((w, h)) Parameters ---------- w : (float, float) or float Width and height in inches (if height not specified as a separate argument) or width. h : float Height in inches. forward : bool, default: True If ``True``, the canvas size is automatically updated, e.g., you can resize the figure window from the shell. See Also -------- matplotlib.figure.Figure.get_size_inches matplotlib.figure.Figure.set_figwidth matplotlib.figure.Figure.set_figheight Notes ----- To transform from pixels to inches divide by `Figure.dpi`. """ if h is None: # Got called with a single pair as argument. w, h = w size = np.array([w, h]) if not np.isfinite(size).all() or (size < 0).any(): raise ValueError(f'figure size must be positive finite not {size}') self.bbox_inches.p1 = size if forward: manager = self.canvas.manager if manager is not None: manager.resize(*(size * self.dpi).astype(int)) self.stale = True def get_size_inches(self): """ Return the current size of the figure in inches. Returns ------- ndarray The size (width, height) of the figure in inches. See Also -------- matplotlib.figure.Figure.set_size_inches matplotlib.figure.Figure.get_figwidth matplotlib.figure.Figure.get_figheight Notes ----- The size in pixels can be obtained by multiplying with `Figure.dpi`. """ return np.array(self.bbox_inches.p1) def get_figwidth(self): """Return the figure width in inches.""" return self.bbox_inches.width def get_figheight(self): """Return the figure height in inches.""" return self.bbox_inches.height def get_dpi(self): """Return the resolution in dots per inch as a float.""" return self.dpi def set_dpi(self, val): """ Set the resolution of the figure in dots-per-inch. Parameters ---------- val : float """ self.dpi = val self.stale = True def set_figwidth(self, val, forward=True): """ Set the width of the figure in inches. Parameters ---------- val : float forward : bool See `set_size_inches`. See Also -------- matplotlib.figure.Figure.set_figheight matplotlib.figure.Figure.set_size_inches """ self.set_size_inches(val, self.get_figheight(), forward=forward) def set_figheight(self, val, forward=True): """ Set the height of the figure in inches. Parameters ---------- val : float forward : bool See `set_size_inches`. See Also -------- matplotlib.figure.Figure.set_figwidth matplotlib.figure.Figure.set_size_inches """ self.set_size_inches(self.get_figwidth(), val, forward=forward) def clear(self, keep_observers=False): # docstring inherited super().clear(keep_observers=keep_observers) # FigureBase.clear does not clear toolbars, as # only Figure can have toolbars toolbar = self.canvas.toolbar if toolbar is not None: toolbar.update() def draw(self, renderer): # docstring inherited # draw the figure bounding box, perhaps none for white figure if not self.get_visible(): return artists = self._get_draw_artists(renderer) try: renderer.open_group('figure', gid=self.get_gid()) if self.axes and self.get_layout_engine() is not None: try: self.get_layout_engine().execute(self) except ValueError: pass # ValueError can occur when resizing a window. self.patch.draw(renderer) mimage._draw_list_compositing_images( renderer, self, artists, self.suppressComposite) for sfig in self.subfigs: sfig.draw(renderer) renderer.close_group('figure') finally: self.stale = False DrawEvent("draw_event", self.canvas, renderer)._process() def draw_without_rendering(self): """ Draw the figure with no output. Useful to get the final size of artists that require a draw before their size is known (e.g. text). """ renderer = _get_renderer(self) with renderer._draw_disabled(): self.draw(renderer) def draw_artist(self, a): """ Draw `.Artist` *a* only. """ a.draw(self.canvas.get_renderer()) def __getstate__(self): state = super().__getstate__() # The canvas cannot currently be pickled, but this has the benefit # of meaning that a figure can be detached from one canvas, and # re-attached to another. state.pop("canvas") # discard any changes to the dpi due to pixel ratio changes state["_dpi"] = state.get('_original_dpi', state['_dpi']) # add version information to the state state['__mpl_version__'] = mpl.__version__ # check whether the figure manager (if any) is registered with pyplot from matplotlib import _pylab_helpers if self.canvas.manager in _pylab_helpers.Gcf.figs.values(): state['_restore_to_pylab'] = True return state def __setstate__(self, state): version = state.pop('__mpl_version__') restore_to_pylab = state.pop('_restore_to_pylab', False) if version != mpl.__version__: _api.warn_external( f"This figure was saved with matplotlib version {version} and " f"is unlikely to function correctly.") self.__dict__ = state # re-initialise some of the unstored state information FigureCanvasBase(self) # Set self.canvas. if restore_to_pylab: # lazy import to avoid circularity import matplotlib.pyplot as plt import matplotlib._pylab_helpers as pylab_helpers allnums = plt.get_fignums() num = max(allnums) + 1 if allnums else 1 backend = plt._get_backend_mod() mgr = backend.new_figure_manager_given_figure(num, self) pylab_helpers.Gcf._set_new_active_manager(mgr) plt.draw_if_interactive() self.stale = True def add_axobserver(self, func): """Whenever the Axes state change, ``func(self)`` will be called.""" # Connect a wrapper lambda and not func itself, to avoid it being # weakref-collected. self._axobservers.connect("_axes_change_event", lambda arg: func(arg)) def savefig(self, fname, *, transparent=None, **kwargs): """ Save the current figure. Call signature:: savefig(fname, *, dpi='figure', format=None, metadata=None, bbox_inches=None, pad_inches=0.1, facecolor='auto', edgecolor='auto', backend=None, **kwargs ) The available output formats depend on the backend being used. Parameters ---------- fname : str or path-like or binary file-like A path, or a Python file-like object, or possibly some backend-dependent object such as `matplotlib.backends.backend_pdf.PdfPages`. If *format* is set, it determines the output format, and the file is saved as *fname*. Note that *fname* is used verbatim, and there is no attempt to make the extension, if any, of *fname* match *format*, and no extension is appended. If *format* is not set, then the format is inferred from the extension of *fname*, if there is one. If *format* is not set and *fname* has no extension, then the file is saved with :rc:`savefig.format` and the appropriate extension is appended to *fname*. Other Parameters ---------------- dpi : float or 'figure', default: :rc:`savefig.dpi` The resolution in dots per inch. If 'figure', use the figure's dpi value. format : str The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under *fname*. metadata : dict, optional Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend: - 'png' with Agg backend: See the parameter ``metadata`` of `~.FigureCanvasAgg.print_png`. - 'pdf' with pdf backend: See the parameter ``metadata`` of `~.backend_pdf.PdfPages`. - 'svg' with svg backend: See the parameter ``metadata`` of `~.FigureCanvasSVG.print_svg`. - 'eps' and 'ps' with PS backend: Only 'Creator' is supported. bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox` Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure. pad_inches : float, default: :rc:`savefig.pad_inches` Amount of padding around the figure when bbox_inches is 'tight'. facecolor : color or 'auto', default: :rc:`savefig.facecolor` The facecolor of the figure. If 'auto', use the current figure facecolor. edgecolor : color or 'auto', default: :rc:`savefig.edgecolor` The edgecolor of the figure. If 'auto', use the current figure edgecolor. backend : str, optional Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See :ref:`the-builtin-backends` for a list of valid backends for each file format. Custom backends can be referenced as "module://...". orientation : {'landscape', 'portrait'} Currently only supported by the postscript backend. papertype : str One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output. transparent : bool If *True*, the Axes patches will all be transparent; the Figure patch will also be transparent unless *facecolor* and/or *edgecolor* are specified via kwargs. If *False* has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the *facecolor* and/or *edgecolor* keyword arguments in which case those colors are used). The transparency of these patches will be restored to their original values upon exit of this function. This is useful, for example, for displaying a plot on top of a colored background on a web page. bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional A list of extra artists that will be considered when the tight bbox is calculated. pil_kwargs : dict, optional Additional keyword arguments that are passed to `PIL.Image.Image.save` when saving the figure. """ kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi']) if transparent is None: transparent = mpl.rcParams['savefig.transparent'] with ExitStack() as stack: if transparent: kwargs.setdefault('facecolor', 'none') kwargs.setdefault('edgecolor', 'none') for ax in self.axes: stack.enter_context( ax.patch._cm_set(facecolor='none', edgecolor='none')) self.canvas.print_figure(fname, **kwargs) def ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE): """ Blocking call to interact with a figure. Wait until the user clicks *n* times on the figure, and return the coordinates of each click in a list. There are three possible interactions: - Add a point. - Remove the most recently added point. - Stop the interaction and return the points added so far. The actions are assigned to mouse buttons via the arguments *mouse_add*, *mouse_pop* and *mouse_stop*. Parameters ---------- n : int, default: 1 Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually. timeout : float, default: 30 seconds Number of seconds to wait before timing out. If zero or negative will never time out. show_clicks : bool, default: True If True, show a red cross at the location of each click. mouse_add : `.MouseButton` or None, default: `.MouseButton.LEFT` Mouse button used to add points. mouse_pop : `.MouseButton` or None, default: `.MouseButton.RIGHT` Mouse button used to remove the most recently added point. mouse_stop : `.MouseButton` or None, default: `.MouseButton.MIDDLE` Mouse button used to stop input. Returns ------- list of tuples A list of the clicked (x, y) coordinates. Notes ----- The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right-clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point. """ clicks = [] marks = [] def handler(event): is_button = event.name == "button_press_event" is_key = event.name == "key_press_event" # Quit (even if not in infinite mode; this is consistent with # MATLAB and sometimes quite useful, but will require the user to # test how many points were actually returned before using data). if (is_button and event.button == mouse_stop or is_key and event.key in ["escape", "enter"]): self.canvas.stop_event_loop() # Pop last click. elif (is_button and event.button == mouse_pop or is_key and event.key in ["backspace", "delete"]): if clicks: clicks.pop() if show_clicks: marks.pop().remove() self.canvas.draw() # Add new click. elif (is_button and event.button == mouse_add # On macOS/gtk, some keys return None. or is_key and event.key is not None): if event.inaxes: clicks.append((event.xdata, event.ydata)) _log.info("input %i: %f, %f", len(clicks), event.xdata, event.ydata) if show_clicks: line = mpl.lines.Line2D([event.xdata], [event.ydata], marker="+", color="r") event.inaxes.add_line(line) marks.append(line) self.canvas.draw() if len(clicks) == n and n > 0: self.canvas.stop_event_loop() _blocking_input.blocking_input_loop( self, ["button_press_event", "key_press_event"], timeout, handler) # Cleanup. for mark in marks: mark.remove() self.canvas.draw() return clicks def waitforbuttonpress(self, timeout=-1): """ Blocking call to interact with the figure. Wait for user input and return True if a key was pressed, False if a mouse button was pressed and None if no input was given within *timeout* seconds. Negative values deactivate *timeout*. """ event = None def handler(ev): nonlocal event event = ev self.canvas.stop_event_loop() _blocking_input.blocking_input_loop( self, ["button_press_event", "key_press_event"], timeout, handler) return None if event is None else event.name == "key_press_event" def execute_constrained_layout(self, renderer=None): """ Use ``layoutgrid`` to determine pos positions within Axes. See also `.set_constrained_layout_pads`. Returns ------- layoutgrid : private debugging object """ if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): return None return self.get_layout_engine().execute(self) def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None): """ Adjust the padding between and around subplots. To exclude an artist on the Axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), set ``a.set_in_layout(False)`` for that artist. Parameters ---------- pad : float, default: 1.08 Padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad : float, default: *pad* Padding (height/width) between edges of adjacent subplots, as a fraction of the font size. rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1) A rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit. See Also -------- .Figure.set_layout_engine .pyplot.tight_layout """ # note that here we do not permanently set the figures engine to # tight_layout but rather just perform the layout in place and remove # any previous engines. engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) try: previous_engine = self.get_layout_engine() self.set_layout_engine(engine) engine.execute(self) if not isinstance(previous_engine, TightLayoutEngine) \ and previous_engine is not None: _api.warn_external('The figure layout has changed to tight') finally: self.set_layout_engine(None) The provided code snippet includes necessary dependencies for implementing the `thumbnail` function. Write a Python function `def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear', preview=False)` to solve the following problem: Make a thumbnail of image in *infile* with output filename *thumbfile*. See :doc:`/gallery/misc/image_thumbnail_sgskip`. Parameters ---------- infile : str or file-like The image file. Matplotlib relies on Pillow_ for image reading, and thus supports a wide range of file formats, including PNG, JPG, TIFF and others. .. _Pillow: https://python-pillow.org/ thumbfile : str or file-like The thumbnail filename. scale : float, default: 0.1 The scale factor for the thumbnail. interpolation : str, default: 'bilinear' The interpolation scheme used in the resampling. See the *interpolation* parameter of `~.Axes.imshow` for possible values. preview : bool, default: False If True, the default backend (presumably a user interface backend) will be used which will cause a figure to be raised if `~matplotlib.pyplot.show` is called. If it is False, the figure is created using `.FigureCanvasBase` and the drawing backend is selected as `.Figure.savefig` would normally do. Returns ------- `.Figure` The figure instance containing the thumbnail. Here is the function: def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear', preview=False): """ Make a thumbnail of image in *infile* with output filename *thumbfile*. See :doc:`/gallery/misc/image_thumbnail_sgskip`. Parameters ---------- infile : str or file-like The image file. Matplotlib relies on Pillow_ for image reading, and thus supports a wide range of file formats, including PNG, JPG, TIFF and others. .. _Pillow: https://python-pillow.org/ thumbfile : str or file-like The thumbnail filename. scale : float, default: 0.1 The scale factor for the thumbnail. interpolation : str, default: 'bilinear' The interpolation scheme used in the resampling. See the *interpolation* parameter of `~.Axes.imshow` for possible values. preview : bool, default: False If True, the default backend (presumably a user interface backend) will be used which will cause a figure to be raised if `~matplotlib.pyplot.show` is called. If it is False, the figure is created using `.FigureCanvasBase` and the drawing backend is selected as `.Figure.savefig` would normally do. Returns ------- `.Figure` The figure instance containing the thumbnail. """ im = imread(infile) rows, cols, depth = im.shape # This doesn't really matter (it cancels in the end) but the API needs it. dpi = 100 height = rows / dpi * scale width = cols / dpi * scale if preview: # Let the UI backend do everything. import matplotlib.pyplot as plt fig = plt.figure(figsize=(width, height), dpi=dpi) else: from matplotlib.figure import Figure fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvasBase(fig) ax = fig.add_axes([0, 0, 1, 1], aspect='auto', frameon=False, xticks=[], yticks=[]) ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation) fig.savefig(thumbfile, dpi=dpi) return fig
Make a thumbnail of image in *infile* with output filename *thumbfile*. See :doc:`/gallery/misc/image_thumbnail_sgskip`. Parameters ---------- infile : str or file-like The image file. Matplotlib relies on Pillow_ for image reading, and thus supports a wide range of file formats, including PNG, JPG, TIFF and others. .. _Pillow: https://python-pillow.org/ thumbfile : str or file-like The thumbnail filename. scale : float, default: 0.1 The scale factor for the thumbnail. interpolation : str, default: 'bilinear' The interpolation scheme used in the resampling. See the *interpolation* parameter of `~.Axes.imshow` for possible values. preview : bool, default: False If True, the default backend (presumably a user interface backend) will be used which will cause a figure to be raised if `~matplotlib.pyplot.show` is called. If it is False, the figure is created using `.FigureCanvasBase` and the drawing backend is selected as `.Figure.savefig` would normally do. Returns ------- `.Figure` The figure instance containing the thumbnail.
171,037
import itertools import logging import locale import math from numbers import Integral import numpy as np import matplotlib as mpl from matplotlib import _api, cbook from matplotlib import transforms as mtransforms def scale_range(vmin, vmax, n=1, threshold=100): dv = abs(vmax - vmin) # > 0 as nonsingular is called before. meanv = (vmax + vmin) / 2 if abs(meanv) / dv < threshold: offset = 0 else: offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv) scale = 10 ** (math.log10(dv / n) // 1) return scale, offset
null
171,038
import itertools import logging import locale import math from numbers import Integral import numpy as np import matplotlib as mpl from matplotlib import _api, cbook from matplotlib import transforms as mtransforms def is_close_to_int(x, *, atol=1e-10): return abs(x - np.round(x)) < atol def is_decade(x, base=10, *, rtol=1e-10): if not np.isfinite(x): return False if x == 0.0: return True lx = np.log(abs(x)) / np.log(base) return is_close_to_int(lx, atol=rtol)
null
171,039
import itertools import logging import locale import math from numbers import Integral import numpy as np import matplotlib as mpl from matplotlib import _api, cbook from matplotlib import transforms as mtransforms The provided code snippet includes necessary dependencies for implementing the `_is_decade` function. Write a Python function `def _is_decade(x, *, base=10, rtol=None)` to solve the following problem: Return True if *x* is an integer power of *base*. Here is the function: def _is_decade(x, *, base=10, rtol=None): """Return True if *x* is an integer power of *base*.""" if not np.isfinite(x): return False if x == 0.0: return True lx = np.log(abs(x)) / np.log(base) if rtol is None: return np.isclose(lx, np.round(lx)) else: return np.isclose(lx, np.round(lx), rtol=rtol)
Return True if *x* is an integer power of *base*.
171,040
import itertools import logging import locale import math from numbers import Integral import numpy as np import matplotlib as mpl from matplotlib import _api, cbook from matplotlib import transforms as mtransforms def _is_close_to_int(x): return math.isclose(x, round(x))
null
171,041
from itertools import cycle import numpy as np from matplotlib import _api, cbook from matplotlib.lines import Line2D from matplotlib.patches import Rectangle import matplotlib.collections as mcoll def update_from_first_child(tgt, src): first_child = next(iter(src.get_children()), None) if first_child is not None: tgt.update_from(first_child)
null
171,042
from collections.abc import Mapping import functools import numpy as np from numpy import ma import matplotlib as mpl from matplotlib import _api, colors, cbook, scale from matplotlib._cm import datad from matplotlib._cm_listed import cmaps as cmaps_listed _LUTSIZE = mpl.rcParams['image.lut'] datad = { 'Blues': _Blues_data, 'BrBG': _BrBG_data, 'BuGn': _BuGn_data, 'BuPu': _BuPu_data, 'CMRmap': _CMRmap_data, 'GnBu': _GnBu_data, 'Greens': _Greens_data, 'Greys': _Greys_data, 'OrRd': _OrRd_data, 'Oranges': _Oranges_data, 'PRGn': _PRGn_data, 'PiYG': _PiYG_data, 'PuBu': _PuBu_data, 'PuBuGn': _PuBuGn_data, 'PuOr': _PuOr_data, 'PuRd': _PuRd_data, 'Purples': _Purples_data, 'RdBu': _RdBu_data, 'RdGy': _RdGy_data, 'RdPu': _RdPu_data, 'RdYlBu': _RdYlBu_data, 'RdYlGn': _RdYlGn_data, 'Reds': _Reds_data, 'Spectral': _Spectral_data, 'Wistia': _wistia_data, 'YlGn': _YlGn_data, 'YlGnBu': _YlGnBu_data, 'YlOrBr': _YlOrBr_data, 'YlOrRd': _YlOrRd_data, 'afmhot': _afmhot_data, 'autumn': _autumn_data, 'binary': _binary_data, 'bone': _bone_data, 'brg': _brg_data, 'bwr': _bwr_data, 'cool': _cool_data, 'coolwarm': _coolwarm_data, 'copper': _copper_data, 'cubehelix': _cubehelix_data, 'flag': _flag_data, 'gist_earth': _gist_earth_data, 'gist_gray': _gist_gray_data, 'gist_heat': _gist_heat_data, 'gist_ncar': _gist_ncar_data, 'gist_rainbow': _gist_rainbow_data, 'gist_stern': _gist_stern_data, 'gist_yarg': _gist_yarg_data, 'gnuplot': _gnuplot_data, 'gnuplot2': _gnuplot2_data, 'gray': _gray_data, 'hot': _hot_data, 'hsv': _hsv_data, 'jet': _jet_data, 'nipy_spectral': _nipy_spectral_data, 'ocean': _ocean_data, 'pink': _pink_data, 'prism': _prism_data, 'rainbow': _rainbow_data, 'seismic': _seismic_data, 'spring': _spring_data, 'summer': _summer_data, 'terrain': _terrain_data, 'winter': _winter_data, # Qualitative 'Accent': {'listed': _Accent_data}, 'Dark2': {'listed': _Dark2_data}, 'Paired': {'listed': _Paired_data}, 'Pastel1': {'listed': _Pastel1_data}, 'Pastel2': {'listed': _Pastel2_data}, 'Set1': {'listed': _Set1_data}, 'Set2': {'listed': _Set2_data}, 'Set3': {'listed': _Set3_data}, 'tab10': {'listed': _tab10_data}, 'tab20': {'listed': _tab20_data}, 'tab20b': {'listed': _tab20b_data}, 'tab20c': {'listed': _tab20c_data}, } The provided code snippet includes necessary dependencies for implementing the `_gen_cmap_registry` function. Write a Python function `def _gen_cmap_registry()` to solve the following problem: Generate a dict mapping standard colormap names to standard colormaps, as well as the reversed colormaps. Here is the function: def _gen_cmap_registry(): """ Generate a dict mapping standard colormap names to standard colormaps, as well as the reversed colormaps. """ cmap_d = {**cmaps_listed} for name, spec in datad.items(): cmap_d[name] = ( # Precache the cmaps at a fixed lutsize.. colors.LinearSegmentedColormap(name, spec, _LUTSIZE) if 'red' in spec else colors.ListedColormap(spec['listed'], name) if 'listed' in spec else colors.LinearSegmentedColormap.from_list(name, spec, _LUTSIZE)) # Generate reversed cmaps. for cmap in list(cmap_d.values()): rmap = cmap.reversed() cmap_d[rmap.name] = rmap return cmap_d
Generate a dict mapping standard colormap names to standard colormaps, as well as the reversed colormaps.
171,043
from collections.abc import Mapping import functools import numpy as np from numpy import ma import matplotlib as mpl from matplotlib import _api, colors, cbook, scale from matplotlib._cm import datad from matplotlib._cm_listed import cmaps as cmaps_listed _colormaps = ColormapRegistry(_gen_cmap_registry()) The provided code snippet includes necessary dependencies for implementing the `register_cmap` function. Write a Python function `def register_cmap(name=None, cmap=None, *, override_builtin=False)` to solve the following problem: Add a colormap to the set recognized by :func:`get_cmap`. Register a new colormap to be accessed by name :: LinearSegmentedColormap('swirly', data, lut) register_cmap(cmap=swirly_cmap) Parameters ---------- name : str, optional The name that can be used in :func:`get_cmap` or :rc:`image.cmap` If absent, the name will be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*. cmap : matplotlib.colors.Colormap Despite being the second argument and having a default value, this is a required argument. override_builtin : bool Allow built-in colormaps to be overridden by a user-supplied colormap. Please do not use this unless you are sure you need it. Here is the function: def register_cmap(name=None, cmap=None, *, override_builtin=False): """ Add a colormap to the set recognized by :func:`get_cmap`. Register a new colormap to be accessed by name :: LinearSegmentedColormap('swirly', data, lut) register_cmap(cmap=swirly_cmap) Parameters ---------- name : str, optional The name that can be used in :func:`get_cmap` or :rc:`image.cmap` If absent, the name will be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*. cmap : matplotlib.colors.Colormap Despite being the second argument and having a default value, this is a required argument. override_builtin : bool Allow built-in colormaps to be overridden by a user-supplied colormap. Please do not use this unless you are sure you need it. """ _api.check_isinstance((str, None), name=name) if name is None: try: name = cmap.name except AttributeError as err: raise ValueError("Arguments must include a name or a " "Colormap") from err # override_builtin is allowed here for backward compatibility # this is just a shim to enable that to work privately in # the global ColormapRegistry _colormaps._allow_override_builtin = override_builtin _colormaps.register(cmap, name=name, force=override_builtin) _colormaps._allow_override_builtin = False
Add a colormap to the set recognized by :func:`get_cmap`. Register a new colormap to be accessed by name :: LinearSegmentedColormap('swirly', data, lut) register_cmap(cmap=swirly_cmap) Parameters ---------- name : str, optional The name that can be used in :func:`get_cmap` or :rc:`image.cmap` If absent, the name will be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*. cmap : matplotlib.colors.Colormap Despite being the second argument and having a default value, this is a required argument. override_builtin : bool Allow built-in colormaps to be overridden by a user-supplied colormap. Please do not use this unless you are sure you need it.
171,044
from collections.abc import Mapping import functools import numpy as np from numpy import ma import matplotlib as mpl from matplotlib import _api, colors, cbook, scale from matplotlib._cm import datad from matplotlib._cm_listed import cmaps as cmaps_listed _colormaps = ColormapRegistry(_gen_cmap_registry()) The provided code snippet includes necessary dependencies for implementing the `unregister_cmap` function. Write a Python function `def unregister_cmap(name)` to solve the following problem: Remove a colormap recognized by :func:`get_cmap`. You may not remove built-in colormaps. If the named colormap is not registered, returns with no error, raises if you try to de-register a default colormap. .. warning:: Colormap names are currently a shared namespace that may be used by multiple packages. Use `unregister_cmap` only if you know you have registered that name before. In particular, do not unregister just in case to clean the name before registering a new colormap. Parameters ---------- name : str The name of the colormap to be un-registered Returns ------- ColorMap or None If the colormap was registered, return it if not return `None` Raises ------ ValueError If you try to de-register a default built-in colormap. Here is the function: def unregister_cmap(name): """ Remove a colormap recognized by :func:`get_cmap`. You may not remove built-in colormaps. If the named colormap is not registered, returns with no error, raises if you try to de-register a default colormap. .. warning:: Colormap names are currently a shared namespace that may be used by multiple packages. Use `unregister_cmap` only if you know you have registered that name before. In particular, do not unregister just in case to clean the name before registering a new colormap. Parameters ---------- name : str The name of the colormap to be un-registered Returns ------- ColorMap or None If the colormap was registered, return it if not return `None` Raises ------ ValueError If you try to de-register a default built-in colormap. """ cmap = _colormaps.get(name, None) _colormaps.unregister(name) return cmap
Remove a colormap recognized by :func:`get_cmap`. You may not remove built-in colormaps. If the named colormap is not registered, returns with no error, raises if you try to de-register a default colormap. .. warning:: Colormap names are currently a shared namespace that may be used by multiple packages. Use `unregister_cmap` only if you know you have registered that name before. In particular, do not unregister just in case to clean the name before registering a new colormap. Parameters ---------- name : str The name of the colormap to be un-registered Returns ------- ColorMap or None If the colormap was registered, return it if not return `None` Raises ------ ValueError If you try to de-register a default built-in colormap.
171,045
from collections.abc import Mapping import functools import numpy as np from numpy import ma import matplotlib as mpl from matplotlib import _api, colors, cbook, scale from matplotlib._cm import datad from matplotlib._cm_listed import cmaps as cmaps_listed The provided code snippet includes necessary dependencies for implementing the `_auto_norm_from_scale` function. Write a Python function `def _auto_norm_from_scale(scale_cls)` to solve the following problem: Automatically generate a norm class from *scale_cls*. This differs from `.colors.make_norm_from_scale` in the following points: - This function is not a class decorator, but directly returns a norm class (as if decorating `.Normalize`). - The scale is automatically constructed with ``nonpositive="mask"``, if it supports such a parameter, to work around the difference in defaults between standard scales (which use "clip") and norms (which use "mask"). Note that ``make_norm_from_scale`` caches the generated norm classes (not the instances) and reuses them for later calls. For example, ``type(_auto_norm_from_scale("log")) == LogNorm``. Here is the function: def _auto_norm_from_scale(scale_cls): """ Automatically generate a norm class from *scale_cls*. This differs from `.colors.make_norm_from_scale` in the following points: - This function is not a class decorator, but directly returns a norm class (as if decorating `.Normalize`). - The scale is automatically constructed with ``nonpositive="mask"``, if it supports such a parameter, to work around the difference in defaults between standard scales (which use "clip") and norms (which use "mask"). Note that ``make_norm_from_scale`` caches the generated norm classes (not the instances) and reuses them for later calls. For example, ``type(_auto_norm_from_scale("log")) == LogNorm``. """ # Actually try to construct an instance, to verify whether # ``nonpositive="mask"`` is supported. try: norm = colors.make_norm_from_scale( functools.partial(scale_cls, nonpositive="mask"))( colors.Normalize)() except TypeError: norm = colors.make_norm_from_scale(scale_cls)( colors.Normalize)() return type(norm)
Automatically generate a norm class from *scale_cls*. This differs from `.colors.make_norm_from_scale` in the following points: - This function is not a class decorator, but directly returns a norm class (as if decorating `.Normalize`). - The scale is automatically constructed with ``nonpositive="mask"``, if it supports such a parameter, to work around the difference in defaults between standard scales (which use "clip") and norms (which use "mask"). Note that ``make_norm_from_scale`` caches the generated norm classes (not the instances) and reuses them for later calls. For example, ``type(_auto_norm_from_scale("log")) == LogNorm``.
171,046
from functools import lru_cache, partial import re from pyparsing import ( Group, Optional, ParseException, Regex, StringEnd, Suppress, ZeroOrMore) from matplotlib import _api _family_escape = partial(re.compile(r'(?=[%s])' % _family_punc).sub, r'\\') _value_escape = partial(re.compile(r'(?=[%s])' % _value_punc).sub, r'\\') The provided code snippet includes necessary dependencies for implementing the `generate_fontconfig_pattern` function. Write a Python function `def generate_fontconfig_pattern(d)` to solve the following problem: Convert a `.FontProperties` to a fontconfig pattern string. Here is the function: def generate_fontconfig_pattern(d): """Convert a `.FontProperties` to a fontconfig pattern string.""" kvs = [(k, getattr(d, f"get_{k}")()) for k in ["style", "variant", "weight", "stretch", "file", "size"]] # Families is given first without a leading keyword. Other entries (which # are necessarily scalar) are given as key=value, skipping Nones. return (",".join(_family_escape(f) for f in d.get_family()) + "".join(f":{k}={_value_escape(str(v))}" for k, v in kvs if v is not None))
Convert a `.FontProperties` to a fontconfig pattern string.
171,047
import itertools import numpy as np from matplotlib import _api The provided code snippet includes necessary dependencies for implementing the `stackplot` function. Write a Python function `def stackplot(axes, x, *args, labels=(), colors=None, baseline='zero', **kwargs)` to solve the following problem: Draw a stacked area plot. Parameters ---------- x : (N,) array-like y : (M, N) array-like The data is assumed to be unstacked. Each of the following calls is legal:: stackplot(x, y) # where y has shape (M, N) stackplot(x, y1, y2, y3) # where y1, y2, y3, y4 have length N baseline : {'zero', 'sym', 'wiggle', 'weighted_wiggle'} Method used to calculate the baseline: - ``'zero'``: Constant zero baseline, i.e. a simple stacked plot. - ``'sym'``: Symmetric around zero and is sometimes called 'ThemeRiver'. - ``'wiggle'``: Minimizes the sum of the squared slopes. - ``'weighted_wiggle'``: Does the same but weights to account for size of each layer. It is also called 'Streamgraph'-layout. More details can be found at http://leebyron.com/streamgraph/. labels : list of str, optional A sequence of labels to assign to each data series. If unspecified, then no labels will be applied to artists. colors : list of color, optional A sequence of colors to be cycled through and used to color the stacked areas. The sequence need not be exactly the same length as the number of provided *y*, in which case the colors will repeat from the beginning. If not specified, the colors from the Axes property cycle will be used. data : indexable object, optional DATA_PARAMETER_PLACEHOLDER **kwargs All other keyword arguments are passed to `.Axes.fill_between`. Returns ------- list of `.PolyCollection` A list of `.PolyCollection` instances, one for each element in the stacked area plot. Here is the function: def stackplot(axes, x, *args, labels=(), colors=None, baseline='zero', **kwargs): """ Draw a stacked area plot. Parameters ---------- x : (N,) array-like y : (M, N) array-like The data is assumed to be unstacked. Each of the following calls is legal:: stackplot(x, y) # where y has shape (M, N) stackplot(x, y1, y2, y3) # where y1, y2, y3, y4 have length N baseline : {'zero', 'sym', 'wiggle', 'weighted_wiggle'} Method used to calculate the baseline: - ``'zero'``: Constant zero baseline, i.e. a simple stacked plot. - ``'sym'``: Symmetric around zero and is sometimes called 'ThemeRiver'. - ``'wiggle'``: Minimizes the sum of the squared slopes. - ``'weighted_wiggle'``: Does the same but weights to account for size of each layer. It is also called 'Streamgraph'-layout. More details can be found at http://leebyron.com/streamgraph/. labels : list of str, optional A sequence of labels to assign to each data series. If unspecified, then no labels will be applied to artists. colors : list of color, optional A sequence of colors to be cycled through and used to color the stacked areas. The sequence need not be exactly the same length as the number of provided *y*, in which case the colors will repeat from the beginning. If not specified, the colors from the Axes property cycle will be used. data : indexable object, optional DATA_PARAMETER_PLACEHOLDER **kwargs All other keyword arguments are passed to `.Axes.fill_between`. Returns ------- list of `.PolyCollection` A list of `.PolyCollection` instances, one for each element in the stacked area plot. """ y = np.row_stack(args) labels = iter(labels) if colors is not None: colors = itertools.cycle(colors) else: colors = (axes._get_lines.get_next_color() for _ in y) # Assume data passed has not been 'stacked', so stack it here. # We'll need a float buffer for the upcoming calculations. stack = np.cumsum(y, axis=0, dtype=np.promote_types(y.dtype, np.float32)) _api.check_in_list(['zero', 'sym', 'wiggle', 'weighted_wiggle'], baseline=baseline) if baseline == 'zero': first_line = 0. elif baseline == 'sym': first_line = -np.sum(y, 0) * 0.5 stack += first_line[None, :] elif baseline == 'wiggle': m = y.shape[0] first_line = (y * (m - 0.5 - np.arange(m)[:, None])).sum(0) first_line /= -m stack += first_line elif baseline == 'weighted_wiggle': total = np.sum(y, 0) # multiply by 1/total (or zero) to avoid infinities in the division: inv_total = np.zeros_like(total) mask = total > 0 inv_total[mask] = 1.0 / total[mask] increase = np.hstack((y[:, 0:1], np.diff(y))) below_size = total - stack below_size += 0.5 * y move_up = below_size * inv_total move_up[:, 0] = 0.5 center = (move_up - 0.5) * increase center = np.cumsum(center.sum(0)) first_line = center - 0.5 * total stack += first_line # Color between x = 0 and the first array. coll = axes.fill_between(x, first_line, stack[0, :], facecolor=next(colors), label=next(labels, None), **kwargs) coll.sticky_edges.y[:] = [0] r = [coll] # Color between array i-1 and array i for i in range(len(y) - 1): r.append(axes.fill_between(x, stack[i, :], stack[i + 1, :], facecolor=next(colors), label=next(labels, None), **kwargs)) return r
Draw a stacked area plot. Parameters ---------- x : (N,) array-like y : (M, N) array-like The data is assumed to be unstacked. Each of the following calls is legal:: stackplot(x, y) # where y has shape (M, N) stackplot(x, y1, y2, y3) # where y1, y2, y3, y4 have length N baseline : {'zero', 'sym', 'wiggle', 'weighted_wiggle'} Method used to calculate the baseline: - ``'zero'``: Constant zero baseline, i.e. a simple stacked plot. - ``'sym'``: Symmetric around zero and is sometimes called 'ThemeRiver'. - ``'wiggle'``: Minimizes the sum of the squared slopes. - ``'weighted_wiggle'``: Does the same but weights to account for size of each layer. It is also called 'Streamgraph'-layout. More details can be found at http://leebyron.com/streamgraph/. labels : list of str, optional A sequence of labels to assign to each data series. If unspecified, then no labels will be applied to artists. colors : list of color, optional A sequence of colors to be cycled through and used to color the stacked areas. The sequence need not be exactly the same length as the number of provided *y*, in which case the colors will repeat from the beginning. If not specified, the colors from the Axes property cycle will be used. data : indexable object, optional DATA_PARAMETER_PLACEHOLDER **kwargs All other keyword arguments are passed to `.Axes.fill_between`. Returns ------- list of `.PolyCollection` A list of `.PolyCollection` instances, one for each element in the stacked area plot.
171,048
from contextlib import ExitStack import copy import itertools from numbers import Integral, Number from cycler import cycler import numpy as np import matplotlib as mpl from . import (_api, _docstring, backend_tools, cbook, collections, colors, text as mtext, ticker, transforms) from .lines import Line2D from .patches import Circle, Rectangle, Ellipse, Polygon from .transforms import TransformedPatchPath, Affine2D def cycler(*args, **kwargs): """ Create a new `Cycler` object from a single positional argument, a pair of positional arguments, or the combination of keyword arguments. cycler(arg) cycler(label1=itr1[, label2=iter2[, ...]]) cycler(label, itr) Form 1 simply copies a given `Cycler` object. Form 2 composes a `Cycler` as an inner product of the pairs of keyword arguments. In other words, all of the iterables are cycled simultaneously, as if through zip(). Form 3 creates a `Cycler` from a label and an iterable. This is useful for when the label cannot be a keyword argument (e.g., an integer or a name that has a space in it). Parameters ---------- arg : Cycler Copy constructor for Cycler (does a shallow copy of iterables). label : name The property key. In the 2-arg form of the function, the label can be any hashable object. In the keyword argument form of the function, it must be a valid python identifier. itr : iterable Finite length iterable of the property values. Can be a single-property `Cycler` that would be like a key change, but as a shallow copy. Returns ------- cycler : Cycler New `Cycler` for the given property """ if args and kwargs: raise TypeError("cyl() can only accept positional OR keyword " "arguments -- not both.") if len(args) == 1: if not isinstance(args[0], Cycler): raise TypeError("If only one positional argument given, it must " "be a Cycler instance.") return Cycler(args[0]) elif len(args) == 2: return _cycler(*args) elif len(args) > 2: raise TypeError("Only a single Cycler can be accepted as the lone " "positional argument. Use keyword arguments instead.") if kwargs: return reduce(add, (_cycler(k, v) for k, v in kwargs.items())) raise TypeError("Must have at least a positional OR keyword arguments") def _expand_text_props(props): props = cbook.normalize_kwargs(props, mtext.Text) return cycler(**props)() if props else itertools.repeat({})
null
171,049
import numpy as np import matplotlib as mpl from matplotlib import _api, cm, patches import matplotlib.colors as mcolors import matplotlib.collections as mcollections import matplotlib.lines as mlines class StreamplotSet: def __init__(self, lines, arrows): self.lines = lines self.arrows = arrows class DomainMap: """ Map representing different coordinate systems. Coordinate definitions: * axes-coordinates goes from 0 to 1 in the domain. * data-coordinates are specified by the input x-y coordinates. * grid-coordinates goes from 0 to N and 0 to M for an N x M grid, where N and M match the shape of the input data. * mask-coordinates goes from 0 to N and 0 to M for an N x M mask, where N and M are user-specified to control the density of streamlines. This class also has methods for adding trajectories to the StreamMask. Before adding a trajectory, run `start_trajectory` to keep track of regions crossed by a given trajectory. Later, if you decide the trajectory is bad (e.g., if the trajectory is very short) just call `undo_trajectory`. """ def __init__(self, grid, mask): self.grid = grid self.mask = mask # Constants for conversion between grid- and mask-coordinates self.x_grid2mask = (mask.nx - 1) / (grid.nx - 1) self.y_grid2mask = (mask.ny - 1) / (grid.ny - 1) self.x_mask2grid = 1. / self.x_grid2mask self.y_mask2grid = 1. / self.y_grid2mask self.x_data2grid = 1. / grid.dx self.y_data2grid = 1. / grid.dy def grid2mask(self, xi, yi): """Return nearest space in mask-coords from given grid-coords.""" return round(xi * self.x_grid2mask), round(yi * self.y_grid2mask) def mask2grid(self, xm, ym): return xm * self.x_mask2grid, ym * self.y_mask2grid def data2grid(self, xd, yd): return xd * self.x_data2grid, yd * self.y_data2grid def grid2data(self, xg, yg): return xg / self.x_data2grid, yg / self.y_data2grid def start_trajectory(self, xg, yg, broken_streamlines=True): xm, ym = self.grid2mask(xg, yg) self.mask._start_trajectory(xm, ym, broken_streamlines) def reset_start_point(self, xg, yg): xm, ym = self.grid2mask(xg, yg) self.mask._current_xy = (xm, ym) def update_trajectory(self, xg, yg, broken_streamlines=True): if not self.grid.within_grid(xg, yg): raise InvalidIndexError xm, ym = self.grid2mask(xg, yg) self.mask._update_trajectory(xm, ym, broken_streamlines) def undo_trajectory(self): self.mask._undo_trajectory() class Grid: """Grid of data.""" def __init__(self, x, y): if np.ndim(x) == 1: pass elif np.ndim(x) == 2: x_row = x[0] if not np.allclose(x_row, x): raise ValueError("The rows of 'x' must be equal") x = x_row else: raise ValueError("'x' can have at maximum 2 dimensions") if np.ndim(y) == 1: pass elif np.ndim(y) == 2: yt = np.transpose(y) # Also works for nested lists. y_col = yt[0] if not np.allclose(y_col, yt): raise ValueError("The columns of 'y' must be equal") y = y_col else: raise ValueError("'y' can have at maximum 2 dimensions") if not (np.diff(x) > 0).all(): raise ValueError("'x' must be strictly increasing") if not (np.diff(y) > 0).all(): raise ValueError("'y' must be strictly increasing") self.nx = len(x) self.ny = len(y) self.dx = x[1] - x[0] self.dy = y[1] - y[0] self.x_origin = x[0] self.y_origin = y[0] self.width = x[-1] - x[0] self.height = y[-1] - y[0] if not np.allclose(np.diff(x), self.width / (self.nx - 1)): raise ValueError("'x' values must be equally spaced") if not np.allclose(np.diff(y), self.height / (self.ny - 1)): raise ValueError("'y' values must be equally spaced") def shape(self): return self.ny, self.nx def within_grid(self, xi, yi): """Return whether (*xi*, *yi*) is a valid index of the grid.""" # Note that xi/yi can be floats; so, for example, we can't simply check # `xi < self.nx` since *xi* can be `self.nx - 1 < xi < self.nx` return 0 <= xi <= self.nx - 1 and 0 <= yi <= self.ny - 1 class StreamMask: """ Mask to keep track of discrete regions crossed by streamlines. The resolution of this grid determines the approximate spacing between trajectories. Streamlines are only allowed to pass through zeroed cells: When a streamline enters a cell, that cell is set to 1, and no new streamlines are allowed to enter. """ def __init__(self, density): try: self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int) except ValueError as err: raise ValueError("'density' must be a scalar or be of length " "2") from err if self.nx < 0 or self.ny < 0: raise ValueError("'density' must be positive") self._mask = np.zeros((self.ny, self.nx)) self.shape = self._mask.shape self._current_xy = None def __getitem__(self, args): return self._mask[args] def _start_trajectory(self, xm, ym, broken_streamlines=True): """Start recording streamline trajectory""" self._traj = [] self._update_trajectory(xm, ym, broken_streamlines) def _undo_trajectory(self): """Remove current trajectory from mask""" for t in self._traj: self._mask[t] = 0 def _update_trajectory(self, xm, ym, broken_streamlines=True): """ Update current trajectory position in mask. If the new position has already been filled, raise `InvalidIndexError`. """ if self._current_xy != (xm, ym): if self[ym, xm] == 0: self._traj.append((ym, xm)) self._mask[ym, xm] = 1 self._current_xy = (xm, ym) else: if broken_streamlines: raise InvalidIndexError else: pass def _get_integrator(u, v, dmap, minlength, maxlength, integration_direction): # rescale velocity onto grid-coordinates for integrations. u, v = dmap.data2grid(u, v) # speed (path length) will be in axes-coordinates u_ax = u / (dmap.grid.nx - 1) v_ax = v / (dmap.grid.ny - 1) speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2) def forward_time(xi, yi): if not dmap.grid.within_grid(xi, yi): raise OutOfBounds ds_dt = interpgrid(speed, xi, yi) if ds_dt == 0: raise TerminateTrajectory() dt_ds = 1. / ds_dt ui = interpgrid(u, xi, yi) vi = interpgrid(v, xi, yi) return ui * dt_ds, vi * dt_ds def backward_time(xi, yi): dxi, dyi = forward_time(xi, yi) return -dxi, -dyi def integrate(x0, y0, broken_streamlines=True): """ Return x, y grid-coordinates of trajectory based on starting point. Integrate both forward and backward in time from starting point in grid coordinates. Integration is terminated when a trajectory reaches a domain boundary or when it crosses into an already occupied cell in the StreamMask. The resulting trajectory is None if it is shorter than `minlength`. """ stotal, xy_traj = 0., [] try: dmap.start_trajectory(x0, y0, broken_streamlines) except InvalidIndexError: return None if integration_direction in ['both', 'backward']: s, xyt = _integrate_rk12(x0, y0, dmap, backward_time, maxlength, broken_streamlines) stotal += s xy_traj += xyt[::-1] if integration_direction in ['both', 'forward']: dmap.reset_start_point(x0, y0) s, xyt = _integrate_rk12(x0, y0, dmap, forward_time, maxlength, broken_streamlines) stotal += s xy_traj += xyt[1:] if stotal > minlength: return np.broadcast_arrays(xy_traj, np.empty((1, 2)))[0] else: # reject short trajectories dmap.undo_trajectory() return None return integrate def interpgrid(a, xi, yi): """Fast 2D, linear interpolation on an integer grid""" Ny, Nx = np.shape(a) if isinstance(xi, np.ndarray): x = xi.astype(int) y = yi.astype(int) # Check that xn, yn don't exceed max index xn = np.clip(x + 1, 0, Nx - 1) yn = np.clip(y + 1, 0, Ny - 1) else: x = int(xi) y = int(yi) # conditional is faster than clipping for integers if x == (Nx - 1): xn = x else: xn = x + 1 if y == (Ny - 1): yn = y else: yn = y + 1 a00 = a[y, x] a01 = a[y, xn] a10 = a[yn, x] a11 = a[yn, xn] xt = xi - x yt = yi - y a0 = a00 * (1 - xt) + a01 * xt a1 = a10 * (1 - xt) + a11 * xt ai = a0 * (1 - yt) + a1 * yt if not isinstance(xi, np.ndarray): if np.ma.is_masked(ai): raise TerminateTrajectory return ai def _gen_starting_points(shape): """ Yield starting points for streamlines. Trying points on the boundary first gives higher quality streamlines. This algorithm starts with a point on the mask corner and spirals inward. This algorithm is inefficient, but fast compared to rest of streamplot. """ ny, nx = shape xfirst = 0 yfirst = 1 xlast = nx - 1 ylast = ny - 1 x, y = 0, 0 direction = 'right' for i in range(nx * ny): yield x, y if direction == 'right': x += 1 if x >= xlast: xlast -= 1 direction = 'up' elif direction == 'up': y += 1 if y >= ylast: ylast -= 1 direction = 'left' elif direction == 'left': x -= 1 if x <= xfirst: xfirst += 1 direction = 'down' elif direction == 'down': y -= 1 if y <= yfirst: yfirst += 1 direction = 'right' "antialiased": ["aa"], "edgecolor": ["ec"], "facecolor": ["fc"], "linestyle": ["ls"], "linewidth": ["lw"], }) "antialiased": ["antialiaseds", "aa"], "edgecolor": ["edgecolors", "ec"], "facecolor": ["facecolors", "fc"], "linestyle": ["linestyles", "dashes", "ls"], "linewidth": ["linewidths", "lw"], "offset_transform": ["transOffset"], }) }) The provided code snippet includes necessary dependencies for implementing the `streamplot` function. Write a Python function `def streamplot(axes, 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)` to solve the following problem: Draw streamlines of a vector flow. Parameters ---------- x, y : 1D/2D arrays Evenly spaced strictly increasing arrays to make a grid. If 2D, all rows of *x* must be equal and all columns of *y* must be equal; i.e., they must be as if generated by ``np.meshgrid(x_1d, y_1d)``. u, v : 2D arrays *x* and *y*-velocities. The number of rows and columns must match the length of *y* and *x*, respectively. density : float or (float, float) Controls the closeness of streamlines. When ``density = 1``, the domain is divided into a 30x30 grid. *density* linearly scales this grid. Each cell in the grid can have, at most, one traversing streamline. For different densities in each direction, use a tuple (density_x, density_y). linewidth : float or 2D array The width of the streamlines. With a 2D array the line width can be varied across the grid. The array must have the same shape as *u* and *v*. color : color or 2D array The streamline color. If given an array, its values are converted to colors using *cmap* and *norm*. The array must have the same shape as *u* and *v*. cmap, norm Data normalization and colormapping parameters for *color*; only used if *color* is an array of floats. See `~.Axes.imshow` for a detailed description. arrowsize : float Scaling factor for the arrow size. arrowstyle : str Arrow style specification. See `~matplotlib.patches.FancyArrowPatch`. minlength : float Minimum length of streamline in axes coordinates. start_points : Nx2 array Coordinates of starting points for the streamlines in data coordinates (the same coordinates as the *x* and *y* arrays). zorder : float The zorder of the streamlines and arrows. Artists with lower zorder values are drawn first. maxlength : float Maximum length of streamline in axes coordinates. integration_direction : {'forward', 'backward', 'both'}, default: 'both' Integrate the streamline in forward, backward or both directions. data : indexable object, optional DATA_PARAMETER_PLACEHOLDER broken_streamlines : boolean, default: True If False, forces streamlines to continue until they leave the plot domain. If True, they may be terminated if they come too close to another streamline. Returns ------- StreamplotSet Container object with attributes - ``lines``: `.LineCollection` of streamlines - ``arrows``: `.PatchCollection` containing `.FancyArrowPatch` objects representing the arrows half-way along streamlines. This container will probably change in the future to allow changes to the colormap, alpha, etc. for both lines and arrows, but these changes should be backward compatible. Here is the function: def streamplot(axes, 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): """ Draw streamlines of a vector flow. Parameters ---------- x, y : 1D/2D arrays Evenly spaced strictly increasing arrays to make a grid. If 2D, all rows of *x* must be equal and all columns of *y* must be equal; i.e., they must be as if generated by ``np.meshgrid(x_1d, y_1d)``. u, v : 2D arrays *x* and *y*-velocities. The number of rows and columns must match the length of *y* and *x*, respectively. density : float or (float, float) Controls the closeness of streamlines. When ``density = 1``, the domain is divided into a 30x30 grid. *density* linearly scales this grid. Each cell in the grid can have, at most, one traversing streamline. For different densities in each direction, use a tuple (density_x, density_y). linewidth : float or 2D array The width of the streamlines. With a 2D array the line width can be varied across the grid. The array must have the same shape as *u* and *v*. color : color or 2D array The streamline color. If given an array, its values are converted to colors using *cmap* and *norm*. The array must have the same shape as *u* and *v*. cmap, norm Data normalization and colormapping parameters for *color*; only used if *color* is an array of floats. See `~.Axes.imshow` for a detailed description. arrowsize : float Scaling factor for the arrow size. arrowstyle : str Arrow style specification. See `~matplotlib.patches.FancyArrowPatch`. minlength : float Minimum length of streamline in axes coordinates. start_points : Nx2 array Coordinates of starting points for the streamlines in data coordinates (the same coordinates as the *x* and *y* arrays). zorder : float The zorder of the streamlines and arrows. Artists with lower zorder values are drawn first. maxlength : float Maximum length of streamline in axes coordinates. integration_direction : {'forward', 'backward', 'both'}, default: 'both' Integrate the streamline in forward, backward or both directions. data : indexable object, optional DATA_PARAMETER_PLACEHOLDER broken_streamlines : boolean, default: True If False, forces streamlines to continue until they leave the plot domain. If True, they may be terminated if they come too close to another streamline. Returns ------- StreamplotSet Container object with attributes - ``lines``: `.LineCollection` of streamlines - ``arrows``: `.PatchCollection` containing `.FancyArrowPatch` objects representing the arrows half-way along streamlines. This container will probably change in the future to allow changes to the colormap, alpha, etc. for both lines and arrows, but these changes should be backward compatible. """ grid = Grid(x, y) mask = StreamMask(density) dmap = DomainMap(grid, mask) if zorder is None: zorder = mlines.Line2D.zorder # default to data coordinates if transform is None: transform = axes.transData if color is None: color = axes._get_lines.get_next_color() if linewidth is None: linewidth = mpl.rcParams['lines.linewidth'] line_kw = {} arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize) _api.check_in_list(['both', 'forward', 'backward'], integration_direction=integration_direction) if integration_direction == 'both': maxlength /= 2. use_multicolor_lines = isinstance(color, np.ndarray) if use_multicolor_lines: if color.shape != grid.shape: raise ValueError("If 'color' is given, it must match the shape of " "the (x, y) grid") line_colors = [[]] # Empty entry allows concatenation of zero arrays. color = np.ma.masked_invalid(color) else: line_kw['color'] = color arrow_kw['color'] = color if isinstance(linewidth, np.ndarray): if linewidth.shape != grid.shape: raise ValueError("If 'linewidth' is given, it must match the " "shape of the (x, y) grid") line_kw['linewidth'] = [] else: line_kw['linewidth'] = linewidth arrow_kw['linewidth'] = linewidth line_kw['zorder'] = zorder arrow_kw['zorder'] = zorder # Sanity checks. if u.shape != grid.shape or v.shape != grid.shape: raise ValueError("'u' and 'v' must match the shape of the (x, y) grid") u = np.ma.masked_invalid(u) v = np.ma.masked_invalid(v) integrate = _get_integrator(u, v, dmap, minlength, maxlength, integration_direction) trajectories = [] if start_points is None: for xm, ym in _gen_starting_points(mask.shape): if mask[ym, xm] == 0: xg, yg = dmap.mask2grid(xm, ym) t = integrate(xg, yg, broken_streamlines) if t is not None: trajectories.append(t) else: sp2 = np.asanyarray(start_points, dtype=float).copy() # Check if start_points are outside the data boundaries for xs, ys in sp2: if not (grid.x_origin <= xs <= grid.x_origin + grid.width and grid.y_origin <= ys <= grid.y_origin + grid.height): raise ValueError("Starting point ({}, {}) outside of data " "boundaries".format(xs, ys)) # Convert start_points from data to array coords # Shift the seed points from the bottom left of the data so that # data2grid works properly. sp2[:, 0] -= grid.x_origin sp2[:, 1] -= grid.y_origin for xs, ys in sp2: xg, yg = dmap.data2grid(xs, ys) # Floating point issues can cause xg, yg to be slightly out of # bounds for xs, ys on the upper boundaries. Because we have # already checked that the starting points are within the original # grid, clip the xg, yg to the grid to work around this issue xg = np.clip(xg, 0, grid.nx - 1) yg = np.clip(yg, 0, grid.ny - 1) t = integrate(xg, yg, broken_streamlines) if t is not None: trajectories.append(t) if use_multicolor_lines: if norm is None: norm = mcolors.Normalize(color.min(), color.max()) cmap = cm._ensure_cmap(cmap) streamlines = [] arrows = [] for t in trajectories: tgx, tgy = t.T # Rescale from grid-coordinates to data-coordinates. tx, ty = dmap.grid2data(tgx, tgy) tx += grid.x_origin ty += grid.y_origin points = np.transpose([tx, ty]).reshape(-1, 1, 2) streamlines.extend(np.hstack([points[:-1], points[1:]])) # Add arrows halfway along each trajectory. s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty))) n = np.searchsorted(s, s[-1] / 2.) arrow_tail = (tx[n], ty[n]) arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2])) if isinstance(linewidth, np.ndarray): line_widths = interpgrid(linewidth, tgx, tgy)[:-1] line_kw['linewidth'].extend(line_widths) arrow_kw['linewidth'] = line_widths[n] if use_multicolor_lines: color_values = interpgrid(color, tgx, tgy)[:-1] line_colors.append(color_values) arrow_kw['color'] = cmap(norm(color_values[n])) p = patches.FancyArrowPatch( arrow_tail, arrow_head, transform=transform, **arrow_kw) arrows.append(p) lc = mcollections.LineCollection( streamlines, transform=transform, **line_kw) lc.sticky_edges.x[:] = [grid.x_origin, grid.x_origin + grid.width] lc.sticky_edges.y[:] = [grid.y_origin, grid.y_origin + grid.height] if use_multicolor_lines: lc.set_array(np.ma.hstack(line_colors)) lc.set_cmap(cmap) lc.set_norm(norm) axes.add_collection(lc) ac = mcollections.PatchCollection(arrows) # Adding the collection itself is broken; see #2341. for p in arrows: axes.add_patch(p) axes.autoscale_view() stream_container = StreamplotSet(lc, ac) return stream_container
Draw streamlines of a vector flow. Parameters ---------- x, y : 1D/2D arrays Evenly spaced strictly increasing arrays to make a grid. If 2D, all rows of *x* must be equal and all columns of *y* must be equal; i.e., they must be as if generated by ``np.meshgrid(x_1d, y_1d)``. u, v : 2D arrays *x* and *y*-velocities. The number of rows and columns must match the length of *y* and *x*, respectively. density : float or (float, float) Controls the closeness of streamlines. When ``density = 1``, the domain is divided into a 30x30 grid. *density* linearly scales this grid. Each cell in the grid can have, at most, one traversing streamline. For different densities in each direction, use a tuple (density_x, density_y). linewidth : float or 2D array The width of the streamlines. With a 2D array the line width can be varied across the grid. The array must have the same shape as *u* and *v*. color : color or 2D array The streamline color. If given an array, its values are converted to colors using *cmap* and *norm*. The array must have the same shape as *u* and *v*. cmap, norm Data normalization and colormapping parameters for *color*; only used if *color* is an array of floats. See `~.Axes.imshow` for a detailed description. arrowsize : float Scaling factor for the arrow size. arrowstyle : str Arrow style specification. See `~matplotlib.patches.FancyArrowPatch`. minlength : float Minimum length of streamline in axes coordinates. start_points : Nx2 array Coordinates of starting points for the streamlines in data coordinates (the same coordinates as the *x* and *y* arrays). zorder : float The zorder of the streamlines and arrows. Artists with lower zorder values are drawn first. maxlength : float Maximum length of streamline in axes coordinates. integration_direction : {'forward', 'backward', 'both'}, default: 'both' Integrate the streamline in forward, backward or both directions. data : indexable object, optional DATA_PARAMETER_PLACEHOLDER broken_streamlines : boolean, default: True If False, forces streamlines to continue until they leave the plot domain. If True, they may be terminated if they come too close to another streamline. Returns ------- StreamplotSet Container object with attributes - ``lines``: `.LineCollection` of streamlines - ``arrows``: `.PatchCollection` containing `.FancyArrowPatch` objects representing the arrows half-way along streamlines. This container will probably change in the future to allow changes to the colormap, alpha, etc. for both lines and arrows, but these changes should be backward compatible.
171,050
import functools import logging import math from numbers import Real import weakref import numpy as np import matplotlib as mpl from . import _api, artist, cbook, _docstring from .artist import Artist from .font_manager import FontProperties from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle from .textpath import TextPath, TextToPath from .transforms import ( Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform) def get_rotation(rotation): """ Return *rotation* normalized to an angle between 0 and 360 degrees. Parameters ---------- rotation : float or {None, 'horizontal', 'vertical'} Rotation angle in degrees. *None* and 'horizontal' equal 0, 'vertical' equals 90. Returns ------- float """ try: return float(rotation) % 360 except (ValueError, TypeError) as err: if cbook._str_equal(rotation, 'horizontal') or rotation is None: return 0. elif cbook._str_equal(rotation, 'vertical'): return 90. else: raise ValueError("rotation is {!r}; expected either 'horizontal', " "'vertical', numeric value, or None" .format(rotation)) from err class Affine2D(Affine2DBase): """ A mutable 2D affine transformation. """ def __init__(self, matrix=None, **kwargs): """ Initialize an Affine transform from a 3x3 numpy float array:: a c e b d f 0 0 1 If *matrix* is None, initialize with the identity transform. """ super().__init__(**kwargs) if matrix is None: # A bit faster than np.identity(3). matrix = IdentityTransform._mtx self._mtx = matrix.copy() self._invalid = 0 _base_str = _make_str_method("_mtx") def __str__(self): return (self._base_str() if (self._mtx != np.diag(np.diag(self._mtx))).any() else f"Affine2D().scale({self._mtx[0, 0]}, {self._mtx[1, 1]})" if self._mtx[0, 0] != self._mtx[1, 1] else f"Affine2D().scale({self._mtx[0, 0]})") def from_values(a, b, c, d, e, f): """ Create a new Affine2D instance from the given values:: a c e b d f 0 0 1 . """ return Affine2D( np.array([a, c, e, b, d, f, 0.0, 0.0, 1.0], float).reshape((3, 3))) def get_matrix(self): """ Get the underlying transformation matrix as a 3x3 numpy array:: a c e b d f 0 0 1 . """ if self._invalid: self._inverted = None self._invalid = 0 return self._mtx def set_matrix(self, mtx): """ Set the underlying transformation matrix from a 3x3 numpy array:: a c e b d f 0 0 1 . """ self._mtx = mtx self.invalidate() def set(self, other): """ Set this transformation from the frozen copy of another `Affine2DBase` object. """ _api.check_isinstance(Affine2DBase, other=other) self._mtx = other.get_matrix() self.invalidate() def identity(): """ Return a new `Affine2D` object that is the identity transform. Unless this transform will be mutated later on, consider using the faster `IdentityTransform` class instead. """ return Affine2D() def clear(self): """ Reset the underlying matrix to the identity transform. """ # A bit faster than np.identity(3). self._mtx = IdentityTransform._mtx.copy() self.invalidate() return self def rotate(self, theta): """ Add a rotation (in radians) to this transform in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ a = math.cos(theta) b = math.sin(theta) mtx = self._mtx # Operating and assigning one scalar at a time is much faster. (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist() # mtx = [[a -b 0], [b a 0], [0 0 1]] * mtx mtx[0, 0] = a * xx - b * yx mtx[0, 1] = a * xy - b * yy mtx[0, 2] = a * x0 - b * y0 mtx[1, 0] = b * xx + a * yx mtx[1, 1] = b * xy + a * yy mtx[1, 2] = b * x0 + a * y0 self.invalidate() return self def rotate_deg(self, degrees): """ Add a rotation (in degrees) to this transform in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ return self.rotate(math.radians(degrees)) def rotate_around(self, x, y, theta): """ Add a rotation (in radians) around the point (x, y) in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ return self.translate(-x, -y).rotate(theta).translate(x, y) def rotate_deg_around(self, x, y, degrees): """ Add a rotation (in degrees) around the point (x, y) in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ # Cast to float to avoid wraparound issues with uint8's x, y = float(x), float(y) return self.translate(-x, -y).rotate_deg(degrees).translate(x, y) def translate(self, tx, ty): """ Add a translation in place. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ self._mtx[0, 2] += tx self._mtx[1, 2] += ty self.invalidate() return self def scale(self, sx, sy=None): """ Add a scale in place. If *sy* is None, the same scale is applied in both the *x*- and *y*-directions. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ if sy is None: sy = sx # explicit element-wise scaling is fastest self._mtx[0, 0] *= sx self._mtx[0, 1] *= sx self._mtx[0, 2] *= sx self._mtx[1, 0] *= sy self._mtx[1, 1] *= sy self._mtx[1, 2] *= sy self.invalidate() return self def skew(self, xShear, yShear): """ Add a skew in place. *xShear* and *yShear* are the shear angles along the *x*- and *y*-axes, respectively, in radians. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ rx = math.tan(xShear) ry = math.tan(yShear) mtx = self._mtx # Operating and assigning one scalar at a time is much faster. (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist() # mtx = [[1 rx 0], [ry 1 0], [0 0 1]] * mtx mtx[0, 0] += rx * yx mtx[0, 1] += rx * yy mtx[0, 2] += rx * y0 mtx[1, 0] += ry * xx mtx[1, 1] += ry * xy mtx[1, 2] += ry * x0 self.invalidate() return self def skew_deg(self, xShear, yShear): """ Add a skew in place. *xShear* and *yShear* are the shear angles along the *x*- and *y*-axes, respectively, in degrees. Returns *self*, so this method can easily be chained with more calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` and :meth:`scale`. """ return self.skew(math.radians(xShear), math.radians(yShear)) The provided code snippet includes necessary dependencies for implementing the `_get_textbox` function. Write a Python function `def _get_textbox(text, renderer)` to solve the following problem: Calculate the bounding box of the text. The bbox position takes text rotation into account, but the width and height are those of the unrotated box (unlike `.Text.get_window_extent`). Here is the function: def _get_textbox(text, renderer): """ Calculate the bounding box of the text. The bbox position takes text rotation into account, but the width and height are those of the unrotated box (unlike `.Text.get_window_extent`). """ # TODO : This function may move into the Text class as a method. As a # matter of fact, the information from the _get_textbox function # should be available during the Text._get_layout() call, which is # called within the _get_textbox. So, it would better to move this # function as a method with some refactoring of _get_layout method. projected_xs = [] projected_ys = [] theta = np.deg2rad(text.get_rotation()) tr = Affine2D().rotate(-theta) _, parts, d = text._get_layout(renderer) for t, wh, x, y in parts: w, h = wh xt1, yt1 = tr.transform((x, y)) yt1 -= d xt2, yt2 = xt1 + w, yt1 + h projected_xs.extend([xt1, xt2]) projected_ys.extend([yt1, yt2]) xt_box, yt_box = min(projected_xs), min(projected_ys) w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box x_box, y_box = Affine2D().rotate(theta).transform((xt_box, yt_box)) return x_box, y_box, w_box, h_box
Calculate the bounding box of the text. The bbox position takes text rotation into account, but the width and height are those of the unrotated box (unlike `.Text.get_window_extent`).
171,051
import functools import logging import math from numbers import Real import weakref import numpy as np import matplotlib as mpl from . import _api, artist, cbook, _docstring from .artist import Artist from .font_manager import FontProperties from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle from .textpath import TextPath, TextToPath from .transforms import ( Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform) def _get_text_metrics_with_cache_impl( renderer_ref, text, fontprop, ismath, dpi): # dpi is unused, but participates in cache invalidation (via the renderer). return renderer_ref().get_text_width_height_descent(text, fontprop, ismath) "color": ["c"], "fontfamily": ["family"], "fontproperties": ["font", "font_properties"], "horizontalalignment": ["ha"], "multialignment": ["ma"], "fontname": ["name"], "fontsize": ["size"], "fontstretch": ["stretch"], "fontstyle": ["style"], "fontvariant": ["variant"], "verticalalignment": ["va"], "fontweight": ["weight"], The provided code snippet includes necessary dependencies for implementing the `_get_text_metrics_with_cache` function. Write a Python function `def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi)` to solve the following problem: Call ``renderer.get_text_width_height_descent``, caching the results. Here is the function: def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi): """Call ``renderer.get_text_width_height_descent``, caching the results.""" # Cached based on a copy of fontprop so that later in-place mutations of # the passed-in argument do not mess up the cache. return _get_text_metrics_with_cache_impl( weakref.ref(renderer), text, fontprop.copy(), ismath, dpi)
Call ``renderer.get_text_width_height_descent``, caching the results.
171,052
import contextlib import logging import os from pathlib import Path import sys import warnings import matplotlib as mpl from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault def use(style): """ Use Matplotlib style settings from a style specification. The style name of 'default' is reserved for reverting back to the default style settings. .. note:: This updates the `.rcParams` with the settings from the style. `.rcParams` not defined in the style are kept. Parameters ---------- style : str, dict, Path or list A style specification. Valid options are: str - One of the style names in `.style.available` (a builtin style or a style installed in the user library path). - A dotted name of the form "package.style_name"; in that case, "package" should be an importable Python package name, e.g. at ``/path/to/package/__init__.py``; the loaded style file is ``/path/to/package/style_name.mplstyle``. (Style files in subpackages are likewise supported.) - The path or URL to a style file, which gets loaded by `.rc_params_from_file`. dict A mapping of key/value pairs for `matplotlib.rcParams`. Path The path to a style file, which gets loaded by `.rc_params_from_file`. list A list of style specifiers (str, Path or dict), which are applied from first to last in the list. Notes ----- The following `.rcParams` are not related to style and will be ignored if found in a style specification: %s """ if isinstance(style, (str, Path)) or hasattr(style, 'keys'): # If name is a single str, Path or dict, make it a single element list. styles = [style] else: styles = style style_alias = {'mpl20': 'default', 'mpl15': 'classic'} for style in styles: if isinstance(style, str): style = style_alias.get(style, style) if style in _DEPRECATED_SEABORN_STYLES: _api.warn_deprecated("3.6", message=_DEPRECATED_SEABORN_MSG) style = _DEPRECATED_SEABORN_STYLES[style] if style == "default": # Deprecation warnings were already handled when creating # rcParamsDefault, no need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): # don't trigger RcParams.__getitem__('backend') style = {k: rcParamsDefault[k] for k in rcParamsDefault if k not in STYLE_BLACKLIST} elif style in library: style = library[style] elif "." in style: pkg, _, name = style.rpartition(".") try: path = (importlib_resources.files(pkg) / f"{name}.{STYLE_EXTENSION}") style = _rc_params_in_file(path) except (ModuleNotFoundError, OSError, TypeError) as exc: # There is an ambiguity whether a dotted name refers to a # package.style_name or to a dotted file path. Currently, # we silently try the first form and then the second one; # in the future, we may consider forcing file paths to # either use Path objects or be prepended with "./" and use # the slash as marker for file paths. pass if isinstance(style, (str, Path)): try: style = _rc_params_in_file(style) except IOError as err: raise IOError( f"{style!r} is not a valid package style, path of style " f"file, URL of style file, or library style name (library " f"styles are listed in `style.available`)") from err filtered = {} for k in style: # don't trigger RcParams.__getitem__('backend') if k in STYLE_BLACKLIST: _api.warn_external( f"Style includes a parameter, {k!r}, that is not " f"related to style. Ignoring this parameter.") else: filtered[k] = style[k] mpl.rcParams.update(filtered) try: import matplotlib as mpl import matplotlib.pyplot as plt has_mpl = True except ImportError: has_mpl = False The provided code snippet includes necessary dependencies for implementing the `context` function. Write a Python function `def context(style, after_reset=False)` to solve the following problem: Context manager for using style settings temporarily. Parameters ---------- style : str, dict, Path or list A style specification. Valid options are: str - One of the style names in `.style.available` (a builtin style or a style installed in the user library path). - A dotted name of the form "package.style_name"; in that case, "package" should be an importable Python package name, e.g. at ``/path/to/package/__init__.py``; the loaded style file is ``/path/to/package/style_name.mplstyle``. (Style files in subpackages are likewise supported.) - The path or URL to a style file, which gets loaded by `.rc_params_from_file`. dict A mapping of key/value pairs for `matplotlib.rcParams`. Path The path to a style file, which gets loaded by `.rc_params_from_file`. list A list of style specifiers (str, Path or dict), which are applied from first to last in the list. after_reset : bool If True, apply style after resetting settings to their defaults; otherwise, apply style on top of the current settings. Here is the function: def context(style, after_reset=False): """ Context manager for using style settings temporarily. Parameters ---------- style : str, dict, Path or list A style specification. Valid options are: str - One of the style names in `.style.available` (a builtin style or a style installed in the user library path). - A dotted name of the form "package.style_name"; in that case, "package" should be an importable Python package name, e.g. at ``/path/to/package/__init__.py``; the loaded style file is ``/path/to/package/style_name.mplstyle``. (Style files in subpackages are likewise supported.) - The path or URL to a style file, which gets loaded by `.rc_params_from_file`. dict A mapping of key/value pairs for `matplotlib.rcParams`. Path The path to a style file, which gets loaded by `.rc_params_from_file`. list A list of style specifiers (str, Path or dict), which are applied from first to last in the list. after_reset : bool If True, apply style after resetting settings to their defaults; otherwise, apply style on top of the current settings. """ with mpl.rc_context(): if after_reset: mpl.rcdefaults() use(style) yield
Context manager for using style settings temporarily. Parameters ---------- style : str, dict, Path or list A style specification. Valid options are: str - One of the style names in `.style.available` (a builtin style or a style installed in the user library path). - A dotted name of the form "package.style_name"; in that case, "package" should be an importable Python package name, e.g. at ``/path/to/package/__init__.py``; the loaded style file is ``/path/to/package/style_name.mplstyle``. (Style files in subpackages are likewise supported.) - The path or URL to a style file, which gets loaded by `.rc_params_from_file`. dict A mapping of key/value pairs for `matplotlib.rcParams`. Path The path to a style file, which gets loaded by `.rc_params_from_file`. list A list of style specifiers (str, Path or dict), which are applied from first to last in the list. after_reset : bool If True, apply style after resetting settings to their defaults; otherwise, apply style on top of the current settings.
171,053
import contextlib import logging import os from pathlib import Path import sys import warnings import matplotlib as mpl from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault def update_user_library(library): """Update style library with user-defined rc files.""" for stylelib_path in map(os.path.expanduser, USER_LIBRARY_PATHS): styles = read_style_directory(stylelib_path) update_nested_dict(library, styles) return library _base_library = read_style_directory(BASE_LIBRARY_PATH) library = _StyleLibrary() available = [] The provided code snippet includes necessary dependencies for implementing the `reload_library` function. Write a Python function `def reload_library()` to solve the following problem: Reload the style library. Here is the function: def reload_library(): """Reload the style library.""" library.clear() library.update(update_user_library(_base_library)) available[:] = sorted(library.keys())
Reload the style library.
171,054
from matplotlib.backend_bases import RendererBase from matplotlib import colors as mcolors from matplotlib import patches as mpatches from matplotlib import transforms as mtransforms from matplotlib.path import Path import numpy as np The provided code snippet includes necessary dependencies for implementing the `_subclass_with_normal` function. Write a Python function `def _subclass_with_normal(effect_class)` to solve the following problem: Create a PathEffect class combining *effect_class* and a normal draw. Here is the function: def _subclass_with_normal(effect_class): """ Create a PathEffect class combining *effect_class* and a normal draw. """ class withEffect(effect_class): def draw_path(self, renderer, gc, tpath, affine, rgbFace): super().draw_path(renderer, gc, tpath, affine, rgbFace) renderer.draw_path(gc, tpath, affine, rgbFace) withEffect.__name__ = f"with{effect_class.__name__}" withEffect.__qualname__ = f"with{effect_class.__name__}" withEffect.__doc__ = f""" A shortcut PathEffect for applying `.{effect_class.__name__}` and then drawing the original Artist. With this class you can use :: artist.set_path_effects([path_effects.with{effect_class.__name__}()]) as a shortcut for :: artist.set_path_effects([path_effects.{effect_class.__name__}(), path_effects.Normal()]) """ # Docstring inheritance doesn't work for locally-defined subclasses. withEffect.draw_path.__doc__ = effect_class.draw_path.__doc__ return withEffect
Create a PathEffect class combining *effect_class* and a normal draw.
171,055
from functools import partial import numpy as np def _flag_red(x): return 0.75 * np.sin((x * 31.5 + 0.25) * np.pi) + 0.5
null
171,056
from functools import partial import numpy as np def _flag_green(x): return np.sin(x * 31.5 * np.pi)
null
171,057
from functools import partial import numpy as np def _flag_blue(x): return 0.75 * np.sin((x * 31.5 - 0.25) * np.pi) + 0.5
null
171,058
from functools import partial import numpy as np def _prism_red(x): return 0.75 * np.sin((x * 20.9 + 0.25) * np.pi) + 0.67
null
171,059
from functools import partial import numpy as np def _prism_green(x): return 0.75 * np.sin((x * 20.9 - 0.25) * np.pi) + 0.33
null
171,060
from functools import partial import numpy as np def _prism_blue(x): return -1.1 * np.sin((x * 20.9) * np.pi)
null
171,061
from functools import partial import numpy as np def _ch_helper(gamma, s, r, h, p0, p1, x): """Helper function for generating picklable cubehelix colormaps.""" # Apply gamma factor to emphasise low or high intensity values xg = x ** gamma # Calculate amplitude and angle of deviation from the black to white # diagonal in the plane of constant perceived intensity. a = h * xg * (1 - xg) / 2 phi = 2 * np.pi * (s / 3 + r * x) return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi)) class partial(Generic[_T]): func: Callable[..., _T] args: Tuple[Any, ...] keywords: Dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... The provided code snippet includes necessary dependencies for implementing the `cubehelix` function. Write a Python function `def cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0)` to solve the following problem: Return custom data dictionary of (r, g, b) conversion functions, which can be used with :func:`register_cmap`, for the cubehelix color scheme. Unlike most other color schemes cubehelix was designed by D.A. Green to be monotonically increasing in terms of perceived brightness. Also, when printed on a black and white postscript printer, the scheme results in a greyscale with monotonically increasing brightness. This color scheme is named cubehelix because the (r, g, b) values produced can be visualised as a squashed helix around the diagonal in the (r, g, b) color cube. For a unit color cube (i.e. 3D coordinates for (r, g, b) each in the range 0 to 1) the color scheme starts at (r, g, b) = (0, 0, 0), i.e. black, and finishes at (r, g, b) = (1, 1, 1), i.e. white. For some fraction *x*, between 0 and 1, the color is the corresponding grey value at that fraction along the black to white diagonal (x, x, x) plus a color element. This color element is calculated in a plane of constant perceived intensity and controlled by the following parameters. Parameters ---------- gamma : float, default: 1 Gamma factor emphasizing either low intensity values (gamma < 1), or high intensity values (gamma > 1). s : float, default: 0.5 (purple) The starting color. r : float, default: -1.5 The number of r, g, b rotations in color that are made from the start to the end of the color scheme. The default of -1.5 corresponds to -> B -> G -> R -> B. h : float, default: 1 The hue, i.e. how saturated the colors are. If this parameter is zero then the color scheme is purely a greyscale. Here is the function: def cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0): """ Return custom data dictionary of (r, g, b) conversion functions, which can be used with :func:`register_cmap`, for the cubehelix color scheme. Unlike most other color schemes cubehelix was designed by D.A. Green to be monotonically increasing in terms of perceived brightness. Also, when printed on a black and white postscript printer, the scheme results in a greyscale with monotonically increasing brightness. This color scheme is named cubehelix because the (r, g, b) values produced can be visualised as a squashed helix around the diagonal in the (r, g, b) color cube. For a unit color cube (i.e. 3D coordinates for (r, g, b) each in the range 0 to 1) the color scheme starts at (r, g, b) = (0, 0, 0), i.e. black, and finishes at (r, g, b) = (1, 1, 1), i.e. white. For some fraction *x*, between 0 and 1, the color is the corresponding grey value at that fraction along the black to white diagonal (x, x, x) plus a color element. This color element is calculated in a plane of constant perceived intensity and controlled by the following parameters. Parameters ---------- gamma : float, default: 1 Gamma factor emphasizing either low intensity values (gamma < 1), or high intensity values (gamma > 1). s : float, default: 0.5 (purple) The starting color. r : float, default: -1.5 The number of r, g, b rotations in color that are made from the start to the end of the color scheme. The default of -1.5 corresponds to -> B -> G -> R -> B. h : float, default: 1 The hue, i.e. how saturated the colors are. If this parameter is zero then the color scheme is purely a greyscale. """ return {'red': partial(_ch_helper, gamma, s, r, h, -0.14861, 1.78277), 'green': partial(_ch_helper, gamma, s, r, h, -0.29227, -0.90649), 'blue': partial(_ch_helper, gamma, s, r, h, 1.97294, 0.0)}
Return custom data dictionary of (r, g, b) conversion functions, which can be used with :func:`register_cmap`, for the cubehelix color scheme. Unlike most other color schemes cubehelix was designed by D.A. Green to be monotonically increasing in terms of perceived brightness. Also, when printed on a black and white postscript printer, the scheme results in a greyscale with monotonically increasing brightness. This color scheme is named cubehelix because the (r, g, b) values produced can be visualised as a squashed helix around the diagonal in the (r, g, b) color cube. For a unit color cube (i.e. 3D coordinates for (r, g, b) each in the range 0 to 1) the color scheme starts at (r, g, b) = (0, 0, 0), i.e. black, and finishes at (r, g, b) = (1, 1, 1), i.e. white. For some fraction *x*, between 0 and 1, the color is the corresponding grey value at that fraction along the black to white diagonal (x, x, x) plus a color element. This color element is calculated in a plane of constant perceived intensity and controlled by the following parameters. Parameters ---------- gamma : float, default: 1 Gamma factor emphasizing either low intensity values (gamma < 1), or high intensity values (gamma > 1). s : float, default: 0.5 (purple) The starting color. r : float, default: -1.5 The number of r, g, b rotations in color that are made from the start to the end of the color scheme. The default of -1.5 corresponds to -> B -> G -> R -> B. h : float, default: 1 The hue, i.e. how saturated the colors are. If this parameter is zero then the color scheme is purely a greyscale.
171,062
from functools import partial import numpy as np def _g0(x): return 0
null
171,063
from functools import partial import numpy as np def _g1(x): return 0.5
null
171,064
from functools import partial import numpy as np def _g2(x): return 1
null
171,065
from functools import partial import numpy as np def _g3(x): return x
null
171,066
from functools import partial import numpy as np def _g4(x): return x ** 2
null
171,067
from functools import partial import numpy as np def _g5(x): return x ** 3
null
171,068
from functools import partial import numpy as np def _g6(x): return x ** 4
null
171,069
from functools import partial import numpy as np def _g7(x): return np.sqrt(x)
null
171,070
from functools import partial import numpy as np def _g8(x): return np.sqrt(np.sqrt(x))
null
171,071
from functools import partial import numpy as np def _g9(x): return np.sin(x * np.pi / 2)
null
171,072
from functools import partial import numpy as np def _g10(x): return np.cos(x * np.pi / 2)
null
171,073
from functools import partial import numpy as np def _g11(x): return np.abs(x - 0.5)
null
171,074
from functools import partial import numpy as np def _g12(x): return (2 * x - 1) ** 2
null
171,075
from functools import partial import numpy as np def _g13(x): return np.sin(x * np.pi)
null
171,076
from functools import partial import numpy as np def _g14(x): return np.abs(np.cos(x * np.pi))
null
171,077
from functools import partial import numpy as np def _g15(x): return np.sin(x * 2 * np.pi)
null
171,078
from functools import partial import numpy as np def _g16(x): return np.cos(x * 2 * np.pi)
null
171,079
from functools import partial import numpy as np def _g17(x): return np.abs(np.sin(x * 2 * np.pi))
null
171,080
from functools import partial import numpy as np def _g18(x): return np.abs(np.cos(x * 2 * np.pi))
null
171,081
from functools import partial import numpy as np def _g19(x): return np.abs(np.sin(x * 4 * np.pi))
null
171,082
from functools import partial import numpy as np def _g20(x): return np.abs(np.cos(x * 4 * np.pi))
null
171,083
from functools import partial import numpy as np def _g21(x): return 3 * x
null
171,084
from functools import partial import numpy as np def _g22(x): return 3 * x - 1
null
171,085
from functools import partial import numpy as np def _g23(x): return 3 * x - 2
null
171,086
from functools import partial import numpy as np def _g24(x): return np.abs(3 * x - 1)
null
171,087
from functools import partial import numpy as np def _g25(x): return np.abs(3 * x - 2)
null
171,088
from functools import partial import numpy as np def _g26(x): return (3 * x - 1) / 2
null
171,089
from functools import partial import numpy as np def _g27(x): return (3 * x - 2) / 2
null
171,090
from functools import partial import numpy as np def _g28(x): return np.abs((3 * x - 1) / 2)
null
171,091
from functools import partial import numpy as np def _g29(x): return np.abs((3 * x - 2) / 2)
null
171,092
from functools import partial import numpy as np def _g30(x): return x / 0.32 - 0.78125
null
171,093
from functools import partial import numpy as np def _g31(x): return 2 * x - 0.84
null
171,094
from functools import partial import numpy as np def _g32(x): ret = np.zeros(len(x)) m = (x < 0.25) ret[m] = 4 * x[m] m = (x >= 0.25) & (x < 0.92) ret[m] = -2 * x[m] + 1.84 m = (x >= 0.92) ret[m] = x[m] / 0.08 - 11.5 return ret
null
171,095
from functools import partial import numpy as np def _g33(x): return np.abs(2 * x - 0.5)
null
171,096
from functools import partial import numpy as np def _g34(x): return 2 * x
null
171,097
from functools import partial import numpy as np def _g35(x): return 2 * x - 0.5
null
171,098
from functools import partial import numpy as np def _g36(x): return 2 * x - 1
null
171,099
from functools import partial import numpy as np def _gist_heat_red(x): return 1.5 * x
null
171,100
from functools import partial import numpy as np def _gist_heat_green(x): return 2 * x - 1
null
171,101
from functools import partial import numpy as np def _gist_heat_blue(x): return 4 * x - 3
null
171,102
from functools import partial import numpy as np def _gist_yarg(x): return 1 - x
null
171,103
import math import numpy as np from numpy import ma from matplotlib import _api, cbook, _docstring import matplotlib.artist as martist import matplotlib.collections as mcollections from matplotlib.patches import CirclePolygon import matplotlib.text as mtext import matplotlib.transforms as transforms The provided code snippet includes necessary dependencies for implementing the `_parse_args` function. Write a Python function `def _parse_args(*args, caller_name='function')` to solve the following problem: Helper function to parse positional parameters for colored vector plots. This is currently used for Quiver and Barbs. Parameters ---------- *args : list list of 2-5 arguments. Depending on their number they are parsed to:: U, V U, V, C X, Y, U, V X, Y, U, V, C caller_name : str Name of the calling method (used in error messages). Here is the function: def _parse_args(*args, caller_name='function'): """ Helper function to parse positional parameters for colored vector plots. This is currently used for Quiver and Barbs. Parameters ---------- *args : list list of 2-5 arguments. Depending on their number they are parsed to:: U, V U, V, C X, Y, U, V X, Y, U, V, C caller_name : str Name of the calling method (used in error messages). """ X = Y = C = None nargs = len(args) if nargs == 2: # The use of atleast_1d allows for handling scalar arguments while also # keeping masked arrays U, V = np.atleast_1d(*args) elif nargs == 3: U, V, C = np.atleast_1d(*args) elif nargs == 4: X, Y, U, V = np.atleast_1d(*args) elif nargs == 5: X, Y, U, V, C = np.atleast_1d(*args) else: raise _api.nargs_error(caller_name, takes="from 2 to 5", given=nargs) nr, nc = (1, U.shape[0]) if U.ndim == 1 else U.shape if X is not None: X = X.ravel() Y = Y.ravel() if len(X) == nc and len(Y) == nr: X, Y = [a.ravel() for a in np.meshgrid(X, Y)] elif len(X) != len(Y): raise ValueError('X and Y must be the same size, but ' f'X.size is {X.size} and Y.size is {Y.size}.') else: indexgrid = np.meshgrid(np.arange(nc), np.arange(nr)) X, Y = [np.ravel(a) for a in indexgrid] # Size validation for U, V, C is left to the set_UVC method. return X, Y, U, V, C
Helper function to parse positional parameters for colored vector plots. This is currently used for Quiver and Barbs. Parameters ---------- *args : list list of 2-5 arguments. Depending on their number they are parsed to:: U, V U, V, C X, Y, U, V X, Y, U, V, C caller_name : str Name of the calling method (used in error messages).
171,104
import math import numpy as np from numpy import ma from matplotlib import _api, cbook, _docstring import matplotlib.artist as martist import matplotlib.collections as mcollections from matplotlib.patches import CirclePolygon import matplotlib.text as mtext import matplotlib.transforms as transforms def _check_consistent_shapes(*arrays): all_shapes = {a.shape for a in arrays} if len(all_shapes) != 1: raise ValueError('The shapes of the passed in arrays do not match')
null
171,105
from collections.abc import Iterable, Sequence from contextlib import ExitStack import functools import inspect import itertools import logging from numbers import Real from operator import attrgetter 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 }) The provided code snippet includes necessary dependencies for implementing the `_process_plot_format` function. Write a Python function `def _process_plot_format(fmt, *, ambiguous_fmt_datakey=False)` to solve the following problem: 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. Here is the function: 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 # Is fmt just a colorspec? try: color = mcolors.to_rgba(fmt) # We need to differentiate grayscale '1.0' from tri_down marker '1' try: fmtint = str(int(fmt)) except ValueError: return linestyle, marker, color # Yes else: if fmt != fmtint: # user definitely doesn't want tri_down marker return linestyle, marker, color # Yes else: # ignore converted color color = None except ValueError: pass # No, not just a color. 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' and i < len(fmt) - 1: color_cycle_number = int(fmt[i + 1]) color = mcolors.to_rgba("C{}".format(color_cycle_number)) i += 2 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
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.
171,106
from collections.abc import Iterable, Sequence from contextlib import ExitStack import functools import inspect import itertools import logging from numbers import Real from operator import attrgetter 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 The provided code snippet includes necessary dependencies for implementing the `_draw_rasterized` function. Write a Python function `def _draw_rasterized(figure, artists, renderer)` to solve the following problem: 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 re-use 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 Here is the function: 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 re-use 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)
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 re-use 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
171,107
import logging import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, collections, cm, colors, contour, ticker import matplotlib.artist as martist import matplotlib.patches as mpatches import matplotlib.path as mpath import matplotlib.spines as mspines import matplotlib.transforms as mtransforms from matplotlib import _docstring def _set_ticks_on_axis_warn(*args, **kwargs): # a top level function which gets put in at the axes' # set_xticks and set_yticks by Colorbar.__init__. _api.warn_external("Use the colorbar set_ticks() method instead.")
null
171,108
import logging import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, collections, cm, colors, contour, ticker import matplotlib.artist as martist import matplotlib.patches as mpatches import matplotlib.path as mpath import matplotlib.spines as mspines import matplotlib.transforms as mtransforms from matplotlib import _docstring def _normalize_location_orientation(location, orientation): if location is None: location = _get_ticklocation_from_orientation(orientation) loc_settings = _api.check_getitem({ "left": {"location": "left", "anchor": (1.0, 0.5), "panchor": (0.0, 0.5), "pad": 0.10}, "right": {"location": "right", "anchor": (0.0, 0.5), "panchor": (1.0, 0.5), "pad": 0.05}, "top": {"location": "top", "anchor": (0.5, 0.0), "panchor": (0.5, 1.0), "pad": 0.05}, "bottom": {"location": "bottom", "anchor": (0.5, 1.0), "panchor": (0.5, 0.0), "pad": 0.15}, }, location=location) loc_settings["orientation"] = _get_orientation_from_location(location) if orientation is not None and orientation != loc_settings["orientation"]: # Allow the user to pass both if they are consistent. raise TypeError("location and orientation are mutually exclusive") return loc_settings The provided code snippet includes necessary dependencies for implementing the `make_axes` function. Write a Python function `def make_axes(parents, location=None, orientation=None, fraction=0.15, shrink=1.0, aspect=20, **kwargs)` to solve the following problem: Create an `~.axes.Axes` suitable for a colorbar. The axes is placed in the figure of the *parents* axes, by resizing and repositioning *parents*. Parameters ---------- parents : `~.axes.Axes` or iterable or `numpy.ndarray` of `~.axes.Axes` The Axes to use as parents for placing the colorbar. %(_make_axes_kw_doc)s Returns ------- cax : `~.axes.Axes` The child axes. kwargs : dict The reduced keyword dictionary to be passed when creating the colorbar instance. Here is the function: def make_axes(parents, location=None, orientation=None, fraction=0.15, shrink=1.0, aspect=20, **kwargs): """ Create an `~.axes.Axes` suitable for a colorbar. The axes is placed in the figure of the *parents* axes, by resizing and repositioning *parents*. Parameters ---------- parents : `~.axes.Axes` or iterable or `numpy.ndarray` of `~.axes.Axes` The Axes to use as parents for placing the colorbar. %(_make_axes_kw_doc)s Returns ------- cax : `~.axes.Axes` The child axes. kwargs : dict The reduced keyword dictionary to be passed when creating the colorbar instance. """ loc_settings = _normalize_location_orientation(location, orientation) # put appropriate values into the kwargs dict for passing back to # the Colorbar class kwargs['orientation'] = loc_settings['orientation'] location = kwargs['ticklocation'] = loc_settings['location'] anchor = kwargs.pop('anchor', loc_settings['anchor']) panchor = kwargs.pop('panchor', loc_settings['panchor']) aspect0 = aspect # turn parents into a list if it is not already. Note we cannot # use .flatten or .ravel as these copy the references rather than # reuse them, leading to a memory leak if isinstance(parents, np.ndarray): parents = list(parents.flat) elif np.iterable(parents): parents = list(parents) else: parents = [parents] fig = parents[0].get_figure() pad0 = 0.05 if fig.get_constrained_layout() else loc_settings['pad'] pad = kwargs.pop('pad', pad0) if not all(fig is ax.get_figure() for ax in parents): raise ValueError('Unable to create a colorbar axes as not all ' 'parents share the same figure.') # take a bounding box around all of the given axes parents_bbox = mtransforms.Bbox.union( [ax.get_position(original=True).frozen() for ax in parents]) pb = parents_bbox if location in ('left', 'right'): if location == 'left': pbcb, _, pb1 = pb.splitx(fraction, fraction + pad) else: pb1, _, pbcb = pb.splitx(1 - fraction - pad, 1 - fraction) pbcb = pbcb.shrunk(1.0, shrink).anchored(anchor, pbcb) else: if location == 'bottom': pbcb, _, pb1 = pb.splity(fraction, fraction + pad) else: pb1, _, pbcb = pb.splity(1 - fraction - pad, 1 - fraction) pbcb = pbcb.shrunk(shrink, 1.0).anchored(anchor, pbcb) # define the aspect ratio in terms of y's per x rather than x's per y aspect = 1.0 / aspect # define a transform which takes us from old axes coordinates to # new axes coordinates shrinking_trans = mtransforms.BboxTransform(parents_bbox, pb1) # transform each of the axes in parents using the new transform for ax in parents: new_posn = shrinking_trans.transform(ax.get_position(original=True)) new_posn = mtransforms.Bbox(new_posn) ax._set_position(new_posn) if panchor is not False: ax.set_anchor(panchor) cax = fig.add_axes(pbcb, label="<colorbar>") for a in parents: # tell the parent it has a colorbar a._colorbars += [cax] cax._colorbar_info = dict( parents=parents, location=location, shrink=shrink, anchor=anchor, panchor=panchor, fraction=fraction, aspect=aspect0, pad=pad) # and we need to set the aspect ratio by hand... cax.set_anchor(anchor) cax.set_box_aspect(aspect) cax.set_aspect('auto') return cax, kwargs
Create an `~.axes.Axes` suitable for a colorbar. The axes is placed in the figure of the *parents* axes, by resizing and repositioning *parents*. Parameters ---------- parents : `~.axes.Axes` or iterable or `numpy.ndarray` of `~.axes.Axes` The Axes to use as parents for placing the colorbar. %(_make_axes_kw_doc)s Returns ------- cax : `~.axes.Axes` The child axes. kwargs : dict The reduced keyword dictionary to be passed when creating the colorbar instance.
171,109
import logging import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, collections, cm, colors, contour, ticker import matplotlib.artist as martist import matplotlib.patches as mpatches import matplotlib.path as mpath import matplotlib.spines as mspines import matplotlib.transforms as mtransforms from matplotlib import _docstring def _normalize_location_orientation(location, orientation): if location is None: location = _get_ticklocation_from_orientation(orientation) loc_settings = _api.check_getitem({ "left": {"location": "left", "anchor": (1.0, 0.5), "panchor": (0.0, 0.5), "pad": 0.10}, "right": {"location": "right", "anchor": (0.0, 0.5), "panchor": (1.0, 0.5), "pad": 0.05}, "top": {"location": "top", "anchor": (0.5, 0.0), "panchor": (0.5, 1.0), "pad": 0.05}, "bottom": {"location": "bottom", "anchor": (0.5, 1.0), "panchor": (0.5, 0.0), "pad": 0.15}, }, location=location) loc_settings["orientation"] = _get_orientation_from_location(location) if orientation is not None and orientation != loc_settings["orientation"]: # Allow the user to pass both if they are consistent. raise TypeError("location and orientation are mutually exclusive") return loc_settings The provided code snippet includes necessary dependencies for implementing the `make_axes_gridspec` function. Write a Python function `def make_axes_gridspec(parent, *, location=None, orientation=None, fraction=0.15, shrink=1.0, aspect=20, **kwargs)` to solve the following problem: Create an `~.axes.Axes` suitable for a colorbar. The axes is placed in the figure of the *parent* axes, by resizing and repositioning *parent*. This function is similar to `.make_axes` and mostly compatible with it. Primary differences are - `.make_axes_gridspec` requires the *parent* to have a subplotspec. - `.make_axes` positions the axes in figure coordinates; `.make_axes_gridspec` positions it using a subplotspec. - `.make_axes` updates the position of the parent. `.make_axes_gridspec` replaces the parent gridspec with a new one. Parameters ---------- parent : `~.axes.Axes` The Axes to use as parent for placing the colorbar. %(_make_axes_kw_doc)s Returns ------- cax : `~.axes.Axes` The child axes. kwargs : dict The reduced keyword dictionary to be passed when creating the colorbar instance. Here is the function: def make_axes_gridspec(parent, *, location=None, orientation=None, fraction=0.15, shrink=1.0, aspect=20, **kwargs): """ Create an `~.axes.Axes` suitable for a colorbar. The axes is placed in the figure of the *parent* axes, by resizing and repositioning *parent*. This function is similar to `.make_axes` and mostly compatible with it. Primary differences are - `.make_axes_gridspec` requires the *parent* to have a subplotspec. - `.make_axes` positions the axes in figure coordinates; `.make_axes_gridspec` positions it using a subplotspec. - `.make_axes` updates the position of the parent. `.make_axes_gridspec` replaces the parent gridspec with a new one. Parameters ---------- parent : `~.axes.Axes` The Axes to use as parent for placing the colorbar. %(_make_axes_kw_doc)s Returns ------- cax : `~.axes.Axes` The child axes. kwargs : dict The reduced keyword dictionary to be passed when creating the colorbar instance. """ loc_settings = _normalize_location_orientation(location, orientation) kwargs['orientation'] = loc_settings['orientation'] location = kwargs['ticklocation'] = loc_settings['location'] aspect0 = aspect anchor = kwargs.pop('anchor', loc_settings['anchor']) panchor = kwargs.pop('panchor', loc_settings['panchor']) pad = kwargs.pop('pad', loc_settings["pad"]) wh_space = 2 * pad / (1 - pad) if location in ('left', 'right'): # for shrinking height_ratios = [ (1-anchor[1])*(1-shrink), shrink, anchor[1]*(1-shrink)] if location == 'left': gs = parent.get_subplotspec().subgridspec( 1, 2, wspace=wh_space, width_ratios=[fraction, 1-fraction-pad]) ss_main = gs[1] ss_cb = gs[0].subgridspec( 3, 1, hspace=0, height_ratios=height_ratios)[1] else: gs = parent.get_subplotspec().subgridspec( 1, 2, wspace=wh_space, width_ratios=[1-fraction-pad, fraction]) ss_main = gs[0] ss_cb = gs[1].subgridspec( 3, 1, hspace=0, height_ratios=height_ratios)[1] else: # for shrinking width_ratios = [ anchor[0]*(1-shrink), shrink, (1-anchor[0])*(1-shrink)] if location == 'bottom': gs = parent.get_subplotspec().subgridspec( 2, 1, hspace=wh_space, height_ratios=[1-fraction-pad, fraction]) ss_main = gs[0] ss_cb = gs[1].subgridspec( 1, 3, wspace=0, width_ratios=width_ratios)[1] aspect = 1 / aspect else: gs = parent.get_subplotspec().subgridspec( 2, 1, hspace=wh_space, height_ratios=[fraction, 1-fraction-pad]) ss_main = gs[1] ss_cb = gs[0].subgridspec( 1, 3, wspace=0, width_ratios=width_ratios)[1] aspect = 1 / aspect parent.set_subplotspec(ss_main) if panchor is not False: parent.set_anchor(panchor) fig = parent.get_figure() cax = fig.add_subplot(ss_cb, label="<colorbar>") cax.set_anchor(anchor) cax.set_box_aspect(aspect) cax.set_aspect('auto') cax._colorbar_info = dict( location=location, parents=[parent], shrink=shrink, anchor=anchor, panchor=panchor, fraction=fraction, aspect=aspect0, pad=pad) return cax, kwargs
Create an `~.axes.Axes` suitable for a colorbar. The axes is placed in the figure of the *parent* axes, by resizing and repositioning *parent*. This function is similar to `.make_axes` and mostly compatible with it. Primary differences are - `.make_axes_gridspec` requires the *parent* to have a subplotspec. - `.make_axes` positions the axes in figure coordinates; `.make_axes_gridspec` positions it using a subplotspec. - `.make_axes` updates the position of the parent. `.make_axes_gridspec` replaces the parent gridspec with a new one. Parameters ---------- parent : `~.axes.Axes` The Axes to use as parent for placing the colorbar. %(_make_axes_kw_doc)s Returns ------- cax : `~.axes.Axes` The child axes. kwargs : dict The reduced keyword dictionary to be passed when creating the colorbar instance.