Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/importlib_metadata/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/_adapters.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/_collections.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/_compat.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/_context.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/_functools.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/_itertools.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/_meta.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/_text.cpython-312.pycAdded
- lib/python3.12/site-packages/importlib_metadata/__pycache__/diagnose.cpython-312.pycAdded
- lib/python3.12/site-packages/matplotlib/_afm.pyAdded+532
- lib/python3.12/site-packages/matplotlib/_animation_data.pyAdded+262
- lib/python3.12/site-packages/matplotlib/_cm_listed.pyAdded
- lib/python3.12/site-packages/matplotlib/_color_data.pyAdded+1141
- lib/python3.12/site-packages/matplotlib/_docstring.pyAdded+141
- lib/python3.12/site-packages/matplotlib/_layoutgrid.pyAdded+547
- lib/python3.12/site-packages/matplotlib/_path.pyiAdded+9
- lib/python3.12/site-packages/matplotlib/_qhull.pyiAdded
- lib/python3.12/site-packages/matplotlib/_tight_layout.pyAdded+301
- lib/python3.12/site-packages/matplotlib/animation.pyiAdded+217
- lib/python3.12/site-packages/matplotlib/artist.pyAdded+1855
- lib/python3.12/site-packages/matplotlib/artist.pyiAdded+199
- lib/python3.12/site-packages/matplotlib/backend_bases.pyiAdded+482
- lib/python3.12/site-packages/matplotlib/cm.pyiAdded+24
- lib/python3.12/site-packages/matplotlib/collections.pyiAdded+262
- lib/python3.12/site-packages/matplotlib/colorbar.pyAdded+1563
- lib/python3.12/site-packages/matplotlib/colorizer.pyiAdded+102
- lib/python3.12/site-packages/matplotlib/colors.pyAdded
- lib/python3.12/site-packages/matplotlib/colors.pyiAdded+449
- lib/python3.12/site-packages/matplotlib/container.pyiAdded+56
- lib/python3.12/site-packages/matplotlib/figure.pyAdded
- lib/python3.12/site-packages/matplotlib/gridspec.pyiAdded+160
- lib/python3.12/site-packages/matplotlib/hatch.pyAdded+225
- lib/python3.12/site-packages/matplotlib/hatch.pyiAdded+68
- lib/python3.12/site-packages/matplotlib/image.pyAdded+1786
- lib/python3.12/site-packages/matplotlib/inset.pyiAdded+25
- lib/python3.12/site-packages/matplotlib/legend_handler.pyAdded+813
- lib/python3.12/site-packages/matplotlib/legend_handler.pyiAdded+294
- lib/python3.12/site-packages/matplotlib/markers.pyAdded+908
- lib/python3.12/site-packages/matplotlib/mlab.pyAdded+913
- lib/python3.12/site-packages/matplotlib/offsetbox.pyAdded+1613
- lib/python3.12/site-packages/matplotlib/patheffects.pyiAdded+106
- lib/python3.12/site-packages/matplotlib/quiver.pyiAdded+184
- lib/python3.12/site-packages/matplotlib/scale.pyiAdded+178
- lib/python3.12/site-packages/matplotlib/spines.pyAdded+596
- lib/python3.12/site-packages/matplotlib/stackplot.pyAdded+147
- lib/python3.12/site-packages/matplotlib/streamplot.pyAdded+712
- lib/python3.12/site-packages/matplotlib/style/__init__.pyAdded+4
- lib/python3.12/site-packages/matplotlib/style/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/matplotlib/style/__pycache__/core.cpython-312.pycAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532"""A python interface to Adobe Font Metrics Files.
Although a number of other Python implementations exist, and may be morecomplete than this, it was decided not to go with them because they wereeither:
1) copyrighted or used a non-BSD compatible license2) had too many dependencies and a free standing lib was needed3) did more than needed and it was easier to write afresh rather than figure out how to get just what was needed.
It is pretty easy to use, and has no external dependencies:
>>> import matplotlib as mpl>>> from pathlib import Path>>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm')>>>>>> from matplotlib.afm import AFM>>> with afm_path.open('rb') as fh:... afm = AFM(fh)>>> afm.string_width_height('What the heck?')(6220.0, 694)>>> afm.get_fontname()'Times-Roman'>>> afm.get_kern_dist('A', 'f')0>>> afm.get_kern_dist('A', 'y')-92.0>>> afm.get_bbox_char('!')[130, -9, 238, 676]
As in the Adobe Font Metrics File Format Specification, all dimensionsare given in units of 1/1000 of the scale factor (point size) of the fontbeing used."""
from collections import namedtupleimport loggingimport re
from ._mathtext_data import uni2type1
_log = logging.getLogger(__name__)
def _to_int(x): # Some AFM files have floats where we are expecting ints -- there is # probably a better way to handle this (support floats, round rather than # truncate). But I don't know what the best approach is now and this # change to _to_int should at least prevent Matplotlib from crashing on # these. JDH (2009-11-06) return int(float(x))
def _to_float(x): # Some AFM files use "," instead of "." as decimal separator -- this # shouldn't be ambiguous (unless someone is wicked enough to use "," as # thousands separator...). if isinstance(x, bytes): # Encoding doesn't really matter -- if we have codepoints >127 the call # to float() will error anyways. x = x.decode('latin-1') return float(x.replace(',', '.'))
def _to_str(x): return x.decode('utf8')
def _to_list_of_ints(s): s = s.replace(b',', b' ') return [_to_int(val) for val in s.split()]
def _to_list_of_floats(s): return [_to_float(val) for val in s.split()]
def _to_bool(s): if s.lower().strip() in (b'false', b'0', b'no'): return False else: return True
def _parse_header(fh): """ Read the font metrics header (up to the char metrics) and returns a dictionary mapping *key* to *val*. *val* will be converted to the appropriate python type as necessary; e.g.:
* 'False'->False * '0'->0 * '-168 -218 1000 898'-> [-168, -218, 1000, 898]
Dictionary keys are
StartFontMetrics, FontName, FullName, FamilyName, Weight, ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition, UnderlineThickness, Version, Notice, EncodingScheme, CapHeight, XHeight, Ascender, Descender, StartCharMetrics """ header_converters = { b'StartFontMetrics': _to_float, b'FontName': _to_str, b'FullName': _to_str, b'FamilyName': _to_str, b'Weight': _to_str, b'ItalicAngle': _to_float, b'IsFixedPitch': _to_bool, b'FontBBox': _to_list_of_ints, b'UnderlinePosition': _to_float, b'UnderlineThickness': _to_float, b'Version': _to_str, # Some AFM files have non-ASCII characters (which are not allowed by # the spec). Given that there is actually no public API to even access # this field, just return it as straight bytes. b'Notice': lambda x: x, b'EncodingScheme': _to_str, b'CapHeight': _to_float, # Is the second version a mistake, or b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS b'XHeight': _to_float, b'Ascender': _to_float, b'Descender': _to_float, b'StdHW': _to_float, b'StdVW': _to_float, b'StartCharMetrics': _to_int, b'CharacterSet': _to_str, b'Characters': _to_int, } d = {} first_line = True for line in fh: line = line.rstrip() if line.startswith(b'Comment'): continue lst = line.split(b' ', 1) key = lst[0] if first_line: # AFM spec, Section 4: The StartFontMetrics keyword # [followed by a version number] must be the first line in # the file, and the EndFontMetrics keyword must be the # last non-empty line in the file. We just check the # first header entry. if key != b'StartFontMetrics': raise RuntimeError('Not an AFM file') first_line = False if len(lst) == 2: val = lst[1] else: val = b'' try: converter = header_converters[key] except KeyError: _log.error("Found an unknown keyword in AFM header (was %r)", key) continue try: d[key] = converter(val) except ValueError: _log.error('Value error parsing header in AFM: %s, %s', key, val) continue if key == b'StartCharMetrics': break else: raise RuntimeError('Bad parse') return d
CharMetrics = namedtuple('CharMetrics', 'width, name, bbox')CharMetrics.__doc__ = """ Represents the character metrics of a single character.
Notes ----- The fields do currently only describe a subset of character metrics information defined in the AFM standard. """CharMetrics.width.__doc__ = """The character width (WX)."""CharMetrics.name.__doc__ = """The character name (N)."""CharMetrics.bbox.__doc__ = """ The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*)."""
def _parse_char_metrics(fh): """ Parse the given filehandle for character metrics information and return the information as dicts.
It is assumed that the file cursor is on the line behind 'StartCharMetrics'.
Returns ------- ascii_d : dict A mapping "ASCII num of the character" to `.CharMetrics`. name_d : dict A mapping "character name" to `.CharMetrics`.
Notes ----- This function is incomplete per the standard, but thus far parses all the sample afm files tried. """ required_keys = {'C', 'WX', 'N', 'B'}
ascii_d = {} name_d = {} for line in fh: # We are defensively letting values be utf8. The spec requires # ascii, but there are non-compliant fonts in circulation line = _to_str(line.rstrip()) # Convert from byte-literal if line.startswith('EndCharMetrics'): return ascii_d, name_d # Split the metric line into a dictionary, keyed by metric identifiers vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s) # There may be other metrics present, but only these are needed if not required_keys.issubset(vals): raise RuntimeError('Bad char metrics line: %s' % line) num = _to_int(vals['C']) wx = _to_float(vals['WX']) name = vals['N'] bbox = _to_list_of_floats(vals['B']) bbox = list(map(int, bbox)) metrics = CharMetrics(wx, name, bbox) # Workaround: If the character name is 'Euro', give it the # corresponding character code, according to WinAnsiEncoding (see PDF # Reference). if name == 'Euro': num = 128 elif name == 'minus': num = ord("\N{MINUS SIGN}") # 0x2212 if num != -1: ascii_d[num] = metrics name_d[name] = metrics raise RuntimeError('Bad parse')
def _parse_kern_pairs(fh): """ Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and values are the kern pair value. For example, a kern pairs line like ``KPX A y -50``
will be represented as::
d[ ('A', 'y') ] = -50
"""
line = next(fh) if not line.startswith(b'StartKernPairs'): raise RuntimeError('Bad start of kern pairs data: %s' % line)
d = {} for line in fh: line = line.rstrip() if not line: continue if line.startswith(b'EndKernPairs'): next(fh) # EndKernData return d vals = line.split() if len(vals) != 4 or vals[0] != b'KPX': raise RuntimeError('Bad kern pairs line: %s' % line) c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3]) d[(c1, c2)] = val raise RuntimeError('Bad kern pairs parse')
CompositePart = namedtuple('CompositePart', 'name, dx, dy')CompositePart.__doc__ = """ Represents the information on a composite element of a composite char."""CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'."""CompositePart.dx.__doc__ = """x-displacement of the part from the origin."""CompositePart.dy.__doc__ = """y-displacement of the part from the origin."""
def _parse_composites(fh): """ Parse the given filehandle for composites information return them as a dict.
It is assumed that the file cursor is on the line behind 'StartComposites'.
Returns ------- dict A dict mapping composite character names to a parts list. The parts list is a list of `.CompositePart` entries describing the parts of the composite.
Examples -------- A composite definition line::
CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;
will be represented as::
composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0), CompositePart(name='acute', dx=160, dy=170)]
""" composites = {} for line in fh: line = line.rstrip() if not line: continue if line.startswith(b'EndComposites'): return composites vals = line.split(b';') cc = vals[0].split() name, _num_parts = cc[1], _to_int(cc[2]) pccParts = [] for s in vals[1:-1]: pcc = s.split() part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3])) pccParts.append(part) composites[name] = pccParts
raise RuntimeError('Bad composites parse')
def _parse_optional(fh): """ Parse the optional fields for kern pair data and composites.
Returns ------- kern_data : dict A dict containing kerning information. May be empty. See `._parse_kern_pairs`. composites : dict A dict containing composite information. May be empty. See `._parse_composites`. """ optional = { b'StartKernData': _parse_kern_pairs, b'StartComposites': _parse_composites, }
d = {b'StartKernData': {}, b'StartComposites': {}} for line in fh: line = line.rstrip() if not line: continue key = line.split()[0]
if key in optional: d[key] = optional[key](fh)
return d[b'StartKernData'], d[b'StartComposites']
class AFM:
def __init__(self, fh): """Parse the AFM file in file object *fh*.""" self._header = _parse_header(fh) self._metrics, self._metrics_by_name = _parse_char_metrics(fh) self._kern, self._composite = _parse_optional(fh)
def get_bbox_char(self, c, isord=False): if not isord: c = ord(c) return self._metrics[c].bbox
def string_width_height(self, s): """ Return the string width (including kerning) and string height as a (*w*, *h*) tuple. """ if not len(s): return 0, 0 total_width = 0 namelast = None miny = 1e9 maxy = 0 for c in s: if c == '\n': continue wx, name, bbox = self._metrics[ord(c)]
total_width += wx + self._kern.get((namelast, name), 0) l, b, w, h = bbox miny = min(miny, b) maxy = max(maxy, b + h)
namelast = name
return total_width, maxy - miny
def get_str_bbox_and_descent(self, s): """Return the string bounding box and the maximal descent.""" if not len(s): return 0, 0, 0, 0, 0 total_width = 0 namelast = None miny = 1e9 maxy = 0 left = 0 if not isinstance(s, str): s = _to_str(s) for c in s: if c == '\n': continue name = uni2type1.get(ord(c), f"uni{ord(c):04X}") try: wx, _, bbox = self._metrics_by_name[name] except KeyError: name = 'question' wx, _, bbox = self._metrics_by_name[name] total_width += wx + self._kern.get((namelast, name), 0) l, b, w, h = bbox left = min(left, l) miny = min(miny, b) maxy = max(maxy, b + h)
namelast = name
return left, miny, total_width, maxy - miny, -miny
def get_str_bbox(self, s): """Return the string bounding box.""" return self.get_str_bbox_and_descent(s)[:4]
def get_name_char(self, c, isord=False): """Get the name of the character, i.e., ';' is 'semicolon'.""" if not isord: c = ord(c) return self._metrics[c].name
def get_width_char(self, c, isord=False): """ Get the width of the character from the character metric WX field. """ if not isord: c = ord(c) return self._metrics[c].width
def get_width_from_char_name(self, name): """Get the width of the character from a type1 character name.""" return self._metrics_by_name[name].width
def get_height_char(self, c, isord=False): """Get the bounding box (ink) height of character *c* (space is 0).""" if not isord: c = ord(c) return self._metrics[c].bbox[-1]
def get_kern_dist(self, c1, c2): """ Return the kerning pair distance (possibly 0) for chars *c1* and *c2*. """ name1, name2 = self.get_name_char(c1), self.get_name_char(c2) return self.get_kern_dist_from_name(name1, name2)
def get_kern_dist_from_name(self, name1, name2): """ Return the kerning pair distance (possibly 0) for chars *name1* and *name2*. """ return self._kern.get((name1, name2), 0)
def get_fontname(self): """Return the font name, e.g., 'Times-Roman'.""" return self._header[b'FontName']
@property def postscript_name(self): # For consistency with FT2Font. return self.get_fontname()
def get_fullname(self): """Return the font full name, e.g., 'Times-Roman'.""" name = self._header.get(b'FullName') if name is None: # use FontName as a substitute name = self._header[b'FontName'] return name
def get_familyname(self): """Return the font family name, e.g., 'Times'.""" name = self._header.get(b'FamilyName') if name is not None: return name
# FamilyName not specified so we'll make a guess name = self.get_fullname() extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|' r'light|ultralight|extra|condensed))+$') return re.sub(extras, '', name)
@property def family_name(self): """The font family name, e.g., 'Times'.""" return self.get_familyname()
def get_weight(self): """Return the font weight, e.g., 'Bold' or 'Roman'.""" return self._header[b'Weight']
def get_angle(self): """Return the fontangle as float.""" return self._header[b'ItalicAngle']
def get_capheight(self): """Return the cap height as float.""" return self._header[b'CapHeight']
def get_xheight(self): """Return the xheight as float.""" return self._header[b'XHeight']
def get_underline_thickness(self): """Return the underline thickness as float.""" return self._header[b'UnderlineThickness']
def get_horizontal_stem_width(self): """ Return the standard horizontal stem width as float, or *None* if not specified in AFM file. """ return self._header.get(b'StdHW', None)
def get_vertical_stem_width(self): """ Return the standard vertical stem width as float, or *None* if not specified in AFM file. """ return self._header.get(b'StdVW', None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262# JavaScript template for HTMLWriterJS_INCLUDE = """<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"><script language="javascript"> function isInternetExplorer() { ua = navigator.userAgent; /* MSIE used to detect old browsers and Trident used to newer ones*/ return ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1; }
/* Define the Animation class */ function Animation(frames, img_id, slider_id, interval, loop_select_id){ this.img_id = img_id; this.slider_id = slider_id; this.loop_select_id = loop_select_id; this.interval = interval; this.current_frame = 0; this.direction = 0; this.timer = null; this.frames = new Array(frames.length);
for (var i=0; i<frames.length; i++) { this.frames[i] = new Image(); this.frames[i].src = frames[i]; } var slider = document.getElementById(this.slider_id); slider.max = this.frames.length - 1; if (isInternetExplorer()) { // switch from oninput to onchange because IE <= 11 does not conform // with W3C specification. It ignores oninput and onchange behaves // like oninput. In contrast, Microsoft Edge behaves correctly. slider.setAttribute('onchange', slider.getAttribute('oninput')); slider.setAttribute('oninput', null); } this.set_frame(this.current_frame); }
Animation.prototype.get_loop_state = function(){ var button_group = document[this.loop_select_id].state; for (var i = 0; i < button_group.length; i++) { var button = button_group[i]; if (button.checked) { return button.value; } } return undefined; }
Animation.prototype.set_frame = function(frame){ this.current_frame = frame; document.getElementById(this.img_id).src = this.frames[this.current_frame].src; document.getElementById(this.slider_id).value = this.current_frame; }
Animation.prototype.next_frame = function() { this.set_frame(Math.min(this.frames.length - 1, this.current_frame + 1)); }
Animation.prototype.previous_frame = function() { this.set_frame(Math.max(0, this.current_frame - 1)); }
Animation.prototype.first_frame = function() { this.set_frame(0); }
Animation.prototype.last_frame = function() { this.set_frame(this.frames.length - 1); }
Animation.prototype.slower = function() { this.interval /= 0.7; if(this.direction > 0){this.play_animation();} else if(this.direction < 0){this.reverse_animation();} }
Animation.prototype.faster = function() { this.interval *= 0.7; if(this.direction > 0){this.play_animation();} else if(this.direction < 0){this.reverse_animation();} }
Animation.prototype.anim_step_forward = function() { this.current_frame += 1; if(this.current_frame < this.frames.length){ this.set_frame(this.current_frame); }else{ var loop_state = this.get_loop_state(); if(loop_state == "loop"){ this.first_frame(); }else if(loop_state == "reflect"){ this.last_frame(); this.reverse_animation(); }else{ this.pause_animation(); this.last_frame(); } } }
Animation.prototype.anim_step_reverse = function() { this.current_frame -= 1; if(this.current_frame >= 0){ this.set_frame(this.current_frame); }else{ var loop_state = this.get_loop_state(); if(loop_state == "loop"){ this.last_frame(); }else if(loop_state == "reflect"){ this.first_frame(); this.play_animation(); }else{ this.pause_animation(); this.first_frame(); } } }
Animation.prototype.pause_animation = function() { this.direction = 0; if (this.timer){ clearInterval(this.timer); this.timer = null; } }
Animation.prototype.play_animation = function() { this.pause_animation(); this.direction = 1; var t = this; if (!this.timer) this.timer = setInterval(function() { t.anim_step_forward(); }, this.interval); }
Animation.prototype.reverse_animation = function() { this.pause_animation(); this.direction = -1; var t = this; if (!this.timer) this.timer = setInterval(function() { t.anim_step_reverse(); }, this.interval); }</script>"""
# Style definitions for the HTML templateSTYLE_INCLUDE = """<style>.animation { display: inline-block; text-align: center;}input[type=range].anim-slider { width: 374px; margin-left: auto; margin-right: auto;}.anim-buttons { margin: 8px 0px;}.anim-buttons button { padding: 0; width: 36px;}.anim-state label { margin-right: 8px;}.anim-state input { margin: 0; vertical-align: middle;}</style>"""
# HTML template for HTMLWriterDISPLAY_TEMPLATE = """<div class="animation"> <img id="_anim_img{id}"> <div class="anim-controls"> <input id="_anim_slider{id}" type="range" class="anim-slider" name="points" min="0" max="1" step="1" value="0" oninput="anim{id}.set_frame(parseInt(this.value));"> <div class="anim-buttons"> <button title="Decrease speed" aria-label="Decrease speed" onclick="anim{id}.slower()"> <i class="fa fa-minus"></i></button> <button title="First frame" aria-label="First frame" onclick="anim{id}.first_frame()"> <i class="fa fa-fast-backward"></i></button> <button title="Previous frame" aria-label="Previous frame" onclick="anim{id}.previous_frame()"> <i class="fa fa-step-backward"></i></button> <button title="Play backwards" aria-label="Play backwards" onclick="anim{id}.reverse_animation()"> <i class="fa fa-play fa-flip-horizontal"></i></button> <button title="Pause" aria-label="Pause" onclick="anim{id}.pause_animation()"> <i class="fa fa-pause"></i></button> <button title="Play" aria-label="Play" onclick="anim{id}.play_animation()"> <i class="fa fa-play"></i></button> <button title="Next frame" aria-label="Next frame" onclick="anim{id}.next_frame()"> <i class="fa fa-step-forward"></i></button> <button title="Last frame" aria-label="Last frame" onclick="anim{id}.last_frame()"> <i class="fa fa-fast-forward"></i></button> <button title="Increase speed" aria-label="Increase speed" onclick="anim{id}.faster()"> <i class="fa fa-plus"></i></button> </div> <form title="Repetition mode" aria-label="Repetition mode" action="#n" name="_anim_loop_select{id}" class="anim-state"> <input type="radio" name="state" value="once" id="_anim_radio1_{id}" {once_checked}> <label for="_anim_radio1_{id}">Once</label> <input type="radio" name="state" value="loop" id="_anim_radio2_{id}" {loop_checked}> <label for="_anim_radio2_{id}">Loop</label> <input type="radio" name="state" value="reflect" id="_anim_radio3_{id}" {reflect_checked}> <label for="_anim_radio3_{id}">Reflect</label> </form> </div></div>
<script language="javascript"> /* Instantiate the Animation class. */ /* The IDs given should match those used in the template above. */ (function() {{ var img_id = "_anim_img{id}"; var slider_id = "_anim_slider{id}"; var loop_select_id = "_anim_loop_select{id}"; var frames = new Array({Nframes}); {fill_frames}
/* set a timeout to make sure all the above elements are created before the object is initialized. */ setTimeout(function() {{ anim{id} = new Animation(frames, img_id, slider_id, {interval}, loop_select_id); }}, 0); }})()</script>""" # noqa: E501
INCLUDED_FRAMES = """ for (var i=0; i<{Nframes}; i++){{ frames[i] = "{frame_dir}/frame" + ("0000000" + i).slice(-7) + ".{frame_format}"; }}"""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141BASE_COLORS = { 'b': (0, 0, 1), # blue 'g': (0, 0.5, 0), # green 'r': (1, 0, 0), # red 'c': (0, 0.75, 0.75), # cyan 'm': (0.75, 0, 0.75), # magenta 'y': (0.75, 0.75, 0), # yellow 'k': (0, 0, 0), # black 'w': (1, 1, 1), # white}
# These colors are from TableauTABLEAU_COLORS = { 'tab:blue': '#1f77b4', 'tab:orange': '#ff7f0e', 'tab:green': '#2ca02c', 'tab:red': '#d62728', 'tab:purple': '#9467bd', 'tab:brown': '#8c564b', 'tab:pink': '#e377c2', 'tab:gray': '#7f7f7f', 'tab:olive': '#bcbd22', 'tab:cyan': '#17becf',}
# This mapping of color names -> hex values is taken from# a survey run by Randall Munroe see:# https://blog.xkcd.com/2010/05/03/color-survey-results/# for more details. The results are hosted at# https://xkcd.com/color/rgb/# and also available as a text file at# https://xkcd.com/color/rgb.txt## License: https://creativecommons.org/publicdomain/zero/1.0/XKCD_COLORS = { 'cloudy blue': '#acc2d9', 'dark pastel green': '#56ae57', 'dust': '#b2996e', 'electric lime': '#a8ff04', 'fresh green': '#69d84f', 'light eggplant': '#894585', 'nasty green': '#70b23f', 'really light blue': '#d4ffff', 'tea': '#65ab7c', 'warm purple': '#952e8f', 'yellowish tan': '#fcfc81', 'cement': '#a5a391', 'dark grass green': '#388004', 'dusty teal': '#4c9085', 'grey teal': '#5e9b8a', 'macaroni and cheese': '#efb435', 'pinkish tan': '#d99b82', 'spruce': '#0a5f38', 'strong blue': '#0c06f7', 'toxic green': '#61de2a', 'windows blue': '#3778bf', 'blue blue': '#2242c7', 'blue with a hint of purple': '#533cc6', 'booger': '#9bb53c', 'bright sea green': '#05ffa6', 'dark green blue': '#1f6357', 'deep turquoise': '#017374', 'green teal': '#0cb577', 'strong pink': '#ff0789', 'bland': '#afa88b', 'deep aqua': '#08787f', 'lavender pink': '#dd85d7', 'light moss green': '#a6c875', 'light seafoam green': '#a7ffb5', 'olive yellow': '#c2b709', 'pig pink': '#e78ea5', 'deep lilac': '#966ebd', 'desert': '#ccad60', 'dusty lavender': '#ac86a8', 'purpley grey': '#947e94', 'purply': '#983fb2', 'candy pink': '#ff63e9', 'light pastel green': '#b2fba5', 'boring green': '#63b365', 'kiwi green': '#8ee53f', 'light grey green': '#b7e1a1', 'orange pink': '#ff6f52', 'tea green': '#bdf8a3', 'very light brown': '#d3b683', 'egg shell': '#fffcc4', 'eggplant purple': '#430541', 'powder pink': '#ffb2d0', 'reddish grey': '#997570', 'baby shit brown': '#ad900d', 'liliac': '#c48efd', 'stormy blue': '#507b9c', 'ugly brown': '#7d7103', 'custard': '#fffd78', 'darkish pink': '#da467d', 'deep brown': '#410200', 'greenish beige': '#c9d179', 'manilla': '#fffa86', 'off blue': '#5684ae', 'battleship grey': '#6b7c85', 'browny green': '#6f6c0a', 'bruise': '#7e4071', 'kelley green': '#009337', 'sickly yellow': '#d0e429', 'sunny yellow': '#fff917', 'azul': '#1d5dec', 'darkgreen': '#054907', 'green/yellow': '#b5ce08', 'lichen': '#8fb67b', 'light light green': '#c8ffb0', 'pale gold': '#fdde6c', 'sun yellow': '#ffdf22', 'tan green': '#a9be70', 'burple': '#6832e3', 'butterscotch': '#fdb147', 'toupe': '#c7ac7d', 'dark cream': '#fff39a', 'indian red': '#850e04', 'light lavendar': '#efc0fe', 'poison green': '#40fd14', 'baby puke green': '#b6c406', 'bright yellow green': '#9dff00', 'charcoal grey': '#3c4142', 'squash': '#f2ab15', 'cinnamon': '#ac4f06', 'light pea green': '#c4fe82', 'radioactive green': '#2cfa1f', 'raw sienna': '#9a6200', 'baby purple': '#ca9bf7', 'cocoa': '#875f42', 'light royal blue': '#3a2efe', 'orangeish': '#fd8d49', 'rust brown': '#8b3103', 'sand brown': '#cba560', 'swamp': '#698339', 'tealish green': '#0cdc73', 'burnt siena': '#b75203', 'camo': '#7f8f4e', 'dusk blue': '#26538d', 'fern': '#63a950', 'old rose': '#c87f89', 'pale light green': '#b1fc99', 'peachy pink': '#ff9a8a', 'rosy pink': '#f6688e', 'light bluish green': '#76fda8', 'light bright green': '#53fe5c', 'light neon green': '#4efd54', 'light seafoam': '#a0febf', 'tiffany blue': '#7bf2da', 'washed out green': '#bcf5a6', 'browny orange': '#ca6b02', 'nice blue': '#107ab0', 'sapphire': '#2138ab', 'greyish teal': '#719f91', 'orangey yellow': '#fdb915', 'parchment': '#fefcaf', 'straw': '#fcf679', 'very dark brown': '#1d0200', 'terracota': '#cb6843', 'ugly blue': '#31668a', 'clear blue': '#247afd', 'creme': '#ffffb6', 'foam green': '#90fda9', 'grey/green': '#86a17d', 'light gold': '#fddc5c', 'seafoam blue': '#78d1b6', 'topaz': '#13bbaf', 'violet pink': '#fb5ffc', 'wintergreen': '#20f986', 'yellow tan': '#ffe36e', 'dark fuchsia': '#9d0759', 'indigo blue': '#3a18b1', 'light yellowish green': '#c2ff89', 'pale magenta': '#d767ad', 'rich purple': '#720058', 'sunflower yellow': '#ffda03', 'green/blue': '#01c08d', 'leather': '#ac7434', 'racing green': '#014600', 'vivid purple': '#9900fa', 'dark royal blue': '#02066f', 'hazel': '#8e7618', 'muted pink': '#d1768f', 'booger green': '#96b403', 'canary': '#fdff63', 'cool grey': '#95a3a6', 'dark taupe': '#7f684e', 'darkish purple': '#751973', 'true green': '#089404', 'coral pink': '#ff6163', 'dark sage': '#598556', 'dark slate blue': '#214761', 'flat blue': '#3c73a8', 'mushroom': '#ba9e88', 'rich blue': '#021bf9', 'dirty purple': '#734a65', 'greenblue': '#23c48b', 'icky green': '#8fae22', 'light khaki': '#e6f2a2', 'warm blue': '#4b57db', 'dark hot pink': '#d90166', 'deep sea blue': '#015482', 'carmine': '#9d0216', 'dark yellow green': '#728f02', 'pale peach': '#ffe5ad', 'plum purple': '#4e0550', 'golden rod': '#f9bc08', 'neon red': '#ff073a', 'old pink': '#c77986', 'very pale blue': '#d6fffe', 'blood orange': '#fe4b03', 'grapefruit': '#fd5956', 'sand yellow': '#fce166', 'clay brown': '#b2713d', 'dark blue grey': '#1f3b4d', 'flat green': '#699d4c', 'light green blue': '#56fca2', 'warm pink': '#fb5581', 'dodger blue': '#3e82fc', 'gross green': '#a0bf16', 'ice': '#d6fffa', 'metallic blue': '#4f738e', 'pale salmon': '#ffb19a', 'sap green': '#5c8b15', 'algae': '#54ac68', 'bluey grey': '#89a0b0', 'greeny grey': '#7ea07a', 'highlighter green': '#1bfc06', 'light light blue': '#cafffb', 'light mint': '#b6ffbb', 'raw umber': '#a75e09', 'vivid blue': '#152eff', 'deep lavender': '#8d5eb7', 'dull teal': '#5f9e8f', 'light greenish blue': '#63f7b4', 'mud green': '#606602', 'pinky': '#fc86aa', 'red wine': '#8c0034', 'shit green': '#758000', 'tan brown': '#ab7e4c', 'darkblue': '#030764', 'rosa': '#fe86a4', 'lipstick': '#d5174e', 'pale mauve': '#fed0fc', 'claret': '#680018', 'dandelion': '#fedf08', 'orangered': '#fe420f', 'poop green': '#6f7c00', 'ruby': '#ca0147', 'dark': '#1b2431', 'greenish turquoise': '#00fbb0', 'pastel red': '#db5856', 'piss yellow': '#ddd618', 'bright cyan': '#41fdfe', 'dark coral': '#cf524e', 'algae green': '#21c36f', 'darkish red': '#a90308', 'reddy brown': '#6e1005', 'blush pink': '#fe828c', 'camouflage green': '#4b6113', 'lawn green': '#4da409', 'putty': '#beae8a', 'vibrant blue': '#0339f8', 'dark sand': '#a88f59', 'purple/blue': '#5d21d0', 'saffron': '#feb209', 'twilight': '#4e518b', 'warm brown': '#964e02', 'bluegrey': '#85a3b2', 'bubble gum pink': '#ff69af', 'duck egg blue': '#c3fbf4', 'greenish cyan': '#2afeb7', 'petrol': '#005f6a', 'royal': '#0c1793', 'butter': '#ffff81', 'dusty orange': '#f0833a', 'off yellow': '#f1f33f', 'pale olive green': '#b1d27b', 'orangish': '#fc824a', 'leaf': '#71aa34', 'light blue grey': '#b7c9e2', 'dried blood': '#4b0101', 'lightish purple': '#a552e6', 'rusty red': '#af2f0d', 'lavender blue': '#8b88f8', 'light grass green': '#9af764', 'light mint green': '#a6fbb2', 'sunflower': '#ffc512', 'velvet': '#750851', 'brick orange': '#c14a09', 'lightish red': '#fe2f4a', 'pure blue': '#0203e2', 'twilight blue': '#0a437a', 'violet red': '#a50055', 'yellowy brown': '#ae8b0c', 'carnation': '#fd798f', 'muddy yellow': '#bfac05', 'dark seafoam green': '#3eaf76', 'deep rose': '#c74767', 'dusty red': '#b9484e', 'grey/blue': '#647d8e', 'lemon lime': '#bffe28', 'purple/pink': '#d725de', 'brown yellow': '#b29705', 'purple brown': '#673a3f', 'wisteria': '#a87dc2', 'banana yellow': '#fafe4b', 'lipstick red': '#c0022f', 'water blue': '#0e87cc', 'brown grey': '#8d8468', 'vibrant purple': '#ad03de', 'baby green': '#8cff9e', 'barf green': '#94ac02', 'eggshell blue': '#c4fff7', 'sandy yellow': '#fdee73', 'cool green': '#33b864', 'pale': '#fff9d0', 'blue/grey': '#758da3', 'hot magenta': '#f504c9', 'greyblue': '#77a1b5', 'purpley': '#8756e4', 'baby shit green': '#889717', 'brownish pink': '#c27e79', 'dark aquamarine': '#017371', 'diarrhea': '#9f8303', 'light mustard': '#f7d560', 'pale sky blue': '#bdf6fe', 'turtle green': '#75b84f', 'bright olive': '#9cbb04', 'dark grey blue': '#29465b', 'greeny brown': '#696006', 'lemon green': '#adf802', 'light periwinkle': '#c1c6fc', 'seaweed green': '#35ad6b', 'sunshine yellow': '#fffd37', 'ugly purple': '#a442a0', 'medium pink': '#f36196', 'puke brown': '#947706', 'very light pink': '#fff4f2', 'viridian': '#1e9167', 'bile': '#b5c306', 'faded yellow': '#feff7f', 'very pale green': '#cffdbc', 'vibrant green': '#0add08', 'bright lime': '#87fd05', 'spearmint': '#1ef876', 'light aquamarine': '#7bfdc7', 'light sage': '#bcecac', 'yellowgreen': '#bbf90f', 'baby poo': '#ab9004', 'dark seafoam': '#1fb57a', 'deep teal': '#00555a', 'heather': '#a484ac', 'rust orange': '#c45508', 'dirty blue': '#3f829d', 'fern green': '#548d44', 'bright lilac': '#c95efb', 'weird green': '#3ae57f', 'peacock blue': '#016795', 'avocado green': '#87a922', 'faded orange': '#f0944d', 'grape purple': '#5d1451', 'hot green': '#25ff29', 'lime yellow': '#d0fe1d', 'mango': '#ffa62b', 'shamrock': '#01b44c', 'bubblegum': '#ff6cb5', 'purplish brown': '#6b4247', 'vomit yellow': '#c7c10c', 'pale cyan': '#b7fffa', 'key lime': '#aeff6e', 'tomato red': '#ec2d01', 'lightgreen': '#76ff7b', 'merlot': '#730039', 'night blue': '#040348', 'purpleish pink': '#df4ec8', 'apple': '#6ecb3c', 'baby poop green': '#8f9805', 'green apple': '#5edc1f', 'heliotrope': '#d94ff5', 'yellow/green': '#c8fd3d', 'almost black': '#070d0d', 'cool blue': '#4984b8', 'leafy green': '#51b73b', 'mustard brown': '#ac7e04', 'dusk': '#4e5481', 'dull brown': '#876e4b', 'frog green': '#58bc08', 'vivid green': '#2fef10', 'bright light green': '#2dfe54', 'fluro green': '#0aff02', 'kiwi': '#9cef43', 'seaweed': '#18d17b', 'navy green': '#35530a', 'ultramarine blue': '#1805db', 'iris': '#6258c4', 'pastel orange': '#ff964f', 'yellowish orange': '#ffab0f', 'perrywinkle': '#8f8ce7', 'tealish': '#24bca8', 'dark plum': '#3f012c', 'pear': '#cbf85f', 'pinkish orange': '#ff724c', 'midnight purple': '#280137', 'light urple': '#b36ff6', 'dark mint': '#48c072', 'greenish tan': '#bccb7a', 'light burgundy': '#a8415b', 'turquoise blue': '#06b1c4', 'ugly pink': '#cd7584', 'sandy': '#f1da7a', 'electric pink': '#ff0490', 'muted purple': '#805b87', 'mid green': '#50a747', 'greyish': '#a8a495', 'neon yellow': '#cfff04', 'banana': '#ffff7e', 'carnation pink': '#ff7fa7', 'tomato': '#ef4026', 'sea': '#3c9992', 'muddy brown': '#886806', 'turquoise green': '#04f489', 'buff': '#fef69e', 'fawn': '#cfaf7b', 'muted blue': '#3b719f', 'pale rose': '#fdc1c5', 'dark mint green': '#20c073', 'amethyst': '#9b5fc0', 'blue/green': '#0f9b8e', 'chestnut': '#742802', 'sick green': '#9db92c', 'pea': '#a4bf20', 'rusty orange': '#cd5909', 'stone': '#ada587', 'rose red': '#be013c', 'pale aqua': '#b8ffeb', 'deep orange': '#dc4d01', 'earth': '#a2653e', 'mossy green': '#638b27', 'grassy green': '#419c03', 'pale lime green': '#b1ff65', 'light grey blue': '#9dbcd4', 'pale grey': '#fdfdfe', 'asparagus': '#77ab56', 'blueberry': '#464196', 'purple red': '#990147', 'pale lime': '#befd73', 'greenish teal': '#32bf84', 'caramel': '#af6f09', 'deep magenta': '#a0025c', 'light peach': '#ffd8b1', 'milk chocolate': '#7f4e1e', 'ocher': '#bf9b0c', 'off green': '#6ba353', 'purply pink': '#f075e6', 'lightblue': '#7bc8f6', 'dusky blue': '#475f94', 'golden': '#f5bf03', 'light beige': '#fffeb6', 'butter yellow': '#fffd74', 'dusky purple': '#895b7b', 'french blue': '#436bad', 'ugly yellow': '#d0c101', 'greeny yellow': '#c6f808', 'orangish red': '#f43605', 'shamrock green': '#02c14d', 'orangish brown': '#b25f03', 'tree green': '#2a7e19', 'deep violet': '#490648', 'gunmetal': '#536267', 'blue/purple': '#5a06ef', 'cherry': '#cf0234', 'sandy brown': '#c4a661', 'warm grey': '#978a84', 'dark indigo': '#1f0954', 'midnight': '#03012d', 'bluey green': '#2bb179', 'grey pink': '#c3909b', 'soft purple': '#a66fb5', 'blood': '#770001', 'brown red': '#922b05', 'medium grey': '#7d7f7c', 'berry': '#990f4b', 'poo': '#8f7303', 'purpley pink': '#c83cb9', 'light salmon': '#fea993', 'snot': '#acbb0d', 'easter purple': '#c071fe', 'light yellow green': '#ccfd7f', 'dark navy blue': '#00022e', 'drab': '#828344', 'light rose': '#ffc5cb', 'rouge': '#ab1239', 'purplish red': '#b0054b', 'slime green': '#99cc04', 'baby poop': '#937c00', 'irish green': '#019529', 'pink/purple': '#ef1de7', 'dark navy': '#000435', 'greeny blue': '#42b395', 'light plum': '#9d5783', 'pinkish grey': '#c8aca9', 'dirty orange': '#c87606', 'rust red': '#aa2704', 'pale lilac': '#e4cbff', 'orangey red': '#fa4224', 'primary blue': '#0804f9', 'kermit green': '#5cb200', 'brownish purple': '#76424e', 'murky green': '#6c7a0e', 'wheat': '#fbdd7e', 'very dark purple': '#2a0134', 'bottle green': '#044a05', 'watermelon': '#fd4659', 'deep sky blue': '#0d75f8', 'fire engine red': '#fe0002', 'yellow ochre': '#cb9d06', 'pumpkin orange': '#fb7d07', 'pale olive': '#b9cc81', 'light lilac': '#edc8ff', 'lightish green': '#61e160', 'carolina blue': '#8ab8fe', 'mulberry': '#920a4e', 'shocking pink': '#fe02a2', 'auburn': '#9a3001', 'bright lime green': '#65fe08', 'celadon': '#befdb7', 'pinkish brown': '#b17261', 'poo brown': '#885f01', 'bright sky blue': '#02ccfe', 'celery': '#c1fd95', 'dirt brown': '#836539', 'strawberry': '#fb2943', 'dark lime': '#84b701', 'copper': '#b66325', 'medium brown': '#7f5112', 'muted green': '#5fa052', "robin's egg": '#6dedfd', 'bright aqua': '#0bf9ea', 'bright lavender': '#c760ff', 'ivory': '#ffffcb', 'very light purple': '#f6cefc', 'light navy': '#155084', 'pink red': '#f5054f', 'olive brown': '#645403', 'poop brown': '#7a5901', 'mustard green': '#a8b504', 'ocean green': '#3d9973', 'very dark blue': '#000133', 'dusty green': '#76a973', 'light navy blue': '#2e5a88', 'minty green': '#0bf77d', 'adobe': '#bd6c48', 'barney': '#ac1db8', 'jade green': '#2baf6a', 'bright light blue': '#26f7fd', 'light lime': '#aefd6c', 'dark khaki': '#9b8f55', 'orange yellow': '#ffad01', 'ocre': '#c69c04', 'maize': '#f4d054', 'faded pink': '#de9dac', 'british racing green': '#05480d', 'sandstone': '#c9ae74', 'mud brown': '#60460f', 'light sea green': '#98f6b0', 'robin egg blue': '#8af1fe', 'aqua marine': '#2ee8bb', 'dark sea green': '#11875d', 'soft pink': '#fdb0c0', 'orangey brown': '#b16002', 'cherry red': '#f7022a', 'burnt yellow': '#d5ab09', 'brownish grey': '#86775f', 'camel': '#c69f59', 'purplish grey': '#7a687f', 'marine': '#042e60', 'greyish pink': '#c88d94', 'pale turquoise': '#a5fbd5', 'pastel yellow': '#fffe71', 'bluey purple': '#6241c7', 'canary yellow': '#fffe40', 'faded red': '#d3494e', 'sepia': '#985e2b', 'coffee': '#a6814c', 'bright magenta': '#ff08e8', 'mocha': '#9d7651', 'ecru': '#feffca', 'purpleish': '#98568d', 'cranberry': '#9e003a', 'darkish green': '#287c37', 'brown orange': '#b96902', 'dusky rose': '#ba6873', 'melon': '#ff7855', 'sickly green': '#94b21c', 'silver': '#c5c9c7', 'purply blue': '#661aee', 'purpleish blue': '#6140ef', 'hospital green': '#9be5aa', 'shit brown': '#7b5804', 'mid blue': '#276ab3', 'amber': '#feb308', 'easter green': '#8cfd7e', 'soft blue': '#6488ea', 'cerulean blue': '#056eee', 'golden brown': '#b27a01', 'bright turquoise': '#0ffef9', 'red pink': '#fa2a55', 'red purple': '#820747', 'greyish brown': '#7a6a4f', 'vermillion': '#f4320c', 'russet': '#a13905', 'steel grey': '#6f828a', 'lighter purple': '#a55af4', 'bright violet': '#ad0afd', 'prussian blue': '#004577', 'slate green': '#658d6d', 'dirty pink': '#ca7b80', 'dark blue green': '#005249', 'pine': '#2b5d34', 'yellowy green': '#bff128', 'dark gold': '#b59410', 'bluish': '#2976bb', 'darkish blue': '#014182', 'dull red': '#bb3f3f', 'pinky red': '#fc2647', 'bronze': '#a87900', 'pale teal': '#82cbb2', 'military green': '#667c3e', 'barbie pink': '#fe46a5', 'bubblegum pink': '#fe83cc', 'pea soup green': '#94a617', 'dark mustard': '#a88905', 'shit': '#7f5f00', 'medium purple': '#9e43a2', 'very dark green': '#062e03', 'dirt': '#8a6e45', 'dusky pink': '#cc7a8b', 'red violet': '#9e0168', 'lemon yellow': '#fdff38', 'pistachio': '#c0fa8b', 'dull yellow': '#eedc5b', 'dark lime green': '#7ebd01', 'denim blue': '#3b5b92', 'teal blue': '#01889f', 'lightish blue': '#3d7afd', 'purpley blue': '#5f34e7', 'light indigo': '#6d5acf', 'swamp green': '#748500', 'brown green': '#706c11', 'dark maroon': '#3c0008', 'hot purple': '#cb00f5', 'dark forest green': '#002d04', 'faded blue': '#658cbb', 'drab green': '#749551', 'light lime green': '#b9ff66', 'snot green': '#9dc100', 'yellowish': '#faee66', 'light blue green': '#7efbb3', 'bordeaux': '#7b002c', 'light mauve': '#c292a1', 'ocean': '#017b92', 'marigold': '#fcc006', 'muddy green': '#657432', 'dull orange': '#d8863b', 'steel': '#738595', 'electric purple': '#aa23ff', 'fluorescent green': '#08ff08', 'yellowish brown': '#9b7a01', 'blush': '#f29e8e', 'soft green': '#6fc276', 'bright orange': '#ff5b00', 'lemon': '#fdff52', 'purple grey': '#866f85', 'acid green': '#8ffe09', 'pale lavender': '#eecffe', 'violet blue': '#510ac9', 'light forest green': '#4f9153', 'burnt red': '#9f2305', 'khaki green': '#728639', 'cerise': '#de0c62', 'faded purple': '#916e99', 'apricot': '#ffb16d', 'dark olive green': '#3c4d03', 'grey brown': '#7f7053', 'green grey': '#77926f', 'true blue': '#010fcc', 'pale violet': '#ceaefa', 'periwinkle blue': '#8f99fb', 'light sky blue': '#c6fcff', 'blurple': '#5539cc', 'green brown': '#544e03', 'bluegreen': '#017a79', 'bright teal': '#01f9c6', 'brownish yellow': '#c9b003', 'pea soup': '#929901', 'forest': '#0b5509', 'barney purple': '#a00498', 'ultramarine': '#2000b1', 'purplish': '#94568c', 'puke yellow': '#c2be0e', 'bluish grey': '#748b97', 'dark periwinkle': '#665fd1', 'dark lilac': '#9c6da5', 'reddish': '#c44240', 'light maroon': '#a24857', 'dusty purple': '#825f87', 'terra cotta': '#c9643b', 'avocado': '#90b134', 'marine blue': '#01386a', 'teal green': '#25a36f', 'slate grey': '#59656d', 'lighter green': '#75fd63', 'electric green': '#21fc0d', 'dusty blue': '#5a86ad', 'golden yellow': '#fec615', 'bright yellow': '#fffd01', 'light lavender': '#dfc5fe', 'umber': '#b26400', 'poop': '#7f5e00', 'dark peach': '#de7e5d', 'jungle green': '#048243', 'eggshell': '#ffffd4', 'denim': '#3b638c', 'yellow brown': '#b79400', 'dull purple': '#84597e', 'chocolate brown': '#411900', 'wine red': '#7b0323', 'neon blue': '#04d9ff', 'dirty green': '#667e2c', 'light tan': '#fbeeac', 'ice blue': '#d7fffe', 'cadet blue': '#4e7496', 'dark mauve': '#874c62', 'very light blue': '#d5ffff', 'grey purple': '#826d8c', 'pastel pink': '#ffbacd', 'very light green': '#d1ffbd', 'dark sky blue': '#448ee4', 'evergreen': '#05472a', 'dull pink': '#d5869d', 'aubergine': '#3d0734', 'mahogany': '#4a0100', 'reddish orange': '#f8481c', 'deep green': '#02590f', 'vomit green': '#89a203', 'purple pink': '#e03fd8', 'dusty pink': '#d58a94', 'faded green': '#7bb274', 'camo green': '#526525', 'pinky purple': '#c94cbe', 'pink purple': '#db4bda', 'brownish red': '#9e3623', 'dark rose': '#b5485d', 'mud': '#735c12', 'brownish': '#9c6d57', 'emerald green': '#028f1e', 'pale brown': '#b1916e', 'dull blue': '#49759c', 'burnt umber': '#a0450e', 'medium green': '#39ad48', 'clay': '#b66a50', 'light aqua': '#8cffdb', 'light olive green': '#a4be5c', 'brownish orange': '#cb7723', 'dark aqua': '#05696b', 'purplish pink': '#ce5dae', 'dark salmon': '#c85a53', 'greenish grey': '#96ae8d', 'jade': '#1fa774', 'ugly green': '#7a9703', 'dark beige': '#ac9362', 'emerald': '#01a049', 'pale red': '#d9544d', 'light magenta': '#fa5ff7', 'sky': '#82cafc', 'light cyan': '#acfffc', 'yellow orange': '#fcb001', 'reddish purple': '#910951', 'reddish pink': '#fe2c54', 'orchid': '#c875c4', 'dirty yellow': '#cdc50a', 'orange red': '#fd411e', 'deep red': '#9a0200', 'orange brown': '#be6400', 'cobalt blue': '#030aa7', 'neon pink': '#fe019a', 'rose pink': '#f7879a', 'greyish purple': '#887191', 'raspberry': '#b00149', 'aqua green': '#12e193', 'salmon pink': '#fe7b7c', 'tangerine': '#ff9408', 'brownish green': '#6a6e09', 'red brown': '#8b2e16', 'greenish brown': '#696112', 'pumpkin': '#e17701', 'pine green': '#0a481e', 'charcoal': '#343837', 'baby pink': '#ffb7ce', 'cornflower': '#6a79f7', 'blue violet': '#5d06e9', 'chocolate': '#3d1c02', 'greyish green': '#82a67d', 'scarlet': '#be0119', 'green yellow': '#c9ff27', 'dark olive': '#373e02', 'sienna': '#a9561e', 'pastel purple': '#caa0ff', 'terracotta': '#ca6641', 'aqua blue': '#02d8e9', 'sage green': '#88b378', 'blood red': '#980002', 'deep pink': '#cb0162', 'grass': '#5cac2d', 'moss': '#769958', 'pastel blue': '#a2bffe', 'bluish green': '#10a674', 'green blue': '#06b48b', 'dark tan': '#af884a', 'greenish blue': '#0b8b87', 'pale orange': '#ffa756', 'vomit': '#a2a415', 'forrest green': '#154406', 'dark lavender': '#856798', 'dark violet': '#34013f', 'purple blue': '#632de9', 'dark cyan': '#0a888a', 'olive drab': '#6f7632', 'pinkish': '#d46a7e', 'cobalt': '#1e488f', 'neon purple': '#bc13fe', 'light turquoise': '#7ef4cc', 'apple green': '#76cd26', 'dull green': '#74a662', 'wine': '#80013f', 'powder blue': '#b1d1fc', 'off white': '#ffffe4', 'electric blue': '#0652ff', 'dark turquoise': '#045c5a', 'blue purple': '#5729ce', 'azure': '#069af3', 'bright red': '#ff000d', 'pinkish red': '#f10c45', 'cornflower blue': '#5170d7', 'light olive': '#acbf69', 'grape': '#6c3461', 'greyish blue': '#5e819d', 'purplish blue': '#601ef9', 'yellowish green': '#b0dd16', 'greenish yellow': '#cdfd02', 'medium blue': '#2c6fbb', 'dusty rose': '#c0737a', 'light violet': '#d6b4fc', 'midnight blue': '#020035', 'bluish purple': '#703be7', 'red orange': '#fd3c06', 'dark magenta': '#960056', 'greenish': '#40a368', 'ocean blue': '#03719c', 'coral': '#fc5a50', 'cream': '#ffffc2', 'reddish brown': '#7f2b0a', 'burnt sienna': '#b04e0f', 'brick': '#a03623', 'sage': '#87ae73', 'grey green': '#789b73', 'white': '#ffffff', "robin's egg blue": '#98eff9', 'moss green': '#658b38', 'steel blue': '#5a7d9a', 'eggplant': '#380835', 'light yellow': '#fffe7a', 'leaf green': '#5ca904', 'light grey': '#d8dcd6', 'puke': '#a5a502', 'pinkish purple': '#d648d7', 'sea blue': '#047495', 'pale purple': '#b790d4', 'slate blue': '#5b7c99', 'blue grey': '#607c8e', 'hunter green': '#0b4008', 'fuchsia': '#ed0dd9', 'crimson': '#8c000f', 'pale yellow': '#ffff84', 'ochre': '#bf9005', 'mustard yellow': '#d2bd0a', 'light red': '#ff474c', 'cerulean': '#0485d1', 'pale pink': '#ffcfdc', 'deep blue': '#040273', 'rust': '#a83c09', 'light teal': '#90e4c1', 'slate': '#516572', 'goldenrod': '#fac205', 'dark yellow': '#d5b60a', 'dark grey': '#363737', 'army green': '#4b5d16', 'grey blue': '#6b8ba4', 'seafoam': '#80f9ad', 'puce': '#a57e52', 'spring green': '#a9f971', 'dark orange': '#c65102', 'sand': '#e2ca76', 'pastel green': '#b0ff9d', 'mint': '#9ffeb0', 'light orange': '#fdaa48', 'bright pink': '#fe01b1', 'chartreuse': '#c1f80a', 'deep purple': '#36013f', 'dark brown': '#341c02', 'taupe': '#b9a281', 'pea green': '#8eab12', 'puke green': '#9aae07', 'kelly green': '#02ab2e', 'seafoam green': '#7af9ab', 'blue green': '#137e6d', 'khaki': '#aaa662', 'burgundy': '#610023', 'dark teal': '#014d4e', 'brick red': '#8f1402', 'royal purple': '#4b006e', 'plum': '#580f41', 'mint green': '#8fff9f', 'gold': '#dbb40c', 'baby blue': '#a2cffe', 'yellow green': '#c0fb2d', 'bright purple': '#be03fd', 'dark red': '#840000', 'pale blue': '#d0fefe', 'grass green': '#3f9b0b', 'navy': '#01153e', 'aquamarine': '#04d8b2', 'burnt orange': '#c04e01', 'neon green': '#0cff0c', 'bright blue': '#0165fc', 'rose': '#cf6275', 'light pink': '#ffd1df', 'mustard': '#ceb301', 'indigo': '#380282', 'lime': '#aaff32', 'sea green': '#53fca1', 'periwinkle': '#8e82fe', 'dark pink': '#cb416b', 'olive green': '#677a04', 'peach': '#ffb07c', 'pale green': '#c7fdb5', 'light brown': '#ad8150', 'hot pink': '#ff028d', 'black': '#000000', 'lilac': '#cea2fd', 'navy blue': '#001146', 'royal blue': '#0504aa', 'beige': '#e6daa6', 'salmon': '#ff796c', 'olive': '#6e750e', 'maroon': '#650021', 'bright green': '#01ff07', 'dark purple': '#35063e', 'mauve': '#ae7181', 'forest green': '#06470c', 'aqua': '#13eac9', 'cyan': '#00ffff', 'tan': '#d1b26f', 'dark blue': '#00035b', 'lavender': '#c79fef', 'turquoise': '#06c2ac', 'dark green': '#033500', 'violet': '#9a0eea', 'light purple': '#bf77f6', 'lime green': '#89fe05', 'grey': '#929591', 'sky blue': '#75bbfd', 'yellow': '#ffff14', 'magenta': '#c20078', 'light green': '#96f97b', 'orange': '#f97306', 'teal': '#029386', 'light blue': '#95d0fc', 'red': '#e50000', 'brown': '#653700', 'pink': '#ff81c0', 'blue': '#0343df', 'green': '#15b01a', 'purple': '#7e1e9c'}
# Normalize name to "xkcd:<name>" to avoid name collisions.XKCD_COLORS = {'xkcd:' + name: value for name, value in XKCD_COLORS.items()}
# https://drafts.csswg.org/css-color-4/#named-colorsCSS4_COLORS = { 'aliceblue': '#F0F8FF', 'antiquewhite': '#FAEBD7', 'aqua': '#00FFFF', 'aquamarine': '#7FFFD4', 'azure': '#F0FFFF', 'beige': '#F5F5DC', 'bisque': '#FFE4C4', 'black': '#000000', 'blanchedalmond': '#FFEBCD', 'blue': '#0000FF', 'blueviolet': '#8A2BE2', 'brown': '#A52A2A', 'burlywood': '#DEB887', 'cadetblue': '#5F9EA0', 'chartreuse': '#7FFF00', 'chocolate': '#D2691E', 'coral': '#FF7F50', 'cornflowerblue': '#6495ED', 'cornsilk': '#FFF8DC', 'crimson': '#DC143C', 'cyan': '#00FFFF', 'darkblue': '#00008B', 'darkcyan': '#008B8B', 'darkgoldenrod': '#B8860B', 'darkgray': '#A9A9A9', 'darkgreen': '#006400', 'darkgrey': '#A9A9A9', 'darkkhaki': '#BDB76B', 'darkmagenta': '#8B008B', 'darkolivegreen': '#556B2F', 'darkorange': '#FF8C00', 'darkorchid': '#9932CC', 'darkred': '#8B0000', 'darksalmon': '#E9967A', 'darkseagreen': '#8FBC8F', 'darkslateblue': '#483D8B', 'darkslategray': '#2F4F4F', 'darkslategrey': '#2F4F4F', 'darkturquoise': '#00CED1', 'darkviolet': '#9400D3', 'deeppink': '#FF1493', 'deepskyblue': '#00BFFF', 'dimgray': '#696969', 'dimgrey': '#696969', 'dodgerblue': '#1E90FF', 'firebrick': '#B22222', 'floralwhite': '#FFFAF0', 'forestgreen': '#228B22', 'fuchsia': '#FF00FF', 'gainsboro': '#DCDCDC', 'ghostwhite': '#F8F8FF', 'gold': '#FFD700', 'goldenrod': '#DAA520', 'gray': '#808080', 'green': '#008000', 'greenyellow': '#ADFF2F', 'grey': '#808080', 'honeydew': '#F0FFF0', 'hotpink': '#FF69B4', 'indianred': '#CD5C5C', 'indigo': '#4B0082', 'ivory': '#FFFFF0', 'khaki': '#F0E68C', 'lavender': '#E6E6FA', 'lavenderblush': '#FFF0F5', 'lawngreen': '#7CFC00', 'lemonchiffon': '#FFFACD', 'lightblue': '#ADD8E6', 'lightcoral': '#F08080', 'lightcyan': '#E0FFFF', 'lightgoldenrodyellow': '#FAFAD2', 'lightgray': '#D3D3D3', 'lightgreen': '#90EE90', 'lightgrey': '#D3D3D3', 'lightpink': '#FFB6C1', 'lightsalmon': '#FFA07A', 'lightseagreen': '#20B2AA', 'lightskyblue': '#87CEFA', 'lightslategray': '#778899', 'lightslategrey': '#778899', 'lightsteelblue': '#B0C4DE', 'lightyellow': '#FFFFE0', 'lime': '#00FF00', 'limegreen': '#32CD32', 'linen': '#FAF0E6', 'magenta': '#FF00FF', 'maroon': '#800000', 'mediumaquamarine': '#66CDAA', 'mediumblue': '#0000CD', 'mediumorchid': '#BA55D3', 'mediumpurple': '#9370DB', 'mediumseagreen': '#3CB371', 'mediumslateblue': '#7B68EE', 'mediumspringgreen': '#00FA9A', 'mediumturquoise': '#48D1CC', 'mediumvioletred': '#C71585', 'midnightblue': '#191970', 'mintcream': '#F5FFFA', 'mistyrose': '#FFE4E1', 'moccasin': '#FFE4B5', 'navajowhite': '#FFDEAD', 'navy': '#000080', 'oldlace': '#FDF5E6', 'olive': '#808000', 'olivedrab': '#6B8E23', 'orange': '#FFA500', 'orangered': '#FF4500', 'orchid': '#DA70D6', 'palegoldenrod': '#EEE8AA', 'palegreen': '#98FB98', 'paleturquoise': '#AFEEEE', 'palevioletred': '#DB7093', 'papayawhip': '#FFEFD5', 'peachpuff': '#FFDAB9', 'peru': '#CD853F', 'pink': '#FFC0CB', 'plum': '#DDA0DD', 'powderblue': '#B0E0E6', 'purple': '#800080', 'rebeccapurple': '#663399', 'red': '#FF0000', 'rosybrown': '#BC8F8F', 'royalblue': '#4169E1', 'saddlebrown': '#8B4513', 'salmon': '#FA8072', 'sandybrown': '#F4A460', 'seagreen': '#2E8B57', 'seashell': '#FFF5EE', 'sienna': '#A0522D', 'silver': '#C0C0C0', 'skyblue': '#87CEEB', 'slateblue': '#6A5ACD', 'slategray': '#708090', 'slategrey': '#708090', 'snow': '#FFFAFA', 'springgreen': '#00FF7F', 'steelblue': '#4682B4', 'tan': '#D2B48C', 'teal': '#008080', 'thistle': '#D8BFD8', 'tomato': '#FF6347', 'turquoise': '#40E0D0', 'violet': '#EE82EE', 'wheat': '#F5DEB3', 'white': '#FFFFFF', 'whitesmoke': '#F5F5F5', 'yellow': '#FFFF00', 'yellowgreen': '#9ACD32'}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import inspect
from . import _api
def kwarg_doc(text): """ Decorator for defining the kwdoc documentation of artist properties.
This decorator can be applied to artist property setter methods. The given text is stored in a private attribute ``_kwarg_doc`` on the method. It is used to overwrite auto-generated documentation in the *kwdoc list* for artists. The kwdoc list is used to document ``**kwargs`` when they are properties of an artist. See e.g. the ``**kwargs`` section in `.Axes.text`.
The text should contain the supported types, as well as the default value if applicable, e.g.:
@_docstring.kwarg_doc("bool, default: :rc:`text.usetex`") def set_usetex(self, usetex):
See Also -------- matplotlib.artist.kwdoc
""" def decorator(func): func._kwarg_doc = text return func return decorator
class Substitution: """ A decorator that performs %-substitution on an object's docstring.
This decorator should be robust even if ``obj.__doc__`` is None (for example, if -OO was passed to the interpreter).
Usage: construct a docstring.Substitution with a sequence or dictionary suitable for performing substitution; then decorate a suitable function with the constructed object, e.g.::
sub_author_name = Substitution(author='Jason')
@sub_author_name def some_function(x): "%(author)s wrote this function"
# note that some_function.__doc__ is now "Jason wrote this function"
One can also use positional arguments::
sub_first_last_names = Substitution('Edgar Allen', 'Poe')
@sub_first_last_names def some_function(x): "%s %s wrote the Raven" """ def __init__(self, *args, **kwargs): if args and kwargs: raise TypeError("Only positional or keyword args are allowed") self.params = args or kwargs
def __call__(self, func): if func.__doc__: func.__doc__ = inspect.cleandoc(func.__doc__) % self.params return func
class _ArtistKwdocLoader(dict): def __missing__(self, key): if not key.endswith(":kwdoc"): raise KeyError(key) name = key[:-len(":kwdoc")] from matplotlib.artist import Artist, kwdoc try: cls, = (cls for cls in _api.recursive_subclasses(Artist) if cls.__name__ == name) except ValueError as e: raise KeyError(key) from e return self.setdefault(key, kwdoc(cls))
class _ArtistPropertiesSubstitution: """ A class to substitute formatted placeholders in docstrings.
This is realized in a single instance ``_docstring.interpd``.
Use `~._ArtistPropertiesSubstition.register` to define placeholders and their substitution, e.g. ``_docstring.interpd.register(name="some value")``.
Use this as a decorator to apply the substitution::
@_docstring.interpd def some_func(): '''Replace %(name)s.'''
Decorating a class triggers substitution both on the class docstring and on the class' ``__init__`` docstring (which is a commonly required pattern for Artist subclasses).
Substitutions of the form ``%(classname:kwdoc)s`` (ending with the literal ":kwdoc" suffix) trigger lookup of an Artist subclass with the given *classname*, and are substituted with the `.kwdoc` of that class. """
def __init__(self): self.params = _ArtistKwdocLoader()
def register(self, **kwargs): """ Register substitutions.
``_docstring.interpd.register(name="some value")`` makes "name" available as a named parameter that will be replaced by "some value". """ self.params.update(**kwargs)
def __call__(self, obj): if obj.__doc__: obj.__doc__ = inspect.cleandoc(obj.__doc__) % self.params if isinstance(obj, type) and obj.__init__ != object.__init__: self(obj.__init__) return obj
def copy(source): """Copy a docstring from another source function (if present).""" def do_copy(target): if source.__doc__: target.__doc__ = source.__doc__ return target return do_copy
# Create a decorator that will house the various docstring snippets reused# throughout Matplotlib.interpd = _ArtistPropertiesSubstitution()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547"""A layoutgrid is a nrows by ncols set of boxes, meant to be used by`._constrained_layout`, each box is analogous to a subplotspec element ofa gridspec.
Each box is defined by left[ncols], right[ncols], bottom[nrows] and top[nrows],and by two editable margins for each side. The main margin gets its valueset by the size of ticklabels, titles, etc on each Axes that is in the figure.The outer margin is the padding around the Axes, and space for anycolorbars.
The "inner" widths and heights of these boxes are then constrained to be thesame (relative the values of `width_ratios[ncols]` and `height_ratios[nrows]`).
The layoutgrid is then constrained to be contained within a parent layoutgrid,its column(s) and row(s) specified when it is created."""
import itertoolsimport kiwisolver as kiwiimport loggingimport numpy as np
import matplotlib as mplimport matplotlib.patches as mpatchesfrom matplotlib.transforms import Bbox
_log = logging.getLogger(__name__)
class LayoutGrid: """ Analogous to a gridspec, and contained in another LayoutGrid. """
def __init__(self, parent=None, parent_pos=(0, 0), parent_inner=False, name='', ncols=1, nrows=1, h_pad=None, w_pad=None, width_ratios=None, height_ratios=None): Variable = kiwi.Variable self.parent_pos = parent_pos self.parent_inner = parent_inner self.name = name + seq_id() if isinstance(parent, LayoutGrid): self.name = f'{parent.name}.{self.name}' self.nrows = nrows self.ncols = ncols self.height_ratios = np.atleast_1d(height_ratios) if height_ratios is None: self.height_ratios = np.ones(nrows) self.width_ratios = np.atleast_1d(width_ratios) if width_ratios is None: self.width_ratios = np.ones(ncols)
sn = self.name + '_' if not isinstance(parent, LayoutGrid): # parent can be a rect if not a LayoutGrid # allows specifying a rectangle to contain the layout. self.solver = kiwi.Solver() else: parent.add_child(self, *parent_pos) self.solver = parent.solver # keep track of artist associated w/ this layout. Can be none self.artists = np.empty((nrows, ncols), dtype=object) self.children = np.empty((nrows, ncols), dtype=object)
self.margins = {} self.margin_vals = {} # all the boxes in each column share the same left/right margins: for todo in ['left', 'right', 'leftcb', 'rightcb']: # track the value so we can change only if a margin is larger # than the current value self.margin_vals[todo] = np.zeros(ncols)
sol = self.solver
self.lefts = [Variable(f'{sn}lefts[{i}]') for i in range(ncols)] self.rights = [Variable(f'{sn}rights[{i}]') for i in range(ncols)] for todo in ['left', 'right', 'leftcb', 'rightcb']: self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]') for i in range(ncols)] for i in range(ncols): sol.addEditVariable(self.margins[todo][i], 'strong')
for todo in ['bottom', 'top', 'bottomcb', 'topcb']: self.margins[todo] = np.empty((nrows), dtype=object) self.margin_vals[todo] = np.zeros(nrows)
self.bottoms = [Variable(f'{sn}bottoms[{i}]') for i in range(nrows)] self.tops = [Variable(f'{sn}tops[{i}]') for i in range(nrows)] for todo in ['bottom', 'top', 'bottomcb', 'topcb']: self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]') for i in range(nrows)] for i in range(nrows): sol.addEditVariable(self.margins[todo][i], 'strong')
# set these margins to zero by default. They will be edited as # children are filled. self.reset_margins() self.add_constraints(parent)
self.h_pad = h_pad self.w_pad = w_pad
def __repr__(self): str = f'LayoutBox: {self.name:25s} {self.nrows}x{self.ncols},\n' for i in range(self.nrows): for j in range(self.ncols): str += f'{i}, {j}: '\ f'L{self.lefts[j].value():1.3f}, ' \ f'B{self.bottoms[i].value():1.3f}, ' \ f'R{self.rights[j].value():1.3f}, ' \ f'T{self.tops[i].value():1.3f}, ' \ f'ML{self.margins["left"][j].value():1.3f}, ' \ f'MR{self.margins["right"][j].value():1.3f}, ' \ f'MB{self.margins["bottom"][i].value():1.3f}, ' \ f'MT{self.margins["top"][i].value():1.3f}, \n' return str
def reset_margins(self): """ Reset all the margins to zero. Must do this after changing figure size, for instance, because the relative size of the axes labels etc changes. """ for todo in ['left', 'right', 'bottom', 'top', 'leftcb', 'rightcb', 'bottomcb', 'topcb']: self.edit_margins(todo, 0.0)
def add_constraints(self, parent): # define self-consistent constraints self.hard_constraints() # define relationship with parent layoutgrid: self.parent_constraints(parent) # define relative widths of the grid cells to each other # and stack horizontally and vertically. self.grid_constraints()
def hard_constraints(self): """ These are the redundant constraints, plus ones that make the rest of the code easier. """ for i in range(self.ncols): hc = [self.rights[i] >= self.lefts[i], (self.rights[i] - self.margins['right'][i] - self.margins['rightcb'][i] >= self.lefts[i] - self.margins['left'][i] - self.margins['leftcb'][i]) ] for c in hc: self.solver.addConstraint(c | 'required')
for i in range(self.nrows): hc = [self.tops[i] >= self.bottoms[i], (self.tops[i] - self.margins['top'][i] - self.margins['topcb'][i] >= self.bottoms[i] - self.margins['bottom'][i] - self.margins['bottomcb'][i]) ] for c in hc: self.solver.addConstraint(c | 'required')
def add_child(self, child, i=0, j=0): # np.ix_ returns the cross product of i and j indices self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child
def parent_constraints(self, parent): # constraints that are due to the parent... # i.e. the first column's left is equal to the # parent's left, the last column right equal to the # parent's right... if not isinstance(parent, LayoutGrid): # specify a rectangle in figure coordinates hc = [self.lefts[0] == parent[0], self.rights[-1] == parent[0] + parent[2], # top and bottom reversed order... self.tops[0] == parent[1] + parent[3], self.bottoms[-1] == parent[1]] else: rows, cols = self.parent_pos rows = np.atleast_1d(rows) cols = np.atleast_1d(cols)
left = parent.lefts[cols[0]] right = parent.rights[cols[-1]] top = parent.tops[rows[0]] bottom = parent.bottoms[rows[-1]] if self.parent_inner: # the layout grid is contained inside the inner # grid of the parent. left += parent.margins['left'][cols[0]] left += parent.margins['leftcb'][cols[0]] right -= parent.margins['right'][cols[-1]] right -= parent.margins['rightcb'][cols[-1]] top -= parent.margins['top'][rows[0]] top -= parent.margins['topcb'][rows[0]] bottom += parent.margins['bottom'][rows[-1]] bottom += parent.margins['bottomcb'][rows[-1]] hc = [self.lefts[0] == left, self.rights[-1] == right, # from top to bottom self.tops[0] == top, self.bottoms[-1] == bottom] for c in hc: self.solver.addConstraint(c | 'required')
def grid_constraints(self): # constrain the ratio of the inner part of the grids # to be the same (relative to width_ratios)
# constrain widths: w = (self.rights[0] - self.margins['right'][0] - self.margins['rightcb'][0]) w = (w - self.lefts[0] - self.margins['left'][0] - self.margins['leftcb'][0]) w0 = w / self.width_ratios[0] # from left to right for i in range(1, self.ncols): w = (self.rights[i] - self.margins['right'][i] - self.margins['rightcb'][i]) w = (w - self.lefts[i] - self.margins['left'][i] - self.margins['leftcb'][i]) c = (w == w0 * self.width_ratios[i]) self.solver.addConstraint(c | 'strong') # constrain the grid cells to be directly next to each other. c = (self.rights[i - 1] == self.lefts[i]) self.solver.addConstraint(c | 'strong')
# constrain heights: h = self.tops[0] - self.margins['top'][0] - self.margins['topcb'][0] h = (h - self.bottoms[0] - self.margins['bottom'][0] - self.margins['bottomcb'][0]) h0 = h / self.height_ratios[0] # from top to bottom: for i in range(1, self.nrows): h = (self.tops[i] - self.margins['top'][i] - self.margins['topcb'][i]) h = (h - self.bottoms[i] - self.margins['bottom'][i] - self.margins['bottomcb'][i]) c = (h == h0 * self.height_ratios[i]) self.solver.addConstraint(c | 'strong') # constrain the grid cells to be directly above each other. c = (self.bottoms[i - 1] == self.tops[i]) self.solver.addConstraint(c | 'strong')
# Margin editing: The margins are variable and meant to # contain things of a fixed size like axes labels, tick labels, titles # etc def edit_margin(self, todo, size, cell): """ Change the size of the margin for one cell.
Parameters ---------- todo : string (one of 'left', 'right', 'bottom', 'top') margin to alter.
size : float Size of the margin. If it is larger than the existing minimum it updates the margin size. Fraction of figure size.
cell : int Cell column or row to edit. """ self.solver.suggestValue(self.margins[todo][cell], size) self.margin_vals[todo][cell] = size
def edit_margin_min(self, todo, size, cell=0): """ Change the minimum size of the margin for one cell.
Parameters ---------- todo : string (one of 'left', 'right', 'bottom', 'top') margin to alter.
size : float Minimum size of the margin . If it is larger than the existing minimum it updates the margin size. Fraction of figure size.
cell : int Cell column or row to edit. """
if size > self.margin_vals[todo][cell]: self.edit_margin(todo, size, cell)
def edit_margins(self, todo, size): """ Change the size of all the margin of all the cells in the layout grid.
Parameters ---------- todo : string (one of 'left', 'right', 'bottom', 'top') margin to alter.
size : float Size to set the margins. Fraction of figure size. """
for i in range(len(self.margin_vals[todo])): self.edit_margin(todo, size, i)
def edit_all_margins_min(self, todo, size): """ Change the minimum size of all the margin of all the cells in the layout grid.
Parameters ---------- todo : {'left', 'right', 'bottom', 'top'} The margin to alter.
size : float Minimum size of the margin. If it is larger than the existing minimum it updates the margin size. Fraction of figure size. """
for i in range(len(self.margin_vals[todo])): self.edit_margin_min(todo, size, i)
def edit_outer_margin_mins(self, margin, ss): """ Edit all four margin minimums in one statement.
Parameters ---------- margin : dict size of margins in a dict with keys 'left', 'right', 'bottom', 'top'
ss : SubplotSpec defines the subplotspec these margins should be applied to """
self.edit_margin_min('left', margin['left'], ss.colspan.start) self.edit_margin_min('leftcb', margin['leftcb'], ss.colspan.start) self.edit_margin_min('right', margin['right'], ss.colspan.stop - 1) self.edit_margin_min('rightcb', margin['rightcb'], ss.colspan.stop - 1) # rows are from the top down: self.edit_margin_min('top', margin['top'], ss.rowspan.start) self.edit_margin_min('topcb', margin['topcb'], ss.rowspan.start) self.edit_margin_min('bottom', margin['bottom'], ss.rowspan.stop - 1) self.edit_margin_min('bottomcb', margin['bottomcb'], ss.rowspan.stop - 1)
def get_margins(self, todo, col): """Return the margin at this position""" return self.margin_vals[todo][col]
def get_outer_bbox(self, rows=0, cols=0): """ Return the outer bounding box of the subplot specs given by rows and cols. rows and cols can be spans. """ rows = np.atleast_1d(rows) cols = np.atleast_1d(cols)
bbox = Bbox.from_extents( self.lefts[cols[0]].value(), self.bottoms[rows[-1]].value(), self.rights[cols[-1]].value(), self.tops[rows[0]].value()) return bbox
def get_inner_bbox(self, rows=0, cols=0): """ Return the inner bounding box of the subplot specs given by rows and cols. rows and cols can be spans. """ rows = np.atleast_1d(rows) cols = np.atleast_1d(cols)
bbox = Bbox.from_extents( (self.lefts[cols[0]].value() + self.margins['left'][cols[0]].value() + self.margins['leftcb'][cols[0]].value()), (self.bottoms[rows[-1]].value() + self.margins['bottom'][rows[-1]].value() + self.margins['bottomcb'][rows[-1]].value()), (self.rights[cols[-1]].value() - self.margins['right'][cols[-1]].value() - self.margins['rightcb'][cols[-1]].value()), (self.tops[rows[0]].value() - self.margins['top'][rows[0]].value() - self.margins['topcb'][rows[0]].value()) ) return bbox
def get_bbox_for_cb(self, rows=0, cols=0): """ Return the bounding box that includes the decorations but, *not* the colorbar... """ rows = np.atleast_1d(rows) cols = np.atleast_1d(cols)
bbox = Bbox.from_extents( (self.lefts[cols[0]].value() + self.margins['leftcb'][cols[0]].value()), (self.bottoms[rows[-1]].value() + self.margins['bottomcb'][rows[-1]].value()), (self.rights[cols[-1]].value() - self.margins['rightcb'][cols[-1]].value()), (self.tops[rows[0]].value() - self.margins['topcb'][rows[0]].value()) ) return bbox
def get_left_margin_bbox(self, rows=0, cols=0): """ Return the left margin bounding box of the subplot specs given by rows and cols. rows and cols can be spans. """ rows = np.atleast_1d(rows) cols = np.atleast_1d(cols)
bbox = Bbox.from_extents( (self.lefts[cols[0]].value() + self.margins['leftcb'][cols[0]].value()), (self.bottoms[rows[-1]].value()), (self.lefts[cols[0]].value() + self.margins['leftcb'][cols[0]].value() + self.margins['left'][cols[0]].value()), (self.tops[rows[0]].value())) return bbox
def get_bottom_margin_bbox(self, rows=0, cols=0): """ Return the left margin bounding box of the subplot specs given by rows and cols. rows and cols can be spans. """ rows = np.atleast_1d(rows) cols = np.atleast_1d(cols)
bbox = Bbox.from_extents( (self.lefts[cols[0]].value()), (self.bottoms[rows[-1]].value() + self.margins['bottomcb'][rows[-1]].value()), (self.rights[cols[-1]].value()), (self.bottoms[rows[-1]].value() + self.margins['bottom'][rows[-1]].value() + self.margins['bottomcb'][rows[-1]].value() )) return bbox
def get_right_margin_bbox(self, rows=0, cols=0): """ Return the left margin bounding box of the subplot specs given by rows and cols. rows and cols can be spans. """ rows = np.atleast_1d(rows) cols = np.atleast_1d(cols)
bbox = Bbox.from_extents( (self.rights[cols[-1]].value() - self.margins['right'][cols[-1]].value() - self.margins['rightcb'][cols[-1]].value()), (self.bottoms[rows[-1]].value()), (self.rights[cols[-1]].value() - self.margins['rightcb'][cols[-1]].value()), (self.tops[rows[0]].value())) return bbox
def get_top_margin_bbox(self, rows=0, cols=0): """ Return the left margin bounding box of the subplot specs given by rows and cols. rows and cols can be spans. """ rows = np.atleast_1d(rows) cols = np.atleast_1d(cols)
bbox = Bbox.from_extents( (self.lefts[cols[0]].value()), (self.tops[rows[0]].value() - self.margins['topcb'][rows[0]].value()), (self.rights[cols[-1]].value()), (self.tops[rows[0]].value() - self.margins['topcb'][rows[0]].value() - self.margins['top'][rows[0]].value())) return bbox
def update_variables(self): """ Update the variables for the solver attached to this layoutgrid. """ self.solver.updateVariables()
_layoutboxobjnum = itertools.count()
def seq_id(): """Generate a short sequential id for layoutbox objects.""" return '%06d' % next(_layoutboxobjnum)
def plot_children(fig, lg=None, level=0): """Simple plotting to show where boxes are.""" if lg is None: _layoutgrids = fig.get_layout_engine().execute(fig) lg = _layoutgrids[fig] colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"] col = colors[level] for i in range(lg.nrows): for j in range(lg.ncols): bb = lg.get_outer_bbox(rows=i, cols=j) fig.add_artist( mpatches.Rectangle(bb.p0, bb.width, bb.height, linewidth=1, edgecolor='0.7', facecolor='0.7', alpha=0.2, transform=fig.transFigure, zorder=-3)) bbi = lg.get_inner_bbox(rows=i, cols=j) fig.add_artist( mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=2, edgecolor=col, facecolor='none', transform=fig.transFigure, zorder=-2))
bbi = lg.get_left_margin_bbox(rows=i, cols=j) fig.add_artist( mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, edgecolor='none', alpha=0.2, facecolor=[0.5, 0.7, 0.5], transform=fig.transFigure, zorder=-2)) bbi = lg.get_right_margin_bbox(rows=i, cols=j) fig.add_artist( mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, edgecolor='none', alpha=0.2, facecolor=[0.7, 0.5, 0.5], transform=fig.transFigure, zorder=-2)) bbi = lg.get_bottom_margin_bbox(rows=i, cols=j) fig.add_artist( mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, edgecolor='none', alpha=0.2, facecolor=[0.5, 0.5, 0.7], transform=fig.transFigure, zorder=-2)) bbi = lg.get_top_margin_bbox(rows=i, cols=j) fig.add_artist( mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, edgecolor='none', alpha=0.2, facecolor=[0.7, 0.2, 0.7], transform=fig.transFigure, zorder=-2)) for ch in lg.children.flat: if ch is not None: plot_children(fig, ch, level=level+1)123456789from collections.abc import Sequence
import numpy as np
from .transforms import BboxBase
def affine_transform(points: np.ndarray, trans: np.ndarray) -> np.ndarray: ...def count_bboxes_overlapping_bbox(bbox: BboxBase, bboxes: Sequence[BboxBase]) -> int: ...def update_path_extents(path, trans, rect, minpos, ignore): ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301"""Routines to adjust subplot params so that subplots arenicely fit in the figure. In doing so, only axis labels, tick labels, Axestitles and offsetboxes that are anchored to Axes are currently considered.
Internally, this module assumes that the margins (left margin, etc.) which aredifferences between ``Axes.get_tightbbox`` and ``Axes.bbox`` are independent ofAxes position. This may fail if ``Axes.adjustable`` is ``datalim`` as well assuch cases as when left or right margin are affected by xlabel."""
import numpy as np
import matplotlib as mplfrom matplotlib import _api, artist as martistfrom matplotlib.font_manager import FontPropertiesfrom matplotlib.transforms import Bbox
def _auto_adjust_subplotpars( fig, renderer, shape, span_pairs, subplot_list, ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None): """ Return a dict of subplot parameters to adjust spacing between subplots or ``None`` if resulting Axes would have zero height or width.
Note that this function ignores geometry information of subplot itself, but uses what is given by the *shape* and *subplot_list* parameters. Also, the results could be incorrect if some subplots have ``adjustable=datalim``.
Parameters ---------- shape : tuple[int, int] Number of rows and columns of the grid. span_pairs : list[tuple[slice, slice]] List of rowspans and colspans occupied by each subplot. subplot_list : list of subplots List of subplots that will be used to calculate optimal subplot_params. pad : float Padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad : float Padding (height/width) between edges of adjacent subplots, as a fraction of the font size. Defaults to *pad*. rect : tuple (left, bottom, right, top), default: None. """ rows, cols = shape
font_size_inch = (FontProperties( size=mpl.rcParams["font.size"]).get_size_in_points() / 72) pad_inch = pad * font_size_inch vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch
if len(span_pairs) != len(subplot_list) or len(subplot_list) == 0: raise ValueError
if rect is None: margin_left = margin_bottom = margin_right = margin_top = None else: margin_left, margin_bottom, _right, _top = rect margin_right = 1 - _right if _right else None margin_top = 1 - _top if _top else None
vspaces = np.zeros((rows + 1, cols)) hspaces = np.zeros((rows, cols + 1))
if ax_bbox_list is None: ax_bbox_list = [ Bbox.union([ax.get_position(original=True) for ax in subplots]) for subplots in subplot_list]
for subplots, ax_bbox, (rowspan, colspan) in zip( subplot_list, ax_bbox_list, span_pairs): if all(not ax.get_visible() for ax in subplots): continue
bb = [] for ax in subplots: if ax.get_visible(): bb += [martist._get_tightbbox_for_layout_only(ax, renderer)]
tight_bbox_raw = Bbox.union(bb) tight_bbox = fig.transFigure.inverted().transform_bbox(tight_bbox_raw)
hspaces[rowspan, colspan.start] += ax_bbox.xmin - tight_bbox.xmin # l hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax # r vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax # t vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin # b
fig_width_inch, fig_height_inch = fig.get_size_inches()
# margins can be negative for Axes with aspect applied, so use max(, 0) to # make them nonnegative. if not margin_left: margin_left = max(hspaces[:, 0].max(), 0) + pad_inch/fig_width_inch suplabel = fig._supylabel if suplabel and suplabel.get_in_layout(): rel_width = fig.transFigure.inverted().transform_bbox( suplabel.get_window_extent(renderer)).width margin_left += rel_width + pad_inch/fig_width_inch if not margin_right: margin_right = max(hspaces[:, -1].max(), 0) + pad_inch/fig_width_inch if not margin_top: margin_top = max(vspaces[0, :].max(), 0) + pad_inch/fig_height_inch if fig._suptitle and fig._suptitle.get_in_layout(): rel_height = fig.transFigure.inverted().transform_bbox( fig._suptitle.get_window_extent(renderer)).height margin_top += rel_height + pad_inch/fig_height_inch if not margin_bottom: margin_bottom = max(vspaces[-1, :].max(), 0) + pad_inch/fig_height_inch suplabel = fig._supxlabel if suplabel and suplabel.get_in_layout(): rel_height = fig.transFigure.inverted().transform_bbox( suplabel.get_window_extent(renderer)).height margin_bottom += rel_height + pad_inch/fig_height_inch
if margin_left + margin_right >= 1: _api.warn_external('Tight layout not applied. The left and right ' 'margins cannot be made large enough to ' 'accommodate all Axes decorations.') return None if margin_bottom + margin_top >= 1: _api.warn_external('Tight layout not applied. The bottom and top ' 'margins cannot be made large enough to ' 'accommodate all Axes decorations.') return None
kwargs = dict(left=margin_left, right=1 - margin_right, bottom=margin_bottom, top=1 - margin_top)
if cols > 1: hspace = hspaces[:, 1:-1].max() + hpad_inch / fig_width_inch # axes widths: h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols if h_axes < 0: _api.warn_external('Tight layout not applied. tight_layout ' 'cannot make Axes width small enough to ' 'accommodate all Axes decorations') return None else: kwargs["wspace"] = hspace / h_axes if rows > 1: vspace = vspaces[1:-1, :].max() + vpad_inch / fig_height_inch v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows if v_axes < 0: _api.warn_external('Tight layout not applied. tight_layout ' 'cannot make Axes height small enough to ' 'accommodate all Axes decorations.') return None else: kwargs["hspace"] = vspace / v_axes
return kwargs
def get_subplotspec_list(axes_list, grid_spec=None): """ Return a list of subplotspec from the given list of Axes.
For an instance of Axes that does not support subplotspec, None is inserted in the list.
If grid_spec is given, None is inserted for those not from the given grid_spec. """ subplotspec_list = [] for ax in axes_list: axes_or_locator = ax.get_axes_locator() if axes_or_locator is None: axes_or_locator = ax
if hasattr(axes_or_locator, "get_subplotspec"): subplotspec = axes_or_locator.get_subplotspec() if subplotspec is not None: subplotspec = subplotspec.get_topmost_subplotspec() gs = subplotspec.get_gridspec() if grid_spec is not None: if gs != grid_spec: subplotspec = None elif gs.locally_modified_subplot_params(): subplotspec = None else: subplotspec = None
subplotspec_list.append(subplotspec)
return subplotspec_list
def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, pad=1.08, h_pad=None, w_pad=None, rect=None): """ Return subplot parameters for tight-layouted-figure with specified padding.
Parameters ---------- fig : Figure axes_list : list of Axes subplotspec_list : list of `.SubplotSpec` The subplotspecs of each Axes. renderer : renderer pad : float Padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad : float Padding (height/width) between edges of adjacent subplots. Defaults to *pad*. rect : tuple (left, bottom, right, top), default: None. rectangle in normalized figure coordinates that the whole subplots area (including labels) will fit into. Defaults to using the entire figure.
Returns ------- subplotspec or None subplotspec kwargs to be passed to `.Figure.subplots_adjust` or None if tight_layout could not be accomplished. """
# Multiple Axes can share same subplotspec (e.g., if using axes_grid1); # we need to group them together. ss_to_subplots = {ss: [] for ss in subplotspec_list} for ax, ss in zip(axes_list, subplotspec_list): ss_to_subplots[ss].append(ax) if ss_to_subplots.pop(None, None): _api.warn_external( "This figure includes Axes that are not compatible with " "tight_layout, so results might be incorrect.") if not ss_to_subplots: return {} subplot_list = list(ss_to_subplots.values()) ax_bbox_list = [ss.get_position(fig) for ss in ss_to_subplots]
max_nrows = max(ss.get_gridspec().nrows for ss in ss_to_subplots) max_ncols = max(ss.get_gridspec().ncols for ss in ss_to_subplots)
span_pairs = [] for ss in ss_to_subplots: # The intent here is to support Axes from different gridspecs where # one's nrows (or ncols) is a multiple of the other (e.g. 2 and 4), # but this doesn't actually work because the computed wspace, in # relative-axes-height, corresponds to different physical spacings for # the 2-row grid and the 4-row grid. Still, this code is left, mostly # for backcompat. rows, cols = ss.get_gridspec().get_geometry() div_row, mod_row = divmod(max_nrows, rows) div_col, mod_col = divmod(max_ncols, cols) if mod_row != 0: _api.warn_external('tight_layout not applied: number of rows ' 'in subplot specifications must be ' 'multiples of one another.') return {} if mod_col != 0: _api.warn_external('tight_layout not applied: number of ' 'columns in subplot specifications must be ' 'multiples of one another.') return {} span_pairs.append(( slice(ss.rowspan.start * div_row, ss.rowspan.stop * div_row), slice(ss.colspan.start * div_col, ss.colspan.stop * div_col)))
kwargs = _auto_adjust_subplotpars(fig, renderer, shape=(max_nrows, max_ncols), span_pairs=span_pairs, subplot_list=subplot_list, ax_bbox_list=ax_bbox_list, pad=pad, h_pad=h_pad, w_pad=w_pad)
# kwargs can be none if tight_layout fails... if rect is not None and kwargs is not None: # if rect is given, the whole subplots area (including # labels) will fit into the rect instead of the # figure. Note that the rect argument of # *auto_adjust_subplotpars* specify the area that will be # covered by the total area of axes.bbox. Thus we call # auto_adjust_subplotpars twice, where the second run # with adjusted rect parameters.
left, bottom, right, top = rect if left is not None: left += kwargs["left"] if bottom is not None: bottom += kwargs["bottom"] if right is not None: right -= (1 - kwargs["right"]) if top is not None: top -= (1 - kwargs["top"])
kwargs = _auto_adjust_subplotpars(fig, renderer, shape=(max_nrows, max_ncols), span_pairs=span_pairs, subplot_list=subplot_list, ax_bbox_list=ax_bbox_list, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=(left, bottom, right, top))
return kwargs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217import abcfrom collections.abc import Callable, Collection, Iterable, Sequence, Generatorimport contextlibfrom pathlib import Pathfrom matplotlib.artist import Artistfrom matplotlib.backend_bases import TimerBasefrom matplotlib.figure import Figure
from typing import Any
subprocess_creation_flags: int
def adjusted_figsize(w: float, h: float, dpi: float, n: int) -> tuple[float, float]: ...
class MovieWriterRegistry: def __init__(self) -> None: ... def register( self, name: str ) -> Callable[[type[AbstractMovieWriter]], type[AbstractMovieWriter]]: ... def is_available(self, name: str) -> bool: ... def __iter__(self) -> Generator[str, None, None]: ... def list(self) -> list[str]: ... def __getitem__(self, name: str) -> type[AbstractMovieWriter]: ...
writers: MovieWriterRegistry
class AbstractMovieWriter(abc.ABC, metaclass=abc.ABCMeta): fps: int metadata: dict[str, str] codec: str bitrate: int def __init__( self, fps: int = ..., metadata: dict[str, str] | None = ..., codec: str | None = ..., bitrate: int | None = ..., ) -> None: ... outfile: str | Path fig: Figure dpi: float
@abc.abstractmethod def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ... @property def frame_size(self) -> tuple[int, int]: ... @abc.abstractmethod def grab_frame(self, **savefig_kwargs) -> None: ... @abc.abstractmethod def finish(self) -> None: ... @contextlib.contextmanager def saving( self, fig: Figure, outfile: str | Path, dpi: float | None, *args, **kwargs ) -> Generator[AbstractMovieWriter, None, None]: ...
class MovieWriter(AbstractMovieWriter): supported_formats: list[str] frame_format: str extra_args: list[str] | None def __init__( self, fps: int = ..., codec: str | None = ..., bitrate: int | None = ..., extra_args: list[str] | None = ..., metadata: dict[str, str] | None = ..., ) -> None: ... def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ... def grab_frame(self, **savefig_kwargs) -> None: ... def finish(self) -> None: ... @classmethod def bin_path(cls) -> str: ... @classmethod def isAvailable(cls) -> bool: ...
class FileMovieWriter(MovieWriter): fig: Figure outfile: str | Path dpi: float temp_prefix: str fname_format_str: str def setup( self, fig: Figure, outfile: str | Path, dpi: float | None = ..., frame_prefix: str | Path | None = ..., ) -> None: ... def __del__(self) -> None: ... @property def frame_format(self) -> str: ... @frame_format.setter def frame_format(self, frame_format: str) -> None: ...
class PillowWriter(AbstractMovieWriter): @classmethod def isAvailable(cls) -> bool: ... def setup( self, fig: Figure, outfile: str | Path, dpi: float | None = ... ) -> None: ... def grab_frame(self, **savefig_kwargs) -> None: ... def finish(self) -> None: ...
class FFMpegBase: codec: str @property def output_args(self) -> list[str]: ...
class FFMpegWriter(FFMpegBase, MovieWriter): ...
class FFMpegFileWriter(FFMpegBase, FileMovieWriter): supported_formats: list[str]
class ImageMagickBase: @classmethod def bin_path(cls) -> str: ... @classmethod def isAvailable(cls) -> bool: ...
class ImageMagickWriter(ImageMagickBase, MovieWriter): input_names: str
class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter): supported_formats: list[str] @property def input_names(self) -> str: ...
class HTMLWriter(FileMovieWriter): supported_formats: list[str] @classmethod def isAvailable(cls) -> bool: ... embed_frames: bool default_mode: str def __init__( self, fps: int = ..., codec: str | None = ..., bitrate: int | None = ..., extra_args: list[str] | None = ..., metadata: dict[str, str] | None = ..., embed_frames: bool = ..., default_mode: str = ..., embed_limit: float | None = ..., ) -> None: ... def setup( self, fig: Figure, outfile: str | Path, dpi: float | None = ..., frame_dir: str | Path | None = ..., ) -> None: ... def grab_frame(self, **savefig_kwargs): ... def finish(self) -> None: ...
class Animation: frame_seq: Iterable[Artist] event_source: Any def __init__( self, fig: Figure, event_source: Any | None = ..., blit: bool = ... ) -> None: ... def __del__(self) -> None: ... def save( self, filename: str | Path, writer: AbstractMovieWriter | str | None = ..., fps: int | None = ..., dpi: float | None = ..., codec: str | None = ..., bitrate: int | None = ..., extra_args: list[str] | None = ..., metadata: dict[str, str] | None = ..., extra_anim: list[Animation] | None = ..., savefig_kwargs: dict[str, Any] | None = ..., *, progress_callback: Callable[[int, int], Any] | None = ... ) -> None: ... def new_frame_seq(self) -> Iterable[Artist]: ... def new_saved_frame_seq(self) -> Iterable[Artist]: ... def to_html5_video(self, embed_limit: float | None = ...) -> str: ... def to_jshtml( self, fps: int | None = ..., embed_frames: bool = ..., default_mode: str | None = ..., ) -> str: ... def _repr_html_(self) -> str: ... def pause(self) -> None: ... def resume(self) -> None: ...
class TimedAnimation(Animation): def __init__( self, fig: Figure, interval: int = ..., repeat_delay: int = ..., repeat: bool = ..., event_source: TimerBase | None = ..., *args, **kwargs ) -> None: ...
class ArtistAnimation(TimedAnimation): def __init__(self, fig: Figure, artists: Sequence[Collection[Artist]], *args, **kwargs) -> None: ...
class FuncAnimation(TimedAnimation): def __init__( self, fig: Figure, func: Callable[..., Iterable[Artist]], frames: Iterable | int | Callable[[], Generator] | None = ..., init_func: Callable[[], Iterable[Artist]] | None = ..., fargs: tuple[Any, ...] | None = ..., save_count: int | None = ..., *, cache_frame_data: bool = ..., **kwargs ) -> None: ...1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855from collections import namedtupleimport contextlibfrom functools import cache, reduce, wrapsimport inspectfrom inspect import Signature, Parameterimport loggingfrom numbers import Number, Realimport operatorimport reimport warnings
import numpy as np
import matplotlib as mplfrom . import _api, cbookfrom .path import Pathfrom .transforms import (BboxBase, Bbox, IdentityTransform, Transform, TransformedBbox, TransformedPatchPath, TransformedPath)
_log = logging.getLogger(__name__)
def _prevent_rasterization(draw): # We assume that by default artists are not allowed to rasterize (unless # its draw method is explicitly decorated). If it is being drawn after a # rasterized artist and it has reached a raster_depth of 0, we stop # rasterization so that it does not affect the behavior of normal artist # (e.g., change in dpi).
@wraps(draw) def draw_wrapper(artist, renderer, *args, **kwargs): if renderer._raster_depth == 0 and renderer._rasterizing: # Only stop when we are not in a rasterized parent # and something has been rasterized since last stop. renderer.stop_rasterizing() renderer._rasterizing = False
return draw(artist, renderer, *args, **kwargs)
draw_wrapper._supports_rasterization = False return draw_wrapper
def allow_rasterization(draw): """ Decorator for Artist.draw method. Provides routines that run before and after the draw call. The before and after functions are useful for changing artist-dependent renderer attributes or making other setup function calls, such as starting and flushing a mixed-mode renderer. """
@wraps(draw) def draw_wrapper(artist, renderer): try: if artist.get_rasterized(): if renderer._raster_depth == 0 and not renderer._rasterizing: renderer.start_rasterizing() renderer._rasterizing = True renderer._raster_depth += 1 else: if renderer._raster_depth == 0 and renderer._rasterizing: # Only stop when we are not in a rasterized parent # and something has be rasterized since last stop renderer.stop_rasterizing() renderer._rasterizing = False
if artist.get_agg_filter() is not None: renderer.start_filter()
return draw(artist, renderer) finally: if artist.get_agg_filter() is not None: renderer.stop_filter(artist.get_agg_filter()) if artist.get_rasterized(): renderer._raster_depth -= 1 if (renderer._rasterizing and (fig := artist.get_figure(root=True)) and fig.suppressComposite): # restart rasterizing to prevent merging renderer.stop_rasterizing() renderer.start_rasterizing()
draw_wrapper._supports_rasterization = True return draw_wrapper
def _finalize_rasterization(draw): """ Decorator for Artist.draw method. Needed on the outermost artist, i.e. Figure, to finish up if the render is still in rasterized mode. """ @wraps(draw) def draw_wrapper(artist, renderer, *args, **kwargs): result = draw(artist, renderer, *args, **kwargs) if renderer._rasterizing: renderer.stop_rasterizing() renderer._rasterizing = False return result return draw_wrapper
def _stale_axes_callback(self, val): if self.axes: self.axes.stale = val
_XYPair = namedtuple("_XYPair", "x y")
class _Unset: def __repr__(self): return "<UNSET>"_UNSET = _Unset()
class Artist: """ Abstract base class for objects that render into a FigureCanvas.
Typically, all visible elements in a figure are subclasses of Artist. """
zorder = 0
def __init_subclass__(cls):
# Decorate draw() method so that all artists are able to stop # rastrization when necessary. If the artist's draw method is already # decorated (has a `_supports_rasterization` attribute), it won't be # decorated.
if not hasattr(cls.draw, "_supports_rasterization"): cls.draw = _prevent_rasterization(cls.draw)
# Inject custom set() methods into the subclass with signature and # docstring based on the subclasses' properties.
if not hasattr(cls.set, '_autogenerated_signature'): # Don't overwrite cls.set if the subclass or one of its parents # has defined a set method set itself. # If there was no explicit definition, cls.set is inherited from # the hierarchy of auto-generated set methods, which hold the # flag _autogenerated_signature. return
cls.set = lambda self, **kwargs: Artist.set(self, **kwargs) cls.set.__name__ = "set" cls.set.__qualname__ = f"{cls.__qualname__}.set" cls._update_set_signature_and_docstring()
_PROPERTIES_EXCLUDED_FROM_SET = [ 'navigate_mode', # not a user-facing function 'figure', # changing the figure is such a profound operation # that we don't want this in set() '3d_properties', # cannot be used as a keyword due to leading digit ]
@classmethod def _update_set_signature_and_docstring(cls): """ Update the signature of the set function to list all properties as keyword arguments.
Property aliases are not listed in the signature for brevity, but are still accepted as keyword arguments. """ cls.set.__signature__ = Signature( [Parameter("self", Parameter.POSITIONAL_OR_KEYWORD), *[Parameter(prop, Parameter.KEYWORD_ONLY, default=_UNSET) for prop in ArtistInspector(cls).get_setters() if prop not in Artist._PROPERTIES_EXCLUDED_FROM_SET]]) cls.set._autogenerated_signature = True
cls.set.__doc__ = ( "Set multiple properties at once.\n\n" "Supported properties are\n\n" + kwdoc(cls))
def __init__(self): self._stale = True self.stale_callback = None self._axes = None self._parent_figure = None
self._transform = None self._transformSet = False self._visible = True self._animated = False self._alpha = None self.clipbox = None self._clippath = None self._clipon = True self._label = '' self._picker = None self._rasterized = False self._agg_filter = None # Normally, artist classes need to be queried for mouseover info if and # only if they override get_cursor_data. self._mouseover = type(self).get_cursor_data != Artist.get_cursor_data self._callbacks = cbook.CallbackRegistry(signals=["pchanged"]) try: self.axes = None except AttributeError: # Handle self.axes as a read-only property, as in Figure. pass self._remove_method = None self._url = None self._gid = None self._snap = None self._sketch = mpl.rcParams['path.sketch'] self._path_effects = mpl.rcParams['path.effects'] self._sticky_edges = _XYPair([], []) self._in_layout = True
def __getstate__(self): d = self.__dict__.copy() d['stale_callback'] = None return d
def remove(self): """ Remove the artist from the figure if possible.
The effect will not be visible until the figure is redrawn, e.g., with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to update the Axes limits if desired.
Note: `~.axes.Axes.relim` will not see collections even if the collection was added to the Axes with *autolim* = True.
Note: there is no support for removing the artist's legend entry. """
# There is no method to set the callback. Instead, the parent should # set the _remove_method attribute directly. This would be a # protected attribute if Python supported that sort of thing. The # callback has one parameter, which is the child to be removed. if self._remove_method is not None: self._remove_method(self) # clear stale callback self.stale_callback = None _ax_flag = False if hasattr(self, 'axes') and self.axes: # remove from the mouse hit list self.axes._mouseover_set.discard(self) self.axes.stale = True self.axes = None # decouple the artist from the Axes _ax_flag = True
if (fig := self.get_figure(root=False)) is not None: if not _ax_flag: fig.stale = True self._parent_figure = None
else: raise NotImplementedError('cannot remove artist') # TODO: the fix for the collections relim problem is to move the # limits calculation into the artist itself, including the property of # whether or not the artist should affect the limits. Then there will # be no distinction between axes.add_line, axes.add_patch, etc. # TODO: add legend support
def have_units(self): """Return whether units are set on any axis.""" ax = self.axes return ax and any(axis.have_units() for axis in ax._axis_map.values())
def convert_xunits(self, x): """ Convert *x* using the unit type of the xaxis.
If the artist is not contained in an Axes or if the xaxis does not have units, *x* itself is returned. """ ax = getattr(self, 'axes', None) if ax is None or ax.xaxis is None: return x return ax.xaxis.convert_units(x)
def convert_yunits(self, y): """ Convert *y* using the unit type of the yaxis.
If the artist is not contained in an Axes or if the yaxis does not have units, *y* itself is returned. """ ax = getattr(self, 'axes', None) if ax is None or ax.yaxis is None: return y return ax.yaxis.convert_units(y)
@property def axes(self): """The `~.axes.Axes` instance the artist resides in, or *None*.""" return self._axes
@axes.setter def axes(self, new_axes): if (new_axes is not None and self._axes is not None and new_axes != self._axes): raise ValueError("Can not reset the Axes. You are probably trying to reuse " "an artist in more than one Axes which is not supported") self._axes = new_axes if new_axes is not None and new_axes is not self: self.stale_callback = _stale_axes_callback
@property def stale(self): """ Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist. """ return self._stale
@stale.setter def stale(self, val): self._stale = val
# if the artist is animated it does not take normal part in the # draw stack and is not expected to be drawn as part of the normal # draw loop (when not saving) so do not propagate this change if self._animated: return
if val and self.stale_callback is not None: self.stale_callback(self, val)
def get_window_extent(self, renderer=None): """ Get the artist's bounding box in display space.
The bounding box' width and height are nonnegative.
Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0.
Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the Axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly. """ return Bbox([[0, 0], [0, 0]])
def get_tightbbox(self, renderer=None): """ Like `.Artist.get_window_extent`, but includes any clipping.
Parameters ---------- renderer : `~matplotlib.backend_bases.RendererBase` subclass, optional renderer that will be used to draw the figures (i.e. ``fig.canvas.get_renderer()``)
Returns ------- `.Bbox` or None The enclosing bounding box (in figure pixel coordinates). Returns None if clipping results in no intersection. """ bbox = self.get_window_extent(renderer) if self.get_clip_on(): clip_box = self.get_clip_box() if clip_box is not None: bbox = Bbox.intersection(bbox, clip_box) clip_path = self.get_clip_path() if clip_path is not None and bbox is not None: clip_path = clip_path.get_fully_transformed_path() bbox = Bbox.intersection(bbox, clip_path.get_extents()) return bbox
def add_callback(self, func): """ Add a callback function that will be called whenever one of the `.Artist`'s properties changes.
Parameters ---------- func : callable The callback function. It must have the signature::
def func(artist: Artist) -> Any
where *artist* is the calling `.Artist`. Return values may exist but are ignored.
Returns ------- int The observer id associated with the callback. This id can be used for removing the callback with `.remove_callback` later.
See Also -------- remove_callback """ # Wrapping func in a lambda ensures it can be connected multiple times # and never gets weakref-gc'ed. return self._callbacks.connect("pchanged", lambda: func(self))
def remove_callback(self, oid): """ Remove a callback based on its observer id.
See Also -------- add_callback """ self._callbacks.disconnect(oid)
def pchanged(self): """ Call all of the registered callbacks.
This function is triggered internally when a property is changed.
See Also -------- add_callback remove_callback """ self._callbacks.process("pchanged")
def is_transform_set(self): """ Return whether the Artist has an explicitly set transform.
This is *True* after `.set_transform` has been called. """ return self._transformSet
def set_transform(self, t): """ Set the artist transform.
Parameters ---------- t : `~matplotlib.transforms.Transform` """ self._transform = t self._transformSet = True self.pchanged() self.stale = True
def get_transform(self): """Return the `.Transform` instance used by this artist.""" if self._transform is None: self._transform = IdentityTransform() elif (not isinstance(self._transform, Transform) and hasattr(self._transform, '_as_mpl_transform')): self._transform = self._transform._as_mpl_transform(self.axes) return self._transform
def get_children(self): r"""Return a list of the child `.Artist`\s of this `.Artist`.""" return []
def _different_canvas(self, event): """ Check whether an *event* occurred on a canvas other that this artist's canvas.
If this method returns True, the event definitely occurred on a different canvas; if it returns False, either it occurred on the same canvas, or we may not have enough information to know.
Subclasses should start their definition of `contains` as follows::
if self._different_canvas(mouseevent): return False, {} # subclass-specific implementation follows """ return (getattr(event, "canvas", None) is not None and (fig := self.get_figure(root=True)) is not None and event.canvas is not fig.canvas)
def contains(self, mouseevent): """ Test whether the artist contains the mouse event.
Parameters ---------- mouseevent : `~matplotlib.backend_bases.MouseEvent`
Returns ------- contains : bool Whether any values are within the radius. details : dict An artist-specific dictionary of details of the event context, such as which points are contained in the pick radius. See the individual Artist subclasses for details. """ _log.warning("%r needs 'contains' method", self.__class__.__name__) return False, {}
def pickable(self): """ Return whether the artist is pickable.
See Also -------- .Artist.set_picker, .Artist.get_picker, .Artist.pick """ return self.get_figure(root=False) is not None and self._picker is not None
def pick(self, mouseevent): """ Process a pick event.
Each child artist will fire a pick event if *mouseevent* is over the artist and the artist has picker set.
See Also -------- .Artist.set_picker, .Artist.get_picker, .Artist.pickable """ from .backend_bases import PickEvent # Circular import. # Pick self if self.pickable(): picker = self.get_picker() if callable(picker): inside, prop = picker(self, mouseevent) else: inside, prop = self.contains(mouseevent) if inside: PickEvent("pick_event", self.get_figure(root=True).canvas, mouseevent, self, **prop)._process()
# Pick children for a in self.get_children(): # make sure the event happened in the same Axes ax = getattr(a, 'axes', None) if (isinstance(a, mpl.figure.SubFigure) or mouseevent.inaxes is None or ax is None or mouseevent.inaxes == ax): # we need to check if mouseevent.inaxes is None # because some objects associated with an Axes (e.g., a # tick label) can be outside the bounding box of the # Axes and inaxes will be None # also check that ax is None so that it traverse objects # which do not have an axes property but children might a.pick(mouseevent)
def set_picker(self, picker): """ Define the picking behavior of the artist.
Parameters ---------- picker : None or bool or float or callable This can be one of the following:
- *None*: Picking is disabled for this artist (default).
- A boolean: If *True* then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist.
- A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
- A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event::
hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return *hit=True* and props is a dictionary of properties you want added to the PickEvent attributes. """ self._picker = picker
def get_picker(self): """ Return the picking behavior of the artist.
The possible values are described in `.Artist.set_picker`.
See Also -------- .Artist.set_picker, .Artist.pickable, .Artist.pick """ return self._picker
def get_url(self): """Return the url.""" return self._url
def set_url(self, url): """ Set the url for the artist.
Parameters ---------- url : str """ self._url = url
def get_gid(self): """Return the group id.""" return self._gid
def set_gid(self, gid): """ Set the (group) id for the artist.
Parameters ---------- gid : str """ self._gid = gid
def get_snap(self): """ Return the snap setting.
See `.set_snap` for details. """ if mpl.rcParams['path.snap']: return self._snap else: return False
def set_snap(self, snap): """ Set the snapping behavior.
Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line.
Snapping is currently only supported by the Agg and MacOSX backends.
Parameters ---------- snap : bool or None Possible values:
- *True*: Snap vertices to the nearest pixel center. - *False*: Do not modify vertex positions. - *None*: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center. """ self._snap = snap self.stale = True
def get_sketch_params(self): """ Return the sketch parameters for the artist.
Returns ------- tuple or None
A 3-tuple with the following elements:
- *scale*: The amplitude of the wiggle perpendicular to the source line. - *length*: The length of the wiggle along the line. - *randomness*: The scale factor by which the length is shrunken or expanded.
Returns *None* if no sketch parameters were set. """ return self._sketch
def set_sketch_params(self, scale=None, length=None, randomness=None): """ Set the sketch parameters.
Parameters ---------- scale : float, optional The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is `None`, or not provided, no sketch filter will be provided. length : float, optional The length of the wiggle along the line, in pixels (default 128.0) randomness : float, optional The scale factor by which the length is shrunken or expanded (default 16.0)
The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
.. ACCEPTS: (scale: float, length: float, randomness: float) """ if scale is None: self._sketch = None else: self._sketch = (scale, length or 128.0, randomness or 16.0) self.stale = True
def set_path_effects(self, path_effects): """ Set the path effects.
Parameters ---------- path_effects : list of `.AbstractPathEffect` """ self._path_effects = path_effects self.stale = True
def get_path_effects(self): return self._path_effects
def get_figure(self, root=False): """ Return the `.Figure` or `.SubFigure` instance the artist belongs to.
Parameters ---------- root : bool, default=False If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures. """ if root and self._parent_figure is not None: return self._parent_figure.get_figure(root=True)
return self._parent_figure
def set_figure(self, fig): """ Set the `.Figure` or `.SubFigure` instance the artist belongs to.
Parameters ---------- fig : `~matplotlib.figure.Figure` or `~matplotlib.figure.SubFigure` """ # if this is a no-op just return if self._parent_figure is fig: return # if we currently have a figure (the case of both `self.figure` # and *fig* being none is taken care of above) we then user is # trying to change the figure an artist is associated with which # is not allowed for the same reason as adding the same instance # to more than one Axes if self._parent_figure is not None: raise RuntimeError("Can not put single artist in " "more than one figure") self._parent_figure = fig if self._parent_figure and self._parent_figure is not self: self.pchanged() self.stale = True
figure = property(get_figure, set_figure, doc=("The (Sub)Figure that the artist is on. For more " "control, use the `get_figure` method."))
def set_clip_box(self, clipbox): """ Set the artist's clip `.Bbox`.
Parameters ---------- clipbox : `~matplotlib.transforms.BboxBase` or None Will typically be created from a `.TransformedBbox`. For instance, ``TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes)`` is the default clipping for an artist added to an Axes.
""" _api.check_isinstance((BboxBase, None), clipbox=clipbox) if clipbox != self.clipbox: self.clipbox = clipbox self.pchanged() self.stale = True
def set_clip_path(self, path, transform=None): """ Set the artist's clip path.
Parameters ---------- path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath` or None The clip path. If given a `.Path`, *transform* must be provided as well. If *None*, a previously set clip path is removed. transform : `~matplotlib.transforms.Transform`, optional Only used if *path* is a `.Path`, in which case the given `.Path` is converted to a `.TransformedPath` using *transform*.
Notes ----- For efficiency, if *path* is a `.Rectangle` this method will set the clipping box to the corresponding rectangle and set the clipping path to ``None``.
For technical reasons (support of `~.Artist.set`), a tuple (*path*, *transform*) is also accepted as a single positional parameter.
.. ACCEPTS: Patch or (Path, Transform) or None """ from matplotlib.patches import Patch, Rectangle
success = False if transform is None: if isinstance(path, Rectangle): self.clipbox = TransformedBbox(Bbox.unit(), path.get_transform()) self._clippath = None success = True elif isinstance(path, Patch): self._clippath = TransformedPatchPath(path) success = True elif isinstance(path, tuple): path, transform = path
if path is None: self._clippath = None success = True elif isinstance(path, Path): self._clippath = TransformedPath(path, transform) success = True elif isinstance(path, TransformedPatchPath): self._clippath = path success = True elif isinstance(path, TransformedPath): self._clippath = path success = True
if not success: raise TypeError( "Invalid arguments to set_clip_path, of type " f"{type(path).__name__} and {type(transform).__name__}") # This may result in the callbacks being hit twice, but guarantees they # will be hit at least once. self.pchanged() self.stale = True
def get_alpha(self): """ Return the alpha value used for blending - not supported on all backends. """ return self._alpha
def get_visible(self): """Return the visibility.""" return self._visible
def get_animated(self): """Return whether the artist is animated.""" return self._animated
def get_in_layout(self): """ Return boolean flag, ``True`` if artist is included in layout calculations.
E.g. :ref:`constrainedlayout_guide`, `.Figure.tight_layout()`, and ``fig.savefig(fname, bbox_inches='tight')``. """ return self._in_layout
def _fully_clipped_to_axes(self): """ Return a boolean flag, ``True`` if the artist is clipped to the Axes and can thus be skipped in layout calculations. Requires `get_clip_on` is True, one of `clip_box` or `clip_path` is set, ``clip_box.extents`` is equivalent to ``ax.bbox.extents`` (if set), and ``clip_path._patch`` is equivalent to ``ax.patch`` (if set). """ # Note that ``clip_path.get_fully_transformed_path().get_extents()`` # cannot be directly compared to ``axes.bbox.extents`` because the # extents may be undefined (i.e. equivalent to ``Bbox.null()``) # before the associated artist is drawn, and this method is meant # to determine whether ``axes.get_tightbbox()`` may bypass drawing clip_box = self.get_clip_box() clip_path = self.get_clip_path() return (self.axes is not None and self.get_clip_on() and (clip_box is not None or clip_path is not None) and (clip_box is None or np.all(clip_box.extents == self.axes.bbox.extents)) and (clip_path is None or isinstance(clip_path, TransformedPatchPath) and clip_path._patch is self.axes.patch))
def get_clip_on(self): """Return whether the artist uses clipping.""" return self._clipon
def get_clip_box(self): """Return the clipbox.""" return self.clipbox
def get_clip_path(self): """Return the clip path.""" return self._clippath
def get_transformed_clip_path_and_affine(self): """ Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation. """ if self._clippath is not None: return self._clippath.get_transformed_path_and_affine() return None, None
def set_clip_on(self, b): """ Set whether the artist uses clipping.
When False, artists will be visible outside the Axes which can lead to unexpected results.
Parameters ---------- b : bool """ self._clipon = b # This may result in the callbacks being hit twice, but ensures they # are hit at least once self.pchanged() self.stale = True
def _set_gc_clip(self, gc): """Set the clip properly for the gc.""" if self._clipon: if self.clipbox is not None: gc.set_clip_rectangle(self.clipbox) gc.set_clip_path(self._clippath) else: gc.set_clip_rectangle(None) gc.set_clip_path(None)
def get_rasterized(self): """Return whether the artist is to be rasterized.""" return self._rasterized
def set_rasterized(self, rasterized): """ Force rasterized (bitmap) drawing for vector graphics output.
Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued.
This setting is ignored for pixel-based output.
See also :doc:`/gallery/misc/rasterization_demo`.
Parameters ---------- rasterized : bool """ supports_rasterization = getattr(self.draw, "_supports_rasterization", False) if rasterized and not supports_rasterization: _api.warn_external(f"Rasterization of '{self}' will be ignored")
self._rasterized = rasterized
def get_agg_filter(self): """Return filter function to be used for agg filter.""" return self._agg_filter
def set_agg_filter(self, filter_func): """ Set the agg filter.
Parameters ---------- filter_func : callable A filter function, which takes a (m, n, depth) float array and a dpi value, and returns a (m, n, depth) array and two offsets from the bottom left corner of the image
.. ACCEPTS: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image """ self._agg_filter = filter_func self.stale = True
def draw(self, renderer): """ Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (`.Artist.get_visible` returns False).
Parameters ---------- renderer : `~matplotlib.backend_bases.RendererBase` subclass.
Notes ----- This method is overridden in the Artist subclasses. """ if not self.get_visible(): return self.stale = False
def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on all backends.
Parameters ---------- alpha : float or None *alpha* must be within the 0-1 range, inclusive. """ if alpha is not None and not isinstance(alpha, Real): raise TypeError( f'alpha must be numeric or None, not {type(alpha)}') if alpha is not None and not (0 <= alpha <= 1): raise ValueError(f'alpha ({alpha}) is outside 0-1 range') if alpha != self._alpha: self._alpha = alpha self.pchanged() self.stale = True
def _set_alpha_for_array(self, alpha): """ Set the alpha value used for blending - not supported on all backends.
Parameters ---------- alpha : array-like or float or None All values must be within the 0-1 range, inclusive. Masked values and nans are not supported. """ if isinstance(alpha, str): raise TypeError("alpha must be numeric or None, not a string") if not np.iterable(alpha): Artist.set_alpha(self, alpha) return alpha = np.asarray(alpha) if not (0 <= alpha.min() and alpha.max() <= 1): raise ValueError('alpha must be between 0 and 1, inclusive, ' f'but min is {alpha.min()}, max is {alpha.max()}') self._alpha = alpha self.pchanged() self.stale = True
def set_visible(self, b): """ Set the artist's visibility.
Parameters ---------- b : bool """ if b != self._visible: self._visible = b self.pchanged() self.stale = True
def set_animated(self, b): """ Set whether the artist is intended to be used in an animation.
If True, the artist is excluded from regular drawing of the figure. You have to call `.Figure.draw_artist` / `.Axes.draw_artist` explicitly on the artist. This approach is used to speed up animations using blitting.
See also `matplotlib.animation` and :ref:`blitting`.
Parameters ---------- b : bool """ if self._animated != b: self._animated = b self.pchanged()
def set_in_layout(self, in_layout): """ Set if artist is to be included in layout calculations, E.g. :ref:`constrainedlayout_guide`, `.Figure.tight_layout()`, and ``fig.savefig(fname, bbox_inches='tight')``.
Parameters ---------- in_layout : bool """ self._in_layout = in_layout
def get_label(self): """Return the label used for this artist in the legend.""" return self._label
def set_label(self, s): """ Set a label that will be displayed in the legend.
Parameters ---------- s : object *s* will be converted to a string by calling `str`. """ label = str(s) if s is not None else None if label != self._label: self._label = label self.pchanged() self.stale = True
def get_zorder(self): """Return the artist's zorder.""" return self.zorder
def set_zorder(self, level): """ Set the zorder for the artist. Artists with lower zorder values are drawn first.
Parameters ---------- level : float """ if level is None: level = self.__class__.zorder if level != self.zorder: self.zorder = level self.pchanged() self.stale = True
@property def sticky_edges(self): """ ``x`` and ``y`` sticky edge lists for autoscaling.
When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram.
Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1.
This attribute cannot be assigned to; however, the ``x`` and ``y`` lists can be modified in place as needed.
Examples -------- >>> artist.sticky_edges.x[:] = (xmin, xmax) >>> artist.sticky_edges.y[:] = (ymin, ymax)
""" return self._sticky_edges
def update_from(self, other): """Copy properties from *other* to *self*.""" self._transform = other._transform self._transformSet = other._transformSet self._visible = other._visible self._alpha = other._alpha self.clipbox = other.clipbox self._clipon = other._clipon self._clippath = other._clippath self._label = other._label self._sketch = other._sketch self._path_effects = other._path_effects self.sticky_edges.x[:] = other.sticky_edges.x.copy() self.sticky_edges.y[:] = other.sticky_edges.y.copy() self.pchanged() self.stale = True
def properties(self): """Return a dictionary of all the properties of the artist.""" return ArtistInspector(self).properties()
def _update_props(self, props, errfmt): """ Helper for `.Artist.set` and `.Artist.update`.
*errfmt* is used to generate error messages for invalid property names; it gets formatted with ``type(self)`` for "{cls}" and the property name for "{prop_name}". """ ret = [] with cbook._setattr_cm(self, eventson=False): for k, v in props.items(): # Allow attributes we want to be able to update through # art.update, art.set, setp. if k == "axes": ret.append(setattr(self, k, v)) else: func = getattr(self, f"set_{k}", None) if not callable(func): raise AttributeError( errfmt.format(cls=type(self), prop_name=k), name=k) ret.append(func(v)) if ret: self.pchanged() self.stale = True return ret
def update(self, props): """ Update this artist's properties from the dict *props*.
Parameters ---------- props : dict """ return self._update_props( props, "{cls.__name__!r} object has no property {prop_name!r}")
def _internal_update(self, kwargs): """ Update artist properties without prenormalizing them, but generating errors as if calling `set`.
The lack of prenormalization is to maintain backcompatibility. """ return self._update_props( kwargs, "{cls.__name__}.set() got an unexpected keyword argument " "{prop_name!r}")
def set(self, **kwargs): # docstring and signature are auto-generated via # Artist._update_set_signature_and_docstring() at the end of the # module. return self._internal_update(cbook.normalize_kwargs(kwargs, self))
@contextlib.contextmanager def _cm_set(self, **kwargs): """ `.Artist.set` context-manager that restores original values at exit. """ orig_vals = {k: getattr(self, f"get_{k}")() for k in kwargs} try: self.set(**kwargs) yield finally: self.set(**orig_vals)
def findobj(self, match=None, include_self=True): """ Find artist objects.
Recursively find all `.Artist` instances contained in the artist.
Parameters ---------- match A filter criterion for the matches. This can be
- *None*: Return all objects contained in artist. - A function with signature ``def match(artist: Artist) -> bool``. The result will only contain artists for which the function returns *True*. - A class instance: e.g., `.Line2D`. The result will only contain artists of this class or its subclasses (``isinstance`` check).
include_self : bool Include *self* in the list to be checked for a match.
Returns ------- list of `.Artist`
""" if match is None: # always return True def matchfunc(x): return True elif isinstance(match, type) and issubclass(match, Artist): def matchfunc(x): return isinstance(x, match) elif callable(match): matchfunc = match else: raise ValueError('match must be None, a matplotlib.artist.Artist ' 'subclass, or a callable')
artists = reduce(operator.iadd, [c.findobj(matchfunc) for c in self.get_children()], []) if include_self and matchfunc(self): artists.append(self) return artists
def get_cursor_data(self, event): """ Return the cursor data for a given event.
.. note:: This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns *None*.
Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that `.format_cursor_data` can convert the data to a string representation.
The only current use case is displaying the z-value of an `.AxesImage` in the status bar of a plot window, while moving the mouse.
Parameters ---------- event : `~matplotlib.backend_bases.MouseEvent`
See Also -------- format_cursor_data
""" return None
def format_cursor_data(self, data): """ Return a string representation of *data*.
.. note:: This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter.
See Also -------- get_cursor_data """ if np.ndim(data) == 0 and hasattr(self, "_format_cursor_data_override"): # workaround for ScalarMappable to be able to define its own # format_cursor_data(). See ScalarMappable._format_cursor_data_override # for details. return self._format_cursor_data_override(data) else: try: data[0] except (TypeError, IndexError): data = [data] data_str = ', '.join(f'{item:0.3g}' for item in data if isinstance(item, Number)) return "[" + data_str + "]"
def get_mouseover(self): """ Return whether this artist is queried for custom context information when the mouse cursor moves over it. """ return self._mouseover
def set_mouseover(self, mouseover): """ Set whether this artist is queried for custom context information when the mouse cursor moves over it.
Parameters ---------- mouseover : bool
See Also -------- get_cursor_data .ToolCursorPosition .NavigationToolbar2 """ self._mouseover = bool(mouseover) ax = self.axes if ax: if self._mouseover: ax._mouseover_set.add(self) else: ax._mouseover_set.discard(self)
mouseover = property(get_mouseover, set_mouseover) # backcompat.
def _get_tightbbox_for_layout_only(obj, *args, **kwargs): """ Matplotlib's `.Axes.get_tightbbox` and `.Axis.get_tightbbox` support a *for_layout_only* kwarg; this helper tries to use the kwarg but skips it when encountering third-party subclasses that do not support it. """ try: return obj.get_tightbbox(*args, **{**kwargs, "for_layout_only": True}) except TypeError: return obj.get_tightbbox(*args, **kwargs)
class ArtistInspector: """ A helper class to inspect an `~matplotlib.artist.Artist` and return information about its settable properties and their current values. """
def __init__(self, o): r""" Initialize the artist inspector with an `Artist` or an iterable of `Artist`\s. If an iterable is used, we assume it is a homogeneous sequence (all `Artist`\s are of the same type) and it is your responsibility to make sure this is so. """ if not isinstance(o, Artist): if np.iterable(o): o = list(o) if len(o): o = o[0]
self.oorig = o if not isinstance(o, type): o = type(o) self.o = o
self.aliasd = self.get_aliases()
def get_aliases(self): """ Get a dict mapping property fullnames to sets of aliases for each alias in the :class:`~matplotlib.artist.ArtistInspector`.
e.g., for lines::
{'markerfacecolor': {'mfc'}, 'linewidth' : {'lw'}, } """ names = [name for name in dir(self.o) if name.startswith(('set_', 'get_')) and callable(getattr(self.o, name))] aliases = {} for name in names: func = getattr(self.o, name) if not self.is_alias(func): continue propname = re.search(f"`({name[:4]}.*)`", # get_.*/set_.* inspect.getdoc(func)).group(1) aliases.setdefault(propname[4:], set()).add(name[4:]) return aliases
_get_valid_values_regex = re.compile( r"\n\s*(?:\.\.\s+)?ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))" )
def get_valid_values(self, attr): """ Get the legal arguments for the setter associated with *attr*.
This is done by querying the docstring of the setter for a line that begins with "ACCEPTS:" or ".. ACCEPTS:", and then by looking for a numpydoc-style documentation for the setter's first argument. """
name = 'set_%s' % attr if not hasattr(self.o, name): raise AttributeError(f'{self.o} has no function {name}') func = getattr(self.o, name)
if hasattr(func, '_kwarg_doc'): return func._kwarg_doc
docstring = inspect.getdoc(func) if docstring is None: return 'unknown'
if docstring.startswith('Alias for '): return None
match = self._get_valid_values_regex.search(docstring) if match is not None: return re.sub("\n *", " ", match.group(1))
# Much faster than list(inspect.signature(func).parameters)[1], # although barely relevant wrt. matplotlib's total import time. param_name = func.__code__.co_varnames[1] # We could set the presence * based on whether the parameter is a # varargs (it can't be a varkwargs) but it's not really worth it. match = re.search(fr"(?m)^ *\*?{param_name} : (.+)", docstring) if match: return match.group(1)
return 'unknown'
def _replace_path(self, source_class): """ Changes the full path to the public API path that is used in sphinx. This is needed for links to work. """ replace_dict = {'_base._AxesBase': 'Axes', '_axes.Axes': 'Axes'} for key, value in replace_dict.items(): source_class = source_class.replace(key, value) return source_class
def get_setters(self): """ Get the attribute strings with setters for object.
For example, for a line, return ``['markerfacecolor', 'linewidth', ....]``. """ setters = [] for name in dir(self.o): if not name.startswith('set_'): continue func = getattr(self.o, name) if (not callable(func) or self.number_of_parameters(func) < 2 or self.is_alias(func)): continue setters.append(name[4:]) return setters
@staticmethod @cache def number_of_parameters(func): """Return number of parameters of the callable *func*.""" return len(inspect.signature(func).parameters)
@staticmethod @cache def is_alias(method): """ Return whether the object *method* is an alias for another method. """
ds = inspect.getdoc(method) if ds is None: return False
return ds.startswith('Alias for ')
def aliased_name(self, s): """ Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME'.
For example, for the line markerfacecolor property, which has an alias, return 'markerfacecolor or mfc' and for the transform property, which does not, return 'transform'. """ aliases = ''.join(' or %s' % x for x in sorted(self.aliasd.get(s, []))) return s + aliases
_NOT_LINKABLE = { # A set of property setter methods that are not available in our # current docs. This is a workaround used to prevent trying to link # these setters which would lead to "target reference not found" # warnings during doc build. 'matplotlib.image._ImageBase.set_alpha', 'matplotlib.image._ImageBase.set_array', 'matplotlib.image._ImageBase.set_data', 'matplotlib.image._ImageBase.set_filternorm', 'matplotlib.image._ImageBase.set_filterrad', 'matplotlib.image._ImageBase.set_interpolation', 'matplotlib.image._ImageBase.set_interpolation_stage', 'matplotlib.image._ImageBase.set_resample', 'matplotlib.text._AnnotationBase.set_annotation_clip', }
def aliased_name_rest(self, s, target): """ Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME', formatted for reST.
For example, for the line markerfacecolor property, which has an alias, return 'markerfacecolor or mfc' and for the transform property, which does not, return 'transform'. """ # workaround to prevent "reference target not found" if target in self._NOT_LINKABLE: return f'``{s}``'
aliases = ''.join( f' or :meth:`{a} <{target}>`' for a in sorted(self.aliasd.get(s, []))) return f':meth:`{s} <{target}>`{aliases}'
def pprint_setters(self, prop=None, leadingspace=2): """ If *prop* is *None*, return a list of strings of all settable properties and their valid values.
If *prop* is not *None*, it is a valid property name and that property will be returned as a string of property : valid values. """ if leadingspace: pad = ' ' * leadingspace else: pad = '' if prop is not None: accepts = self.get_valid_values(prop) return f'{pad}{prop}: {accepts}'
lines = [] for prop in sorted(self.get_setters()): accepts = self.get_valid_values(prop) name = self.aliased_name(prop) lines.append(f'{pad}{name}: {accepts}') return lines
def pprint_setters_rest(self, prop=None, leadingspace=4): """ If *prop* is *None*, return a list of reST-formatted strings of all settable properties and their valid values.
If *prop* is not *None*, it is a valid property name and that property will be returned as a string of "property : valid" values. """ if leadingspace: pad = ' ' * leadingspace else: pad = '' if prop is not None: accepts = self.get_valid_values(prop) return f'{pad}{prop}: {accepts}'
prop_and_qualnames = [] for prop in sorted(self.get_setters()): # Find the parent method which actually provides the docstring. for cls in self.o.__mro__: method = getattr(cls, f"set_{prop}", None) if method and method.__doc__ is not None: break else: # No docstring available. method = getattr(self.o, f"set_{prop}") prop_and_qualnames.append( (prop, f"{method.__module__}.{method.__qualname__}"))
names = [self.aliased_name_rest(prop, target) .replace('_base._AxesBase', 'Axes') .replace('_axes.Axes', 'Axes') for prop, target in prop_and_qualnames] accepts = [self.get_valid_values(prop) for prop, _ in prop_and_qualnames]
col0_len = max(len(n) for n in names) col1_len = max(len(a) for a in accepts) table_formatstr = pad + ' ' + '=' * col0_len + ' ' + '=' * col1_len
return [ '', pad + '.. table::', pad + ' :class: property-table', '', table_formatstr, pad + ' ' + 'Property'.ljust(col0_len) + ' ' + 'Description'.ljust(col1_len), table_formatstr, *[pad + ' ' + n.ljust(col0_len) + ' ' + a.ljust(col1_len) for n, a in zip(names, accepts)], table_formatstr, '', ]
def properties(self): """Return a dictionary mapping property name -> value.""" o = self.oorig getters = [name for name in dir(o) if name.startswith('get_') and callable(getattr(o, name))] getters.sort() d = {} for name in getters: func = getattr(o, name) if self.is_alias(func): continue try: with warnings.catch_warnings(): warnings.simplefilter('ignore') val = func() except Exception: continue else: d[name[4:]] = val return d
def pprint_getters(self): """Return the getters and actual values as list of strings.""" lines = [] for name, val in sorted(self.properties().items()): if getattr(val, 'shape', ()) != () and len(val) > 6: s = str(val[:6]) + '...' else: s = str(val) s = s.replace('\n', ' ') if len(s) > 50: s = s[:50] + '...' name = self.aliased_name(name) lines.append(f' {name} = {s}') return lines
def getp(obj, property=None): """ Return the value of an `.Artist`'s *property*, or print all of them.
Parameters ---------- obj : `~matplotlib.artist.Artist` The queried artist; e.g., a `.Line2D`, a `.Text`, or an `~.axes.Axes`.
property : str or None, default: None If *property* is 'somename', this function returns ``obj.get_somename()``.
If it's None (or unset), it *prints* all gettable properties from *obj*. Many properties have aliases for shorter typing, e.g. 'lw' is an alias for 'linewidth'. In the output, aliases and full property names will be listed as:
property or alias = value
e.g.:
linewidth or lw = 2
See Also -------- setp """ if property is None: insp = ArtistInspector(obj) ret = insp.pprint_getters() print('\n'.join(ret)) return return getattr(obj, 'get_' + property)()
# aliasget = getp
def setp(obj, *args, file=None, **kwargs): """ Set one or more properties on an `.Artist`, or list allowed values.
Parameters ---------- obj : `~matplotlib.artist.Artist` or list of `.Artist` The artist(s) whose properties are being set or queried. When setting properties, all artists are affected; when querying the allowed values, only the first instance in the sequence is queried.
For example, two lines can be made thicker and red with a single call:
>>> x = arange(0, 1, 0.01) >>> lines = plot(x, sin(2*pi*x), x, sin(4*pi*x)) >>> setp(lines, linewidth=2, color='r')
file : file-like, default: `sys.stdout` Where `setp` writes its output when asked to list allowed values.
>>> with open('output.log') as file: ... setp(line, file=file)
The default, ``None``, means `sys.stdout`.
*args, **kwargs The properties to set. The following combinations are supported:
- Set the linestyle of a line to be dashed:
>>> line, = plot([1, 2, 3]) >>> setp(line, linestyle='--')
- Set multiple properties at once:
>>> setp(line, linewidth=2, color='r')
- List allowed values for a line's linestyle:
>>> setp(line, 'linestyle') linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
- List all properties that can be set, and their allowed values:
>>> setp(line) agg_filter: a filter function, ... [long output listing omitted]
`setp` also supports MATLAB style string/value pairs. For example, the following are equivalent:
>>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style >>> setp(lines, linewidth=2, color='r') # Python style
See Also -------- getp """
if isinstance(obj, Artist): objs = [obj] else: objs = list(cbook.flatten(obj))
if not objs: return
insp = ArtistInspector(objs[0])
if not kwargs and len(args) < 2: if args: print(insp.pprint_setters(prop=args[0]), file=file) else: print('\n'.join(insp.pprint_setters()), file=file) return
if len(args) % 2: raise ValueError('The set args must be string, value pairs')
funcvals = dict(zip(args[::2], args[1::2])) ret = [o.update(funcvals) for o in objs] + [o.set(**kwargs) for o in objs] return list(cbook.flatten(ret))
def kwdoc(artist): r""" Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and return information about its settable properties and their current values.
Parameters ---------- artist : `~matplotlib.artist.Artist` or an iterable of `Artist`\s
Returns ------- str The settable properties of *artist*, as plain text if :rc:`docstring.hardcopy` is False and as a rst table (intended for use in Sphinx) if it is True. """ ai = ArtistInspector(artist) return ('\n'.join(ai.pprint_setters_rest(leadingspace=4)) if mpl.rcParams['docstring.hardcopy'] else 'Properties:\n' + '\n'.join(ai.pprint_setters(leadingspace=4)))
# We defer this to the end of them module, because it needs ArtistInspector# to be defined.Artist._update_set_signature_and_docstring()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199from .axes._base import _AxesBasefrom .backend_bases import RendererBase, MouseEventfrom .figure import Figure, SubFigurefrom .path import Pathfrom .patches import Patchfrom .patheffects import AbstractPathEffectfrom .transforms import ( BboxBase, Bbox, Transform, TransformedPatchPath, TransformedPath,)
import numpy as np
from collections.abc import Callable, Iterablefrom typing import Any, Literal, NamedTuple, TextIO, overload, TypeVarfrom numpy.typing import ArrayLike
_T_Artist = TypeVar("_T_Artist", bound=Artist)
def allow_rasterization(draw): ...
class _XYPair(NamedTuple): x: ArrayLike y: ArrayLike
class _Unset: ...
class Artist: zorder: float stale_callback: Callable[[Artist, bool], None] | None @property def figure(self) -> Figure | SubFigure: ... clipbox: BboxBase | None def __init__(self) -> None: ... def remove(self) -> None: ... def have_units(self) -> bool: ... # TODO units def convert_xunits(self, x): ... def convert_yunits(self, y): ... @property def axes(self) -> _AxesBase | None: ... @axes.setter def axes(self, new_axes: _AxesBase | None) -> None: ... @property def stale(self) -> bool: ... @stale.setter def stale(self, val: bool) -> None: ... def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ... def get_tightbbox(self, renderer: RendererBase | None = ...) -> Bbox | None: ... def add_callback(self, func: Callable[[Artist], Any]) -> int: ... def remove_callback(self, oid: int) -> None: ... def pchanged(self) -> None: ... def is_transform_set(self) -> bool: ... def set_transform(self, t: Transform | None) -> None: ... def get_transform(self) -> Transform: ... def get_children(self) -> list[Artist]: ... # TODO can these dicts be type narrowed? e.g. str keys def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ... def pickable(self) -> bool: ... def pick(self, mouseevent: MouseEvent) -> None: ... def set_picker( self, picker: None | bool | float | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]], ) -> None: ... def get_picker( self, ) -> None | bool | float | Callable[ [Artist, MouseEvent], tuple[bool, dict[Any, Any]] ]: ... def get_url(self) -> str | None: ... def set_url(self, url: str | None) -> None: ... def get_gid(self) -> str | None: ... def set_gid(self, gid: str | None) -> None: ... def get_snap(self) -> bool | None: ... def set_snap(self, snap: bool | None) -> None: ... def get_sketch_params(self) -> tuple[float, float, float] | None: ... def set_sketch_params( self, scale: float | None = ..., length: float | None = ..., randomness: float | None = ..., ) -> None: ... def set_path_effects(self, path_effects: list[AbstractPathEffect]) -> None: ... def get_path_effects(self) -> list[AbstractPathEffect]: ... @overload def get_figure(self, root: Literal[True]) -> Figure | None: ... @overload def get_figure(self, root: Literal[False]) -> Figure | SubFigure | None: ... @overload def get_figure(self, root: bool = ...) -> Figure | SubFigure | None: ... def set_figure(self, fig: Figure | SubFigure) -> None: ... def set_clip_box(self, clipbox: BboxBase | None) -> None: ... def set_clip_path( self, path: Patch | Path | TransformedPath | TransformedPatchPath | None, transform: Transform | None = ..., ) -> None: ... def get_alpha(self) -> float | None: ... def get_visible(self) -> bool: ... def get_animated(self) -> bool: ... def get_in_layout(self) -> bool: ... def get_clip_on(self) -> bool: ... def get_clip_box(self) -> Bbox | None: ... def get_clip_path( self, ) -> Patch | Path | TransformedPath | TransformedPatchPath | None: ... def get_transformed_clip_path_and_affine( self, ) -> tuple[None, None] | tuple[Path, Transform]: ... def set_clip_on(self, b: bool) -> None: ... def get_rasterized(self) -> bool: ... def set_rasterized(self, rasterized: bool) -> None: ... def get_agg_filter(self) -> Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None: ... def set_agg_filter( self, filter_func: Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None ) -> None: ... def draw(self, renderer: RendererBase) -> None: ... def set_alpha(self, alpha: float | None) -> None: ... def set_visible(self, b: bool) -> None: ... def set_animated(self, b: bool) -> None: ... def set_in_layout(self, in_layout: bool) -> None: ... def get_label(self) -> object: ... def set_label(self, s: object) -> None: ... def get_zorder(self) -> float: ... def set_zorder(self, level: float) -> None: ... @property def sticky_edges(self) -> _XYPair: ... def update_from(self, other: Artist) -> None: ... def properties(self) -> dict[str, Any]: ... def update(self, props: dict[str, Any]) -> list[Any]: ... def _internal_update(self, kwargs: Any) -> list[Any]: ... def set(self, **kwargs: Any) -> list[Any]: ...
@overload def findobj( self, match: None | Callable[[Artist], bool] = ..., include_self: bool = ..., ) -> list[Artist]: ...
@overload def findobj( self, match: type[_T_Artist], include_self: bool = ..., ) -> list[_T_Artist]: ...
def get_cursor_data(self, event: MouseEvent) -> Any: ... def format_cursor_data(self, data: Any) -> str: ... def get_mouseover(self) -> bool: ... def set_mouseover(self, mouseover: bool) -> None: ... @property def mouseover(self) -> bool: ... @mouseover.setter def mouseover(self, mouseover: bool) -> None: ...
class ArtistInspector: oorig: Artist | type[Artist] o: type[Artist] aliasd: dict[str, set[str]] def __init__( self, o: Artist | type[Artist] | Iterable[Artist | type[Artist]] ) -> None: ... def get_aliases(self) -> dict[str, set[str]]: ... def get_valid_values(self, attr: str) -> str | None: ... def get_setters(self) -> list[str]: ... @staticmethod def number_of_parameters(func: Callable) -> int: ... @staticmethod def is_alias(method: Callable) -> bool: ... def aliased_name(self, s: str) -> str: ... def aliased_name_rest(self, s: str, target: str) -> str: ... @overload def pprint_setters( self, prop: None = ..., leadingspace: int = ... ) -> list[str]: ... @overload def pprint_setters(self, prop: str, leadingspace: int = ...) -> str: ... @overload def pprint_setters_rest( self, prop: None = ..., leadingspace: int = ... ) -> list[str]: ... @overload def pprint_setters_rest(self, prop: str, leadingspace: int = ...) -> str: ... def properties(self) -> dict[str, Any]: ... def pprint_getters(self) -> list[str]: ...
def getp(obj: Artist, property: str | None = ...) -> Any: ...
get = getp
def setp(obj: Artist, *args, file: TextIO | None = ..., **kwargs) -> list[Any] | None: ...def kwdoc(artist: Artist | type[Artist] | Iterable[Artist | type[Artist]]) -> str: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482from enum import Enum, IntEnumimport osfrom matplotlib import ( cbook, transforms, widgets, _api,)from matplotlib.artist import Artistfrom matplotlib.axes import Axesfrom matplotlib.backend_managers import ToolManagerfrom matplotlib.backend_tools import Cursors, ToolBasefrom matplotlib.colorbar import Colorbarfrom matplotlib.figure import Figurefrom matplotlib.font_manager import FontPropertiesfrom matplotlib.path import Pathfrom matplotlib.texmanager import TexManagerfrom matplotlib.text import Textfrom matplotlib.transforms import Bbox, BboxBase, Transform, TransformedPath
from collections.abc import Callable, Iterable, Sequencefrom typing import Any, IO, Literal, NamedTuple, TypeVarfrom numpy.typing import ArrayLikefrom .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
def register_backend( format: str, backend: str | type[FigureCanvasBase], description: str | None = ...) -> None: ...def get_registered_canvas_class(format: str) -> type[FigureCanvasBase]: ...
class RendererBase: def __init__(self) -> None: ... def open_group(self, s: str, gid: str | None = ...) -> None: ... def close_group(self, s: str) -> None: ... def draw_path( self, gc: GraphicsContextBase, path: Path, transform: Transform, rgbFace: ColorType | None = ..., ) -> None: ... def draw_markers( self, gc: GraphicsContextBase, marker_path: Path, marker_trans: Transform, path: Path, trans: Transform, rgbFace: ColorType | None = ..., ) -> None: ... def draw_path_collection( self, gc: GraphicsContextBase, master_transform: Transform, paths: Sequence[Path], all_transforms: Sequence[ArrayLike], offsets: ArrayLike | Sequence[ArrayLike], offset_trans: Transform, facecolors: ColorType | Sequence[ColorType], edgecolors: ColorType | Sequence[ColorType], linewidths: float | Sequence[float], linestyles: LineStyleType | Sequence[LineStyleType], antialiaseds: bool | Sequence[bool], urls: str | Sequence[str], offset_position: Any, ) -> None: ... def draw_quad_mesh( self, gc: GraphicsContextBase, master_transform: Transform, meshWidth, meshHeight, coordinates: ArrayLike, offsets: ArrayLike | Sequence[ArrayLike], offsetTrans: Transform, facecolors: Sequence[ColorType], antialiased: bool, edgecolors: Sequence[ColorType] | ColorType | None, ) -> None: ... def draw_gouraud_triangles( self, gc: GraphicsContextBase, triangles_array: ArrayLike, colors_array: ArrayLike, transform: Transform, ) -> None: ... def get_image_magnification(self) -> float: ... def draw_image( self, gc: GraphicsContextBase, x: float, y: float, im: ArrayLike, transform: transforms.Affine2DBase | None = ..., ) -> None: ... def option_image_nocomposite(self) -> bool: ... def option_scale_image(self) -> bool: ... def draw_tex( self, gc: GraphicsContextBase, x: float, y: float, s: str, prop: FontProperties, angle: float, *, mtext: Text | None = ... ) -> None: ... def draw_text( self, gc: GraphicsContextBase, x: float, y: float, s: str, prop: FontProperties, angle: float, ismath: bool | Literal["TeX"] = ..., mtext: Text | None = ..., ) -> None: ... def get_text_width_height_descent( self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"] ) -> tuple[float, float, float]: ... def flipy(self) -> bool: ... def get_canvas_width_height(self) -> tuple[float, float]: ... def get_texmanager(self) -> TexManager: ... def new_gc(self) -> GraphicsContextBase: ... def points_to_pixels(self, points: ArrayLike) -> ArrayLike: ... def start_rasterizing(self) -> None: ... def stop_rasterizing(self) -> None: ... def start_filter(self) -> None: ... def stop_filter(self, filter_func) -> None: ...
class GraphicsContextBase: def __init__(self) -> None: ... def copy_properties(self, gc: GraphicsContextBase) -> None: ... def restore(self) -> None: ... def get_alpha(self) -> float: ... def get_antialiased(self) -> int: ... def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ... def get_clip_rectangle(self) -> Bbox | None: ... def get_clip_path( self, ) -> tuple[TransformedPath, Transform] | tuple[None, None]: ... def get_dashes(self) -> tuple[float, ArrayLike | None]: ... def get_forced_alpha(self) -> bool: ... def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ... def get_linewidth(self) -> float: ... def get_rgb(self) -> tuple[float, float, float, float]: ... def get_url(self) -> str | None: ... def get_gid(self) -> int | None: ... def get_snap(self) -> bool | None: ... def set_alpha(self, alpha: float) -> None: ... def set_antialiased(self, b: bool) -> None: ... def set_capstyle(self, cs: CapStyleType) -> None: ... def set_clip_rectangle(self, rectangle: Bbox | None) -> None: ... def set_clip_path(self, path: TransformedPath | None) -> None: ... def set_dashes(self, dash_offset: float, dash_list: ArrayLike | None) -> None: ... def set_foreground(self, fg: ColorType, isRGBA: bool = ...) -> None: ... def set_joinstyle(self, js: JoinStyleType) -> None: ... def set_linewidth(self, w: float) -> None: ... def set_url(self, url: str | None) -> None: ... def set_gid(self, id: int | None) -> None: ... def set_snap(self, snap: bool | None) -> None: ... def set_hatch(self, hatch: str | None) -> None: ... def get_hatch(self) -> str | None: ... def get_hatch_path(self, density: float = ...) -> Path: ... def get_hatch_color(self) -> ColorType: ... def set_hatch_color(self, hatch_color: ColorType) -> None: ... def get_hatch_linewidth(self) -> float: ... def set_hatch_linewidth(self, hatch_linewidth: float) -> None: ... def get_sketch_params(self) -> tuple[float, float, float] | None: ... def set_sketch_params( self, scale: float | None = ..., length: float | None = ..., randomness: float | None = ..., ) -> None: ...
class TimerBase: callbacks: list[tuple[Callable, tuple, dict[str, Any]]] def __init__( self, interval: int | None = ..., callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ..., ) -> None: ... def __del__(self) -> None: ... def start(self, interval: int | None = ...) -> None: ... def stop(self) -> None: ... @property def interval(self) -> int: ... @interval.setter def interval(self, interval: int) -> None: ... @property def single_shot(self) -> bool: ... @single_shot.setter def single_shot(self, ss: bool) -> None: ... def add_callback(self, func: Callable, *args, **kwargs) -> Callable: ... def remove_callback(self, func: Callable, *args, **kwargs) -> None: ...
class Event: name: str canvas: FigureCanvasBase guiEvent: Any def __init__( self, name: str, canvas: FigureCanvasBase, guiEvent: Any | None = ... ) -> None: ...
class DrawEvent(Event): renderer: RendererBase def __init__( self, name: str, canvas: FigureCanvasBase, renderer: RendererBase ) -> None: ...
class ResizeEvent(Event): width: int height: int def __init__(self, name: str, canvas: FigureCanvasBase) -> None: ...
class CloseEvent(Event): ...
class LocationEvent(Event): x: int y: int inaxes: Axes | None xdata: float | None ydata: float | None def __init__( self, name: str, canvas: FigureCanvasBase, x: int, y: int, guiEvent: Any | None = ..., *, modifiers: Iterable[str] | None = ..., ) -> None: ...
class MouseButton(IntEnum): LEFT = 1 MIDDLE = 2 RIGHT = 3 BACK = 8 FORWARD = 9
class MouseEvent(LocationEvent): button: MouseButton | Literal["up", "down"] | None key: str | None step: float dblclick: bool def __init__( self, name: str, canvas: FigureCanvasBase, x: int, y: int, button: MouseButton | Literal["up", "down"] | None = ..., key: str | None = ..., step: float = ..., dblclick: bool = ..., guiEvent: Any | None = ..., *, buttons: Iterable[MouseButton] | None = ..., modifiers: Iterable[str] | None = ..., ) -> None: ...
class PickEvent(Event): mouseevent: MouseEvent artist: Artist def __init__( self, name: str, canvas: FigureCanvasBase, mouseevent: MouseEvent, artist: Artist, guiEvent: Any | None = ..., **kwargs ) -> None: ...
class KeyEvent(LocationEvent): key: str | None def __init__( self, name: str, canvas: FigureCanvasBase, key: str | None, x: int = ..., y: int = ..., guiEvent: Any | None = ..., ) -> None: ...
class FigureCanvasBase: required_interactive_framework: str | None
@_api.classproperty def manager_class(cls) -> type[FigureManagerBase]: ... events: list[str] fixed_dpi: None | float filetypes: dict[str, str]
@_api.classproperty def supports_blit(cls) -> bool: ...
figure: Figure manager: None | FigureManagerBase widgetlock: widgets.LockDraw mouse_grabber: None | Axes toolbar: None | NavigationToolbar2 def __init__(self, figure: Figure | None = ...) -> None: ... @property def callbacks(self) -> cbook.CallbackRegistry: ... @property def button_pick_id(self) -> int: ... @property def scroll_pick_id(self) -> int: ... @classmethod def new_manager(cls, figure: Figure, num: int | str) -> FigureManagerBase: ... def is_saving(self) -> bool: ... def blit(self, bbox: BboxBase | None = ...) -> None: ... def inaxes(self, xy: tuple[float, float]) -> Axes | None: ... def grab_mouse(self, ax: Axes) -> None: ... def release_mouse(self, ax: Axes) -> None: ... def set_cursor(self, cursor: Cursors) -> None: ... def draw(self, *args, **kwargs) -> None: ... def draw_idle(self, *args, **kwargs) -> None: ... @property def device_pixel_ratio(self) -> float: ... def get_width_height(self, *, physical: bool = ...) -> tuple[int, int]: ... @classmethod def get_supported_filetypes(cls) -> dict[str, str]: ... @classmethod def get_supported_filetypes_grouped(cls) -> dict[str, list[str]]: ... def print_figure( self, filename: str | os.PathLike | IO, dpi: float | None = ..., facecolor: ColorType | Literal["auto"] | None = ..., edgecolor: ColorType | Literal["auto"] | None = ..., orientation: str = ..., format: str | None = ..., *, bbox_inches: Literal["tight"] | Bbox | None = ..., pad_inches: float | None = ..., bbox_extra_artists: list[Artist] | None = ..., backend: str | None = ..., **kwargs ) -> Any: ... @classmethod def get_default_filetype(cls) -> str: ... def get_default_filename(self) -> str: ... _T = TypeVar("_T", bound=FigureCanvasBase) def mpl_connect(self, s: str, func: Callable[[Event], Any]) -> int: ... def mpl_disconnect(self, cid: int) -> None: ... def new_timer( self, interval: int | None = ..., callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ..., ) -> TimerBase: ... def flush_events(self) -> None: ... def start_event_loop(self, timeout: float = ...) -> None: ... def stop_event_loop(self) -> None: ...
def key_press_handler( event: KeyEvent, canvas: FigureCanvasBase | None = ..., toolbar: NavigationToolbar2 | None = ...,) -> None: ...def button_press_handler( event: MouseEvent, canvas: FigureCanvasBase | None = ..., toolbar: NavigationToolbar2 | None = ...,) -> None: ...
class NonGuiException(Exception): ...
class FigureManagerBase: canvas: FigureCanvasBase num: int | str key_press_handler_id: int | None button_press_handler_id: int | None toolmanager: ToolManager | None toolbar: NavigationToolbar2 | ToolContainerBase | None def __init__(self, canvas: FigureCanvasBase, num: int | str) -> None: ... @classmethod def create_with_canvas( cls, canvas_class: type[FigureCanvasBase], figure: Figure, num: int | str ) -> FigureManagerBase: ... @classmethod def start_main_loop(cls) -> None: ... @classmethod def pyplot_show(cls, *, block: bool | None = ...) -> None: ... def show(self) -> None: ... def destroy(self) -> None: ... def full_screen_toggle(self) -> None: ... def resize(self, w: int, h: int) -> None: ... def get_window_title(self) -> str: ... def set_window_title(self, title: str) -> None: ...
cursors = Cursors
class _Mode(str, Enum): NONE = "" PAN = "pan/zoom" ZOOM = "zoom rect"
class NavigationToolbar2: toolitems: tuple[tuple[str, ...] | tuple[None, ...], ...] UNKNOWN_SAVED_STATUS: object canvas: FigureCanvasBase mode: _Mode def __init__(self, canvas: FigureCanvasBase) -> None: ... def set_message(self, s: str) -> None: ... def draw_rubberband( self, event: Event, x0: float, y0: float, x1: float, y1: float ) -> None: ... def remove_rubberband(self) -> None: ... def home(self, *args) -> None: ... def back(self, *args) -> None: ... def forward(self, *args) -> None: ... def mouse_move(self, event: MouseEvent) -> None: ... def pan(self, *args) -> None: ...
class _PanInfo(NamedTuple): button: MouseButton axes: list[Axes] cid: int def press_pan(self, event: Event) -> None: ... def drag_pan(self, event: Event) -> None: ... def release_pan(self, event: Event) -> None: ... def zoom(self, *args) -> None: ...
class _ZoomInfo(NamedTuple): direction: Literal["in", "out"] start_xy: tuple[float, float] axes: list[Axes] cid: int cbar: Colorbar def press_zoom(self, event: Event) -> None: ... def drag_zoom(self, event: Event) -> None: ... def release_zoom(self, event: Event) -> None: ... def push_current(self) -> None: ... subplot_tool: widgets.SubplotTool def configure_subplots(self, *args): ... def save_figure(self, *args) -> str | None | object: ... def update(self) -> None: ... def set_history_buttons(self) -> None: ...
class ToolContainerBase: toolmanager: ToolManager def __init__(self, toolmanager: ToolManager) -> None: ... def add_tool(self, tool: ToolBase, group: str, position: int = ...) -> None: ... def trigger_tool(self, name: str) -> None: ... def add_toolitem( self, name: str, group: str, position: int, image: str, description: str, toggle: bool, ) -> None: ... def toggle_toolitem(self, name: str, toggled: bool) -> None: ... def remove_toolitem(self, name: str) -> None: ... def set_message(self, s: str) -> None: ...
class _Backend: backend_version: str FigureCanvas: type[FigureCanvasBase] | None FigureManager: type[FigureManagerBase] mainloop: None | Callable[[], Any] @classmethod def new_figure_manager(cls, num: int | str, *args, **kwargs) -> FigureManagerBase: ... @classmethod def new_figure_manager_given_figure(cls, num: int | str, figure: Figure) -> FigureManagerBase: ... @classmethod def draw_if_interactive(cls) -> None: ... @classmethod def show(cls, *, block: bool | None = ...) -> None: ... @staticmethod def export(cls) -> type[_Backend]: ...
class ShowBase(_Backend): def __call__(self, block: bool | None = ...) -> None: ...123456789101112131415161718192021222324from collections.abc import Iterator, Mappingfrom matplotlib import colorsfrom matplotlib.colorizer import _ScalarMappable
class ColormapRegistry(Mapping[str, colors.Colormap]): def __init__(self, cmaps: Mapping[str, colors.Colormap]) -> None: ... def __getitem__(self, item: str) -> colors.Colormap: ... def __iter__(self) -> Iterator[str]: ... def __len__(self) -> int: ... def __call__(self) -> list[str]: ... def register( self, cmap: colors.Colormap, *, name: str | None = ..., force: bool = ... ) -> None: ... def unregister(self, name: str) -> None: ... def get_cmap(self, cmap: str | colors.Colormap) -> colors.Colormap: ...
_colormaps: ColormapRegistry = ..._multivar_colormaps: ColormapRegistry = ..._bivar_colormaps: ColormapRegistry = ...
def get_cmap(name: str | colors.Colormap | None = ..., lut: int | None = ...) -> colors.Colormap: ...
ScalarMappable = _ScalarMappable123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262from collections.abc import Callable, Iterable, Sequencefrom typing import Literal
import numpy as npfrom numpy.typing import ArrayLike, NDArray
from . import colorizer, transformsfrom .backend_bases import MouseEventfrom .artist import Artistfrom .colors import Normalize, Colormapfrom .lines import Line2Dfrom .path import Pathfrom .patches import Patchfrom .ticker import Locator, Formatterfrom .tri import Triangulationfrom .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
class Collection(colorizer.ColorizingArtist): def __init__( self, *, edgecolors: ColorType | Sequence[ColorType] | None = ..., facecolors: ColorType | Sequence[ColorType] | None = ..., linewidths: float | Sequence[float] | None = ..., linestyles: LineStyleType | Sequence[LineStyleType] = ..., capstyle: CapStyleType | None = ..., joinstyle: JoinStyleType | None = ..., antialiaseds: bool | Sequence[bool] | None = ..., offsets: tuple[float, float] | Sequence[tuple[float, float]] | None = ..., offset_transform: transforms.Transform | None = ..., norm: Normalize | None = ..., cmap: Colormap | None = ..., colorizer: colorizer.Colorizer | None = ..., pickradius: float = ..., hatch: str | None = ..., urls: Sequence[str] | None = ..., zorder: float = ..., **kwargs ) -> None: ... def get_paths(self) -> Sequence[Path]: ... def set_paths(self, paths: Sequence[Path]) -> None: ... def get_transforms(self) -> Sequence[transforms.Transform]: ... def get_offset_transform(self) -> transforms.Transform: ... def set_offset_transform(self, offset_transform: transforms.Transform) -> None: ... def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ... def set_pickradius(self, pickradius: float) -> None: ... def get_pickradius(self) -> float: ... def set_urls(self, urls: Sequence[str | None]) -> None: ... def get_urls(self) -> Sequence[str | None]: ... def set_hatch(self, hatch: str) -> None: ... def get_hatch(self) -> str: ... def set_hatch_linewidth(self, lw: float) -> None: ... def get_hatch_linewidth(self) -> float: ... def set_offsets(self, offsets: ArrayLike) -> None: ... def get_offsets(self) -> ArrayLike: ... def set_linewidth(self, lw: float | Sequence[float]) -> None: ... def set_linestyle(self, ls: LineStyleType | Sequence[LineStyleType]) -> None: ... def set_capstyle(self, cs: CapStyleType) -> None: ... def get_capstyle(self) -> Literal["butt", "projecting", "round"] | None: ... def set_joinstyle(self, js: JoinStyleType) -> None: ... def get_joinstyle(self) -> Literal["miter", "round", "bevel"] | None: ... def set_antialiased(self, aa: bool | Sequence[bool]) -> None: ... def get_antialiased(self) -> NDArray[np.bool_]: ... def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ... def set_facecolor(self, c: ColorType | Sequence[ColorType]) -> None: ... def get_facecolor(self) -> ColorType | Sequence[ColorType]: ... def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ... def set_edgecolor(self, c: ColorType | Sequence[ColorType]) -> None: ... def set_alpha(self, alpha: float | Sequence[float] | None) -> None: ... def get_linewidth(self) -> float | Sequence[float]: ... def get_linestyle(self) -> LineStyleType | Sequence[LineStyleType]: ... def update_scalarmappable(self) -> None: ... def get_fill(self) -> bool: ... def update_from(self, other: Artist) -> None: ...
class _CollectionWithSizes(Collection): def get_sizes(self) -> np.ndarray: ... def set_sizes(self, sizes: ArrayLike | None, dpi: float = ...) -> None: ...
class PathCollection(_CollectionWithSizes): def __init__( self, paths: Sequence[Path], sizes: ArrayLike | None = ..., **kwargs ) -> None: ... def set_paths(self, paths: Sequence[Path]) -> None: ... def get_paths(self) -> Sequence[Path]: ... def legend_elements( self, prop: Literal["colors", "sizes"] = ..., num: int | Literal["auto"] | ArrayLike | Locator = ..., fmt: str | Formatter | None = ..., func: Callable[[ArrayLike], ArrayLike] = ..., **kwargs, ) -> tuple[list[Line2D], list[str]]: ...
class PolyCollection(_CollectionWithSizes): def __init__( self, verts: Sequence[ArrayLike], sizes: ArrayLike | None = ..., *, closed: bool = ..., **kwargs ) -> None: ... def set_verts( self, verts: Sequence[ArrayLike | Path], closed: bool = ... ) -> None: ... def set_paths(self, verts: Sequence[Path], closed: bool = ...) -> None: ... def set_verts_and_codes( self, verts: Sequence[ArrayLike | Path], codes: Sequence[int] ) -> None: ...
class FillBetweenPolyCollection(PolyCollection): def __init__( self, t_direction: Literal["x", "y"], t: ArrayLike, f1: ArrayLike, f2: ArrayLike, *, where: Sequence[bool] | None = ..., interpolate: bool = ..., step: Literal["pre", "post", "mid"] | None = ..., **kwargs, ) -> None: ... def set_data( self, t: ArrayLike, f1: ArrayLike, f2: ArrayLike, *, where: Sequence[bool] | None = ..., ) -> None: ... def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ...
class RegularPolyCollection(_CollectionWithSizes): def __init__( self, numsides: int, *, rotation: float = ..., sizes: ArrayLike = ..., **kwargs ) -> None: ... def get_numsides(self) -> int: ... def get_rotation(self) -> float: ...
class StarPolygonCollection(RegularPolyCollection): ...class AsteriskPolygonCollection(RegularPolyCollection): ...
class LineCollection(Collection): def __init__( self, segments: Sequence[ArrayLike], *, zorder: float = ..., **kwargs ) -> None: ... def set_segments(self, segments: Sequence[ArrayLike] | None) -> None: ... def set_verts(self, segments: Sequence[ArrayLike] | None) -> None: ... def set_paths(self, segments: Sequence[ArrayLike] | None) -> None: ... # type: ignore[override] def get_segments(self) -> list[np.ndarray]: ... def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ... def set_colors(self, c: ColorType | Sequence[ColorType]) -> None: ... def set_gapcolor(self, gapcolor: ColorType | Sequence[ColorType] | None) -> None: ... def get_color(self) -> ColorType | Sequence[ColorType]: ... def get_colors(self) -> ColorType | Sequence[ColorType]: ... def get_gapcolor(self) -> ColorType | Sequence[ColorType] | None: ...
class EventCollection(LineCollection): def __init__( self, positions: ArrayLike, orientation: Literal["horizontal", "vertical"] = ..., *, lineoffset: float = ..., linelength: float = ..., linewidth: float | Sequence[float] | None = ..., color: ColorType | Sequence[ColorType] | None = ..., linestyle: LineStyleType | Sequence[LineStyleType] = ..., antialiased: bool | Sequence[bool] | None = ..., **kwargs ) -> None: ... def get_positions(self) -> list[float]: ... def set_positions(self, positions: Sequence[float] | None) -> None: ... def add_positions(self, position: Sequence[float] | None) -> None: ... def extend_positions(self, position: Sequence[float] | None) -> None: ... def append_positions(self, position: Sequence[float] | None) -> None: ... def is_horizontal(self) -> bool: ... def get_orientation(self) -> Literal["horizontal", "vertical"]: ... def switch_orientation(self) -> None: ... def set_orientation( self, orientation: Literal["horizontal", "vertical"] ) -> None: ... def get_linelength(self) -> float | Sequence[float]: ... def set_linelength(self, linelength: float | Sequence[float]) -> None: ... def get_lineoffset(self) -> float: ... def set_lineoffset(self, lineoffset: float) -> None: ... def get_linewidth(self) -> float: ... def get_linewidths(self) -> Sequence[float]: ... def get_color(self) -> ColorType: ...
class CircleCollection(_CollectionWithSizes): def __init__(self, sizes: float | ArrayLike, **kwargs) -> None: ...
class EllipseCollection(Collection): def __init__( self, widths: ArrayLike, heights: ArrayLike, angles: ArrayLike, *, units: Literal[ "points", "inches", "dots", "width", "height", "x", "y", "xy" ] = ..., **kwargs ) -> None: ... def set_widths(self, widths: ArrayLike) -> None: ... def set_heights(self, heights: ArrayLike) -> None: ... def set_angles(self, angles: ArrayLike) -> None: ... def get_widths(self) -> ArrayLike: ... def get_heights(self) -> ArrayLike: ... def get_angles(self) -> ArrayLike: ...
class PatchCollection(Collection): def __init__( self, patches: Iterable[Patch], *, match_original: bool = ..., **kwargs ) -> None: ... def set_paths(self, patches: Iterable[Patch]) -> None: ... # type: ignore[override]
class TriMesh(Collection): def __init__(self, triangulation: Triangulation, **kwargs) -> None: ... def get_paths(self) -> list[Path]: ... # Parent class has an argument, perhaps add a noop arg? def set_paths(self) -> None: ... # type: ignore[override] @staticmethod def convert_mesh_to_paths(tri: Triangulation) -> list[Path]: ...
class _MeshData: def __init__( self, coordinates: ArrayLike, *, shading: Literal["flat", "gouraud"] = ..., ) -> None: ... def set_array(self, A: ArrayLike | None) -> None: ... def get_coordinates(self) -> ArrayLike: ... def get_facecolor(self) -> ColorType | Sequence[ColorType]: ... def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ...
class QuadMesh(_MeshData, Collection): def __init__( self, coordinates: ArrayLike, *, antialiased: bool = ..., shading: Literal["flat", "gouraud"] = ..., **kwargs ) -> None: ... def get_paths(self) -> list[Path]: ... # Parent class has an argument, perhaps add a noop arg? def set_paths(self) -> None: ... # type: ignore[override] def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ... def get_cursor_data(self, event: MouseEvent) -> float: ...
class PolyQuadMesh(_MeshData, PolyCollection): def __init__( self, coordinates: ArrayLike, **kwargs ) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563"""Colorbars are a visualization of the mapping from scalar values to colors.In Matplotlib they are drawn into a dedicated `~.axes.Axes`.
.. note:: Colorbars are typically created through `.Figure.colorbar` or its pyplot wrapper `.pyplot.colorbar`, which internally use `.Colorbar` together with `.make_axes_gridspec` (for `.GridSpec`-positioned Axes) or `.make_axes` (for non-`.GridSpec`-positioned Axes).
End-users most likely won't need to directly use this module's API."""
import logging
import numpy as np
import matplotlib as mplfrom matplotlib import _api, cbook, collections, cm, colors, contour, tickerimport matplotlib.artist as martistimport matplotlib.patches as mpatchesimport matplotlib.path as mpathimport matplotlib.spines as mspinesimport matplotlib.transforms as mtransformsfrom matplotlib import _docstring
_log = logging.getLogger(__name__)
_docstring.interpd.register( _make_axes_kw_doc="""location : None or {'left', 'right', 'top', 'bottom'} The location, relative to the parent Axes, where the colorbar Axes is created. It also determines the *orientation* of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the *orientation* if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if *orientation* is unset.
orientation : None or {'vertical', 'horizontal'} The orientation of the colorbar. It is preferable to set the *location* of the colorbar, as that also determines the *orientation*; passing incompatible values for *location* and *orientation* raises an exception.
fraction : float, default: 0.15 Fraction of original Axes to use for colorbar.
shrink : float, default: 1.0 Fraction by which to multiply the size of the colorbar.
aspect : float, default: 20 Ratio of long to short dimensions.
pad : float, default: 0.05 if vertical, 0.15 if horizontal Fraction of original Axes between colorbar and new image Axes.
anchor : (float, float), optional The anchor point of the colorbar Axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.
panchor : (float, float), or *False*, optional The anchor point of the colorbar parent Axes. If *False*, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.""", _colormap_kw_doc="""extend : {'neither', 'both', 'min', 'max'} Make pointed end(s) for out-of-range values (unless 'neither'). These are set for a given colormap using the colormap set_under and set_over methods.
extendfrac : {*None*, 'auto', length, lengths} If set to *None*, both the minimum and maximum triangular colorbar extensions will have a length of 5% of the interior colorbar length (this is the default setting).
If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when *spacing* is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when *spacing* is set to 'proportional').
If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
extendrect : bool If *False* the minimum and maximum colorbar extensions will be triangular (the default). If *True* the extensions will be rectangular.
ticks : None or list of ticks or Locator If None, ticks are determined automatically from the input.
format : None or str or Formatter If None, `~.ticker.ScalarFormatter` is used. Format strings, e.g., ``"%4.2e"`` or ``"{x:.2e}"``, are supported. An alternative `~.ticker.Formatter` may be given instead.
drawedges : bool Whether to draw lines at color boundaries.
label : str The label on the colorbar's long axis.
boundaries, values : None or a sequence If unset, the colormap will be displayed on a 0-1 scale. If sequences, *values* must have a length 1 less than *boundaries*. For each region delimited by adjacent entries in *boundaries*, the color mapped to the corresponding value in *values* will be used. The size of each region is determined by the *spacing* parameter. Normally only useful for indexed colors (i.e. ``norm=NoNorm()``) or other unusual circumstances.
spacing : {'uniform', 'proportional'} For discrete colorbars (`.BoundaryNorm` or contours), 'uniform' gives each color the same space; 'proportional' makes the space proportional to the data interval.""")
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.")
class _ColorbarSpine(mspines.Spine): def __init__(self, axes): self._ax = axes super().__init__(axes, 'colorbar', mpath.Path(np.empty((0, 2)))) mpatches.Patch.set_transform(self, axes.transAxes)
def get_window_extent(self, renderer=None): # This Spine has no Axis associated with it, and doesn't need to adjust # its location, so we can directly get the window extent from the # super-super-class. return mpatches.Patch.get_window_extent(self, renderer=renderer)
def set_xy(self, xy): self._path = mpath.Path(xy, closed=True) self._xy = xy self.stale = True
def draw(self, renderer): ret = mpatches.Patch.draw(self, renderer) self.stale = False return ret
class _ColorbarAxesLocator: """ Shrink the Axes if there are triangular or rectangular extends. """ def __init__(self, cbar): self._cbar = cbar self._orig_locator = cbar.ax._axes_locator
def __call__(self, ax, renderer): if self._orig_locator is not None: pos = self._orig_locator(ax, renderer) else: pos = ax.get_position(original=True) if self._cbar.extend == 'neither': return pos
y, extendlen = self._cbar._proportional_y() if not self._cbar._extend_lower(): extendlen[0] = 0 if not self._cbar._extend_upper(): extendlen[1] = 0 len = sum(extendlen) + 1 shrink = 1 / len offset = extendlen[0] / len # we need to reset the aspect ratio of the axes to account # of the extends... if hasattr(ax, '_colorbar_info'): aspect = ax._colorbar_info['aspect'] else: aspect = False # now shrink and/or offset to take into account the # extend tri/rectangles. if self._cbar.orientation == 'vertical': if aspect: self._cbar.ax.set_box_aspect(aspect*shrink) pos = pos.shrunk(1, shrink).translated(0, offset * pos.height) else: if aspect: self._cbar.ax.set_box_aspect(1/(aspect * shrink)) pos = pos.shrunk(shrink, 1).translated(offset * pos.width, 0) return pos
def get_subplotspec(self): # make tight_layout happy.. return ( self._cbar.ax.get_subplotspec() or getattr(self._orig_locator, "get_subplotspec", lambda: None)())
@_docstring.interpdclass Colorbar: r""" Draw a colorbar in an existing Axes.
Typically, colorbars are created using `.Figure.colorbar` or `.pyplot.colorbar` and associated with `.ScalarMappable`\s (such as an `.AxesImage` generated via `~.axes.Axes.imshow`).
In order to draw a colorbar not associated with other elements in the figure, e.g. when showing a colormap by itself, one can create an empty `.ScalarMappable`, or directly pass *cmap* and *norm* instead of *mappable* to `Colorbar`.
Useful public methods are :meth:`set_label` and :meth:`add_lines`.
Attributes ---------- ax : `~matplotlib.axes.Axes` The `~.axes.Axes` instance in which the colorbar is drawn. lines : list A list of `.LineCollection` (empty if no lines were drawn). dividers : `.LineCollection` A LineCollection (empty if *drawedges* is ``False``). """
n_rasterize = 50 # rasterize solids if number of colors >= n_rasterize
def __init__( self, ax, mappable=None, *, alpha=None, location=None, extend=None, extendfrac=None, extendrect=False, ticks=None, format=None, values=None, boundaries=None, spacing='uniform', drawedges=False, label='', cmap=None, norm=None, # redundant with *mappable* orientation=None, ticklocation='auto', # redundant with *location* ): """ Parameters ---------- ax : `~matplotlib.axes.Axes` The `~.axes.Axes` instance in which the colorbar is drawn.
mappable : `.ScalarMappable` The mappable whose colormap and norm will be used.
To show the colors versus index instead of on a 0-1 scale, set the mappable's norm to ``colors.NoNorm()``.
alpha : float The colorbar transparency between 0 (transparent) and 1 (opaque).
location : None or {'left', 'right', 'top', 'bottom'} Set the colorbar's *orientation* and *ticklocation*. Colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal. The *ticklocation* is the same as *location*, so if *location* is 'top', the ticks are on the top. *orientation* and/or *ticklocation* can be provided as well and overrides the value set by *location*, but there will be an error for incompatible combinations.
.. versionadded:: 3.7
%(_colormap_kw_doc)s
Other Parameters ---------------- cmap : `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` The colormap to use. This parameter is ignored, unless *mappable* is None.
norm : `~matplotlib.colors.Normalize` The normalization to use. This parameter is ignored, unless *mappable* is None.
orientation : None or {'vertical', 'horizontal'} If None, use the value determined by *location*. If both *orientation* and *location* are None then defaults to 'vertical'.
ticklocation : {'auto', 'left', 'right', 'top', 'bottom'} The location of the colorbar ticks. The *ticklocation* must match *orientation*. For example, a horizontal colorbar can only have ticks at the top or the bottom. If 'auto', the ticks will be the same as *location*, so a colorbar to the left will have ticks to the left. If *location* is None, the ticks will be at the bottom for a horizontal colorbar and at the right for a vertical. """ if mappable is None: mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
self.mappable = mappable cmap = mappable.cmap norm = mappable.norm
filled = True if isinstance(mappable, contour.ContourSet): cs = mappable alpha = cs.get_alpha() boundaries = cs._levels values = cs.cvalues extend = cs.extend filled = cs.filled if ticks is None: ticks = ticker.FixedLocator(cs.levels, nbins=10) elif isinstance(mappable, martist.Artist): alpha = mappable.get_alpha()
mappable.colorbar = self mappable.colorbar_cid = mappable.callbacks.connect( 'changed', self.update_normal)
location_orientation = _get_orientation_from_location(location)
_api.check_in_list( [None, 'vertical', 'horizontal'], orientation=orientation) _api.check_in_list( ['auto', 'left', 'right', 'top', 'bottom'], ticklocation=ticklocation) _api.check_in_list( ['uniform', 'proportional'], spacing=spacing)
if location_orientation is not None and orientation is not None: if location_orientation != orientation: raise TypeError( "location and orientation are mutually exclusive") else: orientation = orientation or location_orientation or "vertical"
self.ax = ax self.ax._axes_locator = _ColorbarAxesLocator(self)
if extend is None: if (not isinstance(mappable, contour.ContourSet) and getattr(cmap, 'colorbar_extend', False) is not False): extend = cmap.colorbar_extend elif hasattr(norm, 'extend'): extend = norm.extend else: extend = 'neither' self.alpha = None # Call set_alpha to handle array-like alphas properly self.set_alpha(alpha) self.cmap = cmap self.norm = norm self.values = values self.boundaries = boundaries self.extend = extend self._inside = _api.check_getitem( {'neither': slice(0, None), 'both': slice(1, -1), 'min': slice(1, None), 'max': slice(0, -1)}, extend=extend) self.spacing = spacing self.orientation = orientation self.drawedges = drawedges self._filled = filled self.extendfrac = extendfrac self.extendrect = extendrect self._extend_patches = [] self.solids = None self.solids_patches = [] self.lines = []
for spine in self.ax.spines.values(): spine.set_visible(False) self.outline = self.ax.spines['outline'] = _ColorbarSpine(self.ax)
self.dividers = collections.LineCollection( [], colors=[mpl.rcParams['axes.edgecolor']], linewidths=[0.5 * mpl.rcParams['axes.linewidth']], clip_on=False) self.ax.add_collection(self.dividers)
self._locator = None self._minorlocator = None self._formatter = None self._minorformatter = None
if ticklocation == 'auto': ticklocation = _get_ticklocation_from_orientation( orientation) if location is None else location self.ticklocation = ticklocation
self.set_label(label) self._reset_locator_formatter_scale()
if np.iterable(ticks): self._locator = ticker.FixedLocator(ticks, nbins=len(ticks)) else: self._locator = ticks
if isinstance(format, str): # Check format between FormatStrFormatter and StrMethodFormatter try: self._formatter = ticker.FormatStrFormatter(format) _ = self._formatter(0) except (TypeError, ValueError): self._formatter = ticker.StrMethodFormatter(format) else: self._formatter = format # Assume it is a Formatter or None self._draw_all()
if isinstance(mappable, contour.ContourSet) and not mappable.filled: self.add_lines(mappable)
# Link the Axes and Colorbar for interactive use self.ax._colorbar = self # Don't navigate on any of these types of mappables if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) or isinstance(self.mappable, contour.ContourSet)): self.ax.set_navigate(False)
# These are the functions that set up interactivity on this colorbar self._interactive_funcs = ["_get_view", "_set_view", "_set_view_from_bbox", "drag_pan"] for x in self._interactive_funcs: setattr(self.ax, x, getattr(self, x)) # Set the cla function to the cbar's method to override it self.ax.cla = self._cbar_cla # Callbacks for the extend calculations to handle inverting the axis self._extend_cid1 = self.ax.callbacks.connect( "xlim_changed", self._do_extends) self._extend_cid2 = self.ax.callbacks.connect( "ylim_changed", self._do_extends)
@property def long_axis(self): """Axis that has decorations (ticks, etc) on it.""" if self.orientation == 'vertical': return self.ax.yaxis return self.ax.xaxis
@property def locator(self): """Major tick `.Locator` for the colorbar.""" return self.long_axis.get_major_locator()
@locator.setter def locator(self, loc): self.long_axis.set_major_locator(loc) self._locator = loc
@property def minorlocator(self): """Minor tick `.Locator` for the colorbar.""" return self.long_axis.get_minor_locator()
@minorlocator.setter def minorlocator(self, loc): self.long_axis.set_minor_locator(loc) self._minorlocator = loc
@property def formatter(self): """Major tick label `.Formatter` for the colorbar.""" return self.long_axis.get_major_formatter()
@formatter.setter def formatter(self, fmt): self.long_axis.set_major_formatter(fmt) self._formatter = fmt
@property def minorformatter(self): """Minor tick `.Formatter` for the colorbar.""" return self.long_axis.get_minor_formatter()
@minorformatter.setter def minorformatter(self, fmt): self.long_axis.set_minor_formatter(fmt) self._minorformatter = fmt
def _cbar_cla(self): """Function to clear the interactive colorbar state.""" for x in self._interactive_funcs: delattr(self.ax, x) # We now restore the old cla() back and can call it directly del self.ax.cla self.ax.cla()
def update_normal(self, mappable=None): """ Update solid patches, lines, etc.
This is meant to be called when the norm of the image or contour plot to which this colorbar belongs changes.
If the norm on the mappable is different than before, this resets the locator and formatter for the axis, so if these have been customized, they will need to be customized again. However, if the norm only changes values of *vmin*, *vmax* or *cmap* then the old formatter and locator will be preserved. """ if mappable: # The mappable keyword argument exists because # ScalarMappable.changed() emits self.callbacks.process('changed', self) # in contrast, ColorizingArtist (and Colorizer) does not use this keyword. # [ColorizingArtist.changed() emits self.callbacks.process('changed')] # Also, there is no test where self.mappable == mappable is not True # and possibly no use case. # Therefore, the mappable keyword can be deprecated if cm.ScalarMappable # is removed. self.mappable = mappable _log.debug('colorbar update normal %r %r', self.mappable.norm, self.norm) self.set_alpha(self.mappable.get_alpha()) self.cmap = self.mappable.cmap if self.mappable.norm != self.norm: self.norm = self.mappable.norm self._reset_locator_formatter_scale()
self._draw_all() if isinstance(self.mappable, contour.ContourSet): CS = self.mappable if not CS.filled: self.add_lines(CS) self.stale = True
def _draw_all(self): """ Calculate any free parameters based on the current cmap and norm, and do all the drawing. """ if self.orientation == 'vertical': if mpl.rcParams['ytick.minor.visible']: self.minorticks_on() else: if mpl.rcParams['xtick.minor.visible']: self.minorticks_on() self.long_axis.set(label_position=self.ticklocation, ticks_position=self.ticklocation) self._short_axis().set_ticks([]) self._short_axis().set_ticks([], minor=True)
# Set self._boundaries and self._values, including extensions. # self._boundaries are the edges of each square of color, and # self._values are the value to map into the norm to get the # color: self._process_values() # Set self.vmin and self.vmax to first and last boundary, excluding # extensions: self.vmin, self.vmax = self._boundaries[self._inside][[0, -1]] # Compute the X/Y mesh. X, Y = self._mesh() # draw the extend triangles, and shrink the inner Axes to accommodate. # also adds the outline path to self.outline spine: self._do_extends() lower, upper = self.vmin, self.vmax if self.long_axis.get_inverted(): # If the axis is inverted, we need to swap the vmin/vmax lower, upper = upper, lower if self.orientation == 'vertical': self.ax.set_xlim(0, 1) self.ax.set_ylim(lower, upper) else: self.ax.set_ylim(0, 1) self.ax.set_xlim(lower, upper)
# set up the tick locators and formatters. A bit complicated because # boundary norms + uniform spacing requires a manual locator. self.update_ticks()
if self._filled: ind = np.arange(len(self._values)) if self._extend_lower(): ind = ind[1:] if self._extend_upper(): ind = ind[:-1] self._add_solids(X, Y, self._values[ind, np.newaxis])
def _add_solids(self, X, Y, C): """Draw the colors; optionally add separators.""" # Cleanup previously set artists. if self.solids is not None: self.solids.remove() for solid in self.solids_patches: solid.remove() # Add new artist(s), based on mappable type. Use individual patches if # hatching is needed, pcolormesh otherwise. mappable = getattr(self, 'mappable', None) if (isinstance(mappable, contour.ContourSet) and any(hatch is not None for hatch in mappable.hatches)): self._add_solids_patches(X, Y, C, mappable) else: self.solids = self.ax.pcolormesh( X, Y, C, cmap=self.cmap, norm=self.norm, alpha=self.alpha, edgecolors='none', shading='flat') if not self.drawedges: if len(self._y) >= self.n_rasterize: self.solids.set_rasterized(True) self._update_dividers()
def _update_dividers(self): if not self.drawedges: self.dividers.set_segments([]) return # Place all *internal* dividers. if self.orientation == 'vertical': lims = self.ax.get_ylim() bounds = (lims[0] < self._y) & (self._y < lims[1]) else: lims = self.ax.get_xlim() bounds = (lims[0] < self._y) & (self._y < lims[1]) y = self._y[bounds] # And then add outer dividers if extensions are on. if self._extend_lower(): y = np.insert(y, 0, lims[0]) if self._extend_upper(): y = np.append(y, lims[1]) X, Y = np.meshgrid([0, 1], y) if self.orientation == 'vertical': segments = np.dstack([X, Y]) else: segments = np.dstack([Y, X]) self.dividers.set_segments(segments)
def _add_solids_patches(self, X, Y, C, mappable): hatches = mappable.hatches * (len(C) + 1) # Have enough hatches. if self._extend_lower(): # remove first hatch that goes into the extend patch hatches = hatches[1:] patches = [] for i in range(len(X) - 1): xy = np.array([[X[i, 0], Y[i, 1]], [X[i, 1], Y[i, 0]], [X[i + 1, 1], Y[i + 1, 0]], [X[i + 1, 0], Y[i + 1, 1]]]) patch = mpatches.PathPatch(mpath.Path(xy), facecolor=self.cmap(self.norm(C[i][0])), hatch=hatches[i], linewidth=0, antialiased=False, alpha=self.alpha) self.ax.add_patch(patch) patches.append(patch) self.solids_patches = patches
def _do_extends(self, ax=None): """ Add the extend tri/rectangles on the outside of the Axes.
ax is unused, but required due to the callbacks on xlim/ylim changed """ # Clean up any previous extend patches for patch in self._extend_patches: patch.remove() self._extend_patches = [] # extend lengths are fraction of the *inner* part of colorbar, # not the total colorbar: _, extendlen = self._proportional_y() bot = 0 - (extendlen[0] if self._extend_lower() else 0) top = 1 + (extendlen[1] if self._extend_upper() else 0)
# xyout is the outline of the colorbar including the extend patches: if not self.extendrect: # triangle: xyout = np.array([[0, 0], [0.5, bot], [1, 0], [1, 1], [0.5, top], [0, 1], [0, 0]]) else: # rectangle: xyout = np.array([[0, 0], [0, bot], [1, bot], [1, 0], [1, 1], [1, top], [0, top], [0, 1], [0, 0]])
if self.orientation == 'horizontal': xyout = xyout[:, ::-1]
# xyout is the path for the spine: self.outline.set_xy(xyout) if not self._filled: return
# Make extend triangles or rectangles filled patches. These are # defined in the outer parent axes' coordinates: mappable = getattr(self, 'mappable', None) if (isinstance(mappable, contour.ContourSet) and any(hatch is not None for hatch in mappable.hatches)): hatches = mappable.hatches * (len(self._y) + 1) else: hatches = [None] * (len(self._y) + 1)
if self._extend_lower(): if not self.extendrect: # triangle xy = np.array([[0, 0], [0.5, bot], [1, 0]]) else: # rectangle xy = np.array([[0, 0], [0, bot], [1., bot], [1, 0]]) if self.orientation == 'horizontal': xy = xy[:, ::-1] # add the patch val = -1 if self.long_axis.get_inverted() else 0 color = self.cmap(self.norm(self._values[val])) patch = mpatches.PathPatch( mpath.Path(xy), facecolor=color, alpha=self.alpha, linewidth=0, antialiased=False, transform=self.ax.transAxes, hatch=hatches[0], clip_on=False, # Place it right behind the standard patches, which is # needed if we updated the extends zorder=np.nextafter(self.ax.patch.zorder, -np.inf)) self.ax.add_patch(patch) self._extend_patches.append(patch) # remove first hatch that goes into the extend patch hatches = hatches[1:] if self._extend_upper(): if not self.extendrect: # triangle xy = np.array([[0, 1], [0.5, top], [1, 1]]) else: # rectangle xy = np.array([[0, 1], [0, top], [1, top], [1, 1]]) if self.orientation == 'horizontal': xy = xy[:, ::-1] # add the patch val = 0 if self.long_axis.get_inverted() else -1 color = self.cmap(self.norm(self._values[val])) hatch_idx = len(self._y) - 1 patch = mpatches.PathPatch( mpath.Path(xy), facecolor=color, alpha=self.alpha, linewidth=0, antialiased=False, transform=self.ax.transAxes, hatch=hatches[hatch_idx], clip_on=False, # Place it right behind the standard patches, which is # needed if we updated the extends zorder=np.nextafter(self.ax.patch.zorder, -np.inf)) self.ax.add_patch(patch) self._extend_patches.append(patch)
self._update_dividers()
def add_lines(self, *args, **kwargs): """ Draw lines on the colorbar.
The lines are appended to the list :attr:`lines`.
Parameters ---------- levels : array-like The positions of the lines. colors : :mpltype:`color` or list of :mpltype:`color` Either a single color applying to all lines or one color value for each line. linewidths : float or array-like Either a single linewidth applying to all lines or one linewidth for each line. erase : bool, default: True Whether to remove any previously added lines.
Notes ----- Alternatively, this method can also be called with the signature ``colorbar.add_lines(contour_set, erase=True)``, in which case *levels*, *colors*, and *linewidths* are taken from *contour_set*. """ params = _api.select_matching_signature( [lambda self, CS, erase=True: locals(), lambda self, levels, colors, linewidths, erase=True: locals()], self, *args, **kwargs) if "CS" in params: self, cs, erase = params.values() if not isinstance(cs, contour.ContourSet) or cs.filled: raise ValueError("If a single artist is passed to add_lines, " "it must be a ContourSet of lines") # TODO: Make colorbar lines auto-follow changes in contour lines. return self.add_lines( cs.levels, cs.to_rgba(cs.cvalues, cs.alpha), cs.get_linewidths(), erase=erase) else: self, levels, colors, linewidths, erase = params.values()
y = self._locate(levels) rtol = (self._y[-1] - self._y[0]) * 1e-10 igood = (y < self._y[-1] + rtol) & (y > self._y[0] - rtol) y = y[igood] if np.iterable(colors): colors = np.asarray(colors)[igood] if np.iterable(linewidths): linewidths = np.asarray(linewidths)[igood] X, Y = np.meshgrid([0, 1], y) if self.orientation == 'vertical': xy = np.stack([X, Y], axis=-1) else: xy = np.stack([Y, X], axis=-1) col = collections.LineCollection(xy, linewidths=linewidths, colors=colors)
if erase and self.lines: for lc in self.lines: lc.remove() self.lines = [] self.lines.append(col)
# make a clip path that is just a linewidth bigger than the Axes... fac = np.max(linewidths) / 72 xy = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]) inches = self.ax.get_figure().dpi_scale_trans # do in inches: xy = inches.inverted().transform(self.ax.transAxes.transform(xy)) xy[[0, 1, 4], 1] -= fac xy[[2, 3], 1] += fac # back to axes units... xy = self.ax.transAxes.inverted().transform(inches.transform(xy)) col.set_clip_path(mpath.Path(xy, closed=True), self.ax.transAxes) self.ax.add_collection(col) self.stale = True
def update_ticks(self): """ Set up the ticks and ticklabels. This should not be needed by users. """ # Get the locator and formatter; defaults to self._locator if not None. self._get_ticker_locator_formatter() self.long_axis.set_major_locator(self._locator) self.long_axis.set_minor_locator(self._minorlocator) self.long_axis.set_major_formatter(self._formatter)
def _get_ticker_locator_formatter(self): """ Return the ``locator`` and ``formatter`` of the colorbar.
If they have not been defined (i.e. are *None*), the formatter and locator are retrieved from the axis, or from the value of the boundaries for a boundary norm.
Called by update_ticks... """ locator = self._locator formatter = self._formatter minorlocator = self._minorlocator if isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries if locator is None: locator = ticker.FixedLocator(b, nbins=10) if minorlocator is None: minorlocator = ticker.FixedLocator(b) elif isinstance(self.norm, colors.NoNorm): if locator is None: # put ticks on integers between the boundaries of NoNorm nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=.5) elif self.boundaries is not None: b = self._boundaries[self._inside] if locator is None: locator = ticker.FixedLocator(b, nbins=10) else: # most cases: if locator is None: # we haven't set the locator explicitly, so use the default # for this axis: locator = self.long_axis.get_major_locator() if minorlocator is None: minorlocator = self.long_axis.get_minor_locator()
if minorlocator is None: minorlocator = ticker.NullLocator()
if formatter is None: formatter = self.long_axis.get_major_formatter()
self._locator = locator self._formatter = formatter self._minorlocator = minorlocator _log.debug('locator: %r', locator)
def set_ticks(self, ticks, *, labels=None, minor=False, **kwargs): """ Set tick locations.
Parameters ---------- ticks : 1D array-like List of tick locations. labels : list of str, optional List of tick labels. If not set, the labels show the data value. minor : bool, default: False If ``False``, set the major ticks; if ``True``, the minor ticks. **kwargs `.Text` properties for the labels. These take effect only if you pass *labels*. In other cases, please use `~.Axes.tick_params`. """ if np.iterable(ticks): self.long_axis.set_ticks(ticks, labels=labels, minor=minor, **kwargs) self._locator = self.long_axis.get_major_locator() else: self._locator = ticks self.long_axis.set_major_locator(self._locator) self.stale = True
def get_ticks(self, minor=False): """ Return the ticks as a list of locations.
Parameters ---------- minor : boolean, default: False if True return the minor ticks. """ if minor: return self.long_axis.get_minorticklocs() else: return self.long_axis.get_majorticklocs()
def set_ticklabels(self, ticklabels, *, minor=False, **kwargs): """ [*Discouraged*] Set tick labels.
.. admonition:: Discouraged
The use of this method is discouraged, because of the dependency on tick positions. In most cases, you'll want to use ``set_ticks(positions, labels=labels)`` instead.
If you are using this method, you should always fix the tick positions before, e.g. by using `.Colorbar.set_ticks` or by explicitly setting a `~.ticker.FixedLocator` on the long axis of the colorbar. Otherwise, ticks are free to move and the labels may end up in unexpected positions.
Parameters ---------- ticklabels : sequence of str or of `.Text` Texts for labeling each tick location in the sequence set by `.Colorbar.set_ticks`; the number of labels must match the number of locations.
update_ticks : bool, default: True This keyword argument is ignored and will be removed. Deprecated
minor : bool If True, set minor ticks instead of major ticks.
**kwargs `.Text` properties for the labels. """ self.long_axis.set_ticklabels(ticklabels, minor=minor, **kwargs)
def minorticks_on(self): """ Turn on colorbar minor ticks. """ self.ax.minorticks_on() self._short_axis().set_minor_locator(ticker.NullLocator())
def minorticks_off(self): """Turn the minor ticks of the colorbar off.""" self._minorlocator = ticker.NullLocator() self.long_axis.set_minor_locator(self._minorlocator)
def set_label(self, label, *, loc=None, **kwargs): """ Add a label to the long axis of the colorbar.
Parameters ---------- label : str The label text. loc : str, optional The location of the label.
- For horizontal orientation one of {'left', 'center', 'right'} - For vertical orientation one of {'bottom', 'center', 'top'}
Defaults to :rc:`xaxis.labellocation` or :rc:`yaxis.labellocation` depending on the orientation. **kwargs Keyword arguments are passed to `~.Axes.set_xlabel` / `~.Axes.set_ylabel`. Supported keywords are *labelpad* and `.Text` properties. """ if self.orientation == "vertical": self.ax.set_ylabel(label, loc=loc, **kwargs) else: self.ax.set_xlabel(label, loc=loc, **kwargs) self.stale = True
def set_alpha(self, alpha): """ Set the transparency between 0 (transparent) and 1 (opaque).
If an array is provided, *alpha* will be set to None to use the transparency values associated with the colormap. """ self.alpha = None if isinstance(alpha, np.ndarray) else alpha
def _set_scale(self, scale, **kwargs): """ Set the colorbar long axis scale.
Parameters ---------- scale : {"linear", "log", "symlog", "logit", ...} or `.ScaleBase` The axis scale type to apply.
**kwargs Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:
- `matplotlib.scale.LinearScale` - `matplotlib.scale.LogScale` - `matplotlib.scale.SymmetricalLogScale` - `matplotlib.scale.LogitScale` - `matplotlib.scale.FuncScale` - `matplotlib.scale.AsinhScale`
Notes ----- By default, Matplotlib supports the above-mentioned scales. Additionally, custom scales may be registered using `matplotlib.scale.register_scale`. These scales can then also be used here. """ self.long_axis._set_axes_scale(scale, **kwargs)
def remove(self): """ Remove this colorbar from the figure.
If the colorbar was created with ``use_gridspec=True`` the previous gridspec is restored. """ if hasattr(self.ax, '_colorbar_info'): parents = self.ax._colorbar_info['parents'] for a in parents: if self.ax in a._colorbars: a._colorbars.remove(self.ax)
self.ax.remove()
self.mappable.callbacks.disconnect(self.mappable.colorbar_cid) self.mappable.colorbar = None self.mappable.colorbar_cid = None # Remove the extension callbacks self.ax.callbacks.disconnect(self._extend_cid1) self.ax.callbacks.disconnect(self._extend_cid2)
try: ax = self.mappable.axes except AttributeError: return try: subplotspec = self.ax.get_subplotspec().get_gridspec()._subplot_spec except AttributeError: # use_gridspec was False pos = ax.get_position(original=True) ax._set_position(pos) else: # use_gridspec was True ax.set_subplotspec(subplotspec)
def _process_values(self): """ Set `_boundaries` and `_values` based on the self.boundaries and self.values if not None, or based on the size of the colormap and the vmin/vmax of the norm. """ if self.values is not None: # set self._boundaries from the values... self._values = np.array(self.values) if self.boundaries is None: # bracket values by 1/2 dv: b = np.zeros(len(self.values) + 1) b[1:-1] = 0.5 * (self._values[:-1] + self._values[1:]) b[0] = 2.0 * b[1] - b[2] b[-1] = 2.0 * b[-2] - b[-3] self._boundaries = b return self._boundaries = np.array(self.boundaries) return
# otherwise values are set from the boundaries if isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries elif isinstance(self.norm, colors.NoNorm): # NoNorm has N blocks, so N+1 boundaries, centered on integers: b = np.arange(self.cmap.N + 1) - .5 elif self.boundaries is not None: b = self.boundaries else: # otherwise make the boundaries from the size of the cmap: N = self.cmap.N + 1 b, _ = self._uniform_y(N) # add extra boundaries if needed: if self._extend_lower(): b = np.hstack((b[0] - 1, b)) if self._extend_upper(): b = np.hstack((b, b[-1] + 1))
# transform from 0-1 to vmin-vmax: if self.mappable.get_array() is not None: self.mappable.autoscale_None() if not self.norm.scaled(): # If we still aren't scaled after autoscaling, use 0, 1 as default self.norm.vmin = 0 self.norm.vmax = 1 self.norm.vmin, self.norm.vmax = mtransforms.nonsingular( self.norm.vmin, self.norm.vmax, expander=0.1) if (not isinstance(self.norm, colors.BoundaryNorm) and (self.boundaries is None)): b = self.norm.inverse(b)
self._boundaries = np.asarray(b, dtype=float) self._values = 0.5 * (self._boundaries[:-1] + self._boundaries[1:]) if isinstance(self.norm, colors.NoNorm): self._values = (self._values + 0.00001).astype(np.int16)
def _mesh(self): """ Return the coordinate arrays for the colorbar pcolormesh/patches.
These are scaled between vmin and vmax, and already handle colorbar orientation. """ y, _ = self._proportional_y() # Use the vmin and vmax of the colorbar, which may not be the same # as the norm. There are situations where the colormap has a # narrower range than the colorbar and we want to accommodate the # extra contours. if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) or self.boundaries is not None): # not using a norm. y = y * (self.vmax - self.vmin) + self.vmin else: # Update the norm values in a context manager as it is only # a temporary change and we don't want to propagate any signals # attached to the norm (callbacks.blocked). with (self.norm.callbacks.blocked(), cbook._setattr_cm(self.norm, vmin=self.vmin, vmax=self.vmax)): y = self.norm.inverse(y) self._y = y X, Y = np.meshgrid([0., 1.], y) if self.orientation == 'vertical': return (X, Y) else: return (Y, X)
def _forward_boundaries(self, x): # map boundaries equally between 0 and 1... b = self._boundaries y = np.interp(x, b, np.linspace(0, 1, len(b))) # the following avoids ticks in the extends: eps = (b[-1] - b[0]) * 1e-6 # map these _well_ out of bounds to keep any ticks out # of the extends region... y[x < b[0]-eps] = -1 y[x > b[-1]+eps] = 2 return y
def _inverse_boundaries(self, x): # invert the above... b = self._boundaries return np.interp(x, np.linspace(0, 1, len(b)), b)
def _reset_locator_formatter_scale(self): """ Reset the locator et al to defaults. Any user-hardcoded changes need to be re-entered if this gets called (either at init, or when the mappable normal gets changed: Colorbar.update_normal) """ self._process_values() self._locator = None self._minorlocator = None self._formatter = None self._minorformatter = None if (isinstance(self.mappable, contour.ContourSet) and isinstance(self.norm, colors.LogNorm)): # if contours have lognorm, give them a log scale... self._set_scale('log') elif (self.boundaries is not None or isinstance(self.norm, colors.BoundaryNorm)): if self.spacing == 'uniform': funcs = (self._forward_boundaries, self._inverse_boundaries) self._set_scale('function', functions=funcs) elif self.spacing == 'proportional': self._set_scale('linear') elif getattr(self.norm, '_scale', None): # use the norm's scale (if it exists and is not None): self._set_scale(self.norm._scale) elif type(self.norm) is colors.Normalize: # plain Normalize: self._set_scale('linear') else: # norm._scale is None or not an attr: derive the scale from # the Norm: funcs = (self.norm, self.norm.inverse) self._set_scale('function', functions=funcs)
def _locate(self, x): """ Given a set of color data values, return their corresponding colorbar data coordinates. """ if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)): b = self._boundaries xn = x else: # Do calculations using normalized coordinates so # as to make the interpolation more accurate. b = self.norm(self._boundaries, clip=False).filled() xn = self.norm(x, clip=False).filled()
bunique = b[self._inside] yunique = self._y
z = np.interp(xn, bunique, yunique) return z
# trivial helpers
def _uniform_y(self, N): """ Return colorbar data coordinates for *N* uniformly spaced boundaries, plus extension lengths if required. """ automin = automax = 1. / (N - 1.) extendlength = self._get_extension_lengths(self.extendfrac, automin, automax, default=0.05) y = np.linspace(0, 1, N) return y, extendlength
def _proportional_y(self): """ Return colorbar data coordinates for the boundaries of a proportional colorbar, plus extension lengths if required: """ if (isinstance(self.norm, colors.BoundaryNorm) or self.boundaries is not None): y = (self._boundaries - self._boundaries[self._inside][0]) y = y / (self._boundaries[self._inside][-1] - self._boundaries[self._inside][0]) # need yscaled the same as the axes scale to get # the extend lengths. if self.spacing == 'uniform': yscaled = self._forward_boundaries(self._boundaries) else: yscaled = y else: y = self.norm(self._boundaries.copy()) y = np.ma.filled(y, np.nan) # the norm and the scale should be the same... yscaled = y y = y[self._inside] yscaled = yscaled[self._inside] # normalize from 0..1: norm = colors.Normalize(y[0], y[-1]) y = np.ma.filled(norm(y), np.nan) norm = colors.Normalize(yscaled[0], yscaled[-1]) yscaled = np.ma.filled(norm(yscaled), np.nan) # make the lower and upper extend lengths proportional to the lengths # of the first and last boundary spacing (if extendfrac='auto'): automin = yscaled[1] - yscaled[0] automax = yscaled[-1] - yscaled[-2] extendlength = [0, 0] if self._extend_lower() or self._extend_upper(): extendlength = self._get_extension_lengths( self.extendfrac, automin, automax, default=0.05) return y, extendlength
def _get_extension_lengths(self, frac, automin, automax, default=0.05): """ Return the lengths of colorbar extensions.
This is a helper method for _uniform_y and _proportional_y. """ # Set the default value. extendlength = np.array([default, default]) if isinstance(frac, str): _api.check_in_list(['auto'], extendfrac=frac.lower()) # Use the provided values when 'auto' is required. extendlength[:] = [automin, automax] elif frac is not None: try: # Try to set min and max extension fractions directly. extendlength[:] = frac # If frac is a sequence containing None then NaN may # be encountered. This is an error. if np.isnan(extendlength).any(): raise ValueError() except (TypeError, ValueError) as err: # Raise an error on encountering an invalid value for frac. raise ValueError('invalid value for extendfrac') from err return extendlength
def _extend_lower(self): """Return whether the lower limit is open ended.""" minmax = "max" if self.long_axis.get_inverted() else "min" return self.extend in ('both', minmax)
def _extend_upper(self): """Return whether the upper limit is open ended.""" minmax = "min" if self.long_axis.get_inverted() else "max" return self.extend in ('both', minmax)
def _short_axis(self): """Return the short axis""" if self.orientation == 'vertical': return self.ax.xaxis return self.ax.yaxis
def _get_view(self): # docstring inherited # An interactive view for a colorbar is the norm's vmin/vmax return self.norm.vmin, self.norm.vmax
def _set_view(self, view): # docstring inherited # An interactive view for a colorbar is the norm's vmin/vmax self.norm.vmin, self.norm.vmax = view
def _set_view_from_bbox(self, bbox, direction='in', mode=None, twinx=False, twiny=False): # docstring inherited # For colorbars, we use the zoom bbox to scale the norm's vmin/vmax new_xbound, new_ybound = self.ax._prepare_view_from_bbox( bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny) if self.orientation == 'horizontal': self.norm.vmin, self.norm.vmax = new_xbound elif self.orientation == 'vertical': self.norm.vmin, self.norm.vmax = new_ybound
def drag_pan(self, button, key, x, y): # docstring inherited points = self.ax._get_pan_points(button, key, x, y) if points is not None: if self.orientation == 'horizontal': self.norm.vmin, self.norm.vmax = points[:, 0] elif self.orientation == 'vertical': self.norm.vmin, self.norm.vmax = points[:, 1]
ColorbarBase = Colorbar # Backcompat API
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
def _get_orientation_from_location(location): return _api.check_getitem( {None: None, "left": "vertical", "right": "vertical", "top": "horizontal", "bottom": "horizontal"}, location=location)
def _get_ticklocation_from_orientation(orientation): return _api.check_getitem( {None: "right", "vertical": "right", "horizontal": "bottom"}, orientation=orientation)
@_docstring.interpddef 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 : `~matplotlib.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 : `~matplotlib.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
@_docstring.interpddef 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 : `~matplotlib.axes.Axes` The Axes to use as parent for placing the colorbar. %(_make_axes_kw_doc)s
Returns ------- cax : `~matplotlib.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'): gs = parent.get_subplotspec().subgridspec( 3, 2, wspace=wh_space, hspace=0, height_ratios=[(1-anchor[1])*(1-shrink), shrink, anchor[1]*(1-shrink)]) if location == 'left': gs.set_width_ratios([fraction, 1 - fraction - pad]) ss_main = gs[:, 1] ss_cb = gs[1, 0] else: gs.set_width_ratios([1 - fraction - pad, fraction]) ss_main = gs[:, 0] ss_cb = gs[1, 1] else: gs = parent.get_subplotspec().subgridspec( 2, 3, hspace=wh_space, wspace=0, width_ratios=[anchor[0]*(1-shrink), shrink, (1-anchor[0])*(1-shrink)]) if location == 'top': gs.set_height_ratios([fraction, 1 - fraction - pad]) ss_main = gs[1, :] ss_cb = gs[0, 1] else: gs.set_height_ratios([1 - fraction - pad, fraction]) ss_main = gs[0, :] ss_cb = gs[1, 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, kwargs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102from matplotlib import cbook, colorbar, colors, artist
from typing import overloadimport numpy as npfrom numpy.typing import ArrayLike
class Colorizer: colorbar: colorbar.Colorbar | None callbacks: cbook.CallbackRegistry def __init__( self, cmap: str | colors.Colormap | None = ..., norm: str | colors.Normalize | None = ..., ) -> None: ... @property def norm(self) -> colors.Normalize: ... @norm.setter def norm(self, norm: colors.Normalize | str | None) -> None: ... def to_rgba( self, x: np.ndarray, alpha: float | ArrayLike | None = ..., bytes: bool = ..., norm: bool = ..., ) -> np.ndarray: ... def autoscale(self, A: ArrayLike) -> None: ... def autoscale_None(self, A: ArrayLike) -> None: ... @property def cmap(self) -> colors.Colormap: ... @cmap.setter def cmap(self, cmap: colors.Colormap | str | None) -> None: ... def get_clim(self) -> tuple[float, float]: ... def set_clim(self, vmin: float | tuple[float, float] | None = ..., vmax: float | None = ...) -> None: ... def changed(self) -> None: ... @property def vmin(self) -> float | None: ... @vmin.setter def vmin(self, value: float | None) -> None: ... @property def vmax(self) -> float | None: ... @vmax.setter def vmax(self, value: float | None) -> None: ... @property def clip(self) -> bool: ... @clip.setter def clip(self, value: bool) -> None: ...
class _ColorizerInterface: cmap: colors.Colormap colorbar: colorbar.Colorbar | None callbacks: cbook.CallbackRegistry def to_rgba( self, x: np.ndarray, alpha: float | ArrayLike | None = ..., bytes: bool = ..., norm: bool = ..., ) -> np.ndarray: ... def get_clim(self) -> tuple[float, float]: ... def set_clim(self, vmin: float | tuple[float, float] | None = ..., vmax: float | None = ...) -> None: ... def get_alpha(self) -> float | None: ... def get_cmap(self) -> colors.Colormap: ... def set_cmap(self, cmap: str | colors.Colormap) -> None: ... @property def norm(self) -> colors.Normalize: ... @norm.setter def norm(self, norm: colors.Normalize | str | None) -> None: ... def set_norm(self, norm: colors.Normalize | str | None) -> None: ... def autoscale(self) -> None: ... def autoscale_None(self) -> None: ...
class _ScalarMappable(_ColorizerInterface): def __init__( self, norm: colors.Normalize | None = ..., cmap: str | colors.Colormap | None = ..., *, colorizer: Colorizer | None = ..., **kwargs ) -> None: ... def set_array(self, A: ArrayLike | None) -> None: ... def get_array(self) -> np.ndarray | None: ... def changed(self) -> None: ...
class ColorizingArtist(_ScalarMappable, artist.Artist): callbacks: cbook.CallbackRegistry def __init__( self, colorizer: Colorizer, **kwargs ) -> None: ... def set_array(self, A: ArrayLike | None) -> None: ... def get_array(self) -> np.ndarray | None: ... def changed(self) -> None: ... @property def colorizer(self) -> Colorizer: ... @colorizer.setter def colorizer(self, cl: Colorizer) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449from collections.abc import Callable, Iterable, Iterator, Mapping, Sequencefrom matplotlib import cbook, scaleimport re
from typing import Any, Literal, overloadfrom .typing import ColorType
import numpy as npfrom numpy.typing import ArrayLike
# Explicitly export colors dictionaries which are imported in the implBASE_COLORS: dict[str, ColorType]CSS4_COLORS: dict[str, ColorType]TABLEAU_COLORS: dict[str, ColorType]XKCD_COLORS: dict[str, ColorType]
class _ColorMapping(dict[str, ColorType]): cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]] def __init__(self, mapping) -> None: ... def __setitem__(self, key, value) -> None: ... def __delitem__(self, key) -> None: ...
def get_named_colors_mapping() -> _ColorMapping: ...
class ColorSequenceRegistry(Mapping): def __init__(self) -> None: ... def __getitem__(self, item: str) -> list[ColorType]: ... def __iter__(self) -> Iterator[str]: ... def __len__(self) -> int: ... def register(self, name: str, color_list: Iterable[ColorType]) -> None: ... def unregister(self, name: str) -> None: ...
_color_sequences: ColorSequenceRegistry = ...
def is_color_like(c: Any) -> bool: ...def same_color(c1: ColorType, c2: ColorType) -> bool: ...def to_rgba( c: ColorType, alpha: float | None = ...) -> tuple[float, float, float, float]: ...def to_rgba_array( c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ...) -> np.ndarray: ...def to_rgb(c: ColorType) -> tuple[float, float, float]: ...def to_hex(c: ColorType, keep_alpha: bool = ...) -> str: ...
cnames: dict[str, ColorType]hexColorPattern: re.Patternrgb2hex = to_hexhex2color = to_rgb
class ColorConverter: colors: _ColorMapping cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]] @staticmethod def to_rgb(c: ColorType) -> tuple[float, float, float]: ... @staticmethod def to_rgba( c: ColorType, alpha: float | None = ... ) -> tuple[float, float, float, float]: ... @staticmethod def to_rgba_array( c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ... ) -> np.ndarray: ...
colorConverter: ColorConverter
class Colormap: name: str N: int colorbar_extend: bool def __init__(self, name: str, N: int = ...) -> None: ... @overload def __call__( self, X: Sequence[float] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ... ) -> np.ndarray: ... @overload def __call__( self, X: float, alpha: float | None = ..., bytes: bool = ... ) -> tuple[float, float, float, float]: ... @overload def __call__( self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ... ) -> tuple[float, float, float, float] | np.ndarray: ... def __copy__(self) -> Colormap: ... def __eq__(self, other: object) -> bool: ... def get_bad(self) -> np.ndarray: ... def set_bad(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... def get_under(self) -> np.ndarray: ... def set_under(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... def get_over(self) -> np.ndarray: ... def set_over(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... def set_extremes( self, *, bad: ColorType | None = ..., under: ColorType | None = ..., over: ColorType | None = ... ) -> None: ... def with_extremes( self, *, bad: ColorType | None = ..., under: ColorType | None = ..., over: ColorType | None = ... ) -> Colormap: ... def is_gray(self) -> bool: ... def resampled(self, lutsize: int) -> Colormap: ... def reversed(self, name: str | None = ...) -> Colormap: ... def _repr_html_(self) -> str: ... def _repr_png_(self) -> bytes: ... def copy(self) -> Colormap: ...
class LinearSegmentedColormap(Colormap): monochrome: bool def __init__( self, name: str, segmentdata: dict[ Literal["red", "green", "blue", "alpha"], Sequence[tuple[float, ...]] ], N: int = ..., gamma: float = ..., ) -> None: ... def set_gamma(self, gamma: float) -> None: ... @staticmethod def from_list( name: str, colors: ArrayLike | Sequence[tuple[float, ColorType]], N: int = ..., gamma: float = ... ) -> LinearSegmentedColormap: ... def resampled(self, lutsize: int) -> LinearSegmentedColormap: ... def reversed(self, name: str | None = ...) -> LinearSegmentedColormap: ...
class ListedColormap(Colormap): monochrome: bool colors: ArrayLike | ColorType def __init__( self, colors: ArrayLike | ColorType, name: str = ..., N: int | None = ... ) -> None: ... def resampled(self, lutsize: int) -> ListedColormap: ... def reversed(self, name: str | None = ...) -> ListedColormap: ...
class MultivarColormap: name: str n_variates: int def __init__(self, colormaps: list[Colormap], combination_mode: Literal['sRGB_add', 'sRGB_sub'], name: str = ...) -> None: ... @overload def __call__( self, X: Sequence[Sequence[float]] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ..., clip: bool = ... ) -> np.ndarray: ... @overload def __call__( self, X: Sequence[float], alpha: float | None = ..., bytes: bool = ..., clip: bool = ... ) -> tuple[float, float, float, float]: ... @overload def __call__( self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ..., clip: bool = ... ) -> tuple[float, float, float, float] | np.ndarray: ... def copy(self) -> MultivarColormap: ... def __copy__(self) -> MultivarColormap: ... def __eq__(self, other: Any) -> bool: ... def __getitem__(self, item: int) -> Colormap: ... def __iter__(self) -> Iterator[Colormap]: ... def __len__(self) -> int: ... def get_bad(self) -> np.ndarray: ... def resampled(self, lutshape: Sequence[int | None]) -> MultivarColormap: ... def with_extremes( self, *, bad: ColorType | None = ..., under: Sequence[ColorType] | None = ..., over: Sequence[ColorType] | None = ... ) -> MultivarColormap: ... @property def combination_mode(self) -> str: ... def _repr_html_(self) -> str: ... def _repr_png_(self) -> bytes: ...
class BivarColormap: name: str N: int M: int n_variates: int def __init__( self, N: int = ..., M: int | None = ..., shape: Literal['square', 'circle', 'ignore', 'circleignore'] = ..., origin: Sequence[float] = ..., name: str = ... ) -> None: ... @overload def __call__( self, X: Sequence[Sequence[float]] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ... ) -> np.ndarray: ... @overload def __call__( self, X: Sequence[float], alpha: float | None = ..., bytes: bool = ... ) -> tuple[float, float, float, float]: ... @overload def __call__( self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ... ) -> tuple[float, float, float, float] | np.ndarray: ... @property def lut(self) -> np.ndarray: ... @property def shape(self) -> str: ... @property def origin(self) -> tuple[float, float]: ... def copy(self) -> BivarColormap: ... def __copy__(self) -> BivarColormap: ... def __getitem__(self, item: int) -> Colormap: ... def __eq__(self, other: Any) -> bool: ... def get_bad(self) -> np.ndarray: ... def get_outside(self) -> np.ndarray: ... def resampled(self, lutshape: Sequence[int | None], transposed: bool = ...) -> BivarColormap: ... def transposed(self) -> BivarColormap: ... def reversed(self, axis_0: bool = ..., axis_1: bool = ...) -> BivarColormap: ... def with_extremes( self, *, bad: ColorType | None = ..., outside: ColorType | None = ..., shape: str | None = ..., origin: None | Sequence[float] = ..., ) -> MultivarColormap: ... def _repr_html_(self) -> str: ... def _repr_png_(self) -> bytes: ...
class SegmentedBivarColormap(BivarColormap): def __init__( self, patch: np.ndarray, N: int = ..., shape: Literal['square', 'circle', 'ignore', 'circleignore'] = ..., origin: Sequence[float] = ..., name: str = ... ) -> None: ...
class BivarColormapFromImage(BivarColormap): def __init__( self, lut: np.ndarray, shape: Literal['square', 'circle', 'ignore', 'circleignore'] = ..., origin: Sequence[float] = ..., name: str = ... ) -> None: ...
class Normalize: callbacks: cbook.CallbackRegistry def __init__( self, vmin: float | None = ..., vmax: float | None = ..., clip: bool = ... ) -> None: ... @property def vmin(self) -> float | None: ... @vmin.setter def vmin(self, value: float | None) -> None: ... @property def vmax(self) -> float | None: ... @vmax.setter def vmax(self, value: float | None) -> None: ... @property def clip(self) -> bool: ... @clip.setter def clip(self, value: bool) -> None: ... @staticmethod def process_value(value: ArrayLike) -> tuple[np.ma.MaskedArray, bool]: ... @overload def __call__(self, value: float, clip: bool | None = ...) -> float: ... @overload def __call__(self, value: np.ndarray, clip: bool | None = ...) -> np.ma.MaskedArray: ... @overload def __call__(self, value: ArrayLike, clip: bool | None = ...) -> ArrayLike: ... @overload def inverse(self, value: float) -> float: ... @overload def inverse(self, value: np.ndarray) -> np.ma.MaskedArray: ... @overload def inverse(self, value: ArrayLike) -> ArrayLike: ... def autoscale(self, A: ArrayLike) -> None: ... def autoscale_None(self, A: ArrayLike) -> None: ... def scaled(self) -> bool: ...
class TwoSlopeNorm(Normalize): def __init__( self, vcenter: float, vmin: float | None = ..., vmax: float | None = ... ) -> None: ... @property def vcenter(self) -> float: ... @vcenter.setter def vcenter(self, value: float) -> None: ... def autoscale_None(self, A: ArrayLike) -> None: ...
class CenteredNorm(Normalize): def __init__( self, vcenter: float = ..., halfrange: float | None = ..., clip: bool = ... ) -> None: ... @property def vcenter(self) -> float: ... @vcenter.setter def vcenter(self, vcenter: float) -> None: ... @property def halfrange(self) -> float: ... @halfrange.setter def halfrange(self, halfrange: float) -> None: ...
@overloaddef make_norm_from_scale( scale_cls: type[scale.ScaleBase], base_norm_cls: type[Normalize], *, init: Callable | None = ...) -> type[Normalize]: ...@overloaddef make_norm_from_scale( scale_cls: type[scale.ScaleBase], base_norm_cls: None = ..., *, init: Callable | None = ...) -> Callable[[type[Normalize]], type[Normalize]]: ...
class FuncNorm(Normalize): def __init__( self, functions: tuple[Callable, Callable], vmin: float | None = ..., vmax: float | None = ..., clip: bool = ..., ) -> None: ...class LogNorm(Normalize): ...
class SymLogNorm(Normalize): def __init__( self, linthresh: float, linscale: float = ..., vmin: float | None = ..., vmax: float | None = ..., clip: bool = ..., *, base: float = ..., ) -> None: ... @property def linthresh(self) -> float: ... @linthresh.setter def linthresh(self, value: float) -> None: ...
class AsinhNorm(Normalize): def __init__( self, linear_width: float = ..., vmin: float | None = ..., vmax: float | None = ..., clip: bool = ..., ) -> None: ... @property def linear_width(self) -> float: ... @linear_width.setter def linear_width(self, value: float) -> None: ...
class PowerNorm(Normalize): gamma: float def __init__( self, gamma: float, vmin: float | None = ..., vmax: float | None = ..., clip: bool = ..., ) -> None: ...
class BoundaryNorm(Normalize): boundaries: np.ndarray N: int Ncmap: int extend: Literal["neither", "both", "min", "max"] def __init__( self, boundaries: ArrayLike, ncolors: int, clip: bool = ..., *, extend: Literal["neither", "both", "min", "max"] = ... ) -> None: ...
class NoNorm(Normalize): ...
def rgb_to_hsv(arr: ArrayLike) -> np.ndarray: ...def hsv_to_rgb(hsv: ArrayLike) -> np.ndarray: ...
class LightSource: azdeg: float altdeg: float hsv_min_val: float hsv_max_val: float hsv_min_sat: float hsv_max_sat: float def __init__( self, azdeg: float = ..., altdeg: float = ..., hsv_min_val: float = ..., hsv_max_val: float = ..., hsv_min_sat: float = ..., hsv_max_sat: float = ..., ) -> None: ... @property def direction(self) -> np.ndarray: ... def hillshade( self, elevation: ArrayLike, vert_exag: float = ..., dx: float = ..., dy: float = ..., fraction: float = ..., ) -> np.ndarray: ... def shade_normals( self, normals: np.ndarray, fraction: float = ... ) -> np.ndarray: ... def shade( self, data: ArrayLike, cmap: Colormap, norm: Normalize | None = ..., blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ..., vmin: float | None = ..., vmax: float | None = ..., vert_exag: float = ..., dx: float = ..., dy: float = ..., fraction: float = ..., **kwargs ) -> np.ndarray: ... def shade_rgb( self, rgb: ArrayLike, elevation: ArrayLike, fraction: float = ..., blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ..., vert_exag: float = ..., dx: float = ..., dy: float = ..., **kwargs ) -> np.ndarray: ... def blend_hsv( self, rgb: ArrayLike, intensity: ArrayLike, hsv_max_sat: float | None = ..., hsv_max_val: float | None = ..., hsv_min_val: float | None = ..., hsv_min_sat: float | None = ..., ) -> ArrayLike: ... def blend_soft_light( self, rgb: np.ndarray, intensity: np.ndarray ) -> np.ndarray: ... def blend_overlay(self, rgb: np.ndarray, intensity: np.ndarray) -> np.ndarray: ...
def from_levels_and_colors( levels: Sequence[float], colors: Sequence[ColorType], extend: Literal["neither", "min", "max", "both"] = ...,) -> tuple[ListedColormap, BoundaryNorm]: ...1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556from matplotlib.artist import Artistfrom matplotlib.lines import Line2Dfrom matplotlib.collections import LineCollectionfrom matplotlib.patches import Rectangle
from collections.abc import Callablefrom typing import Any, Literalfrom numpy.typing import ArrayLike
class Container(tuple): def __new__(cls, *args, **kwargs): ... def __init__(self, kl, label: Any | None = ...) -> None: ... def remove(self) -> None: ... def get_children(self) -> list[Artist]: ... def get_label(self) -> str | None: ... def set_label(self, s: Any) -> None: ... def add_callback(self, func: Callable[[Artist], Any]) -> int: ... def remove_callback(self, oid: int) -> None: ... def pchanged(self) -> None: ...
class BarContainer(Container): patches: list[Rectangle] errorbar: None | ErrorbarContainer datavalues: None | ArrayLike orientation: None | Literal["vertical", "horizontal"] def __init__( self, patches: list[Rectangle], errorbar: ErrorbarContainer | None = ..., *, datavalues: ArrayLike | None = ..., orientation: Literal["vertical", "horizontal"] | None = ..., **kwargs ) -> None: ...
class ErrorbarContainer(Container): lines: tuple[Line2D, tuple[Line2D, ...], tuple[LineCollection, ...]] has_xerr: bool has_yerr: bool def __init__( self, lines: tuple[Line2D, tuple[Line2D, ...], tuple[LineCollection, ...]], has_xerr: bool = ..., has_yerr: bool = ..., **kwargs ) -> None: ...
class StemContainer(Container): markerline: Line2D stemlines: LineCollection baseline: Line2D def __init__( self, markerline_stemlines_baseline: tuple[Line2D, LineCollection, Line2D], **kwargs ) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160from typing import Any, Literal, overload
from numpy.typing import ArrayLikeimport numpy as np
from matplotlib.axes import Axesfrom matplotlib.backend_bases import RendererBasefrom matplotlib.figure import Figurefrom matplotlib.transforms import Bbox
class GridSpecBase: def __init__( self, nrows: int, ncols: int, height_ratios: ArrayLike | None = ..., width_ratios: ArrayLike | None = ..., ) -> None: ... @property def nrows(self) -> int: ... @property def ncols(self) -> int: ... def get_geometry(self) -> tuple[int, int]: ... def get_subplot_params(self, figure: Figure | None = ...) -> SubplotParams: ... def new_subplotspec( self, loc: tuple[int, int], rowspan: int = ..., colspan: int = ... ) -> SubplotSpec: ... def set_width_ratios(self, width_ratios: ArrayLike | None) -> None: ... def get_width_ratios(self) -> ArrayLike: ... def set_height_ratios(self, height_ratios: ArrayLike | None) -> None: ... def get_height_ratios(self) -> ArrayLike: ... def get_grid_positions( self, fig: Figure ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: ... @staticmethod def _check_gridspec_exists(figure: Figure, nrows: int, ncols: int) -> GridSpec: ... def __getitem__( self, key: tuple[int | slice, int | slice] | slice | int ) -> SubplotSpec: ... @overload def subplots( self, *, sharex: bool | Literal["all", "row", "col", "none"] = ..., sharey: bool | Literal["all", "row", "col", "none"] = ..., squeeze: Literal[False], subplot_kw: dict[str, Any] | None = ... ) -> np.ndarray: ... @overload def subplots( self, *, sharex: bool | Literal["all", "row", "col", "none"] = ..., sharey: bool | Literal["all", "row", "col", "none"] = ..., squeeze: Literal[True] = ..., subplot_kw: dict[str, Any] | None = ... ) -> np.ndarray | Axes: ...
class GridSpec(GridSpecBase): left: float | None bottom: float | None right: float | None top: float | None wspace: float | None hspace: float | None figure: Figure | None def __init__( self, nrows: int, ncols: int, figure: Figure | None = ..., left: float | None = ..., bottom: float | None = ..., right: float | None = ..., top: float | None = ..., wspace: float | None = ..., hspace: float | None = ..., width_ratios: ArrayLike | None = ..., height_ratios: ArrayLike | None = ..., ) -> None: ... def update(self, **kwargs: float | None) -> None: ... def locally_modified_subplot_params(self) -> list[str]: ... def tight_layout( self, figure: Figure, renderer: RendererBase | None = ..., pad: float = ..., h_pad: float | None = ..., w_pad: float | None = ..., rect: tuple[float, float, float, float] | None = ..., ) -> None: ...
class GridSpecFromSubplotSpec(GridSpecBase): figure: Figure | None def __init__( self, nrows: int, ncols: int, subplot_spec: SubplotSpec, wspace: float | None = ..., hspace: float | None = ..., height_ratios: ArrayLike | None = ..., width_ratios: ArrayLike | None = ..., ) -> None: ... def get_topmost_subplotspec(self) -> SubplotSpec: ...
class SubplotSpec: num1: int def __init__( self, gridspec: GridSpecBase, num1: int, num2: int | None = ... ) -> None: ... @staticmethod def _from_subplot_args(figure, args): ... @property def num2(self) -> int: ... @num2.setter def num2(self, value: int) -> None: ... def get_gridspec(self) -> GridSpecBase: ... def get_geometry(self) -> tuple[int, int, int, int]: ... @property def rowspan(self) -> range: ... @property def colspan(self) -> range: ... def is_first_row(self) -> bool: ... def is_last_row(self) -> bool: ... def is_first_col(self) -> bool: ... def is_last_col(self) -> bool: ... def get_position(self, figure: Figure) -> Bbox: ... def get_topmost_subplotspec(self) -> SubplotSpec: ... def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... def subgridspec( self, nrows: int, ncols: int, **kwargs ) -> GridSpecFromSubplotSpec: ...
class SubplotParams: def __init__( self, left: float | None = ..., bottom: float | None = ..., right: float | None = ..., top: float | None = ..., wspace: float | None = ..., hspace: float | None = ..., ) -> None: ... left: float right: float bottom: float top: float wspace: float hspace: float def update( self, left: float | None = ..., bottom: float | None = ..., right: float | None = ..., top: float | None = ..., wspace: float | None = ..., hspace: float | None = ..., ) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225"""Contains classes for generating hatch patterns."""
import numpy as np
from matplotlib import _apifrom matplotlib.path import Path
class HatchPatternBase: """The base class for a hatch pattern.""" pass
class HorizontalHatch(HatchPatternBase): def __init__(self, hatch, density): self.num_lines = int((hatch.count('-') + hatch.count('+')) * density) self.num_vertices = self.num_lines * 2
def set_vertices_and_codes(self, vertices, codes): steps, stepsize = np.linspace(0.0, 1.0, self.num_lines, False, retstep=True) steps += stepsize / 2. vertices[0::2, 0] = 0.0 vertices[0::2, 1] = steps vertices[1::2, 0] = 1.0 vertices[1::2, 1] = steps codes[0::2] = Path.MOVETO codes[1::2] = Path.LINETO
class VerticalHatch(HatchPatternBase): def __init__(self, hatch, density): self.num_lines = int((hatch.count('|') + hatch.count('+')) * density) self.num_vertices = self.num_lines * 2
def set_vertices_and_codes(self, vertices, codes): steps, stepsize = np.linspace(0.0, 1.0, self.num_lines, False, retstep=True) steps += stepsize / 2. vertices[0::2, 0] = steps vertices[0::2, 1] = 0.0 vertices[1::2, 0] = steps vertices[1::2, 1] = 1.0 codes[0::2] = Path.MOVETO codes[1::2] = Path.LINETO
class NorthEastHatch(HatchPatternBase): def __init__(self, hatch, density): self.num_lines = int( (hatch.count('/') + hatch.count('x') + hatch.count('X')) * density) if self.num_lines: self.num_vertices = (self.num_lines + 1) * 2 else: self.num_vertices = 0
def set_vertices_and_codes(self, vertices, codes): steps = np.linspace(-0.5, 0.5, self.num_lines + 1) vertices[0::2, 0] = 0.0 + steps vertices[0::2, 1] = 0.0 - steps vertices[1::2, 0] = 1.0 + steps vertices[1::2, 1] = 1.0 - steps codes[0::2] = Path.MOVETO codes[1::2] = Path.LINETO
class SouthEastHatch(HatchPatternBase): def __init__(self, hatch, density): self.num_lines = int( (hatch.count('\\') + hatch.count('x') + hatch.count('X')) * density) if self.num_lines: self.num_vertices = (self.num_lines + 1) * 2 else: self.num_vertices = 0
def set_vertices_and_codes(self, vertices, codes): steps = np.linspace(-0.5, 0.5, self.num_lines + 1) vertices[0::2, 0] = 0.0 + steps vertices[0::2, 1] = 1.0 + steps vertices[1::2, 0] = 1.0 + steps vertices[1::2, 1] = 0.0 + steps codes[0::2] = Path.MOVETO codes[1::2] = Path.LINETO
class Shapes(HatchPatternBase): filled = False
def __init__(self, hatch, density): if self.num_rows == 0: self.num_shapes = 0 self.num_vertices = 0 else: self.num_shapes = ((self.num_rows // 2 + 1) * (self.num_rows + 1) + (self.num_rows // 2) * self.num_rows) self.num_vertices = (self.num_shapes * len(self.shape_vertices) * (1 if self.filled else 2))
def set_vertices_and_codes(self, vertices, codes): offset = 1.0 / self.num_rows shape_vertices = self.shape_vertices * offset * self.size shape_codes = self.shape_codes if not self.filled: shape_vertices = np.concatenate( # Forward, then backward. [shape_vertices, shape_vertices[::-1] * 0.9]) shape_codes = np.concatenate([shape_codes, shape_codes]) vertices_parts = [] codes_parts = [] for row in range(self.num_rows + 1): if row % 2 == 0: cols = np.linspace(0, 1, self.num_rows + 1) else: cols = np.linspace(offset / 2, 1 - offset / 2, self.num_rows) row_pos = row * offset for col_pos in cols: vertices_parts.append(shape_vertices + [col_pos, row_pos]) codes_parts.append(shape_codes) np.concatenate(vertices_parts, out=vertices) np.concatenate(codes_parts, out=codes)
class Circles(Shapes): def __init__(self, hatch, density): path = Path.unit_circle() self.shape_vertices = path.vertices self.shape_codes = path.codes super().__init__(hatch, density)
class SmallCircles(Circles): size = 0.2
def __init__(self, hatch, density): self.num_rows = (hatch.count('o')) * density super().__init__(hatch, density)
class LargeCircles(Circles): size = 0.35
def __init__(self, hatch, density): self.num_rows = (hatch.count('O')) * density super().__init__(hatch, density)
class SmallFilledCircles(Circles): size = 0.1 filled = True
def __init__(self, hatch, density): self.num_rows = (hatch.count('.')) * density super().__init__(hatch, density)
class Stars(Shapes): size = 1.0 / 3.0 filled = True
def __init__(self, hatch, density): self.num_rows = (hatch.count('*')) * density path = Path.unit_regular_star(5) self.shape_vertices = path.vertices self.shape_codes = np.full(len(self.shape_vertices), Path.LINETO, dtype=Path.code_type) self.shape_codes[0] = Path.MOVETO super().__init__(hatch, density)
_hatch_types = [ HorizontalHatch, VerticalHatch, NorthEastHatch, SouthEastHatch, SmallCircles, LargeCircles, SmallFilledCircles, Stars ]
def _validate_hatch_pattern(hatch): valid_hatch_patterns = set(r'-+|/\xXoO.*') if hatch is not None: invalids = set(hatch).difference(valid_hatch_patterns) if invalids: valid = ''.join(sorted(valid_hatch_patterns)) invalids = ''.join(sorted(invalids)) _api.warn_deprecated( '3.4', removal='3.11', # one release after custom hatches (#20690) message=f'hatch must consist of a string of "{valid}" or ' 'None, but found the following invalid values ' f'"{invalids}". Passing invalid values is deprecated ' 'since %(since)s and will become an error in %(removal)s.' )
def get_path(hatchpattern, density=6): """ Given a hatch specifier, *hatchpattern*, generates Path to render the hatch in a unit square. *density* is the number of lines per unit square. """ density = int(density)
patterns = [hatch_type(hatchpattern, density) for hatch_type in _hatch_types] num_vertices = sum([pattern.num_vertices for pattern in patterns])
if num_vertices == 0: return Path(np.empty((0, 2)))
vertices = np.empty((num_vertices, 2)) codes = np.empty(num_vertices, Path.code_type)
cursor = 0 for pattern in patterns: if pattern.num_vertices != 0: vertices_chunk = vertices[cursor:cursor + pattern.num_vertices] codes_chunk = codes[cursor:cursor + pattern.num_vertices] pattern.set_vertices_and_codes(vertices_chunk, codes_chunk) cursor += pattern.num_vertices
return Path(vertices, codes)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768from matplotlib.path import Path
import numpy as npfrom numpy.typing import ArrayLike
class HatchPatternBase: ...
class HorizontalHatch(HatchPatternBase): num_lines: int num_vertices: int def __init__(self, hatch: str, density: int) -> None: ... def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
class VerticalHatch(HatchPatternBase): num_lines: int num_vertices: int def __init__(self, hatch: str, density: int) -> None: ... def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
class NorthEastHatch(HatchPatternBase): num_lines: int num_vertices: int def __init__(self, hatch: str, density: int) -> None: ... def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
class SouthEastHatch(HatchPatternBase): num_lines: int num_vertices: int def __init__(self, hatch: str, density: int) -> None: ... def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
class Shapes(HatchPatternBase): filled: bool num_shapes: int num_vertices: int def __init__(self, hatch: str, density: int) -> None: ... def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
class Circles(Shapes): shape_vertices: np.ndarray shape_codes: np.ndarray def __init__(self, hatch: str, density: int) -> None: ...
class SmallCircles(Circles): size: float num_rows: int def __init__(self, hatch: str, density: int) -> None: ...
class LargeCircles(Circles): size: float num_rows: int def __init__(self, hatch: str, density: int) -> None: ...
class SmallFilledCircles(Circles): size: float filled: bool num_rows: int def __init__(self, hatch: str, density: int) -> None: ...
class Stars(Shapes): size: float filled: bool num_rows: int shape_vertices: np.ndarray shape_codes: np.ndarray def __init__(self, hatch: str, density: int) -> None: ...
def get_path(hatchpattern: str, density: int = ...) -> Path: ...1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786"""The image module supports basic image loading, rescaling and displayoperations."""
import mathimport osimport loggingfrom pathlib import Pathimport warnings
import numpy as npimport PIL.Imageimport PIL.PngImagePlugin
import matplotlib as mplfrom matplotlib import _api, cbook# For clarity, names from _image are given explicitly in this modulefrom matplotlib import _image# For user convenience, the names from _image are also imported into# the image namespacefrom matplotlib._image import * # noqa: F401, F403import matplotlib.artist as martistimport matplotlib.colorizer as mcolorizerfrom matplotlib.backend_bases import FigureCanvasBaseimport matplotlib.colors as mcolorsfrom matplotlib.transforms import ( Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo, IdentityTransform, TransformedBbox)
_log = logging.getLogger(__name__)
# map interpolation strings to module constants_interpd_ = { 'auto': _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, 'antialiased': _image.NEAREST, # this will use nearest or Hanning...}
interpolations_names = set(_interpd_)
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 : (M, N, 4) `numpy.uint8` array 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
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()
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 in ['antialiased', 'auto']: # 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
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
class _ImageBase(mcolorizer.ColorizingArtist): """ 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, colorizer=None, interpolation=None, origin=None, filternorm=True, filterrad=4.0, resample=False, *, interpolation_stage=None, **kwargs ): super().__init__(self._get_colorizer(cmap, norm, colorizer)) 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: shape = self.get_shape() return f"{type(self).__name__}(shape={shape!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).""" return self.get_shape()[:2]
def get_shape(self): """ Return the shape of the image as tuple (numrows, numcols, channels). """ if self._A is None: raise RuntimeError('You must first set the image array')
return self._A.shape
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 super().changed()
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.
Parameters ---------- A : ndarray
- a (M, N) array interpreted as scalar (greyscale) image, with one of the dtypes `~numpy.float32`, `~numpy.float64`, `~numpy.float128`, `~numpy.uint16` or `~numpy.uint8`. - (M, N, 4) RGBA image with a dtype of `~numpy.float32`, `~numpy.float64`, `~numpy.float128`, or `~numpy.uint8`.
in_bbox : `~matplotlib.transforms.Bbox`
out_bbox : `~matplotlib.transforms.Bbox`
clip_bbox : `~matplotlib.transforms.Bbox`
magnification : float, default: 1
unsampled : bool, default: False If True, the image will not be scaled, but an appropriate affine transformation will be returned instead.
round_to_pixel_border : bool, default: True If 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) `numpy.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 : `~matplotlib.transforms.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 ((not unsampled) and 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 antialiased, this needs to change as window sizes # change: interpolation_stage = self._interpolation_stage if interpolation_stage in ['antialiased', 'auto']: pos = np.array([[0, 0], [A.shape[1], A.shape[0]]]) disp = t.transform(pos) dispx = np.abs(np.diff(disp[:, 0])) / A.shape[1] dispy = np.abs(np.diff(disp[:, 1])) / A.shape[0] if (dispx < 3) or (dispy < 3): interpolation_stage = 'rgba' else: interpolation_stage = 'data'
if A.ndim == 2 and interpolation_stage == 'data': # 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
if A.dtype.kind == 'f': # Float dtype: scale to same dtype. scaled_dtype = np.dtype("f8" if A.dtype.itemsize > 4 else "f4") 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. # TODO slice input array first # Scale to appropriately sized float: use float32 if the # dynamic range is small, to limit the memory footprint. da = A.max().astype("f8") - A.min().astype("f8") scaled_dtype = "f8" if da > 1e8 else "f4"
# resample the input data to the correct resolution and shape A_resampled = _resample(self, A.astype(scaled_dtype), out_shape, t)
# if using NoNorm, cast back to the original datatype if isinstance(self.norm, mcolors.NoNorm): A_resampled = A_resampled.astype(A.dtype)
# Compute out_mask (what screen pixels include "bad" data # pixels) and out_alpha (to what extent screen pixels are # covered by data pixels: 0 outside the data extent, 1 inside # (even for bad data), and intermediate values at the edges). 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! 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) output = self.norm(resampled_masked) else: if A.ndim == 2: # interpolation_stage = 'rgba' self.norm.autoscale_None(A) A = self.to_rgba(A) alpha = self.get_alpha() if alpha is None: # alpha parameter not specified if A.shape[2] == 3: # image has no alpha channel output_alpha = 255 if A.dtype == np.uint8 else 1.0 else: output_alpha = _resample( # resample alpha channel self, A[..., 3], out_shape, t) output = _resample( # resample rgb channels self, _rgb_to_rgba(A[..., :3]), out_shape, t) elif np.ndim(alpha) > 0: # Array alpha # user-specified array alpha overrides the existing alpha channel output_alpha = _resample(self, alpha, out_shape, t) output = _resample( self, _rgb_to_rgba(A[..., :3]), out_shape, t) else: # Scalar alpha if A.shape[2] == 3: # broadcast scalar alpha output_alpha = (255 * alpha) if A.dtype == np.uint8 else alpha else: # or apply scalar alpha to existing alpha channel output_alpha = _resample(self, A[..., 3], out_shape, t) * alpha output = _resample( self, _rgb_to_rgba(A[..., :3]), out_shape, t) 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) `numpy.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 : `~matplotlib.transforms.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
@martist.allow_rasterization def draw(self, renderer): # 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.""" if (self._different_canvas(mouseevent) # This doesn't work for figimage. or not self.axes.contains(mouseevent)[0]): 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() # This checks xmin <= x <= xmax *or* xmax <= x <= xmin. inside = (x is not None and (x - xmin) * (x - xmax) <= 0 and y is not None and (y - ymin) * (y - ymax) <= 0) 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")
@staticmethod def _normalize_image_array(A): """ Check validity of image-like input *A* and normalize it to a format suitable for Image subclasses. """ A = cbook.safe_masked_invalid(A, copy=True) if A.dtype != np.uint8 and not np.can_cast(A.dtype, float, "same_kind"): raise TypeError(f"Image data of dtype {A.dtype} cannot be " f"converted to float") if A.ndim == 3 and A.shape[-1] == 1: A = A.squeeze(-1) # If just (M, N, 1), assume scalar and apply colormap. if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in [3, 4]): raise TypeError(f"Invalid shape {A.shape} for image data") if 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(A.dtype, np.integer) else 1 if A.min() < 0 or high < 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). ' 'Got range [%s..%s].', A.min(), A.max() ) A = np.clip(A, 0, high) # Cast unsupported integer types to uint8 if A.dtype != np.uint8 and np.issubdtype(A.dtype, np.integer): A = A.astype(np.uint8) return A
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 = self._normalize_image_array(A) 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 'auto', '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 : {'auto', 'nearest', 'bilinear', 'bicubic', 'spline16', \'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', \'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'} or None """ s = mpl._val_or_rc(s, 'image.interpolation').lower() _api.check_in_list(interpolations_names, interpolation=s) self._interpolation = s self.stale = True
def get_interpolation_stage(self): """ Return when interpolation happens during the transform to RGBA.
One of 'data', 'rgba', 'auto'. """ return self._interpolation_stage
def set_interpolation_stage(self, s): """ Set when interpolation happens during the transform to RGBA.
Parameters ---------- s : {'data', 'rgba', 'auto'} or None Whether to apply up/downsampling interpolation in data or RGBA space. If None, use :rc:`image.interpolation_stage`. If 'auto' we will check upsampling rate and if less than 3 then use 'rgba', otherwise use 'data'. """ s = mpl._val_or_rc(s, 'image.interpolation_stage') _api.check_in_list(['data', 'rgba', 'auto'], 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`. """ v = mpl._val_or_rc(v, '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
class AxesImage(_ImageBase): """ An image with pixels on a regular grid, attached to an Axes.
Parameters ---------- ax : `~matplotlib.axes.Axes` The Axes the image will belong to. cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` The Colormap instance or registered colormap name used to map scalar data to colors. norm : str or `~matplotlib.colors.Normalize` Maps luminance to 0-1. interpolation : str, default: :rc:`image.interpolation` Supported values are 'none', 'auto', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'blackman'. interpolation_stage : {'data', 'rgba'}, default: 'data' If 'data', interpolation is carried out on the data provided by the user. If 'rgba', the interpolation is carried out after the colormapping has been applied (visual interpolation). origin : {'upper', 'lower'}, default: :rc:`image.origin` Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention 'upper' is typically used for matrices and images. extent : tuple, optional The 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. filternorm : bool, default: True A parameter for the antigrain image resize filter (see the antigrain documentation). If filternorm is set, the filter normalizes integer values and corrects the rounding errors. It doesn't do anything with the source floating point values, it corrects only integers according to the rule of 1.0 which means that any sum of pixel weights must be equal to 1.0. So, the filter function must produce a graph of the proper shape. filterrad : float > 0, default: 4 The filter radius for filters that have a radius parameter, i.e. when interpolation is one of: 'sinc', 'lanczos' or 'blackman'. resample : bool, default: False When True, use a full resampling method. When False, only resample when the output image is larger than the input image. **kwargs : `~matplotlib.artist.Artist` properties """
def __init__(self, ax, *, cmap=None, norm=None, colorizer=None, interpolation=None, origin=None, extent=None, filternorm=True, filterrad=4.0, resample=False, interpolation_stage=None, **kwargs ):
self._extent = extent
super().__init__( ax, cmap=cmap, norm=norm, colorizer=colorizer, interpolation=interpolation, origin=origin, filternorm=filternorm, filterrad=filterrad, resample=resample, interpolation_stage=interpolation_stage, **kwargs )
def get_window_extent(self, renderer=None): x0, x1, y0, y1 = self._extent bbox = Bbox.from_extents([x0, y0, x1, y1]) return bbox.transformed(self.get_transform())
def make_image(self, renderer, magnification=1.0, unsampled=False): # docstring inherited trans = self.get_transform() # image is created in the canvas coordinate. x1, x2, y1, y2 = self.get_extent() bbox = Bbox(np.array([[x1, y1], [x2, y2]])) transformed_bbox = TransformedBbox(bbox, trans) clip = ((self.get_clip_box() or self.axes.bbox) if self.get_clip_on() else self.get_figure(root=True).bbox) return self._make_image(self._A, bbox, transformed_bbox, clip, magnification, unsampled=unsampled)
def _check_unsampled_image(self): """Return whether the image would be better drawn unsampled.""" return self.get_interpolation() == "none"
def set_extent(self, extent, **kwargs): """ Set the image extent.
Parameters ---------- extent : 4-tuple of float The position and size of the image as tuple ``(left, right, bottom, top)`` in data coordinates. **kwargs Other parameters from which unit info (i.e., the *xunits*, *yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for polar Axes) entries are applied, if present.
Notes ----- This updates `.Axes.dataLim`, and, if autoscaling, sets `.Axes.viewLim` to tightly fit the image, regardless of `~.Axes.dataLim`. Autoscaling state is not changed, so a subsequent call to `.Axes.autoscale_view` will redo the autoscaling in accord with `~.Axes.dataLim`. """ (xmin, xmax), (ymin, ymax) = self.axes._process_unit_info( [("x", [extent[0], extent[1]]), ("y", [extent[2], extent[3]])], kwargs) if kwargs: raise _api.kwarg_error("set_extent", kwargs) xmin = self.axes._validate_converted_limits( xmin, self.convert_xunits) xmax = self.axes._validate_converted_limits( xmax, self.convert_xunits) ymin = self.axes._validate_converted_limits( ymin, self.convert_yunits) ymax = self.axes._validate_converted_limits( ymax, self.convert_yunits) extent = [xmin, xmax, ymin, ymax]
self._extent = extent corners = (xmin, ymin), (xmax, ymax) self.axes.update_datalim(corners) self.sticky_edges.x[:] = [xmin, xmax] self.sticky_edges.y[:] = [ymin, ymax] if self.axes.get_autoscalex_on(): self.axes.set_xlim((xmin, xmax), auto=None) if self.axes.get_autoscaley_on(): self.axes.set_ylim((ymin, ymax), auto=None) self.stale = True
def get_extent(self): """Return the image extent as tuple (left, right, bottom, top).""" if self._extent is not None: return self._extent else: sz = self.get_size() numrows, numcols = sz if self.origin == 'upper': return (-0.5, numcols-0.5, numrows-0.5, -0.5) else: return (-0.5, numcols-0.5, -0.5, numrows-0.5)
def get_cursor_data(self, event): """ Return the image value at the event position or *None* if the event is outside the image.
See Also -------- matplotlib.artist.Artist.get_cursor_data """ xmin, xmax, ymin, ymax = self.get_extent() if self.origin == 'upper': ymin, ymax = ymax, ymin arr = self.get_array() data_extent = Bbox([[xmin, ymin], [xmax, ymax]]) array_extent = Bbox([[0, 0], [arr.shape[1], arr.shape[0]]]) trans = self.get_transform().inverted() trans += BboxTransform(boxin=data_extent, boxout=array_extent) point = trans.transform([event.x, event.y]) if any(np.isnan(point)): return None j, i = point.astype(int) # Clip the coordinates at array bounds if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]): return None else: return arr[i, j]
class NonUniformImage(AxesImage): """ An image with pixels on a rectilinear grid.
In contrast to `.AxesImage`, where pixels are on a regular grid, NonUniformImage allows rows and columns with individual heights / widths.
See also :doc:`/gallery/images_contours_and_fields/image_nonuniform`. """
def __init__(self, ax, *, interpolation='nearest', **kwargs): """ Parameters ---------- ax : `~matplotlib.axes.Axes` The Axes the image will belong to. interpolation : {'nearest', 'bilinear'}, default: 'nearest' The interpolation scheme used in the resampling. **kwargs All other keyword arguments are identical to those of `.AxesImage`. """ super().__init__(ax, **kwargs) self.set_interpolation(interpolation)
def _check_unsampled_image(self): """Return False. Do not use unsampled image.""" return False
def make_image(self, renderer, magnification=1.0, unsampled=False): # docstring inherited if self._A is None: raise RuntimeError('You must first set the image array') if unsampled: raise ValueError('unsampled not supported on NonUniformImage') A = self._A if A.ndim == 2: if A.dtype != np.uint8: A = self.to_rgba(A, bytes=True) else: A = np.repeat(A[:, :, np.newaxis], 4, 2) A[:, :, 3] = 255 else: if A.dtype != np.uint8: A = (255*A).astype(np.uint8) if A.shape[2] == 3: B = np.zeros(tuple([*A.shape[0:2], 4]), np.uint8) B[:, :, 0:3] = A B[:, :, 3] = 255 A = B l, b, r, t = self.axes.bbox.extents width = int(((round(r) + 0.5) - (round(l) - 0.5)) * magnification) height = int(((round(t) + 0.5) - (round(b) - 0.5)) * magnification)
invertedTransform = self.axes.transData.inverted() x_pix = invertedTransform.transform( [(x, b) for x in np.linspace(l, r, width)])[:, 0] y_pix = invertedTransform.transform( [(l, y) for y in np.linspace(b, t, height)])[:, 1]
if self._interpolation == "nearest": x_mid = (self._Ax[:-1] + self._Ax[1:]) / 2 y_mid = (self._Ay[:-1] + self._Ay[1:]) / 2 x_int = x_mid.searchsorted(x_pix) y_int = y_mid.searchsorted(y_pix) # The following is equal to `A[y_int[:, None], x_int[None, :]]`, # but many times faster. Both casting to uint32 (to have an # effectively 1D array) and manual index flattening matter. im = ( np.ascontiguousarray(A).view(np.uint32).ravel()[ np.add.outer(y_int * A.shape[1], x_int)] .view(np.uint8).reshape((height, width, 4))) else: # self._interpolation == "bilinear" # Use np.interp to compute x_int/x_float has similar speed. x_int = np.clip( self._Ax.searchsorted(x_pix) - 1, 0, len(self._Ax) - 2) y_int = np.clip( self._Ay.searchsorted(y_pix) - 1, 0, len(self._Ay) - 2) idx_int = np.add.outer(y_int * A.shape[1], x_int) x_frac = np.clip( np.divide(x_pix - self._Ax[x_int], np.diff(self._Ax)[x_int], dtype=np.float32), # Downcasting helps with speed. 0, 1) y_frac = np.clip( np.divide(y_pix - self._Ay[y_int], np.diff(self._Ay)[y_int], dtype=np.float32), 0, 1) f00 = np.outer(1 - y_frac, 1 - x_frac) f10 = np.outer(y_frac, 1 - x_frac) f01 = np.outer(1 - y_frac, x_frac) f11 = np.outer(y_frac, x_frac) im = np.empty((height, width, 4), np.uint8) for chan in range(4): ac = A[:, :, chan].reshape(-1) # reshape(-1) avoids a copy. # Shifting the buffer start (`ac[offset:]`) avoids an array # addition (`ac[idx_int + offset]`). buf = f00 * ac[idx_int] buf += f10 * ac[A.shape[1]:][idx_int] buf += f01 * ac[1:][idx_int] buf += f11 * ac[A.shape[1] + 1:][idx_int] im[:, :, chan] = buf # Implicitly casts to uint8. return im, l, b, IdentityTransform()
def set_data(self, x, y, A): """ Set the grid for the pixel centers, and the pixel values.
Parameters ---------- x, y : 1D array-like Monotonic arrays of shapes (N,) and (M,), respectively, specifying pixel centers. A : array-like (M, N) `~numpy.ndarray` or masked array of values to be colormapped, or (M, N, 3) RGB array, or (M, N, 4) RGBA array. """ A = self._normalize_image_array(A) x = np.array(x, np.float32) y = np.array(y, np.float32) if not (x.ndim == y.ndim == 1 and A.shape[:2] == y.shape + x.shape): raise TypeError("Axes don't match array shape") self._A = A self._Ax = x self._Ay = y self._imcache = None self.stale = True
def set_array(self, *args): raise NotImplementedError('Method not supported')
def set_interpolation(self, s): """ Parameters ---------- s : {'nearest', 'bilinear'} or None If None, use :rc:`image.interpolation`. """ if s is not None and s not in ('nearest', 'bilinear'): raise NotImplementedError('Only nearest neighbor and ' 'bilinear interpolations are supported') super().set_interpolation(s)
def get_extent(self): if self._A is None: raise RuntimeError('Must set data first') return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1]
def set_filternorm(self, filternorm): pass
def set_filterrad(self, filterrad): pass
def set_norm(self, norm): if self._A is not None: raise RuntimeError('Cannot change colors after loading data') super().set_norm(norm)
def set_cmap(self, cmap): if self._A is not None: raise RuntimeError('Cannot change colors after loading data') super().set_cmap(cmap)
def get_cursor_data(self, event): # docstring inherited x, y = event.xdata, event.ydata if (x < self._Ax[0] or x > self._Ax[-1] or y < self._Ay[0] or y > self._Ay[-1]): return None j = np.searchsorted(self._Ax, x) - 1 i = np.searchsorted(self._Ay, y) - 1 return self._A[i, j]
class PcolorImage(AxesImage): """ Make a pcolor-style plot with an irregular rectangular grid.
This uses a variation of the original irregular image code, and it is used by pcolorfast for the corresponding grid type. """
def __init__(self, ax, x=None, y=None, A=None, *, cmap=None, norm=None, colorizer=None, **kwargs ): """ Parameters ---------- ax : `~matplotlib.axes.Axes` The Axes the image will belong to. x, y : 1D array-like, optional Monotonic arrays of length N+1 and M+1, respectively, specifying rectangle boundaries. If not given, will default to ``range(N + 1)`` and ``range(M + 1)``, respectively. A : array-like The data to be color-coded. The interpretation depends on the shape:
- (M, N) `~numpy.ndarray` or masked array: values to be colormapped - (M, N, 3): RGB array - (M, N, 4): RGBA array
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` The Colormap instance or registered colormap name used to map scalar data to colors. norm : str or `~matplotlib.colors.Normalize` Maps luminance to 0-1. **kwargs : `~matplotlib.artist.Artist` properties """ super().__init__(ax, norm=norm, cmap=cmap, colorizer=colorizer) self._internal_update(kwargs) if A is not None: self.set_data(x, y, A)
def make_image(self, renderer, magnification=1.0, unsampled=False): # docstring inherited if self._A is None: raise RuntimeError('You must first set the image array') if unsampled: raise ValueError('unsampled not supported on PColorImage')
if self._imcache is None: A = self.to_rgba(self._A, bytes=True) self._imcache = np.pad(A, [(1, 1), (1, 1), (0, 0)], "constant") padded_A = self._imcache bg = mcolors.to_rgba(self.axes.patch.get_facecolor(), 0) bg = (np.array(bg) * 255).astype(np.uint8) if (padded_A[0, 0] != bg).all(): padded_A[[0, -1], :] = padded_A[:, [0, -1]] = bg
l, b, r, t = self.axes.bbox.extents width = (round(r) + 0.5) - (round(l) - 0.5) height = (round(t) + 0.5) - (round(b) - 0.5) width = round(width * magnification) height = round(height * magnification) vl = self.axes.viewLim
x_pix = np.linspace(vl.x0, vl.x1, width) y_pix = np.linspace(vl.y0, vl.y1, height) x_int = self._Ax.searchsorted(x_pix) y_int = self._Ay.searchsorted(y_pix) im = ( # See comment in NonUniformImage.make_image re: performance. padded_A.view(np.uint32).ravel()[ np.add.outer(y_int * padded_A.shape[1], x_int)] .view(np.uint8).reshape((height, width, 4))) return im, l, b, IdentityTransform()
def _check_unsampled_image(self): return False
def set_data(self, x, y, A): """ Set the grid for the rectangle boundaries, and the data values.
Parameters ---------- x, y : 1D array-like, optional Monotonic arrays of length N+1 and M+1, respectively, specifying rectangle boundaries. If not given, will default to ``range(N + 1)`` and ``range(M + 1)``, respectively. A : array-like The data to be color-coded. The interpretation depends on the shape:
- (M, N) `~numpy.ndarray` or masked array: values to be colormapped - (M, N, 3): RGB array - (M, N, 4): RGBA array """ A = self._normalize_image_array(A) x = np.arange(0., A.shape[1] + 1) if x is None else np.array(x, float).ravel() y = np.arange(0., A.shape[0] + 1) if y is None else np.array(y, float).ravel() if A.shape[:2] != (y.size - 1, x.size - 1): raise ValueError( "Axes don't match array shape. Got %s, expected %s." % (A.shape[:2], (y.size - 1, x.size - 1))) # For efficient cursor readout, ensure x and y are increasing. if x[-1] < x[0]: x = x[::-1] A = A[:, ::-1] if y[-1] < y[0]: y = y[::-1] A = A[::-1] self._A = A self._Ax = x self._Ay = y self._imcache = None self.stale = True
def set_array(self, *args): raise NotImplementedError('Method not supported')
def get_cursor_data(self, event): # docstring inherited x, y = event.xdata, event.ydata if (x < self._Ax[0] or x > self._Ax[-1] or y < self._Ay[0] or y > self._Ay[-1]): return None j = np.searchsorted(self._Ax, x) - 1 i = np.searchsorted(self._Ay, y) - 1 return self._A[i, j]
class FigureImage(_ImageBase): """An image attached to a figure."""
zorder = 0
_interpolation = 'nearest'
def __init__(self, fig, *, cmap=None, norm=None, colorizer=None, offsetx=0, offsety=0, origin=None, **kwargs ): """ cmap is a colors.Colormap instance norm is a colors.Normalize instance to map luminance to 0-1
kwargs are an optional list of Artist keyword args """ super().__init__( None, norm=norm, cmap=cmap, colorizer=colorizer, origin=origin ) self.set_figure(fig) self.ox = offsetx self.oy = offsety self._internal_update(kwargs) self.magnification = 1.0
def get_extent(self): """Return the image extent as tuple (left, right, bottom, top).""" numrows, numcols = self.get_size() return (-0.5 + self.ox, numcols-0.5 + self.ox, -0.5 + self.oy, numrows-0.5 + self.oy)
def make_image(self, renderer, magnification=1.0, unsampled=False): # docstring inherited fig = self.get_figure(root=True) fac = renderer.dpi/fig.dpi # fac here is to account for pdf, eps, svg backends where # figure.dpi is set to 72. This means we need to scale the # image (using magnification) and offset it appropriately. bbox = Bbox([[self.ox/fac, self.oy/fac], [(self.ox/fac + self._A.shape[1]), (self.oy/fac + self._A.shape[0])]]) width, height = fig.get_size_inches() width *= renderer.dpi height *= renderer.dpi clip = Bbox([[0, 0], [width, height]]) return self._make_image( self._A, bbox, bbox, clip, magnification=magnification / fac, unsampled=unsampled, round_to_pixel_border=False)
def set_data(self, A): """Set the image array.""" super().set_data(A) self.stale = True
class BboxImage(_ImageBase): """The Image class whose size is determined by the given bbox."""
def __init__(self, bbox, *, cmap=None, norm=None, colorizer=None, interpolation=None, origin=None, filternorm=True, filterrad=4.0, resample=False, **kwargs ): """ cmap is a colors.Colormap instance norm is a colors.Normalize instance to map luminance to 0-1
kwargs are an optional list of Artist keyword args """ super().__init__( None, cmap=cmap, norm=norm, colorizer=colorizer, interpolation=interpolation, origin=origin, filternorm=filternorm, filterrad=filterrad, resample=resample, **kwargs ) self.bbox = bbox
def get_window_extent(self, renderer=None): if renderer is None: renderer = self.get_figure()._get_renderer()
if isinstance(self.bbox, BboxBase): return self.bbox elif callable(self.bbox): return self.bbox(renderer) else: raise ValueError("Unknown type of bbox")
def contains(self, mouseevent): """Test whether the mouse event occurred within the image.""" if self._different_canvas(mouseevent) or not self.get_visible(): return False, {} x, y = mouseevent.x, mouseevent.y inside = self.get_window_extent().contains(x, y) return inside, {}
def make_image(self, renderer, magnification=1.0, unsampled=False): # docstring inherited width, height = renderer.get_canvas_width_height() bbox_in = self.get_window_extent(renderer).frozen() bbox_in._points /= [width, height] bbox_out = self.get_window_extent(renderer) clip = Bbox([[0, 0], [width, height]]) self._transform = BboxTransformTo(clip) return self._make_image( self._A, bbox_in, bbox_out, clip, magnification, unsampled=unsampled)
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))
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. Accepts NumPy arrays or sequences (e.g., lists or tuples). 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. Currently only supported for "png", "pdf", "ps", "eps", and "svg". 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
# Normalizing input (e.g., list or tuples) to NumPy array if needed arr = np.asanyarray(arr)
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"] else: _api.check_in_list(('upper', 'lower'), origin=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 = mcolorizer.Colorizer(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]) rgba = np.require(rgba, requirements='C') 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) elif metadata is not None: raise ValueError(f"metadata not supported for format {format!r}") 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)
def pil_to_array(pilImage): """ Load a `PIL image`_ and return it as a numpy int array.
.. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
Returns ------- numpy.array
The array shape depends on the image type:
- (M, N) for grayscale images. - (M, N, 3) for RGB images. - (M, N, 4) for RGBA images. """ if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']: # return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array return np.asarray(pilImage) elif pilImage.mode.startswith('I;16'): # return MxN luminance array of uint16 raw = pilImage.tobytes('raw', pilImage.mode) if pilImage.mode.endswith('B'): x = np.frombuffer(raw, '>u2') else: x = np.frombuffer(raw, '<u2') return x.reshape(pilImage.size[::-1]).astype('=u2') else: # try to convert to an rgba image try: pilImage = pilImage.convert('RGBA') except ValueError as err: raise RuntimeError('Unknown image mode') from err return np.asarray(pilImage) # return MxNx4 RGBA array
def _pil_png_to_float_array(pil_png): """Convert a PIL `PNGImageFile` to a 0-1 float array.""" # Unlike pil_to_array this converts to 0-1 float32s for backcompat with the # old libpng-based loader. # The supported rawmodes are from PIL.PngImagePlugin._MODES. When # mode == "RGB(A)", the 16-bit raw data has already been coarsened to 8-bit # by Pillow. mode = pil_png.mode rawmode = pil_png.png.im_rawmode if rawmode == "1": # Grayscale. return np.asarray(pil_png, np.float32) if rawmode == "L;2": # Grayscale. return np.divide(pil_png, 2**2 - 1, dtype=np.float32) if rawmode == "L;4": # Grayscale. return np.divide(pil_png, 2**4 - 1, dtype=np.float32) if rawmode == "L": # Grayscale. return np.divide(pil_png, 2**8 - 1, dtype=np.float32) if rawmode == "I;16B": # Grayscale. return np.divide(pil_png, 2**16 - 1, dtype=np.float32) if mode == "RGB": # RGB. return np.divide(pil_png, 2**8 - 1, dtype=np.float32) if mode == "P": # Palette. return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32) if mode == "LA": # Grayscale + alpha. return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32) if mode == "RGBA": # RGBA. return np.divide(pil_png, 2**8 - 1, dtype=np.float32) raise ValueError(f"Unknown PIL rawmode: {rawmode}")
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.github.io
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 fig12345678910111213141516171819202122232425from . import artistfrom .axes import Axesfrom .backend_bases import RendererBasefrom .patches import ConnectionPatch, Rectangle
from .typing import ColorType, LineStyleType
class InsetIndicator(artist.Artist): def __init__( self, bounds: tuple[float, float, float, float] | None = ..., inset_ax: Axes | None = ..., zorder: float | None = ..., **kwargs ) -> None: ... def set_alpha(self, alpha: float | None) -> None: ... def set_edgecolor(self, color: ColorType | None) -> None: ... def set_color(self, c: ColorType | None) -> None: ... def set_linewidth(self, w: float | None) -> None: ... def set_linestyle(self, ls: LineStyleType | None) -> None: ... @property def rectangle(self) -> Rectangle: ... @property def connectors(self) -> tuple[ConnectionPatch, ConnectionPatch, ConnectionPatch, ConnectionPatch] | None: ... def draw(self, renderer: RendererBase) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813"""Default legend handlers.
.. important::
This is a low-level legend API, which most end users do not need.
We recommend that you are familiar with the :ref:`legend guide <legend_guide>` before reading this documentation.
Legend handlers are expected to be a callable object with a followingsignature::
legend_handler(legend, orig_handle, fontsize, handlebox)
Where *legend* is the legend itself, *orig_handle* is the originalplot, *fontsize* is the fontsize in pixels, and *handlebox* is an`.OffsetBox` instance. Within the call, you should create relevantartists (using relevant properties from the *legend* and/or*orig_handle*) and add them into the *handlebox*. The artists need tobe scaled according to the *fontsize* (note that the size is in pixels,i.e., this is dpi-scaled value).
This module includes definition of several legend handler classesderived from the base class (HandlerBase) with the following method::
def legend_artist(self, legend, orig_handle, fontsize, handlebox)"""
from itertools import cycle
import numpy as np
from matplotlib import cbookfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Rectangleimport 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)
class HandlerBase: """ A base class for default legend handlers.
The derived classes are meant to override *create_artists* method, which has the following signature::
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
The overridden method needs to create artists of the given transform that fits in the given dimension (xdescent, ydescent, width, height) that are scaled by fontsize if necessary.
""" def __init__(self, xpad=0., ypad=0., update_func=None): """ Parameters ---------- xpad : float, optional Padding in x-direction. ypad : float, optional Padding in y-direction. update_func : callable, optional Function for updating the legend handler properties from another legend handler, used by `~HandlerBase.update_prop`. """ self._xpad, self._ypad = xpad, ypad self._update_prop_func = update_func
def _update_prop(self, legend_handle, orig_handle): if self._update_prop_func is None: self._default_update_prop(legend_handle, orig_handle) else: self._update_prop_func(legend_handle, orig_handle)
def _default_update_prop(self, legend_handle, orig_handle): legend_handle.update_from(orig_handle)
def update_prop(self, legend_handle, orig_handle, legend):
self._update_prop(legend_handle, orig_handle)
legend._set_artist_props(legend_handle) legend_handle.set_clip_box(None) legend_handle.set_clip_path(None)
def adjust_drawing_area(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, ): xdescent = xdescent - self._xpad * fontsize ydescent = ydescent - self._ypad * fontsize width = width - self._xpad * fontsize height = height - self._ypad * fontsize return xdescent, ydescent, width, height
def legend_artist(self, legend, orig_handle, fontsize, handlebox): """ Return the artist that this HandlerBase generates for the given original artist/handle.
Parameters ---------- legend : `~matplotlib.legend.Legend` The legend for which these legend artists are being created. orig_handle : :class:`matplotlib.artist.Artist` or similar The object for which these legend artists are being created. fontsize : int The fontsize in pixels. The artists being created should be scaled according to the given fontsize. handlebox : `~matplotlib.offsetbox.OffsetBox` The box which has been created to hold this legend entry's artists. Artists created in the `legend_artist` method must be added to this handlebox inside this method.
""" xdescent, ydescent, width, height = self.adjust_drawing_area( legend, orig_handle, handlebox.xdescent, handlebox.ydescent, handlebox.width, handlebox.height, fontsize) artists = self.create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, handlebox.get_transform())
# create_artists will return a list of artists. for a in artists: handlebox.add_artist(a)
# we only return the first artist return artists[0]
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): """ Return the legend artists generated.
Parameters ---------- legend : `~matplotlib.legend.Legend` The legend for which these legend artists are being created. orig_handle : `~matplotlib.artist.Artist` or similar The object for which these legend artists are being created. xdescent, ydescent, width, height : int The rectangle (*xdescent*, *ydescent*, *width*, *height*) that the legend artists being created should fit within. fontsize : int The fontsize in pixels. The legend artists being created should be scaled according to the given fontsize. trans : `~matplotlib.transforms.Transform` The transform that is applied to the legend artists being created. Typically from unit coordinates in the handler box to screen coordinates. """ raise NotImplementedError('Derived must override')
class HandlerNpoints(HandlerBase): """ A legend handler that shows *numpoints* points in the legend entry. """
def __init__(self, marker_pad=0.3, numpoints=None, **kwargs): """ Parameters ---------- marker_pad : float Padding between points in legend entry. numpoints : int Number of points to show in legend entry. **kwargs Keyword arguments forwarded to `.HandlerBase`. """ super().__init__(**kwargs)
self._numpoints = numpoints self._marker_pad = marker_pad
def get_numpoints(self, legend): if self._numpoints is None: return legend.numpoints else: return self._numpoints
def get_xdata(self, legend, xdescent, ydescent, width, height, fontsize): numpoints = self.get_numpoints(legend) if numpoints > 1: # we put some pad here to compensate the size of the marker pad = self._marker_pad * fontsize xdata = np.linspace(-xdescent + pad, -xdescent + width - pad, numpoints) xdata_marker = xdata else: xdata = [-xdescent, -xdescent + width] xdata_marker = [-xdescent + 0.5 * width] return xdata, xdata_marker
class HandlerNpointsYoffsets(HandlerNpoints): """ A legend handler that shows *numpoints* in the legend, and allows them to be individually offset in the y-direction. """
def __init__(self, numpoints=None, yoffsets=None, **kwargs): """ Parameters ---------- numpoints : int Number of points to show in legend entry. yoffsets : array of floats Length *numpoints* list of y offsets for each point in legend entry. **kwargs Keyword arguments forwarded to `.HandlerNpoints`. """ super().__init__(numpoints=numpoints, **kwargs) self._yoffsets = yoffsets
def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize): if self._yoffsets is None: ydata = height * legend._scatteryoffsets else: ydata = height * np.asarray(self._yoffsets)
return ydata
class HandlerLine2DCompound(HandlerNpoints): """ Original handler for `.Line2D` instances, that relies on combining a line-only with a marker-only artist. May be deprecated in the future. """
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, width, height, fontsize)
ydata = np.full_like(xdata, ((height - ydescent) / 2)) legline = Line2D(xdata, ydata)
self.update_prop(legline, orig_handle, legend) legline.set_drawstyle('default') legline.set_marker("")
legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)]) self.update_prop(legline_marker, orig_handle, legend) legline_marker.set_linestyle('None') if legend.markerscale != 1: newsz = legline_marker.get_markersize() * legend.markerscale legline_marker.set_markersize(newsz) # we don't want to add this to the return list because # the texts and handles are assumed to be in one-to-one # correspondence. legline._legmarker = legline_marker
legline.set_transform(trans) legline_marker.set_transform(trans)
return [legline, legline_marker]
class HandlerLine2D(HandlerNpoints): """ Handler for `.Line2D` instances.
See Also -------- HandlerLine2DCompound : An earlier handler implementation, which used one artist for the line and another for the marker(s). """
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, width, height, fontsize)
markevery = None if self.get_numpoints(legend) == 1: # Special case: one wants a single marker in the center # and a line that extends on both sides. One will use a # 3 points line, but only mark the #1 (i.e. middle) point. xdata = np.linspace(xdata[0], xdata[-1], 3) markevery = [1]
ydata = np.full_like(xdata, (height - ydescent) / 2) legline = Line2D(xdata, ydata, markevery=markevery)
self.update_prop(legline, orig_handle, legend)
if legend.markerscale != 1: newsz = legline.get_markersize() * legend.markerscale legline.set_markersize(newsz)
legline.set_transform(trans)
return [legline]
class HandlerPatch(HandlerBase): """ Handler for `.Patch` instances. """
def __init__(self, patch_func=None, **kwargs): """ Parameters ---------- patch_func : callable, optional The function that creates the legend key artist. *patch_func* should have the signature::
def patch_func(legend=legend, orig_handle=orig_handle, xdescent=xdescent, ydescent=ydescent, width=width, height=height, fontsize=fontsize)
Subsequently, the created artist will have its ``update_prop`` method called and the appropriate transform will be applied.
**kwargs Keyword arguments forwarded to `.HandlerBase`. """ super().__init__(**kwargs) self._patch_func = patch_func
def _create_patch(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize): if self._patch_func is None: p = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) else: p = self._patch_func(legend=legend, orig_handle=orig_handle, xdescent=xdescent, ydescent=ydescent, width=width, height=height, fontsize=fontsize) return p
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited p = self._create_patch(legend, orig_handle, xdescent, ydescent, width, height, fontsize) self.update_prop(p, orig_handle, legend) p.set_transform(trans) return [p]
class HandlerStepPatch(HandlerBase): """ Handler for `~.matplotlib.patches.StepPatch` instances. """
@staticmethod def _create_patch(orig_handle, xdescent, ydescent, width, height): return Rectangle(xy=(-xdescent, -ydescent), width=width, height=height, color=orig_handle.get_facecolor())
@staticmethod def _create_line(orig_handle, width, height): # Unfilled StepPatch should show as a line legline = Line2D([0, width], [height/2, height/2], color=orig_handle.get_edgecolor(), linestyle=orig_handle.get_linestyle(), linewidth=orig_handle.get_linewidth(), )
# Overwrite manually because patch and line properties don't mix legline.set_drawstyle('default') legline.set_marker("") return legline
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited if orig_handle.get_fill() or (orig_handle.get_hatch() is not None): p = self._create_patch(orig_handle, xdescent, ydescent, width, height) self.update_prop(p, orig_handle, legend) else: p = self._create_line(orig_handle, width, height) p.set_transform(trans) return [p]
class HandlerLineCollection(HandlerLine2D): """ Handler for `.LineCollection` instances. """ def get_numpoints(self, legend): if self._numpoints is None: return legend.scatterpoints else: return self._numpoints
def _default_update_prop(self, legend_handle, orig_handle): lw = orig_handle.get_linewidths()[0] dashes = orig_handle._us_linestyles[0] color = orig_handle.get_colors()[0] legend_handle.set_color(color) legend_handle.set_linestyle(dashes) legend_handle.set_linewidth(lw)
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, width, height, fontsize) ydata = np.full_like(xdata, (height - ydescent) / 2) legline = Line2D(xdata, ydata)
self.update_prop(legline, orig_handle, legend) legline.set_transform(trans)
return [legline]
class HandlerRegularPolyCollection(HandlerNpointsYoffsets): r"""Handler for `.RegularPolyCollection`\s."""
def __init__(self, yoffsets=None, sizes=None, **kwargs): super().__init__(yoffsets=yoffsets, **kwargs)
self._sizes = sizes
def get_numpoints(self, legend): if self._numpoints is None: return legend.scatterpoints else: return self._numpoints
def get_sizes(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize): if self._sizes is None: handle_sizes = orig_handle.get_sizes() if not len(handle_sizes): handle_sizes = [1] size_max = max(handle_sizes) * legend.markerscale ** 2 size_min = min(handle_sizes) * legend.markerscale ** 2
numpoints = self.get_numpoints(legend) if numpoints < 4: sizes = [.5 * (size_max + size_min), size_max, size_min][:numpoints] else: rng = (size_max - size_min) sizes = rng * np.linspace(0, 1, numpoints) + size_min else: sizes = self._sizes
return sizes
def update_prop(self, legend_handle, orig_handle, legend):
self._update_prop(legend_handle, orig_handle)
legend_handle.set_figure(legend.get_figure(root=False)) # legend._set_artist_props(legend_handle) legend_handle.set_clip_box(None) legend_handle.set_clip_path(None)
def create_collection(self, orig_handle, sizes, offsets, offset_transform): return type(orig_handle)( orig_handle.get_numsides(), rotation=orig_handle.get_rotation(), sizes=sizes, offsets=offsets, offset_transform=offset_transform, )
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, width, height, fontsize)
ydata = self.get_ydata(legend, xdescent, ydescent, width, height, fontsize)
sizes = self.get_sizes(legend, orig_handle, xdescent, ydescent, width, height, fontsize)
p = self.create_collection( orig_handle, sizes, offsets=list(zip(xdata_marker, ydata)), offset_transform=trans)
self.update_prop(p, orig_handle, legend) p.set_offset_transform(trans) return [p]
class HandlerPathCollection(HandlerRegularPolyCollection): r"""Handler for `.PathCollection`\s, which are used by `~.Axes.scatter`."""
def create_collection(self, orig_handle, sizes, offsets, offset_transform): return type(orig_handle)( [orig_handle.get_paths()[0]], sizes=sizes, offsets=offsets, offset_transform=offset_transform, )
class HandlerCircleCollection(HandlerRegularPolyCollection): r"""Handler for `.CircleCollection`\s."""
def create_collection(self, orig_handle, sizes, offsets, offset_transform): return type(orig_handle)( sizes, offsets=offsets, offset_transform=offset_transform)
class HandlerErrorbar(HandlerLine2D): """Handler for Errorbars."""
def __init__(self, xerr_size=0.5, yerr_size=None, marker_pad=0.3, numpoints=None, **kwargs):
self._xerr_size = xerr_size self._yerr_size = yerr_size
super().__init__(marker_pad=marker_pad, numpoints=numpoints, **kwargs)
def get_err_size(self, legend, xdescent, ydescent, width, height, fontsize): xerr_size = self._xerr_size * fontsize
if self._yerr_size is None: yerr_size = xerr_size else: yerr_size = self._yerr_size * fontsize
return xerr_size, yerr_size
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited plotlines, caplines, barlinecols = orig_handle
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, width, height, fontsize)
ydata = np.full_like(xdata, (height - ydescent) / 2) legline = Line2D(xdata, ydata)
xdata_marker = np.asarray(xdata_marker) ydata_marker = np.asarray(ydata[:len(xdata_marker)])
xerr_size, yerr_size = self.get_err_size(legend, xdescent, ydescent, width, height, fontsize)
legline_marker = Line2D(xdata_marker, ydata_marker)
# when plotlines are None (only errorbars are drawn), we just # make legline invisible. if plotlines is None: legline.set_visible(False) legline_marker.set_visible(False) else: self.update_prop(legline, plotlines, legend)
legline.set_drawstyle('default') legline.set_marker('none')
self.update_prop(legline_marker, plotlines, legend) legline_marker.set_linestyle('None')
if legend.markerscale != 1: newsz = legline_marker.get_markersize() * legend.markerscale legline_marker.set_markersize(newsz)
handle_barlinecols = [] handle_caplines = []
if orig_handle.has_xerr: verts = [((x - xerr_size, y), (x + xerr_size, y)) for x, y in zip(xdata_marker, ydata_marker)] coll = mcoll.LineCollection(verts) self.update_prop(coll, barlinecols[0], legend) handle_barlinecols.append(coll)
if caplines: capline_left = Line2D(xdata_marker - xerr_size, ydata_marker) capline_right = Line2D(xdata_marker + xerr_size, ydata_marker) self.update_prop(capline_left, caplines[0], legend) self.update_prop(capline_right, caplines[0], legend) capline_left.set_marker("|") capline_right.set_marker("|")
handle_caplines.append(capline_left) handle_caplines.append(capline_right)
if orig_handle.has_yerr: verts = [((x, y - yerr_size), (x, y + yerr_size)) for x, y in zip(xdata_marker, ydata_marker)] coll = mcoll.LineCollection(verts) self.update_prop(coll, barlinecols[0], legend) handle_barlinecols.append(coll)
if caplines: capline_left = Line2D(xdata_marker, ydata_marker - yerr_size) capline_right = Line2D(xdata_marker, ydata_marker + yerr_size) self.update_prop(capline_left, caplines[0], legend) self.update_prop(capline_right, caplines[0], legend) capline_left.set_marker("_") capline_right.set_marker("_")
handle_caplines.append(capline_left) handle_caplines.append(capline_right)
artists = [ *handle_barlinecols, *handle_caplines, legline, legline_marker, ] for artist in artists: artist.set_transform(trans) return artists
class HandlerStem(HandlerNpointsYoffsets): """ Handler for plots produced by `~.Axes.stem`. """
def __init__(self, marker_pad=0.3, numpoints=None, bottom=None, yoffsets=None, **kwargs): """ Parameters ---------- marker_pad : float, default: 0.3 Padding between points in legend entry. numpoints : int, optional Number of points to show in legend entry. bottom : float, optional
yoffsets : array of floats, optional Length *numpoints* list of y offsets for each point in legend entry. **kwargs Keyword arguments forwarded to `.HandlerNpointsYoffsets`. """ super().__init__(marker_pad=marker_pad, numpoints=numpoints, yoffsets=yoffsets, **kwargs) self._bottom = bottom
def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize): if self._yoffsets is None: ydata = height * (0.5 * legend._scatteryoffsets + 0.5) else: ydata = height * np.asarray(self._yoffsets)
return ydata
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited markerline, stemlines, baseline = orig_handle # Check to see if the stemcontainer is storing lines as a list or a # LineCollection. Eventually using a list will be removed, and this # logic can also be removed. using_linecoll = isinstance(stemlines, mcoll.LineCollection)
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, width, height, fontsize)
ydata = self.get_ydata(legend, xdescent, ydescent, width, height, fontsize)
if self._bottom is None: bottom = 0. else: bottom = self._bottom
leg_markerline = Line2D(xdata_marker, ydata[:len(xdata_marker)]) self.update_prop(leg_markerline, markerline, legend)
leg_stemlines = [Line2D([x, x], [bottom, y]) for x, y in zip(xdata_marker, ydata)]
if using_linecoll: # change the function used by update_prop() from the default # to one that handles LineCollection with cbook._setattr_cm( self, _update_prop_func=self._copy_collection_props): for line in leg_stemlines: self.update_prop(line, stemlines, legend)
else: for lm, m in zip(leg_stemlines, stemlines): self.update_prop(lm, m, legend)
leg_baseline = Line2D([np.min(xdata), np.max(xdata)], [bottom, bottom]) self.update_prop(leg_baseline, baseline, legend)
artists = [*leg_stemlines, leg_baseline, leg_markerline] for artist in artists: artist.set_transform(trans) return artists
def _copy_collection_props(self, legend_handle, orig_handle): """ Copy properties from the `.LineCollection` *orig_handle* to the `.Line2D` *legend_handle*. """ legend_handle.set_color(orig_handle.get_color()[0]) legend_handle.set_linestyle(orig_handle.get_linestyle()[0])
class HandlerTuple(HandlerBase): """ Handler for Tuple. """
def __init__(self, ndivide=1, pad=None, **kwargs): """ Parameters ---------- ndivide : int or None, default: 1 The number of sections to divide the legend area into. If None, use the length of the input tuple. pad : float, default: :rc:`legend.borderpad` Padding in units of fraction of font size. **kwargs Keyword arguments forwarded to `.HandlerBase`. """ self._ndivide = ndivide self._pad = pad super().__init__(**kwargs)
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited handler_map = legend.get_legend_handler_map()
if self._ndivide is None: ndivide = len(orig_handle) else: ndivide = self._ndivide
if self._pad is None: pad = legend.borderpad * fontsize else: pad = self._pad * fontsize
if ndivide > 1: width = (width - pad * (ndivide - 1)) / ndivide
xds_cycle = cycle(xdescent - (width + pad) * np.arange(ndivide))
a_list = [] for handle1 in orig_handle: handler = legend.get_legend_handler(handler_map, handle1) _a_list = handler.create_artists( legend, handle1, next(xds_cycle), ydescent, width, height, fontsize, trans) a_list.extend(_a_list)
return a_list
class HandlerPolyCollection(HandlerBase): """ Handler for `.PolyCollection` used in `~.Axes.fill_between` and `~.Axes.stackplot`. """ def _update_prop(self, legend_handle, orig_handle): def first_color(colors): if colors.size == 0: return (0, 0, 0, 0) return tuple(colors[0])
def get_first(prop_array): if len(prop_array): return prop_array[0] else: return None
# orig_handle is a PolyCollection and legend_handle is a Patch. # Directly set Patch color attributes (must be RGBA tuples). legend_handle._facecolor = first_color(orig_handle.get_facecolor()) legend_handle._edgecolor = first_color(orig_handle.get_edgecolor()) legend_handle._original_facecolor = orig_handle._original_facecolor legend_handle._original_edgecolor = orig_handle._original_edgecolor legend_handle._fill = orig_handle.get_fill() legend_handle._hatch = orig_handle.get_hatch() # Hatch color is anomalous in having no getters and setters. legend_handle._hatch_color = orig_handle._hatch_color # Setters are fine for the remaining attributes. legend_handle.set_linewidth(get_first(orig_handle.get_linewidths())) legend_handle.set_linestyle(get_first(orig_handle.get_linestyles())) legend_handle.set_transform(get_first(orig_handle.get_transforms())) legend_handle.set_figure(orig_handle.get_figure()) # Alpha is already taken into account by the color attributes.
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited p = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) self.update_prop(p, orig_handle, legend) p.set_transform(trans) return [p]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294from collections.abc import Callable, Sequencefrom matplotlib.artist import Artistfrom matplotlib.legend import Legendfrom matplotlib.offsetbox import OffsetBoxfrom matplotlib.transforms import Transform
from typing import TypeVar
from numpy.typing import ArrayLike
def update_from_first_child(tgt: Artist, src: Artist) -> None: ...
class HandlerBase: def __init__( self, xpad: float = ..., ypad: float = ..., update_func: Callable[[Artist, Artist], None] | None = ..., ) -> None: ... def update_prop( self, legend_handle: Artist, orig_handle: Artist, legend: Legend ) -> None: ... def adjust_drawing_area( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, ) -> tuple[float, float, float, float]: ... def legend_artist( self, legend: Legend, orig_handle: Artist, fontsize: float, handlebox: OffsetBox ) -> Artist: ... def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerNpoints(HandlerBase): def __init__( self, marker_pad: float = ..., numpoints: int | None = ..., **kwargs ) -> None: ... def get_numpoints(self, legend: Legend) -> int | None: ... def get_xdata( self, legend: Legend, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, ) -> tuple[ArrayLike, ArrayLike]: ...
class HandlerNpointsYoffsets(HandlerNpoints): def __init__( self, numpoints: int | None = ..., yoffsets: Sequence[float] | None = ..., **kwargs ) -> None: ... def get_ydata( self, legend: Legend, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, ) -> ArrayLike: ...
class HandlerLine2DCompound(HandlerNpoints): def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerLine2D(HandlerNpoints): def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerPatch(HandlerBase): def __init__(self, patch_func: Callable | None = ..., **kwargs) -> None: ... def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerStepPatch(HandlerBase): def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerLineCollection(HandlerLine2D): def get_numpoints(self, legend: Legend) -> int: ... def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
_T = TypeVar("_T", bound=Artist)
class HandlerRegularPolyCollection(HandlerNpointsYoffsets): def __init__( self, yoffsets: Sequence[float] | None = ..., sizes: Sequence[float] | None = ..., **kwargs ) -> None: ... def get_numpoints(self, legend: Legend) -> int: ... def get_sizes( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, ) -> Sequence[float]: ... def update_prop( self, legend_handle, orig_handle: Artist, legend: Legend ) -> None: ... def create_collection( self, orig_handle: _T, sizes: Sequence[float] | None, offsets: Sequence[float] | None, offset_transform: Transform, ) -> _T: ... def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerPathCollection(HandlerRegularPolyCollection): def create_collection( self, orig_handle: _T, sizes: Sequence[float] | None, offsets: Sequence[float] | None, offset_transform: Transform, ) -> _T: ...
class HandlerCircleCollection(HandlerRegularPolyCollection): def create_collection( self, orig_handle: _T, sizes: Sequence[float] | None, offsets: Sequence[float] | None, offset_transform: Transform, ) -> _T: ...
class HandlerErrorbar(HandlerLine2D): def __init__( self, xerr_size: float = ..., yerr_size: float | None = ..., marker_pad: float = ..., numpoints: int | None = ..., **kwargs ) -> None: ... def get_err_size( self, legend: Legend, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, ) -> tuple[float, float]: ... def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerStem(HandlerNpointsYoffsets): def __init__( self, marker_pad: float = ..., numpoints: int | None = ..., bottom: float | None = ..., yoffsets: Sequence[float] | None = ..., **kwargs ) -> None: ... def get_ydata( self, legend: Legend, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, ) -> ArrayLike: ... def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerTuple(HandlerBase): def __init__( self, ndivide: int | None = ..., pad: float | None = ..., **kwargs ) -> None: ... def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...
class HandlerPolyCollection(HandlerBase): def create_artists( self, legend: Legend, orig_handle: Artist, xdescent: float, ydescent: float, width: float, height: float, fontsize: float, trans: Transform, ) -> Sequence[Artist]: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908r"""Functions to handle markers; used by the marker functionality of`~matplotlib.axes.Axes.plot`, `~matplotlib.axes.Axes.scatter`, and`~matplotlib.axes.Axes.errorbar`.
All possible markers are defined here:
============================== ====== =========================================marker symbol description============================== ====== =========================================``"."`` |m00| point``","`` |m01| pixel``"o"`` |m02| circle``"v"`` |m03| triangle_down``"^"`` |m04| triangle_up``"<"`` |m05| triangle_left``">"`` |m06| triangle_right``"1"`` |m07| tri_down``"2"`` |m08| tri_up``"3"`` |m09| tri_left``"4"`` |m10| tri_right``"8"`` |m11| octagon``"s"`` |m12| square``"p"`` |m13| pentagon``"P"`` |m23| plus (filled)``"*"`` |m14| star``"h"`` |m15| hexagon1``"H"`` |m16| hexagon2``"+"`` |m17| plus``"x"`` |m18| x``"X"`` |m24| x (filled)``"D"`` |m19| diamond``"d"`` |m20| thin_diamond``"|"`` |m21| vline``"_"`` |m22| hline``0`` (``TICKLEFT``) |m25| tickleft``1`` (``TICKRIGHT``) |m26| tickright``2`` (``TICKUP``) |m27| tickup``3`` (``TICKDOWN``) |m28| tickdown``4`` (``CARETLEFT``) |m29| caretleft``5`` (``CARETRIGHT``) |m30| caretright``6`` (``CARETUP``) |m31| caretup``7`` (``CARETDOWN``) |m32| caretdown``8`` (``CARETLEFTBASE``) |m33| caretleft (centered at base)``9`` (``CARETRIGHTBASE``) |m34| caretright (centered at base)``10`` (``CARETUPBASE``) |m35| caretup (centered at base)``11`` (``CARETDOWNBASE``) |m36| caretdown (centered at base)``"none"`` or ``"None"`` nothing``" "`` or ``""`` nothing``"$...$"`` |m37| Render the string using mathtext. E.g ``"$f$"`` for marker showing the letter ``f``.``verts`` A list of (x, y) pairs used for Path vertices. The center of the marker is located at (0, 0) and the size is normalized, such that the created path is encapsulated inside the unit cell.``path`` A `~matplotlib.path.Path` instance.``(numsides, 0, angle)`` A regular polygon with ``numsides`` sides, rotated by ``angle``.``(numsides, 1, angle)`` A star-like symbol with ``numsides`` sides, rotated by ``angle``.``(numsides, 2, angle)`` An asterisk with ``numsides`` sides, rotated by ``angle``.============================== ====== =========================================
Note that special symbols can be defined via the:ref:`STIX math font <mathtext>`,e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer to the`STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
Integer numbers from ``0`` to ``11`` create lines and triangles. Those areequally accessible via capitalized variables, like ``CARETDOWNBASE``.Hence the following are equivalent::
plt.plot([1, 2, 3], marker=11) plt.plot([1, 2, 3], marker=matplotlib.markers.CARETDOWNBASE)
Markers join and cap styles can be customized by creating a new instance ofMarkerStyle.A MarkerStyle can also have a custom `~matplotlib.transforms.Transform`allowing it to be arbitrarily rotated or offset.
Examples showing the use of markers:
* :doc:`/gallery/lines_bars_and_markers/marker_reference`* :doc:`/gallery/lines_bars_and_markers/scatter_star_poly`* :doc:`/gallery/lines_bars_and_markers/multivariate_marker_plot`
.. |m00| image:: /_static/markers/m00.png.. |m01| image:: /_static/markers/m01.png.. |m02| image:: /_static/markers/m02.png.. |m03| image:: /_static/markers/m03.png.. |m04| image:: /_static/markers/m04.png.. |m05| image:: /_static/markers/m05.png.. |m06| image:: /_static/markers/m06.png.. |m07| image:: /_static/markers/m07.png.. |m08| image:: /_static/markers/m08.png.. |m09| image:: /_static/markers/m09.png.. |m10| image:: /_static/markers/m10.png.. |m11| image:: /_static/markers/m11.png.. |m12| image:: /_static/markers/m12.png.. |m13| image:: /_static/markers/m13.png.. |m14| image:: /_static/markers/m14.png.. |m15| image:: /_static/markers/m15.png.. |m16| image:: /_static/markers/m16.png.. |m17| image:: /_static/markers/m17.png.. |m18| image:: /_static/markers/m18.png.. |m19| image:: /_static/markers/m19.png.. |m20| image:: /_static/markers/m20.png.. |m21| image:: /_static/markers/m21.png.. |m22| image:: /_static/markers/m22.png.. |m23| image:: /_static/markers/m23.png.. |m24| image:: /_static/markers/m24.png.. |m25| image:: /_static/markers/m25.png.. |m26| image:: /_static/markers/m26.png.. |m27| image:: /_static/markers/m27.png.. |m28| image:: /_static/markers/m28.png.. |m29| image:: /_static/markers/m29.png.. |m30| image:: /_static/markers/m30.png.. |m31| image:: /_static/markers/m31.png.. |m32| image:: /_static/markers/m32.png.. |m33| image:: /_static/markers/m33.png.. |m34| image:: /_static/markers/m34.png.. |m35| image:: /_static/markers/m35.png.. |m36| image:: /_static/markers/m36.png.. |m37| image:: /_static/markers/m37.png"""import copy
from collections.abc import Sized
import numpy as np
import matplotlib as mplfrom . import _api, cbookfrom .path import Pathfrom .transforms import IdentityTransform, Affine2Dfrom ._enums import JoinStyle, CapStyle
# special-purpose marker identifiers:(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN, CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN, CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = range(12)
_empty_path = Path(np.empty((0, 2)))
class MarkerStyle: """ A class representing marker types.
Instances are immutable. If you need to change anything, create a new instance.
Attributes ---------- markers : dict All known markers. filled_markers : tuple All known filled markers. This is a subset of *markers*. fillstyles : tuple The supported fillstyles. """
markers = { '.': 'point', ',': 'pixel', 'o': 'circle', 'v': 'triangle_down', '^': 'triangle_up', '<': 'triangle_left', '>': 'triangle_right', '1': 'tri_down', '2': 'tri_up', '3': 'tri_left', '4': 'tri_right', '8': 'octagon', 's': 'square', 'p': 'pentagon', '*': 'star', 'h': 'hexagon1', 'H': 'hexagon2', '+': 'plus', 'x': 'x', 'D': 'diamond', 'd': 'thin_diamond', '|': 'vline', '_': 'hline', 'P': 'plus_filled', 'X': 'x_filled', TICKLEFT: 'tickleft', TICKRIGHT: 'tickright', TICKUP: 'tickup', TICKDOWN: 'tickdown', CARETLEFT: 'caretleft', CARETRIGHT: 'caretright', CARETUP: 'caretup', CARETDOWN: 'caretdown', CARETLEFTBASE: 'caretleftbase', CARETRIGHTBASE: 'caretrightbase', CARETUPBASE: 'caretupbase', CARETDOWNBASE: 'caretdownbase', "None": 'nothing', "none": 'nothing', ' ': 'nothing', '': 'nothing' }
# Just used for informational purposes. is_filled() # is calculated in the _set_* functions. filled_markers = ( '.', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X')
fillstyles = ('full', 'left', 'right', 'bottom', 'top', 'none') _half_fillstyles = ('left', 'right', 'bottom', 'top')
def __init__(self, marker, fillstyle=None, transform=None, capstyle=None, joinstyle=None): """ Parameters ---------- marker : str, array-like, Path, MarkerStyle - Another instance of `MarkerStyle` copies the details of that *marker*. - For other possible marker values, see the module docstring `matplotlib.markers`.
fillstyle : str, default: :rc:`markers.fillstyle` One of 'full', 'left', 'right', 'bottom', 'top', 'none'.
transform : `~matplotlib.transforms.Transform`, optional Transform that will be combined with the native transform of the marker.
capstyle : `.CapStyle` or %(CapStyle)s, optional Cap style that will override the default cap style of the marker.
joinstyle : `.JoinStyle` or %(JoinStyle)s, optional Join style that will override the default join style of the marker. """ self._marker_function = None self._user_transform = transform self._user_capstyle = CapStyle(capstyle) if capstyle is not None else None self._user_joinstyle = JoinStyle(joinstyle) if joinstyle is not None else None self._set_fillstyle(fillstyle) self._set_marker(marker)
def _recache(self): if self._marker_function is None: return self._path = _empty_path self._transform = IdentityTransform() self._alt_path = None self._alt_transform = None self._snap_threshold = None self._joinstyle = JoinStyle.round self._capstyle = self._user_capstyle or CapStyle.butt # Initial guess: Assume the marker is filled unless the fillstyle is # set to 'none'. The marker function will override this for unfilled # markers. self._filled = self._fillstyle != 'none' self._marker_function()
def __bool__(self): return bool(len(self._path.vertices))
def is_filled(self): return self._filled
def get_fillstyle(self): return self._fillstyle
def _set_fillstyle(self, fillstyle): """ Set the fillstyle.
Parameters ---------- fillstyle : {'full', 'left', 'right', 'bottom', 'top', 'none'} The part of the marker surface that is colored with markerfacecolor. """ if fillstyle is None: fillstyle = mpl.rcParams['markers.fillstyle'] _api.check_in_list(self.fillstyles, fillstyle=fillstyle) self._fillstyle = fillstyle
def get_joinstyle(self): return self._joinstyle.name
def get_capstyle(self): return self._capstyle.name
def get_marker(self): return self._marker
def _set_marker(self, marker): """ Set the marker.
Parameters ---------- marker : str, array-like, Path, MarkerStyle - Another instance of `MarkerStyle` copies the details of that *marker*. - For other possible marker values see the module docstring `matplotlib.markers`. """ if isinstance(marker, str) and cbook.is_math_text(marker): self._marker_function = self._set_mathtext_path elif isinstance(marker, (int, str)) and marker in self.markers: self._marker_function = getattr(self, '_set_' + self.markers[marker]) elif (isinstance(marker, np.ndarray) and marker.ndim == 2 and marker.shape[1] == 2): self._marker_function = self._set_vertices elif isinstance(marker, Path): self._marker_function = self._set_path_marker elif (isinstance(marker, Sized) and len(marker) in (2, 3) and marker[1] in (0, 1, 2)): self._marker_function = self._set_tuple_marker elif isinstance(marker, MarkerStyle): self.__dict__ = copy.deepcopy(marker.__dict__) else: try: Path(marker) self._marker_function = self._set_vertices except ValueError as err: raise ValueError( f'Unrecognized marker style {marker!r}') from err
if not isinstance(marker, MarkerStyle): self._marker = marker self._recache()
def get_path(self): """ Return a `.Path` for the primary part of the marker.
For unfilled markers this is the whole marker, for filled markers, this is the area to be drawn with *markerfacecolor*. """ return self._path
def get_transform(self): """ Return the transform to be applied to the `.Path` from `MarkerStyle.get_path()`. """ if self._user_transform is None: return self._transform.frozen() else: return (self._transform + self._user_transform).frozen()
def get_alt_path(self): """ Return a `.Path` for the alternate part of the marker.
For unfilled markers, this is *None*; for filled markers, this is the area to be drawn with *markerfacecoloralt*. """ return self._alt_path
def get_alt_transform(self): """ Return the transform to be applied to the `.Path` from `MarkerStyle.get_alt_path()`. """ if self._user_transform is None: return self._alt_transform.frozen() else: return (self._alt_transform + self._user_transform).frozen()
def get_snap_threshold(self): return self._snap_threshold
def get_user_transform(self): """Return user supplied part of marker transform.""" if self._user_transform is not None: return self._user_transform.frozen()
def transformed(self, transform): """ Return a new version of this marker with the transform applied.
Parameters ---------- transform : `~matplotlib.transforms.Affine2D` Transform will be combined with current user supplied transform. """ new_marker = MarkerStyle(self) if new_marker._user_transform is not None: new_marker._user_transform += transform else: new_marker._user_transform = transform return new_marker
def rotated(self, *, deg=None, rad=None): """ Return a new version of this marker rotated by specified angle.
Parameters ---------- deg : float, optional Rotation angle in degrees.
rad : float, optional Rotation angle in radians.
.. note:: You must specify exactly one of deg or rad. """ if deg is None and rad is None: raise ValueError('One of deg or rad is required') if deg is not None and rad is not None: raise ValueError('Only one of deg and rad can be supplied') new_marker = MarkerStyle(self) if new_marker._user_transform is None: new_marker._user_transform = Affine2D()
if deg is not None: new_marker._user_transform.rotate_deg(deg) if rad is not None: new_marker._user_transform.rotate(rad)
return new_marker
def scaled(self, sx, sy=None): """ Return new marker scaled by specified scale factors.
If *sy* is not given, the same scale is applied in both the *x*- and *y*-directions.
Parameters ---------- sx : float *X*-direction scaling factor. sy : float, optional *Y*-direction scaling factor. """ if sy is None: sy = sx
new_marker = MarkerStyle(self) _transform = new_marker._user_transform or Affine2D() new_marker._user_transform = _transform.scale(sx, sy) return new_marker
def _set_nothing(self): self._filled = False
def _set_custom_marker(self, path): rescale = np.max(np.abs(path.vertices)) # max of x's and y's. self._transform = Affine2D().scale(0.5 / rescale) self._path = path
def _set_path_marker(self): self._set_custom_marker(self._marker)
def _set_vertices(self): self._set_custom_marker(Path(self._marker))
def _set_tuple_marker(self): marker = self._marker if len(marker) == 2: numsides, rotation = marker[0], 0.0 elif len(marker) == 3: numsides, rotation = marker[0], marker[2] symstyle = marker[1] if symstyle == 0: self._path = Path.unit_regular_polygon(numsides) self._joinstyle = self._user_joinstyle or JoinStyle.miter elif symstyle == 1: self._path = Path.unit_regular_star(numsides) self._joinstyle = self._user_joinstyle or JoinStyle.bevel elif symstyle == 2: self._path = Path.unit_regular_asterisk(numsides) self._filled = False self._joinstyle = self._user_joinstyle or JoinStyle.bevel else: raise ValueError(f"Unexpected tuple marker: {marker}") self._transform = Affine2D().scale(0.5).rotate_deg(rotation)
def _set_mathtext_path(self): """ Draw mathtext markers '$...$' using `.TextPath` object.
Submitted by tcb """ from matplotlib.text import TextPath
# again, the properties could be initialised just once outside # this function text = TextPath(xy=(0, 0), s=self.get_marker(), usetex=mpl.rcParams['text.usetex']) if len(text.vertices) == 0: return
bbox = text.get_extents() max_dim = max(bbox.width, bbox.height) self._transform = ( Affine2D() .translate(-bbox.xmin + 0.5 * -bbox.width, -bbox.ymin + 0.5 * -bbox.height) .scale(1.0 / max_dim)) self._path = text self._snap = False
def _half_fill(self): return self.get_fillstyle() in self._half_fillstyles
def _set_circle(self, size=1.0): self._transform = Affine2D().scale(0.5 * size) self._snap_threshold = np.inf if not self._half_fill(): self._path = Path.unit_circle() else: self._path = self._alt_path = Path.unit_circle_righthalf() fs = self.get_fillstyle() self._transform.rotate_deg( {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs]) self._alt_transform = self._transform.frozen().rotate_deg(180.)
def _set_point(self): self._set_circle(size=0.5)
def _set_pixel(self): self._path = Path.unit_rectangle() # Ideally, you'd want -0.5, -0.5 here, but then the snapping # algorithm in the Agg backend will round this to a 2x2 # rectangle from (-1, -1) to (1, 1). By offsetting it # slightly, we can force it to be (0, 0) to (1, 1), which both # makes it only be a single pixel and places it correctly # aligned to 1-width stroking (i.e. the ticks). This hack is # the best of a number of bad alternatives, mainly because the # backends are not aware of what marker is actually being used # beyond just its path data. self._transform = Affine2D().translate(-0.49999, -0.49999) self._snap_threshold = None
_triangle_path = Path._create_closed([[0, 1], [-1, -1], [1, -1]]) # Going down halfway looks to small. Golden ratio is too far. _triangle_path_u = Path._create_closed([[0, 1], [-3/5, -1/5], [3/5, -1/5]]) _triangle_path_d = Path._create_closed( [[-3/5, -1/5], [3/5, -1/5], [1, -1], [-1, -1]]) _triangle_path_l = Path._create_closed([[0, 1], [0, -1], [-1, -1]]) _triangle_path_r = Path._create_closed([[0, 1], [0, -1], [1, -1]])
def _set_triangle(self, rot, skip): self._transform = Affine2D().scale(0.5).rotate_deg(rot) self._snap_threshold = 5.0
if not self._half_fill(): self._path = self._triangle_path else: mpaths = [self._triangle_path_u, self._triangle_path_l, self._triangle_path_d, self._triangle_path_r]
fs = self.get_fillstyle() if fs == 'top': self._path = mpaths[(0 + skip) % 4] self._alt_path = mpaths[(2 + skip) % 4] elif fs == 'bottom': self._path = mpaths[(2 + skip) % 4] self._alt_path = mpaths[(0 + skip) % 4] elif fs == 'left': self._path = mpaths[(1 + skip) % 4] self._alt_path = mpaths[(3 + skip) % 4] else: self._path = mpaths[(3 + skip) % 4] self._alt_path = mpaths[(1 + skip) % 4]
self._alt_transform = self._transform
self._joinstyle = self._user_joinstyle or JoinStyle.miter
def _set_triangle_up(self): return self._set_triangle(0.0, 0)
def _set_triangle_down(self): return self._set_triangle(180.0, 2)
def _set_triangle_left(self): return self._set_triangle(90.0, 3)
def _set_triangle_right(self): return self._set_triangle(270.0, 1)
def _set_square(self): self._transform = Affine2D().translate(-0.5, -0.5) self._snap_threshold = 2.0 if not self._half_fill(): self._path = Path.unit_rectangle() else: # Build a bottom filled square out of two rectangles, one filled. self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5], [0.0, 0.5], [0.0, 0.0]]) self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0], [0.0, 1.0], [0.0, 0.5]]) fs = self.get_fillstyle() rotate = {'bottom': 0, 'right': 90, 'top': 180, 'left': 270}[fs] self._transform.rotate_deg(rotate) self._alt_transform = self._transform
self._joinstyle = self._user_joinstyle or JoinStyle.miter
def _set_diamond(self): self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45) self._snap_threshold = 5.0 if not self._half_fill(): self._path = Path.unit_rectangle() else: self._path = Path([[0, 0], [1, 0], [1, 1], [0, 0]]) self._alt_path = Path([[0, 0], [0, 1], [1, 1], [0, 0]]) fs = self.get_fillstyle() rotate = {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs] self._transform.rotate_deg(rotate) self._alt_transform = self._transform self._joinstyle = self._user_joinstyle or JoinStyle.miter
def _set_thin_diamond(self): self._set_diamond() self._transform.scale(0.6, 1.0)
def _set_pentagon(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0
polypath = Path.unit_regular_polygon(5)
if not self._half_fill(): self._path = polypath else: verts = polypath.vertices y = (1 + np.sqrt(5)) / 4. top = Path(verts[[0, 1, 4, 0]]) bottom = Path(verts[[1, 2, 3, 4, 1]]) left = Path([verts[0], verts[1], verts[2], [0, -y], verts[0]]) right = Path([verts[0], verts[4], verts[3], [0, -y], verts[0]]) self._path, self._alt_path = { 'top': (top, bottom), 'bottom': (bottom, top), 'left': (left, right), 'right': (right, left), }[self.get_fillstyle()] self._alt_transform = self._transform
self._joinstyle = self._user_joinstyle or JoinStyle.miter
def _set_star(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0
polypath = Path.unit_regular_star(5, innerCircle=0.381966)
if not self._half_fill(): self._path = polypath else: verts = polypath.vertices top = Path(np.concatenate([verts[0:4], verts[7:10], verts[0:1]])) bottom = Path(np.concatenate([verts[3:8], verts[3:4]])) left = Path(np.concatenate([verts[0:6], verts[0:1]])) right = Path(np.concatenate([verts[0:1], verts[5:10], verts[0:1]])) self._path, self._alt_path = { 'top': (top, bottom), 'bottom': (bottom, top), 'left': (left, right), 'right': (right, left), }[self.get_fillstyle()] self._alt_transform = self._transform
self._joinstyle = self._user_joinstyle or JoinStyle.bevel
def _set_hexagon1(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = None
polypath = Path.unit_regular_polygon(6)
if not self._half_fill(): self._path = polypath else: verts = polypath.vertices # not drawing inside lines x = np.abs(np.cos(5 * np.pi / 6.)) top = Path(np.concatenate([[(-x, 0)], verts[[1, 0, 5]], [(x, 0)]])) bottom = Path(np.concatenate([[(-x, 0)], verts[2:5], [(x, 0)]])) left = Path(verts[0:4]) right = Path(verts[[0, 5, 4, 3]]) self._path, self._alt_path = { 'top': (top, bottom), 'bottom': (bottom, top), 'left': (left, right), 'right': (right, left), }[self.get_fillstyle()] self._alt_transform = self._transform
self._joinstyle = self._user_joinstyle or JoinStyle.miter
def _set_hexagon2(self): self._transform = Affine2D().scale(0.5).rotate_deg(30) self._snap_threshold = None
polypath = Path.unit_regular_polygon(6)
if not self._half_fill(): self._path = polypath else: verts = polypath.vertices # not drawing inside lines x, y = np.sqrt(3) / 4, 3 / 4. top = Path(verts[[1, 0, 5, 4, 1]]) bottom = Path(verts[1:5]) left = Path(np.concatenate([ [(x, y)], verts[:3], [(-x, -y), (x, y)]])) right = Path(np.concatenate([ [(x, y)], verts[5:2:-1], [(-x, -y)]])) self._path, self._alt_path = { 'top': (top, bottom), 'bottom': (bottom, top), 'left': (left, right), 'right': (right, left), }[self.get_fillstyle()] self._alt_transform = self._transform
self._joinstyle = self._user_joinstyle or JoinStyle.miter
def _set_octagon(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0
polypath = Path.unit_regular_polygon(8)
if not self._half_fill(): self._transform.rotate_deg(22.5) self._path = polypath else: x = np.sqrt(2.) / 4. self._path = self._alt_path = Path( [[0, -1], [0, 1], [-x, 1], [-1, x], [-1, -x], [-x, -1], [0, -1]]) fs = self.get_fillstyle() self._transform.rotate_deg( {'left': 0, 'bottom': 90, 'right': 180, 'top': 270}[fs]) self._alt_transform = self._transform.frozen().rotate_deg(180.0)
self._joinstyle = self._user_joinstyle or JoinStyle.miter
_line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]])
def _set_vline(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 1.0 self._filled = False self._path = self._line_marker_path
def _set_hline(self): self._set_vline() self._transform = self._transform.rotate_deg(90)
_tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]])
def _set_tickleft(self): self._transform = Affine2D().scale(-1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickhoriz_path
def _set_tickright(self): self._transform = Affine2D().scale(1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickhoriz_path
_tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]])
def _set_tickup(self): self._transform = Affine2D().scale(1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickvert_path
def _set_tickdown(self): self._transform = Affine2D().scale(1.0, -1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickvert_path
_tri_path = Path([[0.0, 0.0], [0.0, -1.0], [0.0, 0.0], [0.8, 0.5], [0.0, 0.0], [-0.8, 0.5]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO])
def _set_tri_down(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path
def _set_tri_up(self): self._set_tri_down() self._transform = self._transform.rotate_deg(180)
def _set_tri_left(self): self._set_tri_down() self._transform = self._transform.rotate_deg(270)
def _set_tri_right(self): self._set_tri_down() self._transform = self._transform.rotate_deg(90)
_caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]])
def _set_caretdown(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = self._user_joinstyle or JoinStyle.miter
def _set_caretup(self): self._set_caretdown() self._transform = self._transform.rotate_deg(180)
def _set_caretleft(self): self._set_caretdown() self._transform = self._transform.rotate_deg(270)
def _set_caretright(self): self._set_caretdown() self._transform = self._transform.rotate_deg(90)
_caret_path_base = Path([[-1.0, 0.0], [0.0, -1.5], [1.0, 0]])
def _set_caretdownbase(self): self._set_caretdown() self._path = self._caret_path_base
def _set_caretupbase(self): self._set_caretdownbase() self._transform = self._transform.rotate_deg(180)
def _set_caretleftbase(self): self._set_caretdownbase() self._transform = self._transform.rotate_deg(270)
def _set_caretrightbase(self): self._set_caretdownbase() self._transform = self._transform.rotate_deg(90)
_plus_path = Path([[-1.0, 0.0], [1.0, 0.0], [0.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO])
def _set_plus(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 1.0 self._filled = False self._path = self._plus_path
_x_path = Path([[-1.0, -1.0], [1.0, 1.0], [-1.0, 1.0], [1.0, -1.0]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO])
def _set_x(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 3.0 self._filled = False self._path = self._x_path
_plus_filled_path = Path._create_closed(np.array([ (-1, -3), (+1, -3), (+1, -1), (+3, -1), (+3, +1), (+1, +1), (+1, +3), (-1, +3), (-1, +1), (-3, +1), (-3, -1), (-1, -1)]) / 6) _plus_filled_path_t = Path._create_closed(np.array([ (+3, 0), (+3, +1), (+1, +1), (+1, +3), (-1, +3), (-1, +1), (-3, +1), (-3, 0)]) / 6)
def _set_plus_filled(self): self._transform = Affine2D() self._snap_threshold = 5.0 self._joinstyle = self._user_joinstyle or JoinStyle.miter if not self._half_fill(): self._path = self._plus_filled_path else: # Rotate top half path to support all partitions self._path = self._alt_path = self._plus_filled_path_t fs = self.get_fillstyle() self._transform.rotate_deg( {'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs]) self._alt_transform = self._transform.frozen().rotate_deg(180)
_x_filled_path = Path._create_closed(np.array([ (-1, -2), (0, -1), (+1, -2), (+2, -1), (+1, 0), (+2, +1), (+1, +2), (0, +1), (-1, +2), (-2, +1), (-1, 0), (-2, -1)]) / 4) _x_filled_path_t = Path._create_closed(np.array([ (+1, 0), (+2, +1), (+1, +2), (0, +1), (-1, +2), (-2, +1), (-1, 0)]) / 4)
def _set_x_filled(self): self._transform = Affine2D() self._snap_threshold = 5.0 self._joinstyle = self._user_joinstyle or JoinStyle.miter if not self._half_fill(): self._path = self._x_filled_path else: # Rotate top half path to support all partitions self._path = self._alt_path = self._x_filled_path_t fs = self.get_fillstyle() self._transform.rotate_deg( {'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs]) self._alt_transform = self._transform.frozen().rotate_deg(180)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913"""Numerical Python functions written for compatibility with MATLABcommands with the same names. Most numerical Python functions can be found inthe `NumPy`_ and `SciPy`_ libraries. What remains here is code for performingspectral computations and kernel density estimations.
.. _NumPy: https://numpy.org.. _SciPy: https://www.scipy.org
Spectral functions------------------
`cohere` Coherence (normalized cross spectral density)
`csd` Cross spectral density using Welch's average periodogram
`detrend` Remove the mean or best fit line from an array
`psd` Power spectral density using Welch's average periodogram
`specgram` Spectrogram (spectrum over segments of time)
`complex_spectrum` Return the complex-valued frequency spectrum of a signal
`magnitude_spectrum` Return the magnitude of the frequency spectrum of a signal
`angle_spectrum` Return the angle (wrapped phase) of the frequency spectrum of a signal
`phase_spectrum` Return the phase (unwrapped angle) of the frequency spectrum of a signal
`detrend_mean` Remove the mean from a line.
`detrend_linear` Remove the best fit line from a line.
`detrend_none` Return the original line."""
import functoolsfrom numbers import Number
import numpy as np
from matplotlib import _api, _docstring, cbook
def window_hanning(x): """ Return *x* times the Hanning (or Hann) window of len(*x*).
See Also -------- window_none : Another window algorithm. """ return np.hanning(len(x))*x
def window_none(x): """ No window function; simply return *x*.
See Also -------- window_hanning : Another window algorithm. """ return x
def detrend(x, key=None, axis=None): """ Return *x* with its trend removed.
Parameters ---------- x : array or sequence Array or sequence containing the data.
key : {'default', 'constant', 'mean', 'linear', 'none'} or function The detrending algorithm to use. 'default', 'mean', and 'constant' are the same as `detrend_mean`. 'linear' is the same as `detrend_linear`. 'none' is the same as `detrend_none`. The default is 'mean'. See the corresponding functions for more details regarding the algorithms. Can also be a function that carries out the detrend operation.
axis : int The axis along which to do the detrending.
See Also -------- detrend_mean : Implementation of the 'mean' algorithm. detrend_linear : Implementation of the 'linear' algorithm. detrend_none : Implementation of the 'none' algorithm. """ if key is None or key in ['constant', 'mean', 'default']: return detrend(x, key=detrend_mean, axis=axis) elif key == 'linear': return detrend(x, key=detrend_linear, axis=axis) elif key == 'none': return detrend(x, key=detrend_none, axis=axis) elif callable(key): x = np.asarray(x) if axis is not None and axis + 1 > x.ndim: raise ValueError(f'axis(={axis}) out of bounds') if (axis is None and x.ndim == 0) or (not axis and x.ndim == 1): return key(x) # try to use the 'axis' argument if the function supports it, # otherwise use apply_along_axis to do it try: return key(x, axis=axis) except TypeError: return np.apply_along_axis(key, axis=axis, arr=x) else: raise ValueError( f"Unknown value for key: {key!r}, must be one of: 'default', " f"'constant', 'mean', 'linear', or a function")
def detrend_mean(x, axis=None): """ Return *x* minus the mean(*x*).
Parameters ---------- x : array or sequence Array or sequence containing the data Can have any dimensionality
axis : int The axis along which to take the mean. See `numpy.mean` for a description of this argument.
See Also -------- detrend_linear : Another detrend algorithm. detrend_none : Another detrend algorithm. detrend : A wrapper around all the detrend algorithms. """ x = np.asarray(x)
if axis is not None and axis+1 > x.ndim: raise ValueError('axis(=%s) out of bounds' % axis)
return x - x.mean(axis, keepdims=True)
def detrend_none(x, axis=None): """ Return *x*: no detrending.
Parameters ---------- x : any object An object containing the data
axis : int This parameter is ignored. It is included for compatibility with detrend_mean
See Also -------- detrend_mean : Another detrend algorithm. detrend_linear : Another detrend algorithm. detrend : A wrapper around all the detrend algorithms. """ return x
def detrend_linear(y): """ Return *x* minus best fit line; 'linear' detrending.
Parameters ---------- y : 0-D or 1-D array or sequence Array or sequence containing the data
See Also -------- detrend_mean : Another detrend algorithm. detrend_none : Another detrend algorithm. detrend : A wrapper around all the detrend algorithms. """ # This is faster than an algorithm based on linalg.lstsq. y = np.asarray(y)
if y.ndim > 1: raise ValueError('y cannot have ndim > 1')
# short-circuit 0-D array. if not y.ndim: return np.array(0., dtype=y.dtype)
x = np.arange(y.size, dtype=float)
C = np.cov(x, y, bias=1) b = C[0, 1]/C[0, 0]
a = y.mean() - b*x.mean() return y - (b*x + a)
def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, mode=None): """ Private helper implementing the common parts between the psd, csd, spectrogram and complex, magnitude, angle, and phase spectrums. """ if y is None: # if y is None use x for y same_data = True else: # The checks for if y is x are so that we can use the same function to # implement the core of psd(), csd(), and spectrogram() without doing # extra calculations. We return the unaveraged Pxy, freqs, and t. same_data = y is x
if Fs is None: Fs = 2 if noverlap is None: noverlap = 0 if detrend_func is None: detrend_func = detrend_none if window is None: window = window_hanning
# if NFFT is set to None use the whole signal if NFFT is None: NFFT = 256
if noverlap >= NFFT: raise ValueError('noverlap must be less than NFFT')
if mode is None or mode == 'default': mode = 'psd' _api.check_in_list( ['default', 'psd', 'complex', 'magnitude', 'angle', 'phase'], mode=mode)
if not same_data and mode != 'psd': raise ValueError("x and y must be equal if mode is not 'psd'")
# Make sure we're dealing with a numpy array. If y and x were the same # object to start with, keep them that way x = np.asarray(x) if not same_data: y = np.asarray(y)
if sides is None or sides == 'default': if np.iscomplexobj(x): sides = 'twosided' else: sides = 'onesided' _api.check_in_list(['default', 'onesided', 'twosided'], sides=sides)
# zero pad x and y up to NFFT if they are shorter than NFFT if len(x) < NFFT: n = len(x) x = np.resize(x, NFFT) x[n:] = 0
if not same_data and len(y) < NFFT: n = len(y) y = np.resize(y, NFFT) y[n:] = 0
if pad_to is None: pad_to = NFFT
if mode != 'psd': scale_by_freq = False elif scale_by_freq is None: scale_by_freq = True
# For real x, ignore the negative frequencies unless told otherwise if sides == 'twosided': numFreqs = pad_to if pad_to % 2: freqcenter = (pad_to - 1)//2 + 1 else: freqcenter = pad_to//2 scaling_factor = 1. elif sides == 'onesided': if pad_to % 2: numFreqs = (pad_to + 1)//2 else: numFreqs = pad_to//2 + 1 scaling_factor = 2.
if not np.iterable(window): window = window(np.ones(NFFT, x.dtype)) if len(window) != NFFT: raise ValueError( "The window length must match the data's first dimension")
result = np.lib.stride_tricks.sliding_window_view( x, NFFT, axis=0)[::NFFT - noverlap].T result = detrend(result, detrend_func, axis=0) result = result * window.reshape((-1, 1)) result = np.fft.fft(result, n=pad_to, axis=0)[:numFreqs, :] freqs = np.fft.fftfreq(pad_to, 1/Fs)[:numFreqs]
if not same_data: # if same_data is False, mode must be 'psd' resultY = np.lib.stride_tricks.sliding_window_view( y, NFFT, axis=0)[::NFFT - noverlap].T resultY = detrend(resultY, detrend_func, axis=0) resultY = resultY * window.reshape((-1, 1)) resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :] result = np.conj(result) * resultY elif mode == 'psd': result = np.conj(result) * result elif mode == 'magnitude': result = np.abs(result) / window.sum() elif mode == 'angle' or mode == 'phase': # we unwrap the phase later to handle the onesided vs. twosided case result = np.angle(result) elif mode == 'complex': result /= window.sum()
if mode == 'psd':
# Also include scaling factors for one-sided densities and dividing by # the sampling frequency, if desired. Scale everything, except the DC # component and the NFFT/2 component:
# if we have a even number of frequencies, don't scale NFFT/2 if not NFFT % 2: slc = slice(1, -1, None) # if we have an odd number, just don't scale DC else: slc = slice(1, None, None)
result[slc] *= scaling_factor
# MATLAB divides by the sampling frequency so that density function # has units of dB/Hz and can be integrated by the plotted frequency # values. Perform the same scaling here. if scale_by_freq: result /= Fs # Scale the spectrum by the norm of the window to compensate for # windowing loss; see Bendat & Piersol Sec 11.5.2. result /= (window**2).sum() else: # In this case, preserve power in the segment, not amplitude result /= window.sum()**2
t = np.arange(NFFT/2, len(x) - NFFT/2 + 1, NFFT - noverlap)/Fs
if sides == 'twosided': # center the frequency range at zero freqs = np.roll(freqs, -freqcenter, axis=0) result = np.roll(result, -freqcenter, axis=0) elif not pad_to % 2: # get the last value correctly, it is negative otherwise freqs[-1] *= -1
# we unwrap the phase here to handle the onesided vs. twosided case if mode == 'phase': result = np.unwrap(result, axis=0)
return result, freqs, t
def _single_spectrum_helper( mode, x, Fs=None, window=None, pad_to=None, sides=None): """ Private helper implementing the commonality between the complex, magnitude, angle, and phase spectrums. """ _api.check_in_list(['complex', 'magnitude', 'angle', 'phase'], mode=mode)
if pad_to is None: pad_to = len(x)
spec, freqs, _ = _spectral_helper(x=x, y=None, NFFT=len(x), Fs=Fs, detrend_func=detrend_none, window=window, noverlap=0, pad_to=pad_to, sides=sides, scale_by_freq=False, mode=mode) if mode != 'complex': spec = spec.real
if spec.ndim == 2 and spec.shape[1] == 1: spec = spec[:, 0]
return spec, freqs
# Split out these keyword docs so that they can be used elsewhere_docstring.interpd.register( Spectral="""\Fs : float, default: 2 The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, *freqs*, in cycles per time unit.
window : callable or ndarray, default: `.window_hanning` A function or a vector of length *NFFT*. To create window vectors see `.window_hanning`, `.window_none`, `numpy.blackman`, `numpy.hamming`, `numpy.bartlett`, `scipy.signal`, `scipy.signal.get_window`, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides : {'default', 'onesided', 'twosided'}, optional Which sides of the spectrum to return. 'default' is one-sided for real data and two-sided for complex data. 'onesided' forces the return of a one-sided spectrum, while 'twosided' forces two-sided.""",
Single_Spectrum="""\pad_to : int, optional The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the *n* parameter in the call to `~numpy.fft.fft`. The default is None, which sets *pad_to* equal to the length of the input signal (i.e. no padding).""",
PSD="""\pad_to : int, optional The number of points to which the data segment is padded when performing the FFT. This can be different from *NFFT*, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the *n* parameter in the call to `~numpy.fft.fft`. The default is None, which sets *pad_to* equal to *NFFT*
NFFT : int, default: 256 The number of data points used in each block for the FFT. A power 2 is most efficient. This should *NOT* be used to get zero padding, or the scaling of the result will be incorrect; use *pad_to* for this instead.
detrend : {'none', 'mean', 'linear'} or callable, default: 'none' The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the *detrend* parameter is a vector, in Matplotlib it is a function. The :mod:`~matplotlib.mlab` module defines `.detrend_none`, `.detrend_mean`, and `.detrend_linear`, but you can use a custom function as well. You can also use a string to choose one of the functions: 'none' calls `.detrend_none`. 'mean' calls `.detrend_mean`. 'linear' calls `.detrend_linear`.
scale_by_freq : bool, default: True Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.""")
@_docstring.interpddef psd(x, NFFT=None, Fs=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None): r""" Compute the power spectral density.
The power spectral density :math:`P_{xx}` by Welch's average periodogram method. The vector *x* is divided into *NFFT* length segments. Each segment is detrended by function *detrend* and windowed by function *window*. *noverlap* gives the length of the overlap between segments. The :math:`|\mathrm{fft}(i)|^2` of each segment :math:`i` are averaged to compute :math:`P_{xx}`.
If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
Parameters ---------- x : 1-D array or sequence Array or sequence containing the data
%(Spectral)s
%(PSD)s
noverlap : int, default: 0 (no overlap) The number of points of overlap between segments.
Returns ------- Pxx : 1-D array The values for the power spectrum :math:`P_{xx}` (real valued)
freqs : 1-D array The frequencies corresponding to the elements in *Pxx*
References ---------- Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)
See Also -------- specgram `specgram` differs in the default overlap; in not returning the mean of the segment periodograms; and in returning the times of the segments.
magnitude_spectrum : returns the magnitude spectrum.
csd : returns the spectral density between two signals. """ Pxx, freqs = csd(x=x, y=None, NFFT=NFFT, Fs=Fs, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq) return Pxx.real, freqs
@_docstring.interpddef csd(x, y, NFFT=None, Fs=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None): """ Compute the cross-spectral density.
The cross spectral density :math:`P_{xy}` by Welch's average periodogram method. The vectors *x* and *y* are divided into *NFFT* length segments. Each segment is detrended by function *detrend* and windowed by function *window*. *noverlap* gives the length of the overlap between segments. The product of the direct FFTs of *x* and *y* are averaged over each segment to compute :math:`P_{xy}`, with a scaling to correct for power loss due to windowing.
If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero padded to *NFFT*.
Parameters ---------- x, y : 1-D arrays or sequences Arrays or sequences containing the data
%(Spectral)s
%(PSD)s
noverlap : int, default: 0 (no overlap) The number of points of overlap between segments.
Returns ------- Pxy : 1-D array The values for the cross spectrum :math:`P_{xy}` before scaling (real valued)
freqs : 1-D array The frequencies corresponding to the elements in *Pxy*
References ---------- Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)
See Also -------- psd : equivalent to setting ``y = x``. """ if NFFT is None: NFFT = 256 Pxy, freqs, _ = _spectral_helper(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend_func=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, mode='psd')
if Pxy.ndim == 2: if Pxy.shape[1] > 1: Pxy = Pxy.mean(axis=1) else: Pxy = Pxy[:, 0] return Pxy, freqs
_single_spectrum_docs = """\Compute the {quantity} of *x*.Data is padded to a length of *pad_to* and the windowing function *window* isapplied to the signal.
Parameters----------x : 1-D array or sequence Array or sequence containing the data
{Spectral}
{Single_Spectrum}
Returns-------spectrum : 1-D array The {quantity}.freqs : 1-D array The frequencies corresponding to the elements in *spectrum*.
See Also--------psd Returns the power spectral density.complex_spectrum Returns the complex-valued frequency spectrum.magnitude_spectrum Returns the absolute value of the `complex_spectrum`.angle_spectrum Returns the angle of the `complex_spectrum`.phase_spectrum Returns the phase (unwrapped angle) of the `complex_spectrum`.specgram Can return the complex spectrum of segments within the signal."""
complex_spectrum = functools.partial(_single_spectrum_helper, "complex")complex_spectrum.__doc__ = _single_spectrum_docs.format( quantity="complex-valued frequency spectrum", **_docstring.interpd.params)magnitude_spectrum = functools.partial(_single_spectrum_helper, "magnitude")magnitude_spectrum.__doc__ = _single_spectrum_docs.format( quantity="magnitude (absolute value) of the frequency spectrum", **_docstring.interpd.params)angle_spectrum = functools.partial(_single_spectrum_helper, "angle")angle_spectrum.__doc__ = _single_spectrum_docs.format( quantity="angle of the frequency spectrum (wrapped phase spectrum)", **_docstring.interpd.params)phase_spectrum = functools.partial(_single_spectrum_helper, "phase")phase_spectrum.__doc__ = _single_spectrum_docs.format( quantity="phase of the frequency spectrum (unwrapped phase spectrum)", **_docstring.interpd.params)
@_docstring.interpddef specgram(x, NFFT=None, Fs=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, mode=None): """ Compute a spectrogram.
Compute and plot a spectrogram of data in *x*. Data are split into *NFFT* length segments and the spectrum of each section is computed. The windowing function *window* is applied to each segment, and the amount of overlap of each segment is specified with *noverlap*.
Parameters ---------- x : array-like 1-D array or sequence.
%(Spectral)s
%(PSD)s
noverlap : int, default: 128 The number of points of overlap between blocks. mode : str, default: 'psd' What sort of spectrum to use: 'psd' Returns the power spectral density. 'complex' Returns the complex-valued frequency spectrum. 'magnitude' Returns the magnitude spectrum. 'angle' Returns the phase spectrum without unwrapping. 'phase' Returns the phase spectrum with unwrapping.
Returns ------- spectrum : array-like 2D array, columns are the periodograms of successive segments.
freqs : array-like 1-D array, frequencies corresponding to the rows in *spectrum*.
t : array-like 1-D array, the times corresponding to midpoints of segments (i.e the columns in *spectrum*).
See Also -------- psd : differs in the overlap and in the return values. complex_spectrum : similar, but with complex valued frequencies. magnitude_spectrum : similar single segment when *mode* is 'magnitude'. angle_spectrum : similar to single segment when *mode* is 'angle'. phase_spectrum : similar to single segment when *mode* is 'phase'.
Notes ----- *detrend* and *scale_by_freq* only apply when *mode* is set to 'psd'.
""" if noverlap is None: noverlap = 128 # default in _spectral_helper() is noverlap = 0 if NFFT is None: NFFT = 256 # same default as in _spectral_helper() if len(x) <= NFFT: _api.warn_external("Only one segment is calculated since parameter " f"NFFT (={NFFT}) >= signal length (={len(x)}).")
spec, freqs, t = _spectral_helper(x=x, y=None, NFFT=NFFT, Fs=Fs, detrend_func=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, mode=mode)
if mode != 'complex': spec = spec.real # Needed since helper implements generically
return spec, freqs, t
@_docstring.interpddef cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None): r""" The coherence between *x* and *y*. Coherence is the normalized cross spectral density:
.. math::
C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}
Parameters ---------- x, y Array or sequence containing the data
%(Spectral)s
%(PSD)s
noverlap : int, default: 0 (no overlap) The number of points of overlap between segments.
Returns ------- Cxy : 1-D array The coherence vector. freqs : 1-D array The frequencies for the elements in *Cxy*.
See Also -------- :func:`psd`, :func:`csd` : For information about the methods used to compute :math:`P_{xy}`, :math:`P_{xx}` and :math:`P_{yy}`. """ if len(x) < 2 * NFFT: raise ValueError( "Coherence is calculated by averaging over *NFFT* length " "segments. Your signal is too short for your choice of *NFFT*.") Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq) Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq) Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq) Cxy = np.abs(Pxy) ** 2 / (Pxx * Pyy) return Cxy, f
class GaussianKDE: """ Representation of a kernel-density estimate using Gaussian kernels.
Parameters ---------- dataset : array-like Datapoints to estimate from. In case of univariate data this is a 1-D array, otherwise a 2D array with shape (# of dims, # of data). bw_method : {'scott', 'silverman'} or float or callable, optional The method used to calculate the estimator bandwidth. If a float, this will be used directly as `kde.factor`. If a callable, it should take a `GaussianKDE` instance as only parameter and return a float. If None (default), 'scott' is used.
Attributes ---------- dataset : ndarray The dataset passed to the constructor. dim : int Number of dimensions. num_dp : int Number of datapoints. factor : float The bandwidth factor, obtained from `kde.covariance_factor`, with which the covariance matrix is multiplied. covariance : ndarray The covariance matrix of *dataset*, scaled by the calculated bandwidth (`kde.factor`). inv_cov : ndarray The inverse of *covariance*.
Methods ------- kde.evaluate(points) : ndarray Evaluate the estimated pdf on a provided set of points. kde(points) : ndarray Same as kde.evaluate(points) """
# This implementation with minor modification was too good to pass up. # from scipy: https://github.com/scipy/scipy/blob/master/scipy/stats/kde.py
def __init__(self, dataset, bw_method=None): self.dataset = np.atleast_2d(dataset) if not np.array(self.dataset).size > 1: raise ValueError("`dataset` input should have multiple elements.")
self.dim, self.num_dp = np.array(self.dataset).shape
if bw_method is None: pass elif cbook._str_equal(bw_method, 'scott'): self.covariance_factor = self.scotts_factor elif cbook._str_equal(bw_method, 'silverman'): self.covariance_factor = self.silverman_factor elif isinstance(bw_method, Number): self._bw_method = 'use constant' self.covariance_factor = lambda: bw_method elif callable(bw_method): self._bw_method = bw_method self.covariance_factor = lambda: self._bw_method(self) else: raise ValueError("`bw_method` should be 'scott', 'silverman', a " "scalar or a callable")
# Computes the covariance matrix for each Gaussian kernel using # covariance_factor().
self.factor = self.covariance_factor() # Cache covariance and inverse covariance of the data if not hasattr(self, '_data_inv_cov'): self.data_covariance = np.atleast_2d( np.cov( self.dataset, rowvar=1, bias=False)) self.data_inv_cov = np.linalg.inv(self.data_covariance)
self.covariance = self.data_covariance * self.factor ** 2 self.inv_cov = self.data_inv_cov / self.factor ** 2 self.norm_factor = (np.sqrt(np.linalg.det(2 * np.pi * self.covariance)) * self.num_dp)
def scotts_factor(self): return np.power(self.num_dp, -1. / (self.dim + 4))
def silverman_factor(self): return np.power( self.num_dp * (self.dim + 2.0) / 4.0, -1. / (self.dim + 4))
# Default method to calculate bandwidth, can be overwritten by subclass covariance_factor = scotts_factor
def evaluate(self, points): """ Evaluate the estimated pdf on a set of points.
Parameters ---------- points : (# of dimensions, # of points)-array Alternatively, a (# of dimensions,) vector can be passed in and treated as a single point.
Returns ------- (# of points,)-array The values at each point.
Raises ------ ValueError : if the dimensionality of the input points is different than the dimensionality of the KDE.
""" points = np.atleast_2d(points)
dim, num_m = np.array(points).shape if dim != self.dim: raise ValueError(f"points have dimension {dim}, dataset has " f"dimension {self.dim}")
result = np.zeros(num_m)
if num_m >= self.num_dp: # there are more points than data, so loop over data for i in range(self.num_dp): diff = self.dataset[:, i, np.newaxis] - points tdiff = np.dot(self.inv_cov, diff) energy = np.sum(diff * tdiff, axis=0) / 2.0 result = result + np.exp(-energy) else: # loop over points for i in range(num_m): diff = self.dataset - points[:, i, np.newaxis] tdiff = np.dot(self.inv_cov, diff) energy = np.sum(diff * tdiff, axis=0) / 2.0 result[i] = np.sum(np.exp(-energy), axis=0)
result = result / self.norm_factor
return result
__call__ = evaluate12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613r"""Container classes for `.Artist`\s.
`OffsetBox` The base of all container artists defined in this module.
`AnchoredOffsetbox`, `AnchoredText` Anchor and align an arbitrary `.Artist` or a text relative to the parent axes or a specific anchor point.
`DrawingArea` A container with fixed width and height. Children have a fixed position inside the container and may be clipped.
`HPacker`, `VPacker` Containers for layouting their children vertically or horizontally.
`PaddedBox` A container to add a padding around an `.Artist`.
`TextArea` Contains a single `.Text` instance."""
import functools
import numpy as np
import matplotlib as mplfrom matplotlib import _api, _docstringimport matplotlib.artist as martistimport matplotlib.path as mpathimport matplotlib.text as mtextimport matplotlib.transforms as mtransformsfrom matplotlib.font_manager import FontPropertiesfrom matplotlib.image import BboxImagefrom matplotlib.patches import ( FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist)from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
DEBUG = False
def _compat_get_offset(meth): """ Decorator for the get_offset method of OffsetBox and subclasses, that allows supporting both the new signature (self, bbox, renderer) and the old signature (self, width, height, xdescent, ydescent, renderer). """ sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(), lambda self, bbox, renderer: locals()]
@functools.wraps(meth) def get_offset(self, *args, **kwargs): params = _api.select_matching_signature(sigs, self, *args, **kwargs) bbox = (params["bbox"] if "bbox" in params else Bbox.from_bounds(-params["xdescent"], -params["ydescent"], params["width"], params["height"])) return meth(params["self"], bbox, params["renderer"]) return get_offset
# for debugging usedef _bbox_artist(*args, **kwargs): if DEBUG: mbbox_artist(*args, **kwargs)
def _get_packed_offsets(widths, total, sep, mode="fixed"): r""" Pack boxes specified by their *widths*.
For simplicity of the description, the terminology used here assumes a horizontal layout, but the function works equally for a vertical layout.
There are three packing *mode*\s:
- 'fixed': The elements are packed tight to the left with a spacing of *sep* in between. If *total* is *None* the returned total will be the right edge of the last box. A non-*None* total will be passed unchecked to the output. In particular this means that right edge of the last box may be further to the right than the returned total.
- 'expand': Distribute the boxes with equal spacing so that the left edge of the first box is at 0, and the right edge of the last box is at *total*. The parameter *sep* is ignored in this mode. A total of *None* is accepted and considered equal to 1. The total is returned unchanged (except for the conversion *None* to 1). If the total is smaller than the sum of the widths, the laid out boxes will overlap.
- 'equal': If *total* is given, the total space is divided in N equal ranges and each box is left-aligned within its subspace. Otherwise (*total* is *None*), *sep* must be provided and each box is left-aligned in its subspace of width ``(max(widths) + sep)``. The total width is then calculated to be ``N * (max(widths) + sep)``.
Parameters ---------- widths : list of float Widths of boxes to be packed. total : float or None Intended total length. *None* if not used. sep : float or None Spacing between boxes. mode : {'fixed', 'expand', 'equal'} The packing mode.
Returns ------- total : float The total width needed to accommodate the laid out boxes. offsets : array of float The left offsets of the boxes. """ _api.check_in_list(["fixed", "expand", "equal"], mode=mode)
if mode == "fixed": offsets_ = np.cumsum([0] + [w + sep for w in widths]) offsets = offsets_[:-1] if total is None: total = offsets_[-1] - sep return total, offsets
elif mode == "expand": # This is a bit of a hack to avoid a TypeError when *total* # is None and used in conjugation with tight layout. if total is None: total = 1 if len(widths) > 1: sep = (total - sum(widths)) / (len(widths) - 1) else: sep = 0 offsets_ = np.cumsum([0] + [w + sep for w in widths]) offsets = offsets_[:-1] return total, offsets
elif mode == "equal": maxh = max(widths) if total is None: if sep is None: raise ValueError("total and sep cannot both be None when " "using layout mode 'equal'") total = (maxh + sep) * len(widths) else: sep = total / len(widths) - maxh offsets = (maxh + sep) * np.arange(len(widths)) return total, offsets
def _get_aligned_offsets(yspans, height, align="baseline"): """ Align boxes each specified by their ``(y0, y1)`` spans.
For simplicity of the description, the terminology used here assumes a horizontal layout (i.e., vertical alignment), but the function works equally for a vertical layout.
Parameters ---------- yspans List of (y0, y1) spans of boxes to be aligned. height : float or None Intended total height. If None, the maximum of the heights (``y1 - y0``) in *yspans* is used. align : {'baseline', 'left', 'top', 'right', 'bottom', 'center'} The alignment anchor of the boxes.
Returns ------- (y0, y1) y range spanned by the packing. If a *height* was originally passed in, then for all alignments other than "baseline", a span of ``(0, height)`` is used without checking that it is actually large enough). descent The descent of the packing. offsets The bottom offsets of the boxes. """
_api.check_in_list( ["baseline", "left", "top", "right", "bottom", "center"], align=align) if height is None: height = max(y1 - y0 for y0, y1 in yspans)
if align == "baseline": yspan = (min(y0 for y0, y1 in yspans), max(y1 for y0, y1 in yspans)) offsets = [0] * len(yspans) elif align in ["left", "bottom"]: yspan = (0, height) offsets = [-y0 for y0, y1 in yspans] elif align in ["right", "top"]: yspan = (0, height) offsets = [height - y1 for y0, y1 in yspans] elif align == "center": yspan = (0, height) offsets = [(height - (y1 - y0)) * .5 - y0 for y0, y1 in yspans]
return yspan, offsets
class OffsetBox(martist.Artist): """ The OffsetBox is a simple container artist.
The child artists are meant to be drawn at a relative position to its parent.
Being an artist itself, all parameters are passed on to `.Artist`. """ def __init__(self, *args, **kwargs): super().__init__(*args) self._internal_update(kwargs) # Clipping has not been implemented in the OffsetBox family, so # disable the clip flag for consistency. It can always be turned back # on to zero effect. self.set_clip_on(False) self._children = [] self._offset = (0, 0)
def set_figure(self, fig): """ Set the `.Figure` for the `.OffsetBox` and all its children.
Parameters ---------- fig : `~matplotlib.figure.Figure` """ super().set_figure(fig) for c in self.get_children(): c.set_figure(fig)
@martist.Artist.axes.setter def axes(self, ax): # TODO deal with this better martist.Artist.axes.fset(self, ax) for c in self.get_children(): if c is not None: c.axes = ax
def contains(self, mouseevent): """ Delegate the mouse event contains-check to the children.
As a container, the `.OffsetBox` does not respond itself to mouseevents.
Parameters ---------- mouseevent : `~matplotlib.backend_bases.MouseEvent`
Returns ------- contains : bool Whether any values are within the radius. details : dict An artist-specific dictionary of details of the event context, such as which points are contained in the pick radius. See the individual Artist subclasses for details.
See Also -------- .Artist.contains """ if self._different_canvas(mouseevent): return False, {} for c in self.get_children(): a, b = c.contains(mouseevent) if a: return a, b return False, {}
def set_offset(self, xy): """ Set the offset.
Parameters ---------- xy : (float, float) or callable The (x, y) coordinates of the offset in display units. These can either be given explicitly as a tuple (x, y), or by providing a function that converts the extent into the offset. This function must have the signature::
def offset(width, height, xdescent, ydescent, renderer) \-> (float, float) """ self._offset = xy self.stale = True
@_compat_get_offset def get_offset(self, bbox, renderer): """ Return the offset as a tuple (x, y).
The extent parameters have to be provided to handle the case where the offset is dynamically determined by a callable (see `~.OffsetBox.set_offset`).
Parameters ---------- bbox : `.Bbox` renderer : `.RendererBase` subclass """ return ( self._offset(bbox.width, bbox.height, -bbox.x0, -bbox.y0, renderer) if callable(self._offset) else self._offset)
def set_width(self, width): """ Set the width of the box.
Parameters ---------- width : float """ self.width = width self.stale = True
def set_height(self, height): """ Set the height of the box.
Parameters ---------- height : float """ self.height = height self.stale = True
def get_visible_children(self): r"""Return a list of the visible child `.Artist`\s.""" return [c for c in self._children if c.get_visible()]
def get_children(self): r"""Return a list of the child `.Artist`\s.""" return self._children
def _get_bbox_and_child_offsets(self, renderer): """ Return the bbox of the offsetbox and the child offsets.
The bbox should satisfy ``x0 <= x1 and y0 <= y1``.
Parameters ---------- renderer : `.RendererBase` subclass
Returns ------- bbox list of (xoffset, yoffset) pairs """ raise NotImplementedError( "get_bbox_and_offsets must be overridden in derived classes")
def get_bbox(self, renderer): """Return the bbox of the offsetbox, ignoring parent offsets.""" bbox, offsets = self._get_bbox_and_child_offsets(renderer) return bbox
def get_window_extent(self, renderer=None): # docstring inherited if renderer is None: renderer = self.get_figure(root=True)._get_renderer() bbox = self.get_bbox(renderer) try: # Some subclasses redefine get_offset to take no args. px, py = self.get_offset(bbox, renderer) except TypeError: px, py = self.get_offset() return bbox.translated(px, py)
def draw(self, renderer): """ Update the location of children if necessary and draw them to the given *renderer*. """ bbox, offsets = self._get_bbox_and_child_offsets(renderer) px, py = self.get_offset(bbox, renderer) for c, (ox, oy) in zip(self.get_visible_children(), offsets): c.set_offset((px + ox, py + oy)) c.draw(renderer) _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) self.stale = False
class PackerBase(OffsetBox): def __init__(self, pad=0., sep=0., width=None, height=None, align="baseline", mode="fixed", children=None): """ Parameters ---------- pad : float, default: 0.0 The boundary padding in points.
sep : float, default: 0.0 The spacing between items in points.
width, height : float, optional Width and height of the container box in pixels, calculated if *None*.
align : {'top', 'bottom', 'left', 'right', 'center', 'baseline'}, \default: 'baseline' Alignment of boxes.
mode : {'fixed', 'expand', 'equal'}, default: 'fixed' The packing mode.
- 'fixed' packs the given `.Artist`\\s tight with *sep* spacing. - 'expand' uses the maximal available space to distribute the artists with equal spacing in between. - 'equal': Each artist an equal fraction of the available space and is left-aligned (or top-aligned) therein.
children : list of `.Artist` The artists to pack.
Notes ----- *pad* and *sep* are in points and will be scaled with the renderer dpi, while *width* and *height* are in pixels. """ super().__init__() self.height = height self.width = width self.sep = sep self.pad = pad self.mode = mode self.align = align self._children = children
class VPacker(PackerBase): """ VPacker packs its children vertically, automatically adjusting their relative positions at draw time.
.. code-block:: none
+---------+ | Child 1 | | Child 2 | | Child 3 | +---------+ """
def _get_bbox_and_child_offsets(self, renderer): # docstring inherited dpicor = renderer.points_to_pixels(1.) pad = self.pad * dpicor sep = self.sep * dpicor
if self.width is not None: for c in self.get_visible_children(): if isinstance(c, PackerBase) and c.mode == "expand": c.set_width(self.width)
bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()] (x0, x1), xoffsets = _get_aligned_offsets( [bbox.intervalx for bbox in bboxes], self.width, self.align) height, yoffsets = _get_packed_offsets( [bbox.height for bbox in bboxes], self.height, sep, self.mode)
yoffsets = height - (yoffsets + [bbox.y1 for bbox in bboxes]) ydescent = yoffsets[0] yoffsets = yoffsets - ydescent
return ( Bbox.from_bounds(x0, -ydescent, x1 - x0, height).padded(pad), [*zip(xoffsets, yoffsets)])
class HPacker(PackerBase): """ HPacker packs its children horizontally, automatically adjusting their relative positions at draw time.
.. code-block:: none
+-------------------------------+ | Child 1 Child 2 Child 3 | +-------------------------------+ """
def _get_bbox_and_child_offsets(self, renderer): # docstring inherited dpicor = renderer.points_to_pixels(1.) pad = self.pad * dpicor sep = self.sep * dpicor
bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()] if not bboxes: return Bbox.from_bounds(0, 0, 0, 0).padded(pad), []
(y0, y1), yoffsets = _get_aligned_offsets( [bbox.intervaly for bbox in bboxes], self.height, self.align) width, xoffsets = _get_packed_offsets( [bbox.width for bbox in bboxes], self.width, sep, self.mode)
x0 = bboxes[0].x0 xoffsets -= ([bbox.x0 for bbox in bboxes] - x0)
return (Bbox.from_bounds(x0, y0, width, y1 - y0).padded(pad), [*zip(xoffsets, yoffsets)])
class PaddedBox(OffsetBox): """ A container to add a padding around an `.Artist`.
The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize it when rendering.
.. code-block:: none
+----------------------------+ | | | | | | | <--pad--> Artist | | ^ | | pad | | v | +----------------------------+
Attributes ---------- pad : float The padding in points. patch : `.FancyBboxPatch` When *draw_frame* is True, this `.FancyBboxPatch` is made visible and creates a border around the box. """
def __init__(self, child, pad=0., *, draw_frame=False, patch_attrs=None): """ Parameters ---------- child : `~matplotlib.artist.Artist` The contained `.Artist`. pad : float, default: 0.0 The padding in points. This will be scaled with the renderer dpi. In contrast, *width* and *height* are in *pixels* and thus not scaled. draw_frame : bool Whether to draw the contained `.FancyBboxPatch`. patch_attrs : dict or None Additional parameters passed to the contained `.FancyBboxPatch`. """ super().__init__() self.pad = pad self._children = [child] self.patch = FancyBboxPatch( xy=(0.0, 0.0), width=1., height=1., facecolor='w', edgecolor='k', mutation_scale=1, # self.prop.get_size_in_points(), snap=True, visible=draw_frame, boxstyle="square,pad=0", ) if patch_attrs is not None: self.patch.update(patch_attrs)
def _get_bbox_and_child_offsets(self, renderer): # docstring inherited. pad = self.pad * renderer.points_to_pixels(1.) return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)])
def draw(self, renderer): # docstring inherited bbox, offsets = self._get_bbox_and_child_offsets(renderer) px, py = self.get_offset(bbox, renderer) for c, (ox, oy) in zip(self.get_visible_children(), offsets): c.set_offset((px + ox, py + oy))
self.draw_frame(renderer)
for c in self.get_visible_children(): c.draw(renderer)
self.stale = False
def update_frame(self, bbox, fontsize=None): self.patch.set_bounds(bbox.bounds) if fontsize: self.patch.set_mutation_scale(fontsize) self.stale = True
def draw_frame(self, renderer): # update the location and size of the legend self.update_frame(self.get_window_extent(renderer)) self.patch.draw(renderer)
class DrawingArea(OffsetBox): """ The DrawingArea can contain any Artist as a child. The DrawingArea has a fixed width and height. The position of children relative to the parent is fixed. The children can be clipped at the boundaries of the parent. """
def __init__(self, width, height, xdescent=0., ydescent=0., clip=False): """ Parameters ---------- width, height : float Width and height of the container box. xdescent, ydescent : float Descent of the box in x- and y-direction. clip : bool Whether to clip the children to the box. """ super().__init__() self.width = width self.height = height self.xdescent = xdescent self.ydescent = ydescent self._clip_children = clip self.offset_transform = mtransforms.Affine2D() self.dpi_transform = mtransforms.Affine2D()
@property def clip_children(self): """ If the children of this DrawingArea should be clipped by DrawingArea bounding box. """ return self._clip_children
@clip_children.setter def clip_children(self, val): self._clip_children = bool(val) self.stale = True
def get_transform(self): """ Return the `~matplotlib.transforms.Transform` applied to the children. """ return self.dpi_transform + self.offset_transform
def set_transform(self, t): """ set_transform is ignored. """
def set_offset(self, xy): """ Set the offset of the container.
Parameters ---------- xy : (float, float) The (x, y) coordinates of the offset in display units. """ self._offset = xy self.offset_transform.clear() self.offset_transform.translate(xy[0], xy[1]) self.stale = True
def get_offset(self): """Return offset of the container.""" return self._offset
def get_bbox(self, renderer): # docstring inherited dpi_cor = renderer.points_to_pixels(1.) return Bbox.from_bounds( -self.xdescent * dpi_cor, -self.ydescent * dpi_cor, self.width * dpi_cor, self.height * dpi_cor)
def add_artist(self, a): """Add an `.Artist` to the container box.""" self._children.append(a) if not a.is_transform_set(): a.set_transform(self.get_transform()) if self.axes is not None: a.axes = self.axes fig = self.get_figure(root=False) if fig is not None: a.set_figure(fig)
def draw(self, renderer): # docstring inherited
dpi_cor = renderer.points_to_pixels(1.) self.dpi_transform.clear() self.dpi_transform.scale(dpi_cor)
# At this point the DrawingArea has a transform # to the display space so the path created is # good for clipping children tpath = mtransforms.TransformedPath( mpath.Path([[0, 0], [0, self.height], [self.width, self.height], [self.width, 0]]), self.get_transform()) for c in self._children: if self._clip_children and not (c.clipbox or c._clippath): c.set_clip_path(tpath) c.draw(renderer)
_bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) self.stale = False
class TextArea(OffsetBox): """ The TextArea is a container artist for a single Text instance.
The text is placed at (0, 0) with baseline+left alignment, by default. The width and height of the TextArea instance is the width and height of its child text. """
def __init__(self, s, *, textprops=None, multilinebaseline=False, ): """ Parameters ---------- s : str The text to be displayed. textprops : dict, default: {} Dictionary of keyword parameters to be passed to the `.Text` instance in the TextArea. multilinebaseline : bool, default: False Whether the baseline for multiline text is adjusted so that it is (approximately) center-aligned with single-line text. """ if textprops is None: textprops = {} self._text = mtext.Text(0, 0, s, **textprops) super().__init__() self._children = [self._text] self.offset_transform = mtransforms.Affine2D() self._baseline_transform = mtransforms.Affine2D() self._text.set_transform(self.offset_transform + self._baseline_transform) self._multilinebaseline = multilinebaseline
def set_text(self, s): """Set the text of this area as a string.""" self._text.set_text(s) self.stale = True
def get_text(self): """Return the string representation of this area's text.""" return self._text.get_text()
def set_multilinebaseline(self, t): """ Set multilinebaseline.
If True, the baseline for multiline text is adjusted so that it is (approximately) center-aligned with single-line text. This is used e.g. by the legend implementation so that single-line labels are baseline-aligned, but multiline labels are "center"-aligned with them. """ self._multilinebaseline = t self.stale = True
def get_multilinebaseline(self): """ Get multilinebaseline. """ return self._multilinebaseline
def set_transform(self, t): """ set_transform is ignored. """
def set_offset(self, xy): """ Set the offset of the container.
Parameters ---------- xy : (float, float) The (x, y) coordinates of the offset in display units. """ self._offset = xy self.offset_transform.clear() self.offset_transform.translate(xy[0], xy[1]) self.stale = True
def get_offset(self): """Return offset of the container.""" return self._offset
def get_bbox(self, renderer): _, h_, d_ = mtext._get_text_metrics_with_cache( renderer, "lp", self._text._fontproperties, ismath="TeX" if self._text.get_usetex() else False, dpi=self.get_figure(root=True).dpi)
bbox, info, yd = self._text._get_layout(renderer) w, h = bbox.size
self._baseline_transform.clear()
if len(info) > 1 and self._multilinebaseline: yd_new = 0.5 * h - 0.5 * (h_ - d_) self._baseline_transform.translate(0, yd - yd_new) yd = yd_new else: # single line h_d = max(h_ - d_, h - yd) h = h_d + yd
ha = self._text.get_horizontalalignment() x0 = {"left": 0, "center": -w / 2, "right": -w}[ha]
return Bbox.from_bounds(x0, -yd, w, h)
def draw(self, renderer): # docstring inherited self._text.draw(renderer) _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) self.stale = False
class AuxTransformBox(OffsetBox): """ Offset Box with the aux_transform. Its children will be transformed with the aux_transform first then will be offsetted. The absolute coordinate of the aux_transform is meaning as it will be automatically adjust so that the left-lower corner of the bounding box of children will be set to (0, 0) before the offset transform.
It is similar to drawing area, except that the extent of the box is not predetermined but calculated from the window extent of its children. Furthermore, the extent of the children will be calculated in the transformed coordinate. """ def __init__(self, aux_transform): self.aux_transform = aux_transform super().__init__() self.offset_transform = mtransforms.Affine2D() # ref_offset_transform makes offset_transform always relative to the # lower-left corner of the bbox of its children. self.ref_offset_transform = mtransforms.Affine2D()
def add_artist(self, a): """Add an `.Artist` to the container box.""" self._children.append(a) a.set_transform(self.get_transform()) self.stale = True
def get_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` applied to the children """ return (self.aux_transform + self.ref_offset_transform + self.offset_transform)
def set_transform(self, t): """ set_transform is ignored. """
def set_offset(self, xy): """ Set the offset of the container.
Parameters ---------- xy : (float, float) The (x, y) coordinates of the offset in display units. """ self._offset = xy self.offset_transform.clear() self.offset_transform.translate(xy[0], xy[1]) self.stale = True
def get_offset(self): """Return offset of the container.""" return self._offset
def get_bbox(self, renderer): # clear the offset transforms _off = self.offset_transform.get_matrix() # to be restored later self.ref_offset_transform.clear() self.offset_transform.clear() # calculate the extent bboxes = [c.get_window_extent(renderer) for c in self._children] ub = Bbox.union(bboxes) # adjust ref_offset_transform self.ref_offset_transform.translate(-ub.x0, -ub.y0) # restore offset transform self.offset_transform.set_matrix(_off) return Bbox.from_bounds(0, 0, ub.width, ub.height)
def draw(self, renderer): # docstring inherited for c in self._children: c.draw(renderer) _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) self.stale = False
class AnchoredOffsetbox(OffsetBox): """ An offset box placed according to location *loc*.
AnchoredOffsetbox has a single child. When multiple children are needed, use an extra OffsetBox to enclose them. By default, the offset box is anchored against its parent Axes. You may explicitly specify the *bbox_to_anchor*. """ zorder = 5 # zorder of the legend
# Location codes codes = {'upper right': 1, 'upper left': 2, 'lower left': 3, 'lower right': 4, 'right': 5, 'center left': 6, 'center right': 7, 'lower center': 8, 'upper center': 9, 'center': 10, }
def __init__(self, loc, *, pad=0.4, borderpad=0.5, child=None, prop=None, frameon=True, bbox_to_anchor=None, bbox_transform=None, **kwargs): """ Parameters ---------- loc : str The box location. Valid locations are 'upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center', 'lower right'. For backward compatibility, numeric values are accepted as well. See the parameter *loc* of `.Legend` for details. pad : float, default: 0.4 Padding around the child as fraction of the fontsize. borderpad : float, default: 0.5 Padding between the offsetbox frame and the *bbox_to_anchor*. child : `.OffsetBox` The box that will be anchored. prop : `.FontProperties` This is only used as a reference for paddings. If not given, :rc:`legend.fontsize` is used. frameon : bool Whether to draw a frame around the box. bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats Box that is used to position the legend in conjunction with *loc*. bbox_transform : None or :class:`matplotlib.transforms.Transform` The transform for the bounding box (*bbox_to_anchor*). **kwargs All other parameters are passed on to `.OffsetBox`.
Notes ----- See `.Legend` for a detailed description of the anchoring mechanism. """ super().__init__(**kwargs)
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) self.set_child(child)
if isinstance(loc, str): loc = _api.check_getitem(self.codes, loc=loc)
self.loc = loc self.borderpad = borderpad self.pad = pad
if prop is None: self.prop = FontProperties(size=mpl.rcParams["legend.fontsize"]) else: self.prop = FontProperties._from_any(prop) if isinstance(prop, dict) and "size" not in prop: self.prop.set_size(mpl.rcParams["legend.fontsize"])
self.patch = FancyBboxPatch( xy=(0.0, 0.0), width=1., height=1., facecolor='w', edgecolor='k', mutation_scale=self.prop.get_size_in_points(), snap=True, visible=frameon, boxstyle="square,pad=0", )
def set_child(self, child): """Set the child to be anchored.""" self._child = child if child is not None: child.axes = self.axes self.stale = True
def get_child(self): """Return the child.""" return self._child
def get_children(self): """Return the list of children.""" return [self._child]
def get_bbox(self, renderer): # docstring inherited fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) pad = self.pad * fontsize return self.get_child().get_bbox(renderer).padded(pad)
def get_bbox_to_anchor(self): """Return the bbox that the box is anchored to.""" if self._bbox_to_anchor is None: return self.axes.bbox else: transform = self._bbox_to_anchor_transform if transform is None: return self._bbox_to_anchor else: return TransformedBbox(self._bbox_to_anchor, transform)
def set_bbox_to_anchor(self, bbox, transform=None): """ Set the bbox that the box is anchored to.
*bbox* can be a Bbox instance, a list of [left, bottom, width, height], or a list of [left, bottom] where the width and height will be assumed to be zero. The bbox will be transformed to display coordinate by the given transform. """ if bbox is None or isinstance(bbox, BboxBase): self._bbox_to_anchor = bbox else: try: l = len(bbox) except TypeError as err: raise ValueError(f"Invalid bbox: {bbox}") from err
if l == 2: bbox = [bbox[0], bbox[1], 0, 0]
self._bbox_to_anchor = Bbox.from_bounds(*bbox)
self._bbox_to_anchor_transform = transform self.stale = True
@_compat_get_offset def get_offset(self, bbox, renderer): # docstring inherited pad = (self.borderpad * renderer.points_to_pixels(self.prop.get_size_in_points())) bbox_to_anchor = self.get_bbox_to_anchor() x0, y0 = _get_anchored_bbox( self.loc, Bbox.from_bounds(0, 0, bbox.width, bbox.height), bbox_to_anchor, pad) return x0 - bbox.x0, y0 - bbox.y0
def update_frame(self, bbox, fontsize=None): self.patch.set_bounds(bbox.bounds) if fontsize: self.patch.set_mutation_scale(fontsize)
def draw(self, renderer): # docstring inherited if not self.get_visible(): return
# update the location and size of the legend bbox = self.get_window_extent(renderer) fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) self.update_frame(bbox, fontsize) self.patch.draw(renderer)
px, py = self.get_offset(self.get_bbox(renderer), renderer) self.get_child().set_offset((px, py)) self.get_child().draw(renderer) self.stale = False
def _get_anchored_bbox(loc, bbox, parentbbox, borderpad): """ Return the (x, y) position of the *bbox* anchored at the *parentbbox* with the *loc* code with the *borderpad*. """ # This is only called internally and *loc* should already have been # validated. If 0 (None), we just let ``bbox.anchored`` raise. c = [None, "NE", "NW", "SW", "SE", "E", "W", "E", "S", "N", "C"][loc] container = parentbbox.padded(-borderpad) return bbox.anchored(c, container=container).p0
class AnchoredText(AnchoredOffsetbox): """ AnchoredOffsetbox with Text. """
def __init__(self, s, loc, *, pad=0.4, borderpad=0.5, prop=None, **kwargs): """ Parameters ---------- s : str Text.
loc : str Location code. See `AnchoredOffsetbox`.
pad : float, default: 0.4 Padding around the text as fraction of the fontsize.
borderpad : float, default: 0.5 Spacing between the offsetbox frame and the *bbox_to_anchor*.
prop : dict, optional Dictionary of keyword parameters to be passed to the `~matplotlib.text.Text` instance contained inside AnchoredText.
**kwargs All other parameters are passed to `AnchoredOffsetbox`. """
if prop is None: prop = {} badkwargs = {'va', 'verticalalignment'} if badkwargs & set(prop): raise ValueError( 'Mixing verticalalignment with AnchoredText is not supported.')
self.txt = TextArea(s, textprops=prop) fp = self.txt._text.get_fontproperties() super().__init__( loc, pad=pad, borderpad=borderpad, child=self.txt, prop=fp, **kwargs)
class OffsetImage(OffsetBox):
def __init__(self, arr, *, zoom=1, cmap=None, norm=None, interpolation=None, origin=None, filternorm=True, filterrad=4.0, resample=False, dpi_cor=True, **kwargs ):
super().__init__() self._dpi_cor = dpi_cor
self.image = BboxImage(bbox=self.get_window_extent, cmap=cmap, norm=norm, interpolation=interpolation, origin=origin, filternorm=filternorm, filterrad=filterrad, resample=resample, **kwargs )
self._children = [self.image]
self.set_zoom(zoom) self.set_data(arr)
def set_data(self, arr): self._data = np.asarray(arr) self.image.set_data(self._data) self.stale = True
def get_data(self): return self._data
def set_zoom(self, zoom): self._zoom = zoom self.stale = True
def get_zoom(self): return self._zoom
def get_offset(self): """Return offset of the container.""" return self._offset
def get_children(self): return [self.image]
def get_bbox(self, renderer): dpi_cor = renderer.points_to_pixels(1.) if self._dpi_cor else 1. zoom = self.get_zoom() data = self.get_data() ny, nx = data.shape[:2] w, h = dpi_cor * nx * zoom, dpi_cor * ny * zoom return Bbox.from_bounds(0, 0, w, h)
def draw(self, renderer): # docstring inherited self.image.draw(renderer) # bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) self.stale = False
class AnnotationBbox(martist.Artist, mtext._AnnotationBase): """ Container for an `OffsetBox` referring to a specific position *xy*.
Optionally an arrow pointing from the offsetbox to *xy* can be drawn.
This is like `.Annotation`, but with `OffsetBox` instead of `.Text`. """
zorder = 3
def __str__(self): return f"AnnotationBbox({self.xy[0]:g},{self.xy[1]:g})"
@_docstring.interpd def __init__(self, offsetbox, xy, xybox=None, xycoords='data', boxcoords=None, *, frameon=True, pad=0.4, # FancyBboxPatch boxstyle. annotation_clip=None, box_alignment=(0.5, 0.5), bboxprops=None, arrowprops=None, fontsize=None, **kwargs): """ Parameters ---------- offsetbox : `OffsetBox`
xy : (float, float) The point *(x, y)* to annotate. The coordinate system is determined by *xycoords*.
xybox : (float, float), default: *xy* The position *(x, y)* to place the text at. The coordinate system is determined by *boxcoords*.
xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \callable, default: 'data' The coordinate system that *xy* is given in. See the parameter *xycoords* in `.Annotation` for a detailed description.
boxcoords : single or two-tuple of str or `.Artist` or `.Transform` \or callable, default: value of *xycoords* The coordinate system that *xybox* is given in. See the parameter *textcoords* in `.Annotation` for a detailed description.
frameon : bool, default: True By default, the text is surrounded by a white `.FancyBboxPatch` (accessible as the ``patch`` attribute of the `.AnnotationBbox`). If *frameon* is set to False, this patch is made invisible.
annotation_clip: bool or None, default: None Whether to clip (i.e. not draw) the annotation when the annotation point *xy* is outside the Axes area.
- If *True*, the annotation will be clipped when *xy* is outside the Axes. - If *False*, the annotation will always be drawn. - If *None*, the annotation will be clipped when *xy* is outside the Axes and *xycoords* is 'data'.
pad : float, default: 0.4 Padding around the offsetbox.
box_alignment : (float, float) A tuple of two floats for a vertical and horizontal alignment of the offset box w.r.t. the *boxcoords*. The lower-left corner is (0, 0) and upper-right corner is (1, 1).
bboxprops : dict, optional A dictionary of properties to set for the annotation bounding box, for example *boxstyle* and *alpha*. See `.FancyBboxPatch` for details.
arrowprops: dict, optional Arrow properties, see `.Annotation` for description.
fontsize: float or str, optional Translated to points and passed as *mutation_scale* into `.FancyBboxPatch` to scale attributes of the box style (e.g. pad or rounding_size). The name is chosen in analogy to `.Text` where *fontsize* defines the mutation scale as well. If not given, :rc:`legend.fontsize` is used. See `.Text.set_fontsize` for valid values.
**kwargs Other `AnnotationBbox` properties. See `.AnnotationBbox.set` for a list. """
martist.Artist.__init__(self) mtext._AnnotationBase.__init__( self, xy, xycoords=xycoords, annotation_clip=annotation_clip)
self.offsetbox = offsetbox self.arrowprops = arrowprops.copy() if arrowprops is not None else None self.set_fontsize(fontsize) self.xybox = xybox if xybox is not None else xy self.boxcoords = boxcoords if boxcoords is not None else xycoords self._box_alignment = box_alignment
if arrowprops is not None: self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5)) self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), **self.arrowprops) else: self._arrow_relpos = None self.arrow_patch = None
self.patch = FancyBboxPatch( # frame xy=(0.0, 0.0), width=1., height=1., facecolor='w', edgecolor='k', mutation_scale=self.prop.get_size_in_points(), snap=True, visible=frameon, ) self.patch.set_boxstyle("square", pad=pad) if bboxprops: self.patch.set(**bboxprops)
self._internal_update(kwargs)
@property def xyann(self): return self.xybox
@xyann.setter def xyann(self, xyann): self.xybox = xyann self.stale = True
@property def anncoords(self): return self.boxcoords
@anncoords.setter def anncoords(self, coords): self.boxcoords = coords self.stale = True
def contains(self, mouseevent): if self._different_canvas(mouseevent): return False, {} if not self._check_xy(None): return False, {} return self.offsetbox.contains(mouseevent) # self.arrow_patch is currently not checked as this can be a line - JJ
def get_children(self): children = [self.offsetbox, self.patch] if self.arrow_patch: children.append(self.arrow_patch) return children
def set_figure(self, fig): if self.arrow_patch is not None: self.arrow_patch.set_figure(fig) self.offsetbox.set_figure(fig) martist.Artist.set_figure(self, fig)
def set_fontsize(self, s=None): """ Set the fontsize in points.
If *s* is not given, reset to :rc:`legend.fontsize`. """ if s is None: s = mpl.rcParams["legend.fontsize"]
self.prop = FontProperties(size=s) self.stale = True
def get_fontsize(self): """Return the fontsize in points.""" return self.prop.get_size_in_points()
def get_window_extent(self, renderer=None): # docstring inherited if renderer is None: renderer = self.get_figure(root=True)._get_renderer() self.update_positions(renderer) return Bbox.union([child.get_window_extent(renderer) for child in self.get_children()])
def get_tightbbox(self, renderer=None): # docstring inherited if renderer is None: renderer = self.get_figure(root=True)._get_renderer() self.update_positions(renderer) return Bbox.union([child.get_tightbbox(renderer) for child in self.get_children()])
def update_positions(self, renderer): """Update pixel positions for the annotated point, the text, and the arrow."""
ox0, oy0 = self._get_xy(renderer, self.xybox, self.boxcoords) bbox = self.offsetbox.get_bbox(renderer) fw, fh = self._box_alignment self.offsetbox.set_offset( (ox0 - fw*bbox.width - bbox.x0, oy0 - fh*bbox.height - bbox.y0))
bbox = self.offsetbox.get_window_extent(renderer) self.patch.set_bounds(bbox.bounds)
mutation_scale = renderer.points_to_pixels(self.get_fontsize()) self.patch.set_mutation_scale(mutation_scale)
if self.arrowprops: # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.
# Adjust the starting point of the arrow relative to the textbox. # TODO: Rotation needs to be accounted. arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos arrow_end = self._get_position_xy(renderer) # The arrow (from arrow_begin to arrow_end) will be first clipped # by patchA and patchB, then shrunk by shrinkA and shrinkB (in # points). If patch A is not set, self.bbox_patch is used. self.arrow_patch.set_positions(arrow_begin, arrow_end)
if "mutation_scale" in self.arrowprops: mutation_scale = renderer.points_to_pixels( self.arrowprops["mutation_scale"]) # Else, use fontsize-based mutation_scale defined above. self.arrow_patch.set_mutation_scale(mutation_scale)
patchA = self.arrowprops.get("patchA", self.patch) self.arrow_patch.set_patchA(patchA)
def draw(self, renderer): # docstring inherited if not self.get_visible() or not self._check_xy(renderer): return renderer.open_group(self.__class__.__name__, gid=self.get_gid()) self.update_positions(renderer) if self.arrow_patch is not None: if (self.arrow_patch.get_figure(root=False) is None and (fig := self.get_figure(root=False)) is not None): self.arrow_patch.set_figure(fig) self.arrow_patch.draw(renderer) self.patch.draw(renderer) self.offsetbox.draw(renderer) renderer.close_group(self.__class__.__name__) self.stale = False
class DraggableBase: """ Helper base class for a draggable artist (legend, offsetbox).
Derived classes must override the following methods::
def save_offset(self): ''' Called when the object is picked for dragging; should save the reference position of the artist. '''
def update_offset(self, dx, dy): ''' Called during the dragging; (*dx*, *dy*) is the pixel offset from the point where the mouse drag started. '''
Optionally, you may override the following method::
def finalize_offset(self): '''Called when the mouse is released.'''
In the current implementation of `.DraggableLegend` and `DraggableAnnotation`, `update_offset` places the artists in display coordinates, and `finalize_offset` recalculates their position in axes coordinate and set a relevant attribute. """
def __init__(self, ref_artist, use_blit=False): self.ref_artist = ref_artist if not ref_artist.pickable(): ref_artist.set_picker(self._picker) self.got_artist = False self._use_blit = use_blit and self.canvas.supports_blit callbacks = self.canvas.callbacks self._disconnectors = [ functools.partial( callbacks.disconnect, callbacks._connect_picklable(name, func)) for name, func in [ ("pick_event", self.on_pick), ("button_release_event", self.on_release), ("motion_notify_event", self.on_motion), ] ]
@staticmethod def _picker(artist, mouseevent): # A custom picker to prevent dragging on mouse scroll events return (artist.contains(mouseevent) and mouseevent.name != "scroll_event"), {}
# A property, not an attribute, to maintain picklability. canvas = property(lambda self: self.ref_artist.get_figure(root=True).canvas) cids = property(lambda self: [ disconnect.args[0] for disconnect in self._disconnectors[:2]])
def on_motion(self, evt): if self._check_still_parented() and self.got_artist: dx = evt.x - self.mouse_x dy = evt.y - self.mouse_y self.update_offset(dx, dy) if self._use_blit: self.canvas.restore_region(self.background) self.ref_artist.draw( self.ref_artist.get_figure(root=True)._get_renderer()) self.canvas.blit() else: self.canvas.draw()
def on_pick(self, evt): if self._check_still_parented(): if evt.artist == self.ref_artist: self.mouse_x = evt.mouseevent.x self.mouse_y = evt.mouseevent.y self.save_offset() self.got_artist = True if self.got_artist and self._use_blit: self.ref_artist.set_animated(True) self.canvas.draw() fig = self.ref_artist.get_figure(root=False) self.background = self.canvas.copy_from_bbox(fig.bbox) self.ref_artist.draw(fig._get_renderer()) self.canvas.blit()
def on_release(self, event): if self._check_still_parented() and self.got_artist: self.finalize_offset() self.got_artist = False if self._use_blit: self.canvas.restore_region(self.background) self.ref_artist.draw(self.ref_artist.figure._get_renderer()) self.canvas.blit() self.ref_artist.set_animated(False)
def _check_still_parented(self): if self.ref_artist.get_figure(root=False) is None: self.disconnect() return False else: return True
def disconnect(self): """Disconnect the callbacks.""" for disconnector in self._disconnectors: disconnector()
def save_offset(self): pass
def update_offset(self, dx, dy): pass
def finalize_offset(self): pass
class DraggableOffsetBox(DraggableBase): def __init__(self, ref_artist, offsetbox, use_blit=False): super().__init__(ref_artist, use_blit=use_blit) self.offsetbox = offsetbox
def save_offset(self): offsetbox = self.offsetbox renderer = offsetbox.get_figure(root=True)._get_renderer() offset = offsetbox.get_offset(offsetbox.get_bbox(renderer), renderer) self.offsetbox_x, self.offsetbox_y = offset self.offsetbox.set_offset(offset)
def update_offset(self, dx, dy): loc_in_canvas = self.offsetbox_x + dx, self.offsetbox_y + dy self.offsetbox.set_offset(loc_in_canvas)
def get_loc_in_canvas(self): offsetbox = self.offsetbox renderer = offsetbox.get_figure(root=True)._get_renderer() bbox = offsetbox.get_bbox(renderer) ox, oy = offsetbox._offset loc_in_canvas = (ox + bbox.x0, oy + bbox.y0) return loc_in_canvas
class DraggableAnnotation(DraggableBase): def __init__(self, annotation, use_blit=False): super().__init__(annotation, use_blit=use_blit) self.annotation = annotation
def save_offset(self): ann = self.annotation self.ox, self.oy = ann.get_transform().transform(ann.xyann)
def update_offset(self, dx, dy): ann = self.annotation ann.xyann = ann.get_transform().inverted().transform( (self.ox + dx, self.oy + dy))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106from collections.abc import Iterable, Sequencefrom typing import Any
from matplotlib.backend_bases import RendererBase, GraphicsContextBasefrom matplotlib.path import Pathfrom matplotlib.patches import Patchfrom matplotlib.transforms import Transform
from matplotlib.typing import ColorType
class AbstractPathEffect: def __init__(self, offset: tuple[float, float] = ...) -> None: ... def draw_path( self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType | None = ..., ) -> None: ...
class PathEffectRenderer(RendererBase): def __init__( self, path_effects: Iterable[AbstractPathEffect], renderer: RendererBase ) -> None: ... def copy_with_path_effect(self, path_effects: Iterable[AbstractPathEffect]) -> PathEffectRenderer: ... def draw_path( self, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType | None = ..., ) -> None: ... def draw_markers( self, gc: GraphicsContextBase, marker_path: Path, marker_trans: Transform, path: Path, *args, **kwargs ) -> None: ... def draw_path_collection( self, gc: GraphicsContextBase, master_transform: Transform, paths: Sequence[Path], *args, **kwargs ) -> None: ... def __getattribute__(self, name: str) -> Any: ...
class Normal(AbstractPathEffect): ...
class Stroke(AbstractPathEffect): def __init__(self, offset: tuple[float, float] = ..., **kwargs) -> None: ... # rgbFace becomes non-optional def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
class withStroke(Stroke): ...
class SimplePatchShadow(AbstractPathEffect): def __init__( self, offset: tuple[float, float] = ..., shadow_rgbFace: ColorType | None = ..., alpha: float | None = ..., rho: float = ..., **kwargs ) -> None: ... # rgbFace becomes non-optional def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
class withSimplePatchShadow(SimplePatchShadow): ...
class SimpleLineShadow(AbstractPathEffect): def __init__( self, offset: tuple[float, float] = ..., shadow_color: ColorType = ..., alpha: float = ..., rho: float = ..., **kwargs ) -> None: ... # rgbFace becomes non-optional def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
class PathPatchEffect(AbstractPathEffect): patch: Patch def __init__(self, offset: tuple[float, float] = ..., **kwargs) -> None: ... # rgbFace becomes non-optional def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
class TickedStroke(AbstractPathEffect): def __init__( self, offset: tuple[float, float] = ..., spacing: float = ..., angle: float = ..., length: float = ..., **kwargs ) -> None: ... # rgbFace becomes non-optional def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
class withTickedStroke(TickedStroke): ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184import matplotlib.artist as martistimport matplotlib.collections as mcollectionsfrom matplotlib.axes import Axesfrom matplotlib.figure import Figure, SubFigurefrom matplotlib.text import Textfrom matplotlib.transforms import Transform, Bbox
import numpy as npfrom numpy.typing import ArrayLikefrom collections.abc import Sequencefrom typing import Any, Literal, overloadfrom matplotlib.typing import ColorType
class QuiverKey(martist.Artist): halign: dict[Literal["N", "S", "E", "W"], Literal["left", "center", "right"]] valign: dict[Literal["N", "S", "E", "W"], Literal["top", "center", "bottom"]] pivot: dict[Literal["N", "S", "E", "W"], Literal["middle", "tip", "tail"]] Q: Quiver X: float Y: float U: float angle: float coord: Literal["axes", "figure", "data", "inches"] color: ColorType | None label: str labelpos: Literal["N", "S", "E", "W"] labelcolor: ColorType | None fontproperties: dict[str, Any] kw: dict[str, Any] text: Text zorder: float def __init__( self, Q: Quiver, X: float, Y: float, U: float, label: str, *, angle: float = ..., coordinates: Literal["axes", "figure", "data", "inches"] = ..., color: ColorType | None = ..., labelsep: float = ..., labelpos: Literal["N", "S", "E", "W"] = ..., labelcolor: ColorType | None = ..., fontproperties: dict[str, Any] | None = ..., zorder: float | None = ..., **kwargs ) -> None: ... @property def labelsep(self) -> float: ... def set_figure(self, fig: Figure | SubFigure) -> None: ...
class Quiver(mcollections.PolyCollection): X: ArrayLike Y: ArrayLike XY: ArrayLike U: ArrayLike V: ArrayLike Umask: ArrayLike N: int scale: float | None headwidth: float headlength: float headaxislength: float minshaft: float minlength: float units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] scale_units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] | None angles: Literal["uv", "xy"] | ArrayLike width: float | None pivot: Literal["tail", "middle", "tip"] transform: Transform polykw: dict[str, Any]
@overload def __init__( self, ax: Axes, U: ArrayLike, V: ArrayLike, C: ArrayLike = ..., *, scale: float | None = ..., headwidth: float = ..., headlength: float = ..., headaxislength: float = ..., minshaft: float = ..., minlength: float = ..., units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] = ..., scale_units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] | None = ..., angles: Literal["uv", "xy"] | ArrayLike = ..., width: float | None = ..., color: ColorType | Sequence[ColorType] = ..., pivot: Literal["tail", "mid", "middle", "tip"] = ..., **kwargs ) -> None: ... @overload def __init__( self, ax: Axes, X: ArrayLike, Y: ArrayLike, U: ArrayLike, V: ArrayLike, C: ArrayLike = ..., *, scale: float | None = ..., headwidth: float = ..., headlength: float = ..., headaxislength: float = ..., minshaft: float = ..., minlength: float = ..., units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] = ..., scale_units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] | None = ..., angles: Literal["uv", "xy"] | ArrayLike = ..., width: float | None = ..., color: ColorType | Sequence[ColorType] = ..., pivot: Literal["tail", "mid", "middle", "tip"] = ..., **kwargs ) -> None: ... def get_datalim(self, transData: Transform) -> Bbox: ... def set_UVC( self, U: ArrayLike, V: ArrayLike, C: ArrayLike | None = ... ) -> None: ...
class Barbs(mcollections.PolyCollection): sizes: dict[str, float] fill_empty: bool barb_increments: dict[str, float] rounding: bool flip: np.ndarray x: ArrayLike y: ArrayLike u: ArrayLike v: ArrayLike
@overload def __init__( self, ax: Axes, U: ArrayLike, V: ArrayLike, C: ArrayLike = ..., *, pivot: str = ..., length: int = ..., barbcolor: ColorType | Sequence[ColorType] | None = ..., flagcolor: ColorType | Sequence[ColorType] | None = ..., sizes: dict[str, float] | None = ..., fill_empty: bool = ..., barb_increments: dict[str, float] | None = ..., rounding: bool = ..., flip_barb: bool | ArrayLike = ..., **kwargs ) -> None: ... @overload def __init__( self, ax: Axes, X: ArrayLike, Y: ArrayLike, U: ArrayLike, V: ArrayLike, C: ArrayLike = ..., *, pivot: str = ..., length: int = ..., barbcolor: ColorType | Sequence[ColorType] | None = ..., flagcolor: ColorType | Sequence[ColorType] | None = ..., sizes: dict[str, float] | None = ..., fill_empty: bool = ..., barb_increments: dict[str, float] | None = ..., rounding: bool = ..., flip_barb: bool | ArrayLike = ..., **kwargs ) -> None: ... def set_UVC( self, U: ArrayLike, V: ArrayLike, C: ArrayLike | None = ... ) -> None: ... def set_offsets(self, xy: ArrayLike) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178from matplotlib.axis import Axisfrom matplotlib.transforms import Transform
from collections.abc import Callable, Iterablefrom typing import Literalfrom numpy.typing import ArrayLike
class ScaleBase: def __init__(self, axis: Axis | None) -> None: ... def get_transform(self) -> Transform: ... def set_default_locators_and_formatters(self, axis: Axis) -> None: ... def limit_range_for_scale( self, vmin: float, vmax: float, minpos: float ) -> tuple[float, float]: ...
class LinearScale(ScaleBase): name: str
class FuncTransform(Transform): input_dims: int output_dims: int def __init__( self, forward: Callable[[ArrayLike], ArrayLike], inverse: Callable[[ArrayLike], ArrayLike], ) -> None: ... def inverted(self) -> FuncTransform: ...
class FuncScale(ScaleBase): name: str def __init__( self, axis: Axis | None, functions: tuple[ Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] ], ) -> None: ...
class LogTransform(Transform): input_dims: int output_dims: int base: float def __init__( self, base: float, nonpositive: Literal["clip", "mask"] = ... ) -> None: ... def inverted(self) -> InvertedLogTransform: ...
class InvertedLogTransform(Transform): input_dims: int output_dims: int base: float def __init__(self, base: float) -> None: ... def inverted(self) -> LogTransform: ...
class LogScale(ScaleBase): name: str subs: Iterable[int] | None def __init__( self, axis: Axis | None, *, base: float = ..., subs: Iterable[int] | None = ..., nonpositive: Literal["clip", "mask"] = ... ) -> None: ... @property def base(self) -> float: ... def get_transform(self) -> Transform: ...
class FuncScaleLog(LogScale): def __init__( self, axis: Axis | None, functions: tuple[ Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] ], base: float = ..., ) -> None: ... @property def base(self) -> float: ... def get_transform(self) -> Transform: ...
class SymmetricalLogTransform(Transform): input_dims: int output_dims: int base: float linthresh: float linscale: float def __init__(self, base: float, linthresh: float, linscale: float) -> None: ... def inverted(self) -> InvertedSymmetricalLogTransform: ...
class InvertedSymmetricalLogTransform(Transform): input_dims: int output_dims: int base: float linthresh: float invlinthresh: float linscale: float def __init__(self, base: float, linthresh: float, linscale: float) -> None: ... def inverted(self) -> SymmetricalLogTransform: ...
class SymmetricalLogScale(ScaleBase): name: str subs: Iterable[int] | None def __init__( self, axis: Axis | None, *, base: float = ..., linthresh: float = ..., subs: Iterable[int] | None = ..., linscale: float = ... ) -> None: ... @property def base(self) -> float: ... @property def linthresh(self) -> float: ... @property def linscale(self) -> float: ... def get_transform(self) -> SymmetricalLogTransform: ...
class AsinhTransform(Transform): input_dims: int output_dims: int linear_width: float def __init__(self, linear_width: float) -> None: ... def inverted(self) -> InvertedAsinhTransform: ...
class InvertedAsinhTransform(Transform): input_dims: int output_dims: int linear_width: float def __init__(self, linear_width: float) -> None: ... def inverted(self) -> AsinhTransform: ...
class AsinhScale(ScaleBase): name: str auto_tick_multipliers: dict[int, tuple[int, ...]] def __init__( self, axis: Axis | None, *, linear_width: float = ..., base: float = ..., subs: Iterable[int] | Literal["auto"] | None = ..., **kwargs ) -> None: ... @property def linear_width(self) -> float: ... def get_transform(self) -> AsinhTransform: ...
class LogitTransform(Transform): input_dims: int output_dims: int def __init__(self, nonpositive: Literal["mask", "clip"] = ...) -> None: ... def inverted(self) -> LogisticTransform: ...
class LogisticTransform(Transform): input_dims: int output_dims: int def __init__(self, nonpositive: Literal["mask", "clip"] = ...) -> None: ... def inverted(self) -> LogitTransform: ...
class LogitScale(ScaleBase): name: str def __init__( self, axis: Axis | None, nonpositive: Literal["mask", "clip"] = ..., *, one_half: str = ..., use_overline: bool = ... ) -> None: ... def get_transform(self) -> LogitTransform: ...
def get_scale_names() -> list[str]: ...def scale_factory(scale: str, axis: Axis, **kwargs) -> ScaleBase: ...def register_scale(scale_class: type[ScaleBase]) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596from collections.abc import MutableMappingimport functools
import numpy as np
import matplotlib as mplfrom matplotlib import _api, _docstringfrom matplotlib.artist import allow_rasterizationimport matplotlib.transforms as mtransformsimport matplotlib.patches as mpatchesimport matplotlib.path as mpath
class Spine(mpatches.Patch): """ An axis spine -- the line noting the data area boundaries.
Spines are the lines connecting the axis tick marks and noting the boundaries of the data area. They can be placed at arbitrary positions. See `~.Spine.set_position` for more information.
The default position is ``('outward', 0)``.
Spines are subclasses of `.Patch`, and inherit much of their behavior.
Spines draw a line, a circle, or an arc depending on if `~.Spine.set_patch_line`, `~.Spine.set_patch_circle`, or `~.Spine.set_patch_arc` has been called. Line-like is the default.
For examples see :ref:`spines_examples`. """ def __str__(self): return "Spine"
@_docstring.interpd def __init__(self, axes, spine_type, path, **kwargs): """ Parameters ---------- axes : `~matplotlib.axes.Axes` The `~.axes.Axes` instance containing the spine. spine_type : str The spine type. path : `~matplotlib.path.Path` The `.Path` instance used to draw the spine.
Other Parameters ---------------- **kwargs Valid keyword arguments are:
%(Patch:kwdoc)s """ super().__init__(**kwargs) self.axes = axes self.set_figure(self.axes.get_figure(root=False)) self.spine_type = spine_type self.set_facecolor('none') self.set_edgecolor(mpl.rcParams['axes.edgecolor']) self.set_linewidth(mpl.rcParams['axes.linewidth']) self.set_capstyle('projecting') self.axis = None
self.set_zorder(2.5) self.set_transform(self.axes.transData) # default transform
self._bounds = None # default bounds
# Defer initial position determination. (Not much support for # non-rectangular axes is currently implemented, and this lets # them pass through the spines machinery without errors.) self._position = None _api.check_isinstance(mpath.Path, path=path) self._path = path
# To support drawing both linear and circular spines, this # class implements Patch behavior three ways. If # self._patch_type == 'line', behave like a mpatches.PathPatch # instance. If self._patch_type == 'circle', behave like a # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like # a mpatches.Arc instance. self._patch_type = 'line'
# Behavior copied from mpatches.Ellipse: # Note: This cannot be calculated until this is added to an Axes self._patch_transform = mtransforms.IdentityTransform()
def set_patch_arc(self, center, radius, theta1, theta2): """Set the spine to be arc-like.""" self._patch_type = 'arc' self._center = center self._width = radius * 2 self._height = radius * 2 self._theta1 = theta1 self._theta2 = theta2 self._path = mpath.Path.arc(theta1, theta2) # arc drawn on axes transform self.set_transform(self.axes.transAxes) self.stale = True
def set_patch_circle(self, center, radius): """Set the spine to be circular.""" self._patch_type = 'circle' self._center = center self._width = radius * 2 self._height = radius * 2 # circle drawn on axes transform self.set_transform(self.axes.transAxes) self.stale = True
def set_patch_line(self): """Set the spine to be linear.""" self._patch_type = 'line' self.stale = True
# Behavior copied from mpatches.Ellipse: def _recompute_transform(self): """ Notes ----- 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. """ assert self._patch_type in ('arc', 'circle') center = (self.convert_xunits(self._center[0]), self.convert_yunits(self._center[1])) width = self.convert_xunits(self._width) height = self.convert_yunits(self._height) self._patch_transform = mtransforms.Affine2D() \ .scale(width * 0.5, height * 0.5) \ .translate(*center)
def get_patch_transform(self): if self._patch_type in ('arc', 'circle'): self._recompute_transform() return self._patch_transform else: return super().get_patch_transform()
def get_window_extent(self, renderer=None): """ Return the window extent of the spines in display space, including padding for ticks (but not their labels)
See Also -------- matplotlib.axes.Axes.get_tightbbox matplotlib.axes.Axes.get_window_extent """ # make sure the location is updated so that transforms etc are correct: self._adjust_location() bb = super().get_window_extent(renderer=renderer) if self.axis is None or not self.axis.get_visible(): return bb bboxes = [bb] drawn_ticks = self.axis._update_ticks()
major_tick = next(iter({*drawn_ticks} & {*self.axis.majorTicks}), None) minor_tick = next(iter({*drawn_ticks} & {*self.axis.minorTicks}), None) for tick in [major_tick, minor_tick]: if tick is None: continue bb0 = bb.frozen() tickl = tick._size tickdir = tick._tickdir if tickdir == 'out': padout = 1 padin = 0 elif tickdir == 'in': padout = 0 padin = 1 else: padout = 0.5 padin = 0.5 dpi = self.get_figure(root=True).dpi padout = padout * tickl / 72 * dpi padin = padin * tickl / 72 * dpi
if tick.tick1line.get_visible(): if self.spine_type == 'left': bb0.x0 = bb0.x0 - padout bb0.x1 = bb0.x1 + padin elif self.spine_type == 'bottom': bb0.y0 = bb0.y0 - padout bb0.y1 = bb0.y1 + padin
if tick.tick2line.get_visible(): if self.spine_type == 'right': bb0.x1 = bb0.x1 + padout bb0.x0 = bb0.x0 - padin elif self.spine_type == 'top': bb0.y1 = bb0.y1 + padout bb0.y0 = bb0.y0 - padout bboxes.append(bb0)
return mtransforms.Bbox.union(bboxes)
def get_path(self): return self._path
def _ensure_position_is_set(self): if self._position is None: # default position self._position = ('outward', 0.0) # in points self.set_position(self._position)
def register_axis(self, axis): """ Register an axis.
An axis should be registered with its corresponding spine from the Axes instance. This allows the spine to clear any axis properties when needed. """ self.axis = axis self.stale = True
def clear(self): """Clear the current spine.""" self._clear() if self.axis is not None: self.axis.clear()
def _clear(self): """ Clear things directly related to the spine.
In this way it is possible to avoid clearing the Axis as well when calling from library code where it is known that the Axis is cleared separately. """ self._position = None # clear position
def _adjust_location(self): """Automatically set spine bounds to the view interval."""
if self.spine_type == 'circle': return
if self._bounds is not None: low, high = self._bounds elif self.spine_type in ('left', 'right'): low, high = self.axes.viewLim.intervaly elif self.spine_type in ('top', 'bottom'): low, high = self.axes.viewLim.intervalx else: raise ValueError(f'unknown spine spine_type: {self.spine_type}')
if self._patch_type == 'arc': if self.spine_type in ('bottom', 'top'): try: direction = self.axes.get_theta_direction() except AttributeError: direction = 1 try: offset = self.axes.get_theta_offset() except AttributeError: offset = 0 low = low * direction + offset high = high * direction + offset if low > high: low, high = high, low
self._path = mpath.Path.arc(np.rad2deg(low), np.rad2deg(high))
if self.spine_type == 'bottom': rmin, rmax = self.axes.viewLim.intervaly try: rorigin = self.axes.get_rorigin() except AttributeError: rorigin = rmin scaled_diameter = (rmin - rorigin) / (rmax - rorigin) self._height = scaled_diameter self._width = scaled_diameter
else: raise ValueError('unable to set bounds for spine "%s"' % self.spine_type) else: v1 = self._path.vertices assert v1.shape == (2, 2), 'unexpected vertices shape' if self.spine_type in ['left', 'right']: v1[0, 1] = low v1[1, 1] = high elif self.spine_type in ['bottom', 'top']: v1[0, 0] = low v1[1, 0] = high else: raise ValueError('unable to set bounds for spine "%s"' % self.spine_type)
@allow_rasterization def draw(self, renderer): self._adjust_location() ret = super().draw(renderer) self.stale = False return ret
def set_position(self, position): """ Set the position of the spine.
Spine position is specified by a 2 tuple of (position type, amount). The position types are:
* 'outward': place the spine out from the data area by the specified number of points. (Negative values place the spine inwards.) * 'axes': place the spine at the specified Axes coordinate (0 to 1). * 'data': place the spine at the specified data coordinate.
Additionally, shorthand notations define a special positions:
* 'center' -> ``('axes', 0.5)`` * 'zero' -> ``('data', 0.0)``
Examples -------- :doc:`/gallery/spines/spine_placement_demo` """ if position in ('center', 'zero'): # special positions pass else: if len(position) != 2: raise ValueError("position should be 'center' or 2-tuple") if position[0] not in ['outward', 'axes', 'data']: raise ValueError("position[0] should be one of 'outward', " "'axes', or 'data' ") self._position = position self.set_transform(self.get_spine_transform()) if self.axis is not None: self.axis.reset_ticks() self.stale = True
def get_position(self): """Return the spine position.""" self._ensure_position_is_set() return self._position
def get_spine_transform(self): """Return the spine transform.""" self._ensure_position_is_set()
position = self._position if isinstance(position, str): if position == 'center': position = ('axes', 0.5) elif position == 'zero': position = ('data', 0) assert len(position) == 2, 'position should be 2-tuple' position_type, amount = position _api.check_in_list(['axes', 'outward', 'data'], position_type=position_type) if self.spine_type in ['left', 'right']: base_transform = self.axes.get_yaxis_transform(which='grid') elif self.spine_type in ['top', 'bottom']: base_transform = self.axes.get_xaxis_transform(which='grid') else: raise ValueError(f'unknown spine spine_type: {self.spine_type!r}')
if position_type == 'outward': if amount == 0: # short circuit commonest case return base_transform else: offset_vec = {'left': (-1, 0), 'right': (1, 0), 'bottom': (0, -1), 'top': (0, 1), }[self.spine_type] # calculate x and y offset in dots offset_dots = amount * np.array(offset_vec) / 72 return (base_transform + mtransforms.ScaledTranslation( *offset_dots, self.get_figure(root=False).dpi_scale_trans)) elif position_type == 'axes': if self.spine_type in ['left', 'right']: # keep y unchanged, fix x at amount return (mtransforms.Affine2D.from_values(0, 0, 0, 1, amount, 0) + base_transform) elif self.spine_type in ['bottom', 'top']: # keep x unchanged, fix y at amount return (mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, amount) + base_transform) elif position_type == 'data': if self.spine_type in ('right', 'top'): # The right and top spines have a default position of 1 in # axes coordinates. When specifying the position in data # coordinates, we need to calculate the position relative to 0. amount -= 1 if self.spine_type in ('left', 'right'): return mtransforms.blended_transform_factory( mtransforms.Affine2D().translate(amount, 0) + self.axes.transData, self.axes.transData) elif self.spine_type in ('bottom', 'top'): return mtransforms.blended_transform_factory( self.axes.transData, mtransforms.Affine2D().translate(0, amount) + self.axes.transData)
def set_bounds(self, low=None, high=None): """ Set the spine bounds.
Parameters ---------- low : float or None, optional The lower spine bound. Passing *None* leaves the limit unchanged.
The bounds may also be passed as the tuple (*low*, *high*) as the first positional argument.
.. ACCEPTS: (low: float, high: float)
high : float or None, optional The higher spine bound. Passing *None* leaves the limit unchanged. """ if self.spine_type == 'circle': raise ValueError( 'set_bounds() method incompatible with circular spines') if high is None and np.iterable(low): low, high = low old_low, old_high = self.get_bounds() or (None, None) if low is None: low = old_low if high is None: high = old_high self._bounds = (low, high) self.stale = True
def get_bounds(self): """Get the bounds of the spine.""" return self._bounds
@classmethod def linear_spine(cls, axes, spine_type, **kwargs): """Create and return a linear `Spine`.""" # all values of 0.999 get replaced upon call to set_bounds() if spine_type == 'left': path = mpath.Path([(0.0, 0.999), (0.0, 0.999)]) elif spine_type == 'right': path = mpath.Path([(1.0, 0.999), (1.0, 0.999)]) elif spine_type == 'bottom': path = mpath.Path([(0.999, 0.0), (0.999, 0.0)]) elif spine_type == 'top': path = mpath.Path([(0.999, 1.0), (0.999, 1.0)]) else: raise ValueError('unable to make path for spine "%s"' % spine_type) result = cls(axes, spine_type, path, **kwargs) result.set_visible(mpl.rcParams[f'axes.spines.{spine_type}'])
return result
@classmethod def arc_spine(cls, axes, spine_type, center, radius, theta1, theta2, **kwargs): """Create and return an arc `Spine`.""" path = mpath.Path.arc(theta1, theta2) result = cls(axes, spine_type, path, **kwargs) result.set_patch_arc(center, radius, theta1, theta2) return result
@classmethod def circular_spine(cls, axes, center, radius, **kwargs): """Create and return a circular `Spine`.""" path = mpath.Path.unit_circle() spine_type = 'circle' result = cls(axes, spine_type, path, **kwargs) result.set_patch_circle(center, radius) return result
def set_color(self, c): """ Set the edgecolor.
Parameters ---------- c : :mpltype:`color`
Notes ----- This method does not modify the facecolor (which defaults to "none"), unlike the `.Patch.set_color` method defined in the parent class. Use `.Patch.set_facecolor` to set the facecolor. """ self.set_edgecolor(c) self.stale = True
class SpinesProxy: """ A proxy to broadcast ``set_*()`` and ``set()`` method calls to contained `.Spines`.
The proxy cannot be used for any other operations on its members.
The supported methods are determined dynamically based on the contained spines. If not all spines support a given method, it's executed only on the subset of spines that support it. """ def __init__(self, spine_dict): self._spine_dict = spine_dict
def __getattr__(self, name): broadcast_targets = [spine for spine in self._spine_dict.values() if hasattr(spine, name)] if (name != 'set' and not name.startswith('set_')) or not broadcast_targets: raise AttributeError( f"'SpinesProxy' object has no attribute '{name}'")
def x(_targets, _funcname, *args, **kwargs): for spine in _targets: getattr(spine, _funcname)(*args, **kwargs) x = functools.partial(x, broadcast_targets, name) x.__doc__ = broadcast_targets[0].__doc__ return x
def __dir__(self): names = [] for spine in self._spine_dict.values(): names.extend(name for name in dir(spine) if name.startswith('set_')) return list(sorted(set(names)))
class Spines(MutableMapping): r""" The container of all `.Spine`\s in an Axes.
The interface is dict-like mapping names (e.g. 'left') to `.Spine` objects. Additionally, it implements some pandas.Series-like features like accessing elements by attribute::
spines['top'].set_visible(False) spines.top.set_visible(False)
Multiple spines can be addressed simultaneously by passing a list::
spines[['top', 'right']].set_visible(False)
Use an open slice to address all spines::
spines[:].set_visible(False)
The latter two indexing methods will return a `SpinesProxy` that broadcasts all ``set_*()`` and ``set()`` calls to its members, but cannot be used for any other operation. """ def __init__(self, **kwargs): self._dict = kwargs
@classmethod def from_dict(cls, d): return cls(**d)
def __getstate__(self): return self._dict
def __setstate__(self, state): self.__init__(**state)
def __getattr__(self, name): try: return self._dict[name] except KeyError: raise AttributeError( f"'Spines' object does not contain a '{name}' spine")
def __getitem__(self, key): if isinstance(key, list): unknown_keys = [k for k in key if k not in self._dict] if unknown_keys: raise KeyError(', '.join(unknown_keys)) return SpinesProxy({k: v for k, v in self._dict.items() if k in key}) if isinstance(key, tuple): raise ValueError('Multiple spines must be passed as a single list') if isinstance(key, slice): if key.start is None and key.stop is None and key.step is None: return SpinesProxy(self._dict) else: raise ValueError( 'Spines does not support slicing except for the fully ' 'open slice [:] to access all spines.') return self._dict[key]
def __setitem__(self, key, value): # TODO: Do we want to deprecate adding spines? self._dict[key] = value
def __delitem__(self, key): # TODO: Do we want to deprecate deleting spines? del self._dict[key]
def __iter__(self): return iter(self._dict)
def __len__(self): return len(self._dict)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""Stacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflowanswer:https://stackoverflow.com/q/2225995/
(https://stackoverflow.com/users/66549/doug)"""
import itertools
import numpy as np
from matplotlib import _api
__all__ = ['stackplot']
def stackplot(axes, x, *args, labels=(), colors=None, hatch=None, baseline='zero', **kwargs): """ Draw a stacked area plot or a streamgraph.
Parameters ---------- x : (N,) array-like
y : (M, N) array-like The data can be either stacked or unstacked. Each of the following calls is legal::
stackplot(x, y) # where y has shape (M, N) e.g. y = [y1, y2, y3, y4] stackplot(x, y1, y2, y3, y4) # 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 :mpltype:`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.
hatch : list of str, default: None A sequence of hatching styles. See :doc:`/gallery/shapes_and_collections/hatch_style_reference`. The sequence will be cycled through for filling the stacked areas from bottom to top. It need not be exactly the same length as the number of provided *y*, in which case the styles will repeat from the beginning.
.. versionadded:: 3.9 Support for list input
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.vstack(args)
labels = iter(labels) if colors is not None: colors = itertools.cycle(colors) else: colors = (axes._get_lines.get_next_color() for _ in y)
if hatch is None or isinstance(hatch, str): hatch = itertools.cycle([hatch]) else: hatch = itertools.cycle(hatch)
# 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), hatch=next(hatch), 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), hatch=next(hatch), label=next(labels, None), **kwargs)) return r123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712"""Streamline plotting for 2D vector fields.
"""
import numpy as np
import matplotlib as mplfrom matplotlib import _api, cm, patchesimport matplotlib.colors as mcolorsimport matplotlib.collections as mcollectionsimport matplotlib.lines as mlines
__all__ = ['streamplot']
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 : :mpltype:`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 : (N, 2) 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(f"Starting point ({xs}, {ys}) outside of " "data boundaries")
# 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
# Create multiple tiny segments if varying width or color is given if isinstance(linewidth, np.ndarray) or use_multicolor_lines: points = np.transpose([tx, ty]).reshape(-1, 1, 2) streamlines.extend(np.hstack([points[:-1], points[1:]])) else: points = np.transpose([tx, ty]) streamlines.append(points)
# 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
class StreamplotSet:
def __init__(self, lines, arrows): self.lines = lines self.arrows = arrows
# Coordinate definitions# ========================
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")
@property 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
class InvalidIndexError(Exception): pass
class TerminateTrajectory(Exception): pass
# Integrator definitions# =======================
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
class OutOfBounds(IndexError): pass
def _integrate_rk12(x0, y0, dmap, f, maxlength, broken_streamlines=True): """ 2nd-order Runge-Kutta algorithm with adaptive step size.
This method is also referred to as the improved Euler's method, or Heun's method. This method is favored over higher-order methods because:
1. To get decent looking trajectories and to sample every mask cell on the trajectory we need a small timestep, so a lower order solver doesn't hurt us unless the data is *very* high resolution. In fact, for cases where the user inputs data smaller or of similar grid size to the mask grid, the higher order corrections are negligible because of the very fast linear interpolation used in `interpgrid`.
2. For high resolution input data (i.e. beyond the mask resolution), we must reduce the timestep. Therefore, an adaptive timestep is more suited to the problem as this would be very hard to judge automatically otherwise.
This integrator is about 1.5 - 2x as fast as RK4 and RK45 solvers (using similar Python implementations) in most setups. """ # This error is below that needed to match the RK4 integrator. It # is set for visual reasons -- too low and corners start # appearing ugly and jagged. Can be tuned. maxerror = 0.003
# This limit is important (for all integrators) to avoid the # trajectory skipping some mask cells. We could relax this # condition if we use the code which is commented out below to # increment the location gradually. However, due to the efficient # nature of the interpolation, this doesn't boost speed by much # for quite a bit of complexity. maxds = min(1. / dmap.mask.nx, 1. / dmap.mask.ny, 0.1)
ds = maxds stotal = 0 xi = x0 yi = y0 xyf_traj = []
while True: try: if dmap.grid.within_grid(xi, yi): xyf_traj.append((xi, yi)) else: raise OutOfBounds
# Compute the two intermediate gradients. # f should raise OutOfBounds if the locations given are # outside the grid. k1x, k1y = f(xi, yi) k2x, k2y = f(xi + ds * k1x, yi + ds * k1y)
except OutOfBounds: # Out of the domain during this step. # Take an Euler step to the boundary to improve neatness # unless the trajectory is currently empty. if xyf_traj: ds, xyf_traj = _euler_step(xyf_traj, dmap, f) stotal += ds break except TerminateTrajectory: break
dx1 = ds * k1x dy1 = ds * k1y dx2 = ds * 0.5 * (k1x + k2x) dy2 = ds * 0.5 * (k1y + k2y)
ny, nx = dmap.grid.shape # Error is normalized to the axes coordinates error = np.hypot((dx2 - dx1) / (nx - 1), (dy2 - dy1) / (ny - 1))
# Only save step if within error tolerance if error < maxerror: xi += dx2 yi += dy2 try: dmap.update_trajectory(xi, yi, broken_streamlines) except InvalidIndexError: break if stotal + ds > maxlength: break stotal += ds
# recalculate stepsize based on step error if error == 0: ds = maxds else: ds = min(maxds, 0.85 * ds * (maxerror / error) ** 0.5)
return stotal, xyf_traj
def _euler_step(xyf_traj, dmap, f): """Simple Euler integration step that extends streamline to boundary.""" ny, nx = dmap.grid.shape xi, yi = xyf_traj[-1] cx, cy = f(xi, yi) if cx == 0: dsx = np.inf elif cx < 0: dsx = xi / -cx else: dsx = (nx - 1 - xi) / cx if cy == 0: dsy = np.inf elif cy < 0: dsy = yi / -cy else: dsy = (ny - 1 - yi) / cy ds = min(dsx, dsy) xyf_traj.append((xi + cx * ds, yi + cy * ds)) return ds, xyf_traj
# Utility functions# ========================
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'1234from .core import available, context, library, reload_library, use
__all__ = ["available", "context", "library", "reload_library", "use"]lib/python3.12/site-packages/importlib_metadata/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/_adapters.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/_collections.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/_compat.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/_context.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/_functools.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/_itertools.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/_meta.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/_text.cpython-312.pycAdded
lib/python3.12/site-packages/importlib_metadata/__pycache__/diagnose.cpython-312.pycAdded
lib/python3.12/site-packages/matplotlib/_afm.pyAdded+532
lib/python3.12/site-packages/matplotlib/_animation_data.pyAdded+262
lib/python3.12/site-packages/matplotlib/_cm_listed.pyAdded
lib/python3.12/site-packages/matplotlib/_color_data.pyAdded+1141
lib/python3.12/site-packages/matplotlib/_docstring.pyAdded+141
lib/python3.12/site-packages/matplotlib/_layoutgrid.pyAdded+547
lib/python3.12/site-packages/matplotlib/_path.pyiAdded+9
lib/python3.12/site-packages/matplotlib/_qhull.pyiAdded
lib/python3.12/site-packages/matplotlib/_tight_layout.pyAdded+301
lib/python3.12/site-packages/matplotlib/animation.pyiAdded+217
lib/python3.12/site-packages/matplotlib/artist.pyAdded+1855
lib/python3.12/site-packages/matplotlib/artist.pyiAdded+199
lib/python3.12/site-packages/matplotlib/backend_bases.pyiAdded+482
lib/python3.12/site-packages/matplotlib/cm.pyiAdded+24
lib/python3.12/site-packages/matplotlib/collections.pyiAdded+262
lib/python3.12/site-packages/matplotlib/colorbar.pyAdded+1563
lib/python3.12/site-packages/matplotlib/colorizer.pyiAdded+102
lib/python3.12/site-packages/matplotlib/colors.pyAdded
lib/python3.12/site-packages/matplotlib/colors.pyiAdded+449
lib/python3.12/site-packages/matplotlib/container.pyiAdded+56
lib/python3.12/site-packages/matplotlib/figure.pyAdded
lib/python3.12/site-packages/matplotlib/gridspec.pyiAdded+160
lib/python3.12/site-packages/matplotlib/hatch.pyAdded+225
lib/python3.12/site-packages/matplotlib/hatch.pyiAdded+68
lib/python3.12/site-packages/matplotlib/image.pyAdded+1786
lib/python3.12/site-packages/matplotlib/inset.pyiAdded+25
lib/python3.12/site-packages/matplotlib/legend_handler.pyAdded+813
lib/python3.12/site-packages/matplotlib/legend_handler.pyiAdded+294
lib/python3.12/site-packages/matplotlib/markers.pyAdded+908
lib/python3.12/site-packages/matplotlib/mlab.pyAdded+913
lib/python3.12/site-packages/matplotlib/offsetbox.pyAdded+1613
lib/python3.12/site-packages/matplotlib/patheffects.pyiAdded+106
lib/python3.12/site-packages/matplotlib/quiver.pyiAdded+184
lib/python3.12/site-packages/matplotlib/scale.pyiAdded+178
lib/python3.12/site-packages/matplotlib/spines.pyAdded+596
lib/python3.12/site-packages/matplotlib/stackplot.pyAdded+147
lib/python3.12/site-packages/matplotlib/streamplot.pyAdded+712
lib/python3.12/site-packages/matplotlib/style/__init__.pyAdded+4
lib/python3.12/site-packages/matplotlib/style/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/matplotlib/style/__pycache__/core.cpython-312.pycAdded